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/FoldingSet.h"
21 #include "llvm/ADT/None.h"
22 #include "llvm/ADT/STLExtras.h"
23 #include "llvm/ADT/SmallPtrSet.h"
24 #include "llvm/ADT/SmallVector.h"
25 #include "llvm/ADT/Triple.h"
26 #include "llvm/ADT/Twine.h"
27 #include "llvm/Analysis/MemoryLocation.h"
28 #include "llvm/Analysis/ValueTracking.h"
29 #include "llvm/CodeGen/Analysis.h"
30 #include "llvm/CodeGen/FunctionLoweringInfo.h"
31 #include "llvm/CodeGen/ISDOpcodes.h"
32 #include "llvm/CodeGen/MachineBasicBlock.h"
33 #include "llvm/CodeGen/MachineConstantPool.h"
34 #include "llvm/CodeGen/MachineFrameInfo.h"
35 #include "llvm/CodeGen/MachineFunction.h"
36 #include "llvm/CodeGen/MachineMemOperand.h"
37 #include "llvm/CodeGen/RuntimeLibcalls.h"
38 #include "llvm/CodeGen/SelectionDAGAddressAnalysis.h"
39 #include "llvm/CodeGen/SelectionDAGNodes.h"
40 #include "llvm/CodeGen/SelectionDAGTargetInfo.h"
41 #include "llvm/CodeGen/TargetFrameLowering.h"
42 #include "llvm/CodeGen/TargetLowering.h"
43 #include "llvm/CodeGen/TargetRegisterInfo.h"
44 #include "llvm/CodeGen/TargetSubtargetInfo.h"
45 #include "llvm/CodeGen/ValueTypes.h"
46 #include "llvm/IR/Constant.h"
47 #include "llvm/IR/Constants.h"
48 #include "llvm/IR/DataLayout.h"
49 #include "llvm/IR/DebugInfoMetadata.h"
50 #include "llvm/IR/DebugLoc.h"
51 #include "llvm/IR/DerivedTypes.h"
52 #include "llvm/IR/Function.h"
53 #include "llvm/IR/GlobalValue.h"
54 #include "llvm/IR/Metadata.h"
55 #include "llvm/IR/Type.h"
56 #include "llvm/Support/Casting.h"
57 #include "llvm/Support/CodeGen.h"
58 #include "llvm/Support/Compiler.h"
59 #include "llvm/Support/Debug.h"
60 #include "llvm/Support/ErrorHandling.h"
61 #include "llvm/Support/KnownBits.h"
62 #include "llvm/Support/MachineValueType.h"
63 #include "llvm/Support/MathExtras.h"
64 #include "llvm/Support/Mutex.h"
65 #include "llvm/Support/raw_ostream.h"
66 #include "llvm/Target/TargetMachine.h"
67 #include "llvm/Target/TargetOptions.h"
68 #include "llvm/Transforms/Utils/SizeOpts.h"
69 #include <algorithm>
70 #include <cassert>
71 #include <cstdint>
72 #include <cstdlib>
73 #include <limits>
74 #include <set>
75 #include <string>
76 #include <utility>
77 #include <vector>
78 
79 using namespace llvm;
80 
81 /// makeVTList - Return an instance of the SDVTList struct initialized with the
82 /// specified members.
83 static SDVTList makeVTList(const EVT *VTs, unsigned NumVTs) {
84   SDVTList Res = {VTs, NumVTs};
85   return Res;
86 }
87 
88 // Default null implementations of the callbacks.
89 void SelectionDAG::DAGUpdateListener::NodeDeleted(SDNode*, SDNode*) {}
90 void SelectionDAG::DAGUpdateListener::NodeUpdated(SDNode*) {}
91 void SelectionDAG::DAGUpdateListener::NodeInserted(SDNode *) {}
92 
93 void SelectionDAG::DAGNodeDeletedListener::anchor() {}
94 
95 #define DEBUG_TYPE "selectiondag"
96 
97 static cl::opt<bool> EnableMemCpyDAGOpt("enable-memcpy-dag-opt",
98        cl::Hidden, cl::init(true),
99        cl::desc("Gang up loads and stores generated by inlining of memcpy"));
100 
101 static cl::opt<int> MaxLdStGlue("ldstmemcpy-glue-max",
102        cl::desc("Number limit for gluing ld/st of memcpy."),
103        cl::Hidden, cl::init(0));
104 
105 static void NewSDValueDbgMsg(SDValue V, StringRef Msg, SelectionDAG *G) {
106   LLVM_DEBUG(dbgs() << Msg; V.getNode()->dump(G););
107 }
108 
109 //===----------------------------------------------------------------------===//
110 //                              ConstantFPSDNode Class
111 //===----------------------------------------------------------------------===//
112 
113 /// isExactlyValue - We don't rely on operator== working on double values, as
114 /// it returns true for things that are clearly not equal, like -0.0 and 0.0.
115 /// As such, this method can be used to do an exact bit-for-bit comparison of
116 /// two floating point values.
117 bool ConstantFPSDNode::isExactlyValue(const APFloat& V) const {
118   return getValueAPF().bitwiseIsEqual(V);
119 }
120 
121 bool ConstantFPSDNode::isValueValidForType(EVT VT,
122                                            const APFloat& Val) {
123   assert(VT.isFloatingPoint() && "Can only convert between FP types");
124 
125   // convert modifies in place, so make a copy.
126   APFloat Val2 = APFloat(Val);
127   bool losesInfo;
128   (void) Val2.convert(SelectionDAG::EVTToAPFloatSemantics(VT),
129                       APFloat::rmNearestTiesToEven,
130                       &losesInfo);
131   return !losesInfo;
132 }
133 
134 //===----------------------------------------------------------------------===//
135 //                              ISD Namespace
136 //===----------------------------------------------------------------------===//
137 
138 bool ISD::isConstantSplatVector(const SDNode *N, APInt &SplatVal) {
139   if (N->getOpcode() == ISD::SPLAT_VECTOR) {
140     unsigned EltSize =
141         N->getValueType(0).getVectorElementType().getSizeInBits();
142     if (auto *Op0 = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
143       SplatVal = Op0->getAPIntValue().trunc(EltSize);
144       return true;
145     }
146     if (auto *Op0 = dyn_cast<ConstantFPSDNode>(N->getOperand(0))) {
147       SplatVal = Op0->getValueAPF().bitcastToAPInt().trunc(EltSize);
148       return true;
149     }
150   }
151 
152   auto *BV = dyn_cast<BuildVectorSDNode>(N);
153   if (!BV)
154     return false;
155 
156   APInt SplatUndef;
157   unsigned SplatBitSize;
158   bool HasUndefs;
159   unsigned EltSize = N->getValueType(0).getVectorElementType().getSizeInBits();
160   return BV->isConstantSplat(SplatVal, SplatUndef, SplatBitSize, HasUndefs,
161                              EltSize) &&
162          EltSize == SplatBitSize;
163 }
164 
165 // FIXME: AllOnes and AllZeros duplicate a lot of code. Could these be
166 // specializations of the more general isConstantSplatVector()?
167 
168 bool ISD::isConstantSplatVectorAllOnes(const SDNode *N, bool BuildVectorOnly) {
169   // Look through a bit convert.
170   while (N->getOpcode() == ISD::BITCAST)
171     N = N->getOperand(0).getNode();
172 
173   if (!BuildVectorOnly && N->getOpcode() == ISD::SPLAT_VECTOR) {
174     APInt SplatVal;
175     return isConstantSplatVector(N, SplatVal) && SplatVal.isAllOnes();
176   }
177 
178   if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
179 
180   unsigned i = 0, e = N->getNumOperands();
181 
182   // Skip over all of the undef values.
183   while (i != e && N->getOperand(i).isUndef())
184     ++i;
185 
186   // Do not accept an all-undef vector.
187   if (i == e) return false;
188 
189   // Do not accept build_vectors that aren't all constants or which have non-~0
190   // elements. We have to be a bit careful here, as the type of the constant
191   // may not be the same as the type of the vector elements due to type
192   // legalization (the elements are promoted to a legal type for the target and
193   // a vector of a type may be legal when the base element type is not).
194   // We only want to check enough bits to cover the vector elements, because
195   // we care if the resultant vector is all ones, not whether the individual
196   // constants are.
197   SDValue NotZero = N->getOperand(i);
198   unsigned EltSize = N->getValueType(0).getScalarSizeInBits();
199   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(NotZero)) {
200     if (CN->getAPIntValue().countTrailingOnes() < EltSize)
201       return false;
202   } else if (ConstantFPSDNode *CFPN = dyn_cast<ConstantFPSDNode>(NotZero)) {
203     if (CFPN->getValueAPF().bitcastToAPInt().countTrailingOnes() < EltSize)
204       return false;
205   } else
206     return false;
207 
208   // Okay, we have at least one ~0 value, check to see if the rest match or are
209   // undefs. Even with the above element type twiddling, this should be OK, as
210   // the same type legalization should have applied to all the elements.
211   for (++i; i != e; ++i)
212     if (N->getOperand(i) != NotZero && !N->getOperand(i).isUndef())
213       return false;
214   return true;
215 }
216 
217 bool ISD::isConstantSplatVectorAllZeros(const SDNode *N, bool BuildVectorOnly) {
218   // Look through a bit convert.
219   while (N->getOpcode() == ISD::BITCAST)
220     N = N->getOperand(0).getNode();
221 
222   if (!BuildVectorOnly && N->getOpcode() == ISD::SPLAT_VECTOR) {
223     APInt SplatVal;
224     return isConstantSplatVector(N, SplatVal) && SplatVal.isZero();
225   }
226 
227   if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
228 
229   bool IsAllUndef = true;
230   for (const SDValue &Op : N->op_values()) {
231     if (Op.isUndef())
232       continue;
233     IsAllUndef = false;
234     // Do not accept build_vectors that aren't all constants or which have non-0
235     // elements. We have to be a bit careful here, as the type of the constant
236     // may not be the same as the type of the vector elements due to type
237     // legalization (the elements are promoted to a legal type for the target
238     // and a vector of a type may be legal when the base element type is not).
239     // We only want to check enough bits to cover the vector elements, because
240     // we care if the resultant vector is all zeros, not whether the individual
241     // constants are.
242     unsigned EltSize = N->getValueType(0).getScalarSizeInBits();
243     if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Op)) {
244       if (CN->getAPIntValue().countTrailingZeros() < EltSize)
245         return false;
246     } else if (ConstantFPSDNode *CFPN = dyn_cast<ConstantFPSDNode>(Op)) {
247       if (CFPN->getValueAPF().bitcastToAPInt().countTrailingZeros() < EltSize)
248         return false;
249     } else
250       return false;
251   }
252 
253   // Do not accept an all-undef vector.
254   if (IsAllUndef)
255     return false;
256   return true;
257 }
258 
259 bool ISD::isBuildVectorAllOnes(const SDNode *N) {
260   return isConstantSplatVectorAllOnes(N, /*BuildVectorOnly*/ true);
261 }
262 
263 bool ISD::isBuildVectorAllZeros(const SDNode *N) {
264   return isConstantSplatVectorAllZeros(N, /*BuildVectorOnly*/ true);
265 }
266 
267 bool ISD::isBuildVectorOfConstantSDNodes(const SDNode *N) {
268   if (N->getOpcode() != ISD::BUILD_VECTOR)
269     return false;
270 
271   for (const SDValue &Op : N->op_values()) {
272     if (Op.isUndef())
273       continue;
274     if (!isa<ConstantSDNode>(Op))
275       return false;
276   }
277   return true;
278 }
279 
280 bool ISD::isBuildVectorOfConstantFPSDNodes(const SDNode *N) {
281   if (N->getOpcode() != ISD::BUILD_VECTOR)
282     return false;
283 
284   for (const SDValue &Op : N->op_values()) {
285     if (Op.isUndef())
286       continue;
287     if (!isa<ConstantFPSDNode>(Op))
288       return false;
289   }
290   return true;
291 }
292 
293 bool ISD::allOperandsUndef(const SDNode *N) {
294   // Return false if the node has no operands.
295   // This is "logically inconsistent" with the definition of "all" but
296   // is probably the desired behavior.
297   if (N->getNumOperands() == 0)
298     return false;
299   return all_of(N->op_values(), [](SDValue Op) { return Op.isUndef(); });
300 }
301 
302 bool ISD::matchUnaryPredicate(SDValue Op,
303                               std::function<bool(ConstantSDNode *)> Match,
304                               bool AllowUndefs) {
305   // FIXME: Add support for scalar UNDEF cases?
306   if (auto *Cst = dyn_cast<ConstantSDNode>(Op))
307     return Match(Cst);
308 
309   // FIXME: Add support for vector UNDEF cases?
310   if (ISD::BUILD_VECTOR != Op.getOpcode() &&
311       ISD::SPLAT_VECTOR != Op.getOpcode())
312     return false;
313 
314   EVT SVT = Op.getValueType().getScalarType();
315   for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
316     if (AllowUndefs && Op.getOperand(i).isUndef()) {
317       if (!Match(nullptr))
318         return false;
319       continue;
320     }
321 
322     auto *Cst = dyn_cast<ConstantSDNode>(Op.getOperand(i));
323     if (!Cst || Cst->getValueType(0) != SVT || !Match(Cst))
324       return false;
325   }
326   return true;
327 }
328 
329 bool ISD::matchBinaryPredicate(
330     SDValue LHS, SDValue RHS,
331     std::function<bool(ConstantSDNode *, ConstantSDNode *)> Match,
332     bool AllowUndefs, bool AllowTypeMismatch) {
333   if (!AllowTypeMismatch && LHS.getValueType() != RHS.getValueType())
334     return false;
335 
336   // TODO: Add support for scalar UNDEF cases?
337   if (auto *LHSCst = dyn_cast<ConstantSDNode>(LHS))
338     if (auto *RHSCst = dyn_cast<ConstantSDNode>(RHS))
339       return Match(LHSCst, RHSCst);
340 
341   // TODO: Add support for vector UNDEF cases?
342   if (LHS.getOpcode() != RHS.getOpcode() ||
343       (LHS.getOpcode() != ISD::BUILD_VECTOR &&
344        LHS.getOpcode() != ISD::SPLAT_VECTOR))
345     return false;
346 
347   EVT SVT = LHS.getValueType().getScalarType();
348   for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
349     SDValue LHSOp = LHS.getOperand(i);
350     SDValue RHSOp = RHS.getOperand(i);
351     bool LHSUndef = AllowUndefs && LHSOp.isUndef();
352     bool RHSUndef = AllowUndefs && RHSOp.isUndef();
353     auto *LHSCst = dyn_cast<ConstantSDNode>(LHSOp);
354     auto *RHSCst = dyn_cast<ConstantSDNode>(RHSOp);
355     if ((!LHSCst && !LHSUndef) || (!RHSCst && !RHSUndef))
356       return false;
357     if (!AllowTypeMismatch && (LHSOp.getValueType() != SVT ||
358                                LHSOp.getValueType() != RHSOp.getValueType()))
359       return false;
360     if (!Match(LHSCst, RHSCst))
361       return false;
362   }
363   return true;
364 }
365 
366 ISD::NodeType ISD::getVecReduceBaseOpcode(unsigned VecReduceOpcode) {
367   switch (VecReduceOpcode) {
368   default:
369     llvm_unreachable("Expected VECREDUCE opcode");
370   case ISD::VECREDUCE_FADD:
371   case ISD::VECREDUCE_SEQ_FADD:
372   case ISD::VP_REDUCE_FADD:
373   case ISD::VP_REDUCE_SEQ_FADD:
374     return ISD::FADD;
375   case ISD::VECREDUCE_FMUL:
376   case ISD::VECREDUCE_SEQ_FMUL:
377   case ISD::VP_REDUCE_FMUL:
378   case ISD::VP_REDUCE_SEQ_FMUL:
379     return ISD::FMUL;
380   case ISD::VECREDUCE_ADD:
381   case ISD::VP_REDUCE_ADD:
382     return ISD::ADD;
383   case ISD::VECREDUCE_MUL:
384   case ISD::VP_REDUCE_MUL:
385     return ISD::MUL;
386   case ISD::VECREDUCE_AND:
387   case ISD::VP_REDUCE_AND:
388     return ISD::AND;
389   case ISD::VECREDUCE_OR:
390   case ISD::VP_REDUCE_OR:
391     return ISD::OR;
392   case ISD::VECREDUCE_XOR:
393   case ISD::VP_REDUCE_XOR:
394     return ISD::XOR;
395   case ISD::VECREDUCE_SMAX:
396   case ISD::VP_REDUCE_SMAX:
397     return ISD::SMAX;
398   case ISD::VECREDUCE_SMIN:
399   case ISD::VP_REDUCE_SMIN:
400     return ISD::SMIN;
401   case ISD::VECREDUCE_UMAX:
402   case ISD::VP_REDUCE_UMAX:
403     return ISD::UMAX;
404   case ISD::VECREDUCE_UMIN:
405   case ISD::VP_REDUCE_UMIN:
406     return ISD::UMIN;
407   case ISD::VECREDUCE_FMAX:
408   case ISD::VP_REDUCE_FMAX:
409     return ISD::FMAXNUM;
410   case ISD::VECREDUCE_FMIN:
411   case ISD::VP_REDUCE_FMIN:
412     return ISD::FMINNUM;
413   }
414 }
415 
416 bool ISD::isVPOpcode(unsigned Opcode) {
417   switch (Opcode) {
418   default:
419     return false;
420 #define BEGIN_REGISTER_VP_SDNODE(VPSD, ...)                                    \
421   case ISD::VPSD:                                                              \
422     return true;
423 #include "llvm/IR/VPIntrinsics.def"
424   }
425 }
426 
427 bool ISD::isVPBinaryOp(unsigned Opcode) {
428   switch (Opcode) {
429   default:
430     break;
431 #define BEGIN_REGISTER_VP_SDNODE(VPSD, ...) case ISD::VPSD:
432 #define VP_PROPERTY_BINARYOP return true;
433 #define END_REGISTER_VP_SDNODE(VPSD) break;
434 #include "llvm/IR/VPIntrinsics.def"
435   }
436   return false;
437 }
438 
439 bool ISD::isVPReduction(unsigned Opcode) {
440   switch (Opcode) {
441   default:
442     break;
443 #define BEGIN_REGISTER_VP_SDNODE(VPSD, ...) case ISD::VPSD:
444 #define VP_PROPERTY_REDUCTION(STARTPOS, ...) return true;
445 #define END_REGISTER_VP_SDNODE(VPSD) break;
446 #include "llvm/IR/VPIntrinsics.def"
447   }
448   return false;
449 }
450 
451 /// The operand position of the vector mask.
452 Optional<unsigned> ISD::getVPMaskIdx(unsigned Opcode) {
453   switch (Opcode) {
454   default:
455     return None;
456 #define BEGIN_REGISTER_VP_SDNODE(VPSD, LEGALPOS, TDNAME, MASKPOS, ...)         \
457   case ISD::VPSD:                                                              \
458     return MASKPOS;
459 #include "llvm/IR/VPIntrinsics.def"
460   }
461 }
462 
463 /// The operand position of the explicit vector length parameter.
464 Optional<unsigned> ISD::getVPExplicitVectorLengthIdx(unsigned Opcode) {
465   switch (Opcode) {
466   default:
467     return None;
468 #define BEGIN_REGISTER_VP_SDNODE(VPSD, LEGALPOS, TDNAME, MASKPOS, EVLPOS)      \
469   case ISD::VPSD:                                                              \
470     return EVLPOS;
471 #include "llvm/IR/VPIntrinsics.def"
472   }
473 }
474 
475 ISD::NodeType ISD::getExtForLoadExtType(bool IsFP, ISD::LoadExtType ExtType) {
476   switch (ExtType) {
477   case ISD::EXTLOAD:
478     return IsFP ? ISD::FP_EXTEND : ISD::ANY_EXTEND;
479   case ISD::SEXTLOAD:
480     return ISD::SIGN_EXTEND;
481   case ISD::ZEXTLOAD:
482     return ISD::ZERO_EXTEND;
483   default:
484     break;
485   }
486 
487   llvm_unreachable("Invalid LoadExtType");
488 }
489 
490 ISD::CondCode ISD::getSetCCSwappedOperands(ISD::CondCode Operation) {
491   // To perform this operation, we just need to swap the L and G bits of the
492   // operation.
493   unsigned OldL = (Operation >> 2) & 1;
494   unsigned OldG = (Operation >> 1) & 1;
495   return ISD::CondCode((Operation & ~6) |  // Keep the N, U, E bits
496                        (OldL << 1) |       // New G bit
497                        (OldG << 2));       // New L bit.
498 }
499 
500 static ISD::CondCode getSetCCInverseImpl(ISD::CondCode Op, bool isIntegerLike) {
501   unsigned Operation = Op;
502   if (isIntegerLike)
503     Operation ^= 7;   // Flip L, G, E bits, but not U.
504   else
505     Operation ^= 15;  // Flip all of the condition bits.
506 
507   if (Operation > ISD::SETTRUE2)
508     Operation &= ~8;  // Don't let N and U bits get set.
509 
510   return ISD::CondCode(Operation);
511 }
512 
513 ISD::CondCode ISD::getSetCCInverse(ISD::CondCode Op, EVT Type) {
514   return getSetCCInverseImpl(Op, Type.isInteger());
515 }
516 
517 ISD::CondCode ISD::GlobalISel::getSetCCInverse(ISD::CondCode Op,
518                                                bool isIntegerLike) {
519   return getSetCCInverseImpl(Op, isIntegerLike);
520 }
521 
522 /// For an integer comparison, return 1 if the comparison is a signed operation
523 /// and 2 if the result is an unsigned comparison. Return zero if the operation
524 /// does not depend on the sign of the input (setne and seteq).
525 static int isSignedOp(ISD::CondCode Opcode) {
526   switch (Opcode) {
527   default: llvm_unreachable("Illegal integer setcc operation!");
528   case ISD::SETEQ:
529   case ISD::SETNE: return 0;
530   case ISD::SETLT:
531   case ISD::SETLE:
532   case ISD::SETGT:
533   case ISD::SETGE: return 1;
534   case ISD::SETULT:
535   case ISD::SETULE:
536   case ISD::SETUGT:
537   case ISD::SETUGE: return 2;
538   }
539 }
540 
541 ISD::CondCode ISD::getSetCCOrOperation(ISD::CondCode Op1, ISD::CondCode Op2,
542                                        EVT Type) {
543   bool IsInteger = Type.isInteger();
544   if (IsInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
545     // Cannot fold a signed integer setcc with an unsigned integer setcc.
546     return ISD::SETCC_INVALID;
547 
548   unsigned Op = Op1 | Op2;  // Combine all of the condition bits.
549 
550   // If the N and U bits get set, then the resultant comparison DOES suddenly
551   // care about orderedness, and it is true when ordered.
552   if (Op > ISD::SETTRUE2)
553     Op &= ~16;     // Clear the U bit if the N bit is set.
554 
555   // Canonicalize illegal integer setcc's.
556   if (IsInteger && Op == ISD::SETUNE)  // e.g. SETUGT | SETULT
557     Op = ISD::SETNE;
558 
559   return ISD::CondCode(Op);
560 }
561 
562 ISD::CondCode ISD::getSetCCAndOperation(ISD::CondCode Op1, ISD::CondCode Op2,
563                                         EVT Type) {
564   bool IsInteger = Type.isInteger();
565   if (IsInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
566     // Cannot fold a signed setcc with an unsigned setcc.
567     return ISD::SETCC_INVALID;
568 
569   // Combine all of the condition bits.
570   ISD::CondCode Result = ISD::CondCode(Op1 & Op2);
571 
572   // Canonicalize illegal integer setcc's.
573   if (IsInteger) {
574     switch (Result) {
575     default: break;
576     case ISD::SETUO : Result = ISD::SETFALSE; break;  // SETUGT & SETULT
577     case ISD::SETOEQ:                                 // SETEQ  & SETU[LG]E
578     case ISD::SETUEQ: Result = ISD::SETEQ   ; break;  // SETUGE & SETULE
579     case ISD::SETOLT: Result = ISD::SETULT  ; break;  // SETULT & SETNE
580     case ISD::SETOGT: Result = ISD::SETUGT  ; break;  // SETUGT & SETNE
581     }
582   }
583 
584   return Result;
585 }
586 
587 //===----------------------------------------------------------------------===//
588 //                           SDNode Profile Support
589 //===----------------------------------------------------------------------===//
590 
591 /// AddNodeIDOpcode - Add the node opcode to the NodeID data.
592 static void AddNodeIDOpcode(FoldingSetNodeID &ID, unsigned OpC)  {
593   ID.AddInteger(OpC);
594 }
595 
596 /// AddNodeIDValueTypes - Value type lists are intern'd so we can represent them
597 /// solely with their pointer.
598 static void AddNodeIDValueTypes(FoldingSetNodeID &ID, SDVTList VTList) {
599   ID.AddPointer(VTList.VTs);
600 }
601 
602 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data.
603 static void AddNodeIDOperands(FoldingSetNodeID &ID,
604                               ArrayRef<SDValue> Ops) {
605   for (auto& Op : Ops) {
606     ID.AddPointer(Op.getNode());
607     ID.AddInteger(Op.getResNo());
608   }
609 }
610 
611 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data.
612 static void AddNodeIDOperands(FoldingSetNodeID &ID,
613                               ArrayRef<SDUse> Ops) {
614   for (auto& Op : Ops) {
615     ID.AddPointer(Op.getNode());
616     ID.AddInteger(Op.getResNo());
617   }
618 }
619 
620 static void AddNodeIDNode(FoldingSetNodeID &ID, unsigned short OpC,
621                           SDVTList VTList, ArrayRef<SDValue> OpList) {
622   AddNodeIDOpcode(ID, OpC);
623   AddNodeIDValueTypes(ID, VTList);
624   AddNodeIDOperands(ID, OpList);
625 }
626 
627 /// If this is an SDNode with special info, add this info to the NodeID data.
628 static void AddNodeIDCustom(FoldingSetNodeID &ID, const SDNode *N) {
629   switch (N->getOpcode()) {
630   case ISD::TargetExternalSymbol:
631   case ISD::ExternalSymbol:
632   case ISD::MCSymbol:
633     llvm_unreachable("Should only be used on nodes with operands");
634   default: break;  // Normal nodes don't need extra info.
635   case ISD::TargetConstant:
636   case ISD::Constant: {
637     const ConstantSDNode *C = cast<ConstantSDNode>(N);
638     ID.AddPointer(C->getConstantIntValue());
639     ID.AddBoolean(C->isOpaque());
640     break;
641   }
642   case ISD::TargetConstantFP:
643   case ISD::ConstantFP:
644     ID.AddPointer(cast<ConstantFPSDNode>(N)->getConstantFPValue());
645     break;
646   case ISD::TargetGlobalAddress:
647   case ISD::GlobalAddress:
648   case ISD::TargetGlobalTLSAddress:
649   case ISD::GlobalTLSAddress: {
650     const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(N);
651     ID.AddPointer(GA->getGlobal());
652     ID.AddInteger(GA->getOffset());
653     ID.AddInteger(GA->getTargetFlags());
654     break;
655   }
656   case ISD::BasicBlock:
657     ID.AddPointer(cast<BasicBlockSDNode>(N)->getBasicBlock());
658     break;
659   case ISD::Register:
660     ID.AddInteger(cast<RegisterSDNode>(N)->getReg());
661     break;
662   case ISD::RegisterMask:
663     ID.AddPointer(cast<RegisterMaskSDNode>(N)->getRegMask());
664     break;
665   case ISD::SRCVALUE:
666     ID.AddPointer(cast<SrcValueSDNode>(N)->getValue());
667     break;
668   case ISD::FrameIndex:
669   case ISD::TargetFrameIndex:
670     ID.AddInteger(cast<FrameIndexSDNode>(N)->getIndex());
671     break;
672   case ISD::LIFETIME_START:
673   case ISD::LIFETIME_END:
674     if (cast<LifetimeSDNode>(N)->hasOffset()) {
675       ID.AddInteger(cast<LifetimeSDNode>(N)->getSize());
676       ID.AddInteger(cast<LifetimeSDNode>(N)->getOffset());
677     }
678     break;
679   case ISD::PSEUDO_PROBE:
680     ID.AddInteger(cast<PseudoProbeSDNode>(N)->getGuid());
681     ID.AddInteger(cast<PseudoProbeSDNode>(N)->getIndex());
682     ID.AddInteger(cast<PseudoProbeSDNode>(N)->getAttributes());
683     break;
684   case ISD::JumpTable:
685   case ISD::TargetJumpTable:
686     ID.AddInteger(cast<JumpTableSDNode>(N)->getIndex());
687     ID.AddInteger(cast<JumpTableSDNode>(N)->getTargetFlags());
688     break;
689   case ISD::ConstantPool:
690   case ISD::TargetConstantPool: {
691     const ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(N);
692     ID.AddInteger(CP->getAlign().value());
693     ID.AddInteger(CP->getOffset());
694     if (CP->isMachineConstantPoolEntry())
695       CP->getMachineCPVal()->addSelectionDAGCSEId(ID);
696     else
697       ID.AddPointer(CP->getConstVal());
698     ID.AddInteger(CP->getTargetFlags());
699     break;
700   }
701   case ISD::TargetIndex: {
702     const TargetIndexSDNode *TI = cast<TargetIndexSDNode>(N);
703     ID.AddInteger(TI->getIndex());
704     ID.AddInteger(TI->getOffset());
705     ID.AddInteger(TI->getTargetFlags());
706     break;
707   }
708   case ISD::LOAD: {
709     const LoadSDNode *LD = cast<LoadSDNode>(N);
710     ID.AddInteger(LD->getMemoryVT().getRawBits());
711     ID.AddInteger(LD->getRawSubclassData());
712     ID.AddInteger(LD->getPointerInfo().getAddrSpace());
713     ID.AddInteger(LD->getMemOperand()->getFlags());
714     break;
715   }
716   case ISD::STORE: {
717     const StoreSDNode *ST = cast<StoreSDNode>(N);
718     ID.AddInteger(ST->getMemoryVT().getRawBits());
719     ID.AddInteger(ST->getRawSubclassData());
720     ID.AddInteger(ST->getPointerInfo().getAddrSpace());
721     ID.AddInteger(ST->getMemOperand()->getFlags());
722     break;
723   }
724   case ISD::VP_LOAD: {
725     const VPLoadSDNode *ELD = cast<VPLoadSDNode>(N);
726     ID.AddInteger(ELD->getMemoryVT().getRawBits());
727     ID.AddInteger(ELD->getRawSubclassData());
728     ID.AddInteger(ELD->getPointerInfo().getAddrSpace());
729     ID.AddInteger(ELD->getMemOperand()->getFlags());
730     break;
731   }
732   case ISD::VP_STORE: {
733     const VPStoreSDNode *EST = cast<VPStoreSDNode>(N);
734     ID.AddInteger(EST->getMemoryVT().getRawBits());
735     ID.AddInteger(EST->getRawSubclassData());
736     ID.AddInteger(EST->getPointerInfo().getAddrSpace());
737     ID.AddInteger(EST->getMemOperand()->getFlags());
738     break;
739   }
740   case ISD::EXPERIMENTAL_VP_STRIDED_LOAD: {
741     const VPStridedLoadSDNode *SLD = cast<VPStridedLoadSDNode>(N);
742     ID.AddInteger(SLD->getMemoryVT().getRawBits());
743     ID.AddInteger(SLD->getRawSubclassData());
744     ID.AddInteger(SLD->getPointerInfo().getAddrSpace());
745     break;
746   }
747   case ISD::EXPERIMENTAL_VP_STRIDED_STORE: {
748     const VPStridedStoreSDNode *SST = cast<VPStridedStoreSDNode>(N);
749     ID.AddInteger(SST->getMemoryVT().getRawBits());
750     ID.AddInteger(SST->getRawSubclassData());
751     ID.AddInteger(SST->getPointerInfo().getAddrSpace());
752     break;
753   }
754   case ISD::VP_GATHER: {
755     const VPGatherSDNode *EG = cast<VPGatherSDNode>(N);
756     ID.AddInteger(EG->getMemoryVT().getRawBits());
757     ID.AddInteger(EG->getRawSubclassData());
758     ID.AddInteger(EG->getPointerInfo().getAddrSpace());
759     ID.AddInteger(EG->getMemOperand()->getFlags());
760     break;
761   }
762   case ISD::VP_SCATTER: {
763     const VPScatterSDNode *ES = cast<VPScatterSDNode>(N);
764     ID.AddInteger(ES->getMemoryVT().getRawBits());
765     ID.AddInteger(ES->getRawSubclassData());
766     ID.AddInteger(ES->getPointerInfo().getAddrSpace());
767     ID.AddInteger(ES->getMemOperand()->getFlags());
768     break;
769   }
770   case ISD::MLOAD: {
771     const MaskedLoadSDNode *MLD = cast<MaskedLoadSDNode>(N);
772     ID.AddInteger(MLD->getMemoryVT().getRawBits());
773     ID.AddInteger(MLD->getRawSubclassData());
774     ID.AddInteger(MLD->getPointerInfo().getAddrSpace());
775     ID.AddInteger(MLD->getMemOperand()->getFlags());
776     break;
777   }
778   case ISD::MSTORE: {
779     const MaskedStoreSDNode *MST = cast<MaskedStoreSDNode>(N);
780     ID.AddInteger(MST->getMemoryVT().getRawBits());
781     ID.AddInteger(MST->getRawSubclassData());
782     ID.AddInteger(MST->getPointerInfo().getAddrSpace());
783     ID.AddInteger(MST->getMemOperand()->getFlags());
784     break;
785   }
786   case ISD::MGATHER: {
787     const MaskedGatherSDNode *MG = cast<MaskedGatherSDNode>(N);
788     ID.AddInteger(MG->getMemoryVT().getRawBits());
789     ID.AddInteger(MG->getRawSubclassData());
790     ID.AddInteger(MG->getPointerInfo().getAddrSpace());
791     ID.AddInteger(MG->getMemOperand()->getFlags());
792     break;
793   }
794   case ISD::MSCATTER: {
795     const MaskedScatterSDNode *MS = cast<MaskedScatterSDNode>(N);
796     ID.AddInteger(MS->getMemoryVT().getRawBits());
797     ID.AddInteger(MS->getRawSubclassData());
798     ID.AddInteger(MS->getPointerInfo().getAddrSpace());
799     ID.AddInteger(MS->getMemOperand()->getFlags());
800     break;
801   }
802   case ISD::ATOMIC_CMP_SWAP:
803   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
804   case ISD::ATOMIC_SWAP:
805   case ISD::ATOMIC_LOAD_ADD:
806   case ISD::ATOMIC_LOAD_SUB:
807   case ISD::ATOMIC_LOAD_AND:
808   case ISD::ATOMIC_LOAD_CLR:
809   case ISD::ATOMIC_LOAD_OR:
810   case ISD::ATOMIC_LOAD_XOR:
811   case ISD::ATOMIC_LOAD_NAND:
812   case ISD::ATOMIC_LOAD_MIN:
813   case ISD::ATOMIC_LOAD_MAX:
814   case ISD::ATOMIC_LOAD_UMIN:
815   case ISD::ATOMIC_LOAD_UMAX:
816   case ISD::ATOMIC_LOAD:
817   case ISD::ATOMIC_STORE: {
818     const AtomicSDNode *AT = cast<AtomicSDNode>(N);
819     ID.AddInteger(AT->getMemoryVT().getRawBits());
820     ID.AddInteger(AT->getRawSubclassData());
821     ID.AddInteger(AT->getPointerInfo().getAddrSpace());
822     ID.AddInteger(AT->getMemOperand()->getFlags());
823     break;
824   }
825   case ISD::PREFETCH: {
826     const MemSDNode *PF = cast<MemSDNode>(N);
827     ID.AddInteger(PF->getPointerInfo().getAddrSpace());
828     ID.AddInteger(PF->getMemOperand()->getFlags());
829     break;
830   }
831   case ISD::VECTOR_SHUFFLE: {
832     const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
833     for (unsigned i = 0, e = N->getValueType(0).getVectorNumElements();
834          i != e; ++i)
835       ID.AddInteger(SVN->getMaskElt(i));
836     break;
837   }
838   case ISD::TargetBlockAddress:
839   case ISD::BlockAddress: {
840     const BlockAddressSDNode *BA = cast<BlockAddressSDNode>(N);
841     ID.AddPointer(BA->getBlockAddress());
842     ID.AddInteger(BA->getOffset());
843     ID.AddInteger(BA->getTargetFlags());
844     break;
845   }
846   case ISD::AssertAlign:
847     ID.AddInteger(cast<AssertAlignSDNode>(N)->getAlign().value());
848     break;
849   } // end switch (N->getOpcode())
850 
851   // Target specific memory nodes could also have address spaces and flags
852   // to check.
853   if (N->isTargetMemoryOpcode()) {
854     const MemSDNode *MN = cast<MemSDNode>(N);
855     ID.AddInteger(MN->getPointerInfo().getAddrSpace());
856     ID.AddInteger(MN->getMemOperand()->getFlags());
857   }
858 }
859 
860 /// AddNodeIDNode - Generic routine for adding a nodes info to the NodeID
861 /// data.
862 static void AddNodeIDNode(FoldingSetNodeID &ID, const SDNode *N) {
863   AddNodeIDOpcode(ID, N->getOpcode());
864   // Add the return value info.
865   AddNodeIDValueTypes(ID, N->getVTList());
866   // Add the operand info.
867   AddNodeIDOperands(ID, N->ops());
868 
869   // Handle SDNode leafs with special info.
870   AddNodeIDCustom(ID, N);
871 }
872 
873 //===----------------------------------------------------------------------===//
874 //                              SelectionDAG Class
875 //===----------------------------------------------------------------------===//
876 
877 /// doNotCSE - Return true if CSE should not be performed for this node.
878 static bool doNotCSE(SDNode *N) {
879   if (N->getValueType(0) == MVT::Glue)
880     return true; // Never CSE anything that produces a flag.
881 
882   switch (N->getOpcode()) {
883   default: break;
884   case ISD::HANDLENODE:
885   case ISD::EH_LABEL:
886     return true;   // Never CSE these nodes.
887   }
888 
889   // Check that remaining values produced are not flags.
890   for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
891     if (N->getValueType(i) == MVT::Glue)
892       return true; // Never CSE anything that produces a flag.
893 
894   return false;
895 }
896 
897 /// RemoveDeadNodes - This method deletes all unreachable nodes in the
898 /// SelectionDAG.
899 void SelectionDAG::RemoveDeadNodes() {
900   // Create a dummy node (which is not added to allnodes), that adds a reference
901   // to the root node, preventing it from being deleted.
902   HandleSDNode Dummy(getRoot());
903 
904   SmallVector<SDNode*, 128> DeadNodes;
905 
906   // Add all obviously-dead nodes to the DeadNodes worklist.
907   for (SDNode &Node : allnodes())
908     if (Node.use_empty())
909       DeadNodes.push_back(&Node);
910 
911   RemoveDeadNodes(DeadNodes);
912 
913   // If the root changed (e.g. it was a dead load, update the root).
914   setRoot(Dummy.getValue());
915 }
916 
917 /// RemoveDeadNodes - This method deletes the unreachable nodes in the
918 /// given list, and any nodes that become unreachable as a result.
919 void SelectionDAG::RemoveDeadNodes(SmallVectorImpl<SDNode *> &DeadNodes) {
920 
921   // Process the worklist, deleting the nodes and adding their uses to the
922   // worklist.
923   while (!DeadNodes.empty()) {
924     SDNode *N = DeadNodes.pop_back_val();
925     // Skip to next node if we've already managed to delete the node. This could
926     // happen if replacing a node causes a node previously added to the node to
927     // be deleted.
928     if (N->getOpcode() == ISD::DELETED_NODE)
929       continue;
930 
931     for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
932       DUL->NodeDeleted(N, nullptr);
933 
934     // Take the node out of the appropriate CSE map.
935     RemoveNodeFromCSEMaps(N);
936 
937     // Next, brutally remove the operand list.  This is safe to do, as there are
938     // no cycles in the graph.
939     for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) {
940       SDUse &Use = *I++;
941       SDNode *Operand = Use.getNode();
942       Use.set(SDValue());
943 
944       // Now that we removed this operand, see if there are no uses of it left.
945       if (Operand->use_empty())
946         DeadNodes.push_back(Operand);
947     }
948 
949     DeallocateNode(N);
950   }
951 }
952 
953 void SelectionDAG::RemoveDeadNode(SDNode *N){
954   SmallVector<SDNode*, 16> DeadNodes(1, N);
955 
956   // Create a dummy node that adds a reference to the root node, preventing
957   // it from being deleted.  (This matters if the root is an operand of the
958   // dead node.)
959   HandleSDNode Dummy(getRoot());
960 
961   RemoveDeadNodes(DeadNodes);
962 }
963 
964 void SelectionDAG::DeleteNode(SDNode *N) {
965   // First take this out of the appropriate CSE map.
966   RemoveNodeFromCSEMaps(N);
967 
968   // Finally, remove uses due to operands of this node, remove from the
969   // AllNodes list, and delete the node.
970   DeleteNodeNotInCSEMaps(N);
971 }
972 
973 void SelectionDAG::DeleteNodeNotInCSEMaps(SDNode *N) {
974   assert(N->getIterator() != AllNodes.begin() &&
975          "Cannot delete the entry node!");
976   assert(N->use_empty() && "Cannot delete a node that is not dead!");
977 
978   // Drop all of the operands and decrement used node's use counts.
979   N->DropOperands();
980 
981   DeallocateNode(N);
982 }
983 
984 void SDDbgInfo::add(SDDbgValue *V, bool isParameter) {
985   assert(!(V->isVariadic() && isParameter));
986   if (isParameter)
987     ByvalParmDbgValues.push_back(V);
988   else
989     DbgValues.push_back(V);
990   for (const SDNode *Node : V->getSDNodes())
991     if (Node)
992       DbgValMap[Node].push_back(V);
993 }
994 
995 void SDDbgInfo::erase(const SDNode *Node) {
996   DbgValMapType::iterator I = DbgValMap.find(Node);
997   if (I == DbgValMap.end())
998     return;
999   for (auto &Val: I->second)
1000     Val->setIsInvalidated();
1001   DbgValMap.erase(I);
1002 }
1003 
1004 void SelectionDAG::DeallocateNode(SDNode *N) {
1005   // If we have operands, deallocate them.
1006   removeOperands(N);
1007 
1008   NodeAllocator.Deallocate(AllNodes.remove(N));
1009 
1010   // Set the opcode to DELETED_NODE to help catch bugs when node
1011   // memory is reallocated.
1012   // FIXME: There are places in SDag that have grown a dependency on the opcode
1013   // value in the released node.
1014   __asan_unpoison_memory_region(&N->NodeType, sizeof(N->NodeType));
1015   N->NodeType = ISD::DELETED_NODE;
1016 
1017   // If any of the SDDbgValue nodes refer to this SDNode, invalidate
1018   // them and forget about that node.
1019   DbgInfo->erase(N);
1020 }
1021 
1022 #ifndef NDEBUG
1023 /// VerifySDNode - Check the given SDNode.  Aborts if it is invalid.
1024 static void VerifySDNode(SDNode *N) {
1025   switch (N->getOpcode()) {
1026   default:
1027     break;
1028   case ISD::BUILD_PAIR: {
1029     EVT VT = N->getValueType(0);
1030     assert(N->getNumValues() == 1 && "Too many results!");
1031     assert(!VT.isVector() && (VT.isInteger() || VT.isFloatingPoint()) &&
1032            "Wrong return type!");
1033     assert(N->getNumOperands() == 2 && "Wrong number of operands!");
1034     assert(N->getOperand(0).getValueType() == N->getOperand(1).getValueType() &&
1035            "Mismatched operand types!");
1036     assert(N->getOperand(0).getValueType().isInteger() == VT.isInteger() &&
1037            "Wrong operand type!");
1038     assert(VT.getSizeInBits() == 2 * N->getOperand(0).getValueSizeInBits() &&
1039            "Wrong return type size");
1040     break;
1041   }
1042   case ISD::BUILD_VECTOR: {
1043     assert(N->getNumValues() == 1 && "Too many results!");
1044     assert(N->getValueType(0).isVector() && "Wrong return type!");
1045     assert(N->getNumOperands() == N->getValueType(0).getVectorNumElements() &&
1046            "Wrong number of operands!");
1047     EVT EltVT = N->getValueType(0).getVectorElementType();
1048     for (const SDUse &Op : N->ops()) {
1049       assert((Op.getValueType() == EltVT ||
1050               (EltVT.isInteger() && Op.getValueType().isInteger() &&
1051                EltVT.bitsLE(Op.getValueType()))) &&
1052              "Wrong operand type!");
1053       assert(Op.getValueType() == N->getOperand(0).getValueType() &&
1054              "Operands must all have the same type");
1055     }
1056     break;
1057   }
1058   }
1059 }
1060 #endif // NDEBUG
1061 
1062 /// Insert a newly allocated node into the DAG.
1063 ///
1064 /// Handles insertion into the all nodes list and CSE map, as well as
1065 /// verification and other common operations when a new node is allocated.
1066 void SelectionDAG::InsertNode(SDNode *N) {
1067   AllNodes.push_back(N);
1068 #ifndef NDEBUG
1069   N->PersistentId = NextPersistentId++;
1070   VerifySDNode(N);
1071 #endif
1072   for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
1073     DUL->NodeInserted(N);
1074 }
1075 
1076 /// RemoveNodeFromCSEMaps - Take the specified node out of the CSE map that
1077 /// correspond to it.  This is useful when we're about to delete or repurpose
1078 /// the node.  We don't want future request for structurally identical nodes
1079 /// to return N anymore.
1080 bool SelectionDAG::RemoveNodeFromCSEMaps(SDNode *N) {
1081   bool Erased = false;
1082   switch (N->getOpcode()) {
1083   case ISD::HANDLENODE: return false;  // noop.
1084   case ISD::CONDCODE:
1085     assert(CondCodeNodes[cast<CondCodeSDNode>(N)->get()] &&
1086            "Cond code doesn't exist!");
1087     Erased = CondCodeNodes[cast<CondCodeSDNode>(N)->get()] != nullptr;
1088     CondCodeNodes[cast<CondCodeSDNode>(N)->get()] = nullptr;
1089     break;
1090   case ISD::ExternalSymbol:
1091     Erased = ExternalSymbols.erase(cast<ExternalSymbolSDNode>(N)->getSymbol());
1092     break;
1093   case ISD::TargetExternalSymbol: {
1094     ExternalSymbolSDNode *ESN = cast<ExternalSymbolSDNode>(N);
1095     Erased = TargetExternalSymbols.erase(std::pair<std::string, unsigned>(
1096         ESN->getSymbol(), ESN->getTargetFlags()));
1097     break;
1098   }
1099   case ISD::MCSymbol: {
1100     auto *MCSN = cast<MCSymbolSDNode>(N);
1101     Erased = MCSymbols.erase(MCSN->getMCSymbol());
1102     break;
1103   }
1104   case ISD::VALUETYPE: {
1105     EVT VT = cast<VTSDNode>(N)->getVT();
1106     if (VT.isExtended()) {
1107       Erased = ExtendedValueTypeNodes.erase(VT);
1108     } else {
1109       Erased = ValueTypeNodes[VT.getSimpleVT().SimpleTy] != nullptr;
1110       ValueTypeNodes[VT.getSimpleVT().SimpleTy] = nullptr;
1111     }
1112     break;
1113   }
1114   default:
1115     // Remove it from the CSE Map.
1116     assert(N->getOpcode() != ISD::DELETED_NODE && "DELETED_NODE in CSEMap!");
1117     assert(N->getOpcode() != ISD::EntryToken && "EntryToken in CSEMap!");
1118     Erased = CSEMap.RemoveNode(N);
1119     break;
1120   }
1121 #ifndef NDEBUG
1122   // Verify that the node was actually in one of the CSE maps, unless it has a
1123   // flag result (which cannot be CSE'd) or is one of the special cases that are
1124   // not subject to CSE.
1125   if (!Erased && N->getValueType(N->getNumValues()-1) != MVT::Glue &&
1126       !N->isMachineOpcode() && !doNotCSE(N)) {
1127     N->dump(this);
1128     dbgs() << "\n";
1129     llvm_unreachable("Node is not in map!");
1130   }
1131 #endif
1132   return Erased;
1133 }
1134 
1135 /// AddModifiedNodeToCSEMaps - The specified node has been removed from the CSE
1136 /// maps and modified in place. Add it back to the CSE maps, unless an identical
1137 /// node already exists, in which case transfer all its users to the existing
1138 /// node. This transfer can potentially trigger recursive merging.
1139 void
1140 SelectionDAG::AddModifiedNodeToCSEMaps(SDNode *N) {
1141   // For node types that aren't CSE'd, just act as if no identical node
1142   // already exists.
1143   if (!doNotCSE(N)) {
1144     SDNode *Existing = CSEMap.GetOrInsertNode(N);
1145     if (Existing != N) {
1146       // If there was already an existing matching node, use ReplaceAllUsesWith
1147       // to replace the dead one with the existing one.  This can cause
1148       // recursive merging of other unrelated nodes down the line.
1149       ReplaceAllUsesWith(N, Existing);
1150 
1151       // N is now dead. Inform the listeners and delete it.
1152       for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
1153         DUL->NodeDeleted(N, Existing);
1154       DeleteNodeNotInCSEMaps(N);
1155       return;
1156     }
1157   }
1158 
1159   // If the node doesn't already exist, we updated it.  Inform listeners.
1160   for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
1161     DUL->NodeUpdated(N);
1162 }
1163 
1164 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
1165 /// were replaced with those specified.  If this node is never memoized,
1166 /// return null, otherwise return a pointer to the slot it would take.  If a
1167 /// node already exists with these operands, the slot will be non-null.
1168 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, SDValue Op,
1169                                            void *&InsertPos) {
1170   if (doNotCSE(N))
1171     return nullptr;
1172 
1173   SDValue Ops[] = { Op };
1174   FoldingSetNodeID ID;
1175   AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops);
1176   AddNodeIDCustom(ID, N);
1177   SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos);
1178   if (Node)
1179     Node->intersectFlagsWith(N->getFlags());
1180   return Node;
1181 }
1182 
1183 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
1184 /// were replaced with those specified.  If this node is never memoized,
1185 /// return null, otherwise return a pointer to the slot it would take.  If a
1186 /// node already exists with these operands, the slot will be non-null.
1187 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N,
1188                                            SDValue Op1, SDValue Op2,
1189                                            void *&InsertPos) {
1190   if (doNotCSE(N))
1191     return nullptr;
1192 
1193   SDValue Ops[] = { Op1, Op2 };
1194   FoldingSetNodeID ID;
1195   AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops);
1196   AddNodeIDCustom(ID, N);
1197   SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos);
1198   if (Node)
1199     Node->intersectFlagsWith(N->getFlags());
1200   return Node;
1201 }
1202 
1203 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
1204 /// were replaced with those specified.  If this node is never memoized,
1205 /// return null, otherwise return a pointer to the slot it would take.  If a
1206 /// node already exists with these operands, the slot will be non-null.
1207 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, ArrayRef<SDValue> Ops,
1208                                            void *&InsertPos) {
1209   if (doNotCSE(N))
1210     return nullptr;
1211 
1212   FoldingSetNodeID ID;
1213   AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops);
1214   AddNodeIDCustom(ID, N);
1215   SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos);
1216   if (Node)
1217     Node->intersectFlagsWith(N->getFlags());
1218   return Node;
1219 }
1220 
1221 Align SelectionDAG::getEVTAlign(EVT VT) const {
1222   Type *Ty = VT == MVT::iPTR ?
1223                    PointerType::get(Type::getInt8Ty(*getContext()), 0) :
1224                    VT.getTypeForEVT(*getContext());
1225 
1226   return getDataLayout().getABITypeAlign(Ty);
1227 }
1228 
1229 // EntryNode could meaningfully have debug info if we can find it...
1230 SelectionDAG::SelectionDAG(const TargetMachine &tm, CodeGenOpt::Level OL)
1231     : TM(tm), OptLevel(OL),
1232       EntryNode(ISD::EntryToken, 0, DebugLoc(), getVTList(MVT::Other)),
1233       Root(getEntryNode()) {
1234   InsertNode(&EntryNode);
1235   DbgInfo = new SDDbgInfo();
1236 }
1237 
1238 void SelectionDAG::init(MachineFunction &NewMF,
1239                         OptimizationRemarkEmitter &NewORE,
1240                         Pass *PassPtr, const TargetLibraryInfo *LibraryInfo,
1241                         LegacyDivergenceAnalysis * Divergence,
1242                         ProfileSummaryInfo *PSIin,
1243                         BlockFrequencyInfo *BFIin) {
1244   MF = &NewMF;
1245   SDAGISelPass = PassPtr;
1246   ORE = &NewORE;
1247   TLI = getSubtarget().getTargetLowering();
1248   TSI = getSubtarget().getSelectionDAGInfo();
1249   LibInfo = LibraryInfo;
1250   Context = &MF->getFunction().getContext();
1251   DA = Divergence;
1252   PSI = PSIin;
1253   BFI = BFIin;
1254 }
1255 
1256 SelectionDAG::~SelectionDAG() {
1257   assert(!UpdateListeners && "Dangling registered DAGUpdateListeners");
1258   allnodes_clear();
1259   OperandRecycler.clear(OperandAllocator);
1260   delete DbgInfo;
1261 }
1262 
1263 bool SelectionDAG::shouldOptForSize() const {
1264   return MF->getFunction().hasOptSize() ||
1265       llvm::shouldOptimizeForSize(FLI->MBB->getBasicBlock(), PSI, BFI);
1266 }
1267 
1268 void SelectionDAG::allnodes_clear() {
1269   assert(&*AllNodes.begin() == &EntryNode);
1270   AllNodes.remove(AllNodes.begin());
1271   while (!AllNodes.empty())
1272     DeallocateNode(&AllNodes.front());
1273 #ifndef NDEBUG
1274   NextPersistentId = 0;
1275 #endif
1276 }
1277 
1278 SDNode *SelectionDAG::FindNodeOrInsertPos(const FoldingSetNodeID &ID,
1279                                           void *&InsertPos) {
1280   SDNode *N = CSEMap.FindNodeOrInsertPos(ID, InsertPos);
1281   if (N) {
1282     switch (N->getOpcode()) {
1283     default: break;
1284     case ISD::Constant:
1285     case ISD::ConstantFP:
1286       llvm_unreachable("Querying for Constant and ConstantFP nodes requires "
1287                        "debug location.  Use another overload.");
1288     }
1289   }
1290   return N;
1291 }
1292 
1293 SDNode *SelectionDAG::FindNodeOrInsertPos(const FoldingSetNodeID &ID,
1294                                           const SDLoc &DL, void *&InsertPos) {
1295   SDNode *N = CSEMap.FindNodeOrInsertPos(ID, InsertPos);
1296   if (N) {
1297     switch (N->getOpcode()) {
1298     case ISD::Constant:
1299     case ISD::ConstantFP:
1300       // Erase debug location from the node if the node is used at several
1301       // different places. Do not propagate one location to all uses as it
1302       // will cause a worse single stepping debugging experience.
1303       if (N->getDebugLoc() != DL.getDebugLoc())
1304         N->setDebugLoc(DebugLoc());
1305       break;
1306     default:
1307       // When the node's point of use is located earlier in the instruction
1308       // sequence than its prior point of use, update its debug info to the
1309       // earlier location.
1310       if (DL.getIROrder() && DL.getIROrder() < N->getIROrder())
1311         N->setDebugLoc(DL.getDebugLoc());
1312       break;
1313     }
1314   }
1315   return N;
1316 }
1317 
1318 void SelectionDAG::clear() {
1319   allnodes_clear();
1320   OperandRecycler.clear(OperandAllocator);
1321   OperandAllocator.Reset();
1322   CSEMap.clear();
1323 
1324   ExtendedValueTypeNodes.clear();
1325   ExternalSymbols.clear();
1326   TargetExternalSymbols.clear();
1327   MCSymbols.clear();
1328   SDCallSiteDbgInfo.clear();
1329   std::fill(CondCodeNodes.begin(), CondCodeNodes.end(),
1330             static_cast<CondCodeSDNode*>(nullptr));
1331   std::fill(ValueTypeNodes.begin(), ValueTypeNodes.end(),
1332             static_cast<SDNode*>(nullptr));
1333 
1334   EntryNode.UseList = nullptr;
1335   InsertNode(&EntryNode);
1336   Root = getEntryNode();
1337   DbgInfo->clear();
1338 }
1339 
1340 SDValue SelectionDAG::getFPExtendOrRound(SDValue Op, const SDLoc &DL, EVT VT) {
1341   return VT.bitsGT(Op.getValueType())
1342              ? getNode(ISD::FP_EXTEND, DL, VT, Op)
1343              : getNode(ISD::FP_ROUND, DL, VT, Op, getIntPtrConstant(0, DL));
1344 }
1345 
1346 std::pair<SDValue, SDValue>
1347 SelectionDAG::getStrictFPExtendOrRound(SDValue Op, SDValue Chain,
1348                                        const SDLoc &DL, EVT VT) {
1349   assert(!VT.bitsEq(Op.getValueType()) &&
1350          "Strict no-op FP extend/round not allowed.");
1351   SDValue Res =
1352       VT.bitsGT(Op.getValueType())
1353           ? getNode(ISD::STRICT_FP_EXTEND, DL, {VT, MVT::Other}, {Chain, Op})
1354           : getNode(ISD::STRICT_FP_ROUND, DL, {VT, MVT::Other},
1355                     {Chain, Op, getIntPtrConstant(0, DL)});
1356 
1357   return std::pair<SDValue, SDValue>(Res, SDValue(Res.getNode(), 1));
1358 }
1359 
1360 SDValue SelectionDAG::getAnyExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
1361   return VT.bitsGT(Op.getValueType()) ?
1362     getNode(ISD::ANY_EXTEND, DL, VT, Op) :
1363     getNode(ISD::TRUNCATE, DL, VT, Op);
1364 }
1365 
1366 SDValue SelectionDAG::getSExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
1367   return VT.bitsGT(Op.getValueType()) ?
1368     getNode(ISD::SIGN_EXTEND, DL, VT, Op) :
1369     getNode(ISD::TRUNCATE, DL, VT, Op);
1370 }
1371 
1372 SDValue SelectionDAG::getZExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
1373   return VT.bitsGT(Op.getValueType()) ?
1374     getNode(ISD::ZERO_EXTEND, DL, VT, Op) :
1375     getNode(ISD::TRUNCATE, DL, VT, Op);
1376 }
1377 
1378 SDValue SelectionDAG::getBoolExtOrTrunc(SDValue Op, const SDLoc &SL, EVT VT,
1379                                         EVT OpVT) {
1380   if (VT.bitsLE(Op.getValueType()))
1381     return getNode(ISD::TRUNCATE, SL, VT, Op);
1382 
1383   TargetLowering::BooleanContent BType = TLI->getBooleanContents(OpVT);
1384   return getNode(TLI->getExtendForContent(BType), SL, VT, Op);
1385 }
1386 
1387 SDValue SelectionDAG::getZeroExtendInReg(SDValue Op, const SDLoc &DL, EVT VT) {
1388   EVT OpVT = Op.getValueType();
1389   assert(VT.isInteger() && OpVT.isInteger() &&
1390          "Cannot getZeroExtendInReg FP types");
1391   assert(VT.isVector() == OpVT.isVector() &&
1392          "getZeroExtendInReg type should be vector iff the operand "
1393          "type is vector!");
1394   assert((!VT.isVector() ||
1395           VT.getVectorElementCount() == OpVT.getVectorElementCount()) &&
1396          "Vector element counts must match in getZeroExtendInReg");
1397   assert(VT.bitsLE(OpVT) && "Not extending!");
1398   if (OpVT == VT)
1399     return Op;
1400   APInt Imm = APInt::getLowBitsSet(OpVT.getScalarSizeInBits(),
1401                                    VT.getScalarSizeInBits());
1402   return getNode(ISD::AND, DL, OpVT, Op, getConstant(Imm, DL, OpVT));
1403 }
1404 
1405 SDValue SelectionDAG::getPtrExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
1406   // Only unsigned pointer semantics are supported right now. In the future this
1407   // might delegate to TLI to check pointer signedness.
1408   return getZExtOrTrunc(Op, DL, VT);
1409 }
1410 
1411 SDValue SelectionDAG::getPtrExtendInReg(SDValue Op, const SDLoc &DL, EVT VT) {
1412   // Only unsigned pointer semantics are supported right now. In the future this
1413   // might delegate to TLI to check pointer signedness.
1414   return getZeroExtendInReg(Op, DL, VT);
1415 }
1416 
1417 /// getNOT - Create a bitwise NOT operation as (XOR Val, -1).
1418 SDValue SelectionDAG::getNOT(const SDLoc &DL, SDValue Val, EVT VT) {
1419   return getNode(ISD::XOR, DL, VT, Val, getAllOnesConstant(DL, VT));
1420 }
1421 
1422 SDValue SelectionDAG::getLogicalNOT(const SDLoc &DL, SDValue Val, EVT VT) {
1423   SDValue TrueValue = getBoolConstant(true, DL, VT, VT);
1424   return getNode(ISD::XOR, DL, VT, Val, TrueValue);
1425 }
1426 
1427 SDValue SelectionDAG::getVPLogicalNOT(const SDLoc &DL, SDValue Val,
1428                                       SDValue Mask, SDValue EVL, EVT VT) {
1429   SDValue TrueValue = getBoolConstant(true, DL, VT, VT);
1430   return getNode(ISD::VP_XOR, DL, VT, Val, TrueValue, Mask, EVL);
1431 }
1432 
1433 SDValue SelectionDAG::getBoolConstant(bool V, const SDLoc &DL, EVT VT,
1434                                       EVT OpVT) {
1435   if (!V)
1436     return getConstant(0, DL, VT);
1437 
1438   switch (TLI->getBooleanContents(OpVT)) {
1439   case TargetLowering::ZeroOrOneBooleanContent:
1440   case TargetLowering::UndefinedBooleanContent:
1441     return getConstant(1, DL, VT);
1442   case TargetLowering::ZeroOrNegativeOneBooleanContent:
1443     return getAllOnesConstant(DL, VT);
1444   }
1445   llvm_unreachable("Unexpected boolean content enum!");
1446 }
1447 
1448 SDValue SelectionDAG::getConstant(uint64_t Val, const SDLoc &DL, EVT VT,
1449                                   bool isT, bool isO) {
1450   EVT EltVT = VT.getScalarType();
1451   assert((EltVT.getSizeInBits() >= 64 ||
1452           (uint64_t)((int64_t)Val >> EltVT.getSizeInBits()) + 1 < 2) &&
1453          "getConstant with a uint64_t value that doesn't fit in the type!");
1454   return getConstant(APInt(EltVT.getSizeInBits(), Val), DL, VT, isT, isO);
1455 }
1456 
1457 SDValue SelectionDAG::getConstant(const APInt &Val, const SDLoc &DL, EVT VT,
1458                                   bool isT, bool isO) {
1459   return getConstant(*ConstantInt::get(*Context, Val), DL, VT, isT, isO);
1460 }
1461 
1462 SDValue SelectionDAG::getConstant(const ConstantInt &Val, const SDLoc &DL,
1463                                   EVT VT, bool isT, bool isO) {
1464   assert(VT.isInteger() && "Cannot create FP integer constant!");
1465 
1466   EVT EltVT = VT.getScalarType();
1467   const ConstantInt *Elt = &Val;
1468 
1469   // In some cases the vector type is legal but the element type is illegal and
1470   // needs to be promoted, for example v8i8 on ARM.  In this case, promote the
1471   // inserted value (the type does not need to match the vector element type).
1472   // Any extra bits introduced will be truncated away.
1473   if (VT.isVector() && TLI->getTypeAction(*getContext(), EltVT) ==
1474                            TargetLowering::TypePromoteInteger) {
1475     EltVT = TLI->getTypeToTransformTo(*getContext(), EltVT);
1476     APInt NewVal = Elt->getValue().zextOrTrunc(EltVT.getSizeInBits());
1477     Elt = ConstantInt::get(*getContext(), NewVal);
1478   }
1479   // In other cases the element type is illegal and needs to be expanded, for
1480   // example v2i64 on MIPS32. In this case, find the nearest legal type, split
1481   // the value into n parts and use a vector type with n-times the elements.
1482   // Then bitcast to the type requested.
1483   // Legalizing constants too early makes the DAGCombiner's job harder so we
1484   // only legalize if the DAG tells us we must produce legal types.
1485   else if (NewNodesMustHaveLegalTypes && VT.isVector() &&
1486            TLI->getTypeAction(*getContext(), EltVT) ==
1487                TargetLowering::TypeExpandInteger) {
1488     const APInt &NewVal = Elt->getValue();
1489     EVT ViaEltVT = TLI->getTypeToTransformTo(*getContext(), EltVT);
1490     unsigned ViaEltSizeInBits = ViaEltVT.getSizeInBits();
1491 
1492     // For scalable vectors, try to use a SPLAT_VECTOR_PARTS node.
1493     if (VT.isScalableVector()) {
1494       assert(EltVT.getSizeInBits() % ViaEltSizeInBits == 0 &&
1495              "Can only handle an even split!");
1496       unsigned Parts = EltVT.getSizeInBits() / ViaEltSizeInBits;
1497 
1498       SmallVector<SDValue, 2> ScalarParts;
1499       for (unsigned i = 0; i != Parts; ++i)
1500         ScalarParts.push_back(getConstant(
1501             NewVal.extractBits(ViaEltSizeInBits, i * ViaEltSizeInBits), DL,
1502             ViaEltVT, isT, isO));
1503 
1504       return getNode(ISD::SPLAT_VECTOR_PARTS, DL, VT, ScalarParts);
1505     }
1506 
1507     unsigned ViaVecNumElts = VT.getSizeInBits() / ViaEltSizeInBits;
1508     EVT ViaVecVT = EVT::getVectorVT(*getContext(), ViaEltVT, ViaVecNumElts);
1509 
1510     // Check the temporary vector is the correct size. If this fails then
1511     // getTypeToTransformTo() probably returned a type whose size (in bits)
1512     // isn't a power-of-2 factor of the requested type size.
1513     assert(ViaVecVT.getSizeInBits() == VT.getSizeInBits());
1514 
1515     SmallVector<SDValue, 2> EltParts;
1516     for (unsigned i = 0; i < ViaVecNumElts / VT.getVectorNumElements(); ++i)
1517       EltParts.push_back(getConstant(
1518           NewVal.extractBits(ViaEltSizeInBits, i * ViaEltSizeInBits), DL,
1519           ViaEltVT, isT, isO));
1520 
1521     // EltParts is currently in little endian order. If we actually want
1522     // big-endian order then reverse it now.
1523     if (getDataLayout().isBigEndian())
1524       std::reverse(EltParts.begin(), EltParts.end());
1525 
1526     // The elements must be reversed when the element order is different
1527     // to the endianness of the elements (because the BITCAST is itself a
1528     // vector shuffle in this situation). However, we do not need any code to
1529     // perform this reversal because getConstant() is producing a vector
1530     // splat.
1531     // This situation occurs in MIPS MSA.
1532 
1533     SmallVector<SDValue, 8> Ops;
1534     for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
1535       llvm::append_range(Ops, EltParts);
1536 
1537     SDValue V =
1538         getNode(ISD::BITCAST, DL, VT, getBuildVector(ViaVecVT, DL, Ops));
1539     return V;
1540   }
1541 
1542   assert(Elt->getBitWidth() == EltVT.getSizeInBits() &&
1543          "APInt size does not match type size!");
1544   unsigned Opc = isT ? ISD::TargetConstant : ISD::Constant;
1545   FoldingSetNodeID ID;
1546   AddNodeIDNode(ID, Opc, getVTList(EltVT), None);
1547   ID.AddPointer(Elt);
1548   ID.AddBoolean(isO);
1549   void *IP = nullptr;
1550   SDNode *N = nullptr;
1551   if ((N = FindNodeOrInsertPos(ID, DL, IP)))
1552     if (!VT.isVector())
1553       return SDValue(N, 0);
1554 
1555   if (!N) {
1556     N = newSDNode<ConstantSDNode>(isT, isO, Elt, EltVT);
1557     CSEMap.InsertNode(N, IP);
1558     InsertNode(N);
1559     NewSDValueDbgMsg(SDValue(N, 0), "Creating constant: ", this);
1560   }
1561 
1562   SDValue Result(N, 0);
1563   if (VT.isScalableVector())
1564     Result = getSplatVector(VT, DL, Result);
1565   else if (VT.isVector())
1566     Result = getSplatBuildVector(VT, DL, Result);
1567 
1568   return Result;
1569 }
1570 
1571 SDValue SelectionDAG::getIntPtrConstant(uint64_t Val, const SDLoc &DL,
1572                                         bool isTarget) {
1573   return getConstant(Val, DL, TLI->getPointerTy(getDataLayout()), isTarget);
1574 }
1575 
1576 SDValue SelectionDAG::getShiftAmountConstant(uint64_t Val, EVT VT,
1577                                              const SDLoc &DL, bool LegalTypes) {
1578   assert(VT.isInteger() && "Shift amount is not an integer type!");
1579   EVT ShiftVT = TLI->getShiftAmountTy(VT, getDataLayout(), LegalTypes);
1580   return getConstant(Val, DL, ShiftVT);
1581 }
1582 
1583 SDValue SelectionDAG::getVectorIdxConstant(uint64_t Val, const SDLoc &DL,
1584                                            bool isTarget) {
1585   return getConstant(Val, DL, TLI->getVectorIdxTy(getDataLayout()), isTarget);
1586 }
1587 
1588 SDValue SelectionDAG::getConstantFP(const APFloat &V, const SDLoc &DL, EVT VT,
1589                                     bool isTarget) {
1590   return getConstantFP(*ConstantFP::get(*getContext(), V), DL, VT, isTarget);
1591 }
1592 
1593 SDValue SelectionDAG::getConstantFP(const ConstantFP &V, const SDLoc &DL,
1594                                     EVT VT, bool isTarget) {
1595   assert(VT.isFloatingPoint() && "Cannot create integer FP constant!");
1596 
1597   EVT EltVT = VT.getScalarType();
1598 
1599   // Do the map lookup using the actual bit pattern for the floating point
1600   // value, so that we don't have problems with 0.0 comparing equal to -0.0, and
1601   // we don't have issues with SNANs.
1602   unsigned Opc = isTarget ? ISD::TargetConstantFP : ISD::ConstantFP;
1603   FoldingSetNodeID ID;
1604   AddNodeIDNode(ID, Opc, getVTList(EltVT), None);
1605   ID.AddPointer(&V);
1606   void *IP = nullptr;
1607   SDNode *N = nullptr;
1608   if ((N = FindNodeOrInsertPos(ID, DL, IP)))
1609     if (!VT.isVector())
1610       return SDValue(N, 0);
1611 
1612   if (!N) {
1613     N = newSDNode<ConstantFPSDNode>(isTarget, &V, EltVT);
1614     CSEMap.InsertNode(N, IP);
1615     InsertNode(N);
1616   }
1617 
1618   SDValue Result(N, 0);
1619   if (VT.isScalableVector())
1620     Result = getSplatVector(VT, DL, Result);
1621   else if (VT.isVector())
1622     Result = getSplatBuildVector(VT, DL, Result);
1623   NewSDValueDbgMsg(Result, "Creating fp constant: ", this);
1624   return Result;
1625 }
1626 
1627 SDValue SelectionDAG::getConstantFP(double Val, const SDLoc &DL, EVT VT,
1628                                     bool isTarget) {
1629   EVT EltVT = VT.getScalarType();
1630   if (EltVT == MVT::f32)
1631     return getConstantFP(APFloat((float)Val), DL, VT, isTarget);
1632   if (EltVT == MVT::f64)
1633     return getConstantFP(APFloat(Val), DL, VT, isTarget);
1634   if (EltVT == MVT::f80 || EltVT == MVT::f128 || EltVT == MVT::ppcf128 ||
1635       EltVT == MVT::f16 || EltVT == MVT::bf16) {
1636     bool Ignored;
1637     APFloat APF = APFloat(Val);
1638     APF.convert(EVTToAPFloatSemantics(EltVT), APFloat::rmNearestTiesToEven,
1639                 &Ignored);
1640     return getConstantFP(APF, DL, VT, isTarget);
1641   }
1642   llvm_unreachable("Unsupported type in getConstantFP");
1643 }
1644 
1645 SDValue SelectionDAG::getGlobalAddress(const GlobalValue *GV, const SDLoc &DL,
1646                                        EVT VT, int64_t Offset, bool isTargetGA,
1647                                        unsigned TargetFlags) {
1648   assert((TargetFlags == 0 || isTargetGA) &&
1649          "Cannot set target flags on target-independent globals");
1650 
1651   // Truncate (with sign-extension) the offset value to the pointer size.
1652   unsigned BitWidth = getDataLayout().getPointerTypeSizeInBits(GV->getType());
1653   if (BitWidth < 64)
1654     Offset = SignExtend64(Offset, BitWidth);
1655 
1656   unsigned Opc;
1657   if (GV->isThreadLocal())
1658     Opc = isTargetGA ? ISD::TargetGlobalTLSAddress : ISD::GlobalTLSAddress;
1659   else
1660     Opc = isTargetGA ? ISD::TargetGlobalAddress : ISD::GlobalAddress;
1661 
1662   FoldingSetNodeID ID;
1663   AddNodeIDNode(ID, Opc, getVTList(VT), None);
1664   ID.AddPointer(GV);
1665   ID.AddInteger(Offset);
1666   ID.AddInteger(TargetFlags);
1667   void *IP = nullptr;
1668   if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
1669     return SDValue(E, 0);
1670 
1671   auto *N = newSDNode<GlobalAddressSDNode>(
1672       Opc, DL.getIROrder(), DL.getDebugLoc(), GV, VT, Offset, TargetFlags);
1673   CSEMap.InsertNode(N, IP);
1674     InsertNode(N);
1675   return SDValue(N, 0);
1676 }
1677 
1678 SDValue SelectionDAG::getFrameIndex(int FI, EVT VT, bool isTarget) {
1679   unsigned Opc = isTarget ? ISD::TargetFrameIndex : ISD::FrameIndex;
1680   FoldingSetNodeID ID;
1681   AddNodeIDNode(ID, Opc, getVTList(VT), None);
1682   ID.AddInteger(FI);
1683   void *IP = nullptr;
1684   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1685     return SDValue(E, 0);
1686 
1687   auto *N = newSDNode<FrameIndexSDNode>(FI, VT, isTarget);
1688   CSEMap.InsertNode(N, IP);
1689   InsertNode(N);
1690   return SDValue(N, 0);
1691 }
1692 
1693 SDValue SelectionDAG::getJumpTable(int JTI, EVT VT, bool isTarget,
1694                                    unsigned TargetFlags) {
1695   assert((TargetFlags == 0 || isTarget) &&
1696          "Cannot set target flags on target-independent jump tables");
1697   unsigned Opc = isTarget ? ISD::TargetJumpTable : ISD::JumpTable;
1698   FoldingSetNodeID ID;
1699   AddNodeIDNode(ID, Opc, getVTList(VT), None);
1700   ID.AddInteger(JTI);
1701   ID.AddInteger(TargetFlags);
1702   void *IP = nullptr;
1703   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1704     return SDValue(E, 0);
1705 
1706   auto *N = newSDNode<JumpTableSDNode>(JTI, VT, isTarget, TargetFlags);
1707   CSEMap.InsertNode(N, IP);
1708   InsertNode(N);
1709   return SDValue(N, 0);
1710 }
1711 
1712 SDValue SelectionDAG::getConstantPool(const Constant *C, EVT VT,
1713                                       MaybeAlign Alignment, int Offset,
1714                                       bool isTarget, unsigned TargetFlags) {
1715   assert((TargetFlags == 0 || isTarget) &&
1716          "Cannot set target flags on target-independent globals");
1717   if (!Alignment)
1718     Alignment = shouldOptForSize()
1719                     ? getDataLayout().getABITypeAlign(C->getType())
1720                     : getDataLayout().getPrefTypeAlign(C->getType());
1721   unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
1722   FoldingSetNodeID ID;
1723   AddNodeIDNode(ID, Opc, getVTList(VT), None);
1724   ID.AddInteger(Alignment->value());
1725   ID.AddInteger(Offset);
1726   ID.AddPointer(C);
1727   ID.AddInteger(TargetFlags);
1728   void *IP = nullptr;
1729   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1730     return SDValue(E, 0);
1731 
1732   auto *N = newSDNode<ConstantPoolSDNode>(isTarget, C, VT, Offset, *Alignment,
1733                                           TargetFlags);
1734   CSEMap.InsertNode(N, IP);
1735   InsertNode(N);
1736   SDValue V = SDValue(N, 0);
1737   NewSDValueDbgMsg(V, "Creating new constant pool: ", this);
1738   return V;
1739 }
1740 
1741 SDValue SelectionDAG::getConstantPool(MachineConstantPoolValue *C, EVT VT,
1742                                       MaybeAlign Alignment, int Offset,
1743                                       bool isTarget, unsigned TargetFlags) {
1744   assert((TargetFlags == 0 || isTarget) &&
1745          "Cannot set target flags on target-independent globals");
1746   if (!Alignment)
1747     Alignment = getDataLayout().getPrefTypeAlign(C->getType());
1748   unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
1749   FoldingSetNodeID ID;
1750   AddNodeIDNode(ID, Opc, getVTList(VT), None);
1751   ID.AddInteger(Alignment->value());
1752   ID.AddInteger(Offset);
1753   C->addSelectionDAGCSEId(ID);
1754   ID.AddInteger(TargetFlags);
1755   void *IP = nullptr;
1756   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1757     return SDValue(E, 0);
1758 
1759   auto *N = newSDNode<ConstantPoolSDNode>(isTarget, C, VT, Offset, *Alignment,
1760                                           TargetFlags);
1761   CSEMap.InsertNode(N, IP);
1762   InsertNode(N);
1763   return SDValue(N, 0);
1764 }
1765 
1766 SDValue SelectionDAG::getTargetIndex(int Index, EVT VT, int64_t Offset,
1767                                      unsigned TargetFlags) {
1768   FoldingSetNodeID ID;
1769   AddNodeIDNode(ID, ISD::TargetIndex, getVTList(VT), None);
1770   ID.AddInteger(Index);
1771   ID.AddInteger(Offset);
1772   ID.AddInteger(TargetFlags);
1773   void *IP = nullptr;
1774   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1775     return SDValue(E, 0);
1776 
1777   auto *N = newSDNode<TargetIndexSDNode>(Index, VT, Offset, TargetFlags);
1778   CSEMap.InsertNode(N, IP);
1779   InsertNode(N);
1780   return SDValue(N, 0);
1781 }
1782 
1783 SDValue SelectionDAG::getBasicBlock(MachineBasicBlock *MBB) {
1784   FoldingSetNodeID ID;
1785   AddNodeIDNode(ID, ISD::BasicBlock, getVTList(MVT::Other), None);
1786   ID.AddPointer(MBB);
1787   void *IP = nullptr;
1788   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1789     return SDValue(E, 0);
1790 
1791   auto *N = newSDNode<BasicBlockSDNode>(MBB);
1792   CSEMap.InsertNode(N, IP);
1793   InsertNode(N);
1794   return SDValue(N, 0);
1795 }
1796 
1797 SDValue SelectionDAG::getValueType(EVT VT) {
1798   if (VT.isSimple() && (unsigned)VT.getSimpleVT().SimpleTy >=
1799       ValueTypeNodes.size())
1800     ValueTypeNodes.resize(VT.getSimpleVT().SimpleTy+1);
1801 
1802   SDNode *&N = VT.isExtended() ?
1803     ExtendedValueTypeNodes[VT] : ValueTypeNodes[VT.getSimpleVT().SimpleTy];
1804 
1805   if (N) return SDValue(N, 0);
1806   N = newSDNode<VTSDNode>(VT);
1807   InsertNode(N);
1808   return SDValue(N, 0);
1809 }
1810 
1811 SDValue SelectionDAG::getExternalSymbol(const char *Sym, EVT VT) {
1812   SDNode *&N = ExternalSymbols[Sym];
1813   if (N) return SDValue(N, 0);
1814   N = newSDNode<ExternalSymbolSDNode>(false, Sym, 0, VT);
1815   InsertNode(N);
1816   return SDValue(N, 0);
1817 }
1818 
1819 SDValue SelectionDAG::getMCSymbol(MCSymbol *Sym, EVT VT) {
1820   SDNode *&N = MCSymbols[Sym];
1821   if (N)
1822     return SDValue(N, 0);
1823   N = newSDNode<MCSymbolSDNode>(Sym, VT);
1824   InsertNode(N);
1825   return SDValue(N, 0);
1826 }
1827 
1828 SDValue SelectionDAG::getTargetExternalSymbol(const char *Sym, EVT VT,
1829                                               unsigned TargetFlags) {
1830   SDNode *&N =
1831       TargetExternalSymbols[std::pair<std::string, unsigned>(Sym, TargetFlags)];
1832   if (N) return SDValue(N, 0);
1833   N = newSDNode<ExternalSymbolSDNode>(true, Sym, TargetFlags, VT);
1834   InsertNode(N);
1835   return SDValue(N, 0);
1836 }
1837 
1838 SDValue SelectionDAG::getCondCode(ISD::CondCode Cond) {
1839   if ((unsigned)Cond >= CondCodeNodes.size())
1840     CondCodeNodes.resize(Cond+1);
1841 
1842   if (!CondCodeNodes[Cond]) {
1843     auto *N = newSDNode<CondCodeSDNode>(Cond);
1844     CondCodeNodes[Cond] = N;
1845     InsertNode(N);
1846   }
1847 
1848   return SDValue(CondCodeNodes[Cond], 0);
1849 }
1850 
1851 SDValue SelectionDAG::getStepVector(const SDLoc &DL, EVT ResVT) {
1852   APInt One(ResVT.getScalarSizeInBits(), 1);
1853   return getStepVector(DL, ResVT, One);
1854 }
1855 
1856 SDValue SelectionDAG::getStepVector(const SDLoc &DL, EVT ResVT, APInt StepVal) {
1857   assert(ResVT.getScalarSizeInBits() == StepVal.getBitWidth());
1858   if (ResVT.isScalableVector())
1859     return getNode(
1860         ISD::STEP_VECTOR, DL, ResVT,
1861         getTargetConstant(StepVal, DL, ResVT.getVectorElementType()));
1862 
1863   SmallVector<SDValue, 16> OpsStepConstants;
1864   for (uint64_t i = 0; i < ResVT.getVectorNumElements(); i++)
1865     OpsStepConstants.push_back(
1866         getConstant(StepVal * i, DL, ResVT.getVectorElementType()));
1867   return getBuildVector(ResVT, DL, OpsStepConstants);
1868 }
1869 
1870 /// Swaps the values of N1 and N2. Swaps all indices in the shuffle mask M that
1871 /// point at N1 to point at N2 and indices that point at N2 to point at N1.
1872 static void commuteShuffle(SDValue &N1, SDValue &N2, MutableArrayRef<int> M) {
1873   std::swap(N1, N2);
1874   ShuffleVectorSDNode::commuteMask(M);
1875 }
1876 
1877 SDValue SelectionDAG::getVectorShuffle(EVT VT, const SDLoc &dl, SDValue N1,
1878                                        SDValue N2, ArrayRef<int> Mask) {
1879   assert(VT.getVectorNumElements() == Mask.size() &&
1880          "Must have the same number of vector elements as mask elements!");
1881   assert(VT == N1.getValueType() && VT == N2.getValueType() &&
1882          "Invalid VECTOR_SHUFFLE");
1883 
1884   // Canonicalize shuffle undef, undef -> undef
1885   if (N1.isUndef() && N2.isUndef())
1886     return getUNDEF(VT);
1887 
1888   // Validate that all indices in Mask are within the range of the elements
1889   // input to the shuffle.
1890   int NElts = Mask.size();
1891   assert(llvm::all_of(Mask,
1892                       [&](int M) { return M < (NElts * 2) && M >= -1; }) &&
1893          "Index out of range");
1894 
1895   // Copy the mask so we can do any needed cleanup.
1896   SmallVector<int, 8> MaskVec(Mask.begin(), Mask.end());
1897 
1898   // Canonicalize shuffle v, v -> v, undef
1899   if (N1 == N2) {
1900     N2 = getUNDEF(VT);
1901     for (int i = 0; i != NElts; ++i)
1902       if (MaskVec[i] >= NElts) MaskVec[i] -= NElts;
1903   }
1904 
1905   // Canonicalize shuffle undef, v -> v, undef.  Commute the shuffle mask.
1906   if (N1.isUndef())
1907     commuteShuffle(N1, N2, MaskVec);
1908 
1909   if (TLI->hasVectorBlend()) {
1910     // If shuffling a splat, try to blend the splat instead. We do this here so
1911     // that even when this arises during lowering we don't have to re-handle it.
1912     auto BlendSplat = [&](BuildVectorSDNode *BV, int Offset) {
1913       BitVector UndefElements;
1914       SDValue Splat = BV->getSplatValue(&UndefElements);
1915       if (!Splat)
1916         return;
1917 
1918       for (int i = 0; i < NElts; ++i) {
1919         if (MaskVec[i] < Offset || MaskVec[i] >= (Offset + NElts))
1920           continue;
1921 
1922         // If this input comes from undef, mark it as such.
1923         if (UndefElements[MaskVec[i] - Offset]) {
1924           MaskVec[i] = -1;
1925           continue;
1926         }
1927 
1928         // If we can blend a non-undef lane, use that instead.
1929         if (!UndefElements[i])
1930           MaskVec[i] = i + Offset;
1931       }
1932     };
1933     if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
1934       BlendSplat(N1BV, 0);
1935     if (auto *N2BV = dyn_cast<BuildVectorSDNode>(N2))
1936       BlendSplat(N2BV, NElts);
1937   }
1938 
1939   // Canonicalize all index into lhs, -> shuffle lhs, undef
1940   // Canonicalize all index into rhs, -> shuffle rhs, undef
1941   bool AllLHS = true, AllRHS = true;
1942   bool N2Undef = N2.isUndef();
1943   for (int i = 0; i != NElts; ++i) {
1944     if (MaskVec[i] >= NElts) {
1945       if (N2Undef)
1946         MaskVec[i] = -1;
1947       else
1948         AllLHS = false;
1949     } else if (MaskVec[i] >= 0) {
1950       AllRHS = false;
1951     }
1952   }
1953   if (AllLHS && AllRHS)
1954     return getUNDEF(VT);
1955   if (AllLHS && !N2Undef)
1956     N2 = getUNDEF(VT);
1957   if (AllRHS) {
1958     N1 = getUNDEF(VT);
1959     commuteShuffle(N1, N2, MaskVec);
1960   }
1961   // Reset our undef status after accounting for the mask.
1962   N2Undef = N2.isUndef();
1963   // Re-check whether both sides ended up undef.
1964   if (N1.isUndef() && N2Undef)
1965     return getUNDEF(VT);
1966 
1967   // If Identity shuffle return that node.
1968   bool Identity = true, AllSame = true;
1969   for (int i = 0; i != NElts; ++i) {
1970     if (MaskVec[i] >= 0 && MaskVec[i] != i) Identity = false;
1971     if (MaskVec[i] != MaskVec[0]) AllSame = false;
1972   }
1973   if (Identity && NElts)
1974     return N1;
1975 
1976   // Shuffling a constant splat doesn't change the result.
1977   if (N2Undef) {
1978     SDValue V = N1;
1979 
1980     // Look through any bitcasts. We check that these don't change the number
1981     // (and size) of elements and just changes their types.
1982     while (V.getOpcode() == ISD::BITCAST)
1983       V = V->getOperand(0);
1984 
1985     // A splat should always show up as a build vector node.
1986     if (auto *BV = dyn_cast<BuildVectorSDNode>(V)) {
1987       BitVector UndefElements;
1988       SDValue Splat = BV->getSplatValue(&UndefElements);
1989       // If this is a splat of an undef, shuffling it is also undef.
1990       if (Splat && Splat.isUndef())
1991         return getUNDEF(VT);
1992 
1993       bool SameNumElts =
1994           V.getValueType().getVectorNumElements() == VT.getVectorNumElements();
1995 
1996       // We only have a splat which can skip shuffles if there is a splatted
1997       // value and no undef lanes rearranged by the shuffle.
1998       if (Splat && UndefElements.none()) {
1999         // Splat of <x, x, ..., x>, return <x, x, ..., x>, provided that the
2000         // number of elements match or the value splatted is a zero constant.
2001         if (SameNumElts)
2002           return N1;
2003         if (auto *C = dyn_cast<ConstantSDNode>(Splat))
2004           if (C->isZero())
2005             return N1;
2006       }
2007 
2008       // If the shuffle itself creates a splat, build the vector directly.
2009       if (AllSame && SameNumElts) {
2010         EVT BuildVT = BV->getValueType(0);
2011         const SDValue &Splatted = BV->getOperand(MaskVec[0]);
2012         SDValue NewBV = getSplatBuildVector(BuildVT, dl, Splatted);
2013 
2014         // We may have jumped through bitcasts, so the type of the
2015         // BUILD_VECTOR may not match the type of the shuffle.
2016         if (BuildVT != VT)
2017           NewBV = getNode(ISD::BITCAST, dl, VT, NewBV);
2018         return NewBV;
2019       }
2020     }
2021   }
2022 
2023   FoldingSetNodeID ID;
2024   SDValue Ops[2] = { N1, N2 };
2025   AddNodeIDNode(ID, ISD::VECTOR_SHUFFLE, getVTList(VT), Ops);
2026   for (int i = 0; i != NElts; ++i)
2027     ID.AddInteger(MaskVec[i]);
2028 
2029   void* IP = nullptr;
2030   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
2031     return SDValue(E, 0);
2032 
2033   // Allocate the mask array for the node out of the BumpPtrAllocator, since
2034   // SDNode doesn't have access to it.  This memory will be "leaked" when
2035   // the node is deallocated, but recovered when the NodeAllocator is released.
2036   int *MaskAlloc = OperandAllocator.Allocate<int>(NElts);
2037   llvm::copy(MaskVec, MaskAlloc);
2038 
2039   auto *N = newSDNode<ShuffleVectorSDNode>(VT, dl.getIROrder(),
2040                                            dl.getDebugLoc(), MaskAlloc);
2041   createOperands(N, Ops);
2042 
2043   CSEMap.InsertNode(N, IP);
2044   InsertNode(N);
2045   SDValue V = SDValue(N, 0);
2046   NewSDValueDbgMsg(V, "Creating new node: ", this);
2047   return V;
2048 }
2049 
2050 SDValue SelectionDAG::getCommutedVectorShuffle(const ShuffleVectorSDNode &SV) {
2051   EVT VT = SV.getValueType(0);
2052   SmallVector<int, 8> MaskVec(SV.getMask().begin(), SV.getMask().end());
2053   ShuffleVectorSDNode::commuteMask(MaskVec);
2054 
2055   SDValue Op0 = SV.getOperand(0);
2056   SDValue Op1 = SV.getOperand(1);
2057   return getVectorShuffle(VT, SDLoc(&SV), Op1, Op0, MaskVec);
2058 }
2059 
2060 SDValue SelectionDAG::getRegister(unsigned RegNo, EVT VT) {
2061   FoldingSetNodeID ID;
2062   AddNodeIDNode(ID, ISD::Register, getVTList(VT), None);
2063   ID.AddInteger(RegNo);
2064   void *IP = nullptr;
2065   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2066     return SDValue(E, 0);
2067 
2068   auto *N = newSDNode<RegisterSDNode>(RegNo, VT);
2069   N->SDNodeBits.IsDivergent = TLI->isSDNodeSourceOfDivergence(N, FLI, DA);
2070   CSEMap.InsertNode(N, IP);
2071   InsertNode(N);
2072   return SDValue(N, 0);
2073 }
2074 
2075 SDValue SelectionDAG::getRegisterMask(const uint32_t *RegMask) {
2076   FoldingSetNodeID ID;
2077   AddNodeIDNode(ID, ISD::RegisterMask, getVTList(MVT::Untyped), None);
2078   ID.AddPointer(RegMask);
2079   void *IP = nullptr;
2080   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2081     return SDValue(E, 0);
2082 
2083   auto *N = newSDNode<RegisterMaskSDNode>(RegMask);
2084   CSEMap.InsertNode(N, IP);
2085   InsertNode(N);
2086   return SDValue(N, 0);
2087 }
2088 
2089 SDValue SelectionDAG::getEHLabel(const SDLoc &dl, SDValue Root,
2090                                  MCSymbol *Label) {
2091   return getLabelNode(ISD::EH_LABEL, dl, Root, Label);
2092 }
2093 
2094 SDValue SelectionDAG::getLabelNode(unsigned Opcode, const SDLoc &dl,
2095                                    SDValue Root, MCSymbol *Label) {
2096   FoldingSetNodeID ID;
2097   SDValue Ops[] = { Root };
2098   AddNodeIDNode(ID, Opcode, getVTList(MVT::Other), Ops);
2099   ID.AddPointer(Label);
2100   void *IP = nullptr;
2101   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2102     return SDValue(E, 0);
2103 
2104   auto *N =
2105       newSDNode<LabelSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(), Label);
2106   createOperands(N, Ops);
2107 
2108   CSEMap.InsertNode(N, IP);
2109   InsertNode(N);
2110   return SDValue(N, 0);
2111 }
2112 
2113 SDValue SelectionDAG::getBlockAddress(const BlockAddress *BA, EVT VT,
2114                                       int64_t Offset, bool isTarget,
2115                                       unsigned TargetFlags) {
2116   unsigned Opc = isTarget ? ISD::TargetBlockAddress : ISD::BlockAddress;
2117 
2118   FoldingSetNodeID ID;
2119   AddNodeIDNode(ID, Opc, getVTList(VT), None);
2120   ID.AddPointer(BA);
2121   ID.AddInteger(Offset);
2122   ID.AddInteger(TargetFlags);
2123   void *IP = nullptr;
2124   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2125     return SDValue(E, 0);
2126 
2127   auto *N = newSDNode<BlockAddressSDNode>(Opc, VT, BA, Offset, TargetFlags);
2128   CSEMap.InsertNode(N, IP);
2129   InsertNode(N);
2130   return SDValue(N, 0);
2131 }
2132 
2133 SDValue SelectionDAG::getSrcValue(const Value *V) {
2134   FoldingSetNodeID ID;
2135   AddNodeIDNode(ID, ISD::SRCVALUE, getVTList(MVT::Other), None);
2136   ID.AddPointer(V);
2137 
2138   void *IP = nullptr;
2139   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2140     return SDValue(E, 0);
2141 
2142   auto *N = newSDNode<SrcValueSDNode>(V);
2143   CSEMap.InsertNode(N, IP);
2144   InsertNode(N);
2145   return SDValue(N, 0);
2146 }
2147 
2148 SDValue SelectionDAG::getMDNode(const MDNode *MD) {
2149   FoldingSetNodeID ID;
2150   AddNodeIDNode(ID, ISD::MDNODE_SDNODE, getVTList(MVT::Other), None);
2151   ID.AddPointer(MD);
2152 
2153   void *IP = nullptr;
2154   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2155     return SDValue(E, 0);
2156 
2157   auto *N = newSDNode<MDNodeSDNode>(MD);
2158   CSEMap.InsertNode(N, IP);
2159   InsertNode(N);
2160   return SDValue(N, 0);
2161 }
2162 
2163 SDValue SelectionDAG::getBitcast(EVT VT, SDValue V) {
2164   if (VT == V.getValueType())
2165     return V;
2166 
2167   return getNode(ISD::BITCAST, SDLoc(V), VT, V);
2168 }
2169 
2170 SDValue SelectionDAG::getAddrSpaceCast(const SDLoc &dl, EVT VT, SDValue Ptr,
2171                                        unsigned SrcAS, unsigned DestAS) {
2172   SDValue Ops[] = {Ptr};
2173   FoldingSetNodeID ID;
2174   AddNodeIDNode(ID, ISD::ADDRSPACECAST, getVTList(VT), Ops);
2175   ID.AddInteger(SrcAS);
2176   ID.AddInteger(DestAS);
2177 
2178   void *IP = nullptr;
2179   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
2180     return SDValue(E, 0);
2181 
2182   auto *N = newSDNode<AddrSpaceCastSDNode>(dl.getIROrder(), dl.getDebugLoc(),
2183                                            VT, SrcAS, DestAS);
2184   createOperands(N, Ops);
2185 
2186   CSEMap.InsertNode(N, IP);
2187   InsertNode(N);
2188   return SDValue(N, 0);
2189 }
2190 
2191 SDValue SelectionDAG::getFreeze(SDValue V) {
2192   return getNode(ISD::FREEZE, SDLoc(V), V.getValueType(), V);
2193 }
2194 
2195 /// getShiftAmountOperand - Return the specified value casted to
2196 /// the target's desired shift amount type.
2197 SDValue SelectionDAG::getShiftAmountOperand(EVT LHSTy, SDValue Op) {
2198   EVT OpTy = Op.getValueType();
2199   EVT ShTy = TLI->getShiftAmountTy(LHSTy, getDataLayout());
2200   if (OpTy == ShTy || OpTy.isVector()) return Op;
2201 
2202   return getZExtOrTrunc(Op, SDLoc(Op), ShTy);
2203 }
2204 
2205 SDValue SelectionDAG::expandVAArg(SDNode *Node) {
2206   SDLoc dl(Node);
2207   const TargetLowering &TLI = getTargetLoweringInfo();
2208   const Value *V = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
2209   EVT VT = Node->getValueType(0);
2210   SDValue Tmp1 = Node->getOperand(0);
2211   SDValue Tmp2 = Node->getOperand(1);
2212   const MaybeAlign MA(Node->getConstantOperandVal(3));
2213 
2214   SDValue VAListLoad = getLoad(TLI.getPointerTy(getDataLayout()), dl, Tmp1,
2215                                Tmp2, MachinePointerInfo(V));
2216   SDValue VAList = VAListLoad;
2217 
2218   if (MA && *MA > TLI.getMinStackArgumentAlignment()) {
2219     VAList = getNode(ISD::ADD, dl, VAList.getValueType(), VAList,
2220                      getConstant(MA->value() - 1, dl, VAList.getValueType()));
2221 
2222     VAList =
2223         getNode(ISD::AND, dl, VAList.getValueType(), VAList,
2224                 getConstant(-(int64_t)MA->value(), dl, VAList.getValueType()));
2225   }
2226 
2227   // Increment the pointer, VAList, to the next vaarg
2228   Tmp1 = getNode(ISD::ADD, dl, VAList.getValueType(), VAList,
2229                  getConstant(getDataLayout().getTypeAllocSize(
2230                                                VT.getTypeForEVT(*getContext())),
2231                              dl, VAList.getValueType()));
2232   // Store the incremented VAList to the legalized pointer
2233   Tmp1 =
2234       getStore(VAListLoad.getValue(1), dl, Tmp1, Tmp2, MachinePointerInfo(V));
2235   // Load the actual argument out of the pointer VAList
2236   return getLoad(VT, dl, Tmp1, VAList, MachinePointerInfo());
2237 }
2238 
2239 SDValue SelectionDAG::expandVACopy(SDNode *Node) {
2240   SDLoc dl(Node);
2241   const TargetLowering &TLI = getTargetLoweringInfo();
2242   // This defaults to loading a pointer from the input and storing it to the
2243   // output, returning the chain.
2244   const Value *VD = cast<SrcValueSDNode>(Node->getOperand(3))->getValue();
2245   const Value *VS = cast<SrcValueSDNode>(Node->getOperand(4))->getValue();
2246   SDValue Tmp1 =
2247       getLoad(TLI.getPointerTy(getDataLayout()), dl, Node->getOperand(0),
2248               Node->getOperand(2), MachinePointerInfo(VS));
2249   return getStore(Tmp1.getValue(1), dl, Tmp1, Node->getOperand(1),
2250                   MachinePointerInfo(VD));
2251 }
2252 
2253 Align SelectionDAG::getReducedAlign(EVT VT, bool UseABI) {
2254   const DataLayout &DL = getDataLayout();
2255   Type *Ty = VT.getTypeForEVT(*getContext());
2256   Align RedAlign = UseABI ? DL.getABITypeAlign(Ty) : DL.getPrefTypeAlign(Ty);
2257 
2258   if (TLI->isTypeLegal(VT) || !VT.isVector())
2259     return RedAlign;
2260 
2261   const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering();
2262   const Align StackAlign = TFI->getStackAlign();
2263 
2264   // See if we can choose a smaller ABI alignment in cases where it's an
2265   // illegal vector type that will get broken down.
2266   if (RedAlign > StackAlign) {
2267     EVT IntermediateVT;
2268     MVT RegisterVT;
2269     unsigned NumIntermediates;
2270     TLI->getVectorTypeBreakdown(*getContext(), VT, IntermediateVT,
2271                                 NumIntermediates, RegisterVT);
2272     Ty = IntermediateVT.getTypeForEVT(*getContext());
2273     Align RedAlign2 = UseABI ? DL.getABITypeAlign(Ty) : DL.getPrefTypeAlign(Ty);
2274     if (RedAlign2 < RedAlign)
2275       RedAlign = RedAlign2;
2276   }
2277 
2278   return RedAlign;
2279 }
2280 
2281 SDValue SelectionDAG::CreateStackTemporary(TypeSize Bytes, Align Alignment) {
2282   MachineFrameInfo &MFI = MF->getFrameInfo();
2283   const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering();
2284   int StackID = 0;
2285   if (Bytes.isScalable())
2286     StackID = TFI->getStackIDForScalableVectors();
2287   // The stack id gives an indication of whether the object is scalable or
2288   // not, so it's safe to pass in the minimum size here.
2289   int FrameIdx = MFI.CreateStackObject(Bytes.getKnownMinSize(), Alignment,
2290                                        false, nullptr, StackID);
2291   return getFrameIndex(FrameIdx, TLI->getFrameIndexTy(getDataLayout()));
2292 }
2293 
2294 SDValue SelectionDAG::CreateStackTemporary(EVT VT, unsigned minAlign) {
2295   Type *Ty = VT.getTypeForEVT(*getContext());
2296   Align StackAlign =
2297       std::max(getDataLayout().getPrefTypeAlign(Ty), Align(minAlign));
2298   return CreateStackTemporary(VT.getStoreSize(), StackAlign);
2299 }
2300 
2301 SDValue SelectionDAG::CreateStackTemporary(EVT VT1, EVT VT2) {
2302   TypeSize VT1Size = VT1.getStoreSize();
2303   TypeSize VT2Size = VT2.getStoreSize();
2304   assert(VT1Size.isScalable() == VT2Size.isScalable() &&
2305          "Don't know how to choose the maximum size when creating a stack "
2306          "temporary");
2307   TypeSize Bytes =
2308       VT1Size.getKnownMinSize() > VT2Size.getKnownMinSize() ? VT1Size : VT2Size;
2309 
2310   Type *Ty1 = VT1.getTypeForEVT(*getContext());
2311   Type *Ty2 = VT2.getTypeForEVT(*getContext());
2312   const DataLayout &DL = getDataLayout();
2313   Align Align = std::max(DL.getPrefTypeAlign(Ty1), DL.getPrefTypeAlign(Ty2));
2314   return CreateStackTemporary(Bytes, Align);
2315 }
2316 
2317 SDValue SelectionDAG::FoldSetCC(EVT VT, SDValue N1, SDValue N2,
2318                                 ISD::CondCode Cond, const SDLoc &dl) {
2319   EVT OpVT = N1.getValueType();
2320 
2321   // These setcc operations always fold.
2322   switch (Cond) {
2323   default: break;
2324   case ISD::SETFALSE:
2325   case ISD::SETFALSE2: return getBoolConstant(false, dl, VT, OpVT);
2326   case ISD::SETTRUE:
2327   case ISD::SETTRUE2: return getBoolConstant(true, dl, VT, OpVT);
2328 
2329   case ISD::SETOEQ:
2330   case ISD::SETOGT:
2331   case ISD::SETOGE:
2332   case ISD::SETOLT:
2333   case ISD::SETOLE:
2334   case ISD::SETONE:
2335   case ISD::SETO:
2336   case ISD::SETUO:
2337   case ISD::SETUEQ:
2338   case ISD::SETUNE:
2339     assert(!OpVT.isInteger() && "Illegal setcc for integer!");
2340     break;
2341   }
2342 
2343   if (OpVT.isInteger()) {
2344     // For EQ and NE, we can always pick a value for the undef to make the
2345     // predicate pass or fail, so we can return undef.
2346     // Matches behavior in llvm::ConstantFoldCompareInstruction.
2347     // icmp eq/ne X, undef -> undef.
2348     if ((N1.isUndef() || N2.isUndef()) &&
2349         (Cond == ISD::SETEQ || Cond == ISD::SETNE))
2350       return getUNDEF(VT);
2351 
2352     // If both operands are undef, we can return undef for int comparison.
2353     // icmp undef, undef -> undef.
2354     if (N1.isUndef() && N2.isUndef())
2355       return getUNDEF(VT);
2356 
2357     // icmp X, X -> true/false
2358     // icmp X, undef -> true/false because undef could be X.
2359     if (N1 == N2)
2360       return getBoolConstant(ISD::isTrueWhenEqual(Cond), dl, VT, OpVT);
2361   }
2362 
2363   if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2)) {
2364     const APInt &C2 = N2C->getAPIntValue();
2365     if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1)) {
2366       const APInt &C1 = N1C->getAPIntValue();
2367 
2368       return getBoolConstant(ICmpInst::compare(C1, C2, getICmpCondCode(Cond)),
2369                              dl, VT, OpVT);
2370     }
2371   }
2372 
2373   auto *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
2374   auto *N2CFP = dyn_cast<ConstantFPSDNode>(N2);
2375 
2376   if (N1CFP && N2CFP) {
2377     APFloat::cmpResult R = N1CFP->getValueAPF().compare(N2CFP->getValueAPF());
2378     switch (Cond) {
2379     default: break;
2380     case ISD::SETEQ:  if (R==APFloat::cmpUnordered)
2381                         return getUNDEF(VT);
2382                       LLVM_FALLTHROUGH;
2383     case ISD::SETOEQ: return getBoolConstant(R==APFloat::cmpEqual, dl, VT,
2384                                              OpVT);
2385     case ISD::SETNE:  if (R==APFloat::cmpUnordered)
2386                         return getUNDEF(VT);
2387                       LLVM_FALLTHROUGH;
2388     case ISD::SETONE: return getBoolConstant(R==APFloat::cmpGreaterThan ||
2389                                              R==APFloat::cmpLessThan, dl, VT,
2390                                              OpVT);
2391     case ISD::SETLT:  if (R==APFloat::cmpUnordered)
2392                         return getUNDEF(VT);
2393                       LLVM_FALLTHROUGH;
2394     case ISD::SETOLT: return getBoolConstant(R==APFloat::cmpLessThan, dl, VT,
2395                                              OpVT);
2396     case ISD::SETGT:  if (R==APFloat::cmpUnordered)
2397                         return getUNDEF(VT);
2398                       LLVM_FALLTHROUGH;
2399     case ISD::SETOGT: return getBoolConstant(R==APFloat::cmpGreaterThan, dl,
2400                                              VT, OpVT);
2401     case ISD::SETLE:  if (R==APFloat::cmpUnordered)
2402                         return getUNDEF(VT);
2403                       LLVM_FALLTHROUGH;
2404     case ISD::SETOLE: return getBoolConstant(R==APFloat::cmpLessThan ||
2405                                              R==APFloat::cmpEqual, dl, VT,
2406                                              OpVT);
2407     case ISD::SETGE:  if (R==APFloat::cmpUnordered)
2408                         return getUNDEF(VT);
2409                       LLVM_FALLTHROUGH;
2410     case ISD::SETOGE: return getBoolConstant(R==APFloat::cmpGreaterThan ||
2411                                          R==APFloat::cmpEqual, dl, VT, OpVT);
2412     case ISD::SETO:   return getBoolConstant(R!=APFloat::cmpUnordered, dl, VT,
2413                                              OpVT);
2414     case ISD::SETUO:  return getBoolConstant(R==APFloat::cmpUnordered, dl, VT,
2415                                              OpVT);
2416     case ISD::SETUEQ: return getBoolConstant(R==APFloat::cmpUnordered ||
2417                                              R==APFloat::cmpEqual, dl, VT,
2418                                              OpVT);
2419     case ISD::SETUNE: return getBoolConstant(R!=APFloat::cmpEqual, dl, VT,
2420                                              OpVT);
2421     case ISD::SETULT: return getBoolConstant(R==APFloat::cmpUnordered ||
2422                                              R==APFloat::cmpLessThan, dl, VT,
2423                                              OpVT);
2424     case ISD::SETUGT: return getBoolConstant(R==APFloat::cmpGreaterThan ||
2425                                              R==APFloat::cmpUnordered, dl, VT,
2426                                              OpVT);
2427     case ISD::SETULE: return getBoolConstant(R!=APFloat::cmpGreaterThan, dl,
2428                                              VT, OpVT);
2429     case ISD::SETUGE: return getBoolConstant(R!=APFloat::cmpLessThan, dl, VT,
2430                                              OpVT);
2431     }
2432   } else if (N1CFP && OpVT.isSimple() && !N2.isUndef()) {
2433     // Ensure that the constant occurs on the RHS.
2434     ISD::CondCode SwappedCond = ISD::getSetCCSwappedOperands(Cond);
2435     if (!TLI->isCondCodeLegal(SwappedCond, OpVT.getSimpleVT()))
2436       return SDValue();
2437     return getSetCC(dl, VT, N2, N1, SwappedCond);
2438   } else if ((N2CFP && N2CFP->getValueAPF().isNaN()) ||
2439              (OpVT.isFloatingPoint() && (N1.isUndef() || N2.isUndef()))) {
2440     // If an operand is known to be a nan (or undef that could be a nan), we can
2441     // fold it.
2442     // Choosing NaN for the undef will always make unordered comparison succeed
2443     // and ordered comparison fails.
2444     // Matches behavior in llvm::ConstantFoldCompareInstruction.
2445     switch (ISD::getUnorderedFlavor(Cond)) {
2446     default:
2447       llvm_unreachable("Unknown flavor!");
2448     case 0: // Known false.
2449       return getBoolConstant(false, dl, VT, OpVT);
2450     case 1: // Known true.
2451       return getBoolConstant(true, dl, VT, OpVT);
2452     case 2: // Undefined.
2453       return getUNDEF(VT);
2454     }
2455   }
2456 
2457   // Could not fold it.
2458   return SDValue();
2459 }
2460 
2461 /// See if the specified operand can be simplified with the knowledge that only
2462 /// the bits specified by DemandedBits are used.
2463 /// TODO: really we should be making this into the DAG equivalent of
2464 /// SimplifyMultipleUseDemandedBits and not generate any new nodes.
2465 SDValue SelectionDAG::GetDemandedBits(SDValue V, const APInt &DemandedBits) {
2466   EVT VT = V.getValueType();
2467 
2468   if (VT.isScalableVector())
2469     return SDValue();
2470 
2471   switch (V.getOpcode()) {
2472   default:
2473     return TLI->SimplifyMultipleUseDemandedBits(V, DemandedBits, *this);
2474   case ISD::Constant: {
2475     const APInt &CVal = cast<ConstantSDNode>(V)->getAPIntValue();
2476     APInt NewVal = CVal & DemandedBits;
2477     if (NewVal != CVal)
2478       return getConstant(NewVal, SDLoc(V), V.getValueType());
2479     break;
2480   }
2481   case ISD::SRL:
2482     // Only look at single-use SRLs.
2483     if (!V.getNode()->hasOneUse())
2484       break;
2485     if (auto *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
2486       // See if we can recursively simplify the LHS.
2487       unsigned Amt = RHSC->getZExtValue();
2488 
2489       // Watch out for shift count overflow though.
2490       if (Amt >= DemandedBits.getBitWidth())
2491         break;
2492       APInt SrcDemandedBits = DemandedBits << Amt;
2493       if (SDValue SimplifyLHS = TLI->SimplifyMultipleUseDemandedBits(
2494               V.getOperand(0), SrcDemandedBits, *this))
2495         return getNode(ISD::SRL, SDLoc(V), V.getValueType(), SimplifyLHS,
2496                        V.getOperand(1));
2497     }
2498     break;
2499   }
2500   return SDValue();
2501 }
2502 
2503 /// SignBitIsZero - Return true if the sign bit of Op is known to be zero.  We
2504 /// use this predicate to simplify operations downstream.
2505 bool SelectionDAG::SignBitIsZero(SDValue Op, unsigned Depth) const {
2506   unsigned BitWidth = Op.getScalarValueSizeInBits();
2507   return MaskedValueIsZero(Op, APInt::getSignMask(BitWidth), Depth);
2508 }
2509 
2510 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero.  We use
2511 /// this predicate to simplify operations downstream.  Mask is known to be zero
2512 /// for bits that V cannot have.
2513 bool SelectionDAG::MaskedValueIsZero(SDValue V, const APInt &Mask,
2514                                      unsigned Depth) const {
2515   return Mask.isSubsetOf(computeKnownBits(V, Depth).Zero);
2516 }
2517 
2518 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero in
2519 /// DemandedElts.  We use this predicate to simplify operations downstream.
2520 /// Mask is known to be zero for bits that V cannot have.
2521 bool SelectionDAG::MaskedValueIsZero(SDValue V, const APInt &Mask,
2522                                      const APInt &DemandedElts,
2523                                      unsigned Depth) const {
2524   return Mask.isSubsetOf(computeKnownBits(V, DemandedElts, Depth).Zero);
2525 }
2526 
2527 /// MaskedVectorIsZero - Return true if 'Op' is known to be zero in
2528 /// DemandedElts.  We use this predicate to simplify operations downstream.
2529 bool SelectionDAG::MaskedVectorIsZero(SDValue V, const APInt &DemandedElts,
2530                                       unsigned Depth /* = 0 */) const {
2531   APInt Mask = APInt::getAllOnes(V.getScalarValueSizeInBits());
2532   return Mask.isSubsetOf(computeKnownBits(V, DemandedElts, Depth).Zero);
2533 }
2534 
2535 /// MaskedValueIsAllOnes - Return true if '(Op & Mask) == Mask'.
2536 bool SelectionDAG::MaskedValueIsAllOnes(SDValue V, const APInt &Mask,
2537                                         unsigned Depth) const {
2538   return Mask.isSubsetOf(computeKnownBits(V, Depth).One);
2539 }
2540 
2541 /// isSplatValue - Return true if the vector V has the same value
2542 /// across all DemandedElts. For scalable vectors it does not make
2543 /// sense to specify which elements are demanded or undefined, therefore
2544 /// they are simply ignored.
2545 bool SelectionDAG::isSplatValue(SDValue V, const APInt &DemandedElts,
2546                                 APInt &UndefElts, unsigned Depth) const {
2547   unsigned Opcode = V.getOpcode();
2548   EVT VT = V.getValueType();
2549   assert(VT.isVector() && "Vector type expected");
2550 
2551   if (!VT.isScalableVector() && !DemandedElts)
2552     return false; // No demanded elts, better to assume we don't know anything.
2553 
2554   if (Depth >= MaxRecursionDepth)
2555     return false; // Limit search depth.
2556 
2557   // Deal with some common cases here that work for both fixed and scalable
2558   // vector types.
2559   switch (Opcode) {
2560   case ISD::SPLAT_VECTOR:
2561     UndefElts = V.getOperand(0).isUndef()
2562                     ? APInt::getAllOnes(DemandedElts.getBitWidth())
2563                     : APInt(DemandedElts.getBitWidth(), 0);
2564     return true;
2565   case ISD::ADD:
2566   case ISD::SUB:
2567   case ISD::AND:
2568   case ISD::XOR:
2569   case ISD::OR: {
2570     APInt UndefLHS, UndefRHS;
2571     SDValue LHS = V.getOperand(0);
2572     SDValue RHS = V.getOperand(1);
2573     if (isSplatValue(LHS, DemandedElts, UndefLHS, Depth + 1) &&
2574         isSplatValue(RHS, DemandedElts, UndefRHS, Depth + 1)) {
2575       UndefElts = UndefLHS | UndefRHS;
2576       return true;
2577     }
2578     return false;
2579   }
2580   case ISD::ABS:
2581   case ISD::TRUNCATE:
2582   case ISD::SIGN_EXTEND:
2583   case ISD::ZERO_EXTEND:
2584     return isSplatValue(V.getOperand(0), DemandedElts, UndefElts, Depth + 1);
2585   default:
2586     if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::INTRINSIC_WO_CHAIN ||
2587         Opcode == ISD::INTRINSIC_W_CHAIN || Opcode == ISD::INTRINSIC_VOID)
2588       return TLI->isSplatValueForTargetNode(V, DemandedElts, UndefElts, Depth);
2589     break;
2590 }
2591 
2592   // We don't support other cases than those above for scalable vectors at
2593   // the moment.
2594   if (VT.isScalableVector())
2595     return false;
2596 
2597   unsigned NumElts = VT.getVectorNumElements();
2598   assert(NumElts == DemandedElts.getBitWidth() && "Vector size mismatch");
2599   UndefElts = APInt::getZero(NumElts);
2600 
2601   switch (Opcode) {
2602   case ISD::BUILD_VECTOR: {
2603     SDValue Scl;
2604     for (unsigned i = 0; i != NumElts; ++i) {
2605       SDValue Op = V.getOperand(i);
2606       if (Op.isUndef()) {
2607         UndefElts.setBit(i);
2608         continue;
2609       }
2610       if (!DemandedElts[i])
2611         continue;
2612       if (Scl && Scl != Op)
2613         return false;
2614       Scl = Op;
2615     }
2616     return true;
2617   }
2618   case ISD::VECTOR_SHUFFLE: {
2619     // Check if this is a shuffle node doing a splat or a shuffle of a splat.
2620     APInt DemandedLHS = APInt::getNullValue(NumElts);
2621     APInt DemandedRHS = APInt::getNullValue(NumElts);
2622     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(V)->getMask();
2623     for (int i = 0; i != (int)NumElts; ++i) {
2624       int M = Mask[i];
2625       if (M < 0) {
2626         UndefElts.setBit(i);
2627         continue;
2628       }
2629       if (!DemandedElts[i])
2630         continue;
2631       if (M < (int)NumElts)
2632         DemandedLHS.setBit(M);
2633       else
2634         DemandedRHS.setBit(M - NumElts);
2635     }
2636 
2637     // If we aren't demanding either op, assume there's no splat.
2638     // If we are demanding both ops, assume there's no splat.
2639     if ((DemandedLHS.isZero() && DemandedRHS.isZero()) ||
2640         (!DemandedLHS.isZero() && !DemandedRHS.isZero()))
2641       return false;
2642 
2643     // See if the demanded elts of the source op is a splat or we only demand
2644     // one element, which should always be a splat.
2645     // TODO: Handle source ops splats with undefs.
2646     auto CheckSplatSrc = [&](SDValue Src, const APInt &SrcElts) {
2647       APInt SrcUndefs;
2648       return (SrcElts.countPopulation() == 1) ||
2649              (isSplatValue(Src, SrcElts, SrcUndefs, Depth + 1) &&
2650               (SrcElts & SrcUndefs).isZero());
2651     };
2652     if (!DemandedLHS.isZero())
2653       return CheckSplatSrc(V.getOperand(0), DemandedLHS);
2654     return CheckSplatSrc(V.getOperand(1), DemandedRHS);
2655   }
2656   case ISD::EXTRACT_SUBVECTOR: {
2657     // Offset the demanded elts by the subvector index.
2658     SDValue Src = V.getOperand(0);
2659     // We don't support scalable vectors at the moment.
2660     if (Src.getValueType().isScalableVector())
2661       return false;
2662     uint64_t Idx = V.getConstantOperandVal(1);
2663     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
2664     APInt UndefSrcElts;
2665     APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts).shl(Idx);
2666     if (isSplatValue(Src, DemandedSrcElts, UndefSrcElts, Depth + 1)) {
2667       UndefElts = UndefSrcElts.extractBits(NumElts, Idx);
2668       return true;
2669     }
2670     break;
2671   }
2672   case ISD::ANY_EXTEND_VECTOR_INREG:
2673   case ISD::SIGN_EXTEND_VECTOR_INREG:
2674   case ISD::ZERO_EXTEND_VECTOR_INREG: {
2675     // Widen the demanded elts by the src element count.
2676     SDValue Src = V.getOperand(0);
2677     // We don't support scalable vectors at the moment.
2678     if (Src.getValueType().isScalableVector())
2679       return false;
2680     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
2681     APInt UndefSrcElts;
2682     APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts);
2683     if (isSplatValue(Src, DemandedSrcElts, UndefSrcElts, Depth + 1)) {
2684       UndefElts = UndefSrcElts.trunc(NumElts);
2685       return true;
2686     }
2687     break;
2688   }
2689   case ISD::BITCAST: {
2690     SDValue Src = V.getOperand(0);
2691     EVT SrcVT = Src.getValueType();
2692     unsigned SrcBitWidth = SrcVT.getScalarSizeInBits();
2693     unsigned BitWidth = VT.getScalarSizeInBits();
2694 
2695     // Ignore bitcasts from unsupported types.
2696     // TODO: Add fp support?
2697     if (!SrcVT.isVector() || !SrcVT.isInteger() || !VT.isInteger())
2698       break;
2699 
2700     // Bitcast 'small element' vector to 'large element' vector.
2701     if ((BitWidth % SrcBitWidth) == 0) {
2702       // See if each sub element is a splat.
2703       unsigned Scale = BitWidth / SrcBitWidth;
2704       unsigned NumSrcElts = SrcVT.getVectorNumElements();
2705       APInt ScaledDemandedElts =
2706           APIntOps::ScaleBitMask(DemandedElts, NumSrcElts);
2707       for (unsigned I = 0; I != Scale; ++I) {
2708         APInt SubUndefElts;
2709         APInt SubDemandedElt = APInt::getOneBitSet(Scale, I);
2710         APInt SubDemandedElts = APInt::getSplat(NumSrcElts, SubDemandedElt);
2711         SubDemandedElts &= ScaledDemandedElts;
2712         if (!isSplatValue(Src, SubDemandedElts, SubUndefElts, Depth + 1))
2713           return false;
2714 
2715         // Here we can't do "MatchAnyBits" operation merge for undef bits.
2716         // Because some operation only use part value of the source.
2717         // Take llvm.fshl.* for example:
2718         // t1: v4i32 = Constant:i32<12>, undef:i32, Constant:i32<12>, undef:i32
2719         // t2: v2i64 = bitcast t1
2720         // t5: v2i64 = fshl t3, t4, t2
2721         // We can not convert t2 to {i64 undef, i64 undef}
2722         UndefElts |= APIntOps::ScaleBitMask(SubUndefElts, NumElts,
2723                                             /*MatchAllBits=*/true);
2724       }
2725       return true;
2726     }
2727     break;
2728   }
2729   }
2730 
2731   return false;
2732 }
2733 
2734 /// Helper wrapper to main isSplatValue function.
2735 bool SelectionDAG::isSplatValue(SDValue V, bool AllowUndefs) const {
2736   EVT VT = V.getValueType();
2737   assert(VT.isVector() && "Vector type expected");
2738 
2739   APInt UndefElts;
2740   APInt DemandedElts;
2741 
2742   // For now we don't support this with scalable vectors.
2743   if (!VT.isScalableVector())
2744     DemandedElts = APInt::getAllOnes(VT.getVectorNumElements());
2745   return isSplatValue(V, DemandedElts, UndefElts) &&
2746          (AllowUndefs || !UndefElts);
2747 }
2748 
2749 SDValue SelectionDAG::getSplatSourceVector(SDValue V, int &SplatIdx) {
2750   V = peekThroughExtractSubvectors(V);
2751 
2752   EVT VT = V.getValueType();
2753   unsigned Opcode = V.getOpcode();
2754   switch (Opcode) {
2755   default: {
2756     APInt UndefElts;
2757     APInt DemandedElts;
2758 
2759     if (!VT.isScalableVector())
2760       DemandedElts = APInt::getAllOnes(VT.getVectorNumElements());
2761 
2762     if (isSplatValue(V, DemandedElts, UndefElts)) {
2763       if (VT.isScalableVector()) {
2764         // DemandedElts and UndefElts are ignored for scalable vectors, since
2765         // the only supported cases are SPLAT_VECTOR nodes.
2766         SplatIdx = 0;
2767       } else {
2768         // Handle case where all demanded elements are UNDEF.
2769         if (DemandedElts.isSubsetOf(UndefElts)) {
2770           SplatIdx = 0;
2771           return getUNDEF(VT);
2772         }
2773         SplatIdx = (UndefElts & DemandedElts).countTrailingOnes();
2774       }
2775       return V;
2776     }
2777     break;
2778   }
2779   case ISD::SPLAT_VECTOR:
2780     SplatIdx = 0;
2781     return V;
2782   case ISD::VECTOR_SHUFFLE: {
2783     if (VT.isScalableVector())
2784       return SDValue();
2785 
2786     // Check if this is a shuffle node doing a splat.
2787     // TODO - remove this and rely purely on SelectionDAG::isSplatValue,
2788     // getTargetVShiftNode currently struggles without the splat source.
2789     auto *SVN = cast<ShuffleVectorSDNode>(V);
2790     if (!SVN->isSplat())
2791       break;
2792     int Idx = SVN->getSplatIndex();
2793     int NumElts = V.getValueType().getVectorNumElements();
2794     SplatIdx = Idx % NumElts;
2795     return V.getOperand(Idx / NumElts);
2796   }
2797   }
2798 
2799   return SDValue();
2800 }
2801 
2802 SDValue SelectionDAG::getSplatValue(SDValue V, bool LegalTypes) {
2803   int SplatIdx;
2804   if (SDValue SrcVector = getSplatSourceVector(V, SplatIdx)) {
2805     EVT SVT = SrcVector.getValueType().getScalarType();
2806     EVT LegalSVT = SVT;
2807     if (LegalTypes && !TLI->isTypeLegal(SVT)) {
2808       if (!SVT.isInteger())
2809         return SDValue();
2810       LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT);
2811       if (LegalSVT.bitsLT(SVT))
2812         return SDValue();
2813     }
2814     return getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(V), LegalSVT, SrcVector,
2815                    getVectorIdxConstant(SplatIdx, SDLoc(V)));
2816   }
2817   return SDValue();
2818 }
2819 
2820 const APInt *
2821 SelectionDAG::getValidShiftAmountConstant(SDValue V,
2822                                           const APInt &DemandedElts) const {
2823   assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL ||
2824           V.getOpcode() == ISD::SRA) &&
2825          "Unknown shift node");
2826   unsigned BitWidth = V.getScalarValueSizeInBits();
2827   if (ConstantSDNode *SA = isConstOrConstSplat(V.getOperand(1), DemandedElts)) {
2828     // Shifting more than the bitwidth is not valid.
2829     const APInt &ShAmt = SA->getAPIntValue();
2830     if (ShAmt.ult(BitWidth))
2831       return &ShAmt;
2832   }
2833   return nullptr;
2834 }
2835 
2836 const APInt *SelectionDAG::getValidMinimumShiftAmountConstant(
2837     SDValue V, const APInt &DemandedElts) const {
2838   assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL ||
2839           V.getOpcode() == ISD::SRA) &&
2840          "Unknown shift node");
2841   if (const APInt *ValidAmt = getValidShiftAmountConstant(V, DemandedElts))
2842     return ValidAmt;
2843   unsigned BitWidth = V.getScalarValueSizeInBits();
2844   auto *BV = dyn_cast<BuildVectorSDNode>(V.getOperand(1));
2845   if (!BV)
2846     return nullptr;
2847   const APInt *MinShAmt = nullptr;
2848   for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
2849     if (!DemandedElts[i])
2850       continue;
2851     auto *SA = dyn_cast<ConstantSDNode>(BV->getOperand(i));
2852     if (!SA)
2853       return nullptr;
2854     // Shifting more than the bitwidth is not valid.
2855     const APInt &ShAmt = SA->getAPIntValue();
2856     if (ShAmt.uge(BitWidth))
2857       return nullptr;
2858     if (MinShAmt && MinShAmt->ule(ShAmt))
2859       continue;
2860     MinShAmt = &ShAmt;
2861   }
2862   return MinShAmt;
2863 }
2864 
2865 const APInt *SelectionDAG::getValidMaximumShiftAmountConstant(
2866     SDValue V, const APInt &DemandedElts) const {
2867   assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL ||
2868           V.getOpcode() == ISD::SRA) &&
2869          "Unknown shift node");
2870   if (const APInt *ValidAmt = getValidShiftAmountConstant(V, DemandedElts))
2871     return ValidAmt;
2872   unsigned BitWidth = V.getScalarValueSizeInBits();
2873   auto *BV = dyn_cast<BuildVectorSDNode>(V.getOperand(1));
2874   if (!BV)
2875     return nullptr;
2876   const APInt *MaxShAmt = nullptr;
2877   for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
2878     if (!DemandedElts[i])
2879       continue;
2880     auto *SA = dyn_cast<ConstantSDNode>(BV->getOperand(i));
2881     if (!SA)
2882       return nullptr;
2883     // Shifting more than the bitwidth is not valid.
2884     const APInt &ShAmt = SA->getAPIntValue();
2885     if (ShAmt.uge(BitWidth))
2886       return nullptr;
2887     if (MaxShAmt && MaxShAmt->uge(ShAmt))
2888       continue;
2889     MaxShAmt = &ShAmt;
2890   }
2891   return MaxShAmt;
2892 }
2893 
2894 /// Determine which bits of Op are known to be either zero or one and return
2895 /// them in Known. For vectors, the known bits are those that are shared by
2896 /// every vector element.
2897 KnownBits SelectionDAG::computeKnownBits(SDValue Op, unsigned Depth) const {
2898   EVT VT = Op.getValueType();
2899 
2900   // TOOD: Until we have a plan for how to represent demanded elements for
2901   // scalable vectors, we can just bail out for now.
2902   if (Op.getValueType().isScalableVector()) {
2903     unsigned BitWidth = Op.getScalarValueSizeInBits();
2904     return KnownBits(BitWidth);
2905   }
2906 
2907   APInt DemandedElts = VT.isVector()
2908                            ? APInt::getAllOnes(VT.getVectorNumElements())
2909                            : APInt(1, 1);
2910   return computeKnownBits(Op, DemandedElts, Depth);
2911 }
2912 
2913 /// Determine which bits of Op are known to be either zero or one and return
2914 /// them in Known. The DemandedElts argument allows us to only collect the known
2915 /// bits that are shared by the requested vector elements.
2916 KnownBits SelectionDAG::computeKnownBits(SDValue Op, const APInt &DemandedElts,
2917                                          unsigned Depth) const {
2918   unsigned BitWidth = Op.getScalarValueSizeInBits();
2919 
2920   KnownBits Known(BitWidth);   // Don't know anything.
2921 
2922   // TOOD: Until we have a plan for how to represent demanded elements for
2923   // scalable vectors, we can just bail out for now.
2924   if (Op.getValueType().isScalableVector())
2925     return Known;
2926 
2927   if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
2928     // We know all of the bits for a constant!
2929     return KnownBits::makeConstant(C->getAPIntValue());
2930   }
2931   if (auto *C = dyn_cast<ConstantFPSDNode>(Op)) {
2932     // We know all of the bits for a constant fp!
2933     return KnownBits::makeConstant(C->getValueAPF().bitcastToAPInt());
2934   }
2935 
2936   if (Depth >= MaxRecursionDepth)
2937     return Known;  // Limit search depth.
2938 
2939   KnownBits Known2;
2940   unsigned NumElts = DemandedElts.getBitWidth();
2941   assert((!Op.getValueType().isVector() ||
2942           NumElts == Op.getValueType().getVectorNumElements()) &&
2943          "Unexpected vector size");
2944 
2945   if (!DemandedElts)
2946     return Known;  // No demanded elts, better to assume we don't know anything.
2947 
2948   unsigned Opcode = Op.getOpcode();
2949   switch (Opcode) {
2950   case ISD::BUILD_VECTOR:
2951     // Collect the known bits that are shared by every demanded vector element.
2952     Known.Zero.setAllBits(); Known.One.setAllBits();
2953     for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
2954       if (!DemandedElts[i])
2955         continue;
2956 
2957       SDValue SrcOp = Op.getOperand(i);
2958       Known2 = computeKnownBits(SrcOp, Depth + 1);
2959 
2960       // BUILD_VECTOR can implicitly truncate sources, we must handle this.
2961       if (SrcOp.getValueSizeInBits() != BitWidth) {
2962         assert(SrcOp.getValueSizeInBits() > BitWidth &&
2963                "Expected BUILD_VECTOR implicit truncation");
2964         Known2 = Known2.trunc(BitWidth);
2965       }
2966 
2967       // Known bits are the values that are shared by every demanded element.
2968       Known = KnownBits::commonBits(Known, Known2);
2969 
2970       // If we don't know any bits, early out.
2971       if (Known.isUnknown())
2972         break;
2973     }
2974     break;
2975   case ISD::VECTOR_SHUFFLE: {
2976     // Collect the known bits that are shared by every vector element referenced
2977     // by the shuffle.
2978     APInt DemandedLHS(NumElts, 0), DemandedRHS(NumElts, 0);
2979     Known.Zero.setAllBits(); Known.One.setAllBits();
2980     const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op);
2981     assert(NumElts == SVN->getMask().size() && "Unexpected vector size");
2982     for (unsigned i = 0; i != NumElts; ++i) {
2983       if (!DemandedElts[i])
2984         continue;
2985 
2986       int M = SVN->getMaskElt(i);
2987       if (M < 0) {
2988         // For UNDEF elements, we don't know anything about the common state of
2989         // the shuffle result.
2990         Known.resetAll();
2991         DemandedLHS.clearAllBits();
2992         DemandedRHS.clearAllBits();
2993         break;
2994       }
2995 
2996       if ((unsigned)M < NumElts)
2997         DemandedLHS.setBit((unsigned)M % NumElts);
2998       else
2999         DemandedRHS.setBit((unsigned)M % NumElts);
3000     }
3001     // Known bits are the values that are shared by every demanded element.
3002     if (!!DemandedLHS) {
3003       SDValue LHS = Op.getOperand(0);
3004       Known2 = computeKnownBits(LHS, DemandedLHS, Depth + 1);
3005       Known = KnownBits::commonBits(Known, Known2);
3006     }
3007     // If we don't know any bits, early out.
3008     if (Known.isUnknown())
3009       break;
3010     if (!!DemandedRHS) {
3011       SDValue RHS = Op.getOperand(1);
3012       Known2 = computeKnownBits(RHS, DemandedRHS, Depth + 1);
3013       Known = KnownBits::commonBits(Known, Known2);
3014     }
3015     break;
3016   }
3017   case ISD::CONCAT_VECTORS: {
3018     // Split DemandedElts and test each of the demanded subvectors.
3019     Known.Zero.setAllBits(); Known.One.setAllBits();
3020     EVT SubVectorVT = Op.getOperand(0).getValueType();
3021     unsigned NumSubVectorElts = SubVectorVT.getVectorNumElements();
3022     unsigned NumSubVectors = Op.getNumOperands();
3023     for (unsigned i = 0; i != NumSubVectors; ++i) {
3024       APInt DemandedSub =
3025           DemandedElts.extractBits(NumSubVectorElts, i * NumSubVectorElts);
3026       if (!!DemandedSub) {
3027         SDValue Sub = Op.getOperand(i);
3028         Known2 = computeKnownBits(Sub, DemandedSub, Depth + 1);
3029         Known = KnownBits::commonBits(Known, Known2);
3030       }
3031       // If we don't know any bits, early out.
3032       if (Known.isUnknown())
3033         break;
3034     }
3035     break;
3036   }
3037   case ISD::INSERT_SUBVECTOR: {
3038     // Demand any elements from the subvector and the remainder from the src its
3039     // inserted into.
3040     SDValue Src = Op.getOperand(0);
3041     SDValue Sub = Op.getOperand(1);
3042     uint64_t Idx = Op.getConstantOperandVal(2);
3043     unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
3044     APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
3045     APInt DemandedSrcElts = DemandedElts;
3046     DemandedSrcElts.insertBits(APInt::getZero(NumSubElts), Idx);
3047 
3048     Known.One.setAllBits();
3049     Known.Zero.setAllBits();
3050     if (!!DemandedSubElts) {
3051       Known = computeKnownBits(Sub, DemandedSubElts, Depth + 1);
3052       if (Known.isUnknown())
3053         break; // early-out.
3054     }
3055     if (!!DemandedSrcElts) {
3056       Known2 = computeKnownBits(Src, DemandedSrcElts, Depth + 1);
3057       Known = KnownBits::commonBits(Known, Known2);
3058     }
3059     break;
3060   }
3061   case ISD::EXTRACT_SUBVECTOR: {
3062     // Offset the demanded elts by the subvector index.
3063     SDValue Src = Op.getOperand(0);
3064     // Bail until we can represent demanded elements for scalable vectors.
3065     if (Src.getValueType().isScalableVector())
3066       break;
3067     uint64_t Idx = Op.getConstantOperandVal(1);
3068     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
3069     APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts).shl(Idx);
3070     Known = computeKnownBits(Src, DemandedSrcElts, Depth + 1);
3071     break;
3072   }
3073   case ISD::SCALAR_TO_VECTOR: {
3074     // We know about scalar_to_vector as much as we know about it source,
3075     // which becomes the first element of otherwise unknown vector.
3076     if (DemandedElts != 1)
3077       break;
3078 
3079     SDValue N0 = Op.getOperand(0);
3080     Known = computeKnownBits(N0, Depth + 1);
3081     if (N0.getValueSizeInBits() != BitWidth)
3082       Known = Known.trunc(BitWidth);
3083 
3084     break;
3085   }
3086   case ISD::BITCAST: {
3087     SDValue N0 = Op.getOperand(0);
3088     EVT SubVT = N0.getValueType();
3089     unsigned SubBitWidth = SubVT.getScalarSizeInBits();
3090 
3091     // Ignore bitcasts from unsupported types.
3092     if (!(SubVT.isInteger() || SubVT.isFloatingPoint()))
3093       break;
3094 
3095     // Fast handling of 'identity' bitcasts.
3096     if (BitWidth == SubBitWidth) {
3097       Known = computeKnownBits(N0, DemandedElts, Depth + 1);
3098       break;
3099     }
3100 
3101     bool IsLE = getDataLayout().isLittleEndian();
3102 
3103     // Bitcast 'small element' vector to 'large element' scalar/vector.
3104     if ((BitWidth % SubBitWidth) == 0) {
3105       assert(N0.getValueType().isVector() && "Expected bitcast from vector");
3106 
3107       // Collect known bits for the (larger) output by collecting the known
3108       // bits from each set of sub elements and shift these into place.
3109       // We need to separately call computeKnownBits for each set of
3110       // sub elements as the knownbits for each is likely to be different.
3111       unsigned SubScale = BitWidth / SubBitWidth;
3112       APInt SubDemandedElts(NumElts * SubScale, 0);
3113       for (unsigned i = 0; i != NumElts; ++i)
3114         if (DemandedElts[i])
3115           SubDemandedElts.setBit(i * SubScale);
3116 
3117       for (unsigned i = 0; i != SubScale; ++i) {
3118         Known2 = computeKnownBits(N0, SubDemandedElts.shl(i),
3119                          Depth + 1);
3120         unsigned Shifts = IsLE ? i : SubScale - 1 - i;
3121         Known.insertBits(Known2, SubBitWidth * Shifts);
3122       }
3123     }
3124 
3125     // Bitcast 'large element' scalar/vector to 'small element' vector.
3126     if ((SubBitWidth % BitWidth) == 0) {
3127       assert(Op.getValueType().isVector() && "Expected bitcast to vector");
3128 
3129       // Collect known bits for the (smaller) output by collecting the known
3130       // bits from the overlapping larger input elements and extracting the
3131       // sub sections we actually care about.
3132       unsigned SubScale = SubBitWidth / BitWidth;
3133       APInt SubDemandedElts =
3134           APIntOps::ScaleBitMask(DemandedElts, NumElts / SubScale);
3135       Known2 = computeKnownBits(N0, SubDemandedElts, Depth + 1);
3136 
3137       Known.Zero.setAllBits(); Known.One.setAllBits();
3138       for (unsigned i = 0; i != NumElts; ++i)
3139         if (DemandedElts[i]) {
3140           unsigned Shifts = IsLE ? i : NumElts - 1 - i;
3141           unsigned Offset = (Shifts % SubScale) * BitWidth;
3142           Known = KnownBits::commonBits(Known,
3143                                         Known2.extractBits(BitWidth, Offset));
3144           // If we don't know any bits, early out.
3145           if (Known.isUnknown())
3146             break;
3147         }
3148     }
3149     break;
3150   }
3151   case ISD::AND:
3152     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3153     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3154 
3155     Known &= Known2;
3156     break;
3157   case ISD::OR:
3158     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3159     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3160 
3161     Known |= Known2;
3162     break;
3163   case ISD::XOR:
3164     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3165     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3166 
3167     Known ^= Known2;
3168     break;
3169   case ISD::MUL: {
3170     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3171     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3172     bool SelfMultiply = Op.getOperand(0) == Op.getOperand(1);
3173     // TODO: SelfMultiply can be poison, but not undef.
3174     if (SelfMultiply)
3175       SelfMultiply &= isGuaranteedNotToBeUndefOrPoison(
3176           Op.getOperand(0), DemandedElts, false, Depth + 1);
3177     Known = KnownBits::mul(Known, Known2, SelfMultiply);
3178 
3179     // If the multiplication is known not to overflow, the product of a number
3180     // with itself is non-negative. Only do this if we didn't already computed
3181     // the opposite value for the sign bit.
3182     if (Op->getFlags().hasNoSignedWrap() &&
3183         Op.getOperand(0) == Op.getOperand(1) &&
3184         !Known.isNegative())
3185       Known.makeNonNegative();
3186     break;
3187   }
3188   case ISD::MULHU: {
3189     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3190     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3191     Known = KnownBits::mulhu(Known, Known2);
3192     break;
3193   }
3194   case ISD::MULHS: {
3195     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3196     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3197     Known = KnownBits::mulhs(Known, Known2);
3198     break;
3199   }
3200   case ISD::UMUL_LOHI: {
3201     assert((Op.getResNo() == 0 || Op.getResNo() == 1) && "Unknown result");
3202     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3203     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3204     bool SelfMultiply = Op.getOperand(0) == Op.getOperand(1);
3205     if (Op.getResNo() == 0)
3206       Known = KnownBits::mul(Known, Known2, SelfMultiply);
3207     else
3208       Known = KnownBits::mulhu(Known, Known2);
3209     break;
3210   }
3211   case ISD::SMUL_LOHI: {
3212     assert((Op.getResNo() == 0 || Op.getResNo() == 1) && "Unknown result");
3213     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3214     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3215     bool SelfMultiply = Op.getOperand(0) == Op.getOperand(1);
3216     if (Op.getResNo() == 0)
3217       Known = KnownBits::mul(Known, Known2, SelfMultiply);
3218     else
3219       Known = KnownBits::mulhs(Known, Known2);
3220     break;
3221   }
3222   case ISD::UDIV: {
3223     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3224     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3225     Known = KnownBits::udiv(Known, Known2);
3226     break;
3227   }
3228   case ISD::AVGCEILU: {
3229     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3230     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3231     Known = Known.zext(BitWidth + 1);
3232     Known2 = Known2.zext(BitWidth + 1);
3233     KnownBits One = KnownBits::makeConstant(APInt(1, 1));
3234     Known = KnownBits::computeForAddCarry(Known, Known2, One);
3235     Known = Known.extractBits(BitWidth, 1);
3236     break;
3237   }
3238   case ISD::SELECT:
3239   case ISD::VSELECT:
3240     Known = computeKnownBits(Op.getOperand(2), DemandedElts, Depth+1);
3241     // If we don't know any bits, early out.
3242     if (Known.isUnknown())
3243       break;
3244     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth+1);
3245 
3246     // Only known if known in both the LHS and RHS.
3247     Known = KnownBits::commonBits(Known, Known2);
3248     break;
3249   case ISD::SELECT_CC:
3250     Known = computeKnownBits(Op.getOperand(3), DemandedElts, Depth+1);
3251     // If we don't know any bits, early out.
3252     if (Known.isUnknown())
3253       break;
3254     Known2 = computeKnownBits(Op.getOperand(2), DemandedElts, Depth+1);
3255 
3256     // Only known if known in both the LHS and RHS.
3257     Known = KnownBits::commonBits(Known, Known2);
3258     break;
3259   case ISD::SMULO:
3260   case ISD::UMULO:
3261     if (Op.getResNo() != 1)
3262       break;
3263     // The boolean result conforms to getBooleanContents.
3264     // If we know the result of a setcc has the top bits zero, use this info.
3265     // We know that we have an integer-based boolean since these operations
3266     // are only available for integer.
3267     if (TLI->getBooleanContents(Op.getValueType().isVector(), false) ==
3268             TargetLowering::ZeroOrOneBooleanContent &&
3269         BitWidth > 1)
3270       Known.Zero.setBitsFrom(1);
3271     break;
3272   case ISD::SETCC:
3273   case ISD::SETCCCARRY:
3274   case ISD::STRICT_FSETCC:
3275   case ISD::STRICT_FSETCCS: {
3276     unsigned OpNo = Op->isStrictFPOpcode() ? 1 : 0;
3277     // If we know the result of a setcc has the top bits zero, use this info.
3278     if (TLI->getBooleanContents(Op.getOperand(OpNo).getValueType()) ==
3279             TargetLowering::ZeroOrOneBooleanContent &&
3280         BitWidth > 1)
3281       Known.Zero.setBitsFrom(1);
3282     break;
3283   }
3284   case ISD::SHL:
3285     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3286     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3287     Known = KnownBits::shl(Known, Known2);
3288 
3289     // Minimum shift low bits are known zero.
3290     if (const APInt *ShMinAmt =
3291             getValidMinimumShiftAmountConstant(Op, DemandedElts))
3292       Known.Zero.setLowBits(ShMinAmt->getZExtValue());
3293     break;
3294   case ISD::SRL:
3295     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3296     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3297     Known = KnownBits::lshr(Known, Known2);
3298 
3299     // Minimum shift high bits are known zero.
3300     if (const APInt *ShMinAmt =
3301             getValidMinimumShiftAmountConstant(Op, DemandedElts))
3302       Known.Zero.setHighBits(ShMinAmt->getZExtValue());
3303     break;
3304   case ISD::SRA:
3305     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3306     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3307     Known = KnownBits::ashr(Known, Known2);
3308     // TODO: Add minimum shift high known sign bits.
3309     break;
3310   case ISD::FSHL:
3311   case ISD::FSHR:
3312     if (ConstantSDNode *C = isConstOrConstSplat(Op.getOperand(2), DemandedElts)) {
3313       unsigned Amt = C->getAPIntValue().urem(BitWidth);
3314 
3315       // For fshl, 0-shift returns the 1st arg.
3316       // For fshr, 0-shift returns the 2nd arg.
3317       if (Amt == 0) {
3318         Known = computeKnownBits(Op.getOperand(Opcode == ISD::FSHL ? 0 : 1),
3319                                  DemandedElts, Depth + 1);
3320         break;
3321       }
3322 
3323       // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW)))
3324       // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW))
3325       Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3326       Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3327       if (Opcode == ISD::FSHL) {
3328         Known.One <<= Amt;
3329         Known.Zero <<= Amt;
3330         Known2.One.lshrInPlace(BitWidth - Amt);
3331         Known2.Zero.lshrInPlace(BitWidth - Amt);
3332       } else {
3333         Known.One <<= BitWidth - Amt;
3334         Known.Zero <<= BitWidth - Amt;
3335         Known2.One.lshrInPlace(Amt);
3336         Known2.Zero.lshrInPlace(Amt);
3337       }
3338       Known.One |= Known2.One;
3339       Known.Zero |= Known2.Zero;
3340     }
3341     break;
3342   case ISD::SIGN_EXTEND_INREG: {
3343     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3344     EVT EVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
3345     Known = Known.sextInReg(EVT.getScalarSizeInBits());
3346     break;
3347   }
3348   case ISD::CTTZ:
3349   case ISD::CTTZ_ZERO_UNDEF: {
3350     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3351     // If we have a known 1, its position is our upper bound.
3352     unsigned PossibleTZ = Known2.countMaxTrailingZeros();
3353     unsigned LowBits = Log2_32(PossibleTZ) + 1;
3354     Known.Zero.setBitsFrom(LowBits);
3355     break;
3356   }
3357   case ISD::CTLZ:
3358   case ISD::CTLZ_ZERO_UNDEF: {
3359     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3360     // If we have a known 1, its position is our upper bound.
3361     unsigned PossibleLZ = Known2.countMaxLeadingZeros();
3362     unsigned LowBits = Log2_32(PossibleLZ) + 1;
3363     Known.Zero.setBitsFrom(LowBits);
3364     break;
3365   }
3366   case ISD::CTPOP: {
3367     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3368     // If we know some of the bits are zero, they can't be one.
3369     unsigned PossibleOnes = Known2.countMaxPopulation();
3370     Known.Zero.setBitsFrom(Log2_32(PossibleOnes) + 1);
3371     break;
3372   }
3373   case ISD::PARITY: {
3374     // Parity returns 0 everywhere but the LSB.
3375     Known.Zero.setBitsFrom(1);
3376     break;
3377   }
3378   case ISD::LOAD: {
3379     LoadSDNode *LD = cast<LoadSDNode>(Op);
3380     const Constant *Cst = TLI->getTargetConstantFromLoad(LD);
3381     if (ISD::isNON_EXTLoad(LD) && Cst) {
3382       // Determine any common known bits from the loaded constant pool value.
3383       Type *CstTy = Cst->getType();
3384       if ((NumElts * BitWidth) == CstTy->getPrimitiveSizeInBits()) {
3385         // If its a vector splat, then we can (quickly) reuse the scalar path.
3386         // NOTE: We assume all elements match and none are UNDEF.
3387         if (CstTy->isVectorTy()) {
3388           if (const Constant *Splat = Cst->getSplatValue()) {
3389             Cst = Splat;
3390             CstTy = Cst->getType();
3391           }
3392         }
3393         // TODO - do we need to handle different bitwidths?
3394         if (CstTy->isVectorTy() && BitWidth == CstTy->getScalarSizeInBits()) {
3395           // Iterate across all vector elements finding common known bits.
3396           Known.One.setAllBits();
3397           Known.Zero.setAllBits();
3398           for (unsigned i = 0; i != NumElts; ++i) {
3399             if (!DemandedElts[i])
3400               continue;
3401             if (Constant *Elt = Cst->getAggregateElement(i)) {
3402               if (auto *CInt = dyn_cast<ConstantInt>(Elt)) {
3403                 const APInt &Value = CInt->getValue();
3404                 Known.One &= Value;
3405                 Known.Zero &= ~Value;
3406                 continue;
3407               }
3408               if (auto *CFP = dyn_cast<ConstantFP>(Elt)) {
3409                 APInt Value = CFP->getValueAPF().bitcastToAPInt();
3410                 Known.One &= Value;
3411                 Known.Zero &= ~Value;
3412                 continue;
3413               }
3414             }
3415             Known.One.clearAllBits();
3416             Known.Zero.clearAllBits();
3417             break;
3418           }
3419         } else if (BitWidth == CstTy->getPrimitiveSizeInBits()) {
3420           if (auto *CInt = dyn_cast<ConstantInt>(Cst)) {
3421             Known = KnownBits::makeConstant(CInt->getValue());
3422           } else if (auto *CFP = dyn_cast<ConstantFP>(Cst)) {
3423             Known =
3424                 KnownBits::makeConstant(CFP->getValueAPF().bitcastToAPInt());
3425           }
3426         }
3427       }
3428     } else if (ISD::isZEXTLoad(Op.getNode()) && Op.getResNo() == 0) {
3429       // If this is a ZEXTLoad and we are looking at the loaded value.
3430       EVT VT = LD->getMemoryVT();
3431       unsigned MemBits = VT.getScalarSizeInBits();
3432       Known.Zero.setBitsFrom(MemBits);
3433     } else if (const MDNode *Ranges = LD->getRanges()) {
3434       if (LD->getExtensionType() == ISD::NON_EXTLOAD)
3435         computeKnownBitsFromRangeMetadata(*Ranges, Known);
3436     }
3437     break;
3438   }
3439   case ISD::ZERO_EXTEND_VECTOR_INREG: {
3440     EVT InVT = Op.getOperand(0).getValueType();
3441     APInt InDemandedElts = DemandedElts.zext(InVT.getVectorNumElements());
3442     Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1);
3443     Known = Known.zext(BitWidth);
3444     break;
3445   }
3446   case ISD::ZERO_EXTEND: {
3447     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3448     Known = Known.zext(BitWidth);
3449     break;
3450   }
3451   case ISD::SIGN_EXTEND_VECTOR_INREG: {
3452     EVT InVT = Op.getOperand(0).getValueType();
3453     APInt InDemandedElts = DemandedElts.zext(InVT.getVectorNumElements());
3454     Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1);
3455     // If the sign bit is known to be zero or one, then sext will extend
3456     // it to the top bits, else it will just zext.
3457     Known = Known.sext(BitWidth);
3458     break;
3459   }
3460   case ISD::SIGN_EXTEND: {
3461     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3462     // If the sign bit is known to be zero or one, then sext will extend
3463     // it to the top bits, else it will just zext.
3464     Known = Known.sext(BitWidth);
3465     break;
3466   }
3467   case ISD::ANY_EXTEND_VECTOR_INREG: {
3468     EVT InVT = Op.getOperand(0).getValueType();
3469     APInt InDemandedElts = DemandedElts.zext(InVT.getVectorNumElements());
3470     Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1);
3471     Known = Known.anyext(BitWidth);
3472     break;
3473   }
3474   case ISD::ANY_EXTEND: {
3475     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3476     Known = Known.anyext(BitWidth);
3477     break;
3478   }
3479   case ISD::TRUNCATE: {
3480     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3481     Known = Known.trunc(BitWidth);
3482     break;
3483   }
3484   case ISD::AssertZext: {
3485     EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
3486     APInt InMask = APInt::getLowBitsSet(BitWidth, VT.getSizeInBits());
3487     Known = computeKnownBits(Op.getOperand(0), Depth+1);
3488     Known.Zero |= (~InMask);
3489     Known.One  &= (~Known.Zero);
3490     break;
3491   }
3492   case ISD::AssertAlign: {
3493     unsigned LogOfAlign = Log2(cast<AssertAlignSDNode>(Op)->getAlign());
3494     assert(LogOfAlign != 0);
3495 
3496     // TODO: Should use maximum with source
3497     // If a node is guaranteed to be aligned, set low zero bits accordingly as
3498     // well as clearing one bits.
3499     Known.Zero.setLowBits(LogOfAlign);
3500     Known.One.clearLowBits(LogOfAlign);
3501     break;
3502   }
3503   case ISD::FGETSIGN:
3504     // All bits are zero except the low bit.
3505     Known.Zero.setBitsFrom(1);
3506     break;
3507   case ISD::USUBO:
3508   case ISD::SSUBO:
3509   case ISD::SUBCARRY:
3510   case ISD::SSUBO_CARRY:
3511     if (Op.getResNo() == 1) {
3512       // If we know the result of a setcc has the top bits zero, use this info.
3513       if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) ==
3514               TargetLowering::ZeroOrOneBooleanContent &&
3515           BitWidth > 1)
3516         Known.Zero.setBitsFrom(1);
3517       break;
3518     }
3519     LLVM_FALLTHROUGH;
3520   case ISD::SUB:
3521   case ISD::SUBC: {
3522     assert(Op.getResNo() == 0 &&
3523            "We only compute knownbits for the difference here.");
3524 
3525     // TODO: Compute influence of the carry operand.
3526     if (Opcode == ISD::SUBCARRY || Opcode == ISD::SSUBO_CARRY)
3527       break;
3528 
3529     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3530     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3531     Known = KnownBits::computeForAddSub(/* Add */ false, /* NSW */ false,
3532                                         Known, Known2);
3533     break;
3534   }
3535   case ISD::UADDO:
3536   case ISD::SADDO:
3537   case ISD::ADDCARRY:
3538   case ISD::SADDO_CARRY:
3539     if (Op.getResNo() == 1) {
3540       // If we know the result of a setcc has the top bits zero, use this info.
3541       if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) ==
3542               TargetLowering::ZeroOrOneBooleanContent &&
3543           BitWidth > 1)
3544         Known.Zero.setBitsFrom(1);
3545       break;
3546     }
3547     LLVM_FALLTHROUGH;
3548   case ISD::ADD:
3549   case ISD::ADDC:
3550   case ISD::ADDE: {
3551     assert(Op.getResNo() == 0 && "We only compute knownbits for the sum here.");
3552 
3553     // With ADDE and ADDCARRY, a carry bit may be added in.
3554     KnownBits Carry(1);
3555     if (Opcode == ISD::ADDE)
3556       // Can't track carry from glue, set carry to unknown.
3557       Carry.resetAll();
3558     else if (Opcode == ISD::ADDCARRY || Opcode == ISD::SADDO_CARRY)
3559       // TODO: Compute known bits for the carry operand. Not sure if it is worth
3560       // the trouble (how often will we find a known carry bit). And I haven't
3561       // tested this very much yet, but something like this might work:
3562       //   Carry = computeKnownBits(Op.getOperand(2), DemandedElts, Depth + 1);
3563       //   Carry = Carry.zextOrTrunc(1, false);
3564       Carry.resetAll();
3565     else
3566       Carry.setAllZero();
3567 
3568     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3569     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3570     Known = KnownBits::computeForAddCarry(Known, Known2, Carry);
3571     break;
3572   }
3573   case ISD::SREM: {
3574     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3575     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3576     Known = KnownBits::srem(Known, Known2);
3577     break;
3578   }
3579   case ISD::UREM: {
3580     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3581     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3582     Known = KnownBits::urem(Known, Known2);
3583     break;
3584   }
3585   case ISD::EXTRACT_ELEMENT: {
3586     Known = computeKnownBits(Op.getOperand(0), Depth+1);
3587     const unsigned Index = Op.getConstantOperandVal(1);
3588     const unsigned EltBitWidth = Op.getValueSizeInBits();
3589 
3590     // Remove low part of known bits mask
3591     Known.Zero = Known.Zero.getHiBits(Known.getBitWidth() - Index * EltBitWidth);
3592     Known.One = Known.One.getHiBits(Known.getBitWidth() - Index * EltBitWidth);
3593 
3594     // Remove high part of known bit mask
3595     Known = Known.trunc(EltBitWidth);
3596     break;
3597   }
3598   case ISD::EXTRACT_VECTOR_ELT: {
3599     SDValue InVec = Op.getOperand(0);
3600     SDValue EltNo = Op.getOperand(1);
3601     EVT VecVT = InVec.getValueType();
3602     // computeKnownBits not yet implemented for scalable vectors.
3603     if (VecVT.isScalableVector())
3604       break;
3605     const unsigned EltBitWidth = VecVT.getScalarSizeInBits();
3606     const unsigned NumSrcElts = VecVT.getVectorNumElements();
3607 
3608     // If BitWidth > EltBitWidth the value is anyext:ed. So we do not know
3609     // anything about the extended bits.
3610     if (BitWidth > EltBitWidth)
3611       Known = Known.trunc(EltBitWidth);
3612 
3613     // If we know the element index, just demand that vector element, else for
3614     // an unknown element index, ignore DemandedElts and demand them all.
3615     APInt DemandedSrcElts = APInt::getAllOnes(NumSrcElts);
3616     auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
3617     if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts))
3618       DemandedSrcElts =
3619           APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue());
3620 
3621     Known = computeKnownBits(InVec, DemandedSrcElts, Depth + 1);
3622     if (BitWidth > EltBitWidth)
3623       Known = Known.anyext(BitWidth);
3624     break;
3625   }
3626   case ISD::INSERT_VECTOR_ELT: {
3627     // If we know the element index, split the demand between the
3628     // source vector and the inserted element, otherwise assume we need
3629     // the original demanded vector elements and the value.
3630     SDValue InVec = Op.getOperand(0);
3631     SDValue InVal = Op.getOperand(1);
3632     SDValue EltNo = Op.getOperand(2);
3633     bool DemandedVal = true;
3634     APInt DemandedVecElts = DemandedElts;
3635     auto *CEltNo = dyn_cast<ConstantSDNode>(EltNo);
3636     if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) {
3637       unsigned EltIdx = CEltNo->getZExtValue();
3638       DemandedVal = !!DemandedElts[EltIdx];
3639       DemandedVecElts.clearBit(EltIdx);
3640     }
3641     Known.One.setAllBits();
3642     Known.Zero.setAllBits();
3643     if (DemandedVal) {
3644       Known2 = computeKnownBits(InVal, Depth + 1);
3645       Known = KnownBits::commonBits(Known, Known2.zextOrTrunc(BitWidth));
3646     }
3647     if (!!DemandedVecElts) {
3648       Known2 = computeKnownBits(InVec, DemandedVecElts, Depth + 1);
3649       Known = KnownBits::commonBits(Known, Known2);
3650     }
3651     break;
3652   }
3653   case ISD::BITREVERSE: {
3654     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3655     Known = Known2.reverseBits();
3656     break;
3657   }
3658   case ISD::BSWAP: {
3659     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3660     Known = Known2.byteSwap();
3661     break;
3662   }
3663   case ISD::ABS: {
3664     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3665     Known = Known2.abs();
3666     break;
3667   }
3668   case ISD::USUBSAT: {
3669     // The result of usubsat will never be larger than the LHS.
3670     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3671     Known.Zero.setHighBits(Known2.countMinLeadingZeros());
3672     break;
3673   }
3674   case ISD::UMIN: {
3675     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3676     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3677     Known = KnownBits::umin(Known, Known2);
3678     break;
3679   }
3680   case ISD::UMAX: {
3681     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3682     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3683     Known = KnownBits::umax(Known, Known2);
3684     break;
3685   }
3686   case ISD::SMIN:
3687   case ISD::SMAX: {
3688     // If we have a clamp pattern, we know that the number of sign bits will be
3689     // the minimum of the clamp min/max range.
3690     bool IsMax = (Opcode == ISD::SMAX);
3691     ConstantSDNode *CstLow = nullptr, *CstHigh = nullptr;
3692     if ((CstLow = isConstOrConstSplat(Op.getOperand(1), DemandedElts)))
3693       if (Op.getOperand(0).getOpcode() == (IsMax ? ISD::SMIN : ISD::SMAX))
3694         CstHigh =
3695             isConstOrConstSplat(Op.getOperand(0).getOperand(1), DemandedElts);
3696     if (CstLow && CstHigh) {
3697       if (!IsMax)
3698         std::swap(CstLow, CstHigh);
3699 
3700       const APInt &ValueLow = CstLow->getAPIntValue();
3701       const APInt &ValueHigh = CstHigh->getAPIntValue();
3702       if (ValueLow.sle(ValueHigh)) {
3703         unsigned LowSignBits = ValueLow.getNumSignBits();
3704         unsigned HighSignBits = ValueHigh.getNumSignBits();
3705         unsigned MinSignBits = std::min(LowSignBits, HighSignBits);
3706         if (ValueLow.isNegative() && ValueHigh.isNegative()) {
3707           Known.One.setHighBits(MinSignBits);
3708           break;
3709         }
3710         if (ValueLow.isNonNegative() && ValueHigh.isNonNegative()) {
3711           Known.Zero.setHighBits(MinSignBits);
3712           break;
3713         }
3714       }
3715     }
3716 
3717     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3718     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3719     if (IsMax)
3720       Known = KnownBits::smax(Known, Known2);
3721     else
3722       Known = KnownBits::smin(Known, Known2);
3723 
3724     // For SMAX, if CstLow is non-negative we know the result will be
3725     // non-negative and thus all sign bits are 0.
3726     // TODO: There's an equivalent of this for smin with negative constant for
3727     // known ones.
3728     if (IsMax && CstLow) {
3729       const APInt &ValueLow = CstLow->getAPIntValue();
3730       if (ValueLow.isNonNegative()) {
3731         unsigned SignBits = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
3732         Known.Zero.setHighBits(std::min(SignBits, ValueLow.getNumSignBits()));
3733       }
3734     }
3735 
3736     break;
3737   }
3738   case ISD::FP_TO_UINT_SAT: {
3739     // FP_TO_UINT_SAT produces an unsigned value that fits in the saturating VT.
3740     EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
3741     Known.Zero |= APInt::getBitsSetFrom(BitWidth, VT.getScalarSizeInBits());
3742     break;
3743   }
3744   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
3745     if (Op.getResNo() == 1) {
3746       // The boolean result conforms to getBooleanContents.
3747       // If we know the result of a setcc has the top bits zero, use this info.
3748       // We know that we have an integer-based boolean since these operations
3749       // are only available for integer.
3750       if (TLI->getBooleanContents(Op.getValueType().isVector(), false) ==
3751               TargetLowering::ZeroOrOneBooleanContent &&
3752           BitWidth > 1)
3753         Known.Zero.setBitsFrom(1);
3754       break;
3755     }
3756     LLVM_FALLTHROUGH;
3757   case ISD::ATOMIC_CMP_SWAP:
3758   case ISD::ATOMIC_SWAP:
3759   case ISD::ATOMIC_LOAD_ADD:
3760   case ISD::ATOMIC_LOAD_SUB:
3761   case ISD::ATOMIC_LOAD_AND:
3762   case ISD::ATOMIC_LOAD_CLR:
3763   case ISD::ATOMIC_LOAD_OR:
3764   case ISD::ATOMIC_LOAD_XOR:
3765   case ISD::ATOMIC_LOAD_NAND:
3766   case ISD::ATOMIC_LOAD_MIN:
3767   case ISD::ATOMIC_LOAD_MAX:
3768   case ISD::ATOMIC_LOAD_UMIN:
3769   case ISD::ATOMIC_LOAD_UMAX:
3770   case ISD::ATOMIC_LOAD: {
3771     unsigned MemBits =
3772         cast<AtomicSDNode>(Op)->getMemoryVT().getScalarSizeInBits();
3773     // If we are looking at the loaded value.
3774     if (Op.getResNo() == 0) {
3775       if (TLI->getExtendForAtomicOps() == ISD::ZERO_EXTEND)
3776         Known.Zero.setBitsFrom(MemBits);
3777     }
3778     break;
3779   }
3780   case ISD::FrameIndex:
3781   case ISD::TargetFrameIndex:
3782     TLI->computeKnownBitsForFrameIndex(cast<FrameIndexSDNode>(Op)->getIndex(),
3783                                        Known, getMachineFunction());
3784     break;
3785 
3786   default:
3787     if (Opcode < ISD::BUILTIN_OP_END)
3788       break;
3789     LLVM_FALLTHROUGH;
3790   case ISD::INTRINSIC_WO_CHAIN:
3791   case ISD::INTRINSIC_W_CHAIN:
3792   case ISD::INTRINSIC_VOID:
3793     // Allow the target to implement this method for its nodes.
3794     TLI->computeKnownBitsForTargetNode(Op, Known, DemandedElts, *this, Depth);
3795     break;
3796   }
3797 
3798   assert(!Known.hasConflict() && "Bits known to be one AND zero?");
3799   return Known;
3800 }
3801 
3802 SelectionDAG::OverflowKind SelectionDAG::computeOverflowKind(SDValue N0,
3803                                                              SDValue N1) const {
3804   // X + 0 never overflow
3805   if (isNullConstant(N1))
3806     return OFK_Never;
3807 
3808   KnownBits N1Known = computeKnownBits(N1);
3809   if (N1Known.Zero.getBoolValue()) {
3810     KnownBits N0Known = computeKnownBits(N0);
3811 
3812     bool overflow;
3813     (void)N0Known.getMaxValue().uadd_ov(N1Known.getMaxValue(), overflow);
3814     if (!overflow)
3815       return OFK_Never;
3816   }
3817 
3818   // mulhi + 1 never overflow
3819   if (N0.getOpcode() == ISD::UMUL_LOHI && N0.getResNo() == 1 &&
3820       (N1Known.getMaxValue() & 0x01) == N1Known.getMaxValue())
3821     return OFK_Never;
3822 
3823   if (N1.getOpcode() == ISD::UMUL_LOHI && N1.getResNo() == 1) {
3824     KnownBits N0Known = computeKnownBits(N0);
3825 
3826     if ((N0Known.getMaxValue() & 0x01) == N0Known.getMaxValue())
3827       return OFK_Never;
3828   }
3829 
3830   return OFK_Sometime;
3831 }
3832 
3833 bool SelectionDAG::isKnownToBeAPowerOfTwo(SDValue Val) const {
3834   EVT OpVT = Val.getValueType();
3835   unsigned BitWidth = OpVT.getScalarSizeInBits();
3836 
3837   // Is the constant a known power of 2?
3838   if (ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Val))
3839     return Const->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2();
3840 
3841   // A left-shift of a constant one will have exactly one bit set because
3842   // shifting the bit off the end is undefined.
3843   if (Val.getOpcode() == ISD::SHL) {
3844     auto *C = isConstOrConstSplat(Val.getOperand(0));
3845     if (C && C->getAPIntValue() == 1)
3846       return true;
3847   }
3848 
3849   // Similarly, a logical right-shift of a constant sign-bit will have exactly
3850   // one bit set.
3851   if (Val.getOpcode() == ISD::SRL) {
3852     auto *C = isConstOrConstSplat(Val.getOperand(0));
3853     if (C && C->getAPIntValue().isSignMask())
3854       return true;
3855   }
3856 
3857   // Are all operands of a build vector constant powers of two?
3858   if (Val.getOpcode() == ISD::BUILD_VECTOR)
3859     if (llvm::all_of(Val->ops(), [BitWidth](SDValue E) {
3860           if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(E))
3861             return C->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2();
3862           return false;
3863         }))
3864       return true;
3865 
3866   // Is the operand of a splat vector a constant power of two?
3867   if (Val.getOpcode() == ISD::SPLAT_VECTOR)
3868     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val->getOperand(0)))
3869       if (C->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2())
3870         return true;
3871 
3872   // More could be done here, though the above checks are enough
3873   // to handle some common cases.
3874 
3875   // Fall back to computeKnownBits to catch other known cases.
3876   KnownBits Known = computeKnownBits(Val);
3877   return (Known.countMaxPopulation() == 1) && (Known.countMinPopulation() == 1);
3878 }
3879 
3880 unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, unsigned Depth) const {
3881   EVT VT = Op.getValueType();
3882 
3883   // TODO: Assume we don't know anything for now.
3884   if (VT.isScalableVector())
3885     return 1;
3886 
3887   APInt DemandedElts = VT.isVector()
3888                            ? APInt::getAllOnes(VT.getVectorNumElements())
3889                            : APInt(1, 1);
3890   return ComputeNumSignBits(Op, DemandedElts, Depth);
3891 }
3892 
3893 unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, const APInt &DemandedElts,
3894                                           unsigned Depth) const {
3895   EVT VT = Op.getValueType();
3896   assert((VT.isInteger() || VT.isFloatingPoint()) && "Invalid VT!");
3897   unsigned VTBits = VT.getScalarSizeInBits();
3898   unsigned NumElts = DemandedElts.getBitWidth();
3899   unsigned Tmp, Tmp2;
3900   unsigned FirstAnswer = 1;
3901 
3902   if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
3903     const APInt &Val = C->getAPIntValue();
3904     return Val.getNumSignBits();
3905   }
3906 
3907   if (Depth >= MaxRecursionDepth)
3908     return 1;  // Limit search depth.
3909 
3910   if (!DemandedElts || VT.isScalableVector())
3911     return 1;  // No demanded elts, better to assume we don't know anything.
3912 
3913   unsigned Opcode = Op.getOpcode();
3914   switch (Opcode) {
3915   default: break;
3916   case ISD::AssertSext:
3917     Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
3918     return VTBits-Tmp+1;
3919   case ISD::AssertZext:
3920     Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
3921     return VTBits-Tmp;
3922 
3923   case ISD::BUILD_VECTOR:
3924     Tmp = VTBits;
3925     for (unsigned i = 0, e = Op.getNumOperands(); (i < e) && (Tmp > 1); ++i) {
3926       if (!DemandedElts[i])
3927         continue;
3928 
3929       SDValue SrcOp = Op.getOperand(i);
3930       Tmp2 = ComputeNumSignBits(SrcOp, Depth + 1);
3931 
3932       // BUILD_VECTOR can implicitly truncate sources, we must handle this.
3933       if (SrcOp.getValueSizeInBits() != VTBits) {
3934         assert(SrcOp.getValueSizeInBits() > VTBits &&
3935                "Expected BUILD_VECTOR implicit truncation");
3936         unsigned ExtraBits = SrcOp.getValueSizeInBits() - VTBits;
3937         Tmp2 = (Tmp2 > ExtraBits ? Tmp2 - ExtraBits : 1);
3938       }
3939       Tmp = std::min(Tmp, Tmp2);
3940     }
3941     return Tmp;
3942 
3943   case ISD::VECTOR_SHUFFLE: {
3944     // Collect the minimum number of sign bits that are shared by every vector
3945     // element referenced by the shuffle.
3946     APInt DemandedLHS(NumElts, 0), DemandedRHS(NumElts, 0);
3947     const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op);
3948     assert(NumElts == SVN->getMask().size() && "Unexpected vector size");
3949     for (unsigned i = 0; i != NumElts; ++i) {
3950       int M = SVN->getMaskElt(i);
3951       if (!DemandedElts[i])
3952         continue;
3953       // For UNDEF elements, we don't know anything about the common state of
3954       // the shuffle result.
3955       if (M < 0)
3956         return 1;
3957       if ((unsigned)M < NumElts)
3958         DemandedLHS.setBit((unsigned)M % NumElts);
3959       else
3960         DemandedRHS.setBit((unsigned)M % NumElts);
3961     }
3962     Tmp = std::numeric_limits<unsigned>::max();
3963     if (!!DemandedLHS)
3964       Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedLHS, Depth + 1);
3965     if (!!DemandedRHS) {
3966       Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedRHS, Depth + 1);
3967       Tmp = std::min(Tmp, Tmp2);
3968     }
3969     // If we don't know anything, early out and try computeKnownBits fall-back.
3970     if (Tmp == 1)
3971       break;
3972     assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
3973     return Tmp;
3974   }
3975 
3976   case ISD::BITCAST: {
3977     SDValue N0 = Op.getOperand(0);
3978     EVT SrcVT = N0.getValueType();
3979     unsigned SrcBits = SrcVT.getScalarSizeInBits();
3980 
3981     // Ignore bitcasts from unsupported types..
3982     if (!(SrcVT.isInteger() || SrcVT.isFloatingPoint()))
3983       break;
3984 
3985     // Fast handling of 'identity' bitcasts.
3986     if (VTBits == SrcBits)
3987       return ComputeNumSignBits(N0, DemandedElts, Depth + 1);
3988 
3989     bool IsLE = getDataLayout().isLittleEndian();
3990 
3991     // Bitcast 'large element' scalar/vector to 'small element' vector.
3992     if ((SrcBits % VTBits) == 0) {
3993       assert(VT.isVector() && "Expected bitcast to vector");
3994 
3995       unsigned Scale = SrcBits / VTBits;
3996       APInt SrcDemandedElts =
3997           APIntOps::ScaleBitMask(DemandedElts, NumElts / Scale);
3998 
3999       // Fast case - sign splat can be simply split across the small elements.
4000       Tmp = ComputeNumSignBits(N0, SrcDemandedElts, Depth + 1);
4001       if (Tmp == SrcBits)
4002         return VTBits;
4003 
4004       // Slow case - determine how far the sign extends into each sub-element.
4005       Tmp2 = VTBits;
4006       for (unsigned i = 0; i != NumElts; ++i)
4007         if (DemandedElts[i]) {
4008           unsigned SubOffset = i % Scale;
4009           SubOffset = (IsLE ? ((Scale - 1) - SubOffset) : SubOffset);
4010           SubOffset = SubOffset * VTBits;
4011           if (Tmp <= SubOffset)
4012             return 1;
4013           Tmp2 = std::min(Tmp2, Tmp - SubOffset);
4014         }
4015       return Tmp2;
4016     }
4017     break;
4018   }
4019 
4020   case ISD::FP_TO_SINT_SAT:
4021     // FP_TO_SINT_SAT produces a signed value that fits in the saturating VT.
4022     Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getScalarSizeInBits();
4023     return VTBits - Tmp + 1;
4024   case ISD::SIGN_EXTEND:
4025     Tmp = VTBits - Op.getOperand(0).getScalarValueSizeInBits();
4026     return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1) + Tmp;
4027   case ISD::SIGN_EXTEND_INREG:
4028     // Max of the input and what this extends.
4029     Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getScalarSizeInBits();
4030     Tmp = VTBits-Tmp+1;
4031     Tmp2 = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1);
4032     return std::max(Tmp, Tmp2);
4033   case ISD::SIGN_EXTEND_VECTOR_INREG: {
4034     SDValue Src = Op.getOperand(0);
4035     EVT SrcVT = Src.getValueType();
4036     APInt DemandedSrcElts = DemandedElts.zext(SrcVT.getVectorNumElements());
4037     Tmp = VTBits - SrcVT.getScalarSizeInBits();
4038     return ComputeNumSignBits(Src, DemandedSrcElts, Depth+1) + Tmp;
4039   }
4040   case ISD::SRA:
4041     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
4042     // SRA X, C -> adds C sign bits.
4043     if (const APInt *ShAmt =
4044             getValidMinimumShiftAmountConstant(Op, DemandedElts))
4045       Tmp = std::min<uint64_t>(Tmp + ShAmt->getZExtValue(), VTBits);
4046     return Tmp;
4047   case ISD::SHL:
4048     if (const APInt *ShAmt =
4049             getValidMaximumShiftAmountConstant(Op, DemandedElts)) {
4050       // shl destroys sign bits, ensure it doesn't shift out all sign bits.
4051       Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
4052       if (ShAmt->ult(Tmp))
4053         return Tmp - ShAmt->getZExtValue();
4054     }
4055     break;
4056   case ISD::AND:
4057   case ISD::OR:
4058   case ISD::XOR:    // NOT is handled here.
4059     // Logical binary ops preserve the number of sign bits at the worst.
4060     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1);
4061     if (Tmp != 1) {
4062       Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth+1);
4063       FirstAnswer = std::min(Tmp, Tmp2);
4064       // We computed what we know about the sign bits as our first
4065       // answer. Now proceed to the generic code that uses
4066       // computeKnownBits, and pick whichever answer is better.
4067     }
4068     break;
4069 
4070   case ISD::SELECT:
4071   case ISD::VSELECT:
4072     Tmp = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth+1);
4073     if (Tmp == 1) return 1;  // Early out.
4074     Tmp2 = ComputeNumSignBits(Op.getOperand(2), DemandedElts, Depth+1);
4075     return std::min(Tmp, Tmp2);
4076   case ISD::SELECT_CC:
4077     Tmp = ComputeNumSignBits(Op.getOperand(2), DemandedElts, Depth+1);
4078     if (Tmp == 1) return 1;  // Early out.
4079     Tmp2 = ComputeNumSignBits(Op.getOperand(3), DemandedElts, Depth+1);
4080     return std::min(Tmp, Tmp2);
4081 
4082   case ISD::SMIN:
4083   case ISD::SMAX: {
4084     // If we have a clamp pattern, we know that the number of sign bits will be
4085     // the minimum of the clamp min/max range.
4086     bool IsMax = (Opcode == ISD::SMAX);
4087     ConstantSDNode *CstLow = nullptr, *CstHigh = nullptr;
4088     if ((CstLow = isConstOrConstSplat(Op.getOperand(1), DemandedElts)))
4089       if (Op.getOperand(0).getOpcode() == (IsMax ? ISD::SMIN : ISD::SMAX))
4090         CstHigh =
4091             isConstOrConstSplat(Op.getOperand(0).getOperand(1), DemandedElts);
4092     if (CstLow && CstHigh) {
4093       if (!IsMax)
4094         std::swap(CstLow, CstHigh);
4095       if (CstLow->getAPIntValue().sle(CstHigh->getAPIntValue())) {
4096         Tmp = CstLow->getAPIntValue().getNumSignBits();
4097         Tmp2 = CstHigh->getAPIntValue().getNumSignBits();
4098         return std::min(Tmp, Tmp2);
4099       }
4100     }
4101 
4102     // Fallback - just get the minimum number of sign bits of the operands.
4103     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
4104     if (Tmp == 1)
4105       return 1;  // Early out.
4106     Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
4107     return std::min(Tmp, Tmp2);
4108   }
4109   case ISD::UMIN:
4110   case ISD::UMAX:
4111     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
4112     if (Tmp == 1)
4113       return 1;  // Early out.
4114     Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
4115     return std::min(Tmp, Tmp2);
4116   case ISD::SADDO:
4117   case ISD::UADDO:
4118   case ISD::SADDO_CARRY:
4119   case ISD::ADDCARRY:
4120   case ISD::SSUBO:
4121   case ISD::USUBO:
4122   case ISD::SSUBO_CARRY:
4123   case ISD::SUBCARRY:
4124   case ISD::SMULO:
4125   case ISD::UMULO:
4126     if (Op.getResNo() != 1)
4127       break;
4128     // The boolean result conforms to getBooleanContents.  Fall through.
4129     // If setcc returns 0/-1, all bits are sign bits.
4130     // We know that we have an integer-based boolean since these operations
4131     // are only available for integer.
4132     if (TLI->getBooleanContents(VT.isVector(), false) ==
4133         TargetLowering::ZeroOrNegativeOneBooleanContent)
4134       return VTBits;
4135     break;
4136   case ISD::SETCC:
4137   case ISD::SETCCCARRY:
4138   case ISD::STRICT_FSETCC:
4139   case ISD::STRICT_FSETCCS: {
4140     unsigned OpNo = Op->isStrictFPOpcode() ? 1 : 0;
4141     // If setcc returns 0/-1, all bits are sign bits.
4142     if (TLI->getBooleanContents(Op.getOperand(OpNo).getValueType()) ==
4143         TargetLowering::ZeroOrNegativeOneBooleanContent)
4144       return VTBits;
4145     break;
4146   }
4147   case ISD::ROTL:
4148   case ISD::ROTR:
4149     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
4150 
4151     // If we're rotating an 0/-1 value, then it stays an 0/-1 value.
4152     if (Tmp == VTBits)
4153       return VTBits;
4154 
4155     if (ConstantSDNode *C =
4156             isConstOrConstSplat(Op.getOperand(1), DemandedElts)) {
4157       unsigned RotAmt = C->getAPIntValue().urem(VTBits);
4158 
4159       // Handle rotate right by N like a rotate left by 32-N.
4160       if (Opcode == ISD::ROTR)
4161         RotAmt = (VTBits - RotAmt) % VTBits;
4162 
4163       // If we aren't rotating out all of the known-in sign bits, return the
4164       // number that are left.  This handles rotl(sext(x), 1) for example.
4165       if (Tmp > (RotAmt + 1)) return (Tmp - RotAmt);
4166     }
4167     break;
4168   case ISD::ADD:
4169   case ISD::ADDC:
4170     // Add can have at most one carry bit.  Thus we know that the output
4171     // is, at worst, one more bit than the inputs.
4172     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
4173     if (Tmp == 1) return 1; // Early out.
4174 
4175     // Special case decrementing a value (ADD X, -1):
4176     if (ConstantSDNode *CRHS =
4177             isConstOrConstSplat(Op.getOperand(1), DemandedElts))
4178       if (CRHS->isAllOnes()) {
4179         KnownBits Known =
4180             computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4181 
4182         // If the input is known to be 0 or 1, the output is 0/-1, which is all
4183         // sign bits set.
4184         if ((Known.Zero | 1).isAllOnes())
4185           return VTBits;
4186 
4187         // If we are subtracting one from a positive number, there is no carry
4188         // out of the result.
4189         if (Known.isNonNegative())
4190           return Tmp;
4191       }
4192 
4193     Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
4194     if (Tmp2 == 1) return 1; // Early out.
4195     return std::min(Tmp, Tmp2) - 1;
4196   case ISD::SUB:
4197     Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
4198     if (Tmp2 == 1) return 1; // Early out.
4199 
4200     // Handle NEG.
4201     if (ConstantSDNode *CLHS =
4202             isConstOrConstSplat(Op.getOperand(0), DemandedElts))
4203       if (CLHS->isZero()) {
4204         KnownBits Known =
4205             computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4206         // If the input is known to be 0 or 1, the output is 0/-1, which is all
4207         // sign bits set.
4208         if ((Known.Zero | 1).isAllOnes())
4209           return VTBits;
4210 
4211         // If the input is known to be positive (the sign bit is known clear),
4212         // the output of the NEG has the same number of sign bits as the input.
4213         if (Known.isNonNegative())
4214           return Tmp2;
4215 
4216         // Otherwise, we treat this like a SUB.
4217       }
4218 
4219     // Sub can have at most one carry bit.  Thus we know that the output
4220     // is, at worst, one more bit than the inputs.
4221     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
4222     if (Tmp == 1) return 1; // Early out.
4223     return std::min(Tmp, Tmp2) - 1;
4224   case ISD::MUL: {
4225     // The output of the Mul can be at most twice the valid bits in the inputs.
4226     unsigned SignBitsOp0 = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
4227     if (SignBitsOp0 == 1)
4228       break;
4229     unsigned SignBitsOp1 = ComputeNumSignBits(Op.getOperand(1), Depth + 1);
4230     if (SignBitsOp1 == 1)
4231       break;
4232     unsigned OutValidBits =
4233         (VTBits - SignBitsOp0 + 1) + (VTBits - SignBitsOp1 + 1);
4234     return OutValidBits > VTBits ? 1 : VTBits - OutValidBits + 1;
4235   }
4236   case ISD::SREM:
4237     // The sign bit is the LHS's sign bit, except when the result of the
4238     // remainder is zero. The magnitude of the result should be less than or
4239     // equal to the magnitude of the LHS. Therefore, the result should have
4240     // at least as many sign bits as the left hand side.
4241     return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
4242   case ISD::TRUNCATE: {
4243     // Check if the sign bits of source go down as far as the truncated value.
4244     unsigned NumSrcBits = Op.getOperand(0).getScalarValueSizeInBits();
4245     unsigned NumSrcSignBits = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
4246     if (NumSrcSignBits > (NumSrcBits - VTBits))
4247       return NumSrcSignBits - (NumSrcBits - VTBits);
4248     break;
4249   }
4250   case ISD::EXTRACT_ELEMENT: {
4251     const int KnownSign = ComputeNumSignBits(Op.getOperand(0), Depth+1);
4252     const int BitWidth = Op.getValueSizeInBits();
4253     const int Items = Op.getOperand(0).getValueSizeInBits() / BitWidth;
4254 
4255     // Get reverse index (starting from 1), Op1 value indexes elements from
4256     // little end. Sign starts at big end.
4257     const int rIndex = Items - 1 - Op.getConstantOperandVal(1);
4258 
4259     // If the sign portion ends in our element the subtraction gives correct
4260     // result. Otherwise it gives either negative or > bitwidth result
4261     return std::max(std::min(KnownSign - rIndex * BitWidth, BitWidth), 0);
4262   }
4263   case ISD::INSERT_VECTOR_ELT: {
4264     // If we know the element index, split the demand between the
4265     // source vector and the inserted element, otherwise assume we need
4266     // the original demanded vector elements and the value.
4267     SDValue InVec = Op.getOperand(0);
4268     SDValue InVal = Op.getOperand(1);
4269     SDValue EltNo = Op.getOperand(2);
4270     bool DemandedVal = true;
4271     APInt DemandedVecElts = DemandedElts;
4272     auto *CEltNo = dyn_cast<ConstantSDNode>(EltNo);
4273     if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) {
4274       unsigned EltIdx = CEltNo->getZExtValue();
4275       DemandedVal = !!DemandedElts[EltIdx];
4276       DemandedVecElts.clearBit(EltIdx);
4277     }
4278     Tmp = std::numeric_limits<unsigned>::max();
4279     if (DemandedVal) {
4280       // TODO - handle implicit truncation of inserted elements.
4281       if (InVal.getScalarValueSizeInBits() != VTBits)
4282         break;
4283       Tmp2 = ComputeNumSignBits(InVal, Depth + 1);
4284       Tmp = std::min(Tmp, Tmp2);
4285     }
4286     if (!!DemandedVecElts) {
4287       Tmp2 = ComputeNumSignBits(InVec, DemandedVecElts, Depth + 1);
4288       Tmp = std::min(Tmp, Tmp2);
4289     }
4290     assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
4291     return Tmp;
4292   }
4293   case ISD::EXTRACT_VECTOR_ELT: {
4294     SDValue InVec = Op.getOperand(0);
4295     SDValue EltNo = Op.getOperand(1);
4296     EVT VecVT = InVec.getValueType();
4297     // ComputeNumSignBits not yet implemented for scalable vectors.
4298     if (VecVT.isScalableVector())
4299       break;
4300     const unsigned BitWidth = Op.getValueSizeInBits();
4301     const unsigned EltBitWidth = Op.getOperand(0).getScalarValueSizeInBits();
4302     const unsigned NumSrcElts = VecVT.getVectorNumElements();
4303 
4304     // If BitWidth > EltBitWidth the value is anyext:ed, and we do not know
4305     // anything about sign bits. But if the sizes match we can derive knowledge
4306     // about sign bits from the vector operand.
4307     if (BitWidth != EltBitWidth)
4308       break;
4309 
4310     // If we know the element index, just demand that vector element, else for
4311     // an unknown element index, ignore DemandedElts and demand them all.
4312     APInt DemandedSrcElts = APInt::getAllOnes(NumSrcElts);
4313     auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
4314     if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts))
4315       DemandedSrcElts =
4316           APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue());
4317 
4318     return ComputeNumSignBits(InVec, DemandedSrcElts, Depth + 1);
4319   }
4320   case ISD::EXTRACT_SUBVECTOR: {
4321     // Offset the demanded elts by the subvector index.
4322     SDValue Src = Op.getOperand(0);
4323     // Bail until we can represent demanded elements for scalable vectors.
4324     if (Src.getValueType().isScalableVector())
4325       break;
4326     uint64_t Idx = Op.getConstantOperandVal(1);
4327     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
4328     APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts).shl(Idx);
4329     return ComputeNumSignBits(Src, DemandedSrcElts, Depth + 1);
4330   }
4331   case ISD::CONCAT_VECTORS: {
4332     // Determine the minimum number of sign bits across all demanded
4333     // elts of the input vectors. Early out if the result is already 1.
4334     Tmp = std::numeric_limits<unsigned>::max();
4335     EVT SubVectorVT = Op.getOperand(0).getValueType();
4336     unsigned NumSubVectorElts = SubVectorVT.getVectorNumElements();
4337     unsigned NumSubVectors = Op.getNumOperands();
4338     for (unsigned i = 0; (i < NumSubVectors) && (Tmp > 1); ++i) {
4339       APInt DemandedSub =
4340           DemandedElts.extractBits(NumSubVectorElts, i * NumSubVectorElts);
4341       if (!DemandedSub)
4342         continue;
4343       Tmp2 = ComputeNumSignBits(Op.getOperand(i), DemandedSub, Depth + 1);
4344       Tmp = std::min(Tmp, Tmp2);
4345     }
4346     assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
4347     return Tmp;
4348   }
4349   case ISD::INSERT_SUBVECTOR: {
4350     // Demand any elements from the subvector and the remainder from the src its
4351     // inserted into.
4352     SDValue Src = Op.getOperand(0);
4353     SDValue Sub = Op.getOperand(1);
4354     uint64_t Idx = Op.getConstantOperandVal(2);
4355     unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
4356     APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
4357     APInt DemandedSrcElts = DemandedElts;
4358     DemandedSrcElts.insertBits(APInt::getZero(NumSubElts), Idx);
4359 
4360     Tmp = std::numeric_limits<unsigned>::max();
4361     if (!!DemandedSubElts) {
4362       Tmp = ComputeNumSignBits(Sub, DemandedSubElts, Depth + 1);
4363       if (Tmp == 1)
4364         return 1; // early-out
4365     }
4366     if (!!DemandedSrcElts) {
4367       Tmp2 = ComputeNumSignBits(Src, DemandedSrcElts, Depth + 1);
4368       Tmp = std::min(Tmp, Tmp2);
4369     }
4370     assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
4371     return Tmp;
4372   }
4373   case ISD::ATOMIC_CMP_SWAP:
4374   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
4375   case ISD::ATOMIC_SWAP:
4376   case ISD::ATOMIC_LOAD_ADD:
4377   case ISD::ATOMIC_LOAD_SUB:
4378   case ISD::ATOMIC_LOAD_AND:
4379   case ISD::ATOMIC_LOAD_CLR:
4380   case ISD::ATOMIC_LOAD_OR:
4381   case ISD::ATOMIC_LOAD_XOR:
4382   case ISD::ATOMIC_LOAD_NAND:
4383   case ISD::ATOMIC_LOAD_MIN:
4384   case ISD::ATOMIC_LOAD_MAX:
4385   case ISD::ATOMIC_LOAD_UMIN:
4386   case ISD::ATOMIC_LOAD_UMAX:
4387   case ISD::ATOMIC_LOAD: {
4388     Tmp = cast<AtomicSDNode>(Op)->getMemoryVT().getScalarSizeInBits();
4389     // If we are looking at the loaded value.
4390     if (Op.getResNo() == 0) {
4391       if (Tmp == VTBits)
4392         return 1; // early-out
4393       if (TLI->getExtendForAtomicOps() == ISD::SIGN_EXTEND)
4394         return VTBits - Tmp + 1;
4395       if (TLI->getExtendForAtomicOps() == ISD::ZERO_EXTEND)
4396         return VTBits - Tmp;
4397     }
4398     break;
4399   }
4400   }
4401 
4402   // If we are looking at the loaded value of the SDNode.
4403   if (Op.getResNo() == 0) {
4404     // Handle LOADX separately here. EXTLOAD case will fallthrough.
4405     if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
4406       unsigned ExtType = LD->getExtensionType();
4407       switch (ExtType) {
4408       default: break;
4409       case ISD::SEXTLOAD: // e.g. i16->i32 = '17' bits known.
4410         Tmp = LD->getMemoryVT().getScalarSizeInBits();
4411         return VTBits - Tmp + 1;
4412       case ISD::ZEXTLOAD: // e.g. i16->i32 = '16' bits known.
4413         Tmp = LD->getMemoryVT().getScalarSizeInBits();
4414         return VTBits - Tmp;
4415       case ISD::NON_EXTLOAD:
4416         if (const Constant *Cst = TLI->getTargetConstantFromLoad(LD)) {
4417           // We only need to handle vectors - computeKnownBits should handle
4418           // scalar cases.
4419           Type *CstTy = Cst->getType();
4420           if (CstTy->isVectorTy() &&
4421               (NumElts * VTBits) == CstTy->getPrimitiveSizeInBits() &&
4422               VTBits == CstTy->getScalarSizeInBits()) {
4423             Tmp = VTBits;
4424             for (unsigned i = 0; i != NumElts; ++i) {
4425               if (!DemandedElts[i])
4426                 continue;
4427               if (Constant *Elt = Cst->getAggregateElement(i)) {
4428                 if (auto *CInt = dyn_cast<ConstantInt>(Elt)) {
4429                   const APInt &Value = CInt->getValue();
4430                   Tmp = std::min(Tmp, Value.getNumSignBits());
4431                   continue;
4432                 }
4433                 if (auto *CFP = dyn_cast<ConstantFP>(Elt)) {
4434                   APInt Value = CFP->getValueAPF().bitcastToAPInt();
4435                   Tmp = std::min(Tmp, Value.getNumSignBits());
4436                   continue;
4437                 }
4438               }
4439               // Unknown type. Conservatively assume no bits match sign bit.
4440               return 1;
4441             }
4442             return Tmp;
4443           }
4444         }
4445         break;
4446       }
4447     }
4448   }
4449 
4450   // Allow the target to implement this method for its nodes.
4451   if (Opcode >= ISD::BUILTIN_OP_END ||
4452       Opcode == ISD::INTRINSIC_WO_CHAIN ||
4453       Opcode == ISD::INTRINSIC_W_CHAIN ||
4454       Opcode == ISD::INTRINSIC_VOID) {
4455     unsigned NumBits =
4456         TLI->ComputeNumSignBitsForTargetNode(Op, DemandedElts, *this, Depth);
4457     if (NumBits > 1)
4458       FirstAnswer = std::max(FirstAnswer, NumBits);
4459   }
4460 
4461   // Finally, if we can prove that the top bits of the result are 0's or 1's,
4462   // use this information.
4463   KnownBits Known = computeKnownBits(Op, DemandedElts, Depth);
4464   return std::max(FirstAnswer, Known.countMinSignBits());
4465 }
4466 
4467 unsigned SelectionDAG::ComputeMaxSignificantBits(SDValue Op,
4468                                                  unsigned Depth) const {
4469   unsigned SignBits = ComputeNumSignBits(Op, Depth);
4470   return Op.getScalarValueSizeInBits() - SignBits + 1;
4471 }
4472 
4473 unsigned SelectionDAG::ComputeMaxSignificantBits(SDValue Op,
4474                                                  const APInt &DemandedElts,
4475                                                  unsigned Depth) const {
4476   unsigned SignBits = ComputeNumSignBits(Op, DemandedElts, Depth);
4477   return Op.getScalarValueSizeInBits() - SignBits + 1;
4478 }
4479 
4480 bool SelectionDAG::isGuaranteedNotToBeUndefOrPoison(SDValue Op, bool PoisonOnly,
4481                                                     unsigned Depth) const {
4482   // Early out for FREEZE.
4483   if (Op.getOpcode() == ISD::FREEZE)
4484     return true;
4485 
4486   // TODO: Assume we don't know anything for now.
4487   EVT VT = Op.getValueType();
4488   if (VT.isScalableVector())
4489     return false;
4490 
4491   APInt DemandedElts = VT.isVector()
4492                            ? APInt::getAllOnes(VT.getVectorNumElements())
4493                            : APInt(1, 1);
4494   return isGuaranteedNotToBeUndefOrPoison(Op, DemandedElts, PoisonOnly, Depth);
4495 }
4496 
4497 bool SelectionDAG::isGuaranteedNotToBeUndefOrPoison(SDValue Op,
4498                                                     const APInt &DemandedElts,
4499                                                     bool PoisonOnly,
4500                                                     unsigned Depth) const {
4501   unsigned Opcode = Op.getOpcode();
4502 
4503   // Early out for FREEZE.
4504   if (Opcode == ISD::FREEZE)
4505     return true;
4506 
4507   if (Depth >= MaxRecursionDepth)
4508     return false; // Limit search depth.
4509 
4510   if (isIntOrFPConstant(Op))
4511     return true;
4512 
4513   switch (Opcode) {
4514   case ISD::UNDEF:
4515     return PoisonOnly;
4516 
4517   case ISD::BUILD_VECTOR:
4518     // NOTE: BUILD_VECTOR has implicit truncation of wider scalar elements -
4519     // this shouldn't affect the result.
4520     for (unsigned i = 0, e = Op.getNumOperands(); i < e; ++i) {
4521       if (!DemandedElts[i])
4522         continue;
4523       if (!isGuaranteedNotToBeUndefOrPoison(Op.getOperand(i), PoisonOnly,
4524                                             Depth + 1))
4525         return false;
4526     }
4527     return true;
4528 
4529   // TODO: Search for noundef attributes from library functions.
4530 
4531   // TODO: Pointers dereferenced by ISD::LOAD/STORE ops are noundef.
4532 
4533   default:
4534     // Allow the target to implement this method for its nodes.
4535     if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::INTRINSIC_WO_CHAIN ||
4536         Opcode == ISD::INTRINSIC_W_CHAIN || Opcode == ISD::INTRINSIC_VOID)
4537       return TLI->isGuaranteedNotToBeUndefOrPoisonForTargetNode(
4538           Op, DemandedElts, *this, PoisonOnly, Depth);
4539     break;
4540   }
4541 
4542   return false;
4543 }
4544 
4545 bool SelectionDAG::isBaseWithConstantOffset(SDValue Op) const {
4546   if ((Op.getOpcode() != ISD::ADD && Op.getOpcode() != ISD::OR) ||
4547       !isa<ConstantSDNode>(Op.getOperand(1)))
4548     return false;
4549 
4550   if (Op.getOpcode() == ISD::OR &&
4551       !MaskedValueIsZero(Op.getOperand(0), Op.getConstantOperandAPInt(1)))
4552     return false;
4553 
4554   return true;
4555 }
4556 
4557 bool SelectionDAG::isKnownNeverNaN(SDValue Op, bool SNaN, unsigned Depth) const {
4558   // If we're told that NaNs won't happen, assume they won't.
4559   if (getTarget().Options.NoNaNsFPMath || Op->getFlags().hasNoNaNs())
4560     return true;
4561 
4562   if (Depth >= MaxRecursionDepth)
4563     return false; // Limit search depth.
4564 
4565   // TODO: Handle vectors.
4566   // If the value is a constant, we can obviously see if it is a NaN or not.
4567   if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) {
4568     return !C->getValueAPF().isNaN() ||
4569            (SNaN && !C->getValueAPF().isSignaling());
4570   }
4571 
4572   unsigned Opcode = Op.getOpcode();
4573   switch (Opcode) {
4574   case ISD::FADD:
4575   case ISD::FSUB:
4576   case ISD::FMUL:
4577   case ISD::FDIV:
4578   case ISD::FREM:
4579   case ISD::FSIN:
4580   case ISD::FCOS: {
4581     if (SNaN)
4582       return true;
4583     // TODO: Need isKnownNeverInfinity
4584     return false;
4585   }
4586   case ISD::FCANONICALIZE:
4587   case ISD::FEXP:
4588   case ISD::FEXP2:
4589   case ISD::FTRUNC:
4590   case ISD::FFLOOR:
4591   case ISD::FCEIL:
4592   case ISD::FROUND:
4593   case ISD::FROUNDEVEN:
4594   case ISD::FRINT:
4595   case ISD::FNEARBYINT: {
4596     if (SNaN)
4597       return true;
4598     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
4599   }
4600   case ISD::FABS:
4601   case ISD::FNEG:
4602   case ISD::FCOPYSIGN: {
4603     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
4604   }
4605   case ISD::SELECT:
4606     return isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1) &&
4607            isKnownNeverNaN(Op.getOperand(2), SNaN, Depth + 1);
4608   case ISD::FP_EXTEND:
4609   case ISD::FP_ROUND: {
4610     if (SNaN)
4611       return true;
4612     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
4613   }
4614   case ISD::SINT_TO_FP:
4615   case ISD::UINT_TO_FP:
4616     return true;
4617   case ISD::FMA:
4618   case ISD::FMAD: {
4619     if (SNaN)
4620       return true;
4621     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) &&
4622            isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1) &&
4623            isKnownNeverNaN(Op.getOperand(2), SNaN, Depth + 1);
4624   }
4625   case ISD::FSQRT: // Need is known positive
4626   case ISD::FLOG:
4627   case ISD::FLOG2:
4628   case ISD::FLOG10:
4629   case ISD::FPOWI:
4630   case ISD::FPOW: {
4631     if (SNaN)
4632       return true;
4633     // TODO: Refine on operand
4634     return false;
4635   }
4636   case ISD::FMINNUM:
4637   case ISD::FMAXNUM: {
4638     // Only one needs to be known not-nan, since it will be returned if the
4639     // other ends up being one.
4640     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) ||
4641            isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1);
4642   }
4643   case ISD::FMINNUM_IEEE:
4644   case ISD::FMAXNUM_IEEE: {
4645     if (SNaN)
4646       return true;
4647     // This can return a NaN if either operand is an sNaN, or if both operands
4648     // are NaN.
4649     return (isKnownNeverNaN(Op.getOperand(0), false, Depth + 1) &&
4650             isKnownNeverSNaN(Op.getOperand(1), Depth + 1)) ||
4651            (isKnownNeverNaN(Op.getOperand(1), false, Depth + 1) &&
4652             isKnownNeverSNaN(Op.getOperand(0), Depth + 1));
4653   }
4654   case ISD::FMINIMUM:
4655   case ISD::FMAXIMUM: {
4656     // TODO: Does this quiet or return the origina NaN as-is?
4657     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) &&
4658            isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1);
4659   }
4660   case ISD::EXTRACT_VECTOR_ELT: {
4661     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
4662   }
4663   default:
4664     if (Opcode >= ISD::BUILTIN_OP_END ||
4665         Opcode == ISD::INTRINSIC_WO_CHAIN ||
4666         Opcode == ISD::INTRINSIC_W_CHAIN ||
4667         Opcode == ISD::INTRINSIC_VOID) {
4668       return TLI->isKnownNeverNaNForTargetNode(Op, *this, SNaN, Depth);
4669     }
4670 
4671     return false;
4672   }
4673 }
4674 
4675 bool SelectionDAG::isKnownNeverZeroFloat(SDValue Op) const {
4676   assert(Op.getValueType().isFloatingPoint() &&
4677          "Floating point type expected");
4678 
4679   // If the value is a constant, we can obviously see if it is a zero or not.
4680   // TODO: Add BuildVector support.
4681   if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op))
4682     return !C->isZero();
4683   return false;
4684 }
4685 
4686 bool SelectionDAG::isKnownNeverZero(SDValue Op) const {
4687   assert(!Op.getValueType().isFloatingPoint() &&
4688          "Floating point types unsupported - use isKnownNeverZeroFloat");
4689 
4690   // If the value is a constant, we can obviously see if it is a zero or not.
4691   if (ISD::matchUnaryPredicate(Op,
4692                                [](ConstantSDNode *C) { return !C->isZero(); }))
4693     return true;
4694 
4695   // TODO: Recognize more cases here.
4696   switch (Op.getOpcode()) {
4697   default: break;
4698   case ISD::OR:
4699     if (isKnownNeverZero(Op.getOperand(1)) ||
4700         isKnownNeverZero(Op.getOperand(0)))
4701       return true;
4702     break;
4703   }
4704 
4705   return false;
4706 }
4707 
4708 bool SelectionDAG::isEqualTo(SDValue A, SDValue B) const {
4709   // Check the obvious case.
4710   if (A == B) return true;
4711 
4712   // For for negative and positive zero.
4713   if (const ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A))
4714     if (const ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B))
4715       if (CA->isZero() && CB->isZero()) return true;
4716 
4717   // Otherwise they may not be equal.
4718   return false;
4719 }
4720 
4721 // Only bits set in Mask must be negated, other bits may be arbitrary.
4722 SDValue llvm::getBitwiseNotOperand(SDValue V, SDValue Mask, bool AllowUndefs) {
4723   if (isBitwiseNot(V, AllowUndefs))
4724     return V.getOperand(0);
4725 
4726   // Handle any_extend (not (truncate X)) pattern, where Mask only sets
4727   // bits in the non-extended part.
4728   ConstantSDNode *MaskC = isConstOrConstSplat(Mask);
4729   if (!MaskC || V.getOpcode() != ISD::ANY_EXTEND)
4730     return SDValue();
4731   SDValue ExtArg = V.getOperand(0);
4732   if (ExtArg.getScalarValueSizeInBits() >=
4733           MaskC->getAPIntValue().getActiveBits() &&
4734       isBitwiseNot(ExtArg, AllowUndefs) &&
4735       ExtArg.getOperand(0).getOpcode() == ISD::TRUNCATE &&
4736       ExtArg.getOperand(0).getOperand(0).getValueType() == V.getValueType())
4737     return ExtArg.getOperand(0).getOperand(0);
4738   return SDValue();
4739 }
4740 
4741 static bool haveNoCommonBitsSetCommutative(SDValue A, SDValue B) {
4742   // Match masked merge pattern (X & ~M) op (Y & M)
4743   // Including degenerate case (X & ~M) op M
4744   auto MatchNoCommonBitsPattern = [&](SDValue Not, SDValue Mask,
4745                                       SDValue Other) {
4746     if (SDValue NotOperand =
4747             getBitwiseNotOperand(Not, Mask, /* AllowUndefs */ true)) {
4748       if (Other == NotOperand)
4749         return true;
4750       if (Other->getOpcode() == ISD::AND)
4751         return NotOperand == Other->getOperand(0) ||
4752                NotOperand == Other->getOperand(1);
4753     }
4754     return false;
4755   };
4756   if (A->getOpcode() == ISD::AND)
4757     return MatchNoCommonBitsPattern(A->getOperand(0), A->getOperand(1), B) ||
4758            MatchNoCommonBitsPattern(A->getOperand(1), A->getOperand(0), B);
4759   return false;
4760 }
4761 
4762 // FIXME: unify with llvm::haveNoCommonBitsSet.
4763 bool SelectionDAG::haveNoCommonBitsSet(SDValue A, SDValue B) const {
4764   assert(A.getValueType() == B.getValueType() &&
4765          "Values must have the same type");
4766   if (haveNoCommonBitsSetCommutative(A, B) ||
4767       haveNoCommonBitsSetCommutative(B, A))
4768     return true;
4769   return KnownBits::haveNoCommonBitsSet(computeKnownBits(A),
4770                                         computeKnownBits(B));
4771 }
4772 
4773 static SDValue FoldSTEP_VECTOR(const SDLoc &DL, EVT VT, SDValue Step,
4774                                SelectionDAG &DAG) {
4775   if (cast<ConstantSDNode>(Step)->isZero())
4776     return DAG.getConstant(0, DL, VT);
4777 
4778   return SDValue();
4779 }
4780 
4781 static SDValue FoldBUILD_VECTOR(const SDLoc &DL, EVT VT,
4782                                 ArrayRef<SDValue> Ops,
4783                                 SelectionDAG &DAG) {
4784   int NumOps = Ops.size();
4785   assert(NumOps != 0 && "Can't build an empty vector!");
4786   assert(!VT.isScalableVector() &&
4787          "BUILD_VECTOR cannot be used with scalable types");
4788   assert(VT.getVectorNumElements() == (unsigned)NumOps &&
4789          "Incorrect element count in BUILD_VECTOR!");
4790 
4791   // BUILD_VECTOR of UNDEFs is UNDEF.
4792   if (llvm::all_of(Ops, [](SDValue Op) { return Op.isUndef(); }))
4793     return DAG.getUNDEF(VT);
4794 
4795   // BUILD_VECTOR of seq extract/insert from the same vector + type is Identity.
4796   SDValue IdentitySrc;
4797   bool IsIdentity = true;
4798   for (int i = 0; i != NumOps; ++i) {
4799     if (Ops[i].getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
4800         Ops[i].getOperand(0).getValueType() != VT ||
4801         (IdentitySrc && Ops[i].getOperand(0) != IdentitySrc) ||
4802         !isa<ConstantSDNode>(Ops[i].getOperand(1)) ||
4803         cast<ConstantSDNode>(Ops[i].getOperand(1))->getAPIntValue() != i) {
4804       IsIdentity = false;
4805       break;
4806     }
4807     IdentitySrc = Ops[i].getOperand(0);
4808   }
4809   if (IsIdentity)
4810     return IdentitySrc;
4811 
4812   return SDValue();
4813 }
4814 
4815 /// Try to simplify vector concatenation to an input value, undef, or build
4816 /// vector.
4817 static SDValue foldCONCAT_VECTORS(const SDLoc &DL, EVT VT,
4818                                   ArrayRef<SDValue> Ops,
4819                                   SelectionDAG &DAG) {
4820   assert(!Ops.empty() && "Can't concatenate an empty list of vectors!");
4821   assert(llvm::all_of(Ops,
4822                       [Ops](SDValue Op) {
4823                         return Ops[0].getValueType() == Op.getValueType();
4824                       }) &&
4825          "Concatenation of vectors with inconsistent value types!");
4826   assert((Ops[0].getValueType().getVectorElementCount() * Ops.size()) ==
4827              VT.getVectorElementCount() &&
4828          "Incorrect element count in vector concatenation!");
4829 
4830   if (Ops.size() == 1)
4831     return Ops[0];
4832 
4833   // Concat of UNDEFs is UNDEF.
4834   if (llvm::all_of(Ops, [](SDValue Op) { return Op.isUndef(); }))
4835     return DAG.getUNDEF(VT);
4836 
4837   // Scan the operands and look for extract operations from a single source
4838   // that correspond to insertion at the same location via this concatenation:
4839   // concat (extract X, 0*subvec_elts), (extract X, 1*subvec_elts), ...
4840   SDValue IdentitySrc;
4841   bool IsIdentity = true;
4842   for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
4843     SDValue Op = Ops[i];
4844     unsigned IdentityIndex = i * Op.getValueType().getVectorMinNumElements();
4845     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
4846         Op.getOperand(0).getValueType() != VT ||
4847         (IdentitySrc && Op.getOperand(0) != IdentitySrc) ||
4848         Op.getConstantOperandVal(1) != IdentityIndex) {
4849       IsIdentity = false;
4850       break;
4851     }
4852     assert((!IdentitySrc || IdentitySrc == Op.getOperand(0)) &&
4853            "Unexpected identity source vector for concat of extracts");
4854     IdentitySrc = Op.getOperand(0);
4855   }
4856   if (IsIdentity) {
4857     assert(IdentitySrc && "Failed to set source vector of extracts");
4858     return IdentitySrc;
4859   }
4860 
4861   // The code below this point is only designed to work for fixed width
4862   // vectors, so we bail out for now.
4863   if (VT.isScalableVector())
4864     return SDValue();
4865 
4866   // A CONCAT_VECTOR with all UNDEF/BUILD_VECTOR operands can be
4867   // simplified to one big BUILD_VECTOR.
4868   // FIXME: Add support for SCALAR_TO_VECTOR as well.
4869   EVT SVT = VT.getScalarType();
4870   SmallVector<SDValue, 16> Elts;
4871   for (SDValue Op : Ops) {
4872     EVT OpVT = Op.getValueType();
4873     if (Op.isUndef())
4874       Elts.append(OpVT.getVectorNumElements(), DAG.getUNDEF(SVT));
4875     else if (Op.getOpcode() == ISD::BUILD_VECTOR)
4876       Elts.append(Op->op_begin(), Op->op_end());
4877     else
4878       return SDValue();
4879   }
4880 
4881   // BUILD_VECTOR requires all inputs to be of the same type, find the
4882   // maximum type and extend them all.
4883   for (SDValue Op : Elts)
4884     SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
4885 
4886   if (SVT.bitsGT(VT.getScalarType())) {
4887     for (SDValue &Op : Elts) {
4888       if (Op.isUndef())
4889         Op = DAG.getUNDEF(SVT);
4890       else
4891         Op = DAG.getTargetLoweringInfo().isZExtFree(Op.getValueType(), SVT)
4892                  ? DAG.getZExtOrTrunc(Op, DL, SVT)
4893                  : DAG.getSExtOrTrunc(Op, DL, SVT);
4894     }
4895   }
4896 
4897   SDValue V = DAG.getBuildVector(VT, DL, Elts);
4898   NewSDValueDbgMsg(V, "New node fold concat vectors: ", &DAG);
4899   return V;
4900 }
4901 
4902 /// Gets or creates the specified node.
4903 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT) {
4904   FoldingSetNodeID ID;
4905   AddNodeIDNode(ID, Opcode, getVTList(VT), None);
4906   void *IP = nullptr;
4907   if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
4908     return SDValue(E, 0);
4909 
4910   auto *N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(),
4911                               getVTList(VT));
4912   CSEMap.InsertNode(N, IP);
4913 
4914   InsertNode(N);
4915   SDValue V = SDValue(N, 0);
4916   NewSDValueDbgMsg(V, "Creating new node: ", this);
4917   return V;
4918 }
4919 
4920 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
4921                               SDValue Operand) {
4922   SDNodeFlags Flags;
4923   if (Inserter)
4924     Flags = Inserter->getFlags();
4925   return getNode(Opcode, DL, VT, Operand, Flags);
4926 }
4927 
4928 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
4929                               SDValue Operand, const SDNodeFlags Flags) {
4930   assert(Operand.getOpcode() != ISD::DELETED_NODE &&
4931          "Operand is DELETED_NODE!");
4932   // Constant fold unary operations with an integer constant operand. Even
4933   // opaque constant will be folded, because the folding of unary operations
4934   // doesn't create new constants with different values. Nevertheless, the
4935   // opaque flag is preserved during folding to prevent future folding with
4936   // other constants.
4937   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Operand)) {
4938     const APInt &Val = C->getAPIntValue();
4939     switch (Opcode) {
4940     default: break;
4941     case ISD::SIGN_EXTEND:
4942       return getConstant(Val.sextOrTrunc(VT.getSizeInBits()), DL, VT,
4943                          C->isTargetOpcode(), C->isOpaque());
4944     case ISD::TRUNCATE:
4945       if (C->isOpaque())
4946         break;
4947       LLVM_FALLTHROUGH;
4948     case ISD::ZERO_EXTEND:
4949       return getConstant(Val.zextOrTrunc(VT.getSizeInBits()), DL, VT,
4950                          C->isTargetOpcode(), C->isOpaque());
4951     case ISD::ANY_EXTEND:
4952       // Some targets like RISCV prefer to sign extend some types.
4953       if (TLI->isSExtCheaperThanZExt(Operand.getValueType(), VT))
4954         return getConstant(Val.sextOrTrunc(VT.getSizeInBits()), DL, VT,
4955                            C->isTargetOpcode(), C->isOpaque());
4956       return getConstant(Val.zextOrTrunc(VT.getSizeInBits()), DL, VT,
4957                          C->isTargetOpcode(), C->isOpaque());
4958     case ISD::UINT_TO_FP:
4959     case ISD::SINT_TO_FP: {
4960       APFloat apf(EVTToAPFloatSemantics(VT),
4961                   APInt::getZero(VT.getSizeInBits()));
4962       (void)apf.convertFromAPInt(Val,
4963                                  Opcode==ISD::SINT_TO_FP,
4964                                  APFloat::rmNearestTiesToEven);
4965       return getConstantFP(apf, DL, VT);
4966     }
4967     case ISD::BITCAST:
4968       if (VT == MVT::f16 && C->getValueType(0) == MVT::i16)
4969         return getConstantFP(APFloat(APFloat::IEEEhalf(), Val), DL, VT);
4970       if (VT == MVT::f32 && C->getValueType(0) == MVT::i32)
4971         return getConstantFP(APFloat(APFloat::IEEEsingle(), Val), DL, VT);
4972       if (VT == MVT::f64 && C->getValueType(0) == MVT::i64)
4973         return getConstantFP(APFloat(APFloat::IEEEdouble(), Val), DL, VT);
4974       if (VT == MVT::f128 && C->getValueType(0) == MVT::i128)
4975         return getConstantFP(APFloat(APFloat::IEEEquad(), Val), DL, VT);
4976       break;
4977     case ISD::ABS:
4978       return getConstant(Val.abs(), DL, VT, C->isTargetOpcode(),
4979                          C->isOpaque());
4980     case ISD::BITREVERSE:
4981       return getConstant(Val.reverseBits(), DL, VT, C->isTargetOpcode(),
4982                          C->isOpaque());
4983     case ISD::BSWAP:
4984       return getConstant(Val.byteSwap(), DL, VT, C->isTargetOpcode(),
4985                          C->isOpaque());
4986     case ISD::CTPOP:
4987       return getConstant(Val.countPopulation(), DL, VT, C->isTargetOpcode(),
4988                          C->isOpaque());
4989     case ISD::CTLZ:
4990     case ISD::CTLZ_ZERO_UNDEF:
4991       return getConstant(Val.countLeadingZeros(), DL, VT, C->isTargetOpcode(),
4992                          C->isOpaque());
4993     case ISD::CTTZ:
4994     case ISD::CTTZ_ZERO_UNDEF:
4995       return getConstant(Val.countTrailingZeros(), DL, VT, C->isTargetOpcode(),
4996                          C->isOpaque());
4997     case ISD::FP16_TO_FP:
4998     case ISD::BF16_TO_FP: {
4999       bool Ignored;
5000       APFloat FPV(Opcode == ISD::FP16_TO_FP ? APFloat::IEEEhalf()
5001                                             : APFloat::BFloat(),
5002                   (Val.getBitWidth() == 16) ? Val : Val.trunc(16));
5003 
5004       // This can return overflow, underflow, or inexact; we don't care.
5005       // FIXME need to be more flexible about rounding mode.
5006       (void)FPV.convert(EVTToAPFloatSemantics(VT),
5007                         APFloat::rmNearestTiesToEven, &Ignored);
5008       return getConstantFP(FPV, DL, VT);
5009     }
5010     case ISD::STEP_VECTOR: {
5011       if (SDValue V = FoldSTEP_VECTOR(DL, VT, Operand, *this))
5012         return V;
5013       break;
5014     }
5015     }
5016   }
5017 
5018   // Constant fold unary operations with a floating point constant operand.
5019   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Operand)) {
5020     APFloat V = C->getValueAPF();    // make copy
5021     switch (Opcode) {
5022     case ISD::FNEG:
5023       V.changeSign();
5024       return getConstantFP(V, DL, VT);
5025     case ISD::FABS:
5026       V.clearSign();
5027       return getConstantFP(V, DL, VT);
5028     case ISD::FCEIL: {
5029       APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardPositive);
5030       if (fs == APFloat::opOK || fs == APFloat::opInexact)
5031         return getConstantFP(V, DL, VT);
5032       break;
5033     }
5034     case ISD::FTRUNC: {
5035       APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardZero);
5036       if (fs == APFloat::opOK || fs == APFloat::opInexact)
5037         return getConstantFP(V, DL, VT);
5038       break;
5039     }
5040     case ISD::FFLOOR: {
5041       APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardNegative);
5042       if (fs == APFloat::opOK || fs == APFloat::opInexact)
5043         return getConstantFP(V, DL, VT);
5044       break;
5045     }
5046     case ISD::FP_EXTEND: {
5047       bool ignored;
5048       // This can return overflow, underflow, or inexact; we don't care.
5049       // FIXME need to be more flexible about rounding mode.
5050       (void)V.convert(EVTToAPFloatSemantics(VT),
5051                       APFloat::rmNearestTiesToEven, &ignored);
5052       return getConstantFP(V, DL, VT);
5053     }
5054     case ISD::FP_TO_SINT:
5055     case ISD::FP_TO_UINT: {
5056       bool ignored;
5057       APSInt IntVal(VT.getSizeInBits(), Opcode == ISD::FP_TO_UINT);
5058       // FIXME need to be more flexible about rounding mode.
5059       APFloat::opStatus s =
5060           V.convertToInteger(IntVal, APFloat::rmTowardZero, &ignored);
5061       if (s == APFloat::opInvalidOp) // inexact is OK, in fact usual
5062         break;
5063       return getConstant(IntVal, DL, VT);
5064     }
5065     case ISD::BITCAST:
5066       if (VT == MVT::i16 && C->getValueType(0) == MVT::f16)
5067         return getConstant((uint16_t)V.bitcastToAPInt().getZExtValue(), DL, VT);
5068       if (VT == MVT::i16 && C->getValueType(0) == MVT::bf16)
5069         return getConstant((uint16_t)V.bitcastToAPInt().getZExtValue(), DL, VT);
5070       if (VT == MVT::i32 && C->getValueType(0) == MVT::f32)
5071         return getConstant((uint32_t)V.bitcastToAPInt().getZExtValue(), DL, VT);
5072       if (VT == MVT::i64 && C->getValueType(0) == MVT::f64)
5073         return getConstant(V.bitcastToAPInt().getZExtValue(), DL, VT);
5074       break;
5075     case ISD::FP_TO_FP16:
5076     case ISD::FP_TO_BF16: {
5077       bool Ignored;
5078       // This can return overflow, underflow, or inexact; we don't care.
5079       // FIXME need to be more flexible about rounding mode.
5080       (void)V.convert(Opcode == ISD::FP_TO_FP16 ? APFloat::IEEEhalf()
5081                                                 : APFloat::BFloat(),
5082                       APFloat::rmNearestTiesToEven, &Ignored);
5083       return getConstant(V.bitcastToAPInt().getZExtValue(), DL, VT);
5084     }
5085     }
5086   }
5087 
5088   // Constant fold unary operations with a vector integer or float operand.
5089   switch (Opcode) {
5090   default:
5091     // FIXME: Entirely reasonable to perform folding of other unary
5092     // operations here as the need arises.
5093     break;
5094   case ISD::FNEG:
5095   case ISD::FABS:
5096   case ISD::FCEIL:
5097   case ISD::FTRUNC:
5098   case ISD::FFLOOR:
5099   case ISD::FP_EXTEND:
5100   case ISD::FP_TO_SINT:
5101   case ISD::FP_TO_UINT:
5102   case ISD::TRUNCATE:
5103   case ISD::ANY_EXTEND:
5104   case ISD::ZERO_EXTEND:
5105   case ISD::SIGN_EXTEND:
5106   case ISD::UINT_TO_FP:
5107   case ISD::SINT_TO_FP:
5108   case ISD::ABS:
5109   case ISD::BITREVERSE:
5110   case ISD::BSWAP:
5111   case ISD::CTLZ:
5112   case ISD::CTLZ_ZERO_UNDEF:
5113   case ISD::CTTZ:
5114   case ISD::CTTZ_ZERO_UNDEF:
5115   case ISD::CTPOP: {
5116     SDValue Ops = {Operand};
5117     if (SDValue Fold = FoldConstantArithmetic(Opcode, DL, VT, Ops))
5118       return Fold;
5119   }
5120   }
5121 
5122   unsigned OpOpcode = Operand.getNode()->getOpcode();
5123   switch (Opcode) {
5124   case ISD::STEP_VECTOR:
5125     assert(VT.isScalableVector() &&
5126            "STEP_VECTOR can only be used with scalable types");
5127     assert(OpOpcode == ISD::TargetConstant &&
5128            VT.getVectorElementType() == Operand.getValueType() &&
5129            "Unexpected step operand");
5130     break;
5131   case ISD::FREEZE:
5132     assert(VT == Operand.getValueType() && "Unexpected VT!");
5133     if (isGuaranteedNotToBeUndefOrPoison(Operand))
5134       return Operand;
5135     break;
5136   case ISD::TokenFactor:
5137   case ISD::MERGE_VALUES:
5138   case ISD::CONCAT_VECTORS:
5139     return Operand;         // Factor, merge or concat of one node?  No need.
5140   case ISD::BUILD_VECTOR: {
5141     // Attempt to simplify BUILD_VECTOR.
5142     SDValue Ops[] = {Operand};
5143     if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
5144       return V;
5145     break;
5146   }
5147   case ISD::FP_ROUND: llvm_unreachable("Invalid method to make FP_ROUND node");
5148   case ISD::FP_EXTEND:
5149     assert(VT.isFloatingPoint() &&
5150            Operand.getValueType().isFloatingPoint() && "Invalid FP cast!");
5151     if (Operand.getValueType() == VT) return Operand;  // noop conversion.
5152     assert((!VT.isVector() ||
5153             VT.getVectorElementCount() ==
5154             Operand.getValueType().getVectorElementCount()) &&
5155            "Vector element count mismatch!");
5156     assert(Operand.getValueType().bitsLT(VT) &&
5157            "Invalid fpext node, dst < src!");
5158     if (Operand.isUndef())
5159       return getUNDEF(VT);
5160     break;
5161   case ISD::FP_TO_SINT:
5162   case ISD::FP_TO_UINT:
5163     if (Operand.isUndef())
5164       return getUNDEF(VT);
5165     break;
5166   case ISD::SINT_TO_FP:
5167   case ISD::UINT_TO_FP:
5168     // [us]itofp(undef) = 0, because the result value is bounded.
5169     if (Operand.isUndef())
5170       return getConstantFP(0.0, DL, VT);
5171     break;
5172   case ISD::SIGN_EXTEND:
5173     assert(VT.isInteger() && Operand.getValueType().isInteger() &&
5174            "Invalid SIGN_EXTEND!");
5175     assert(VT.isVector() == Operand.getValueType().isVector() &&
5176            "SIGN_EXTEND result type type should be vector iff the operand "
5177            "type is vector!");
5178     if (Operand.getValueType() == VT) return Operand;   // noop extension
5179     assert((!VT.isVector() ||
5180             VT.getVectorElementCount() ==
5181                 Operand.getValueType().getVectorElementCount()) &&
5182            "Vector element count mismatch!");
5183     assert(Operand.getValueType().bitsLT(VT) &&
5184            "Invalid sext node, dst < src!");
5185     if (OpOpcode == ISD::SIGN_EXTEND || OpOpcode == ISD::ZERO_EXTEND)
5186       return getNode(OpOpcode, DL, VT, Operand.getOperand(0));
5187     if (OpOpcode == ISD::UNDEF)
5188       // sext(undef) = 0, because the top bits will all be the same.
5189       return getConstant(0, DL, VT);
5190     break;
5191   case ISD::ZERO_EXTEND:
5192     assert(VT.isInteger() && Operand.getValueType().isInteger() &&
5193            "Invalid ZERO_EXTEND!");
5194     assert(VT.isVector() == Operand.getValueType().isVector() &&
5195            "ZERO_EXTEND result type type should be vector iff the operand "
5196            "type is vector!");
5197     if (Operand.getValueType() == VT) return Operand;   // noop extension
5198     assert((!VT.isVector() ||
5199             VT.getVectorElementCount() ==
5200                 Operand.getValueType().getVectorElementCount()) &&
5201            "Vector element count mismatch!");
5202     assert(Operand.getValueType().bitsLT(VT) &&
5203            "Invalid zext node, dst < src!");
5204     if (OpOpcode == ISD::ZERO_EXTEND)   // (zext (zext x)) -> (zext x)
5205       return getNode(ISD::ZERO_EXTEND, DL, VT, Operand.getOperand(0));
5206     if (OpOpcode == ISD::UNDEF)
5207       // zext(undef) = 0, because the top bits will be zero.
5208       return getConstant(0, DL, VT);
5209     break;
5210   case ISD::ANY_EXTEND:
5211     assert(VT.isInteger() && Operand.getValueType().isInteger() &&
5212            "Invalid ANY_EXTEND!");
5213     assert(VT.isVector() == Operand.getValueType().isVector() &&
5214            "ANY_EXTEND result type type should be vector iff the operand "
5215            "type is vector!");
5216     if (Operand.getValueType() == VT) return Operand;   // noop extension
5217     assert((!VT.isVector() ||
5218             VT.getVectorElementCount() ==
5219                 Operand.getValueType().getVectorElementCount()) &&
5220            "Vector element count mismatch!");
5221     assert(Operand.getValueType().bitsLT(VT) &&
5222            "Invalid anyext node, dst < src!");
5223 
5224     if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
5225         OpOpcode == ISD::ANY_EXTEND)
5226       // (ext (zext x)) -> (zext x)  and  (ext (sext x)) -> (sext x)
5227       return getNode(OpOpcode, DL, VT, Operand.getOperand(0));
5228     if (OpOpcode == ISD::UNDEF)
5229       return getUNDEF(VT);
5230 
5231     // (ext (trunc x)) -> x
5232     if (OpOpcode == ISD::TRUNCATE) {
5233       SDValue OpOp = Operand.getOperand(0);
5234       if (OpOp.getValueType() == VT) {
5235         transferDbgValues(Operand, OpOp);
5236         return OpOp;
5237       }
5238     }
5239     break;
5240   case ISD::TRUNCATE:
5241     assert(VT.isInteger() && Operand.getValueType().isInteger() &&
5242            "Invalid TRUNCATE!");
5243     assert(VT.isVector() == Operand.getValueType().isVector() &&
5244            "TRUNCATE result type type should be vector iff the operand "
5245            "type is vector!");
5246     if (Operand.getValueType() == VT) return Operand;   // noop truncate
5247     assert((!VT.isVector() ||
5248             VT.getVectorElementCount() ==
5249                 Operand.getValueType().getVectorElementCount()) &&
5250            "Vector element count mismatch!");
5251     assert(Operand.getValueType().bitsGT(VT) &&
5252            "Invalid truncate node, src < dst!");
5253     if (OpOpcode == ISD::TRUNCATE)
5254       return getNode(ISD::TRUNCATE, DL, VT, Operand.getOperand(0));
5255     if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
5256         OpOpcode == ISD::ANY_EXTEND) {
5257       // If the source is smaller than the dest, we still need an extend.
5258       if (Operand.getOperand(0).getValueType().getScalarType()
5259             .bitsLT(VT.getScalarType()))
5260         return getNode(OpOpcode, DL, VT, Operand.getOperand(0));
5261       if (Operand.getOperand(0).getValueType().bitsGT(VT))
5262         return getNode(ISD::TRUNCATE, DL, VT, Operand.getOperand(0));
5263       return Operand.getOperand(0);
5264     }
5265     if (OpOpcode == ISD::UNDEF)
5266       return getUNDEF(VT);
5267     if (OpOpcode == ISD::VSCALE && !NewNodesMustHaveLegalTypes)
5268       return getVScale(DL, VT, Operand.getConstantOperandAPInt(0));
5269     break;
5270   case ISD::ANY_EXTEND_VECTOR_INREG:
5271   case ISD::ZERO_EXTEND_VECTOR_INREG:
5272   case ISD::SIGN_EXTEND_VECTOR_INREG:
5273     assert(VT.isVector() && "This DAG node is restricted to vector types.");
5274     assert(Operand.getValueType().bitsLE(VT) &&
5275            "The input must be the same size or smaller than the result.");
5276     assert(VT.getVectorMinNumElements() <
5277                Operand.getValueType().getVectorMinNumElements() &&
5278            "The destination vector type must have fewer lanes than the input.");
5279     break;
5280   case ISD::ABS:
5281     assert(VT.isInteger() && VT == Operand.getValueType() &&
5282            "Invalid ABS!");
5283     if (OpOpcode == ISD::UNDEF)
5284       return getConstant(0, DL, VT);
5285     break;
5286   case ISD::BSWAP:
5287     assert(VT.isInteger() && VT == Operand.getValueType() &&
5288            "Invalid BSWAP!");
5289     assert((VT.getScalarSizeInBits() % 16 == 0) &&
5290            "BSWAP types must be a multiple of 16 bits!");
5291     if (OpOpcode == ISD::UNDEF)
5292       return getUNDEF(VT);
5293     // bswap(bswap(X)) -> X.
5294     if (OpOpcode == ISD::BSWAP)
5295       return Operand.getOperand(0);
5296     break;
5297   case ISD::BITREVERSE:
5298     assert(VT.isInteger() && VT == Operand.getValueType() &&
5299            "Invalid BITREVERSE!");
5300     if (OpOpcode == ISD::UNDEF)
5301       return getUNDEF(VT);
5302     break;
5303   case ISD::BITCAST:
5304     assert(VT.getSizeInBits() == Operand.getValueSizeInBits() &&
5305            "Cannot BITCAST between types of different sizes!");
5306     if (VT == Operand.getValueType()) return Operand;  // noop conversion.
5307     if (OpOpcode == ISD::BITCAST)  // bitconv(bitconv(x)) -> bitconv(x)
5308       return getNode(ISD::BITCAST, DL, VT, Operand.getOperand(0));
5309     if (OpOpcode == ISD::UNDEF)
5310       return getUNDEF(VT);
5311     break;
5312   case ISD::SCALAR_TO_VECTOR:
5313     assert(VT.isVector() && !Operand.getValueType().isVector() &&
5314            (VT.getVectorElementType() == Operand.getValueType() ||
5315             (VT.getVectorElementType().isInteger() &&
5316              Operand.getValueType().isInteger() &&
5317              VT.getVectorElementType().bitsLE(Operand.getValueType()))) &&
5318            "Illegal SCALAR_TO_VECTOR node!");
5319     if (OpOpcode == ISD::UNDEF)
5320       return getUNDEF(VT);
5321     // scalar_to_vector(extract_vector_elt V, 0) -> V, top bits are undefined.
5322     if (OpOpcode == ISD::EXTRACT_VECTOR_ELT &&
5323         isa<ConstantSDNode>(Operand.getOperand(1)) &&
5324         Operand.getConstantOperandVal(1) == 0 &&
5325         Operand.getOperand(0).getValueType() == VT)
5326       return Operand.getOperand(0);
5327     break;
5328   case ISD::FNEG:
5329     // Negation of an unknown bag of bits is still completely undefined.
5330     if (OpOpcode == ISD::UNDEF)
5331       return getUNDEF(VT);
5332 
5333     if (OpOpcode == ISD::FNEG)  // --X -> X
5334       return Operand.getOperand(0);
5335     break;
5336   case ISD::FABS:
5337     if (OpOpcode == ISD::FNEG)  // abs(-X) -> abs(X)
5338       return getNode(ISD::FABS, DL, VT, Operand.getOperand(0));
5339     break;
5340   case ISD::VSCALE:
5341     assert(VT == Operand.getValueType() && "Unexpected VT!");
5342     break;
5343   case ISD::CTPOP:
5344     if (Operand.getValueType().getScalarType() == MVT::i1)
5345       return Operand;
5346     break;
5347   case ISD::CTLZ:
5348   case ISD::CTTZ:
5349     if (Operand.getValueType().getScalarType() == MVT::i1)
5350       return getNOT(DL, Operand, Operand.getValueType());
5351     break;
5352   case ISD::VECREDUCE_ADD:
5353     if (Operand.getValueType().getScalarType() == MVT::i1)
5354       return getNode(ISD::VECREDUCE_XOR, DL, VT, Operand);
5355     break;
5356   case ISD::VECREDUCE_SMIN:
5357   case ISD::VECREDUCE_UMAX:
5358     if (Operand.getValueType().getScalarType() == MVT::i1)
5359       return getNode(ISD::VECREDUCE_OR, DL, VT, Operand);
5360     break;
5361   case ISD::VECREDUCE_SMAX:
5362   case ISD::VECREDUCE_UMIN:
5363     if (Operand.getValueType().getScalarType() == MVT::i1)
5364       return getNode(ISD::VECREDUCE_AND, DL, VT, Operand);
5365     break;
5366   }
5367 
5368   SDNode *N;
5369   SDVTList VTs = getVTList(VT);
5370   SDValue Ops[] = {Operand};
5371   if (VT != MVT::Glue) { // Don't CSE flag producing nodes
5372     FoldingSetNodeID ID;
5373     AddNodeIDNode(ID, Opcode, VTs, Ops);
5374     void *IP = nullptr;
5375     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
5376       E->intersectFlagsWith(Flags);
5377       return SDValue(E, 0);
5378     }
5379 
5380     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
5381     N->setFlags(Flags);
5382     createOperands(N, Ops);
5383     CSEMap.InsertNode(N, IP);
5384   } else {
5385     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
5386     createOperands(N, Ops);
5387   }
5388 
5389   InsertNode(N);
5390   SDValue V = SDValue(N, 0);
5391   NewSDValueDbgMsg(V, "Creating new node: ", this);
5392   return V;
5393 }
5394 
5395 static llvm::Optional<APInt> FoldValue(unsigned Opcode, const APInt &C1,
5396                                        const APInt &C2) {
5397   switch (Opcode) {
5398   case ISD::ADD:  return C1 + C2;
5399   case ISD::SUB:  return C1 - C2;
5400   case ISD::MUL:  return C1 * C2;
5401   case ISD::AND:  return C1 & C2;
5402   case ISD::OR:   return C1 | C2;
5403   case ISD::XOR:  return C1 ^ C2;
5404   case ISD::SHL:  return C1 << C2;
5405   case ISD::SRL:  return C1.lshr(C2);
5406   case ISD::SRA:  return C1.ashr(C2);
5407   case ISD::ROTL: return C1.rotl(C2);
5408   case ISD::ROTR: return C1.rotr(C2);
5409   case ISD::SMIN: return C1.sle(C2) ? C1 : C2;
5410   case ISD::SMAX: return C1.sge(C2) ? C1 : C2;
5411   case ISD::UMIN: return C1.ule(C2) ? C1 : C2;
5412   case ISD::UMAX: return C1.uge(C2) ? C1 : C2;
5413   case ISD::SADDSAT: return C1.sadd_sat(C2);
5414   case ISD::UADDSAT: return C1.uadd_sat(C2);
5415   case ISD::SSUBSAT: return C1.ssub_sat(C2);
5416   case ISD::USUBSAT: return C1.usub_sat(C2);
5417   case ISD::SSHLSAT: return C1.sshl_sat(C2);
5418   case ISD::USHLSAT: return C1.ushl_sat(C2);
5419   case ISD::UDIV:
5420     if (!C2.getBoolValue())
5421       break;
5422     return C1.udiv(C2);
5423   case ISD::UREM:
5424     if (!C2.getBoolValue())
5425       break;
5426     return C1.urem(C2);
5427   case ISD::SDIV:
5428     if (!C2.getBoolValue())
5429       break;
5430     return C1.sdiv(C2);
5431   case ISD::SREM:
5432     if (!C2.getBoolValue())
5433       break;
5434     return C1.srem(C2);
5435   case ISD::MULHS: {
5436     unsigned FullWidth = C1.getBitWidth() * 2;
5437     APInt C1Ext = C1.sext(FullWidth);
5438     APInt C2Ext = C2.sext(FullWidth);
5439     return (C1Ext * C2Ext).extractBits(C1.getBitWidth(), C1.getBitWidth());
5440   }
5441   case ISD::MULHU: {
5442     unsigned FullWidth = C1.getBitWidth() * 2;
5443     APInt C1Ext = C1.zext(FullWidth);
5444     APInt C2Ext = C2.zext(FullWidth);
5445     return (C1Ext * C2Ext).extractBits(C1.getBitWidth(), C1.getBitWidth());
5446   }
5447   case ISD::AVGFLOORS: {
5448     unsigned FullWidth = C1.getBitWidth() + 1;
5449     APInt C1Ext = C1.sext(FullWidth);
5450     APInt C2Ext = C2.sext(FullWidth);
5451     return (C1Ext + C2Ext).extractBits(C1.getBitWidth(), 1);
5452   }
5453   case ISD::AVGFLOORU: {
5454     unsigned FullWidth = C1.getBitWidth() + 1;
5455     APInt C1Ext = C1.zext(FullWidth);
5456     APInt C2Ext = C2.zext(FullWidth);
5457     return (C1Ext + C2Ext).extractBits(C1.getBitWidth(), 1);
5458   }
5459   case ISD::AVGCEILS: {
5460     unsigned FullWidth = C1.getBitWidth() + 1;
5461     APInt C1Ext = C1.sext(FullWidth);
5462     APInt C2Ext = C2.sext(FullWidth);
5463     return (C1Ext + C2Ext + 1).extractBits(C1.getBitWidth(), 1);
5464   }
5465   case ISD::AVGCEILU: {
5466     unsigned FullWidth = C1.getBitWidth() + 1;
5467     APInt C1Ext = C1.zext(FullWidth);
5468     APInt C2Ext = C2.zext(FullWidth);
5469     return (C1Ext + C2Ext + 1).extractBits(C1.getBitWidth(), 1);
5470   }
5471   }
5472   return llvm::None;
5473 }
5474 
5475 SDValue SelectionDAG::FoldSymbolOffset(unsigned Opcode, EVT VT,
5476                                        const GlobalAddressSDNode *GA,
5477                                        const SDNode *N2) {
5478   if (GA->getOpcode() != ISD::GlobalAddress)
5479     return SDValue();
5480   if (!TLI->isOffsetFoldingLegal(GA))
5481     return SDValue();
5482   auto *C2 = dyn_cast<ConstantSDNode>(N2);
5483   if (!C2)
5484     return SDValue();
5485   int64_t Offset = C2->getSExtValue();
5486   switch (Opcode) {
5487   case ISD::ADD: break;
5488   case ISD::SUB: Offset = -uint64_t(Offset); break;
5489   default: return SDValue();
5490   }
5491   return getGlobalAddress(GA->getGlobal(), SDLoc(C2), VT,
5492                           GA->getOffset() + uint64_t(Offset));
5493 }
5494 
5495 bool SelectionDAG::isUndef(unsigned Opcode, ArrayRef<SDValue> Ops) {
5496   switch (Opcode) {
5497   case ISD::SDIV:
5498   case ISD::UDIV:
5499   case ISD::SREM:
5500   case ISD::UREM: {
5501     // If a divisor is zero/undef or any element of a divisor vector is
5502     // zero/undef, the whole op is undef.
5503     assert(Ops.size() == 2 && "Div/rem should have 2 operands");
5504     SDValue Divisor = Ops[1];
5505     if (Divisor.isUndef() || isNullConstant(Divisor))
5506       return true;
5507 
5508     return ISD::isBuildVectorOfConstantSDNodes(Divisor.getNode()) &&
5509            llvm::any_of(Divisor->op_values(),
5510                         [](SDValue V) { return V.isUndef() ||
5511                                         isNullConstant(V); });
5512     // TODO: Handle signed overflow.
5513   }
5514   // TODO: Handle oversized shifts.
5515   default:
5516     return false;
5517   }
5518 }
5519 
5520 SDValue SelectionDAG::FoldConstantArithmetic(unsigned Opcode, const SDLoc &DL,
5521                                              EVT VT, ArrayRef<SDValue> Ops) {
5522   // If the opcode is a target-specific ISD node, there's nothing we can
5523   // do here and the operand rules may not line up with the below, so
5524   // bail early.
5525   // We can't create a scalar CONCAT_VECTORS so skip it. It will break
5526   // for concats involving SPLAT_VECTOR. Concats of BUILD_VECTORS are handled by
5527   // foldCONCAT_VECTORS in getNode before this is called.
5528   if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::CONCAT_VECTORS)
5529     return SDValue();
5530 
5531   unsigned NumOps = Ops.size();
5532   if (NumOps == 0)
5533     return SDValue();
5534 
5535   if (isUndef(Opcode, Ops))
5536     return getUNDEF(VT);
5537 
5538   // Handle binops special cases.
5539   if (NumOps == 2) {
5540     if (SDValue CFP = foldConstantFPMath(Opcode, DL, VT, Ops[0], Ops[1]))
5541       return CFP;
5542 
5543     if (auto *C1 = dyn_cast<ConstantSDNode>(Ops[0])) {
5544       if (auto *C2 = dyn_cast<ConstantSDNode>(Ops[1])) {
5545         if (C1->isOpaque() || C2->isOpaque())
5546           return SDValue();
5547 
5548         Optional<APInt> FoldAttempt =
5549             FoldValue(Opcode, C1->getAPIntValue(), C2->getAPIntValue());
5550         if (!FoldAttempt)
5551           return SDValue();
5552 
5553         SDValue Folded = getConstant(*FoldAttempt, DL, VT);
5554         assert((!Folded || !VT.isVector()) &&
5555                "Can't fold vectors ops with scalar operands");
5556         return Folded;
5557       }
5558     }
5559 
5560     // fold (add Sym, c) -> Sym+c
5561     if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Ops[0]))
5562       return FoldSymbolOffset(Opcode, VT, GA, Ops[1].getNode());
5563     if (TLI->isCommutativeBinOp(Opcode))
5564       if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Ops[1]))
5565         return FoldSymbolOffset(Opcode, VT, GA, Ops[0].getNode());
5566   }
5567 
5568   // This is for vector folding only from here on.
5569   if (!VT.isVector())
5570     return SDValue();
5571 
5572   ElementCount NumElts = VT.getVectorElementCount();
5573 
5574   // See if we can fold through bitcasted integer ops.
5575   // TODO: Can we handle undef elements?
5576   if (NumOps == 2 && VT.isFixedLengthVector() && VT.isInteger() &&
5577       Ops[0].getValueType() == VT && Ops[1].getValueType() == VT &&
5578       Ops[0].getOpcode() == ISD::BITCAST &&
5579       Ops[1].getOpcode() == ISD::BITCAST) {
5580     SDValue N1 = peekThroughBitcasts(Ops[0]);
5581     SDValue N2 = peekThroughBitcasts(Ops[1]);
5582     auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
5583     auto *BV2 = dyn_cast<BuildVectorSDNode>(N2);
5584     EVT BVVT = N1.getValueType();
5585     if (BV1 && BV2 && BVVT.isInteger() && BVVT == N2.getValueType()) {
5586       bool IsLE = getDataLayout().isLittleEndian();
5587       unsigned EltBits = VT.getScalarSizeInBits();
5588       SmallVector<APInt> RawBits1, RawBits2;
5589       BitVector UndefElts1, UndefElts2;
5590       if (BV1->getConstantRawBits(IsLE, EltBits, RawBits1, UndefElts1) &&
5591           BV2->getConstantRawBits(IsLE, EltBits, RawBits2, UndefElts2) &&
5592           UndefElts1.none() && UndefElts2.none()) {
5593         SmallVector<APInt> RawBits;
5594         for (unsigned I = 0, E = NumElts.getFixedValue(); I != E; ++I) {
5595           Optional<APInt> Fold = FoldValue(Opcode, RawBits1[I], RawBits2[I]);
5596           if (!Fold)
5597             break;
5598           RawBits.push_back(*Fold);
5599         }
5600         if (RawBits.size() == NumElts.getFixedValue()) {
5601           // We have constant folded, but we need to cast this again back to
5602           // the original (possibly legalized) type.
5603           SmallVector<APInt> DstBits;
5604           BitVector DstUndefs;
5605           BuildVectorSDNode::recastRawBits(IsLE, BVVT.getScalarSizeInBits(),
5606                                            DstBits, RawBits, DstUndefs,
5607                                            BitVector(RawBits.size(), false));
5608           EVT BVEltVT = BV1->getOperand(0).getValueType();
5609           unsigned BVEltBits = BVEltVT.getSizeInBits();
5610           SmallVector<SDValue> Ops(DstBits.size(), getUNDEF(BVEltVT));
5611           for (unsigned I = 0, E = DstBits.size(); I != E; ++I) {
5612             if (DstUndefs[I])
5613               continue;
5614             Ops[I] = getConstant(DstBits[I].sext(BVEltBits), DL, BVEltVT);
5615           }
5616           return getBitcast(VT, getBuildVector(BVVT, DL, Ops));
5617         }
5618       }
5619     }
5620   }
5621 
5622   // Fold (mul step_vector(C0), C1) to (step_vector(C0 * C1)).
5623   //      (shl step_vector(C0), C1) -> (step_vector(C0 << C1))
5624   if ((Opcode == ISD::MUL || Opcode == ISD::SHL) &&
5625       Ops[0].getOpcode() == ISD::STEP_VECTOR) {
5626     APInt RHSVal;
5627     if (ISD::isConstantSplatVector(Ops[1].getNode(), RHSVal)) {
5628       APInt NewStep = Opcode == ISD::MUL
5629                           ? Ops[0].getConstantOperandAPInt(0) * RHSVal
5630                           : Ops[0].getConstantOperandAPInt(0) << RHSVal;
5631       return getStepVector(DL, VT, NewStep);
5632     }
5633   }
5634 
5635   auto IsScalarOrSameVectorSize = [NumElts](const SDValue &Op) {
5636     return !Op.getValueType().isVector() ||
5637            Op.getValueType().getVectorElementCount() == NumElts;
5638   };
5639 
5640   auto IsBuildVectorSplatVectorOrUndef = [](const SDValue &Op) {
5641     return Op.isUndef() || Op.getOpcode() == ISD::CONDCODE ||
5642            Op.getOpcode() == ISD::BUILD_VECTOR ||
5643            Op.getOpcode() == ISD::SPLAT_VECTOR;
5644   };
5645 
5646   // All operands must be vector types with the same number of elements as
5647   // the result type and must be either UNDEF or a build/splat vector
5648   // or UNDEF scalars.
5649   if (!llvm::all_of(Ops, IsBuildVectorSplatVectorOrUndef) ||
5650       !llvm::all_of(Ops, IsScalarOrSameVectorSize))
5651     return SDValue();
5652 
5653   // If we are comparing vectors, then the result needs to be a i1 boolean that
5654   // is then extended back to the legal result type depending on how booleans
5655   // are represented.
5656   EVT SVT = (Opcode == ISD::SETCC ? MVT::i1 : VT.getScalarType());
5657   ISD::NodeType ExtendCode =
5658       (Opcode == ISD::SETCC && SVT != VT.getScalarType())
5659           ? TargetLowering::getExtendForContent(TLI->getBooleanContents(VT))
5660           : ISD::SIGN_EXTEND;
5661 
5662   // Find legal integer scalar type for constant promotion and
5663   // ensure that its scalar size is at least as large as source.
5664   EVT LegalSVT = VT.getScalarType();
5665   if (NewNodesMustHaveLegalTypes && LegalSVT.isInteger()) {
5666     LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT);
5667     if (LegalSVT.bitsLT(VT.getScalarType()))
5668       return SDValue();
5669   }
5670 
5671   // For scalable vector types we know we're dealing with SPLAT_VECTORs. We
5672   // only have one operand to check. For fixed-length vector types we may have
5673   // a combination of BUILD_VECTOR and SPLAT_VECTOR.
5674   unsigned NumVectorElts = NumElts.isScalable() ? 1 : NumElts.getFixedValue();
5675 
5676   // Constant fold each scalar lane separately.
5677   SmallVector<SDValue, 4> ScalarResults;
5678   for (unsigned I = 0; I != NumVectorElts; I++) {
5679     SmallVector<SDValue, 4> ScalarOps;
5680     for (SDValue Op : Ops) {
5681       EVT InSVT = Op.getValueType().getScalarType();
5682       if (Op.getOpcode() != ISD::BUILD_VECTOR &&
5683           Op.getOpcode() != ISD::SPLAT_VECTOR) {
5684         if (Op.isUndef())
5685           ScalarOps.push_back(getUNDEF(InSVT));
5686         else
5687           ScalarOps.push_back(Op);
5688         continue;
5689       }
5690 
5691       SDValue ScalarOp =
5692           Op.getOperand(Op.getOpcode() == ISD::SPLAT_VECTOR ? 0 : I);
5693       EVT ScalarVT = ScalarOp.getValueType();
5694 
5695       // Build vector (integer) scalar operands may need implicit
5696       // truncation - do this before constant folding.
5697       if (ScalarVT.isInteger() && ScalarVT.bitsGT(InSVT)) {
5698         // Don't create illegally-typed nodes unless they're constants or undef
5699         // - if we fail to constant fold we can't guarantee the (dead) nodes
5700         // we're creating will be cleaned up before being visited for
5701         // legalization.
5702         if (NewNodesMustHaveLegalTypes && !ScalarOp.isUndef() &&
5703             !isa<ConstantSDNode>(ScalarOp) &&
5704             TLI->getTypeAction(*getContext(), InSVT) !=
5705                 TargetLowering::TypeLegal)
5706           return SDValue();
5707         ScalarOp = getNode(ISD::TRUNCATE, DL, InSVT, ScalarOp);
5708       }
5709 
5710       ScalarOps.push_back(ScalarOp);
5711     }
5712 
5713     // Constant fold the scalar operands.
5714     SDValue ScalarResult = getNode(Opcode, DL, SVT, ScalarOps);
5715 
5716     // Legalize the (integer) scalar constant if necessary.
5717     if (LegalSVT != SVT)
5718       ScalarResult = getNode(ExtendCode, DL, LegalSVT, ScalarResult);
5719 
5720     // Scalar folding only succeeded if the result is a constant or UNDEF.
5721     if (!ScalarResult.isUndef() && ScalarResult.getOpcode() != ISD::Constant &&
5722         ScalarResult.getOpcode() != ISD::ConstantFP)
5723       return SDValue();
5724     ScalarResults.push_back(ScalarResult);
5725   }
5726 
5727   SDValue V = NumElts.isScalable() ? getSplatVector(VT, DL, ScalarResults[0])
5728                                    : getBuildVector(VT, DL, ScalarResults);
5729   NewSDValueDbgMsg(V, "New node fold constant vector: ", this);
5730   return V;
5731 }
5732 
5733 SDValue SelectionDAG::foldConstantFPMath(unsigned Opcode, const SDLoc &DL,
5734                                          EVT VT, SDValue N1, SDValue N2) {
5735   // TODO: We don't do any constant folding for strict FP opcodes here, but we
5736   //       should. That will require dealing with a potentially non-default
5737   //       rounding mode, checking the "opStatus" return value from the APFloat
5738   //       math calculations, and possibly other variations.
5739   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1, /*AllowUndefs*/ false);
5740   ConstantFPSDNode *N2CFP = isConstOrConstSplatFP(N2, /*AllowUndefs*/ false);
5741   if (N1CFP && N2CFP) {
5742     APFloat C1 = N1CFP->getValueAPF(); // make copy
5743     const APFloat &C2 = N2CFP->getValueAPF();
5744     switch (Opcode) {
5745     case ISD::FADD:
5746       C1.add(C2, APFloat::rmNearestTiesToEven);
5747       return getConstantFP(C1, DL, VT);
5748     case ISD::FSUB:
5749       C1.subtract(C2, APFloat::rmNearestTiesToEven);
5750       return getConstantFP(C1, DL, VT);
5751     case ISD::FMUL:
5752       C1.multiply(C2, APFloat::rmNearestTiesToEven);
5753       return getConstantFP(C1, DL, VT);
5754     case ISD::FDIV:
5755       C1.divide(C2, APFloat::rmNearestTiesToEven);
5756       return getConstantFP(C1, DL, VT);
5757     case ISD::FREM:
5758       C1.mod(C2);
5759       return getConstantFP(C1, DL, VT);
5760     case ISD::FCOPYSIGN:
5761       C1.copySign(C2);
5762       return getConstantFP(C1, DL, VT);
5763     case ISD::FMINNUM:
5764       return getConstantFP(minnum(C1, C2), DL, VT);
5765     case ISD::FMAXNUM:
5766       return getConstantFP(maxnum(C1, C2), DL, VT);
5767     case ISD::FMINIMUM:
5768       return getConstantFP(minimum(C1, C2), DL, VT);
5769     case ISD::FMAXIMUM:
5770       return getConstantFP(maximum(C1, C2), DL, VT);
5771     default: break;
5772     }
5773   }
5774   if (N1CFP && Opcode == ISD::FP_ROUND) {
5775     APFloat C1 = N1CFP->getValueAPF();    // make copy
5776     bool Unused;
5777     // This can return overflow, underflow, or inexact; we don't care.
5778     // FIXME need to be more flexible about rounding mode.
5779     (void) C1.convert(EVTToAPFloatSemantics(VT), APFloat::rmNearestTiesToEven,
5780                       &Unused);
5781     return getConstantFP(C1, DL, VT);
5782   }
5783 
5784   switch (Opcode) {
5785   case ISD::FSUB:
5786     // -0.0 - undef --> undef (consistent with "fneg undef")
5787     if (ConstantFPSDNode *N1C = isConstOrConstSplatFP(N1, /*AllowUndefs*/ true))
5788       if (N1C && N1C->getValueAPF().isNegZero() && N2.isUndef())
5789         return getUNDEF(VT);
5790     LLVM_FALLTHROUGH;
5791 
5792   case ISD::FADD:
5793   case ISD::FMUL:
5794   case ISD::FDIV:
5795   case ISD::FREM:
5796     // If both operands are undef, the result is undef. If 1 operand is undef,
5797     // the result is NaN. This should match the behavior of the IR optimizer.
5798     if (N1.isUndef() && N2.isUndef())
5799       return getUNDEF(VT);
5800     if (N1.isUndef() || N2.isUndef())
5801       return getConstantFP(APFloat::getNaN(EVTToAPFloatSemantics(VT)), DL, VT);
5802   }
5803   return SDValue();
5804 }
5805 
5806 SDValue SelectionDAG::getAssertAlign(const SDLoc &DL, SDValue Val, Align A) {
5807   assert(Val.getValueType().isInteger() && "Invalid AssertAlign!");
5808 
5809   // There's no need to assert on a byte-aligned pointer. All pointers are at
5810   // least byte aligned.
5811   if (A == Align(1))
5812     return Val;
5813 
5814   FoldingSetNodeID ID;
5815   AddNodeIDNode(ID, ISD::AssertAlign, getVTList(Val.getValueType()), {Val});
5816   ID.AddInteger(A.value());
5817 
5818   void *IP = nullptr;
5819   if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
5820     return SDValue(E, 0);
5821 
5822   auto *N = newSDNode<AssertAlignSDNode>(DL.getIROrder(), DL.getDebugLoc(),
5823                                          Val.getValueType(), A);
5824   createOperands(N, {Val});
5825 
5826   CSEMap.InsertNode(N, IP);
5827   InsertNode(N);
5828 
5829   SDValue V(N, 0);
5830   NewSDValueDbgMsg(V, "Creating new node: ", this);
5831   return V;
5832 }
5833 
5834 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
5835                               SDValue N1, SDValue N2) {
5836   SDNodeFlags Flags;
5837   if (Inserter)
5838     Flags = Inserter->getFlags();
5839   return getNode(Opcode, DL, VT, N1, N2, Flags);
5840 }
5841 
5842 void SelectionDAG::canonicalizeCommutativeBinop(unsigned Opcode, SDValue &N1,
5843                                                 SDValue &N2) const {
5844   if (!TLI->isCommutativeBinOp(Opcode))
5845     return;
5846 
5847   // Canonicalize:
5848   //   binop(const, nonconst) -> binop(nonconst, const)
5849   bool IsN1C = isConstantIntBuildVectorOrConstantInt(N1);
5850   bool IsN2C = isConstantIntBuildVectorOrConstantInt(N2);
5851   bool IsN1CFP = isConstantFPBuildVectorOrConstantFP(N1);
5852   bool IsN2CFP = isConstantFPBuildVectorOrConstantFP(N2);
5853   if ((IsN1C && !IsN2C) || (IsN1CFP && !IsN2CFP))
5854     std::swap(N1, N2);
5855 
5856   // Canonicalize:
5857   //  binop(splat(x), step_vector) -> binop(step_vector, splat(x))
5858   else if (N1.getOpcode() == ISD::SPLAT_VECTOR &&
5859            N2.getOpcode() == ISD::STEP_VECTOR)
5860     std::swap(N1, N2);
5861 }
5862 
5863 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
5864                               SDValue N1, SDValue N2, const SDNodeFlags Flags) {
5865   assert(N1.getOpcode() != ISD::DELETED_NODE &&
5866          N2.getOpcode() != ISD::DELETED_NODE &&
5867          "Operand is DELETED_NODE!");
5868 
5869   canonicalizeCommutativeBinop(Opcode, N1, N2);
5870 
5871   auto *N1C = dyn_cast<ConstantSDNode>(N1);
5872   auto *N2C = dyn_cast<ConstantSDNode>(N2);
5873 
5874   // Don't allow undefs in vector splats - we might be returning N2 when folding
5875   // to zero etc.
5876   ConstantSDNode *N2CV =
5877       isConstOrConstSplat(N2, /*AllowUndefs*/ false, /*AllowTruncation*/ true);
5878 
5879   switch (Opcode) {
5880   default: break;
5881   case ISD::TokenFactor:
5882     assert(VT == MVT::Other && N1.getValueType() == MVT::Other &&
5883            N2.getValueType() == MVT::Other && "Invalid token factor!");
5884     // Fold trivial token factors.
5885     if (N1.getOpcode() == ISD::EntryToken) return N2;
5886     if (N2.getOpcode() == ISD::EntryToken) return N1;
5887     if (N1 == N2) return N1;
5888     break;
5889   case ISD::BUILD_VECTOR: {
5890     // Attempt to simplify BUILD_VECTOR.
5891     SDValue Ops[] = {N1, N2};
5892     if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
5893       return V;
5894     break;
5895   }
5896   case ISD::CONCAT_VECTORS: {
5897     SDValue Ops[] = {N1, N2};
5898     if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this))
5899       return V;
5900     break;
5901   }
5902   case ISD::AND:
5903     assert(VT.isInteger() && "This operator does not apply to FP types!");
5904     assert(N1.getValueType() == N2.getValueType() &&
5905            N1.getValueType() == VT && "Binary operator types must match!");
5906     // (X & 0) -> 0.  This commonly occurs when legalizing i64 values, so it's
5907     // worth handling here.
5908     if (N2CV && N2CV->isZero())
5909       return N2;
5910     if (N2CV && N2CV->isAllOnes()) // X & -1 -> X
5911       return N1;
5912     break;
5913   case ISD::OR:
5914   case ISD::XOR:
5915   case ISD::ADD:
5916   case ISD::SUB:
5917     assert(VT.isInteger() && "This operator does not apply to FP types!");
5918     assert(N1.getValueType() == N2.getValueType() &&
5919            N1.getValueType() == VT && "Binary operator types must match!");
5920     // (X ^|+- 0) -> X.  This commonly occurs when legalizing i64 values, so
5921     // it's worth handling here.
5922     if (N2CV && N2CV->isZero())
5923       return N1;
5924     if ((Opcode == ISD::ADD || Opcode == ISD::SUB) && VT.isVector() &&
5925         VT.getVectorElementType() == MVT::i1)
5926       return getNode(ISD::XOR, DL, VT, N1, N2);
5927     break;
5928   case ISD::MUL:
5929     assert(VT.isInteger() && "This operator does not apply to FP types!");
5930     assert(N1.getValueType() == N2.getValueType() &&
5931            N1.getValueType() == VT && "Binary operator types must match!");
5932     if (VT.isVector() && VT.getVectorElementType() == MVT::i1)
5933       return getNode(ISD::AND, DL, VT, N1, N2);
5934     if (N2C && (N1.getOpcode() == ISD::VSCALE) && Flags.hasNoSignedWrap()) {
5935       const APInt &MulImm = N1->getConstantOperandAPInt(0);
5936       const APInt &N2CImm = N2C->getAPIntValue();
5937       return getVScale(DL, VT, MulImm * N2CImm);
5938     }
5939     break;
5940   case ISD::UDIV:
5941   case ISD::UREM:
5942   case ISD::MULHU:
5943   case ISD::MULHS:
5944   case ISD::SDIV:
5945   case ISD::SREM:
5946   case ISD::SADDSAT:
5947   case ISD::SSUBSAT:
5948   case ISD::UADDSAT:
5949   case ISD::USUBSAT:
5950     assert(VT.isInteger() && "This operator does not apply to FP types!");
5951     assert(N1.getValueType() == N2.getValueType() &&
5952            N1.getValueType() == VT && "Binary operator types must match!");
5953     if (VT.isVector() && VT.getVectorElementType() == MVT::i1) {
5954       // fold (add_sat x, y) -> (or x, y) for bool types.
5955       if (Opcode == ISD::SADDSAT || Opcode == ISD::UADDSAT)
5956         return getNode(ISD::OR, DL, VT, N1, N2);
5957       // fold (sub_sat x, y) -> (and x, ~y) for bool types.
5958       if (Opcode == ISD::SSUBSAT || Opcode == ISD::USUBSAT)
5959         return getNode(ISD::AND, DL, VT, N1, getNOT(DL, N2, VT));
5960     }
5961     break;
5962   case ISD::SMIN:
5963   case ISD::UMAX:
5964     assert(VT.isInteger() && "This operator does not apply to FP types!");
5965     assert(N1.getValueType() == N2.getValueType() &&
5966            N1.getValueType() == VT && "Binary operator types must match!");
5967     if (VT.isVector() && VT.getVectorElementType() == MVT::i1)
5968       return getNode(ISD::OR, DL, VT, N1, N2);
5969     break;
5970   case ISD::SMAX:
5971   case ISD::UMIN:
5972     assert(VT.isInteger() && "This operator does not apply to FP types!");
5973     assert(N1.getValueType() == N2.getValueType() &&
5974            N1.getValueType() == VT && "Binary operator types must match!");
5975     if (VT.isVector() && VT.getVectorElementType() == MVT::i1)
5976       return getNode(ISD::AND, DL, VT, N1, N2);
5977     break;
5978   case ISD::FADD:
5979   case ISD::FSUB:
5980   case ISD::FMUL:
5981   case ISD::FDIV:
5982   case ISD::FREM:
5983     assert(VT.isFloatingPoint() && "This operator only applies to FP types!");
5984     assert(N1.getValueType() == N2.getValueType() &&
5985            N1.getValueType() == VT && "Binary operator types must match!");
5986     if (SDValue V = simplifyFPBinop(Opcode, N1, N2, Flags))
5987       return V;
5988     break;
5989   case ISD::FCOPYSIGN:   // N1 and result must match.  N1/N2 need not match.
5990     assert(N1.getValueType() == VT &&
5991            N1.getValueType().isFloatingPoint() &&
5992            N2.getValueType().isFloatingPoint() &&
5993            "Invalid FCOPYSIGN!");
5994     break;
5995   case ISD::SHL:
5996     if (N2C && (N1.getOpcode() == ISD::VSCALE) && Flags.hasNoSignedWrap()) {
5997       const APInt &MulImm = N1->getConstantOperandAPInt(0);
5998       const APInt &ShiftImm = N2C->getAPIntValue();
5999       return getVScale(DL, VT, MulImm << ShiftImm);
6000     }
6001     LLVM_FALLTHROUGH;
6002   case ISD::SRA:
6003   case ISD::SRL:
6004     if (SDValue V = simplifyShift(N1, N2))
6005       return V;
6006     LLVM_FALLTHROUGH;
6007   case ISD::ROTL:
6008   case ISD::ROTR:
6009     assert(VT == N1.getValueType() &&
6010            "Shift operators return type must be the same as their first arg");
6011     assert(VT.isInteger() && N2.getValueType().isInteger() &&
6012            "Shifts only work on integers");
6013     assert((!VT.isVector() || VT == N2.getValueType()) &&
6014            "Vector shift amounts must be in the same as their first arg");
6015     // Verify that the shift amount VT is big enough to hold valid shift
6016     // amounts.  This catches things like trying to shift an i1024 value by an
6017     // i8, which is easy to fall into in generic code that uses
6018     // TLI.getShiftAmount().
6019     assert(N2.getValueType().getScalarSizeInBits() >=
6020                Log2_32_Ceil(VT.getScalarSizeInBits()) &&
6021            "Invalid use of small shift amount with oversized value!");
6022 
6023     // Always fold shifts of i1 values so the code generator doesn't need to
6024     // handle them.  Since we know the size of the shift has to be less than the
6025     // size of the value, the shift/rotate count is guaranteed to be zero.
6026     if (VT == MVT::i1)
6027       return N1;
6028     if (N2CV && N2CV->isZero())
6029       return N1;
6030     break;
6031   case ISD::FP_ROUND:
6032     assert(VT.isFloatingPoint() &&
6033            N1.getValueType().isFloatingPoint() &&
6034            VT.bitsLE(N1.getValueType()) &&
6035            N2C && (N2C->getZExtValue() == 0 || N2C->getZExtValue() == 1) &&
6036            "Invalid FP_ROUND!");
6037     if (N1.getValueType() == VT) return N1;  // noop conversion.
6038     break;
6039   case ISD::AssertSext:
6040   case ISD::AssertZext: {
6041     EVT EVT = cast<VTSDNode>(N2)->getVT();
6042     assert(VT == N1.getValueType() && "Not an inreg extend!");
6043     assert(VT.isInteger() && EVT.isInteger() &&
6044            "Cannot *_EXTEND_INREG FP types");
6045     assert(!EVT.isVector() &&
6046            "AssertSExt/AssertZExt type should be the vector element type "
6047            "rather than the vector type!");
6048     assert(EVT.bitsLE(VT.getScalarType()) && "Not extending!");
6049     if (VT.getScalarType() == EVT) return N1; // noop assertion.
6050     break;
6051   }
6052   case ISD::SIGN_EXTEND_INREG: {
6053     EVT EVT = cast<VTSDNode>(N2)->getVT();
6054     assert(VT == N1.getValueType() && "Not an inreg extend!");
6055     assert(VT.isInteger() && EVT.isInteger() &&
6056            "Cannot *_EXTEND_INREG FP types");
6057     assert(EVT.isVector() == VT.isVector() &&
6058            "SIGN_EXTEND_INREG type should be vector iff the operand "
6059            "type is vector!");
6060     assert((!EVT.isVector() ||
6061             EVT.getVectorElementCount() == VT.getVectorElementCount()) &&
6062            "Vector element counts must match in SIGN_EXTEND_INREG");
6063     assert(EVT.bitsLE(VT) && "Not extending!");
6064     if (EVT == VT) return N1;  // Not actually extending
6065 
6066     auto SignExtendInReg = [&](APInt Val, llvm::EVT ConstantVT) {
6067       unsigned FromBits = EVT.getScalarSizeInBits();
6068       Val <<= Val.getBitWidth() - FromBits;
6069       Val.ashrInPlace(Val.getBitWidth() - FromBits);
6070       return getConstant(Val, DL, ConstantVT);
6071     };
6072 
6073     if (N1C) {
6074       const APInt &Val = N1C->getAPIntValue();
6075       return SignExtendInReg(Val, VT);
6076     }
6077 
6078     if (ISD::isBuildVectorOfConstantSDNodes(N1.getNode())) {
6079       SmallVector<SDValue, 8> Ops;
6080       llvm::EVT OpVT = N1.getOperand(0).getValueType();
6081       for (int i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
6082         SDValue Op = N1.getOperand(i);
6083         if (Op.isUndef()) {
6084           Ops.push_back(getUNDEF(OpVT));
6085           continue;
6086         }
6087         ConstantSDNode *C = cast<ConstantSDNode>(Op);
6088         APInt Val = C->getAPIntValue();
6089         Ops.push_back(SignExtendInReg(Val, OpVT));
6090       }
6091       return getBuildVector(VT, DL, Ops);
6092     }
6093     break;
6094   }
6095   case ISD::FP_TO_SINT_SAT:
6096   case ISD::FP_TO_UINT_SAT: {
6097     assert(VT.isInteger() && cast<VTSDNode>(N2)->getVT().isInteger() &&
6098            N1.getValueType().isFloatingPoint() && "Invalid FP_TO_*INT_SAT");
6099     assert(N1.getValueType().isVector() == VT.isVector() &&
6100            "FP_TO_*INT_SAT type should be vector iff the operand type is "
6101            "vector!");
6102     assert((!VT.isVector() || VT.getVectorNumElements() ==
6103                                   N1.getValueType().getVectorNumElements()) &&
6104            "Vector element counts must match in FP_TO_*INT_SAT");
6105     assert(!cast<VTSDNode>(N2)->getVT().isVector() &&
6106            "Type to saturate to must be a scalar.");
6107     assert(cast<VTSDNode>(N2)->getVT().bitsLE(VT.getScalarType()) &&
6108            "Not extending!");
6109     break;
6110   }
6111   case ISD::EXTRACT_VECTOR_ELT:
6112     assert(VT.getSizeInBits() >= N1.getValueType().getScalarSizeInBits() &&
6113            "The result of EXTRACT_VECTOR_ELT must be at least as wide as the \
6114              element type of the vector.");
6115 
6116     // Extract from an undefined value or using an undefined index is undefined.
6117     if (N1.isUndef() || N2.isUndef())
6118       return getUNDEF(VT);
6119 
6120     // EXTRACT_VECTOR_ELT of out-of-bounds element is an UNDEF for fixed length
6121     // vectors. For scalable vectors we will provide appropriate support for
6122     // dealing with arbitrary indices.
6123     if (N2C && N1.getValueType().isFixedLengthVector() &&
6124         N2C->getAPIntValue().uge(N1.getValueType().getVectorNumElements()))
6125       return getUNDEF(VT);
6126 
6127     // EXTRACT_VECTOR_ELT of CONCAT_VECTORS is often formed while lowering is
6128     // expanding copies of large vectors from registers. This only works for
6129     // fixed length vectors, since we need to know the exact number of
6130     // elements.
6131     if (N2C && N1.getOperand(0).getValueType().isFixedLengthVector() &&
6132         N1.getOpcode() == ISD::CONCAT_VECTORS && N1.getNumOperands() > 0) {
6133       unsigned Factor =
6134         N1.getOperand(0).getValueType().getVectorNumElements();
6135       return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
6136                      N1.getOperand(N2C->getZExtValue() / Factor),
6137                      getVectorIdxConstant(N2C->getZExtValue() % Factor, DL));
6138     }
6139 
6140     // EXTRACT_VECTOR_ELT of BUILD_VECTOR or SPLAT_VECTOR is often formed while
6141     // lowering is expanding large vector constants.
6142     if (N2C && (N1.getOpcode() == ISD::BUILD_VECTOR ||
6143                 N1.getOpcode() == ISD::SPLAT_VECTOR)) {
6144       assert((N1.getOpcode() != ISD::BUILD_VECTOR ||
6145               N1.getValueType().isFixedLengthVector()) &&
6146              "BUILD_VECTOR used for scalable vectors");
6147       unsigned Index =
6148           N1.getOpcode() == ISD::BUILD_VECTOR ? N2C->getZExtValue() : 0;
6149       SDValue Elt = N1.getOperand(Index);
6150 
6151       if (VT != Elt.getValueType())
6152         // If the vector element type is not legal, the BUILD_VECTOR operands
6153         // are promoted and implicitly truncated, and the result implicitly
6154         // extended. Make that explicit here.
6155         Elt = getAnyExtOrTrunc(Elt, DL, VT);
6156 
6157       return Elt;
6158     }
6159 
6160     // EXTRACT_VECTOR_ELT of INSERT_VECTOR_ELT is often formed when vector
6161     // operations are lowered to scalars.
6162     if (N1.getOpcode() == ISD::INSERT_VECTOR_ELT) {
6163       // If the indices are the same, return the inserted element else
6164       // if the indices are known different, extract the element from
6165       // the original vector.
6166       SDValue N1Op2 = N1.getOperand(2);
6167       ConstantSDNode *N1Op2C = dyn_cast<ConstantSDNode>(N1Op2);
6168 
6169       if (N1Op2C && N2C) {
6170         if (N1Op2C->getZExtValue() == N2C->getZExtValue()) {
6171           if (VT == N1.getOperand(1).getValueType())
6172             return N1.getOperand(1);
6173           if (VT.isFloatingPoint()) {
6174             assert(VT.getSizeInBits() > N1.getOperand(1).getValueType().getSizeInBits());
6175             return getFPExtendOrRound(N1.getOperand(1), DL, VT);
6176           }
6177           return getSExtOrTrunc(N1.getOperand(1), DL, VT);
6178         }
6179         return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0), N2);
6180       }
6181     }
6182 
6183     // EXTRACT_VECTOR_ELT of v1iX EXTRACT_SUBVECTOR could be formed
6184     // when vector types are scalarized and v1iX is legal.
6185     // vextract (v1iX extract_subvector(vNiX, Idx)) -> vextract(vNiX,Idx).
6186     // Here we are completely ignoring the extract element index (N2),
6187     // which is fine for fixed width vectors, since any index other than 0
6188     // is undefined anyway. However, this cannot be ignored for scalable
6189     // vectors - in theory we could support this, but we don't want to do this
6190     // without a profitability check.
6191     if (N1.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
6192         N1.getValueType().isFixedLengthVector() &&
6193         N1.getValueType().getVectorNumElements() == 1) {
6194       return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0),
6195                      N1.getOperand(1));
6196     }
6197     break;
6198   case ISD::EXTRACT_ELEMENT:
6199     assert(N2C && (unsigned)N2C->getZExtValue() < 2 && "Bad EXTRACT_ELEMENT!");
6200     assert(!N1.getValueType().isVector() && !VT.isVector() &&
6201            (N1.getValueType().isInteger() == VT.isInteger()) &&
6202            N1.getValueType() != VT &&
6203            "Wrong types for EXTRACT_ELEMENT!");
6204 
6205     // EXTRACT_ELEMENT of BUILD_PAIR is often formed while legalize is expanding
6206     // 64-bit integers into 32-bit parts.  Instead of building the extract of
6207     // the BUILD_PAIR, only to have legalize rip it apart, just do it now.
6208     if (N1.getOpcode() == ISD::BUILD_PAIR)
6209       return N1.getOperand(N2C->getZExtValue());
6210 
6211     // EXTRACT_ELEMENT of a constant int is also very common.
6212     if (N1C) {
6213       unsigned ElementSize = VT.getSizeInBits();
6214       unsigned Shift = ElementSize * N2C->getZExtValue();
6215       const APInt &Val = N1C->getAPIntValue();
6216       return getConstant(Val.extractBits(ElementSize, Shift), DL, VT);
6217     }
6218     break;
6219   case ISD::EXTRACT_SUBVECTOR: {
6220     EVT N1VT = N1.getValueType();
6221     assert(VT.isVector() && N1VT.isVector() &&
6222            "Extract subvector VTs must be vectors!");
6223     assert(VT.getVectorElementType() == N1VT.getVectorElementType() &&
6224            "Extract subvector VTs must have the same element type!");
6225     assert((VT.isFixedLengthVector() || N1VT.isScalableVector()) &&
6226            "Cannot extract a scalable vector from a fixed length vector!");
6227     assert((VT.isScalableVector() != N1VT.isScalableVector() ||
6228             VT.getVectorMinNumElements() <= N1VT.getVectorMinNumElements()) &&
6229            "Extract subvector must be from larger vector to smaller vector!");
6230     assert(N2C && "Extract subvector index must be a constant");
6231     assert((VT.isScalableVector() != N1VT.isScalableVector() ||
6232             (VT.getVectorMinNumElements() + N2C->getZExtValue()) <=
6233                 N1VT.getVectorMinNumElements()) &&
6234            "Extract subvector overflow!");
6235     assert(N2C->getAPIntValue().getBitWidth() ==
6236                TLI->getVectorIdxTy(getDataLayout()).getFixedSizeInBits() &&
6237            "Constant index for EXTRACT_SUBVECTOR has an invalid size");
6238 
6239     // Trivial extraction.
6240     if (VT == N1VT)
6241       return N1;
6242 
6243     // EXTRACT_SUBVECTOR of an UNDEF is an UNDEF.
6244     if (N1.isUndef())
6245       return getUNDEF(VT);
6246 
6247     // EXTRACT_SUBVECTOR of CONCAT_VECTOR can be simplified if the pieces of
6248     // the concat have the same type as the extract.
6249     if (N1.getOpcode() == ISD::CONCAT_VECTORS && N1.getNumOperands() > 0 &&
6250         VT == N1.getOperand(0).getValueType()) {
6251       unsigned Factor = VT.getVectorMinNumElements();
6252       return N1.getOperand(N2C->getZExtValue() / Factor);
6253     }
6254 
6255     // EXTRACT_SUBVECTOR of INSERT_SUBVECTOR is often created
6256     // during shuffle legalization.
6257     if (N1.getOpcode() == ISD::INSERT_SUBVECTOR && N2 == N1.getOperand(2) &&
6258         VT == N1.getOperand(1).getValueType())
6259       return N1.getOperand(1);
6260     break;
6261   }
6262   }
6263 
6264   // Perform trivial constant folding.
6265   if (SDValue SV = FoldConstantArithmetic(Opcode, DL, VT, {N1, N2}))
6266     return SV;
6267 
6268   // Canonicalize an UNDEF to the RHS, even over a constant.
6269   if (N1.isUndef()) {
6270     if (TLI->isCommutativeBinOp(Opcode)) {
6271       std::swap(N1, N2);
6272     } else {
6273       switch (Opcode) {
6274       case ISD::SUB:
6275         return getUNDEF(VT);     // fold op(undef, arg2) -> undef
6276       case ISD::SIGN_EXTEND_INREG:
6277       case ISD::UDIV:
6278       case ISD::SDIV:
6279       case ISD::UREM:
6280       case ISD::SREM:
6281       case ISD::SSUBSAT:
6282       case ISD::USUBSAT:
6283         return getConstant(0, DL, VT);    // fold op(undef, arg2) -> 0
6284       }
6285     }
6286   }
6287 
6288   // Fold a bunch of operators when the RHS is undef.
6289   if (N2.isUndef()) {
6290     switch (Opcode) {
6291     case ISD::XOR:
6292       if (N1.isUndef())
6293         // Handle undef ^ undef -> 0 special case. This is a common
6294         // idiom (misuse).
6295         return getConstant(0, DL, VT);
6296       LLVM_FALLTHROUGH;
6297     case ISD::ADD:
6298     case ISD::SUB:
6299     case ISD::UDIV:
6300     case ISD::SDIV:
6301     case ISD::UREM:
6302     case ISD::SREM:
6303       return getUNDEF(VT);       // fold op(arg1, undef) -> undef
6304     case ISD::MUL:
6305     case ISD::AND:
6306     case ISD::SSUBSAT:
6307     case ISD::USUBSAT:
6308       return getConstant(0, DL, VT);  // fold op(arg1, undef) -> 0
6309     case ISD::OR:
6310     case ISD::SADDSAT:
6311     case ISD::UADDSAT:
6312       return getAllOnesConstant(DL, VT);
6313     }
6314   }
6315 
6316   // Memoize this node if possible.
6317   SDNode *N;
6318   SDVTList VTs = getVTList(VT);
6319   SDValue Ops[] = {N1, N2};
6320   if (VT != MVT::Glue) {
6321     FoldingSetNodeID ID;
6322     AddNodeIDNode(ID, Opcode, VTs, Ops);
6323     void *IP = nullptr;
6324     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
6325       E->intersectFlagsWith(Flags);
6326       return SDValue(E, 0);
6327     }
6328 
6329     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
6330     N->setFlags(Flags);
6331     createOperands(N, Ops);
6332     CSEMap.InsertNode(N, IP);
6333   } else {
6334     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
6335     createOperands(N, Ops);
6336   }
6337 
6338   InsertNode(N);
6339   SDValue V = SDValue(N, 0);
6340   NewSDValueDbgMsg(V, "Creating new node: ", this);
6341   return V;
6342 }
6343 
6344 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
6345                               SDValue N1, SDValue N2, SDValue N3) {
6346   SDNodeFlags Flags;
6347   if (Inserter)
6348     Flags = Inserter->getFlags();
6349   return getNode(Opcode, DL, VT, N1, N2, N3, Flags);
6350 }
6351 
6352 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
6353                               SDValue N1, SDValue N2, SDValue N3,
6354                               const SDNodeFlags Flags) {
6355   assert(N1.getOpcode() != ISD::DELETED_NODE &&
6356          N2.getOpcode() != ISD::DELETED_NODE &&
6357          N3.getOpcode() != ISD::DELETED_NODE &&
6358          "Operand is DELETED_NODE!");
6359   // Perform various simplifications.
6360   switch (Opcode) {
6361   case ISD::FMA: {
6362     assert(VT.isFloatingPoint() && "This operator only applies to FP types!");
6363     assert(N1.getValueType() == VT && N2.getValueType() == VT &&
6364            N3.getValueType() == VT && "FMA types must match!");
6365     ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6366     ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2);
6367     ConstantFPSDNode *N3CFP = dyn_cast<ConstantFPSDNode>(N3);
6368     if (N1CFP && N2CFP && N3CFP) {
6369       APFloat  V1 = N1CFP->getValueAPF();
6370       const APFloat &V2 = N2CFP->getValueAPF();
6371       const APFloat &V3 = N3CFP->getValueAPF();
6372       V1.fusedMultiplyAdd(V2, V3, APFloat::rmNearestTiesToEven);
6373       return getConstantFP(V1, DL, VT);
6374     }
6375     break;
6376   }
6377   case ISD::BUILD_VECTOR: {
6378     // Attempt to simplify BUILD_VECTOR.
6379     SDValue Ops[] = {N1, N2, N3};
6380     if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
6381       return V;
6382     break;
6383   }
6384   case ISD::CONCAT_VECTORS: {
6385     SDValue Ops[] = {N1, N2, N3};
6386     if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this))
6387       return V;
6388     break;
6389   }
6390   case ISD::SETCC: {
6391     assert(VT.isInteger() && "SETCC result type must be an integer!");
6392     assert(N1.getValueType() == N2.getValueType() &&
6393            "SETCC operands must have the same type!");
6394     assert(VT.isVector() == N1.getValueType().isVector() &&
6395            "SETCC type should be vector iff the operand type is vector!");
6396     assert((!VT.isVector() || VT.getVectorElementCount() ==
6397                                   N1.getValueType().getVectorElementCount()) &&
6398            "SETCC vector element counts must match!");
6399     // Use FoldSetCC to simplify SETCC's.
6400     if (SDValue V = FoldSetCC(VT, N1, N2, cast<CondCodeSDNode>(N3)->get(), DL))
6401       return V;
6402     // Vector constant folding.
6403     SDValue Ops[] = {N1, N2, N3};
6404     if (SDValue V = FoldConstantArithmetic(Opcode, DL, VT, Ops)) {
6405       NewSDValueDbgMsg(V, "New node vector constant folding: ", this);
6406       return V;
6407     }
6408     break;
6409   }
6410   case ISD::SELECT:
6411   case ISD::VSELECT:
6412     if (SDValue V = simplifySelect(N1, N2, N3))
6413       return V;
6414     break;
6415   case ISD::VECTOR_SHUFFLE:
6416     llvm_unreachable("should use getVectorShuffle constructor!");
6417   case ISD::VECTOR_SPLICE: {
6418     if (cast<ConstantSDNode>(N3)->isNullValue())
6419       return N1;
6420     break;
6421   }
6422   case ISD::INSERT_VECTOR_ELT: {
6423     ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3);
6424     // INSERT_VECTOR_ELT into out-of-bounds element is an UNDEF, except
6425     // for scalable vectors where we will generate appropriate code to
6426     // deal with out-of-bounds cases correctly.
6427     if (N3C && N1.getValueType().isFixedLengthVector() &&
6428         N3C->getZExtValue() >= N1.getValueType().getVectorNumElements())
6429       return getUNDEF(VT);
6430 
6431     // Undefined index can be assumed out-of-bounds, so that's UNDEF too.
6432     if (N3.isUndef())
6433       return getUNDEF(VT);
6434 
6435     // If the inserted element is an UNDEF, just use the input vector.
6436     if (N2.isUndef())
6437       return N1;
6438 
6439     break;
6440   }
6441   case ISD::INSERT_SUBVECTOR: {
6442     // Inserting undef into undef is still undef.
6443     if (N1.isUndef() && N2.isUndef())
6444       return getUNDEF(VT);
6445 
6446     EVT N2VT = N2.getValueType();
6447     assert(VT == N1.getValueType() &&
6448            "Dest and insert subvector source types must match!");
6449     assert(VT.isVector() && N2VT.isVector() &&
6450            "Insert subvector VTs must be vectors!");
6451     assert((VT.isScalableVector() || N2VT.isFixedLengthVector()) &&
6452            "Cannot insert a scalable vector into a fixed length vector!");
6453     assert((VT.isScalableVector() != N2VT.isScalableVector() ||
6454             VT.getVectorMinNumElements() >= N2VT.getVectorMinNumElements()) &&
6455            "Insert subvector must be from smaller vector to larger vector!");
6456     assert(isa<ConstantSDNode>(N3) &&
6457            "Insert subvector index must be constant");
6458     assert((VT.isScalableVector() != N2VT.isScalableVector() ||
6459             (N2VT.getVectorMinNumElements() +
6460              cast<ConstantSDNode>(N3)->getZExtValue()) <=
6461                 VT.getVectorMinNumElements()) &&
6462            "Insert subvector overflow!");
6463     assert(cast<ConstantSDNode>(N3)->getAPIntValue().getBitWidth() ==
6464                TLI->getVectorIdxTy(getDataLayout()).getFixedSizeInBits() &&
6465            "Constant index for INSERT_SUBVECTOR has an invalid size");
6466 
6467     // Trivial insertion.
6468     if (VT == N2VT)
6469       return N2;
6470 
6471     // If this is an insert of an extracted vector into an undef vector, we
6472     // can just use the input to the extract.
6473     if (N1.isUndef() && N2.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
6474         N2.getOperand(1) == N3 && N2.getOperand(0).getValueType() == VT)
6475       return N2.getOperand(0);
6476     break;
6477   }
6478   case ISD::BITCAST:
6479     // Fold bit_convert nodes from a type to themselves.
6480     if (N1.getValueType() == VT)
6481       return N1;
6482     break;
6483   }
6484 
6485   // Memoize node if it doesn't produce a flag.
6486   SDNode *N;
6487   SDVTList VTs = getVTList(VT);
6488   SDValue Ops[] = {N1, N2, N3};
6489   if (VT != MVT::Glue) {
6490     FoldingSetNodeID ID;
6491     AddNodeIDNode(ID, Opcode, VTs, Ops);
6492     void *IP = nullptr;
6493     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
6494       E->intersectFlagsWith(Flags);
6495       return SDValue(E, 0);
6496     }
6497 
6498     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
6499     N->setFlags(Flags);
6500     createOperands(N, Ops);
6501     CSEMap.InsertNode(N, IP);
6502   } else {
6503     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
6504     createOperands(N, Ops);
6505   }
6506 
6507   InsertNode(N);
6508   SDValue V = SDValue(N, 0);
6509   NewSDValueDbgMsg(V, "Creating new node: ", this);
6510   return V;
6511 }
6512 
6513 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
6514                               SDValue N1, SDValue N2, SDValue N3, SDValue N4) {
6515   SDValue Ops[] = { N1, N2, N3, N4 };
6516   return getNode(Opcode, DL, VT, Ops);
6517 }
6518 
6519 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
6520                               SDValue N1, SDValue N2, SDValue N3, SDValue N4,
6521                               SDValue N5) {
6522   SDValue Ops[] = { N1, N2, N3, N4, N5 };
6523   return getNode(Opcode, DL, VT, Ops);
6524 }
6525 
6526 /// getStackArgumentTokenFactor - Compute a TokenFactor to force all
6527 /// the incoming stack arguments to be loaded from the stack.
6528 SDValue SelectionDAG::getStackArgumentTokenFactor(SDValue Chain) {
6529   SmallVector<SDValue, 8> ArgChains;
6530 
6531   // Include the original chain at the beginning of the list. When this is
6532   // used by target LowerCall hooks, this helps legalize find the
6533   // CALLSEQ_BEGIN node.
6534   ArgChains.push_back(Chain);
6535 
6536   // Add a chain value for each stack argument.
6537   for (SDNode *U : getEntryNode().getNode()->uses())
6538     if (LoadSDNode *L = dyn_cast<LoadSDNode>(U))
6539       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
6540         if (FI->getIndex() < 0)
6541           ArgChains.push_back(SDValue(L, 1));
6542 
6543   // Build a tokenfactor for all the chains.
6544   return getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains);
6545 }
6546 
6547 /// getMemsetValue - Vectorized representation of the memset value
6548 /// operand.
6549 static SDValue getMemsetValue(SDValue Value, EVT VT, SelectionDAG &DAG,
6550                               const SDLoc &dl) {
6551   assert(!Value.isUndef());
6552 
6553   unsigned NumBits = VT.getScalarSizeInBits();
6554   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
6555     assert(C->getAPIntValue().getBitWidth() == 8);
6556     APInt Val = APInt::getSplat(NumBits, C->getAPIntValue());
6557     if (VT.isInteger()) {
6558       bool IsOpaque = VT.getSizeInBits() > 64 ||
6559           !DAG.getTargetLoweringInfo().isLegalStoreImmediate(C->getSExtValue());
6560       return DAG.getConstant(Val, dl, VT, false, IsOpaque);
6561     }
6562     return DAG.getConstantFP(APFloat(DAG.EVTToAPFloatSemantics(VT), Val), dl,
6563                              VT);
6564   }
6565 
6566   assert(Value.getValueType() == MVT::i8 && "memset with non-byte fill value?");
6567   EVT IntVT = VT.getScalarType();
6568   if (!IntVT.isInteger())
6569     IntVT = EVT::getIntegerVT(*DAG.getContext(), IntVT.getSizeInBits());
6570 
6571   Value = DAG.getNode(ISD::ZERO_EXTEND, dl, IntVT, Value);
6572   if (NumBits > 8) {
6573     // Use a multiplication with 0x010101... to extend the input to the
6574     // required length.
6575     APInt Magic = APInt::getSplat(NumBits, APInt(8, 0x01));
6576     Value = DAG.getNode(ISD::MUL, dl, IntVT, Value,
6577                         DAG.getConstant(Magic, dl, IntVT));
6578   }
6579 
6580   if (VT != Value.getValueType() && !VT.isInteger())
6581     Value = DAG.getBitcast(VT.getScalarType(), Value);
6582   if (VT != Value.getValueType())
6583     Value = DAG.getSplatBuildVector(VT, dl, Value);
6584 
6585   return Value;
6586 }
6587 
6588 /// getMemsetStringVal - Similar to getMemsetValue. Except this is only
6589 /// used when a memcpy is turned into a memset when the source is a constant
6590 /// string ptr.
6591 static SDValue getMemsetStringVal(EVT VT, const SDLoc &dl, SelectionDAG &DAG,
6592                                   const TargetLowering &TLI,
6593                                   const ConstantDataArraySlice &Slice) {
6594   // Handle vector with all elements zero.
6595   if (Slice.Array == nullptr) {
6596     if (VT.isInteger())
6597       return DAG.getConstant(0, dl, VT);
6598     if (VT == MVT::f32 || VT == MVT::f64 || VT == MVT::f128)
6599       return DAG.getConstantFP(0.0, dl, VT);
6600     if (VT.isVector()) {
6601       unsigned NumElts = VT.getVectorNumElements();
6602       MVT EltVT = (VT.getVectorElementType() == MVT::f32) ? MVT::i32 : MVT::i64;
6603       return DAG.getNode(ISD::BITCAST, dl, VT,
6604                          DAG.getConstant(0, dl,
6605                                          EVT::getVectorVT(*DAG.getContext(),
6606                                                           EltVT, NumElts)));
6607     }
6608     llvm_unreachable("Expected type!");
6609   }
6610 
6611   assert(!VT.isVector() && "Can't handle vector type here!");
6612   unsigned NumVTBits = VT.getSizeInBits();
6613   unsigned NumVTBytes = NumVTBits / 8;
6614   unsigned NumBytes = std::min(NumVTBytes, unsigned(Slice.Length));
6615 
6616   APInt Val(NumVTBits, 0);
6617   if (DAG.getDataLayout().isLittleEndian()) {
6618     for (unsigned i = 0; i != NumBytes; ++i)
6619       Val |= (uint64_t)(unsigned char)Slice[i] << i*8;
6620   } else {
6621     for (unsigned i = 0; i != NumBytes; ++i)
6622       Val |= (uint64_t)(unsigned char)Slice[i] << (NumVTBytes-i-1)*8;
6623   }
6624 
6625   // If the "cost" of materializing the integer immediate is less than the cost
6626   // of a load, then it is cost effective to turn the load into the immediate.
6627   Type *Ty = VT.getTypeForEVT(*DAG.getContext());
6628   if (TLI.shouldConvertConstantLoadToIntImm(Val, Ty))
6629     return DAG.getConstant(Val, dl, VT);
6630   return SDValue();
6631 }
6632 
6633 SDValue SelectionDAG::getMemBasePlusOffset(SDValue Base, TypeSize Offset,
6634                                            const SDLoc &DL,
6635                                            const SDNodeFlags Flags) {
6636   EVT VT = Base.getValueType();
6637   SDValue Index;
6638 
6639   if (Offset.isScalable())
6640     Index = getVScale(DL, Base.getValueType(),
6641                       APInt(Base.getValueSizeInBits().getFixedSize(),
6642                             Offset.getKnownMinSize()));
6643   else
6644     Index = getConstant(Offset.getFixedSize(), DL, VT);
6645 
6646   return getMemBasePlusOffset(Base, Index, DL, Flags);
6647 }
6648 
6649 SDValue SelectionDAG::getMemBasePlusOffset(SDValue Ptr, SDValue Offset,
6650                                            const SDLoc &DL,
6651                                            const SDNodeFlags Flags) {
6652   assert(Offset.getValueType().isInteger());
6653   EVT BasePtrVT = Ptr.getValueType();
6654   return getNode(ISD::ADD, DL, BasePtrVT, Ptr, Offset, Flags);
6655 }
6656 
6657 /// Returns true if memcpy source is constant data.
6658 static bool isMemSrcFromConstant(SDValue Src, ConstantDataArraySlice &Slice) {
6659   uint64_t SrcDelta = 0;
6660   GlobalAddressSDNode *G = nullptr;
6661   if (Src.getOpcode() == ISD::GlobalAddress)
6662     G = cast<GlobalAddressSDNode>(Src);
6663   else if (Src.getOpcode() == ISD::ADD &&
6664            Src.getOperand(0).getOpcode() == ISD::GlobalAddress &&
6665            Src.getOperand(1).getOpcode() == ISD::Constant) {
6666     G = cast<GlobalAddressSDNode>(Src.getOperand(0));
6667     SrcDelta = cast<ConstantSDNode>(Src.getOperand(1))->getZExtValue();
6668   }
6669   if (!G)
6670     return false;
6671 
6672   return getConstantDataArrayInfo(G->getGlobal(), Slice, 8,
6673                                   SrcDelta + G->getOffset());
6674 }
6675 
6676 static bool shouldLowerMemFuncForSize(const MachineFunction &MF,
6677                                       SelectionDAG &DAG) {
6678   // On Darwin, -Os means optimize for size without hurting performance, so
6679   // only really optimize for size when -Oz (MinSize) is used.
6680   if (MF.getTarget().getTargetTriple().isOSDarwin())
6681     return MF.getFunction().hasMinSize();
6682   return DAG.shouldOptForSize();
6683 }
6684 
6685 static void chainLoadsAndStoresForMemcpy(SelectionDAG &DAG, const SDLoc &dl,
6686                           SmallVector<SDValue, 32> &OutChains, unsigned From,
6687                           unsigned To, SmallVector<SDValue, 16> &OutLoadChains,
6688                           SmallVector<SDValue, 16> &OutStoreChains) {
6689   assert(OutLoadChains.size() && "Missing loads in memcpy inlining");
6690   assert(OutStoreChains.size() && "Missing stores in memcpy inlining");
6691   SmallVector<SDValue, 16> GluedLoadChains;
6692   for (unsigned i = From; i < To; ++i) {
6693     OutChains.push_back(OutLoadChains[i]);
6694     GluedLoadChains.push_back(OutLoadChains[i]);
6695   }
6696 
6697   // Chain for all loads.
6698   SDValue LoadToken = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
6699                                   GluedLoadChains);
6700 
6701   for (unsigned i = From; i < To; ++i) {
6702     StoreSDNode *ST = dyn_cast<StoreSDNode>(OutStoreChains[i]);
6703     SDValue NewStore = DAG.getTruncStore(LoadToken, dl, ST->getValue(),
6704                                   ST->getBasePtr(), ST->getMemoryVT(),
6705                                   ST->getMemOperand());
6706     OutChains.push_back(NewStore);
6707   }
6708 }
6709 
6710 static SDValue getMemcpyLoadsAndStores(SelectionDAG &DAG, const SDLoc &dl,
6711                                        SDValue Chain, SDValue Dst, SDValue Src,
6712                                        uint64_t Size, Align Alignment,
6713                                        bool isVol, bool AlwaysInline,
6714                                        MachinePointerInfo DstPtrInfo,
6715                                        MachinePointerInfo SrcPtrInfo,
6716                                        const AAMDNodes &AAInfo) {
6717   // Turn a memcpy of undef to nop.
6718   // FIXME: We need to honor volatile even is Src is undef.
6719   if (Src.isUndef())
6720     return Chain;
6721 
6722   // Expand memcpy to a series of load and store ops if the size operand falls
6723   // below a certain threshold.
6724   // TODO: In the AlwaysInline case, if the size is big then generate a loop
6725   // rather than maybe a humongous number of loads and stores.
6726   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6727   const DataLayout &DL = DAG.getDataLayout();
6728   LLVMContext &C = *DAG.getContext();
6729   std::vector<EVT> MemOps;
6730   bool DstAlignCanChange = false;
6731   MachineFunction &MF = DAG.getMachineFunction();
6732   MachineFrameInfo &MFI = MF.getFrameInfo();
6733   bool OptSize = shouldLowerMemFuncForSize(MF, DAG);
6734   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
6735   if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
6736     DstAlignCanChange = true;
6737   MaybeAlign SrcAlign = DAG.InferPtrAlign(Src);
6738   if (!SrcAlign || Alignment > *SrcAlign)
6739     SrcAlign = Alignment;
6740   assert(SrcAlign && "SrcAlign must be set");
6741   ConstantDataArraySlice Slice;
6742   // If marked as volatile, perform a copy even when marked as constant.
6743   bool CopyFromConstant = !isVol && isMemSrcFromConstant(Src, Slice);
6744   bool isZeroConstant = CopyFromConstant && Slice.Array == nullptr;
6745   unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemcpy(OptSize);
6746   const MemOp Op = isZeroConstant
6747                        ? MemOp::Set(Size, DstAlignCanChange, Alignment,
6748                                     /*IsZeroMemset*/ true, isVol)
6749                        : MemOp::Copy(Size, DstAlignCanChange, Alignment,
6750                                      *SrcAlign, isVol, CopyFromConstant);
6751   if (!TLI.findOptimalMemOpLowering(
6752           MemOps, Limit, Op, DstPtrInfo.getAddrSpace(),
6753           SrcPtrInfo.getAddrSpace(), MF.getFunction().getAttributes()))
6754     return SDValue();
6755 
6756   if (DstAlignCanChange) {
6757     Type *Ty = MemOps[0].getTypeForEVT(C);
6758     Align NewAlign = DL.getABITypeAlign(Ty);
6759 
6760     // Don't promote to an alignment that would require dynamic stack
6761     // realignment.
6762     const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
6763     if (!TRI->hasStackRealignment(MF))
6764       while (NewAlign > Alignment && DL.exceedsNaturalStackAlignment(NewAlign))
6765         NewAlign = NewAlign.previous();
6766 
6767     if (NewAlign > Alignment) {
6768       // Give the stack frame object a larger alignment if needed.
6769       if (MFI.getObjectAlign(FI->getIndex()) < NewAlign)
6770         MFI.setObjectAlignment(FI->getIndex(), NewAlign);
6771       Alignment = NewAlign;
6772     }
6773   }
6774 
6775   // Prepare AAInfo for loads/stores after lowering this memcpy.
6776   AAMDNodes NewAAInfo = AAInfo;
6777   NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr;
6778 
6779   MachineMemOperand::Flags MMOFlags =
6780       isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone;
6781   SmallVector<SDValue, 16> OutLoadChains;
6782   SmallVector<SDValue, 16> OutStoreChains;
6783   SmallVector<SDValue, 32> OutChains;
6784   unsigned NumMemOps = MemOps.size();
6785   uint64_t SrcOff = 0, DstOff = 0;
6786   for (unsigned i = 0; i != NumMemOps; ++i) {
6787     EVT VT = MemOps[i];
6788     unsigned VTSize = VT.getSizeInBits() / 8;
6789     SDValue Value, Store;
6790 
6791     if (VTSize > Size) {
6792       // Issuing an unaligned load / store pair  that overlaps with the previous
6793       // pair. Adjust the offset accordingly.
6794       assert(i == NumMemOps-1 && i != 0);
6795       SrcOff -= VTSize - Size;
6796       DstOff -= VTSize - Size;
6797     }
6798 
6799     if (CopyFromConstant &&
6800         (isZeroConstant || (VT.isInteger() && !VT.isVector()))) {
6801       // It's unlikely a store of a vector immediate can be done in a single
6802       // instruction. It would require a load from a constantpool first.
6803       // We only handle zero vectors here.
6804       // FIXME: Handle other cases where store of vector immediate is done in
6805       // a single instruction.
6806       ConstantDataArraySlice SubSlice;
6807       if (SrcOff < Slice.Length) {
6808         SubSlice = Slice;
6809         SubSlice.move(SrcOff);
6810       } else {
6811         // This is an out-of-bounds access and hence UB. Pretend we read zero.
6812         SubSlice.Array = nullptr;
6813         SubSlice.Offset = 0;
6814         SubSlice.Length = VTSize;
6815       }
6816       Value = getMemsetStringVal(VT, dl, DAG, TLI, SubSlice);
6817       if (Value.getNode()) {
6818         Store = DAG.getStore(
6819             Chain, dl, Value,
6820             DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl),
6821             DstPtrInfo.getWithOffset(DstOff), Alignment, MMOFlags, NewAAInfo);
6822         OutChains.push_back(Store);
6823       }
6824     }
6825 
6826     if (!Store.getNode()) {
6827       // The type might not be legal for the target.  This should only happen
6828       // if the type is smaller than a legal type, as on PPC, so the right
6829       // thing to do is generate a LoadExt/StoreTrunc pair.  These simplify
6830       // to Load/Store if NVT==VT.
6831       // FIXME does the case above also need this?
6832       EVT NVT = TLI.getTypeToTransformTo(C, VT);
6833       assert(NVT.bitsGE(VT));
6834 
6835       bool isDereferenceable =
6836         SrcPtrInfo.getWithOffset(SrcOff).isDereferenceable(VTSize, C, DL);
6837       MachineMemOperand::Flags SrcMMOFlags = MMOFlags;
6838       if (isDereferenceable)
6839         SrcMMOFlags |= MachineMemOperand::MODereferenceable;
6840 
6841       Value = DAG.getExtLoad(
6842           ISD::EXTLOAD, dl, NVT, Chain,
6843           DAG.getMemBasePlusOffset(Src, TypeSize::Fixed(SrcOff), dl),
6844           SrcPtrInfo.getWithOffset(SrcOff), VT,
6845           commonAlignment(*SrcAlign, SrcOff), SrcMMOFlags, NewAAInfo);
6846       OutLoadChains.push_back(Value.getValue(1));
6847 
6848       Store = DAG.getTruncStore(
6849           Chain, dl, Value,
6850           DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl),
6851           DstPtrInfo.getWithOffset(DstOff), VT, Alignment, MMOFlags, NewAAInfo);
6852       OutStoreChains.push_back(Store);
6853     }
6854     SrcOff += VTSize;
6855     DstOff += VTSize;
6856     Size -= VTSize;
6857   }
6858 
6859   unsigned GluedLdStLimit = MaxLdStGlue == 0 ?
6860                                 TLI.getMaxGluedStoresPerMemcpy() : MaxLdStGlue;
6861   unsigned NumLdStInMemcpy = OutStoreChains.size();
6862 
6863   if (NumLdStInMemcpy) {
6864     // It may be that memcpy might be converted to memset if it's memcpy
6865     // of constants. In such a case, we won't have loads and stores, but
6866     // just stores. In the absence of loads, there is nothing to gang up.
6867     if ((GluedLdStLimit <= 1) || !EnableMemCpyDAGOpt) {
6868       // If target does not care, just leave as it.
6869       for (unsigned i = 0; i < NumLdStInMemcpy; ++i) {
6870         OutChains.push_back(OutLoadChains[i]);
6871         OutChains.push_back(OutStoreChains[i]);
6872       }
6873     } else {
6874       // Ld/St less than/equal limit set by target.
6875       if (NumLdStInMemcpy <= GluedLdStLimit) {
6876           chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, 0,
6877                                         NumLdStInMemcpy, OutLoadChains,
6878                                         OutStoreChains);
6879       } else {
6880         unsigned NumberLdChain =  NumLdStInMemcpy / GluedLdStLimit;
6881         unsigned RemainingLdStInMemcpy = NumLdStInMemcpy % GluedLdStLimit;
6882         unsigned GlueIter = 0;
6883 
6884         for (unsigned cnt = 0; cnt < NumberLdChain; ++cnt) {
6885           unsigned IndexFrom = NumLdStInMemcpy - GlueIter - GluedLdStLimit;
6886           unsigned IndexTo   = NumLdStInMemcpy - GlueIter;
6887 
6888           chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, IndexFrom, IndexTo,
6889                                        OutLoadChains, OutStoreChains);
6890           GlueIter += GluedLdStLimit;
6891         }
6892 
6893         // Residual ld/st.
6894         if (RemainingLdStInMemcpy) {
6895           chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, 0,
6896                                         RemainingLdStInMemcpy, OutLoadChains,
6897                                         OutStoreChains);
6898         }
6899       }
6900     }
6901   }
6902   return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
6903 }
6904 
6905 static SDValue getMemmoveLoadsAndStores(SelectionDAG &DAG, const SDLoc &dl,
6906                                         SDValue Chain, SDValue Dst, SDValue Src,
6907                                         uint64_t Size, Align Alignment,
6908                                         bool isVol, bool AlwaysInline,
6909                                         MachinePointerInfo DstPtrInfo,
6910                                         MachinePointerInfo SrcPtrInfo,
6911                                         const AAMDNodes &AAInfo) {
6912   // Turn a memmove of undef to nop.
6913   // FIXME: We need to honor volatile even is Src is undef.
6914   if (Src.isUndef())
6915     return Chain;
6916 
6917   // Expand memmove to a series of load and store ops if the size operand falls
6918   // below a certain threshold.
6919   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6920   const DataLayout &DL = DAG.getDataLayout();
6921   LLVMContext &C = *DAG.getContext();
6922   std::vector<EVT> MemOps;
6923   bool DstAlignCanChange = false;
6924   MachineFunction &MF = DAG.getMachineFunction();
6925   MachineFrameInfo &MFI = MF.getFrameInfo();
6926   bool OptSize = shouldLowerMemFuncForSize(MF, DAG);
6927   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
6928   if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
6929     DstAlignCanChange = true;
6930   MaybeAlign SrcAlign = DAG.InferPtrAlign(Src);
6931   if (!SrcAlign || Alignment > *SrcAlign)
6932     SrcAlign = Alignment;
6933   assert(SrcAlign && "SrcAlign must be set");
6934   unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemmove(OptSize);
6935   if (!TLI.findOptimalMemOpLowering(
6936           MemOps, Limit,
6937           MemOp::Copy(Size, DstAlignCanChange, Alignment, *SrcAlign,
6938                       /*IsVolatile*/ true),
6939           DstPtrInfo.getAddrSpace(), SrcPtrInfo.getAddrSpace(),
6940           MF.getFunction().getAttributes()))
6941     return SDValue();
6942 
6943   if (DstAlignCanChange) {
6944     Type *Ty = MemOps[0].getTypeForEVT(C);
6945     Align NewAlign = DL.getABITypeAlign(Ty);
6946     if (NewAlign > Alignment) {
6947       // Give the stack frame object a larger alignment if needed.
6948       if (MFI.getObjectAlign(FI->getIndex()) < NewAlign)
6949         MFI.setObjectAlignment(FI->getIndex(), NewAlign);
6950       Alignment = NewAlign;
6951     }
6952   }
6953 
6954   // Prepare AAInfo for loads/stores after lowering this memmove.
6955   AAMDNodes NewAAInfo = AAInfo;
6956   NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr;
6957 
6958   MachineMemOperand::Flags MMOFlags =
6959       isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone;
6960   uint64_t SrcOff = 0, DstOff = 0;
6961   SmallVector<SDValue, 8> LoadValues;
6962   SmallVector<SDValue, 8> LoadChains;
6963   SmallVector<SDValue, 8> OutChains;
6964   unsigned NumMemOps = MemOps.size();
6965   for (unsigned i = 0; i < NumMemOps; i++) {
6966     EVT VT = MemOps[i];
6967     unsigned VTSize = VT.getSizeInBits() / 8;
6968     SDValue Value;
6969 
6970     bool isDereferenceable =
6971       SrcPtrInfo.getWithOffset(SrcOff).isDereferenceable(VTSize, C, DL);
6972     MachineMemOperand::Flags SrcMMOFlags = MMOFlags;
6973     if (isDereferenceable)
6974       SrcMMOFlags |= MachineMemOperand::MODereferenceable;
6975 
6976     Value = DAG.getLoad(
6977         VT, dl, Chain,
6978         DAG.getMemBasePlusOffset(Src, TypeSize::Fixed(SrcOff), dl),
6979         SrcPtrInfo.getWithOffset(SrcOff), *SrcAlign, SrcMMOFlags, NewAAInfo);
6980     LoadValues.push_back(Value);
6981     LoadChains.push_back(Value.getValue(1));
6982     SrcOff += VTSize;
6983   }
6984   Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
6985   OutChains.clear();
6986   for (unsigned i = 0; i < NumMemOps; i++) {
6987     EVT VT = MemOps[i];
6988     unsigned VTSize = VT.getSizeInBits() / 8;
6989     SDValue Store;
6990 
6991     Store = DAG.getStore(
6992         Chain, dl, LoadValues[i],
6993         DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl),
6994         DstPtrInfo.getWithOffset(DstOff), Alignment, MMOFlags, NewAAInfo);
6995     OutChains.push_back(Store);
6996     DstOff += VTSize;
6997   }
6998 
6999   return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
7000 }
7001 
7002 /// Lower the call to 'memset' intrinsic function into a series of store
7003 /// operations.
7004 ///
7005 /// \param DAG Selection DAG where lowered code is placed.
7006 /// \param dl Link to corresponding IR location.
7007 /// \param Chain Control flow dependency.
7008 /// \param Dst Pointer to destination memory location.
7009 /// \param Src Value of byte to write into the memory.
7010 /// \param Size Number of bytes to write.
7011 /// \param Alignment Alignment of the destination in bytes.
7012 /// \param isVol True if destination is volatile.
7013 /// \param AlwaysInline Makes sure no function call is generated.
7014 /// \param DstPtrInfo IR information on the memory pointer.
7015 /// \returns New head in the control flow, if lowering was successful, empty
7016 /// SDValue otherwise.
7017 ///
7018 /// The function tries to replace 'llvm.memset' intrinsic with several store
7019 /// operations and value calculation code. This is usually profitable for small
7020 /// memory size or when the semantic requires inlining.
7021 static SDValue getMemsetStores(SelectionDAG &DAG, const SDLoc &dl,
7022                                SDValue Chain, SDValue Dst, SDValue Src,
7023                                uint64_t Size, Align Alignment, bool isVol,
7024                                bool AlwaysInline, MachinePointerInfo DstPtrInfo,
7025                                const AAMDNodes &AAInfo) {
7026   // Turn a memset of undef to nop.
7027   // FIXME: We need to honor volatile even is Src is undef.
7028   if (Src.isUndef())
7029     return Chain;
7030 
7031   // Expand memset to a series of load/store ops if the size operand
7032   // falls below a certain threshold.
7033   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7034   std::vector<EVT> MemOps;
7035   bool DstAlignCanChange = false;
7036   MachineFunction &MF = DAG.getMachineFunction();
7037   MachineFrameInfo &MFI = MF.getFrameInfo();
7038   bool OptSize = shouldLowerMemFuncForSize(MF, DAG);
7039   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
7040   if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
7041     DstAlignCanChange = true;
7042   bool IsZeroVal =
7043       isa<ConstantSDNode>(Src) && cast<ConstantSDNode>(Src)->isZero();
7044   unsigned Limit = AlwaysInline ? ~0 : TLI.getMaxStoresPerMemset(OptSize);
7045 
7046   if (!TLI.findOptimalMemOpLowering(
7047           MemOps, Limit,
7048           MemOp::Set(Size, DstAlignCanChange, Alignment, IsZeroVal, isVol),
7049           DstPtrInfo.getAddrSpace(), ~0u, MF.getFunction().getAttributes()))
7050     return SDValue();
7051 
7052   if (DstAlignCanChange) {
7053     Type *Ty = MemOps[0].getTypeForEVT(*DAG.getContext());
7054     Align NewAlign = DAG.getDataLayout().getABITypeAlign(Ty);
7055     if (NewAlign > Alignment) {
7056       // Give the stack frame object a larger alignment if needed.
7057       if (MFI.getObjectAlign(FI->getIndex()) < NewAlign)
7058         MFI.setObjectAlignment(FI->getIndex(), NewAlign);
7059       Alignment = NewAlign;
7060     }
7061   }
7062 
7063   SmallVector<SDValue, 8> OutChains;
7064   uint64_t DstOff = 0;
7065   unsigned NumMemOps = MemOps.size();
7066 
7067   // Find the largest store and generate the bit pattern for it.
7068   EVT LargestVT = MemOps[0];
7069   for (unsigned i = 1; i < NumMemOps; i++)
7070     if (MemOps[i].bitsGT(LargestVT))
7071       LargestVT = MemOps[i];
7072   SDValue MemSetValue = getMemsetValue(Src, LargestVT, DAG, dl);
7073 
7074   // Prepare AAInfo for loads/stores after lowering this memset.
7075   AAMDNodes NewAAInfo = AAInfo;
7076   NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr;
7077 
7078   for (unsigned i = 0; i < NumMemOps; i++) {
7079     EVT VT = MemOps[i];
7080     unsigned VTSize = VT.getSizeInBits() / 8;
7081     if (VTSize > Size) {
7082       // Issuing an unaligned load / store pair  that overlaps with the previous
7083       // pair. Adjust the offset accordingly.
7084       assert(i == NumMemOps-1 && i != 0);
7085       DstOff -= VTSize - Size;
7086     }
7087 
7088     // If this store is smaller than the largest store see whether we can get
7089     // the smaller value for free with a truncate.
7090     SDValue Value = MemSetValue;
7091     if (VT.bitsLT(LargestVT)) {
7092       if (!LargestVT.isVector() && !VT.isVector() &&
7093           TLI.isTruncateFree(LargestVT, VT))
7094         Value = DAG.getNode(ISD::TRUNCATE, dl, VT, MemSetValue);
7095       else
7096         Value = getMemsetValue(Src, VT, DAG, dl);
7097     }
7098     assert(Value.getValueType() == VT && "Value with wrong type.");
7099     SDValue Store = DAG.getStore(
7100         Chain, dl, Value,
7101         DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl),
7102         DstPtrInfo.getWithOffset(DstOff), Alignment,
7103         isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone,
7104         NewAAInfo);
7105     OutChains.push_back(Store);
7106     DstOff += VT.getSizeInBits() / 8;
7107     Size -= VTSize;
7108   }
7109 
7110   return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
7111 }
7112 
7113 static void checkAddrSpaceIsValidForLibcall(const TargetLowering *TLI,
7114                                             unsigned AS) {
7115   // Lowering memcpy / memset / memmove intrinsics to calls is only valid if all
7116   // pointer operands can be losslessly bitcasted to pointers of address space 0
7117   if (AS != 0 && !TLI->getTargetMachine().isNoopAddrSpaceCast(AS, 0)) {
7118     report_fatal_error("cannot lower memory intrinsic in address space " +
7119                        Twine(AS));
7120   }
7121 }
7122 
7123 SDValue SelectionDAG::getMemcpy(SDValue Chain, const SDLoc &dl, SDValue Dst,
7124                                 SDValue Src, SDValue Size, Align Alignment,
7125                                 bool isVol, bool AlwaysInline, bool isTailCall,
7126                                 MachinePointerInfo DstPtrInfo,
7127                                 MachinePointerInfo SrcPtrInfo,
7128                                 const AAMDNodes &AAInfo) {
7129   // Check to see if we should lower the memcpy to loads and stores first.
7130   // For cases within the target-specified limits, this is the best choice.
7131   ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
7132   if (ConstantSize) {
7133     // Memcpy with size zero? Just return the original chain.
7134     if (ConstantSize->isZero())
7135       return Chain;
7136 
7137     SDValue Result = getMemcpyLoadsAndStores(
7138         *this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), Alignment,
7139         isVol, false, DstPtrInfo, SrcPtrInfo, AAInfo);
7140     if (Result.getNode())
7141       return Result;
7142   }
7143 
7144   // Then check to see if we should lower the memcpy with target-specific
7145   // code. If the target chooses to do this, this is the next best.
7146   if (TSI) {
7147     SDValue Result = TSI->EmitTargetCodeForMemcpy(
7148         *this, dl, Chain, Dst, Src, Size, Alignment, isVol, AlwaysInline,
7149         DstPtrInfo, SrcPtrInfo);
7150     if (Result.getNode())
7151       return Result;
7152   }
7153 
7154   // If we really need inline code and the target declined to provide it,
7155   // use a (potentially long) sequence of loads and stores.
7156   if (AlwaysInline) {
7157     assert(ConstantSize && "AlwaysInline requires a constant size!");
7158     return getMemcpyLoadsAndStores(*this, dl, Chain, Dst, Src,
7159                                    ConstantSize->getZExtValue(), Alignment,
7160                                    isVol, true, DstPtrInfo, SrcPtrInfo, AAInfo);
7161   }
7162 
7163   checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace());
7164   checkAddrSpaceIsValidForLibcall(TLI, SrcPtrInfo.getAddrSpace());
7165 
7166   // FIXME: If the memcpy is volatile (isVol), lowering it to a plain libc
7167   // memcpy is not guaranteed to be safe. libc memcpys aren't required to
7168   // respect volatile, so they may do things like read or write memory
7169   // beyond the given memory regions. But fixing this isn't easy, and most
7170   // people don't care.
7171 
7172   // Emit a library call.
7173   TargetLowering::ArgListTy Args;
7174   TargetLowering::ArgListEntry Entry;
7175   Entry.Ty = Type::getInt8PtrTy(*getContext());
7176   Entry.Node = Dst; Args.push_back(Entry);
7177   Entry.Node = Src; Args.push_back(Entry);
7178 
7179   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
7180   Entry.Node = Size; Args.push_back(Entry);
7181   // FIXME: pass in SDLoc
7182   TargetLowering::CallLoweringInfo CLI(*this);
7183   CLI.setDebugLoc(dl)
7184       .setChain(Chain)
7185       .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMCPY),
7186                     Dst.getValueType().getTypeForEVT(*getContext()),
7187                     getExternalSymbol(TLI->getLibcallName(RTLIB::MEMCPY),
7188                                       TLI->getPointerTy(getDataLayout())),
7189                     std::move(Args))
7190       .setDiscardResult()
7191       .setTailCall(isTailCall);
7192 
7193   std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
7194   return CallResult.second;
7195 }
7196 
7197 SDValue SelectionDAG::getAtomicMemcpy(SDValue Chain, const SDLoc &dl,
7198                                       SDValue Dst, SDValue Src, SDValue Size,
7199                                       Type *SizeTy, unsigned ElemSz,
7200                                       bool isTailCall,
7201                                       MachinePointerInfo DstPtrInfo,
7202                                       MachinePointerInfo SrcPtrInfo) {
7203   // Emit a library call.
7204   TargetLowering::ArgListTy Args;
7205   TargetLowering::ArgListEntry Entry;
7206   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
7207   Entry.Node = Dst;
7208   Args.push_back(Entry);
7209 
7210   Entry.Node = Src;
7211   Args.push_back(Entry);
7212 
7213   Entry.Ty = SizeTy;
7214   Entry.Node = Size;
7215   Args.push_back(Entry);
7216 
7217   RTLIB::Libcall LibraryCall =
7218       RTLIB::getMEMCPY_ELEMENT_UNORDERED_ATOMIC(ElemSz);
7219   if (LibraryCall == RTLIB::UNKNOWN_LIBCALL)
7220     report_fatal_error("Unsupported element size");
7221 
7222   TargetLowering::CallLoweringInfo CLI(*this);
7223   CLI.setDebugLoc(dl)
7224       .setChain(Chain)
7225       .setLibCallee(TLI->getLibcallCallingConv(LibraryCall),
7226                     Type::getVoidTy(*getContext()),
7227                     getExternalSymbol(TLI->getLibcallName(LibraryCall),
7228                                       TLI->getPointerTy(getDataLayout())),
7229                     std::move(Args))
7230       .setDiscardResult()
7231       .setTailCall(isTailCall);
7232 
7233   std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
7234   return CallResult.second;
7235 }
7236 
7237 SDValue SelectionDAG::getMemmove(SDValue Chain, const SDLoc &dl, SDValue Dst,
7238                                  SDValue Src, SDValue Size, Align Alignment,
7239                                  bool isVol, bool isTailCall,
7240                                  MachinePointerInfo DstPtrInfo,
7241                                  MachinePointerInfo SrcPtrInfo,
7242                                  const AAMDNodes &AAInfo) {
7243   // Check to see if we should lower the memmove to loads and stores first.
7244   // For cases within the target-specified limits, this is the best choice.
7245   ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
7246   if (ConstantSize) {
7247     // Memmove with size zero? Just return the original chain.
7248     if (ConstantSize->isZero())
7249       return Chain;
7250 
7251     SDValue Result = getMemmoveLoadsAndStores(
7252         *this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), Alignment,
7253         isVol, false, DstPtrInfo, SrcPtrInfo, AAInfo);
7254     if (Result.getNode())
7255       return Result;
7256   }
7257 
7258   // Then check to see if we should lower the memmove with target-specific
7259   // code. If the target chooses to do this, this is the next best.
7260   if (TSI) {
7261     SDValue Result =
7262         TSI->EmitTargetCodeForMemmove(*this, dl, Chain, Dst, Src, Size,
7263                                       Alignment, isVol, DstPtrInfo, SrcPtrInfo);
7264     if (Result.getNode())
7265       return Result;
7266   }
7267 
7268   checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace());
7269   checkAddrSpaceIsValidForLibcall(TLI, SrcPtrInfo.getAddrSpace());
7270 
7271   // FIXME: If the memmove is volatile, lowering it to plain libc memmove may
7272   // not be safe.  See memcpy above for more details.
7273 
7274   // Emit a library call.
7275   TargetLowering::ArgListTy Args;
7276   TargetLowering::ArgListEntry Entry;
7277   Entry.Ty = Type::getInt8PtrTy(*getContext());
7278   Entry.Node = Dst; Args.push_back(Entry);
7279   Entry.Node = Src; Args.push_back(Entry);
7280 
7281   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
7282   Entry.Node = Size; Args.push_back(Entry);
7283   // FIXME:  pass in SDLoc
7284   TargetLowering::CallLoweringInfo CLI(*this);
7285   CLI.setDebugLoc(dl)
7286       .setChain(Chain)
7287       .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMMOVE),
7288                     Dst.getValueType().getTypeForEVT(*getContext()),
7289                     getExternalSymbol(TLI->getLibcallName(RTLIB::MEMMOVE),
7290                                       TLI->getPointerTy(getDataLayout())),
7291                     std::move(Args))
7292       .setDiscardResult()
7293       .setTailCall(isTailCall);
7294 
7295   std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
7296   return CallResult.second;
7297 }
7298 
7299 SDValue SelectionDAG::getAtomicMemmove(SDValue Chain, const SDLoc &dl,
7300                                        SDValue Dst, SDValue Src, SDValue Size,
7301                                        Type *SizeTy, unsigned ElemSz,
7302                                        bool isTailCall,
7303                                        MachinePointerInfo DstPtrInfo,
7304                                        MachinePointerInfo SrcPtrInfo) {
7305   // Emit a library call.
7306   TargetLowering::ArgListTy Args;
7307   TargetLowering::ArgListEntry Entry;
7308   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
7309   Entry.Node = Dst;
7310   Args.push_back(Entry);
7311 
7312   Entry.Node = Src;
7313   Args.push_back(Entry);
7314 
7315   Entry.Ty = SizeTy;
7316   Entry.Node = Size;
7317   Args.push_back(Entry);
7318 
7319   RTLIB::Libcall LibraryCall =
7320       RTLIB::getMEMMOVE_ELEMENT_UNORDERED_ATOMIC(ElemSz);
7321   if (LibraryCall == RTLIB::UNKNOWN_LIBCALL)
7322     report_fatal_error("Unsupported element size");
7323 
7324   TargetLowering::CallLoweringInfo CLI(*this);
7325   CLI.setDebugLoc(dl)
7326       .setChain(Chain)
7327       .setLibCallee(TLI->getLibcallCallingConv(LibraryCall),
7328                     Type::getVoidTy(*getContext()),
7329                     getExternalSymbol(TLI->getLibcallName(LibraryCall),
7330                                       TLI->getPointerTy(getDataLayout())),
7331                     std::move(Args))
7332       .setDiscardResult()
7333       .setTailCall(isTailCall);
7334 
7335   std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
7336   return CallResult.second;
7337 }
7338 
7339 SDValue SelectionDAG::getMemset(SDValue Chain, const SDLoc &dl, SDValue Dst,
7340                                 SDValue Src, SDValue Size, Align Alignment,
7341                                 bool isVol, bool AlwaysInline, bool isTailCall,
7342                                 MachinePointerInfo DstPtrInfo,
7343                                 const AAMDNodes &AAInfo) {
7344   // Check to see if we should lower the memset to stores first.
7345   // For cases within the target-specified limits, this is the best choice.
7346   ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
7347   if (ConstantSize) {
7348     // Memset with size zero? Just return the original chain.
7349     if (ConstantSize->isZero())
7350       return Chain;
7351 
7352     SDValue Result = getMemsetStores(*this, dl, Chain, Dst, Src,
7353                                      ConstantSize->getZExtValue(), Alignment,
7354                                      isVol, false, DstPtrInfo, AAInfo);
7355 
7356     if (Result.getNode())
7357       return Result;
7358   }
7359 
7360   // Then check to see if we should lower the memset with target-specific
7361   // code. If the target chooses to do this, this is the next best.
7362   if (TSI) {
7363     SDValue Result = TSI->EmitTargetCodeForMemset(
7364         *this, dl, Chain, Dst, Src, Size, Alignment, isVol, AlwaysInline, DstPtrInfo);
7365     if (Result.getNode())
7366       return Result;
7367   }
7368 
7369   // If we really need inline code and the target declined to provide it,
7370   // use a (potentially long) sequence of loads and stores.
7371   if (AlwaysInline) {
7372     assert(ConstantSize && "AlwaysInline requires a constant size!");
7373     SDValue Result = getMemsetStores(*this, dl, Chain, Dst, Src,
7374                                      ConstantSize->getZExtValue(), Alignment,
7375                                      isVol, true, DstPtrInfo, AAInfo);
7376     assert(Result &&
7377            "getMemsetStores must return a valid sequence when AlwaysInline");
7378     return Result;
7379   }
7380 
7381   checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace());
7382 
7383   // Emit a library call.
7384   auto &Ctx = *getContext();
7385   const auto& DL = getDataLayout();
7386 
7387   TargetLowering::CallLoweringInfo CLI(*this);
7388   // FIXME: pass in SDLoc
7389   CLI.setDebugLoc(dl).setChain(Chain);
7390 
7391   ConstantSDNode *ConstantSrc = dyn_cast<ConstantSDNode>(Src);
7392   const bool SrcIsZero = ConstantSrc && ConstantSrc->isZero();
7393   const char *BzeroName = getTargetLoweringInfo().getLibcallName(RTLIB::BZERO);
7394 
7395   // Helper function to create an Entry from Node and Type.
7396   const auto CreateEntry = [](SDValue Node, Type *Ty) {
7397     TargetLowering::ArgListEntry Entry;
7398     Entry.Node = Node;
7399     Entry.Ty = Ty;
7400     return Entry;
7401   };
7402 
7403   // If zeroing out and bzero is present, use it.
7404   if (SrcIsZero && BzeroName) {
7405     TargetLowering::ArgListTy Args;
7406     Args.push_back(CreateEntry(Dst, Type::getInt8PtrTy(Ctx)));
7407     Args.push_back(CreateEntry(Size, DL.getIntPtrType(Ctx)));
7408     CLI.setLibCallee(
7409         TLI->getLibcallCallingConv(RTLIB::BZERO), Type::getVoidTy(Ctx),
7410         getExternalSymbol(BzeroName, TLI->getPointerTy(DL)), std::move(Args));
7411   } else {
7412     TargetLowering::ArgListTy Args;
7413     Args.push_back(CreateEntry(Dst, Type::getInt8PtrTy(Ctx)));
7414     Args.push_back(CreateEntry(Src, Src.getValueType().getTypeForEVT(Ctx)));
7415     Args.push_back(CreateEntry(Size, DL.getIntPtrType(Ctx)));
7416     CLI.setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMSET),
7417                      Dst.getValueType().getTypeForEVT(Ctx),
7418                      getExternalSymbol(TLI->getLibcallName(RTLIB::MEMSET),
7419                                        TLI->getPointerTy(DL)),
7420                      std::move(Args));
7421   }
7422 
7423   CLI.setDiscardResult().setTailCall(isTailCall);
7424 
7425   std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
7426   return CallResult.second;
7427 }
7428 
7429 SDValue SelectionDAG::getAtomicMemset(SDValue Chain, const SDLoc &dl,
7430                                       SDValue Dst, SDValue Value, SDValue Size,
7431                                       Type *SizeTy, unsigned ElemSz,
7432                                       bool isTailCall,
7433                                       MachinePointerInfo DstPtrInfo) {
7434   // Emit a library call.
7435   TargetLowering::ArgListTy Args;
7436   TargetLowering::ArgListEntry Entry;
7437   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
7438   Entry.Node = Dst;
7439   Args.push_back(Entry);
7440 
7441   Entry.Ty = Type::getInt8Ty(*getContext());
7442   Entry.Node = Value;
7443   Args.push_back(Entry);
7444 
7445   Entry.Ty = SizeTy;
7446   Entry.Node = Size;
7447   Args.push_back(Entry);
7448 
7449   RTLIB::Libcall LibraryCall =
7450       RTLIB::getMEMSET_ELEMENT_UNORDERED_ATOMIC(ElemSz);
7451   if (LibraryCall == RTLIB::UNKNOWN_LIBCALL)
7452     report_fatal_error("Unsupported element size");
7453 
7454   TargetLowering::CallLoweringInfo CLI(*this);
7455   CLI.setDebugLoc(dl)
7456       .setChain(Chain)
7457       .setLibCallee(TLI->getLibcallCallingConv(LibraryCall),
7458                     Type::getVoidTy(*getContext()),
7459                     getExternalSymbol(TLI->getLibcallName(LibraryCall),
7460                                       TLI->getPointerTy(getDataLayout())),
7461                     std::move(Args))
7462       .setDiscardResult()
7463       .setTailCall(isTailCall);
7464 
7465   std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
7466   return CallResult.second;
7467 }
7468 
7469 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
7470                                 SDVTList VTList, ArrayRef<SDValue> Ops,
7471                                 MachineMemOperand *MMO) {
7472   FoldingSetNodeID ID;
7473   ID.AddInteger(MemVT.getRawBits());
7474   AddNodeIDNode(ID, Opcode, VTList, Ops);
7475   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7476   ID.AddInteger(MMO->getFlags());
7477   void* IP = nullptr;
7478   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7479     cast<AtomicSDNode>(E)->refineAlignment(MMO);
7480     return SDValue(E, 0);
7481   }
7482 
7483   auto *N = newSDNode<AtomicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
7484                                     VTList, MemVT, MMO);
7485   createOperands(N, Ops);
7486 
7487   CSEMap.InsertNode(N, IP);
7488   InsertNode(N);
7489   return SDValue(N, 0);
7490 }
7491 
7492 SDValue SelectionDAG::getAtomicCmpSwap(unsigned Opcode, const SDLoc &dl,
7493                                        EVT MemVT, SDVTList VTs, SDValue Chain,
7494                                        SDValue Ptr, SDValue Cmp, SDValue Swp,
7495                                        MachineMemOperand *MMO) {
7496   assert(Opcode == ISD::ATOMIC_CMP_SWAP ||
7497          Opcode == ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS);
7498   assert(Cmp.getValueType() == Swp.getValueType() && "Invalid Atomic Op Types");
7499 
7500   SDValue Ops[] = {Chain, Ptr, Cmp, Swp};
7501   return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
7502 }
7503 
7504 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
7505                                 SDValue Chain, SDValue Ptr, SDValue Val,
7506                                 MachineMemOperand *MMO) {
7507   assert((Opcode == ISD::ATOMIC_LOAD_ADD ||
7508           Opcode == ISD::ATOMIC_LOAD_SUB ||
7509           Opcode == ISD::ATOMIC_LOAD_AND ||
7510           Opcode == ISD::ATOMIC_LOAD_CLR ||
7511           Opcode == ISD::ATOMIC_LOAD_OR ||
7512           Opcode == ISD::ATOMIC_LOAD_XOR ||
7513           Opcode == ISD::ATOMIC_LOAD_NAND ||
7514           Opcode == ISD::ATOMIC_LOAD_MIN ||
7515           Opcode == ISD::ATOMIC_LOAD_MAX ||
7516           Opcode == ISD::ATOMIC_LOAD_UMIN ||
7517           Opcode == ISD::ATOMIC_LOAD_UMAX ||
7518           Opcode == ISD::ATOMIC_LOAD_FADD ||
7519           Opcode == ISD::ATOMIC_LOAD_FSUB ||
7520           Opcode == ISD::ATOMIC_LOAD_FMAX ||
7521           Opcode == ISD::ATOMIC_LOAD_FMIN ||
7522           Opcode == ISD::ATOMIC_SWAP ||
7523           Opcode == ISD::ATOMIC_STORE) &&
7524          "Invalid Atomic Op");
7525 
7526   EVT VT = Val.getValueType();
7527 
7528   SDVTList VTs = Opcode == ISD::ATOMIC_STORE ? getVTList(MVT::Other) :
7529                                                getVTList(VT, MVT::Other);
7530   SDValue Ops[] = {Chain, Ptr, Val};
7531   return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
7532 }
7533 
7534 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
7535                                 EVT VT, SDValue Chain, SDValue Ptr,
7536                                 MachineMemOperand *MMO) {
7537   assert(Opcode == ISD::ATOMIC_LOAD && "Invalid Atomic Op");
7538 
7539   SDVTList VTs = getVTList(VT, MVT::Other);
7540   SDValue Ops[] = {Chain, Ptr};
7541   return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
7542 }
7543 
7544 /// getMergeValues - Create a MERGE_VALUES node from the given operands.
7545 SDValue SelectionDAG::getMergeValues(ArrayRef<SDValue> Ops, const SDLoc &dl) {
7546   if (Ops.size() == 1)
7547     return Ops[0];
7548 
7549   SmallVector<EVT, 4> VTs;
7550   VTs.reserve(Ops.size());
7551   for (const SDValue &Op : Ops)
7552     VTs.push_back(Op.getValueType());
7553   return getNode(ISD::MERGE_VALUES, dl, getVTList(VTs), Ops);
7554 }
7555 
7556 SDValue SelectionDAG::getMemIntrinsicNode(
7557     unsigned Opcode, const SDLoc &dl, SDVTList VTList, ArrayRef<SDValue> Ops,
7558     EVT MemVT, MachinePointerInfo PtrInfo, Align Alignment,
7559     MachineMemOperand::Flags Flags, uint64_t Size, const AAMDNodes &AAInfo) {
7560   if (!Size && MemVT.isScalableVector())
7561     Size = MemoryLocation::UnknownSize;
7562   else if (!Size)
7563     Size = MemVT.getStoreSize();
7564 
7565   MachineFunction &MF = getMachineFunction();
7566   MachineMemOperand *MMO =
7567       MF.getMachineMemOperand(PtrInfo, Flags, Size, Alignment, AAInfo);
7568 
7569   return getMemIntrinsicNode(Opcode, dl, VTList, Ops, MemVT, MMO);
7570 }
7571 
7572 SDValue SelectionDAG::getMemIntrinsicNode(unsigned Opcode, const SDLoc &dl,
7573                                           SDVTList VTList,
7574                                           ArrayRef<SDValue> Ops, EVT MemVT,
7575                                           MachineMemOperand *MMO) {
7576   assert((Opcode == ISD::INTRINSIC_VOID ||
7577           Opcode == ISD::INTRINSIC_W_CHAIN ||
7578           Opcode == ISD::PREFETCH ||
7579           ((int)Opcode <= std::numeric_limits<int>::max() &&
7580            (int)Opcode >= ISD::FIRST_TARGET_MEMORY_OPCODE)) &&
7581          "Opcode is not a memory-accessing opcode!");
7582 
7583   // Memoize the node unless it returns a flag.
7584   MemIntrinsicSDNode *N;
7585   if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) {
7586     FoldingSetNodeID ID;
7587     AddNodeIDNode(ID, Opcode, VTList, Ops);
7588     ID.AddInteger(getSyntheticNodeSubclassData<MemIntrinsicSDNode>(
7589         Opcode, dl.getIROrder(), VTList, MemVT, MMO));
7590     ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7591     ID.AddInteger(MMO->getFlags());
7592     void *IP = nullptr;
7593     if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7594       cast<MemIntrinsicSDNode>(E)->refineAlignment(MMO);
7595       return SDValue(E, 0);
7596     }
7597 
7598     N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
7599                                       VTList, MemVT, MMO);
7600     createOperands(N, Ops);
7601 
7602   CSEMap.InsertNode(N, IP);
7603   } else {
7604     N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
7605                                       VTList, MemVT, MMO);
7606     createOperands(N, Ops);
7607   }
7608   InsertNode(N);
7609   SDValue V(N, 0);
7610   NewSDValueDbgMsg(V, "Creating new node: ", this);
7611   return V;
7612 }
7613 
7614 SDValue SelectionDAG::getLifetimeNode(bool IsStart, const SDLoc &dl,
7615                                       SDValue Chain, int FrameIndex,
7616                                       int64_t Size, int64_t Offset) {
7617   const unsigned Opcode = IsStart ? ISD::LIFETIME_START : ISD::LIFETIME_END;
7618   const auto VTs = getVTList(MVT::Other);
7619   SDValue Ops[2] = {
7620       Chain,
7621       getFrameIndex(FrameIndex,
7622                     getTargetLoweringInfo().getFrameIndexTy(getDataLayout()),
7623                     true)};
7624 
7625   FoldingSetNodeID ID;
7626   AddNodeIDNode(ID, Opcode, VTs, Ops);
7627   ID.AddInteger(FrameIndex);
7628   ID.AddInteger(Size);
7629   ID.AddInteger(Offset);
7630   void *IP = nullptr;
7631   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
7632     return SDValue(E, 0);
7633 
7634   LifetimeSDNode *N = newSDNode<LifetimeSDNode>(
7635       Opcode, dl.getIROrder(), dl.getDebugLoc(), VTs, Size, Offset);
7636   createOperands(N, Ops);
7637   CSEMap.InsertNode(N, IP);
7638   InsertNode(N);
7639   SDValue V(N, 0);
7640   NewSDValueDbgMsg(V, "Creating new node: ", this);
7641   return V;
7642 }
7643 
7644 SDValue SelectionDAG::getPseudoProbeNode(const SDLoc &Dl, SDValue Chain,
7645                                          uint64_t Guid, uint64_t Index,
7646                                          uint32_t Attr) {
7647   const unsigned Opcode = ISD::PSEUDO_PROBE;
7648   const auto VTs = getVTList(MVT::Other);
7649   SDValue Ops[] = {Chain};
7650   FoldingSetNodeID ID;
7651   AddNodeIDNode(ID, Opcode, VTs, Ops);
7652   ID.AddInteger(Guid);
7653   ID.AddInteger(Index);
7654   void *IP = nullptr;
7655   if (SDNode *E = FindNodeOrInsertPos(ID, Dl, IP))
7656     return SDValue(E, 0);
7657 
7658   auto *N = newSDNode<PseudoProbeSDNode>(
7659       Opcode, Dl.getIROrder(), Dl.getDebugLoc(), VTs, Guid, Index, Attr);
7660   createOperands(N, Ops);
7661   CSEMap.InsertNode(N, IP);
7662   InsertNode(N);
7663   SDValue V(N, 0);
7664   NewSDValueDbgMsg(V, "Creating new node: ", this);
7665   return V;
7666 }
7667 
7668 /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a
7669 /// MachinePointerInfo record from it.  This is particularly useful because the
7670 /// code generator has many cases where it doesn't bother passing in a
7671 /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst".
7672 static MachinePointerInfo InferPointerInfo(const MachinePointerInfo &Info,
7673                                            SelectionDAG &DAG, SDValue Ptr,
7674                                            int64_t Offset = 0) {
7675   // If this is FI+Offset, we can model it.
7676   if (const FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr))
7677     return MachinePointerInfo::getFixedStack(DAG.getMachineFunction(),
7678                                              FI->getIndex(), Offset);
7679 
7680   // If this is (FI+Offset1)+Offset2, we can model it.
7681   if (Ptr.getOpcode() != ISD::ADD ||
7682       !isa<ConstantSDNode>(Ptr.getOperand(1)) ||
7683       !isa<FrameIndexSDNode>(Ptr.getOperand(0)))
7684     return Info;
7685 
7686   int FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
7687   return MachinePointerInfo::getFixedStack(
7688       DAG.getMachineFunction(), FI,
7689       Offset + cast<ConstantSDNode>(Ptr.getOperand(1))->getSExtValue());
7690 }
7691 
7692 /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a
7693 /// MachinePointerInfo record from it.  This is particularly useful because the
7694 /// code generator has many cases where it doesn't bother passing in a
7695 /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst".
7696 static MachinePointerInfo InferPointerInfo(const MachinePointerInfo &Info,
7697                                            SelectionDAG &DAG, SDValue Ptr,
7698                                            SDValue OffsetOp) {
7699   // If the 'Offset' value isn't a constant, we can't handle this.
7700   if (ConstantSDNode *OffsetNode = dyn_cast<ConstantSDNode>(OffsetOp))
7701     return InferPointerInfo(Info, DAG, Ptr, OffsetNode->getSExtValue());
7702   if (OffsetOp.isUndef())
7703     return InferPointerInfo(Info, DAG, Ptr);
7704   return Info;
7705 }
7706 
7707 SDValue SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType,
7708                               EVT VT, const SDLoc &dl, SDValue Chain,
7709                               SDValue Ptr, SDValue Offset,
7710                               MachinePointerInfo PtrInfo, EVT MemVT,
7711                               Align Alignment,
7712                               MachineMemOperand::Flags MMOFlags,
7713                               const AAMDNodes &AAInfo, const MDNode *Ranges) {
7714   assert(Chain.getValueType() == MVT::Other &&
7715         "Invalid chain type");
7716 
7717   MMOFlags |= MachineMemOperand::MOLoad;
7718   assert((MMOFlags & MachineMemOperand::MOStore) == 0);
7719   // If we don't have a PtrInfo, infer the trivial frame index case to simplify
7720   // clients.
7721   if (PtrInfo.V.isNull())
7722     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr, Offset);
7723 
7724   uint64_t Size = MemoryLocation::getSizeOrUnknown(MemVT.getStoreSize());
7725   MachineFunction &MF = getMachineFunction();
7726   MachineMemOperand *MMO = MF.getMachineMemOperand(PtrInfo, MMOFlags, Size,
7727                                                    Alignment, AAInfo, Ranges);
7728   return getLoad(AM, ExtType, VT, dl, Chain, Ptr, Offset, MemVT, MMO);
7729 }
7730 
7731 SDValue SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType,
7732                               EVT VT, const SDLoc &dl, SDValue Chain,
7733                               SDValue Ptr, SDValue Offset, EVT MemVT,
7734                               MachineMemOperand *MMO) {
7735   if (VT == MemVT) {
7736     ExtType = ISD::NON_EXTLOAD;
7737   } else if (ExtType == ISD::NON_EXTLOAD) {
7738     assert(VT == MemVT && "Non-extending load from different memory type!");
7739   } else {
7740     // Extending load.
7741     assert(MemVT.getScalarType().bitsLT(VT.getScalarType()) &&
7742            "Should only be an extending load, not truncating!");
7743     assert(VT.isInteger() == MemVT.isInteger() &&
7744            "Cannot convert from FP to Int or Int -> FP!");
7745     assert(VT.isVector() == MemVT.isVector() &&
7746            "Cannot use an ext load to convert to or from a vector!");
7747     assert((!VT.isVector() ||
7748             VT.getVectorElementCount() == MemVT.getVectorElementCount()) &&
7749            "Cannot use an ext load to change the number of vector elements!");
7750   }
7751 
7752   bool Indexed = AM != ISD::UNINDEXED;
7753   assert((Indexed || Offset.isUndef()) && "Unindexed load with an offset!");
7754 
7755   SDVTList VTs = Indexed ?
7756     getVTList(VT, Ptr.getValueType(), MVT::Other) : getVTList(VT, MVT::Other);
7757   SDValue Ops[] = { Chain, Ptr, Offset };
7758   FoldingSetNodeID ID;
7759   AddNodeIDNode(ID, ISD::LOAD, VTs, Ops);
7760   ID.AddInteger(MemVT.getRawBits());
7761   ID.AddInteger(getSyntheticNodeSubclassData<LoadSDNode>(
7762       dl.getIROrder(), VTs, AM, ExtType, MemVT, MMO));
7763   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7764   ID.AddInteger(MMO->getFlags());
7765   void *IP = nullptr;
7766   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7767     cast<LoadSDNode>(E)->refineAlignment(MMO);
7768     return SDValue(E, 0);
7769   }
7770   auto *N = newSDNode<LoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
7771                                   ExtType, MemVT, MMO);
7772   createOperands(N, Ops);
7773 
7774   CSEMap.InsertNode(N, IP);
7775   InsertNode(N);
7776   SDValue V(N, 0);
7777   NewSDValueDbgMsg(V, "Creating new node: ", this);
7778   return V;
7779 }
7780 
7781 SDValue SelectionDAG::getLoad(EVT VT, const SDLoc &dl, SDValue Chain,
7782                               SDValue Ptr, MachinePointerInfo PtrInfo,
7783                               MaybeAlign Alignment,
7784                               MachineMemOperand::Flags MMOFlags,
7785                               const AAMDNodes &AAInfo, const MDNode *Ranges) {
7786   SDValue Undef = getUNDEF(Ptr.getValueType());
7787   return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
7788                  PtrInfo, VT, Alignment, MMOFlags, AAInfo, Ranges);
7789 }
7790 
7791 SDValue SelectionDAG::getLoad(EVT VT, const SDLoc &dl, SDValue Chain,
7792                               SDValue Ptr, MachineMemOperand *MMO) {
7793   SDValue Undef = getUNDEF(Ptr.getValueType());
7794   return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
7795                  VT, MMO);
7796 }
7797 
7798 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl,
7799                                  EVT VT, SDValue Chain, SDValue Ptr,
7800                                  MachinePointerInfo PtrInfo, EVT MemVT,
7801                                  MaybeAlign Alignment,
7802                                  MachineMemOperand::Flags MMOFlags,
7803                                  const AAMDNodes &AAInfo) {
7804   SDValue Undef = getUNDEF(Ptr.getValueType());
7805   return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, PtrInfo,
7806                  MemVT, Alignment, MMOFlags, AAInfo);
7807 }
7808 
7809 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl,
7810                                  EVT VT, SDValue Chain, SDValue Ptr, EVT MemVT,
7811                                  MachineMemOperand *MMO) {
7812   SDValue Undef = getUNDEF(Ptr.getValueType());
7813   return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef,
7814                  MemVT, MMO);
7815 }
7816 
7817 SDValue SelectionDAG::getIndexedLoad(SDValue OrigLoad, const SDLoc &dl,
7818                                      SDValue Base, SDValue Offset,
7819                                      ISD::MemIndexedMode AM) {
7820   LoadSDNode *LD = cast<LoadSDNode>(OrigLoad);
7821   assert(LD->getOffset().isUndef() && "Load is already a indexed load!");
7822   // Don't propagate the invariant or dereferenceable flags.
7823   auto MMOFlags =
7824       LD->getMemOperand()->getFlags() &
7825       ~(MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable);
7826   return getLoad(AM, LD->getExtensionType(), OrigLoad.getValueType(), dl,
7827                  LD->getChain(), Base, Offset, LD->getPointerInfo(),
7828                  LD->getMemoryVT(), LD->getAlign(), MMOFlags, LD->getAAInfo());
7829 }
7830 
7831 SDValue SelectionDAG::getStore(SDValue Chain, const SDLoc &dl, SDValue Val,
7832                                SDValue Ptr, MachinePointerInfo PtrInfo,
7833                                Align Alignment,
7834                                MachineMemOperand::Flags MMOFlags,
7835                                const AAMDNodes &AAInfo) {
7836   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
7837 
7838   MMOFlags |= MachineMemOperand::MOStore;
7839   assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
7840 
7841   if (PtrInfo.V.isNull())
7842     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
7843 
7844   MachineFunction &MF = getMachineFunction();
7845   uint64_t Size =
7846       MemoryLocation::getSizeOrUnknown(Val.getValueType().getStoreSize());
7847   MachineMemOperand *MMO =
7848       MF.getMachineMemOperand(PtrInfo, MMOFlags, Size, Alignment, AAInfo);
7849   return getStore(Chain, dl, Val, Ptr, MMO);
7850 }
7851 
7852 SDValue SelectionDAG::getStore(SDValue Chain, const SDLoc &dl, SDValue Val,
7853                                SDValue Ptr, MachineMemOperand *MMO) {
7854   assert(Chain.getValueType() == MVT::Other &&
7855         "Invalid chain type");
7856   EVT VT = Val.getValueType();
7857   SDVTList VTs = getVTList(MVT::Other);
7858   SDValue Undef = getUNDEF(Ptr.getValueType());
7859   SDValue Ops[] = { Chain, Val, Ptr, Undef };
7860   FoldingSetNodeID ID;
7861   AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
7862   ID.AddInteger(VT.getRawBits());
7863   ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>(
7864       dl.getIROrder(), VTs, ISD::UNINDEXED, false, VT, MMO));
7865   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7866   ID.AddInteger(MMO->getFlags());
7867   void *IP = nullptr;
7868   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7869     cast<StoreSDNode>(E)->refineAlignment(MMO);
7870     return SDValue(E, 0);
7871   }
7872   auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
7873                                    ISD::UNINDEXED, false, VT, MMO);
7874   createOperands(N, Ops);
7875 
7876   CSEMap.InsertNode(N, IP);
7877   InsertNode(N);
7878   SDValue V(N, 0);
7879   NewSDValueDbgMsg(V, "Creating new node: ", this);
7880   return V;
7881 }
7882 
7883 SDValue SelectionDAG::getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val,
7884                                     SDValue Ptr, MachinePointerInfo PtrInfo,
7885                                     EVT SVT, Align Alignment,
7886                                     MachineMemOperand::Flags MMOFlags,
7887                                     const AAMDNodes &AAInfo) {
7888   assert(Chain.getValueType() == MVT::Other &&
7889         "Invalid chain type");
7890 
7891   MMOFlags |= MachineMemOperand::MOStore;
7892   assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
7893 
7894   if (PtrInfo.V.isNull())
7895     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
7896 
7897   MachineFunction &MF = getMachineFunction();
7898   MachineMemOperand *MMO = MF.getMachineMemOperand(
7899       PtrInfo, MMOFlags, MemoryLocation::getSizeOrUnknown(SVT.getStoreSize()),
7900       Alignment, AAInfo);
7901   return getTruncStore(Chain, dl, Val, Ptr, SVT, MMO);
7902 }
7903 
7904 SDValue SelectionDAG::getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val,
7905                                     SDValue Ptr, EVT SVT,
7906                                     MachineMemOperand *MMO) {
7907   EVT VT = Val.getValueType();
7908 
7909   assert(Chain.getValueType() == MVT::Other &&
7910         "Invalid chain type");
7911   if (VT == SVT)
7912     return getStore(Chain, dl, Val, Ptr, MMO);
7913 
7914   assert(SVT.getScalarType().bitsLT(VT.getScalarType()) &&
7915          "Should only be a truncating store, not extending!");
7916   assert(VT.isInteger() == SVT.isInteger() &&
7917          "Can't do FP-INT conversion!");
7918   assert(VT.isVector() == SVT.isVector() &&
7919          "Cannot use trunc store to convert to or from a vector!");
7920   assert((!VT.isVector() ||
7921           VT.getVectorElementCount() == SVT.getVectorElementCount()) &&
7922          "Cannot use trunc store to change the number of vector elements!");
7923 
7924   SDVTList VTs = getVTList(MVT::Other);
7925   SDValue Undef = getUNDEF(Ptr.getValueType());
7926   SDValue Ops[] = { Chain, Val, Ptr, Undef };
7927   FoldingSetNodeID ID;
7928   AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
7929   ID.AddInteger(SVT.getRawBits());
7930   ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>(
7931       dl.getIROrder(), VTs, ISD::UNINDEXED, true, SVT, MMO));
7932   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7933   ID.AddInteger(MMO->getFlags());
7934   void *IP = nullptr;
7935   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7936     cast<StoreSDNode>(E)->refineAlignment(MMO);
7937     return SDValue(E, 0);
7938   }
7939   auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
7940                                    ISD::UNINDEXED, true, SVT, MMO);
7941   createOperands(N, Ops);
7942 
7943   CSEMap.InsertNode(N, IP);
7944   InsertNode(N);
7945   SDValue V(N, 0);
7946   NewSDValueDbgMsg(V, "Creating new node: ", this);
7947   return V;
7948 }
7949 
7950 SDValue SelectionDAG::getIndexedStore(SDValue OrigStore, const SDLoc &dl,
7951                                       SDValue Base, SDValue Offset,
7952                                       ISD::MemIndexedMode AM) {
7953   StoreSDNode *ST = cast<StoreSDNode>(OrigStore);
7954   assert(ST->getOffset().isUndef() && "Store is already a indexed store!");
7955   SDVTList VTs = getVTList(Base.getValueType(), MVT::Other);
7956   SDValue Ops[] = { ST->getChain(), ST->getValue(), Base, Offset };
7957   FoldingSetNodeID ID;
7958   AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
7959   ID.AddInteger(ST->getMemoryVT().getRawBits());
7960   ID.AddInteger(ST->getRawSubclassData());
7961   ID.AddInteger(ST->getPointerInfo().getAddrSpace());
7962   ID.AddInteger(ST->getMemOperand()->getFlags());
7963   void *IP = nullptr;
7964   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
7965     return SDValue(E, 0);
7966 
7967   auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
7968                                    ST->isTruncatingStore(), ST->getMemoryVT(),
7969                                    ST->getMemOperand());
7970   createOperands(N, Ops);
7971 
7972   CSEMap.InsertNode(N, IP);
7973   InsertNode(N);
7974   SDValue V(N, 0);
7975   NewSDValueDbgMsg(V, "Creating new node: ", this);
7976   return V;
7977 }
7978 
7979 SDValue SelectionDAG::getLoadVP(
7980     ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, EVT VT, const SDLoc &dl,
7981     SDValue Chain, SDValue Ptr, SDValue Offset, SDValue Mask, SDValue EVL,
7982     MachinePointerInfo PtrInfo, EVT MemVT, Align Alignment,
7983     MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo,
7984     const MDNode *Ranges, bool IsExpanding) {
7985   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
7986 
7987   MMOFlags |= MachineMemOperand::MOLoad;
7988   assert((MMOFlags & MachineMemOperand::MOStore) == 0);
7989   // If we don't have a PtrInfo, infer the trivial frame index case to simplify
7990   // clients.
7991   if (PtrInfo.V.isNull())
7992     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr, Offset);
7993 
7994   uint64_t Size = MemoryLocation::getSizeOrUnknown(MemVT.getStoreSize());
7995   MachineFunction &MF = getMachineFunction();
7996   MachineMemOperand *MMO = MF.getMachineMemOperand(PtrInfo, MMOFlags, Size,
7997                                                    Alignment, AAInfo, Ranges);
7998   return getLoadVP(AM, ExtType, VT, dl, Chain, Ptr, Offset, Mask, EVL, MemVT,
7999                    MMO, IsExpanding);
8000 }
8001 
8002 SDValue SelectionDAG::getLoadVP(ISD::MemIndexedMode AM,
8003                                 ISD::LoadExtType ExtType, EVT VT,
8004                                 const SDLoc &dl, SDValue Chain, SDValue Ptr,
8005                                 SDValue Offset, SDValue Mask, SDValue EVL,
8006                                 EVT MemVT, MachineMemOperand *MMO,
8007                                 bool IsExpanding) {
8008   bool Indexed = AM != ISD::UNINDEXED;
8009   assert((Indexed || Offset.isUndef()) && "Unindexed load with an offset!");
8010 
8011   SDVTList VTs = Indexed ? getVTList(VT, Ptr.getValueType(), MVT::Other)
8012                          : getVTList(VT, MVT::Other);
8013   SDValue Ops[] = {Chain, Ptr, Offset, Mask, EVL};
8014   FoldingSetNodeID ID;
8015   AddNodeIDNode(ID, ISD::VP_LOAD, VTs, Ops);
8016   ID.AddInteger(VT.getRawBits());
8017   ID.AddInteger(getSyntheticNodeSubclassData<VPLoadSDNode>(
8018       dl.getIROrder(), VTs, AM, ExtType, IsExpanding, MemVT, MMO));
8019   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8020   ID.AddInteger(MMO->getFlags());
8021   void *IP = nullptr;
8022   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
8023     cast<VPLoadSDNode>(E)->refineAlignment(MMO);
8024     return SDValue(E, 0);
8025   }
8026   auto *N = newSDNode<VPLoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
8027                                     ExtType, IsExpanding, MemVT, MMO);
8028   createOperands(N, Ops);
8029 
8030   CSEMap.InsertNode(N, IP);
8031   InsertNode(N);
8032   SDValue V(N, 0);
8033   NewSDValueDbgMsg(V, "Creating new node: ", this);
8034   return V;
8035 }
8036 
8037 SDValue SelectionDAG::getLoadVP(EVT VT, const SDLoc &dl, SDValue Chain,
8038                                 SDValue Ptr, SDValue Mask, SDValue EVL,
8039                                 MachinePointerInfo PtrInfo,
8040                                 MaybeAlign Alignment,
8041                                 MachineMemOperand::Flags MMOFlags,
8042                                 const AAMDNodes &AAInfo, const MDNode *Ranges,
8043                                 bool IsExpanding) {
8044   SDValue Undef = getUNDEF(Ptr.getValueType());
8045   return getLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
8046                    Mask, EVL, PtrInfo, VT, Alignment, MMOFlags, AAInfo, Ranges,
8047                    IsExpanding);
8048 }
8049 
8050 SDValue SelectionDAG::getLoadVP(EVT VT, const SDLoc &dl, SDValue Chain,
8051                                 SDValue Ptr, SDValue Mask, SDValue EVL,
8052                                 MachineMemOperand *MMO, bool IsExpanding) {
8053   SDValue Undef = getUNDEF(Ptr.getValueType());
8054   return getLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
8055                    Mask, EVL, VT, MMO, IsExpanding);
8056 }
8057 
8058 SDValue SelectionDAG::getExtLoadVP(ISD::LoadExtType ExtType, const SDLoc &dl,
8059                                    EVT VT, SDValue Chain, SDValue Ptr,
8060                                    SDValue Mask, SDValue EVL,
8061                                    MachinePointerInfo PtrInfo, EVT MemVT,
8062                                    MaybeAlign Alignment,
8063                                    MachineMemOperand::Flags MMOFlags,
8064                                    const AAMDNodes &AAInfo, bool IsExpanding) {
8065   SDValue Undef = getUNDEF(Ptr.getValueType());
8066   return getLoadVP(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, Mask,
8067                    EVL, PtrInfo, MemVT, Alignment, MMOFlags, AAInfo, nullptr,
8068                    IsExpanding);
8069 }
8070 
8071 SDValue SelectionDAG::getExtLoadVP(ISD::LoadExtType ExtType, const SDLoc &dl,
8072                                    EVT VT, SDValue Chain, SDValue Ptr,
8073                                    SDValue Mask, SDValue EVL, EVT MemVT,
8074                                    MachineMemOperand *MMO, bool IsExpanding) {
8075   SDValue Undef = getUNDEF(Ptr.getValueType());
8076   return getLoadVP(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, Mask,
8077                    EVL, MemVT, MMO, IsExpanding);
8078 }
8079 
8080 SDValue SelectionDAG::getIndexedLoadVP(SDValue OrigLoad, const SDLoc &dl,
8081                                        SDValue Base, SDValue Offset,
8082                                        ISD::MemIndexedMode AM) {
8083   auto *LD = cast<VPLoadSDNode>(OrigLoad);
8084   assert(LD->getOffset().isUndef() && "Load is already a indexed load!");
8085   // Don't propagate the invariant or dereferenceable flags.
8086   auto MMOFlags =
8087       LD->getMemOperand()->getFlags() &
8088       ~(MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable);
8089   return getLoadVP(AM, LD->getExtensionType(), OrigLoad.getValueType(), dl,
8090                    LD->getChain(), Base, Offset, LD->getMask(),
8091                    LD->getVectorLength(), LD->getPointerInfo(),
8092                    LD->getMemoryVT(), LD->getAlign(), MMOFlags, LD->getAAInfo(),
8093                    nullptr, LD->isExpandingLoad());
8094 }
8095 
8096 SDValue SelectionDAG::getStoreVP(SDValue Chain, const SDLoc &dl, SDValue Val,
8097                                  SDValue Ptr, SDValue Offset, SDValue Mask,
8098                                  SDValue EVL, EVT MemVT, MachineMemOperand *MMO,
8099                                  ISD::MemIndexedMode AM, bool IsTruncating,
8100                                  bool IsCompressing) {
8101   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
8102   bool Indexed = AM != ISD::UNINDEXED;
8103   assert((Indexed || Offset.isUndef()) && "Unindexed vp_store with an offset!");
8104   SDVTList VTs = Indexed ? getVTList(Ptr.getValueType(), MVT::Other)
8105                          : getVTList(MVT::Other);
8106   SDValue Ops[] = {Chain, Val, Ptr, Offset, Mask, EVL};
8107   FoldingSetNodeID ID;
8108   AddNodeIDNode(ID, ISD::VP_STORE, VTs, Ops);
8109   ID.AddInteger(MemVT.getRawBits());
8110   ID.AddInteger(getSyntheticNodeSubclassData<VPStoreSDNode>(
8111       dl.getIROrder(), VTs, AM, IsTruncating, IsCompressing, MemVT, MMO));
8112   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8113   ID.AddInteger(MMO->getFlags());
8114   void *IP = nullptr;
8115   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
8116     cast<VPStoreSDNode>(E)->refineAlignment(MMO);
8117     return SDValue(E, 0);
8118   }
8119   auto *N = newSDNode<VPStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
8120                                      IsTruncating, IsCompressing, MemVT, MMO);
8121   createOperands(N, Ops);
8122 
8123   CSEMap.InsertNode(N, IP);
8124   InsertNode(N);
8125   SDValue V(N, 0);
8126   NewSDValueDbgMsg(V, "Creating new node: ", this);
8127   return V;
8128 }
8129 
8130 SDValue SelectionDAG::getTruncStoreVP(SDValue Chain, const SDLoc &dl,
8131                                       SDValue Val, SDValue Ptr, SDValue Mask,
8132                                       SDValue EVL, MachinePointerInfo PtrInfo,
8133                                       EVT SVT, Align Alignment,
8134                                       MachineMemOperand::Flags MMOFlags,
8135                                       const AAMDNodes &AAInfo,
8136                                       bool IsCompressing) {
8137   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
8138 
8139   MMOFlags |= MachineMemOperand::MOStore;
8140   assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
8141 
8142   if (PtrInfo.V.isNull())
8143     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
8144 
8145   MachineFunction &MF = getMachineFunction();
8146   MachineMemOperand *MMO = MF.getMachineMemOperand(
8147       PtrInfo, MMOFlags, MemoryLocation::getSizeOrUnknown(SVT.getStoreSize()),
8148       Alignment, AAInfo);
8149   return getTruncStoreVP(Chain, dl, Val, Ptr, Mask, EVL, SVT, MMO,
8150                          IsCompressing);
8151 }
8152 
8153 SDValue SelectionDAG::getTruncStoreVP(SDValue Chain, const SDLoc &dl,
8154                                       SDValue Val, SDValue Ptr, SDValue Mask,
8155                                       SDValue EVL, EVT SVT,
8156                                       MachineMemOperand *MMO,
8157                                       bool IsCompressing) {
8158   EVT VT = Val.getValueType();
8159 
8160   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
8161   if (VT == SVT)
8162     return getStoreVP(Chain, dl, Val, Ptr, getUNDEF(Ptr.getValueType()), Mask,
8163                       EVL, VT, MMO, ISD::UNINDEXED,
8164                       /*IsTruncating*/ false, IsCompressing);
8165 
8166   assert(SVT.getScalarType().bitsLT(VT.getScalarType()) &&
8167          "Should only be a truncating store, not extending!");
8168   assert(VT.isInteger() == SVT.isInteger() && "Can't do FP-INT conversion!");
8169   assert(VT.isVector() == SVT.isVector() &&
8170          "Cannot use trunc store to convert to or from a vector!");
8171   assert((!VT.isVector() ||
8172           VT.getVectorElementCount() == SVT.getVectorElementCount()) &&
8173          "Cannot use trunc store to change the number of vector elements!");
8174 
8175   SDVTList VTs = getVTList(MVT::Other);
8176   SDValue Undef = getUNDEF(Ptr.getValueType());
8177   SDValue Ops[] = {Chain, Val, Ptr, Undef, Mask, EVL};
8178   FoldingSetNodeID ID;
8179   AddNodeIDNode(ID, ISD::VP_STORE, VTs, Ops);
8180   ID.AddInteger(SVT.getRawBits());
8181   ID.AddInteger(getSyntheticNodeSubclassData<VPStoreSDNode>(
8182       dl.getIROrder(), VTs, ISD::UNINDEXED, true, IsCompressing, SVT, MMO));
8183   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8184   ID.AddInteger(MMO->getFlags());
8185   void *IP = nullptr;
8186   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
8187     cast<VPStoreSDNode>(E)->refineAlignment(MMO);
8188     return SDValue(E, 0);
8189   }
8190   auto *N =
8191       newSDNode<VPStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
8192                                ISD::UNINDEXED, true, IsCompressing, SVT, MMO);
8193   createOperands(N, Ops);
8194 
8195   CSEMap.InsertNode(N, IP);
8196   InsertNode(N);
8197   SDValue V(N, 0);
8198   NewSDValueDbgMsg(V, "Creating new node: ", this);
8199   return V;
8200 }
8201 
8202 SDValue SelectionDAG::getIndexedStoreVP(SDValue OrigStore, const SDLoc &dl,
8203                                         SDValue Base, SDValue Offset,
8204                                         ISD::MemIndexedMode AM) {
8205   auto *ST = cast<VPStoreSDNode>(OrigStore);
8206   assert(ST->getOffset().isUndef() && "Store is already an indexed store!");
8207   SDVTList VTs = getVTList(Base.getValueType(), MVT::Other);
8208   SDValue Ops[] = {ST->getChain(), ST->getValue(), Base,
8209                    Offset,         ST->getMask(),  ST->getVectorLength()};
8210   FoldingSetNodeID ID;
8211   AddNodeIDNode(ID, ISD::VP_STORE, VTs, Ops);
8212   ID.AddInteger(ST->getMemoryVT().getRawBits());
8213   ID.AddInteger(ST->getRawSubclassData());
8214   ID.AddInteger(ST->getPointerInfo().getAddrSpace());
8215   ID.AddInteger(ST->getMemOperand()->getFlags());
8216   void *IP = nullptr;
8217   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
8218     return SDValue(E, 0);
8219 
8220   auto *N = newSDNode<VPStoreSDNode>(
8221       dl.getIROrder(), dl.getDebugLoc(), VTs, AM, ST->isTruncatingStore(),
8222       ST->isCompressingStore(), ST->getMemoryVT(), ST->getMemOperand());
8223   createOperands(N, Ops);
8224 
8225   CSEMap.InsertNode(N, IP);
8226   InsertNode(N);
8227   SDValue V(N, 0);
8228   NewSDValueDbgMsg(V, "Creating new node: ", this);
8229   return V;
8230 }
8231 
8232 SDValue SelectionDAG::getStridedLoadVP(
8233     ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, EVT VT, const SDLoc &DL,
8234     SDValue Chain, SDValue Ptr, SDValue Offset, SDValue Stride, SDValue Mask,
8235     SDValue EVL, MachinePointerInfo PtrInfo, EVT MemVT, Align Alignment,
8236     MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo,
8237     const MDNode *Ranges, bool IsExpanding) {
8238   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
8239 
8240   MMOFlags |= MachineMemOperand::MOLoad;
8241   assert((MMOFlags & MachineMemOperand::MOStore) == 0);
8242   // If we don't have a PtrInfo, infer the trivial frame index case to simplify
8243   // clients.
8244   if (PtrInfo.V.isNull())
8245     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr, Offset);
8246 
8247   uint64_t Size = MemoryLocation::UnknownSize;
8248   MachineFunction &MF = getMachineFunction();
8249   MachineMemOperand *MMO = MF.getMachineMemOperand(PtrInfo, MMOFlags, Size,
8250                                                    Alignment, AAInfo, Ranges);
8251   return getStridedLoadVP(AM, ExtType, VT, DL, Chain, Ptr, Offset, Stride, Mask,
8252                           EVL, MemVT, MMO, IsExpanding);
8253 }
8254 
8255 SDValue SelectionDAG::getStridedLoadVP(
8256     ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, EVT VT, const SDLoc &DL,
8257     SDValue Chain, SDValue Ptr, SDValue Offset, SDValue Stride, SDValue Mask,
8258     SDValue EVL, EVT MemVT, MachineMemOperand *MMO, bool IsExpanding) {
8259   bool Indexed = AM != ISD::UNINDEXED;
8260   assert((Indexed || Offset.isUndef()) && "Unindexed load with an offset!");
8261 
8262   SDValue Ops[] = {Chain, Ptr, Offset, Stride, Mask, EVL};
8263   SDVTList VTs = Indexed ? getVTList(VT, Ptr.getValueType(), MVT::Other)
8264                          : getVTList(VT, MVT::Other);
8265   FoldingSetNodeID ID;
8266   AddNodeIDNode(ID, ISD::EXPERIMENTAL_VP_STRIDED_LOAD, VTs, Ops);
8267   ID.AddInteger(VT.getRawBits());
8268   ID.AddInteger(getSyntheticNodeSubclassData<VPStridedLoadSDNode>(
8269       DL.getIROrder(), VTs, AM, ExtType, IsExpanding, MemVT, MMO));
8270   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8271 
8272   void *IP = nullptr;
8273   if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
8274     cast<VPStridedLoadSDNode>(E)->refineAlignment(MMO);
8275     return SDValue(E, 0);
8276   }
8277 
8278   auto *N =
8279       newSDNode<VPStridedLoadSDNode>(DL.getIROrder(), DL.getDebugLoc(), VTs, AM,
8280                                      ExtType, IsExpanding, MemVT, MMO);
8281   createOperands(N, Ops);
8282   CSEMap.InsertNode(N, IP);
8283   InsertNode(N);
8284   SDValue V(N, 0);
8285   NewSDValueDbgMsg(V, "Creating new node: ", this);
8286   return V;
8287 }
8288 
8289 SDValue SelectionDAG::getStridedLoadVP(
8290     EVT VT, const SDLoc &DL, SDValue Chain, SDValue Ptr, SDValue Stride,
8291     SDValue Mask, SDValue EVL, MachinePointerInfo PtrInfo, MaybeAlign Alignment,
8292     MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo,
8293     const MDNode *Ranges, bool IsExpanding) {
8294   SDValue Undef = getUNDEF(Ptr.getValueType());
8295   return getStridedLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, DL, Chain, Ptr,
8296                           Undef, Stride, Mask, EVL, PtrInfo, VT, Alignment,
8297                           MMOFlags, AAInfo, Ranges, IsExpanding);
8298 }
8299 
8300 SDValue SelectionDAG::getStridedLoadVP(EVT VT, const SDLoc &DL, SDValue Chain,
8301                                        SDValue Ptr, SDValue Stride,
8302                                        SDValue Mask, SDValue EVL,
8303                                        MachineMemOperand *MMO,
8304                                        bool IsExpanding) {
8305   SDValue Undef = getUNDEF(Ptr.getValueType());
8306   return getStridedLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, DL, Chain, Ptr,
8307                           Undef, Stride, Mask, EVL, VT, MMO, IsExpanding);
8308 }
8309 
8310 SDValue SelectionDAG::getExtStridedLoadVP(
8311     ISD::LoadExtType ExtType, const SDLoc &DL, EVT VT, SDValue Chain,
8312     SDValue Ptr, SDValue Stride, SDValue Mask, SDValue EVL,
8313     MachinePointerInfo PtrInfo, EVT MemVT, MaybeAlign Alignment,
8314     MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo,
8315     bool IsExpanding) {
8316   SDValue Undef = getUNDEF(Ptr.getValueType());
8317   return getStridedLoadVP(ISD::UNINDEXED, ExtType, VT, DL, Chain, Ptr, Undef,
8318                           Stride, Mask, EVL, PtrInfo, MemVT, Alignment,
8319                           MMOFlags, AAInfo, nullptr, IsExpanding);
8320 }
8321 
8322 SDValue SelectionDAG::getExtStridedLoadVP(
8323     ISD::LoadExtType ExtType, const SDLoc &DL, EVT VT, SDValue Chain,
8324     SDValue Ptr, SDValue Stride, SDValue Mask, SDValue EVL, EVT MemVT,
8325     MachineMemOperand *MMO, bool IsExpanding) {
8326   SDValue Undef = getUNDEF(Ptr.getValueType());
8327   return getStridedLoadVP(ISD::UNINDEXED, ExtType, VT, DL, Chain, Ptr, Undef,
8328                           Stride, Mask, EVL, MemVT, MMO, IsExpanding);
8329 }
8330 
8331 SDValue SelectionDAG::getIndexedStridedLoadVP(SDValue OrigLoad, const SDLoc &DL,
8332                                               SDValue Base, SDValue Offset,
8333                                               ISD::MemIndexedMode AM) {
8334   auto *SLD = cast<VPStridedLoadSDNode>(OrigLoad);
8335   assert(SLD->getOffset().isUndef() &&
8336          "Strided load is already a indexed load!");
8337   // Don't propagate the invariant or dereferenceable flags.
8338   auto MMOFlags =
8339       SLD->getMemOperand()->getFlags() &
8340       ~(MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable);
8341   return getStridedLoadVP(
8342       AM, SLD->getExtensionType(), OrigLoad.getValueType(), DL, SLD->getChain(),
8343       Base, Offset, SLD->getStride(), SLD->getMask(), SLD->getVectorLength(),
8344       SLD->getPointerInfo(), SLD->getMemoryVT(), SLD->getAlign(), MMOFlags,
8345       SLD->getAAInfo(), nullptr, SLD->isExpandingLoad());
8346 }
8347 
8348 SDValue SelectionDAG::getStridedStoreVP(SDValue Chain, const SDLoc &DL,
8349                                         SDValue Val, SDValue Ptr,
8350                                         SDValue Offset, SDValue Stride,
8351                                         SDValue Mask, SDValue EVL, EVT MemVT,
8352                                         MachineMemOperand *MMO,
8353                                         ISD::MemIndexedMode AM,
8354                                         bool IsTruncating, bool IsCompressing) {
8355   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
8356   bool Indexed = AM != ISD::UNINDEXED;
8357   assert((Indexed || Offset.isUndef()) && "Unindexed vp_store with an offset!");
8358   SDVTList VTs = Indexed ? getVTList(Ptr.getValueType(), MVT::Other)
8359                          : getVTList(MVT::Other);
8360   SDValue Ops[] = {Chain, Val, Ptr, Offset, Stride, Mask, EVL};
8361   FoldingSetNodeID ID;
8362   AddNodeIDNode(ID, ISD::EXPERIMENTAL_VP_STRIDED_STORE, VTs, Ops);
8363   ID.AddInteger(MemVT.getRawBits());
8364   ID.AddInteger(getSyntheticNodeSubclassData<VPStridedStoreSDNode>(
8365       DL.getIROrder(), VTs, AM, IsTruncating, IsCompressing, MemVT, MMO));
8366   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8367   void *IP = nullptr;
8368   if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
8369     cast<VPStridedStoreSDNode>(E)->refineAlignment(MMO);
8370     return SDValue(E, 0);
8371   }
8372   auto *N = newSDNode<VPStridedStoreSDNode>(DL.getIROrder(), DL.getDebugLoc(),
8373                                             VTs, AM, IsTruncating,
8374                                             IsCompressing, MemVT, MMO);
8375   createOperands(N, Ops);
8376 
8377   CSEMap.InsertNode(N, IP);
8378   InsertNode(N);
8379   SDValue V(N, 0);
8380   NewSDValueDbgMsg(V, "Creating new node: ", this);
8381   return V;
8382 }
8383 
8384 SDValue SelectionDAG::getTruncStridedStoreVP(
8385     SDValue Chain, const SDLoc &DL, SDValue Val, SDValue Ptr, SDValue Stride,
8386     SDValue Mask, SDValue EVL, MachinePointerInfo PtrInfo, EVT SVT,
8387     Align Alignment, MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo,
8388     bool IsCompressing) {
8389   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
8390 
8391   MMOFlags |= MachineMemOperand::MOStore;
8392   assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
8393 
8394   if (PtrInfo.V.isNull())
8395     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
8396 
8397   MachineFunction &MF = getMachineFunction();
8398   MachineMemOperand *MMO = MF.getMachineMemOperand(
8399       PtrInfo, MMOFlags, MemoryLocation::UnknownSize, Alignment, AAInfo);
8400   return getTruncStridedStoreVP(Chain, DL, Val, Ptr, Stride, Mask, EVL, SVT,
8401                                 MMO, IsCompressing);
8402 }
8403 
8404 SDValue SelectionDAG::getTruncStridedStoreVP(SDValue Chain, const SDLoc &DL,
8405                                              SDValue Val, SDValue Ptr,
8406                                              SDValue Stride, SDValue Mask,
8407                                              SDValue EVL, EVT SVT,
8408                                              MachineMemOperand *MMO,
8409                                              bool IsCompressing) {
8410   EVT VT = Val.getValueType();
8411 
8412   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
8413   if (VT == SVT)
8414     return getStridedStoreVP(Chain, DL, Val, Ptr, getUNDEF(Ptr.getValueType()),
8415                              Stride, Mask, EVL, VT, MMO, ISD::UNINDEXED,
8416                              /*IsTruncating*/ false, IsCompressing);
8417 
8418   assert(SVT.getScalarType().bitsLT(VT.getScalarType()) &&
8419          "Should only be a truncating store, not extending!");
8420   assert(VT.isInteger() == SVT.isInteger() && "Can't do FP-INT conversion!");
8421   assert(VT.isVector() == SVT.isVector() &&
8422          "Cannot use trunc store to convert to or from a vector!");
8423   assert((!VT.isVector() ||
8424           VT.getVectorElementCount() == SVT.getVectorElementCount()) &&
8425          "Cannot use trunc store to change the number of vector elements!");
8426 
8427   SDVTList VTs = getVTList(MVT::Other);
8428   SDValue Undef = getUNDEF(Ptr.getValueType());
8429   SDValue Ops[] = {Chain, Val, Ptr, Undef, Stride, Mask, EVL};
8430   FoldingSetNodeID ID;
8431   AddNodeIDNode(ID, ISD::EXPERIMENTAL_VP_STRIDED_STORE, VTs, Ops);
8432   ID.AddInteger(SVT.getRawBits());
8433   ID.AddInteger(getSyntheticNodeSubclassData<VPStridedStoreSDNode>(
8434       DL.getIROrder(), VTs, ISD::UNINDEXED, true, IsCompressing, SVT, MMO));
8435   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8436   void *IP = nullptr;
8437   if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
8438     cast<VPStridedStoreSDNode>(E)->refineAlignment(MMO);
8439     return SDValue(E, 0);
8440   }
8441   auto *N = newSDNode<VPStridedStoreSDNode>(DL.getIROrder(), DL.getDebugLoc(),
8442                                             VTs, ISD::UNINDEXED, true,
8443                                             IsCompressing, SVT, MMO);
8444   createOperands(N, Ops);
8445 
8446   CSEMap.InsertNode(N, IP);
8447   InsertNode(N);
8448   SDValue V(N, 0);
8449   NewSDValueDbgMsg(V, "Creating new node: ", this);
8450   return V;
8451 }
8452 
8453 SDValue SelectionDAG::getIndexedStridedStoreVP(SDValue OrigStore,
8454                                                const SDLoc &DL, SDValue Base,
8455                                                SDValue Offset,
8456                                                ISD::MemIndexedMode AM) {
8457   auto *SST = cast<VPStridedStoreSDNode>(OrigStore);
8458   assert(SST->getOffset().isUndef() &&
8459          "Strided store is already an indexed store!");
8460   SDVTList VTs = getVTList(Base.getValueType(), MVT::Other);
8461   SDValue Ops[] = {
8462       SST->getChain(), SST->getValue(),       Base, Offset, SST->getStride(),
8463       SST->getMask(),  SST->getVectorLength()};
8464   FoldingSetNodeID ID;
8465   AddNodeIDNode(ID, ISD::EXPERIMENTAL_VP_STRIDED_STORE, VTs, Ops);
8466   ID.AddInteger(SST->getMemoryVT().getRawBits());
8467   ID.AddInteger(SST->getRawSubclassData());
8468   ID.AddInteger(SST->getPointerInfo().getAddrSpace());
8469   void *IP = nullptr;
8470   if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
8471     return SDValue(E, 0);
8472 
8473   auto *N = newSDNode<VPStridedStoreSDNode>(
8474       DL.getIROrder(), DL.getDebugLoc(), VTs, AM, SST->isTruncatingStore(),
8475       SST->isCompressingStore(), SST->getMemoryVT(), SST->getMemOperand());
8476   createOperands(N, Ops);
8477 
8478   CSEMap.InsertNode(N, IP);
8479   InsertNode(N);
8480   SDValue V(N, 0);
8481   NewSDValueDbgMsg(V, "Creating new node: ", this);
8482   return V;
8483 }
8484 
8485 SDValue SelectionDAG::getGatherVP(SDVTList VTs, EVT VT, const SDLoc &dl,
8486                                   ArrayRef<SDValue> Ops, MachineMemOperand *MMO,
8487                                   ISD::MemIndexType IndexType) {
8488   assert(Ops.size() == 6 && "Incompatible number of operands");
8489 
8490   FoldingSetNodeID ID;
8491   AddNodeIDNode(ID, ISD::VP_GATHER, VTs, Ops);
8492   ID.AddInteger(VT.getRawBits());
8493   ID.AddInteger(getSyntheticNodeSubclassData<VPGatherSDNode>(
8494       dl.getIROrder(), VTs, VT, MMO, IndexType));
8495   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8496   ID.AddInteger(MMO->getFlags());
8497   void *IP = nullptr;
8498   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
8499     cast<VPGatherSDNode>(E)->refineAlignment(MMO);
8500     return SDValue(E, 0);
8501   }
8502 
8503   auto *N = newSDNode<VPGatherSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
8504                                       VT, MMO, IndexType);
8505   createOperands(N, Ops);
8506 
8507   assert(N->getMask().getValueType().getVectorElementCount() ==
8508              N->getValueType(0).getVectorElementCount() &&
8509          "Vector width mismatch between mask and data");
8510   assert(N->getIndex().getValueType().getVectorElementCount().isScalable() ==
8511              N->getValueType(0).getVectorElementCount().isScalable() &&
8512          "Scalable flags of index and data do not match");
8513   assert(ElementCount::isKnownGE(
8514              N->getIndex().getValueType().getVectorElementCount(),
8515              N->getValueType(0).getVectorElementCount()) &&
8516          "Vector width mismatch between index and data");
8517   assert(isa<ConstantSDNode>(N->getScale()) &&
8518          cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() &&
8519          "Scale should be a constant power of 2");
8520 
8521   CSEMap.InsertNode(N, IP);
8522   InsertNode(N);
8523   SDValue V(N, 0);
8524   NewSDValueDbgMsg(V, "Creating new node: ", this);
8525   return V;
8526 }
8527 
8528 SDValue SelectionDAG::getScatterVP(SDVTList VTs, EVT VT, const SDLoc &dl,
8529                                    ArrayRef<SDValue> Ops,
8530                                    MachineMemOperand *MMO,
8531                                    ISD::MemIndexType IndexType) {
8532   assert(Ops.size() == 7 && "Incompatible number of operands");
8533 
8534   FoldingSetNodeID ID;
8535   AddNodeIDNode(ID, ISD::VP_SCATTER, VTs, Ops);
8536   ID.AddInteger(VT.getRawBits());
8537   ID.AddInteger(getSyntheticNodeSubclassData<VPScatterSDNode>(
8538       dl.getIROrder(), VTs, VT, MMO, IndexType));
8539   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8540   ID.AddInteger(MMO->getFlags());
8541   void *IP = nullptr;
8542   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
8543     cast<VPScatterSDNode>(E)->refineAlignment(MMO);
8544     return SDValue(E, 0);
8545   }
8546   auto *N = newSDNode<VPScatterSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
8547                                        VT, MMO, IndexType);
8548   createOperands(N, Ops);
8549 
8550   assert(N->getMask().getValueType().getVectorElementCount() ==
8551              N->getValue().getValueType().getVectorElementCount() &&
8552          "Vector width mismatch between mask and data");
8553   assert(
8554       N->getIndex().getValueType().getVectorElementCount().isScalable() ==
8555           N->getValue().getValueType().getVectorElementCount().isScalable() &&
8556       "Scalable flags of index and data do not match");
8557   assert(ElementCount::isKnownGE(
8558              N->getIndex().getValueType().getVectorElementCount(),
8559              N->getValue().getValueType().getVectorElementCount()) &&
8560          "Vector width mismatch between index and data");
8561   assert(isa<ConstantSDNode>(N->getScale()) &&
8562          cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() &&
8563          "Scale should be a constant power of 2");
8564 
8565   CSEMap.InsertNode(N, IP);
8566   InsertNode(N);
8567   SDValue V(N, 0);
8568   NewSDValueDbgMsg(V, "Creating new node: ", this);
8569   return V;
8570 }
8571 
8572 SDValue SelectionDAG::getMaskedLoad(EVT VT, const SDLoc &dl, SDValue Chain,
8573                                     SDValue Base, SDValue Offset, SDValue Mask,
8574                                     SDValue PassThru, EVT MemVT,
8575                                     MachineMemOperand *MMO,
8576                                     ISD::MemIndexedMode AM,
8577                                     ISD::LoadExtType ExtTy, bool isExpanding) {
8578   bool Indexed = AM != ISD::UNINDEXED;
8579   assert((Indexed || Offset.isUndef()) &&
8580          "Unindexed masked load with an offset!");
8581   SDVTList VTs = Indexed ? getVTList(VT, Base.getValueType(), MVT::Other)
8582                          : getVTList(VT, MVT::Other);
8583   SDValue Ops[] = {Chain, Base, Offset, Mask, PassThru};
8584   FoldingSetNodeID ID;
8585   AddNodeIDNode(ID, ISD::MLOAD, VTs, Ops);
8586   ID.AddInteger(MemVT.getRawBits());
8587   ID.AddInteger(getSyntheticNodeSubclassData<MaskedLoadSDNode>(
8588       dl.getIROrder(), VTs, AM, ExtTy, isExpanding, MemVT, MMO));
8589   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8590   ID.AddInteger(MMO->getFlags());
8591   void *IP = nullptr;
8592   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
8593     cast<MaskedLoadSDNode>(E)->refineAlignment(MMO);
8594     return SDValue(E, 0);
8595   }
8596   auto *N = newSDNode<MaskedLoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
8597                                         AM, ExtTy, isExpanding, MemVT, MMO);
8598   createOperands(N, Ops);
8599 
8600   CSEMap.InsertNode(N, IP);
8601   InsertNode(N);
8602   SDValue V(N, 0);
8603   NewSDValueDbgMsg(V, "Creating new node: ", this);
8604   return V;
8605 }
8606 
8607 SDValue SelectionDAG::getIndexedMaskedLoad(SDValue OrigLoad, const SDLoc &dl,
8608                                            SDValue Base, SDValue Offset,
8609                                            ISD::MemIndexedMode AM) {
8610   MaskedLoadSDNode *LD = cast<MaskedLoadSDNode>(OrigLoad);
8611   assert(LD->getOffset().isUndef() && "Masked load is already a indexed load!");
8612   return getMaskedLoad(OrigLoad.getValueType(), dl, LD->getChain(), Base,
8613                        Offset, LD->getMask(), LD->getPassThru(),
8614                        LD->getMemoryVT(), LD->getMemOperand(), AM,
8615                        LD->getExtensionType(), LD->isExpandingLoad());
8616 }
8617 
8618 SDValue SelectionDAG::getMaskedStore(SDValue Chain, const SDLoc &dl,
8619                                      SDValue Val, SDValue Base, SDValue Offset,
8620                                      SDValue Mask, EVT MemVT,
8621                                      MachineMemOperand *MMO,
8622                                      ISD::MemIndexedMode AM, bool IsTruncating,
8623                                      bool IsCompressing) {
8624   assert(Chain.getValueType() == MVT::Other &&
8625         "Invalid chain type");
8626   bool Indexed = AM != ISD::UNINDEXED;
8627   assert((Indexed || Offset.isUndef()) &&
8628          "Unindexed masked store with an offset!");
8629   SDVTList VTs = Indexed ? getVTList(Base.getValueType(), MVT::Other)
8630                          : getVTList(MVT::Other);
8631   SDValue Ops[] = {Chain, Val, Base, Offset, Mask};
8632   FoldingSetNodeID ID;
8633   AddNodeIDNode(ID, ISD::MSTORE, VTs, Ops);
8634   ID.AddInteger(MemVT.getRawBits());
8635   ID.AddInteger(getSyntheticNodeSubclassData<MaskedStoreSDNode>(
8636       dl.getIROrder(), VTs, AM, IsTruncating, IsCompressing, MemVT, MMO));
8637   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8638   ID.AddInteger(MMO->getFlags());
8639   void *IP = nullptr;
8640   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
8641     cast<MaskedStoreSDNode>(E)->refineAlignment(MMO);
8642     return SDValue(E, 0);
8643   }
8644   auto *N =
8645       newSDNode<MaskedStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
8646                                    IsTruncating, IsCompressing, MemVT, MMO);
8647   createOperands(N, Ops);
8648 
8649   CSEMap.InsertNode(N, IP);
8650   InsertNode(N);
8651   SDValue V(N, 0);
8652   NewSDValueDbgMsg(V, "Creating new node: ", this);
8653   return V;
8654 }
8655 
8656 SDValue SelectionDAG::getIndexedMaskedStore(SDValue OrigStore, const SDLoc &dl,
8657                                             SDValue Base, SDValue Offset,
8658                                             ISD::MemIndexedMode AM) {
8659   MaskedStoreSDNode *ST = cast<MaskedStoreSDNode>(OrigStore);
8660   assert(ST->getOffset().isUndef() &&
8661          "Masked store is already a indexed store!");
8662   return getMaskedStore(ST->getChain(), dl, ST->getValue(), Base, Offset,
8663                         ST->getMask(), ST->getMemoryVT(), ST->getMemOperand(),
8664                         AM, ST->isTruncatingStore(), ST->isCompressingStore());
8665 }
8666 
8667 SDValue SelectionDAG::getMaskedGather(SDVTList VTs, EVT MemVT, const SDLoc &dl,
8668                                       ArrayRef<SDValue> Ops,
8669                                       MachineMemOperand *MMO,
8670                                       ISD::MemIndexType IndexType,
8671                                       ISD::LoadExtType ExtTy) {
8672   assert(Ops.size() == 6 && "Incompatible number of operands");
8673 
8674   FoldingSetNodeID ID;
8675   AddNodeIDNode(ID, ISD::MGATHER, VTs, Ops);
8676   ID.AddInteger(MemVT.getRawBits());
8677   ID.AddInteger(getSyntheticNodeSubclassData<MaskedGatherSDNode>(
8678       dl.getIROrder(), VTs, MemVT, MMO, IndexType, ExtTy));
8679   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8680   ID.AddInteger(MMO->getFlags());
8681   void *IP = nullptr;
8682   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
8683     cast<MaskedGatherSDNode>(E)->refineAlignment(MMO);
8684     return SDValue(E, 0);
8685   }
8686 
8687   auto *N = newSDNode<MaskedGatherSDNode>(dl.getIROrder(), dl.getDebugLoc(),
8688                                           VTs, MemVT, MMO, IndexType, ExtTy);
8689   createOperands(N, Ops);
8690 
8691   assert(N->getPassThru().getValueType() == N->getValueType(0) &&
8692          "Incompatible type of the PassThru value in MaskedGatherSDNode");
8693   assert(N->getMask().getValueType().getVectorElementCount() ==
8694              N->getValueType(0).getVectorElementCount() &&
8695          "Vector width mismatch between mask and data");
8696   assert(N->getIndex().getValueType().getVectorElementCount().isScalable() ==
8697              N->getValueType(0).getVectorElementCount().isScalable() &&
8698          "Scalable flags of index and data do not match");
8699   assert(ElementCount::isKnownGE(
8700              N->getIndex().getValueType().getVectorElementCount(),
8701              N->getValueType(0).getVectorElementCount()) &&
8702          "Vector width mismatch between index and data");
8703   assert(isa<ConstantSDNode>(N->getScale()) &&
8704          cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() &&
8705          "Scale should be a constant power of 2");
8706 
8707   CSEMap.InsertNode(N, IP);
8708   InsertNode(N);
8709   SDValue V(N, 0);
8710   NewSDValueDbgMsg(V, "Creating new node: ", this);
8711   return V;
8712 }
8713 
8714 SDValue SelectionDAG::getMaskedScatter(SDVTList VTs, EVT MemVT, const SDLoc &dl,
8715                                        ArrayRef<SDValue> Ops,
8716                                        MachineMemOperand *MMO,
8717                                        ISD::MemIndexType IndexType,
8718                                        bool IsTrunc) {
8719   assert(Ops.size() == 6 && "Incompatible number of operands");
8720 
8721   FoldingSetNodeID ID;
8722   AddNodeIDNode(ID, ISD::MSCATTER, VTs, Ops);
8723   ID.AddInteger(MemVT.getRawBits());
8724   ID.AddInteger(getSyntheticNodeSubclassData<MaskedScatterSDNode>(
8725       dl.getIROrder(), VTs, MemVT, MMO, IndexType, IsTrunc));
8726   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8727   ID.AddInteger(MMO->getFlags());
8728   void *IP = nullptr;
8729   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
8730     cast<MaskedScatterSDNode>(E)->refineAlignment(MMO);
8731     return SDValue(E, 0);
8732   }
8733 
8734   auto *N = newSDNode<MaskedScatterSDNode>(dl.getIROrder(), dl.getDebugLoc(),
8735                                            VTs, MemVT, MMO, IndexType, IsTrunc);
8736   createOperands(N, Ops);
8737 
8738   assert(N->getMask().getValueType().getVectorElementCount() ==
8739              N->getValue().getValueType().getVectorElementCount() &&
8740          "Vector width mismatch between mask and data");
8741   assert(
8742       N->getIndex().getValueType().getVectorElementCount().isScalable() ==
8743           N->getValue().getValueType().getVectorElementCount().isScalable() &&
8744       "Scalable flags of index and data do not match");
8745   assert(ElementCount::isKnownGE(
8746              N->getIndex().getValueType().getVectorElementCount(),
8747              N->getValue().getValueType().getVectorElementCount()) &&
8748          "Vector width mismatch between index and data");
8749   assert(isa<ConstantSDNode>(N->getScale()) &&
8750          cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() &&
8751          "Scale should be a constant power of 2");
8752 
8753   CSEMap.InsertNode(N, IP);
8754   InsertNode(N);
8755   SDValue V(N, 0);
8756   NewSDValueDbgMsg(V, "Creating new node: ", this);
8757   return V;
8758 }
8759 
8760 SDValue SelectionDAG::simplifySelect(SDValue Cond, SDValue T, SDValue F) {
8761   // select undef, T, F --> T (if T is a constant), otherwise F
8762   // select, ?, undef, F --> F
8763   // select, ?, T, undef --> T
8764   if (Cond.isUndef())
8765     return isConstantValueOfAnyType(T) ? T : F;
8766   if (T.isUndef())
8767     return F;
8768   if (F.isUndef())
8769     return T;
8770 
8771   // select true, T, F --> T
8772   // select false, T, F --> F
8773   if (auto *CondC = dyn_cast<ConstantSDNode>(Cond))
8774     return CondC->isZero() ? F : T;
8775 
8776   // TODO: This should simplify VSELECT with constant condition using something
8777   // like this (but check boolean contents to be complete?):
8778   //  if (ISD::isBuildVectorAllOnes(Cond.getNode()))
8779   //    return T;
8780   //  if (ISD::isBuildVectorAllZeros(Cond.getNode()))
8781   //    return F;
8782 
8783   // select ?, T, T --> T
8784   if (T == F)
8785     return T;
8786 
8787   return SDValue();
8788 }
8789 
8790 SDValue SelectionDAG::simplifyShift(SDValue X, SDValue Y) {
8791   // shift undef, Y --> 0 (can always assume that the undef value is 0)
8792   if (X.isUndef())
8793     return getConstant(0, SDLoc(X.getNode()), X.getValueType());
8794   // shift X, undef --> undef (because it may shift by the bitwidth)
8795   if (Y.isUndef())
8796     return getUNDEF(X.getValueType());
8797 
8798   // shift 0, Y --> 0
8799   // shift X, 0 --> X
8800   if (isNullOrNullSplat(X) || isNullOrNullSplat(Y))
8801     return X;
8802 
8803   // shift X, C >= bitwidth(X) --> undef
8804   // All vector elements must be too big (or undef) to avoid partial undefs.
8805   auto isShiftTooBig = [X](ConstantSDNode *Val) {
8806     return !Val || Val->getAPIntValue().uge(X.getScalarValueSizeInBits());
8807   };
8808   if (ISD::matchUnaryPredicate(Y, isShiftTooBig, true))
8809     return getUNDEF(X.getValueType());
8810 
8811   return SDValue();
8812 }
8813 
8814 SDValue SelectionDAG::simplifyFPBinop(unsigned Opcode, SDValue X, SDValue Y,
8815                                       SDNodeFlags Flags) {
8816   // If this operation has 'nnan' or 'ninf' and at least 1 disallowed operand
8817   // (an undef operand can be chosen to be Nan/Inf), then the result of this
8818   // operation is poison. That result can be relaxed to undef.
8819   ConstantFPSDNode *XC = isConstOrConstSplatFP(X, /* AllowUndefs */ true);
8820   ConstantFPSDNode *YC = isConstOrConstSplatFP(Y, /* AllowUndefs */ true);
8821   bool HasNan = (XC && XC->getValueAPF().isNaN()) ||
8822                 (YC && YC->getValueAPF().isNaN());
8823   bool HasInf = (XC && XC->getValueAPF().isInfinity()) ||
8824                 (YC && YC->getValueAPF().isInfinity());
8825 
8826   if (Flags.hasNoNaNs() && (HasNan || X.isUndef() || Y.isUndef()))
8827     return getUNDEF(X.getValueType());
8828 
8829   if (Flags.hasNoInfs() && (HasInf || X.isUndef() || Y.isUndef()))
8830     return getUNDEF(X.getValueType());
8831 
8832   if (!YC)
8833     return SDValue();
8834 
8835   // X + -0.0 --> X
8836   if (Opcode == ISD::FADD)
8837     if (YC->getValueAPF().isNegZero())
8838       return X;
8839 
8840   // X - +0.0 --> X
8841   if (Opcode == ISD::FSUB)
8842     if (YC->getValueAPF().isPosZero())
8843       return X;
8844 
8845   // X * 1.0 --> X
8846   // X / 1.0 --> X
8847   if (Opcode == ISD::FMUL || Opcode == ISD::FDIV)
8848     if (YC->getValueAPF().isExactlyValue(1.0))
8849       return X;
8850 
8851   // X * 0.0 --> 0.0
8852   if (Opcode == ISD::FMUL && Flags.hasNoNaNs() && Flags.hasNoSignedZeros())
8853     if (YC->getValueAPF().isZero())
8854       return getConstantFP(0.0, SDLoc(Y), Y.getValueType());
8855 
8856   return SDValue();
8857 }
8858 
8859 SDValue SelectionDAG::getVAArg(EVT VT, const SDLoc &dl, SDValue Chain,
8860                                SDValue Ptr, SDValue SV, unsigned Align) {
8861   SDValue Ops[] = { Chain, Ptr, SV, getTargetConstant(Align, dl, MVT::i32) };
8862   return getNode(ISD::VAARG, dl, getVTList(VT, MVT::Other), Ops);
8863 }
8864 
8865 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
8866                               ArrayRef<SDUse> Ops) {
8867   switch (Ops.size()) {
8868   case 0: return getNode(Opcode, DL, VT);
8869   case 1: return getNode(Opcode, DL, VT, static_cast<const SDValue>(Ops[0]));
8870   case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1]);
8871   case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2]);
8872   default: break;
8873   }
8874 
8875   // Copy from an SDUse array into an SDValue array for use with
8876   // the regular getNode logic.
8877   SmallVector<SDValue, 8> NewOps(Ops.begin(), Ops.end());
8878   return getNode(Opcode, DL, VT, NewOps);
8879 }
8880 
8881 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
8882                               ArrayRef<SDValue> Ops) {
8883   SDNodeFlags Flags;
8884   if (Inserter)
8885     Flags = Inserter->getFlags();
8886   return getNode(Opcode, DL, VT, Ops, Flags);
8887 }
8888 
8889 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
8890                               ArrayRef<SDValue> Ops, const SDNodeFlags Flags) {
8891   unsigned NumOps = Ops.size();
8892   switch (NumOps) {
8893   case 0: return getNode(Opcode, DL, VT);
8894   case 1: return getNode(Opcode, DL, VT, Ops[0], Flags);
8895   case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Flags);
8896   case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2], Flags);
8897   default: break;
8898   }
8899 
8900 #ifndef NDEBUG
8901   for (auto &Op : Ops)
8902     assert(Op.getOpcode() != ISD::DELETED_NODE &&
8903            "Operand is DELETED_NODE!");
8904 #endif
8905 
8906   switch (Opcode) {
8907   default: break;
8908   case ISD::BUILD_VECTOR:
8909     // Attempt to simplify BUILD_VECTOR.
8910     if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
8911       return V;
8912     break;
8913   case ISD::CONCAT_VECTORS:
8914     if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this))
8915       return V;
8916     break;
8917   case ISD::SELECT_CC:
8918     assert(NumOps == 5 && "SELECT_CC takes 5 operands!");
8919     assert(Ops[0].getValueType() == Ops[1].getValueType() &&
8920            "LHS and RHS of condition must have same type!");
8921     assert(Ops[2].getValueType() == Ops[3].getValueType() &&
8922            "True and False arms of SelectCC must have same type!");
8923     assert(Ops[2].getValueType() == VT &&
8924            "select_cc node must be of same type as true and false value!");
8925     break;
8926   case ISD::BR_CC:
8927     assert(NumOps == 5 && "BR_CC takes 5 operands!");
8928     assert(Ops[2].getValueType() == Ops[3].getValueType() &&
8929            "LHS/RHS of comparison should match types!");
8930     break;
8931   case ISD::VP_ADD:
8932   case ISD::VP_SUB:
8933     // If it is VP_ADD/VP_SUB mask operation then turn it to VP_XOR
8934     if (VT.isVector() && VT.getVectorElementType() == MVT::i1)
8935       Opcode = ISD::VP_XOR;
8936     break;
8937   case ISD::VP_MUL:
8938     // If it is VP_MUL mask operation then turn it to VP_AND
8939     if (VT.isVector() && VT.getVectorElementType() == MVT::i1)
8940       Opcode = ISD::VP_AND;
8941     break;
8942   case ISD::VP_REDUCE_MUL:
8943     // If it is VP_REDUCE_MUL mask operation then turn it to VP_REDUCE_AND
8944     if (VT == MVT::i1)
8945       Opcode = ISD::VP_REDUCE_AND;
8946     break;
8947   case ISD::VP_REDUCE_ADD:
8948     // If it is VP_REDUCE_ADD mask operation then turn it to VP_REDUCE_XOR
8949     if (VT == MVT::i1)
8950       Opcode = ISD::VP_REDUCE_XOR;
8951     break;
8952   case ISD::VP_REDUCE_SMAX:
8953   case ISD::VP_REDUCE_UMIN:
8954     // If it is VP_REDUCE_SMAX/VP_REDUCE_UMIN mask operation then turn it to
8955     // VP_REDUCE_AND.
8956     if (VT == MVT::i1)
8957       Opcode = ISD::VP_REDUCE_AND;
8958     break;
8959   case ISD::VP_REDUCE_SMIN:
8960   case ISD::VP_REDUCE_UMAX:
8961     // If it is VP_REDUCE_SMIN/VP_REDUCE_UMAX mask operation then turn it to
8962     // VP_REDUCE_OR.
8963     if (VT == MVT::i1)
8964       Opcode = ISD::VP_REDUCE_OR;
8965     break;
8966   }
8967 
8968   // Memoize nodes.
8969   SDNode *N;
8970   SDVTList VTs = getVTList(VT);
8971 
8972   if (VT != MVT::Glue) {
8973     FoldingSetNodeID ID;
8974     AddNodeIDNode(ID, Opcode, VTs, Ops);
8975     void *IP = nullptr;
8976 
8977     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
8978       return SDValue(E, 0);
8979 
8980     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
8981     createOperands(N, Ops);
8982 
8983     CSEMap.InsertNode(N, IP);
8984   } else {
8985     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
8986     createOperands(N, Ops);
8987   }
8988 
8989   N->setFlags(Flags);
8990   InsertNode(N);
8991   SDValue V(N, 0);
8992   NewSDValueDbgMsg(V, "Creating new node: ", this);
8993   return V;
8994 }
8995 
8996 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL,
8997                               ArrayRef<EVT> ResultTys, ArrayRef<SDValue> Ops) {
8998   return getNode(Opcode, DL, getVTList(ResultTys), Ops);
8999 }
9000 
9001 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
9002                               ArrayRef<SDValue> Ops) {
9003   SDNodeFlags Flags;
9004   if (Inserter)
9005     Flags = Inserter->getFlags();
9006   return getNode(Opcode, DL, VTList, Ops, Flags);
9007 }
9008 
9009 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
9010                               ArrayRef<SDValue> Ops, const SDNodeFlags Flags) {
9011   if (VTList.NumVTs == 1)
9012     return getNode(Opcode, DL, VTList.VTs[0], Ops, Flags);
9013 
9014 #ifndef NDEBUG
9015   for (auto &Op : Ops)
9016     assert(Op.getOpcode() != ISD::DELETED_NODE &&
9017            "Operand is DELETED_NODE!");
9018 #endif
9019 
9020   switch (Opcode) {
9021   case ISD::STRICT_FP_EXTEND:
9022     assert(VTList.NumVTs == 2 && Ops.size() == 2 &&
9023            "Invalid STRICT_FP_EXTEND!");
9024     assert(VTList.VTs[0].isFloatingPoint() &&
9025            Ops[1].getValueType().isFloatingPoint() && "Invalid FP cast!");
9026     assert(VTList.VTs[0].isVector() == Ops[1].getValueType().isVector() &&
9027            "STRICT_FP_EXTEND result type should be vector iff the operand "
9028            "type is vector!");
9029     assert((!VTList.VTs[0].isVector() ||
9030             VTList.VTs[0].getVectorNumElements() ==
9031             Ops[1].getValueType().getVectorNumElements()) &&
9032            "Vector element count mismatch!");
9033     assert(Ops[1].getValueType().bitsLT(VTList.VTs[0]) &&
9034            "Invalid fpext node, dst <= src!");
9035     break;
9036   case ISD::STRICT_FP_ROUND:
9037     assert(VTList.NumVTs == 2 && Ops.size() == 3 && "Invalid STRICT_FP_ROUND!");
9038     assert(VTList.VTs[0].isVector() == Ops[1].getValueType().isVector() &&
9039            "STRICT_FP_ROUND result type should be vector iff the operand "
9040            "type is vector!");
9041     assert((!VTList.VTs[0].isVector() ||
9042             VTList.VTs[0].getVectorNumElements() ==
9043             Ops[1].getValueType().getVectorNumElements()) &&
9044            "Vector element count mismatch!");
9045     assert(VTList.VTs[0].isFloatingPoint() &&
9046            Ops[1].getValueType().isFloatingPoint() &&
9047            VTList.VTs[0].bitsLT(Ops[1].getValueType()) &&
9048            isa<ConstantSDNode>(Ops[2]) &&
9049            (cast<ConstantSDNode>(Ops[2])->getZExtValue() == 0 ||
9050             cast<ConstantSDNode>(Ops[2])->getZExtValue() == 1) &&
9051            "Invalid STRICT_FP_ROUND!");
9052     break;
9053 #if 0
9054   // FIXME: figure out how to safely handle things like
9055   // int foo(int x) { return 1 << (x & 255); }
9056   // int bar() { return foo(256); }
9057   case ISD::SRA_PARTS:
9058   case ISD::SRL_PARTS:
9059   case ISD::SHL_PARTS:
9060     if (N3.getOpcode() == ISD::SIGN_EXTEND_INREG &&
9061         cast<VTSDNode>(N3.getOperand(1))->getVT() != MVT::i1)
9062       return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0));
9063     else if (N3.getOpcode() == ISD::AND)
9064       if (ConstantSDNode *AndRHS = dyn_cast<ConstantSDNode>(N3.getOperand(1))) {
9065         // If the and is only masking out bits that cannot effect the shift,
9066         // eliminate the and.
9067         unsigned NumBits = VT.getScalarSizeInBits()*2;
9068         if ((AndRHS->getValue() & (NumBits-1)) == NumBits-1)
9069           return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0));
9070       }
9071     break;
9072 #endif
9073   }
9074 
9075   // Memoize the node unless it returns a flag.
9076   SDNode *N;
9077   if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) {
9078     FoldingSetNodeID ID;
9079     AddNodeIDNode(ID, Opcode, VTList, Ops);
9080     void *IP = nullptr;
9081     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
9082       return SDValue(E, 0);
9083 
9084     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList);
9085     createOperands(N, Ops);
9086     CSEMap.InsertNode(N, IP);
9087   } else {
9088     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList);
9089     createOperands(N, Ops);
9090   }
9091 
9092   N->setFlags(Flags);
9093   InsertNode(N);
9094   SDValue V(N, 0);
9095   NewSDValueDbgMsg(V, "Creating new node: ", this);
9096   return V;
9097 }
9098 
9099 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL,
9100                               SDVTList VTList) {
9101   return getNode(Opcode, DL, VTList, None);
9102 }
9103 
9104 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
9105                               SDValue N1) {
9106   SDValue Ops[] = { N1 };
9107   return getNode(Opcode, DL, VTList, Ops);
9108 }
9109 
9110 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
9111                               SDValue N1, SDValue N2) {
9112   SDValue Ops[] = { N1, N2 };
9113   return getNode(Opcode, DL, VTList, Ops);
9114 }
9115 
9116 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
9117                               SDValue N1, SDValue N2, SDValue N3) {
9118   SDValue Ops[] = { N1, N2, N3 };
9119   return getNode(Opcode, DL, VTList, Ops);
9120 }
9121 
9122 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
9123                               SDValue N1, SDValue N2, SDValue N3, SDValue N4) {
9124   SDValue Ops[] = { N1, N2, N3, N4 };
9125   return getNode(Opcode, DL, VTList, Ops);
9126 }
9127 
9128 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
9129                               SDValue N1, SDValue N2, SDValue N3, SDValue N4,
9130                               SDValue N5) {
9131   SDValue Ops[] = { N1, N2, N3, N4, N5 };
9132   return getNode(Opcode, DL, VTList, Ops);
9133 }
9134 
9135 SDVTList SelectionDAG::getVTList(EVT VT) {
9136   return makeVTList(SDNode::getValueTypeList(VT), 1);
9137 }
9138 
9139 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2) {
9140   FoldingSetNodeID ID;
9141   ID.AddInteger(2U);
9142   ID.AddInteger(VT1.getRawBits());
9143   ID.AddInteger(VT2.getRawBits());
9144 
9145   void *IP = nullptr;
9146   SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
9147   if (!Result) {
9148     EVT *Array = Allocator.Allocate<EVT>(2);
9149     Array[0] = VT1;
9150     Array[1] = VT2;
9151     Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 2);
9152     VTListMap.InsertNode(Result, IP);
9153   }
9154   return Result->getSDVTList();
9155 }
9156 
9157 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3) {
9158   FoldingSetNodeID ID;
9159   ID.AddInteger(3U);
9160   ID.AddInteger(VT1.getRawBits());
9161   ID.AddInteger(VT2.getRawBits());
9162   ID.AddInteger(VT3.getRawBits());
9163 
9164   void *IP = nullptr;
9165   SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
9166   if (!Result) {
9167     EVT *Array = Allocator.Allocate<EVT>(3);
9168     Array[0] = VT1;
9169     Array[1] = VT2;
9170     Array[2] = VT3;
9171     Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 3);
9172     VTListMap.InsertNode(Result, IP);
9173   }
9174   return Result->getSDVTList();
9175 }
9176 
9177 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3, EVT VT4) {
9178   FoldingSetNodeID ID;
9179   ID.AddInteger(4U);
9180   ID.AddInteger(VT1.getRawBits());
9181   ID.AddInteger(VT2.getRawBits());
9182   ID.AddInteger(VT3.getRawBits());
9183   ID.AddInteger(VT4.getRawBits());
9184 
9185   void *IP = nullptr;
9186   SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
9187   if (!Result) {
9188     EVT *Array = Allocator.Allocate<EVT>(4);
9189     Array[0] = VT1;
9190     Array[1] = VT2;
9191     Array[2] = VT3;
9192     Array[3] = VT4;
9193     Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 4);
9194     VTListMap.InsertNode(Result, IP);
9195   }
9196   return Result->getSDVTList();
9197 }
9198 
9199 SDVTList SelectionDAG::getVTList(ArrayRef<EVT> VTs) {
9200   unsigned NumVTs = VTs.size();
9201   FoldingSetNodeID ID;
9202   ID.AddInteger(NumVTs);
9203   for (unsigned index = 0; index < NumVTs; index++) {
9204     ID.AddInteger(VTs[index].getRawBits());
9205   }
9206 
9207   void *IP = nullptr;
9208   SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
9209   if (!Result) {
9210     EVT *Array = Allocator.Allocate<EVT>(NumVTs);
9211     llvm::copy(VTs, Array);
9212     Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, NumVTs);
9213     VTListMap.InsertNode(Result, IP);
9214   }
9215   return Result->getSDVTList();
9216 }
9217 
9218 
9219 /// UpdateNodeOperands - *Mutate* the specified node in-place to have the
9220 /// specified operands.  If the resultant node already exists in the DAG,
9221 /// this does not modify the specified node, instead it returns the node that
9222 /// already exists.  If the resultant node does not exist in the DAG, the
9223 /// input node is returned.  As a degenerate case, if you specify the same
9224 /// input operands as the node already has, the input node is returned.
9225 SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op) {
9226   assert(N->getNumOperands() == 1 && "Update with wrong number of operands");
9227 
9228   // Check to see if there is no change.
9229   if (Op == N->getOperand(0)) return N;
9230 
9231   // See if the modified node already exists.
9232   void *InsertPos = nullptr;
9233   if (SDNode *Existing = FindModifiedNodeSlot(N, Op, InsertPos))
9234     return Existing;
9235 
9236   // Nope it doesn't.  Remove the node from its current place in the maps.
9237   if (InsertPos)
9238     if (!RemoveNodeFromCSEMaps(N))
9239       InsertPos = nullptr;
9240 
9241   // Now we update the operands.
9242   N->OperandList[0].set(Op);
9243 
9244   updateDivergence(N);
9245   // If this gets put into a CSE map, add it.
9246   if (InsertPos) CSEMap.InsertNode(N, InsertPos);
9247   return N;
9248 }
9249 
9250 SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2) {
9251   assert(N->getNumOperands() == 2 && "Update with wrong number of operands");
9252 
9253   // Check to see if there is no change.
9254   if (Op1 == N->getOperand(0) && Op2 == N->getOperand(1))
9255     return N;   // No operands changed, just return the input node.
9256 
9257   // See if the modified node already exists.
9258   void *InsertPos = nullptr;
9259   if (SDNode *Existing = FindModifiedNodeSlot(N, Op1, Op2, InsertPos))
9260     return Existing;
9261 
9262   // Nope it doesn't.  Remove the node from its current place in the maps.
9263   if (InsertPos)
9264     if (!RemoveNodeFromCSEMaps(N))
9265       InsertPos = nullptr;
9266 
9267   // Now we update the operands.
9268   if (N->OperandList[0] != Op1)
9269     N->OperandList[0].set(Op1);
9270   if (N->OperandList[1] != Op2)
9271     N->OperandList[1].set(Op2);
9272 
9273   updateDivergence(N);
9274   // If this gets put into a CSE map, add it.
9275   if (InsertPos) CSEMap.InsertNode(N, InsertPos);
9276   return N;
9277 }
9278 
9279 SDNode *SelectionDAG::
9280 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2, SDValue Op3) {
9281   SDValue Ops[] = { Op1, Op2, Op3 };
9282   return UpdateNodeOperands(N, Ops);
9283 }
9284 
9285 SDNode *SelectionDAG::
9286 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2,
9287                    SDValue Op3, SDValue Op4) {
9288   SDValue Ops[] = { Op1, Op2, Op3, Op4 };
9289   return UpdateNodeOperands(N, Ops);
9290 }
9291 
9292 SDNode *SelectionDAG::
9293 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2,
9294                    SDValue Op3, SDValue Op4, SDValue Op5) {
9295   SDValue Ops[] = { Op1, Op2, Op3, Op4, Op5 };
9296   return UpdateNodeOperands(N, Ops);
9297 }
9298 
9299 SDNode *SelectionDAG::
9300 UpdateNodeOperands(SDNode *N, ArrayRef<SDValue> Ops) {
9301   unsigned NumOps = Ops.size();
9302   assert(N->getNumOperands() == NumOps &&
9303          "Update with wrong number of operands");
9304 
9305   // If no operands changed just return the input node.
9306   if (std::equal(Ops.begin(), Ops.end(), N->op_begin()))
9307     return N;
9308 
9309   // See if the modified node already exists.
9310   void *InsertPos = nullptr;
9311   if (SDNode *Existing = FindModifiedNodeSlot(N, Ops, InsertPos))
9312     return Existing;
9313 
9314   // Nope it doesn't.  Remove the node from its current place in the maps.
9315   if (InsertPos)
9316     if (!RemoveNodeFromCSEMaps(N))
9317       InsertPos = nullptr;
9318 
9319   // Now we update the operands.
9320   for (unsigned i = 0; i != NumOps; ++i)
9321     if (N->OperandList[i] != Ops[i])
9322       N->OperandList[i].set(Ops[i]);
9323 
9324   updateDivergence(N);
9325   // If this gets put into a CSE map, add it.
9326   if (InsertPos) CSEMap.InsertNode(N, InsertPos);
9327   return N;
9328 }
9329 
9330 /// DropOperands - Release the operands and set this node to have
9331 /// zero operands.
9332 void SDNode::DropOperands() {
9333   // Unlike the code in MorphNodeTo that does this, we don't need to
9334   // watch for dead nodes here.
9335   for (op_iterator I = op_begin(), E = op_end(); I != E; ) {
9336     SDUse &Use = *I++;
9337     Use.set(SDValue());
9338   }
9339 }
9340 
9341 void SelectionDAG::setNodeMemRefs(MachineSDNode *N,
9342                                   ArrayRef<MachineMemOperand *> NewMemRefs) {
9343   if (NewMemRefs.empty()) {
9344     N->clearMemRefs();
9345     return;
9346   }
9347 
9348   // Check if we can avoid allocating by storing a single reference directly.
9349   if (NewMemRefs.size() == 1) {
9350     N->MemRefs = NewMemRefs[0];
9351     N->NumMemRefs = 1;
9352     return;
9353   }
9354 
9355   MachineMemOperand **MemRefsBuffer =
9356       Allocator.template Allocate<MachineMemOperand *>(NewMemRefs.size());
9357   llvm::copy(NewMemRefs, MemRefsBuffer);
9358   N->MemRefs = MemRefsBuffer;
9359   N->NumMemRefs = static_cast<int>(NewMemRefs.size());
9360 }
9361 
9362 /// SelectNodeTo - These are wrappers around MorphNodeTo that accept a
9363 /// machine opcode.
9364 ///
9365 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
9366                                    EVT VT) {
9367   SDVTList VTs = getVTList(VT);
9368   return SelectNodeTo(N, MachineOpc, VTs, None);
9369 }
9370 
9371 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
9372                                    EVT VT, SDValue Op1) {
9373   SDVTList VTs = getVTList(VT);
9374   SDValue Ops[] = { Op1 };
9375   return SelectNodeTo(N, MachineOpc, VTs, Ops);
9376 }
9377 
9378 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
9379                                    EVT VT, SDValue Op1,
9380                                    SDValue Op2) {
9381   SDVTList VTs = getVTList(VT);
9382   SDValue Ops[] = { Op1, Op2 };
9383   return SelectNodeTo(N, MachineOpc, VTs, Ops);
9384 }
9385 
9386 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
9387                                    EVT VT, SDValue Op1,
9388                                    SDValue Op2, SDValue Op3) {
9389   SDVTList VTs = getVTList(VT);
9390   SDValue Ops[] = { Op1, Op2, Op3 };
9391   return SelectNodeTo(N, MachineOpc, VTs, Ops);
9392 }
9393 
9394 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
9395                                    EVT VT, ArrayRef<SDValue> Ops) {
9396   SDVTList VTs = getVTList(VT);
9397   return SelectNodeTo(N, MachineOpc, VTs, Ops);
9398 }
9399 
9400 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
9401                                    EVT VT1, EVT VT2, ArrayRef<SDValue> Ops) {
9402   SDVTList VTs = getVTList(VT1, VT2);
9403   return SelectNodeTo(N, MachineOpc, VTs, Ops);
9404 }
9405 
9406 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
9407                                    EVT VT1, EVT VT2) {
9408   SDVTList VTs = getVTList(VT1, VT2);
9409   return SelectNodeTo(N, MachineOpc, VTs, None);
9410 }
9411 
9412 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
9413                                    EVT VT1, EVT VT2, EVT VT3,
9414                                    ArrayRef<SDValue> Ops) {
9415   SDVTList VTs = getVTList(VT1, VT2, VT3);
9416   return SelectNodeTo(N, MachineOpc, VTs, Ops);
9417 }
9418 
9419 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
9420                                    EVT VT1, EVT VT2,
9421                                    SDValue Op1, SDValue Op2) {
9422   SDVTList VTs = getVTList(VT1, VT2);
9423   SDValue Ops[] = { Op1, Op2 };
9424   return SelectNodeTo(N, MachineOpc, VTs, Ops);
9425 }
9426 
9427 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
9428                                    SDVTList VTs,ArrayRef<SDValue> Ops) {
9429   SDNode *New = MorphNodeTo(N, ~MachineOpc, VTs, Ops);
9430   // Reset the NodeID to -1.
9431   New->setNodeId(-1);
9432   if (New != N) {
9433     ReplaceAllUsesWith(N, New);
9434     RemoveDeadNode(N);
9435   }
9436   return New;
9437 }
9438 
9439 /// UpdateSDLocOnMergeSDNode - If the opt level is -O0 then it throws away
9440 /// the line number information on the merged node since it is not possible to
9441 /// preserve the information that operation is associated with multiple lines.
9442 /// This will make the debugger working better at -O0, were there is a higher
9443 /// probability having other instructions associated with that line.
9444 ///
9445 /// For IROrder, we keep the smaller of the two
9446 SDNode *SelectionDAG::UpdateSDLocOnMergeSDNode(SDNode *N, const SDLoc &OLoc) {
9447   DebugLoc NLoc = N->getDebugLoc();
9448   if (NLoc && OptLevel == CodeGenOpt::None && OLoc.getDebugLoc() != NLoc) {
9449     N->setDebugLoc(DebugLoc());
9450   }
9451   unsigned Order = std::min(N->getIROrder(), OLoc.getIROrder());
9452   N->setIROrder(Order);
9453   return N;
9454 }
9455 
9456 /// MorphNodeTo - This *mutates* the specified node to have the specified
9457 /// return type, opcode, and operands.
9458 ///
9459 /// Note that MorphNodeTo returns the resultant node.  If there is already a
9460 /// node of the specified opcode and operands, it returns that node instead of
9461 /// the current one.  Note that the SDLoc need not be the same.
9462 ///
9463 /// Using MorphNodeTo is faster than creating a new node and swapping it in
9464 /// with ReplaceAllUsesWith both because it often avoids allocating a new
9465 /// node, and because it doesn't require CSE recalculation for any of
9466 /// the node's users.
9467 ///
9468 /// However, note that MorphNodeTo recursively deletes dead nodes from the DAG.
9469 /// As a consequence it isn't appropriate to use from within the DAG combiner or
9470 /// the legalizer which maintain worklists that would need to be updated when
9471 /// deleting things.
9472 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
9473                                   SDVTList VTs, ArrayRef<SDValue> Ops) {
9474   // If an identical node already exists, use it.
9475   void *IP = nullptr;
9476   if (VTs.VTs[VTs.NumVTs-1] != MVT::Glue) {
9477     FoldingSetNodeID ID;
9478     AddNodeIDNode(ID, Opc, VTs, Ops);
9479     if (SDNode *ON = FindNodeOrInsertPos(ID, SDLoc(N), IP))
9480       return UpdateSDLocOnMergeSDNode(ON, SDLoc(N));
9481   }
9482 
9483   if (!RemoveNodeFromCSEMaps(N))
9484     IP = nullptr;
9485 
9486   // Start the morphing.
9487   N->NodeType = Opc;
9488   N->ValueList = VTs.VTs;
9489   N->NumValues = VTs.NumVTs;
9490 
9491   // Clear the operands list, updating used nodes to remove this from their
9492   // use list.  Keep track of any operands that become dead as a result.
9493   SmallPtrSet<SDNode*, 16> DeadNodeSet;
9494   for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) {
9495     SDUse &Use = *I++;
9496     SDNode *Used = Use.getNode();
9497     Use.set(SDValue());
9498     if (Used->use_empty())
9499       DeadNodeSet.insert(Used);
9500   }
9501 
9502   // For MachineNode, initialize the memory references information.
9503   if (MachineSDNode *MN = dyn_cast<MachineSDNode>(N))
9504     MN->clearMemRefs();
9505 
9506   // Swap for an appropriately sized array from the recycler.
9507   removeOperands(N);
9508   createOperands(N, Ops);
9509 
9510   // Delete any nodes that are still dead after adding the uses for the
9511   // new operands.
9512   if (!DeadNodeSet.empty()) {
9513     SmallVector<SDNode *, 16> DeadNodes;
9514     for (SDNode *N : DeadNodeSet)
9515       if (N->use_empty())
9516         DeadNodes.push_back(N);
9517     RemoveDeadNodes(DeadNodes);
9518   }
9519 
9520   if (IP)
9521     CSEMap.InsertNode(N, IP);   // Memoize the new node.
9522   return N;
9523 }
9524 
9525 SDNode* SelectionDAG::mutateStrictFPToFP(SDNode *Node) {
9526   unsigned OrigOpc = Node->getOpcode();
9527   unsigned NewOpc;
9528   switch (OrigOpc) {
9529   default:
9530     llvm_unreachable("mutateStrictFPToFP called with unexpected opcode!");
9531 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN)               \
9532   case ISD::STRICT_##DAGN: NewOpc = ISD::DAGN; break;
9533 #define CMP_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN)               \
9534   case ISD::STRICT_##DAGN: NewOpc = ISD::SETCC; break;
9535 #include "llvm/IR/ConstrainedOps.def"
9536   }
9537 
9538   assert(Node->getNumValues() == 2 && "Unexpected number of results!");
9539 
9540   // We're taking this node out of the chain, so we need to re-link things.
9541   SDValue InputChain = Node->getOperand(0);
9542   SDValue OutputChain = SDValue(Node, 1);
9543   ReplaceAllUsesOfValueWith(OutputChain, InputChain);
9544 
9545   SmallVector<SDValue, 3> Ops;
9546   for (unsigned i = 1, e = Node->getNumOperands(); i != e; ++i)
9547     Ops.push_back(Node->getOperand(i));
9548 
9549   SDVTList VTs = getVTList(Node->getValueType(0));
9550   SDNode *Res = MorphNodeTo(Node, NewOpc, VTs, Ops);
9551 
9552   // MorphNodeTo can operate in two ways: if an existing node with the
9553   // specified operands exists, it can just return it.  Otherwise, it
9554   // updates the node in place to have the requested operands.
9555   if (Res == Node) {
9556     // If we updated the node in place, reset the node ID.  To the isel,
9557     // this should be just like a newly allocated machine node.
9558     Res->setNodeId(-1);
9559   } else {
9560     ReplaceAllUsesWith(Node, Res);
9561     RemoveDeadNode(Node);
9562   }
9563 
9564   return Res;
9565 }
9566 
9567 /// getMachineNode - These are used for target selectors to create a new node
9568 /// with specified return type(s), MachineInstr opcode, and operands.
9569 ///
9570 /// Note that getMachineNode returns the resultant node.  If there is already a
9571 /// node of the specified opcode and operands, it returns that node instead of
9572 /// the current one.
9573 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9574                                             EVT VT) {
9575   SDVTList VTs = getVTList(VT);
9576   return getMachineNode(Opcode, dl, VTs, None);
9577 }
9578 
9579 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9580                                             EVT VT, SDValue Op1) {
9581   SDVTList VTs = getVTList(VT);
9582   SDValue Ops[] = { Op1 };
9583   return getMachineNode(Opcode, dl, VTs, Ops);
9584 }
9585 
9586 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9587                                             EVT VT, SDValue Op1, SDValue Op2) {
9588   SDVTList VTs = getVTList(VT);
9589   SDValue Ops[] = { Op1, Op2 };
9590   return getMachineNode(Opcode, dl, VTs, Ops);
9591 }
9592 
9593 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9594                                             EVT VT, SDValue Op1, SDValue Op2,
9595                                             SDValue Op3) {
9596   SDVTList VTs = getVTList(VT);
9597   SDValue Ops[] = { Op1, Op2, Op3 };
9598   return getMachineNode(Opcode, dl, VTs, Ops);
9599 }
9600 
9601 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9602                                             EVT VT, ArrayRef<SDValue> Ops) {
9603   SDVTList VTs = getVTList(VT);
9604   return getMachineNode(Opcode, dl, VTs, Ops);
9605 }
9606 
9607 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9608                                             EVT VT1, EVT VT2, SDValue Op1,
9609                                             SDValue Op2) {
9610   SDVTList VTs = getVTList(VT1, VT2);
9611   SDValue Ops[] = { Op1, Op2 };
9612   return getMachineNode(Opcode, dl, VTs, Ops);
9613 }
9614 
9615 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9616                                             EVT VT1, EVT VT2, SDValue Op1,
9617                                             SDValue Op2, SDValue Op3) {
9618   SDVTList VTs = getVTList(VT1, VT2);
9619   SDValue Ops[] = { Op1, Op2, Op3 };
9620   return getMachineNode(Opcode, dl, VTs, Ops);
9621 }
9622 
9623 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9624                                             EVT VT1, EVT VT2,
9625                                             ArrayRef<SDValue> Ops) {
9626   SDVTList VTs = getVTList(VT1, VT2);
9627   return getMachineNode(Opcode, dl, VTs, Ops);
9628 }
9629 
9630 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9631                                             EVT VT1, EVT VT2, EVT VT3,
9632                                             SDValue Op1, SDValue Op2) {
9633   SDVTList VTs = getVTList(VT1, VT2, VT3);
9634   SDValue Ops[] = { Op1, Op2 };
9635   return getMachineNode(Opcode, dl, VTs, Ops);
9636 }
9637 
9638 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9639                                             EVT VT1, EVT VT2, EVT VT3,
9640                                             SDValue Op1, SDValue Op2,
9641                                             SDValue Op3) {
9642   SDVTList VTs = getVTList(VT1, VT2, VT3);
9643   SDValue Ops[] = { Op1, Op2, Op3 };
9644   return getMachineNode(Opcode, dl, VTs, Ops);
9645 }
9646 
9647 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9648                                             EVT VT1, EVT VT2, EVT VT3,
9649                                             ArrayRef<SDValue> Ops) {
9650   SDVTList VTs = getVTList(VT1, VT2, VT3);
9651   return getMachineNode(Opcode, dl, VTs, Ops);
9652 }
9653 
9654 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9655                                             ArrayRef<EVT> ResultTys,
9656                                             ArrayRef<SDValue> Ops) {
9657   SDVTList VTs = getVTList(ResultTys);
9658   return getMachineNode(Opcode, dl, VTs, Ops);
9659 }
9660 
9661 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &DL,
9662                                             SDVTList VTs,
9663                                             ArrayRef<SDValue> Ops) {
9664   bool DoCSE = VTs.VTs[VTs.NumVTs-1] != MVT::Glue;
9665   MachineSDNode *N;
9666   void *IP = nullptr;
9667 
9668   if (DoCSE) {
9669     FoldingSetNodeID ID;
9670     AddNodeIDNode(ID, ~Opcode, VTs, Ops);
9671     IP = nullptr;
9672     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
9673       return cast<MachineSDNode>(UpdateSDLocOnMergeSDNode(E, DL));
9674     }
9675   }
9676 
9677   // Allocate a new MachineSDNode.
9678   N = newSDNode<MachineSDNode>(~Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
9679   createOperands(N, Ops);
9680 
9681   if (DoCSE)
9682     CSEMap.InsertNode(N, IP);
9683 
9684   InsertNode(N);
9685   NewSDValueDbgMsg(SDValue(N, 0), "Creating new machine node: ", this);
9686   return N;
9687 }
9688 
9689 /// getTargetExtractSubreg - A convenience function for creating
9690 /// TargetOpcode::EXTRACT_SUBREG nodes.
9691 SDValue SelectionDAG::getTargetExtractSubreg(int SRIdx, const SDLoc &DL, EVT VT,
9692                                              SDValue Operand) {
9693   SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32);
9694   SDNode *Subreg = getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL,
9695                                   VT, Operand, SRIdxVal);
9696   return SDValue(Subreg, 0);
9697 }
9698 
9699 /// getTargetInsertSubreg - A convenience function for creating
9700 /// TargetOpcode::INSERT_SUBREG nodes.
9701 SDValue SelectionDAG::getTargetInsertSubreg(int SRIdx, const SDLoc &DL, EVT VT,
9702                                             SDValue Operand, SDValue Subreg) {
9703   SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32);
9704   SDNode *Result = getMachineNode(TargetOpcode::INSERT_SUBREG, DL,
9705                                   VT, Operand, Subreg, SRIdxVal);
9706   return SDValue(Result, 0);
9707 }
9708 
9709 /// getNodeIfExists - Get the specified node if it's already available, or
9710 /// else return NULL.
9711 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList,
9712                                       ArrayRef<SDValue> Ops) {
9713   SDNodeFlags Flags;
9714   if (Inserter)
9715     Flags = Inserter->getFlags();
9716   return getNodeIfExists(Opcode, VTList, Ops, Flags);
9717 }
9718 
9719 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList,
9720                                       ArrayRef<SDValue> Ops,
9721                                       const SDNodeFlags Flags) {
9722   if (VTList.VTs[VTList.NumVTs - 1] != MVT::Glue) {
9723     FoldingSetNodeID ID;
9724     AddNodeIDNode(ID, Opcode, VTList, Ops);
9725     void *IP = nullptr;
9726     if (SDNode *E = FindNodeOrInsertPos(ID, SDLoc(), IP)) {
9727       E->intersectFlagsWith(Flags);
9728       return E;
9729     }
9730   }
9731   return nullptr;
9732 }
9733 
9734 /// doesNodeExist - Check if a node exists without modifying its flags.
9735 bool SelectionDAG::doesNodeExist(unsigned Opcode, SDVTList VTList,
9736                                  ArrayRef<SDValue> Ops) {
9737   if (VTList.VTs[VTList.NumVTs - 1] != MVT::Glue) {
9738     FoldingSetNodeID ID;
9739     AddNodeIDNode(ID, Opcode, VTList, Ops);
9740     void *IP = nullptr;
9741     if (FindNodeOrInsertPos(ID, SDLoc(), IP))
9742       return true;
9743   }
9744   return false;
9745 }
9746 
9747 /// getDbgValue - Creates a SDDbgValue node.
9748 ///
9749 /// SDNode
9750 SDDbgValue *SelectionDAG::getDbgValue(DIVariable *Var, DIExpression *Expr,
9751                                       SDNode *N, unsigned R, bool IsIndirect,
9752                                       const DebugLoc &DL, unsigned O) {
9753   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
9754          "Expected inlined-at fields to agree");
9755   return new (DbgInfo->getAlloc())
9756       SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromNode(N, R),
9757                  {}, IsIndirect, DL, O,
9758                  /*IsVariadic=*/false);
9759 }
9760 
9761 /// Constant
9762 SDDbgValue *SelectionDAG::getConstantDbgValue(DIVariable *Var,
9763                                               DIExpression *Expr,
9764                                               const Value *C,
9765                                               const DebugLoc &DL, unsigned O) {
9766   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
9767          "Expected inlined-at fields to agree");
9768   return new (DbgInfo->getAlloc())
9769       SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromConst(C), {},
9770                  /*IsIndirect=*/false, DL, O,
9771                  /*IsVariadic=*/false);
9772 }
9773 
9774 /// FrameIndex
9775 SDDbgValue *SelectionDAG::getFrameIndexDbgValue(DIVariable *Var,
9776                                                 DIExpression *Expr, unsigned FI,
9777                                                 bool IsIndirect,
9778                                                 const DebugLoc &DL,
9779                                                 unsigned O) {
9780   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
9781          "Expected inlined-at fields to agree");
9782   return getFrameIndexDbgValue(Var, Expr, FI, {}, IsIndirect, DL, O);
9783 }
9784 
9785 /// FrameIndex with dependencies
9786 SDDbgValue *SelectionDAG::getFrameIndexDbgValue(DIVariable *Var,
9787                                                 DIExpression *Expr, unsigned FI,
9788                                                 ArrayRef<SDNode *> Dependencies,
9789                                                 bool IsIndirect,
9790                                                 const DebugLoc &DL,
9791                                                 unsigned O) {
9792   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
9793          "Expected inlined-at fields to agree");
9794   return new (DbgInfo->getAlloc())
9795       SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromFrameIdx(FI),
9796                  Dependencies, IsIndirect, DL, O,
9797                  /*IsVariadic=*/false);
9798 }
9799 
9800 /// VReg
9801 SDDbgValue *SelectionDAG::getVRegDbgValue(DIVariable *Var, DIExpression *Expr,
9802                                           unsigned VReg, bool IsIndirect,
9803                                           const DebugLoc &DL, unsigned O) {
9804   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
9805          "Expected inlined-at fields to agree");
9806   return new (DbgInfo->getAlloc())
9807       SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromVReg(VReg),
9808                  {}, IsIndirect, DL, O,
9809                  /*IsVariadic=*/false);
9810 }
9811 
9812 SDDbgValue *SelectionDAG::getDbgValueList(DIVariable *Var, DIExpression *Expr,
9813                                           ArrayRef<SDDbgOperand> Locs,
9814                                           ArrayRef<SDNode *> Dependencies,
9815                                           bool IsIndirect, const DebugLoc &DL,
9816                                           unsigned O, bool IsVariadic) {
9817   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
9818          "Expected inlined-at fields to agree");
9819   return new (DbgInfo->getAlloc())
9820       SDDbgValue(DbgInfo->getAlloc(), Var, Expr, Locs, Dependencies, IsIndirect,
9821                  DL, O, IsVariadic);
9822 }
9823 
9824 void SelectionDAG::transferDbgValues(SDValue From, SDValue To,
9825                                      unsigned OffsetInBits, unsigned SizeInBits,
9826                                      bool InvalidateDbg) {
9827   SDNode *FromNode = From.getNode();
9828   SDNode *ToNode = To.getNode();
9829   assert(FromNode && ToNode && "Can't modify dbg values");
9830 
9831   // PR35338
9832   // TODO: assert(From != To && "Redundant dbg value transfer");
9833   // TODO: assert(FromNode != ToNode && "Intranode dbg value transfer");
9834   if (From == To || FromNode == ToNode)
9835     return;
9836 
9837   if (!FromNode->getHasDebugValue())
9838     return;
9839 
9840   SDDbgOperand FromLocOp =
9841       SDDbgOperand::fromNode(From.getNode(), From.getResNo());
9842   SDDbgOperand ToLocOp = SDDbgOperand::fromNode(To.getNode(), To.getResNo());
9843 
9844   SmallVector<SDDbgValue *, 2> ClonedDVs;
9845   for (SDDbgValue *Dbg : GetDbgValues(FromNode)) {
9846     if (Dbg->isInvalidated())
9847       continue;
9848 
9849     // TODO: assert(!Dbg->isInvalidated() && "Transfer of invalid dbg value");
9850 
9851     // Create a new location ops vector that is equal to the old vector, but
9852     // with each instance of FromLocOp replaced with ToLocOp.
9853     bool Changed = false;
9854     auto NewLocOps = Dbg->copyLocationOps();
9855     std::replace_if(
9856         NewLocOps.begin(), NewLocOps.end(),
9857         [&Changed, FromLocOp](const SDDbgOperand &Op) {
9858           bool Match = Op == FromLocOp;
9859           Changed |= Match;
9860           return Match;
9861         },
9862         ToLocOp);
9863     // Ignore this SDDbgValue if we didn't find a matching location.
9864     if (!Changed)
9865       continue;
9866 
9867     DIVariable *Var = Dbg->getVariable();
9868     auto *Expr = Dbg->getExpression();
9869     // If a fragment is requested, update the expression.
9870     if (SizeInBits) {
9871       // When splitting a larger (e.g., sign-extended) value whose
9872       // lower bits are described with an SDDbgValue, do not attempt
9873       // to transfer the SDDbgValue to the upper bits.
9874       if (auto FI = Expr->getFragmentInfo())
9875         if (OffsetInBits + SizeInBits > FI->SizeInBits)
9876           continue;
9877       auto Fragment = DIExpression::createFragmentExpression(Expr, OffsetInBits,
9878                                                              SizeInBits);
9879       if (!Fragment)
9880         continue;
9881       Expr = *Fragment;
9882     }
9883 
9884     auto AdditionalDependencies = Dbg->getAdditionalDependencies();
9885     // Clone the SDDbgValue and move it to To.
9886     SDDbgValue *Clone = getDbgValueList(
9887         Var, Expr, NewLocOps, AdditionalDependencies, Dbg->isIndirect(),
9888         Dbg->getDebugLoc(), std::max(ToNode->getIROrder(), Dbg->getOrder()),
9889         Dbg->isVariadic());
9890     ClonedDVs.push_back(Clone);
9891 
9892     if (InvalidateDbg) {
9893       // Invalidate value and indicate the SDDbgValue should not be emitted.
9894       Dbg->setIsInvalidated();
9895       Dbg->setIsEmitted();
9896     }
9897   }
9898 
9899   for (SDDbgValue *Dbg : ClonedDVs) {
9900     assert(is_contained(Dbg->getSDNodes(), ToNode) &&
9901            "Transferred DbgValues should depend on the new SDNode");
9902     AddDbgValue(Dbg, false);
9903   }
9904 }
9905 
9906 void SelectionDAG::salvageDebugInfo(SDNode &N) {
9907   if (!N.getHasDebugValue())
9908     return;
9909 
9910   SmallVector<SDDbgValue *, 2> ClonedDVs;
9911   for (auto DV : GetDbgValues(&N)) {
9912     if (DV->isInvalidated())
9913       continue;
9914     switch (N.getOpcode()) {
9915     default:
9916       break;
9917     case ISD::ADD:
9918       SDValue N0 = N.getOperand(0);
9919       SDValue N1 = N.getOperand(1);
9920       if (!isConstantIntBuildVectorOrConstantInt(N0) &&
9921           isConstantIntBuildVectorOrConstantInt(N1)) {
9922         uint64_t Offset = N.getConstantOperandVal(1);
9923 
9924         // Rewrite an ADD constant node into a DIExpression. Since we are
9925         // performing arithmetic to compute the variable's *value* in the
9926         // DIExpression, we need to mark the expression with a
9927         // DW_OP_stack_value.
9928         auto *DIExpr = DV->getExpression();
9929         auto NewLocOps = DV->copyLocationOps();
9930         bool Changed = false;
9931         for (size_t i = 0; i < NewLocOps.size(); ++i) {
9932           // We're not given a ResNo to compare against because the whole
9933           // node is going away. We know that any ISD::ADD only has one
9934           // result, so we can assume any node match is using the result.
9935           if (NewLocOps[i].getKind() != SDDbgOperand::SDNODE ||
9936               NewLocOps[i].getSDNode() != &N)
9937             continue;
9938           NewLocOps[i] = SDDbgOperand::fromNode(N0.getNode(), N0.getResNo());
9939           SmallVector<uint64_t, 3> ExprOps;
9940           DIExpression::appendOffset(ExprOps, Offset);
9941           DIExpr = DIExpression::appendOpsToArg(DIExpr, ExprOps, i, true);
9942           Changed = true;
9943         }
9944         (void)Changed;
9945         assert(Changed && "Salvage target doesn't use N");
9946 
9947         auto AdditionalDependencies = DV->getAdditionalDependencies();
9948         SDDbgValue *Clone = getDbgValueList(DV->getVariable(), DIExpr,
9949                                             NewLocOps, AdditionalDependencies,
9950                                             DV->isIndirect(), DV->getDebugLoc(),
9951                                             DV->getOrder(), DV->isVariadic());
9952         ClonedDVs.push_back(Clone);
9953         DV->setIsInvalidated();
9954         DV->setIsEmitted();
9955         LLVM_DEBUG(dbgs() << "SALVAGE: Rewriting";
9956                    N0.getNode()->dumprFull(this);
9957                    dbgs() << " into " << *DIExpr << '\n');
9958       }
9959     }
9960   }
9961 
9962   for (SDDbgValue *Dbg : ClonedDVs) {
9963     assert(!Dbg->getSDNodes().empty() &&
9964            "Salvaged DbgValue should depend on a new SDNode");
9965     AddDbgValue(Dbg, false);
9966   }
9967 }
9968 
9969 /// Creates a SDDbgLabel node.
9970 SDDbgLabel *SelectionDAG::getDbgLabel(DILabel *Label,
9971                                       const DebugLoc &DL, unsigned O) {
9972   assert(cast<DILabel>(Label)->isValidLocationForIntrinsic(DL) &&
9973          "Expected inlined-at fields to agree");
9974   return new (DbgInfo->getAlloc()) SDDbgLabel(Label, DL, O);
9975 }
9976 
9977 namespace {
9978 
9979 /// RAUWUpdateListener - Helper for ReplaceAllUsesWith - When the node
9980 /// pointed to by a use iterator is deleted, increment the use iterator
9981 /// so that it doesn't dangle.
9982 ///
9983 class RAUWUpdateListener : public SelectionDAG::DAGUpdateListener {
9984   SDNode::use_iterator &UI;
9985   SDNode::use_iterator &UE;
9986 
9987   void NodeDeleted(SDNode *N, SDNode *E) override {
9988     // Increment the iterator as needed.
9989     while (UI != UE && N == *UI)
9990       ++UI;
9991   }
9992 
9993 public:
9994   RAUWUpdateListener(SelectionDAG &d,
9995                      SDNode::use_iterator &ui,
9996                      SDNode::use_iterator &ue)
9997     : SelectionDAG::DAGUpdateListener(d), UI(ui), UE(ue) {}
9998 };
9999 
10000 } // end anonymous namespace
10001 
10002 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
10003 /// This can cause recursive merging of nodes in the DAG.
10004 ///
10005 /// This version assumes From has a single result value.
10006 ///
10007 void SelectionDAG::ReplaceAllUsesWith(SDValue FromN, SDValue To) {
10008   SDNode *From = FromN.getNode();
10009   assert(From->getNumValues() == 1 && FromN.getResNo() == 0 &&
10010          "Cannot replace with this method!");
10011   assert(From != To.getNode() && "Cannot replace uses of with self");
10012 
10013   // Preserve Debug Values
10014   transferDbgValues(FromN, To);
10015 
10016   // Iterate over all the existing uses of From. New uses will be added
10017   // to the beginning of the use list, which we avoid visiting.
10018   // This specifically avoids visiting uses of From that arise while the
10019   // replacement is happening, because any such uses would be the result
10020   // of CSE: If an existing node looks like From after one of its operands
10021   // is replaced by To, we don't want to replace of all its users with To
10022   // too. See PR3018 for more info.
10023   SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
10024   RAUWUpdateListener Listener(*this, UI, UE);
10025   while (UI != UE) {
10026     SDNode *User = *UI;
10027 
10028     // This node is about to morph, remove its old self from the CSE maps.
10029     RemoveNodeFromCSEMaps(User);
10030 
10031     // A user can appear in a use list multiple times, and when this
10032     // happens the uses are usually next to each other in the list.
10033     // To help reduce the number of CSE recomputations, process all
10034     // the uses of this user that we can find this way.
10035     do {
10036       SDUse &Use = UI.getUse();
10037       ++UI;
10038       Use.set(To);
10039       if (To->isDivergent() != From->isDivergent())
10040         updateDivergence(User);
10041     } while (UI != UE && *UI == User);
10042     // Now that we have modified User, add it back to the CSE maps.  If it
10043     // already exists there, recursively merge the results together.
10044     AddModifiedNodeToCSEMaps(User);
10045   }
10046 
10047   // If we just RAUW'd the root, take note.
10048   if (FromN == getRoot())
10049     setRoot(To);
10050 }
10051 
10052 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
10053 /// This can cause recursive merging of nodes in the DAG.
10054 ///
10055 /// This version assumes that for each value of From, there is a
10056 /// corresponding value in To in the same position with the same type.
10057 ///
10058 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, SDNode *To) {
10059 #ifndef NDEBUG
10060   for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
10061     assert((!From->hasAnyUseOfValue(i) ||
10062             From->getValueType(i) == To->getValueType(i)) &&
10063            "Cannot use this version of ReplaceAllUsesWith!");
10064 #endif
10065 
10066   // Handle the trivial case.
10067   if (From == To)
10068     return;
10069 
10070   // Preserve Debug Info. Only do this if there's a use.
10071   for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
10072     if (From->hasAnyUseOfValue(i)) {
10073       assert((i < To->getNumValues()) && "Invalid To location");
10074       transferDbgValues(SDValue(From, i), SDValue(To, i));
10075     }
10076 
10077   // Iterate over just the existing users of From. See the comments in
10078   // the ReplaceAllUsesWith above.
10079   SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
10080   RAUWUpdateListener Listener(*this, UI, UE);
10081   while (UI != UE) {
10082     SDNode *User = *UI;
10083 
10084     // This node is about to morph, remove its old self from the CSE maps.
10085     RemoveNodeFromCSEMaps(User);
10086 
10087     // A user can appear in a use list multiple times, and when this
10088     // happens the uses are usually next to each other in the list.
10089     // To help reduce the number of CSE recomputations, process all
10090     // the uses of this user that we can find this way.
10091     do {
10092       SDUse &Use = UI.getUse();
10093       ++UI;
10094       Use.setNode(To);
10095       if (To->isDivergent() != From->isDivergent())
10096         updateDivergence(User);
10097     } while (UI != UE && *UI == User);
10098 
10099     // Now that we have modified User, add it back to the CSE maps.  If it
10100     // already exists there, recursively merge the results together.
10101     AddModifiedNodeToCSEMaps(User);
10102   }
10103 
10104   // If we just RAUW'd the root, take note.
10105   if (From == getRoot().getNode())
10106     setRoot(SDValue(To, getRoot().getResNo()));
10107 }
10108 
10109 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
10110 /// This can cause recursive merging of nodes in the DAG.
10111 ///
10112 /// This version can replace From with any result values.  To must match the
10113 /// number and types of values returned by From.
10114 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, const SDValue *To) {
10115   if (From->getNumValues() == 1)  // Handle the simple case efficiently.
10116     return ReplaceAllUsesWith(SDValue(From, 0), To[0]);
10117 
10118   // Preserve Debug Info.
10119   for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
10120     transferDbgValues(SDValue(From, i), To[i]);
10121 
10122   // Iterate over just the existing users of From. See the comments in
10123   // the ReplaceAllUsesWith above.
10124   SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
10125   RAUWUpdateListener Listener(*this, UI, UE);
10126   while (UI != UE) {
10127     SDNode *User = *UI;
10128 
10129     // This node is about to morph, remove its old self from the CSE maps.
10130     RemoveNodeFromCSEMaps(User);
10131 
10132     // A user can appear in a use list multiple times, and when this happens the
10133     // uses are usually next to each other in the list.  To help reduce the
10134     // number of CSE and divergence recomputations, process all the uses of this
10135     // user that we can find this way.
10136     bool To_IsDivergent = false;
10137     do {
10138       SDUse &Use = UI.getUse();
10139       const SDValue &ToOp = To[Use.getResNo()];
10140       ++UI;
10141       Use.set(ToOp);
10142       To_IsDivergent |= ToOp->isDivergent();
10143     } while (UI != UE && *UI == User);
10144 
10145     if (To_IsDivergent != From->isDivergent())
10146       updateDivergence(User);
10147 
10148     // Now that we have modified User, add it back to the CSE maps.  If it
10149     // already exists there, recursively merge the results together.
10150     AddModifiedNodeToCSEMaps(User);
10151   }
10152 
10153   // If we just RAUW'd the root, take note.
10154   if (From == getRoot().getNode())
10155     setRoot(SDValue(To[getRoot().getResNo()]));
10156 }
10157 
10158 /// ReplaceAllUsesOfValueWith - Replace any uses of From with To, leaving
10159 /// uses of other values produced by From.getNode() alone.  The Deleted
10160 /// vector is handled the same way as for ReplaceAllUsesWith.
10161 void SelectionDAG::ReplaceAllUsesOfValueWith(SDValue From, SDValue To){
10162   // Handle the really simple, really trivial case efficiently.
10163   if (From == To) return;
10164 
10165   // Handle the simple, trivial, case efficiently.
10166   if (From.getNode()->getNumValues() == 1) {
10167     ReplaceAllUsesWith(From, To);
10168     return;
10169   }
10170 
10171   // Preserve Debug Info.
10172   transferDbgValues(From, To);
10173 
10174   // Iterate over just the existing users of From. See the comments in
10175   // the ReplaceAllUsesWith above.
10176   SDNode::use_iterator UI = From.getNode()->use_begin(),
10177                        UE = From.getNode()->use_end();
10178   RAUWUpdateListener Listener(*this, UI, UE);
10179   while (UI != UE) {
10180     SDNode *User = *UI;
10181     bool UserRemovedFromCSEMaps = false;
10182 
10183     // A user can appear in a use list multiple times, and when this
10184     // happens the uses are usually next to each other in the list.
10185     // To help reduce the number of CSE recomputations, process all
10186     // the uses of this user that we can find this way.
10187     do {
10188       SDUse &Use = UI.getUse();
10189 
10190       // Skip uses of different values from the same node.
10191       if (Use.getResNo() != From.getResNo()) {
10192         ++UI;
10193         continue;
10194       }
10195 
10196       // If this node hasn't been modified yet, it's still in the CSE maps,
10197       // so remove its old self from the CSE maps.
10198       if (!UserRemovedFromCSEMaps) {
10199         RemoveNodeFromCSEMaps(User);
10200         UserRemovedFromCSEMaps = true;
10201       }
10202 
10203       ++UI;
10204       Use.set(To);
10205       if (To->isDivergent() != From->isDivergent())
10206         updateDivergence(User);
10207     } while (UI != UE && *UI == User);
10208     // We are iterating over all uses of the From node, so if a use
10209     // doesn't use the specific value, no changes are made.
10210     if (!UserRemovedFromCSEMaps)
10211       continue;
10212 
10213     // Now that we have modified User, add it back to the CSE maps.  If it
10214     // already exists there, recursively merge the results together.
10215     AddModifiedNodeToCSEMaps(User);
10216   }
10217 
10218   // If we just RAUW'd the root, take note.
10219   if (From == getRoot())
10220     setRoot(To);
10221 }
10222 
10223 namespace {
10224 
10225 /// UseMemo - This class is used by SelectionDAG::ReplaceAllUsesOfValuesWith
10226 /// to record information about a use.
10227 struct UseMemo {
10228   SDNode *User;
10229   unsigned Index;
10230   SDUse *Use;
10231 };
10232 
10233 /// operator< - Sort Memos by User.
10234 bool operator<(const UseMemo &L, const UseMemo &R) {
10235   return (intptr_t)L.User < (intptr_t)R.User;
10236 }
10237 
10238 /// RAUOVWUpdateListener - Helper for ReplaceAllUsesOfValuesWith - When the node
10239 /// pointed to by a UseMemo is deleted, set the User to nullptr to indicate that
10240 /// the node already has been taken care of recursively.
10241 class RAUOVWUpdateListener : public SelectionDAG::DAGUpdateListener {
10242   SmallVector<UseMemo, 4> &Uses;
10243 
10244   void NodeDeleted(SDNode *N, SDNode *E) override {
10245     for (UseMemo &Memo : Uses)
10246       if (Memo.User == N)
10247         Memo.User = nullptr;
10248   }
10249 
10250 public:
10251   RAUOVWUpdateListener(SelectionDAG &d, SmallVector<UseMemo, 4> &uses)
10252       : SelectionDAG::DAGUpdateListener(d), Uses(uses) {}
10253 };
10254 
10255 } // end anonymous namespace
10256 
10257 bool SelectionDAG::calculateDivergence(SDNode *N) {
10258   if (TLI->isSDNodeAlwaysUniform(N)) {
10259     assert(!TLI->isSDNodeSourceOfDivergence(N, FLI, DA) &&
10260            "Conflicting divergence information!");
10261     return false;
10262   }
10263   if (TLI->isSDNodeSourceOfDivergence(N, FLI, DA))
10264     return true;
10265   for (auto &Op : N->ops()) {
10266     if (Op.Val.getValueType() != MVT::Other && Op.getNode()->isDivergent())
10267       return true;
10268   }
10269   return false;
10270 }
10271 
10272 void SelectionDAG::updateDivergence(SDNode *N) {
10273   SmallVector<SDNode *, 16> Worklist(1, N);
10274   do {
10275     N = Worklist.pop_back_val();
10276     bool IsDivergent = calculateDivergence(N);
10277     if (N->SDNodeBits.IsDivergent != IsDivergent) {
10278       N->SDNodeBits.IsDivergent = IsDivergent;
10279       llvm::append_range(Worklist, N->uses());
10280     }
10281   } while (!Worklist.empty());
10282 }
10283 
10284 void SelectionDAG::CreateTopologicalOrder(std::vector<SDNode *> &Order) {
10285   DenseMap<SDNode *, unsigned> Degree;
10286   Order.reserve(AllNodes.size());
10287   for (auto &N : allnodes()) {
10288     unsigned NOps = N.getNumOperands();
10289     Degree[&N] = NOps;
10290     if (0 == NOps)
10291       Order.push_back(&N);
10292   }
10293   for (size_t I = 0; I != Order.size(); ++I) {
10294     SDNode *N = Order[I];
10295     for (auto U : N->uses()) {
10296       unsigned &UnsortedOps = Degree[U];
10297       if (0 == --UnsortedOps)
10298         Order.push_back(U);
10299     }
10300   }
10301 }
10302 
10303 #ifndef NDEBUG
10304 void SelectionDAG::VerifyDAGDivergence() {
10305   std::vector<SDNode *> TopoOrder;
10306   CreateTopologicalOrder(TopoOrder);
10307   for (auto *N : TopoOrder) {
10308     assert(calculateDivergence(N) == N->isDivergent() &&
10309            "Divergence bit inconsistency detected");
10310   }
10311 }
10312 #endif
10313 
10314 /// ReplaceAllUsesOfValuesWith - Replace any uses of From with To, leaving
10315 /// uses of other values produced by From.getNode() alone.  The same value
10316 /// may appear in both the From and To list.  The Deleted vector is
10317 /// handled the same way as for ReplaceAllUsesWith.
10318 void SelectionDAG::ReplaceAllUsesOfValuesWith(const SDValue *From,
10319                                               const SDValue *To,
10320                                               unsigned Num){
10321   // Handle the simple, trivial case efficiently.
10322   if (Num == 1)
10323     return ReplaceAllUsesOfValueWith(*From, *To);
10324 
10325   transferDbgValues(*From, *To);
10326 
10327   // Read up all the uses and make records of them. This helps
10328   // processing new uses that are introduced during the
10329   // replacement process.
10330   SmallVector<UseMemo, 4> Uses;
10331   for (unsigned i = 0; i != Num; ++i) {
10332     unsigned FromResNo = From[i].getResNo();
10333     SDNode *FromNode = From[i].getNode();
10334     for (SDNode::use_iterator UI = FromNode->use_begin(),
10335          E = FromNode->use_end(); UI != E; ++UI) {
10336       SDUse &Use = UI.getUse();
10337       if (Use.getResNo() == FromResNo) {
10338         UseMemo Memo = { *UI, i, &Use };
10339         Uses.push_back(Memo);
10340       }
10341     }
10342   }
10343 
10344   // Sort the uses, so that all the uses from a given User are together.
10345   llvm::sort(Uses);
10346   RAUOVWUpdateListener Listener(*this, Uses);
10347 
10348   for (unsigned UseIndex = 0, UseIndexEnd = Uses.size();
10349        UseIndex != UseIndexEnd; ) {
10350     // We know that this user uses some value of From.  If it is the right
10351     // value, update it.
10352     SDNode *User = Uses[UseIndex].User;
10353     // If the node has been deleted by recursive CSE updates when updating
10354     // another node, then just skip this entry.
10355     if (User == nullptr) {
10356       ++UseIndex;
10357       continue;
10358     }
10359 
10360     // This node is about to morph, remove its old self from the CSE maps.
10361     RemoveNodeFromCSEMaps(User);
10362 
10363     // The Uses array is sorted, so all the uses for a given User
10364     // are next to each other in the list.
10365     // To help reduce the number of CSE recomputations, process all
10366     // the uses of this user that we can find this way.
10367     do {
10368       unsigned i = Uses[UseIndex].Index;
10369       SDUse &Use = *Uses[UseIndex].Use;
10370       ++UseIndex;
10371 
10372       Use.set(To[i]);
10373     } while (UseIndex != UseIndexEnd && Uses[UseIndex].User == User);
10374 
10375     // Now that we have modified User, add it back to the CSE maps.  If it
10376     // already exists there, recursively merge the results together.
10377     AddModifiedNodeToCSEMaps(User);
10378   }
10379 }
10380 
10381 /// AssignTopologicalOrder - Assign a unique node id for each node in the DAG
10382 /// based on their topological order. It returns the maximum id and a vector
10383 /// of the SDNodes* in assigned order by reference.
10384 unsigned SelectionDAG::AssignTopologicalOrder() {
10385   unsigned DAGSize = 0;
10386 
10387   // SortedPos tracks the progress of the algorithm. Nodes before it are
10388   // sorted, nodes after it are unsorted. When the algorithm completes
10389   // it is at the end of the list.
10390   allnodes_iterator SortedPos = allnodes_begin();
10391 
10392   // Visit all the nodes. Move nodes with no operands to the front of
10393   // the list immediately. Annotate nodes that do have operands with their
10394   // operand count. Before we do this, the Node Id fields of the nodes
10395   // may contain arbitrary values. After, the Node Id fields for nodes
10396   // before SortedPos will contain the topological sort index, and the
10397   // Node Id fields for nodes At SortedPos and after will contain the
10398   // count of outstanding operands.
10399   for (SDNode &N : llvm::make_early_inc_range(allnodes())) {
10400     checkForCycles(&N, this);
10401     unsigned Degree = N.getNumOperands();
10402     if (Degree == 0) {
10403       // A node with no uses, add it to the result array immediately.
10404       N.setNodeId(DAGSize++);
10405       allnodes_iterator Q(&N);
10406       if (Q != SortedPos)
10407         SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(Q));
10408       assert(SortedPos != AllNodes.end() && "Overran node list");
10409       ++SortedPos;
10410     } else {
10411       // Temporarily use the Node Id as scratch space for the degree count.
10412       N.setNodeId(Degree);
10413     }
10414   }
10415 
10416   // Visit all the nodes. As we iterate, move nodes into sorted order,
10417   // such that by the time the end is reached all nodes will be sorted.
10418   for (SDNode &Node : allnodes()) {
10419     SDNode *N = &Node;
10420     checkForCycles(N, this);
10421     // N is in sorted position, so all its uses have one less operand
10422     // that needs to be sorted.
10423     for (SDNode *P : N->uses()) {
10424       unsigned Degree = P->getNodeId();
10425       assert(Degree != 0 && "Invalid node degree");
10426       --Degree;
10427       if (Degree == 0) {
10428         // All of P's operands are sorted, so P may sorted now.
10429         P->setNodeId(DAGSize++);
10430         if (P->getIterator() != SortedPos)
10431           SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(P));
10432         assert(SortedPos != AllNodes.end() && "Overran node list");
10433         ++SortedPos;
10434       } else {
10435         // Update P's outstanding operand count.
10436         P->setNodeId(Degree);
10437       }
10438     }
10439     if (Node.getIterator() == SortedPos) {
10440 #ifndef NDEBUG
10441       allnodes_iterator I(N);
10442       SDNode *S = &*++I;
10443       dbgs() << "Overran sorted position:\n";
10444       S->dumprFull(this); dbgs() << "\n";
10445       dbgs() << "Checking if this is due to cycles\n";
10446       checkForCycles(this, true);
10447 #endif
10448       llvm_unreachable(nullptr);
10449     }
10450   }
10451 
10452   assert(SortedPos == AllNodes.end() &&
10453          "Topological sort incomplete!");
10454   assert(AllNodes.front().getOpcode() == ISD::EntryToken &&
10455          "First node in topological sort is not the entry token!");
10456   assert(AllNodes.front().getNodeId() == 0 &&
10457          "First node in topological sort has non-zero id!");
10458   assert(AllNodes.front().getNumOperands() == 0 &&
10459          "First node in topological sort has operands!");
10460   assert(AllNodes.back().getNodeId() == (int)DAGSize-1 &&
10461          "Last node in topologic sort has unexpected id!");
10462   assert(AllNodes.back().use_empty() &&
10463          "Last node in topologic sort has users!");
10464   assert(DAGSize == allnodes_size() && "Node count mismatch!");
10465   return DAGSize;
10466 }
10467 
10468 /// AddDbgValue - Add a dbg_value SDNode. If SD is non-null that means the
10469 /// value is produced by SD.
10470 void SelectionDAG::AddDbgValue(SDDbgValue *DB, bool isParameter) {
10471   for (SDNode *SD : DB->getSDNodes()) {
10472     if (!SD)
10473       continue;
10474     assert(DbgInfo->getSDDbgValues(SD).empty() || SD->getHasDebugValue());
10475     SD->setHasDebugValue(true);
10476   }
10477   DbgInfo->add(DB, isParameter);
10478 }
10479 
10480 void SelectionDAG::AddDbgLabel(SDDbgLabel *DB) { DbgInfo->add(DB); }
10481 
10482 SDValue SelectionDAG::makeEquivalentMemoryOrdering(SDValue OldChain,
10483                                                    SDValue NewMemOpChain) {
10484   assert(isa<MemSDNode>(NewMemOpChain) && "Expected a memop node");
10485   assert(NewMemOpChain.getValueType() == MVT::Other && "Expected a token VT");
10486   // The new memory operation must have the same position as the old load in
10487   // terms of memory dependency. Create a TokenFactor for the old load and new
10488   // memory operation and update uses of the old load's output chain to use that
10489   // TokenFactor.
10490   if (OldChain == NewMemOpChain || OldChain.use_empty())
10491     return NewMemOpChain;
10492 
10493   SDValue TokenFactor = getNode(ISD::TokenFactor, SDLoc(OldChain), MVT::Other,
10494                                 OldChain, NewMemOpChain);
10495   ReplaceAllUsesOfValueWith(OldChain, TokenFactor);
10496   UpdateNodeOperands(TokenFactor.getNode(), OldChain, NewMemOpChain);
10497   return TokenFactor;
10498 }
10499 
10500 SDValue SelectionDAG::makeEquivalentMemoryOrdering(LoadSDNode *OldLoad,
10501                                                    SDValue NewMemOp) {
10502   assert(isa<MemSDNode>(NewMemOp.getNode()) && "Expected a memop node");
10503   SDValue OldChain = SDValue(OldLoad, 1);
10504   SDValue NewMemOpChain = NewMemOp.getValue(1);
10505   return makeEquivalentMemoryOrdering(OldChain, NewMemOpChain);
10506 }
10507 
10508 SDValue SelectionDAG::getSymbolFunctionGlobalAddress(SDValue Op,
10509                                                      Function **OutFunction) {
10510   assert(isa<ExternalSymbolSDNode>(Op) && "Node should be an ExternalSymbol");
10511 
10512   auto *Symbol = cast<ExternalSymbolSDNode>(Op)->getSymbol();
10513   auto *Module = MF->getFunction().getParent();
10514   auto *Function = Module->getFunction(Symbol);
10515 
10516   if (OutFunction != nullptr)
10517       *OutFunction = Function;
10518 
10519   if (Function != nullptr) {
10520     auto PtrTy = TLI->getPointerTy(getDataLayout(), Function->getAddressSpace());
10521     return getGlobalAddress(Function, SDLoc(Op), PtrTy);
10522   }
10523 
10524   std::string ErrorStr;
10525   raw_string_ostream ErrorFormatter(ErrorStr);
10526   ErrorFormatter << "Undefined external symbol ";
10527   ErrorFormatter << '"' << Symbol << '"';
10528   report_fatal_error(Twine(ErrorFormatter.str()));
10529 }
10530 
10531 //===----------------------------------------------------------------------===//
10532 //                              SDNode Class
10533 //===----------------------------------------------------------------------===//
10534 
10535 bool llvm::isNullConstant(SDValue V) {
10536   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
10537   return Const != nullptr && Const->isZero();
10538 }
10539 
10540 bool llvm::isNullFPConstant(SDValue V) {
10541   ConstantFPSDNode *Const = dyn_cast<ConstantFPSDNode>(V);
10542   return Const != nullptr && Const->isZero() && !Const->isNegative();
10543 }
10544 
10545 bool llvm::isAllOnesConstant(SDValue V) {
10546   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
10547   return Const != nullptr && Const->isAllOnes();
10548 }
10549 
10550 bool llvm::isOneConstant(SDValue V) {
10551   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
10552   return Const != nullptr && Const->isOne();
10553 }
10554 
10555 bool llvm::isMinSignedConstant(SDValue V) {
10556   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
10557   return Const != nullptr && Const->isMinSignedValue();
10558 }
10559 
10560 SDValue llvm::peekThroughBitcasts(SDValue V) {
10561   while (V.getOpcode() == ISD::BITCAST)
10562     V = V.getOperand(0);
10563   return V;
10564 }
10565 
10566 SDValue llvm::peekThroughOneUseBitcasts(SDValue V) {
10567   while (V.getOpcode() == ISD::BITCAST && V.getOperand(0).hasOneUse())
10568     V = V.getOperand(0);
10569   return V;
10570 }
10571 
10572 SDValue llvm::peekThroughExtractSubvectors(SDValue V) {
10573   while (V.getOpcode() == ISD::EXTRACT_SUBVECTOR)
10574     V = V.getOperand(0);
10575   return V;
10576 }
10577 
10578 bool llvm::isBitwiseNot(SDValue V, bool AllowUndefs) {
10579   if (V.getOpcode() != ISD::XOR)
10580     return false;
10581   V = peekThroughBitcasts(V.getOperand(1));
10582   unsigned NumBits = V.getScalarValueSizeInBits();
10583   ConstantSDNode *C =
10584       isConstOrConstSplat(V, AllowUndefs, /*AllowTruncation*/ true);
10585   return C && (C->getAPIntValue().countTrailingOnes() >= NumBits);
10586 }
10587 
10588 ConstantSDNode *llvm::isConstOrConstSplat(SDValue N, bool AllowUndefs,
10589                                           bool AllowTruncation) {
10590   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
10591     return CN;
10592 
10593   // SplatVectors can truncate their operands. Ignore that case here unless
10594   // AllowTruncation is set.
10595   if (N->getOpcode() == ISD::SPLAT_VECTOR) {
10596     EVT VecEltVT = N->getValueType(0).getVectorElementType();
10597     if (auto *CN = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
10598       EVT CVT = CN->getValueType(0);
10599       assert(CVT.bitsGE(VecEltVT) && "Illegal splat_vector element extension");
10600       if (AllowTruncation || CVT == VecEltVT)
10601         return CN;
10602     }
10603   }
10604 
10605   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
10606     BitVector UndefElements;
10607     ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
10608 
10609     // BuildVectors can truncate their operands. Ignore that case here unless
10610     // AllowTruncation is set.
10611     if (CN && (UndefElements.none() || AllowUndefs)) {
10612       EVT CVT = CN->getValueType(0);
10613       EVT NSVT = N.getValueType().getScalarType();
10614       assert(CVT.bitsGE(NSVT) && "Illegal build vector element extension");
10615       if (AllowTruncation || (CVT == NSVT))
10616         return CN;
10617     }
10618   }
10619 
10620   return nullptr;
10621 }
10622 
10623 ConstantSDNode *llvm::isConstOrConstSplat(SDValue N, const APInt &DemandedElts,
10624                                           bool AllowUndefs,
10625                                           bool AllowTruncation) {
10626   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
10627     return CN;
10628 
10629   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
10630     BitVector UndefElements;
10631     ConstantSDNode *CN = BV->getConstantSplatNode(DemandedElts, &UndefElements);
10632 
10633     // BuildVectors can truncate their operands. Ignore that case here unless
10634     // AllowTruncation is set.
10635     if (CN && (UndefElements.none() || AllowUndefs)) {
10636       EVT CVT = CN->getValueType(0);
10637       EVT NSVT = N.getValueType().getScalarType();
10638       assert(CVT.bitsGE(NSVT) && "Illegal build vector element extension");
10639       if (AllowTruncation || (CVT == NSVT))
10640         return CN;
10641     }
10642   }
10643 
10644   return nullptr;
10645 }
10646 
10647 ConstantFPSDNode *llvm::isConstOrConstSplatFP(SDValue N, bool AllowUndefs) {
10648   if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
10649     return CN;
10650 
10651   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
10652     BitVector UndefElements;
10653     ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements);
10654     if (CN && (UndefElements.none() || AllowUndefs))
10655       return CN;
10656   }
10657 
10658   if (N.getOpcode() == ISD::SPLAT_VECTOR)
10659     if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N.getOperand(0)))
10660       return CN;
10661 
10662   return nullptr;
10663 }
10664 
10665 ConstantFPSDNode *llvm::isConstOrConstSplatFP(SDValue N,
10666                                               const APInt &DemandedElts,
10667                                               bool AllowUndefs) {
10668   if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
10669     return CN;
10670 
10671   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
10672     BitVector UndefElements;
10673     ConstantFPSDNode *CN =
10674         BV->getConstantFPSplatNode(DemandedElts, &UndefElements);
10675     if (CN && (UndefElements.none() || AllowUndefs))
10676       return CN;
10677   }
10678 
10679   return nullptr;
10680 }
10681 
10682 bool llvm::isNullOrNullSplat(SDValue N, bool AllowUndefs) {
10683   // TODO: may want to use peekThroughBitcast() here.
10684   ConstantSDNode *C =
10685       isConstOrConstSplat(N, AllowUndefs, /*AllowTruncation=*/true);
10686   return C && C->isZero();
10687 }
10688 
10689 bool llvm::isOneOrOneSplat(SDValue N, bool AllowUndefs) {
10690   ConstantSDNode *C =
10691       isConstOrConstSplat(N, AllowUndefs, /*AllowTruncation*/ true);
10692   return C && C->isOne();
10693 }
10694 
10695 bool llvm::isAllOnesOrAllOnesSplat(SDValue N, bool AllowUndefs) {
10696   N = peekThroughBitcasts(N);
10697   unsigned BitWidth = N.getScalarValueSizeInBits();
10698   ConstantSDNode *C = isConstOrConstSplat(N, AllowUndefs);
10699   return C && C->isAllOnes() && C->getValueSizeInBits(0) == BitWidth;
10700 }
10701 
10702 HandleSDNode::~HandleSDNode() {
10703   DropOperands();
10704 }
10705 
10706 GlobalAddressSDNode::GlobalAddressSDNode(unsigned Opc, unsigned Order,
10707                                          const DebugLoc &DL,
10708                                          const GlobalValue *GA, EVT VT,
10709                                          int64_t o, unsigned TF)
10710     : SDNode(Opc, Order, DL, getSDVTList(VT)), Offset(o), TargetFlags(TF) {
10711   TheGlobal = GA;
10712 }
10713 
10714 AddrSpaceCastSDNode::AddrSpaceCastSDNode(unsigned Order, const DebugLoc &dl,
10715                                          EVT VT, unsigned SrcAS,
10716                                          unsigned DestAS)
10717     : SDNode(ISD::ADDRSPACECAST, Order, dl, getSDVTList(VT)),
10718       SrcAddrSpace(SrcAS), DestAddrSpace(DestAS) {}
10719 
10720 MemSDNode::MemSDNode(unsigned Opc, unsigned Order, const DebugLoc &dl,
10721                      SDVTList VTs, EVT memvt, MachineMemOperand *mmo)
10722     : SDNode(Opc, Order, dl, VTs), MemoryVT(memvt), MMO(mmo) {
10723   MemSDNodeBits.IsVolatile = MMO->isVolatile();
10724   MemSDNodeBits.IsNonTemporal = MMO->isNonTemporal();
10725   MemSDNodeBits.IsDereferenceable = MMO->isDereferenceable();
10726   MemSDNodeBits.IsInvariant = MMO->isInvariant();
10727 
10728   // We check here that the size of the memory operand fits within the size of
10729   // the MMO. This is because the MMO might indicate only a possible address
10730   // range instead of specifying the affected memory addresses precisely.
10731   // TODO: Make MachineMemOperands aware of scalable vectors.
10732   assert(memvt.getStoreSize().getKnownMinSize() <= MMO->getSize() &&
10733          "Size mismatch!");
10734 }
10735 
10736 /// Profile - Gather unique data for the node.
10737 ///
10738 void SDNode::Profile(FoldingSetNodeID &ID) const {
10739   AddNodeIDNode(ID, this);
10740 }
10741 
10742 namespace {
10743 
10744   struct EVTArray {
10745     std::vector<EVT> VTs;
10746 
10747     EVTArray() {
10748       VTs.reserve(MVT::VALUETYPE_SIZE);
10749       for (unsigned i = 0; i < MVT::VALUETYPE_SIZE; ++i)
10750         VTs.push_back(MVT((MVT::SimpleValueType)i));
10751     }
10752   };
10753 
10754 } // end anonymous namespace
10755 
10756 /// getValueTypeList - Return a pointer to the specified value type.
10757 ///
10758 const EVT *SDNode::getValueTypeList(EVT VT) {
10759   static std::set<EVT, EVT::compareRawBits> EVTs;
10760   static EVTArray SimpleVTArray;
10761   static sys::SmartMutex<true> VTMutex;
10762 
10763   if (VT.isExtended()) {
10764     sys::SmartScopedLock<true> Lock(VTMutex);
10765     return &(*EVTs.insert(VT).first);
10766   }
10767   assert(VT.getSimpleVT() < MVT::VALUETYPE_SIZE && "Value type out of range!");
10768   return &SimpleVTArray.VTs[VT.getSimpleVT().SimpleTy];
10769 }
10770 
10771 /// hasNUsesOfValue - Return true if there are exactly NUSES uses of the
10772 /// indicated value.  This method ignores uses of other values defined by this
10773 /// operation.
10774 bool SDNode::hasNUsesOfValue(unsigned NUses, unsigned Value) const {
10775   assert(Value < getNumValues() && "Bad value!");
10776 
10777   // TODO: Only iterate over uses of a given value of the node
10778   for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) {
10779     if (UI.getUse().getResNo() == Value) {
10780       if (NUses == 0)
10781         return false;
10782       --NUses;
10783     }
10784   }
10785 
10786   // Found exactly the right number of uses?
10787   return NUses == 0;
10788 }
10789 
10790 /// hasAnyUseOfValue - Return true if there are any use of the indicated
10791 /// value. This method ignores uses of other values defined by this operation.
10792 bool SDNode::hasAnyUseOfValue(unsigned Value) const {
10793   assert(Value < getNumValues() && "Bad value!");
10794 
10795   for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI)
10796     if (UI.getUse().getResNo() == Value)
10797       return true;
10798 
10799   return false;
10800 }
10801 
10802 /// isOnlyUserOf - Return true if this node is the only use of N.
10803 bool SDNode::isOnlyUserOf(const SDNode *N) const {
10804   bool Seen = false;
10805   for (const SDNode *User : N->uses()) {
10806     if (User == this)
10807       Seen = true;
10808     else
10809       return false;
10810   }
10811 
10812   return Seen;
10813 }
10814 
10815 /// Return true if the only users of N are contained in Nodes.
10816 bool SDNode::areOnlyUsersOf(ArrayRef<const SDNode *> Nodes, const SDNode *N) {
10817   bool Seen = false;
10818   for (const SDNode *User : N->uses()) {
10819     if (llvm::is_contained(Nodes, User))
10820       Seen = true;
10821     else
10822       return false;
10823   }
10824 
10825   return Seen;
10826 }
10827 
10828 /// isOperand - Return true if this node is an operand of N.
10829 bool SDValue::isOperandOf(const SDNode *N) const {
10830   return is_contained(N->op_values(), *this);
10831 }
10832 
10833 bool SDNode::isOperandOf(const SDNode *N) const {
10834   return any_of(N->op_values(),
10835                 [this](SDValue Op) { return this == Op.getNode(); });
10836 }
10837 
10838 /// reachesChainWithoutSideEffects - Return true if this operand (which must
10839 /// be a chain) reaches the specified operand without crossing any
10840 /// side-effecting instructions on any chain path.  In practice, this looks
10841 /// through token factors and non-volatile loads.  In order to remain efficient,
10842 /// this only looks a couple of nodes in, it does not do an exhaustive search.
10843 ///
10844 /// Note that we only need to examine chains when we're searching for
10845 /// side-effects; SelectionDAG requires that all side-effects are represented
10846 /// by chains, even if another operand would force a specific ordering. This
10847 /// constraint is necessary to allow transformations like splitting loads.
10848 bool SDValue::reachesChainWithoutSideEffects(SDValue Dest,
10849                                              unsigned Depth) const {
10850   if (*this == Dest) return true;
10851 
10852   // Don't search too deeply, we just want to be able to see through
10853   // TokenFactor's etc.
10854   if (Depth == 0) return false;
10855 
10856   // If this is a token factor, all inputs to the TF happen in parallel.
10857   if (getOpcode() == ISD::TokenFactor) {
10858     // First, try a shallow search.
10859     if (is_contained((*this)->ops(), Dest)) {
10860       // We found the chain we want as an operand of this TokenFactor.
10861       // Essentially, we reach the chain without side-effects if we could
10862       // serialize the TokenFactor into a simple chain of operations with
10863       // Dest as the last operation. This is automatically true if the
10864       // chain has one use: there are no other ordering constraints.
10865       // If the chain has more than one use, we give up: some other
10866       // use of Dest might force a side-effect between Dest and the current
10867       // node.
10868       if (Dest.hasOneUse())
10869         return true;
10870     }
10871     // Next, try a deep search: check whether every operand of the TokenFactor
10872     // reaches Dest.
10873     return llvm::all_of((*this)->ops(), [=](SDValue Op) {
10874       return Op.reachesChainWithoutSideEffects(Dest, Depth - 1);
10875     });
10876   }
10877 
10878   // Loads don't have side effects, look through them.
10879   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(*this)) {
10880     if (Ld->isUnordered())
10881       return Ld->getChain().reachesChainWithoutSideEffects(Dest, Depth-1);
10882   }
10883   return false;
10884 }
10885 
10886 bool SDNode::hasPredecessor(const SDNode *N) const {
10887   SmallPtrSet<const SDNode *, 32> Visited;
10888   SmallVector<const SDNode *, 16> Worklist;
10889   Worklist.push_back(this);
10890   return hasPredecessorHelper(N, Visited, Worklist);
10891 }
10892 
10893 void SDNode::intersectFlagsWith(const SDNodeFlags Flags) {
10894   this->Flags.intersectWith(Flags);
10895 }
10896 
10897 SDValue
10898 SelectionDAG::matchBinOpReduction(SDNode *Extract, ISD::NodeType &BinOp,
10899                                   ArrayRef<ISD::NodeType> CandidateBinOps,
10900                                   bool AllowPartials) {
10901   // The pattern must end in an extract from index 0.
10902   if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10903       !isNullConstant(Extract->getOperand(1)))
10904     return SDValue();
10905 
10906   // Match against one of the candidate binary ops.
10907   SDValue Op = Extract->getOperand(0);
10908   if (llvm::none_of(CandidateBinOps, [Op](ISD::NodeType BinOp) {
10909         return Op.getOpcode() == unsigned(BinOp);
10910       }))
10911     return SDValue();
10912 
10913   // Floating-point reductions may require relaxed constraints on the final step
10914   // of the reduction because they may reorder intermediate operations.
10915   unsigned CandidateBinOp = Op.getOpcode();
10916   if (Op.getValueType().isFloatingPoint()) {
10917     SDNodeFlags Flags = Op->getFlags();
10918     switch (CandidateBinOp) {
10919     case ISD::FADD:
10920       if (!Flags.hasNoSignedZeros() || !Flags.hasAllowReassociation())
10921         return SDValue();
10922       break;
10923     default:
10924       llvm_unreachable("Unhandled FP opcode for binop reduction");
10925     }
10926   }
10927 
10928   // Matching failed - attempt to see if we did enough stages that a partial
10929   // reduction from a subvector is possible.
10930   auto PartialReduction = [&](SDValue Op, unsigned NumSubElts) {
10931     if (!AllowPartials || !Op)
10932       return SDValue();
10933     EVT OpVT = Op.getValueType();
10934     EVT OpSVT = OpVT.getScalarType();
10935     EVT SubVT = EVT::getVectorVT(*getContext(), OpSVT, NumSubElts);
10936     if (!TLI->isExtractSubvectorCheap(SubVT, OpVT, 0))
10937       return SDValue();
10938     BinOp = (ISD::NodeType)CandidateBinOp;
10939     return getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(Op), SubVT, Op,
10940                    getVectorIdxConstant(0, SDLoc(Op)));
10941   };
10942 
10943   // At each stage, we're looking for something that looks like:
10944   // %s = shufflevector <8 x i32> %op, <8 x i32> undef,
10945   //                    <8 x i32> <i32 2, i32 3, i32 undef, i32 undef,
10946   //                               i32 undef, i32 undef, i32 undef, i32 undef>
10947   // %a = binop <8 x i32> %op, %s
10948   // Where the mask changes according to the stage. E.g. for a 3-stage pyramid,
10949   // we expect something like:
10950   // <4,5,6,7,u,u,u,u>
10951   // <2,3,u,u,u,u,u,u>
10952   // <1,u,u,u,u,u,u,u>
10953   // While a partial reduction match would be:
10954   // <2,3,u,u,u,u,u,u>
10955   // <1,u,u,u,u,u,u,u>
10956   unsigned Stages = Log2_32(Op.getValueType().getVectorNumElements());
10957   SDValue PrevOp;
10958   for (unsigned i = 0; i < Stages; ++i) {
10959     unsigned MaskEnd = (1 << i);
10960 
10961     if (Op.getOpcode() != CandidateBinOp)
10962       return PartialReduction(PrevOp, MaskEnd);
10963 
10964     SDValue Op0 = Op.getOperand(0);
10965     SDValue Op1 = Op.getOperand(1);
10966 
10967     ShuffleVectorSDNode *Shuffle = dyn_cast<ShuffleVectorSDNode>(Op0);
10968     if (Shuffle) {
10969       Op = Op1;
10970     } else {
10971       Shuffle = dyn_cast<ShuffleVectorSDNode>(Op1);
10972       Op = Op0;
10973     }
10974 
10975     // The first operand of the shuffle should be the same as the other operand
10976     // of the binop.
10977     if (!Shuffle || Shuffle->getOperand(0) != Op)
10978       return PartialReduction(PrevOp, MaskEnd);
10979 
10980     // Verify the shuffle has the expected (at this stage of the pyramid) mask.
10981     for (int Index = 0; Index < (int)MaskEnd; ++Index)
10982       if (Shuffle->getMaskElt(Index) != (int)(MaskEnd + Index))
10983         return PartialReduction(PrevOp, MaskEnd);
10984 
10985     PrevOp = Op;
10986   }
10987 
10988   // Handle subvector reductions, which tend to appear after the shuffle
10989   // reduction stages.
10990   while (Op.getOpcode() == CandidateBinOp) {
10991     unsigned NumElts = Op.getValueType().getVectorNumElements();
10992     SDValue Op0 = Op.getOperand(0);
10993     SDValue Op1 = Op.getOperand(1);
10994     if (Op0.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
10995         Op1.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
10996         Op0.getOperand(0) != Op1.getOperand(0))
10997       break;
10998     SDValue Src = Op0.getOperand(0);
10999     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
11000     if (NumSrcElts != (2 * NumElts))
11001       break;
11002     if (!(Op0.getConstantOperandAPInt(1) == 0 &&
11003           Op1.getConstantOperandAPInt(1) == NumElts) &&
11004         !(Op1.getConstantOperandAPInt(1) == 0 &&
11005           Op0.getConstantOperandAPInt(1) == NumElts))
11006       break;
11007     Op = Src;
11008   }
11009 
11010   BinOp = (ISD::NodeType)CandidateBinOp;
11011   return Op;
11012 }
11013 
11014 SDValue SelectionDAG::UnrollVectorOp(SDNode *N, unsigned ResNE) {
11015   assert(N->getNumValues() == 1 &&
11016          "Can't unroll a vector with multiple results!");
11017 
11018   EVT VT = N->getValueType(0);
11019   unsigned NE = VT.getVectorNumElements();
11020   EVT EltVT = VT.getVectorElementType();
11021   SDLoc dl(N);
11022 
11023   SmallVector<SDValue, 8> Scalars;
11024   SmallVector<SDValue, 4> Operands(N->getNumOperands());
11025 
11026   // If ResNE is 0, fully unroll the vector op.
11027   if (ResNE == 0)
11028     ResNE = NE;
11029   else if (NE > ResNE)
11030     NE = ResNE;
11031 
11032   unsigned i;
11033   for (i= 0; i != NE; ++i) {
11034     for (unsigned j = 0, e = N->getNumOperands(); j != e; ++j) {
11035       SDValue Operand = N->getOperand(j);
11036       EVT OperandVT = Operand.getValueType();
11037       if (OperandVT.isVector()) {
11038         // A vector operand; extract a single element.
11039         EVT OperandEltVT = OperandVT.getVectorElementType();
11040         Operands[j] = getNode(ISD::EXTRACT_VECTOR_ELT, dl, OperandEltVT,
11041                               Operand, getVectorIdxConstant(i, dl));
11042       } else {
11043         // A scalar operand; just use it as is.
11044         Operands[j] = Operand;
11045       }
11046     }
11047 
11048     switch (N->getOpcode()) {
11049     default: {
11050       Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands,
11051                                 N->getFlags()));
11052       break;
11053     }
11054     case ISD::VSELECT:
11055       Scalars.push_back(getNode(ISD::SELECT, dl, EltVT, Operands));
11056       break;
11057     case ISD::SHL:
11058     case ISD::SRA:
11059     case ISD::SRL:
11060     case ISD::ROTL:
11061     case ISD::ROTR:
11062       Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands[0],
11063                                getShiftAmountOperand(Operands[0].getValueType(),
11064                                                      Operands[1])));
11065       break;
11066     case ISD::SIGN_EXTEND_INREG: {
11067       EVT ExtVT = cast<VTSDNode>(Operands[1])->getVT().getVectorElementType();
11068       Scalars.push_back(getNode(N->getOpcode(), dl, EltVT,
11069                                 Operands[0],
11070                                 getValueType(ExtVT)));
11071     }
11072     }
11073   }
11074 
11075   for (; i < ResNE; ++i)
11076     Scalars.push_back(getUNDEF(EltVT));
11077 
11078   EVT VecVT = EVT::getVectorVT(*getContext(), EltVT, ResNE);
11079   return getBuildVector(VecVT, dl, Scalars);
11080 }
11081 
11082 std::pair<SDValue, SDValue> SelectionDAG::UnrollVectorOverflowOp(
11083     SDNode *N, unsigned ResNE) {
11084   unsigned Opcode = N->getOpcode();
11085   assert((Opcode == ISD::UADDO || Opcode == ISD::SADDO ||
11086           Opcode == ISD::USUBO || Opcode == ISD::SSUBO ||
11087           Opcode == ISD::UMULO || Opcode == ISD::SMULO) &&
11088          "Expected an overflow opcode");
11089 
11090   EVT ResVT = N->getValueType(0);
11091   EVT OvVT = N->getValueType(1);
11092   EVT ResEltVT = ResVT.getVectorElementType();
11093   EVT OvEltVT = OvVT.getVectorElementType();
11094   SDLoc dl(N);
11095 
11096   // If ResNE is 0, fully unroll the vector op.
11097   unsigned NE = ResVT.getVectorNumElements();
11098   if (ResNE == 0)
11099     ResNE = NE;
11100   else if (NE > ResNE)
11101     NE = ResNE;
11102 
11103   SmallVector<SDValue, 8> LHSScalars;
11104   SmallVector<SDValue, 8> RHSScalars;
11105   ExtractVectorElements(N->getOperand(0), LHSScalars, 0, NE);
11106   ExtractVectorElements(N->getOperand(1), RHSScalars, 0, NE);
11107 
11108   EVT SVT = TLI->getSetCCResultType(getDataLayout(), *getContext(), ResEltVT);
11109   SDVTList VTs = getVTList(ResEltVT, SVT);
11110   SmallVector<SDValue, 8> ResScalars;
11111   SmallVector<SDValue, 8> OvScalars;
11112   for (unsigned i = 0; i < NE; ++i) {
11113     SDValue Res = getNode(Opcode, dl, VTs, LHSScalars[i], RHSScalars[i]);
11114     SDValue Ov =
11115         getSelect(dl, OvEltVT, Res.getValue(1),
11116                   getBoolConstant(true, dl, OvEltVT, ResVT),
11117                   getConstant(0, dl, OvEltVT));
11118 
11119     ResScalars.push_back(Res);
11120     OvScalars.push_back(Ov);
11121   }
11122 
11123   ResScalars.append(ResNE - NE, getUNDEF(ResEltVT));
11124   OvScalars.append(ResNE - NE, getUNDEF(OvEltVT));
11125 
11126   EVT NewResVT = EVT::getVectorVT(*getContext(), ResEltVT, ResNE);
11127   EVT NewOvVT = EVT::getVectorVT(*getContext(), OvEltVT, ResNE);
11128   return std::make_pair(getBuildVector(NewResVT, dl, ResScalars),
11129                         getBuildVector(NewOvVT, dl, OvScalars));
11130 }
11131 
11132 bool SelectionDAG::areNonVolatileConsecutiveLoads(LoadSDNode *LD,
11133                                                   LoadSDNode *Base,
11134                                                   unsigned Bytes,
11135                                                   int Dist) const {
11136   if (LD->isVolatile() || Base->isVolatile())
11137     return false;
11138   // TODO: probably too restrictive for atomics, revisit
11139   if (!LD->isSimple())
11140     return false;
11141   if (LD->isIndexed() || Base->isIndexed())
11142     return false;
11143   if (LD->getChain() != Base->getChain())
11144     return false;
11145   EVT VT = LD->getValueType(0);
11146   if (VT.getSizeInBits() / 8 != Bytes)
11147     return false;
11148 
11149   auto BaseLocDecomp = BaseIndexOffset::match(Base, *this);
11150   auto LocDecomp = BaseIndexOffset::match(LD, *this);
11151 
11152   int64_t Offset = 0;
11153   if (BaseLocDecomp.equalBaseIndex(LocDecomp, *this, Offset))
11154     return (Dist * Bytes == Offset);
11155   return false;
11156 }
11157 
11158 /// InferPtrAlignment - Infer alignment of a load / store address. Return None
11159 /// if it cannot be inferred.
11160 MaybeAlign SelectionDAG::InferPtrAlign(SDValue Ptr) const {
11161   // If this is a GlobalAddress + cst, return the alignment.
11162   const GlobalValue *GV = nullptr;
11163   int64_t GVOffset = 0;
11164   if (TLI->isGAPlusOffset(Ptr.getNode(), GV, GVOffset)) {
11165     unsigned PtrWidth = getDataLayout().getPointerTypeSizeInBits(GV->getType());
11166     KnownBits Known(PtrWidth);
11167     llvm::computeKnownBits(GV, Known, getDataLayout());
11168     unsigned AlignBits = Known.countMinTrailingZeros();
11169     if (AlignBits)
11170       return commonAlignment(Align(1ull << std::min(31U, AlignBits)), GVOffset);
11171   }
11172 
11173   // If this is a direct reference to a stack slot, use information about the
11174   // stack slot's alignment.
11175   int FrameIdx = INT_MIN;
11176   int64_t FrameOffset = 0;
11177   if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr)) {
11178     FrameIdx = FI->getIndex();
11179   } else if (isBaseWithConstantOffset(Ptr) &&
11180              isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
11181     // Handle FI+Cst
11182     FrameIdx = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
11183     FrameOffset = Ptr.getConstantOperandVal(1);
11184   }
11185 
11186   if (FrameIdx != INT_MIN) {
11187     const MachineFrameInfo &MFI = getMachineFunction().getFrameInfo();
11188     return commonAlignment(MFI.getObjectAlign(FrameIdx), FrameOffset);
11189   }
11190 
11191   return None;
11192 }
11193 
11194 /// GetSplitDestVTs - Compute the VTs needed for the low/hi parts of a type
11195 /// which is split (or expanded) into two not necessarily identical pieces.
11196 std::pair<EVT, EVT> SelectionDAG::GetSplitDestVTs(const EVT &VT) const {
11197   // Currently all types are split in half.
11198   EVT LoVT, HiVT;
11199   if (!VT.isVector())
11200     LoVT = HiVT = TLI->getTypeToTransformTo(*getContext(), VT);
11201   else
11202     LoVT = HiVT = VT.getHalfNumVectorElementsVT(*getContext());
11203 
11204   return std::make_pair(LoVT, HiVT);
11205 }
11206 
11207 /// GetDependentSplitDestVTs - Compute the VTs needed for the low/hi parts of a
11208 /// type, dependent on an enveloping VT that has been split into two identical
11209 /// pieces. Sets the HiIsEmpty flag when hi type has zero storage size.
11210 std::pair<EVT, EVT>
11211 SelectionDAG::GetDependentSplitDestVTs(const EVT &VT, const EVT &EnvVT,
11212                                        bool *HiIsEmpty) const {
11213   EVT EltTp = VT.getVectorElementType();
11214   // Examples:
11215   //   custom VL=8  with enveloping VL=8/8 yields 8/0 (hi empty)
11216   //   custom VL=9  with enveloping VL=8/8 yields 8/1
11217   //   custom VL=10 with enveloping VL=8/8 yields 8/2
11218   //   etc.
11219   ElementCount VTNumElts = VT.getVectorElementCount();
11220   ElementCount EnvNumElts = EnvVT.getVectorElementCount();
11221   assert(VTNumElts.isScalable() == EnvNumElts.isScalable() &&
11222          "Mixing fixed width and scalable vectors when enveloping a type");
11223   EVT LoVT, HiVT;
11224   if (VTNumElts.getKnownMinValue() > EnvNumElts.getKnownMinValue()) {
11225     LoVT = EVT::getVectorVT(*getContext(), EltTp, EnvNumElts);
11226     HiVT = EVT::getVectorVT(*getContext(), EltTp, VTNumElts - EnvNumElts);
11227     *HiIsEmpty = false;
11228   } else {
11229     // Flag that hi type has zero storage size, but return split envelop type
11230     // (this would be easier if vector types with zero elements were allowed).
11231     LoVT = EVT::getVectorVT(*getContext(), EltTp, VTNumElts);
11232     HiVT = EVT::getVectorVT(*getContext(), EltTp, EnvNumElts);
11233     *HiIsEmpty = true;
11234   }
11235   return std::make_pair(LoVT, HiVT);
11236 }
11237 
11238 /// SplitVector - Split the vector with EXTRACT_SUBVECTOR and return the
11239 /// low/high part.
11240 std::pair<SDValue, SDValue>
11241 SelectionDAG::SplitVector(const SDValue &N, const SDLoc &DL, const EVT &LoVT,
11242                           const EVT &HiVT) {
11243   assert(LoVT.isScalableVector() == HiVT.isScalableVector() &&
11244          LoVT.isScalableVector() == N.getValueType().isScalableVector() &&
11245          "Splitting vector with an invalid mixture of fixed and scalable "
11246          "vector types");
11247   assert(LoVT.getVectorMinNumElements() + HiVT.getVectorMinNumElements() <=
11248              N.getValueType().getVectorMinNumElements() &&
11249          "More vector elements requested than available!");
11250   SDValue Lo, Hi;
11251   Lo =
11252       getNode(ISD::EXTRACT_SUBVECTOR, DL, LoVT, N, getVectorIdxConstant(0, DL));
11253   // For scalable vectors it is safe to use LoVT.getVectorMinNumElements()
11254   // (rather than having to use ElementCount), because EXTRACT_SUBVECTOR scales
11255   // IDX with the runtime scaling factor of the result vector type. For
11256   // fixed-width result vectors, that runtime scaling factor is 1.
11257   Hi = getNode(ISD::EXTRACT_SUBVECTOR, DL, HiVT, N,
11258                getVectorIdxConstant(LoVT.getVectorMinNumElements(), DL));
11259   return std::make_pair(Lo, Hi);
11260 }
11261 
11262 std::pair<SDValue, SDValue> SelectionDAG::SplitEVL(SDValue N, EVT VecVT,
11263                                                    const SDLoc &DL) {
11264   // Split the vector length parameter.
11265   // %evl -> umin(%evl, %halfnumelts) and usubsat(%evl - %halfnumelts).
11266   EVT VT = N.getValueType();
11267   assert(VecVT.getVectorElementCount().isKnownEven() &&
11268          "Expecting the mask to be an evenly-sized vector");
11269   unsigned HalfMinNumElts = VecVT.getVectorMinNumElements() / 2;
11270   SDValue HalfNumElts =
11271       VecVT.isFixedLengthVector()
11272           ? getConstant(HalfMinNumElts, DL, VT)
11273           : getVScale(DL, VT, APInt(VT.getScalarSizeInBits(), HalfMinNumElts));
11274   SDValue Lo = getNode(ISD::UMIN, DL, VT, N, HalfNumElts);
11275   SDValue Hi = getNode(ISD::USUBSAT, DL, VT, N, HalfNumElts);
11276   return std::make_pair(Lo, Hi);
11277 }
11278 
11279 /// Widen the vector up to the next power of two using INSERT_SUBVECTOR.
11280 SDValue SelectionDAG::WidenVector(const SDValue &N, const SDLoc &DL) {
11281   EVT VT = N.getValueType();
11282   EVT WideVT = EVT::getVectorVT(*getContext(), VT.getVectorElementType(),
11283                                 NextPowerOf2(VT.getVectorNumElements()));
11284   return getNode(ISD::INSERT_SUBVECTOR, DL, WideVT, getUNDEF(WideVT), N,
11285                  getVectorIdxConstant(0, DL));
11286 }
11287 
11288 void SelectionDAG::ExtractVectorElements(SDValue Op,
11289                                          SmallVectorImpl<SDValue> &Args,
11290                                          unsigned Start, unsigned Count,
11291                                          EVT EltVT) {
11292   EVT VT = Op.getValueType();
11293   if (Count == 0)
11294     Count = VT.getVectorNumElements();
11295   if (EltVT == EVT())
11296     EltVT = VT.getVectorElementType();
11297   SDLoc SL(Op);
11298   for (unsigned i = Start, e = Start + Count; i != e; ++i) {
11299     Args.push_back(getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Op,
11300                            getVectorIdxConstant(i, SL)));
11301   }
11302 }
11303 
11304 // getAddressSpace - Return the address space this GlobalAddress belongs to.
11305 unsigned GlobalAddressSDNode::getAddressSpace() const {
11306   return getGlobal()->getType()->getAddressSpace();
11307 }
11308 
11309 Type *ConstantPoolSDNode::getType() const {
11310   if (isMachineConstantPoolEntry())
11311     return Val.MachineCPVal->getType();
11312   return Val.ConstVal->getType();
11313 }
11314 
11315 bool BuildVectorSDNode::isConstantSplat(APInt &SplatValue, APInt &SplatUndef,
11316                                         unsigned &SplatBitSize,
11317                                         bool &HasAnyUndefs,
11318                                         unsigned MinSplatBits,
11319                                         bool IsBigEndian) const {
11320   EVT VT = getValueType(0);
11321   assert(VT.isVector() && "Expected a vector type");
11322   unsigned VecWidth = VT.getSizeInBits();
11323   if (MinSplatBits > VecWidth)
11324     return false;
11325 
11326   // FIXME: The widths are based on this node's type, but build vectors can
11327   // truncate their operands.
11328   SplatValue = APInt(VecWidth, 0);
11329   SplatUndef = APInt(VecWidth, 0);
11330 
11331   // Get the bits. Bits with undefined values (when the corresponding element
11332   // of the vector is an ISD::UNDEF value) are set in SplatUndef and cleared
11333   // in SplatValue. If any of the values are not constant, give up and return
11334   // false.
11335   unsigned int NumOps = getNumOperands();
11336   assert(NumOps > 0 && "isConstantSplat has 0-size build vector");
11337   unsigned EltWidth = VT.getScalarSizeInBits();
11338 
11339   for (unsigned j = 0; j < NumOps; ++j) {
11340     unsigned i = IsBigEndian ? NumOps - 1 - j : j;
11341     SDValue OpVal = getOperand(i);
11342     unsigned BitPos = j * EltWidth;
11343 
11344     if (OpVal.isUndef())
11345       SplatUndef.setBits(BitPos, BitPos + EltWidth);
11346     else if (auto *CN = dyn_cast<ConstantSDNode>(OpVal))
11347       SplatValue.insertBits(CN->getAPIntValue().zextOrTrunc(EltWidth), BitPos);
11348     else if (auto *CN = dyn_cast<ConstantFPSDNode>(OpVal))
11349       SplatValue.insertBits(CN->getValueAPF().bitcastToAPInt(), BitPos);
11350     else
11351       return false;
11352   }
11353 
11354   // The build_vector is all constants or undefs. Find the smallest element
11355   // size that splats the vector.
11356   HasAnyUndefs = (SplatUndef != 0);
11357 
11358   // FIXME: This does not work for vectors with elements less than 8 bits.
11359   while (VecWidth > 8) {
11360     unsigned HalfSize = VecWidth / 2;
11361     APInt HighValue = SplatValue.extractBits(HalfSize, HalfSize);
11362     APInt LowValue = SplatValue.extractBits(HalfSize, 0);
11363     APInt HighUndef = SplatUndef.extractBits(HalfSize, HalfSize);
11364     APInt LowUndef = SplatUndef.extractBits(HalfSize, 0);
11365 
11366     // If the two halves do not match (ignoring undef bits), stop here.
11367     if ((HighValue & ~LowUndef) != (LowValue & ~HighUndef) ||
11368         MinSplatBits > HalfSize)
11369       break;
11370 
11371     SplatValue = HighValue | LowValue;
11372     SplatUndef = HighUndef & LowUndef;
11373 
11374     VecWidth = HalfSize;
11375   }
11376 
11377   SplatBitSize = VecWidth;
11378   return true;
11379 }
11380 
11381 SDValue BuildVectorSDNode::getSplatValue(const APInt &DemandedElts,
11382                                          BitVector *UndefElements) const {
11383   unsigned NumOps = getNumOperands();
11384   if (UndefElements) {
11385     UndefElements->clear();
11386     UndefElements->resize(NumOps);
11387   }
11388   assert(NumOps == DemandedElts.getBitWidth() && "Unexpected vector size");
11389   if (!DemandedElts)
11390     return SDValue();
11391   SDValue Splatted;
11392   for (unsigned i = 0; i != NumOps; ++i) {
11393     if (!DemandedElts[i])
11394       continue;
11395     SDValue Op = getOperand(i);
11396     if (Op.isUndef()) {
11397       if (UndefElements)
11398         (*UndefElements)[i] = true;
11399     } else if (!Splatted) {
11400       Splatted = Op;
11401     } else if (Splatted != Op) {
11402       return SDValue();
11403     }
11404   }
11405 
11406   if (!Splatted) {
11407     unsigned FirstDemandedIdx = DemandedElts.countTrailingZeros();
11408     assert(getOperand(FirstDemandedIdx).isUndef() &&
11409            "Can only have a splat without a constant for all undefs.");
11410     return getOperand(FirstDemandedIdx);
11411   }
11412 
11413   return Splatted;
11414 }
11415 
11416 SDValue BuildVectorSDNode::getSplatValue(BitVector *UndefElements) const {
11417   APInt DemandedElts = APInt::getAllOnes(getNumOperands());
11418   return getSplatValue(DemandedElts, UndefElements);
11419 }
11420 
11421 bool BuildVectorSDNode::getRepeatedSequence(const APInt &DemandedElts,
11422                                             SmallVectorImpl<SDValue> &Sequence,
11423                                             BitVector *UndefElements) const {
11424   unsigned NumOps = getNumOperands();
11425   Sequence.clear();
11426   if (UndefElements) {
11427     UndefElements->clear();
11428     UndefElements->resize(NumOps);
11429   }
11430   assert(NumOps == DemandedElts.getBitWidth() && "Unexpected vector size");
11431   if (!DemandedElts || NumOps < 2 || !isPowerOf2_32(NumOps))
11432     return false;
11433 
11434   // Set the undefs even if we don't find a sequence (like getSplatValue).
11435   if (UndefElements)
11436     for (unsigned I = 0; I != NumOps; ++I)
11437       if (DemandedElts[I] && getOperand(I).isUndef())
11438         (*UndefElements)[I] = true;
11439 
11440   // Iteratively widen the sequence length looking for repetitions.
11441   for (unsigned SeqLen = 1; SeqLen < NumOps; SeqLen *= 2) {
11442     Sequence.append(SeqLen, SDValue());
11443     for (unsigned I = 0; I != NumOps; ++I) {
11444       if (!DemandedElts[I])
11445         continue;
11446       SDValue &SeqOp = Sequence[I % SeqLen];
11447       SDValue Op = getOperand(I);
11448       if (Op.isUndef()) {
11449         if (!SeqOp)
11450           SeqOp = Op;
11451         continue;
11452       }
11453       if (SeqOp && !SeqOp.isUndef() && SeqOp != Op) {
11454         Sequence.clear();
11455         break;
11456       }
11457       SeqOp = Op;
11458     }
11459     if (!Sequence.empty())
11460       return true;
11461   }
11462 
11463   assert(Sequence.empty() && "Failed to empty non-repeating sequence pattern");
11464   return false;
11465 }
11466 
11467 bool BuildVectorSDNode::getRepeatedSequence(SmallVectorImpl<SDValue> &Sequence,
11468                                             BitVector *UndefElements) const {
11469   APInt DemandedElts = APInt::getAllOnes(getNumOperands());
11470   return getRepeatedSequence(DemandedElts, Sequence, UndefElements);
11471 }
11472 
11473 ConstantSDNode *
11474 BuildVectorSDNode::getConstantSplatNode(const APInt &DemandedElts,
11475                                         BitVector *UndefElements) const {
11476   return dyn_cast_or_null<ConstantSDNode>(
11477       getSplatValue(DemandedElts, UndefElements));
11478 }
11479 
11480 ConstantSDNode *
11481 BuildVectorSDNode::getConstantSplatNode(BitVector *UndefElements) const {
11482   return dyn_cast_or_null<ConstantSDNode>(getSplatValue(UndefElements));
11483 }
11484 
11485 ConstantFPSDNode *
11486 BuildVectorSDNode::getConstantFPSplatNode(const APInt &DemandedElts,
11487                                           BitVector *UndefElements) const {
11488   return dyn_cast_or_null<ConstantFPSDNode>(
11489       getSplatValue(DemandedElts, UndefElements));
11490 }
11491 
11492 ConstantFPSDNode *
11493 BuildVectorSDNode::getConstantFPSplatNode(BitVector *UndefElements) const {
11494   return dyn_cast_or_null<ConstantFPSDNode>(getSplatValue(UndefElements));
11495 }
11496 
11497 int32_t
11498 BuildVectorSDNode::getConstantFPSplatPow2ToLog2Int(BitVector *UndefElements,
11499                                                    uint32_t BitWidth) const {
11500   if (ConstantFPSDNode *CN =
11501           dyn_cast_or_null<ConstantFPSDNode>(getSplatValue(UndefElements))) {
11502     bool IsExact;
11503     APSInt IntVal(BitWidth);
11504     const APFloat &APF = CN->getValueAPF();
11505     if (APF.convertToInteger(IntVal, APFloat::rmTowardZero, &IsExact) !=
11506             APFloat::opOK ||
11507         !IsExact)
11508       return -1;
11509 
11510     return IntVal.exactLogBase2();
11511   }
11512   return -1;
11513 }
11514 
11515 bool BuildVectorSDNode::getConstantRawBits(
11516     bool IsLittleEndian, unsigned DstEltSizeInBits,
11517     SmallVectorImpl<APInt> &RawBitElements, BitVector &UndefElements) const {
11518   // Early-out if this contains anything but Undef/Constant/ConstantFP.
11519   if (!isConstant())
11520     return false;
11521 
11522   unsigned NumSrcOps = getNumOperands();
11523   unsigned SrcEltSizeInBits = getValueType(0).getScalarSizeInBits();
11524   assert(((NumSrcOps * SrcEltSizeInBits) % DstEltSizeInBits) == 0 &&
11525          "Invalid bitcast scale");
11526 
11527   // Extract raw src bits.
11528   SmallVector<APInt> SrcBitElements(NumSrcOps,
11529                                     APInt::getNullValue(SrcEltSizeInBits));
11530   BitVector SrcUndeElements(NumSrcOps, false);
11531 
11532   for (unsigned I = 0; I != NumSrcOps; ++I) {
11533     SDValue Op = getOperand(I);
11534     if (Op.isUndef()) {
11535       SrcUndeElements.set(I);
11536       continue;
11537     }
11538     auto *CInt = dyn_cast<ConstantSDNode>(Op);
11539     auto *CFP = dyn_cast<ConstantFPSDNode>(Op);
11540     assert((CInt || CFP) && "Unknown constant");
11541     SrcBitElements[I] = CInt ? CInt->getAPIntValue().trunc(SrcEltSizeInBits)
11542                              : CFP->getValueAPF().bitcastToAPInt();
11543   }
11544 
11545   // Recast to dst width.
11546   recastRawBits(IsLittleEndian, DstEltSizeInBits, RawBitElements,
11547                 SrcBitElements, UndefElements, SrcUndeElements);
11548   return true;
11549 }
11550 
11551 void BuildVectorSDNode::recastRawBits(bool IsLittleEndian,
11552                                       unsigned DstEltSizeInBits,
11553                                       SmallVectorImpl<APInt> &DstBitElements,
11554                                       ArrayRef<APInt> SrcBitElements,
11555                                       BitVector &DstUndefElements,
11556                                       const BitVector &SrcUndefElements) {
11557   unsigned NumSrcOps = SrcBitElements.size();
11558   unsigned SrcEltSizeInBits = SrcBitElements[0].getBitWidth();
11559   assert(((NumSrcOps * SrcEltSizeInBits) % DstEltSizeInBits) == 0 &&
11560          "Invalid bitcast scale");
11561   assert(NumSrcOps == SrcUndefElements.size() &&
11562          "Vector size mismatch");
11563 
11564   unsigned NumDstOps = (NumSrcOps * SrcEltSizeInBits) / DstEltSizeInBits;
11565   DstUndefElements.clear();
11566   DstUndefElements.resize(NumDstOps, false);
11567   DstBitElements.assign(NumDstOps, APInt::getNullValue(DstEltSizeInBits));
11568 
11569   // Concatenate src elements constant bits together into dst element.
11570   if (SrcEltSizeInBits <= DstEltSizeInBits) {
11571     unsigned Scale = DstEltSizeInBits / SrcEltSizeInBits;
11572     for (unsigned I = 0; I != NumDstOps; ++I) {
11573       DstUndefElements.set(I);
11574       APInt &DstBits = DstBitElements[I];
11575       for (unsigned J = 0; J != Scale; ++J) {
11576         unsigned Idx = (I * Scale) + (IsLittleEndian ? J : (Scale - J - 1));
11577         if (SrcUndefElements[Idx])
11578           continue;
11579         DstUndefElements.reset(I);
11580         const APInt &SrcBits = SrcBitElements[Idx];
11581         assert(SrcBits.getBitWidth() == SrcEltSizeInBits &&
11582                "Illegal constant bitwidths");
11583         DstBits.insertBits(SrcBits, J * SrcEltSizeInBits);
11584       }
11585     }
11586     return;
11587   }
11588 
11589   // Split src element constant bits into dst elements.
11590   unsigned Scale = SrcEltSizeInBits / DstEltSizeInBits;
11591   for (unsigned I = 0; I != NumSrcOps; ++I) {
11592     if (SrcUndefElements[I]) {
11593       DstUndefElements.set(I * Scale, (I + 1) * Scale);
11594       continue;
11595     }
11596     const APInt &SrcBits = SrcBitElements[I];
11597     for (unsigned J = 0; J != Scale; ++J) {
11598       unsigned Idx = (I * Scale) + (IsLittleEndian ? J : (Scale - J - 1));
11599       APInt &DstBits = DstBitElements[Idx];
11600       DstBits = SrcBits.extractBits(DstEltSizeInBits, J * DstEltSizeInBits);
11601     }
11602   }
11603 }
11604 
11605 bool BuildVectorSDNode::isConstant() const {
11606   for (const SDValue &Op : op_values()) {
11607     unsigned Opc = Op.getOpcode();
11608     if (Opc != ISD::UNDEF && Opc != ISD::Constant && Opc != ISD::ConstantFP)
11609       return false;
11610   }
11611   return true;
11612 }
11613 
11614 bool ShuffleVectorSDNode::isSplatMask(const int *Mask, EVT VT) {
11615   // Find the first non-undef value in the shuffle mask.
11616   unsigned i, e;
11617   for (i = 0, e = VT.getVectorNumElements(); i != e && Mask[i] < 0; ++i)
11618     /* search */;
11619 
11620   // If all elements are undefined, this shuffle can be considered a splat
11621   // (although it should eventually get simplified away completely).
11622   if (i == e)
11623     return true;
11624 
11625   // Make sure all remaining elements are either undef or the same as the first
11626   // non-undef value.
11627   for (int Idx = Mask[i]; i != e; ++i)
11628     if (Mask[i] >= 0 && Mask[i] != Idx)
11629       return false;
11630   return true;
11631 }
11632 
11633 // Returns the SDNode if it is a constant integer BuildVector
11634 // or constant integer.
11635 SDNode *SelectionDAG::isConstantIntBuildVectorOrConstantInt(SDValue N) const {
11636   if (isa<ConstantSDNode>(N))
11637     return N.getNode();
11638   if (ISD::isBuildVectorOfConstantSDNodes(N.getNode()))
11639     return N.getNode();
11640   // Treat a GlobalAddress supporting constant offset folding as a
11641   // constant integer.
11642   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N))
11643     if (GA->getOpcode() == ISD::GlobalAddress &&
11644         TLI->isOffsetFoldingLegal(GA))
11645       return GA;
11646   if ((N.getOpcode() == ISD::SPLAT_VECTOR) &&
11647       isa<ConstantSDNode>(N.getOperand(0)))
11648     return N.getNode();
11649   return nullptr;
11650 }
11651 
11652 // Returns the SDNode if it is a constant float BuildVector
11653 // or constant float.
11654 SDNode *SelectionDAG::isConstantFPBuildVectorOrConstantFP(SDValue N) const {
11655   if (isa<ConstantFPSDNode>(N))
11656     return N.getNode();
11657 
11658   if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode()))
11659     return N.getNode();
11660 
11661   if ((N.getOpcode() == ISD::SPLAT_VECTOR) &&
11662       isa<ConstantFPSDNode>(N.getOperand(0)))
11663     return N.getNode();
11664 
11665   return nullptr;
11666 }
11667 
11668 void SelectionDAG::createOperands(SDNode *Node, ArrayRef<SDValue> Vals) {
11669   assert(!Node->OperandList && "Node already has operands");
11670   assert(SDNode::getMaxNumOperands() >= Vals.size() &&
11671          "too many operands to fit into SDNode");
11672   SDUse *Ops = OperandRecycler.allocate(
11673       ArrayRecycler<SDUse>::Capacity::get(Vals.size()), OperandAllocator);
11674 
11675   bool IsDivergent = false;
11676   for (unsigned I = 0; I != Vals.size(); ++I) {
11677     Ops[I].setUser(Node);
11678     Ops[I].setInitial(Vals[I]);
11679     if (Ops[I].Val.getValueType() != MVT::Other) // Skip Chain. It does not carry divergence.
11680       IsDivergent |= Ops[I].getNode()->isDivergent();
11681   }
11682   Node->NumOperands = Vals.size();
11683   Node->OperandList = Ops;
11684   if (!TLI->isSDNodeAlwaysUniform(Node)) {
11685     IsDivergent |= TLI->isSDNodeSourceOfDivergence(Node, FLI, DA);
11686     Node->SDNodeBits.IsDivergent = IsDivergent;
11687   }
11688   checkForCycles(Node);
11689 }
11690 
11691 SDValue SelectionDAG::getTokenFactor(const SDLoc &DL,
11692                                      SmallVectorImpl<SDValue> &Vals) {
11693   size_t Limit = SDNode::getMaxNumOperands();
11694   while (Vals.size() > Limit) {
11695     unsigned SliceIdx = Vals.size() - Limit;
11696     auto ExtractedTFs = ArrayRef<SDValue>(Vals).slice(SliceIdx, Limit);
11697     SDValue NewTF = getNode(ISD::TokenFactor, DL, MVT::Other, ExtractedTFs);
11698     Vals.erase(Vals.begin() + SliceIdx, Vals.end());
11699     Vals.emplace_back(NewTF);
11700   }
11701   return getNode(ISD::TokenFactor, DL, MVT::Other, Vals);
11702 }
11703 
11704 SDValue SelectionDAG::getNeutralElement(unsigned Opcode, const SDLoc &DL,
11705                                         EVT VT, SDNodeFlags Flags) {
11706   switch (Opcode) {
11707   default:
11708     return SDValue();
11709   case ISD::ADD:
11710   case ISD::OR:
11711   case ISD::XOR:
11712   case ISD::UMAX:
11713     return getConstant(0, DL, VT);
11714   case ISD::MUL:
11715     return getConstant(1, DL, VT);
11716   case ISD::AND:
11717   case ISD::UMIN:
11718     return getAllOnesConstant(DL, VT);
11719   case ISD::SMAX:
11720     return getConstant(APInt::getSignedMinValue(VT.getSizeInBits()), DL, VT);
11721   case ISD::SMIN:
11722     return getConstant(APInt::getSignedMaxValue(VT.getSizeInBits()), DL, VT);
11723   case ISD::FADD:
11724     return getConstantFP(-0.0, DL, VT);
11725   case ISD::FMUL:
11726     return getConstantFP(1.0, DL, VT);
11727   case ISD::FMINNUM:
11728   case ISD::FMAXNUM: {
11729     // Neutral element for fminnum is NaN, Inf or FLT_MAX, depending on FMF.
11730     const fltSemantics &Semantics = EVTToAPFloatSemantics(VT);
11731     APFloat NeutralAF = !Flags.hasNoNaNs() ? APFloat::getQNaN(Semantics) :
11732                         !Flags.hasNoInfs() ? APFloat::getInf(Semantics) :
11733                         APFloat::getLargest(Semantics);
11734     if (Opcode == ISD::FMAXNUM)
11735       NeutralAF.changeSign();
11736 
11737     return getConstantFP(NeutralAF, DL, VT);
11738   }
11739   }
11740 }
11741 
11742 #ifndef NDEBUG
11743 static void checkForCyclesHelper(const SDNode *N,
11744                                  SmallPtrSetImpl<const SDNode*> &Visited,
11745                                  SmallPtrSetImpl<const SDNode*> &Checked,
11746                                  const llvm::SelectionDAG *DAG) {
11747   // If this node has already been checked, don't check it again.
11748   if (Checked.count(N))
11749     return;
11750 
11751   // If a node has already been visited on this depth-first walk, reject it as
11752   // a cycle.
11753   if (!Visited.insert(N).second) {
11754     errs() << "Detected cycle in SelectionDAG\n";
11755     dbgs() << "Offending node:\n";
11756     N->dumprFull(DAG); dbgs() << "\n";
11757     abort();
11758   }
11759 
11760   for (const SDValue &Op : N->op_values())
11761     checkForCyclesHelper(Op.getNode(), Visited, Checked, DAG);
11762 
11763   Checked.insert(N);
11764   Visited.erase(N);
11765 }
11766 #endif
11767 
11768 void llvm::checkForCycles(const llvm::SDNode *N,
11769                           const llvm::SelectionDAG *DAG,
11770                           bool force) {
11771 #ifndef NDEBUG
11772   bool check = force;
11773 #ifdef EXPENSIVE_CHECKS
11774   check = true;
11775 #endif  // EXPENSIVE_CHECKS
11776   if (check) {
11777     assert(N && "Checking nonexistent SDNode");
11778     SmallPtrSet<const SDNode*, 32> visited;
11779     SmallPtrSet<const SDNode*, 32> checked;
11780     checkForCyclesHelper(N, visited, checked, DAG);
11781   }
11782 #endif  // !NDEBUG
11783 }
11784 
11785 void llvm::checkForCycles(const llvm::SelectionDAG *DAG, bool force) {
11786   checkForCycles(DAG->getRoot().getNode(), DAG, force);
11787 }
11788