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 (const 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 (const 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::MERGE_VALUES:
2951     return computeKnownBits(Op.getOperand(Op.getResNo()), DemandedElts,
2952                             Depth + 1);
2953   case ISD::BUILD_VECTOR:
2954     // Collect the known bits that are shared by every demanded vector element.
2955     Known.Zero.setAllBits(); Known.One.setAllBits();
2956     for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
2957       if (!DemandedElts[i])
2958         continue;
2959 
2960       SDValue SrcOp = Op.getOperand(i);
2961       Known2 = computeKnownBits(SrcOp, Depth + 1);
2962 
2963       // BUILD_VECTOR can implicitly truncate sources, we must handle this.
2964       if (SrcOp.getValueSizeInBits() != BitWidth) {
2965         assert(SrcOp.getValueSizeInBits() > BitWidth &&
2966                "Expected BUILD_VECTOR implicit truncation");
2967         Known2 = Known2.trunc(BitWidth);
2968       }
2969 
2970       // Known bits are the values that are shared by every demanded element.
2971       Known = KnownBits::commonBits(Known, Known2);
2972 
2973       // If we don't know any bits, early out.
2974       if (Known.isUnknown())
2975         break;
2976     }
2977     break;
2978   case ISD::VECTOR_SHUFFLE: {
2979     // Collect the known bits that are shared by every vector element referenced
2980     // by the shuffle.
2981     APInt DemandedLHS(NumElts, 0), DemandedRHS(NumElts, 0);
2982     Known.Zero.setAllBits(); Known.One.setAllBits();
2983     const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op);
2984     assert(NumElts == SVN->getMask().size() && "Unexpected vector size");
2985     for (unsigned i = 0; i != NumElts; ++i) {
2986       if (!DemandedElts[i])
2987         continue;
2988 
2989       int M = SVN->getMaskElt(i);
2990       if (M < 0) {
2991         // For UNDEF elements, we don't know anything about the common state of
2992         // the shuffle result.
2993         Known.resetAll();
2994         DemandedLHS.clearAllBits();
2995         DemandedRHS.clearAllBits();
2996         break;
2997       }
2998 
2999       if ((unsigned)M < NumElts)
3000         DemandedLHS.setBit((unsigned)M % NumElts);
3001       else
3002         DemandedRHS.setBit((unsigned)M % NumElts);
3003     }
3004     // Known bits are the values that are shared by every demanded element.
3005     if (!!DemandedLHS) {
3006       SDValue LHS = Op.getOperand(0);
3007       Known2 = computeKnownBits(LHS, DemandedLHS, Depth + 1);
3008       Known = KnownBits::commonBits(Known, Known2);
3009     }
3010     // If we don't know any bits, early out.
3011     if (Known.isUnknown())
3012       break;
3013     if (!!DemandedRHS) {
3014       SDValue RHS = Op.getOperand(1);
3015       Known2 = computeKnownBits(RHS, DemandedRHS, Depth + 1);
3016       Known = KnownBits::commonBits(Known, Known2);
3017     }
3018     break;
3019   }
3020   case ISD::CONCAT_VECTORS: {
3021     // Split DemandedElts and test each of the demanded subvectors.
3022     Known.Zero.setAllBits(); Known.One.setAllBits();
3023     EVT SubVectorVT = Op.getOperand(0).getValueType();
3024     unsigned NumSubVectorElts = SubVectorVT.getVectorNumElements();
3025     unsigned NumSubVectors = Op.getNumOperands();
3026     for (unsigned i = 0; i != NumSubVectors; ++i) {
3027       APInt DemandedSub =
3028           DemandedElts.extractBits(NumSubVectorElts, i * NumSubVectorElts);
3029       if (!!DemandedSub) {
3030         SDValue Sub = Op.getOperand(i);
3031         Known2 = computeKnownBits(Sub, DemandedSub, Depth + 1);
3032         Known = KnownBits::commonBits(Known, Known2);
3033       }
3034       // If we don't know any bits, early out.
3035       if (Known.isUnknown())
3036         break;
3037     }
3038     break;
3039   }
3040   case ISD::INSERT_SUBVECTOR: {
3041     // Demand any elements from the subvector and the remainder from the src its
3042     // inserted into.
3043     SDValue Src = Op.getOperand(0);
3044     SDValue Sub = Op.getOperand(1);
3045     uint64_t Idx = Op.getConstantOperandVal(2);
3046     unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
3047     APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
3048     APInt DemandedSrcElts = DemandedElts;
3049     DemandedSrcElts.insertBits(APInt::getZero(NumSubElts), Idx);
3050 
3051     Known.One.setAllBits();
3052     Known.Zero.setAllBits();
3053     if (!!DemandedSubElts) {
3054       Known = computeKnownBits(Sub, DemandedSubElts, Depth + 1);
3055       if (Known.isUnknown())
3056         break; // early-out.
3057     }
3058     if (!!DemandedSrcElts) {
3059       Known2 = computeKnownBits(Src, DemandedSrcElts, Depth + 1);
3060       Known = KnownBits::commonBits(Known, Known2);
3061     }
3062     break;
3063   }
3064   case ISD::EXTRACT_SUBVECTOR: {
3065     // Offset the demanded elts by the subvector index.
3066     SDValue Src = Op.getOperand(0);
3067     // Bail until we can represent demanded elements for scalable vectors.
3068     if (Src.getValueType().isScalableVector())
3069       break;
3070     uint64_t Idx = Op.getConstantOperandVal(1);
3071     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
3072     APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts).shl(Idx);
3073     Known = computeKnownBits(Src, DemandedSrcElts, Depth + 1);
3074     break;
3075   }
3076   case ISD::SCALAR_TO_VECTOR: {
3077     // We know about scalar_to_vector as much as we know about it source,
3078     // which becomes the first element of otherwise unknown vector.
3079     if (DemandedElts != 1)
3080       break;
3081 
3082     SDValue N0 = Op.getOperand(0);
3083     Known = computeKnownBits(N0, Depth + 1);
3084     if (N0.getValueSizeInBits() != BitWidth)
3085       Known = Known.trunc(BitWidth);
3086 
3087     break;
3088   }
3089   case ISD::BITCAST: {
3090     SDValue N0 = Op.getOperand(0);
3091     EVT SubVT = N0.getValueType();
3092     unsigned SubBitWidth = SubVT.getScalarSizeInBits();
3093 
3094     // Ignore bitcasts from unsupported types.
3095     if (!(SubVT.isInteger() || SubVT.isFloatingPoint()))
3096       break;
3097 
3098     // Fast handling of 'identity' bitcasts.
3099     if (BitWidth == SubBitWidth) {
3100       Known = computeKnownBits(N0, DemandedElts, Depth + 1);
3101       break;
3102     }
3103 
3104     bool IsLE = getDataLayout().isLittleEndian();
3105 
3106     // Bitcast 'small element' vector to 'large element' scalar/vector.
3107     if ((BitWidth % SubBitWidth) == 0) {
3108       assert(N0.getValueType().isVector() && "Expected bitcast from vector");
3109 
3110       // Collect known bits for the (larger) output by collecting the known
3111       // bits from each set of sub elements and shift these into place.
3112       // We need to separately call computeKnownBits for each set of
3113       // sub elements as the knownbits for each is likely to be different.
3114       unsigned SubScale = BitWidth / SubBitWidth;
3115       APInt SubDemandedElts(NumElts * SubScale, 0);
3116       for (unsigned i = 0; i != NumElts; ++i)
3117         if (DemandedElts[i])
3118           SubDemandedElts.setBit(i * SubScale);
3119 
3120       for (unsigned i = 0; i != SubScale; ++i) {
3121         Known2 = computeKnownBits(N0, SubDemandedElts.shl(i),
3122                          Depth + 1);
3123         unsigned Shifts = IsLE ? i : SubScale - 1 - i;
3124         Known.insertBits(Known2, SubBitWidth * Shifts);
3125       }
3126     }
3127 
3128     // Bitcast 'large element' scalar/vector to 'small element' vector.
3129     if ((SubBitWidth % BitWidth) == 0) {
3130       assert(Op.getValueType().isVector() && "Expected bitcast to vector");
3131 
3132       // Collect known bits for the (smaller) output by collecting the known
3133       // bits from the overlapping larger input elements and extracting the
3134       // sub sections we actually care about.
3135       unsigned SubScale = SubBitWidth / BitWidth;
3136       APInt SubDemandedElts =
3137           APIntOps::ScaleBitMask(DemandedElts, NumElts / SubScale);
3138       Known2 = computeKnownBits(N0, SubDemandedElts, Depth + 1);
3139 
3140       Known.Zero.setAllBits(); Known.One.setAllBits();
3141       for (unsigned i = 0; i != NumElts; ++i)
3142         if (DemandedElts[i]) {
3143           unsigned Shifts = IsLE ? i : NumElts - 1 - i;
3144           unsigned Offset = (Shifts % SubScale) * BitWidth;
3145           Known = KnownBits::commonBits(Known,
3146                                         Known2.extractBits(BitWidth, Offset));
3147           // If we don't know any bits, early out.
3148           if (Known.isUnknown())
3149             break;
3150         }
3151     }
3152     break;
3153   }
3154   case ISD::AND:
3155     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3156     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3157 
3158     Known &= Known2;
3159     break;
3160   case ISD::OR:
3161     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3162     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3163 
3164     Known |= Known2;
3165     break;
3166   case ISD::XOR:
3167     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3168     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3169 
3170     Known ^= Known2;
3171     break;
3172   case ISD::MUL: {
3173     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3174     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3175     bool SelfMultiply = Op.getOperand(0) == Op.getOperand(1);
3176     // TODO: SelfMultiply can be poison, but not undef.
3177     if (SelfMultiply)
3178       SelfMultiply &= isGuaranteedNotToBeUndefOrPoison(
3179           Op.getOperand(0), DemandedElts, false, Depth + 1);
3180     Known = KnownBits::mul(Known, Known2, SelfMultiply);
3181 
3182     // If the multiplication is known not to overflow, the product of a number
3183     // with itself is non-negative. Only do this if we didn't already computed
3184     // the opposite value for the sign bit.
3185     if (Op->getFlags().hasNoSignedWrap() &&
3186         Op.getOperand(0) == Op.getOperand(1) &&
3187         !Known.isNegative())
3188       Known.makeNonNegative();
3189     break;
3190   }
3191   case ISD::MULHU: {
3192     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3193     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3194     Known = KnownBits::mulhu(Known, Known2);
3195     break;
3196   }
3197   case ISD::MULHS: {
3198     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3199     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3200     Known = KnownBits::mulhs(Known, Known2);
3201     break;
3202   }
3203   case ISD::UMUL_LOHI: {
3204     assert((Op.getResNo() == 0 || Op.getResNo() == 1) && "Unknown result");
3205     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3206     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3207     bool SelfMultiply = Op.getOperand(0) == Op.getOperand(1);
3208     if (Op.getResNo() == 0)
3209       Known = KnownBits::mul(Known, Known2, SelfMultiply);
3210     else
3211       Known = KnownBits::mulhu(Known, Known2);
3212     break;
3213   }
3214   case ISD::SMUL_LOHI: {
3215     assert((Op.getResNo() == 0 || Op.getResNo() == 1) && "Unknown result");
3216     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3217     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3218     bool SelfMultiply = Op.getOperand(0) == Op.getOperand(1);
3219     if (Op.getResNo() == 0)
3220       Known = KnownBits::mul(Known, Known2, SelfMultiply);
3221     else
3222       Known = KnownBits::mulhs(Known, Known2);
3223     break;
3224   }
3225   case ISD::AVGCEILU: {
3226     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3227     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3228     Known = Known.zext(BitWidth + 1);
3229     Known2 = Known2.zext(BitWidth + 1);
3230     KnownBits One = KnownBits::makeConstant(APInt(1, 1));
3231     Known = KnownBits::computeForAddCarry(Known, Known2, One);
3232     Known = Known.extractBits(BitWidth, 1);
3233     break;
3234   }
3235   case ISD::SELECT:
3236   case ISD::VSELECT:
3237     Known = computeKnownBits(Op.getOperand(2), DemandedElts, Depth+1);
3238     // If we don't know any bits, early out.
3239     if (Known.isUnknown())
3240       break;
3241     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth+1);
3242 
3243     // Only known if known in both the LHS and RHS.
3244     Known = KnownBits::commonBits(Known, Known2);
3245     break;
3246   case ISD::SELECT_CC:
3247     Known = computeKnownBits(Op.getOperand(3), DemandedElts, Depth+1);
3248     // If we don't know any bits, early out.
3249     if (Known.isUnknown())
3250       break;
3251     Known2 = computeKnownBits(Op.getOperand(2), DemandedElts, Depth+1);
3252 
3253     // Only known if known in both the LHS and RHS.
3254     Known = KnownBits::commonBits(Known, Known2);
3255     break;
3256   case ISD::SMULO:
3257   case ISD::UMULO:
3258     if (Op.getResNo() != 1)
3259       break;
3260     // The boolean result conforms to getBooleanContents.
3261     // If we know the result of a setcc has the top bits zero, use this info.
3262     // We know that we have an integer-based boolean since these operations
3263     // are only available for integer.
3264     if (TLI->getBooleanContents(Op.getValueType().isVector(), false) ==
3265             TargetLowering::ZeroOrOneBooleanContent &&
3266         BitWidth > 1)
3267       Known.Zero.setBitsFrom(1);
3268     break;
3269   case ISD::SETCC:
3270   case ISD::SETCCCARRY:
3271   case ISD::STRICT_FSETCC:
3272   case ISD::STRICT_FSETCCS: {
3273     unsigned OpNo = Op->isStrictFPOpcode() ? 1 : 0;
3274     // If we know the result of a setcc has the top bits zero, use this info.
3275     if (TLI->getBooleanContents(Op.getOperand(OpNo).getValueType()) ==
3276             TargetLowering::ZeroOrOneBooleanContent &&
3277         BitWidth > 1)
3278       Known.Zero.setBitsFrom(1);
3279     break;
3280   }
3281   case ISD::SHL:
3282     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3283     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3284     Known = KnownBits::shl(Known, Known2);
3285 
3286     // Minimum shift low bits are known zero.
3287     if (const APInt *ShMinAmt =
3288             getValidMinimumShiftAmountConstant(Op, DemandedElts))
3289       Known.Zero.setLowBits(ShMinAmt->getZExtValue());
3290     break;
3291   case ISD::SRL:
3292     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3293     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3294     Known = KnownBits::lshr(Known, Known2);
3295 
3296     // Minimum shift high bits are known zero.
3297     if (const APInt *ShMinAmt =
3298             getValidMinimumShiftAmountConstant(Op, DemandedElts))
3299       Known.Zero.setHighBits(ShMinAmt->getZExtValue());
3300     break;
3301   case ISD::SRA:
3302     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3303     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3304     Known = KnownBits::ashr(Known, Known2);
3305     // TODO: Add minimum shift high known sign bits.
3306     break;
3307   case ISD::FSHL:
3308   case ISD::FSHR:
3309     if (ConstantSDNode *C = isConstOrConstSplat(Op.getOperand(2), DemandedElts)) {
3310       unsigned Amt = C->getAPIntValue().urem(BitWidth);
3311 
3312       // For fshl, 0-shift returns the 1st arg.
3313       // For fshr, 0-shift returns the 2nd arg.
3314       if (Amt == 0) {
3315         Known = computeKnownBits(Op.getOperand(Opcode == ISD::FSHL ? 0 : 1),
3316                                  DemandedElts, Depth + 1);
3317         break;
3318       }
3319 
3320       // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW)))
3321       // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW))
3322       Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3323       Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3324       if (Opcode == ISD::FSHL) {
3325         Known.One <<= Amt;
3326         Known.Zero <<= Amt;
3327         Known2.One.lshrInPlace(BitWidth - Amt);
3328         Known2.Zero.lshrInPlace(BitWidth - Amt);
3329       } else {
3330         Known.One <<= BitWidth - Amt;
3331         Known.Zero <<= BitWidth - Amt;
3332         Known2.One.lshrInPlace(Amt);
3333         Known2.Zero.lshrInPlace(Amt);
3334       }
3335       Known.One |= Known2.One;
3336       Known.Zero |= Known2.Zero;
3337     }
3338     break;
3339   case ISD::SIGN_EXTEND_INREG: {
3340     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3341     EVT EVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
3342     Known = Known.sextInReg(EVT.getScalarSizeInBits());
3343     break;
3344   }
3345   case ISD::CTTZ:
3346   case ISD::CTTZ_ZERO_UNDEF: {
3347     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3348     // If we have a known 1, its position is our upper bound.
3349     unsigned PossibleTZ = Known2.countMaxTrailingZeros();
3350     unsigned LowBits = Log2_32(PossibleTZ) + 1;
3351     Known.Zero.setBitsFrom(LowBits);
3352     break;
3353   }
3354   case ISD::CTLZ:
3355   case ISD::CTLZ_ZERO_UNDEF: {
3356     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3357     // If we have a known 1, its position is our upper bound.
3358     unsigned PossibleLZ = Known2.countMaxLeadingZeros();
3359     unsigned LowBits = Log2_32(PossibleLZ) + 1;
3360     Known.Zero.setBitsFrom(LowBits);
3361     break;
3362   }
3363   case ISD::CTPOP: {
3364     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3365     // If we know some of the bits are zero, they can't be one.
3366     unsigned PossibleOnes = Known2.countMaxPopulation();
3367     Known.Zero.setBitsFrom(Log2_32(PossibleOnes) + 1);
3368     break;
3369   }
3370   case ISD::PARITY: {
3371     // Parity returns 0 everywhere but the LSB.
3372     Known.Zero.setBitsFrom(1);
3373     break;
3374   }
3375   case ISD::LOAD: {
3376     LoadSDNode *LD = cast<LoadSDNode>(Op);
3377     const Constant *Cst = TLI->getTargetConstantFromLoad(LD);
3378     if (ISD::isNON_EXTLoad(LD) && Cst) {
3379       // Determine any common known bits from the loaded constant pool value.
3380       Type *CstTy = Cst->getType();
3381       if ((NumElts * BitWidth) == CstTy->getPrimitiveSizeInBits()) {
3382         // If its a vector splat, then we can (quickly) reuse the scalar path.
3383         // NOTE: We assume all elements match and none are UNDEF.
3384         if (CstTy->isVectorTy()) {
3385           if (const Constant *Splat = Cst->getSplatValue()) {
3386             Cst = Splat;
3387             CstTy = Cst->getType();
3388           }
3389         }
3390         // TODO - do we need to handle different bitwidths?
3391         if (CstTy->isVectorTy() && BitWidth == CstTy->getScalarSizeInBits()) {
3392           // Iterate across all vector elements finding common known bits.
3393           Known.One.setAllBits();
3394           Known.Zero.setAllBits();
3395           for (unsigned i = 0; i != NumElts; ++i) {
3396             if (!DemandedElts[i])
3397               continue;
3398             if (Constant *Elt = Cst->getAggregateElement(i)) {
3399               if (auto *CInt = dyn_cast<ConstantInt>(Elt)) {
3400                 const APInt &Value = CInt->getValue();
3401                 Known.One &= Value;
3402                 Known.Zero &= ~Value;
3403                 continue;
3404               }
3405               if (auto *CFP = dyn_cast<ConstantFP>(Elt)) {
3406                 APInt Value = CFP->getValueAPF().bitcastToAPInt();
3407                 Known.One &= Value;
3408                 Known.Zero &= ~Value;
3409                 continue;
3410               }
3411             }
3412             Known.One.clearAllBits();
3413             Known.Zero.clearAllBits();
3414             break;
3415           }
3416         } else if (BitWidth == CstTy->getPrimitiveSizeInBits()) {
3417           if (auto *CInt = dyn_cast<ConstantInt>(Cst)) {
3418             Known = KnownBits::makeConstant(CInt->getValue());
3419           } else if (auto *CFP = dyn_cast<ConstantFP>(Cst)) {
3420             Known =
3421                 KnownBits::makeConstant(CFP->getValueAPF().bitcastToAPInt());
3422           }
3423         }
3424       }
3425     } else if (ISD::isZEXTLoad(Op.getNode()) && Op.getResNo() == 0) {
3426       // If this is a ZEXTLoad and we are looking at the loaded value.
3427       EVT VT = LD->getMemoryVT();
3428       unsigned MemBits = VT.getScalarSizeInBits();
3429       Known.Zero.setBitsFrom(MemBits);
3430     } else if (const MDNode *Ranges = LD->getRanges()) {
3431       if (LD->getExtensionType() == ISD::NON_EXTLOAD)
3432         computeKnownBitsFromRangeMetadata(*Ranges, Known);
3433     }
3434     break;
3435   }
3436   case ISD::ZERO_EXTEND_VECTOR_INREG: {
3437     EVT InVT = Op.getOperand(0).getValueType();
3438     APInt InDemandedElts = DemandedElts.zext(InVT.getVectorNumElements());
3439     Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1);
3440     Known = Known.zext(BitWidth);
3441     break;
3442   }
3443   case ISD::ZERO_EXTEND: {
3444     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3445     Known = Known.zext(BitWidth);
3446     break;
3447   }
3448   case ISD::SIGN_EXTEND_VECTOR_INREG: {
3449     EVT InVT = Op.getOperand(0).getValueType();
3450     APInt InDemandedElts = DemandedElts.zext(InVT.getVectorNumElements());
3451     Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1);
3452     // If the sign bit is known to be zero or one, then sext will extend
3453     // it to the top bits, else it will just zext.
3454     Known = Known.sext(BitWidth);
3455     break;
3456   }
3457   case ISD::SIGN_EXTEND: {
3458     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3459     // If the sign bit is known to be zero or one, then sext will extend
3460     // it to the top bits, else it will just zext.
3461     Known = Known.sext(BitWidth);
3462     break;
3463   }
3464   case ISD::ANY_EXTEND_VECTOR_INREG: {
3465     EVT InVT = Op.getOperand(0).getValueType();
3466     APInt InDemandedElts = DemandedElts.zext(InVT.getVectorNumElements());
3467     Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1);
3468     Known = Known.anyext(BitWidth);
3469     break;
3470   }
3471   case ISD::ANY_EXTEND: {
3472     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3473     Known = Known.anyext(BitWidth);
3474     break;
3475   }
3476   case ISD::TRUNCATE: {
3477     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3478     Known = Known.trunc(BitWidth);
3479     break;
3480   }
3481   case ISD::AssertZext: {
3482     EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
3483     APInt InMask = APInt::getLowBitsSet(BitWidth, VT.getSizeInBits());
3484     Known = computeKnownBits(Op.getOperand(0), Depth+1);
3485     Known.Zero |= (~InMask);
3486     Known.One  &= (~Known.Zero);
3487     break;
3488   }
3489   case ISD::AssertAlign: {
3490     unsigned LogOfAlign = Log2(cast<AssertAlignSDNode>(Op)->getAlign());
3491     assert(LogOfAlign != 0);
3492 
3493     // TODO: Should use maximum with source
3494     // If a node is guaranteed to be aligned, set low zero bits accordingly as
3495     // well as clearing one bits.
3496     Known.Zero.setLowBits(LogOfAlign);
3497     Known.One.clearLowBits(LogOfAlign);
3498     break;
3499   }
3500   case ISD::FGETSIGN:
3501     // All bits are zero except the low bit.
3502     Known.Zero.setBitsFrom(1);
3503     break;
3504   case ISD::USUBO:
3505   case ISD::SSUBO:
3506   case ISD::SUBCARRY:
3507   case ISD::SSUBO_CARRY:
3508     if (Op.getResNo() == 1) {
3509       // If we know the result of a setcc has the top bits zero, use this info.
3510       if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) ==
3511               TargetLowering::ZeroOrOneBooleanContent &&
3512           BitWidth > 1)
3513         Known.Zero.setBitsFrom(1);
3514       break;
3515     }
3516     LLVM_FALLTHROUGH;
3517   case ISD::SUB:
3518   case ISD::SUBC: {
3519     assert(Op.getResNo() == 0 &&
3520            "We only compute knownbits for the difference here.");
3521 
3522     // TODO: Compute influence of the carry operand.
3523     if (Opcode == ISD::SUBCARRY || Opcode == ISD::SSUBO_CARRY)
3524       break;
3525 
3526     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3527     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3528     Known = KnownBits::computeForAddSub(/* Add */ false, /* NSW */ false,
3529                                         Known, Known2);
3530     break;
3531   }
3532   case ISD::UADDO:
3533   case ISD::SADDO:
3534   case ISD::ADDCARRY:
3535   case ISD::SADDO_CARRY:
3536     if (Op.getResNo() == 1) {
3537       // If we know the result of a setcc has the top bits zero, use this info.
3538       if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) ==
3539               TargetLowering::ZeroOrOneBooleanContent &&
3540           BitWidth > 1)
3541         Known.Zero.setBitsFrom(1);
3542       break;
3543     }
3544     LLVM_FALLTHROUGH;
3545   case ISD::ADD:
3546   case ISD::ADDC:
3547   case ISD::ADDE: {
3548     assert(Op.getResNo() == 0 && "We only compute knownbits for the sum here.");
3549 
3550     // With ADDE and ADDCARRY, a carry bit may be added in.
3551     KnownBits Carry(1);
3552     if (Opcode == ISD::ADDE)
3553       // Can't track carry from glue, set carry to unknown.
3554       Carry.resetAll();
3555     else if (Opcode == ISD::ADDCARRY || Opcode == ISD::SADDO_CARRY)
3556       // TODO: Compute known bits for the carry operand. Not sure if it is worth
3557       // the trouble (how often will we find a known carry bit). And I haven't
3558       // tested this very much yet, but something like this might work:
3559       //   Carry = computeKnownBits(Op.getOperand(2), DemandedElts, Depth + 1);
3560       //   Carry = Carry.zextOrTrunc(1, false);
3561       Carry.resetAll();
3562     else
3563       Carry.setAllZero();
3564 
3565     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3566     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3567     Known = KnownBits::computeForAddCarry(Known, Known2, Carry);
3568     break;
3569   }
3570   case ISD::UDIV: {
3571     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3572     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3573     Known = KnownBits::udiv(Known, Known2);
3574     break;
3575   }
3576   case ISD::SREM: {
3577     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3578     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3579     Known = KnownBits::srem(Known, Known2);
3580     break;
3581   }
3582   case ISD::UREM: {
3583     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3584     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3585     Known = KnownBits::urem(Known, Known2);
3586     break;
3587   }
3588   case ISD::EXTRACT_ELEMENT: {
3589     Known = computeKnownBits(Op.getOperand(0), Depth+1);
3590     const unsigned Index = Op.getConstantOperandVal(1);
3591     const unsigned EltBitWidth = Op.getValueSizeInBits();
3592 
3593     // Remove low part of known bits mask
3594     Known.Zero = Known.Zero.getHiBits(Known.getBitWidth() - Index * EltBitWidth);
3595     Known.One = Known.One.getHiBits(Known.getBitWidth() - Index * EltBitWidth);
3596 
3597     // Remove high part of known bit mask
3598     Known = Known.trunc(EltBitWidth);
3599     break;
3600   }
3601   case ISD::EXTRACT_VECTOR_ELT: {
3602     SDValue InVec = Op.getOperand(0);
3603     SDValue EltNo = Op.getOperand(1);
3604     EVT VecVT = InVec.getValueType();
3605     // computeKnownBits not yet implemented for scalable vectors.
3606     if (VecVT.isScalableVector())
3607       break;
3608     const unsigned EltBitWidth = VecVT.getScalarSizeInBits();
3609     const unsigned NumSrcElts = VecVT.getVectorNumElements();
3610 
3611     // If BitWidth > EltBitWidth the value is anyext:ed. So we do not know
3612     // anything about the extended bits.
3613     if (BitWidth > EltBitWidth)
3614       Known = Known.trunc(EltBitWidth);
3615 
3616     // If we know the element index, just demand that vector element, else for
3617     // an unknown element index, ignore DemandedElts and demand them all.
3618     APInt DemandedSrcElts = APInt::getAllOnes(NumSrcElts);
3619     auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
3620     if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts))
3621       DemandedSrcElts =
3622           APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue());
3623 
3624     Known = computeKnownBits(InVec, DemandedSrcElts, Depth + 1);
3625     if (BitWidth > EltBitWidth)
3626       Known = Known.anyext(BitWidth);
3627     break;
3628   }
3629   case ISD::INSERT_VECTOR_ELT: {
3630     // If we know the element index, split the demand between the
3631     // source vector and the inserted element, otherwise assume we need
3632     // the original demanded vector elements and the value.
3633     SDValue InVec = Op.getOperand(0);
3634     SDValue InVal = Op.getOperand(1);
3635     SDValue EltNo = Op.getOperand(2);
3636     bool DemandedVal = true;
3637     APInt DemandedVecElts = DemandedElts;
3638     auto *CEltNo = dyn_cast<ConstantSDNode>(EltNo);
3639     if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) {
3640       unsigned EltIdx = CEltNo->getZExtValue();
3641       DemandedVal = !!DemandedElts[EltIdx];
3642       DemandedVecElts.clearBit(EltIdx);
3643     }
3644     Known.One.setAllBits();
3645     Known.Zero.setAllBits();
3646     if (DemandedVal) {
3647       Known2 = computeKnownBits(InVal, Depth + 1);
3648       Known = KnownBits::commonBits(Known, Known2.zextOrTrunc(BitWidth));
3649     }
3650     if (!!DemandedVecElts) {
3651       Known2 = computeKnownBits(InVec, DemandedVecElts, Depth + 1);
3652       Known = KnownBits::commonBits(Known, Known2);
3653     }
3654     break;
3655   }
3656   case ISD::BITREVERSE: {
3657     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3658     Known = Known2.reverseBits();
3659     break;
3660   }
3661   case ISD::BSWAP: {
3662     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3663     Known = Known2.byteSwap();
3664     break;
3665   }
3666   case ISD::ABS: {
3667     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3668     Known = Known2.abs();
3669     break;
3670   }
3671   case ISD::USUBSAT: {
3672     // The result of usubsat will never be larger than the LHS.
3673     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3674     Known.Zero.setHighBits(Known2.countMinLeadingZeros());
3675     break;
3676   }
3677   case ISD::UMIN: {
3678     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3679     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3680     Known = KnownBits::umin(Known, Known2);
3681     break;
3682   }
3683   case ISD::UMAX: {
3684     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3685     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3686     Known = KnownBits::umax(Known, Known2);
3687     break;
3688   }
3689   case ISD::SMIN:
3690   case ISD::SMAX: {
3691     // If we have a clamp pattern, we know that the number of sign bits will be
3692     // the minimum of the clamp min/max range.
3693     bool IsMax = (Opcode == ISD::SMAX);
3694     ConstantSDNode *CstLow = nullptr, *CstHigh = nullptr;
3695     if ((CstLow = isConstOrConstSplat(Op.getOperand(1), DemandedElts)))
3696       if (Op.getOperand(0).getOpcode() == (IsMax ? ISD::SMIN : ISD::SMAX))
3697         CstHigh =
3698             isConstOrConstSplat(Op.getOperand(0).getOperand(1), DemandedElts);
3699     if (CstLow && CstHigh) {
3700       if (!IsMax)
3701         std::swap(CstLow, CstHigh);
3702 
3703       const APInt &ValueLow = CstLow->getAPIntValue();
3704       const APInt &ValueHigh = CstHigh->getAPIntValue();
3705       if (ValueLow.sle(ValueHigh)) {
3706         unsigned LowSignBits = ValueLow.getNumSignBits();
3707         unsigned HighSignBits = ValueHigh.getNumSignBits();
3708         unsigned MinSignBits = std::min(LowSignBits, HighSignBits);
3709         if (ValueLow.isNegative() && ValueHigh.isNegative()) {
3710           Known.One.setHighBits(MinSignBits);
3711           break;
3712         }
3713         if (ValueLow.isNonNegative() && ValueHigh.isNonNegative()) {
3714           Known.Zero.setHighBits(MinSignBits);
3715           break;
3716         }
3717       }
3718     }
3719 
3720     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3721     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3722     if (IsMax)
3723       Known = KnownBits::smax(Known, Known2);
3724     else
3725       Known = KnownBits::smin(Known, Known2);
3726 
3727     // For SMAX, if CstLow is non-negative we know the result will be
3728     // non-negative and thus all sign bits are 0.
3729     // TODO: There's an equivalent of this for smin with negative constant for
3730     // known ones.
3731     if (IsMax && CstLow) {
3732       const APInt &ValueLow = CstLow->getAPIntValue();
3733       if (ValueLow.isNonNegative()) {
3734         unsigned SignBits = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
3735         Known.Zero.setHighBits(std::min(SignBits, ValueLow.getNumSignBits()));
3736       }
3737     }
3738 
3739     break;
3740   }
3741   case ISD::FP_TO_UINT_SAT: {
3742     // FP_TO_UINT_SAT produces an unsigned value that fits in the saturating VT.
3743     EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
3744     Known.Zero |= APInt::getBitsSetFrom(BitWidth, VT.getScalarSizeInBits());
3745     break;
3746   }
3747   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
3748     if (Op.getResNo() == 1) {
3749       // The boolean result conforms to getBooleanContents.
3750       // If we know the result of a setcc has the top bits zero, use this info.
3751       // We know that we have an integer-based boolean since these operations
3752       // are only available for integer.
3753       if (TLI->getBooleanContents(Op.getValueType().isVector(), false) ==
3754               TargetLowering::ZeroOrOneBooleanContent &&
3755           BitWidth > 1)
3756         Known.Zero.setBitsFrom(1);
3757       break;
3758     }
3759     LLVM_FALLTHROUGH;
3760   case ISD::ATOMIC_CMP_SWAP:
3761   case ISD::ATOMIC_SWAP:
3762   case ISD::ATOMIC_LOAD_ADD:
3763   case ISD::ATOMIC_LOAD_SUB:
3764   case ISD::ATOMIC_LOAD_AND:
3765   case ISD::ATOMIC_LOAD_CLR:
3766   case ISD::ATOMIC_LOAD_OR:
3767   case ISD::ATOMIC_LOAD_XOR:
3768   case ISD::ATOMIC_LOAD_NAND:
3769   case ISD::ATOMIC_LOAD_MIN:
3770   case ISD::ATOMIC_LOAD_MAX:
3771   case ISD::ATOMIC_LOAD_UMIN:
3772   case ISD::ATOMIC_LOAD_UMAX:
3773   case ISD::ATOMIC_LOAD: {
3774     unsigned MemBits =
3775         cast<AtomicSDNode>(Op)->getMemoryVT().getScalarSizeInBits();
3776     // If we are looking at the loaded value.
3777     if (Op.getResNo() == 0) {
3778       if (TLI->getExtendForAtomicOps() == ISD::ZERO_EXTEND)
3779         Known.Zero.setBitsFrom(MemBits);
3780     }
3781     break;
3782   }
3783   case ISD::FrameIndex:
3784   case ISD::TargetFrameIndex:
3785     TLI->computeKnownBitsForFrameIndex(cast<FrameIndexSDNode>(Op)->getIndex(),
3786                                        Known, getMachineFunction());
3787     break;
3788 
3789   default:
3790     if (Opcode < ISD::BUILTIN_OP_END)
3791       break;
3792     LLVM_FALLTHROUGH;
3793   case ISD::INTRINSIC_WO_CHAIN:
3794   case ISD::INTRINSIC_W_CHAIN:
3795   case ISD::INTRINSIC_VOID:
3796     // Allow the target to implement this method for its nodes.
3797     TLI->computeKnownBitsForTargetNode(Op, Known, DemandedElts, *this, Depth);
3798     break;
3799   }
3800 
3801   assert(!Known.hasConflict() && "Bits known to be one AND zero?");
3802   return Known;
3803 }
3804 
3805 SelectionDAG::OverflowKind SelectionDAG::computeOverflowKind(SDValue N0,
3806                                                              SDValue N1) const {
3807   // X + 0 never overflow
3808   if (isNullConstant(N1))
3809     return OFK_Never;
3810 
3811   KnownBits N1Known = computeKnownBits(N1);
3812   if (N1Known.Zero.getBoolValue()) {
3813     KnownBits N0Known = computeKnownBits(N0);
3814 
3815     bool overflow;
3816     (void)N0Known.getMaxValue().uadd_ov(N1Known.getMaxValue(), overflow);
3817     if (!overflow)
3818       return OFK_Never;
3819   }
3820 
3821   // mulhi + 1 never overflow
3822   if (N0.getOpcode() == ISD::UMUL_LOHI && N0.getResNo() == 1 &&
3823       (N1Known.getMaxValue() & 0x01) == N1Known.getMaxValue())
3824     return OFK_Never;
3825 
3826   if (N1.getOpcode() == ISD::UMUL_LOHI && N1.getResNo() == 1) {
3827     KnownBits N0Known = computeKnownBits(N0);
3828 
3829     if ((N0Known.getMaxValue() & 0x01) == N0Known.getMaxValue())
3830       return OFK_Never;
3831   }
3832 
3833   return OFK_Sometime;
3834 }
3835 
3836 bool SelectionDAG::isKnownToBeAPowerOfTwo(SDValue Val) const {
3837   EVT OpVT = Val.getValueType();
3838   unsigned BitWidth = OpVT.getScalarSizeInBits();
3839 
3840   // Is the constant a known power of 2?
3841   if (ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Val))
3842     return Const->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2();
3843 
3844   // A left-shift of a constant one will have exactly one bit set because
3845   // shifting the bit off the end is undefined.
3846   if (Val.getOpcode() == ISD::SHL) {
3847     auto *C = isConstOrConstSplat(Val.getOperand(0));
3848     if (C && C->getAPIntValue() == 1)
3849       return true;
3850   }
3851 
3852   // Similarly, a logical right-shift of a constant sign-bit will have exactly
3853   // one bit set.
3854   if (Val.getOpcode() == ISD::SRL) {
3855     auto *C = isConstOrConstSplat(Val.getOperand(0));
3856     if (C && C->getAPIntValue().isSignMask())
3857       return true;
3858   }
3859 
3860   // Are all operands of a build vector constant powers of two?
3861   if (Val.getOpcode() == ISD::BUILD_VECTOR)
3862     if (llvm::all_of(Val->ops(), [BitWidth](SDValue E) {
3863           if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(E))
3864             return C->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2();
3865           return false;
3866         }))
3867       return true;
3868 
3869   // Is the operand of a splat vector a constant power of two?
3870   if (Val.getOpcode() == ISD::SPLAT_VECTOR)
3871     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val->getOperand(0)))
3872       if (C->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2())
3873         return true;
3874 
3875   // vscale(power-of-two) is a power-of-two for some targets
3876   if (Val.getOpcode() == ISD::VSCALE &&
3877       getTargetLoweringInfo().isVScaleKnownToBeAPowerOfTwo() &&
3878       isKnownToBeAPowerOfTwo(Val.getOperand(0)))
3879     return true;
3880 
3881   // More could be done here, though the above checks are enough
3882   // to handle some common cases.
3883 
3884   // Fall back to computeKnownBits to catch other known cases.
3885   KnownBits Known = computeKnownBits(Val);
3886   return (Known.countMaxPopulation() == 1) && (Known.countMinPopulation() == 1);
3887 }
3888 
3889 unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, unsigned Depth) const {
3890   EVT VT = Op.getValueType();
3891 
3892   // TODO: Assume we don't know anything for now.
3893   if (VT.isScalableVector())
3894     return 1;
3895 
3896   APInt DemandedElts = VT.isVector()
3897                            ? APInt::getAllOnes(VT.getVectorNumElements())
3898                            : APInt(1, 1);
3899   return ComputeNumSignBits(Op, DemandedElts, Depth);
3900 }
3901 
3902 unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, const APInt &DemandedElts,
3903                                           unsigned Depth) const {
3904   EVT VT = Op.getValueType();
3905   assert((VT.isInteger() || VT.isFloatingPoint()) && "Invalid VT!");
3906   unsigned VTBits = VT.getScalarSizeInBits();
3907   unsigned NumElts = DemandedElts.getBitWidth();
3908   unsigned Tmp, Tmp2;
3909   unsigned FirstAnswer = 1;
3910 
3911   if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
3912     const APInt &Val = C->getAPIntValue();
3913     return Val.getNumSignBits();
3914   }
3915 
3916   if (Depth >= MaxRecursionDepth)
3917     return 1;  // Limit search depth.
3918 
3919   if (!DemandedElts || VT.isScalableVector())
3920     return 1;  // No demanded elts, better to assume we don't know anything.
3921 
3922   unsigned Opcode = Op.getOpcode();
3923   switch (Opcode) {
3924   default: break;
3925   case ISD::AssertSext:
3926     Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
3927     return VTBits-Tmp+1;
3928   case ISD::AssertZext:
3929     Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
3930     return VTBits-Tmp;
3931   case ISD::MERGE_VALUES:
3932     return ComputeNumSignBits(Op.getOperand(Op.getResNo()), DemandedElts,
3933                               Depth + 1);
3934   case ISD::BUILD_VECTOR:
3935     Tmp = VTBits;
3936     for (unsigned i = 0, e = Op.getNumOperands(); (i < e) && (Tmp > 1); ++i) {
3937       if (!DemandedElts[i])
3938         continue;
3939 
3940       SDValue SrcOp = Op.getOperand(i);
3941       Tmp2 = ComputeNumSignBits(SrcOp, Depth + 1);
3942 
3943       // BUILD_VECTOR can implicitly truncate sources, we must handle this.
3944       if (SrcOp.getValueSizeInBits() != VTBits) {
3945         assert(SrcOp.getValueSizeInBits() > VTBits &&
3946                "Expected BUILD_VECTOR implicit truncation");
3947         unsigned ExtraBits = SrcOp.getValueSizeInBits() - VTBits;
3948         Tmp2 = (Tmp2 > ExtraBits ? Tmp2 - ExtraBits : 1);
3949       }
3950       Tmp = std::min(Tmp, Tmp2);
3951     }
3952     return Tmp;
3953 
3954   case ISD::VECTOR_SHUFFLE: {
3955     // Collect the minimum number of sign bits that are shared by every vector
3956     // element referenced by the shuffle.
3957     APInt DemandedLHS(NumElts, 0), DemandedRHS(NumElts, 0);
3958     const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op);
3959     assert(NumElts == SVN->getMask().size() && "Unexpected vector size");
3960     for (unsigned i = 0; i != NumElts; ++i) {
3961       int M = SVN->getMaskElt(i);
3962       if (!DemandedElts[i])
3963         continue;
3964       // For UNDEF elements, we don't know anything about the common state of
3965       // the shuffle result.
3966       if (M < 0)
3967         return 1;
3968       if ((unsigned)M < NumElts)
3969         DemandedLHS.setBit((unsigned)M % NumElts);
3970       else
3971         DemandedRHS.setBit((unsigned)M % NumElts);
3972     }
3973     Tmp = std::numeric_limits<unsigned>::max();
3974     if (!!DemandedLHS)
3975       Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedLHS, Depth + 1);
3976     if (!!DemandedRHS) {
3977       Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedRHS, Depth + 1);
3978       Tmp = std::min(Tmp, Tmp2);
3979     }
3980     // If we don't know anything, early out and try computeKnownBits fall-back.
3981     if (Tmp == 1)
3982       break;
3983     assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
3984     return Tmp;
3985   }
3986 
3987   case ISD::BITCAST: {
3988     SDValue N0 = Op.getOperand(0);
3989     EVT SrcVT = N0.getValueType();
3990     unsigned SrcBits = SrcVT.getScalarSizeInBits();
3991 
3992     // Ignore bitcasts from unsupported types..
3993     if (!(SrcVT.isInteger() || SrcVT.isFloatingPoint()))
3994       break;
3995 
3996     // Fast handling of 'identity' bitcasts.
3997     if (VTBits == SrcBits)
3998       return ComputeNumSignBits(N0, DemandedElts, Depth + 1);
3999 
4000     bool IsLE = getDataLayout().isLittleEndian();
4001 
4002     // Bitcast 'large element' scalar/vector to 'small element' vector.
4003     if ((SrcBits % VTBits) == 0) {
4004       assert(VT.isVector() && "Expected bitcast to vector");
4005 
4006       unsigned Scale = SrcBits / VTBits;
4007       APInt SrcDemandedElts =
4008           APIntOps::ScaleBitMask(DemandedElts, NumElts / Scale);
4009 
4010       // Fast case - sign splat can be simply split across the small elements.
4011       Tmp = ComputeNumSignBits(N0, SrcDemandedElts, Depth + 1);
4012       if (Tmp == SrcBits)
4013         return VTBits;
4014 
4015       // Slow case - determine how far the sign extends into each sub-element.
4016       Tmp2 = VTBits;
4017       for (unsigned i = 0; i != NumElts; ++i)
4018         if (DemandedElts[i]) {
4019           unsigned SubOffset = i % Scale;
4020           SubOffset = (IsLE ? ((Scale - 1) - SubOffset) : SubOffset);
4021           SubOffset = SubOffset * VTBits;
4022           if (Tmp <= SubOffset)
4023             return 1;
4024           Tmp2 = std::min(Tmp2, Tmp - SubOffset);
4025         }
4026       return Tmp2;
4027     }
4028     break;
4029   }
4030 
4031   case ISD::FP_TO_SINT_SAT:
4032     // FP_TO_SINT_SAT produces a signed value that fits in the saturating VT.
4033     Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getScalarSizeInBits();
4034     return VTBits - Tmp + 1;
4035   case ISD::SIGN_EXTEND:
4036     Tmp = VTBits - Op.getOperand(0).getScalarValueSizeInBits();
4037     return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1) + Tmp;
4038   case ISD::SIGN_EXTEND_INREG:
4039     // Max of the input and what this extends.
4040     Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getScalarSizeInBits();
4041     Tmp = VTBits-Tmp+1;
4042     Tmp2 = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1);
4043     return std::max(Tmp, Tmp2);
4044   case ISD::SIGN_EXTEND_VECTOR_INREG: {
4045     SDValue Src = Op.getOperand(0);
4046     EVT SrcVT = Src.getValueType();
4047     APInt DemandedSrcElts = DemandedElts.zext(SrcVT.getVectorNumElements());
4048     Tmp = VTBits - SrcVT.getScalarSizeInBits();
4049     return ComputeNumSignBits(Src, DemandedSrcElts, Depth+1) + Tmp;
4050   }
4051   case ISD::SRA:
4052     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
4053     // SRA X, C -> adds C sign bits.
4054     if (const APInt *ShAmt =
4055             getValidMinimumShiftAmountConstant(Op, DemandedElts))
4056       Tmp = std::min<uint64_t>(Tmp + ShAmt->getZExtValue(), VTBits);
4057     return Tmp;
4058   case ISD::SHL:
4059     if (const APInt *ShAmt =
4060             getValidMaximumShiftAmountConstant(Op, DemandedElts)) {
4061       // shl destroys sign bits, ensure it doesn't shift out all sign bits.
4062       Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
4063       if (ShAmt->ult(Tmp))
4064         return Tmp - ShAmt->getZExtValue();
4065     }
4066     break;
4067   case ISD::AND:
4068   case ISD::OR:
4069   case ISD::XOR:    // NOT is handled here.
4070     // Logical binary ops preserve the number of sign bits at the worst.
4071     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1);
4072     if (Tmp != 1) {
4073       Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth+1);
4074       FirstAnswer = std::min(Tmp, Tmp2);
4075       // We computed what we know about the sign bits as our first
4076       // answer. Now proceed to the generic code that uses
4077       // computeKnownBits, and pick whichever answer is better.
4078     }
4079     break;
4080 
4081   case ISD::SELECT:
4082   case ISD::VSELECT:
4083     Tmp = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth+1);
4084     if (Tmp == 1) return 1;  // Early out.
4085     Tmp2 = ComputeNumSignBits(Op.getOperand(2), DemandedElts, Depth+1);
4086     return std::min(Tmp, Tmp2);
4087   case ISD::SELECT_CC:
4088     Tmp = ComputeNumSignBits(Op.getOperand(2), DemandedElts, Depth+1);
4089     if (Tmp == 1) return 1;  // Early out.
4090     Tmp2 = ComputeNumSignBits(Op.getOperand(3), DemandedElts, Depth+1);
4091     return std::min(Tmp, Tmp2);
4092 
4093   case ISD::SMIN:
4094   case ISD::SMAX: {
4095     // If we have a clamp pattern, we know that the number of sign bits will be
4096     // the minimum of the clamp min/max range.
4097     bool IsMax = (Opcode == ISD::SMAX);
4098     ConstantSDNode *CstLow = nullptr, *CstHigh = nullptr;
4099     if ((CstLow = isConstOrConstSplat(Op.getOperand(1), DemandedElts)))
4100       if (Op.getOperand(0).getOpcode() == (IsMax ? ISD::SMIN : ISD::SMAX))
4101         CstHigh =
4102             isConstOrConstSplat(Op.getOperand(0).getOperand(1), DemandedElts);
4103     if (CstLow && CstHigh) {
4104       if (!IsMax)
4105         std::swap(CstLow, CstHigh);
4106       if (CstLow->getAPIntValue().sle(CstHigh->getAPIntValue())) {
4107         Tmp = CstLow->getAPIntValue().getNumSignBits();
4108         Tmp2 = CstHigh->getAPIntValue().getNumSignBits();
4109         return std::min(Tmp, Tmp2);
4110       }
4111     }
4112 
4113     // Fallback - just get the minimum number of sign bits of the operands.
4114     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
4115     if (Tmp == 1)
4116       return 1;  // Early out.
4117     Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
4118     return std::min(Tmp, Tmp2);
4119   }
4120   case ISD::UMIN:
4121   case ISD::UMAX:
4122     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
4123     if (Tmp == 1)
4124       return 1;  // Early out.
4125     Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
4126     return std::min(Tmp, Tmp2);
4127   case ISD::SADDO:
4128   case ISD::UADDO:
4129   case ISD::SADDO_CARRY:
4130   case ISD::ADDCARRY:
4131   case ISD::SSUBO:
4132   case ISD::USUBO:
4133   case ISD::SSUBO_CARRY:
4134   case ISD::SUBCARRY:
4135   case ISD::SMULO:
4136   case ISD::UMULO:
4137     if (Op.getResNo() != 1)
4138       break;
4139     // The boolean result conforms to getBooleanContents.  Fall through.
4140     // If setcc returns 0/-1, all bits are sign bits.
4141     // We know that we have an integer-based boolean since these operations
4142     // are only available for integer.
4143     if (TLI->getBooleanContents(VT.isVector(), false) ==
4144         TargetLowering::ZeroOrNegativeOneBooleanContent)
4145       return VTBits;
4146     break;
4147   case ISD::SETCC:
4148   case ISD::SETCCCARRY:
4149   case ISD::STRICT_FSETCC:
4150   case ISD::STRICT_FSETCCS: {
4151     unsigned OpNo = Op->isStrictFPOpcode() ? 1 : 0;
4152     // If setcc returns 0/-1, all bits are sign bits.
4153     if (TLI->getBooleanContents(Op.getOperand(OpNo).getValueType()) ==
4154         TargetLowering::ZeroOrNegativeOneBooleanContent)
4155       return VTBits;
4156     break;
4157   }
4158   case ISD::ROTL:
4159   case ISD::ROTR:
4160     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
4161 
4162     // If we're rotating an 0/-1 value, then it stays an 0/-1 value.
4163     if (Tmp == VTBits)
4164       return VTBits;
4165 
4166     if (ConstantSDNode *C =
4167             isConstOrConstSplat(Op.getOperand(1), DemandedElts)) {
4168       unsigned RotAmt = C->getAPIntValue().urem(VTBits);
4169 
4170       // Handle rotate right by N like a rotate left by 32-N.
4171       if (Opcode == ISD::ROTR)
4172         RotAmt = (VTBits - RotAmt) % VTBits;
4173 
4174       // If we aren't rotating out all of the known-in sign bits, return the
4175       // number that are left.  This handles rotl(sext(x), 1) for example.
4176       if (Tmp > (RotAmt + 1)) return (Tmp - RotAmt);
4177     }
4178     break;
4179   case ISD::ADD:
4180   case ISD::ADDC:
4181     // Add can have at most one carry bit.  Thus we know that the output
4182     // is, at worst, one more bit than the inputs.
4183     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
4184     if (Tmp == 1) return 1; // Early out.
4185 
4186     // Special case decrementing a value (ADD X, -1):
4187     if (ConstantSDNode *CRHS =
4188             isConstOrConstSplat(Op.getOperand(1), DemandedElts))
4189       if (CRHS->isAllOnes()) {
4190         KnownBits Known =
4191             computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4192 
4193         // If the input is known to be 0 or 1, the output is 0/-1, which is all
4194         // sign bits set.
4195         if ((Known.Zero | 1).isAllOnes())
4196           return VTBits;
4197 
4198         // If we are subtracting one from a positive number, there is no carry
4199         // out of the result.
4200         if (Known.isNonNegative())
4201           return Tmp;
4202       }
4203 
4204     Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
4205     if (Tmp2 == 1) return 1; // Early out.
4206     return std::min(Tmp, Tmp2) - 1;
4207   case ISD::SUB:
4208     Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
4209     if (Tmp2 == 1) return 1; // Early out.
4210 
4211     // Handle NEG.
4212     if (ConstantSDNode *CLHS =
4213             isConstOrConstSplat(Op.getOperand(0), DemandedElts))
4214       if (CLHS->isZero()) {
4215         KnownBits Known =
4216             computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4217         // If the input is known to be 0 or 1, the output is 0/-1, which is all
4218         // sign bits set.
4219         if ((Known.Zero | 1).isAllOnes())
4220           return VTBits;
4221 
4222         // If the input is known to be positive (the sign bit is known clear),
4223         // the output of the NEG has the same number of sign bits as the input.
4224         if (Known.isNonNegative())
4225           return Tmp2;
4226 
4227         // Otherwise, we treat this like a SUB.
4228       }
4229 
4230     // Sub can have at most one carry bit.  Thus we know that the output
4231     // is, at worst, one more bit than the inputs.
4232     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
4233     if (Tmp == 1) return 1; // Early out.
4234     return std::min(Tmp, Tmp2) - 1;
4235   case ISD::MUL: {
4236     // The output of the Mul can be at most twice the valid bits in the inputs.
4237     unsigned SignBitsOp0 = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
4238     if (SignBitsOp0 == 1)
4239       break;
4240     unsigned SignBitsOp1 = ComputeNumSignBits(Op.getOperand(1), Depth + 1);
4241     if (SignBitsOp1 == 1)
4242       break;
4243     unsigned OutValidBits =
4244         (VTBits - SignBitsOp0 + 1) + (VTBits - SignBitsOp1 + 1);
4245     return OutValidBits > VTBits ? 1 : VTBits - OutValidBits + 1;
4246   }
4247   case ISD::SREM:
4248     // The sign bit is the LHS's sign bit, except when the result of the
4249     // remainder is zero. The magnitude of the result should be less than or
4250     // equal to the magnitude of the LHS. Therefore, the result should have
4251     // at least as many sign bits as the left hand side.
4252     return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
4253   case ISD::TRUNCATE: {
4254     // Check if the sign bits of source go down as far as the truncated value.
4255     unsigned NumSrcBits = Op.getOperand(0).getScalarValueSizeInBits();
4256     unsigned NumSrcSignBits = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
4257     if (NumSrcSignBits > (NumSrcBits - VTBits))
4258       return NumSrcSignBits - (NumSrcBits - VTBits);
4259     break;
4260   }
4261   case ISD::EXTRACT_ELEMENT: {
4262     const int KnownSign = ComputeNumSignBits(Op.getOperand(0), Depth+1);
4263     const int BitWidth = Op.getValueSizeInBits();
4264     const int Items = Op.getOperand(0).getValueSizeInBits() / BitWidth;
4265 
4266     // Get reverse index (starting from 1), Op1 value indexes elements from
4267     // little end. Sign starts at big end.
4268     const int rIndex = Items - 1 - Op.getConstantOperandVal(1);
4269 
4270     // If the sign portion ends in our element the subtraction gives correct
4271     // result. Otherwise it gives either negative or > bitwidth result
4272     return std::max(std::min(KnownSign - rIndex * BitWidth, BitWidth), 0);
4273   }
4274   case ISD::INSERT_VECTOR_ELT: {
4275     // If we know the element index, split the demand between the
4276     // source vector and the inserted element, otherwise assume we need
4277     // the original demanded vector elements and the value.
4278     SDValue InVec = Op.getOperand(0);
4279     SDValue InVal = Op.getOperand(1);
4280     SDValue EltNo = Op.getOperand(2);
4281     bool DemandedVal = true;
4282     APInt DemandedVecElts = DemandedElts;
4283     auto *CEltNo = dyn_cast<ConstantSDNode>(EltNo);
4284     if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) {
4285       unsigned EltIdx = CEltNo->getZExtValue();
4286       DemandedVal = !!DemandedElts[EltIdx];
4287       DemandedVecElts.clearBit(EltIdx);
4288     }
4289     Tmp = std::numeric_limits<unsigned>::max();
4290     if (DemandedVal) {
4291       // TODO - handle implicit truncation of inserted elements.
4292       if (InVal.getScalarValueSizeInBits() != VTBits)
4293         break;
4294       Tmp2 = ComputeNumSignBits(InVal, Depth + 1);
4295       Tmp = std::min(Tmp, Tmp2);
4296     }
4297     if (!!DemandedVecElts) {
4298       Tmp2 = ComputeNumSignBits(InVec, DemandedVecElts, Depth + 1);
4299       Tmp = std::min(Tmp, Tmp2);
4300     }
4301     assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
4302     return Tmp;
4303   }
4304   case ISD::EXTRACT_VECTOR_ELT: {
4305     SDValue InVec = Op.getOperand(0);
4306     SDValue EltNo = Op.getOperand(1);
4307     EVT VecVT = InVec.getValueType();
4308     // ComputeNumSignBits not yet implemented for scalable vectors.
4309     if (VecVT.isScalableVector())
4310       break;
4311     const unsigned BitWidth = Op.getValueSizeInBits();
4312     const unsigned EltBitWidth = Op.getOperand(0).getScalarValueSizeInBits();
4313     const unsigned NumSrcElts = VecVT.getVectorNumElements();
4314 
4315     // If BitWidth > EltBitWidth the value is anyext:ed, and we do not know
4316     // anything about sign bits. But if the sizes match we can derive knowledge
4317     // about sign bits from the vector operand.
4318     if (BitWidth != EltBitWidth)
4319       break;
4320 
4321     // If we know the element index, just demand that vector element, else for
4322     // an unknown element index, ignore DemandedElts and demand them all.
4323     APInt DemandedSrcElts = APInt::getAllOnes(NumSrcElts);
4324     auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
4325     if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts))
4326       DemandedSrcElts =
4327           APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue());
4328 
4329     return ComputeNumSignBits(InVec, DemandedSrcElts, Depth + 1);
4330   }
4331   case ISD::EXTRACT_SUBVECTOR: {
4332     // Offset the demanded elts by the subvector index.
4333     SDValue Src = Op.getOperand(0);
4334     // Bail until we can represent demanded elements for scalable vectors.
4335     if (Src.getValueType().isScalableVector())
4336       break;
4337     uint64_t Idx = Op.getConstantOperandVal(1);
4338     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
4339     APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts).shl(Idx);
4340     return ComputeNumSignBits(Src, DemandedSrcElts, Depth + 1);
4341   }
4342   case ISD::CONCAT_VECTORS: {
4343     // Determine the minimum number of sign bits across all demanded
4344     // elts of the input vectors. Early out if the result is already 1.
4345     Tmp = std::numeric_limits<unsigned>::max();
4346     EVT SubVectorVT = Op.getOperand(0).getValueType();
4347     unsigned NumSubVectorElts = SubVectorVT.getVectorNumElements();
4348     unsigned NumSubVectors = Op.getNumOperands();
4349     for (unsigned i = 0; (i < NumSubVectors) && (Tmp > 1); ++i) {
4350       APInt DemandedSub =
4351           DemandedElts.extractBits(NumSubVectorElts, i * NumSubVectorElts);
4352       if (!DemandedSub)
4353         continue;
4354       Tmp2 = ComputeNumSignBits(Op.getOperand(i), DemandedSub, Depth + 1);
4355       Tmp = std::min(Tmp, Tmp2);
4356     }
4357     assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
4358     return Tmp;
4359   }
4360   case ISD::INSERT_SUBVECTOR: {
4361     // Demand any elements from the subvector and the remainder from the src its
4362     // inserted into.
4363     SDValue Src = Op.getOperand(0);
4364     SDValue Sub = Op.getOperand(1);
4365     uint64_t Idx = Op.getConstantOperandVal(2);
4366     unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
4367     APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
4368     APInt DemandedSrcElts = DemandedElts;
4369     DemandedSrcElts.insertBits(APInt::getZero(NumSubElts), Idx);
4370 
4371     Tmp = std::numeric_limits<unsigned>::max();
4372     if (!!DemandedSubElts) {
4373       Tmp = ComputeNumSignBits(Sub, DemandedSubElts, Depth + 1);
4374       if (Tmp == 1)
4375         return 1; // early-out
4376     }
4377     if (!!DemandedSrcElts) {
4378       Tmp2 = ComputeNumSignBits(Src, DemandedSrcElts, Depth + 1);
4379       Tmp = std::min(Tmp, Tmp2);
4380     }
4381     assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
4382     return Tmp;
4383   }
4384   case ISD::ATOMIC_CMP_SWAP:
4385   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
4386   case ISD::ATOMIC_SWAP:
4387   case ISD::ATOMIC_LOAD_ADD:
4388   case ISD::ATOMIC_LOAD_SUB:
4389   case ISD::ATOMIC_LOAD_AND:
4390   case ISD::ATOMIC_LOAD_CLR:
4391   case ISD::ATOMIC_LOAD_OR:
4392   case ISD::ATOMIC_LOAD_XOR:
4393   case ISD::ATOMIC_LOAD_NAND:
4394   case ISD::ATOMIC_LOAD_MIN:
4395   case ISD::ATOMIC_LOAD_MAX:
4396   case ISD::ATOMIC_LOAD_UMIN:
4397   case ISD::ATOMIC_LOAD_UMAX:
4398   case ISD::ATOMIC_LOAD: {
4399     Tmp = cast<AtomicSDNode>(Op)->getMemoryVT().getScalarSizeInBits();
4400     // If we are looking at the loaded value.
4401     if (Op.getResNo() == 0) {
4402       if (Tmp == VTBits)
4403         return 1; // early-out
4404       if (TLI->getExtendForAtomicOps() == ISD::SIGN_EXTEND)
4405         return VTBits - Tmp + 1;
4406       if (TLI->getExtendForAtomicOps() == ISD::ZERO_EXTEND)
4407         return VTBits - Tmp;
4408     }
4409     break;
4410   }
4411   }
4412 
4413   // If we are looking at the loaded value of the SDNode.
4414   if (Op.getResNo() == 0) {
4415     // Handle LOADX separately here. EXTLOAD case will fallthrough.
4416     if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
4417       unsigned ExtType = LD->getExtensionType();
4418       switch (ExtType) {
4419       default: break;
4420       case ISD::SEXTLOAD: // e.g. i16->i32 = '17' bits known.
4421         Tmp = LD->getMemoryVT().getScalarSizeInBits();
4422         return VTBits - Tmp + 1;
4423       case ISD::ZEXTLOAD: // e.g. i16->i32 = '16' bits known.
4424         Tmp = LD->getMemoryVT().getScalarSizeInBits();
4425         return VTBits - Tmp;
4426       case ISD::NON_EXTLOAD:
4427         if (const Constant *Cst = TLI->getTargetConstantFromLoad(LD)) {
4428           // We only need to handle vectors - computeKnownBits should handle
4429           // scalar cases.
4430           Type *CstTy = Cst->getType();
4431           if (CstTy->isVectorTy() &&
4432               (NumElts * VTBits) == CstTy->getPrimitiveSizeInBits() &&
4433               VTBits == CstTy->getScalarSizeInBits()) {
4434             Tmp = VTBits;
4435             for (unsigned i = 0; i != NumElts; ++i) {
4436               if (!DemandedElts[i])
4437                 continue;
4438               if (Constant *Elt = Cst->getAggregateElement(i)) {
4439                 if (auto *CInt = dyn_cast<ConstantInt>(Elt)) {
4440                   const APInt &Value = CInt->getValue();
4441                   Tmp = std::min(Tmp, Value.getNumSignBits());
4442                   continue;
4443                 }
4444                 if (auto *CFP = dyn_cast<ConstantFP>(Elt)) {
4445                   APInt Value = CFP->getValueAPF().bitcastToAPInt();
4446                   Tmp = std::min(Tmp, Value.getNumSignBits());
4447                   continue;
4448                 }
4449               }
4450               // Unknown type. Conservatively assume no bits match sign bit.
4451               return 1;
4452             }
4453             return Tmp;
4454           }
4455         }
4456         break;
4457       }
4458     }
4459   }
4460 
4461   // Allow the target to implement this method for its nodes.
4462   if (Opcode >= ISD::BUILTIN_OP_END ||
4463       Opcode == ISD::INTRINSIC_WO_CHAIN ||
4464       Opcode == ISD::INTRINSIC_W_CHAIN ||
4465       Opcode == ISD::INTRINSIC_VOID) {
4466     unsigned NumBits =
4467         TLI->ComputeNumSignBitsForTargetNode(Op, DemandedElts, *this, Depth);
4468     if (NumBits > 1)
4469       FirstAnswer = std::max(FirstAnswer, NumBits);
4470   }
4471 
4472   // Finally, if we can prove that the top bits of the result are 0's or 1's,
4473   // use this information.
4474   KnownBits Known = computeKnownBits(Op, DemandedElts, Depth);
4475   return std::max(FirstAnswer, Known.countMinSignBits());
4476 }
4477 
4478 unsigned SelectionDAG::ComputeMaxSignificantBits(SDValue Op,
4479                                                  unsigned Depth) const {
4480   unsigned SignBits = ComputeNumSignBits(Op, Depth);
4481   return Op.getScalarValueSizeInBits() - SignBits + 1;
4482 }
4483 
4484 unsigned SelectionDAG::ComputeMaxSignificantBits(SDValue Op,
4485                                                  const APInt &DemandedElts,
4486                                                  unsigned Depth) const {
4487   unsigned SignBits = ComputeNumSignBits(Op, DemandedElts, Depth);
4488   return Op.getScalarValueSizeInBits() - SignBits + 1;
4489 }
4490 
4491 bool SelectionDAG::isGuaranteedNotToBeUndefOrPoison(SDValue Op, bool PoisonOnly,
4492                                                     unsigned Depth) const {
4493   // Early out for FREEZE.
4494   if (Op.getOpcode() == ISD::FREEZE)
4495     return true;
4496 
4497   // TODO: Assume we don't know anything for now.
4498   EVT VT = Op.getValueType();
4499   if (VT.isScalableVector())
4500     return false;
4501 
4502   APInt DemandedElts = VT.isVector()
4503                            ? APInt::getAllOnes(VT.getVectorNumElements())
4504                            : APInt(1, 1);
4505   return isGuaranteedNotToBeUndefOrPoison(Op, DemandedElts, PoisonOnly, Depth);
4506 }
4507 
4508 bool SelectionDAG::isGuaranteedNotToBeUndefOrPoison(SDValue Op,
4509                                                     const APInt &DemandedElts,
4510                                                     bool PoisonOnly,
4511                                                     unsigned Depth) const {
4512   unsigned Opcode = Op.getOpcode();
4513 
4514   // Early out for FREEZE.
4515   if (Opcode == ISD::FREEZE)
4516     return true;
4517 
4518   if (Depth >= MaxRecursionDepth)
4519     return false; // Limit search depth.
4520 
4521   if (isIntOrFPConstant(Op))
4522     return true;
4523 
4524   switch (Opcode) {
4525   case ISD::UNDEF:
4526     return PoisonOnly;
4527 
4528   case ISD::BUILD_VECTOR:
4529     // NOTE: BUILD_VECTOR has implicit truncation of wider scalar elements -
4530     // this shouldn't affect the result.
4531     for (unsigned i = 0, e = Op.getNumOperands(); i < e; ++i) {
4532       if (!DemandedElts[i])
4533         continue;
4534       if (!isGuaranteedNotToBeUndefOrPoison(Op.getOperand(i), PoisonOnly,
4535                                             Depth + 1))
4536         return false;
4537     }
4538     return true;
4539 
4540   // TODO: Search for noundef attributes from library functions.
4541 
4542   // TODO: Pointers dereferenced by ISD::LOAD/STORE ops are noundef.
4543 
4544   default:
4545     // Allow the target to implement this method for its nodes.
4546     if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::INTRINSIC_WO_CHAIN ||
4547         Opcode == ISD::INTRINSIC_W_CHAIN || Opcode == ISD::INTRINSIC_VOID)
4548       return TLI->isGuaranteedNotToBeUndefOrPoisonForTargetNode(
4549           Op, DemandedElts, *this, PoisonOnly, Depth);
4550     break;
4551   }
4552 
4553   return false;
4554 }
4555 
4556 bool SelectionDAG::isBaseWithConstantOffset(SDValue Op) const {
4557   if ((Op.getOpcode() != ISD::ADD && Op.getOpcode() != ISD::OR) ||
4558       !isa<ConstantSDNode>(Op.getOperand(1)))
4559     return false;
4560 
4561   if (Op.getOpcode() == ISD::OR &&
4562       !MaskedValueIsZero(Op.getOperand(0), Op.getConstantOperandAPInt(1)))
4563     return false;
4564 
4565   return true;
4566 }
4567 
4568 bool SelectionDAG::isKnownNeverNaN(SDValue Op, bool SNaN, unsigned Depth) const {
4569   // If we're told that NaNs won't happen, assume they won't.
4570   if (getTarget().Options.NoNaNsFPMath || Op->getFlags().hasNoNaNs())
4571     return true;
4572 
4573   if (Depth >= MaxRecursionDepth)
4574     return false; // Limit search depth.
4575 
4576   // TODO: Handle vectors.
4577   // If the value is a constant, we can obviously see if it is a NaN or not.
4578   if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) {
4579     return !C->getValueAPF().isNaN() ||
4580            (SNaN && !C->getValueAPF().isSignaling());
4581   }
4582 
4583   unsigned Opcode = Op.getOpcode();
4584   switch (Opcode) {
4585   case ISD::FADD:
4586   case ISD::FSUB:
4587   case ISD::FMUL:
4588   case ISD::FDIV:
4589   case ISD::FREM:
4590   case ISD::FSIN:
4591   case ISD::FCOS: {
4592     if (SNaN)
4593       return true;
4594     // TODO: Need isKnownNeverInfinity
4595     return false;
4596   }
4597   case ISD::FCANONICALIZE:
4598   case ISD::FEXP:
4599   case ISD::FEXP2:
4600   case ISD::FTRUNC:
4601   case ISD::FFLOOR:
4602   case ISD::FCEIL:
4603   case ISD::FROUND:
4604   case ISD::FROUNDEVEN:
4605   case ISD::FRINT:
4606   case ISD::FNEARBYINT: {
4607     if (SNaN)
4608       return true;
4609     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
4610   }
4611   case ISD::FABS:
4612   case ISD::FNEG:
4613   case ISD::FCOPYSIGN: {
4614     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
4615   }
4616   case ISD::SELECT:
4617     return isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1) &&
4618            isKnownNeverNaN(Op.getOperand(2), SNaN, Depth + 1);
4619   case ISD::FP_EXTEND:
4620   case ISD::FP_ROUND: {
4621     if (SNaN)
4622       return true;
4623     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
4624   }
4625   case ISD::SINT_TO_FP:
4626   case ISD::UINT_TO_FP:
4627     return true;
4628   case ISD::FMA:
4629   case ISD::FMAD: {
4630     if (SNaN)
4631       return true;
4632     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) &&
4633            isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1) &&
4634            isKnownNeverNaN(Op.getOperand(2), SNaN, Depth + 1);
4635   }
4636   case ISD::FSQRT: // Need is known positive
4637   case ISD::FLOG:
4638   case ISD::FLOG2:
4639   case ISD::FLOG10:
4640   case ISD::FPOWI:
4641   case ISD::FPOW: {
4642     if (SNaN)
4643       return true;
4644     // TODO: Refine on operand
4645     return false;
4646   }
4647   case ISD::FMINNUM:
4648   case ISD::FMAXNUM: {
4649     // Only one needs to be known not-nan, since it will be returned if the
4650     // other ends up being one.
4651     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) ||
4652            isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1);
4653   }
4654   case ISD::FMINNUM_IEEE:
4655   case ISD::FMAXNUM_IEEE: {
4656     if (SNaN)
4657       return true;
4658     // This can return a NaN if either operand is an sNaN, or if both operands
4659     // are NaN.
4660     return (isKnownNeverNaN(Op.getOperand(0), false, Depth + 1) &&
4661             isKnownNeverSNaN(Op.getOperand(1), Depth + 1)) ||
4662            (isKnownNeverNaN(Op.getOperand(1), false, Depth + 1) &&
4663             isKnownNeverSNaN(Op.getOperand(0), Depth + 1));
4664   }
4665   case ISD::FMINIMUM:
4666   case ISD::FMAXIMUM: {
4667     // TODO: Does this quiet or return the origina NaN as-is?
4668     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) &&
4669            isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1);
4670   }
4671   case ISD::EXTRACT_VECTOR_ELT: {
4672     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
4673   }
4674   default:
4675     if (Opcode >= ISD::BUILTIN_OP_END ||
4676         Opcode == ISD::INTRINSIC_WO_CHAIN ||
4677         Opcode == ISD::INTRINSIC_W_CHAIN ||
4678         Opcode == ISD::INTRINSIC_VOID) {
4679       return TLI->isKnownNeverNaNForTargetNode(Op, *this, SNaN, Depth);
4680     }
4681 
4682     return false;
4683   }
4684 }
4685 
4686 bool SelectionDAG::isKnownNeverZeroFloat(SDValue Op) const {
4687   assert(Op.getValueType().isFloatingPoint() &&
4688          "Floating point type expected");
4689 
4690   // If the value is a constant, we can obviously see if it is a zero or not.
4691   // TODO: Add BuildVector support.
4692   if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op))
4693     return !C->isZero();
4694   return false;
4695 }
4696 
4697 bool SelectionDAG::isKnownNeverZero(SDValue Op) const {
4698   assert(!Op.getValueType().isFloatingPoint() &&
4699          "Floating point types unsupported - use isKnownNeverZeroFloat");
4700 
4701   // If the value is a constant, we can obviously see if it is a zero or not.
4702   if (ISD::matchUnaryPredicate(Op,
4703                                [](ConstantSDNode *C) { return !C->isZero(); }))
4704     return true;
4705 
4706   // TODO: Recognize more cases here.
4707   switch (Op.getOpcode()) {
4708   default: break;
4709   case ISD::OR:
4710     if (isKnownNeverZero(Op.getOperand(1)) ||
4711         isKnownNeverZero(Op.getOperand(0)))
4712       return true;
4713     break;
4714   }
4715 
4716   return false;
4717 }
4718 
4719 bool SelectionDAG::isEqualTo(SDValue A, SDValue B) const {
4720   // Check the obvious case.
4721   if (A == B) return true;
4722 
4723   // For for negative and positive zero.
4724   if (const ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A))
4725     if (const ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B))
4726       if (CA->isZero() && CB->isZero()) return true;
4727 
4728   // Otherwise they may not be equal.
4729   return false;
4730 }
4731 
4732 // Only bits set in Mask must be negated, other bits may be arbitrary.
4733 SDValue llvm::getBitwiseNotOperand(SDValue V, SDValue Mask, bool AllowUndefs) {
4734   if (isBitwiseNot(V, AllowUndefs))
4735     return V.getOperand(0);
4736 
4737   // Handle any_extend (not (truncate X)) pattern, where Mask only sets
4738   // bits in the non-extended part.
4739   ConstantSDNode *MaskC = isConstOrConstSplat(Mask);
4740   if (!MaskC || V.getOpcode() != ISD::ANY_EXTEND)
4741     return SDValue();
4742   SDValue ExtArg = V.getOperand(0);
4743   if (ExtArg.getScalarValueSizeInBits() >=
4744           MaskC->getAPIntValue().getActiveBits() &&
4745       isBitwiseNot(ExtArg, AllowUndefs) &&
4746       ExtArg.getOperand(0).getOpcode() == ISD::TRUNCATE &&
4747       ExtArg.getOperand(0).getOperand(0).getValueType() == V.getValueType())
4748     return ExtArg.getOperand(0).getOperand(0);
4749   return SDValue();
4750 }
4751 
4752 static bool haveNoCommonBitsSetCommutative(SDValue A, SDValue B) {
4753   // Match masked merge pattern (X & ~M) op (Y & M)
4754   // Including degenerate case (X & ~M) op M
4755   auto MatchNoCommonBitsPattern = [&](SDValue Not, SDValue Mask,
4756                                       SDValue Other) {
4757     if (SDValue NotOperand =
4758             getBitwiseNotOperand(Not, Mask, /* AllowUndefs */ true)) {
4759       if (Other == NotOperand)
4760         return true;
4761       if (Other->getOpcode() == ISD::AND)
4762         return NotOperand == Other->getOperand(0) ||
4763                NotOperand == Other->getOperand(1);
4764     }
4765     return false;
4766   };
4767   if (A->getOpcode() == ISD::AND)
4768     return MatchNoCommonBitsPattern(A->getOperand(0), A->getOperand(1), B) ||
4769            MatchNoCommonBitsPattern(A->getOperand(1), A->getOperand(0), B);
4770   return false;
4771 }
4772 
4773 // FIXME: unify with llvm::haveNoCommonBitsSet.
4774 bool SelectionDAG::haveNoCommonBitsSet(SDValue A, SDValue B) const {
4775   assert(A.getValueType() == B.getValueType() &&
4776          "Values must have the same type");
4777   if (haveNoCommonBitsSetCommutative(A, B) ||
4778       haveNoCommonBitsSetCommutative(B, A))
4779     return true;
4780   return KnownBits::haveNoCommonBitsSet(computeKnownBits(A),
4781                                         computeKnownBits(B));
4782 }
4783 
4784 static SDValue FoldSTEP_VECTOR(const SDLoc &DL, EVT VT, SDValue Step,
4785                                SelectionDAG &DAG) {
4786   if (cast<ConstantSDNode>(Step)->isZero())
4787     return DAG.getConstant(0, DL, VT);
4788 
4789   return SDValue();
4790 }
4791 
4792 static SDValue FoldBUILD_VECTOR(const SDLoc &DL, EVT VT,
4793                                 ArrayRef<SDValue> Ops,
4794                                 SelectionDAG &DAG) {
4795   int NumOps = Ops.size();
4796   assert(NumOps != 0 && "Can't build an empty vector!");
4797   assert(!VT.isScalableVector() &&
4798          "BUILD_VECTOR cannot be used with scalable types");
4799   assert(VT.getVectorNumElements() == (unsigned)NumOps &&
4800          "Incorrect element count in BUILD_VECTOR!");
4801 
4802   // BUILD_VECTOR of UNDEFs is UNDEF.
4803   if (llvm::all_of(Ops, [](SDValue Op) { return Op.isUndef(); }))
4804     return DAG.getUNDEF(VT);
4805 
4806   // BUILD_VECTOR of seq extract/insert from the same vector + type is Identity.
4807   SDValue IdentitySrc;
4808   bool IsIdentity = true;
4809   for (int i = 0; i != NumOps; ++i) {
4810     if (Ops[i].getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
4811         Ops[i].getOperand(0).getValueType() != VT ||
4812         (IdentitySrc && Ops[i].getOperand(0) != IdentitySrc) ||
4813         !isa<ConstantSDNode>(Ops[i].getOperand(1)) ||
4814         cast<ConstantSDNode>(Ops[i].getOperand(1))->getAPIntValue() != i) {
4815       IsIdentity = false;
4816       break;
4817     }
4818     IdentitySrc = Ops[i].getOperand(0);
4819   }
4820   if (IsIdentity)
4821     return IdentitySrc;
4822 
4823   return SDValue();
4824 }
4825 
4826 /// Try to simplify vector concatenation to an input value, undef, or build
4827 /// vector.
4828 static SDValue foldCONCAT_VECTORS(const SDLoc &DL, EVT VT,
4829                                   ArrayRef<SDValue> Ops,
4830                                   SelectionDAG &DAG) {
4831   assert(!Ops.empty() && "Can't concatenate an empty list of vectors!");
4832   assert(llvm::all_of(Ops,
4833                       [Ops](SDValue Op) {
4834                         return Ops[0].getValueType() == Op.getValueType();
4835                       }) &&
4836          "Concatenation of vectors with inconsistent value types!");
4837   assert((Ops[0].getValueType().getVectorElementCount() * Ops.size()) ==
4838              VT.getVectorElementCount() &&
4839          "Incorrect element count in vector concatenation!");
4840 
4841   if (Ops.size() == 1)
4842     return Ops[0];
4843 
4844   // Concat of UNDEFs is UNDEF.
4845   if (llvm::all_of(Ops, [](SDValue Op) { return Op.isUndef(); }))
4846     return DAG.getUNDEF(VT);
4847 
4848   // Scan the operands and look for extract operations from a single source
4849   // that correspond to insertion at the same location via this concatenation:
4850   // concat (extract X, 0*subvec_elts), (extract X, 1*subvec_elts), ...
4851   SDValue IdentitySrc;
4852   bool IsIdentity = true;
4853   for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
4854     SDValue Op = Ops[i];
4855     unsigned IdentityIndex = i * Op.getValueType().getVectorMinNumElements();
4856     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
4857         Op.getOperand(0).getValueType() != VT ||
4858         (IdentitySrc && Op.getOperand(0) != IdentitySrc) ||
4859         Op.getConstantOperandVal(1) != IdentityIndex) {
4860       IsIdentity = false;
4861       break;
4862     }
4863     assert((!IdentitySrc || IdentitySrc == Op.getOperand(0)) &&
4864            "Unexpected identity source vector for concat of extracts");
4865     IdentitySrc = Op.getOperand(0);
4866   }
4867   if (IsIdentity) {
4868     assert(IdentitySrc && "Failed to set source vector of extracts");
4869     return IdentitySrc;
4870   }
4871 
4872   // The code below this point is only designed to work for fixed width
4873   // vectors, so we bail out for now.
4874   if (VT.isScalableVector())
4875     return SDValue();
4876 
4877   // A CONCAT_VECTOR with all UNDEF/BUILD_VECTOR operands can be
4878   // simplified to one big BUILD_VECTOR.
4879   // FIXME: Add support for SCALAR_TO_VECTOR as well.
4880   EVT SVT = VT.getScalarType();
4881   SmallVector<SDValue, 16> Elts;
4882   for (SDValue Op : Ops) {
4883     EVT OpVT = Op.getValueType();
4884     if (Op.isUndef())
4885       Elts.append(OpVT.getVectorNumElements(), DAG.getUNDEF(SVT));
4886     else if (Op.getOpcode() == ISD::BUILD_VECTOR)
4887       Elts.append(Op->op_begin(), Op->op_end());
4888     else
4889       return SDValue();
4890   }
4891 
4892   // BUILD_VECTOR requires all inputs to be of the same type, find the
4893   // maximum type and extend them all.
4894   for (SDValue Op : Elts)
4895     SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
4896 
4897   if (SVT.bitsGT(VT.getScalarType())) {
4898     for (SDValue &Op : Elts) {
4899       if (Op.isUndef())
4900         Op = DAG.getUNDEF(SVT);
4901       else
4902         Op = DAG.getTargetLoweringInfo().isZExtFree(Op.getValueType(), SVT)
4903                  ? DAG.getZExtOrTrunc(Op, DL, SVT)
4904                  : DAG.getSExtOrTrunc(Op, DL, SVT);
4905     }
4906   }
4907 
4908   SDValue V = DAG.getBuildVector(VT, DL, Elts);
4909   NewSDValueDbgMsg(V, "New node fold concat vectors: ", &DAG);
4910   return V;
4911 }
4912 
4913 /// Gets or creates the specified node.
4914 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT) {
4915   FoldingSetNodeID ID;
4916   AddNodeIDNode(ID, Opcode, getVTList(VT), None);
4917   void *IP = nullptr;
4918   if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
4919     return SDValue(E, 0);
4920 
4921   auto *N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(),
4922                               getVTList(VT));
4923   CSEMap.InsertNode(N, IP);
4924 
4925   InsertNode(N);
4926   SDValue V = SDValue(N, 0);
4927   NewSDValueDbgMsg(V, "Creating new node: ", this);
4928   return V;
4929 }
4930 
4931 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
4932                               SDValue Operand) {
4933   SDNodeFlags Flags;
4934   if (Inserter)
4935     Flags = Inserter->getFlags();
4936   return getNode(Opcode, DL, VT, Operand, Flags);
4937 }
4938 
4939 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
4940                               SDValue Operand, const SDNodeFlags Flags) {
4941   assert(Operand.getOpcode() != ISD::DELETED_NODE &&
4942          "Operand is DELETED_NODE!");
4943   // Constant fold unary operations with an integer constant operand. Even
4944   // opaque constant will be folded, because the folding of unary operations
4945   // doesn't create new constants with different values. Nevertheless, the
4946   // opaque flag is preserved during folding to prevent future folding with
4947   // other constants.
4948   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Operand)) {
4949     const APInt &Val = C->getAPIntValue();
4950     switch (Opcode) {
4951     default: break;
4952     case ISD::SIGN_EXTEND:
4953       return getConstant(Val.sextOrTrunc(VT.getSizeInBits()), DL, VT,
4954                          C->isTargetOpcode(), C->isOpaque());
4955     case ISD::TRUNCATE:
4956       if (C->isOpaque())
4957         break;
4958       LLVM_FALLTHROUGH;
4959     case ISD::ZERO_EXTEND:
4960       return getConstant(Val.zextOrTrunc(VT.getSizeInBits()), DL, VT,
4961                          C->isTargetOpcode(), C->isOpaque());
4962     case ISD::ANY_EXTEND:
4963       // Some targets like RISCV prefer to sign extend some types.
4964       if (TLI->isSExtCheaperThanZExt(Operand.getValueType(), VT))
4965         return getConstant(Val.sextOrTrunc(VT.getSizeInBits()), DL, VT,
4966                            C->isTargetOpcode(), C->isOpaque());
4967       return getConstant(Val.zextOrTrunc(VT.getSizeInBits()), DL, VT,
4968                          C->isTargetOpcode(), C->isOpaque());
4969     case ISD::UINT_TO_FP:
4970     case ISD::SINT_TO_FP: {
4971       APFloat apf(EVTToAPFloatSemantics(VT),
4972                   APInt::getZero(VT.getSizeInBits()));
4973       (void)apf.convertFromAPInt(Val,
4974                                  Opcode==ISD::SINT_TO_FP,
4975                                  APFloat::rmNearestTiesToEven);
4976       return getConstantFP(apf, DL, VT);
4977     }
4978     case ISD::BITCAST:
4979       if (VT == MVT::f16 && C->getValueType(0) == MVT::i16)
4980         return getConstantFP(APFloat(APFloat::IEEEhalf(), Val), DL, VT);
4981       if (VT == MVT::f32 && C->getValueType(0) == MVT::i32)
4982         return getConstantFP(APFloat(APFloat::IEEEsingle(), Val), DL, VT);
4983       if (VT == MVT::f64 && C->getValueType(0) == MVT::i64)
4984         return getConstantFP(APFloat(APFloat::IEEEdouble(), Val), DL, VT);
4985       if (VT == MVT::f128 && C->getValueType(0) == MVT::i128)
4986         return getConstantFP(APFloat(APFloat::IEEEquad(), Val), DL, VT);
4987       break;
4988     case ISD::ABS:
4989       return getConstant(Val.abs(), DL, VT, C->isTargetOpcode(),
4990                          C->isOpaque());
4991     case ISD::BITREVERSE:
4992       return getConstant(Val.reverseBits(), DL, VT, C->isTargetOpcode(),
4993                          C->isOpaque());
4994     case ISD::BSWAP:
4995       return getConstant(Val.byteSwap(), DL, VT, C->isTargetOpcode(),
4996                          C->isOpaque());
4997     case ISD::CTPOP:
4998       return getConstant(Val.countPopulation(), DL, VT, C->isTargetOpcode(),
4999                          C->isOpaque());
5000     case ISD::CTLZ:
5001     case ISD::CTLZ_ZERO_UNDEF:
5002       return getConstant(Val.countLeadingZeros(), DL, VT, C->isTargetOpcode(),
5003                          C->isOpaque());
5004     case ISD::CTTZ:
5005     case ISD::CTTZ_ZERO_UNDEF:
5006       return getConstant(Val.countTrailingZeros(), DL, VT, C->isTargetOpcode(),
5007                          C->isOpaque());
5008     case ISD::FP16_TO_FP:
5009     case ISD::BF16_TO_FP: {
5010       bool Ignored;
5011       APFloat FPV(Opcode == ISD::FP16_TO_FP ? APFloat::IEEEhalf()
5012                                             : APFloat::BFloat(),
5013                   (Val.getBitWidth() == 16) ? Val : Val.trunc(16));
5014 
5015       // This can return overflow, underflow, or inexact; we don't care.
5016       // FIXME need to be more flexible about rounding mode.
5017       (void)FPV.convert(EVTToAPFloatSemantics(VT),
5018                         APFloat::rmNearestTiesToEven, &Ignored);
5019       return getConstantFP(FPV, DL, VT);
5020     }
5021     case ISD::STEP_VECTOR: {
5022       if (SDValue V = FoldSTEP_VECTOR(DL, VT, Operand, *this))
5023         return V;
5024       break;
5025     }
5026     }
5027   }
5028 
5029   // Constant fold unary operations with a floating point constant operand.
5030   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Operand)) {
5031     APFloat V = C->getValueAPF();    // make copy
5032     switch (Opcode) {
5033     case ISD::FNEG:
5034       V.changeSign();
5035       return getConstantFP(V, DL, VT);
5036     case ISD::FABS:
5037       V.clearSign();
5038       return getConstantFP(V, DL, VT);
5039     case ISD::FCEIL: {
5040       APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardPositive);
5041       if (fs == APFloat::opOK || fs == APFloat::opInexact)
5042         return getConstantFP(V, DL, VT);
5043       break;
5044     }
5045     case ISD::FTRUNC: {
5046       APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardZero);
5047       if (fs == APFloat::opOK || fs == APFloat::opInexact)
5048         return getConstantFP(V, DL, VT);
5049       break;
5050     }
5051     case ISD::FFLOOR: {
5052       APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardNegative);
5053       if (fs == APFloat::opOK || fs == APFloat::opInexact)
5054         return getConstantFP(V, DL, VT);
5055       break;
5056     }
5057     case ISD::FP_EXTEND: {
5058       bool ignored;
5059       // This can return overflow, underflow, or inexact; we don't care.
5060       // FIXME need to be more flexible about rounding mode.
5061       (void)V.convert(EVTToAPFloatSemantics(VT),
5062                       APFloat::rmNearestTiesToEven, &ignored);
5063       return getConstantFP(V, DL, VT);
5064     }
5065     case ISD::FP_TO_SINT:
5066     case ISD::FP_TO_UINT: {
5067       bool ignored;
5068       APSInt IntVal(VT.getSizeInBits(), Opcode == ISD::FP_TO_UINT);
5069       // FIXME need to be more flexible about rounding mode.
5070       APFloat::opStatus s =
5071           V.convertToInteger(IntVal, APFloat::rmTowardZero, &ignored);
5072       if (s == APFloat::opInvalidOp) // inexact is OK, in fact usual
5073         break;
5074       return getConstant(IntVal, DL, VT);
5075     }
5076     case ISD::BITCAST:
5077       if (VT == MVT::i16 && C->getValueType(0) == MVT::f16)
5078         return getConstant((uint16_t)V.bitcastToAPInt().getZExtValue(), DL, VT);
5079       if (VT == MVT::i16 && C->getValueType(0) == MVT::bf16)
5080         return getConstant((uint16_t)V.bitcastToAPInt().getZExtValue(), DL, VT);
5081       if (VT == MVT::i32 && C->getValueType(0) == MVT::f32)
5082         return getConstant((uint32_t)V.bitcastToAPInt().getZExtValue(), DL, VT);
5083       if (VT == MVT::i64 && C->getValueType(0) == MVT::f64)
5084         return getConstant(V.bitcastToAPInt().getZExtValue(), DL, VT);
5085       break;
5086     case ISD::FP_TO_FP16:
5087     case ISD::FP_TO_BF16: {
5088       bool Ignored;
5089       // This can return overflow, underflow, or inexact; we don't care.
5090       // FIXME need to be more flexible about rounding mode.
5091       (void)V.convert(Opcode == ISD::FP_TO_FP16 ? APFloat::IEEEhalf()
5092                                                 : APFloat::BFloat(),
5093                       APFloat::rmNearestTiesToEven, &Ignored);
5094       return getConstant(V.bitcastToAPInt().getZExtValue(), DL, VT);
5095     }
5096     }
5097   }
5098 
5099   // Constant fold unary operations with a vector integer or float operand.
5100   switch (Opcode) {
5101   default:
5102     // FIXME: Entirely reasonable to perform folding of other unary
5103     // operations here as the need arises.
5104     break;
5105   case ISD::FNEG:
5106   case ISD::FABS:
5107   case ISD::FCEIL:
5108   case ISD::FTRUNC:
5109   case ISD::FFLOOR:
5110   case ISD::FP_EXTEND:
5111   case ISD::FP_TO_SINT:
5112   case ISD::FP_TO_UINT:
5113   case ISD::TRUNCATE:
5114   case ISD::ANY_EXTEND:
5115   case ISD::ZERO_EXTEND:
5116   case ISD::SIGN_EXTEND:
5117   case ISD::UINT_TO_FP:
5118   case ISD::SINT_TO_FP:
5119   case ISD::ABS:
5120   case ISD::BITREVERSE:
5121   case ISD::BSWAP:
5122   case ISD::CTLZ:
5123   case ISD::CTLZ_ZERO_UNDEF:
5124   case ISD::CTTZ:
5125   case ISD::CTTZ_ZERO_UNDEF:
5126   case ISD::CTPOP: {
5127     SDValue Ops = {Operand};
5128     if (SDValue Fold = FoldConstantArithmetic(Opcode, DL, VT, Ops))
5129       return Fold;
5130   }
5131   }
5132 
5133   unsigned OpOpcode = Operand.getNode()->getOpcode();
5134   switch (Opcode) {
5135   case ISD::STEP_VECTOR:
5136     assert(VT.isScalableVector() &&
5137            "STEP_VECTOR can only be used with scalable types");
5138     assert(OpOpcode == ISD::TargetConstant &&
5139            VT.getVectorElementType() == Operand.getValueType() &&
5140            "Unexpected step operand");
5141     break;
5142   case ISD::FREEZE:
5143     assert(VT == Operand.getValueType() && "Unexpected VT!");
5144     if (isGuaranteedNotToBeUndefOrPoison(Operand))
5145       return Operand;
5146     break;
5147   case ISD::TokenFactor:
5148   case ISD::MERGE_VALUES:
5149   case ISD::CONCAT_VECTORS:
5150     return Operand;         // Factor, merge or concat of one node?  No need.
5151   case ISD::BUILD_VECTOR: {
5152     // Attempt to simplify BUILD_VECTOR.
5153     SDValue Ops[] = {Operand};
5154     if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
5155       return V;
5156     break;
5157   }
5158   case ISD::FP_ROUND: llvm_unreachable("Invalid method to make FP_ROUND node");
5159   case ISD::FP_EXTEND:
5160     assert(VT.isFloatingPoint() &&
5161            Operand.getValueType().isFloatingPoint() && "Invalid FP cast!");
5162     if (Operand.getValueType() == VT) return Operand;  // noop conversion.
5163     assert((!VT.isVector() ||
5164             VT.getVectorElementCount() ==
5165             Operand.getValueType().getVectorElementCount()) &&
5166            "Vector element count mismatch!");
5167     assert(Operand.getValueType().bitsLT(VT) &&
5168            "Invalid fpext node, dst < src!");
5169     if (Operand.isUndef())
5170       return getUNDEF(VT);
5171     break;
5172   case ISD::FP_TO_SINT:
5173   case ISD::FP_TO_UINT:
5174     if (Operand.isUndef())
5175       return getUNDEF(VT);
5176     break;
5177   case ISD::SINT_TO_FP:
5178   case ISD::UINT_TO_FP:
5179     // [us]itofp(undef) = 0, because the result value is bounded.
5180     if (Operand.isUndef())
5181       return getConstantFP(0.0, DL, VT);
5182     break;
5183   case ISD::SIGN_EXTEND:
5184     assert(VT.isInteger() && Operand.getValueType().isInteger() &&
5185            "Invalid SIGN_EXTEND!");
5186     assert(VT.isVector() == Operand.getValueType().isVector() &&
5187            "SIGN_EXTEND result type type should be vector iff the operand "
5188            "type is vector!");
5189     if (Operand.getValueType() == VT) return Operand;   // noop extension
5190     assert((!VT.isVector() ||
5191             VT.getVectorElementCount() ==
5192                 Operand.getValueType().getVectorElementCount()) &&
5193            "Vector element count mismatch!");
5194     assert(Operand.getValueType().bitsLT(VT) &&
5195            "Invalid sext node, dst < src!");
5196     if (OpOpcode == ISD::SIGN_EXTEND || OpOpcode == ISD::ZERO_EXTEND)
5197       return getNode(OpOpcode, DL, VT, Operand.getOperand(0));
5198     if (OpOpcode == ISD::UNDEF)
5199       // sext(undef) = 0, because the top bits will all be the same.
5200       return getConstant(0, DL, VT);
5201     break;
5202   case ISD::ZERO_EXTEND:
5203     assert(VT.isInteger() && Operand.getValueType().isInteger() &&
5204            "Invalid ZERO_EXTEND!");
5205     assert(VT.isVector() == Operand.getValueType().isVector() &&
5206            "ZERO_EXTEND result type type should be vector iff the operand "
5207            "type is vector!");
5208     if (Operand.getValueType() == VT) return Operand;   // noop extension
5209     assert((!VT.isVector() ||
5210             VT.getVectorElementCount() ==
5211                 Operand.getValueType().getVectorElementCount()) &&
5212            "Vector element count mismatch!");
5213     assert(Operand.getValueType().bitsLT(VT) &&
5214            "Invalid zext node, dst < src!");
5215     if (OpOpcode == ISD::ZERO_EXTEND)   // (zext (zext x)) -> (zext x)
5216       return getNode(ISD::ZERO_EXTEND, DL, VT, Operand.getOperand(0));
5217     if (OpOpcode == ISD::UNDEF)
5218       // zext(undef) = 0, because the top bits will be zero.
5219       return getConstant(0, DL, VT);
5220     break;
5221   case ISD::ANY_EXTEND:
5222     assert(VT.isInteger() && Operand.getValueType().isInteger() &&
5223            "Invalid ANY_EXTEND!");
5224     assert(VT.isVector() == Operand.getValueType().isVector() &&
5225            "ANY_EXTEND result type type should be vector iff the operand "
5226            "type is vector!");
5227     if (Operand.getValueType() == VT) return Operand;   // noop extension
5228     assert((!VT.isVector() ||
5229             VT.getVectorElementCount() ==
5230                 Operand.getValueType().getVectorElementCount()) &&
5231            "Vector element count mismatch!");
5232     assert(Operand.getValueType().bitsLT(VT) &&
5233            "Invalid anyext node, dst < src!");
5234 
5235     if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
5236         OpOpcode == ISD::ANY_EXTEND)
5237       // (ext (zext x)) -> (zext x)  and  (ext (sext x)) -> (sext x)
5238       return getNode(OpOpcode, DL, VT, Operand.getOperand(0));
5239     if (OpOpcode == ISD::UNDEF)
5240       return getUNDEF(VT);
5241 
5242     // (ext (trunc x)) -> x
5243     if (OpOpcode == ISD::TRUNCATE) {
5244       SDValue OpOp = Operand.getOperand(0);
5245       if (OpOp.getValueType() == VT) {
5246         transferDbgValues(Operand, OpOp);
5247         return OpOp;
5248       }
5249     }
5250     break;
5251   case ISD::TRUNCATE:
5252     assert(VT.isInteger() && Operand.getValueType().isInteger() &&
5253            "Invalid TRUNCATE!");
5254     assert(VT.isVector() == Operand.getValueType().isVector() &&
5255            "TRUNCATE result type type should be vector iff the operand "
5256            "type is vector!");
5257     if (Operand.getValueType() == VT) return Operand;   // noop truncate
5258     assert((!VT.isVector() ||
5259             VT.getVectorElementCount() ==
5260                 Operand.getValueType().getVectorElementCount()) &&
5261            "Vector element count mismatch!");
5262     assert(Operand.getValueType().bitsGT(VT) &&
5263            "Invalid truncate node, src < dst!");
5264     if (OpOpcode == ISD::TRUNCATE)
5265       return getNode(ISD::TRUNCATE, DL, VT, Operand.getOperand(0));
5266     if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
5267         OpOpcode == ISD::ANY_EXTEND) {
5268       // If the source is smaller than the dest, we still need an extend.
5269       if (Operand.getOperand(0).getValueType().getScalarType()
5270             .bitsLT(VT.getScalarType()))
5271         return getNode(OpOpcode, DL, VT, Operand.getOperand(0));
5272       if (Operand.getOperand(0).getValueType().bitsGT(VT))
5273         return getNode(ISD::TRUNCATE, DL, VT, Operand.getOperand(0));
5274       return Operand.getOperand(0);
5275     }
5276     if (OpOpcode == ISD::UNDEF)
5277       return getUNDEF(VT);
5278     if (OpOpcode == ISD::VSCALE && !NewNodesMustHaveLegalTypes)
5279       return getVScale(DL, VT, Operand.getConstantOperandAPInt(0));
5280     break;
5281   case ISD::ANY_EXTEND_VECTOR_INREG:
5282   case ISD::ZERO_EXTEND_VECTOR_INREG:
5283   case ISD::SIGN_EXTEND_VECTOR_INREG:
5284     assert(VT.isVector() && "This DAG node is restricted to vector types.");
5285     assert(Operand.getValueType().bitsLE(VT) &&
5286            "The input must be the same size or smaller than the result.");
5287     assert(VT.getVectorMinNumElements() <
5288                Operand.getValueType().getVectorMinNumElements() &&
5289            "The destination vector type must have fewer lanes than the input.");
5290     break;
5291   case ISD::ABS:
5292     assert(VT.isInteger() && VT == Operand.getValueType() &&
5293            "Invalid ABS!");
5294     if (OpOpcode == ISD::UNDEF)
5295       return getConstant(0, DL, VT);
5296     break;
5297   case ISD::BSWAP:
5298     assert(VT.isInteger() && VT == Operand.getValueType() &&
5299            "Invalid BSWAP!");
5300     assert((VT.getScalarSizeInBits() % 16 == 0) &&
5301            "BSWAP types must be a multiple of 16 bits!");
5302     if (OpOpcode == ISD::UNDEF)
5303       return getUNDEF(VT);
5304     // bswap(bswap(X)) -> X.
5305     if (OpOpcode == ISD::BSWAP)
5306       return Operand.getOperand(0);
5307     break;
5308   case ISD::BITREVERSE:
5309     assert(VT.isInteger() && VT == Operand.getValueType() &&
5310            "Invalid BITREVERSE!");
5311     if (OpOpcode == ISD::UNDEF)
5312       return getUNDEF(VT);
5313     break;
5314   case ISD::BITCAST:
5315     assert(VT.getSizeInBits() == Operand.getValueSizeInBits() &&
5316            "Cannot BITCAST between types of different sizes!");
5317     if (VT == Operand.getValueType()) return Operand;  // noop conversion.
5318     if (OpOpcode == ISD::BITCAST)  // bitconv(bitconv(x)) -> bitconv(x)
5319       return getNode(ISD::BITCAST, DL, VT, Operand.getOperand(0));
5320     if (OpOpcode == ISD::UNDEF)
5321       return getUNDEF(VT);
5322     break;
5323   case ISD::SCALAR_TO_VECTOR:
5324     assert(VT.isVector() && !Operand.getValueType().isVector() &&
5325            (VT.getVectorElementType() == Operand.getValueType() ||
5326             (VT.getVectorElementType().isInteger() &&
5327              Operand.getValueType().isInteger() &&
5328              VT.getVectorElementType().bitsLE(Operand.getValueType()))) &&
5329            "Illegal SCALAR_TO_VECTOR node!");
5330     if (OpOpcode == ISD::UNDEF)
5331       return getUNDEF(VT);
5332     // scalar_to_vector(extract_vector_elt V, 0) -> V, top bits are undefined.
5333     if (OpOpcode == ISD::EXTRACT_VECTOR_ELT &&
5334         isa<ConstantSDNode>(Operand.getOperand(1)) &&
5335         Operand.getConstantOperandVal(1) == 0 &&
5336         Operand.getOperand(0).getValueType() == VT)
5337       return Operand.getOperand(0);
5338     break;
5339   case ISD::FNEG:
5340     // Negation of an unknown bag of bits is still completely undefined.
5341     if (OpOpcode == ISD::UNDEF)
5342       return getUNDEF(VT);
5343 
5344     if (OpOpcode == ISD::FNEG)  // --X -> X
5345       return Operand.getOperand(0);
5346     break;
5347   case ISD::FABS:
5348     if (OpOpcode == ISD::FNEG)  // abs(-X) -> abs(X)
5349       return getNode(ISD::FABS, DL, VT, Operand.getOperand(0));
5350     break;
5351   case ISD::VSCALE:
5352     assert(VT == Operand.getValueType() && "Unexpected VT!");
5353     break;
5354   case ISD::CTPOP:
5355     if (Operand.getValueType().getScalarType() == MVT::i1)
5356       return Operand;
5357     break;
5358   case ISD::CTLZ:
5359   case ISD::CTTZ:
5360     if (Operand.getValueType().getScalarType() == MVT::i1)
5361       return getNOT(DL, Operand, Operand.getValueType());
5362     break;
5363   case ISD::VECREDUCE_ADD:
5364     if (Operand.getValueType().getScalarType() == MVT::i1)
5365       return getNode(ISD::VECREDUCE_XOR, DL, VT, Operand);
5366     break;
5367   case ISD::VECREDUCE_SMIN:
5368   case ISD::VECREDUCE_UMAX:
5369     if (Operand.getValueType().getScalarType() == MVT::i1)
5370       return getNode(ISD::VECREDUCE_OR, DL, VT, Operand);
5371     break;
5372   case ISD::VECREDUCE_SMAX:
5373   case ISD::VECREDUCE_UMIN:
5374     if (Operand.getValueType().getScalarType() == MVT::i1)
5375       return getNode(ISD::VECREDUCE_AND, DL, VT, Operand);
5376     break;
5377   }
5378 
5379   SDNode *N;
5380   SDVTList VTs = getVTList(VT);
5381   SDValue Ops[] = {Operand};
5382   if (VT != MVT::Glue) { // Don't CSE flag producing nodes
5383     FoldingSetNodeID ID;
5384     AddNodeIDNode(ID, Opcode, VTs, Ops);
5385     void *IP = nullptr;
5386     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
5387       E->intersectFlagsWith(Flags);
5388       return SDValue(E, 0);
5389     }
5390 
5391     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
5392     N->setFlags(Flags);
5393     createOperands(N, Ops);
5394     CSEMap.InsertNode(N, IP);
5395   } else {
5396     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
5397     createOperands(N, Ops);
5398   }
5399 
5400   InsertNode(N);
5401   SDValue V = SDValue(N, 0);
5402   NewSDValueDbgMsg(V, "Creating new node: ", this);
5403   return V;
5404 }
5405 
5406 static llvm::Optional<APInt> FoldValue(unsigned Opcode, const APInt &C1,
5407                                        const APInt &C2) {
5408   switch (Opcode) {
5409   case ISD::ADD:  return C1 + C2;
5410   case ISD::SUB:  return C1 - C2;
5411   case ISD::MUL:  return C1 * C2;
5412   case ISD::AND:  return C1 & C2;
5413   case ISD::OR:   return C1 | C2;
5414   case ISD::XOR:  return C1 ^ C2;
5415   case ISD::SHL:  return C1 << C2;
5416   case ISD::SRL:  return C1.lshr(C2);
5417   case ISD::SRA:  return C1.ashr(C2);
5418   case ISD::ROTL: return C1.rotl(C2);
5419   case ISD::ROTR: return C1.rotr(C2);
5420   case ISD::SMIN: return C1.sle(C2) ? C1 : C2;
5421   case ISD::SMAX: return C1.sge(C2) ? C1 : C2;
5422   case ISD::UMIN: return C1.ule(C2) ? C1 : C2;
5423   case ISD::UMAX: return C1.uge(C2) ? C1 : C2;
5424   case ISD::SADDSAT: return C1.sadd_sat(C2);
5425   case ISD::UADDSAT: return C1.uadd_sat(C2);
5426   case ISD::SSUBSAT: return C1.ssub_sat(C2);
5427   case ISD::USUBSAT: return C1.usub_sat(C2);
5428   case ISD::SSHLSAT: return C1.sshl_sat(C2);
5429   case ISD::USHLSAT: return C1.ushl_sat(C2);
5430   case ISD::UDIV:
5431     if (!C2.getBoolValue())
5432       break;
5433     return C1.udiv(C2);
5434   case ISD::UREM:
5435     if (!C2.getBoolValue())
5436       break;
5437     return C1.urem(C2);
5438   case ISD::SDIV:
5439     if (!C2.getBoolValue())
5440       break;
5441     return C1.sdiv(C2);
5442   case ISD::SREM:
5443     if (!C2.getBoolValue())
5444       break;
5445     return C1.srem(C2);
5446   case ISD::MULHS: {
5447     unsigned FullWidth = C1.getBitWidth() * 2;
5448     APInt C1Ext = C1.sext(FullWidth);
5449     APInt C2Ext = C2.sext(FullWidth);
5450     return (C1Ext * C2Ext).extractBits(C1.getBitWidth(), C1.getBitWidth());
5451   }
5452   case ISD::MULHU: {
5453     unsigned FullWidth = C1.getBitWidth() * 2;
5454     APInt C1Ext = C1.zext(FullWidth);
5455     APInt C2Ext = C2.zext(FullWidth);
5456     return (C1Ext * C2Ext).extractBits(C1.getBitWidth(), C1.getBitWidth());
5457   }
5458   case ISD::AVGFLOORS: {
5459     unsigned FullWidth = C1.getBitWidth() + 1;
5460     APInt C1Ext = C1.sext(FullWidth);
5461     APInt C2Ext = C2.sext(FullWidth);
5462     return (C1Ext + C2Ext).extractBits(C1.getBitWidth(), 1);
5463   }
5464   case ISD::AVGFLOORU: {
5465     unsigned FullWidth = C1.getBitWidth() + 1;
5466     APInt C1Ext = C1.zext(FullWidth);
5467     APInt C2Ext = C2.zext(FullWidth);
5468     return (C1Ext + C2Ext).extractBits(C1.getBitWidth(), 1);
5469   }
5470   case ISD::AVGCEILS: {
5471     unsigned FullWidth = C1.getBitWidth() + 1;
5472     APInt C1Ext = C1.sext(FullWidth);
5473     APInt C2Ext = C2.sext(FullWidth);
5474     return (C1Ext + C2Ext + 1).extractBits(C1.getBitWidth(), 1);
5475   }
5476   case ISD::AVGCEILU: {
5477     unsigned FullWidth = C1.getBitWidth() + 1;
5478     APInt C1Ext = C1.zext(FullWidth);
5479     APInt C2Ext = C2.zext(FullWidth);
5480     return (C1Ext + C2Ext + 1).extractBits(C1.getBitWidth(), 1);
5481   }
5482   }
5483   return llvm::None;
5484 }
5485 
5486 SDValue SelectionDAG::FoldSymbolOffset(unsigned Opcode, EVT VT,
5487                                        const GlobalAddressSDNode *GA,
5488                                        const SDNode *N2) {
5489   if (GA->getOpcode() != ISD::GlobalAddress)
5490     return SDValue();
5491   if (!TLI->isOffsetFoldingLegal(GA))
5492     return SDValue();
5493   auto *C2 = dyn_cast<ConstantSDNode>(N2);
5494   if (!C2)
5495     return SDValue();
5496   int64_t Offset = C2->getSExtValue();
5497   switch (Opcode) {
5498   case ISD::ADD: break;
5499   case ISD::SUB: Offset = -uint64_t(Offset); break;
5500   default: return SDValue();
5501   }
5502   return getGlobalAddress(GA->getGlobal(), SDLoc(C2), VT,
5503                           GA->getOffset() + uint64_t(Offset));
5504 }
5505 
5506 bool SelectionDAG::isUndef(unsigned Opcode, ArrayRef<SDValue> Ops) {
5507   switch (Opcode) {
5508   case ISD::SDIV:
5509   case ISD::UDIV:
5510   case ISD::SREM:
5511   case ISD::UREM: {
5512     // If a divisor is zero/undef or any element of a divisor vector is
5513     // zero/undef, the whole op is undef.
5514     assert(Ops.size() == 2 && "Div/rem should have 2 operands");
5515     SDValue Divisor = Ops[1];
5516     if (Divisor.isUndef() || isNullConstant(Divisor))
5517       return true;
5518 
5519     return ISD::isBuildVectorOfConstantSDNodes(Divisor.getNode()) &&
5520            llvm::any_of(Divisor->op_values(),
5521                         [](SDValue V) { return V.isUndef() ||
5522                                         isNullConstant(V); });
5523     // TODO: Handle signed overflow.
5524   }
5525   // TODO: Handle oversized shifts.
5526   default:
5527     return false;
5528   }
5529 }
5530 
5531 SDValue SelectionDAG::FoldConstantArithmetic(unsigned Opcode, const SDLoc &DL,
5532                                              EVT VT, ArrayRef<SDValue> Ops) {
5533   // If the opcode is a target-specific ISD node, there's nothing we can
5534   // do here and the operand rules may not line up with the below, so
5535   // bail early.
5536   // We can't create a scalar CONCAT_VECTORS so skip it. It will break
5537   // for concats involving SPLAT_VECTOR. Concats of BUILD_VECTORS are handled by
5538   // foldCONCAT_VECTORS in getNode before this is called.
5539   if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::CONCAT_VECTORS)
5540     return SDValue();
5541 
5542   unsigned NumOps = Ops.size();
5543   if (NumOps == 0)
5544     return SDValue();
5545 
5546   if (isUndef(Opcode, Ops))
5547     return getUNDEF(VT);
5548 
5549   // Handle binops special cases.
5550   if (NumOps == 2) {
5551     if (SDValue CFP = foldConstantFPMath(Opcode, DL, VT, Ops[0], Ops[1]))
5552       return CFP;
5553 
5554     if (auto *C1 = dyn_cast<ConstantSDNode>(Ops[0])) {
5555       if (auto *C2 = dyn_cast<ConstantSDNode>(Ops[1])) {
5556         if (C1->isOpaque() || C2->isOpaque())
5557           return SDValue();
5558 
5559         Optional<APInt> FoldAttempt =
5560             FoldValue(Opcode, C1->getAPIntValue(), C2->getAPIntValue());
5561         if (!FoldAttempt)
5562           return SDValue();
5563 
5564         SDValue Folded = getConstant(*FoldAttempt, DL, VT);
5565         assert((!Folded || !VT.isVector()) &&
5566                "Can't fold vectors ops with scalar operands");
5567         return Folded;
5568       }
5569     }
5570 
5571     // fold (add Sym, c) -> Sym+c
5572     if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Ops[0]))
5573       return FoldSymbolOffset(Opcode, VT, GA, Ops[1].getNode());
5574     if (TLI->isCommutativeBinOp(Opcode))
5575       if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Ops[1]))
5576         return FoldSymbolOffset(Opcode, VT, GA, Ops[0].getNode());
5577   }
5578 
5579   // This is for vector folding only from here on.
5580   if (!VT.isVector())
5581     return SDValue();
5582 
5583   ElementCount NumElts = VT.getVectorElementCount();
5584 
5585   // See if we can fold through bitcasted integer ops.
5586   // TODO: Can we handle undef elements?
5587   if (NumOps == 2 && VT.isFixedLengthVector() && VT.isInteger() &&
5588       Ops[0].getValueType() == VT && Ops[1].getValueType() == VT &&
5589       Ops[0].getOpcode() == ISD::BITCAST &&
5590       Ops[1].getOpcode() == ISD::BITCAST) {
5591     SDValue N1 = peekThroughBitcasts(Ops[0]);
5592     SDValue N2 = peekThroughBitcasts(Ops[1]);
5593     auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
5594     auto *BV2 = dyn_cast<BuildVectorSDNode>(N2);
5595     EVT BVVT = N1.getValueType();
5596     if (BV1 && BV2 && BVVT.isInteger() && BVVT == N2.getValueType()) {
5597       bool IsLE = getDataLayout().isLittleEndian();
5598       unsigned EltBits = VT.getScalarSizeInBits();
5599       SmallVector<APInt> RawBits1, RawBits2;
5600       BitVector UndefElts1, UndefElts2;
5601       if (BV1->getConstantRawBits(IsLE, EltBits, RawBits1, UndefElts1) &&
5602           BV2->getConstantRawBits(IsLE, EltBits, RawBits2, UndefElts2) &&
5603           UndefElts1.none() && UndefElts2.none()) {
5604         SmallVector<APInt> RawBits;
5605         for (unsigned I = 0, E = NumElts.getFixedValue(); I != E; ++I) {
5606           Optional<APInt> Fold = FoldValue(Opcode, RawBits1[I], RawBits2[I]);
5607           if (!Fold)
5608             break;
5609           RawBits.push_back(*Fold);
5610         }
5611         if (RawBits.size() == NumElts.getFixedValue()) {
5612           // We have constant folded, but we need to cast this again back to
5613           // the original (possibly legalized) type.
5614           SmallVector<APInt> DstBits;
5615           BitVector DstUndefs;
5616           BuildVectorSDNode::recastRawBits(IsLE, BVVT.getScalarSizeInBits(),
5617                                            DstBits, RawBits, DstUndefs,
5618                                            BitVector(RawBits.size(), false));
5619           EVT BVEltVT = BV1->getOperand(0).getValueType();
5620           unsigned BVEltBits = BVEltVT.getSizeInBits();
5621           SmallVector<SDValue> Ops(DstBits.size(), getUNDEF(BVEltVT));
5622           for (unsigned I = 0, E = DstBits.size(); I != E; ++I) {
5623             if (DstUndefs[I])
5624               continue;
5625             Ops[I] = getConstant(DstBits[I].sext(BVEltBits), DL, BVEltVT);
5626           }
5627           return getBitcast(VT, getBuildVector(BVVT, DL, Ops));
5628         }
5629       }
5630     }
5631   }
5632 
5633   // Fold (mul step_vector(C0), C1) to (step_vector(C0 * C1)).
5634   //      (shl step_vector(C0), C1) -> (step_vector(C0 << C1))
5635   if ((Opcode == ISD::MUL || Opcode == ISD::SHL) &&
5636       Ops[0].getOpcode() == ISD::STEP_VECTOR) {
5637     APInt RHSVal;
5638     if (ISD::isConstantSplatVector(Ops[1].getNode(), RHSVal)) {
5639       APInt NewStep = Opcode == ISD::MUL
5640                           ? Ops[0].getConstantOperandAPInt(0) * RHSVal
5641                           : Ops[0].getConstantOperandAPInt(0) << RHSVal;
5642       return getStepVector(DL, VT, NewStep);
5643     }
5644   }
5645 
5646   auto IsScalarOrSameVectorSize = [NumElts](const SDValue &Op) {
5647     return !Op.getValueType().isVector() ||
5648            Op.getValueType().getVectorElementCount() == NumElts;
5649   };
5650 
5651   auto IsBuildVectorSplatVectorOrUndef = [](const SDValue &Op) {
5652     return Op.isUndef() || Op.getOpcode() == ISD::CONDCODE ||
5653            Op.getOpcode() == ISD::BUILD_VECTOR ||
5654            Op.getOpcode() == ISD::SPLAT_VECTOR;
5655   };
5656 
5657   // All operands must be vector types with the same number of elements as
5658   // the result type and must be either UNDEF or a build/splat vector
5659   // or UNDEF scalars.
5660   if (!llvm::all_of(Ops, IsBuildVectorSplatVectorOrUndef) ||
5661       !llvm::all_of(Ops, IsScalarOrSameVectorSize))
5662     return SDValue();
5663 
5664   // If we are comparing vectors, then the result needs to be a i1 boolean that
5665   // is then extended back to the legal result type depending on how booleans
5666   // are represented.
5667   EVT SVT = (Opcode == ISD::SETCC ? MVT::i1 : VT.getScalarType());
5668   ISD::NodeType ExtendCode =
5669       (Opcode == ISD::SETCC && SVT != VT.getScalarType())
5670           ? TargetLowering::getExtendForContent(TLI->getBooleanContents(VT))
5671           : ISD::SIGN_EXTEND;
5672 
5673   // Find legal integer scalar type for constant promotion and
5674   // ensure that its scalar size is at least as large as source.
5675   EVT LegalSVT = VT.getScalarType();
5676   if (NewNodesMustHaveLegalTypes && LegalSVT.isInteger()) {
5677     LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT);
5678     if (LegalSVT.bitsLT(VT.getScalarType()))
5679       return SDValue();
5680   }
5681 
5682   // For scalable vector types we know we're dealing with SPLAT_VECTORs. We
5683   // only have one operand to check. For fixed-length vector types we may have
5684   // a combination of BUILD_VECTOR and SPLAT_VECTOR.
5685   unsigned NumVectorElts = NumElts.isScalable() ? 1 : NumElts.getFixedValue();
5686 
5687   // Constant fold each scalar lane separately.
5688   SmallVector<SDValue, 4> ScalarResults;
5689   for (unsigned I = 0; I != NumVectorElts; I++) {
5690     SmallVector<SDValue, 4> ScalarOps;
5691     for (SDValue Op : Ops) {
5692       EVT InSVT = Op.getValueType().getScalarType();
5693       if (Op.getOpcode() != ISD::BUILD_VECTOR &&
5694           Op.getOpcode() != ISD::SPLAT_VECTOR) {
5695         if (Op.isUndef())
5696           ScalarOps.push_back(getUNDEF(InSVT));
5697         else
5698           ScalarOps.push_back(Op);
5699         continue;
5700       }
5701 
5702       SDValue ScalarOp =
5703           Op.getOperand(Op.getOpcode() == ISD::SPLAT_VECTOR ? 0 : I);
5704       EVT ScalarVT = ScalarOp.getValueType();
5705 
5706       // Build vector (integer) scalar operands may need implicit
5707       // truncation - do this before constant folding.
5708       if (ScalarVT.isInteger() && ScalarVT.bitsGT(InSVT)) {
5709         // Don't create illegally-typed nodes unless they're constants or undef
5710         // - if we fail to constant fold we can't guarantee the (dead) nodes
5711         // we're creating will be cleaned up before being visited for
5712         // legalization.
5713         if (NewNodesMustHaveLegalTypes && !ScalarOp.isUndef() &&
5714             !isa<ConstantSDNode>(ScalarOp) &&
5715             TLI->getTypeAction(*getContext(), InSVT) !=
5716                 TargetLowering::TypeLegal)
5717           return SDValue();
5718         ScalarOp = getNode(ISD::TRUNCATE, DL, InSVT, ScalarOp);
5719       }
5720 
5721       ScalarOps.push_back(ScalarOp);
5722     }
5723 
5724     // Constant fold the scalar operands.
5725     SDValue ScalarResult = getNode(Opcode, DL, SVT, ScalarOps);
5726 
5727     // Legalize the (integer) scalar constant if necessary.
5728     if (LegalSVT != SVT)
5729       ScalarResult = getNode(ExtendCode, DL, LegalSVT, ScalarResult);
5730 
5731     // Scalar folding only succeeded if the result is a constant or UNDEF.
5732     if (!ScalarResult.isUndef() && ScalarResult.getOpcode() != ISD::Constant &&
5733         ScalarResult.getOpcode() != ISD::ConstantFP)
5734       return SDValue();
5735     ScalarResults.push_back(ScalarResult);
5736   }
5737 
5738   SDValue V = NumElts.isScalable() ? getSplatVector(VT, DL, ScalarResults[0])
5739                                    : getBuildVector(VT, DL, ScalarResults);
5740   NewSDValueDbgMsg(V, "New node fold constant vector: ", this);
5741   return V;
5742 }
5743 
5744 SDValue SelectionDAG::foldConstantFPMath(unsigned Opcode, const SDLoc &DL,
5745                                          EVT VT, SDValue N1, SDValue N2) {
5746   // TODO: We don't do any constant folding for strict FP opcodes here, but we
5747   //       should. That will require dealing with a potentially non-default
5748   //       rounding mode, checking the "opStatus" return value from the APFloat
5749   //       math calculations, and possibly other variations.
5750   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1, /*AllowUndefs*/ false);
5751   ConstantFPSDNode *N2CFP = isConstOrConstSplatFP(N2, /*AllowUndefs*/ false);
5752   if (N1CFP && N2CFP) {
5753     APFloat C1 = N1CFP->getValueAPF(); // make copy
5754     const APFloat &C2 = N2CFP->getValueAPF();
5755     switch (Opcode) {
5756     case ISD::FADD:
5757       C1.add(C2, APFloat::rmNearestTiesToEven);
5758       return getConstantFP(C1, DL, VT);
5759     case ISD::FSUB:
5760       C1.subtract(C2, APFloat::rmNearestTiesToEven);
5761       return getConstantFP(C1, DL, VT);
5762     case ISD::FMUL:
5763       C1.multiply(C2, APFloat::rmNearestTiesToEven);
5764       return getConstantFP(C1, DL, VT);
5765     case ISD::FDIV:
5766       C1.divide(C2, APFloat::rmNearestTiesToEven);
5767       return getConstantFP(C1, DL, VT);
5768     case ISD::FREM:
5769       C1.mod(C2);
5770       return getConstantFP(C1, DL, VT);
5771     case ISD::FCOPYSIGN:
5772       C1.copySign(C2);
5773       return getConstantFP(C1, DL, VT);
5774     case ISD::FMINNUM:
5775       return getConstantFP(minnum(C1, C2), DL, VT);
5776     case ISD::FMAXNUM:
5777       return getConstantFP(maxnum(C1, C2), DL, VT);
5778     case ISD::FMINIMUM:
5779       return getConstantFP(minimum(C1, C2), DL, VT);
5780     case ISD::FMAXIMUM:
5781       return getConstantFP(maximum(C1, C2), DL, VT);
5782     default: break;
5783     }
5784   }
5785   if (N1CFP && Opcode == ISD::FP_ROUND) {
5786     APFloat C1 = N1CFP->getValueAPF();    // make copy
5787     bool Unused;
5788     // This can return overflow, underflow, or inexact; we don't care.
5789     // FIXME need to be more flexible about rounding mode.
5790     (void) C1.convert(EVTToAPFloatSemantics(VT), APFloat::rmNearestTiesToEven,
5791                       &Unused);
5792     return getConstantFP(C1, DL, VT);
5793   }
5794 
5795   switch (Opcode) {
5796   case ISD::FSUB:
5797     // -0.0 - undef --> undef (consistent with "fneg undef")
5798     if (ConstantFPSDNode *N1C = isConstOrConstSplatFP(N1, /*AllowUndefs*/ true))
5799       if (N1C && N1C->getValueAPF().isNegZero() && N2.isUndef())
5800         return getUNDEF(VT);
5801     LLVM_FALLTHROUGH;
5802 
5803   case ISD::FADD:
5804   case ISD::FMUL:
5805   case ISD::FDIV:
5806   case ISD::FREM:
5807     // If both operands are undef, the result is undef. If 1 operand is undef,
5808     // the result is NaN. This should match the behavior of the IR optimizer.
5809     if (N1.isUndef() && N2.isUndef())
5810       return getUNDEF(VT);
5811     if (N1.isUndef() || N2.isUndef())
5812       return getConstantFP(APFloat::getNaN(EVTToAPFloatSemantics(VT)), DL, VT);
5813   }
5814   return SDValue();
5815 }
5816 
5817 SDValue SelectionDAG::getAssertAlign(const SDLoc &DL, SDValue Val, Align A) {
5818   assert(Val.getValueType().isInteger() && "Invalid AssertAlign!");
5819 
5820   // There's no need to assert on a byte-aligned pointer. All pointers are at
5821   // least byte aligned.
5822   if (A == Align(1))
5823     return Val;
5824 
5825   FoldingSetNodeID ID;
5826   AddNodeIDNode(ID, ISD::AssertAlign, getVTList(Val.getValueType()), {Val});
5827   ID.AddInteger(A.value());
5828 
5829   void *IP = nullptr;
5830   if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
5831     return SDValue(E, 0);
5832 
5833   auto *N = newSDNode<AssertAlignSDNode>(DL.getIROrder(), DL.getDebugLoc(),
5834                                          Val.getValueType(), A);
5835   createOperands(N, {Val});
5836 
5837   CSEMap.InsertNode(N, IP);
5838   InsertNode(N);
5839 
5840   SDValue V(N, 0);
5841   NewSDValueDbgMsg(V, "Creating new node: ", this);
5842   return V;
5843 }
5844 
5845 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
5846                               SDValue N1, SDValue N2) {
5847   SDNodeFlags Flags;
5848   if (Inserter)
5849     Flags = Inserter->getFlags();
5850   return getNode(Opcode, DL, VT, N1, N2, Flags);
5851 }
5852 
5853 void SelectionDAG::canonicalizeCommutativeBinop(unsigned Opcode, SDValue &N1,
5854                                                 SDValue &N2) const {
5855   if (!TLI->isCommutativeBinOp(Opcode))
5856     return;
5857 
5858   // Canonicalize:
5859   //   binop(const, nonconst) -> binop(nonconst, const)
5860   bool IsN1C = isConstantIntBuildVectorOrConstantInt(N1);
5861   bool IsN2C = isConstantIntBuildVectorOrConstantInt(N2);
5862   bool IsN1CFP = isConstantFPBuildVectorOrConstantFP(N1);
5863   bool IsN2CFP = isConstantFPBuildVectorOrConstantFP(N2);
5864   if ((IsN1C && !IsN2C) || (IsN1CFP && !IsN2CFP))
5865     std::swap(N1, N2);
5866 
5867   // Canonicalize:
5868   //  binop(splat(x), step_vector) -> binop(step_vector, splat(x))
5869   else if (N1.getOpcode() == ISD::SPLAT_VECTOR &&
5870            N2.getOpcode() == ISD::STEP_VECTOR)
5871     std::swap(N1, N2);
5872 }
5873 
5874 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
5875                               SDValue N1, SDValue N2, const SDNodeFlags Flags) {
5876   assert(N1.getOpcode() != ISD::DELETED_NODE &&
5877          N2.getOpcode() != ISD::DELETED_NODE &&
5878          "Operand is DELETED_NODE!");
5879 
5880   canonicalizeCommutativeBinop(Opcode, N1, N2);
5881 
5882   auto *N1C = dyn_cast<ConstantSDNode>(N1);
5883   auto *N2C = dyn_cast<ConstantSDNode>(N2);
5884 
5885   // Don't allow undefs in vector splats - we might be returning N2 when folding
5886   // to zero etc.
5887   ConstantSDNode *N2CV =
5888       isConstOrConstSplat(N2, /*AllowUndefs*/ false, /*AllowTruncation*/ true);
5889 
5890   switch (Opcode) {
5891   default: break;
5892   case ISD::TokenFactor:
5893     assert(VT == MVT::Other && N1.getValueType() == MVT::Other &&
5894            N2.getValueType() == MVT::Other && "Invalid token factor!");
5895     // Fold trivial token factors.
5896     if (N1.getOpcode() == ISD::EntryToken) return N2;
5897     if (N2.getOpcode() == ISD::EntryToken) return N1;
5898     if (N1 == N2) return N1;
5899     break;
5900   case ISD::BUILD_VECTOR: {
5901     // Attempt to simplify BUILD_VECTOR.
5902     SDValue Ops[] = {N1, N2};
5903     if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
5904       return V;
5905     break;
5906   }
5907   case ISD::CONCAT_VECTORS: {
5908     SDValue Ops[] = {N1, N2};
5909     if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this))
5910       return V;
5911     break;
5912   }
5913   case ISD::AND:
5914     assert(VT.isInteger() && "This operator does not apply to FP types!");
5915     assert(N1.getValueType() == N2.getValueType() &&
5916            N1.getValueType() == VT && "Binary operator types must match!");
5917     // (X & 0) -> 0.  This commonly occurs when legalizing i64 values, so it's
5918     // worth handling here.
5919     if (N2CV && N2CV->isZero())
5920       return N2;
5921     if (N2CV && N2CV->isAllOnes()) // X & -1 -> X
5922       return N1;
5923     break;
5924   case ISD::OR:
5925   case ISD::XOR:
5926   case ISD::ADD:
5927   case ISD::SUB:
5928     assert(VT.isInteger() && "This operator does not apply to FP types!");
5929     assert(N1.getValueType() == N2.getValueType() &&
5930            N1.getValueType() == VT && "Binary operator types must match!");
5931     // (X ^|+- 0) -> X.  This commonly occurs when legalizing i64 values, so
5932     // it's worth handling here.
5933     if (N2CV && N2CV->isZero())
5934       return N1;
5935     if ((Opcode == ISD::ADD || Opcode == ISD::SUB) && VT.isVector() &&
5936         VT.getVectorElementType() == MVT::i1)
5937       return getNode(ISD::XOR, DL, VT, N1, N2);
5938     break;
5939   case ISD::MUL:
5940     assert(VT.isInteger() && "This operator does not apply to FP types!");
5941     assert(N1.getValueType() == N2.getValueType() &&
5942            N1.getValueType() == VT && "Binary operator types must match!");
5943     if (VT.isVector() && VT.getVectorElementType() == MVT::i1)
5944       return getNode(ISD::AND, DL, VT, N1, N2);
5945     if (N2C && (N1.getOpcode() == ISD::VSCALE) && Flags.hasNoSignedWrap()) {
5946       const APInt &MulImm = N1->getConstantOperandAPInt(0);
5947       const APInt &N2CImm = N2C->getAPIntValue();
5948       return getVScale(DL, VT, MulImm * N2CImm);
5949     }
5950     break;
5951   case ISD::UDIV:
5952   case ISD::UREM:
5953   case ISD::MULHU:
5954   case ISD::MULHS:
5955   case ISD::SDIV:
5956   case ISD::SREM:
5957   case ISD::SADDSAT:
5958   case ISD::SSUBSAT:
5959   case ISD::UADDSAT:
5960   case ISD::USUBSAT:
5961     assert(VT.isInteger() && "This operator does not apply to FP types!");
5962     assert(N1.getValueType() == N2.getValueType() &&
5963            N1.getValueType() == VT && "Binary operator types must match!");
5964     if (VT.isVector() && VT.getVectorElementType() == MVT::i1) {
5965       // fold (add_sat x, y) -> (or x, y) for bool types.
5966       if (Opcode == ISD::SADDSAT || Opcode == ISD::UADDSAT)
5967         return getNode(ISD::OR, DL, VT, N1, N2);
5968       // fold (sub_sat x, y) -> (and x, ~y) for bool types.
5969       if (Opcode == ISD::SSUBSAT || Opcode == ISD::USUBSAT)
5970         return getNode(ISD::AND, DL, VT, N1, getNOT(DL, N2, VT));
5971     }
5972     break;
5973   case ISD::SMIN:
5974   case ISD::UMAX:
5975     assert(VT.isInteger() && "This operator does not apply to FP types!");
5976     assert(N1.getValueType() == N2.getValueType() &&
5977            N1.getValueType() == VT && "Binary operator types must match!");
5978     if (VT.isVector() && VT.getVectorElementType() == MVT::i1)
5979       return getNode(ISD::OR, DL, VT, N1, N2);
5980     break;
5981   case ISD::SMAX:
5982   case ISD::UMIN:
5983     assert(VT.isInteger() && "This operator does not apply to FP types!");
5984     assert(N1.getValueType() == N2.getValueType() &&
5985            N1.getValueType() == VT && "Binary operator types must match!");
5986     if (VT.isVector() && VT.getVectorElementType() == MVT::i1)
5987       return getNode(ISD::AND, DL, VT, N1, N2);
5988     break;
5989   case ISD::FADD:
5990   case ISD::FSUB:
5991   case ISD::FMUL:
5992   case ISD::FDIV:
5993   case ISD::FREM:
5994     assert(VT.isFloatingPoint() && "This operator only applies to FP types!");
5995     assert(N1.getValueType() == N2.getValueType() &&
5996            N1.getValueType() == VT && "Binary operator types must match!");
5997     if (SDValue V = simplifyFPBinop(Opcode, N1, N2, Flags))
5998       return V;
5999     break;
6000   case ISD::FCOPYSIGN:   // N1 and result must match.  N1/N2 need not match.
6001     assert(N1.getValueType() == VT &&
6002            N1.getValueType().isFloatingPoint() &&
6003            N2.getValueType().isFloatingPoint() &&
6004            "Invalid FCOPYSIGN!");
6005     break;
6006   case ISD::SHL:
6007     if (N2C && (N1.getOpcode() == ISD::VSCALE) && Flags.hasNoSignedWrap()) {
6008       const APInt &MulImm = N1->getConstantOperandAPInt(0);
6009       const APInt &ShiftImm = N2C->getAPIntValue();
6010       return getVScale(DL, VT, MulImm << ShiftImm);
6011     }
6012     LLVM_FALLTHROUGH;
6013   case ISD::SRA:
6014   case ISD::SRL:
6015     if (SDValue V = simplifyShift(N1, N2))
6016       return V;
6017     LLVM_FALLTHROUGH;
6018   case ISD::ROTL:
6019   case ISD::ROTR:
6020     assert(VT == N1.getValueType() &&
6021            "Shift operators return type must be the same as their first arg");
6022     assert(VT.isInteger() && N2.getValueType().isInteger() &&
6023            "Shifts only work on integers");
6024     assert((!VT.isVector() || VT == N2.getValueType()) &&
6025            "Vector shift amounts must be in the same as their first arg");
6026     // Verify that the shift amount VT is big enough to hold valid shift
6027     // amounts.  This catches things like trying to shift an i1024 value by an
6028     // i8, which is easy to fall into in generic code that uses
6029     // TLI.getShiftAmount().
6030     assert(N2.getValueType().getScalarSizeInBits() >=
6031                Log2_32_Ceil(VT.getScalarSizeInBits()) &&
6032            "Invalid use of small shift amount with oversized value!");
6033 
6034     // Always fold shifts of i1 values so the code generator doesn't need to
6035     // handle them.  Since we know the size of the shift has to be less than the
6036     // size of the value, the shift/rotate count is guaranteed to be zero.
6037     if (VT == MVT::i1)
6038       return N1;
6039     if (N2CV && N2CV->isZero())
6040       return N1;
6041     break;
6042   case ISD::FP_ROUND:
6043     assert(VT.isFloatingPoint() &&
6044            N1.getValueType().isFloatingPoint() &&
6045            VT.bitsLE(N1.getValueType()) &&
6046            N2C && (N2C->getZExtValue() == 0 || N2C->getZExtValue() == 1) &&
6047            "Invalid FP_ROUND!");
6048     if (N1.getValueType() == VT) return N1;  // noop conversion.
6049     break;
6050   case ISD::AssertSext:
6051   case ISD::AssertZext: {
6052     EVT EVT = cast<VTSDNode>(N2)->getVT();
6053     assert(VT == N1.getValueType() && "Not an inreg extend!");
6054     assert(VT.isInteger() && EVT.isInteger() &&
6055            "Cannot *_EXTEND_INREG FP types");
6056     assert(!EVT.isVector() &&
6057            "AssertSExt/AssertZExt type should be the vector element type "
6058            "rather than the vector type!");
6059     assert(EVT.bitsLE(VT.getScalarType()) && "Not extending!");
6060     if (VT.getScalarType() == EVT) return N1; // noop assertion.
6061     break;
6062   }
6063   case ISD::SIGN_EXTEND_INREG: {
6064     EVT EVT = cast<VTSDNode>(N2)->getVT();
6065     assert(VT == N1.getValueType() && "Not an inreg extend!");
6066     assert(VT.isInteger() && EVT.isInteger() &&
6067            "Cannot *_EXTEND_INREG FP types");
6068     assert(EVT.isVector() == VT.isVector() &&
6069            "SIGN_EXTEND_INREG type should be vector iff the operand "
6070            "type is vector!");
6071     assert((!EVT.isVector() ||
6072             EVT.getVectorElementCount() == VT.getVectorElementCount()) &&
6073            "Vector element counts must match in SIGN_EXTEND_INREG");
6074     assert(EVT.bitsLE(VT) && "Not extending!");
6075     if (EVT == VT) return N1;  // Not actually extending
6076 
6077     auto SignExtendInReg = [&](APInt Val, llvm::EVT ConstantVT) {
6078       unsigned FromBits = EVT.getScalarSizeInBits();
6079       Val <<= Val.getBitWidth() - FromBits;
6080       Val.ashrInPlace(Val.getBitWidth() - FromBits);
6081       return getConstant(Val, DL, ConstantVT);
6082     };
6083 
6084     if (N1C) {
6085       const APInt &Val = N1C->getAPIntValue();
6086       return SignExtendInReg(Val, VT);
6087     }
6088 
6089     if (ISD::isBuildVectorOfConstantSDNodes(N1.getNode())) {
6090       SmallVector<SDValue, 8> Ops;
6091       llvm::EVT OpVT = N1.getOperand(0).getValueType();
6092       for (int i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
6093         SDValue Op = N1.getOperand(i);
6094         if (Op.isUndef()) {
6095           Ops.push_back(getUNDEF(OpVT));
6096           continue;
6097         }
6098         ConstantSDNode *C = cast<ConstantSDNode>(Op);
6099         APInt Val = C->getAPIntValue();
6100         Ops.push_back(SignExtendInReg(Val, OpVT));
6101       }
6102       return getBuildVector(VT, DL, Ops);
6103     }
6104     break;
6105   }
6106   case ISD::FP_TO_SINT_SAT:
6107   case ISD::FP_TO_UINT_SAT: {
6108     assert(VT.isInteger() && cast<VTSDNode>(N2)->getVT().isInteger() &&
6109            N1.getValueType().isFloatingPoint() && "Invalid FP_TO_*INT_SAT");
6110     assert(N1.getValueType().isVector() == VT.isVector() &&
6111            "FP_TO_*INT_SAT type should be vector iff the operand type is "
6112            "vector!");
6113     assert((!VT.isVector() || VT.getVectorNumElements() ==
6114                                   N1.getValueType().getVectorNumElements()) &&
6115            "Vector element counts must match in FP_TO_*INT_SAT");
6116     assert(!cast<VTSDNode>(N2)->getVT().isVector() &&
6117            "Type to saturate to must be a scalar.");
6118     assert(cast<VTSDNode>(N2)->getVT().bitsLE(VT.getScalarType()) &&
6119            "Not extending!");
6120     break;
6121   }
6122   case ISD::EXTRACT_VECTOR_ELT:
6123     assert(VT.getSizeInBits() >= N1.getValueType().getScalarSizeInBits() &&
6124            "The result of EXTRACT_VECTOR_ELT must be at least as wide as the \
6125              element type of the vector.");
6126 
6127     // Extract from an undefined value or using an undefined index is undefined.
6128     if (N1.isUndef() || N2.isUndef())
6129       return getUNDEF(VT);
6130 
6131     // EXTRACT_VECTOR_ELT of out-of-bounds element is an UNDEF for fixed length
6132     // vectors. For scalable vectors we will provide appropriate support for
6133     // dealing with arbitrary indices.
6134     if (N2C && N1.getValueType().isFixedLengthVector() &&
6135         N2C->getAPIntValue().uge(N1.getValueType().getVectorNumElements()))
6136       return getUNDEF(VT);
6137 
6138     // EXTRACT_VECTOR_ELT of CONCAT_VECTORS is often formed while lowering is
6139     // expanding copies of large vectors from registers. This only works for
6140     // fixed length vectors, since we need to know the exact number of
6141     // elements.
6142     if (N2C && N1.getOperand(0).getValueType().isFixedLengthVector() &&
6143         N1.getOpcode() == ISD::CONCAT_VECTORS && N1.getNumOperands() > 0) {
6144       unsigned Factor =
6145         N1.getOperand(0).getValueType().getVectorNumElements();
6146       return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
6147                      N1.getOperand(N2C->getZExtValue() / Factor),
6148                      getVectorIdxConstant(N2C->getZExtValue() % Factor, DL));
6149     }
6150 
6151     // EXTRACT_VECTOR_ELT of BUILD_VECTOR or SPLAT_VECTOR is often formed while
6152     // lowering is expanding large vector constants.
6153     if (N2C && (N1.getOpcode() == ISD::BUILD_VECTOR ||
6154                 N1.getOpcode() == ISD::SPLAT_VECTOR)) {
6155       assert((N1.getOpcode() != ISD::BUILD_VECTOR ||
6156               N1.getValueType().isFixedLengthVector()) &&
6157              "BUILD_VECTOR used for scalable vectors");
6158       unsigned Index =
6159           N1.getOpcode() == ISD::BUILD_VECTOR ? N2C->getZExtValue() : 0;
6160       SDValue Elt = N1.getOperand(Index);
6161 
6162       if (VT != Elt.getValueType())
6163         // If the vector element type is not legal, the BUILD_VECTOR operands
6164         // are promoted and implicitly truncated, and the result implicitly
6165         // extended. Make that explicit here.
6166         Elt = getAnyExtOrTrunc(Elt, DL, VT);
6167 
6168       return Elt;
6169     }
6170 
6171     // EXTRACT_VECTOR_ELT of INSERT_VECTOR_ELT is often formed when vector
6172     // operations are lowered to scalars.
6173     if (N1.getOpcode() == ISD::INSERT_VECTOR_ELT) {
6174       // If the indices are the same, return the inserted element else
6175       // if the indices are known different, extract the element from
6176       // the original vector.
6177       SDValue N1Op2 = N1.getOperand(2);
6178       ConstantSDNode *N1Op2C = dyn_cast<ConstantSDNode>(N1Op2);
6179 
6180       if (N1Op2C && N2C) {
6181         if (N1Op2C->getZExtValue() == N2C->getZExtValue()) {
6182           if (VT == N1.getOperand(1).getValueType())
6183             return N1.getOperand(1);
6184           if (VT.isFloatingPoint()) {
6185             assert(VT.getSizeInBits() > N1.getOperand(1).getValueType().getSizeInBits());
6186             return getFPExtendOrRound(N1.getOperand(1), DL, VT);
6187           }
6188           return getSExtOrTrunc(N1.getOperand(1), DL, VT);
6189         }
6190         return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0), N2);
6191       }
6192     }
6193 
6194     // EXTRACT_VECTOR_ELT of v1iX EXTRACT_SUBVECTOR could be formed
6195     // when vector types are scalarized and v1iX is legal.
6196     // vextract (v1iX extract_subvector(vNiX, Idx)) -> vextract(vNiX,Idx).
6197     // Here we are completely ignoring the extract element index (N2),
6198     // which is fine for fixed width vectors, since any index other than 0
6199     // is undefined anyway. However, this cannot be ignored for scalable
6200     // vectors - in theory we could support this, but we don't want to do this
6201     // without a profitability check.
6202     if (N1.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
6203         N1.getValueType().isFixedLengthVector() &&
6204         N1.getValueType().getVectorNumElements() == 1) {
6205       return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0),
6206                      N1.getOperand(1));
6207     }
6208     break;
6209   case ISD::EXTRACT_ELEMENT:
6210     assert(N2C && (unsigned)N2C->getZExtValue() < 2 && "Bad EXTRACT_ELEMENT!");
6211     assert(!N1.getValueType().isVector() && !VT.isVector() &&
6212            (N1.getValueType().isInteger() == VT.isInteger()) &&
6213            N1.getValueType() != VT &&
6214            "Wrong types for EXTRACT_ELEMENT!");
6215 
6216     // EXTRACT_ELEMENT of BUILD_PAIR is often formed while legalize is expanding
6217     // 64-bit integers into 32-bit parts.  Instead of building the extract of
6218     // the BUILD_PAIR, only to have legalize rip it apart, just do it now.
6219     if (N1.getOpcode() == ISD::BUILD_PAIR)
6220       return N1.getOperand(N2C->getZExtValue());
6221 
6222     // EXTRACT_ELEMENT of a constant int is also very common.
6223     if (N1C) {
6224       unsigned ElementSize = VT.getSizeInBits();
6225       unsigned Shift = ElementSize * N2C->getZExtValue();
6226       const APInt &Val = N1C->getAPIntValue();
6227       return getConstant(Val.extractBits(ElementSize, Shift), DL, VT);
6228     }
6229     break;
6230   case ISD::EXTRACT_SUBVECTOR: {
6231     EVT N1VT = N1.getValueType();
6232     assert(VT.isVector() && N1VT.isVector() &&
6233            "Extract subvector VTs must be vectors!");
6234     assert(VT.getVectorElementType() == N1VT.getVectorElementType() &&
6235            "Extract subvector VTs must have the same element type!");
6236     assert((VT.isFixedLengthVector() || N1VT.isScalableVector()) &&
6237            "Cannot extract a scalable vector from a fixed length vector!");
6238     assert((VT.isScalableVector() != N1VT.isScalableVector() ||
6239             VT.getVectorMinNumElements() <= N1VT.getVectorMinNumElements()) &&
6240            "Extract subvector must be from larger vector to smaller vector!");
6241     assert(N2C && "Extract subvector index must be a constant");
6242     assert((VT.isScalableVector() != N1VT.isScalableVector() ||
6243             (VT.getVectorMinNumElements() + N2C->getZExtValue()) <=
6244                 N1VT.getVectorMinNumElements()) &&
6245            "Extract subvector overflow!");
6246     assert(N2C->getAPIntValue().getBitWidth() ==
6247                TLI->getVectorIdxTy(getDataLayout()).getFixedSizeInBits() &&
6248            "Constant index for EXTRACT_SUBVECTOR has an invalid size");
6249 
6250     // Trivial extraction.
6251     if (VT == N1VT)
6252       return N1;
6253 
6254     // EXTRACT_SUBVECTOR of an UNDEF is an UNDEF.
6255     if (N1.isUndef())
6256       return getUNDEF(VT);
6257 
6258     // EXTRACT_SUBVECTOR of CONCAT_VECTOR can be simplified if the pieces of
6259     // the concat have the same type as the extract.
6260     if (N1.getOpcode() == ISD::CONCAT_VECTORS && N1.getNumOperands() > 0 &&
6261         VT == N1.getOperand(0).getValueType()) {
6262       unsigned Factor = VT.getVectorMinNumElements();
6263       return N1.getOperand(N2C->getZExtValue() / Factor);
6264     }
6265 
6266     // EXTRACT_SUBVECTOR of INSERT_SUBVECTOR is often created
6267     // during shuffle legalization.
6268     if (N1.getOpcode() == ISD::INSERT_SUBVECTOR && N2 == N1.getOperand(2) &&
6269         VT == N1.getOperand(1).getValueType())
6270       return N1.getOperand(1);
6271     break;
6272   }
6273   }
6274 
6275   // Perform trivial constant folding.
6276   if (SDValue SV = FoldConstantArithmetic(Opcode, DL, VT, {N1, N2}))
6277     return SV;
6278 
6279   // Canonicalize an UNDEF to the RHS, even over a constant.
6280   if (N1.isUndef()) {
6281     if (TLI->isCommutativeBinOp(Opcode)) {
6282       std::swap(N1, N2);
6283     } else {
6284       switch (Opcode) {
6285       case ISD::SUB:
6286         return getUNDEF(VT);     // fold op(undef, arg2) -> undef
6287       case ISD::SIGN_EXTEND_INREG:
6288       case ISD::UDIV:
6289       case ISD::SDIV:
6290       case ISD::UREM:
6291       case ISD::SREM:
6292       case ISD::SSUBSAT:
6293       case ISD::USUBSAT:
6294         return getConstant(0, DL, VT);    // fold op(undef, arg2) -> 0
6295       }
6296     }
6297   }
6298 
6299   // Fold a bunch of operators when the RHS is undef.
6300   if (N2.isUndef()) {
6301     switch (Opcode) {
6302     case ISD::XOR:
6303       if (N1.isUndef())
6304         // Handle undef ^ undef -> 0 special case. This is a common
6305         // idiom (misuse).
6306         return getConstant(0, DL, VT);
6307       LLVM_FALLTHROUGH;
6308     case ISD::ADD:
6309     case ISD::SUB:
6310     case ISD::UDIV:
6311     case ISD::SDIV:
6312     case ISD::UREM:
6313     case ISD::SREM:
6314       return getUNDEF(VT);       // fold op(arg1, undef) -> undef
6315     case ISD::MUL:
6316     case ISD::AND:
6317     case ISD::SSUBSAT:
6318     case ISD::USUBSAT:
6319       return getConstant(0, DL, VT);  // fold op(arg1, undef) -> 0
6320     case ISD::OR:
6321     case ISD::SADDSAT:
6322     case ISD::UADDSAT:
6323       return getAllOnesConstant(DL, VT);
6324     }
6325   }
6326 
6327   // Memoize this node if possible.
6328   SDNode *N;
6329   SDVTList VTs = getVTList(VT);
6330   SDValue Ops[] = {N1, N2};
6331   if (VT != MVT::Glue) {
6332     FoldingSetNodeID ID;
6333     AddNodeIDNode(ID, Opcode, VTs, Ops);
6334     void *IP = nullptr;
6335     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
6336       E->intersectFlagsWith(Flags);
6337       return SDValue(E, 0);
6338     }
6339 
6340     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
6341     N->setFlags(Flags);
6342     createOperands(N, Ops);
6343     CSEMap.InsertNode(N, IP);
6344   } else {
6345     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
6346     createOperands(N, Ops);
6347   }
6348 
6349   InsertNode(N);
6350   SDValue V = SDValue(N, 0);
6351   NewSDValueDbgMsg(V, "Creating new node: ", this);
6352   return V;
6353 }
6354 
6355 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
6356                               SDValue N1, SDValue N2, SDValue N3) {
6357   SDNodeFlags Flags;
6358   if (Inserter)
6359     Flags = Inserter->getFlags();
6360   return getNode(Opcode, DL, VT, N1, N2, N3, Flags);
6361 }
6362 
6363 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
6364                               SDValue N1, SDValue N2, SDValue N3,
6365                               const SDNodeFlags Flags) {
6366   assert(N1.getOpcode() != ISD::DELETED_NODE &&
6367          N2.getOpcode() != ISD::DELETED_NODE &&
6368          N3.getOpcode() != ISD::DELETED_NODE &&
6369          "Operand is DELETED_NODE!");
6370   // Perform various simplifications.
6371   switch (Opcode) {
6372   case ISD::FMA: {
6373     assert(VT.isFloatingPoint() && "This operator only applies to FP types!");
6374     assert(N1.getValueType() == VT && N2.getValueType() == VT &&
6375            N3.getValueType() == VT && "FMA types must match!");
6376     ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6377     ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2);
6378     ConstantFPSDNode *N3CFP = dyn_cast<ConstantFPSDNode>(N3);
6379     if (N1CFP && N2CFP && N3CFP) {
6380       APFloat  V1 = N1CFP->getValueAPF();
6381       const APFloat &V2 = N2CFP->getValueAPF();
6382       const APFloat &V3 = N3CFP->getValueAPF();
6383       V1.fusedMultiplyAdd(V2, V3, APFloat::rmNearestTiesToEven);
6384       return getConstantFP(V1, DL, VT);
6385     }
6386     break;
6387   }
6388   case ISD::BUILD_VECTOR: {
6389     // Attempt to simplify BUILD_VECTOR.
6390     SDValue Ops[] = {N1, N2, N3};
6391     if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
6392       return V;
6393     break;
6394   }
6395   case ISD::CONCAT_VECTORS: {
6396     SDValue Ops[] = {N1, N2, N3};
6397     if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this))
6398       return V;
6399     break;
6400   }
6401   case ISD::SETCC: {
6402     assert(VT.isInteger() && "SETCC result type must be an integer!");
6403     assert(N1.getValueType() == N2.getValueType() &&
6404            "SETCC operands must have the same type!");
6405     assert(VT.isVector() == N1.getValueType().isVector() &&
6406            "SETCC type should be vector iff the operand type is vector!");
6407     assert((!VT.isVector() || VT.getVectorElementCount() ==
6408                                   N1.getValueType().getVectorElementCount()) &&
6409            "SETCC vector element counts must match!");
6410     // Use FoldSetCC to simplify SETCC's.
6411     if (SDValue V = FoldSetCC(VT, N1, N2, cast<CondCodeSDNode>(N3)->get(), DL))
6412       return V;
6413     // Vector constant folding.
6414     SDValue Ops[] = {N1, N2, N3};
6415     if (SDValue V = FoldConstantArithmetic(Opcode, DL, VT, Ops)) {
6416       NewSDValueDbgMsg(V, "New node vector constant folding: ", this);
6417       return V;
6418     }
6419     break;
6420   }
6421   case ISD::SELECT:
6422   case ISD::VSELECT:
6423     if (SDValue V = simplifySelect(N1, N2, N3))
6424       return V;
6425     break;
6426   case ISD::VECTOR_SHUFFLE:
6427     llvm_unreachable("should use getVectorShuffle constructor!");
6428   case ISD::VECTOR_SPLICE: {
6429     if (cast<ConstantSDNode>(N3)->isNullValue())
6430       return N1;
6431     break;
6432   }
6433   case ISD::INSERT_VECTOR_ELT: {
6434     ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3);
6435     // INSERT_VECTOR_ELT into out-of-bounds element is an UNDEF, except
6436     // for scalable vectors where we will generate appropriate code to
6437     // deal with out-of-bounds cases correctly.
6438     if (N3C && N1.getValueType().isFixedLengthVector() &&
6439         N3C->getZExtValue() >= N1.getValueType().getVectorNumElements())
6440       return getUNDEF(VT);
6441 
6442     // Undefined index can be assumed out-of-bounds, so that's UNDEF too.
6443     if (N3.isUndef())
6444       return getUNDEF(VT);
6445 
6446     // If the inserted element is an UNDEF, just use the input vector.
6447     if (N2.isUndef())
6448       return N1;
6449 
6450     break;
6451   }
6452   case ISD::INSERT_SUBVECTOR: {
6453     // Inserting undef into undef is still undef.
6454     if (N1.isUndef() && N2.isUndef())
6455       return getUNDEF(VT);
6456 
6457     EVT N2VT = N2.getValueType();
6458     assert(VT == N1.getValueType() &&
6459            "Dest and insert subvector source types must match!");
6460     assert(VT.isVector() && N2VT.isVector() &&
6461            "Insert subvector VTs must be vectors!");
6462     assert((VT.isScalableVector() || N2VT.isFixedLengthVector()) &&
6463            "Cannot insert a scalable vector into a fixed length vector!");
6464     assert((VT.isScalableVector() != N2VT.isScalableVector() ||
6465             VT.getVectorMinNumElements() >= N2VT.getVectorMinNumElements()) &&
6466            "Insert subvector must be from smaller vector to larger vector!");
6467     assert(isa<ConstantSDNode>(N3) &&
6468            "Insert subvector index must be constant");
6469     assert((VT.isScalableVector() != N2VT.isScalableVector() ||
6470             (N2VT.getVectorMinNumElements() +
6471              cast<ConstantSDNode>(N3)->getZExtValue()) <=
6472                 VT.getVectorMinNumElements()) &&
6473            "Insert subvector overflow!");
6474     assert(cast<ConstantSDNode>(N3)->getAPIntValue().getBitWidth() ==
6475                TLI->getVectorIdxTy(getDataLayout()).getFixedSizeInBits() &&
6476            "Constant index for INSERT_SUBVECTOR has an invalid size");
6477 
6478     // Trivial insertion.
6479     if (VT == N2VT)
6480       return N2;
6481 
6482     // If this is an insert of an extracted vector into an undef vector, we
6483     // can just use the input to the extract.
6484     if (N1.isUndef() && N2.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
6485         N2.getOperand(1) == N3 && N2.getOperand(0).getValueType() == VT)
6486       return N2.getOperand(0);
6487     break;
6488   }
6489   case ISD::BITCAST:
6490     // Fold bit_convert nodes from a type to themselves.
6491     if (N1.getValueType() == VT)
6492       return N1;
6493     break;
6494   }
6495 
6496   // Memoize node if it doesn't produce a flag.
6497   SDNode *N;
6498   SDVTList VTs = getVTList(VT);
6499   SDValue Ops[] = {N1, N2, N3};
6500   if (VT != MVT::Glue) {
6501     FoldingSetNodeID ID;
6502     AddNodeIDNode(ID, Opcode, VTs, Ops);
6503     void *IP = nullptr;
6504     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
6505       E->intersectFlagsWith(Flags);
6506       return SDValue(E, 0);
6507     }
6508 
6509     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
6510     N->setFlags(Flags);
6511     createOperands(N, Ops);
6512     CSEMap.InsertNode(N, IP);
6513   } else {
6514     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
6515     createOperands(N, Ops);
6516   }
6517 
6518   InsertNode(N);
6519   SDValue V = SDValue(N, 0);
6520   NewSDValueDbgMsg(V, "Creating new node: ", this);
6521   return V;
6522 }
6523 
6524 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
6525                               SDValue N1, SDValue N2, SDValue N3, SDValue N4) {
6526   SDValue Ops[] = { N1, N2, N3, N4 };
6527   return getNode(Opcode, DL, VT, Ops);
6528 }
6529 
6530 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
6531                               SDValue N1, SDValue N2, SDValue N3, SDValue N4,
6532                               SDValue N5) {
6533   SDValue Ops[] = { N1, N2, N3, N4, N5 };
6534   return getNode(Opcode, DL, VT, Ops);
6535 }
6536 
6537 /// getStackArgumentTokenFactor - Compute a TokenFactor to force all
6538 /// the incoming stack arguments to be loaded from the stack.
6539 SDValue SelectionDAG::getStackArgumentTokenFactor(SDValue Chain) {
6540   SmallVector<SDValue, 8> ArgChains;
6541 
6542   // Include the original chain at the beginning of the list. When this is
6543   // used by target LowerCall hooks, this helps legalize find the
6544   // CALLSEQ_BEGIN node.
6545   ArgChains.push_back(Chain);
6546 
6547   // Add a chain value for each stack argument.
6548   for (SDNode *U : getEntryNode().getNode()->uses())
6549     if (LoadSDNode *L = dyn_cast<LoadSDNode>(U))
6550       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
6551         if (FI->getIndex() < 0)
6552           ArgChains.push_back(SDValue(L, 1));
6553 
6554   // Build a tokenfactor for all the chains.
6555   return getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains);
6556 }
6557 
6558 /// getMemsetValue - Vectorized representation of the memset value
6559 /// operand.
6560 static SDValue getMemsetValue(SDValue Value, EVT VT, SelectionDAG &DAG,
6561                               const SDLoc &dl) {
6562   assert(!Value.isUndef());
6563 
6564   unsigned NumBits = VT.getScalarSizeInBits();
6565   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
6566     assert(C->getAPIntValue().getBitWidth() == 8);
6567     APInt Val = APInt::getSplat(NumBits, C->getAPIntValue());
6568     if (VT.isInteger()) {
6569       bool IsOpaque = VT.getSizeInBits() > 64 ||
6570           !DAG.getTargetLoweringInfo().isLegalStoreImmediate(C->getSExtValue());
6571       return DAG.getConstant(Val, dl, VT, false, IsOpaque);
6572     }
6573     return DAG.getConstantFP(APFloat(DAG.EVTToAPFloatSemantics(VT), Val), dl,
6574                              VT);
6575   }
6576 
6577   assert(Value.getValueType() == MVT::i8 && "memset with non-byte fill value?");
6578   EVT IntVT = VT.getScalarType();
6579   if (!IntVT.isInteger())
6580     IntVT = EVT::getIntegerVT(*DAG.getContext(), IntVT.getSizeInBits());
6581 
6582   Value = DAG.getNode(ISD::ZERO_EXTEND, dl, IntVT, Value);
6583   if (NumBits > 8) {
6584     // Use a multiplication with 0x010101... to extend the input to the
6585     // required length.
6586     APInt Magic = APInt::getSplat(NumBits, APInt(8, 0x01));
6587     Value = DAG.getNode(ISD::MUL, dl, IntVT, Value,
6588                         DAG.getConstant(Magic, dl, IntVT));
6589   }
6590 
6591   if (VT != Value.getValueType() && !VT.isInteger())
6592     Value = DAG.getBitcast(VT.getScalarType(), Value);
6593   if (VT != Value.getValueType())
6594     Value = DAG.getSplatBuildVector(VT, dl, Value);
6595 
6596   return Value;
6597 }
6598 
6599 /// getMemsetStringVal - Similar to getMemsetValue. Except this is only
6600 /// used when a memcpy is turned into a memset when the source is a constant
6601 /// string ptr.
6602 static SDValue getMemsetStringVal(EVT VT, const SDLoc &dl, SelectionDAG &DAG,
6603                                   const TargetLowering &TLI,
6604                                   const ConstantDataArraySlice &Slice) {
6605   // Handle vector with all elements zero.
6606   if (Slice.Array == nullptr) {
6607     if (VT.isInteger())
6608       return DAG.getConstant(0, dl, VT);
6609     if (VT == MVT::f32 || VT == MVT::f64 || VT == MVT::f128)
6610       return DAG.getConstantFP(0.0, dl, VT);
6611     if (VT.isVector()) {
6612       unsigned NumElts = VT.getVectorNumElements();
6613       MVT EltVT = (VT.getVectorElementType() == MVT::f32) ? MVT::i32 : MVT::i64;
6614       return DAG.getNode(ISD::BITCAST, dl, VT,
6615                          DAG.getConstant(0, dl,
6616                                          EVT::getVectorVT(*DAG.getContext(),
6617                                                           EltVT, NumElts)));
6618     }
6619     llvm_unreachable("Expected type!");
6620   }
6621 
6622   assert(!VT.isVector() && "Can't handle vector type here!");
6623   unsigned NumVTBits = VT.getSizeInBits();
6624   unsigned NumVTBytes = NumVTBits / 8;
6625   unsigned NumBytes = std::min(NumVTBytes, unsigned(Slice.Length));
6626 
6627   APInt Val(NumVTBits, 0);
6628   if (DAG.getDataLayout().isLittleEndian()) {
6629     for (unsigned i = 0; i != NumBytes; ++i)
6630       Val |= (uint64_t)(unsigned char)Slice[i] << i*8;
6631   } else {
6632     for (unsigned i = 0; i != NumBytes; ++i)
6633       Val |= (uint64_t)(unsigned char)Slice[i] << (NumVTBytes-i-1)*8;
6634   }
6635 
6636   // If the "cost" of materializing the integer immediate is less than the cost
6637   // of a load, then it is cost effective to turn the load into the immediate.
6638   Type *Ty = VT.getTypeForEVT(*DAG.getContext());
6639   if (TLI.shouldConvertConstantLoadToIntImm(Val, Ty))
6640     return DAG.getConstant(Val, dl, VT);
6641   return SDValue();
6642 }
6643 
6644 SDValue SelectionDAG::getMemBasePlusOffset(SDValue Base, TypeSize Offset,
6645                                            const SDLoc &DL,
6646                                            const SDNodeFlags Flags) {
6647   EVT VT = Base.getValueType();
6648   SDValue Index;
6649 
6650   if (Offset.isScalable())
6651     Index = getVScale(DL, Base.getValueType(),
6652                       APInt(Base.getValueSizeInBits().getFixedSize(),
6653                             Offset.getKnownMinSize()));
6654   else
6655     Index = getConstant(Offset.getFixedSize(), DL, VT);
6656 
6657   return getMemBasePlusOffset(Base, Index, DL, Flags);
6658 }
6659 
6660 SDValue SelectionDAG::getMemBasePlusOffset(SDValue Ptr, SDValue Offset,
6661                                            const SDLoc &DL,
6662                                            const SDNodeFlags Flags) {
6663   assert(Offset.getValueType().isInteger());
6664   EVT BasePtrVT = Ptr.getValueType();
6665   return getNode(ISD::ADD, DL, BasePtrVT, Ptr, Offset, Flags);
6666 }
6667 
6668 /// Returns true if memcpy source is constant data.
6669 static bool isMemSrcFromConstant(SDValue Src, ConstantDataArraySlice &Slice) {
6670   uint64_t SrcDelta = 0;
6671   GlobalAddressSDNode *G = nullptr;
6672   if (Src.getOpcode() == ISD::GlobalAddress)
6673     G = cast<GlobalAddressSDNode>(Src);
6674   else if (Src.getOpcode() == ISD::ADD &&
6675            Src.getOperand(0).getOpcode() == ISD::GlobalAddress &&
6676            Src.getOperand(1).getOpcode() == ISD::Constant) {
6677     G = cast<GlobalAddressSDNode>(Src.getOperand(0));
6678     SrcDelta = cast<ConstantSDNode>(Src.getOperand(1))->getZExtValue();
6679   }
6680   if (!G)
6681     return false;
6682 
6683   return getConstantDataArrayInfo(G->getGlobal(), Slice, 8,
6684                                   SrcDelta + G->getOffset());
6685 }
6686 
6687 static bool shouldLowerMemFuncForSize(const MachineFunction &MF,
6688                                       SelectionDAG &DAG) {
6689   // On Darwin, -Os means optimize for size without hurting performance, so
6690   // only really optimize for size when -Oz (MinSize) is used.
6691   if (MF.getTarget().getTargetTriple().isOSDarwin())
6692     return MF.getFunction().hasMinSize();
6693   return DAG.shouldOptForSize();
6694 }
6695 
6696 static void chainLoadsAndStoresForMemcpy(SelectionDAG &DAG, const SDLoc &dl,
6697                           SmallVector<SDValue, 32> &OutChains, unsigned From,
6698                           unsigned To, SmallVector<SDValue, 16> &OutLoadChains,
6699                           SmallVector<SDValue, 16> &OutStoreChains) {
6700   assert(OutLoadChains.size() && "Missing loads in memcpy inlining");
6701   assert(OutStoreChains.size() && "Missing stores in memcpy inlining");
6702   SmallVector<SDValue, 16> GluedLoadChains;
6703   for (unsigned i = From; i < To; ++i) {
6704     OutChains.push_back(OutLoadChains[i]);
6705     GluedLoadChains.push_back(OutLoadChains[i]);
6706   }
6707 
6708   // Chain for all loads.
6709   SDValue LoadToken = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
6710                                   GluedLoadChains);
6711 
6712   for (unsigned i = From; i < To; ++i) {
6713     StoreSDNode *ST = dyn_cast<StoreSDNode>(OutStoreChains[i]);
6714     SDValue NewStore = DAG.getTruncStore(LoadToken, dl, ST->getValue(),
6715                                   ST->getBasePtr(), ST->getMemoryVT(),
6716                                   ST->getMemOperand());
6717     OutChains.push_back(NewStore);
6718   }
6719 }
6720 
6721 static SDValue getMemcpyLoadsAndStores(SelectionDAG &DAG, const SDLoc &dl,
6722                                        SDValue Chain, SDValue Dst, SDValue Src,
6723                                        uint64_t Size, Align Alignment,
6724                                        bool isVol, bool AlwaysInline,
6725                                        MachinePointerInfo DstPtrInfo,
6726                                        MachinePointerInfo SrcPtrInfo,
6727                                        const AAMDNodes &AAInfo) {
6728   // Turn a memcpy of undef to nop.
6729   // FIXME: We need to honor volatile even is Src is undef.
6730   if (Src.isUndef())
6731     return Chain;
6732 
6733   // Expand memcpy to a series of load and store ops if the size operand falls
6734   // below a certain threshold.
6735   // TODO: In the AlwaysInline case, if the size is big then generate a loop
6736   // rather than maybe a humongous number of loads and stores.
6737   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6738   const DataLayout &DL = DAG.getDataLayout();
6739   LLVMContext &C = *DAG.getContext();
6740   std::vector<EVT> MemOps;
6741   bool DstAlignCanChange = false;
6742   MachineFunction &MF = DAG.getMachineFunction();
6743   MachineFrameInfo &MFI = MF.getFrameInfo();
6744   bool OptSize = shouldLowerMemFuncForSize(MF, DAG);
6745   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
6746   if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
6747     DstAlignCanChange = true;
6748   MaybeAlign SrcAlign = DAG.InferPtrAlign(Src);
6749   if (!SrcAlign || Alignment > *SrcAlign)
6750     SrcAlign = Alignment;
6751   assert(SrcAlign && "SrcAlign must be set");
6752   ConstantDataArraySlice Slice;
6753   // If marked as volatile, perform a copy even when marked as constant.
6754   bool CopyFromConstant = !isVol && isMemSrcFromConstant(Src, Slice);
6755   bool isZeroConstant = CopyFromConstant && Slice.Array == nullptr;
6756   unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemcpy(OptSize);
6757   const MemOp Op = isZeroConstant
6758                        ? MemOp::Set(Size, DstAlignCanChange, Alignment,
6759                                     /*IsZeroMemset*/ true, isVol)
6760                        : MemOp::Copy(Size, DstAlignCanChange, Alignment,
6761                                      *SrcAlign, isVol, CopyFromConstant);
6762   if (!TLI.findOptimalMemOpLowering(
6763           MemOps, Limit, Op, DstPtrInfo.getAddrSpace(),
6764           SrcPtrInfo.getAddrSpace(), MF.getFunction().getAttributes()))
6765     return SDValue();
6766 
6767   if (DstAlignCanChange) {
6768     Type *Ty = MemOps[0].getTypeForEVT(C);
6769     Align NewAlign = DL.getABITypeAlign(Ty);
6770 
6771     // Don't promote to an alignment that would require dynamic stack
6772     // realignment.
6773     const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
6774     if (!TRI->hasStackRealignment(MF))
6775       while (NewAlign > Alignment && DL.exceedsNaturalStackAlignment(NewAlign))
6776         NewAlign = NewAlign.previous();
6777 
6778     if (NewAlign > Alignment) {
6779       // Give the stack frame object a larger alignment if needed.
6780       if (MFI.getObjectAlign(FI->getIndex()) < NewAlign)
6781         MFI.setObjectAlignment(FI->getIndex(), NewAlign);
6782       Alignment = NewAlign;
6783     }
6784   }
6785 
6786   // Prepare AAInfo for loads/stores after lowering this memcpy.
6787   AAMDNodes NewAAInfo = AAInfo;
6788   NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr;
6789 
6790   MachineMemOperand::Flags MMOFlags =
6791       isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone;
6792   SmallVector<SDValue, 16> OutLoadChains;
6793   SmallVector<SDValue, 16> OutStoreChains;
6794   SmallVector<SDValue, 32> OutChains;
6795   unsigned NumMemOps = MemOps.size();
6796   uint64_t SrcOff = 0, DstOff = 0;
6797   for (unsigned i = 0; i != NumMemOps; ++i) {
6798     EVT VT = MemOps[i];
6799     unsigned VTSize = VT.getSizeInBits() / 8;
6800     SDValue Value, Store;
6801 
6802     if (VTSize > Size) {
6803       // Issuing an unaligned load / store pair  that overlaps with the previous
6804       // pair. Adjust the offset accordingly.
6805       assert(i == NumMemOps-1 && i != 0);
6806       SrcOff -= VTSize - Size;
6807       DstOff -= VTSize - Size;
6808     }
6809 
6810     if (CopyFromConstant &&
6811         (isZeroConstant || (VT.isInteger() && !VT.isVector()))) {
6812       // It's unlikely a store of a vector immediate can be done in a single
6813       // instruction. It would require a load from a constantpool first.
6814       // We only handle zero vectors here.
6815       // FIXME: Handle other cases where store of vector immediate is done in
6816       // a single instruction.
6817       ConstantDataArraySlice SubSlice;
6818       if (SrcOff < Slice.Length) {
6819         SubSlice = Slice;
6820         SubSlice.move(SrcOff);
6821       } else {
6822         // This is an out-of-bounds access and hence UB. Pretend we read zero.
6823         SubSlice.Array = nullptr;
6824         SubSlice.Offset = 0;
6825         SubSlice.Length = VTSize;
6826       }
6827       Value = getMemsetStringVal(VT, dl, DAG, TLI, SubSlice);
6828       if (Value.getNode()) {
6829         Store = DAG.getStore(
6830             Chain, dl, Value,
6831             DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl),
6832             DstPtrInfo.getWithOffset(DstOff), Alignment, MMOFlags, NewAAInfo);
6833         OutChains.push_back(Store);
6834       }
6835     }
6836 
6837     if (!Store.getNode()) {
6838       // The type might not be legal for the target.  This should only happen
6839       // if the type is smaller than a legal type, as on PPC, so the right
6840       // thing to do is generate a LoadExt/StoreTrunc pair.  These simplify
6841       // to Load/Store if NVT==VT.
6842       // FIXME does the case above also need this?
6843       EVT NVT = TLI.getTypeToTransformTo(C, VT);
6844       assert(NVT.bitsGE(VT));
6845 
6846       bool isDereferenceable =
6847         SrcPtrInfo.getWithOffset(SrcOff).isDereferenceable(VTSize, C, DL);
6848       MachineMemOperand::Flags SrcMMOFlags = MMOFlags;
6849       if (isDereferenceable)
6850         SrcMMOFlags |= MachineMemOperand::MODereferenceable;
6851 
6852       Value = DAG.getExtLoad(
6853           ISD::EXTLOAD, dl, NVT, Chain,
6854           DAG.getMemBasePlusOffset(Src, TypeSize::Fixed(SrcOff), dl),
6855           SrcPtrInfo.getWithOffset(SrcOff), VT,
6856           commonAlignment(*SrcAlign, SrcOff), SrcMMOFlags, NewAAInfo);
6857       OutLoadChains.push_back(Value.getValue(1));
6858 
6859       Store = DAG.getTruncStore(
6860           Chain, dl, Value,
6861           DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl),
6862           DstPtrInfo.getWithOffset(DstOff), VT, Alignment, MMOFlags, NewAAInfo);
6863       OutStoreChains.push_back(Store);
6864     }
6865     SrcOff += VTSize;
6866     DstOff += VTSize;
6867     Size -= VTSize;
6868   }
6869 
6870   unsigned GluedLdStLimit = MaxLdStGlue == 0 ?
6871                                 TLI.getMaxGluedStoresPerMemcpy() : MaxLdStGlue;
6872   unsigned NumLdStInMemcpy = OutStoreChains.size();
6873 
6874   if (NumLdStInMemcpy) {
6875     // It may be that memcpy might be converted to memset if it's memcpy
6876     // of constants. In such a case, we won't have loads and stores, but
6877     // just stores. In the absence of loads, there is nothing to gang up.
6878     if ((GluedLdStLimit <= 1) || !EnableMemCpyDAGOpt) {
6879       // If target does not care, just leave as it.
6880       for (unsigned i = 0; i < NumLdStInMemcpy; ++i) {
6881         OutChains.push_back(OutLoadChains[i]);
6882         OutChains.push_back(OutStoreChains[i]);
6883       }
6884     } else {
6885       // Ld/St less than/equal limit set by target.
6886       if (NumLdStInMemcpy <= GluedLdStLimit) {
6887           chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, 0,
6888                                         NumLdStInMemcpy, OutLoadChains,
6889                                         OutStoreChains);
6890       } else {
6891         unsigned NumberLdChain =  NumLdStInMemcpy / GluedLdStLimit;
6892         unsigned RemainingLdStInMemcpy = NumLdStInMemcpy % GluedLdStLimit;
6893         unsigned GlueIter = 0;
6894 
6895         for (unsigned cnt = 0; cnt < NumberLdChain; ++cnt) {
6896           unsigned IndexFrom = NumLdStInMemcpy - GlueIter - GluedLdStLimit;
6897           unsigned IndexTo   = NumLdStInMemcpy - GlueIter;
6898 
6899           chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, IndexFrom, IndexTo,
6900                                        OutLoadChains, OutStoreChains);
6901           GlueIter += GluedLdStLimit;
6902         }
6903 
6904         // Residual ld/st.
6905         if (RemainingLdStInMemcpy) {
6906           chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, 0,
6907                                         RemainingLdStInMemcpy, OutLoadChains,
6908                                         OutStoreChains);
6909         }
6910       }
6911     }
6912   }
6913   return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
6914 }
6915 
6916 static SDValue getMemmoveLoadsAndStores(SelectionDAG &DAG, const SDLoc &dl,
6917                                         SDValue Chain, SDValue Dst, SDValue Src,
6918                                         uint64_t Size, Align Alignment,
6919                                         bool isVol, bool AlwaysInline,
6920                                         MachinePointerInfo DstPtrInfo,
6921                                         MachinePointerInfo SrcPtrInfo,
6922                                         const AAMDNodes &AAInfo) {
6923   // Turn a memmove of undef to nop.
6924   // FIXME: We need to honor volatile even is Src is undef.
6925   if (Src.isUndef())
6926     return Chain;
6927 
6928   // Expand memmove to a series of load and store ops if the size operand falls
6929   // below a certain threshold.
6930   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6931   const DataLayout &DL = DAG.getDataLayout();
6932   LLVMContext &C = *DAG.getContext();
6933   std::vector<EVT> MemOps;
6934   bool DstAlignCanChange = false;
6935   MachineFunction &MF = DAG.getMachineFunction();
6936   MachineFrameInfo &MFI = MF.getFrameInfo();
6937   bool OptSize = shouldLowerMemFuncForSize(MF, DAG);
6938   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
6939   if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
6940     DstAlignCanChange = true;
6941   MaybeAlign SrcAlign = DAG.InferPtrAlign(Src);
6942   if (!SrcAlign || Alignment > *SrcAlign)
6943     SrcAlign = Alignment;
6944   assert(SrcAlign && "SrcAlign must be set");
6945   unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemmove(OptSize);
6946   if (!TLI.findOptimalMemOpLowering(
6947           MemOps, Limit,
6948           MemOp::Copy(Size, DstAlignCanChange, Alignment, *SrcAlign,
6949                       /*IsVolatile*/ true),
6950           DstPtrInfo.getAddrSpace(), SrcPtrInfo.getAddrSpace(),
6951           MF.getFunction().getAttributes()))
6952     return SDValue();
6953 
6954   if (DstAlignCanChange) {
6955     Type *Ty = MemOps[0].getTypeForEVT(C);
6956     Align NewAlign = DL.getABITypeAlign(Ty);
6957     if (NewAlign > Alignment) {
6958       // Give the stack frame object a larger alignment if needed.
6959       if (MFI.getObjectAlign(FI->getIndex()) < NewAlign)
6960         MFI.setObjectAlignment(FI->getIndex(), NewAlign);
6961       Alignment = NewAlign;
6962     }
6963   }
6964 
6965   // Prepare AAInfo for loads/stores after lowering this memmove.
6966   AAMDNodes NewAAInfo = AAInfo;
6967   NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr;
6968 
6969   MachineMemOperand::Flags MMOFlags =
6970       isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone;
6971   uint64_t SrcOff = 0, DstOff = 0;
6972   SmallVector<SDValue, 8> LoadValues;
6973   SmallVector<SDValue, 8> LoadChains;
6974   SmallVector<SDValue, 8> OutChains;
6975   unsigned NumMemOps = MemOps.size();
6976   for (unsigned i = 0; i < NumMemOps; i++) {
6977     EVT VT = MemOps[i];
6978     unsigned VTSize = VT.getSizeInBits() / 8;
6979     SDValue Value;
6980 
6981     bool isDereferenceable =
6982       SrcPtrInfo.getWithOffset(SrcOff).isDereferenceable(VTSize, C, DL);
6983     MachineMemOperand::Flags SrcMMOFlags = MMOFlags;
6984     if (isDereferenceable)
6985       SrcMMOFlags |= MachineMemOperand::MODereferenceable;
6986 
6987     Value = DAG.getLoad(
6988         VT, dl, Chain,
6989         DAG.getMemBasePlusOffset(Src, TypeSize::Fixed(SrcOff), dl),
6990         SrcPtrInfo.getWithOffset(SrcOff), *SrcAlign, SrcMMOFlags, NewAAInfo);
6991     LoadValues.push_back(Value);
6992     LoadChains.push_back(Value.getValue(1));
6993     SrcOff += VTSize;
6994   }
6995   Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
6996   OutChains.clear();
6997   for (unsigned i = 0; i < NumMemOps; i++) {
6998     EVT VT = MemOps[i];
6999     unsigned VTSize = VT.getSizeInBits() / 8;
7000     SDValue Store;
7001 
7002     Store = DAG.getStore(
7003         Chain, dl, LoadValues[i],
7004         DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl),
7005         DstPtrInfo.getWithOffset(DstOff), Alignment, MMOFlags, NewAAInfo);
7006     OutChains.push_back(Store);
7007     DstOff += VTSize;
7008   }
7009 
7010   return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
7011 }
7012 
7013 /// Lower the call to 'memset' intrinsic function into a series of store
7014 /// operations.
7015 ///
7016 /// \param DAG Selection DAG where lowered code is placed.
7017 /// \param dl Link to corresponding IR location.
7018 /// \param Chain Control flow dependency.
7019 /// \param Dst Pointer to destination memory location.
7020 /// \param Src Value of byte to write into the memory.
7021 /// \param Size Number of bytes to write.
7022 /// \param Alignment Alignment of the destination in bytes.
7023 /// \param isVol True if destination is volatile.
7024 /// \param AlwaysInline Makes sure no function call is generated.
7025 /// \param DstPtrInfo IR information on the memory pointer.
7026 /// \returns New head in the control flow, if lowering was successful, empty
7027 /// SDValue otherwise.
7028 ///
7029 /// The function tries to replace 'llvm.memset' intrinsic with several store
7030 /// operations and value calculation code. This is usually profitable for small
7031 /// memory size or when the semantic requires inlining.
7032 static SDValue getMemsetStores(SelectionDAG &DAG, const SDLoc &dl,
7033                                SDValue Chain, SDValue Dst, SDValue Src,
7034                                uint64_t Size, Align Alignment, bool isVol,
7035                                bool AlwaysInline, MachinePointerInfo DstPtrInfo,
7036                                const AAMDNodes &AAInfo) {
7037   // Turn a memset of undef to nop.
7038   // FIXME: We need to honor volatile even is Src is undef.
7039   if (Src.isUndef())
7040     return Chain;
7041 
7042   // Expand memset to a series of load/store ops if the size operand
7043   // falls below a certain threshold.
7044   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7045   std::vector<EVT> MemOps;
7046   bool DstAlignCanChange = false;
7047   MachineFunction &MF = DAG.getMachineFunction();
7048   MachineFrameInfo &MFI = MF.getFrameInfo();
7049   bool OptSize = shouldLowerMemFuncForSize(MF, DAG);
7050   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
7051   if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
7052     DstAlignCanChange = true;
7053   bool IsZeroVal =
7054       isa<ConstantSDNode>(Src) && cast<ConstantSDNode>(Src)->isZero();
7055   unsigned Limit = AlwaysInline ? ~0 : TLI.getMaxStoresPerMemset(OptSize);
7056 
7057   if (!TLI.findOptimalMemOpLowering(
7058           MemOps, Limit,
7059           MemOp::Set(Size, DstAlignCanChange, Alignment, IsZeroVal, isVol),
7060           DstPtrInfo.getAddrSpace(), ~0u, MF.getFunction().getAttributes()))
7061     return SDValue();
7062 
7063   if (DstAlignCanChange) {
7064     Type *Ty = MemOps[0].getTypeForEVT(*DAG.getContext());
7065     Align NewAlign = DAG.getDataLayout().getABITypeAlign(Ty);
7066     if (NewAlign > Alignment) {
7067       // Give the stack frame object a larger alignment if needed.
7068       if (MFI.getObjectAlign(FI->getIndex()) < NewAlign)
7069         MFI.setObjectAlignment(FI->getIndex(), NewAlign);
7070       Alignment = NewAlign;
7071     }
7072   }
7073 
7074   SmallVector<SDValue, 8> OutChains;
7075   uint64_t DstOff = 0;
7076   unsigned NumMemOps = MemOps.size();
7077 
7078   // Find the largest store and generate the bit pattern for it.
7079   EVT LargestVT = MemOps[0];
7080   for (unsigned i = 1; i < NumMemOps; i++)
7081     if (MemOps[i].bitsGT(LargestVT))
7082       LargestVT = MemOps[i];
7083   SDValue MemSetValue = getMemsetValue(Src, LargestVT, DAG, dl);
7084 
7085   // Prepare AAInfo for loads/stores after lowering this memset.
7086   AAMDNodes NewAAInfo = AAInfo;
7087   NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr;
7088 
7089   for (unsigned i = 0; i < NumMemOps; i++) {
7090     EVT VT = MemOps[i];
7091     unsigned VTSize = VT.getSizeInBits() / 8;
7092     if (VTSize > Size) {
7093       // Issuing an unaligned load / store pair  that overlaps with the previous
7094       // pair. Adjust the offset accordingly.
7095       assert(i == NumMemOps-1 && i != 0);
7096       DstOff -= VTSize - Size;
7097     }
7098 
7099     // If this store is smaller than the largest store see whether we can get
7100     // the smaller value for free with a truncate.
7101     SDValue Value = MemSetValue;
7102     if (VT.bitsLT(LargestVT)) {
7103       if (!LargestVT.isVector() && !VT.isVector() &&
7104           TLI.isTruncateFree(LargestVT, VT))
7105         Value = DAG.getNode(ISD::TRUNCATE, dl, VT, MemSetValue);
7106       else
7107         Value = getMemsetValue(Src, VT, DAG, dl);
7108     }
7109     assert(Value.getValueType() == VT && "Value with wrong type.");
7110     SDValue Store = DAG.getStore(
7111         Chain, dl, Value,
7112         DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl),
7113         DstPtrInfo.getWithOffset(DstOff), Alignment,
7114         isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone,
7115         NewAAInfo);
7116     OutChains.push_back(Store);
7117     DstOff += VT.getSizeInBits() / 8;
7118     Size -= VTSize;
7119   }
7120 
7121   return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
7122 }
7123 
7124 static void checkAddrSpaceIsValidForLibcall(const TargetLowering *TLI,
7125                                             unsigned AS) {
7126   // Lowering memcpy / memset / memmove intrinsics to calls is only valid if all
7127   // pointer operands can be losslessly bitcasted to pointers of address space 0
7128   if (AS != 0 && !TLI->getTargetMachine().isNoopAddrSpaceCast(AS, 0)) {
7129     report_fatal_error("cannot lower memory intrinsic in address space " +
7130                        Twine(AS));
7131   }
7132 }
7133 
7134 SDValue SelectionDAG::getMemcpy(SDValue Chain, const SDLoc &dl, SDValue Dst,
7135                                 SDValue Src, SDValue Size, Align Alignment,
7136                                 bool isVol, bool AlwaysInline, bool isTailCall,
7137                                 MachinePointerInfo DstPtrInfo,
7138                                 MachinePointerInfo SrcPtrInfo,
7139                                 const AAMDNodes &AAInfo) {
7140   // Check to see if we should lower the memcpy to loads and stores first.
7141   // For cases within the target-specified limits, this is the best choice.
7142   ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
7143   if (ConstantSize) {
7144     // Memcpy with size zero? Just return the original chain.
7145     if (ConstantSize->isZero())
7146       return Chain;
7147 
7148     SDValue Result = getMemcpyLoadsAndStores(
7149         *this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), Alignment,
7150         isVol, false, DstPtrInfo, SrcPtrInfo, AAInfo);
7151     if (Result.getNode())
7152       return Result;
7153   }
7154 
7155   // Then check to see if we should lower the memcpy with target-specific
7156   // code. If the target chooses to do this, this is the next best.
7157   if (TSI) {
7158     SDValue Result = TSI->EmitTargetCodeForMemcpy(
7159         *this, dl, Chain, Dst, Src, Size, Alignment, isVol, AlwaysInline,
7160         DstPtrInfo, SrcPtrInfo);
7161     if (Result.getNode())
7162       return Result;
7163   }
7164 
7165   // If we really need inline code and the target declined to provide it,
7166   // use a (potentially long) sequence of loads and stores.
7167   if (AlwaysInline) {
7168     assert(ConstantSize && "AlwaysInline requires a constant size!");
7169     return getMemcpyLoadsAndStores(*this, dl, Chain, Dst, Src,
7170                                    ConstantSize->getZExtValue(), Alignment,
7171                                    isVol, true, DstPtrInfo, SrcPtrInfo, AAInfo);
7172   }
7173 
7174   checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace());
7175   checkAddrSpaceIsValidForLibcall(TLI, SrcPtrInfo.getAddrSpace());
7176 
7177   // FIXME: If the memcpy is volatile (isVol), lowering it to a plain libc
7178   // memcpy is not guaranteed to be safe. libc memcpys aren't required to
7179   // respect volatile, so they may do things like read or write memory
7180   // beyond the given memory regions. But fixing this isn't easy, and most
7181   // people don't care.
7182 
7183   // Emit a library call.
7184   TargetLowering::ArgListTy Args;
7185   TargetLowering::ArgListEntry Entry;
7186   Entry.Ty = Type::getInt8PtrTy(*getContext());
7187   Entry.Node = Dst; Args.push_back(Entry);
7188   Entry.Node = Src; Args.push_back(Entry);
7189 
7190   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
7191   Entry.Node = Size; Args.push_back(Entry);
7192   // FIXME: pass in SDLoc
7193   TargetLowering::CallLoweringInfo CLI(*this);
7194   CLI.setDebugLoc(dl)
7195       .setChain(Chain)
7196       .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMCPY),
7197                     Dst.getValueType().getTypeForEVT(*getContext()),
7198                     getExternalSymbol(TLI->getLibcallName(RTLIB::MEMCPY),
7199                                       TLI->getPointerTy(getDataLayout())),
7200                     std::move(Args))
7201       .setDiscardResult()
7202       .setTailCall(isTailCall);
7203 
7204   std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
7205   return CallResult.second;
7206 }
7207 
7208 SDValue SelectionDAG::getAtomicMemcpy(SDValue Chain, const SDLoc &dl,
7209                                       SDValue Dst, SDValue Src, SDValue Size,
7210                                       Type *SizeTy, unsigned ElemSz,
7211                                       bool isTailCall,
7212                                       MachinePointerInfo DstPtrInfo,
7213                                       MachinePointerInfo SrcPtrInfo) {
7214   // Emit a library call.
7215   TargetLowering::ArgListTy Args;
7216   TargetLowering::ArgListEntry Entry;
7217   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
7218   Entry.Node = Dst;
7219   Args.push_back(Entry);
7220 
7221   Entry.Node = Src;
7222   Args.push_back(Entry);
7223 
7224   Entry.Ty = SizeTy;
7225   Entry.Node = Size;
7226   Args.push_back(Entry);
7227 
7228   RTLIB::Libcall LibraryCall =
7229       RTLIB::getMEMCPY_ELEMENT_UNORDERED_ATOMIC(ElemSz);
7230   if (LibraryCall == RTLIB::UNKNOWN_LIBCALL)
7231     report_fatal_error("Unsupported element size");
7232 
7233   TargetLowering::CallLoweringInfo CLI(*this);
7234   CLI.setDebugLoc(dl)
7235       .setChain(Chain)
7236       .setLibCallee(TLI->getLibcallCallingConv(LibraryCall),
7237                     Type::getVoidTy(*getContext()),
7238                     getExternalSymbol(TLI->getLibcallName(LibraryCall),
7239                                       TLI->getPointerTy(getDataLayout())),
7240                     std::move(Args))
7241       .setDiscardResult()
7242       .setTailCall(isTailCall);
7243 
7244   std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
7245   return CallResult.second;
7246 }
7247 
7248 SDValue SelectionDAG::getMemmove(SDValue Chain, const SDLoc &dl, SDValue Dst,
7249                                  SDValue Src, SDValue Size, Align Alignment,
7250                                  bool isVol, bool isTailCall,
7251                                  MachinePointerInfo DstPtrInfo,
7252                                  MachinePointerInfo SrcPtrInfo,
7253                                  const AAMDNodes &AAInfo) {
7254   // Check to see if we should lower the memmove to loads and stores first.
7255   // For cases within the target-specified limits, this is the best choice.
7256   ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
7257   if (ConstantSize) {
7258     // Memmove with size zero? Just return the original chain.
7259     if (ConstantSize->isZero())
7260       return Chain;
7261 
7262     SDValue Result = getMemmoveLoadsAndStores(
7263         *this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), Alignment,
7264         isVol, false, DstPtrInfo, SrcPtrInfo, AAInfo);
7265     if (Result.getNode())
7266       return Result;
7267   }
7268 
7269   // Then check to see if we should lower the memmove with target-specific
7270   // code. If the target chooses to do this, this is the next best.
7271   if (TSI) {
7272     SDValue Result =
7273         TSI->EmitTargetCodeForMemmove(*this, dl, Chain, Dst, Src, Size,
7274                                       Alignment, isVol, DstPtrInfo, SrcPtrInfo);
7275     if (Result.getNode())
7276       return Result;
7277   }
7278 
7279   checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace());
7280   checkAddrSpaceIsValidForLibcall(TLI, SrcPtrInfo.getAddrSpace());
7281 
7282   // FIXME: If the memmove is volatile, lowering it to plain libc memmove may
7283   // not be safe.  See memcpy above for more details.
7284 
7285   // Emit a library call.
7286   TargetLowering::ArgListTy Args;
7287   TargetLowering::ArgListEntry Entry;
7288   Entry.Ty = Type::getInt8PtrTy(*getContext());
7289   Entry.Node = Dst; Args.push_back(Entry);
7290   Entry.Node = Src; Args.push_back(Entry);
7291 
7292   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
7293   Entry.Node = Size; Args.push_back(Entry);
7294   // FIXME:  pass in SDLoc
7295   TargetLowering::CallLoweringInfo CLI(*this);
7296   CLI.setDebugLoc(dl)
7297       .setChain(Chain)
7298       .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMMOVE),
7299                     Dst.getValueType().getTypeForEVT(*getContext()),
7300                     getExternalSymbol(TLI->getLibcallName(RTLIB::MEMMOVE),
7301                                       TLI->getPointerTy(getDataLayout())),
7302                     std::move(Args))
7303       .setDiscardResult()
7304       .setTailCall(isTailCall);
7305 
7306   std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
7307   return CallResult.second;
7308 }
7309 
7310 SDValue SelectionDAG::getAtomicMemmove(SDValue Chain, const SDLoc &dl,
7311                                        SDValue Dst, SDValue Src, SDValue Size,
7312                                        Type *SizeTy, unsigned ElemSz,
7313                                        bool isTailCall,
7314                                        MachinePointerInfo DstPtrInfo,
7315                                        MachinePointerInfo SrcPtrInfo) {
7316   // Emit a library call.
7317   TargetLowering::ArgListTy Args;
7318   TargetLowering::ArgListEntry Entry;
7319   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
7320   Entry.Node = Dst;
7321   Args.push_back(Entry);
7322 
7323   Entry.Node = Src;
7324   Args.push_back(Entry);
7325 
7326   Entry.Ty = SizeTy;
7327   Entry.Node = Size;
7328   Args.push_back(Entry);
7329 
7330   RTLIB::Libcall LibraryCall =
7331       RTLIB::getMEMMOVE_ELEMENT_UNORDERED_ATOMIC(ElemSz);
7332   if (LibraryCall == RTLIB::UNKNOWN_LIBCALL)
7333     report_fatal_error("Unsupported element size");
7334 
7335   TargetLowering::CallLoweringInfo CLI(*this);
7336   CLI.setDebugLoc(dl)
7337       .setChain(Chain)
7338       .setLibCallee(TLI->getLibcallCallingConv(LibraryCall),
7339                     Type::getVoidTy(*getContext()),
7340                     getExternalSymbol(TLI->getLibcallName(LibraryCall),
7341                                       TLI->getPointerTy(getDataLayout())),
7342                     std::move(Args))
7343       .setDiscardResult()
7344       .setTailCall(isTailCall);
7345 
7346   std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
7347   return CallResult.second;
7348 }
7349 
7350 SDValue SelectionDAG::getMemset(SDValue Chain, const SDLoc &dl, SDValue Dst,
7351                                 SDValue Src, SDValue Size, Align Alignment,
7352                                 bool isVol, bool AlwaysInline, bool isTailCall,
7353                                 MachinePointerInfo DstPtrInfo,
7354                                 const AAMDNodes &AAInfo) {
7355   // Check to see if we should lower the memset to stores first.
7356   // For cases within the target-specified limits, this is the best choice.
7357   ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
7358   if (ConstantSize) {
7359     // Memset with size zero? Just return the original chain.
7360     if (ConstantSize->isZero())
7361       return Chain;
7362 
7363     SDValue Result = getMemsetStores(*this, dl, Chain, Dst, Src,
7364                                      ConstantSize->getZExtValue(), Alignment,
7365                                      isVol, false, DstPtrInfo, AAInfo);
7366 
7367     if (Result.getNode())
7368       return Result;
7369   }
7370 
7371   // Then check to see if we should lower the memset with target-specific
7372   // code. If the target chooses to do this, this is the next best.
7373   if (TSI) {
7374     SDValue Result = TSI->EmitTargetCodeForMemset(
7375         *this, dl, Chain, Dst, Src, Size, Alignment, isVol, AlwaysInline, DstPtrInfo);
7376     if (Result.getNode())
7377       return Result;
7378   }
7379 
7380   // If we really need inline code and the target declined to provide it,
7381   // use a (potentially long) sequence of loads and stores.
7382   if (AlwaysInline) {
7383     assert(ConstantSize && "AlwaysInline requires a constant size!");
7384     SDValue Result = getMemsetStores(*this, dl, Chain, Dst, Src,
7385                                      ConstantSize->getZExtValue(), Alignment,
7386                                      isVol, true, DstPtrInfo, AAInfo);
7387     assert(Result &&
7388            "getMemsetStores must return a valid sequence when AlwaysInline");
7389     return Result;
7390   }
7391 
7392   checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace());
7393 
7394   // Emit a library call.
7395   auto &Ctx = *getContext();
7396   const auto& DL = getDataLayout();
7397 
7398   TargetLowering::CallLoweringInfo CLI(*this);
7399   // FIXME: pass in SDLoc
7400   CLI.setDebugLoc(dl).setChain(Chain);
7401 
7402   ConstantSDNode *ConstantSrc = dyn_cast<ConstantSDNode>(Src);
7403   const bool SrcIsZero = ConstantSrc && ConstantSrc->isZero();
7404   const char *BzeroName = getTargetLoweringInfo().getLibcallName(RTLIB::BZERO);
7405 
7406   // Helper function to create an Entry from Node and Type.
7407   const auto CreateEntry = [](SDValue Node, Type *Ty) {
7408     TargetLowering::ArgListEntry Entry;
7409     Entry.Node = Node;
7410     Entry.Ty = Ty;
7411     return Entry;
7412   };
7413 
7414   // If zeroing out and bzero is present, use it.
7415   if (SrcIsZero && BzeroName) {
7416     TargetLowering::ArgListTy Args;
7417     Args.push_back(CreateEntry(Dst, Type::getInt8PtrTy(Ctx)));
7418     Args.push_back(CreateEntry(Size, DL.getIntPtrType(Ctx)));
7419     CLI.setLibCallee(
7420         TLI->getLibcallCallingConv(RTLIB::BZERO), Type::getVoidTy(Ctx),
7421         getExternalSymbol(BzeroName, TLI->getPointerTy(DL)), std::move(Args));
7422   } else {
7423     TargetLowering::ArgListTy Args;
7424     Args.push_back(CreateEntry(Dst, Type::getInt8PtrTy(Ctx)));
7425     Args.push_back(CreateEntry(Src, Src.getValueType().getTypeForEVT(Ctx)));
7426     Args.push_back(CreateEntry(Size, DL.getIntPtrType(Ctx)));
7427     CLI.setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMSET),
7428                      Dst.getValueType().getTypeForEVT(Ctx),
7429                      getExternalSymbol(TLI->getLibcallName(RTLIB::MEMSET),
7430                                        TLI->getPointerTy(DL)),
7431                      std::move(Args));
7432   }
7433 
7434   CLI.setDiscardResult().setTailCall(isTailCall);
7435 
7436   std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
7437   return CallResult.second;
7438 }
7439 
7440 SDValue SelectionDAG::getAtomicMemset(SDValue Chain, const SDLoc &dl,
7441                                       SDValue Dst, SDValue Value, SDValue Size,
7442                                       Type *SizeTy, unsigned ElemSz,
7443                                       bool isTailCall,
7444                                       MachinePointerInfo DstPtrInfo) {
7445   // Emit a library call.
7446   TargetLowering::ArgListTy Args;
7447   TargetLowering::ArgListEntry Entry;
7448   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
7449   Entry.Node = Dst;
7450   Args.push_back(Entry);
7451 
7452   Entry.Ty = Type::getInt8Ty(*getContext());
7453   Entry.Node = Value;
7454   Args.push_back(Entry);
7455 
7456   Entry.Ty = SizeTy;
7457   Entry.Node = Size;
7458   Args.push_back(Entry);
7459 
7460   RTLIB::Libcall LibraryCall =
7461       RTLIB::getMEMSET_ELEMENT_UNORDERED_ATOMIC(ElemSz);
7462   if (LibraryCall == RTLIB::UNKNOWN_LIBCALL)
7463     report_fatal_error("Unsupported element size");
7464 
7465   TargetLowering::CallLoweringInfo CLI(*this);
7466   CLI.setDebugLoc(dl)
7467       .setChain(Chain)
7468       .setLibCallee(TLI->getLibcallCallingConv(LibraryCall),
7469                     Type::getVoidTy(*getContext()),
7470                     getExternalSymbol(TLI->getLibcallName(LibraryCall),
7471                                       TLI->getPointerTy(getDataLayout())),
7472                     std::move(Args))
7473       .setDiscardResult()
7474       .setTailCall(isTailCall);
7475 
7476   std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
7477   return CallResult.second;
7478 }
7479 
7480 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
7481                                 SDVTList VTList, ArrayRef<SDValue> Ops,
7482                                 MachineMemOperand *MMO) {
7483   FoldingSetNodeID ID;
7484   ID.AddInteger(MemVT.getRawBits());
7485   AddNodeIDNode(ID, Opcode, VTList, Ops);
7486   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7487   ID.AddInteger(MMO->getFlags());
7488   void* IP = nullptr;
7489   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7490     cast<AtomicSDNode>(E)->refineAlignment(MMO);
7491     return SDValue(E, 0);
7492   }
7493 
7494   auto *N = newSDNode<AtomicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
7495                                     VTList, MemVT, MMO);
7496   createOperands(N, Ops);
7497 
7498   CSEMap.InsertNode(N, IP);
7499   InsertNode(N);
7500   return SDValue(N, 0);
7501 }
7502 
7503 SDValue SelectionDAG::getAtomicCmpSwap(unsigned Opcode, const SDLoc &dl,
7504                                        EVT MemVT, SDVTList VTs, SDValue Chain,
7505                                        SDValue Ptr, SDValue Cmp, SDValue Swp,
7506                                        MachineMemOperand *MMO) {
7507   assert(Opcode == ISD::ATOMIC_CMP_SWAP ||
7508          Opcode == ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS);
7509   assert(Cmp.getValueType() == Swp.getValueType() && "Invalid Atomic Op Types");
7510 
7511   SDValue Ops[] = {Chain, Ptr, Cmp, Swp};
7512   return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
7513 }
7514 
7515 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
7516                                 SDValue Chain, SDValue Ptr, SDValue Val,
7517                                 MachineMemOperand *MMO) {
7518   assert((Opcode == ISD::ATOMIC_LOAD_ADD ||
7519           Opcode == ISD::ATOMIC_LOAD_SUB ||
7520           Opcode == ISD::ATOMIC_LOAD_AND ||
7521           Opcode == ISD::ATOMIC_LOAD_CLR ||
7522           Opcode == ISD::ATOMIC_LOAD_OR ||
7523           Opcode == ISD::ATOMIC_LOAD_XOR ||
7524           Opcode == ISD::ATOMIC_LOAD_NAND ||
7525           Opcode == ISD::ATOMIC_LOAD_MIN ||
7526           Opcode == ISD::ATOMIC_LOAD_MAX ||
7527           Opcode == ISD::ATOMIC_LOAD_UMIN ||
7528           Opcode == ISD::ATOMIC_LOAD_UMAX ||
7529           Opcode == ISD::ATOMIC_LOAD_FADD ||
7530           Opcode == ISD::ATOMIC_LOAD_FSUB ||
7531           Opcode == ISD::ATOMIC_LOAD_FMAX ||
7532           Opcode == ISD::ATOMIC_LOAD_FMIN ||
7533           Opcode == ISD::ATOMIC_SWAP ||
7534           Opcode == ISD::ATOMIC_STORE) &&
7535          "Invalid Atomic Op");
7536 
7537   EVT VT = Val.getValueType();
7538 
7539   SDVTList VTs = Opcode == ISD::ATOMIC_STORE ? getVTList(MVT::Other) :
7540                                                getVTList(VT, MVT::Other);
7541   SDValue Ops[] = {Chain, Ptr, Val};
7542   return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
7543 }
7544 
7545 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
7546                                 EVT VT, SDValue Chain, SDValue Ptr,
7547                                 MachineMemOperand *MMO) {
7548   assert(Opcode == ISD::ATOMIC_LOAD && "Invalid Atomic Op");
7549 
7550   SDVTList VTs = getVTList(VT, MVT::Other);
7551   SDValue Ops[] = {Chain, Ptr};
7552   return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
7553 }
7554 
7555 /// getMergeValues - Create a MERGE_VALUES node from the given operands.
7556 SDValue SelectionDAG::getMergeValues(ArrayRef<SDValue> Ops, const SDLoc &dl) {
7557   if (Ops.size() == 1)
7558     return Ops[0];
7559 
7560   SmallVector<EVT, 4> VTs;
7561   VTs.reserve(Ops.size());
7562   for (const SDValue &Op : Ops)
7563     VTs.push_back(Op.getValueType());
7564   return getNode(ISD::MERGE_VALUES, dl, getVTList(VTs), Ops);
7565 }
7566 
7567 SDValue SelectionDAG::getMemIntrinsicNode(
7568     unsigned Opcode, const SDLoc &dl, SDVTList VTList, ArrayRef<SDValue> Ops,
7569     EVT MemVT, MachinePointerInfo PtrInfo, Align Alignment,
7570     MachineMemOperand::Flags Flags, uint64_t Size, const AAMDNodes &AAInfo) {
7571   if (!Size && MemVT.isScalableVector())
7572     Size = MemoryLocation::UnknownSize;
7573   else if (!Size)
7574     Size = MemVT.getStoreSize();
7575 
7576   MachineFunction &MF = getMachineFunction();
7577   MachineMemOperand *MMO =
7578       MF.getMachineMemOperand(PtrInfo, Flags, Size, Alignment, AAInfo);
7579 
7580   return getMemIntrinsicNode(Opcode, dl, VTList, Ops, MemVT, MMO);
7581 }
7582 
7583 SDValue SelectionDAG::getMemIntrinsicNode(unsigned Opcode, const SDLoc &dl,
7584                                           SDVTList VTList,
7585                                           ArrayRef<SDValue> Ops, EVT MemVT,
7586                                           MachineMemOperand *MMO) {
7587   assert((Opcode == ISD::INTRINSIC_VOID ||
7588           Opcode == ISD::INTRINSIC_W_CHAIN ||
7589           Opcode == ISD::PREFETCH ||
7590           ((int)Opcode <= std::numeric_limits<int>::max() &&
7591            (int)Opcode >= ISD::FIRST_TARGET_MEMORY_OPCODE)) &&
7592          "Opcode is not a memory-accessing opcode!");
7593 
7594   // Memoize the node unless it returns a flag.
7595   MemIntrinsicSDNode *N;
7596   if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) {
7597     FoldingSetNodeID ID;
7598     AddNodeIDNode(ID, Opcode, VTList, Ops);
7599     ID.AddInteger(getSyntheticNodeSubclassData<MemIntrinsicSDNode>(
7600         Opcode, dl.getIROrder(), VTList, MemVT, MMO));
7601     ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7602     ID.AddInteger(MMO->getFlags());
7603     void *IP = nullptr;
7604     if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7605       cast<MemIntrinsicSDNode>(E)->refineAlignment(MMO);
7606       return SDValue(E, 0);
7607     }
7608 
7609     N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
7610                                       VTList, MemVT, MMO);
7611     createOperands(N, Ops);
7612 
7613   CSEMap.InsertNode(N, IP);
7614   } else {
7615     N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
7616                                       VTList, MemVT, MMO);
7617     createOperands(N, Ops);
7618   }
7619   InsertNode(N);
7620   SDValue V(N, 0);
7621   NewSDValueDbgMsg(V, "Creating new node: ", this);
7622   return V;
7623 }
7624 
7625 SDValue SelectionDAG::getLifetimeNode(bool IsStart, const SDLoc &dl,
7626                                       SDValue Chain, int FrameIndex,
7627                                       int64_t Size, int64_t Offset) {
7628   const unsigned Opcode = IsStart ? ISD::LIFETIME_START : ISD::LIFETIME_END;
7629   const auto VTs = getVTList(MVT::Other);
7630   SDValue Ops[2] = {
7631       Chain,
7632       getFrameIndex(FrameIndex,
7633                     getTargetLoweringInfo().getFrameIndexTy(getDataLayout()),
7634                     true)};
7635 
7636   FoldingSetNodeID ID;
7637   AddNodeIDNode(ID, Opcode, VTs, Ops);
7638   ID.AddInteger(FrameIndex);
7639   ID.AddInteger(Size);
7640   ID.AddInteger(Offset);
7641   void *IP = nullptr;
7642   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
7643     return SDValue(E, 0);
7644 
7645   LifetimeSDNode *N = newSDNode<LifetimeSDNode>(
7646       Opcode, dl.getIROrder(), dl.getDebugLoc(), VTs, Size, Offset);
7647   createOperands(N, Ops);
7648   CSEMap.InsertNode(N, IP);
7649   InsertNode(N);
7650   SDValue V(N, 0);
7651   NewSDValueDbgMsg(V, "Creating new node: ", this);
7652   return V;
7653 }
7654 
7655 SDValue SelectionDAG::getPseudoProbeNode(const SDLoc &Dl, SDValue Chain,
7656                                          uint64_t Guid, uint64_t Index,
7657                                          uint32_t Attr) {
7658   const unsigned Opcode = ISD::PSEUDO_PROBE;
7659   const auto VTs = getVTList(MVT::Other);
7660   SDValue Ops[] = {Chain};
7661   FoldingSetNodeID ID;
7662   AddNodeIDNode(ID, Opcode, VTs, Ops);
7663   ID.AddInteger(Guid);
7664   ID.AddInteger(Index);
7665   void *IP = nullptr;
7666   if (SDNode *E = FindNodeOrInsertPos(ID, Dl, IP))
7667     return SDValue(E, 0);
7668 
7669   auto *N = newSDNode<PseudoProbeSDNode>(
7670       Opcode, Dl.getIROrder(), Dl.getDebugLoc(), VTs, Guid, Index, Attr);
7671   createOperands(N, Ops);
7672   CSEMap.InsertNode(N, IP);
7673   InsertNode(N);
7674   SDValue V(N, 0);
7675   NewSDValueDbgMsg(V, "Creating new node: ", this);
7676   return V;
7677 }
7678 
7679 /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a
7680 /// MachinePointerInfo record from it.  This is particularly useful because the
7681 /// code generator has many cases where it doesn't bother passing in a
7682 /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst".
7683 static MachinePointerInfo InferPointerInfo(const MachinePointerInfo &Info,
7684                                            SelectionDAG &DAG, SDValue Ptr,
7685                                            int64_t Offset = 0) {
7686   // If this is FI+Offset, we can model it.
7687   if (const FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr))
7688     return MachinePointerInfo::getFixedStack(DAG.getMachineFunction(),
7689                                              FI->getIndex(), Offset);
7690 
7691   // If this is (FI+Offset1)+Offset2, we can model it.
7692   if (Ptr.getOpcode() != ISD::ADD ||
7693       !isa<ConstantSDNode>(Ptr.getOperand(1)) ||
7694       !isa<FrameIndexSDNode>(Ptr.getOperand(0)))
7695     return Info;
7696 
7697   int FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
7698   return MachinePointerInfo::getFixedStack(
7699       DAG.getMachineFunction(), FI,
7700       Offset + cast<ConstantSDNode>(Ptr.getOperand(1))->getSExtValue());
7701 }
7702 
7703 /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a
7704 /// MachinePointerInfo record from it.  This is particularly useful because the
7705 /// code generator has many cases where it doesn't bother passing in a
7706 /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst".
7707 static MachinePointerInfo InferPointerInfo(const MachinePointerInfo &Info,
7708                                            SelectionDAG &DAG, SDValue Ptr,
7709                                            SDValue OffsetOp) {
7710   // If the 'Offset' value isn't a constant, we can't handle this.
7711   if (ConstantSDNode *OffsetNode = dyn_cast<ConstantSDNode>(OffsetOp))
7712     return InferPointerInfo(Info, DAG, Ptr, OffsetNode->getSExtValue());
7713   if (OffsetOp.isUndef())
7714     return InferPointerInfo(Info, DAG, Ptr);
7715   return Info;
7716 }
7717 
7718 SDValue SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType,
7719                               EVT VT, const SDLoc &dl, SDValue Chain,
7720                               SDValue Ptr, SDValue Offset,
7721                               MachinePointerInfo PtrInfo, EVT MemVT,
7722                               Align Alignment,
7723                               MachineMemOperand::Flags MMOFlags,
7724                               const AAMDNodes &AAInfo, const MDNode *Ranges) {
7725   assert(Chain.getValueType() == MVT::Other &&
7726         "Invalid chain type");
7727 
7728   MMOFlags |= MachineMemOperand::MOLoad;
7729   assert((MMOFlags & MachineMemOperand::MOStore) == 0);
7730   // If we don't have a PtrInfo, infer the trivial frame index case to simplify
7731   // clients.
7732   if (PtrInfo.V.isNull())
7733     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr, Offset);
7734 
7735   uint64_t Size = MemoryLocation::getSizeOrUnknown(MemVT.getStoreSize());
7736   MachineFunction &MF = getMachineFunction();
7737   MachineMemOperand *MMO = MF.getMachineMemOperand(PtrInfo, MMOFlags, Size,
7738                                                    Alignment, AAInfo, Ranges);
7739   return getLoad(AM, ExtType, VT, dl, Chain, Ptr, Offset, MemVT, MMO);
7740 }
7741 
7742 SDValue SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType,
7743                               EVT VT, const SDLoc &dl, SDValue Chain,
7744                               SDValue Ptr, SDValue Offset, EVT MemVT,
7745                               MachineMemOperand *MMO) {
7746   if (VT == MemVT) {
7747     ExtType = ISD::NON_EXTLOAD;
7748   } else if (ExtType == ISD::NON_EXTLOAD) {
7749     assert(VT == MemVT && "Non-extending load from different memory type!");
7750   } else {
7751     // Extending load.
7752     assert(MemVT.getScalarType().bitsLT(VT.getScalarType()) &&
7753            "Should only be an extending load, not truncating!");
7754     assert(VT.isInteger() == MemVT.isInteger() &&
7755            "Cannot convert from FP to Int or Int -> FP!");
7756     assert(VT.isVector() == MemVT.isVector() &&
7757            "Cannot use an ext load to convert to or from a vector!");
7758     assert((!VT.isVector() ||
7759             VT.getVectorElementCount() == MemVT.getVectorElementCount()) &&
7760            "Cannot use an ext load to change the number of vector elements!");
7761   }
7762 
7763   bool Indexed = AM != ISD::UNINDEXED;
7764   assert((Indexed || Offset.isUndef()) && "Unindexed load with an offset!");
7765 
7766   SDVTList VTs = Indexed ?
7767     getVTList(VT, Ptr.getValueType(), MVT::Other) : getVTList(VT, MVT::Other);
7768   SDValue Ops[] = { Chain, Ptr, Offset };
7769   FoldingSetNodeID ID;
7770   AddNodeIDNode(ID, ISD::LOAD, VTs, Ops);
7771   ID.AddInteger(MemVT.getRawBits());
7772   ID.AddInteger(getSyntheticNodeSubclassData<LoadSDNode>(
7773       dl.getIROrder(), VTs, AM, ExtType, MemVT, MMO));
7774   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7775   ID.AddInteger(MMO->getFlags());
7776   void *IP = nullptr;
7777   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7778     cast<LoadSDNode>(E)->refineAlignment(MMO);
7779     return SDValue(E, 0);
7780   }
7781   auto *N = newSDNode<LoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
7782                                   ExtType, MemVT, MMO);
7783   createOperands(N, Ops);
7784 
7785   CSEMap.InsertNode(N, IP);
7786   InsertNode(N);
7787   SDValue V(N, 0);
7788   NewSDValueDbgMsg(V, "Creating new node: ", this);
7789   return V;
7790 }
7791 
7792 SDValue SelectionDAG::getLoad(EVT VT, const SDLoc &dl, SDValue Chain,
7793                               SDValue Ptr, MachinePointerInfo PtrInfo,
7794                               MaybeAlign Alignment,
7795                               MachineMemOperand::Flags MMOFlags,
7796                               const AAMDNodes &AAInfo, const MDNode *Ranges) {
7797   SDValue Undef = getUNDEF(Ptr.getValueType());
7798   return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
7799                  PtrInfo, VT, Alignment, MMOFlags, AAInfo, Ranges);
7800 }
7801 
7802 SDValue SelectionDAG::getLoad(EVT VT, const SDLoc &dl, SDValue Chain,
7803                               SDValue Ptr, MachineMemOperand *MMO) {
7804   SDValue Undef = getUNDEF(Ptr.getValueType());
7805   return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
7806                  VT, MMO);
7807 }
7808 
7809 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl,
7810                                  EVT VT, SDValue Chain, SDValue Ptr,
7811                                  MachinePointerInfo PtrInfo, EVT MemVT,
7812                                  MaybeAlign Alignment,
7813                                  MachineMemOperand::Flags MMOFlags,
7814                                  const AAMDNodes &AAInfo) {
7815   SDValue Undef = getUNDEF(Ptr.getValueType());
7816   return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, PtrInfo,
7817                  MemVT, Alignment, MMOFlags, AAInfo);
7818 }
7819 
7820 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl,
7821                                  EVT VT, SDValue Chain, SDValue Ptr, EVT MemVT,
7822                                  MachineMemOperand *MMO) {
7823   SDValue Undef = getUNDEF(Ptr.getValueType());
7824   return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef,
7825                  MemVT, MMO);
7826 }
7827 
7828 SDValue SelectionDAG::getIndexedLoad(SDValue OrigLoad, const SDLoc &dl,
7829                                      SDValue Base, SDValue Offset,
7830                                      ISD::MemIndexedMode AM) {
7831   LoadSDNode *LD = cast<LoadSDNode>(OrigLoad);
7832   assert(LD->getOffset().isUndef() && "Load is already a indexed load!");
7833   // Don't propagate the invariant or dereferenceable flags.
7834   auto MMOFlags =
7835       LD->getMemOperand()->getFlags() &
7836       ~(MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable);
7837   return getLoad(AM, LD->getExtensionType(), OrigLoad.getValueType(), dl,
7838                  LD->getChain(), Base, Offset, LD->getPointerInfo(),
7839                  LD->getMemoryVT(), LD->getAlign(), MMOFlags, LD->getAAInfo());
7840 }
7841 
7842 SDValue SelectionDAG::getStore(SDValue Chain, const SDLoc &dl, SDValue Val,
7843                                SDValue Ptr, MachinePointerInfo PtrInfo,
7844                                Align Alignment,
7845                                MachineMemOperand::Flags MMOFlags,
7846                                const AAMDNodes &AAInfo) {
7847   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
7848 
7849   MMOFlags |= MachineMemOperand::MOStore;
7850   assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
7851 
7852   if (PtrInfo.V.isNull())
7853     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
7854 
7855   MachineFunction &MF = getMachineFunction();
7856   uint64_t Size =
7857       MemoryLocation::getSizeOrUnknown(Val.getValueType().getStoreSize());
7858   MachineMemOperand *MMO =
7859       MF.getMachineMemOperand(PtrInfo, MMOFlags, Size, Alignment, AAInfo);
7860   return getStore(Chain, dl, Val, Ptr, MMO);
7861 }
7862 
7863 SDValue SelectionDAG::getStore(SDValue Chain, const SDLoc &dl, SDValue Val,
7864                                SDValue Ptr, MachineMemOperand *MMO) {
7865   assert(Chain.getValueType() == MVT::Other &&
7866         "Invalid chain type");
7867   EVT VT = Val.getValueType();
7868   SDVTList VTs = getVTList(MVT::Other);
7869   SDValue Undef = getUNDEF(Ptr.getValueType());
7870   SDValue Ops[] = { Chain, Val, Ptr, Undef };
7871   FoldingSetNodeID ID;
7872   AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
7873   ID.AddInteger(VT.getRawBits());
7874   ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>(
7875       dl.getIROrder(), VTs, ISD::UNINDEXED, false, VT, MMO));
7876   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7877   ID.AddInteger(MMO->getFlags());
7878   void *IP = nullptr;
7879   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7880     cast<StoreSDNode>(E)->refineAlignment(MMO);
7881     return SDValue(E, 0);
7882   }
7883   auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
7884                                    ISD::UNINDEXED, false, VT, MMO);
7885   createOperands(N, Ops);
7886 
7887   CSEMap.InsertNode(N, IP);
7888   InsertNode(N);
7889   SDValue V(N, 0);
7890   NewSDValueDbgMsg(V, "Creating new node: ", this);
7891   return V;
7892 }
7893 
7894 SDValue SelectionDAG::getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val,
7895                                     SDValue Ptr, MachinePointerInfo PtrInfo,
7896                                     EVT SVT, Align Alignment,
7897                                     MachineMemOperand::Flags MMOFlags,
7898                                     const AAMDNodes &AAInfo) {
7899   assert(Chain.getValueType() == MVT::Other &&
7900         "Invalid chain type");
7901 
7902   MMOFlags |= MachineMemOperand::MOStore;
7903   assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
7904 
7905   if (PtrInfo.V.isNull())
7906     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
7907 
7908   MachineFunction &MF = getMachineFunction();
7909   MachineMemOperand *MMO = MF.getMachineMemOperand(
7910       PtrInfo, MMOFlags, MemoryLocation::getSizeOrUnknown(SVT.getStoreSize()),
7911       Alignment, AAInfo);
7912   return getTruncStore(Chain, dl, Val, Ptr, SVT, MMO);
7913 }
7914 
7915 SDValue SelectionDAG::getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val,
7916                                     SDValue Ptr, EVT SVT,
7917                                     MachineMemOperand *MMO) {
7918   EVT VT = Val.getValueType();
7919 
7920   assert(Chain.getValueType() == MVT::Other &&
7921         "Invalid chain type");
7922   if (VT == SVT)
7923     return getStore(Chain, dl, Val, Ptr, MMO);
7924 
7925   assert(SVT.getScalarType().bitsLT(VT.getScalarType()) &&
7926          "Should only be a truncating store, not extending!");
7927   assert(VT.isInteger() == SVT.isInteger() &&
7928          "Can't do FP-INT conversion!");
7929   assert(VT.isVector() == SVT.isVector() &&
7930          "Cannot use trunc store to convert to or from a vector!");
7931   assert((!VT.isVector() ||
7932           VT.getVectorElementCount() == SVT.getVectorElementCount()) &&
7933          "Cannot use trunc store to change the number of vector elements!");
7934 
7935   SDVTList VTs = getVTList(MVT::Other);
7936   SDValue Undef = getUNDEF(Ptr.getValueType());
7937   SDValue Ops[] = { Chain, Val, Ptr, Undef };
7938   FoldingSetNodeID ID;
7939   AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
7940   ID.AddInteger(SVT.getRawBits());
7941   ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>(
7942       dl.getIROrder(), VTs, ISD::UNINDEXED, true, SVT, MMO));
7943   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7944   ID.AddInteger(MMO->getFlags());
7945   void *IP = nullptr;
7946   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7947     cast<StoreSDNode>(E)->refineAlignment(MMO);
7948     return SDValue(E, 0);
7949   }
7950   auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
7951                                    ISD::UNINDEXED, true, SVT, MMO);
7952   createOperands(N, Ops);
7953 
7954   CSEMap.InsertNode(N, IP);
7955   InsertNode(N);
7956   SDValue V(N, 0);
7957   NewSDValueDbgMsg(V, "Creating new node: ", this);
7958   return V;
7959 }
7960 
7961 SDValue SelectionDAG::getIndexedStore(SDValue OrigStore, const SDLoc &dl,
7962                                       SDValue Base, SDValue Offset,
7963                                       ISD::MemIndexedMode AM) {
7964   StoreSDNode *ST = cast<StoreSDNode>(OrigStore);
7965   assert(ST->getOffset().isUndef() && "Store is already a indexed store!");
7966   SDVTList VTs = getVTList(Base.getValueType(), MVT::Other);
7967   SDValue Ops[] = { ST->getChain(), ST->getValue(), Base, Offset };
7968   FoldingSetNodeID ID;
7969   AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
7970   ID.AddInteger(ST->getMemoryVT().getRawBits());
7971   ID.AddInteger(ST->getRawSubclassData());
7972   ID.AddInteger(ST->getPointerInfo().getAddrSpace());
7973   ID.AddInteger(ST->getMemOperand()->getFlags());
7974   void *IP = nullptr;
7975   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
7976     return SDValue(E, 0);
7977 
7978   auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
7979                                    ST->isTruncatingStore(), ST->getMemoryVT(),
7980                                    ST->getMemOperand());
7981   createOperands(N, Ops);
7982 
7983   CSEMap.InsertNode(N, IP);
7984   InsertNode(N);
7985   SDValue V(N, 0);
7986   NewSDValueDbgMsg(V, "Creating new node: ", this);
7987   return V;
7988 }
7989 
7990 SDValue SelectionDAG::getLoadVP(
7991     ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, EVT VT, const SDLoc &dl,
7992     SDValue Chain, SDValue Ptr, SDValue Offset, SDValue Mask, SDValue EVL,
7993     MachinePointerInfo PtrInfo, EVT MemVT, Align Alignment,
7994     MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo,
7995     const MDNode *Ranges, bool IsExpanding) {
7996   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
7997 
7998   MMOFlags |= MachineMemOperand::MOLoad;
7999   assert((MMOFlags & MachineMemOperand::MOStore) == 0);
8000   // If we don't have a PtrInfo, infer the trivial frame index case to simplify
8001   // clients.
8002   if (PtrInfo.V.isNull())
8003     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr, Offset);
8004 
8005   uint64_t Size = MemoryLocation::getSizeOrUnknown(MemVT.getStoreSize());
8006   MachineFunction &MF = getMachineFunction();
8007   MachineMemOperand *MMO = MF.getMachineMemOperand(PtrInfo, MMOFlags, Size,
8008                                                    Alignment, AAInfo, Ranges);
8009   return getLoadVP(AM, ExtType, VT, dl, Chain, Ptr, Offset, Mask, EVL, MemVT,
8010                    MMO, IsExpanding);
8011 }
8012 
8013 SDValue SelectionDAG::getLoadVP(ISD::MemIndexedMode AM,
8014                                 ISD::LoadExtType ExtType, EVT VT,
8015                                 const SDLoc &dl, SDValue Chain, SDValue Ptr,
8016                                 SDValue Offset, SDValue Mask, SDValue EVL,
8017                                 EVT MemVT, MachineMemOperand *MMO,
8018                                 bool IsExpanding) {
8019   bool Indexed = AM != ISD::UNINDEXED;
8020   assert((Indexed || Offset.isUndef()) && "Unindexed load with an offset!");
8021 
8022   SDVTList VTs = Indexed ? getVTList(VT, Ptr.getValueType(), MVT::Other)
8023                          : getVTList(VT, MVT::Other);
8024   SDValue Ops[] = {Chain, Ptr, Offset, Mask, EVL};
8025   FoldingSetNodeID ID;
8026   AddNodeIDNode(ID, ISD::VP_LOAD, VTs, Ops);
8027   ID.AddInteger(VT.getRawBits());
8028   ID.AddInteger(getSyntheticNodeSubclassData<VPLoadSDNode>(
8029       dl.getIROrder(), VTs, AM, ExtType, IsExpanding, MemVT, MMO));
8030   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8031   ID.AddInteger(MMO->getFlags());
8032   void *IP = nullptr;
8033   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
8034     cast<VPLoadSDNode>(E)->refineAlignment(MMO);
8035     return SDValue(E, 0);
8036   }
8037   auto *N = newSDNode<VPLoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
8038                                     ExtType, IsExpanding, MemVT, MMO);
8039   createOperands(N, Ops);
8040 
8041   CSEMap.InsertNode(N, IP);
8042   InsertNode(N);
8043   SDValue V(N, 0);
8044   NewSDValueDbgMsg(V, "Creating new node: ", this);
8045   return V;
8046 }
8047 
8048 SDValue SelectionDAG::getLoadVP(EVT VT, const SDLoc &dl, SDValue Chain,
8049                                 SDValue Ptr, SDValue Mask, SDValue EVL,
8050                                 MachinePointerInfo PtrInfo,
8051                                 MaybeAlign Alignment,
8052                                 MachineMemOperand::Flags MMOFlags,
8053                                 const AAMDNodes &AAInfo, const MDNode *Ranges,
8054                                 bool IsExpanding) {
8055   SDValue Undef = getUNDEF(Ptr.getValueType());
8056   return getLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
8057                    Mask, EVL, PtrInfo, VT, Alignment, MMOFlags, AAInfo, Ranges,
8058                    IsExpanding);
8059 }
8060 
8061 SDValue SelectionDAG::getLoadVP(EVT VT, const SDLoc &dl, SDValue Chain,
8062                                 SDValue Ptr, SDValue Mask, SDValue EVL,
8063                                 MachineMemOperand *MMO, bool IsExpanding) {
8064   SDValue Undef = getUNDEF(Ptr.getValueType());
8065   return getLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
8066                    Mask, EVL, VT, MMO, IsExpanding);
8067 }
8068 
8069 SDValue SelectionDAG::getExtLoadVP(ISD::LoadExtType ExtType, const SDLoc &dl,
8070                                    EVT VT, SDValue Chain, SDValue Ptr,
8071                                    SDValue Mask, SDValue EVL,
8072                                    MachinePointerInfo PtrInfo, EVT MemVT,
8073                                    MaybeAlign Alignment,
8074                                    MachineMemOperand::Flags MMOFlags,
8075                                    const AAMDNodes &AAInfo, bool IsExpanding) {
8076   SDValue Undef = getUNDEF(Ptr.getValueType());
8077   return getLoadVP(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, Mask,
8078                    EVL, PtrInfo, MemVT, Alignment, MMOFlags, AAInfo, nullptr,
8079                    IsExpanding);
8080 }
8081 
8082 SDValue SelectionDAG::getExtLoadVP(ISD::LoadExtType ExtType, const SDLoc &dl,
8083                                    EVT VT, SDValue Chain, SDValue Ptr,
8084                                    SDValue Mask, SDValue EVL, EVT MemVT,
8085                                    MachineMemOperand *MMO, bool IsExpanding) {
8086   SDValue Undef = getUNDEF(Ptr.getValueType());
8087   return getLoadVP(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, Mask,
8088                    EVL, MemVT, MMO, IsExpanding);
8089 }
8090 
8091 SDValue SelectionDAG::getIndexedLoadVP(SDValue OrigLoad, const SDLoc &dl,
8092                                        SDValue Base, SDValue Offset,
8093                                        ISD::MemIndexedMode AM) {
8094   auto *LD = cast<VPLoadSDNode>(OrigLoad);
8095   assert(LD->getOffset().isUndef() && "Load is already a indexed load!");
8096   // Don't propagate the invariant or dereferenceable flags.
8097   auto MMOFlags =
8098       LD->getMemOperand()->getFlags() &
8099       ~(MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable);
8100   return getLoadVP(AM, LD->getExtensionType(), OrigLoad.getValueType(), dl,
8101                    LD->getChain(), Base, Offset, LD->getMask(),
8102                    LD->getVectorLength(), LD->getPointerInfo(),
8103                    LD->getMemoryVT(), LD->getAlign(), MMOFlags, LD->getAAInfo(),
8104                    nullptr, LD->isExpandingLoad());
8105 }
8106 
8107 SDValue SelectionDAG::getStoreVP(SDValue Chain, const SDLoc &dl, SDValue Val,
8108                                  SDValue Ptr, SDValue Offset, SDValue Mask,
8109                                  SDValue EVL, EVT MemVT, MachineMemOperand *MMO,
8110                                  ISD::MemIndexedMode AM, bool IsTruncating,
8111                                  bool IsCompressing) {
8112   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
8113   bool Indexed = AM != ISD::UNINDEXED;
8114   assert((Indexed || Offset.isUndef()) && "Unindexed vp_store with an offset!");
8115   SDVTList VTs = Indexed ? getVTList(Ptr.getValueType(), MVT::Other)
8116                          : getVTList(MVT::Other);
8117   SDValue Ops[] = {Chain, Val, Ptr, Offset, Mask, EVL};
8118   FoldingSetNodeID ID;
8119   AddNodeIDNode(ID, ISD::VP_STORE, VTs, Ops);
8120   ID.AddInteger(MemVT.getRawBits());
8121   ID.AddInteger(getSyntheticNodeSubclassData<VPStoreSDNode>(
8122       dl.getIROrder(), VTs, AM, IsTruncating, IsCompressing, MemVT, MMO));
8123   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8124   ID.AddInteger(MMO->getFlags());
8125   void *IP = nullptr;
8126   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
8127     cast<VPStoreSDNode>(E)->refineAlignment(MMO);
8128     return SDValue(E, 0);
8129   }
8130   auto *N = newSDNode<VPStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
8131                                      IsTruncating, IsCompressing, MemVT, MMO);
8132   createOperands(N, Ops);
8133 
8134   CSEMap.InsertNode(N, IP);
8135   InsertNode(N);
8136   SDValue V(N, 0);
8137   NewSDValueDbgMsg(V, "Creating new node: ", this);
8138   return V;
8139 }
8140 
8141 SDValue SelectionDAG::getTruncStoreVP(SDValue Chain, const SDLoc &dl,
8142                                       SDValue Val, SDValue Ptr, SDValue Mask,
8143                                       SDValue EVL, MachinePointerInfo PtrInfo,
8144                                       EVT SVT, Align Alignment,
8145                                       MachineMemOperand::Flags MMOFlags,
8146                                       const AAMDNodes &AAInfo,
8147                                       bool IsCompressing) {
8148   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
8149 
8150   MMOFlags |= MachineMemOperand::MOStore;
8151   assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
8152 
8153   if (PtrInfo.V.isNull())
8154     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
8155 
8156   MachineFunction &MF = getMachineFunction();
8157   MachineMemOperand *MMO = MF.getMachineMemOperand(
8158       PtrInfo, MMOFlags, MemoryLocation::getSizeOrUnknown(SVT.getStoreSize()),
8159       Alignment, AAInfo);
8160   return getTruncStoreVP(Chain, dl, Val, Ptr, Mask, EVL, SVT, MMO,
8161                          IsCompressing);
8162 }
8163 
8164 SDValue SelectionDAG::getTruncStoreVP(SDValue Chain, const SDLoc &dl,
8165                                       SDValue Val, SDValue Ptr, SDValue Mask,
8166                                       SDValue EVL, EVT SVT,
8167                                       MachineMemOperand *MMO,
8168                                       bool IsCompressing) {
8169   EVT VT = Val.getValueType();
8170 
8171   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
8172   if (VT == SVT)
8173     return getStoreVP(Chain, dl, Val, Ptr, getUNDEF(Ptr.getValueType()), Mask,
8174                       EVL, VT, MMO, ISD::UNINDEXED,
8175                       /*IsTruncating*/ false, IsCompressing);
8176 
8177   assert(SVT.getScalarType().bitsLT(VT.getScalarType()) &&
8178          "Should only be a truncating store, not extending!");
8179   assert(VT.isInteger() == SVT.isInteger() && "Can't do FP-INT conversion!");
8180   assert(VT.isVector() == SVT.isVector() &&
8181          "Cannot use trunc store to convert to or from a vector!");
8182   assert((!VT.isVector() ||
8183           VT.getVectorElementCount() == SVT.getVectorElementCount()) &&
8184          "Cannot use trunc store to change the number of vector elements!");
8185 
8186   SDVTList VTs = getVTList(MVT::Other);
8187   SDValue Undef = getUNDEF(Ptr.getValueType());
8188   SDValue Ops[] = {Chain, Val, Ptr, Undef, Mask, EVL};
8189   FoldingSetNodeID ID;
8190   AddNodeIDNode(ID, ISD::VP_STORE, VTs, Ops);
8191   ID.AddInteger(SVT.getRawBits());
8192   ID.AddInteger(getSyntheticNodeSubclassData<VPStoreSDNode>(
8193       dl.getIROrder(), VTs, ISD::UNINDEXED, true, IsCompressing, SVT, MMO));
8194   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8195   ID.AddInteger(MMO->getFlags());
8196   void *IP = nullptr;
8197   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
8198     cast<VPStoreSDNode>(E)->refineAlignment(MMO);
8199     return SDValue(E, 0);
8200   }
8201   auto *N =
8202       newSDNode<VPStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
8203                                ISD::UNINDEXED, true, IsCompressing, SVT, MMO);
8204   createOperands(N, Ops);
8205 
8206   CSEMap.InsertNode(N, IP);
8207   InsertNode(N);
8208   SDValue V(N, 0);
8209   NewSDValueDbgMsg(V, "Creating new node: ", this);
8210   return V;
8211 }
8212 
8213 SDValue SelectionDAG::getIndexedStoreVP(SDValue OrigStore, const SDLoc &dl,
8214                                         SDValue Base, SDValue Offset,
8215                                         ISD::MemIndexedMode AM) {
8216   auto *ST = cast<VPStoreSDNode>(OrigStore);
8217   assert(ST->getOffset().isUndef() && "Store is already an indexed store!");
8218   SDVTList VTs = getVTList(Base.getValueType(), MVT::Other);
8219   SDValue Ops[] = {ST->getChain(), ST->getValue(), Base,
8220                    Offset,         ST->getMask(),  ST->getVectorLength()};
8221   FoldingSetNodeID ID;
8222   AddNodeIDNode(ID, ISD::VP_STORE, VTs, Ops);
8223   ID.AddInteger(ST->getMemoryVT().getRawBits());
8224   ID.AddInteger(ST->getRawSubclassData());
8225   ID.AddInteger(ST->getPointerInfo().getAddrSpace());
8226   ID.AddInteger(ST->getMemOperand()->getFlags());
8227   void *IP = nullptr;
8228   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
8229     return SDValue(E, 0);
8230 
8231   auto *N = newSDNode<VPStoreSDNode>(
8232       dl.getIROrder(), dl.getDebugLoc(), VTs, AM, ST->isTruncatingStore(),
8233       ST->isCompressingStore(), ST->getMemoryVT(), ST->getMemOperand());
8234   createOperands(N, Ops);
8235 
8236   CSEMap.InsertNode(N, IP);
8237   InsertNode(N);
8238   SDValue V(N, 0);
8239   NewSDValueDbgMsg(V, "Creating new node: ", this);
8240   return V;
8241 }
8242 
8243 SDValue SelectionDAG::getStridedLoadVP(
8244     ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, EVT VT, const SDLoc &DL,
8245     SDValue Chain, SDValue Ptr, SDValue Offset, SDValue Stride, SDValue Mask,
8246     SDValue EVL, MachinePointerInfo PtrInfo, EVT MemVT, Align Alignment,
8247     MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo,
8248     const MDNode *Ranges, bool IsExpanding) {
8249   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
8250 
8251   MMOFlags |= MachineMemOperand::MOLoad;
8252   assert((MMOFlags & MachineMemOperand::MOStore) == 0);
8253   // If we don't have a PtrInfo, infer the trivial frame index case to simplify
8254   // clients.
8255   if (PtrInfo.V.isNull())
8256     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr, Offset);
8257 
8258   uint64_t Size = MemoryLocation::UnknownSize;
8259   MachineFunction &MF = getMachineFunction();
8260   MachineMemOperand *MMO = MF.getMachineMemOperand(PtrInfo, MMOFlags, Size,
8261                                                    Alignment, AAInfo, Ranges);
8262   return getStridedLoadVP(AM, ExtType, VT, DL, Chain, Ptr, Offset, Stride, Mask,
8263                           EVL, MemVT, MMO, IsExpanding);
8264 }
8265 
8266 SDValue SelectionDAG::getStridedLoadVP(
8267     ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, EVT VT, const SDLoc &DL,
8268     SDValue Chain, SDValue Ptr, SDValue Offset, SDValue Stride, SDValue Mask,
8269     SDValue EVL, EVT MemVT, MachineMemOperand *MMO, bool IsExpanding) {
8270   bool Indexed = AM != ISD::UNINDEXED;
8271   assert((Indexed || Offset.isUndef()) && "Unindexed load with an offset!");
8272 
8273   SDValue Ops[] = {Chain, Ptr, Offset, Stride, Mask, EVL};
8274   SDVTList VTs = Indexed ? getVTList(VT, Ptr.getValueType(), MVT::Other)
8275                          : getVTList(VT, MVT::Other);
8276   FoldingSetNodeID ID;
8277   AddNodeIDNode(ID, ISD::EXPERIMENTAL_VP_STRIDED_LOAD, VTs, Ops);
8278   ID.AddInteger(VT.getRawBits());
8279   ID.AddInteger(getSyntheticNodeSubclassData<VPStridedLoadSDNode>(
8280       DL.getIROrder(), VTs, AM, ExtType, IsExpanding, MemVT, MMO));
8281   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8282 
8283   void *IP = nullptr;
8284   if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
8285     cast<VPStridedLoadSDNode>(E)->refineAlignment(MMO);
8286     return SDValue(E, 0);
8287   }
8288 
8289   auto *N =
8290       newSDNode<VPStridedLoadSDNode>(DL.getIROrder(), DL.getDebugLoc(), VTs, AM,
8291                                      ExtType, IsExpanding, MemVT, MMO);
8292   createOperands(N, Ops);
8293   CSEMap.InsertNode(N, IP);
8294   InsertNode(N);
8295   SDValue V(N, 0);
8296   NewSDValueDbgMsg(V, "Creating new node: ", this);
8297   return V;
8298 }
8299 
8300 SDValue SelectionDAG::getStridedLoadVP(
8301     EVT VT, const SDLoc &DL, SDValue Chain, SDValue Ptr, SDValue Stride,
8302     SDValue Mask, SDValue EVL, MachinePointerInfo PtrInfo, MaybeAlign Alignment,
8303     MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo,
8304     const MDNode *Ranges, 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, PtrInfo, VT, Alignment,
8308                           MMOFlags, AAInfo, Ranges, IsExpanding);
8309 }
8310 
8311 SDValue SelectionDAG::getStridedLoadVP(EVT VT, const SDLoc &DL, SDValue Chain,
8312                                        SDValue Ptr, SDValue Stride,
8313                                        SDValue Mask, SDValue EVL,
8314                                        MachineMemOperand *MMO,
8315                                        bool IsExpanding) {
8316   SDValue Undef = getUNDEF(Ptr.getValueType());
8317   return getStridedLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, DL, Chain, Ptr,
8318                           Undef, Stride, Mask, EVL, VT, MMO, IsExpanding);
8319 }
8320 
8321 SDValue SelectionDAG::getExtStridedLoadVP(
8322     ISD::LoadExtType ExtType, const SDLoc &DL, EVT VT, SDValue Chain,
8323     SDValue Ptr, SDValue Stride, SDValue Mask, SDValue EVL,
8324     MachinePointerInfo PtrInfo, EVT MemVT, MaybeAlign Alignment,
8325     MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo,
8326     bool IsExpanding) {
8327   SDValue Undef = getUNDEF(Ptr.getValueType());
8328   return getStridedLoadVP(ISD::UNINDEXED, ExtType, VT, DL, Chain, Ptr, Undef,
8329                           Stride, Mask, EVL, PtrInfo, MemVT, Alignment,
8330                           MMOFlags, AAInfo, nullptr, IsExpanding);
8331 }
8332 
8333 SDValue SelectionDAG::getExtStridedLoadVP(
8334     ISD::LoadExtType ExtType, const SDLoc &DL, EVT VT, SDValue Chain,
8335     SDValue Ptr, SDValue Stride, SDValue Mask, SDValue EVL, EVT MemVT,
8336     MachineMemOperand *MMO, bool IsExpanding) {
8337   SDValue Undef = getUNDEF(Ptr.getValueType());
8338   return getStridedLoadVP(ISD::UNINDEXED, ExtType, VT, DL, Chain, Ptr, Undef,
8339                           Stride, Mask, EVL, MemVT, MMO, IsExpanding);
8340 }
8341 
8342 SDValue SelectionDAG::getIndexedStridedLoadVP(SDValue OrigLoad, const SDLoc &DL,
8343                                               SDValue Base, SDValue Offset,
8344                                               ISD::MemIndexedMode AM) {
8345   auto *SLD = cast<VPStridedLoadSDNode>(OrigLoad);
8346   assert(SLD->getOffset().isUndef() &&
8347          "Strided load is already a indexed load!");
8348   // Don't propagate the invariant or dereferenceable flags.
8349   auto MMOFlags =
8350       SLD->getMemOperand()->getFlags() &
8351       ~(MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable);
8352   return getStridedLoadVP(
8353       AM, SLD->getExtensionType(), OrigLoad.getValueType(), DL, SLD->getChain(),
8354       Base, Offset, SLD->getStride(), SLD->getMask(), SLD->getVectorLength(),
8355       SLD->getPointerInfo(), SLD->getMemoryVT(), SLD->getAlign(), MMOFlags,
8356       SLD->getAAInfo(), nullptr, SLD->isExpandingLoad());
8357 }
8358 
8359 SDValue SelectionDAG::getStridedStoreVP(SDValue Chain, const SDLoc &DL,
8360                                         SDValue Val, SDValue Ptr,
8361                                         SDValue Offset, SDValue Stride,
8362                                         SDValue Mask, SDValue EVL, EVT MemVT,
8363                                         MachineMemOperand *MMO,
8364                                         ISD::MemIndexedMode AM,
8365                                         bool IsTruncating, bool IsCompressing) {
8366   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
8367   bool Indexed = AM != ISD::UNINDEXED;
8368   assert((Indexed || Offset.isUndef()) && "Unindexed vp_store with an offset!");
8369   SDVTList VTs = Indexed ? getVTList(Ptr.getValueType(), MVT::Other)
8370                          : getVTList(MVT::Other);
8371   SDValue Ops[] = {Chain, Val, Ptr, Offset, Stride, Mask, EVL};
8372   FoldingSetNodeID ID;
8373   AddNodeIDNode(ID, ISD::EXPERIMENTAL_VP_STRIDED_STORE, VTs, Ops);
8374   ID.AddInteger(MemVT.getRawBits());
8375   ID.AddInteger(getSyntheticNodeSubclassData<VPStridedStoreSDNode>(
8376       DL.getIROrder(), VTs, AM, IsTruncating, IsCompressing, MemVT, MMO));
8377   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8378   void *IP = nullptr;
8379   if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
8380     cast<VPStridedStoreSDNode>(E)->refineAlignment(MMO);
8381     return SDValue(E, 0);
8382   }
8383   auto *N = newSDNode<VPStridedStoreSDNode>(DL.getIROrder(), DL.getDebugLoc(),
8384                                             VTs, AM, IsTruncating,
8385                                             IsCompressing, MemVT, MMO);
8386   createOperands(N, Ops);
8387 
8388   CSEMap.InsertNode(N, IP);
8389   InsertNode(N);
8390   SDValue V(N, 0);
8391   NewSDValueDbgMsg(V, "Creating new node: ", this);
8392   return V;
8393 }
8394 
8395 SDValue SelectionDAG::getTruncStridedStoreVP(
8396     SDValue Chain, const SDLoc &DL, SDValue Val, SDValue Ptr, SDValue Stride,
8397     SDValue Mask, SDValue EVL, MachinePointerInfo PtrInfo, EVT SVT,
8398     Align Alignment, MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo,
8399     bool IsCompressing) {
8400   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
8401 
8402   MMOFlags |= MachineMemOperand::MOStore;
8403   assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
8404 
8405   if (PtrInfo.V.isNull())
8406     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
8407 
8408   MachineFunction &MF = getMachineFunction();
8409   MachineMemOperand *MMO = MF.getMachineMemOperand(
8410       PtrInfo, MMOFlags, MemoryLocation::UnknownSize, Alignment, AAInfo);
8411   return getTruncStridedStoreVP(Chain, DL, Val, Ptr, Stride, Mask, EVL, SVT,
8412                                 MMO, IsCompressing);
8413 }
8414 
8415 SDValue SelectionDAG::getTruncStridedStoreVP(SDValue Chain, const SDLoc &DL,
8416                                              SDValue Val, SDValue Ptr,
8417                                              SDValue Stride, SDValue Mask,
8418                                              SDValue EVL, EVT SVT,
8419                                              MachineMemOperand *MMO,
8420                                              bool IsCompressing) {
8421   EVT VT = Val.getValueType();
8422 
8423   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
8424   if (VT == SVT)
8425     return getStridedStoreVP(Chain, DL, Val, Ptr, getUNDEF(Ptr.getValueType()),
8426                              Stride, Mask, EVL, VT, MMO, ISD::UNINDEXED,
8427                              /*IsTruncating*/ false, IsCompressing);
8428 
8429   assert(SVT.getScalarType().bitsLT(VT.getScalarType()) &&
8430          "Should only be a truncating store, not extending!");
8431   assert(VT.isInteger() == SVT.isInteger() && "Can't do FP-INT conversion!");
8432   assert(VT.isVector() == SVT.isVector() &&
8433          "Cannot use trunc store to convert to or from a vector!");
8434   assert((!VT.isVector() ||
8435           VT.getVectorElementCount() == SVT.getVectorElementCount()) &&
8436          "Cannot use trunc store to change the number of vector elements!");
8437 
8438   SDVTList VTs = getVTList(MVT::Other);
8439   SDValue Undef = getUNDEF(Ptr.getValueType());
8440   SDValue Ops[] = {Chain, Val, Ptr, Undef, Stride, Mask, EVL};
8441   FoldingSetNodeID ID;
8442   AddNodeIDNode(ID, ISD::EXPERIMENTAL_VP_STRIDED_STORE, VTs, Ops);
8443   ID.AddInteger(SVT.getRawBits());
8444   ID.AddInteger(getSyntheticNodeSubclassData<VPStridedStoreSDNode>(
8445       DL.getIROrder(), VTs, ISD::UNINDEXED, true, IsCompressing, SVT, MMO));
8446   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8447   void *IP = nullptr;
8448   if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
8449     cast<VPStridedStoreSDNode>(E)->refineAlignment(MMO);
8450     return SDValue(E, 0);
8451   }
8452   auto *N = newSDNode<VPStridedStoreSDNode>(DL.getIROrder(), DL.getDebugLoc(),
8453                                             VTs, ISD::UNINDEXED, true,
8454                                             IsCompressing, SVT, MMO);
8455   createOperands(N, Ops);
8456 
8457   CSEMap.InsertNode(N, IP);
8458   InsertNode(N);
8459   SDValue V(N, 0);
8460   NewSDValueDbgMsg(V, "Creating new node: ", this);
8461   return V;
8462 }
8463 
8464 SDValue SelectionDAG::getIndexedStridedStoreVP(SDValue OrigStore,
8465                                                const SDLoc &DL, SDValue Base,
8466                                                SDValue Offset,
8467                                                ISD::MemIndexedMode AM) {
8468   auto *SST = cast<VPStridedStoreSDNode>(OrigStore);
8469   assert(SST->getOffset().isUndef() &&
8470          "Strided store is already an indexed store!");
8471   SDVTList VTs = getVTList(Base.getValueType(), MVT::Other);
8472   SDValue Ops[] = {
8473       SST->getChain(), SST->getValue(),       Base, Offset, SST->getStride(),
8474       SST->getMask(),  SST->getVectorLength()};
8475   FoldingSetNodeID ID;
8476   AddNodeIDNode(ID, ISD::EXPERIMENTAL_VP_STRIDED_STORE, VTs, Ops);
8477   ID.AddInteger(SST->getMemoryVT().getRawBits());
8478   ID.AddInteger(SST->getRawSubclassData());
8479   ID.AddInteger(SST->getPointerInfo().getAddrSpace());
8480   void *IP = nullptr;
8481   if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
8482     return SDValue(E, 0);
8483 
8484   auto *N = newSDNode<VPStridedStoreSDNode>(
8485       DL.getIROrder(), DL.getDebugLoc(), VTs, AM, SST->isTruncatingStore(),
8486       SST->isCompressingStore(), SST->getMemoryVT(), SST->getMemOperand());
8487   createOperands(N, Ops);
8488 
8489   CSEMap.InsertNode(N, IP);
8490   InsertNode(N);
8491   SDValue V(N, 0);
8492   NewSDValueDbgMsg(V, "Creating new node: ", this);
8493   return V;
8494 }
8495 
8496 SDValue SelectionDAG::getGatherVP(SDVTList VTs, EVT VT, const SDLoc &dl,
8497                                   ArrayRef<SDValue> Ops, MachineMemOperand *MMO,
8498                                   ISD::MemIndexType IndexType) {
8499   assert(Ops.size() == 6 && "Incompatible number of operands");
8500 
8501   FoldingSetNodeID ID;
8502   AddNodeIDNode(ID, ISD::VP_GATHER, VTs, Ops);
8503   ID.AddInteger(VT.getRawBits());
8504   ID.AddInteger(getSyntheticNodeSubclassData<VPGatherSDNode>(
8505       dl.getIROrder(), VTs, VT, MMO, IndexType));
8506   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8507   ID.AddInteger(MMO->getFlags());
8508   void *IP = nullptr;
8509   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
8510     cast<VPGatherSDNode>(E)->refineAlignment(MMO);
8511     return SDValue(E, 0);
8512   }
8513 
8514   auto *N = newSDNode<VPGatherSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
8515                                       VT, MMO, IndexType);
8516   createOperands(N, Ops);
8517 
8518   assert(N->getMask().getValueType().getVectorElementCount() ==
8519              N->getValueType(0).getVectorElementCount() &&
8520          "Vector width mismatch between mask and data");
8521   assert(N->getIndex().getValueType().getVectorElementCount().isScalable() ==
8522              N->getValueType(0).getVectorElementCount().isScalable() &&
8523          "Scalable flags of index and data do not match");
8524   assert(ElementCount::isKnownGE(
8525              N->getIndex().getValueType().getVectorElementCount(),
8526              N->getValueType(0).getVectorElementCount()) &&
8527          "Vector width mismatch between index and data");
8528   assert(isa<ConstantSDNode>(N->getScale()) &&
8529          cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() &&
8530          "Scale should be a constant power of 2");
8531 
8532   CSEMap.InsertNode(N, IP);
8533   InsertNode(N);
8534   SDValue V(N, 0);
8535   NewSDValueDbgMsg(V, "Creating new node: ", this);
8536   return V;
8537 }
8538 
8539 SDValue SelectionDAG::getScatterVP(SDVTList VTs, EVT VT, const SDLoc &dl,
8540                                    ArrayRef<SDValue> Ops,
8541                                    MachineMemOperand *MMO,
8542                                    ISD::MemIndexType IndexType) {
8543   assert(Ops.size() == 7 && "Incompatible number of operands");
8544 
8545   FoldingSetNodeID ID;
8546   AddNodeIDNode(ID, ISD::VP_SCATTER, VTs, Ops);
8547   ID.AddInteger(VT.getRawBits());
8548   ID.AddInteger(getSyntheticNodeSubclassData<VPScatterSDNode>(
8549       dl.getIROrder(), VTs, VT, MMO, IndexType));
8550   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8551   ID.AddInteger(MMO->getFlags());
8552   void *IP = nullptr;
8553   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
8554     cast<VPScatterSDNode>(E)->refineAlignment(MMO);
8555     return SDValue(E, 0);
8556   }
8557   auto *N = newSDNode<VPScatterSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
8558                                        VT, MMO, IndexType);
8559   createOperands(N, Ops);
8560 
8561   assert(N->getMask().getValueType().getVectorElementCount() ==
8562              N->getValue().getValueType().getVectorElementCount() &&
8563          "Vector width mismatch between mask and data");
8564   assert(
8565       N->getIndex().getValueType().getVectorElementCount().isScalable() ==
8566           N->getValue().getValueType().getVectorElementCount().isScalable() &&
8567       "Scalable flags of index and data do not match");
8568   assert(ElementCount::isKnownGE(
8569              N->getIndex().getValueType().getVectorElementCount(),
8570              N->getValue().getValueType().getVectorElementCount()) &&
8571          "Vector width mismatch between index and data");
8572   assert(isa<ConstantSDNode>(N->getScale()) &&
8573          cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() &&
8574          "Scale should be a constant power of 2");
8575 
8576   CSEMap.InsertNode(N, IP);
8577   InsertNode(N);
8578   SDValue V(N, 0);
8579   NewSDValueDbgMsg(V, "Creating new node: ", this);
8580   return V;
8581 }
8582 
8583 SDValue SelectionDAG::getMaskedLoad(EVT VT, const SDLoc &dl, SDValue Chain,
8584                                     SDValue Base, SDValue Offset, SDValue Mask,
8585                                     SDValue PassThru, EVT MemVT,
8586                                     MachineMemOperand *MMO,
8587                                     ISD::MemIndexedMode AM,
8588                                     ISD::LoadExtType ExtTy, bool isExpanding) {
8589   bool Indexed = AM != ISD::UNINDEXED;
8590   assert((Indexed || Offset.isUndef()) &&
8591          "Unindexed masked load with an offset!");
8592   SDVTList VTs = Indexed ? getVTList(VT, Base.getValueType(), MVT::Other)
8593                          : getVTList(VT, MVT::Other);
8594   SDValue Ops[] = {Chain, Base, Offset, Mask, PassThru};
8595   FoldingSetNodeID ID;
8596   AddNodeIDNode(ID, ISD::MLOAD, VTs, Ops);
8597   ID.AddInteger(MemVT.getRawBits());
8598   ID.AddInteger(getSyntheticNodeSubclassData<MaskedLoadSDNode>(
8599       dl.getIROrder(), VTs, AM, ExtTy, isExpanding, MemVT, MMO));
8600   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8601   ID.AddInteger(MMO->getFlags());
8602   void *IP = nullptr;
8603   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
8604     cast<MaskedLoadSDNode>(E)->refineAlignment(MMO);
8605     return SDValue(E, 0);
8606   }
8607   auto *N = newSDNode<MaskedLoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
8608                                         AM, ExtTy, isExpanding, MemVT, MMO);
8609   createOperands(N, Ops);
8610 
8611   CSEMap.InsertNode(N, IP);
8612   InsertNode(N);
8613   SDValue V(N, 0);
8614   NewSDValueDbgMsg(V, "Creating new node: ", this);
8615   return V;
8616 }
8617 
8618 SDValue SelectionDAG::getIndexedMaskedLoad(SDValue OrigLoad, const SDLoc &dl,
8619                                            SDValue Base, SDValue Offset,
8620                                            ISD::MemIndexedMode AM) {
8621   MaskedLoadSDNode *LD = cast<MaskedLoadSDNode>(OrigLoad);
8622   assert(LD->getOffset().isUndef() && "Masked load is already a indexed load!");
8623   return getMaskedLoad(OrigLoad.getValueType(), dl, LD->getChain(), Base,
8624                        Offset, LD->getMask(), LD->getPassThru(),
8625                        LD->getMemoryVT(), LD->getMemOperand(), AM,
8626                        LD->getExtensionType(), LD->isExpandingLoad());
8627 }
8628 
8629 SDValue SelectionDAG::getMaskedStore(SDValue Chain, const SDLoc &dl,
8630                                      SDValue Val, SDValue Base, SDValue Offset,
8631                                      SDValue Mask, EVT MemVT,
8632                                      MachineMemOperand *MMO,
8633                                      ISD::MemIndexedMode AM, bool IsTruncating,
8634                                      bool IsCompressing) {
8635   assert(Chain.getValueType() == MVT::Other &&
8636         "Invalid chain type");
8637   bool Indexed = AM != ISD::UNINDEXED;
8638   assert((Indexed || Offset.isUndef()) &&
8639          "Unindexed masked store with an offset!");
8640   SDVTList VTs = Indexed ? getVTList(Base.getValueType(), MVT::Other)
8641                          : getVTList(MVT::Other);
8642   SDValue Ops[] = {Chain, Val, Base, Offset, Mask};
8643   FoldingSetNodeID ID;
8644   AddNodeIDNode(ID, ISD::MSTORE, VTs, Ops);
8645   ID.AddInteger(MemVT.getRawBits());
8646   ID.AddInteger(getSyntheticNodeSubclassData<MaskedStoreSDNode>(
8647       dl.getIROrder(), VTs, AM, IsTruncating, IsCompressing, MemVT, MMO));
8648   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8649   ID.AddInteger(MMO->getFlags());
8650   void *IP = nullptr;
8651   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
8652     cast<MaskedStoreSDNode>(E)->refineAlignment(MMO);
8653     return SDValue(E, 0);
8654   }
8655   auto *N =
8656       newSDNode<MaskedStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
8657                                    IsTruncating, IsCompressing, MemVT, MMO);
8658   createOperands(N, Ops);
8659 
8660   CSEMap.InsertNode(N, IP);
8661   InsertNode(N);
8662   SDValue V(N, 0);
8663   NewSDValueDbgMsg(V, "Creating new node: ", this);
8664   return V;
8665 }
8666 
8667 SDValue SelectionDAG::getIndexedMaskedStore(SDValue OrigStore, const SDLoc &dl,
8668                                             SDValue Base, SDValue Offset,
8669                                             ISD::MemIndexedMode AM) {
8670   MaskedStoreSDNode *ST = cast<MaskedStoreSDNode>(OrigStore);
8671   assert(ST->getOffset().isUndef() &&
8672          "Masked store is already a indexed store!");
8673   return getMaskedStore(ST->getChain(), dl, ST->getValue(), Base, Offset,
8674                         ST->getMask(), ST->getMemoryVT(), ST->getMemOperand(),
8675                         AM, ST->isTruncatingStore(), ST->isCompressingStore());
8676 }
8677 
8678 SDValue SelectionDAG::getMaskedGather(SDVTList VTs, EVT MemVT, const SDLoc &dl,
8679                                       ArrayRef<SDValue> Ops,
8680                                       MachineMemOperand *MMO,
8681                                       ISD::MemIndexType IndexType,
8682                                       ISD::LoadExtType ExtTy) {
8683   assert(Ops.size() == 6 && "Incompatible number of operands");
8684 
8685   FoldingSetNodeID ID;
8686   AddNodeIDNode(ID, ISD::MGATHER, VTs, Ops);
8687   ID.AddInteger(MemVT.getRawBits());
8688   ID.AddInteger(getSyntheticNodeSubclassData<MaskedGatherSDNode>(
8689       dl.getIROrder(), VTs, MemVT, MMO, IndexType, ExtTy));
8690   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8691   ID.AddInteger(MMO->getFlags());
8692   void *IP = nullptr;
8693   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
8694     cast<MaskedGatherSDNode>(E)->refineAlignment(MMO);
8695     return SDValue(E, 0);
8696   }
8697 
8698   auto *N = newSDNode<MaskedGatherSDNode>(dl.getIROrder(), dl.getDebugLoc(),
8699                                           VTs, MemVT, MMO, IndexType, ExtTy);
8700   createOperands(N, Ops);
8701 
8702   assert(N->getPassThru().getValueType() == N->getValueType(0) &&
8703          "Incompatible type of the PassThru value in MaskedGatherSDNode");
8704   assert(N->getMask().getValueType().getVectorElementCount() ==
8705              N->getValueType(0).getVectorElementCount() &&
8706          "Vector width mismatch between mask and data");
8707   assert(N->getIndex().getValueType().getVectorElementCount().isScalable() ==
8708              N->getValueType(0).getVectorElementCount().isScalable() &&
8709          "Scalable flags of index and data do not match");
8710   assert(ElementCount::isKnownGE(
8711              N->getIndex().getValueType().getVectorElementCount(),
8712              N->getValueType(0).getVectorElementCount()) &&
8713          "Vector width mismatch between index and data");
8714   assert(isa<ConstantSDNode>(N->getScale()) &&
8715          cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() &&
8716          "Scale should be a constant power of 2");
8717 
8718   CSEMap.InsertNode(N, IP);
8719   InsertNode(N);
8720   SDValue V(N, 0);
8721   NewSDValueDbgMsg(V, "Creating new node: ", this);
8722   return V;
8723 }
8724 
8725 SDValue SelectionDAG::getMaskedScatter(SDVTList VTs, EVT MemVT, const SDLoc &dl,
8726                                        ArrayRef<SDValue> Ops,
8727                                        MachineMemOperand *MMO,
8728                                        ISD::MemIndexType IndexType,
8729                                        bool IsTrunc) {
8730   assert(Ops.size() == 6 && "Incompatible number of operands");
8731 
8732   FoldingSetNodeID ID;
8733   AddNodeIDNode(ID, ISD::MSCATTER, VTs, Ops);
8734   ID.AddInteger(MemVT.getRawBits());
8735   ID.AddInteger(getSyntheticNodeSubclassData<MaskedScatterSDNode>(
8736       dl.getIROrder(), VTs, MemVT, MMO, IndexType, IsTrunc));
8737   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8738   ID.AddInteger(MMO->getFlags());
8739   void *IP = nullptr;
8740   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
8741     cast<MaskedScatterSDNode>(E)->refineAlignment(MMO);
8742     return SDValue(E, 0);
8743   }
8744 
8745   auto *N = newSDNode<MaskedScatterSDNode>(dl.getIROrder(), dl.getDebugLoc(),
8746                                            VTs, MemVT, MMO, IndexType, IsTrunc);
8747   createOperands(N, Ops);
8748 
8749   assert(N->getMask().getValueType().getVectorElementCount() ==
8750              N->getValue().getValueType().getVectorElementCount() &&
8751          "Vector width mismatch between mask and data");
8752   assert(
8753       N->getIndex().getValueType().getVectorElementCount().isScalable() ==
8754           N->getValue().getValueType().getVectorElementCount().isScalable() &&
8755       "Scalable flags of index and data do not match");
8756   assert(ElementCount::isKnownGE(
8757              N->getIndex().getValueType().getVectorElementCount(),
8758              N->getValue().getValueType().getVectorElementCount()) &&
8759          "Vector width mismatch between index and data");
8760   assert(isa<ConstantSDNode>(N->getScale()) &&
8761          cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() &&
8762          "Scale should be a constant power of 2");
8763 
8764   CSEMap.InsertNode(N, IP);
8765   InsertNode(N);
8766   SDValue V(N, 0);
8767   NewSDValueDbgMsg(V, "Creating new node: ", this);
8768   return V;
8769 }
8770 
8771 SDValue SelectionDAG::simplifySelect(SDValue Cond, SDValue T, SDValue F) {
8772   // select undef, T, F --> T (if T is a constant), otherwise F
8773   // select, ?, undef, F --> F
8774   // select, ?, T, undef --> T
8775   if (Cond.isUndef())
8776     return isConstantValueOfAnyType(T) ? T : F;
8777   if (T.isUndef())
8778     return F;
8779   if (F.isUndef())
8780     return T;
8781 
8782   // select true, T, F --> T
8783   // select false, T, F --> F
8784   if (auto *CondC = dyn_cast<ConstantSDNode>(Cond))
8785     return CondC->isZero() ? F : T;
8786 
8787   // TODO: This should simplify VSELECT with constant condition using something
8788   // like this (but check boolean contents to be complete?):
8789   //  if (ISD::isBuildVectorAllOnes(Cond.getNode()))
8790   //    return T;
8791   //  if (ISD::isBuildVectorAllZeros(Cond.getNode()))
8792   //    return F;
8793 
8794   // select ?, T, T --> T
8795   if (T == F)
8796     return T;
8797 
8798   return SDValue();
8799 }
8800 
8801 SDValue SelectionDAG::simplifyShift(SDValue X, SDValue Y) {
8802   // shift undef, Y --> 0 (can always assume that the undef value is 0)
8803   if (X.isUndef())
8804     return getConstant(0, SDLoc(X.getNode()), X.getValueType());
8805   // shift X, undef --> undef (because it may shift by the bitwidth)
8806   if (Y.isUndef())
8807     return getUNDEF(X.getValueType());
8808 
8809   // shift 0, Y --> 0
8810   // shift X, 0 --> X
8811   if (isNullOrNullSplat(X) || isNullOrNullSplat(Y))
8812     return X;
8813 
8814   // shift X, C >= bitwidth(X) --> undef
8815   // All vector elements must be too big (or undef) to avoid partial undefs.
8816   auto isShiftTooBig = [X](ConstantSDNode *Val) {
8817     return !Val || Val->getAPIntValue().uge(X.getScalarValueSizeInBits());
8818   };
8819   if (ISD::matchUnaryPredicate(Y, isShiftTooBig, true))
8820     return getUNDEF(X.getValueType());
8821 
8822   return SDValue();
8823 }
8824 
8825 SDValue SelectionDAG::simplifyFPBinop(unsigned Opcode, SDValue X, SDValue Y,
8826                                       SDNodeFlags Flags) {
8827   // If this operation has 'nnan' or 'ninf' and at least 1 disallowed operand
8828   // (an undef operand can be chosen to be Nan/Inf), then the result of this
8829   // operation is poison. That result can be relaxed to undef.
8830   ConstantFPSDNode *XC = isConstOrConstSplatFP(X, /* AllowUndefs */ true);
8831   ConstantFPSDNode *YC = isConstOrConstSplatFP(Y, /* AllowUndefs */ true);
8832   bool HasNan = (XC && XC->getValueAPF().isNaN()) ||
8833                 (YC && YC->getValueAPF().isNaN());
8834   bool HasInf = (XC && XC->getValueAPF().isInfinity()) ||
8835                 (YC && YC->getValueAPF().isInfinity());
8836 
8837   if (Flags.hasNoNaNs() && (HasNan || X.isUndef() || Y.isUndef()))
8838     return getUNDEF(X.getValueType());
8839 
8840   if (Flags.hasNoInfs() && (HasInf || X.isUndef() || Y.isUndef()))
8841     return getUNDEF(X.getValueType());
8842 
8843   if (!YC)
8844     return SDValue();
8845 
8846   // X + -0.0 --> X
8847   if (Opcode == ISD::FADD)
8848     if (YC->getValueAPF().isNegZero())
8849       return X;
8850 
8851   // X - +0.0 --> X
8852   if (Opcode == ISD::FSUB)
8853     if (YC->getValueAPF().isPosZero())
8854       return X;
8855 
8856   // X * 1.0 --> X
8857   // X / 1.0 --> X
8858   if (Opcode == ISD::FMUL || Opcode == ISD::FDIV)
8859     if (YC->getValueAPF().isExactlyValue(1.0))
8860       return X;
8861 
8862   // X * 0.0 --> 0.0
8863   if (Opcode == ISD::FMUL && Flags.hasNoNaNs() && Flags.hasNoSignedZeros())
8864     if (YC->getValueAPF().isZero())
8865       return getConstantFP(0.0, SDLoc(Y), Y.getValueType());
8866 
8867   return SDValue();
8868 }
8869 
8870 SDValue SelectionDAG::getVAArg(EVT VT, const SDLoc &dl, SDValue Chain,
8871                                SDValue Ptr, SDValue SV, unsigned Align) {
8872   SDValue Ops[] = { Chain, Ptr, SV, getTargetConstant(Align, dl, MVT::i32) };
8873   return getNode(ISD::VAARG, dl, getVTList(VT, MVT::Other), Ops);
8874 }
8875 
8876 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
8877                               ArrayRef<SDUse> Ops) {
8878   switch (Ops.size()) {
8879   case 0: return getNode(Opcode, DL, VT);
8880   case 1: return getNode(Opcode, DL, VT, static_cast<const SDValue>(Ops[0]));
8881   case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1]);
8882   case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2]);
8883   default: break;
8884   }
8885 
8886   // Copy from an SDUse array into an SDValue array for use with
8887   // the regular getNode logic.
8888   SmallVector<SDValue, 8> NewOps(Ops.begin(), Ops.end());
8889   return getNode(Opcode, DL, VT, NewOps);
8890 }
8891 
8892 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
8893                               ArrayRef<SDValue> Ops) {
8894   SDNodeFlags Flags;
8895   if (Inserter)
8896     Flags = Inserter->getFlags();
8897   return getNode(Opcode, DL, VT, Ops, Flags);
8898 }
8899 
8900 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
8901                               ArrayRef<SDValue> Ops, const SDNodeFlags Flags) {
8902   unsigned NumOps = Ops.size();
8903   switch (NumOps) {
8904   case 0: return getNode(Opcode, DL, VT);
8905   case 1: return getNode(Opcode, DL, VT, Ops[0], Flags);
8906   case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Flags);
8907   case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2], Flags);
8908   default: break;
8909   }
8910 
8911 #ifndef NDEBUG
8912   for (const auto &Op : Ops)
8913     assert(Op.getOpcode() != ISD::DELETED_NODE &&
8914            "Operand is DELETED_NODE!");
8915 #endif
8916 
8917   switch (Opcode) {
8918   default: break;
8919   case ISD::BUILD_VECTOR:
8920     // Attempt to simplify BUILD_VECTOR.
8921     if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
8922       return V;
8923     break;
8924   case ISD::CONCAT_VECTORS:
8925     if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this))
8926       return V;
8927     break;
8928   case ISD::SELECT_CC:
8929     assert(NumOps == 5 && "SELECT_CC takes 5 operands!");
8930     assert(Ops[0].getValueType() == Ops[1].getValueType() &&
8931            "LHS and RHS of condition must have same type!");
8932     assert(Ops[2].getValueType() == Ops[3].getValueType() &&
8933            "True and False arms of SelectCC must have same type!");
8934     assert(Ops[2].getValueType() == VT &&
8935            "select_cc node must be of same type as true and false value!");
8936     break;
8937   case ISD::BR_CC:
8938     assert(NumOps == 5 && "BR_CC takes 5 operands!");
8939     assert(Ops[2].getValueType() == Ops[3].getValueType() &&
8940            "LHS/RHS of comparison should match types!");
8941     break;
8942   case ISD::VP_ADD:
8943   case ISD::VP_SUB:
8944     // If it is VP_ADD/VP_SUB mask operation then turn it to VP_XOR
8945     if (VT.isVector() && VT.getVectorElementType() == MVT::i1)
8946       Opcode = ISD::VP_XOR;
8947     break;
8948   case ISD::VP_MUL:
8949     // If it is VP_MUL mask operation then turn it to VP_AND
8950     if (VT.isVector() && VT.getVectorElementType() == MVT::i1)
8951       Opcode = ISD::VP_AND;
8952     break;
8953   case ISD::VP_REDUCE_MUL:
8954     // If it is VP_REDUCE_MUL mask operation then turn it to VP_REDUCE_AND
8955     if (VT == MVT::i1)
8956       Opcode = ISD::VP_REDUCE_AND;
8957     break;
8958   case ISD::VP_REDUCE_ADD:
8959     // If it is VP_REDUCE_ADD mask operation then turn it to VP_REDUCE_XOR
8960     if (VT == MVT::i1)
8961       Opcode = ISD::VP_REDUCE_XOR;
8962     break;
8963   case ISD::VP_REDUCE_SMAX:
8964   case ISD::VP_REDUCE_UMIN:
8965     // If it is VP_REDUCE_SMAX/VP_REDUCE_UMIN mask operation then turn it to
8966     // VP_REDUCE_AND.
8967     if (VT == MVT::i1)
8968       Opcode = ISD::VP_REDUCE_AND;
8969     break;
8970   case ISD::VP_REDUCE_SMIN:
8971   case ISD::VP_REDUCE_UMAX:
8972     // If it is VP_REDUCE_SMIN/VP_REDUCE_UMAX mask operation then turn it to
8973     // VP_REDUCE_OR.
8974     if (VT == MVT::i1)
8975       Opcode = ISD::VP_REDUCE_OR;
8976     break;
8977   }
8978 
8979   // Memoize nodes.
8980   SDNode *N;
8981   SDVTList VTs = getVTList(VT);
8982 
8983   if (VT != MVT::Glue) {
8984     FoldingSetNodeID ID;
8985     AddNodeIDNode(ID, Opcode, VTs, Ops);
8986     void *IP = nullptr;
8987 
8988     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
8989       return SDValue(E, 0);
8990 
8991     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
8992     createOperands(N, Ops);
8993 
8994     CSEMap.InsertNode(N, IP);
8995   } else {
8996     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
8997     createOperands(N, Ops);
8998   }
8999 
9000   N->setFlags(Flags);
9001   InsertNode(N);
9002   SDValue V(N, 0);
9003   NewSDValueDbgMsg(V, "Creating new node: ", this);
9004   return V;
9005 }
9006 
9007 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL,
9008                               ArrayRef<EVT> ResultTys, ArrayRef<SDValue> Ops) {
9009   return getNode(Opcode, DL, getVTList(ResultTys), Ops);
9010 }
9011 
9012 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
9013                               ArrayRef<SDValue> Ops) {
9014   SDNodeFlags Flags;
9015   if (Inserter)
9016     Flags = Inserter->getFlags();
9017   return getNode(Opcode, DL, VTList, Ops, Flags);
9018 }
9019 
9020 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
9021                               ArrayRef<SDValue> Ops, const SDNodeFlags Flags) {
9022   if (VTList.NumVTs == 1)
9023     return getNode(Opcode, DL, VTList.VTs[0], Ops, Flags);
9024 
9025 #ifndef NDEBUG
9026   for (const auto &Op : Ops)
9027     assert(Op.getOpcode() != ISD::DELETED_NODE &&
9028            "Operand is DELETED_NODE!");
9029 #endif
9030 
9031   switch (Opcode) {
9032   case ISD::STRICT_FP_EXTEND:
9033     assert(VTList.NumVTs == 2 && Ops.size() == 2 &&
9034            "Invalid STRICT_FP_EXTEND!");
9035     assert(VTList.VTs[0].isFloatingPoint() &&
9036            Ops[1].getValueType().isFloatingPoint() && "Invalid FP cast!");
9037     assert(VTList.VTs[0].isVector() == Ops[1].getValueType().isVector() &&
9038            "STRICT_FP_EXTEND result type should be vector iff the operand "
9039            "type is vector!");
9040     assert((!VTList.VTs[0].isVector() ||
9041             VTList.VTs[0].getVectorNumElements() ==
9042             Ops[1].getValueType().getVectorNumElements()) &&
9043            "Vector element count mismatch!");
9044     assert(Ops[1].getValueType().bitsLT(VTList.VTs[0]) &&
9045            "Invalid fpext node, dst <= src!");
9046     break;
9047   case ISD::STRICT_FP_ROUND:
9048     assert(VTList.NumVTs == 2 && Ops.size() == 3 && "Invalid STRICT_FP_ROUND!");
9049     assert(VTList.VTs[0].isVector() == Ops[1].getValueType().isVector() &&
9050            "STRICT_FP_ROUND result type should be vector iff the operand "
9051            "type is vector!");
9052     assert((!VTList.VTs[0].isVector() ||
9053             VTList.VTs[0].getVectorNumElements() ==
9054             Ops[1].getValueType().getVectorNumElements()) &&
9055            "Vector element count mismatch!");
9056     assert(VTList.VTs[0].isFloatingPoint() &&
9057            Ops[1].getValueType().isFloatingPoint() &&
9058            VTList.VTs[0].bitsLT(Ops[1].getValueType()) &&
9059            isa<ConstantSDNode>(Ops[2]) &&
9060            (cast<ConstantSDNode>(Ops[2])->getZExtValue() == 0 ||
9061             cast<ConstantSDNode>(Ops[2])->getZExtValue() == 1) &&
9062            "Invalid STRICT_FP_ROUND!");
9063     break;
9064 #if 0
9065   // FIXME: figure out how to safely handle things like
9066   // int foo(int x) { return 1 << (x & 255); }
9067   // int bar() { return foo(256); }
9068   case ISD::SRA_PARTS:
9069   case ISD::SRL_PARTS:
9070   case ISD::SHL_PARTS:
9071     if (N3.getOpcode() == ISD::SIGN_EXTEND_INREG &&
9072         cast<VTSDNode>(N3.getOperand(1))->getVT() != MVT::i1)
9073       return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0));
9074     else if (N3.getOpcode() == ISD::AND)
9075       if (ConstantSDNode *AndRHS = dyn_cast<ConstantSDNode>(N3.getOperand(1))) {
9076         // If the and is only masking out bits that cannot effect the shift,
9077         // eliminate the and.
9078         unsigned NumBits = VT.getScalarSizeInBits()*2;
9079         if ((AndRHS->getValue() & (NumBits-1)) == NumBits-1)
9080           return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0));
9081       }
9082     break;
9083 #endif
9084   }
9085 
9086   // Memoize the node unless it returns a flag.
9087   SDNode *N;
9088   if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) {
9089     FoldingSetNodeID ID;
9090     AddNodeIDNode(ID, Opcode, VTList, Ops);
9091     void *IP = nullptr;
9092     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
9093       return SDValue(E, 0);
9094 
9095     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList);
9096     createOperands(N, Ops);
9097     CSEMap.InsertNode(N, IP);
9098   } else {
9099     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList);
9100     createOperands(N, Ops);
9101   }
9102 
9103   N->setFlags(Flags);
9104   InsertNode(N);
9105   SDValue V(N, 0);
9106   NewSDValueDbgMsg(V, "Creating new node: ", this);
9107   return V;
9108 }
9109 
9110 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL,
9111                               SDVTList VTList) {
9112   return getNode(Opcode, DL, VTList, None);
9113 }
9114 
9115 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
9116                               SDValue N1) {
9117   SDValue Ops[] = { N1 };
9118   return getNode(Opcode, DL, VTList, Ops);
9119 }
9120 
9121 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
9122                               SDValue N1, SDValue N2) {
9123   SDValue Ops[] = { N1, N2 };
9124   return getNode(Opcode, DL, VTList, Ops);
9125 }
9126 
9127 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
9128                               SDValue N1, SDValue N2, SDValue N3) {
9129   SDValue Ops[] = { N1, N2, N3 };
9130   return getNode(Opcode, DL, VTList, Ops);
9131 }
9132 
9133 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
9134                               SDValue N1, SDValue N2, SDValue N3, SDValue N4) {
9135   SDValue Ops[] = { N1, N2, N3, N4 };
9136   return getNode(Opcode, DL, VTList, Ops);
9137 }
9138 
9139 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
9140                               SDValue N1, SDValue N2, SDValue N3, SDValue N4,
9141                               SDValue N5) {
9142   SDValue Ops[] = { N1, N2, N3, N4, N5 };
9143   return getNode(Opcode, DL, VTList, Ops);
9144 }
9145 
9146 SDVTList SelectionDAG::getVTList(EVT VT) {
9147   return makeVTList(SDNode::getValueTypeList(VT), 1);
9148 }
9149 
9150 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2) {
9151   FoldingSetNodeID ID;
9152   ID.AddInteger(2U);
9153   ID.AddInteger(VT1.getRawBits());
9154   ID.AddInteger(VT2.getRawBits());
9155 
9156   void *IP = nullptr;
9157   SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
9158   if (!Result) {
9159     EVT *Array = Allocator.Allocate<EVT>(2);
9160     Array[0] = VT1;
9161     Array[1] = VT2;
9162     Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 2);
9163     VTListMap.InsertNode(Result, IP);
9164   }
9165   return Result->getSDVTList();
9166 }
9167 
9168 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3) {
9169   FoldingSetNodeID ID;
9170   ID.AddInteger(3U);
9171   ID.AddInteger(VT1.getRawBits());
9172   ID.AddInteger(VT2.getRawBits());
9173   ID.AddInteger(VT3.getRawBits());
9174 
9175   void *IP = nullptr;
9176   SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
9177   if (!Result) {
9178     EVT *Array = Allocator.Allocate<EVT>(3);
9179     Array[0] = VT1;
9180     Array[1] = VT2;
9181     Array[2] = VT3;
9182     Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 3);
9183     VTListMap.InsertNode(Result, IP);
9184   }
9185   return Result->getSDVTList();
9186 }
9187 
9188 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3, EVT VT4) {
9189   FoldingSetNodeID ID;
9190   ID.AddInteger(4U);
9191   ID.AddInteger(VT1.getRawBits());
9192   ID.AddInteger(VT2.getRawBits());
9193   ID.AddInteger(VT3.getRawBits());
9194   ID.AddInteger(VT4.getRawBits());
9195 
9196   void *IP = nullptr;
9197   SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
9198   if (!Result) {
9199     EVT *Array = Allocator.Allocate<EVT>(4);
9200     Array[0] = VT1;
9201     Array[1] = VT2;
9202     Array[2] = VT3;
9203     Array[3] = VT4;
9204     Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 4);
9205     VTListMap.InsertNode(Result, IP);
9206   }
9207   return Result->getSDVTList();
9208 }
9209 
9210 SDVTList SelectionDAG::getVTList(ArrayRef<EVT> VTs) {
9211   unsigned NumVTs = VTs.size();
9212   FoldingSetNodeID ID;
9213   ID.AddInteger(NumVTs);
9214   for (unsigned index = 0; index < NumVTs; index++) {
9215     ID.AddInteger(VTs[index].getRawBits());
9216   }
9217 
9218   void *IP = nullptr;
9219   SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
9220   if (!Result) {
9221     EVT *Array = Allocator.Allocate<EVT>(NumVTs);
9222     llvm::copy(VTs, Array);
9223     Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, NumVTs);
9224     VTListMap.InsertNode(Result, IP);
9225   }
9226   return Result->getSDVTList();
9227 }
9228 
9229 
9230 /// UpdateNodeOperands - *Mutate* the specified node in-place to have the
9231 /// specified operands.  If the resultant node already exists in the DAG,
9232 /// this does not modify the specified node, instead it returns the node that
9233 /// already exists.  If the resultant node does not exist in the DAG, the
9234 /// input node is returned.  As a degenerate case, if you specify the same
9235 /// input operands as the node already has, the input node is returned.
9236 SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op) {
9237   assert(N->getNumOperands() == 1 && "Update with wrong number of operands");
9238 
9239   // Check to see if there is no change.
9240   if (Op == N->getOperand(0)) return N;
9241 
9242   // See if the modified node already exists.
9243   void *InsertPos = nullptr;
9244   if (SDNode *Existing = FindModifiedNodeSlot(N, Op, InsertPos))
9245     return Existing;
9246 
9247   // Nope it doesn't.  Remove the node from its current place in the maps.
9248   if (InsertPos)
9249     if (!RemoveNodeFromCSEMaps(N))
9250       InsertPos = nullptr;
9251 
9252   // Now we update the operands.
9253   N->OperandList[0].set(Op);
9254 
9255   updateDivergence(N);
9256   // If this gets put into a CSE map, add it.
9257   if (InsertPos) CSEMap.InsertNode(N, InsertPos);
9258   return N;
9259 }
9260 
9261 SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2) {
9262   assert(N->getNumOperands() == 2 && "Update with wrong number of operands");
9263 
9264   // Check to see if there is no change.
9265   if (Op1 == N->getOperand(0) && Op2 == N->getOperand(1))
9266     return N;   // No operands changed, just return the input node.
9267 
9268   // See if the modified node already exists.
9269   void *InsertPos = nullptr;
9270   if (SDNode *Existing = FindModifiedNodeSlot(N, Op1, Op2, InsertPos))
9271     return Existing;
9272 
9273   // Nope it doesn't.  Remove the node from its current place in the maps.
9274   if (InsertPos)
9275     if (!RemoveNodeFromCSEMaps(N))
9276       InsertPos = nullptr;
9277 
9278   // Now we update the operands.
9279   if (N->OperandList[0] != Op1)
9280     N->OperandList[0].set(Op1);
9281   if (N->OperandList[1] != Op2)
9282     N->OperandList[1].set(Op2);
9283 
9284   updateDivergence(N);
9285   // If this gets put into a CSE map, add it.
9286   if (InsertPos) CSEMap.InsertNode(N, InsertPos);
9287   return N;
9288 }
9289 
9290 SDNode *SelectionDAG::
9291 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2, SDValue Op3) {
9292   SDValue Ops[] = { Op1, Op2, Op3 };
9293   return UpdateNodeOperands(N, Ops);
9294 }
9295 
9296 SDNode *SelectionDAG::
9297 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2,
9298                    SDValue Op3, SDValue Op4) {
9299   SDValue Ops[] = { Op1, Op2, Op3, Op4 };
9300   return UpdateNodeOperands(N, Ops);
9301 }
9302 
9303 SDNode *SelectionDAG::
9304 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2,
9305                    SDValue Op3, SDValue Op4, SDValue Op5) {
9306   SDValue Ops[] = { Op1, Op2, Op3, Op4, Op5 };
9307   return UpdateNodeOperands(N, Ops);
9308 }
9309 
9310 SDNode *SelectionDAG::
9311 UpdateNodeOperands(SDNode *N, ArrayRef<SDValue> Ops) {
9312   unsigned NumOps = Ops.size();
9313   assert(N->getNumOperands() == NumOps &&
9314          "Update with wrong number of operands");
9315 
9316   // If no operands changed just return the input node.
9317   if (std::equal(Ops.begin(), Ops.end(), N->op_begin()))
9318     return N;
9319 
9320   // See if the modified node already exists.
9321   void *InsertPos = nullptr;
9322   if (SDNode *Existing = FindModifiedNodeSlot(N, Ops, InsertPos))
9323     return Existing;
9324 
9325   // Nope it doesn't.  Remove the node from its current place in the maps.
9326   if (InsertPos)
9327     if (!RemoveNodeFromCSEMaps(N))
9328       InsertPos = nullptr;
9329 
9330   // Now we update the operands.
9331   for (unsigned i = 0; i != NumOps; ++i)
9332     if (N->OperandList[i] != Ops[i])
9333       N->OperandList[i].set(Ops[i]);
9334 
9335   updateDivergence(N);
9336   // If this gets put into a CSE map, add it.
9337   if (InsertPos) CSEMap.InsertNode(N, InsertPos);
9338   return N;
9339 }
9340 
9341 /// DropOperands - Release the operands and set this node to have
9342 /// zero operands.
9343 void SDNode::DropOperands() {
9344   // Unlike the code in MorphNodeTo that does this, we don't need to
9345   // watch for dead nodes here.
9346   for (op_iterator I = op_begin(), E = op_end(); I != E; ) {
9347     SDUse &Use = *I++;
9348     Use.set(SDValue());
9349   }
9350 }
9351 
9352 void SelectionDAG::setNodeMemRefs(MachineSDNode *N,
9353                                   ArrayRef<MachineMemOperand *> NewMemRefs) {
9354   if (NewMemRefs.empty()) {
9355     N->clearMemRefs();
9356     return;
9357   }
9358 
9359   // Check if we can avoid allocating by storing a single reference directly.
9360   if (NewMemRefs.size() == 1) {
9361     N->MemRefs = NewMemRefs[0];
9362     N->NumMemRefs = 1;
9363     return;
9364   }
9365 
9366   MachineMemOperand **MemRefsBuffer =
9367       Allocator.template Allocate<MachineMemOperand *>(NewMemRefs.size());
9368   llvm::copy(NewMemRefs, MemRefsBuffer);
9369   N->MemRefs = MemRefsBuffer;
9370   N->NumMemRefs = static_cast<int>(NewMemRefs.size());
9371 }
9372 
9373 /// SelectNodeTo - These are wrappers around MorphNodeTo that accept a
9374 /// machine opcode.
9375 ///
9376 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
9377                                    EVT VT) {
9378   SDVTList VTs = getVTList(VT);
9379   return SelectNodeTo(N, MachineOpc, VTs, None);
9380 }
9381 
9382 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
9383                                    EVT VT, SDValue Op1) {
9384   SDVTList VTs = getVTList(VT);
9385   SDValue Ops[] = { Op1 };
9386   return SelectNodeTo(N, MachineOpc, VTs, Ops);
9387 }
9388 
9389 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
9390                                    EVT VT, SDValue Op1,
9391                                    SDValue Op2) {
9392   SDVTList VTs = getVTList(VT);
9393   SDValue Ops[] = { Op1, Op2 };
9394   return SelectNodeTo(N, MachineOpc, VTs, Ops);
9395 }
9396 
9397 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
9398                                    EVT VT, SDValue Op1,
9399                                    SDValue Op2, SDValue Op3) {
9400   SDVTList VTs = getVTList(VT);
9401   SDValue Ops[] = { Op1, Op2, Op3 };
9402   return SelectNodeTo(N, MachineOpc, VTs, Ops);
9403 }
9404 
9405 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
9406                                    EVT VT, ArrayRef<SDValue> Ops) {
9407   SDVTList VTs = getVTList(VT);
9408   return SelectNodeTo(N, MachineOpc, VTs, Ops);
9409 }
9410 
9411 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
9412                                    EVT VT1, EVT VT2, ArrayRef<SDValue> Ops) {
9413   SDVTList VTs = getVTList(VT1, VT2);
9414   return SelectNodeTo(N, MachineOpc, VTs, Ops);
9415 }
9416 
9417 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
9418                                    EVT VT1, EVT VT2) {
9419   SDVTList VTs = getVTList(VT1, VT2);
9420   return SelectNodeTo(N, MachineOpc, VTs, None);
9421 }
9422 
9423 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
9424                                    EVT VT1, EVT VT2, EVT VT3,
9425                                    ArrayRef<SDValue> Ops) {
9426   SDVTList VTs = getVTList(VT1, VT2, VT3);
9427   return SelectNodeTo(N, MachineOpc, VTs, Ops);
9428 }
9429 
9430 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
9431                                    EVT VT1, EVT VT2,
9432                                    SDValue Op1, SDValue Op2) {
9433   SDVTList VTs = getVTList(VT1, VT2);
9434   SDValue Ops[] = { Op1, Op2 };
9435   return SelectNodeTo(N, MachineOpc, VTs, Ops);
9436 }
9437 
9438 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
9439                                    SDVTList VTs,ArrayRef<SDValue> Ops) {
9440   SDNode *New = MorphNodeTo(N, ~MachineOpc, VTs, Ops);
9441   // Reset the NodeID to -1.
9442   New->setNodeId(-1);
9443   if (New != N) {
9444     ReplaceAllUsesWith(N, New);
9445     RemoveDeadNode(N);
9446   }
9447   return New;
9448 }
9449 
9450 /// UpdateSDLocOnMergeSDNode - If the opt level is -O0 then it throws away
9451 /// the line number information on the merged node since it is not possible to
9452 /// preserve the information that operation is associated with multiple lines.
9453 /// This will make the debugger working better at -O0, were there is a higher
9454 /// probability having other instructions associated with that line.
9455 ///
9456 /// For IROrder, we keep the smaller of the two
9457 SDNode *SelectionDAG::UpdateSDLocOnMergeSDNode(SDNode *N, const SDLoc &OLoc) {
9458   DebugLoc NLoc = N->getDebugLoc();
9459   if (NLoc && OptLevel == CodeGenOpt::None && OLoc.getDebugLoc() != NLoc) {
9460     N->setDebugLoc(DebugLoc());
9461   }
9462   unsigned Order = std::min(N->getIROrder(), OLoc.getIROrder());
9463   N->setIROrder(Order);
9464   return N;
9465 }
9466 
9467 /// MorphNodeTo - This *mutates* the specified node to have the specified
9468 /// return type, opcode, and operands.
9469 ///
9470 /// Note that MorphNodeTo returns the resultant node.  If there is already a
9471 /// node of the specified opcode and operands, it returns that node instead of
9472 /// the current one.  Note that the SDLoc need not be the same.
9473 ///
9474 /// Using MorphNodeTo is faster than creating a new node and swapping it in
9475 /// with ReplaceAllUsesWith both because it often avoids allocating a new
9476 /// node, and because it doesn't require CSE recalculation for any of
9477 /// the node's users.
9478 ///
9479 /// However, note that MorphNodeTo recursively deletes dead nodes from the DAG.
9480 /// As a consequence it isn't appropriate to use from within the DAG combiner or
9481 /// the legalizer which maintain worklists that would need to be updated when
9482 /// deleting things.
9483 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
9484                                   SDVTList VTs, ArrayRef<SDValue> Ops) {
9485   // If an identical node already exists, use it.
9486   void *IP = nullptr;
9487   if (VTs.VTs[VTs.NumVTs-1] != MVT::Glue) {
9488     FoldingSetNodeID ID;
9489     AddNodeIDNode(ID, Opc, VTs, Ops);
9490     if (SDNode *ON = FindNodeOrInsertPos(ID, SDLoc(N), IP))
9491       return UpdateSDLocOnMergeSDNode(ON, SDLoc(N));
9492   }
9493 
9494   if (!RemoveNodeFromCSEMaps(N))
9495     IP = nullptr;
9496 
9497   // Start the morphing.
9498   N->NodeType = Opc;
9499   N->ValueList = VTs.VTs;
9500   N->NumValues = VTs.NumVTs;
9501 
9502   // Clear the operands list, updating used nodes to remove this from their
9503   // use list.  Keep track of any operands that become dead as a result.
9504   SmallPtrSet<SDNode*, 16> DeadNodeSet;
9505   for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) {
9506     SDUse &Use = *I++;
9507     SDNode *Used = Use.getNode();
9508     Use.set(SDValue());
9509     if (Used->use_empty())
9510       DeadNodeSet.insert(Used);
9511   }
9512 
9513   // For MachineNode, initialize the memory references information.
9514   if (MachineSDNode *MN = dyn_cast<MachineSDNode>(N))
9515     MN->clearMemRefs();
9516 
9517   // Swap for an appropriately sized array from the recycler.
9518   removeOperands(N);
9519   createOperands(N, Ops);
9520 
9521   // Delete any nodes that are still dead after adding the uses for the
9522   // new operands.
9523   if (!DeadNodeSet.empty()) {
9524     SmallVector<SDNode *, 16> DeadNodes;
9525     for (SDNode *N : DeadNodeSet)
9526       if (N->use_empty())
9527         DeadNodes.push_back(N);
9528     RemoveDeadNodes(DeadNodes);
9529   }
9530 
9531   if (IP)
9532     CSEMap.InsertNode(N, IP);   // Memoize the new node.
9533   return N;
9534 }
9535 
9536 SDNode* SelectionDAG::mutateStrictFPToFP(SDNode *Node) {
9537   unsigned OrigOpc = Node->getOpcode();
9538   unsigned NewOpc;
9539   switch (OrigOpc) {
9540   default:
9541     llvm_unreachable("mutateStrictFPToFP called with unexpected opcode!");
9542 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN)               \
9543   case ISD::STRICT_##DAGN: NewOpc = ISD::DAGN; break;
9544 #define CMP_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN)               \
9545   case ISD::STRICT_##DAGN: NewOpc = ISD::SETCC; break;
9546 #include "llvm/IR/ConstrainedOps.def"
9547   }
9548 
9549   assert(Node->getNumValues() == 2 && "Unexpected number of results!");
9550 
9551   // We're taking this node out of the chain, so we need to re-link things.
9552   SDValue InputChain = Node->getOperand(0);
9553   SDValue OutputChain = SDValue(Node, 1);
9554   ReplaceAllUsesOfValueWith(OutputChain, InputChain);
9555 
9556   SmallVector<SDValue, 3> Ops;
9557   for (unsigned i = 1, e = Node->getNumOperands(); i != e; ++i)
9558     Ops.push_back(Node->getOperand(i));
9559 
9560   SDVTList VTs = getVTList(Node->getValueType(0));
9561   SDNode *Res = MorphNodeTo(Node, NewOpc, VTs, Ops);
9562 
9563   // MorphNodeTo can operate in two ways: if an existing node with the
9564   // specified operands exists, it can just return it.  Otherwise, it
9565   // updates the node in place to have the requested operands.
9566   if (Res == Node) {
9567     // If we updated the node in place, reset the node ID.  To the isel,
9568     // this should be just like a newly allocated machine node.
9569     Res->setNodeId(-1);
9570   } else {
9571     ReplaceAllUsesWith(Node, Res);
9572     RemoveDeadNode(Node);
9573   }
9574 
9575   return Res;
9576 }
9577 
9578 /// getMachineNode - These are used for target selectors to create a new node
9579 /// with specified return type(s), MachineInstr opcode, and operands.
9580 ///
9581 /// Note that getMachineNode returns the resultant node.  If there is already a
9582 /// node of the specified opcode and operands, it returns that node instead of
9583 /// the current one.
9584 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9585                                             EVT VT) {
9586   SDVTList VTs = getVTList(VT);
9587   return getMachineNode(Opcode, dl, VTs, None);
9588 }
9589 
9590 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9591                                             EVT VT, SDValue Op1) {
9592   SDVTList VTs = getVTList(VT);
9593   SDValue Ops[] = { Op1 };
9594   return getMachineNode(Opcode, dl, VTs, Ops);
9595 }
9596 
9597 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9598                                             EVT VT, SDValue Op1, SDValue Op2) {
9599   SDVTList VTs = getVTList(VT);
9600   SDValue Ops[] = { Op1, Op2 };
9601   return getMachineNode(Opcode, dl, VTs, Ops);
9602 }
9603 
9604 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9605                                             EVT VT, SDValue Op1, SDValue Op2,
9606                                             SDValue Op3) {
9607   SDVTList VTs = getVTList(VT);
9608   SDValue Ops[] = { Op1, Op2, Op3 };
9609   return getMachineNode(Opcode, dl, VTs, Ops);
9610 }
9611 
9612 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9613                                             EVT VT, ArrayRef<SDValue> Ops) {
9614   SDVTList VTs = getVTList(VT);
9615   return getMachineNode(Opcode, dl, VTs, Ops);
9616 }
9617 
9618 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9619                                             EVT VT1, EVT VT2, SDValue Op1,
9620                                             SDValue Op2) {
9621   SDVTList VTs = getVTList(VT1, VT2);
9622   SDValue Ops[] = { Op1, Op2 };
9623   return getMachineNode(Opcode, dl, VTs, Ops);
9624 }
9625 
9626 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9627                                             EVT VT1, EVT VT2, SDValue Op1,
9628                                             SDValue Op2, SDValue Op3) {
9629   SDVTList VTs = getVTList(VT1, VT2);
9630   SDValue Ops[] = { Op1, Op2, Op3 };
9631   return getMachineNode(Opcode, dl, VTs, Ops);
9632 }
9633 
9634 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9635                                             EVT VT1, EVT VT2,
9636                                             ArrayRef<SDValue> Ops) {
9637   SDVTList VTs = getVTList(VT1, VT2);
9638   return getMachineNode(Opcode, dl, VTs, Ops);
9639 }
9640 
9641 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9642                                             EVT VT1, EVT VT2, EVT VT3,
9643                                             SDValue Op1, SDValue Op2) {
9644   SDVTList VTs = getVTList(VT1, VT2, VT3);
9645   SDValue Ops[] = { Op1, Op2 };
9646   return getMachineNode(Opcode, dl, VTs, Ops);
9647 }
9648 
9649 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9650                                             EVT VT1, EVT VT2, EVT VT3,
9651                                             SDValue Op1, SDValue Op2,
9652                                             SDValue Op3) {
9653   SDVTList VTs = getVTList(VT1, VT2, VT3);
9654   SDValue Ops[] = { Op1, Op2, Op3 };
9655   return getMachineNode(Opcode, dl, VTs, Ops);
9656 }
9657 
9658 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9659                                             EVT VT1, EVT VT2, EVT VT3,
9660                                             ArrayRef<SDValue> Ops) {
9661   SDVTList VTs = getVTList(VT1, VT2, VT3);
9662   return getMachineNode(Opcode, dl, VTs, Ops);
9663 }
9664 
9665 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9666                                             ArrayRef<EVT> ResultTys,
9667                                             ArrayRef<SDValue> Ops) {
9668   SDVTList VTs = getVTList(ResultTys);
9669   return getMachineNode(Opcode, dl, VTs, Ops);
9670 }
9671 
9672 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &DL,
9673                                             SDVTList VTs,
9674                                             ArrayRef<SDValue> Ops) {
9675   bool DoCSE = VTs.VTs[VTs.NumVTs-1] != MVT::Glue;
9676   MachineSDNode *N;
9677   void *IP = nullptr;
9678 
9679   if (DoCSE) {
9680     FoldingSetNodeID ID;
9681     AddNodeIDNode(ID, ~Opcode, VTs, Ops);
9682     IP = nullptr;
9683     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
9684       return cast<MachineSDNode>(UpdateSDLocOnMergeSDNode(E, DL));
9685     }
9686   }
9687 
9688   // Allocate a new MachineSDNode.
9689   N = newSDNode<MachineSDNode>(~Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
9690   createOperands(N, Ops);
9691 
9692   if (DoCSE)
9693     CSEMap.InsertNode(N, IP);
9694 
9695   InsertNode(N);
9696   NewSDValueDbgMsg(SDValue(N, 0), "Creating new machine node: ", this);
9697   return N;
9698 }
9699 
9700 /// getTargetExtractSubreg - A convenience function for creating
9701 /// TargetOpcode::EXTRACT_SUBREG nodes.
9702 SDValue SelectionDAG::getTargetExtractSubreg(int SRIdx, const SDLoc &DL, EVT VT,
9703                                              SDValue Operand) {
9704   SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32);
9705   SDNode *Subreg = getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL,
9706                                   VT, Operand, SRIdxVal);
9707   return SDValue(Subreg, 0);
9708 }
9709 
9710 /// getTargetInsertSubreg - A convenience function for creating
9711 /// TargetOpcode::INSERT_SUBREG nodes.
9712 SDValue SelectionDAG::getTargetInsertSubreg(int SRIdx, const SDLoc &DL, EVT VT,
9713                                             SDValue Operand, SDValue Subreg) {
9714   SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32);
9715   SDNode *Result = getMachineNode(TargetOpcode::INSERT_SUBREG, DL,
9716                                   VT, Operand, Subreg, SRIdxVal);
9717   return SDValue(Result, 0);
9718 }
9719 
9720 /// getNodeIfExists - Get the specified node if it's already available, or
9721 /// else return NULL.
9722 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList,
9723                                       ArrayRef<SDValue> Ops) {
9724   SDNodeFlags Flags;
9725   if (Inserter)
9726     Flags = Inserter->getFlags();
9727   return getNodeIfExists(Opcode, VTList, Ops, Flags);
9728 }
9729 
9730 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList,
9731                                       ArrayRef<SDValue> Ops,
9732                                       const SDNodeFlags Flags) {
9733   if (VTList.VTs[VTList.NumVTs - 1] != MVT::Glue) {
9734     FoldingSetNodeID ID;
9735     AddNodeIDNode(ID, Opcode, VTList, Ops);
9736     void *IP = nullptr;
9737     if (SDNode *E = FindNodeOrInsertPos(ID, SDLoc(), IP)) {
9738       E->intersectFlagsWith(Flags);
9739       return E;
9740     }
9741   }
9742   return nullptr;
9743 }
9744 
9745 /// doesNodeExist - Check if a node exists without modifying its flags.
9746 bool SelectionDAG::doesNodeExist(unsigned Opcode, SDVTList VTList,
9747                                  ArrayRef<SDValue> Ops) {
9748   if (VTList.VTs[VTList.NumVTs - 1] != MVT::Glue) {
9749     FoldingSetNodeID ID;
9750     AddNodeIDNode(ID, Opcode, VTList, Ops);
9751     void *IP = nullptr;
9752     if (FindNodeOrInsertPos(ID, SDLoc(), IP))
9753       return true;
9754   }
9755   return false;
9756 }
9757 
9758 /// getDbgValue - Creates a SDDbgValue node.
9759 ///
9760 /// SDNode
9761 SDDbgValue *SelectionDAG::getDbgValue(DIVariable *Var, DIExpression *Expr,
9762                                       SDNode *N, unsigned R, bool IsIndirect,
9763                                       const DebugLoc &DL, unsigned O) {
9764   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
9765          "Expected inlined-at fields to agree");
9766   return new (DbgInfo->getAlloc())
9767       SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromNode(N, R),
9768                  {}, IsIndirect, DL, O,
9769                  /*IsVariadic=*/false);
9770 }
9771 
9772 /// Constant
9773 SDDbgValue *SelectionDAG::getConstantDbgValue(DIVariable *Var,
9774                                               DIExpression *Expr,
9775                                               const Value *C,
9776                                               const DebugLoc &DL, unsigned O) {
9777   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
9778          "Expected inlined-at fields to agree");
9779   return new (DbgInfo->getAlloc())
9780       SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromConst(C), {},
9781                  /*IsIndirect=*/false, DL, O,
9782                  /*IsVariadic=*/false);
9783 }
9784 
9785 /// FrameIndex
9786 SDDbgValue *SelectionDAG::getFrameIndexDbgValue(DIVariable *Var,
9787                                                 DIExpression *Expr, unsigned FI,
9788                                                 bool IsIndirect,
9789                                                 const DebugLoc &DL,
9790                                                 unsigned O) {
9791   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
9792          "Expected inlined-at fields to agree");
9793   return getFrameIndexDbgValue(Var, Expr, FI, {}, IsIndirect, DL, O);
9794 }
9795 
9796 /// FrameIndex with dependencies
9797 SDDbgValue *SelectionDAG::getFrameIndexDbgValue(DIVariable *Var,
9798                                                 DIExpression *Expr, unsigned FI,
9799                                                 ArrayRef<SDNode *> Dependencies,
9800                                                 bool IsIndirect,
9801                                                 const DebugLoc &DL,
9802                                                 unsigned O) {
9803   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
9804          "Expected inlined-at fields to agree");
9805   return new (DbgInfo->getAlloc())
9806       SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromFrameIdx(FI),
9807                  Dependencies, IsIndirect, DL, O,
9808                  /*IsVariadic=*/false);
9809 }
9810 
9811 /// VReg
9812 SDDbgValue *SelectionDAG::getVRegDbgValue(DIVariable *Var, DIExpression *Expr,
9813                                           unsigned VReg, bool IsIndirect,
9814                                           const DebugLoc &DL, unsigned O) {
9815   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
9816          "Expected inlined-at fields to agree");
9817   return new (DbgInfo->getAlloc())
9818       SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromVReg(VReg),
9819                  {}, IsIndirect, DL, O,
9820                  /*IsVariadic=*/false);
9821 }
9822 
9823 SDDbgValue *SelectionDAG::getDbgValueList(DIVariable *Var, DIExpression *Expr,
9824                                           ArrayRef<SDDbgOperand> Locs,
9825                                           ArrayRef<SDNode *> Dependencies,
9826                                           bool IsIndirect, const DebugLoc &DL,
9827                                           unsigned O, bool IsVariadic) {
9828   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
9829          "Expected inlined-at fields to agree");
9830   return new (DbgInfo->getAlloc())
9831       SDDbgValue(DbgInfo->getAlloc(), Var, Expr, Locs, Dependencies, IsIndirect,
9832                  DL, O, IsVariadic);
9833 }
9834 
9835 void SelectionDAG::transferDbgValues(SDValue From, SDValue To,
9836                                      unsigned OffsetInBits, unsigned SizeInBits,
9837                                      bool InvalidateDbg) {
9838   SDNode *FromNode = From.getNode();
9839   SDNode *ToNode = To.getNode();
9840   assert(FromNode && ToNode && "Can't modify dbg values");
9841 
9842   // PR35338
9843   // TODO: assert(From != To && "Redundant dbg value transfer");
9844   // TODO: assert(FromNode != ToNode && "Intranode dbg value transfer");
9845   if (From == To || FromNode == ToNode)
9846     return;
9847 
9848   if (!FromNode->getHasDebugValue())
9849     return;
9850 
9851   SDDbgOperand FromLocOp =
9852       SDDbgOperand::fromNode(From.getNode(), From.getResNo());
9853   SDDbgOperand ToLocOp = SDDbgOperand::fromNode(To.getNode(), To.getResNo());
9854 
9855   SmallVector<SDDbgValue *, 2> ClonedDVs;
9856   for (SDDbgValue *Dbg : GetDbgValues(FromNode)) {
9857     if (Dbg->isInvalidated())
9858       continue;
9859 
9860     // TODO: assert(!Dbg->isInvalidated() && "Transfer of invalid dbg value");
9861 
9862     // Create a new location ops vector that is equal to the old vector, but
9863     // with each instance of FromLocOp replaced with ToLocOp.
9864     bool Changed = false;
9865     auto NewLocOps = Dbg->copyLocationOps();
9866     std::replace_if(
9867         NewLocOps.begin(), NewLocOps.end(),
9868         [&Changed, FromLocOp](const SDDbgOperand &Op) {
9869           bool Match = Op == FromLocOp;
9870           Changed |= Match;
9871           return Match;
9872         },
9873         ToLocOp);
9874     // Ignore this SDDbgValue if we didn't find a matching location.
9875     if (!Changed)
9876       continue;
9877 
9878     DIVariable *Var = Dbg->getVariable();
9879     auto *Expr = Dbg->getExpression();
9880     // If a fragment is requested, update the expression.
9881     if (SizeInBits) {
9882       // When splitting a larger (e.g., sign-extended) value whose
9883       // lower bits are described with an SDDbgValue, do not attempt
9884       // to transfer the SDDbgValue to the upper bits.
9885       if (auto FI = Expr->getFragmentInfo())
9886         if (OffsetInBits + SizeInBits > FI->SizeInBits)
9887           continue;
9888       auto Fragment = DIExpression::createFragmentExpression(Expr, OffsetInBits,
9889                                                              SizeInBits);
9890       if (!Fragment)
9891         continue;
9892       Expr = *Fragment;
9893     }
9894 
9895     auto AdditionalDependencies = Dbg->getAdditionalDependencies();
9896     // Clone the SDDbgValue and move it to To.
9897     SDDbgValue *Clone = getDbgValueList(
9898         Var, Expr, NewLocOps, AdditionalDependencies, Dbg->isIndirect(),
9899         Dbg->getDebugLoc(), std::max(ToNode->getIROrder(), Dbg->getOrder()),
9900         Dbg->isVariadic());
9901     ClonedDVs.push_back(Clone);
9902 
9903     if (InvalidateDbg) {
9904       // Invalidate value and indicate the SDDbgValue should not be emitted.
9905       Dbg->setIsInvalidated();
9906       Dbg->setIsEmitted();
9907     }
9908   }
9909 
9910   for (SDDbgValue *Dbg : ClonedDVs) {
9911     assert(is_contained(Dbg->getSDNodes(), ToNode) &&
9912            "Transferred DbgValues should depend on the new SDNode");
9913     AddDbgValue(Dbg, false);
9914   }
9915 }
9916 
9917 void SelectionDAG::salvageDebugInfo(SDNode &N) {
9918   if (!N.getHasDebugValue())
9919     return;
9920 
9921   SmallVector<SDDbgValue *, 2> ClonedDVs;
9922   for (auto *DV : GetDbgValues(&N)) {
9923     if (DV->isInvalidated())
9924       continue;
9925     switch (N.getOpcode()) {
9926     default:
9927       break;
9928     case ISD::ADD:
9929       SDValue N0 = N.getOperand(0);
9930       SDValue N1 = N.getOperand(1);
9931       if (!isConstantIntBuildVectorOrConstantInt(N0) &&
9932           isConstantIntBuildVectorOrConstantInt(N1)) {
9933         uint64_t Offset = N.getConstantOperandVal(1);
9934 
9935         // Rewrite an ADD constant node into a DIExpression. Since we are
9936         // performing arithmetic to compute the variable's *value* in the
9937         // DIExpression, we need to mark the expression with a
9938         // DW_OP_stack_value.
9939         auto *DIExpr = DV->getExpression();
9940         auto NewLocOps = DV->copyLocationOps();
9941         bool Changed = false;
9942         for (size_t i = 0; i < NewLocOps.size(); ++i) {
9943           // We're not given a ResNo to compare against because the whole
9944           // node is going away. We know that any ISD::ADD only has one
9945           // result, so we can assume any node match is using the result.
9946           if (NewLocOps[i].getKind() != SDDbgOperand::SDNODE ||
9947               NewLocOps[i].getSDNode() != &N)
9948             continue;
9949           NewLocOps[i] = SDDbgOperand::fromNode(N0.getNode(), N0.getResNo());
9950           SmallVector<uint64_t, 3> ExprOps;
9951           DIExpression::appendOffset(ExprOps, Offset);
9952           DIExpr = DIExpression::appendOpsToArg(DIExpr, ExprOps, i, true);
9953           Changed = true;
9954         }
9955         (void)Changed;
9956         assert(Changed && "Salvage target doesn't use N");
9957 
9958         auto AdditionalDependencies = DV->getAdditionalDependencies();
9959         SDDbgValue *Clone = getDbgValueList(DV->getVariable(), DIExpr,
9960                                             NewLocOps, AdditionalDependencies,
9961                                             DV->isIndirect(), DV->getDebugLoc(),
9962                                             DV->getOrder(), DV->isVariadic());
9963         ClonedDVs.push_back(Clone);
9964         DV->setIsInvalidated();
9965         DV->setIsEmitted();
9966         LLVM_DEBUG(dbgs() << "SALVAGE: Rewriting";
9967                    N0.getNode()->dumprFull(this);
9968                    dbgs() << " into " << *DIExpr << '\n');
9969       }
9970     }
9971   }
9972 
9973   for (SDDbgValue *Dbg : ClonedDVs) {
9974     assert(!Dbg->getSDNodes().empty() &&
9975            "Salvaged DbgValue should depend on a new SDNode");
9976     AddDbgValue(Dbg, false);
9977   }
9978 }
9979 
9980 /// Creates a SDDbgLabel node.
9981 SDDbgLabel *SelectionDAG::getDbgLabel(DILabel *Label,
9982                                       const DebugLoc &DL, unsigned O) {
9983   assert(cast<DILabel>(Label)->isValidLocationForIntrinsic(DL) &&
9984          "Expected inlined-at fields to agree");
9985   return new (DbgInfo->getAlloc()) SDDbgLabel(Label, DL, O);
9986 }
9987 
9988 namespace {
9989 
9990 /// RAUWUpdateListener - Helper for ReplaceAllUsesWith - When the node
9991 /// pointed to by a use iterator is deleted, increment the use iterator
9992 /// so that it doesn't dangle.
9993 ///
9994 class RAUWUpdateListener : public SelectionDAG::DAGUpdateListener {
9995   SDNode::use_iterator &UI;
9996   SDNode::use_iterator &UE;
9997 
9998   void NodeDeleted(SDNode *N, SDNode *E) override {
9999     // Increment the iterator as needed.
10000     while (UI != UE && N == *UI)
10001       ++UI;
10002   }
10003 
10004 public:
10005   RAUWUpdateListener(SelectionDAG &d,
10006                      SDNode::use_iterator &ui,
10007                      SDNode::use_iterator &ue)
10008     : SelectionDAG::DAGUpdateListener(d), UI(ui), UE(ue) {}
10009 };
10010 
10011 } // end anonymous namespace
10012 
10013 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
10014 /// This can cause recursive merging of nodes in the DAG.
10015 ///
10016 /// This version assumes From has a single result value.
10017 ///
10018 void SelectionDAG::ReplaceAllUsesWith(SDValue FromN, SDValue To) {
10019   SDNode *From = FromN.getNode();
10020   assert(From->getNumValues() == 1 && FromN.getResNo() == 0 &&
10021          "Cannot replace with this method!");
10022   assert(From != To.getNode() && "Cannot replace uses of with self");
10023 
10024   // Preserve Debug Values
10025   transferDbgValues(FromN, To);
10026 
10027   // Iterate over all the existing uses of From. New uses will be added
10028   // to the beginning of the use list, which we avoid visiting.
10029   // This specifically avoids visiting uses of From that arise while the
10030   // replacement is happening, because any such uses would be the result
10031   // of CSE: If an existing node looks like From after one of its operands
10032   // is replaced by To, we don't want to replace of all its users with To
10033   // too. See PR3018 for more info.
10034   SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
10035   RAUWUpdateListener Listener(*this, UI, UE);
10036   while (UI != UE) {
10037     SDNode *User = *UI;
10038 
10039     // This node is about to morph, remove its old self from the CSE maps.
10040     RemoveNodeFromCSEMaps(User);
10041 
10042     // A user can appear in a use list multiple times, and when this
10043     // happens the uses are usually next to each other in the list.
10044     // To help reduce the number of CSE recomputations, process all
10045     // the uses of this user that we can find this way.
10046     do {
10047       SDUse &Use = UI.getUse();
10048       ++UI;
10049       Use.set(To);
10050       if (To->isDivergent() != From->isDivergent())
10051         updateDivergence(User);
10052     } while (UI != UE && *UI == User);
10053     // Now that we have modified User, add it back to the CSE maps.  If it
10054     // already exists there, recursively merge the results together.
10055     AddModifiedNodeToCSEMaps(User);
10056   }
10057 
10058   // If we just RAUW'd the root, take note.
10059   if (FromN == getRoot())
10060     setRoot(To);
10061 }
10062 
10063 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
10064 /// This can cause recursive merging of nodes in the DAG.
10065 ///
10066 /// This version assumes that for each value of From, there is a
10067 /// corresponding value in To in the same position with the same type.
10068 ///
10069 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, SDNode *To) {
10070 #ifndef NDEBUG
10071   for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
10072     assert((!From->hasAnyUseOfValue(i) ||
10073             From->getValueType(i) == To->getValueType(i)) &&
10074            "Cannot use this version of ReplaceAllUsesWith!");
10075 #endif
10076 
10077   // Handle the trivial case.
10078   if (From == To)
10079     return;
10080 
10081   // Preserve Debug Info. Only do this if there's a use.
10082   for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
10083     if (From->hasAnyUseOfValue(i)) {
10084       assert((i < To->getNumValues()) && "Invalid To location");
10085       transferDbgValues(SDValue(From, i), SDValue(To, i));
10086     }
10087 
10088   // Iterate over just the existing users of From. See the comments in
10089   // the ReplaceAllUsesWith above.
10090   SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
10091   RAUWUpdateListener Listener(*this, UI, UE);
10092   while (UI != UE) {
10093     SDNode *User = *UI;
10094 
10095     // This node is about to morph, remove its old self from the CSE maps.
10096     RemoveNodeFromCSEMaps(User);
10097 
10098     // A user can appear in a use list multiple times, and when this
10099     // happens the uses are usually next to each other in the list.
10100     // To help reduce the number of CSE recomputations, process all
10101     // the uses of this user that we can find this way.
10102     do {
10103       SDUse &Use = UI.getUse();
10104       ++UI;
10105       Use.setNode(To);
10106       if (To->isDivergent() != From->isDivergent())
10107         updateDivergence(User);
10108     } while (UI != UE && *UI == User);
10109 
10110     // Now that we have modified User, add it back to the CSE maps.  If it
10111     // already exists there, recursively merge the results together.
10112     AddModifiedNodeToCSEMaps(User);
10113   }
10114 
10115   // If we just RAUW'd the root, take note.
10116   if (From == getRoot().getNode())
10117     setRoot(SDValue(To, getRoot().getResNo()));
10118 }
10119 
10120 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
10121 /// This can cause recursive merging of nodes in the DAG.
10122 ///
10123 /// This version can replace From with any result values.  To must match the
10124 /// number and types of values returned by From.
10125 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, const SDValue *To) {
10126   if (From->getNumValues() == 1)  // Handle the simple case efficiently.
10127     return ReplaceAllUsesWith(SDValue(From, 0), To[0]);
10128 
10129   // Preserve Debug Info.
10130   for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
10131     transferDbgValues(SDValue(From, i), To[i]);
10132 
10133   // Iterate over just the existing users of From. See the comments in
10134   // the ReplaceAllUsesWith above.
10135   SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
10136   RAUWUpdateListener Listener(*this, UI, UE);
10137   while (UI != UE) {
10138     SDNode *User = *UI;
10139 
10140     // This node is about to morph, remove its old self from the CSE maps.
10141     RemoveNodeFromCSEMaps(User);
10142 
10143     // A user can appear in a use list multiple times, and when this happens the
10144     // uses are usually next to each other in the list.  To help reduce the
10145     // number of CSE and divergence recomputations, process all the uses of this
10146     // user that we can find this way.
10147     bool To_IsDivergent = false;
10148     do {
10149       SDUse &Use = UI.getUse();
10150       const SDValue &ToOp = To[Use.getResNo()];
10151       ++UI;
10152       Use.set(ToOp);
10153       To_IsDivergent |= ToOp->isDivergent();
10154     } while (UI != UE && *UI == User);
10155 
10156     if (To_IsDivergent != From->isDivergent())
10157       updateDivergence(User);
10158 
10159     // Now that we have modified User, add it back to the CSE maps.  If it
10160     // already exists there, recursively merge the results together.
10161     AddModifiedNodeToCSEMaps(User);
10162   }
10163 
10164   // If we just RAUW'd the root, take note.
10165   if (From == getRoot().getNode())
10166     setRoot(SDValue(To[getRoot().getResNo()]));
10167 }
10168 
10169 /// ReplaceAllUsesOfValueWith - Replace any uses of From with To, leaving
10170 /// uses of other values produced by From.getNode() alone.  The Deleted
10171 /// vector is handled the same way as for ReplaceAllUsesWith.
10172 void SelectionDAG::ReplaceAllUsesOfValueWith(SDValue From, SDValue To){
10173   // Handle the really simple, really trivial case efficiently.
10174   if (From == To) return;
10175 
10176   // Handle the simple, trivial, case efficiently.
10177   if (From.getNode()->getNumValues() == 1) {
10178     ReplaceAllUsesWith(From, To);
10179     return;
10180   }
10181 
10182   // Preserve Debug Info.
10183   transferDbgValues(From, To);
10184 
10185   // Iterate over just the existing users of From. See the comments in
10186   // the ReplaceAllUsesWith above.
10187   SDNode::use_iterator UI = From.getNode()->use_begin(),
10188                        UE = From.getNode()->use_end();
10189   RAUWUpdateListener Listener(*this, UI, UE);
10190   while (UI != UE) {
10191     SDNode *User = *UI;
10192     bool UserRemovedFromCSEMaps = false;
10193 
10194     // A user can appear in a use list multiple times, and when this
10195     // happens the uses are usually next to each other in the list.
10196     // To help reduce the number of CSE recomputations, process all
10197     // the uses of this user that we can find this way.
10198     do {
10199       SDUse &Use = UI.getUse();
10200 
10201       // Skip uses of different values from the same node.
10202       if (Use.getResNo() != From.getResNo()) {
10203         ++UI;
10204         continue;
10205       }
10206 
10207       // If this node hasn't been modified yet, it's still in the CSE maps,
10208       // so remove its old self from the CSE maps.
10209       if (!UserRemovedFromCSEMaps) {
10210         RemoveNodeFromCSEMaps(User);
10211         UserRemovedFromCSEMaps = true;
10212       }
10213 
10214       ++UI;
10215       Use.set(To);
10216       if (To->isDivergent() != From->isDivergent())
10217         updateDivergence(User);
10218     } while (UI != UE && *UI == User);
10219     // We are iterating over all uses of the From node, so if a use
10220     // doesn't use the specific value, no changes are made.
10221     if (!UserRemovedFromCSEMaps)
10222       continue;
10223 
10224     // Now that we have modified User, add it back to the CSE maps.  If it
10225     // already exists there, recursively merge the results together.
10226     AddModifiedNodeToCSEMaps(User);
10227   }
10228 
10229   // If we just RAUW'd the root, take note.
10230   if (From == getRoot())
10231     setRoot(To);
10232 }
10233 
10234 namespace {
10235 
10236 /// UseMemo - This class is used by SelectionDAG::ReplaceAllUsesOfValuesWith
10237 /// to record information about a use.
10238 struct UseMemo {
10239   SDNode *User;
10240   unsigned Index;
10241   SDUse *Use;
10242 };
10243 
10244 /// operator< - Sort Memos by User.
10245 bool operator<(const UseMemo &L, const UseMemo &R) {
10246   return (intptr_t)L.User < (intptr_t)R.User;
10247 }
10248 
10249 /// RAUOVWUpdateListener - Helper for ReplaceAllUsesOfValuesWith - When the node
10250 /// pointed to by a UseMemo is deleted, set the User to nullptr to indicate that
10251 /// the node already has been taken care of recursively.
10252 class RAUOVWUpdateListener : public SelectionDAG::DAGUpdateListener {
10253   SmallVector<UseMemo, 4> &Uses;
10254 
10255   void NodeDeleted(SDNode *N, SDNode *E) override {
10256     for (UseMemo &Memo : Uses)
10257       if (Memo.User == N)
10258         Memo.User = nullptr;
10259   }
10260 
10261 public:
10262   RAUOVWUpdateListener(SelectionDAG &d, SmallVector<UseMemo, 4> &uses)
10263       : SelectionDAG::DAGUpdateListener(d), Uses(uses) {}
10264 };
10265 
10266 } // end anonymous namespace
10267 
10268 bool SelectionDAG::calculateDivergence(SDNode *N) {
10269   if (TLI->isSDNodeAlwaysUniform(N)) {
10270     assert(!TLI->isSDNodeSourceOfDivergence(N, FLI, DA) &&
10271            "Conflicting divergence information!");
10272     return false;
10273   }
10274   if (TLI->isSDNodeSourceOfDivergence(N, FLI, DA))
10275     return true;
10276   for (const auto &Op : N->ops()) {
10277     if (Op.Val.getValueType() != MVT::Other && Op.getNode()->isDivergent())
10278       return true;
10279   }
10280   return false;
10281 }
10282 
10283 void SelectionDAG::updateDivergence(SDNode *N) {
10284   SmallVector<SDNode *, 16> Worklist(1, N);
10285   do {
10286     N = Worklist.pop_back_val();
10287     bool IsDivergent = calculateDivergence(N);
10288     if (N->SDNodeBits.IsDivergent != IsDivergent) {
10289       N->SDNodeBits.IsDivergent = IsDivergent;
10290       llvm::append_range(Worklist, N->uses());
10291     }
10292   } while (!Worklist.empty());
10293 }
10294 
10295 void SelectionDAG::CreateTopologicalOrder(std::vector<SDNode *> &Order) {
10296   DenseMap<SDNode *, unsigned> Degree;
10297   Order.reserve(AllNodes.size());
10298   for (auto &N : allnodes()) {
10299     unsigned NOps = N.getNumOperands();
10300     Degree[&N] = NOps;
10301     if (0 == NOps)
10302       Order.push_back(&N);
10303   }
10304   for (size_t I = 0; I != Order.size(); ++I) {
10305     SDNode *N = Order[I];
10306     for (auto *U : N->uses()) {
10307       unsigned &UnsortedOps = Degree[U];
10308       if (0 == --UnsortedOps)
10309         Order.push_back(U);
10310     }
10311   }
10312 }
10313 
10314 #ifndef NDEBUG
10315 void SelectionDAG::VerifyDAGDivergence() {
10316   std::vector<SDNode *> TopoOrder;
10317   CreateTopologicalOrder(TopoOrder);
10318   for (auto *N : TopoOrder) {
10319     assert(calculateDivergence(N) == N->isDivergent() &&
10320            "Divergence bit inconsistency detected");
10321   }
10322 }
10323 #endif
10324 
10325 /// ReplaceAllUsesOfValuesWith - Replace any uses of From with To, leaving
10326 /// uses of other values produced by From.getNode() alone.  The same value
10327 /// may appear in both the From and To list.  The Deleted vector is
10328 /// handled the same way as for ReplaceAllUsesWith.
10329 void SelectionDAG::ReplaceAllUsesOfValuesWith(const SDValue *From,
10330                                               const SDValue *To,
10331                                               unsigned Num){
10332   // Handle the simple, trivial case efficiently.
10333   if (Num == 1)
10334     return ReplaceAllUsesOfValueWith(*From, *To);
10335 
10336   transferDbgValues(*From, *To);
10337 
10338   // Read up all the uses and make records of them. This helps
10339   // processing new uses that are introduced during the
10340   // replacement process.
10341   SmallVector<UseMemo, 4> Uses;
10342   for (unsigned i = 0; i != Num; ++i) {
10343     unsigned FromResNo = From[i].getResNo();
10344     SDNode *FromNode = From[i].getNode();
10345     for (SDNode::use_iterator UI = FromNode->use_begin(),
10346          E = FromNode->use_end(); UI != E; ++UI) {
10347       SDUse &Use = UI.getUse();
10348       if (Use.getResNo() == FromResNo) {
10349         UseMemo Memo = { *UI, i, &Use };
10350         Uses.push_back(Memo);
10351       }
10352     }
10353   }
10354 
10355   // Sort the uses, so that all the uses from a given User are together.
10356   llvm::sort(Uses);
10357   RAUOVWUpdateListener Listener(*this, Uses);
10358 
10359   for (unsigned UseIndex = 0, UseIndexEnd = Uses.size();
10360        UseIndex != UseIndexEnd; ) {
10361     // We know that this user uses some value of From.  If it is the right
10362     // value, update it.
10363     SDNode *User = Uses[UseIndex].User;
10364     // If the node has been deleted by recursive CSE updates when updating
10365     // another node, then just skip this entry.
10366     if (User == nullptr) {
10367       ++UseIndex;
10368       continue;
10369     }
10370 
10371     // This node is about to morph, remove its old self from the CSE maps.
10372     RemoveNodeFromCSEMaps(User);
10373 
10374     // The Uses array is sorted, so all the uses for a given User
10375     // are next to each other in the list.
10376     // To help reduce the number of CSE recomputations, process all
10377     // the uses of this user that we can find this way.
10378     do {
10379       unsigned i = Uses[UseIndex].Index;
10380       SDUse &Use = *Uses[UseIndex].Use;
10381       ++UseIndex;
10382 
10383       Use.set(To[i]);
10384     } while (UseIndex != UseIndexEnd && Uses[UseIndex].User == User);
10385 
10386     // Now that we have modified User, add it back to the CSE maps.  If it
10387     // already exists there, recursively merge the results together.
10388     AddModifiedNodeToCSEMaps(User);
10389   }
10390 }
10391 
10392 /// AssignTopologicalOrder - Assign a unique node id for each node in the DAG
10393 /// based on their topological order. It returns the maximum id and a vector
10394 /// of the SDNodes* in assigned order by reference.
10395 unsigned SelectionDAG::AssignTopologicalOrder() {
10396   unsigned DAGSize = 0;
10397 
10398   // SortedPos tracks the progress of the algorithm. Nodes before it are
10399   // sorted, nodes after it are unsorted. When the algorithm completes
10400   // it is at the end of the list.
10401   allnodes_iterator SortedPos = allnodes_begin();
10402 
10403   // Visit all the nodes. Move nodes with no operands to the front of
10404   // the list immediately. Annotate nodes that do have operands with their
10405   // operand count. Before we do this, the Node Id fields of the nodes
10406   // may contain arbitrary values. After, the Node Id fields for nodes
10407   // before SortedPos will contain the topological sort index, and the
10408   // Node Id fields for nodes At SortedPos and after will contain the
10409   // count of outstanding operands.
10410   for (SDNode &N : llvm::make_early_inc_range(allnodes())) {
10411     checkForCycles(&N, this);
10412     unsigned Degree = N.getNumOperands();
10413     if (Degree == 0) {
10414       // A node with no uses, add it to the result array immediately.
10415       N.setNodeId(DAGSize++);
10416       allnodes_iterator Q(&N);
10417       if (Q != SortedPos)
10418         SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(Q));
10419       assert(SortedPos != AllNodes.end() && "Overran node list");
10420       ++SortedPos;
10421     } else {
10422       // Temporarily use the Node Id as scratch space for the degree count.
10423       N.setNodeId(Degree);
10424     }
10425   }
10426 
10427   // Visit all the nodes. As we iterate, move nodes into sorted order,
10428   // such that by the time the end is reached all nodes will be sorted.
10429   for (SDNode &Node : allnodes()) {
10430     SDNode *N = &Node;
10431     checkForCycles(N, this);
10432     // N is in sorted position, so all its uses have one less operand
10433     // that needs to be sorted.
10434     for (SDNode *P : N->uses()) {
10435       unsigned Degree = P->getNodeId();
10436       assert(Degree != 0 && "Invalid node degree");
10437       --Degree;
10438       if (Degree == 0) {
10439         // All of P's operands are sorted, so P may sorted now.
10440         P->setNodeId(DAGSize++);
10441         if (P->getIterator() != SortedPos)
10442           SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(P));
10443         assert(SortedPos != AllNodes.end() && "Overran node list");
10444         ++SortedPos;
10445       } else {
10446         // Update P's outstanding operand count.
10447         P->setNodeId(Degree);
10448       }
10449     }
10450     if (Node.getIterator() == SortedPos) {
10451 #ifndef NDEBUG
10452       allnodes_iterator I(N);
10453       SDNode *S = &*++I;
10454       dbgs() << "Overran sorted position:\n";
10455       S->dumprFull(this); dbgs() << "\n";
10456       dbgs() << "Checking if this is due to cycles\n";
10457       checkForCycles(this, true);
10458 #endif
10459       llvm_unreachable(nullptr);
10460     }
10461   }
10462 
10463   assert(SortedPos == AllNodes.end() &&
10464          "Topological sort incomplete!");
10465   assert(AllNodes.front().getOpcode() == ISD::EntryToken &&
10466          "First node in topological sort is not the entry token!");
10467   assert(AllNodes.front().getNodeId() == 0 &&
10468          "First node in topological sort has non-zero id!");
10469   assert(AllNodes.front().getNumOperands() == 0 &&
10470          "First node in topological sort has operands!");
10471   assert(AllNodes.back().getNodeId() == (int)DAGSize-1 &&
10472          "Last node in topologic sort has unexpected id!");
10473   assert(AllNodes.back().use_empty() &&
10474          "Last node in topologic sort has users!");
10475   assert(DAGSize == allnodes_size() && "Node count mismatch!");
10476   return DAGSize;
10477 }
10478 
10479 /// AddDbgValue - Add a dbg_value SDNode. If SD is non-null that means the
10480 /// value is produced by SD.
10481 void SelectionDAG::AddDbgValue(SDDbgValue *DB, bool isParameter) {
10482   for (SDNode *SD : DB->getSDNodes()) {
10483     if (!SD)
10484       continue;
10485     assert(DbgInfo->getSDDbgValues(SD).empty() || SD->getHasDebugValue());
10486     SD->setHasDebugValue(true);
10487   }
10488   DbgInfo->add(DB, isParameter);
10489 }
10490 
10491 void SelectionDAG::AddDbgLabel(SDDbgLabel *DB) { DbgInfo->add(DB); }
10492 
10493 SDValue SelectionDAG::makeEquivalentMemoryOrdering(SDValue OldChain,
10494                                                    SDValue NewMemOpChain) {
10495   assert(isa<MemSDNode>(NewMemOpChain) && "Expected a memop node");
10496   assert(NewMemOpChain.getValueType() == MVT::Other && "Expected a token VT");
10497   // The new memory operation must have the same position as the old load in
10498   // terms of memory dependency. Create a TokenFactor for the old load and new
10499   // memory operation and update uses of the old load's output chain to use that
10500   // TokenFactor.
10501   if (OldChain == NewMemOpChain || OldChain.use_empty())
10502     return NewMemOpChain;
10503 
10504   SDValue TokenFactor = getNode(ISD::TokenFactor, SDLoc(OldChain), MVT::Other,
10505                                 OldChain, NewMemOpChain);
10506   ReplaceAllUsesOfValueWith(OldChain, TokenFactor);
10507   UpdateNodeOperands(TokenFactor.getNode(), OldChain, NewMemOpChain);
10508   return TokenFactor;
10509 }
10510 
10511 SDValue SelectionDAG::makeEquivalentMemoryOrdering(LoadSDNode *OldLoad,
10512                                                    SDValue NewMemOp) {
10513   assert(isa<MemSDNode>(NewMemOp.getNode()) && "Expected a memop node");
10514   SDValue OldChain = SDValue(OldLoad, 1);
10515   SDValue NewMemOpChain = NewMemOp.getValue(1);
10516   return makeEquivalentMemoryOrdering(OldChain, NewMemOpChain);
10517 }
10518 
10519 SDValue SelectionDAG::getSymbolFunctionGlobalAddress(SDValue Op,
10520                                                      Function **OutFunction) {
10521   assert(isa<ExternalSymbolSDNode>(Op) && "Node should be an ExternalSymbol");
10522 
10523   auto *Symbol = cast<ExternalSymbolSDNode>(Op)->getSymbol();
10524   auto *Module = MF->getFunction().getParent();
10525   auto *Function = Module->getFunction(Symbol);
10526 
10527   if (OutFunction != nullptr)
10528       *OutFunction = Function;
10529 
10530   if (Function != nullptr) {
10531     auto PtrTy = TLI->getPointerTy(getDataLayout(), Function->getAddressSpace());
10532     return getGlobalAddress(Function, SDLoc(Op), PtrTy);
10533   }
10534 
10535   std::string ErrorStr;
10536   raw_string_ostream ErrorFormatter(ErrorStr);
10537   ErrorFormatter << "Undefined external symbol ";
10538   ErrorFormatter << '"' << Symbol << '"';
10539   report_fatal_error(Twine(ErrorFormatter.str()));
10540 }
10541 
10542 //===----------------------------------------------------------------------===//
10543 //                              SDNode Class
10544 //===----------------------------------------------------------------------===//
10545 
10546 bool llvm::isNullConstant(SDValue V) {
10547   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
10548   return Const != nullptr && Const->isZero();
10549 }
10550 
10551 bool llvm::isNullFPConstant(SDValue V) {
10552   ConstantFPSDNode *Const = dyn_cast<ConstantFPSDNode>(V);
10553   return Const != nullptr && Const->isZero() && !Const->isNegative();
10554 }
10555 
10556 bool llvm::isAllOnesConstant(SDValue V) {
10557   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
10558   return Const != nullptr && Const->isAllOnes();
10559 }
10560 
10561 bool llvm::isOneConstant(SDValue V) {
10562   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
10563   return Const != nullptr && Const->isOne();
10564 }
10565 
10566 bool llvm::isMinSignedConstant(SDValue V) {
10567   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
10568   return Const != nullptr && Const->isMinSignedValue();
10569 }
10570 
10571 SDValue llvm::peekThroughBitcasts(SDValue V) {
10572   while (V.getOpcode() == ISD::BITCAST)
10573     V = V.getOperand(0);
10574   return V;
10575 }
10576 
10577 SDValue llvm::peekThroughOneUseBitcasts(SDValue V) {
10578   while (V.getOpcode() == ISD::BITCAST && V.getOperand(0).hasOneUse())
10579     V = V.getOperand(0);
10580   return V;
10581 }
10582 
10583 SDValue llvm::peekThroughExtractSubvectors(SDValue V) {
10584   while (V.getOpcode() == ISD::EXTRACT_SUBVECTOR)
10585     V = V.getOperand(0);
10586   return V;
10587 }
10588 
10589 bool llvm::isBitwiseNot(SDValue V, bool AllowUndefs) {
10590   if (V.getOpcode() != ISD::XOR)
10591     return false;
10592   V = peekThroughBitcasts(V.getOperand(1));
10593   unsigned NumBits = V.getScalarValueSizeInBits();
10594   ConstantSDNode *C =
10595       isConstOrConstSplat(V, AllowUndefs, /*AllowTruncation*/ true);
10596   return C && (C->getAPIntValue().countTrailingOnes() >= NumBits);
10597 }
10598 
10599 ConstantSDNode *llvm::isConstOrConstSplat(SDValue N, bool AllowUndefs,
10600                                           bool AllowTruncation) {
10601   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
10602     return CN;
10603 
10604   // SplatVectors can truncate their operands. Ignore that case here unless
10605   // AllowTruncation is set.
10606   if (N->getOpcode() == ISD::SPLAT_VECTOR) {
10607     EVT VecEltVT = N->getValueType(0).getVectorElementType();
10608     if (auto *CN = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
10609       EVT CVT = CN->getValueType(0);
10610       assert(CVT.bitsGE(VecEltVT) && "Illegal splat_vector element extension");
10611       if (AllowTruncation || CVT == VecEltVT)
10612         return CN;
10613     }
10614   }
10615 
10616   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
10617     BitVector UndefElements;
10618     ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
10619 
10620     // BuildVectors can truncate their operands. Ignore that case here unless
10621     // AllowTruncation is set.
10622     if (CN && (UndefElements.none() || AllowUndefs)) {
10623       EVT CVT = CN->getValueType(0);
10624       EVT NSVT = N.getValueType().getScalarType();
10625       assert(CVT.bitsGE(NSVT) && "Illegal build vector element extension");
10626       if (AllowTruncation || (CVT == NSVT))
10627         return CN;
10628     }
10629   }
10630 
10631   return nullptr;
10632 }
10633 
10634 ConstantSDNode *llvm::isConstOrConstSplat(SDValue N, const APInt &DemandedElts,
10635                                           bool AllowUndefs,
10636                                           bool AllowTruncation) {
10637   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
10638     return CN;
10639 
10640   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
10641     BitVector UndefElements;
10642     ConstantSDNode *CN = BV->getConstantSplatNode(DemandedElts, &UndefElements);
10643 
10644     // BuildVectors can truncate their operands. Ignore that case here unless
10645     // AllowTruncation is set.
10646     if (CN && (UndefElements.none() || AllowUndefs)) {
10647       EVT CVT = CN->getValueType(0);
10648       EVT NSVT = N.getValueType().getScalarType();
10649       assert(CVT.bitsGE(NSVT) && "Illegal build vector element extension");
10650       if (AllowTruncation || (CVT == NSVT))
10651         return CN;
10652     }
10653   }
10654 
10655   return nullptr;
10656 }
10657 
10658 ConstantFPSDNode *llvm::isConstOrConstSplatFP(SDValue N, bool AllowUndefs) {
10659   if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
10660     return CN;
10661 
10662   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
10663     BitVector UndefElements;
10664     ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements);
10665     if (CN && (UndefElements.none() || AllowUndefs))
10666       return CN;
10667   }
10668 
10669   if (N.getOpcode() == ISD::SPLAT_VECTOR)
10670     if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N.getOperand(0)))
10671       return CN;
10672 
10673   return nullptr;
10674 }
10675 
10676 ConstantFPSDNode *llvm::isConstOrConstSplatFP(SDValue N,
10677                                               const APInt &DemandedElts,
10678                                               bool AllowUndefs) {
10679   if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
10680     return CN;
10681 
10682   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
10683     BitVector UndefElements;
10684     ConstantFPSDNode *CN =
10685         BV->getConstantFPSplatNode(DemandedElts, &UndefElements);
10686     if (CN && (UndefElements.none() || AllowUndefs))
10687       return CN;
10688   }
10689 
10690   return nullptr;
10691 }
10692 
10693 bool llvm::isNullOrNullSplat(SDValue N, bool AllowUndefs) {
10694   // TODO: may want to use peekThroughBitcast() here.
10695   ConstantSDNode *C =
10696       isConstOrConstSplat(N, AllowUndefs, /*AllowTruncation=*/true);
10697   return C && C->isZero();
10698 }
10699 
10700 bool llvm::isOneOrOneSplat(SDValue N, bool AllowUndefs) {
10701   ConstantSDNode *C =
10702       isConstOrConstSplat(N, AllowUndefs, /*AllowTruncation*/ true);
10703   return C && C->isOne();
10704 }
10705 
10706 bool llvm::isAllOnesOrAllOnesSplat(SDValue N, bool AllowUndefs) {
10707   N = peekThroughBitcasts(N);
10708   unsigned BitWidth = N.getScalarValueSizeInBits();
10709   ConstantSDNode *C = isConstOrConstSplat(N, AllowUndefs);
10710   return C && C->isAllOnes() && C->getValueSizeInBits(0) == BitWidth;
10711 }
10712 
10713 HandleSDNode::~HandleSDNode() {
10714   DropOperands();
10715 }
10716 
10717 GlobalAddressSDNode::GlobalAddressSDNode(unsigned Opc, unsigned Order,
10718                                          const DebugLoc &DL,
10719                                          const GlobalValue *GA, EVT VT,
10720                                          int64_t o, unsigned TF)
10721     : SDNode(Opc, Order, DL, getSDVTList(VT)), Offset(o), TargetFlags(TF) {
10722   TheGlobal = GA;
10723 }
10724 
10725 AddrSpaceCastSDNode::AddrSpaceCastSDNode(unsigned Order, const DebugLoc &dl,
10726                                          EVT VT, unsigned SrcAS,
10727                                          unsigned DestAS)
10728     : SDNode(ISD::ADDRSPACECAST, Order, dl, getSDVTList(VT)),
10729       SrcAddrSpace(SrcAS), DestAddrSpace(DestAS) {}
10730 
10731 MemSDNode::MemSDNode(unsigned Opc, unsigned Order, const DebugLoc &dl,
10732                      SDVTList VTs, EVT memvt, MachineMemOperand *mmo)
10733     : SDNode(Opc, Order, dl, VTs), MemoryVT(memvt), MMO(mmo) {
10734   MemSDNodeBits.IsVolatile = MMO->isVolatile();
10735   MemSDNodeBits.IsNonTemporal = MMO->isNonTemporal();
10736   MemSDNodeBits.IsDereferenceable = MMO->isDereferenceable();
10737   MemSDNodeBits.IsInvariant = MMO->isInvariant();
10738 
10739   // We check here that the size of the memory operand fits within the size of
10740   // the MMO. This is because the MMO might indicate only a possible address
10741   // range instead of specifying the affected memory addresses precisely.
10742   // TODO: Make MachineMemOperands aware of scalable vectors.
10743   assert(memvt.getStoreSize().getKnownMinSize() <= MMO->getSize() &&
10744          "Size mismatch!");
10745 }
10746 
10747 /// Profile - Gather unique data for the node.
10748 ///
10749 void SDNode::Profile(FoldingSetNodeID &ID) const {
10750   AddNodeIDNode(ID, this);
10751 }
10752 
10753 namespace {
10754 
10755   struct EVTArray {
10756     std::vector<EVT> VTs;
10757 
10758     EVTArray() {
10759       VTs.reserve(MVT::VALUETYPE_SIZE);
10760       for (unsigned i = 0; i < MVT::VALUETYPE_SIZE; ++i)
10761         VTs.push_back(MVT((MVT::SimpleValueType)i));
10762     }
10763   };
10764 
10765 } // end anonymous namespace
10766 
10767 /// getValueTypeList - Return a pointer to the specified value type.
10768 ///
10769 const EVT *SDNode::getValueTypeList(EVT VT) {
10770   static std::set<EVT, EVT::compareRawBits> EVTs;
10771   static EVTArray SimpleVTArray;
10772   static sys::SmartMutex<true> VTMutex;
10773 
10774   if (VT.isExtended()) {
10775     sys::SmartScopedLock<true> Lock(VTMutex);
10776     return &(*EVTs.insert(VT).first);
10777   }
10778   assert(VT.getSimpleVT() < MVT::VALUETYPE_SIZE && "Value type out of range!");
10779   return &SimpleVTArray.VTs[VT.getSimpleVT().SimpleTy];
10780 }
10781 
10782 /// hasNUsesOfValue - Return true if there are exactly NUSES uses of the
10783 /// indicated value.  This method ignores uses of other values defined by this
10784 /// operation.
10785 bool SDNode::hasNUsesOfValue(unsigned NUses, unsigned Value) const {
10786   assert(Value < getNumValues() && "Bad value!");
10787 
10788   // TODO: Only iterate over uses of a given value of the node
10789   for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) {
10790     if (UI.getUse().getResNo() == Value) {
10791       if (NUses == 0)
10792         return false;
10793       --NUses;
10794     }
10795   }
10796 
10797   // Found exactly the right number of uses?
10798   return NUses == 0;
10799 }
10800 
10801 /// hasAnyUseOfValue - Return true if there are any use of the indicated
10802 /// value. This method ignores uses of other values defined by this operation.
10803 bool SDNode::hasAnyUseOfValue(unsigned Value) const {
10804   assert(Value < getNumValues() && "Bad value!");
10805 
10806   for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI)
10807     if (UI.getUse().getResNo() == Value)
10808       return true;
10809 
10810   return false;
10811 }
10812 
10813 /// isOnlyUserOf - Return true if this node is the only use of N.
10814 bool SDNode::isOnlyUserOf(const SDNode *N) const {
10815   bool Seen = false;
10816   for (const SDNode *User : N->uses()) {
10817     if (User == this)
10818       Seen = true;
10819     else
10820       return false;
10821   }
10822 
10823   return Seen;
10824 }
10825 
10826 /// Return true if the only users of N are contained in Nodes.
10827 bool SDNode::areOnlyUsersOf(ArrayRef<const SDNode *> Nodes, const SDNode *N) {
10828   bool Seen = false;
10829   for (const SDNode *User : N->uses()) {
10830     if (llvm::is_contained(Nodes, User))
10831       Seen = true;
10832     else
10833       return false;
10834   }
10835 
10836   return Seen;
10837 }
10838 
10839 /// isOperand - Return true if this node is an operand of N.
10840 bool SDValue::isOperandOf(const SDNode *N) const {
10841   return is_contained(N->op_values(), *this);
10842 }
10843 
10844 bool SDNode::isOperandOf(const SDNode *N) const {
10845   return any_of(N->op_values(),
10846                 [this](SDValue Op) { return this == Op.getNode(); });
10847 }
10848 
10849 /// reachesChainWithoutSideEffects - Return true if this operand (which must
10850 /// be a chain) reaches the specified operand without crossing any
10851 /// side-effecting instructions on any chain path.  In practice, this looks
10852 /// through token factors and non-volatile loads.  In order to remain efficient,
10853 /// this only looks a couple of nodes in, it does not do an exhaustive search.
10854 ///
10855 /// Note that we only need to examine chains when we're searching for
10856 /// side-effects; SelectionDAG requires that all side-effects are represented
10857 /// by chains, even if another operand would force a specific ordering. This
10858 /// constraint is necessary to allow transformations like splitting loads.
10859 bool SDValue::reachesChainWithoutSideEffects(SDValue Dest,
10860                                              unsigned Depth) const {
10861   if (*this == Dest) return true;
10862 
10863   // Don't search too deeply, we just want to be able to see through
10864   // TokenFactor's etc.
10865   if (Depth == 0) return false;
10866 
10867   // If this is a token factor, all inputs to the TF happen in parallel.
10868   if (getOpcode() == ISD::TokenFactor) {
10869     // First, try a shallow search.
10870     if (is_contained((*this)->ops(), Dest)) {
10871       // We found the chain we want as an operand of this TokenFactor.
10872       // Essentially, we reach the chain without side-effects if we could
10873       // serialize the TokenFactor into a simple chain of operations with
10874       // Dest as the last operation. This is automatically true if the
10875       // chain has one use: there are no other ordering constraints.
10876       // If the chain has more than one use, we give up: some other
10877       // use of Dest might force a side-effect between Dest and the current
10878       // node.
10879       if (Dest.hasOneUse())
10880         return true;
10881     }
10882     // Next, try a deep search: check whether every operand of the TokenFactor
10883     // reaches Dest.
10884     return llvm::all_of((*this)->ops(), [=](SDValue Op) {
10885       return Op.reachesChainWithoutSideEffects(Dest, Depth - 1);
10886     });
10887   }
10888 
10889   // Loads don't have side effects, look through them.
10890   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(*this)) {
10891     if (Ld->isUnordered())
10892       return Ld->getChain().reachesChainWithoutSideEffects(Dest, Depth-1);
10893   }
10894   return false;
10895 }
10896 
10897 bool SDNode::hasPredecessor(const SDNode *N) const {
10898   SmallPtrSet<const SDNode *, 32> Visited;
10899   SmallVector<const SDNode *, 16> Worklist;
10900   Worklist.push_back(this);
10901   return hasPredecessorHelper(N, Visited, Worklist);
10902 }
10903 
10904 void SDNode::intersectFlagsWith(const SDNodeFlags Flags) {
10905   this->Flags.intersectWith(Flags);
10906 }
10907 
10908 SDValue
10909 SelectionDAG::matchBinOpReduction(SDNode *Extract, ISD::NodeType &BinOp,
10910                                   ArrayRef<ISD::NodeType> CandidateBinOps,
10911                                   bool AllowPartials) {
10912   // The pattern must end in an extract from index 0.
10913   if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10914       !isNullConstant(Extract->getOperand(1)))
10915     return SDValue();
10916 
10917   // Match against one of the candidate binary ops.
10918   SDValue Op = Extract->getOperand(0);
10919   if (llvm::none_of(CandidateBinOps, [Op](ISD::NodeType BinOp) {
10920         return Op.getOpcode() == unsigned(BinOp);
10921       }))
10922     return SDValue();
10923 
10924   // Floating-point reductions may require relaxed constraints on the final step
10925   // of the reduction because they may reorder intermediate operations.
10926   unsigned CandidateBinOp = Op.getOpcode();
10927   if (Op.getValueType().isFloatingPoint()) {
10928     SDNodeFlags Flags = Op->getFlags();
10929     switch (CandidateBinOp) {
10930     case ISD::FADD:
10931       if (!Flags.hasNoSignedZeros() || !Flags.hasAllowReassociation())
10932         return SDValue();
10933       break;
10934     default:
10935       llvm_unreachable("Unhandled FP opcode for binop reduction");
10936     }
10937   }
10938 
10939   // Matching failed - attempt to see if we did enough stages that a partial
10940   // reduction from a subvector is possible.
10941   auto PartialReduction = [&](SDValue Op, unsigned NumSubElts) {
10942     if (!AllowPartials || !Op)
10943       return SDValue();
10944     EVT OpVT = Op.getValueType();
10945     EVT OpSVT = OpVT.getScalarType();
10946     EVT SubVT = EVT::getVectorVT(*getContext(), OpSVT, NumSubElts);
10947     if (!TLI->isExtractSubvectorCheap(SubVT, OpVT, 0))
10948       return SDValue();
10949     BinOp = (ISD::NodeType)CandidateBinOp;
10950     return getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(Op), SubVT, Op,
10951                    getVectorIdxConstant(0, SDLoc(Op)));
10952   };
10953 
10954   // At each stage, we're looking for something that looks like:
10955   // %s = shufflevector <8 x i32> %op, <8 x i32> undef,
10956   //                    <8 x i32> <i32 2, i32 3, i32 undef, i32 undef,
10957   //                               i32 undef, i32 undef, i32 undef, i32 undef>
10958   // %a = binop <8 x i32> %op, %s
10959   // Where the mask changes according to the stage. E.g. for a 3-stage pyramid,
10960   // we expect something like:
10961   // <4,5,6,7,u,u,u,u>
10962   // <2,3,u,u,u,u,u,u>
10963   // <1,u,u,u,u,u,u,u>
10964   // While a partial reduction match would be:
10965   // <2,3,u,u,u,u,u,u>
10966   // <1,u,u,u,u,u,u,u>
10967   unsigned Stages = Log2_32(Op.getValueType().getVectorNumElements());
10968   SDValue PrevOp;
10969   for (unsigned i = 0; i < Stages; ++i) {
10970     unsigned MaskEnd = (1 << i);
10971 
10972     if (Op.getOpcode() != CandidateBinOp)
10973       return PartialReduction(PrevOp, MaskEnd);
10974 
10975     SDValue Op0 = Op.getOperand(0);
10976     SDValue Op1 = Op.getOperand(1);
10977 
10978     ShuffleVectorSDNode *Shuffle = dyn_cast<ShuffleVectorSDNode>(Op0);
10979     if (Shuffle) {
10980       Op = Op1;
10981     } else {
10982       Shuffle = dyn_cast<ShuffleVectorSDNode>(Op1);
10983       Op = Op0;
10984     }
10985 
10986     // The first operand of the shuffle should be the same as the other operand
10987     // of the binop.
10988     if (!Shuffle || Shuffle->getOperand(0) != Op)
10989       return PartialReduction(PrevOp, MaskEnd);
10990 
10991     // Verify the shuffle has the expected (at this stage of the pyramid) mask.
10992     for (int Index = 0; Index < (int)MaskEnd; ++Index)
10993       if (Shuffle->getMaskElt(Index) != (int)(MaskEnd + Index))
10994         return PartialReduction(PrevOp, MaskEnd);
10995 
10996     PrevOp = Op;
10997   }
10998 
10999   // Handle subvector reductions, which tend to appear after the shuffle
11000   // reduction stages.
11001   while (Op.getOpcode() == CandidateBinOp) {
11002     unsigned NumElts = Op.getValueType().getVectorNumElements();
11003     SDValue Op0 = Op.getOperand(0);
11004     SDValue Op1 = Op.getOperand(1);
11005     if (Op0.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
11006         Op1.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
11007         Op0.getOperand(0) != Op1.getOperand(0))
11008       break;
11009     SDValue Src = Op0.getOperand(0);
11010     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
11011     if (NumSrcElts != (2 * NumElts))
11012       break;
11013     if (!(Op0.getConstantOperandAPInt(1) == 0 &&
11014           Op1.getConstantOperandAPInt(1) == NumElts) &&
11015         !(Op1.getConstantOperandAPInt(1) == 0 &&
11016           Op0.getConstantOperandAPInt(1) == NumElts))
11017       break;
11018     Op = Src;
11019   }
11020 
11021   BinOp = (ISD::NodeType)CandidateBinOp;
11022   return Op;
11023 }
11024 
11025 SDValue SelectionDAG::UnrollVectorOp(SDNode *N, unsigned ResNE) {
11026   assert(N->getNumValues() == 1 &&
11027          "Can't unroll a vector with multiple results!");
11028 
11029   EVT VT = N->getValueType(0);
11030   unsigned NE = VT.getVectorNumElements();
11031   EVT EltVT = VT.getVectorElementType();
11032   SDLoc dl(N);
11033 
11034   SmallVector<SDValue, 8> Scalars;
11035   SmallVector<SDValue, 4> Operands(N->getNumOperands());
11036 
11037   // If ResNE is 0, fully unroll the vector op.
11038   if (ResNE == 0)
11039     ResNE = NE;
11040   else if (NE > ResNE)
11041     NE = ResNE;
11042 
11043   unsigned i;
11044   for (i= 0; i != NE; ++i) {
11045     for (unsigned j = 0, e = N->getNumOperands(); j != e; ++j) {
11046       SDValue Operand = N->getOperand(j);
11047       EVT OperandVT = Operand.getValueType();
11048       if (OperandVT.isVector()) {
11049         // A vector operand; extract a single element.
11050         EVT OperandEltVT = OperandVT.getVectorElementType();
11051         Operands[j] = getNode(ISD::EXTRACT_VECTOR_ELT, dl, OperandEltVT,
11052                               Operand, getVectorIdxConstant(i, dl));
11053       } else {
11054         // A scalar operand; just use it as is.
11055         Operands[j] = Operand;
11056       }
11057     }
11058 
11059     switch (N->getOpcode()) {
11060     default: {
11061       Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands,
11062                                 N->getFlags()));
11063       break;
11064     }
11065     case ISD::VSELECT:
11066       Scalars.push_back(getNode(ISD::SELECT, dl, EltVT, Operands));
11067       break;
11068     case ISD::SHL:
11069     case ISD::SRA:
11070     case ISD::SRL:
11071     case ISD::ROTL:
11072     case ISD::ROTR:
11073       Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands[0],
11074                                getShiftAmountOperand(Operands[0].getValueType(),
11075                                                      Operands[1])));
11076       break;
11077     case ISD::SIGN_EXTEND_INREG: {
11078       EVT ExtVT = cast<VTSDNode>(Operands[1])->getVT().getVectorElementType();
11079       Scalars.push_back(getNode(N->getOpcode(), dl, EltVT,
11080                                 Operands[0],
11081                                 getValueType(ExtVT)));
11082     }
11083     }
11084   }
11085 
11086   for (; i < ResNE; ++i)
11087     Scalars.push_back(getUNDEF(EltVT));
11088 
11089   EVT VecVT = EVT::getVectorVT(*getContext(), EltVT, ResNE);
11090   return getBuildVector(VecVT, dl, Scalars);
11091 }
11092 
11093 std::pair<SDValue, SDValue> SelectionDAG::UnrollVectorOverflowOp(
11094     SDNode *N, unsigned ResNE) {
11095   unsigned Opcode = N->getOpcode();
11096   assert((Opcode == ISD::UADDO || Opcode == ISD::SADDO ||
11097           Opcode == ISD::USUBO || Opcode == ISD::SSUBO ||
11098           Opcode == ISD::UMULO || Opcode == ISD::SMULO) &&
11099          "Expected an overflow opcode");
11100 
11101   EVT ResVT = N->getValueType(0);
11102   EVT OvVT = N->getValueType(1);
11103   EVT ResEltVT = ResVT.getVectorElementType();
11104   EVT OvEltVT = OvVT.getVectorElementType();
11105   SDLoc dl(N);
11106 
11107   // If ResNE is 0, fully unroll the vector op.
11108   unsigned NE = ResVT.getVectorNumElements();
11109   if (ResNE == 0)
11110     ResNE = NE;
11111   else if (NE > ResNE)
11112     NE = ResNE;
11113 
11114   SmallVector<SDValue, 8> LHSScalars;
11115   SmallVector<SDValue, 8> RHSScalars;
11116   ExtractVectorElements(N->getOperand(0), LHSScalars, 0, NE);
11117   ExtractVectorElements(N->getOperand(1), RHSScalars, 0, NE);
11118 
11119   EVT SVT = TLI->getSetCCResultType(getDataLayout(), *getContext(), ResEltVT);
11120   SDVTList VTs = getVTList(ResEltVT, SVT);
11121   SmallVector<SDValue, 8> ResScalars;
11122   SmallVector<SDValue, 8> OvScalars;
11123   for (unsigned i = 0; i < NE; ++i) {
11124     SDValue Res = getNode(Opcode, dl, VTs, LHSScalars[i], RHSScalars[i]);
11125     SDValue Ov =
11126         getSelect(dl, OvEltVT, Res.getValue(1),
11127                   getBoolConstant(true, dl, OvEltVT, ResVT),
11128                   getConstant(0, dl, OvEltVT));
11129 
11130     ResScalars.push_back(Res);
11131     OvScalars.push_back(Ov);
11132   }
11133 
11134   ResScalars.append(ResNE - NE, getUNDEF(ResEltVT));
11135   OvScalars.append(ResNE - NE, getUNDEF(OvEltVT));
11136 
11137   EVT NewResVT = EVT::getVectorVT(*getContext(), ResEltVT, ResNE);
11138   EVT NewOvVT = EVT::getVectorVT(*getContext(), OvEltVT, ResNE);
11139   return std::make_pair(getBuildVector(NewResVT, dl, ResScalars),
11140                         getBuildVector(NewOvVT, dl, OvScalars));
11141 }
11142 
11143 bool SelectionDAG::areNonVolatileConsecutiveLoads(LoadSDNode *LD,
11144                                                   LoadSDNode *Base,
11145                                                   unsigned Bytes,
11146                                                   int Dist) const {
11147   if (LD->isVolatile() || Base->isVolatile())
11148     return false;
11149   // TODO: probably too restrictive for atomics, revisit
11150   if (!LD->isSimple())
11151     return false;
11152   if (LD->isIndexed() || Base->isIndexed())
11153     return false;
11154   if (LD->getChain() != Base->getChain())
11155     return false;
11156   EVT VT = LD->getValueType(0);
11157   if (VT.getSizeInBits() / 8 != Bytes)
11158     return false;
11159 
11160   auto BaseLocDecomp = BaseIndexOffset::match(Base, *this);
11161   auto LocDecomp = BaseIndexOffset::match(LD, *this);
11162 
11163   int64_t Offset = 0;
11164   if (BaseLocDecomp.equalBaseIndex(LocDecomp, *this, Offset))
11165     return (Dist * Bytes == Offset);
11166   return false;
11167 }
11168 
11169 /// InferPtrAlignment - Infer alignment of a load / store address. Return None
11170 /// if it cannot be inferred.
11171 MaybeAlign SelectionDAG::InferPtrAlign(SDValue Ptr) const {
11172   // If this is a GlobalAddress + cst, return the alignment.
11173   const GlobalValue *GV = nullptr;
11174   int64_t GVOffset = 0;
11175   if (TLI->isGAPlusOffset(Ptr.getNode(), GV, GVOffset)) {
11176     unsigned PtrWidth = getDataLayout().getPointerTypeSizeInBits(GV->getType());
11177     KnownBits Known(PtrWidth);
11178     llvm::computeKnownBits(GV, Known, getDataLayout());
11179     unsigned AlignBits = Known.countMinTrailingZeros();
11180     if (AlignBits)
11181       return commonAlignment(Align(1ull << std::min(31U, AlignBits)), GVOffset);
11182   }
11183 
11184   // If this is a direct reference to a stack slot, use information about the
11185   // stack slot's alignment.
11186   int FrameIdx = INT_MIN;
11187   int64_t FrameOffset = 0;
11188   if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr)) {
11189     FrameIdx = FI->getIndex();
11190   } else if (isBaseWithConstantOffset(Ptr) &&
11191              isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
11192     // Handle FI+Cst
11193     FrameIdx = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
11194     FrameOffset = Ptr.getConstantOperandVal(1);
11195   }
11196 
11197   if (FrameIdx != INT_MIN) {
11198     const MachineFrameInfo &MFI = getMachineFunction().getFrameInfo();
11199     return commonAlignment(MFI.getObjectAlign(FrameIdx), FrameOffset);
11200   }
11201 
11202   return None;
11203 }
11204 
11205 /// GetSplitDestVTs - Compute the VTs needed for the low/hi parts of a type
11206 /// which is split (or expanded) into two not necessarily identical pieces.
11207 std::pair<EVT, EVT> SelectionDAG::GetSplitDestVTs(const EVT &VT) const {
11208   // Currently all types are split in half.
11209   EVT LoVT, HiVT;
11210   if (!VT.isVector())
11211     LoVT = HiVT = TLI->getTypeToTransformTo(*getContext(), VT);
11212   else
11213     LoVT = HiVT = VT.getHalfNumVectorElementsVT(*getContext());
11214 
11215   return std::make_pair(LoVT, HiVT);
11216 }
11217 
11218 /// GetDependentSplitDestVTs - Compute the VTs needed for the low/hi parts of a
11219 /// type, dependent on an enveloping VT that has been split into two identical
11220 /// pieces. Sets the HiIsEmpty flag when hi type has zero storage size.
11221 std::pair<EVT, EVT>
11222 SelectionDAG::GetDependentSplitDestVTs(const EVT &VT, const EVT &EnvVT,
11223                                        bool *HiIsEmpty) const {
11224   EVT EltTp = VT.getVectorElementType();
11225   // Examples:
11226   //   custom VL=8  with enveloping VL=8/8 yields 8/0 (hi empty)
11227   //   custom VL=9  with enveloping VL=8/8 yields 8/1
11228   //   custom VL=10 with enveloping VL=8/8 yields 8/2
11229   //   etc.
11230   ElementCount VTNumElts = VT.getVectorElementCount();
11231   ElementCount EnvNumElts = EnvVT.getVectorElementCount();
11232   assert(VTNumElts.isScalable() == EnvNumElts.isScalable() &&
11233          "Mixing fixed width and scalable vectors when enveloping a type");
11234   EVT LoVT, HiVT;
11235   if (VTNumElts.getKnownMinValue() > EnvNumElts.getKnownMinValue()) {
11236     LoVT = EVT::getVectorVT(*getContext(), EltTp, EnvNumElts);
11237     HiVT = EVT::getVectorVT(*getContext(), EltTp, VTNumElts - EnvNumElts);
11238     *HiIsEmpty = false;
11239   } else {
11240     // Flag that hi type has zero storage size, but return split envelop type
11241     // (this would be easier if vector types with zero elements were allowed).
11242     LoVT = EVT::getVectorVT(*getContext(), EltTp, VTNumElts);
11243     HiVT = EVT::getVectorVT(*getContext(), EltTp, EnvNumElts);
11244     *HiIsEmpty = true;
11245   }
11246   return std::make_pair(LoVT, HiVT);
11247 }
11248 
11249 /// SplitVector - Split the vector with EXTRACT_SUBVECTOR and return the
11250 /// low/high part.
11251 std::pair<SDValue, SDValue>
11252 SelectionDAG::SplitVector(const SDValue &N, const SDLoc &DL, const EVT &LoVT,
11253                           const EVT &HiVT) {
11254   assert(LoVT.isScalableVector() == HiVT.isScalableVector() &&
11255          LoVT.isScalableVector() == N.getValueType().isScalableVector() &&
11256          "Splitting vector with an invalid mixture of fixed and scalable "
11257          "vector types");
11258   assert(LoVT.getVectorMinNumElements() + HiVT.getVectorMinNumElements() <=
11259              N.getValueType().getVectorMinNumElements() &&
11260          "More vector elements requested than available!");
11261   SDValue Lo, Hi;
11262   Lo =
11263       getNode(ISD::EXTRACT_SUBVECTOR, DL, LoVT, N, getVectorIdxConstant(0, DL));
11264   // For scalable vectors it is safe to use LoVT.getVectorMinNumElements()
11265   // (rather than having to use ElementCount), because EXTRACT_SUBVECTOR scales
11266   // IDX with the runtime scaling factor of the result vector type. For
11267   // fixed-width result vectors, that runtime scaling factor is 1.
11268   Hi = getNode(ISD::EXTRACT_SUBVECTOR, DL, HiVT, N,
11269                getVectorIdxConstant(LoVT.getVectorMinNumElements(), DL));
11270   return std::make_pair(Lo, Hi);
11271 }
11272 
11273 std::pair<SDValue, SDValue> SelectionDAG::SplitEVL(SDValue N, EVT VecVT,
11274                                                    const SDLoc &DL) {
11275   // Split the vector length parameter.
11276   // %evl -> umin(%evl, %halfnumelts) and usubsat(%evl - %halfnumelts).
11277   EVT VT = N.getValueType();
11278   assert(VecVT.getVectorElementCount().isKnownEven() &&
11279          "Expecting the mask to be an evenly-sized vector");
11280   unsigned HalfMinNumElts = VecVT.getVectorMinNumElements() / 2;
11281   SDValue HalfNumElts =
11282       VecVT.isFixedLengthVector()
11283           ? getConstant(HalfMinNumElts, DL, VT)
11284           : getVScale(DL, VT, APInt(VT.getScalarSizeInBits(), HalfMinNumElts));
11285   SDValue Lo = getNode(ISD::UMIN, DL, VT, N, HalfNumElts);
11286   SDValue Hi = getNode(ISD::USUBSAT, DL, VT, N, HalfNumElts);
11287   return std::make_pair(Lo, Hi);
11288 }
11289 
11290 /// Widen the vector up to the next power of two using INSERT_SUBVECTOR.
11291 SDValue SelectionDAG::WidenVector(const SDValue &N, const SDLoc &DL) {
11292   EVT VT = N.getValueType();
11293   EVT WideVT = EVT::getVectorVT(*getContext(), VT.getVectorElementType(),
11294                                 NextPowerOf2(VT.getVectorNumElements()));
11295   return getNode(ISD::INSERT_SUBVECTOR, DL, WideVT, getUNDEF(WideVT), N,
11296                  getVectorIdxConstant(0, DL));
11297 }
11298 
11299 void SelectionDAG::ExtractVectorElements(SDValue Op,
11300                                          SmallVectorImpl<SDValue> &Args,
11301                                          unsigned Start, unsigned Count,
11302                                          EVT EltVT) {
11303   EVT VT = Op.getValueType();
11304   if (Count == 0)
11305     Count = VT.getVectorNumElements();
11306   if (EltVT == EVT())
11307     EltVT = VT.getVectorElementType();
11308   SDLoc SL(Op);
11309   for (unsigned i = Start, e = Start + Count; i != e; ++i) {
11310     Args.push_back(getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Op,
11311                            getVectorIdxConstant(i, SL)));
11312   }
11313 }
11314 
11315 // getAddressSpace - Return the address space this GlobalAddress belongs to.
11316 unsigned GlobalAddressSDNode::getAddressSpace() const {
11317   return getGlobal()->getType()->getAddressSpace();
11318 }
11319 
11320 Type *ConstantPoolSDNode::getType() const {
11321   if (isMachineConstantPoolEntry())
11322     return Val.MachineCPVal->getType();
11323   return Val.ConstVal->getType();
11324 }
11325 
11326 bool BuildVectorSDNode::isConstantSplat(APInt &SplatValue, APInt &SplatUndef,
11327                                         unsigned &SplatBitSize,
11328                                         bool &HasAnyUndefs,
11329                                         unsigned MinSplatBits,
11330                                         bool IsBigEndian) const {
11331   EVT VT = getValueType(0);
11332   assert(VT.isVector() && "Expected a vector type");
11333   unsigned VecWidth = VT.getSizeInBits();
11334   if (MinSplatBits > VecWidth)
11335     return false;
11336 
11337   // FIXME: The widths are based on this node's type, but build vectors can
11338   // truncate their operands.
11339   SplatValue = APInt(VecWidth, 0);
11340   SplatUndef = APInt(VecWidth, 0);
11341 
11342   // Get the bits. Bits with undefined values (when the corresponding element
11343   // of the vector is an ISD::UNDEF value) are set in SplatUndef and cleared
11344   // in SplatValue. If any of the values are not constant, give up and return
11345   // false.
11346   unsigned int NumOps = getNumOperands();
11347   assert(NumOps > 0 && "isConstantSplat has 0-size build vector");
11348   unsigned EltWidth = VT.getScalarSizeInBits();
11349 
11350   for (unsigned j = 0; j < NumOps; ++j) {
11351     unsigned i = IsBigEndian ? NumOps - 1 - j : j;
11352     SDValue OpVal = getOperand(i);
11353     unsigned BitPos = j * EltWidth;
11354 
11355     if (OpVal.isUndef())
11356       SplatUndef.setBits(BitPos, BitPos + EltWidth);
11357     else if (auto *CN = dyn_cast<ConstantSDNode>(OpVal))
11358       SplatValue.insertBits(CN->getAPIntValue().zextOrTrunc(EltWidth), BitPos);
11359     else if (auto *CN = dyn_cast<ConstantFPSDNode>(OpVal))
11360       SplatValue.insertBits(CN->getValueAPF().bitcastToAPInt(), BitPos);
11361     else
11362       return false;
11363   }
11364 
11365   // The build_vector is all constants or undefs. Find the smallest element
11366   // size that splats the vector.
11367   HasAnyUndefs = (SplatUndef != 0);
11368 
11369   // FIXME: This does not work for vectors with elements less than 8 bits.
11370   while (VecWidth > 8) {
11371     unsigned HalfSize = VecWidth / 2;
11372     APInt HighValue = SplatValue.extractBits(HalfSize, HalfSize);
11373     APInt LowValue = SplatValue.extractBits(HalfSize, 0);
11374     APInt HighUndef = SplatUndef.extractBits(HalfSize, HalfSize);
11375     APInt LowUndef = SplatUndef.extractBits(HalfSize, 0);
11376 
11377     // If the two halves do not match (ignoring undef bits), stop here.
11378     if ((HighValue & ~LowUndef) != (LowValue & ~HighUndef) ||
11379         MinSplatBits > HalfSize)
11380       break;
11381 
11382     SplatValue = HighValue | LowValue;
11383     SplatUndef = HighUndef & LowUndef;
11384 
11385     VecWidth = HalfSize;
11386   }
11387 
11388   SplatBitSize = VecWidth;
11389   return true;
11390 }
11391 
11392 SDValue BuildVectorSDNode::getSplatValue(const APInt &DemandedElts,
11393                                          BitVector *UndefElements) const {
11394   unsigned NumOps = getNumOperands();
11395   if (UndefElements) {
11396     UndefElements->clear();
11397     UndefElements->resize(NumOps);
11398   }
11399   assert(NumOps == DemandedElts.getBitWidth() && "Unexpected vector size");
11400   if (!DemandedElts)
11401     return SDValue();
11402   SDValue Splatted;
11403   for (unsigned i = 0; i != NumOps; ++i) {
11404     if (!DemandedElts[i])
11405       continue;
11406     SDValue Op = getOperand(i);
11407     if (Op.isUndef()) {
11408       if (UndefElements)
11409         (*UndefElements)[i] = true;
11410     } else if (!Splatted) {
11411       Splatted = Op;
11412     } else if (Splatted != Op) {
11413       return SDValue();
11414     }
11415   }
11416 
11417   if (!Splatted) {
11418     unsigned FirstDemandedIdx = DemandedElts.countTrailingZeros();
11419     assert(getOperand(FirstDemandedIdx).isUndef() &&
11420            "Can only have a splat without a constant for all undefs.");
11421     return getOperand(FirstDemandedIdx);
11422   }
11423 
11424   return Splatted;
11425 }
11426 
11427 SDValue BuildVectorSDNode::getSplatValue(BitVector *UndefElements) const {
11428   APInt DemandedElts = APInt::getAllOnes(getNumOperands());
11429   return getSplatValue(DemandedElts, UndefElements);
11430 }
11431 
11432 bool BuildVectorSDNode::getRepeatedSequence(const APInt &DemandedElts,
11433                                             SmallVectorImpl<SDValue> &Sequence,
11434                                             BitVector *UndefElements) const {
11435   unsigned NumOps = getNumOperands();
11436   Sequence.clear();
11437   if (UndefElements) {
11438     UndefElements->clear();
11439     UndefElements->resize(NumOps);
11440   }
11441   assert(NumOps == DemandedElts.getBitWidth() && "Unexpected vector size");
11442   if (!DemandedElts || NumOps < 2 || !isPowerOf2_32(NumOps))
11443     return false;
11444 
11445   // Set the undefs even if we don't find a sequence (like getSplatValue).
11446   if (UndefElements)
11447     for (unsigned I = 0; I != NumOps; ++I)
11448       if (DemandedElts[I] && getOperand(I).isUndef())
11449         (*UndefElements)[I] = true;
11450 
11451   // Iteratively widen the sequence length looking for repetitions.
11452   for (unsigned SeqLen = 1; SeqLen < NumOps; SeqLen *= 2) {
11453     Sequence.append(SeqLen, SDValue());
11454     for (unsigned I = 0; I != NumOps; ++I) {
11455       if (!DemandedElts[I])
11456         continue;
11457       SDValue &SeqOp = Sequence[I % SeqLen];
11458       SDValue Op = getOperand(I);
11459       if (Op.isUndef()) {
11460         if (!SeqOp)
11461           SeqOp = Op;
11462         continue;
11463       }
11464       if (SeqOp && !SeqOp.isUndef() && SeqOp != Op) {
11465         Sequence.clear();
11466         break;
11467       }
11468       SeqOp = Op;
11469     }
11470     if (!Sequence.empty())
11471       return true;
11472   }
11473 
11474   assert(Sequence.empty() && "Failed to empty non-repeating sequence pattern");
11475   return false;
11476 }
11477 
11478 bool BuildVectorSDNode::getRepeatedSequence(SmallVectorImpl<SDValue> &Sequence,
11479                                             BitVector *UndefElements) const {
11480   APInt DemandedElts = APInt::getAllOnes(getNumOperands());
11481   return getRepeatedSequence(DemandedElts, Sequence, UndefElements);
11482 }
11483 
11484 ConstantSDNode *
11485 BuildVectorSDNode::getConstantSplatNode(const APInt &DemandedElts,
11486                                         BitVector *UndefElements) const {
11487   return dyn_cast_or_null<ConstantSDNode>(
11488       getSplatValue(DemandedElts, UndefElements));
11489 }
11490 
11491 ConstantSDNode *
11492 BuildVectorSDNode::getConstantSplatNode(BitVector *UndefElements) const {
11493   return dyn_cast_or_null<ConstantSDNode>(getSplatValue(UndefElements));
11494 }
11495 
11496 ConstantFPSDNode *
11497 BuildVectorSDNode::getConstantFPSplatNode(const APInt &DemandedElts,
11498                                           BitVector *UndefElements) const {
11499   return dyn_cast_or_null<ConstantFPSDNode>(
11500       getSplatValue(DemandedElts, UndefElements));
11501 }
11502 
11503 ConstantFPSDNode *
11504 BuildVectorSDNode::getConstantFPSplatNode(BitVector *UndefElements) const {
11505   return dyn_cast_or_null<ConstantFPSDNode>(getSplatValue(UndefElements));
11506 }
11507 
11508 int32_t
11509 BuildVectorSDNode::getConstantFPSplatPow2ToLog2Int(BitVector *UndefElements,
11510                                                    uint32_t BitWidth) const {
11511   if (ConstantFPSDNode *CN =
11512           dyn_cast_or_null<ConstantFPSDNode>(getSplatValue(UndefElements))) {
11513     bool IsExact;
11514     APSInt IntVal(BitWidth);
11515     const APFloat &APF = CN->getValueAPF();
11516     if (APF.convertToInteger(IntVal, APFloat::rmTowardZero, &IsExact) !=
11517             APFloat::opOK ||
11518         !IsExact)
11519       return -1;
11520 
11521     return IntVal.exactLogBase2();
11522   }
11523   return -1;
11524 }
11525 
11526 bool BuildVectorSDNode::getConstantRawBits(
11527     bool IsLittleEndian, unsigned DstEltSizeInBits,
11528     SmallVectorImpl<APInt> &RawBitElements, BitVector &UndefElements) const {
11529   // Early-out if this contains anything but Undef/Constant/ConstantFP.
11530   if (!isConstant())
11531     return false;
11532 
11533   unsigned NumSrcOps = getNumOperands();
11534   unsigned SrcEltSizeInBits = getValueType(0).getScalarSizeInBits();
11535   assert(((NumSrcOps * SrcEltSizeInBits) % DstEltSizeInBits) == 0 &&
11536          "Invalid bitcast scale");
11537 
11538   // Extract raw src bits.
11539   SmallVector<APInt> SrcBitElements(NumSrcOps,
11540                                     APInt::getNullValue(SrcEltSizeInBits));
11541   BitVector SrcUndeElements(NumSrcOps, false);
11542 
11543   for (unsigned I = 0; I != NumSrcOps; ++I) {
11544     SDValue Op = getOperand(I);
11545     if (Op.isUndef()) {
11546       SrcUndeElements.set(I);
11547       continue;
11548     }
11549     auto *CInt = dyn_cast<ConstantSDNode>(Op);
11550     auto *CFP = dyn_cast<ConstantFPSDNode>(Op);
11551     assert((CInt || CFP) && "Unknown constant");
11552     SrcBitElements[I] = CInt ? CInt->getAPIntValue().trunc(SrcEltSizeInBits)
11553                              : CFP->getValueAPF().bitcastToAPInt();
11554   }
11555 
11556   // Recast to dst width.
11557   recastRawBits(IsLittleEndian, DstEltSizeInBits, RawBitElements,
11558                 SrcBitElements, UndefElements, SrcUndeElements);
11559   return true;
11560 }
11561 
11562 void BuildVectorSDNode::recastRawBits(bool IsLittleEndian,
11563                                       unsigned DstEltSizeInBits,
11564                                       SmallVectorImpl<APInt> &DstBitElements,
11565                                       ArrayRef<APInt> SrcBitElements,
11566                                       BitVector &DstUndefElements,
11567                                       const BitVector &SrcUndefElements) {
11568   unsigned NumSrcOps = SrcBitElements.size();
11569   unsigned SrcEltSizeInBits = SrcBitElements[0].getBitWidth();
11570   assert(((NumSrcOps * SrcEltSizeInBits) % DstEltSizeInBits) == 0 &&
11571          "Invalid bitcast scale");
11572   assert(NumSrcOps == SrcUndefElements.size() &&
11573          "Vector size mismatch");
11574 
11575   unsigned NumDstOps = (NumSrcOps * SrcEltSizeInBits) / DstEltSizeInBits;
11576   DstUndefElements.clear();
11577   DstUndefElements.resize(NumDstOps, false);
11578   DstBitElements.assign(NumDstOps, APInt::getNullValue(DstEltSizeInBits));
11579 
11580   // Concatenate src elements constant bits together into dst element.
11581   if (SrcEltSizeInBits <= DstEltSizeInBits) {
11582     unsigned Scale = DstEltSizeInBits / SrcEltSizeInBits;
11583     for (unsigned I = 0; I != NumDstOps; ++I) {
11584       DstUndefElements.set(I);
11585       APInt &DstBits = DstBitElements[I];
11586       for (unsigned J = 0; J != Scale; ++J) {
11587         unsigned Idx = (I * Scale) + (IsLittleEndian ? J : (Scale - J - 1));
11588         if (SrcUndefElements[Idx])
11589           continue;
11590         DstUndefElements.reset(I);
11591         const APInt &SrcBits = SrcBitElements[Idx];
11592         assert(SrcBits.getBitWidth() == SrcEltSizeInBits &&
11593                "Illegal constant bitwidths");
11594         DstBits.insertBits(SrcBits, J * SrcEltSizeInBits);
11595       }
11596     }
11597     return;
11598   }
11599 
11600   // Split src element constant bits into dst elements.
11601   unsigned Scale = SrcEltSizeInBits / DstEltSizeInBits;
11602   for (unsigned I = 0; I != NumSrcOps; ++I) {
11603     if (SrcUndefElements[I]) {
11604       DstUndefElements.set(I * Scale, (I + 1) * Scale);
11605       continue;
11606     }
11607     const APInt &SrcBits = SrcBitElements[I];
11608     for (unsigned J = 0; J != Scale; ++J) {
11609       unsigned Idx = (I * Scale) + (IsLittleEndian ? J : (Scale - J - 1));
11610       APInt &DstBits = DstBitElements[Idx];
11611       DstBits = SrcBits.extractBits(DstEltSizeInBits, J * DstEltSizeInBits);
11612     }
11613   }
11614 }
11615 
11616 bool BuildVectorSDNode::isConstant() const {
11617   for (const SDValue &Op : op_values()) {
11618     unsigned Opc = Op.getOpcode();
11619     if (Opc != ISD::UNDEF && Opc != ISD::Constant && Opc != ISD::ConstantFP)
11620       return false;
11621   }
11622   return true;
11623 }
11624 
11625 bool ShuffleVectorSDNode::isSplatMask(const int *Mask, EVT VT) {
11626   // Find the first non-undef value in the shuffle mask.
11627   unsigned i, e;
11628   for (i = 0, e = VT.getVectorNumElements(); i != e && Mask[i] < 0; ++i)
11629     /* search */;
11630 
11631   // If all elements are undefined, this shuffle can be considered a splat
11632   // (although it should eventually get simplified away completely).
11633   if (i == e)
11634     return true;
11635 
11636   // Make sure all remaining elements are either undef or the same as the first
11637   // non-undef value.
11638   for (int Idx = Mask[i]; i != e; ++i)
11639     if (Mask[i] >= 0 && Mask[i] != Idx)
11640       return false;
11641   return true;
11642 }
11643 
11644 // Returns the SDNode if it is a constant integer BuildVector
11645 // or constant integer.
11646 SDNode *SelectionDAG::isConstantIntBuildVectorOrConstantInt(SDValue N) const {
11647   if (isa<ConstantSDNode>(N))
11648     return N.getNode();
11649   if (ISD::isBuildVectorOfConstantSDNodes(N.getNode()))
11650     return N.getNode();
11651   // Treat a GlobalAddress supporting constant offset folding as a
11652   // constant integer.
11653   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N))
11654     if (GA->getOpcode() == ISD::GlobalAddress &&
11655         TLI->isOffsetFoldingLegal(GA))
11656       return GA;
11657   if ((N.getOpcode() == ISD::SPLAT_VECTOR) &&
11658       isa<ConstantSDNode>(N.getOperand(0)))
11659     return N.getNode();
11660   return nullptr;
11661 }
11662 
11663 // Returns the SDNode if it is a constant float BuildVector
11664 // or constant float.
11665 SDNode *SelectionDAG::isConstantFPBuildVectorOrConstantFP(SDValue N) const {
11666   if (isa<ConstantFPSDNode>(N))
11667     return N.getNode();
11668 
11669   if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode()))
11670     return N.getNode();
11671 
11672   if ((N.getOpcode() == ISD::SPLAT_VECTOR) &&
11673       isa<ConstantFPSDNode>(N.getOperand(0)))
11674     return N.getNode();
11675 
11676   return nullptr;
11677 }
11678 
11679 void SelectionDAG::createOperands(SDNode *Node, ArrayRef<SDValue> Vals) {
11680   assert(!Node->OperandList && "Node already has operands");
11681   assert(SDNode::getMaxNumOperands() >= Vals.size() &&
11682          "too many operands to fit into SDNode");
11683   SDUse *Ops = OperandRecycler.allocate(
11684       ArrayRecycler<SDUse>::Capacity::get(Vals.size()), OperandAllocator);
11685 
11686   bool IsDivergent = false;
11687   for (unsigned I = 0; I != Vals.size(); ++I) {
11688     Ops[I].setUser(Node);
11689     Ops[I].setInitial(Vals[I]);
11690     if (Ops[I].Val.getValueType() != MVT::Other) // Skip Chain. It does not carry divergence.
11691       IsDivergent |= Ops[I].getNode()->isDivergent();
11692   }
11693   Node->NumOperands = Vals.size();
11694   Node->OperandList = Ops;
11695   if (!TLI->isSDNodeAlwaysUniform(Node)) {
11696     IsDivergent |= TLI->isSDNodeSourceOfDivergence(Node, FLI, DA);
11697     Node->SDNodeBits.IsDivergent = IsDivergent;
11698   }
11699   checkForCycles(Node);
11700 }
11701 
11702 SDValue SelectionDAG::getTokenFactor(const SDLoc &DL,
11703                                      SmallVectorImpl<SDValue> &Vals) {
11704   size_t Limit = SDNode::getMaxNumOperands();
11705   while (Vals.size() > Limit) {
11706     unsigned SliceIdx = Vals.size() - Limit;
11707     auto ExtractedTFs = ArrayRef<SDValue>(Vals).slice(SliceIdx, Limit);
11708     SDValue NewTF = getNode(ISD::TokenFactor, DL, MVT::Other, ExtractedTFs);
11709     Vals.erase(Vals.begin() + SliceIdx, Vals.end());
11710     Vals.emplace_back(NewTF);
11711   }
11712   return getNode(ISD::TokenFactor, DL, MVT::Other, Vals);
11713 }
11714 
11715 SDValue SelectionDAG::getNeutralElement(unsigned Opcode, const SDLoc &DL,
11716                                         EVT VT, SDNodeFlags Flags) {
11717   switch (Opcode) {
11718   default:
11719     return SDValue();
11720   case ISD::ADD:
11721   case ISD::OR:
11722   case ISD::XOR:
11723   case ISD::UMAX:
11724     return getConstant(0, DL, VT);
11725   case ISD::MUL:
11726     return getConstant(1, DL, VT);
11727   case ISD::AND:
11728   case ISD::UMIN:
11729     return getAllOnesConstant(DL, VT);
11730   case ISD::SMAX:
11731     return getConstant(APInt::getSignedMinValue(VT.getSizeInBits()), DL, VT);
11732   case ISD::SMIN:
11733     return getConstant(APInt::getSignedMaxValue(VT.getSizeInBits()), DL, VT);
11734   case ISD::FADD:
11735     return getConstantFP(-0.0, DL, VT);
11736   case ISD::FMUL:
11737     return getConstantFP(1.0, DL, VT);
11738   case ISD::FMINNUM:
11739   case ISD::FMAXNUM: {
11740     // Neutral element for fminnum is NaN, Inf or FLT_MAX, depending on FMF.
11741     const fltSemantics &Semantics = EVTToAPFloatSemantics(VT);
11742     APFloat NeutralAF = !Flags.hasNoNaNs() ? APFloat::getQNaN(Semantics) :
11743                         !Flags.hasNoInfs() ? APFloat::getInf(Semantics) :
11744                         APFloat::getLargest(Semantics);
11745     if (Opcode == ISD::FMAXNUM)
11746       NeutralAF.changeSign();
11747 
11748     return getConstantFP(NeutralAF, DL, VT);
11749   }
11750   }
11751 }
11752 
11753 #ifndef NDEBUG
11754 static void checkForCyclesHelper(const SDNode *N,
11755                                  SmallPtrSetImpl<const SDNode*> &Visited,
11756                                  SmallPtrSetImpl<const SDNode*> &Checked,
11757                                  const llvm::SelectionDAG *DAG) {
11758   // If this node has already been checked, don't check it again.
11759   if (Checked.count(N))
11760     return;
11761 
11762   // If a node has already been visited on this depth-first walk, reject it as
11763   // a cycle.
11764   if (!Visited.insert(N).second) {
11765     errs() << "Detected cycle in SelectionDAG\n";
11766     dbgs() << "Offending node:\n";
11767     N->dumprFull(DAG); dbgs() << "\n";
11768     abort();
11769   }
11770 
11771   for (const SDValue &Op : N->op_values())
11772     checkForCyclesHelper(Op.getNode(), Visited, Checked, DAG);
11773 
11774   Checked.insert(N);
11775   Visited.erase(N);
11776 }
11777 #endif
11778 
11779 void llvm::checkForCycles(const llvm::SDNode *N,
11780                           const llvm::SelectionDAG *DAG,
11781                           bool force) {
11782 #ifndef NDEBUG
11783   bool check = force;
11784 #ifdef EXPENSIVE_CHECKS
11785   check = true;
11786 #endif  // EXPENSIVE_CHECKS
11787   if (check) {
11788     assert(N && "Checking nonexistent SDNode");
11789     SmallPtrSet<const SDNode*, 32> visited;
11790     SmallPtrSet<const SDNode*, 32> checked;
11791     checkForCyclesHelper(N, visited, checked, DAG);
11792   }
11793 #endif  // !NDEBUG
11794 }
11795 
11796 void llvm::checkForCycles(const llvm::SelectionDAG *DAG, bool force) {
11797   checkForCycles(DAG->getRoot().getNode(), DAG, force);
11798 }
11799