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/ManagedStatic.h"
64 #include "llvm/Support/MathExtras.h"
65 #include "llvm/Support/Mutex.h"
66 #include "llvm/Support/raw_ostream.h"
67 #include "llvm/Target/TargetMachine.h"
68 #include "llvm/Target/TargetOptions.h"
69 #include "llvm/Transforms/Utils/SizeOpts.h"
70 #include <algorithm>
71 #include <cassert>
72 #include <cstdint>
73 #include <cstdlib>
74 #include <limits>
75 #include <set>
76 #include <string>
77 #include <utility>
78 #include <vector>
79 
80 using namespace llvm;
81 
82 /// makeVTList - Return an instance of the SDVTList struct initialized with the
83 /// specified members.
84 static SDVTList makeVTList(const EVT *VTs, unsigned NumVTs) {
85   SDVTList Res = {VTs, NumVTs};
86   return Res;
87 }
88 
89 // Default null implementations of the callbacks.
90 void SelectionDAG::DAGUpdateListener::NodeDeleted(SDNode*, SDNode*) {}
91 void SelectionDAG::DAGUpdateListener::NodeUpdated(SDNode*) {}
92 void SelectionDAG::DAGUpdateListener::NodeInserted(SDNode *) {}
93 
94 void SelectionDAG::DAGNodeDeletedListener::anchor() {}
95 
96 #define DEBUG_TYPE "selectiondag"
97 
98 static cl::opt<bool> EnableMemCpyDAGOpt("enable-memcpy-dag-opt",
99        cl::Hidden, cl::init(true),
100        cl::desc("Gang up loads and stores generated by inlining of memcpy"));
101 
102 static cl::opt<int> MaxLdStGlue("ldstmemcpy-glue-max",
103        cl::desc("Number limit for gluing ld/st of memcpy."),
104        cl::Hidden, cl::init(0));
105 
106 static void NewSDValueDbgMsg(SDValue V, StringRef Msg, SelectionDAG *G) {
107   LLVM_DEBUG(dbgs() << Msg; V.getNode()->dump(G););
108 }
109 
110 //===----------------------------------------------------------------------===//
111 //                              ConstantFPSDNode Class
112 //===----------------------------------------------------------------------===//
113 
114 /// isExactlyValue - We don't rely on operator== working on double values, as
115 /// it returns true for things that are clearly not equal, like -0.0 and 0.0.
116 /// As such, this method can be used to do an exact bit-for-bit comparison of
117 /// two floating point values.
118 bool ConstantFPSDNode::isExactlyValue(const APFloat& V) const {
119   return getValueAPF().bitwiseIsEqual(V);
120 }
121 
122 bool ConstantFPSDNode::isValueValidForType(EVT VT,
123                                            const APFloat& Val) {
124   assert(VT.isFloatingPoint() && "Can only convert between FP types");
125 
126   // convert modifies in place, so make a copy.
127   APFloat Val2 = APFloat(Val);
128   bool losesInfo;
129   (void) Val2.convert(SelectionDAG::EVTToAPFloatSemantics(VT),
130                       APFloat::rmNearestTiesToEven,
131                       &losesInfo);
132   return !losesInfo;
133 }
134 
135 //===----------------------------------------------------------------------===//
136 //                              ISD Namespace
137 //===----------------------------------------------------------------------===//
138 
139 bool ISD::isConstantSplatVector(const SDNode *N, APInt &SplatVal) {
140   if (N->getOpcode() == ISD::SPLAT_VECTOR) {
141     unsigned EltSize =
142         N->getValueType(0).getVectorElementType().getSizeInBits();
143     if (auto *Op0 = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
144       SplatVal = Op0->getAPIntValue().truncOrSelf(EltSize);
145       return true;
146     }
147     if (auto *Op0 = dyn_cast<ConstantFPSDNode>(N->getOperand(0))) {
148       SplatVal = Op0->getValueAPF().bitcastToAPInt().truncOrSelf(EltSize);
149       return true;
150     }
151   }
152 
153   auto *BV = dyn_cast<BuildVectorSDNode>(N);
154   if (!BV)
155     return false;
156 
157   APInt SplatUndef;
158   unsigned SplatBitSize;
159   bool HasUndefs;
160   unsigned EltSize = N->getValueType(0).getVectorElementType().getSizeInBits();
161   return BV->isConstantSplat(SplatVal, SplatUndef, SplatBitSize, HasUndefs,
162                              EltSize) &&
163          EltSize == SplatBitSize;
164 }
165 
166 // FIXME: AllOnes and AllZeros duplicate a lot of code. Could these be
167 // specializations of the more general isConstantSplatVector()?
168 
169 bool ISD::isConstantSplatVectorAllOnes(const SDNode *N, bool BuildVectorOnly) {
170   // Look through a bit convert.
171   while (N->getOpcode() == ISD::BITCAST)
172     N = N->getOperand(0).getNode();
173 
174   if (!BuildVectorOnly && N->getOpcode() == ISD::SPLAT_VECTOR) {
175     APInt SplatVal;
176     return isConstantSplatVector(N, SplatVal) && SplatVal.isAllOnes();
177   }
178 
179   if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
180 
181   unsigned i = 0, e = N->getNumOperands();
182 
183   // Skip over all of the undef values.
184   while (i != e && N->getOperand(i).isUndef())
185     ++i;
186 
187   // Do not accept an all-undef vector.
188   if (i == e) return false;
189 
190   // Do not accept build_vectors that aren't all constants or which have non-~0
191   // elements. We have to be a bit careful here, as the type of the constant
192   // may not be the same as the type of the vector elements due to type
193   // legalization (the elements are promoted to a legal type for the target and
194   // a vector of a type may be legal when the base element type is not).
195   // We only want to check enough bits to cover the vector elements, because
196   // we care if the resultant vector is all ones, not whether the individual
197   // constants are.
198   SDValue NotZero = N->getOperand(i);
199   unsigned EltSize = N->getValueType(0).getScalarSizeInBits();
200   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(NotZero)) {
201     if (CN->getAPIntValue().countTrailingOnes() < EltSize)
202       return false;
203   } else if (ConstantFPSDNode *CFPN = dyn_cast<ConstantFPSDNode>(NotZero)) {
204     if (CFPN->getValueAPF().bitcastToAPInt().countTrailingOnes() < EltSize)
205       return false;
206   } else
207     return false;
208 
209   // Okay, we have at least one ~0 value, check to see if the rest match or are
210   // undefs. Even with the above element type twiddling, this should be OK, as
211   // the same type legalization should have applied to all the elements.
212   for (++i; i != e; ++i)
213     if (N->getOperand(i) != NotZero && !N->getOperand(i).isUndef())
214       return false;
215   return true;
216 }
217 
218 bool ISD::isConstantSplatVectorAllZeros(const SDNode *N, bool BuildVectorOnly) {
219   // Look through a bit convert.
220   while (N->getOpcode() == ISD::BITCAST)
221     N = N->getOperand(0).getNode();
222 
223   if (!BuildVectorOnly && N->getOpcode() == ISD::SPLAT_VECTOR) {
224     APInt SplatVal;
225     return isConstantSplatVector(N, SplatVal) && SplatVal.isZero();
226   }
227 
228   if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
229 
230   bool IsAllUndef = true;
231   for (const SDValue &Op : N->op_values()) {
232     if (Op.isUndef())
233       continue;
234     IsAllUndef = false;
235     // Do not accept build_vectors that aren't all constants or which have non-0
236     // elements. We have to be a bit careful here, as the type of the constant
237     // may not be the same as the type of the vector elements due to type
238     // legalization (the elements are promoted to a legal type for the target
239     // and a vector of a type may be legal when the base element type is not).
240     // We only want to check enough bits to cover the vector elements, because
241     // we care if the resultant vector is all zeros, not whether the individual
242     // constants are.
243     unsigned EltSize = N->getValueType(0).getScalarSizeInBits();
244     if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Op)) {
245       if (CN->getAPIntValue().countTrailingZeros() < EltSize)
246         return false;
247     } else if (ConstantFPSDNode *CFPN = dyn_cast<ConstantFPSDNode>(Op)) {
248       if (CFPN->getValueAPF().bitcastToAPInt().countTrailingZeros() < EltSize)
249         return false;
250     } else
251       return false;
252   }
253 
254   // Do not accept an all-undef vector.
255   if (IsAllUndef)
256     return false;
257   return true;
258 }
259 
260 bool ISD::isBuildVectorAllOnes(const SDNode *N) {
261   return isConstantSplatVectorAllOnes(N, /*BuildVectorOnly*/ true);
262 }
263 
264 bool ISD::isBuildVectorAllZeros(const SDNode *N) {
265   return isConstantSplatVectorAllZeros(N, /*BuildVectorOnly*/ true);
266 }
267 
268 bool ISD::isBuildVectorOfConstantSDNodes(const SDNode *N) {
269   if (N->getOpcode() != ISD::BUILD_VECTOR)
270     return false;
271 
272   for (const SDValue &Op : N->op_values()) {
273     if (Op.isUndef())
274       continue;
275     if (!isa<ConstantSDNode>(Op))
276       return false;
277   }
278   return true;
279 }
280 
281 bool ISD::isBuildVectorOfConstantFPSDNodes(const SDNode *N) {
282   if (N->getOpcode() != ISD::BUILD_VECTOR)
283     return false;
284 
285   for (const SDValue &Op : N->op_values()) {
286     if (Op.isUndef())
287       continue;
288     if (!isa<ConstantFPSDNode>(Op))
289       return false;
290   }
291   return true;
292 }
293 
294 bool ISD::allOperandsUndef(const SDNode *N) {
295   // Return false if the node has no operands.
296   // This is "logically inconsistent" with the definition of "all" but
297   // is probably the desired behavior.
298   if (N->getNumOperands() == 0)
299     return false;
300   return all_of(N->op_values(), [](SDValue Op) { return Op.isUndef(); });
301 }
302 
303 bool ISD::matchUnaryPredicate(SDValue Op,
304                               std::function<bool(ConstantSDNode *)> Match,
305                               bool AllowUndefs) {
306   // FIXME: Add support for scalar UNDEF cases?
307   if (auto *Cst = dyn_cast<ConstantSDNode>(Op))
308     return Match(Cst);
309 
310   // FIXME: Add support for vector UNDEF cases?
311   if (ISD::BUILD_VECTOR != Op.getOpcode() &&
312       ISD::SPLAT_VECTOR != Op.getOpcode())
313     return false;
314 
315   EVT SVT = Op.getValueType().getScalarType();
316   for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
317     if (AllowUndefs && Op.getOperand(i).isUndef()) {
318       if (!Match(nullptr))
319         return false;
320       continue;
321     }
322 
323     auto *Cst = dyn_cast<ConstantSDNode>(Op.getOperand(i));
324     if (!Cst || Cst->getValueType(0) != SVT || !Match(Cst))
325       return false;
326   }
327   return true;
328 }
329 
330 bool ISD::matchBinaryPredicate(
331     SDValue LHS, SDValue RHS,
332     std::function<bool(ConstantSDNode *, ConstantSDNode *)> Match,
333     bool AllowUndefs, bool AllowTypeMismatch) {
334   if (!AllowTypeMismatch && LHS.getValueType() != RHS.getValueType())
335     return false;
336 
337   // TODO: Add support for scalar UNDEF cases?
338   if (auto *LHSCst = dyn_cast<ConstantSDNode>(LHS))
339     if (auto *RHSCst = dyn_cast<ConstantSDNode>(RHS))
340       return Match(LHSCst, RHSCst);
341 
342   // TODO: Add support for vector UNDEF cases?
343   if (LHS.getOpcode() != RHS.getOpcode() ||
344       (LHS.getOpcode() != ISD::BUILD_VECTOR &&
345        LHS.getOpcode() != ISD::SPLAT_VECTOR))
346     return false;
347 
348   EVT SVT = LHS.getValueType().getScalarType();
349   for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
350     SDValue LHSOp = LHS.getOperand(i);
351     SDValue RHSOp = RHS.getOperand(i);
352     bool LHSUndef = AllowUndefs && LHSOp.isUndef();
353     bool RHSUndef = AllowUndefs && RHSOp.isUndef();
354     auto *LHSCst = dyn_cast<ConstantSDNode>(LHSOp);
355     auto *RHSCst = dyn_cast<ConstantSDNode>(RHSOp);
356     if ((!LHSCst && !LHSUndef) || (!RHSCst && !RHSUndef))
357       return false;
358     if (!AllowTypeMismatch && (LHSOp.getValueType() != SVT ||
359                                LHSOp.getValueType() != RHSOp.getValueType()))
360       return false;
361     if (!Match(LHSCst, RHSCst))
362       return false;
363   }
364   return true;
365 }
366 
367 ISD::NodeType ISD::getVecReduceBaseOpcode(unsigned VecReduceOpcode) {
368   switch (VecReduceOpcode) {
369   default:
370     llvm_unreachable("Expected VECREDUCE opcode");
371   case ISD::VECREDUCE_FADD:
372   case ISD::VECREDUCE_SEQ_FADD:
373   case ISD::VP_REDUCE_FADD:
374   case ISD::VP_REDUCE_SEQ_FADD:
375     return ISD::FADD;
376   case ISD::VECREDUCE_FMUL:
377   case ISD::VECREDUCE_SEQ_FMUL:
378   case ISD::VP_REDUCE_FMUL:
379   case ISD::VP_REDUCE_SEQ_FMUL:
380     return ISD::FMUL;
381   case ISD::VECREDUCE_ADD:
382   case ISD::VP_REDUCE_ADD:
383     return ISD::ADD;
384   case ISD::VECREDUCE_MUL:
385   case ISD::VP_REDUCE_MUL:
386     return ISD::MUL;
387   case ISD::VECREDUCE_AND:
388   case ISD::VP_REDUCE_AND:
389     return ISD::AND;
390   case ISD::VECREDUCE_OR:
391   case ISD::VP_REDUCE_OR:
392     return ISD::OR;
393   case ISD::VECREDUCE_XOR:
394   case ISD::VP_REDUCE_XOR:
395     return ISD::XOR;
396   case ISD::VECREDUCE_SMAX:
397   case ISD::VP_REDUCE_SMAX:
398     return ISD::SMAX;
399   case ISD::VECREDUCE_SMIN:
400   case ISD::VP_REDUCE_SMIN:
401     return ISD::SMIN;
402   case ISD::VECREDUCE_UMAX:
403   case ISD::VP_REDUCE_UMAX:
404     return ISD::UMAX;
405   case ISD::VECREDUCE_UMIN:
406   case ISD::VP_REDUCE_UMIN:
407     return ISD::UMIN;
408   case ISD::VECREDUCE_FMAX:
409   case ISD::VP_REDUCE_FMAX:
410     return ISD::FMAXNUM;
411   case ISD::VECREDUCE_FMIN:
412   case ISD::VP_REDUCE_FMIN:
413     return ISD::FMINNUM;
414   }
415 }
416 
417 bool ISD::isVPOpcode(unsigned Opcode) {
418   switch (Opcode) {
419   default:
420     return false;
421 #define BEGIN_REGISTER_VP_SDNODE(VPSD, ...)                                    \
422   case ISD::VPSD:                                                              \
423     return true;
424 #include "llvm/IR/VPIntrinsics.def"
425   }
426 }
427 
428 bool ISD::isVPBinaryOp(unsigned Opcode) {
429   switch (Opcode) {
430   default:
431     break;
432 #define BEGIN_REGISTER_VP_SDNODE(VPSD, ...) case ISD::VPSD:
433 #define VP_PROPERTY_BINARYOP return true;
434 #define END_REGISTER_VP_SDNODE(VPSD) break;
435 #include "llvm/IR/VPIntrinsics.def"
436   }
437   return false;
438 }
439 
440 bool ISD::isVPReduction(unsigned Opcode) {
441   switch (Opcode) {
442   default:
443     break;
444 #define BEGIN_REGISTER_VP_SDNODE(VPSD, ...) case ISD::VPSD:
445 #define VP_PROPERTY_REDUCTION(STARTPOS, ...) return true;
446 #define END_REGISTER_VP_SDNODE(VPSD) break;
447 #include "llvm/IR/VPIntrinsics.def"
448   }
449   return false;
450 }
451 
452 /// The operand position of the vector mask.
453 Optional<unsigned> ISD::getVPMaskIdx(unsigned Opcode) {
454   switch (Opcode) {
455   default:
456     return None;
457 #define BEGIN_REGISTER_VP_SDNODE(VPSD, LEGALPOS, TDNAME, MASKPOS, ...)         \
458   case ISD::VPSD:                                                              \
459     return MASKPOS;
460 #include "llvm/IR/VPIntrinsics.def"
461   }
462 }
463 
464 /// The operand position of the explicit vector length parameter.
465 Optional<unsigned> ISD::getVPExplicitVectorLengthIdx(unsigned Opcode) {
466   switch (Opcode) {
467   default:
468     return None;
469 #define BEGIN_REGISTER_VP_SDNODE(VPSD, LEGALPOS, TDNAME, MASKPOS, EVLPOS)      \
470   case ISD::VPSD:                                                              \
471     return EVLPOS;
472 #include "llvm/IR/VPIntrinsics.def"
473   }
474 }
475 
476 ISD::NodeType ISD::getExtForLoadExtType(bool IsFP, ISD::LoadExtType ExtType) {
477   switch (ExtType) {
478   case ISD::EXTLOAD:
479     return IsFP ? ISD::FP_EXTEND : ISD::ANY_EXTEND;
480   case ISD::SEXTLOAD:
481     return ISD::SIGN_EXTEND;
482   case ISD::ZEXTLOAD:
483     return ISD::ZERO_EXTEND;
484   default:
485     break;
486   }
487 
488   llvm_unreachable("Invalid LoadExtType");
489 }
490 
491 ISD::CondCode ISD::getSetCCSwappedOperands(ISD::CondCode Operation) {
492   // To perform this operation, we just need to swap the L and G bits of the
493   // operation.
494   unsigned OldL = (Operation >> 2) & 1;
495   unsigned OldG = (Operation >> 1) & 1;
496   return ISD::CondCode((Operation & ~6) |  // Keep the N, U, E bits
497                        (OldL << 1) |       // New G bit
498                        (OldG << 2));       // New L bit.
499 }
500 
501 static ISD::CondCode getSetCCInverseImpl(ISD::CondCode Op, bool isIntegerLike) {
502   unsigned Operation = Op;
503   if (isIntegerLike)
504     Operation ^= 7;   // Flip L, G, E bits, but not U.
505   else
506     Operation ^= 15;  // Flip all of the condition bits.
507 
508   if (Operation > ISD::SETTRUE2)
509     Operation &= ~8;  // Don't let N and U bits get set.
510 
511   return ISD::CondCode(Operation);
512 }
513 
514 ISD::CondCode ISD::getSetCCInverse(ISD::CondCode Op, EVT Type) {
515   return getSetCCInverseImpl(Op, Type.isInteger());
516 }
517 
518 ISD::CondCode ISD::GlobalISel::getSetCCInverse(ISD::CondCode Op,
519                                                bool isIntegerLike) {
520   return getSetCCInverseImpl(Op, isIntegerLike);
521 }
522 
523 /// For an integer comparison, return 1 if the comparison is a signed operation
524 /// and 2 if the result is an unsigned comparison. Return zero if the operation
525 /// does not depend on the sign of the input (setne and seteq).
526 static int isSignedOp(ISD::CondCode Opcode) {
527   switch (Opcode) {
528   default: llvm_unreachable("Illegal integer setcc operation!");
529   case ISD::SETEQ:
530   case ISD::SETNE: return 0;
531   case ISD::SETLT:
532   case ISD::SETLE:
533   case ISD::SETGT:
534   case ISD::SETGE: return 1;
535   case ISD::SETULT:
536   case ISD::SETULE:
537   case ISD::SETUGT:
538   case ISD::SETUGE: return 2;
539   }
540 }
541 
542 ISD::CondCode ISD::getSetCCOrOperation(ISD::CondCode Op1, ISD::CondCode Op2,
543                                        EVT Type) {
544   bool IsInteger = Type.isInteger();
545   if (IsInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
546     // Cannot fold a signed integer setcc with an unsigned integer setcc.
547     return ISD::SETCC_INVALID;
548 
549   unsigned Op = Op1 | Op2;  // Combine all of the condition bits.
550 
551   // If the N and U bits get set, then the resultant comparison DOES suddenly
552   // care about orderedness, and it is true when ordered.
553   if (Op > ISD::SETTRUE2)
554     Op &= ~16;     // Clear the U bit if the N bit is set.
555 
556   // Canonicalize illegal integer setcc's.
557   if (IsInteger && Op == ISD::SETUNE)  // e.g. SETUGT | SETULT
558     Op = ISD::SETNE;
559 
560   return ISD::CondCode(Op);
561 }
562 
563 ISD::CondCode ISD::getSetCCAndOperation(ISD::CondCode Op1, ISD::CondCode Op2,
564                                         EVT Type) {
565   bool IsInteger = Type.isInteger();
566   if (IsInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
567     // Cannot fold a signed setcc with an unsigned setcc.
568     return ISD::SETCC_INVALID;
569 
570   // Combine all of the condition bits.
571   ISD::CondCode Result = ISD::CondCode(Op1 & Op2);
572 
573   // Canonicalize illegal integer setcc's.
574   if (IsInteger) {
575     switch (Result) {
576     default: break;
577     case ISD::SETUO : Result = ISD::SETFALSE; break;  // SETUGT & SETULT
578     case ISD::SETOEQ:                                 // SETEQ  & SETU[LG]E
579     case ISD::SETUEQ: Result = ISD::SETEQ   ; break;  // SETUGE & SETULE
580     case ISD::SETOLT: Result = ISD::SETULT  ; break;  // SETULT & SETNE
581     case ISD::SETOGT: Result = ISD::SETUGT  ; break;  // SETUGT & SETNE
582     }
583   }
584 
585   return Result;
586 }
587 
588 //===----------------------------------------------------------------------===//
589 //                           SDNode Profile Support
590 //===----------------------------------------------------------------------===//
591 
592 /// AddNodeIDOpcode - Add the node opcode to the NodeID data.
593 static void AddNodeIDOpcode(FoldingSetNodeID &ID, unsigned OpC)  {
594   ID.AddInteger(OpC);
595 }
596 
597 /// AddNodeIDValueTypes - Value type lists are intern'd so we can represent them
598 /// solely with their pointer.
599 static void AddNodeIDValueTypes(FoldingSetNodeID &ID, SDVTList VTList) {
600   ID.AddPointer(VTList.VTs);
601 }
602 
603 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data.
604 static void AddNodeIDOperands(FoldingSetNodeID &ID,
605                               ArrayRef<SDValue> Ops) {
606   for (auto& Op : Ops) {
607     ID.AddPointer(Op.getNode());
608     ID.AddInteger(Op.getResNo());
609   }
610 }
611 
612 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data.
613 static void AddNodeIDOperands(FoldingSetNodeID &ID,
614                               ArrayRef<SDUse> Ops) {
615   for (auto& Op : Ops) {
616     ID.AddPointer(Op.getNode());
617     ID.AddInteger(Op.getResNo());
618   }
619 }
620 
621 static void AddNodeIDNode(FoldingSetNodeID &ID, unsigned short OpC,
622                           SDVTList VTList, ArrayRef<SDValue> OpList) {
623   AddNodeIDOpcode(ID, OpC);
624   AddNodeIDValueTypes(ID, VTList);
625   AddNodeIDOperands(ID, OpList);
626 }
627 
628 /// If this is an SDNode with special info, add this info to the NodeID data.
629 static void AddNodeIDCustom(FoldingSetNodeID &ID, const SDNode *N) {
630   switch (N->getOpcode()) {
631   case ISD::TargetExternalSymbol:
632   case ISD::ExternalSymbol:
633   case ISD::MCSymbol:
634     llvm_unreachable("Should only be used on nodes with operands");
635   default: break;  // Normal nodes don't need extra info.
636   case ISD::TargetConstant:
637   case ISD::Constant: {
638     const ConstantSDNode *C = cast<ConstantSDNode>(N);
639     ID.AddPointer(C->getConstantIntValue());
640     ID.AddBoolean(C->isOpaque());
641     break;
642   }
643   case ISD::TargetConstantFP:
644   case ISD::ConstantFP:
645     ID.AddPointer(cast<ConstantFPSDNode>(N)->getConstantFPValue());
646     break;
647   case ISD::TargetGlobalAddress:
648   case ISD::GlobalAddress:
649   case ISD::TargetGlobalTLSAddress:
650   case ISD::GlobalTLSAddress: {
651     const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(N);
652     ID.AddPointer(GA->getGlobal());
653     ID.AddInteger(GA->getOffset());
654     ID.AddInteger(GA->getTargetFlags());
655     break;
656   }
657   case ISD::BasicBlock:
658     ID.AddPointer(cast<BasicBlockSDNode>(N)->getBasicBlock());
659     break;
660   case ISD::Register:
661     ID.AddInteger(cast<RegisterSDNode>(N)->getReg());
662     break;
663   case ISD::RegisterMask:
664     ID.AddPointer(cast<RegisterMaskSDNode>(N)->getRegMask());
665     break;
666   case ISD::SRCVALUE:
667     ID.AddPointer(cast<SrcValueSDNode>(N)->getValue());
668     break;
669   case ISD::FrameIndex:
670   case ISD::TargetFrameIndex:
671     ID.AddInteger(cast<FrameIndexSDNode>(N)->getIndex());
672     break;
673   case ISD::LIFETIME_START:
674   case ISD::LIFETIME_END:
675     if (cast<LifetimeSDNode>(N)->hasOffset()) {
676       ID.AddInteger(cast<LifetimeSDNode>(N)->getSize());
677       ID.AddInteger(cast<LifetimeSDNode>(N)->getOffset());
678     }
679     break;
680   case ISD::PSEUDO_PROBE:
681     ID.AddInteger(cast<PseudoProbeSDNode>(N)->getGuid());
682     ID.AddInteger(cast<PseudoProbeSDNode>(N)->getIndex());
683     ID.AddInteger(cast<PseudoProbeSDNode>(N)->getAttributes());
684     break;
685   case ISD::JumpTable:
686   case ISD::TargetJumpTable:
687     ID.AddInteger(cast<JumpTableSDNode>(N)->getIndex());
688     ID.AddInteger(cast<JumpTableSDNode>(N)->getTargetFlags());
689     break;
690   case ISD::ConstantPool:
691   case ISD::TargetConstantPool: {
692     const ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(N);
693     ID.AddInteger(CP->getAlign().value());
694     ID.AddInteger(CP->getOffset());
695     if (CP->isMachineConstantPoolEntry())
696       CP->getMachineCPVal()->addSelectionDAGCSEId(ID);
697     else
698       ID.AddPointer(CP->getConstVal());
699     ID.AddInteger(CP->getTargetFlags());
700     break;
701   }
702   case ISD::TargetIndex: {
703     const TargetIndexSDNode *TI = cast<TargetIndexSDNode>(N);
704     ID.AddInteger(TI->getIndex());
705     ID.AddInteger(TI->getOffset());
706     ID.AddInteger(TI->getTargetFlags());
707     break;
708   }
709   case ISD::LOAD: {
710     const LoadSDNode *LD = cast<LoadSDNode>(N);
711     ID.AddInteger(LD->getMemoryVT().getRawBits());
712     ID.AddInteger(LD->getRawSubclassData());
713     ID.AddInteger(LD->getPointerInfo().getAddrSpace());
714     ID.AddInteger(LD->getMemOperand()->getFlags());
715     break;
716   }
717   case ISD::STORE: {
718     const StoreSDNode *ST = cast<StoreSDNode>(N);
719     ID.AddInteger(ST->getMemoryVT().getRawBits());
720     ID.AddInteger(ST->getRawSubclassData());
721     ID.AddInteger(ST->getPointerInfo().getAddrSpace());
722     ID.AddInteger(ST->getMemOperand()->getFlags());
723     break;
724   }
725   case ISD::VP_LOAD: {
726     const VPLoadSDNode *ELD = cast<VPLoadSDNode>(N);
727     ID.AddInteger(ELD->getMemoryVT().getRawBits());
728     ID.AddInteger(ELD->getRawSubclassData());
729     ID.AddInteger(ELD->getPointerInfo().getAddrSpace());
730     ID.AddInteger(ELD->getMemOperand()->getFlags());
731     break;
732   }
733   case ISD::VP_STORE: {
734     const VPStoreSDNode *EST = cast<VPStoreSDNode>(N);
735     ID.AddInteger(EST->getMemoryVT().getRawBits());
736     ID.AddInteger(EST->getRawSubclassData());
737     ID.AddInteger(EST->getPointerInfo().getAddrSpace());
738     ID.AddInteger(EST->getMemOperand()->getFlags());
739     break;
740   }
741   case ISD::EXPERIMENTAL_VP_STRIDED_LOAD: {
742     const VPStridedLoadSDNode *SLD = cast<VPStridedLoadSDNode>(N);
743     ID.AddInteger(SLD->getMemoryVT().getRawBits());
744     ID.AddInteger(SLD->getRawSubclassData());
745     ID.AddInteger(SLD->getPointerInfo().getAddrSpace());
746     break;
747   }
748   case ISD::EXPERIMENTAL_VP_STRIDED_STORE: {
749     const VPStridedStoreSDNode *SST = cast<VPStridedStoreSDNode>(N);
750     ID.AddInteger(SST->getMemoryVT().getRawBits());
751     ID.AddInteger(SST->getRawSubclassData());
752     ID.AddInteger(SST->getPointerInfo().getAddrSpace());
753     break;
754   }
755   case ISD::VP_GATHER: {
756     const VPGatherSDNode *EG = cast<VPGatherSDNode>(N);
757     ID.AddInteger(EG->getMemoryVT().getRawBits());
758     ID.AddInteger(EG->getRawSubclassData());
759     ID.AddInteger(EG->getPointerInfo().getAddrSpace());
760     ID.AddInteger(EG->getMemOperand()->getFlags());
761     break;
762   }
763   case ISD::VP_SCATTER: {
764     const VPScatterSDNode *ES = cast<VPScatterSDNode>(N);
765     ID.AddInteger(ES->getMemoryVT().getRawBits());
766     ID.AddInteger(ES->getRawSubclassData());
767     ID.AddInteger(ES->getPointerInfo().getAddrSpace());
768     ID.AddInteger(ES->getMemOperand()->getFlags());
769     break;
770   }
771   case ISD::MLOAD: {
772     const MaskedLoadSDNode *MLD = cast<MaskedLoadSDNode>(N);
773     ID.AddInteger(MLD->getMemoryVT().getRawBits());
774     ID.AddInteger(MLD->getRawSubclassData());
775     ID.AddInteger(MLD->getPointerInfo().getAddrSpace());
776     ID.AddInteger(MLD->getMemOperand()->getFlags());
777     break;
778   }
779   case ISD::MSTORE: {
780     const MaskedStoreSDNode *MST = cast<MaskedStoreSDNode>(N);
781     ID.AddInteger(MST->getMemoryVT().getRawBits());
782     ID.AddInteger(MST->getRawSubclassData());
783     ID.AddInteger(MST->getPointerInfo().getAddrSpace());
784     ID.AddInteger(MST->getMemOperand()->getFlags());
785     break;
786   }
787   case ISD::MGATHER: {
788     const MaskedGatherSDNode *MG = cast<MaskedGatherSDNode>(N);
789     ID.AddInteger(MG->getMemoryVT().getRawBits());
790     ID.AddInteger(MG->getRawSubclassData());
791     ID.AddInteger(MG->getPointerInfo().getAddrSpace());
792     ID.AddInteger(MG->getMemOperand()->getFlags());
793     break;
794   }
795   case ISD::MSCATTER: {
796     const MaskedScatterSDNode *MS = cast<MaskedScatterSDNode>(N);
797     ID.AddInteger(MS->getMemoryVT().getRawBits());
798     ID.AddInteger(MS->getRawSubclassData());
799     ID.AddInteger(MS->getPointerInfo().getAddrSpace());
800     ID.AddInteger(MS->getMemOperand()->getFlags());
801     break;
802   }
803   case ISD::ATOMIC_CMP_SWAP:
804   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
805   case ISD::ATOMIC_SWAP:
806   case ISD::ATOMIC_LOAD_ADD:
807   case ISD::ATOMIC_LOAD_SUB:
808   case ISD::ATOMIC_LOAD_AND:
809   case ISD::ATOMIC_LOAD_CLR:
810   case ISD::ATOMIC_LOAD_OR:
811   case ISD::ATOMIC_LOAD_XOR:
812   case ISD::ATOMIC_LOAD_NAND:
813   case ISD::ATOMIC_LOAD_MIN:
814   case ISD::ATOMIC_LOAD_MAX:
815   case ISD::ATOMIC_LOAD_UMIN:
816   case ISD::ATOMIC_LOAD_UMAX:
817   case ISD::ATOMIC_LOAD:
818   case ISD::ATOMIC_STORE: {
819     const AtomicSDNode *AT = cast<AtomicSDNode>(N);
820     ID.AddInteger(AT->getMemoryVT().getRawBits());
821     ID.AddInteger(AT->getRawSubclassData());
822     ID.AddInteger(AT->getPointerInfo().getAddrSpace());
823     ID.AddInteger(AT->getMemOperand()->getFlags());
824     break;
825   }
826   case ISD::PREFETCH: {
827     const MemSDNode *PF = cast<MemSDNode>(N);
828     ID.AddInteger(PF->getPointerInfo().getAddrSpace());
829     ID.AddInteger(PF->getMemOperand()->getFlags());
830     break;
831   }
832   case ISD::VECTOR_SHUFFLE: {
833     const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
834     for (unsigned i = 0, e = N->getValueType(0).getVectorNumElements();
835          i != e; ++i)
836       ID.AddInteger(SVN->getMaskElt(i));
837     break;
838   }
839   case ISD::TargetBlockAddress:
840   case ISD::BlockAddress: {
841     const BlockAddressSDNode *BA = cast<BlockAddressSDNode>(N);
842     ID.AddPointer(BA->getBlockAddress());
843     ID.AddInteger(BA->getOffset());
844     ID.AddInteger(BA->getTargetFlags());
845     break;
846   }
847   case ISD::AssertAlign:
848     ID.AddInteger(cast<AssertAlignSDNode>(N)->getAlign().value());
849     break;
850   } // end switch (N->getOpcode())
851 
852   // Target specific memory nodes could also have address spaces and flags
853   // to check.
854   if (N->isTargetMemoryOpcode()) {
855     const MemSDNode *MN = cast<MemSDNode>(N);
856     ID.AddInteger(MN->getPointerInfo().getAddrSpace());
857     ID.AddInteger(MN->getMemOperand()->getFlags());
858   }
859 }
860 
861 /// AddNodeIDNode - Generic routine for adding a nodes info to the NodeID
862 /// data.
863 static void AddNodeIDNode(FoldingSetNodeID &ID, const SDNode *N) {
864   AddNodeIDOpcode(ID, N->getOpcode());
865   // Add the return value info.
866   AddNodeIDValueTypes(ID, N->getVTList());
867   // Add the operand info.
868   AddNodeIDOperands(ID, N->ops());
869 
870   // Handle SDNode leafs with special info.
871   AddNodeIDCustom(ID, N);
872 }
873 
874 //===----------------------------------------------------------------------===//
875 //                              SelectionDAG Class
876 //===----------------------------------------------------------------------===//
877 
878 /// doNotCSE - Return true if CSE should not be performed for this node.
879 static bool doNotCSE(SDNode *N) {
880   if (N->getValueType(0) == MVT::Glue)
881     return true; // Never CSE anything that produces a flag.
882 
883   switch (N->getOpcode()) {
884   default: break;
885   case ISD::HANDLENODE:
886   case ISD::EH_LABEL:
887     return true;   // Never CSE these nodes.
888   }
889 
890   // Check that remaining values produced are not flags.
891   for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
892     if (N->getValueType(i) == MVT::Glue)
893       return true; // Never CSE anything that produces a flag.
894 
895   return false;
896 }
897 
898 /// RemoveDeadNodes - This method deletes all unreachable nodes in the
899 /// SelectionDAG.
900 void SelectionDAG::RemoveDeadNodes() {
901   // Create a dummy node (which is not added to allnodes), that adds a reference
902   // to the root node, preventing it from being deleted.
903   HandleSDNode Dummy(getRoot());
904 
905   SmallVector<SDNode*, 128> DeadNodes;
906 
907   // Add all obviously-dead nodes to the DeadNodes worklist.
908   for (SDNode &Node : allnodes())
909     if (Node.use_empty())
910       DeadNodes.push_back(&Node);
911 
912   RemoveDeadNodes(DeadNodes);
913 
914   // If the root changed (e.g. it was a dead load, update the root).
915   setRoot(Dummy.getValue());
916 }
917 
918 /// RemoveDeadNodes - This method deletes the unreachable nodes in the
919 /// given list, and any nodes that become unreachable as a result.
920 void SelectionDAG::RemoveDeadNodes(SmallVectorImpl<SDNode *> &DeadNodes) {
921 
922   // Process the worklist, deleting the nodes and adding their uses to the
923   // worklist.
924   while (!DeadNodes.empty()) {
925     SDNode *N = DeadNodes.pop_back_val();
926     // Skip to next node if we've already managed to delete the node. This could
927     // happen if replacing a node causes a node previously added to the node to
928     // be deleted.
929     if (N->getOpcode() == ISD::DELETED_NODE)
930       continue;
931 
932     for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
933       DUL->NodeDeleted(N, nullptr);
934 
935     // Take the node out of the appropriate CSE map.
936     RemoveNodeFromCSEMaps(N);
937 
938     // Next, brutally remove the operand list.  This is safe to do, as there are
939     // no cycles in the graph.
940     for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) {
941       SDUse &Use = *I++;
942       SDNode *Operand = Use.getNode();
943       Use.set(SDValue());
944 
945       // Now that we removed this operand, see if there are no uses of it left.
946       if (Operand->use_empty())
947         DeadNodes.push_back(Operand);
948     }
949 
950     DeallocateNode(N);
951   }
952 }
953 
954 void SelectionDAG::RemoveDeadNode(SDNode *N){
955   SmallVector<SDNode*, 16> DeadNodes(1, N);
956 
957   // Create a dummy node that adds a reference to the root node, preventing
958   // it from being deleted.  (This matters if the root is an operand of the
959   // dead node.)
960   HandleSDNode Dummy(getRoot());
961 
962   RemoveDeadNodes(DeadNodes);
963 }
964 
965 void SelectionDAG::DeleteNode(SDNode *N) {
966   // First take this out of the appropriate CSE map.
967   RemoveNodeFromCSEMaps(N);
968 
969   // Finally, remove uses due to operands of this node, remove from the
970   // AllNodes list, and delete the node.
971   DeleteNodeNotInCSEMaps(N);
972 }
973 
974 void SelectionDAG::DeleteNodeNotInCSEMaps(SDNode *N) {
975   assert(N->getIterator() != AllNodes.begin() &&
976          "Cannot delete the entry node!");
977   assert(N->use_empty() && "Cannot delete a node that is not dead!");
978 
979   // Drop all of the operands and decrement used node's use counts.
980   N->DropOperands();
981 
982   DeallocateNode(N);
983 }
984 
985 void SDDbgInfo::add(SDDbgValue *V, bool isParameter) {
986   assert(!(V->isVariadic() && isParameter));
987   if (isParameter)
988     ByvalParmDbgValues.push_back(V);
989   else
990     DbgValues.push_back(V);
991   for (const SDNode *Node : V->getSDNodes())
992     if (Node)
993       DbgValMap[Node].push_back(V);
994 }
995 
996 void SDDbgInfo::erase(const SDNode *Node) {
997   DbgValMapType::iterator I = DbgValMap.find(Node);
998   if (I == DbgValMap.end())
999     return;
1000   for (auto &Val: I->second)
1001     Val->setIsInvalidated();
1002   DbgValMap.erase(I);
1003 }
1004 
1005 void SelectionDAG::DeallocateNode(SDNode *N) {
1006   // If we have operands, deallocate them.
1007   removeOperands(N);
1008 
1009   NodeAllocator.Deallocate(AllNodes.remove(N));
1010 
1011   // Set the opcode to DELETED_NODE to help catch bugs when node
1012   // memory is reallocated.
1013   // FIXME: There are places in SDag that have grown a dependency on the opcode
1014   // value in the released node.
1015   __asan_unpoison_memory_region(&N->NodeType, sizeof(N->NodeType));
1016   N->NodeType = ISD::DELETED_NODE;
1017 
1018   // If any of the SDDbgValue nodes refer to this SDNode, invalidate
1019   // them and forget about that node.
1020   DbgInfo->erase(N);
1021 }
1022 
1023 #ifndef NDEBUG
1024 /// VerifySDNode - Check the given SDNode.  Aborts if it is invalid.
1025 static void VerifySDNode(SDNode *N) {
1026   switch (N->getOpcode()) {
1027   default:
1028     break;
1029   case ISD::BUILD_PAIR: {
1030     EVT VT = N->getValueType(0);
1031     assert(N->getNumValues() == 1 && "Too many results!");
1032     assert(!VT.isVector() && (VT.isInteger() || VT.isFloatingPoint()) &&
1033            "Wrong return type!");
1034     assert(N->getNumOperands() == 2 && "Wrong number of operands!");
1035     assert(N->getOperand(0).getValueType() == N->getOperand(1).getValueType() &&
1036            "Mismatched operand types!");
1037     assert(N->getOperand(0).getValueType().isInteger() == VT.isInteger() &&
1038            "Wrong operand type!");
1039     assert(VT.getSizeInBits() == 2 * N->getOperand(0).getValueSizeInBits() &&
1040            "Wrong return type size");
1041     break;
1042   }
1043   case ISD::BUILD_VECTOR: {
1044     assert(N->getNumValues() == 1 && "Too many results!");
1045     assert(N->getValueType(0).isVector() && "Wrong return type!");
1046     assert(N->getNumOperands() == N->getValueType(0).getVectorNumElements() &&
1047            "Wrong number of operands!");
1048     EVT EltVT = N->getValueType(0).getVectorElementType();
1049     for (const SDUse &Op : N->ops()) {
1050       assert((Op.getValueType() == EltVT ||
1051               (EltVT.isInteger() && Op.getValueType().isInteger() &&
1052                EltVT.bitsLE(Op.getValueType()))) &&
1053              "Wrong operand type!");
1054       assert(Op.getValueType() == N->getOperand(0).getValueType() &&
1055              "Operands must all have the same type");
1056     }
1057     break;
1058   }
1059   }
1060 }
1061 #endif // NDEBUG
1062 
1063 /// Insert a newly allocated node into the DAG.
1064 ///
1065 /// Handles insertion into the all nodes list and CSE map, as well as
1066 /// verification and other common operations when a new node is allocated.
1067 void SelectionDAG::InsertNode(SDNode *N) {
1068   AllNodes.push_back(N);
1069 #ifndef NDEBUG
1070   N->PersistentId = NextPersistentId++;
1071   VerifySDNode(N);
1072 #endif
1073   for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
1074     DUL->NodeInserted(N);
1075 }
1076 
1077 /// RemoveNodeFromCSEMaps - Take the specified node out of the CSE map that
1078 /// correspond to it.  This is useful when we're about to delete or repurpose
1079 /// the node.  We don't want future request for structurally identical nodes
1080 /// to return N anymore.
1081 bool SelectionDAG::RemoveNodeFromCSEMaps(SDNode *N) {
1082   bool Erased = false;
1083   switch (N->getOpcode()) {
1084   case ISD::HANDLENODE: return false;  // noop.
1085   case ISD::CONDCODE:
1086     assert(CondCodeNodes[cast<CondCodeSDNode>(N)->get()] &&
1087            "Cond code doesn't exist!");
1088     Erased = CondCodeNodes[cast<CondCodeSDNode>(N)->get()] != nullptr;
1089     CondCodeNodes[cast<CondCodeSDNode>(N)->get()] = nullptr;
1090     break;
1091   case ISD::ExternalSymbol:
1092     Erased = ExternalSymbols.erase(cast<ExternalSymbolSDNode>(N)->getSymbol());
1093     break;
1094   case ISD::TargetExternalSymbol: {
1095     ExternalSymbolSDNode *ESN = cast<ExternalSymbolSDNode>(N);
1096     Erased = TargetExternalSymbols.erase(std::pair<std::string, unsigned>(
1097         ESN->getSymbol(), ESN->getTargetFlags()));
1098     break;
1099   }
1100   case ISD::MCSymbol: {
1101     auto *MCSN = cast<MCSymbolSDNode>(N);
1102     Erased = MCSymbols.erase(MCSN->getMCSymbol());
1103     break;
1104   }
1105   case ISD::VALUETYPE: {
1106     EVT VT = cast<VTSDNode>(N)->getVT();
1107     if (VT.isExtended()) {
1108       Erased = ExtendedValueTypeNodes.erase(VT);
1109     } else {
1110       Erased = ValueTypeNodes[VT.getSimpleVT().SimpleTy] != nullptr;
1111       ValueTypeNodes[VT.getSimpleVT().SimpleTy] = nullptr;
1112     }
1113     break;
1114   }
1115   default:
1116     // Remove it from the CSE Map.
1117     assert(N->getOpcode() != ISD::DELETED_NODE && "DELETED_NODE in CSEMap!");
1118     assert(N->getOpcode() != ISD::EntryToken && "EntryToken in CSEMap!");
1119     Erased = CSEMap.RemoveNode(N);
1120     break;
1121   }
1122 #ifndef NDEBUG
1123   // Verify that the node was actually in one of the CSE maps, unless it has a
1124   // flag result (which cannot be CSE'd) or is one of the special cases that are
1125   // not subject to CSE.
1126   if (!Erased && N->getValueType(N->getNumValues()-1) != MVT::Glue &&
1127       !N->isMachineOpcode() && !doNotCSE(N)) {
1128     N->dump(this);
1129     dbgs() << "\n";
1130     llvm_unreachable("Node is not in map!");
1131   }
1132 #endif
1133   return Erased;
1134 }
1135 
1136 /// AddModifiedNodeToCSEMaps - The specified node has been removed from the CSE
1137 /// maps and modified in place. Add it back to the CSE maps, unless an identical
1138 /// node already exists, in which case transfer all its users to the existing
1139 /// node. This transfer can potentially trigger recursive merging.
1140 void
1141 SelectionDAG::AddModifiedNodeToCSEMaps(SDNode *N) {
1142   // For node types that aren't CSE'd, just act as if no identical node
1143   // already exists.
1144   if (!doNotCSE(N)) {
1145     SDNode *Existing = CSEMap.GetOrInsertNode(N);
1146     if (Existing != N) {
1147       // If there was already an existing matching node, use ReplaceAllUsesWith
1148       // to replace the dead one with the existing one.  This can cause
1149       // recursive merging of other unrelated nodes down the line.
1150       ReplaceAllUsesWith(N, Existing);
1151 
1152       // N is now dead. Inform the listeners and delete it.
1153       for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
1154         DUL->NodeDeleted(N, Existing);
1155       DeleteNodeNotInCSEMaps(N);
1156       return;
1157     }
1158   }
1159 
1160   // If the node doesn't already exist, we updated it.  Inform listeners.
1161   for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
1162     DUL->NodeUpdated(N);
1163 }
1164 
1165 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
1166 /// were replaced with those specified.  If this node is never memoized,
1167 /// return null, otherwise return a pointer to the slot it would take.  If a
1168 /// node already exists with these operands, the slot will be non-null.
1169 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, SDValue Op,
1170                                            void *&InsertPos) {
1171   if (doNotCSE(N))
1172     return nullptr;
1173 
1174   SDValue Ops[] = { Op };
1175   FoldingSetNodeID ID;
1176   AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops);
1177   AddNodeIDCustom(ID, N);
1178   SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos);
1179   if (Node)
1180     Node->intersectFlagsWith(N->getFlags());
1181   return Node;
1182 }
1183 
1184 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
1185 /// were replaced with those specified.  If this node is never memoized,
1186 /// return null, otherwise return a pointer to the slot it would take.  If a
1187 /// node already exists with these operands, the slot will be non-null.
1188 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N,
1189                                            SDValue Op1, SDValue Op2,
1190                                            void *&InsertPos) {
1191   if (doNotCSE(N))
1192     return nullptr;
1193 
1194   SDValue Ops[] = { Op1, Op2 };
1195   FoldingSetNodeID ID;
1196   AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops);
1197   AddNodeIDCustom(ID, N);
1198   SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos);
1199   if (Node)
1200     Node->intersectFlagsWith(N->getFlags());
1201   return Node;
1202 }
1203 
1204 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
1205 /// were replaced with those specified.  If this node is never memoized,
1206 /// return null, otherwise return a pointer to the slot it would take.  If a
1207 /// node already exists with these operands, the slot will be non-null.
1208 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, ArrayRef<SDValue> Ops,
1209                                            void *&InsertPos) {
1210   if (doNotCSE(N))
1211     return nullptr;
1212 
1213   FoldingSetNodeID ID;
1214   AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops);
1215   AddNodeIDCustom(ID, N);
1216   SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos);
1217   if (Node)
1218     Node->intersectFlagsWith(N->getFlags());
1219   return Node;
1220 }
1221 
1222 Align SelectionDAG::getEVTAlign(EVT VT) const {
1223   Type *Ty = VT == MVT::iPTR ?
1224                    PointerType::get(Type::getInt8Ty(*getContext()), 0) :
1225                    VT.getTypeForEVT(*getContext());
1226 
1227   return getDataLayout().getABITypeAlign(Ty);
1228 }
1229 
1230 // EntryNode could meaningfully have debug info if we can find it...
1231 SelectionDAG::SelectionDAG(const TargetMachine &tm, CodeGenOpt::Level OL)
1232     : TM(tm), OptLevel(OL),
1233       EntryNode(ISD::EntryToken, 0, DebugLoc(), getVTList(MVT::Other)),
1234       Root(getEntryNode()) {
1235   InsertNode(&EntryNode);
1236   DbgInfo = new SDDbgInfo();
1237 }
1238 
1239 void SelectionDAG::init(MachineFunction &NewMF,
1240                         OptimizationRemarkEmitter &NewORE,
1241                         Pass *PassPtr, const TargetLibraryInfo *LibraryInfo,
1242                         LegacyDivergenceAnalysis * Divergence,
1243                         ProfileSummaryInfo *PSIin,
1244                         BlockFrequencyInfo *BFIin) {
1245   MF = &NewMF;
1246   SDAGISelPass = PassPtr;
1247   ORE = &NewORE;
1248   TLI = getSubtarget().getTargetLowering();
1249   TSI = getSubtarget().getSelectionDAGInfo();
1250   LibInfo = LibraryInfo;
1251   Context = &MF->getFunction().getContext();
1252   DA = Divergence;
1253   PSI = PSIin;
1254   BFI = BFIin;
1255 }
1256 
1257 SelectionDAG::~SelectionDAG() {
1258   assert(!UpdateListeners && "Dangling registered DAGUpdateListeners");
1259   allnodes_clear();
1260   OperandRecycler.clear(OperandAllocator);
1261   delete DbgInfo;
1262 }
1263 
1264 bool SelectionDAG::shouldOptForSize() const {
1265   return MF->getFunction().hasOptSize() ||
1266       llvm::shouldOptimizeForSize(FLI->MBB->getBasicBlock(), PSI, BFI);
1267 }
1268 
1269 void SelectionDAG::allnodes_clear() {
1270   assert(&*AllNodes.begin() == &EntryNode);
1271   AllNodes.remove(AllNodes.begin());
1272   while (!AllNodes.empty())
1273     DeallocateNode(&AllNodes.front());
1274 #ifndef NDEBUG
1275   NextPersistentId = 0;
1276 #endif
1277 }
1278 
1279 SDNode *SelectionDAG::FindNodeOrInsertPos(const FoldingSetNodeID &ID,
1280                                           void *&InsertPos) {
1281   SDNode *N = CSEMap.FindNodeOrInsertPos(ID, InsertPos);
1282   if (N) {
1283     switch (N->getOpcode()) {
1284     default: break;
1285     case ISD::Constant:
1286     case ISD::ConstantFP:
1287       llvm_unreachable("Querying for Constant and ConstantFP nodes requires "
1288                        "debug location.  Use another overload.");
1289     }
1290   }
1291   return N;
1292 }
1293 
1294 SDNode *SelectionDAG::FindNodeOrInsertPos(const FoldingSetNodeID &ID,
1295                                           const SDLoc &DL, void *&InsertPos) {
1296   SDNode *N = CSEMap.FindNodeOrInsertPos(ID, InsertPos);
1297   if (N) {
1298     switch (N->getOpcode()) {
1299     case ISD::Constant:
1300     case ISD::ConstantFP:
1301       // Erase debug location from the node if the node is used at several
1302       // different places. Do not propagate one location to all uses as it
1303       // will cause a worse single stepping debugging experience.
1304       if (N->getDebugLoc() != DL.getDebugLoc())
1305         N->setDebugLoc(DebugLoc());
1306       break;
1307     default:
1308       // When the node's point of use is located earlier in the instruction
1309       // sequence than its prior point of use, update its debug info to the
1310       // earlier location.
1311       if (DL.getIROrder() && DL.getIROrder() < N->getIROrder())
1312         N->setDebugLoc(DL.getDebugLoc());
1313       break;
1314     }
1315   }
1316   return N;
1317 }
1318 
1319 void SelectionDAG::clear() {
1320   allnodes_clear();
1321   OperandRecycler.clear(OperandAllocator);
1322   OperandAllocator.Reset();
1323   CSEMap.clear();
1324 
1325   ExtendedValueTypeNodes.clear();
1326   ExternalSymbols.clear();
1327   TargetExternalSymbols.clear();
1328   MCSymbols.clear();
1329   SDCallSiteDbgInfo.clear();
1330   std::fill(CondCodeNodes.begin(), CondCodeNodes.end(),
1331             static_cast<CondCodeSDNode*>(nullptr));
1332   std::fill(ValueTypeNodes.begin(), ValueTypeNodes.end(),
1333             static_cast<SDNode*>(nullptr));
1334 
1335   EntryNode.UseList = nullptr;
1336   InsertNode(&EntryNode);
1337   Root = getEntryNode();
1338   DbgInfo->clear();
1339 }
1340 
1341 SDValue SelectionDAG::getFPExtendOrRound(SDValue Op, const SDLoc &DL, EVT VT) {
1342   return VT.bitsGT(Op.getValueType())
1343              ? getNode(ISD::FP_EXTEND, DL, VT, Op)
1344              : getNode(ISD::FP_ROUND, DL, VT, Op, getIntPtrConstant(0, DL));
1345 }
1346 
1347 std::pair<SDValue, SDValue>
1348 SelectionDAG::getStrictFPExtendOrRound(SDValue Op, SDValue Chain,
1349                                        const SDLoc &DL, EVT VT) {
1350   assert(!VT.bitsEq(Op.getValueType()) &&
1351          "Strict no-op FP extend/round not allowed.");
1352   SDValue Res =
1353       VT.bitsGT(Op.getValueType())
1354           ? getNode(ISD::STRICT_FP_EXTEND, DL, {VT, MVT::Other}, {Chain, Op})
1355           : getNode(ISD::STRICT_FP_ROUND, DL, {VT, MVT::Other},
1356                     {Chain, Op, getIntPtrConstant(0, DL)});
1357 
1358   return std::pair<SDValue, SDValue>(Res, SDValue(Res.getNode(), 1));
1359 }
1360 
1361 SDValue SelectionDAG::getAnyExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
1362   return VT.bitsGT(Op.getValueType()) ?
1363     getNode(ISD::ANY_EXTEND, DL, VT, Op) :
1364     getNode(ISD::TRUNCATE, DL, VT, Op);
1365 }
1366 
1367 SDValue SelectionDAG::getSExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
1368   return VT.bitsGT(Op.getValueType()) ?
1369     getNode(ISD::SIGN_EXTEND, DL, VT, Op) :
1370     getNode(ISD::TRUNCATE, DL, VT, Op);
1371 }
1372 
1373 SDValue SelectionDAG::getZExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
1374   return VT.bitsGT(Op.getValueType()) ?
1375     getNode(ISD::ZERO_EXTEND, DL, VT, Op) :
1376     getNode(ISD::TRUNCATE, DL, VT, Op);
1377 }
1378 
1379 SDValue SelectionDAG::getBoolExtOrTrunc(SDValue Op, const SDLoc &SL, EVT VT,
1380                                         EVT OpVT) {
1381   if (VT.bitsLE(Op.getValueType()))
1382     return getNode(ISD::TRUNCATE, SL, VT, Op);
1383 
1384   TargetLowering::BooleanContent BType = TLI->getBooleanContents(OpVT);
1385   return getNode(TLI->getExtendForContent(BType), SL, VT, Op);
1386 }
1387 
1388 SDValue SelectionDAG::getZeroExtendInReg(SDValue Op, const SDLoc &DL, EVT VT) {
1389   EVT OpVT = Op.getValueType();
1390   assert(VT.isInteger() && OpVT.isInteger() &&
1391          "Cannot getZeroExtendInReg FP types");
1392   assert(VT.isVector() == OpVT.isVector() &&
1393          "getZeroExtendInReg type should be vector iff the operand "
1394          "type is vector!");
1395   assert((!VT.isVector() ||
1396           VT.getVectorElementCount() == OpVT.getVectorElementCount()) &&
1397          "Vector element counts must match in getZeroExtendInReg");
1398   assert(VT.bitsLE(OpVT) && "Not extending!");
1399   if (OpVT == VT)
1400     return Op;
1401   APInt Imm = APInt::getLowBitsSet(OpVT.getScalarSizeInBits(),
1402                                    VT.getScalarSizeInBits());
1403   return getNode(ISD::AND, DL, OpVT, Op, getConstant(Imm, DL, OpVT));
1404 }
1405 
1406 SDValue SelectionDAG::getPtrExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
1407   // Only unsigned pointer semantics are supported right now. In the future this
1408   // might delegate to TLI to check pointer signedness.
1409   return getZExtOrTrunc(Op, DL, VT);
1410 }
1411 
1412 SDValue SelectionDAG::getPtrExtendInReg(SDValue Op, const SDLoc &DL, EVT VT) {
1413   // Only unsigned pointer semantics are supported right now. In the future this
1414   // might delegate to TLI to check pointer signedness.
1415   return getZeroExtendInReg(Op, DL, VT);
1416 }
1417 
1418 /// getNOT - Create a bitwise NOT operation as (XOR Val, -1).
1419 SDValue SelectionDAG::getNOT(const SDLoc &DL, SDValue Val, EVT VT) {
1420   return getNode(ISD::XOR, DL, VT, Val, getAllOnesConstant(DL, VT));
1421 }
1422 
1423 SDValue SelectionDAG::getLogicalNOT(const SDLoc &DL, SDValue Val, EVT VT) {
1424   SDValue TrueValue = getBoolConstant(true, DL, VT, VT);
1425   return getNode(ISD::XOR, DL, VT, Val, TrueValue);
1426 }
1427 
1428 SDValue SelectionDAG::getVPLogicalNOT(const SDLoc &DL, SDValue Val,
1429                                       SDValue Mask, SDValue EVL, EVT VT) {
1430   SDValue TrueValue = getBoolConstant(true, DL, VT, VT);
1431   return getNode(ISD::VP_XOR, DL, VT, Val, TrueValue, Mask, EVL);
1432 }
1433 
1434 SDValue SelectionDAG::getBoolConstant(bool V, const SDLoc &DL, EVT VT,
1435                                       EVT OpVT) {
1436   if (!V)
1437     return getConstant(0, DL, VT);
1438 
1439   switch (TLI->getBooleanContents(OpVT)) {
1440   case TargetLowering::ZeroOrOneBooleanContent:
1441   case TargetLowering::UndefinedBooleanContent:
1442     return getConstant(1, DL, VT);
1443   case TargetLowering::ZeroOrNegativeOneBooleanContent:
1444     return getAllOnesConstant(DL, VT);
1445   }
1446   llvm_unreachable("Unexpected boolean content enum!");
1447 }
1448 
1449 SDValue SelectionDAG::getConstant(uint64_t Val, const SDLoc &DL, EVT VT,
1450                                   bool isT, bool isO) {
1451   EVT EltVT = VT.getScalarType();
1452   assert((EltVT.getSizeInBits() >= 64 ||
1453           (uint64_t)((int64_t)Val >> EltVT.getSizeInBits()) + 1 < 2) &&
1454          "getConstant with a uint64_t value that doesn't fit in the type!");
1455   return getConstant(APInt(EltVT.getSizeInBits(), Val), DL, VT, isT, isO);
1456 }
1457 
1458 SDValue SelectionDAG::getConstant(const APInt &Val, const SDLoc &DL, EVT VT,
1459                                   bool isT, bool isO) {
1460   return getConstant(*ConstantInt::get(*Context, Val), DL, VT, isT, isO);
1461 }
1462 
1463 SDValue SelectionDAG::getConstant(const ConstantInt &Val, const SDLoc &DL,
1464                                   EVT VT, bool isT, bool isO) {
1465   assert(VT.isInteger() && "Cannot create FP integer constant!");
1466 
1467   EVT EltVT = VT.getScalarType();
1468   const ConstantInt *Elt = &Val;
1469 
1470   // In some cases the vector type is legal but the element type is illegal and
1471   // needs to be promoted, for example v8i8 on ARM.  In this case, promote the
1472   // inserted value (the type does not need to match the vector element type).
1473   // Any extra bits introduced will be truncated away.
1474   if (VT.isVector() && TLI->getTypeAction(*getContext(), EltVT) ==
1475                            TargetLowering::TypePromoteInteger) {
1476     EltVT = TLI->getTypeToTransformTo(*getContext(), EltVT);
1477     APInt NewVal = Elt->getValue().zextOrTrunc(EltVT.getSizeInBits());
1478     Elt = ConstantInt::get(*getContext(), NewVal);
1479   }
1480   // In other cases the element type is illegal and needs to be expanded, for
1481   // example v2i64 on MIPS32. In this case, find the nearest legal type, split
1482   // the value into n parts and use a vector type with n-times the elements.
1483   // Then bitcast to the type requested.
1484   // Legalizing constants too early makes the DAGCombiner's job harder so we
1485   // only legalize if the DAG tells us we must produce legal types.
1486   else if (NewNodesMustHaveLegalTypes && VT.isVector() &&
1487            TLI->getTypeAction(*getContext(), EltVT) ==
1488                TargetLowering::TypeExpandInteger) {
1489     const APInt &NewVal = Elt->getValue();
1490     EVT ViaEltVT = TLI->getTypeToTransformTo(*getContext(), EltVT);
1491     unsigned ViaEltSizeInBits = ViaEltVT.getSizeInBits();
1492 
1493     // For scalable vectors, try to use a SPLAT_VECTOR_PARTS node.
1494     if (VT.isScalableVector()) {
1495       assert(EltVT.getSizeInBits() % ViaEltSizeInBits == 0 &&
1496              "Can only handle an even split!");
1497       unsigned Parts = EltVT.getSizeInBits() / ViaEltSizeInBits;
1498 
1499       SmallVector<SDValue, 2> ScalarParts;
1500       for (unsigned i = 0; i != Parts; ++i)
1501         ScalarParts.push_back(getConstant(
1502             NewVal.extractBits(ViaEltSizeInBits, i * ViaEltSizeInBits), DL,
1503             ViaEltVT, isT, isO));
1504 
1505       return getNode(ISD::SPLAT_VECTOR_PARTS, DL, VT, ScalarParts);
1506     }
1507 
1508     unsigned ViaVecNumElts = VT.getSizeInBits() / ViaEltSizeInBits;
1509     EVT ViaVecVT = EVT::getVectorVT(*getContext(), ViaEltVT, ViaVecNumElts);
1510 
1511     // Check the temporary vector is the correct size. If this fails then
1512     // getTypeToTransformTo() probably returned a type whose size (in bits)
1513     // isn't a power-of-2 factor of the requested type size.
1514     assert(ViaVecVT.getSizeInBits() == VT.getSizeInBits());
1515 
1516     SmallVector<SDValue, 2> EltParts;
1517     for (unsigned i = 0; i < ViaVecNumElts / VT.getVectorNumElements(); ++i)
1518       EltParts.push_back(getConstant(
1519           NewVal.extractBits(ViaEltSizeInBits, i * ViaEltSizeInBits), DL,
1520           ViaEltVT, isT, isO));
1521 
1522     // EltParts is currently in little endian order. If we actually want
1523     // big-endian order then reverse it now.
1524     if (getDataLayout().isBigEndian())
1525       std::reverse(EltParts.begin(), EltParts.end());
1526 
1527     // The elements must be reversed when the element order is different
1528     // to the endianness of the elements (because the BITCAST is itself a
1529     // vector shuffle in this situation). However, we do not need any code to
1530     // perform this reversal because getConstant() is producing a vector
1531     // splat.
1532     // This situation occurs in MIPS MSA.
1533 
1534     SmallVector<SDValue, 8> Ops;
1535     for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
1536       llvm::append_range(Ops, EltParts);
1537 
1538     SDValue V =
1539         getNode(ISD::BITCAST, DL, VT, getBuildVector(ViaVecVT, DL, Ops));
1540     return V;
1541   }
1542 
1543   assert(Elt->getBitWidth() == EltVT.getSizeInBits() &&
1544          "APInt size does not match type size!");
1545   unsigned Opc = isT ? ISD::TargetConstant : ISD::Constant;
1546   FoldingSetNodeID ID;
1547   AddNodeIDNode(ID, Opc, getVTList(EltVT), None);
1548   ID.AddPointer(Elt);
1549   ID.AddBoolean(isO);
1550   void *IP = nullptr;
1551   SDNode *N = nullptr;
1552   if ((N = FindNodeOrInsertPos(ID, DL, IP)))
1553     if (!VT.isVector())
1554       return SDValue(N, 0);
1555 
1556   if (!N) {
1557     N = newSDNode<ConstantSDNode>(isT, isO, Elt, EltVT);
1558     CSEMap.InsertNode(N, IP);
1559     InsertNode(N);
1560     NewSDValueDbgMsg(SDValue(N, 0), "Creating constant: ", this);
1561   }
1562 
1563   SDValue Result(N, 0);
1564   if (VT.isScalableVector())
1565     Result = getSplatVector(VT, DL, Result);
1566   else if (VT.isVector())
1567     Result = getSplatBuildVector(VT, DL, Result);
1568 
1569   return Result;
1570 }
1571 
1572 SDValue SelectionDAG::getIntPtrConstant(uint64_t Val, const SDLoc &DL,
1573                                         bool isTarget) {
1574   return getConstant(Val, DL, TLI->getPointerTy(getDataLayout()), isTarget);
1575 }
1576 
1577 SDValue SelectionDAG::getShiftAmountConstant(uint64_t Val, EVT VT,
1578                                              const SDLoc &DL, bool LegalTypes) {
1579   assert(VT.isInteger() && "Shift amount is not an integer type!");
1580   EVT ShiftVT = TLI->getShiftAmountTy(VT, getDataLayout(), LegalTypes);
1581   return getConstant(Val, DL, ShiftVT);
1582 }
1583 
1584 SDValue SelectionDAG::getVectorIdxConstant(uint64_t Val, const SDLoc &DL,
1585                                            bool isTarget) {
1586   return getConstant(Val, DL, TLI->getVectorIdxTy(getDataLayout()), isTarget);
1587 }
1588 
1589 SDValue SelectionDAG::getConstantFP(const APFloat &V, const SDLoc &DL, EVT VT,
1590                                     bool isTarget) {
1591   return getConstantFP(*ConstantFP::get(*getContext(), V), DL, VT, isTarget);
1592 }
1593 
1594 SDValue SelectionDAG::getConstantFP(const ConstantFP &V, const SDLoc &DL,
1595                                     EVT VT, bool isTarget) {
1596   assert(VT.isFloatingPoint() && "Cannot create integer FP constant!");
1597 
1598   EVT EltVT = VT.getScalarType();
1599 
1600   // Do the map lookup using the actual bit pattern for the floating point
1601   // value, so that we don't have problems with 0.0 comparing equal to -0.0, and
1602   // we don't have issues with SNANs.
1603   unsigned Opc = isTarget ? ISD::TargetConstantFP : ISD::ConstantFP;
1604   FoldingSetNodeID ID;
1605   AddNodeIDNode(ID, Opc, getVTList(EltVT), None);
1606   ID.AddPointer(&V);
1607   void *IP = nullptr;
1608   SDNode *N = nullptr;
1609   if ((N = FindNodeOrInsertPos(ID, DL, IP)))
1610     if (!VT.isVector())
1611       return SDValue(N, 0);
1612 
1613   if (!N) {
1614     N = newSDNode<ConstantFPSDNode>(isTarget, &V, EltVT);
1615     CSEMap.InsertNode(N, IP);
1616     InsertNode(N);
1617   }
1618 
1619   SDValue Result(N, 0);
1620   if (VT.isScalableVector())
1621     Result = getSplatVector(VT, DL, Result);
1622   else if (VT.isVector())
1623     Result = getSplatBuildVector(VT, DL, Result);
1624   NewSDValueDbgMsg(Result, "Creating fp constant: ", this);
1625   return Result;
1626 }
1627 
1628 SDValue SelectionDAG::getConstantFP(double Val, const SDLoc &DL, EVT VT,
1629                                     bool isTarget) {
1630   EVT EltVT = VT.getScalarType();
1631   if (EltVT == MVT::f32)
1632     return getConstantFP(APFloat((float)Val), DL, VT, isTarget);
1633   if (EltVT == MVT::f64)
1634     return getConstantFP(APFloat(Val), DL, VT, isTarget);
1635   if (EltVT == MVT::f80 || EltVT == MVT::f128 || EltVT == MVT::ppcf128 ||
1636       EltVT == MVT::f16 || EltVT == MVT::bf16) {
1637     bool Ignored;
1638     APFloat APF = APFloat(Val);
1639     APF.convert(EVTToAPFloatSemantics(EltVT), APFloat::rmNearestTiesToEven,
1640                 &Ignored);
1641     return getConstantFP(APF, DL, VT, isTarget);
1642   }
1643   llvm_unreachable("Unsupported type in getConstantFP");
1644 }
1645 
1646 SDValue SelectionDAG::getGlobalAddress(const GlobalValue *GV, const SDLoc &DL,
1647                                        EVT VT, int64_t Offset, bool isTargetGA,
1648                                        unsigned TargetFlags) {
1649   assert((TargetFlags == 0 || isTargetGA) &&
1650          "Cannot set target flags on target-independent globals");
1651 
1652   // Truncate (with sign-extension) the offset value to the pointer size.
1653   unsigned BitWidth = getDataLayout().getPointerTypeSizeInBits(GV->getType());
1654   if (BitWidth < 64)
1655     Offset = SignExtend64(Offset, BitWidth);
1656 
1657   unsigned Opc;
1658   if (GV->isThreadLocal())
1659     Opc = isTargetGA ? ISD::TargetGlobalTLSAddress : ISD::GlobalTLSAddress;
1660   else
1661     Opc = isTargetGA ? ISD::TargetGlobalAddress : ISD::GlobalAddress;
1662 
1663   FoldingSetNodeID ID;
1664   AddNodeIDNode(ID, Opc, getVTList(VT), None);
1665   ID.AddPointer(GV);
1666   ID.AddInteger(Offset);
1667   ID.AddInteger(TargetFlags);
1668   void *IP = nullptr;
1669   if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
1670     return SDValue(E, 0);
1671 
1672   auto *N = newSDNode<GlobalAddressSDNode>(
1673       Opc, DL.getIROrder(), DL.getDebugLoc(), GV, VT, Offset, TargetFlags);
1674   CSEMap.InsertNode(N, IP);
1675     InsertNode(N);
1676   return SDValue(N, 0);
1677 }
1678 
1679 SDValue SelectionDAG::getFrameIndex(int FI, EVT VT, bool isTarget) {
1680   unsigned Opc = isTarget ? ISD::TargetFrameIndex : ISD::FrameIndex;
1681   FoldingSetNodeID ID;
1682   AddNodeIDNode(ID, Opc, getVTList(VT), None);
1683   ID.AddInteger(FI);
1684   void *IP = nullptr;
1685   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1686     return SDValue(E, 0);
1687 
1688   auto *N = newSDNode<FrameIndexSDNode>(FI, VT, isTarget);
1689   CSEMap.InsertNode(N, IP);
1690   InsertNode(N);
1691   return SDValue(N, 0);
1692 }
1693 
1694 SDValue SelectionDAG::getJumpTable(int JTI, EVT VT, bool isTarget,
1695                                    unsigned TargetFlags) {
1696   assert((TargetFlags == 0 || isTarget) &&
1697          "Cannot set target flags on target-independent jump tables");
1698   unsigned Opc = isTarget ? ISD::TargetJumpTable : ISD::JumpTable;
1699   FoldingSetNodeID ID;
1700   AddNodeIDNode(ID, Opc, getVTList(VT), None);
1701   ID.AddInteger(JTI);
1702   ID.AddInteger(TargetFlags);
1703   void *IP = nullptr;
1704   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1705     return SDValue(E, 0);
1706 
1707   auto *N = newSDNode<JumpTableSDNode>(JTI, VT, isTarget, TargetFlags);
1708   CSEMap.InsertNode(N, IP);
1709   InsertNode(N);
1710   return SDValue(N, 0);
1711 }
1712 
1713 SDValue SelectionDAG::getConstantPool(const Constant *C, EVT VT,
1714                                       MaybeAlign Alignment, int Offset,
1715                                       bool isTarget, unsigned TargetFlags) {
1716   assert((TargetFlags == 0 || isTarget) &&
1717          "Cannot set target flags on target-independent globals");
1718   if (!Alignment)
1719     Alignment = shouldOptForSize()
1720                     ? getDataLayout().getABITypeAlign(C->getType())
1721                     : getDataLayout().getPrefTypeAlign(C->getType());
1722   unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
1723   FoldingSetNodeID ID;
1724   AddNodeIDNode(ID, Opc, getVTList(VT), None);
1725   ID.AddInteger(Alignment->value());
1726   ID.AddInteger(Offset);
1727   ID.AddPointer(C);
1728   ID.AddInteger(TargetFlags);
1729   void *IP = nullptr;
1730   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1731     return SDValue(E, 0);
1732 
1733   auto *N = newSDNode<ConstantPoolSDNode>(isTarget, C, VT, Offset, *Alignment,
1734                                           TargetFlags);
1735   CSEMap.InsertNode(N, IP);
1736   InsertNode(N);
1737   SDValue V = SDValue(N, 0);
1738   NewSDValueDbgMsg(V, "Creating new constant pool: ", this);
1739   return V;
1740 }
1741 
1742 SDValue SelectionDAG::getConstantPool(MachineConstantPoolValue *C, EVT VT,
1743                                       MaybeAlign Alignment, int Offset,
1744                                       bool isTarget, unsigned TargetFlags) {
1745   assert((TargetFlags == 0 || isTarget) &&
1746          "Cannot set target flags on target-independent globals");
1747   if (!Alignment)
1748     Alignment = getDataLayout().getPrefTypeAlign(C->getType());
1749   unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
1750   FoldingSetNodeID ID;
1751   AddNodeIDNode(ID, Opc, getVTList(VT), None);
1752   ID.AddInteger(Alignment->value());
1753   ID.AddInteger(Offset);
1754   C->addSelectionDAGCSEId(ID);
1755   ID.AddInteger(TargetFlags);
1756   void *IP = nullptr;
1757   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1758     return SDValue(E, 0);
1759 
1760   auto *N = newSDNode<ConstantPoolSDNode>(isTarget, C, VT, Offset, *Alignment,
1761                                           TargetFlags);
1762   CSEMap.InsertNode(N, IP);
1763   InsertNode(N);
1764   return SDValue(N, 0);
1765 }
1766 
1767 SDValue SelectionDAG::getTargetIndex(int Index, EVT VT, int64_t Offset,
1768                                      unsigned TargetFlags) {
1769   FoldingSetNodeID ID;
1770   AddNodeIDNode(ID, ISD::TargetIndex, getVTList(VT), None);
1771   ID.AddInteger(Index);
1772   ID.AddInteger(Offset);
1773   ID.AddInteger(TargetFlags);
1774   void *IP = nullptr;
1775   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1776     return SDValue(E, 0);
1777 
1778   auto *N = newSDNode<TargetIndexSDNode>(Index, VT, Offset, TargetFlags);
1779   CSEMap.InsertNode(N, IP);
1780   InsertNode(N);
1781   return SDValue(N, 0);
1782 }
1783 
1784 SDValue SelectionDAG::getBasicBlock(MachineBasicBlock *MBB) {
1785   FoldingSetNodeID ID;
1786   AddNodeIDNode(ID, ISD::BasicBlock, getVTList(MVT::Other), None);
1787   ID.AddPointer(MBB);
1788   void *IP = nullptr;
1789   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1790     return SDValue(E, 0);
1791 
1792   auto *N = newSDNode<BasicBlockSDNode>(MBB);
1793   CSEMap.InsertNode(N, IP);
1794   InsertNode(N);
1795   return SDValue(N, 0);
1796 }
1797 
1798 SDValue SelectionDAG::getValueType(EVT VT) {
1799   if (VT.isSimple() && (unsigned)VT.getSimpleVT().SimpleTy >=
1800       ValueTypeNodes.size())
1801     ValueTypeNodes.resize(VT.getSimpleVT().SimpleTy+1);
1802 
1803   SDNode *&N = VT.isExtended() ?
1804     ExtendedValueTypeNodes[VT] : ValueTypeNodes[VT.getSimpleVT().SimpleTy];
1805 
1806   if (N) return SDValue(N, 0);
1807   N = newSDNode<VTSDNode>(VT);
1808   InsertNode(N);
1809   return SDValue(N, 0);
1810 }
1811 
1812 SDValue SelectionDAG::getExternalSymbol(const char *Sym, EVT VT) {
1813   SDNode *&N = ExternalSymbols[Sym];
1814   if (N) return SDValue(N, 0);
1815   N = newSDNode<ExternalSymbolSDNode>(false, Sym, 0, VT);
1816   InsertNode(N);
1817   return SDValue(N, 0);
1818 }
1819 
1820 SDValue SelectionDAG::getMCSymbol(MCSymbol *Sym, EVT VT) {
1821   SDNode *&N = MCSymbols[Sym];
1822   if (N)
1823     return SDValue(N, 0);
1824   N = newSDNode<MCSymbolSDNode>(Sym, VT);
1825   InsertNode(N);
1826   return SDValue(N, 0);
1827 }
1828 
1829 SDValue SelectionDAG::getTargetExternalSymbol(const char *Sym, EVT VT,
1830                                               unsigned TargetFlags) {
1831   SDNode *&N =
1832       TargetExternalSymbols[std::pair<std::string, unsigned>(Sym, TargetFlags)];
1833   if (N) return SDValue(N, 0);
1834   N = newSDNode<ExternalSymbolSDNode>(true, Sym, TargetFlags, VT);
1835   InsertNode(N);
1836   return SDValue(N, 0);
1837 }
1838 
1839 SDValue SelectionDAG::getCondCode(ISD::CondCode Cond) {
1840   if ((unsigned)Cond >= CondCodeNodes.size())
1841     CondCodeNodes.resize(Cond+1);
1842 
1843   if (!CondCodeNodes[Cond]) {
1844     auto *N = newSDNode<CondCodeSDNode>(Cond);
1845     CondCodeNodes[Cond] = N;
1846     InsertNode(N);
1847   }
1848 
1849   return SDValue(CondCodeNodes[Cond], 0);
1850 }
1851 
1852 SDValue SelectionDAG::getStepVector(const SDLoc &DL, EVT ResVT) {
1853   APInt One(ResVT.getScalarSizeInBits(), 1);
1854   return getStepVector(DL, ResVT, One);
1855 }
1856 
1857 SDValue SelectionDAG::getStepVector(const SDLoc &DL, EVT ResVT, APInt StepVal) {
1858   assert(ResVT.getScalarSizeInBits() == StepVal.getBitWidth());
1859   if (ResVT.isScalableVector())
1860     return getNode(
1861         ISD::STEP_VECTOR, DL, ResVT,
1862         getTargetConstant(StepVal, DL, ResVT.getVectorElementType()));
1863 
1864   SmallVector<SDValue, 16> OpsStepConstants;
1865   for (uint64_t i = 0; i < ResVT.getVectorNumElements(); i++)
1866     OpsStepConstants.push_back(
1867         getConstant(StepVal * i, DL, ResVT.getVectorElementType()));
1868   return getBuildVector(ResVT, DL, OpsStepConstants);
1869 }
1870 
1871 /// Swaps the values of N1 and N2. Swaps all indices in the shuffle mask M that
1872 /// point at N1 to point at N2 and indices that point at N2 to point at N1.
1873 static void commuteShuffle(SDValue &N1, SDValue &N2, MutableArrayRef<int> M) {
1874   std::swap(N1, N2);
1875   ShuffleVectorSDNode::commuteMask(M);
1876 }
1877 
1878 SDValue SelectionDAG::getVectorShuffle(EVT VT, const SDLoc &dl, SDValue N1,
1879                                        SDValue N2, ArrayRef<int> Mask) {
1880   assert(VT.getVectorNumElements() == Mask.size() &&
1881          "Must have the same number of vector elements as mask elements!");
1882   assert(VT == N1.getValueType() && VT == N2.getValueType() &&
1883          "Invalid VECTOR_SHUFFLE");
1884 
1885   // Canonicalize shuffle undef, undef -> undef
1886   if (N1.isUndef() && N2.isUndef())
1887     return getUNDEF(VT);
1888 
1889   // Validate that all indices in Mask are within the range of the elements
1890   // input to the shuffle.
1891   int NElts = Mask.size();
1892   assert(llvm::all_of(Mask,
1893                       [&](int M) { return M < (NElts * 2) && M >= -1; }) &&
1894          "Index out of range");
1895 
1896   // Copy the mask so we can do any needed cleanup.
1897   SmallVector<int, 8> MaskVec(Mask.begin(), Mask.end());
1898 
1899   // Canonicalize shuffle v, v -> v, undef
1900   if (N1 == N2) {
1901     N2 = getUNDEF(VT);
1902     for (int i = 0; i != NElts; ++i)
1903       if (MaskVec[i] >= NElts) MaskVec[i] -= NElts;
1904   }
1905 
1906   // Canonicalize shuffle undef, v -> v, undef.  Commute the shuffle mask.
1907   if (N1.isUndef())
1908     commuteShuffle(N1, N2, MaskVec);
1909 
1910   if (TLI->hasVectorBlend()) {
1911     // If shuffling a splat, try to blend the splat instead. We do this here so
1912     // that even when this arises during lowering we don't have to re-handle it.
1913     auto BlendSplat = [&](BuildVectorSDNode *BV, int Offset) {
1914       BitVector UndefElements;
1915       SDValue Splat = BV->getSplatValue(&UndefElements);
1916       if (!Splat)
1917         return;
1918 
1919       for (int i = 0; i < NElts; ++i) {
1920         if (MaskVec[i] < Offset || MaskVec[i] >= (Offset + NElts))
1921           continue;
1922 
1923         // If this input comes from undef, mark it as such.
1924         if (UndefElements[MaskVec[i] - Offset]) {
1925           MaskVec[i] = -1;
1926           continue;
1927         }
1928 
1929         // If we can blend a non-undef lane, use that instead.
1930         if (!UndefElements[i])
1931           MaskVec[i] = i + Offset;
1932       }
1933     };
1934     if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
1935       BlendSplat(N1BV, 0);
1936     if (auto *N2BV = dyn_cast<BuildVectorSDNode>(N2))
1937       BlendSplat(N2BV, NElts);
1938   }
1939 
1940   // Canonicalize all index into lhs, -> shuffle lhs, undef
1941   // Canonicalize all index into rhs, -> shuffle rhs, undef
1942   bool AllLHS = true, AllRHS = true;
1943   bool N2Undef = N2.isUndef();
1944   for (int i = 0; i != NElts; ++i) {
1945     if (MaskVec[i] >= NElts) {
1946       if (N2Undef)
1947         MaskVec[i] = -1;
1948       else
1949         AllLHS = false;
1950     } else if (MaskVec[i] >= 0) {
1951       AllRHS = false;
1952     }
1953   }
1954   if (AllLHS && AllRHS)
1955     return getUNDEF(VT);
1956   if (AllLHS && !N2Undef)
1957     N2 = getUNDEF(VT);
1958   if (AllRHS) {
1959     N1 = getUNDEF(VT);
1960     commuteShuffle(N1, N2, MaskVec);
1961   }
1962   // Reset our undef status after accounting for the mask.
1963   N2Undef = N2.isUndef();
1964   // Re-check whether both sides ended up undef.
1965   if (N1.isUndef() && N2Undef)
1966     return getUNDEF(VT);
1967 
1968   // If Identity shuffle return that node.
1969   bool Identity = true, AllSame = true;
1970   for (int i = 0; i != NElts; ++i) {
1971     if (MaskVec[i] >= 0 && MaskVec[i] != i) Identity = false;
1972     if (MaskVec[i] != MaskVec[0]) AllSame = false;
1973   }
1974   if (Identity && NElts)
1975     return N1;
1976 
1977   // Shuffling a constant splat doesn't change the result.
1978   if (N2Undef) {
1979     SDValue V = N1;
1980 
1981     // Look through any bitcasts. We check that these don't change the number
1982     // (and size) of elements and just changes their types.
1983     while (V.getOpcode() == ISD::BITCAST)
1984       V = V->getOperand(0);
1985 
1986     // A splat should always show up as a build vector node.
1987     if (auto *BV = dyn_cast<BuildVectorSDNode>(V)) {
1988       BitVector UndefElements;
1989       SDValue Splat = BV->getSplatValue(&UndefElements);
1990       // If this is a splat of an undef, shuffling it is also undef.
1991       if (Splat && Splat.isUndef())
1992         return getUNDEF(VT);
1993 
1994       bool SameNumElts =
1995           V.getValueType().getVectorNumElements() == VT.getVectorNumElements();
1996 
1997       // We only have a splat which can skip shuffles if there is a splatted
1998       // value and no undef lanes rearranged by the shuffle.
1999       if (Splat && UndefElements.none()) {
2000         // Splat of <x, x, ..., x>, return <x, x, ..., x>, provided that the
2001         // number of elements match or the value splatted is a zero constant.
2002         if (SameNumElts)
2003           return N1;
2004         if (auto *C = dyn_cast<ConstantSDNode>(Splat))
2005           if (C->isZero())
2006             return N1;
2007       }
2008 
2009       // If the shuffle itself creates a splat, build the vector directly.
2010       if (AllSame && SameNumElts) {
2011         EVT BuildVT = BV->getValueType(0);
2012         const SDValue &Splatted = BV->getOperand(MaskVec[0]);
2013         SDValue NewBV = getSplatBuildVector(BuildVT, dl, Splatted);
2014 
2015         // We may have jumped through bitcasts, so the type of the
2016         // BUILD_VECTOR may not match the type of the shuffle.
2017         if (BuildVT != VT)
2018           NewBV = getNode(ISD::BITCAST, dl, VT, NewBV);
2019         return NewBV;
2020       }
2021     }
2022   }
2023 
2024   FoldingSetNodeID ID;
2025   SDValue Ops[2] = { N1, N2 };
2026   AddNodeIDNode(ID, ISD::VECTOR_SHUFFLE, getVTList(VT), Ops);
2027   for (int i = 0; i != NElts; ++i)
2028     ID.AddInteger(MaskVec[i]);
2029 
2030   void* IP = nullptr;
2031   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
2032     return SDValue(E, 0);
2033 
2034   // Allocate the mask array for the node out of the BumpPtrAllocator, since
2035   // SDNode doesn't have access to it.  This memory will be "leaked" when
2036   // the node is deallocated, but recovered when the NodeAllocator is released.
2037   int *MaskAlloc = OperandAllocator.Allocate<int>(NElts);
2038   llvm::copy(MaskVec, MaskAlloc);
2039 
2040   auto *N = newSDNode<ShuffleVectorSDNode>(VT, dl.getIROrder(),
2041                                            dl.getDebugLoc(), MaskAlloc);
2042   createOperands(N, Ops);
2043 
2044   CSEMap.InsertNode(N, IP);
2045   InsertNode(N);
2046   SDValue V = SDValue(N, 0);
2047   NewSDValueDbgMsg(V, "Creating new node: ", this);
2048   return V;
2049 }
2050 
2051 SDValue SelectionDAG::getCommutedVectorShuffle(const ShuffleVectorSDNode &SV) {
2052   EVT VT = SV.getValueType(0);
2053   SmallVector<int, 8> MaskVec(SV.getMask().begin(), SV.getMask().end());
2054   ShuffleVectorSDNode::commuteMask(MaskVec);
2055 
2056   SDValue Op0 = SV.getOperand(0);
2057   SDValue Op1 = SV.getOperand(1);
2058   return getVectorShuffle(VT, SDLoc(&SV), Op1, Op0, MaskVec);
2059 }
2060 
2061 SDValue SelectionDAG::getRegister(unsigned RegNo, EVT VT) {
2062   FoldingSetNodeID ID;
2063   AddNodeIDNode(ID, ISD::Register, getVTList(VT), None);
2064   ID.AddInteger(RegNo);
2065   void *IP = nullptr;
2066   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2067     return SDValue(E, 0);
2068 
2069   auto *N = newSDNode<RegisterSDNode>(RegNo, VT);
2070   N->SDNodeBits.IsDivergent = TLI->isSDNodeSourceOfDivergence(N, FLI, DA);
2071   CSEMap.InsertNode(N, IP);
2072   InsertNode(N);
2073   return SDValue(N, 0);
2074 }
2075 
2076 SDValue SelectionDAG::getRegisterMask(const uint32_t *RegMask) {
2077   FoldingSetNodeID ID;
2078   AddNodeIDNode(ID, ISD::RegisterMask, getVTList(MVT::Untyped), None);
2079   ID.AddPointer(RegMask);
2080   void *IP = nullptr;
2081   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2082     return SDValue(E, 0);
2083 
2084   auto *N = newSDNode<RegisterMaskSDNode>(RegMask);
2085   CSEMap.InsertNode(N, IP);
2086   InsertNode(N);
2087   return SDValue(N, 0);
2088 }
2089 
2090 SDValue SelectionDAG::getEHLabel(const SDLoc &dl, SDValue Root,
2091                                  MCSymbol *Label) {
2092   return getLabelNode(ISD::EH_LABEL, dl, Root, Label);
2093 }
2094 
2095 SDValue SelectionDAG::getLabelNode(unsigned Opcode, const SDLoc &dl,
2096                                    SDValue Root, MCSymbol *Label) {
2097   FoldingSetNodeID ID;
2098   SDValue Ops[] = { Root };
2099   AddNodeIDNode(ID, Opcode, getVTList(MVT::Other), Ops);
2100   ID.AddPointer(Label);
2101   void *IP = nullptr;
2102   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2103     return SDValue(E, 0);
2104 
2105   auto *N =
2106       newSDNode<LabelSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(), Label);
2107   createOperands(N, Ops);
2108 
2109   CSEMap.InsertNode(N, IP);
2110   InsertNode(N);
2111   return SDValue(N, 0);
2112 }
2113 
2114 SDValue SelectionDAG::getBlockAddress(const BlockAddress *BA, EVT VT,
2115                                       int64_t Offset, bool isTarget,
2116                                       unsigned TargetFlags) {
2117   unsigned Opc = isTarget ? ISD::TargetBlockAddress : ISD::BlockAddress;
2118 
2119   FoldingSetNodeID ID;
2120   AddNodeIDNode(ID, Opc, getVTList(VT), None);
2121   ID.AddPointer(BA);
2122   ID.AddInteger(Offset);
2123   ID.AddInteger(TargetFlags);
2124   void *IP = nullptr;
2125   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2126     return SDValue(E, 0);
2127 
2128   auto *N = newSDNode<BlockAddressSDNode>(Opc, VT, BA, Offset, TargetFlags);
2129   CSEMap.InsertNode(N, IP);
2130   InsertNode(N);
2131   return SDValue(N, 0);
2132 }
2133 
2134 SDValue SelectionDAG::getSrcValue(const Value *V) {
2135   FoldingSetNodeID ID;
2136   AddNodeIDNode(ID, ISD::SRCVALUE, getVTList(MVT::Other), None);
2137   ID.AddPointer(V);
2138 
2139   void *IP = nullptr;
2140   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2141     return SDValue(E, 0);
2142 
2143   auto *N = newSDNode<SrcValueSDNode>(V);
2144   CSEMap.InsertNode(N, IP);
2145   InsertNode(N);
2146   return SDValue(N, 0);
2147 }
2148 
2149 SDValue SelectionDAG::getMDNode(const MDNode *MD) {
2150   FoldingSetNodeID ID;
2151   AddNodeIDNode(ID, ISD::MDNODE_SDNODE, getVTList(MVT::Other), None);
2152   ID.AddPointer(MD);
2153 
2154   void *IP = nullptr;
2155   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2156     return SDValue(E, 0);
2157 
2158   auto *N = newSDNode<MDNodeSDNode>(MD);
2159   CSEMap.InsertNode(N, IP);
2160   InsertNode(N);
2161   return SDValue(N, 0);
2162 }
2163 
2164 SDValue SelectionDAG::getBitcast(EVT VT, SDValue V) {
2165   if (VT == V.getValueType())
2166     return V;
2167 
2168   return getNode(ISD::BITCAST, SDLoc(V), VT, V);
2169 }
2170 
2171 SDValue SelectionDAG::getAddrSpaceCast(const SDLoc &dl, EVT VT, SDValue Ptr,
2172                                        unsigned SrcAS, unsigned DestAS) {
2173   SDValue Ops[] = {Ptr};
2174   FoldingSetNodeID ID;
2175   AddNodeIDNode(ID, ISD::ADDRSPACECAST, getVTList(VT), Ops);
2176   ID.AddInteger(SrcAS);
2177   ID.AddInteger(DestAS);
2178 
2179   void *IP = nullptr;
2180   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
2181     return SDValue(E, 0);
2182 
2183   auto *N = newSDNode<AddrSpaceCastSDNode>(dl.getIROrder(), dl.getDebugLoc(),
2184                                            VT, SrcAS, DestAS);
2185   createOperands(N, Ops);
2186 
2187   CSEMap.InsertNode(N, IP);
2188   InsertNode(N);
2189   return SDValue(N, 0);
2190 }
2191 
2192 SDValue SelectionDAG::getFreeze(SDValue V) {
2193   return getNode(ISD::FREEZE, SDLoc(V), V.getValueType(), V);
2194 }
2195 
2196 /// getShiftAmountOperand - Return the specified value casted to
2197 /// the target's desired shift amount type.
2198 SDValue SelectionDAG::getShiftAmountOperand(EVT LHSTy, SDValue Op) {
2199   EVT OpTy = Op.getValueType();
2200   EVT ShTy = TLI->getShiftAmountTy(LHSTy, getDataLayout());
2201   if (OpTy == ShTy || OpTy.isVector()) return Op;
2202 
2203   return getZExtOrTrunc(Op, SDLoc(Op), ShTy);
2204 }
2205 
2206 SDValue SelectionDAG::expandVAArg(SDNode *Node) {
2207   SDLoc dl(Node);
2208   const TargetLowering &TLI = getTargetLoweringInfo();
2209   const Value *V = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
2210   EVT VT = Node->getValueType(0);
2211   SDValue Tmp1 = Node->getOperand(0);
2212   SDValue Tmp2 = Node->getOperand(1);
2213   const MaybeAlign MA(Node->getConstantOperandVal(3));
2214 
2215   SDValue VAListLoad = getLoad(TLI.getPointerTy(getDataLayout()), dl, Tmp1,
2216                                Tmp2, MachinePointerInfo(V));
2217   SDValue VAList = VAListLoad;
2218 
2219   if (MA && *MA > TLI.getMinStackArgumentAlignment()) {
2220     VAList = getNode(ISD::ADD, dl, VAList.getValueType(), VAList,
2221                      getConstant(MA->value() - 1, dl, VAList.getValueType()));
2222 
2223     VAList =
2224         getNode(ISD::AND, dl, VAList.getValueType(), VAList,
2225                 getConstant(-(int64_t)MA->value(), dl, VAList.getValueType()));
2226   }
2227 
2228   // Increment the pointer, VAList, to the next vaarg
2229   Tmp1 = getNode(ISD::ADD, dl, VAList.getValueType(), VAList,
2230                  getConstant(getDataLayout().getTypeAllocSize(
2231                                                VT.getTypeForEVT(*getContext())),
2232                              dl, VAList.getValueType()));
2233   // Store the incremented VAList to the legalized pointer
2234   Tmp1 =
2235       getStore(VAListLoad.getValue(1), dl, Tmp1, Tmp2, MachinePointerInfo(V));
2236   // Load the actual argument out of the pointer VAList
2237   return getLoad(VT, dl, Tmp1, VAList, MachinePointerInfo());
2238 }
2239 
2240 SDValue SelectionDAG::expandVACopy(SDNode *Node) {
2241   SDLoc dl(Node);
2242   const TargetLowering &TLI = getTargetLoweringInfo();
2243   // This defaults to loading a pointer from the input and storing it to the
2244   // output, returning the chain.
2245   const Value *VD = cast<SrcValueSDNode>(Node->getOperand(3))->getValue();
2246   const Value *VS = cast<SrcValueSDNode>(Node->getOperand(4))->getValue();
2247   SDValue Tmp1 =
2248       getLoad(TLI.getPointerTy(getDataLayout()), dl, Node->getOperand(0),
2249               Node->getOperand(2), MachinePointerInfo(VS));
2250   return getStore(Tmp1.getValue(1), dl, Tmp1, Node->getOperand(1),
2251                   MachinePointerInfo(VD));
2252 }
2253 
2254 Align SelectionDAG::getReducedAlign(EVT VT, bool UseABI) {
2255   const DataLayout &DL = getDataLayout();
2256   Type *Ty = VT.getTypeForEVT(*getContext());
2257   Align RedAlign = UseABI ? DL.getABITypeAlign(Ty) : DL.getPrefTypeAlign(Ty);
2258 
2259   if (TLI->isTypeLegal(VT) || !VT.isVector())
2260     return RedAlign;
2261 
2262   const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering();
2263   const Align StackAlign = TFI->getStackAlign();
2264 
2265   // See if we can choose a smaller ABI alignment in cases where it's an
2266   // illegal vector type that will get broken down.
2267   if (RedAlign > StackAlign) {
2268     EVT IntermediateVT;
2269     MVT RegisterVT;
2270     unsigned NumIntermediates;
2271     TLI->getVectorTypeBreakdown(*getContext(), VT, IntermediateVT,
2272                                 NumIntermediates, RegisterVT);
2273     Ty = IntermediateVT.getTypeForEVT(*getContext());
2274     Align RedAlign2 = UseABI ? DL.getABITypeAlign(Ty) : DL.getPrefTypeAlign(Ty);
2275     if (RedAlign2 < RedAlign)
2276       RedAlign = RedAlign2;
2277   }
2278 
2279   return RedAlign;
2280 }
2281 
2282 SDValue SelectionDAG::CreateStackTemporary(TypeSize Bytes, Align Alignment) {
2283   MachineFrameInfo &MFI = MF->getFrameInfo();
2284   const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering();
2285   int StackID = 0;
2286   if (Bytes.isScalable())
2287     StackID = TFI->getStackIDForScalableVectors();
2288   // The stack id gives an indication of whether the object is scalable or
2289   // not, so it's safe to pass in the minimum size here.
2290   int FrameIdx = MFI.CreateStackObject(Bytes.getKnownMinSize(), Alignment,
2291                                        false, nullptr, StackID);
2292   return getFrameIndex(FrameIdx, TLI->getFrameIndexTy(getDataLayout()));
2293 }
2294 
2295 SDValue SelectionDAG::CreateStackTemporary(EVT VT, unsigned minAlign) {
2296   Type *Ty = VT.getTypeForEVT(*getContext());
2297   Align StackAlign =
2298       std::max(getDataLayout().getPrefTypeAlign(Ty), Align(minAlign));
2299   return CreateStackTemporary(VT.getStoreSize(), StackAlign);
2300 }
2301 
2302 SDValue SelectionDAG::CreateStackTemporary(EVT VT1, EVT VT2) {
2303   TypeSize VT1Size = VT1.getStoreSize();
2304   TypeSize VT2Size = VT2.getStoreSize();
2305   assert(VT1Size.isScalable() == VT2Size.isScalable() &&
2306          "Don't know how to choose the maximum size when creating a stack "
2307          "temporary");
2308   TypeSize Bytes =
2309       VT1Size.getKnownMinSize() > VT2Size.getKnownMinSize() ? VT1Size : VT2Size;
2310 
2311   Type *Ty1 = VT1.getTypeForEVT(*getContext());
2312   Type *Ty2 = VT2.getTypeForEVT(*getContext());
2313   const DataLayout &DL = getDataLayout();
2314   Align Align = std::max(DL.getPrefTypeAlign(Ty1), DL.getPrefTypeAlign(Ty2));
2315   return CreateStackTemporary(Bytes, Align);
2316 }
2317 
2318 SDValue SelectionDAG::FoldSetCC(EVT VT, SDValue N1, SDValue N2,
2319                                 ISD::CondCode Cond, const SDLoc &dl) {
2320   EVT OpVT = N1.getValueType();
2321 
2322   // These setcc operations always fold.
2323   switch (Cond) {
2324   default: break;
2325   case ISD::SETFALSE:
2326   case ISD::SETFALSE2: return getBoolConstant(false, dl, VT, OpVT);
2327   case ISD::SETTRUE:
2328   case ISD::SETTRUE2: return getBoolConstant(true, dl, VT, OpVT);
2329 
2330   case ISD::SETOEQ:
2331   case ISD::SETOGT:
2332   case ISD::SETOGE:
2333   case ISD::SETOLT:
2334   case ISD::SETOLE:
2335   case ISD::SETONE:
2336   case ISD::SETO:
2337   case ISD::SETUO:
2338   case ISD::SETUEQ:
2339   case ISD::SETUNE:
2340     assert(!OpVT.isInteger() && "Illegal setcc for integer!");
2341     break;
2342   }
2343 
2344   if (OpVT.isInteger()) {
2345     // For EQ and NE, we can always pick a value for the undef to make the
2346     // predicate pass or fail, so we can return undef.
2347     // Matches behavior in llvm::ConstantFoldCompareInstruction.
2348     // icmp eq/ne X, undef -> undef.
2349     if ((N1.isUndef() || N2.isUndef()) &&
2350         (Cond == ISD::SETEQ || Cond == ISD::SETNE))
2351       return getUNDEF(VT);
2352 
2353     // If both operands are undef, we can return undef for int comparison.
2354     // icmp undef, undef -> undef.
2355     if (N1.isUndef() && N2.isUndef())
2356       return getUNDEF(VT);
2357 
2358     // icmp X, X -> true/false
2359     // icmp X, undef -> true/false because undef could be X.
2360     if (N1 == N2)
2361       return getBoolConstant(ISD::isTrueWhenEqual(Cond), dl, VT, OpVT);
2362   }
2363 
2364   if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2)) {
2365     const APInt &C2 = N2C->getAPIntValue();
2366     if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1)) {
2367       const APInt &C1 = N1C->getAPIntValue();
2368 
2369       return getBoolConstant(ICmpInst::compare(C1, C2, getICmpCondCode(Cond)),
2370                              dl, VT, OpVT);
2371     }
2372   }
2373 
2374   auto *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
2375   auto *N2CFP = dyn_cast<ConstantFPSDNode>(N2);
2376 
2377   if (N1CFP && N2CFP) {
2378     APFloat::cmpResult R = N1CFP->getValueAPF().compare(N2CFP->getValueAPF());
2379     switch (Cond) {
2380     default: break;
2381     case ISD::SETEQ:  if (R==APFloat::cmpUnordered)
2382                         return getUNDEF(VT);
2383                       LLVM_FALLTHROUGH;
2384     case ISD::SETOEQ: return getBoolConstant(R==APFloat::cmpEqual, dl, VT,
2385                                              OpVT);
2386     case ISD::SETNE:  if (R==APFloat::cmpUnordered)
2387                         return getUNDEF(VT);
2388                       LLVM_FALLTHROUGH;
2389     case ISD::SETONE: return getBoolConstant(R==APFloat::cmpGreaterThan ||
2390                                              R==APFloat::cmpLessThan, dl, VT,
2391                                              OpVT);
2392     case ISD::SETLT:  if (R==APFloat::cmpUnordered)
2393                         return getUNDEF(VT);
2394                       LLVM_FALLTHROUGH;
2395     case ISD::SETOLT: return getBoolConstant(R==APFloat::cmpLessThan, dl, VT,
2396                                              OpVT);
2397     case ISD::SETGT:  if (R==APFloat::cmpUnordered)
2398                         return getUNDEF(VT);
2399                       LLVM_FALLTHROUGH;
2400     case ISD::SETOGT: return getBoolConstant(R==APFloat::cmpGreaterThan, dl,
2401                                              VT, OpVT);
2402     case ISD::SETLE:  if (R==APFloat::cmpUnordered)
2403                         return getUNDEF(VT);
2404                       LLVM_FALLTHROUGH;
2405     case ISD::SETOLE: return getBoolConstant(R==APFloat::cmpLessThan ||
2406                                              R==APFloat::cmpEqual, dl, VT,
2407                                              OpVT);
2408     case ISD::SETGE:  if (R==APFloat::cmpUnordered)
2409                         return getUNDEF(VT);
2410                       LLVM_FALLTHROUGH;
2411     case ISD::SETOGE: return getBoolConstant(R==APFloat::cmpGreaterThan ||
2412                                          R==APFloat::cmpEqual, dl, VT, OpVT);
2413     case ISD::SETO:   return getBoolConstant(R!=APFloat::cmpUnordered, dl, VT,
2414                                              OpVT);
2415     case ISD::SETUO:  return getBoolConstant(R==APFloat::cmpUnordered, dl, VT,
2416                                              OpVT);
2417     case ISD::SETUEQ: return getBoolConstant(R==APFloat::cmpUnordered ||
2418                                              R==APFloat::cmpEqual, dl, VT,
2419                                              OpVT);
2420     case ISD::SETUNE: return getBoolConstant(R!=APFloat::cmpEqual, dl, VT,
2421                                              OpVT);
2422     case ISD::SETULT: return getBoolConstant(R==APFloat::cmpUnordered ||
2423                                              R==APFloat::cmpLessThan, dl, VT,
2424                                              OpVT);
2425     case ISD::SETUGT: return getBoolConstant(R==APFloat::cmpGreaterThan ||
2426                                              R==APFloat::cmpUnordered, dl, VT,
2427                                              OpVT);
2428     case ISD::SETULE: return getBoolConstant(R!=APFloat::cmpGreaterThan, dl,
2429                                              VT, OpVT);
2430     case ISD::SETUGE: return getBoolConstant(R!=APFloat::cmpLessThan, dl, VT,
2431                                              OpVT);
2432     }
2433   } else if (N1CFP && OpVT.isSimple() && !N2.isUndef()) {
2434     // Ensure that the constant occurs on the RHS.
2435     ISD::CondCode SwappedCond = ISD::getSetCCSwappedOperands(Cond);
2436     if (!TLI->isCondCodeLegal(SwappedCond, OpVT.getSimpleVT()))
2437       return SDValue();
2438     return getSetCC(dl, VT, N2, N1, SwappedCond);
2439   } else if ((N2CFP && N2CFP->getValueAPF().isNaN()) ||
2440              (OpVT.isFloatingPoint() && (N1.isUndef() || N2.isUndef()))) {
2441     // If an operand is known to be a nan (or undef that could be a nan), we can
2442     // fold it.
2443     // Choosing NaN for the undef will always make unordered comparison succeed
2444     // and ordered comparison fails.
2445     // Matches behavior in llvm::ConstantFoldCompareInstruction.
2446     switch (ISD::getUnorderedFlavor(Cond)) {
2447     default:
2448       llvm_unreachable("Unknown flavor!");
2449     case 0: // Known false.
2450       return getBoolConstant(false, dl, VT, OpVT);
2451     case 1: // Known true.
2452       return getBoolConstant(true, dl, VT, OpVT);
2453     case 2: // Undefined.
2454       return getUNDEF(VT);
2455     }
2456   }
2457 
2458   // Could not fold it.
2459   return SDValue();
2460 }
2461 
2462 /// See if the specified operand can be simplified with the knowledge that only
2463 /// the bits specified by DemandedBits are used.
2464 /// TODO: really we should be making this into the DAG equivalent of
2465 /// SimplifyMultipleUseDemandedBits and not generate any new nodes.
2466 SDValue SelectionDAG::GetDemandedBits(SDValue V, const APInt &DemandedBits) {
2467   EVT VT = V.getValueType();
2468 
2469   if (VT.isScalableVector())
2470     return SDValue();
2471 
2472   APInt DemandedElts = VT.isVector()
2473                            ? APInt::getAllOnes(VT.getVectorNumElements())
2474                            : APInt(1, 1);
2475   return GetDemandedBits(V, DemandedBits, DemandedElts);
2476 }
2477 
2478 /// See if the specified operand can be simplified with the knowledge that only
2479 /// the bits specified by DemandedBits are used in the elements specified by
2480 /// DemandedElts.
2481 /// TODO: really we should be making this into the DAG equivalent of
2482 /// SimplifyMultipleUseDemandedBits and not generate any new nodes.
2483 SDValue SelectionDAG::GetDemandedBits(SDValue V, const APInt &DemandedBits,
2484                                       const APInt &DemandedElts) {
2485   switch (V.getOpcode()) {
2486   default:
2487     return TLI->SimplifyMultipleUseDemandedBits(V, DemandedBits, DemandedElts,
2488                                                 *this);
2489   case ISD::Constant: {
2490     const APInt &CVal = cast<ConstantSDNode>(V)->getAPIntValue();
2491     APInt NewVal = CVal & DemandedBits;
2492     if (NewVal != CVal)
2493       return getConstant(NewVal, SDLoc(V), V.getValueType());
2494     break;
2495   }
2496   case ISD::SRL:
2497     // Only look at single-use SRLs.
2498     if (!V.getNode()->hasOneUse())
2499       break;
2500     if (auto *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
2501       // See if we can recursively simplify the LHS.
2502       unsigned Amt = RHSC->getZExtValue();
2503 
2504       // Watch out for shift count overflow though.
2505       if (Amt >= DemandedBits.getBitWidth())
2506         break;
2507       APInt SrcDemandedBits = DemandedBits << Amt;
2508       if (SDValue SimplifyLHS =
2509               GetDemandedBits(V.getOperand(0), SrcDemandedBits))
2510         return getNode(ISD::SRL, SDLoc(V), V.getValueType(), SimplifyLHS,
2511                        V.getOperand(1));
2512     }
2513     break;
2514   }
2515   return SDValue();
2516 }
2517 
2518 /// SignBitIsZero - Return true if the sign bit of Op is known to be zero.  We
2519 /// use this predicate to simplify operations downstream.
2520 bool SelectionDAG::SignBitIsZero(SDValue Op, unsigned Depth) const {
2521   unsigned BitWidth = Op.getScalarValueSizeInBits();
2522   return MaskedValueIsZero(Op, APInt::getSignMask(BitWidth), Depth);
2523 }
2524 
2525 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero.  We use
2526 /// this predicate to simplify operations downstream.  Mask is known to be zero
2527 /// for bits that V cannot have.
2528 bool SelectionDAG::MaskedValueIsZero(SDValue V, const APInt &Mask,
2529                                      unsigned Depth) const {
2530   return Mask.isSubsetOf(computeKnownBits(V, Depth).Zero);
2531 }
2532 
2533 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero in
2534 /// DemandedElts.  We use this predicate to simplify operations downstream.
2535 /// Mask is known to be zero for bits that V cannot have.
2536 bool SelectionDAG::MaskedValueIsZero(SDValue V, const APInt &Mask,
2537                                      const APInt &DemandedElts,
2538                                      unsigned Depth) const {
2539   return Mask.isSubsetOf(computeKnownBits(V, DemandedElts, Depth).Zero);
2540 }
2541 
2542 /// MaskedValueIsAllOnes - Return true if '(Op & Mask) == Mask'.
2543 bool SelectionDAG::MaskedValueIsAllOnes(SDValue V, const APInt &Mask,
2544                                         unsigned Depth) const {
2545   return Mask.isSubsetOf(computeKnownBits(V, Depth).One);
2546 }
2547 
2548 /// isSplatValue - Return true if the vector V has the same value
2549 /// across all DemandedElts. For scalable vectors it does not make
2550 /// sense to specify which elements are demanded or undefined, therefore
2551 /// they are simply ignored.
2552 bool SelectionDAG::isSplatValue(SDValue V, const APInt &DemandedElts,
2553                                 APInt &UndefElts, unsigned Depth) const {
2554   unsigned Opcode = V.getOpcode();
2555   EVT VT = V.getValueType();
2556   assert(VT.isVector() && "Vector type expected");
2557 
2558   if (!VT.isScalableVector() && !DemandedElts)
2559     return false; // No demanded elts, better to assume we don't know anything.
2560 
2561   if (Depth >= MaxRecursionDepth)
2562     return false; // Limit search depth.
2563 
2564   // Deal with some common cases here that work for both fixed and scalable
2565   // vector types.
2566   switch (Opcode) {
2567   case ISD::SPLAT_VECTOR:
2568     UndefElts = V.getOperand(0).isUndef()
2569                     ? APInt::getAllOnes(DemandedElts.getBitWidth())
2570                     : APInt(DemandedElts.getBitWidth(), 0);
2571     return true;
2572   case ISD::ADD:
2573   case ISD::SUB:
2574   case ISD::AND:
2575   case ISD::XOR:
2576   case ISD::OR: {
2577     APInt UndefLHS, UndefRHS;
2578     SDValue LHS = V.getOperand(0);
2579     SDValue RHS = V.getOperand(1);
2580     if (isSplatValue(LHS, DemandedElts, UndefLHS, Depth + 1) &&
2581         isSplatValue(RHS, DemandedElts, UndefRHS, Depth + 1)) {
2582       UndefElts = UndefLHS | UndefRHS;
2583       return true;
2584     }
2585     return false;
2586   }
2587   case ISD::ABS:
2588   case ISD::TRUNCATE:
2589   case ISD::SIGN_EXTEND:
2590   case ISD::ZERO_EXTEND:
2591     return isSplatValue(V.getOperand(0), DemandedElts, UndefElts, Depth + 1);
2592   default:
2593     if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::INTRINSIC_WO_CHAIN ||
2594         Opcode == ISD::INTRINSIC_W_CHAIN || Opcode == ISD::INTRINSIC_VOID)
2595       return TLI->isSplatValueForTargetNode(V, DemandedElts, UndefElts, Depth);
2596     break;
2597 }
2598 
2599   // We don't support other cases than those above for scalable vectors at
2600   // the moment.
2601   if (VT.isScalableVector())
2602     return false;
2603 
2604   unsigned NumElts = VT.getVectorNumElements();
2605   assert(NumElts == DemandedElts.getBitWidth() && "Vector size mismatch");
2606   UndefElts = APInt::getZero(NumElts);
2607 
2608   switch (Opcode) {
2609   case ISD::BUILD_VECTOR: {
2610     SDValue Scl;
2611     for (unsigned i = 0; i != NumElts; ++i) {
2612       SDValue Op = V.getOperand(i);
2613       if (Op.isUndef()) {
2614         UndefElts.setBit(i);
2615         continue;
2616       }
2617       if (!DemandedElts[i])
2618         continue;
2619       if (Scl && Scl != Op)
2620         return false;
2621       Scl = Op;
2622     }
2623     return true;
2624   }
2625   case ISD::VECTOR_SHUFFLE: {
2626     // Check if this is a shuffle node doing a splat or a shuffle of a splat.
2627     APInt DemandedLHS = APInt::getNullValue(NumElts);
2628     APInt DemandedRHS = APInt::getNullValue(NumElts);
2629     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(V)->getMask();
2630     for (int i = 0; i != (int)NumElts; ++i) {
2631       int M = Mask[i];
2632       if (M < 0) {
2633         UndefElts.setBit(i);
2634         continue;
2635       }
2636       if (!DemandedElts[i])
2637         continue;
2638       if (M < (int)NumElts)
2639         DemandedLHS.setBit(M);
2640       else
2641         DemandedRHS.setBit(M - NumElts);
2642     }
2643 
2644     // If we aren't demanding either op, assume there's no splat.
2645     // If we are demanding both ops, assume there's no splat.
2646     if ((DemandedLHS.isZero() && DemandedRHS.isZero()) ||
2647         (!DemandedLHS.isZero() && !DemandedRHS.isZero()))
2648       return false;
2649 
2650     // See if the demanded elts of the source op is a splat or we only demand
2651     // one element, which should always be a splat.
2652     // TODO: Handle source ops splats with undefs.
2653     auto CheckSplatSrc = [&](SDValue Src, const APInt &SrcElts) {
2654       APInt SrcUndefs;
2655       return (SrcElts.countPopulation() == 1) ||
2656              (isSplatValue(Src, SrcElts, SrcUndefs, Depth + 1) &&
2657               (SrcElts & SrcUndefs).isZero());
2658     };
2659     if (!DemandedLHS.isZero())
2660       return CheckSplatSrc(V.getOperand(0), DemandedLHS);
2661     return CheckSplatSrc(V.getOperand(1), DemandedRHS);
2662   }
2663   case ISD::EXTRACT_SUBVECTOR: {
2664     // Offset the demanded elts by the subvector index.
2665     SDValue Src = V.getOperand(0);
2666     // We don't support scalable vectors at the moment.
2667     if (Src.getValueType().isScalableVector())
2668       return false;
2669     uint64_t Idx = V.getConstantOperandVal(1);
2670     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
2671     APInt UndefSrcElts;
2672     APInt DemandedSrcElts = DemandedElts.zextOrSelf(NumSrcElts).shl(Idx);
2673     if (isSplatValue(Src, DemandedSrcElts, UndefSrcElts, Depth + 1)) {
2674       UndefElts = UndefSrcElts.extractBits(NumElts, Idx);
2675       return true;
2676     }
2677     break;
2678   }
2679   case ISD::ANY_EXTEND_VECTOR_INREG:
2680   case ISD::SIGN_EXTEND_VECTOR_INREG:
2681   case ISD::ZERO_EXTEND_VECTOR_INREG: {
2682     // Widen the demanded elts by the src element count.
2683     SDValue Src = V.getOperand(0);
2684     // We don't support scalable vectors at the moment.
2685     if (Src.getValueType().isScalableVector())
2686       return false;
2687     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
2688     APInt UndefSrcElts;
2689     APInt DemandedSrcElts = DemandedElts.zextOrSelf(NumSrcElts);
2690     if (isSplatValue(Src, DemandedSrcElts, UndefSrcElts, Depth + 1)) {
2691       UndefElts = UndefSrcElts.truncOrSelf(NumElts);
2692       return true;
2693     }
2694     break;
2695   }
2696   case ISD::BITCAST: {
2697     SDValue Src = V.getOperand(0);
2698     EVT SrcVT = Src.getValueType();
2699     unsigned SrcBitWidth = SrcVT.getScalarSizeInBits();
2700     unsigned BitWidth = VT.getScalarSizeInBits();
2701 
2702     // Ignore bitcasts from unsupported types.
2703     // TODO: Add fp support?
2704     if (!SrcVT.isVector() || !SrcVT.isInteger() || !VT.isInteger())
2705       break;
2706 
2707     // Bitcast 'small element' vector to 'large element' vector.
2708     if ((BitWidth % SrcBitWidth) == 0) {
2709       // See if each sub element is a splat.
2710       unsigned Scale = BitWidth / SrcBitWidth;
2711       unsigned NumSrcElts = SrcVT.getVectorNumElements();
2712       APInt ScaledDemandedElts =
2713           APIntOps::ScaleBitMask(DemandedElts, NumSrcElts);
2714       for (unsigned I = 0; I != Scale; ++I) {
2715         APInt SubUndefElts;
2716         APInt SubDemandedElt = APInt::getOneBitSet(Scale, I);
2717         APInt SubDemandedElts = APInt::getSplat(NumSrcElts, SubDemandedElt);
2718         SubDemandedElts &= ScaledDemandedElts;
2719         if (!isSplatValue(Src, SubDemandedElts, SubUndefElts, Depth + 1))
2720           return false;
2721         // TODO: Add support for merging sub undef elements.
2722         if (SubDemandedElts.isSubsetOf(SubUndefElts))
2723           return false;
2724       }
2725       return true;
2726     }
2727     break;
2728   }
2729   }
2730 
2731   return false;
2732 }
2733 
2734 /// Helper wrapper to main isSplatValue function.
2735 bool SelectionDAG::isSplatValue(SDValue V, bool AllowUndefs) const {
2736   EVT VT = V.getValueType();
2737   assert(VT.isVector() && "Vector type expected");
2738 
2739   APInt UndefElts;
2740   APInt DemandedElts;
2741 
2742   // For now we don't support this with scalable vectors.
2743   if (!VT.isScalableVector())
2744     DemandedElts = APInt::getAllOnes(VT.getVectorNumElements());
2745   return isSplatValue(V, DemandedElts, UndefElts) &&
2746          (AllowUndefs || !UndefElts);
2747 }
2748 
2749 SDValue SelectionDAG::getSplatSourceVector(SDValue V, int &SplatIdx) {
2750   V = peekThroughExtractSubvectors(V);
2751 
2752   EVT VT = V.getValueType();
2753   unsigned Opcode = V.getOpcode();
2754   switch (Opcode) {
2755   default: {
2756     APInt UndefElts;
2757     APInt DemandedElts;
2758 
2759     if (!VT.isScalableVector())
2760       DemandedElts = APInt::getAllOnes(VT.getVectorNumElements());
2761 
2762     if (isSplatValue(V, DemandedElts, UndefElts)) {
2763       if (VT.isScalableVector()) {
2764         // DemandedElts and UndefElts are ignored for scalable vectors, since
2765         // the only supported cases are SPLAT_VECTOR nodes.
2766         SplatIdx = 0;
2767       } else {
2768         // Handle case where all demanded elements are UNDEF.
2769         if (DemandedElts.isSubsetOf(UndefElts)) {
2770           SplatIdx = 0;
2771           return getUNDEF(VT);
2772         }
2773         SplatIdx = (UndefElts & DemandedElts).countTrailingOnes();
2774       }
2775       return V;
2776     }
2777     break;
2778   }
2779   case ISD::SPLAT_VECTOR:
2780     SplatIdx = 0;
2781     return V;
2782   case ISD::VECTOR_SHUFFLE: {
2783     if (VT.isScalableVector())
2784       return SDValue();
2785 
2786     // Check if this is a shuffle node doing a splat.
2787     // TODO - remove this and rely purely on SelectionDAG::isSplatValue,
2788     // getTargetVShiftNode currently struggles without the splat source.
2789     auto *SVN = cast<ShuffleVectorSDNode>(V);
2790     if (!SVN->isSplat())
2791       break;
2792     int Idx = SVN->getSplatIndex();
2793     int NumElts = V.getValueType().getVectorNumElements();
2794     SplatIdx = Idx % NumElts;
2795     return V.getOperand(Idx / NumElts);
2796   }
2797   }
2798 
2799   return SDValue();
2800 }
2801 
2802 SDValue SelectionDAG::getSplatValue(SDValue V, bool LegalTypes) {
2803   int SplatIdx;
2804   if (SDValue SrcVector = getSplatSourceVector(V, SplatIdx)) {
2805     EVT SVT = SrcVector.getValueType().getScalarType();
2806     EVT LegalSVT = SVT;
2807     if (LegalTypes && !TLI->isTypeLegal(SVT)) {
2808       if (!SVT.isInteger())
2809         return SDValue();
2810       LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT);
2811       if (LegalSVT.bitsLT(SVT))
2812         return SDValue();
2813     }
2814     return getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(V), LegalSVT, SrcVector,
2815                    getVectorIdxConstant(SplatIdx, SDLoc(V)));
2816   }
2817   return SDValue();
2818 }
2819 
2820 const APInt *
2821 SelectionDAG::getValidShiftAmountConstant(SDValue V,
2822                                           const APInt &DemandedElts) const {
2823   assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL ||
2824           V.getOpcode() == ISD::SRA) &&
2825          "Unknown shift node");
2826   unsigned BitWidth = V.getScalarValueSizeInBits();
2827   if (ConstantSDNode *SA = isConstOrConstSplat(V.getOperand(1), DemandedElts)) {
2828     // Shifting more than the bitwidth is not valid.
2829     const APInt &ShAmt = SA->getAPIntValue();
2830     if (ShAmt.ult(BitWidth))
2831       return &ShAmt;
2832   }
2833   return nullptr;
2834 }
2835 
2836 const APInt *SelectionDAG::getValidMinimumShiftAmountConstant(
2837     SDValue V, const APInt &DemandedElts) const {
2838   assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL ||
2839           V.getOpcode() == ISD::SRA) &&
2840          "Unknown shift node");
2841   if (const APInt *ValidAmt = getValidShiftAmountConstant(V, DemandedElts))
2842     return ValidAmt;
2843   unsigned BitWidth = V.getScalarValueSizeInBits();
2844   auto *BV = dyn_cast<BuildVectorSDNode>(V.getOperand(1));
2845   if (!BV)
2846     return nullptr;
2847   const APInt *MinShAmt = nullptr;
2848   for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
2849     if (!DemandedElts[i])
2850       continue;
2851     auto *SA = dyn_cast<ConstantSDNode>(BV->getOperand(i));
2852     if (!SA)
2853       return nullptr;
2854     // Shifting more than the bitwidth is not valid.
2855     const APInt &ShAmt = SA->getAPIntValue();
2856     if (ShAmt.uge(BitWidth))
2857       return nullptr;
2858     if (MinShAmt && MinShAmt->ule(ShAmt))
2859       continue;
2860     MinShAmt = &ShAmt;
2861   }
2862   return MinShAmt;
2863 }
2864 
2865 const APInt *SelectionDAG::getValidMaximumShiftAmountConstant(
2866     SDValue V, const APInt &DemandedElts) const {
2867   assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL ||
2868           V.getOpcode() == ISD::SRA) &&
2869          "Unknown shift node");
2870   if (const APInt *ValidAmt = getValidShiftAmountConstant(V, DemandedElts))
2871     return ValidAmt;
2872   unsigned BitWidth = V.getScalarValueSizeInBits();
2873   auto *BV = dyn_cast<BuildVectorSDNode>(V.getOperand(1));
2874   if (!BV)
2875     return nullptr;
2876   const APInt *MaxShAmt = nullptr;
2877   for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
2878     if (!DemandedElts[i])
2879       continue;
2880     auto *SA = dyn_cast<ConstantSDNode>(BV->getOperand(i));
2881     if (!SA)
2882       return nullptr;
2883     // Shifting more than the bitwidth is not valid.
2884     const APInt &ShAmt = SA->getAPIntValue();
2885     if (ShAmt.uge(BitWidth))
2886       return nullptr;
2887     if (MaxShAmt && MaxShAmt->uge(ShAmt))
2888       continue;
2889     MaxShAmt = &ShAmt;
2890   }
2891   return MaxShAmt;
2892 }
2893 
2894 /// Determine which bits of Op are known to be either zero or one and return
2895 /// them in Known. For vectors, the known bits are those that are shared by
2896 /// every vector element.
2897 KnownBits SelectionDAG::computeKnownBits(SDValue Op, unsigned Depth) const {
2898   EVT VT = Op.getValueType();
2899 
2900   // TOOD: Until we have a plan for how to represent demanded elements for
2901   // scalable vectors, we can just bail out for now.
2902   if (Op.getValueType().isScalableVector()) {
2903     unsigned BitWidth = Op.getScalarValueSizeInBits();
2904     return KnownBits(BitWidth);
2905   }
2906 
2907   APInt DemandedElts = VT.isVector()
2908                            ? APInt::getAllOnes(VT.getVectorNumElements())
2909                            : APInt(1, 1);
2910   return computeKnownBits(Op, DemandedElts, Depth);
2911 }
2912 
2913 /// Determine which bits of Op are known to be either zero or one and return
2914 /// them in Known. The DemandedElts argument allows us to only collect the known
2915 /// bits that are shared by the requested vector elements.
2916 KnownBits SelectionDAG::computeKnownBits(SDValue Op, const APInt &DemandedElts,
2917                                          unsigned Depth) const {
2918   unsigned BitWidth = Op.getScalarValueSizeInBits();
2919 
2920   KnownBits Known(BitWidth);   // Don't know anything.
2921 
2922   // TOOD: Until we have a plan for how to represent demanded elements for
2923   // scalable vectors, we can just bail out for now.
2924   if (Op.getValueType().isScalableVector())
2925     return Known;
2926 
2927   if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
2928     // We know all of the bits for a constant!
2929     return KnownBits::makeConstant(C->getAPIntValue());
2930   }
2931   if (auto *C = dyn_cast<ConstantFPSDNode>(Op)) {
2932     // We know all of the bits for a constant fp!
2933     return KnownBits::makeConstant(C->getValueAPF().bitcastToAPInt());
2934   }
2935 
2936   if (Depth >= MaxRecursionDepth)
2937     return Known;  // Limit search depth.
2938 
2939   KnownBits Known2;
2940   unsigned NumElts = DemandedElts.getBitWidth();
2941   assert((!Op.getValueType().isVector() ||
2942           NumElts == Op.getValueType().getVectorNumElements()) &&
2943          "Unexpected vector size");
2944 
2945   if (!DemandedElts)
2946     return Known;  // No demanded elts, better to assume we don't know anything.
2947 
2948   unsigned Opcode = Op.getOpcode();
2949   switch (Opcode) {
2950   case ISD::BUILD_VECTOR:
2951     // Collect the known bits that are shared by every demanded vector element.
2952     Known.Zero.setAllBits(); Known.One.setAllBits();
2953     for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
2954       if (!DemandedElts[i])
2955         continue;
2956 
2957       SDValue SrcOp = Op.getOperand(i);
2958       Known2 = computeKnownBits(SrcOp, Depth + 1);
2959 
2960       // BUILD_VECTOR can implicitly truncate sources, we must handle this.
2961       if (SrcOp.getValueSizeInBits() != BitWidth) {
2962         assert(SrcOp.getValueSizeInBits() > BitWidth &&
2963                "Expected BUILD_VECTOR implicit truncation");
2964         Known2 = Known2.trunc(BitWidth);
2965       }
2966 
2967       // Known bits are the values that are shared by every demanded element.
2968       Known = KnownBits::commonBits(Known, Known2);
2969 
2970       // If we don't know any bits, early out.
2971       if (Known.isUnknown())
2972         break;
2973     }
2974     break;
2975   case ISD::VECTOR_SHUFFLE: {
2976     // Collect the known bits that are shared by every vector element referenced
2977     // by the shuffle.
2978     APInt DemandedLHS(NumElts, 0), DemandedRHS(NumElts, 0);
2979     Known.Zero.setAllBits(); Known.One.setAllBits();
2980     const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op);
2981     assert(NumElts == SVN->getMask().size() && "Unexpected vector size");
2982     for (unsigned i = 0; i != NumElts; ++i) {
2983       if (!DemandedElts[i])
2984         continue;
2985 
2986       int M = SVN->getMaskElt(i);
2987       if (M < 0) {
2988         // For UNDEF elements, we don't know anything about the common state of
2989         // the shuffle result.
2990         Known.resetAll();
2991         DemandedLHS.clearAllBits();
2992         DemandedRHS.clearAllBits();
2993         break;
2994       }
2995 
2996       if ((unsigned)M < NumElts)
2997         DemandedLHS.setBit((unsigned)M % NumElts);
2998       else
2999         DemandedRHS.setBit((unsigned)M % NumElts);
3000     }
3001     // Known bits are the values that are shared by every demanded element.
3002     if (!!DemandedLHS) {
3003       SDValue LHS = Op.getOperand(0);
3004       Known2 = computeKnownBits(LHS, DemandedLHS, Depth + 1);
3005       Known = KnownBits::commonBits(Known, Known2);
3006     }
3007     // If we don't know any bits, early out.
3008     if (Known.isUnknown())
3009       break;
3010     if (!!DemandedRHS) {
3011       SDValue RHS = Op.getOperand(1);
3012       Known2 = computeKnownBits(RHS, DemandedRHS, Depth + 1);
3013       Known = KnownBits::commonBits(Known, Known2);
3014     }
3015     break;
3016   }
3017   case ISD::CONCAT_VECTORS: {
3018     // Split DemandedElts and test each of the demanded subvectors.
3019     Known.Zero.setAllBits(); Known.One.setAllBits();
3020     EVT SubVectorVT = Op.getOperand(0).getValueType();
3021     unsigned NumSubVectorElts = SubVectorVT.getVectorNumElements();
3022     unsigned NumSubVectors = Op.getNumOperands();
3023     for (unsigned i = 0; i != NumSubVectors; ++i) {
3024       APInt DemandedSub =
3025           DemandedElts.extractBits(NumSubVectorElts, i * NumSubVectorElts);
3026       if (!!DemandedSub) {
3027         SDValue Sub = Op.getOperand(i);
3028         Known2 = computeKnownBits(Sub, DemandedSub, Depth + 1);
3029         Known = KnownBits::commonBits(Known, Known2);
3030       }
3031       // If we don't know any bits, early out.
3032       if (Known.isUnknown())
3033         break;
3034     }
3035     break;
3036   }
3037   case ISD::INSERT_SUBVECTOR: {
3038     // Demand any elements from the subvector and the remainder from the src its
3039     // inserted into.
3040     SDValue Src = Op.getOperand(0);
3041     SDValue Sub = Op.getOperand(1);
3042     uint64_t Idx = Op.getConstantOperandVal(2);
3043     unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
3044     APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
3045     APInt DemandedSrcElts = DemandedElts;
3046     DemandedSrcElts.insertBits(APInt::getZero(NumSubElts), Idx);
3047 
3048     Known.One.setAllBits();
3049     Known.Zero.setAllBits();
3050     if (!!DemandedSubElts) {
3051       Known = computeKnownBits(Sub, DemandedSubElts, Depth + 1);
3052       if (Known.isUnknown())
3053         break; // early-out.
3054     }
3055     if (!!DemandedSrcElts) {
3056       Known2 = computeKnownBits(Src, DemandedSrcElts, Depth + 1);
3057       Known = KnownBits::commonBits(Known, Known2);
3058     }
3059     break;
3060   }
3061   case ISD::EXTRACT_SUBVECTOR: {
3062     // Offset the demanded elts by the subvector index.
3063     SDValue Src = Op.getOperand(0);
3064     // Bail until we can represent demanded elements for scalable vectors.
3065     if (Src.getValueType().isScalableVector())
3066       break;
3067     uint64_t Idx = Op.getConstantOperandVal(1);
3068     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
3069     APInt DemandedSrcElts = DemandedElts.zextOrSelf(NumSrcElts).shl(Idx);
3070     Known = computeKnownBits(Src, DemandedSrcElts, Depth + 1);
3071     break;
3072   }
3073   case ISD::SCALAR_TO_VECTOR: {
3074     // We know about scalar_to_vector as much as we know about it source,
3075     // which becomes the first element of otherwise unknown vector.
3076     if (DemandedElts != 1)
3077       break;
3078 
3079     SDValue N0 = Op.getOperand(0);
3080     Known = computeKnownBits(N0, Depth + 1);
3081     if (N0.getValueSizeInBits() != BitWidth)
3082       Known = Known.trunc(BitWidth);
3083 
3084     break;
3085   }
3086   case ISD::BITCAST: {
3087     SDValue N0 = Op.getOperand(0);
3088     EVT SubVT = N0.getValueType();
3089     unsigned SubBitWidth = SubVT.getScalarSizeInBits();
3090 
3091     // Ignore bitcasts from unsupported types.
3092     if (!(SubVT.isInteger() || SubVT.isFloatingPoint()))
3093       break;
3094 
3095     // Fast handling of 'identity' bitcasts.
3096     if (BitWidth == SubBitWidth) {
3097       Known = computeKnownBits(N0, DemandedElts, Depth + 1);
3098       break;
3099     }
3100 
3101     bool IsLE = getDataLayout().isLittleEndian();
3102 
3103     // Bitcast 'small element' vector to 'large element' scalar/vector.
3104     if ((BitWidth % SubBitWidth) == 0) {
3105       assert(N0.getValueType().isVector() && "Expected bitcast from vector");
3106 
3107       // Collect known bits for the (larger) output by collecting the known
3108       // bits from each set of sub elements and shift these into place.
3109       // We need to separately call computeKnownBits for each set of
3110       // sub elements as the knownbits for each is likely to be different.
3111       unsigned SubScale = BitWidth / SubBitWidth;
3112       APInt SubDemandedElts(NumElts * SubScale, 0);
3113       for (unsigned i = 0; i != NumElts; ++i)
3114         if (DemandedElts[i])
3115           SubDemandedElts.setBit(i * SubScale);
3116 
3117       for (unsigned i = 0; i != SubScale; ++i) {
3118         Known2 = computeKnownBits(N0, SubDemandedElts.shl(i),
3119                          Depth + 1);
3120         unsigned Shifts = IsLE ? i : SubScale - 1 - i;
3121         Known.insertBits(Known2, SubBitWidth * Shifts);
3122       }
3123     }
3124 
3125     // Bitcast 'large element' scalar/vector to 'small element' vector.
3126     if ((SubBitWidth % BitWidth) == 0) {
3127       assert(Op.getValueType().isVector() && "Expected bitcast to vector");
3128 
3129       // Collect known bits for the (smaller) output by collecting the known
3130       // bits from the overlapping larger input elements and extracting the
3131       // sub sections we actually care about.
3132       unsigned SubScale = SubBitWidth / BitWidth;
3133       APInt SubDemandedElts =
3134           APIntOps::ScaleBitMask(DemandedElts, NumElts / SubScale);
3135       Known2 = computeKnownBits(N0, SubDemandedElts, Depth + 1);
3136 
3137       Known.Zero.setAllBits(); Known.One.setAllBits();
3138       for (unsigned i = 0; i != NumElts; ++i)
3139         if (DemandedElts[i]) {
3140           unsigned Shifts = IsLE ? i : NumElts - 1 - i;
3141           unsigned Offset = (Shifts % SubScale) * BitWidth;
3142           Known = KnownBits::commonBits(Known,
3143                                         Known2.extractBits(BitWidth, Offset));
3144           // If we don't know any bits, early out.
3145           if (Known.isUnknown())
3146             break;
3147         }
3148     }
3149     break;
3150   }
3151   case ISD::AND:
3152     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3153     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3154 
3155     Known &= Known2;
3156     break;
3157   case ISD::OR:
3158     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3159     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3160 
3161     Known |= Known2;
3162     break;
3163   case ISD::XOR:
3164     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3165     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3166 
3167     Known ^= Known2;
3168     break;
3169   case ISD::MUL: {
3170     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3171     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3172     bool SelfMultiply = Op.getOperand(0) == Op.getOperand(1);
3173     // TODO: SelfMultiply can be poison, but not undef.
3174     if (SelfMultiply)
3175       SelfMultiply &= isGuaranteedNotToBeUndefOrPoison(
3176           Op.getOperand(0), DemandedElts, false, Depth + 1);
3177     Known = KnownBits::mul(Known, Known2, SelfMultiply);
3178     break;
3179   }
3180   case ISD::MULHU: {
3181     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3182     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3183     Known = KnownBits::mulhu(Known, Known2);
3184     break;
3185   }
3186   case ISD::MULHS: {
3187     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3188     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3189     Known = KnownBits::mulhs(Known, Known2);
3190     break;
3191   }
3192   case ISD::UMUL_LOHI: {
3193     assert((Op.getResNo() == 0 || Op.getResNo() == 1) && "Unknown result");
3194     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3195     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3196     bool SelfMultiply = Op.getOperand(0) == Op.getOperand(1);
3197     if (Op.getResNo() == 0)
3198       Known = KnownBits::mul(Known, Known2, SelfMultiply);
3199     else
3200       Known = KnownBits::mulhu(Known, Known2);
3201     break;
3202   }
3203   case ISD::SMUL_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::mulhs(Known, Known2);
3212     break;
3213   }
3214   case ISD::UDIV: {
3215     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3216     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3217     Known = KnownBits::udiv(Known, Known2);
3218     break;
3219   }
3220   case ISD::AVGCEILU: {
3221     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3222     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3223     Known = Known.zext(BitWidth + 1);
3224     Known2 = Known2.zext(BitWidth + 1);
3225     KnownBits One = KnownBits::makeConstant(APInt(1, 1));
3226     Known = KnownBits::computeForAddCarry(Known, Known2, One);
3227     Known = Known.extractBits(BitWidth, 1);
3228     break;
3229   }
3230   case ISD::SELECT:
3231   case ISD::VSELECT:
3232     Known = computeKnownBits(Op.getOperand(2), DemandedElts, Depth+1);
3233     // If we don't know any bits, early out.
3234     if (Known.isUnknown())
3235       break;
3236     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth+1);
3237 
3238     // Only known if known in both the LHS and RHS.
3239     Known = KnownBits::commonBits(Known, Known2);
3240     break;
3241   case ISD::SELECT_CC:
3242     Known = computeKnownBits(Op.getOperand(3), DemandedElts, Depth+1);
3243     // If we don't know any bits, early out.
3244     if (Known.isUnknown())
3245       break;
3246     Known2 = computeKnownBits(Op.getOperand(2), DemandedElts, Depth+1);
3247 
3248     // Only known if known in both the LHS and RHS.
3249     Known = KnownBits::commonBits(Known, Known2);
3250     break;
3251   case ISD::SMULO:
3252   case ISD::UMULO:
3253     if (Op.getResNo() != 1)
3254       break;
3255     // The boolean result conforms to getBooleanContents.
3256     // If we know the result of a setcc has the top bits zero, use this info.
3257     // We know that we have an integer-based boolean since these operations
3258     // are only available for integer.
3259     if (TLI->getBooleanContents(Op.getValueType().isVector(), false) ==
3260             TargetLowering::ZeroOrOneBooleanContent &&
3261         BitWidth > 1)
3262       Known.Zero.setBitsFrom(1);
3263     break;
3264   case ISD::SETCC:
3265   case ISD::STRICT_FSETCC:
3266   case ISD::STRICT_FSETCCS: {
3267     unsigned OpNo = Op->isStrictFPOpcode() ? 1 : 0;
3268     // If we know the result of a setcc has the top bits zero, use this info.
3269     if (TLI->getBooleanContents(Op.getOperand(OpNo).getValueType()) ==
3270             TargetLowering::ZeroOrOneBooleanContent &&
3271         BitWidth > 1)
3272       Known.Zero.setBitsFrom(1);
3273     break;
3274   }
3275   case ISD::SHL:
3276     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3277     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3278     Known = KnownBits::shl(Known, Known2);
3279 
3280     // Minimum shift low bits are known zero.
3281     if (const APInt *ShMinAmt =
3282             getValidMinimumShiftAmountConstant(Op, DemandedElts))
3283       Known.Zero.setLowBits(ShMinAmt->getZExtValue());
3284     break;
3285   case ISD::SRL:
3286     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3287     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3288     Known = KnownBits::lshr(Known, Known2);
3289 
3290     // Minimum shift high bits are known zero.
3291     if (const APInt *ShMinAmt =
3292             getValidMinimumShiftAmountConstant(Op, DemandedElts))
3293       Known.Zero.setHighBits(ShMinAmt->getZExtValue());
3294     break;
3295   case ISD::SRA:
3296     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3297     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3298     Known = KnownBits::ashr(Known, Known2);
3299     // TODO: Add minimum shift high known sign bits.
3300     break;
3301   case ISD::FSHL:
3302   case ISD::FSHR:
3303     if (ConstantSDNode *C = isConstOrConstSplat(Op.getOperand(2), DemandedElts)) {
3304       unsigned Amt = C->getAPIntValue().urem(BitWidth);
3305 
3306       // For fshl, 0-shift returns the 1st arg.
3307       // For fshr, 0-shift returns the 2nd arg.
3308       if (Amt == 0) {
3309         Known = computeKnownBits(Op.getOperand(Opcode == ISD::FSHL ? 0 : 1),
3310                                  DemandedElts, Depth + 1);
3311         break;
3312       }
3313 
3314       // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW)))
3315       // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW))
3316       Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3317       Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3318       if (Opcode == ISD::FSHL) {
3319         Known.One <<= Amt;
3320         Known.Zero <<= Amt;
3321         Known2.One.lshrInPlace(BitWidth - Amt);
3322         Known2.Zero.lshrInPlace(BitWidth - Amt);
3323       } else {
3324         Known.One <<= BitWidth - Amt;
3325         Known.Zero <<= BitWidth - Amt;
3326         Known2.One.lshrInPlace(Amt);
3327         Known2.Zero.lshrInPlace(Amt);
3328       }
3329       Known.One |= Known2.One;
3330       Known.Zero |= Known2.Zero;
3331     }
3332     break;
3333   case ISD::SIGN_EXTEND_INREG: {
3334     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3335     EVT EVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
3336     Known = Known.sextInReg(EVT.getScalarSizeInBits());
3337     break;
3338   }
3339   case ISD::CTTZ:
3340   case ISD::CTTZ_ZERO_UNDEF: {
3341     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3342     // If we have a known 1, its position is our upper bound.
3343     unsigned PossibleTZ = Known2.countMaxTrailingZeros();
3344     unsigned LowBits = Log2_32(PossibleTZ) + 1;
3345     Known.Zero.setBitsFrom(LowBits);
3346     break;
3347   }
3348   case ISD::CTLZ:
3349   case ISD::CTLZ_ZERO_UNDEF: {
3350     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3351     // If we have a known 1, its position is our upper bound.
3352     unsigned PossibleLZ = Known2.countMaxLeadingZeros();
3353     unsigned LowBits = Log2_32(PossibleLZ) + 1;
3354     Known.Zero.setBitsFrom(LowBits);
3355     break;
3356   }
3357   case ISD::CTPOP: {
3358     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3359     // If we know some of the bits are zero, they can't be one.
3360     unsigned PossibleOnes = Known2.countMaxPopulation();
3361     Known.Zero.setBitsFrom(Log2_32(PossibleOnes) + 1);
3362     break;
3363   }
3364   case ISD::PARITY: {
3365     // Parity returns 0 everywhere but the LSB.
3366     Known.Zero.setBitsFrom(1);
3367     break;
3368   }
3369   case ISD::LOAD: {
3370     LoadSDNode *LD = cast<LoadSDNode>(Op);
3371     const Constant *Cst = TLI->getTargetConstantFromLoad(LD);
3372     if (ISD::isNON_EXTLoad(LD) && Cst) {
3373       // Determine any common known bits from the loaded constant pool value.
3374       Type *CstTy = Cst->getType();
3375       if ((NumElts * BitWidth) == CstTy->getPrimitiveSizeInBits()) {
3376         // If its a vector splat, then we can (quickly) reuse the scalar path.
3377         // NOTE: We assume all elements match and none are UNDEF.
3378         if (CstTy->isVectorTy()) {
3379           if (const Constant *Splat = Cst->getSplatValue()) {
3380             Cst = Splat;
3381             CstTy = Cst->getType();
3382           }
3383         }
3384         // TODO - do we need to handle different bitwidths?
3385         if (CstTy->isVectorTy() && BitWidth == CstTy->getScalarSizeInBits()) {
3386           // Iterate across all vector elements finding common known bits.
3387           Known.One.setAllBits();
3388           Known.Zero.setAllBits();
3389           for (unsigned i = 0; i != NumElts; ++i) {
3390             if (!DemandedElts[i])
3391               continue;
3392             if (Constant *Elt = Cst->getAggregateElement(i)) {
3393               if (auto *CInt = dyn_cast<ConstantInt>(Elt)) {
3394                 const APInt &Value = CInt->getValue();
3395                 Known.One &= Value;
3396                 Known.Zero &= ~Value;
3397                 continue;
3398               }
3399               if (auto *CFP = dyn_cast<ConstantFP>(Elt)) {
3400                 APInt Value = CFP->getValueAPF().bitcastToAPInt();
3401                 Known.One &= Value;
3402                 Known.Zero &= ~Value;
3403                 continue;
3404               }
3405             }
3406             Known.One.clearAllBits();
3407             Known.Zero.clearAllBits();
3408             break;
3409           }
3410         } else if (BitWidth == CstTy->getPrimitiveSizeInBits()) {
3411           if (auto *CInt = dyn_cast<ConstantInt>(Cst)) {
3412             Known = KnownBits::makeConstant(CInt->getValue());
3413           } else if (auto *CFP = dyn_cast<ConstantFP>(Cst)) {
3414             Known =
3415                 KnownBits::makeConstant(CFP->getValueAPF().bitcastToAPInt());
3416           }
3417         }
3418       }
3419     } else if (ISD::isZEXTLoad(Op.getNode()) && Op.getResNo() == 0) {
3420       // If this is a ZEXTLoad and we are looking at the loaded value.
3421       EVT VT = LD->getMemoryVT();
3422       unsigned MemBits = VT.getScalarSizeInBits();
3423       Known.Zero.setBitsFrom(MemBits);
3424     } else if (const MDNode *Ranges = LD->getRanges()) {
3425       if (LD->getExtensionType() == ISD::NON_EXTLOAD)
3426         computeKnownBitsFromRangeMetadata(*Ranges, Known);
3427     }
3428     break;
3429   }
3430   case ISD::ZERO_EXTEND_VECTOR_INREG: {
3431     EVT InVT = Op.getOperand(0).getValueType();
3432     APInt InDemandedElts = DemandedElts.zextOrSelf(InVT.getVectorNumElements());
3433     Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1);
3434     Known = Known.zext(BitWidth);
3435     break;
3436   }
3437   case ISD::ZERO_EXTEND: {
3438     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3439     Known = Known.zext(BitWidth);
3440     break;
3441   }
3442   case ISD::SIGN_EXTEND_VECTOR_INREG: {
3443     EVT InVT = Op.getOperand(0).getValueType();
3444     APInt InDemandedElts = DemandedElts.zextOrSelf(InVT.getVectorNumElements());
3445     Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1);
3446     // If the sign bit is known to be zero or one, then sext will extend
3447     // it to the top bits, else it will just zext.
3448     Known = Known.sext(BitWidth);
3449     break;
3450   }
3451   case ISD::SIGN_EXTEND: {
3452     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3453     // If the sign bit is known to be zero or one, then sext will extend
3454     // it to the top bits, else it will just zext.
3455     Known = Known.sext(BitWidth);
3456     break;
3457   }
3458   case ISD::ANY_EXTEND_VECTOR_INREG: {
3459     EVT InVT = Op.getOperand(0).getValueType();
3460     APInt InDemandedElts = DemandedElts.zextOrSelf(InVT.getVectorNumElements());
3461     Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1);
3462     Known = Known.anyext(BitWidth);
3463     break;
3464   }
3465   case ISD::ANY_EXTEND: {
3466     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3467     Known = Known.anyext(BitWidth);
3468     break;
3469   }
3470   case ISD::TRUNCATE: {
3471     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3472     Known = Known.trunc(BitWidth);
3473     break;
3474   }
3475   case ISD::AssertZext: {
3476     EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
3477     APInt InMask = APInt::getLowBitsSet(BitWidth, VT.getSizeInBits());
3478     Known = computeKnownBits(Op.getOperand(0), Depth+1);
3479     Known.Zero |= (~InMask);
3480     Known.One  &= (~Known.Zero);
3481     break;
3482   }
3483   case ISD::AssertAlign: {
3484     unsigned LogOfAlign = Log2(cast<AssertAlignSDNode>(Op)->getAlign());
3485     assert(LogOfAlign != 0);
3486 
3487     // TODO: Should use maximum with source
3488     // If a node is guaranteed to be aligned, set low zero bits accordingly as
3489     // well as clearing one bits.
3490     Known.Zero.setLowBits(LogOfAlign);
3491     Known.One.clearLowBits(LogOfAlign);
3492     break;
3493   }
3494   case ISD::FGETSIGN:
3495     // All bits are zero except the low bit.
3496     Known.Zero.setBitsFrom(1);
3497     break;
3498   case ISD::USUBO:
3499   case ISD::SSUBO:
3500     if (Op.getResNo() == 1) {
3501       // If we know the result of a setcc has the top bits zero, use this info.
3502       if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) ==
3503               TargetLowering::ZeroOrOneBooleanContent &&
3504           BitWidth > 1)
3505         Known.Zero.setBitsFrom(1);
3506       break;
3507     }
3508     LLVM_FALLTHROUGH;
3509   case ISD::SUB:
3510   case ISD::SUBC: {
3511     assert(Op.getResNo() == 0 &&
3512            "We only compute knownbits for the difference here.");
3513 
3514     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3515     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3516     Known = KnownBits::computeForAddSub(/* Add */ false, /* NSW */ false,
3517                                         Known, Known2);
3518     break;
3519   }
3520   case ISD::UADDO:
3521   case ISD::SADDO:
3522   case ISD::ADDCARRY:
3523     if (Op.getResNo() == 1) {
3524       // If we know the result of a setcc has the top bits zero, use this info.
3525       if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) ==
3526               TargetLowering::ZeroOrOneBooleanContent &&
3527           BitWidth > 1)
3528         Known.Zero.setBitsFrom(1);
3529       break;
3530     }
3531     LLVM_FALLTHROUGH;
3532   case ISD::ADD:
3533   case ISD::ADDC:
3534   case ISD::ADDE: {
3535     assert(Op.getResNo() == 0 && "We only compute knownbits for the sum here.");
3536 
3537     // With ADDE and ADDCARRY, a carry bit may be added in.
3538     KnownBits Carry(1);
3539     if (Opcode == ISD::ADDE)
3540       // Can't track carry from glue, set carry to unknown.
3541       Carry.resetAll();
3542     else if (Opcode == ISD::ADDCARRY)
3543       // TODO: Compute known bits for the carry operand. Not sure if it is worth
3544       // the trouble (how often will we find a known carry bit). And I haven't
3545       // tested this very much yet, but something like this might work:
3546       //   Carry = computeKnownBits(Op.getOperand(2), DemandedElts, Depth + 1);
3547       //   Carry = Carry.zextOrTrunc(1, false);
3548       Carry.resetAll();
3549     else
3550       Carry.setAllZero();
3551 
3552     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3553     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3554     Known = KnownBits::computeForAddCarry(Known, Known2, Carry);
3555     break;
3556   }
3557   case ISD::SREM: {
3558     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3559     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3560     Known = KnownBits::srem(Known, Known2);
3561     break;
3562   }
3563   case ISD::UREM: {
3564     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3565     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3566     Known = KnownBits::urem(Known, Known2);
3567     break;
3568   }
3569   case ISD::EXTRACT_ELEMENT: {
3570     Known = computeKnownBits(Op.getOperand(0), Depth+1);
3571     const unsigned Index = Op.getConstantOperandVal(1);
3572     const unsigned EltBitWidth = Op.getValueSizeInBits();
3573 
3574     // Remove low part of known bits mask
3575     Known.Zero = Known.Zero.getHiBits(Known.getBitWidth() - Index * EltBitWidth);
3576     Known.One = Known.One.getHiBits(Known.getBitWidth() - Index * EltBitWidth);
3577 
3578     // Remove high part of known bit mask
3579     Known = Known.trunc(EltBitWidth);
3580     break;
3581   }
3582   case ISD::EXTRACT_VECTOR_ELT: {
3583     SDValue InVec = Op.getOperand(0);
3584     SDValue EltNo = Op.getOperand(1);
3585     EVT VecVT = InVec.getValueType();
3586     // computeKnownBits not yet implemented for scalable vectors.
3587     if (VecVT.isScalableVector())
3588       break;
3589     const unsigned EltBitWidth = VecVT.getScalarSizeInBits();
3590     const unsigned NumSrcElts = VecVT.getVectorNumElements();
3591 
3592     // If BitWidth > EltBitWidth the value is anyext:ed. So we do not know
3593     // anything about the extended bits.
3594     if (BitWidth > EltBitWidth)
3595       Known = Known.trunc(EltBitWidth);
3596 
3597     // If we know the element index, just demand that vector element, else for
3598     // an unknown element index, ignore DemandedElts and demand them all.
3599     APInt DemandedSrcElts = APInt::getAllOnes(NumSrcElts);
3600     auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
3601     if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts))
3602       DemandedSrcElts =
3603           APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue());
3604 
3605     Known = computeKnownBits(InVec, DemandedSrcElts, Depth + 1);
3606     if (BitWidth > EltBitWidth)
3607       Known = Known.anyext(BitWidth);
3608     break;
3609   }
3610   case ISD::INSERT_VECTOR_ELT: {
3611     // If we know the element index, split the demand between the
3612     // source vector and the inserted element, otherwise assume we need
3613     // the original demanded vector elements and the value.
3614     SDValue InVec = Op.getOperand(0);
3615     SDValue InVal = Op.getOperand(1);
3616     SDValue EltNo = Op.getOperand(2);
3617     bool DemandedVal = true;
3618     APInt DemandedVecElts = DemandedElts;
3619     auto *CEltNo = dyn_cast<ConstantSDNode>(EltNo);
3620     if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) {
3621       unsigned EltIdx = CEltNo->getZExtValue();
3622       DemandedVal = !!DemandedElts[EltIdx];
3623       DemandedVecElts.clearBit(EltIdx);
3624     }
3625     Known.One.setAllBits();
3626     Known.Zero.setAllBits();
3627     if (DemandedVal) {
3628       Known2 = computeKnownBits(InVal, Depth + 1);
3629       Known = KnownBits::commonBits(Known, Known2.zextOrTrunc(BitWidth));
3630     }
3631     if (!!DemandedVecElts) {
3632       Known2 = computeKnownBits(InVec, DemandedVecElts, Depth + 1);
3633       Known = KnownBits::commonBits(Known, Known2);
3634     }
3635     break;
3636   }
3637   case ISD::BITREVERSE: {
3638     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3639     Known = Known2.reverseBits();
3640     break;
3641   }
3642   case ISD::BSWAP: {
3643     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3644     Known = Known2.byteSwap();
3645     break;
3646   }
3647   case ISD::ABS: {
3648     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3649     Known = Known2.abs();
3650     break;
3651   }
3652   case ISD::USUBSAT: {
3653     // The result of usubsat will never be larger than the LHS.
3654     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3655     Known.Zero.setHighBits(Known2.countMinLeadingZeros());
3656     break;
3657   }
3658   case ISD::UMIN: {
3659     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3660     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3661     Known = KnownBits::umin(Known, Known2);
3662     break;
3663   }
3664   case ISD::UMAX: {
3665     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3666     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3667     Known = KnownBits::umax(Known, Known2);
3668     break;
3669   }
3670   case ISD::SMIN:
3671   case ISD::SMAX: {
3672     // If we have a clamp pattern, we know that the number of sign bits will be
3673     // the minimum of the clamp min/max range.
3674     bool IsMax = (Opcode == ISD::SMAX);
3675     ConstantSDNode *CstLow = nullptr, *CstHigh = nullptr;
3676     if ((CstLow = isConstOrConstSplat(Op.getOperand(1), DemandedElts)))
3677       if (Op.getOperand(0).getOpcode() == (IsMax ? ISD::SMIN : ISD::SMAX))
3678         CstHigh =
3679             isConstOrConstSplat(Op.getOperand(0).getOperand(1), DemandedElts);
3680     if (CstLow && CstHigh) {
3681       if (!IsMax)
3682         std::swap(CstLow, CstHigh);
3683 
3684       const APInt &ValueLow = CstLow->getAPIntValue();
3685       const APInt &ValueHigh = CstHigh->getAPIntValue();
3686       if (ValueLow.sle(ValueHigh)) {
3687         unsigned LowSignBits = ValueLow.getNumSignBits();
3688         unsigned HighSignBits = ValueHigh.getNumSignBits();
3689         unsigned MinSignBits = std::min(LowSignBits, HighSignBits);
3690         if (ValueLow.isNegative() && ValueHigh.isNegative()) {
3691           Known.One.setHighBits(MinSignBits);
3692           break;
3693         }
3694         if (ValueLow.isNonNegative() && ValueHigh.isNonNegative()) {
3695           Known.Zero.setHighBits(MinSignBits);
3696           break;
3697         }
3698       }
3699     }
3700 
3701     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3702     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3703     if (IsMax)
3704       Known = KnownBits::smax(Known, Known2);
3705     else
3706       Known = KnownBits::smin(Known, Known2);
3707     break;
3708   }
3709   case ISD::FP_TO_UINT_SAT: {
3710     // FP_TO_UINT_SAT produces an unsigned value that fits in the saturating VT.
3711     EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
3712     Known.Zero |= APInt::getBitsSetFrom(BitWidth, VT.getScalarSizeInBits());
3713     break;
3714   }
3715   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
3716     if (Op.getResNo() == 1) {
3717       // The boolean result conforms to getBooleanContents.
3718       // If we know the result of a setcc has the top bits zero, use this info.
3719       // We know that we have an integer-based boolean since these operations
3720       // are only available for integer.
3721       if (TLI->getBooleanContents(Op.getValueType().isVector(), false) ==
3722               TargetLowering::ZeroOrOneBooleanContent &&
3723           BitWidth > 1)
3724         Known.Zero.setBitsFrom(1);
3725       break;
3726     }
3727     LLVM_FALLTHROUGH;
3728   case ISD::ATOMIC_CMP_SWAP:
3729   case ISD::ATOMIC_SWAP:
3730   case ISD::ATOMIC_LOAD_ADD:
3731   case ISD::ATOMIC_LOAD_SUB:
3732   case ISD::ATOMIC_LOAD_AND:
3733   case ISD::ATOMIC_LOAD_CLR:
3734   case ISD::ATOMIC_LOAD_OR:
3735   case ISD::ATOMIC_LOAD_XOR:
3736   case ISD::ATOMIC_LOAD_NAND:
3737   case ISD::ATOMIC_LOAD_MIN:
3738   case ISD::ATOMIC_LOAD_MAX:
3739   case ISD::ATOMIC_LOAD_UMIN:
3740   case ISD::ATOMIC_LOAD_UMAX:
3741   case ISD::ATOMIC_LOAD: {
3742     unsigned MemBits =
3743         cast<AtomicSDNode>(Op)->getMemoryVT().getScalarSizeInBits();
3744     // If we are looking at the loaded value.
3745     if (Op.getResNo() == 0) {
3746       if (TLI->getExtendForAtomicOps() == ISD::ZERO_EXTEND)
3747         Known.Zero.setBitsFrom(MemBits);
3748     }
3749     break;
3750   }
3751   case ISD::FrameIndex:
3752   case ISD::TargetFrameIndex:
3753     TLI->computeKnownBitsForFrameIndex(cast<FrameIndexSDNode>(Op)->getIndex(),
3754                                        Known, getMachineFunction());
3755     break;
3756 
3757   default:
3758     if (Opcode < ISD::BUILTIN_OP_END)
3759       break;
3760     LLVM_FALLTHROUGH;
3761   case ISD::INTRINSIC_WO_CHAIN:
3762   case ISD::INTRINSIC_W_CHAIN:
3763   case ISD::INTRINSIC_VOID:
3764     // Allow the target to implement this method for its nodes.
3765     TLI->computeKnownBitsForTargetNode(Op, Known, DemandedElts, *this, Depth);
3766     break;
3767   }
3768 
3769   assert(!Known.hasConflict() && "Bits known to be one AND zero?");
3770   return Known;
3771 }
3772 
3773 SelectionDAG::OverflowKind SelectionDAG::computeOverflowKind(SDValue N0,
3774                                                              SDValue N1) const {
3775   // X + 0 never overflow
3776   if (isNullConstant(N1))
3777     return OFK_Never;
3778 
3779   KnownBits N1Known = computeKnownBits(N1);
3780   if (N1Known.Zero.getBoolValue()) {
3781     KnownBits N0Known = computeKnownBits(N0);
3782 
3783     bool overflow;
3784     (void)N0Known.getMaxValue().uadd_ov(N1Known.getMaxValue(), overflow);
3785     if (!overflow)
3786       return OFK_Never;
3787   }
3788 
3789   // mulhi + 1 never overflow
3790   if (N0.getOpcode() == ISD::UMUL_LOHI && N0.getResNo() == 1 &&
3791       (N1Known.getMaxValue() & 0x01) == N1Known.getMaxValue())
3792     return OFK_Never;
3793 
3794   if (N1.getOpcode() == ISD::UMUL_LOHI && N1.getResNo() == 1) {
3795     KnownBits N0Known = computeKnownBits(N0);
3796 
3797     if ((N0Known.getMaxValue() & 0x01) == N0Known.getMaxValue())
3798       return OFK_Never;
3799   }
3800 
3801   return OFK_Sometime;
3802 }
3803 
3804 bool SelectionDAG::isKnownToBeAPowerOfTwo(SDValue Val) const {
3805   EVT OpVT = Val.getValueType();
3806   unsigned BitWidth = OpVT.getScalarSizeInBits();
3807 
3808   // Is the constant a known power of 2?
3809   if (ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Val))
3810     return Const->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2();
3811 
3812   // A left-shift of a constant one will have exactly one bit set because
3813   // shifting the bit off the end is undefined.
3814   if (Val.getOpcode() == ISD::SHL) {
3815     auto *C = isConstOrConstSplat(Val.getOperand(0));
3816     if (C && C->getAPIntValue() == 1)
3817       return true;
3818   }
3819 
3820   // Similarly, a logical right-shift of a constant sign-bit will have exactly
3821   // one bit set.
3822   if (Val.getOpcode() == ISD::SRL) {
3823     auto *C = isConstOrConstSplat(Val.getOperand(0));
3824     if (C && C->getAPIntValue().isSignMask())
3825       return true;
3826   }
3827 
3828   // Are all operands of a build vector constant powers of two?
3829   if (Val.getOpcode() == ISD::BUILD_VECTOR)
3830     if (llvm::all_of(Val->ops(), [BitWidth](SDValue E) {
3831           if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(E))
3832             return C->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2();
3833           return false;
3834         }))
3835       return true;
3836 
3837   // Is the operand of a splat vector a constant power of two?
3838   if (Val.getOpcode() == ISD::SPLAT_VECTOR)
3839     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val->getOperand(0)))
3840       if (C->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2())
3841         return true;
3842 
3843   // More could be done here, though the above checks are enough
3844   // to handle some common cases.
3845 
3846   // Fall back to computeKnownBits to catch other known cases.
3847   KnownBits Known = computeKnownBits(Val);
3848   return (Known.countMaxPopulation() == 1) && (Known.countMinPopulation() == 1);
3849 }
3850 
3851 unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, unsigned Depth) const {
3852   EVT VT = Op.getValueType();
3853 
3854   // TODO: Assume we don't know anything for now.
3855   if (VT.isScalableVector())
3856     return 1;
3857 
3858   APInt DemandedElts = VT.isVector()
3859                            ? APInt::getAllOnes(VT.getVectorNumElements())
3860                            : APInt(1, 1);
3861   return ComputeNumSignBits(Op, DemandedElts, Depth);
3862 }
3863 
3864 unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, const APInt &DemandedElts,
3865                                           unsigned Depth) const {
3866   EVT VT = Op.getValueType();
3867   assert((VT.isInteger() || VT.isFloatingPoint()) && "Invalid VT!");
3868   unsigned VTBits = VT.getScalarSizeInBits();
3869   unsigned NumElts = DemandedElts.getBitWidth();
3870   unsigned Tmp, Tmp2;
3871   unsigned FirstAnswer = 1;
3872 
3873   if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
3874     const APInt &Val = C->getAPIntValue();
3875     return Val.getNumSignBits();
3876   }
3877 
3878   if (Depth >= MaxRecursionDepth)
3879     return 1;  // Limit search depth.
3880 
3881   if (!DemandedElts || VT.isScalableVector())
3882     return 1;  // No demanded elts, better to assume we don't know anything.
3883 
3884   unsigned Opcode = Op.getOpcode();
3885   switch (Opcode) {
3886   default: break;
3887   case ISD::AssertSext:
3888     Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
3889     return VTBits-Tmp+1;
3890   case ISD::AssertZext:
3891     Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
3892     return VTBits-Tmp;
3893 
3894   case ISD::BUILD_VECTOR:
3895     Tmp = VTBits;
3896     for (unsigned i = 0, e = Op.getNumOperands(); (i < e) && (Tmp > 1); ++i) {
3897       if (!DemandedElts[i])
3898         continue;
3899 
3900       SDValue SrcOp = Op.getOperand(i);
3901       Tmp2 = ComputeNumSignBits(SrcOp, Depth + 1);
3902 
3903       // BUILD_VECTOR can implicitly truncate sources, we must handle this.
3904       if (SrcOp.getValueSizeInBits() != VTBits) {
3905         assert(SrcOp.getValueSizeInBits() > VTBits &&
3906                "Expected BUILD_VECTOR implicit truncation");
3907         unsigned ExtraBits = SrcOp.getValueSizeInBits() - VTBits;
3908         Tmp2 = (Tmp2 > ExtraBits ? Tmp2 - ExtraBits : 1);
3909       }
3910       Tmp = std::min(Tmp, Tmp2);
3911     }
3912     return Tmp;
3913 
3914   case ISD::VECTOR_SHUFFLE: {
3915     // Collect the minimum number of sign bits that are shared by every vector
3916     // element referenced by the shuffle.
3917     APInt DemandedLHS(NumElts, 0), DemandedRHS(NumElts, 0);
3918     const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op);
3919     assert(NumElts == SVN->getMask().size() && "Unexpected vector size");
3920     for (unsigned i = 0; i != NumElts; ++i) {
3921       int M = SVN->getMaskElt(i);
3922       if (!DemandedElts[i])
3923         continue;
3924       // For UNDEF elements, we don't know anything about the common state of
3925       // the shuffle result.
3926       if (M < 0)
3927         return 1;
3928       if ((unsigned)M < NumElts)
3929         DemandedLHS.setBit((unsigned)M % NumElts);
3930       else
3931         DemandedRHS.setBit((unsigned)M % NumElts);
3932     }
3933     Tmp = std::numeric_limits<unsigned>::max();
3934     if (!!DemandedLHS)
3935       Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedLHS, Depth + 1);
3936     if (!!DemandedRHS) {
3937       Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedRHS, Depth + 1);
3938       Tmp = std::min(Tmp, Tmp2);
3939     }
3940     // If we don't know anything, early out and try computeKnownBits fall-back.
3941     if (Tmp == 1)
3942       break;
3943     assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
3944     return Tmp;
3945   }
3946 
3947   case ISD::BITCAST: {
3948     SDValue N0 = Op.getOperand(0);
3949     EVT SrcVT = N0.getValueType();
3950     unsigned SrcBits = SrcVT.getScalarSizeInBits();
3951 
3952     // Ignore bitcasts from unsupported types..
3953     if (!(SrcVT.isInteger() || SrcVT.isFloatingPoint()))
3954       break;
3955 
3956     // Fast handling of 'identity' bitcasts.
3957     if (VTBits == SrcBits)
3958       return ComputeNumSignBits(N0, DemandedElts, Depth + 1);
3959 
3960     bool IsLE = getDataLayout().isLittleEndian();
3961 
3962     // Bitcast 'large element' scalar/vector to 'small element' vector.
3963     if ((SrcBits % VTBits) == 0) {
3964       assert(VT.isVector() && "Expected bitcast to vector");
3965 
3966       unsigned Scale = SrcBits / VTBits;
3967       APInt SrcDemandedElts =
3968           APIntOps::ScaleBitMask(DemandedElts, NumElts / Scale);
3969 
3970       // Fast case - sign splat can be simply split across the small elements.
3971       Tmp = ComputeNumSignBits(N0, SrcDemandedElts, Depth + 1);
3972       if (Tmp == SrcBits)
3973         return VTBits;
3974 
3975       // Slow case - determine how far the sign extends into each sub-element.
3976       Tmp2 = VTBits;
3977       for (unsigned i = 0; i != NumElts; ++i)
3978         if (DemandedElts[i]) {
3979           unsigned SubOffset = i % Scale;
3980           SubOffset = (IsLE ? ((Scale - 1) - SubOffset) : SubOffset);
3981           SubOffset = SubOffset * VTBits;
3982           if (Tmp <= SubOffset)
3983             return 1;
3984           Tmp2 = std::min(Tmp2, Tmp - SubOffset);
3985         }
3986       return Tmp2;
3987     }
3988     break;
3989   }
3990 
3991   case ISD::FP_TO_SINT_SAT:
3992     // FP_TO_SINT_SAT produces a signed value that fits in the saturating VT.
3993     Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getScalarSizeInBits();
3994     return VTBits - Tmp + 1;
3995   case ISD::SIGN_EXTEND:
3996     Tmp = VTBits - Op.getOperand(0).getScalarValueSizeInBits();
3997     return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1) + Tmp;
3998   case ISD::SIGN_EXTEND_INREG:
3999     // Max of the input and what this extends.
4000     Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getScalarSizeInBits();
4001     Tmp = VTBits-Tmp+1;
4002     Tmp2 = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1);
4003     return std::max(Tmp, Tmp2);
4004   case ISD::SIGN_EXTEND_VECTOR_INREG: {
4005     SDValue Src = Op.getOperand(0);
4006     EVT SrcVT = Src.getValueType();
4007     APInt DemandedSrcElts = DemandedElts.zextOrSelf(SrcVT.getVectorNumElements());
4008     Tmp = VTBits - SrcVT.getScalarSizeInBits();
4009     return ComputeNumSignBits(Src, DemandedSrcElts, Depth+1) + Tmp;
4010   }
4011   case ISD::SRA:
4012     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
4013     // SRA X, C -> adds C sign bits.
4014     if (const APInt *ShAmt =
4015             getValidMinimumShiftAmountConstant(Op, DemandedElts))
4016       Tmp = std::min<uint64_t>(Tmp + ShAmt->getZExtValue(), VTBits);
4017     return Tmp;
4018   case ISD::SHL:
4019     if (const APInt *ShAmt =
4020             getValidMaximumShiftAmountConstant(Op, DemandedElts)) {
4021       // shl destroys sign bits, ensure it doesn't shift out all sign bits.
4022       Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
4023       if (ShAmt->ult(Tmp))
4024         return Tmp - ShAmt->getZExtValue();
4025     }
4026     break;
4027   case ISD::AND:
4028   case ISD::OR:
4029   case ISD::XOR:    // NOT is handled here.
4030     // Logical binary ops preserve the number of sign bits at the worst.
4031     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1);
4032     if (Tmp != 1) {
4033       Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth+1);
4034       FirstAnswer = std::min(Tmp, Tmp2);
4035       // We computed what we know about the sign bits as our first
4036       // answer. Now proceed to the generic code that uses
4037       // computeKnownBits, and pick whichever answer is better.
4038     }
4039     break;
4040 
4041   case ISD::SELECT:
4042   case ISD::VSELECT:
4043     Tmp = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth+1);
4044     if (Tmp == 1) return 1;  // Early out.
4045     Tmp2 = ComputeNumSignBits(Op.getOperand(2), DemandedElts, Depth+1);
4046     return std::min(Tmp, Tmp2);
4047   case ISD::SELECT_CC:
4048     Tmp = ComputeNumSignBits(Op.getOperand(2), DemandedElts, Depth+1);
4049     if (Tmp == 1) return 1;  // Early out.
4050     Tmp2 = ComputeNumSignBits(Op.getOperand(3), DemandedElts, Depth+1);
4051     return std::min(Tmp, Tmp2);
4052 
4053   case ISD::SMIN:
4054   case ISD::SMAX: {
4055     // If we have a clamp pattern, we know that the number of sign bits will be
4056     // the minimum of the clamp min/max range.
4057     bool IsMax = (Opcode == ISD::SMAX);
4058     ConstantSDNode *CstLow = nullptr, *CstHigh = nullptr;
4059     if ((CstLow = isConstOrConstSplat(Op.getOperand(1), DemandedElts)))
4060       if (Op.getOperand(0).getOpcode() == (IsMax ? ISD::SMIN : ISD::SMAX))
4061         CstHigh =
4062             isConstOrConstSplat(Op.getOperand(0).getOperand(1), DemandedElts);
4063     if (CstLow && CstHigh) {
4064       if (!IsMax)
4065         std::swap(CstLow, CstHigh);
4066       if (CstLow->getAPIntValue().sle(CstHigh->getAPIntValue())) {
4067         Tmp = CstLow->getAPIntValue().getNumSignBits();
4068         Tmp2 = CstHigh->getAPIntValue().getNumSignBits();
4069         return std::min(Tmp, Tmp2);
4070       }
4071     }
4072 
4073     // Fallback - just get the minimum number of sign bits of the operands.
4074     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
4075     if (Tmp == 1)
4076       return 1;  // Early out.
4077     Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
4078     return std::min(Tmp, Tmp2);
4079   }
4080   case ISD::UMIN:
4081   case ISD::UMAX:
4082     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
4083     if (Tmp == 1)
4084       return 1;  // Early out.
4085     Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
4086     return std::min(Tmp, Tmp2);
4087   case ISD::SADDO:
4088   case ISD::UADDO:
4089   case ISD::SSUBO:
4090   case ISD::USUBO:
4091   case ISD::SMULO:
4092   case ISD::UMULO:
4093     if (Op.getResNo() != 1)
4094       break;
4095     // The boolean result conforms to getBooleanContents.  Fall through.
4096     // If setcc returns 0/-1, all bits are sign bits.
4097     // We know that we have an integer-based boolean since these operations
4098     // are only available for integer.
4099     if (TLI->getBooleanContents(VT.isVector(), false) ==
4100         TargetLowering::ZeroOrNegativeOneBooleanContent)
4101       return VTBits;
4102     break;
4103   case ISD::SETCC:
4104   case ISD::STRICT_FSETCC:
4105   case ISD::STRICT_FSETCCS: {
4106     unsigned OpNo = Op->isStrictFPOpcode() ? 1 : 0;
4107     // If setcc returns 0/-1, all bits are sign bits.
4108     if (TLI->getBooleanContents(Op.getOperand(OpNo).getValueType()) ==
4109         TargetLowering::ZeroOrNegativeOneBooleanContent)
4110       return VTBits;
4111     break;
4112   }
4113   case ISD::ROTL:
4114   case ISD::ROTR:
4115     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
4116 
4117     // If we're rotating an 0/-1 value, then it stays an 0/-1 value.
4118     if (Tmp == VTBits)
4119       return VTBits;
4120 
4121     if (ConstantSDNode *C =
4122             isConstOrConstSplat(Op.getOperand(1), DemandedElts)) {
4123       unsigned RotAmt = C->getAPIntValue().urem(VTBits);
4124 
4125       // Handle rotate right by N like a rotate left by 32-N.
4126       if (Opcode == ISD::ROTR)
4127         RotAmt = (VTBits - RotAmt) % VTBits;
4128 
4129       // If we aren't rotating out all of the known-in sign bits, return the
4130       // number that are left.  This handles rotl(sext(x), 1) for example.
4131       if (Tmp > (RotAmt + 1)) return (Tmp - RotAmt);
4132     }
4133     break;
4134   case ISD::ADD:
4135   case ISD::ADDC:
4136     // Add can have at most one carry bit.  Thus we know that the output
4137     // is, at worst, one more bit than the inputs.
4138     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
4139     if (Tmp == 1) return 1; // Early out.
4140 
4141     // Special case decrementing a value (ADD X, -1):
4142     if (ConstantSDNode *CRHS =
4143             isConstOrConstSplat(Op.getOperand(1), DemandedElts))
4144       if (CRHS->isAllOnes()) {
4145         KnownBits Known =
4146             computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4147 
4148         // If the input is known to be 0 or 1, the output is 0/-1, which is all
4149         // sign bits set.
4150         if ((Known.Zero | 1).isAllOnes())
4151           return VTBits;
4152 
4153         // If we are subtracting one from a positive number, there is no carry
4154         // out of the result.
4155         if (Known.isNonNegative())
4156           return Tmp;
4157       }
4158 
4159     Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
4160     if (Tmp2 == 1) return 1; // Early out.
4161     return std::min(Tmp, Tmp2) - 1;
4162   case ISD::SUB:
4163     Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
4164     if (Tmp2 == 1) return 1; // Early out.
4165 
4166     // Handle NEG.
4167     if (ConstantSDNode *CLHS =
4168             isConstOrConstSplat(Op.getOperand(0), DemandedElts))
4169       if (CLHS->isZero()) {
4170         KnownBits Known =
4171             computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4172         // If the input is known to be 0 or 1, the output is 0/-1, which is all
4173         // sign bits set.
4174         if ((Known.Zero | 1).isAllOnes())
4175           return VTBits;
4176 
4177         // If the input is known to be positive (the sign bit is known clear),
4178         // the output of the NEG has the same number of sign bits as the input.
4179         if (Known.isNonNegative())
4180           return Tmp2;
4181 
4182         // Otherwise, we treat this like a SUB.
4183       }
4184 
4185     // Sub can have at most one carry bit.  Thus we know that the output
4186     // is, at worst, one more bit than the inputs.
4187     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
4188     if (Tmp == 1) return 1; // Early out.
4189     return std::min(Tmp, Tmp2) - 1;
4190   case ISD::MUL: {
4191     // The output of the Mul can be at most twice the valid bits in the inputs.
4192     unsigned SignBitsOp0 = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
4193     if (SignBitsOp0 == 1)
4194       break;
4195     unsigned SignBitsOp1 = ComputeNumSignBits(Op.getOperand(1), Depth + 1);
4196     if (SignBitsOp1 == 1)
4197       break;
4198     unsigned OutValidBits =
4199         (VTBits - SignBitsOp0 + 1) + (VTBits - SignBitsOp1 + 1);
4200     return OutValidBits > VTBits ? 1 : VTBits - OutValidBits + 1;
4201   }
4202   case ISD::SREM:
4203     // The sign bit is the LHS's sign bit, except when the result of the
4204     // remainder is zero. The magnitude of the result should be less than or
4205     // equal to the magnitude of the LHS. Therefore, the result should have
4206     // at least as many sign bits as the left hand side.
4207     return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
4208   case ISD::TRUNCATE: {
4209     // Check if the sign bits of source go down as far as the truncated value.
4210     unsigned NumSrcBits = Op.getOperand(0).getScalarValueSizeInBits();
4211     unsigned NumSrcSignBits = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
4212     if (NumSrcSignBits > (NumSrcBits - VTBits))
4213       return NumSrcSignBits - (NumSrcBits - VTBits);
4214     break;
4215   }
4216   case ISD::EXTRACT_ELEMENT: {
4217     const int KnownSign = ComputeNumSignBits(Op.getOperand(0), Depth+1);
4218     const int BitWidth = Op.getValueSizeInBits();
4219     const int Items = Op.getOperand(0).getValueSizeInBits() / BitWidth;
4220 
4221     // Get reverse index (starting from 1), Op1 value indexes elements from
4222     // little end. Sign starts at big end.
4223     const int rIndex = Items - 1 - Op.getConstantOperandVal(1);
4224 
4225     // If the sign portion ends in our element the subtraction gives correct
4226     // result. Otherwise it gives either negative or > bitwidth result
4227     return std::max(std::min(KnownSign - rIndex * BitWidth, BitWidth), 0);
4228   }
4229   case ISD::INSERT_VECTOR_ELT: {
4230     // If we know the element index, split the demand between the
4231     // source vector and the inserted element, otherwise assume we need
4232     // the original demanded vector elements and the value.
4233     SDValue InVec = Op.getOperand(0);
4234     SDValue InVal = Op.getOperand(1);
4235     SDValue EltNo = Op.getOperand(2);
4236     bool DemandedVal = true;
4237     APInt DemandedVecElts = DemandedElts;
4238     auto *CEltNo = dyn_cast<ConstantSDNode>(EltNo);
4239     if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) {
4240       unsigned EltIdx = CEltNo->getZExtValue();
4241       DemandedVal = !!DemandedElts[EltIdx];
4242       DemandedVecElts.clearBit(EltIdx);
4243     }
4244     Tmp = std::numeric_limits<unsigned>::max();
4245     if (DemandedVal) {
4246       // TODO - handle implicit truncation of inserted elements.
4247       if (InVal.getScalarValueSizeInBits() != VTBits)
4248         break;
4249       Tmp2 = ComputeNumSignBits(InVal, Depth + 1);
4250       Tmp = std::min(Tmp, Tmp2);
4251     }
4252     if (!!DemandedVecElts) {
4253       Tmp2 = ComputeNumSignBits(InVec, DemandedVecElts, Depth + 1);
4254       Tmp = std::min(Tmp, Tmp2);
4255     }
4256     assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
4257     return Tmp;
4258   }
4259   case ISD::EXTRACT_VECTOR_ELT: {
4260     SDValue InVec = Op.getOperand(0);
4261     SDValue EltNo = Op.getOperand(1);
4262     EVT VecVT = InVec.getValueType();
4263     // ComputeNumSignBits not yet implemented for scalable vectors.
4264     if (VecVT.isScalableVector())
4265       break;
4266     const unsigned BitWidth = Op.getValueSizeInBits();
4267     const unsigned EltBitWidth = Op.getOperand(0).getScalarValueSizeInBits();
4268     const unsigned NumSrcElts = VecVT.getVectorNumElements();
4269 
4270     // If BitWidth > EltBitWidth the value is anyext:ed, and we do not know
4271     // anything about sign bits. But if the sizes match we can derive knowledge
4272     // about sign bits from the vector operand.
4273     if (BitWidth != EltBitWidth)
4274       break;
4275 
4276     // If we know the element index, just demand that vector element, else for
4277     // an unknown element index, ignore DemandedElts and demand them all.
4278     APInt DemandedSrcElts = APInt::getAllOnes(NumSrcElts);
4279     auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
4280     if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts))
4281       DemandedSrcElts =
4282           APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue());
4283 
4284     return ComputeNumSignBits(InVec, DemandedSrcElts, Depth + 1);
4285   }
4286   case ISD::EXTRACT_SUBVECTOR: {
4287     // Offset the demanded elts by the subvector index.
4288     SDValue Src = Op.getOperand(0);
4289     // Bail until we can represent demanded elements for scalable vectors.
4290     if (Src.getValueType().isScalableVector())
4291       break;
4292     uint64_t Idx = Op.getConstantOperandVal(1);
4293     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
4294     APInt DemandedSrcElts = DemandedElts.zextOrSelf(NumSrcElts).shl(Idx);
4295     return ComputeNumSignBits(Src, DemandedSrcElts, Depth + 1);
4296   }
4297   case ISD::CONCAT_VECTORS: {
4298     // Determine the minimum number of sign bits across all demanded
4299     // elts of the input vectors. Early out if the result is already 1.
4300     Tmp = std::numeric_limits<unsigned>::max();
4301     EVT SubVectorVT = Op.getOperand(0).getValueType();
4302     unsigned NumSubVectorElts = SubVectorVT.getVectorNumElements();
4303     unsigned NumSubVectors = Op.getNumOperands();
4304     for (unsigned i = 0; (i < NumSubVectors) && (Tmp > 1); ++i) {
4305       APInt DemandedSub =
4306           DemandedElts.extractBits(NumSubVectorElts, i * NumSubVectorElts);
4307       if (!DemandedSub)
4308         continue;
4309       Tmp2 = ComputeNumSignBits(Op.getOperand(i), DemandedSub, Depth + 1);
4310       Tmp = std::min(Tmp, Tmp2);
4311     }
4312     assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
4313     return Tmp;
4314   }
4315   case ISD::INSERT_SUBVECTOR: {
4316     // Demand any elements from the subvector and the remainder from the src its
4317     // inserted into.
4318     SDValue Src = Op.getOperand(0);
4319     SDValue Sub = Op.getOperand(1);
4320     uint64_t Idx = Op.getConstantOperandVal(2);
4321     unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
4322     APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
4323     APInt DemandedSrcElts = DemandedElts;
4324     DemandedSrcElts.insertBits(APInt::getZero(NumSubElts), Idx);
4325 
4326     Tmp = std::numeric_limits<unsigned>::max();
4327     if (!!DemandedSubElts) {
4328       Tmp = ComputeNumSignBits(Sub, DemandedSubElts, Depth + 1);
4329       if (Tmp == 1)
4330         return 1; // early-out
4331     }
4332     if (!!DemandedSrcElts) {
4333       Tmp2 = ComputeNumSignBits(Src, DemandedSrcElts, Depth + 1);
4334       Tmp = std::min(Tmp, Tmp2);
4335     }
4336     assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
4337     return Tmp;
4338   }
4339   case ISD::ATOMIC_CMP_SWAP:
4340   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
4341   case ISD::ATOMIC_SWAP:
4342   case ISD::ATOMIC_LOAD_ADD:
4343   case ISD::ATOMIC_LOAD_SUB:
4344   case ISD::ATOMIC_LOAD_AND:
4345   case ISD::ATOMIC_LOAD_CLR:
4346   case ISD::ATOMIC_LOAD_OR:
4347   case ISD::ATOMIC_LOAD_XOR:
4348   case ISD::ATOMIC_LOAD_NAND:
4349   case ISD::ATOMIC_LOAD_MIN:
4350   case ISD::ATOMIC_LOAD_MAX:
4351   case ISD::ATOMIC_LOAD_UMIN:
4352   case ISD::ATOMIC_LOAD_UMAX:
4353   case ISD::ATOMIC_LOAD: {
4354     Tmp = cast<AtomicSDNode>(Op)->getMemoryVT().getScalarSizeInBits();
4355     // If we are looking at the loaded value.
4356     if (Op.getResNo() == 0) {
4357       if (Tmp == VTBits)
4358         return 1; // early-out
4359       if (TLI->getExtendForAtomicOps() == ISD::SIGN_EXTEND)
4360         return VTBits - Tmp + 1;
4361       if (TLI->getExtendForAtomicOps() == ISD::ZERO_EXTEND)
4362         return VTBits - Tmp;
4363     }
4364     break;
4365   }
4366   }
4367 
4368   // If we are looking at the loaded value of the SDNode.
4369   if (Op.getResNo() == 0) {
4370     // Handle LOADX separately here. EXTLOAD case will fallthrough.
4371     if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
4372       unsigned ExtType = LD->getExtensionType();
4373       switch (ExtType) {
4374       default: break;
4375       case ISD::SEXTLOAD: // e.g. i16->i32 = '17' bits known.
4376         Tmp = LD->getMemoryVT().getScalarSizeInBits();
4377         return VTBits - Tmp + 1;
4378       case ISD::ZEXTLOAD: // e.g. i16->i32 = '16' bits known.
4379         Tmp = LD->getMemoryVT().getScalarSizeInBits();
4380         return VTBits - Tmp;
4381       case ISD::NON_EXTLOAD:
4382         if (const Constant *Cst = TLI->getTargetConstantFromLoad(LD)) {
4383           // We only need to handle vectors - computeKnownBits should handle
4384           // scalar cases.
4385           Type *CstTy = Cst->getType();
4386           if (CstTy->isVectorTy() &&
4387               (NumElts * VTBits) == CstTy->getPrimitiveSizeInBits() &&
4388               VTBits == CstTy->getScalarSizeInBits()) {
4389             Tmp = VTBits;
4390             for (unsigned i = 0; i != NumElts; ++i) {
4391               if (!DemandedElts[i])
4392                 continue;
4393               if (Constant *Elt = Cst->getAggregateElement(i)) {
4394                 if (auto *CInt = dyn_cast<ConstantInt>(Elt)) {
4395                   const APInt &Value = CInt->getValue();
4396                   Tmp = std::min(Tmp, Value.getNumSignBits());
4397                   continue;
4398                 }
4399                 if (auto *CFP = dyn_cast<ConstantFP>(Elt)) {
4400                   APInt Value = CFP->getValueAPF().bitcastToAPInt();
4401                   Tmp = std::min(Tmp, Value.getNumSignBits());
4402                   continue;
4403                 }
4404               }
4405               // Unknown type. Conservatively assume no bits match sign bit.
4406               return 1;
4407             }
4408             return Tmp;
4409           }
4410         }
4411         break;
4412       }
4413     }
4414   }
4415 
4416   // Allow the target to implement this method for its nodes.
4417   if (Opcode >= ISD::BUILTIN_OP_END ||
4418       Opcode == ISD::INTRINSIC_WO_CHAIN ||
4419       Opcode == ISD::INTRINSIC_W_CHAIN ||
4420       Opcode == ISD::INTRINSIC_VOID) {
4421     unsigned NumBits =
4422         TLI->ComputeNumSignBitsForTargetNode(Op, DemandedElts, *this, Depth);
4423     if (NumBits > 1)
4424       FirstAnswer = std::max(FirstAnswer, NumBits);
4425   }
4426 
4427   // Finally, if we can prove that the top bits of the result are 0's or 1's,
4428   // use this information.
4429   KnownBits Known = computeKnownBits(Op, DemandedElts, Depth);
4430   return std::max(FirstAnswer, Known.countMinSignBits());
4431 }
4432 
4433 unsigned SelectionDAG::ComputeMaxSignificantBits(SDValue Op,
4434                                                  unsigned Depth) const {
4435   unsigned SignBits = ComputeNumSignBits(Op, Depth);
4436   return Op.getScalarValueSizeInBits() - SignBits + 1;
4437 }
4438 
4439 unsigned SelectionDAG::ComputeMaxSignificantBits(SDValue Op,
4440                                                  const APInt &DemandedElts,
4441                                                  unsigned Depth) const {
4442   unsigned SignBits = ComputeNumSignBits(Op, DemandedElts, Depth);
4443   return Op.getScalarValueSizeInBits() - SignBits + 1;
4444 }
4445 
4446 bool SelectionDAG::isGuaranteedNotToBeUndefOrPoison(SDValue Op, bool PoisonOnly,
4447                                                     unsigned Depth) const {
4448   // Early out for FREEZE.
4449   if (Op.getOpcode() == ISD::FREEZE)
4450     return true;
4451 
4452   // TODO: Assume we don't know anything for now.
4453   EVT VT = Op.getValueType();
4454   if (VT.isScalableVector())
4455     return false;
4456 
4457   APInt DemandedElts = VT.isVector()
4458                            ? APInt::getAllOnes(VT.getVectorNumElements())
4459                            : APInt(1, 1);
4460   return isGuaranteedNotToBeUndefOrPoison(Op, DemandedElts, PoisonOnly, Depth);
4461 }
4462 
4463 bool SelectionDAG::isGuaranteedNotToBeUndefOrPoison(SDValue Op,
4464                                                     const APInt &DemandedElts,
4465                                                     bool PoisonOnly,
4466                                                     unsigned Depth) const {
4467   unsigned Opcode = Op.getOpcode();
4468 
4469   // Early out for FREEZE.
4470   if (Opcode == ISD::FREEZE)
4471     return true;
4472 
4473   if (Depth >= MaxRecursionDepth)
4474     return false; // Limit search depth.
4475 
4476   if (isIntOrFPConstant(Op))
4477     return true;
4478 
4479   switch (Opcode) {
4480   case ISD::UNDEF:
4481     return PoisonOnly;
4482 
4483   case ISD::BUILD_VECTOR:
4484     // NOTE: BUILD_VECTOR has implicit truncation of wider scalar elements -
4485     // this shouldn't affect the result.
4486     for (unsigned i = 0, e = Op.getNumOperands(); i < e; ++i) {
4487       if (!DemandedElts[i])
4488         continue;
4489       if (!isGuaranteedNotToBeUndefOrPoison(Op.getOperand(i), PoisonOnly,
4490                                             Depth + 1))
4491         return false;
4492     }
4493     return true;
4494 
4495   // TODO: Search for noundef attributes from library functions.
4496 
4497   // TODO: Pointers dereferenced by ISD::LOAD/STORE ops are noundef.
4498 
4499   default:
4500     // Allow the target to implement this method for its nodes.
4501     if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::INTRINSIC_WO_CHAIN ||
4502         Opcode == ISD::INTRINSIC_W_CHAIN || Opcode == ISD::INTRINSIC_VOID)
4503       return TLI->isGuaranteedNotToBeUndefOrPoisonForTargetNode(
4504           Op, DemandedElts, *this, PoisonOnly, Depth);
4505     break;
4506   }
4507 
4508   return false;
4509 }
4510 
4511 bool SelectionDAG::isBaseWithConstantOffset(SDValue Op) const {
4512   if ((Op.getOpcode() != ISD::ADD && Op.getOpcode() != ISD::OR) ||
4513       !isa<ConstantSDNode>(Op.getOperand(1)))
4514     return false;
4515 
4516   if (Op.getOpcode() == ISD::OR &&
4517       !MaskedValueIsZero(Op.getOperand(0), Op.getConstantOperandAPInt(1)))
4518     return false;
4519 
4520   return true;
4521 }
4522 
4523 bool SelectionDAG::isKnownNeverNaN(SDValue Op, bool SNaN, unsigned Depth) const {
4524   // If we're told that NaNs won't happen, assume they won't.
4525   if (getTarget().Options.NoNaNsFPMath || Op->getFlags().hasNoNaNs())
4526     return true;
4527 
4528   if (Depth >= MaxRecursionDepth)
4529     return false; // Limit search depth.
4530 
4531   // TODO: Handle vectors.
4532   // If the value is a constant, we can obviously see if it is a NaN or not.
4533   if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) {
4534     return !C->getValueAPF().isNaN() ||
4535            (SNaN && !C->getValueAPF().isSignaling());
4536   }
4537 
4538   unsigned Opcode = Op.getOpcode();
4539   switch (Opcode) {
4540   case ISD::FADD:
4541   case ISD::FSUB:
4542   case ISD::FMUL:
4543   case ISD::FDIV:
4544   case ISD::FREM:
4545   case ISD::FSIN:
4546   case ISD::FCOS: {
4547     if (SNaN)
4548       return true;
4549     // TODO: Need isKnownNeverInfinity
4550     return false;
4551   }
4552   case ISD::FCANONICALIZE:
4553   case ISD::FEXP:
4554   case ISD::FEXP2:
4555   case ISD::FTRUNC:
4556   case ISD::FFLOOR:
4557   case ISD::FCEIL:
4558   case ISD::FROUND:
4559   case ISD::FROUNDEVEN:
4560   case ISD::FRINT:
4561   case ISD::FNEARBYINT: {
4562     if (SNaN)
4563       return true;
4564     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
4565   }
4566   case ISD::FABS:
4567   case ISD::FNEG:
4568   case ISD::FCOPYSIGN: {
4569     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
4570   }
4571   case ISD::SELECT:
4572     return isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1) &&
4573            isKnownNeverNaN(Op.getOperand(2), SNaN, Depth + 1);
4574   case ISD::FP_EXTEND:
4575   case ISD::FP_ROUND: {
4576     if (SNaN)
4577       return true;
4578     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
4579   }
4580   case ISD::SINT_TO_FP:
4581   case ISD::UINT_TO_FP:
4582     return true;
4583   case ISD::FMA:
4584   case ISD::FMAD: {
4585     if (SNaN)
4586       return true;
4587     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) &&
4588            isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1) &&
4589            isKnownNeverNaN(Op.getOperand(2), SNaN, Depth + 1);
4590   }
4591   case ISD::FSQRT: // Need is known positive
4592   case ISD::FLOG:
4593   case ISD::FLOG2:
4594   case ISD::FLOG10:
4595   case ISD::FPOWI:
4596   case ISD::FPOW: {
4597     if (SNaN)
4598       return true;
4599     // TODO: Refine on operand
4600     return false;
4601   }
4602   case ISD::FMINNUM:
4603   case ISD::FMAXNUM: {
4604     // Only one needs to be known not-nan, since it will be returned if the
4605     // other ends up being one.
4606     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) ||
4607            isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1);
4608   }
4609   case ISD::FMINNUM_IEEE:
4610   case ISD::FMAXNUM_IEEE: {
4611     if (SNaN)
4612       return true;
4613     // This can return a NaN if either operand is an sNaN, or if both operands
4614     // are NaN.
4615     return (isKnownNeverNaN(Op.getOperand(0), false, Depth + 1) &&
4616             isKnownNeverSNaN(Op.getOperand(1), Depth + 1)) ||
4617            (isKnownNeverNaN(Op.getOperand(1), false, Depth + 1) &&
4618             isKnownNeverSNaN(Op.getOperand(0), Depth + 1));
4619   }
4620   case ISD::FMINIMUM:
4621   case ISD::FMAXIMUM: {
4622     // TODO: Does this quiet or return the origina NaN as-is?
4623     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) &&
4624            isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1);
4625   }
4626   case ISD::EXTRACT_VECTOR_ELT: {
4627     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
4628   }
4629   default:
4630     if (Opcode >= ISD::BUILTIN_OP_END ||
4631         Opcode == ISD::INTRINSIC_WO_CHAIN ||
4632         Opcode == ISD::INTRINSIC_W_CHAIN ||
4633         Opcode == ISD::INTRINSIC_VOID) {
4634       return TLI->isKnownNeverNaNForTargetNode(Op, *this, SNaN, Depth);
4635     }
4636 
4637     return false;
4638   }
4639 }
4640 
4641 bool SelectionDAG::isKnownNeverZeroFloat(SDValue Op) const {
4642   assert(Op.getValueType().isFloatingPoint() &&
4643          "Floating point type expected");
4644 
4645   // If the value is a constant, we can obviously see if it is a zero or not.
4646   // TODO: Add BuildVector support.
4647   if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op))
4648     return !C->isZero();
4649   return false;
4650 }
4651 
4652 bool SelectionDAG::isKnownNeverZero(SDValue Op) const {
4653   assert(!Op.getValueType().isFloatingPoint() &&
4654          "Floating point types unsupported - use isKnownNeverZeroFloat");
4655 
4656   // If the value is a constant, we can obviously see if it is a zero or not.
4657   if (ISD::matchUnaryPredicate(Op,
4658                                [](ConstantSDNode *C) { return !C->isZero(); }))
4659     return true;
4660 
4661   // TODO: Recognize more cases here.
4662   switch (Op.getOpcode()) {
4663   default: break;
4664   case ISD::OR:
4665     if (isKnownNeverZero(Op.getOperand(1)) ||
4666         isKnownNeverZero(Op.getOperand(0)))
4667       return true;
4668     break;
4669   }
4670 
4671   return false;
4672 }
4673 
4674 bool SelectionDAG::isEqualTo(SDValue A, SDValue B) const {
4675   // Check the obvious case.
4676   if (A == B) return true;
4677 
4678   // For for negative and positive zero.
4679   if (const ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A))
4680     if (const ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B))
4681       if (CA->isZero() && CB->isZero()) return true;
4682 
4683   // Otherwise they may not be equal.
4684   return false;
4685 }
4686 
4687 // Only bits set in Mask must be negated, other bits may be arbitrary.
4688 SDValue llvm::getBitwiseNotOperand(SDValue V, SDValue Mask, bool AllowUndefs) {
4689   if (isBitwiseNot(V, AllowUndefs))
4690     return V.getOperand(0);
4691 
4692   // Handle any_extend (not (truncate X)) pattern, where Mask only sets
4693   // bits in the non-extended part.
4694   ConstantSDNode *MaskC = isConstOrConstSplat(Mask);
4695   if (!MaskC || V.getOpcode() != ISD::ANY_EXTEND)
4696     return SDValue();
4697   SDValue ExtArg = V.getOperand(0);
4698   if (ExtArg.getScalarValueSizeInBits() >=
4699           MaskC->getAPIntValue().getActiveBits() &&
4700       isBitwiseNot(ExtArg, AllowUndefs) &&
4701       ExtArg.getOperand(0).getOpcode() == ISD::TRUNCATE &&
4702       ExtArg.getOperand(0).getOperand(0).getValueType() == V.getValueType())
4703     return ExtArg.getOperand(0).getOperand(0);
4704   return SDValue();
4705 }
4706 
4707 static bool haveNoCommonBitsSetCommutative(SDValue A, SDValue B) {
4708   // Match masked merge pattern (X & ~M) op (Y & M)
4709   // Including degenerate case (X & ~M) op M
4710   auto MatchNoCommonBitsPattern = [&](SDValue Not, SDValue Mask,
4711                                       SDValue Other) {
4712     if (SDValue NotOperand =
4713             getBitwiseNotOperand(Not, Mask, /* AllowUndefs */ true)) {
4714       if (Other == NotOperand)
4715         return true;
4716       if (Other->getOpcode() == ISD::AND)
4717         return NotOperand == Other->getOperand(0) ||
4718                NotOperand == Other->getOperand(1);
4719     }
4720     return false;
4721   };
4722   if (A->getOpcode() == ISD::AND)
4723     return MatchNoCommonBitsPattern(A->getOperand(0), A->getOperand(1), B) ||
4724            MatchNoCommonBitsPattern(A->getOperand(1), A->getOperand(0), B);
4725   return false;
4726 }
4727 
4728 // FIXME: unify with llvm::haveNoCommonBitsSet.
4729 bool SelectionDAG::haveNoCommonBitsSet(SDValue A, SDValue B) const {
4730   assert(A.getValueType() == B.getValueType() &&
4731          "Values must have the same type");
4732   if (haveNoCommonBitsSetCommutative(A, B) ||
4733       haveNoCommonBitsSetCommutative(B, A))
4734     return true;
4735   return KnownBits::haveNoCommonBitsSet(computeKnownBits(A),
4736                                         computeKnownBits(B));
4737 }
4738 
4739 static SDValue FoldSTEP_VECTOR(const SDLoc &DL, EVT VT, SDValue Step,
4740                                SelectionDAG &DAG) {
4741   if (cast<ConstantSDNode>(Step)->isZero())
4742     return DAG.getConstant(0, DL, VT);
4743 
4744   return SDValue();
4745 }
4746 
4747 static SDValue FoldBUILD_VECTOR(const SDLoc &DL, EVT VT,
4748                                 ArrayRef<SDValue> Ops,
4749                                 SelectionDAG &DAG) {
4750   int NumOps = Ops.size();
4751   assert(NumOps != 0 && "Can't build an empty vector!");
4752   assert(!VT.isScalableVector() &&
4753          "BUILD_VECTOR cannot be used with scalable types");
4754   assert(VT.getVectorNumElements() == (unsigned)NumOps &&
4755          "Incorrect element count in BUILD_VECTOR!");
4756 
4757   // BUILD_VECTOR of UNDEFs is UNDEF.
4758   if (llvm::all_of(Ops, [](SDValue Op) { return Op.isUndef(); }))
4759     return DAG.getUNDEF(VT);
4760 
4761   // BUILD_VECTOR of seq extract/insert from the same vector + type is Identity.
4762   SDValue IdentitySrc;
4763   bool IsIdentity = true;
4764   for (int i = 0; i != NumOps; ++i) {
4765     if (Ops[i].getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
4766         Ops[i].getOperand(0).getValueType() != VT ||
4767         (IdentitySrc && Ops[i].getOperand(0) != IdentitySrc) ||
4768         !isa<ConstantSDNode>(Ops[i].getOperand(1)) ||
4769         cast<ConstantSDNode>(Ops[i].getOperand(1))->getAPIntValue() != i) {
4770       IsIdentity = false;
4771       break;
4772     }
4773     IdentitySrc = Ops[i].getOperand(0);
4774   }
4775   if (IsIdentity)
4776     return IdentitySrc;
4777 
4778   return SDValue();
4779 }
4780 
4781 /// Try to simplify vector concatenation to an input value, undef, or build
4782 /// vector.
4783 static SDValue foldCONCAT_VECTORS(const SDLoc &DL, EVT VT,
4784                                   ArrayRef<SDValue> Ops,
4785                                   SelectionDAG &DAG) {
4786   assert(!Ops.empty() && "Can't concatenate an empty list of vectors!");
4787   assert(llvm::all_of(Ops,
4788                       [Ops](SDValue Op) {
4789                         return Ops[0].getValueType() == Op.getValueType();
4790                       }) &&
4791          "Concatenation of vectors with inconsistent value types!");
4792   assert((Ops[0].getValueType().getVectorElementCount() * Ops.size()) ==
4793              VT.getVectorElementCount() &&
4794          "Incorrect element count in vector concatenation!");
4795 
4796   if (Ops.size() == 1)
4797     return Ops[0];
4798 
4799   // Concat of UNDEFs is UNDEF.
4800   if (llvm::all_of(Ops, [](SDValue Op) { return Op.isUndef(); }))
4801     return DAG.getUNDEF(VT);
4802 
4803   // Scan the operands and look for extract operations from a single source
4804   // that correspond to insertion at the same location via this concatenation:
4805   // concat (extract X, 0*subvec_elts), (extract X, 1*subvec_elts), ...
4806   SDValue IdentitySrc;
4807   bool IsIdentity = true;
4808   for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
4809     SDValue Op = Ops[i];
4810     unsigned IdentityIndex = i * Op.getValueType().getVectorMinNumElements();
4811     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
4812         Op.getOperand(0).getValueType() != VT ||
4813         (IdentitySrc && Op.getOperand(0) != IdentitySrc) ||
4814         Op.getConstantOperandVal(1) != IdentityIndex) {
4815       IsIdentity = false;
4816       break;
4817     }
4818     assert((!IdentitySrc || IdentitySrc == Op.getOperand(0)) &&
4819            "Unexpected identity source vector for concat of extracts");
4820     IdentitySrc = Op.getOperand(0);
4821   }
4822   if (IsIdentity) {
4823     assert(IdentitySrc && "Failed to set source vector of extracts");
4824     return IdentitySrc;
4825   }
4826 
4827   // The code below this point is only designed to work for fixed width
4828   // vectors, so we bail out for now.
4829   if (VT.isScalableVector())
4830     return SDValue();
4831 
4832   // A CONCAT_VECTOR with all UNDEF/BUILD_VECTOR operands can be
4833   // simplified to one big BUILD_VECTOR.
4834   // FIXME: Add support for SCALAR_TO_VECTOR as well.
4835   EVT SVT = VT.getScalarType();
4836   SmallVector<SDValue, 16> Elts;
4837   for (SDValue Op : Ops) {
4838     EVT OpVT = Op.getValueType();
4839     if (Op.isUndef())
4840       Elts.append(OpVT.getVectorNumElements(), DAG.getUNDEF(SVT));
4841     else if (Op.getOpcode() == ISD::BUILD_VECTOR)
4842       Elts.append(Op->op_begin(), Op->op_end());
4843     else
4844       return SDValue();
4845   }
4846 
4847   // BUILD_VECTOR requires all inputs to be of the same type, find the
4848   // maximum type and extend them all.
4849   for (SDValue Op : Elts)
4850     SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
4851 
4852   if (SVT.bitsGT(VT.getScalarType())) {
4853     for (SDValue &Op : Elts) {
4854       if (Op.isUndef())
4855         Op = DAG.getUNDEF(SVT);
4856       else
4857         Op = DAG.getTargetLoweringInfo().isZExtFree(Op.getValueType(), SVT)
4858                  ? DAG.getZExtOrTrunc(Op, DL, SVT)
4859                  : DAG.getSExtOrTrunc(Op, DL, SVT);
4860     }
4861   }
4862 
4863   SDValue V = DAG.getBuildVector(VT, DL, Elts);
4864   NewSDValueDbgMsg(V, "New node fold concat vectors: ", &DAG);
4865   return V;
4866 }
4867 
4868 /// Gets or creates the specified node.
4869 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT) {
4870   FoldingSetNodeID ID;
4871   AddNodeIDNode(ID, Opcode, getVTList(VT), None);
4872   void *IP = nullptr;
4873   if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
4874     return SDValue(E, 0);
4875 
4876   auto *N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(),
4877                               getVTList(VT));
4878   CSEMap.InsertNode(N, IP);
4879 
4880   InsertNode(N);
4881   SDValue V = SDValue(N, 0);
4882   NewSDValueDbgMsg(V, "Creating new node: ", this);
4883   return V;
4884 }
4885 
4886 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
4887                               SDValue Operand) {
4888   SDNodeFlags Flags;
4889   if (Inserter)
4890     Flags = Inserter->getFlags();
4891   return getNode(Opcode, DL, VT, Operand, Flags);
4892 }
4893 
4894 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
4895                               SDValue Operand, const SDNodeFlags Flags) {
4896   assert(Operand.getOpcode() != ISD::DELETED_NODE &&
4897          "Operand is DELETED_NODE!");
4898   // Constant fold unary operations with an integer constant operand. Even
4899   // opaque constant will be folded, because the folding of unary operations
4900   // doesn't create new constants with different values. Nevertheless, the
4901   // opaque flag is preserved during folding to prevent future folding with
4902   // other constants.
4903   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Operand)) {
4904     const APInt &Val = C->getAPIntValue();
4905     switch (Opcode) {
4906     default: break;
4907     case ISD::SIGN_EXTEND:
4908       return getConstant(Val.sextOrTrunc(VT.getSizeInBits()), DL, VT,
4909                          C->isTargetOpcode(), C->isOpaque());
4910     case ISD::TRUNCATE:
4911       if (C->isOpaque())
4912         break;
4913       LLVM_FALLTHROUGH;
4914     case ISD::ZERO_EXTEND:
4915       return getConstant(Val.zextOrTrunc(VT.getSizeInBits()), DL, VT,
4916                          C->isTargetOpcode(), C->isOpaque());
4917     case ISD::ANY_EXTEND:
4918       // Some targets like RISCV prefer to sign extend some types.
4919       if (TLI->isSExtCheaperThanZExt(Operand.getValueType(), VT))
4920         return getConstant(Val.sextOrTrunc(VT.getSizeInBits()), DL, VT,
4921                            C->isTargetOpcode(), C->isOpaque());
4922       return getConstant(Val.zextOrTrunc(VT.getSizeInBits()), DL, VT,
4923                          C->isTargetOpcode(), C->isOpaque());
4924     case ISD::UINT_TO_FP:
4925     case ISD::SINT_TO_FP: {
4926       APFloat apf(EVTToAPFloatSemantics(VT),
4927                   APInt::getZero(VT.getSizeInBits()));
4928       (void)apf.convertFromAPInt(Val,
4929                                  Opcode==ISD::SINT_TO_FP,
4930                                  APFloat::rmNearestTiesToEven);
4931       return getConstantFP(apf, DL, VT);
4932     }
4933     case ISD::BITCAST:
4934       if (VT == MVT::f16 && C->getValueType(0) == MVT::i16)
4935         return getConstantFP(APFloat(APFloat::IEEEhalf(), Val), DL, VT);
4936       if (VT == MVT::f32 && C->getValueType(0) == MVT::i32)
4937         return getConstantFP(APFloat(APFloat::IEEEsingle(), Val), DL, VT);
4938       if (VT == MVT::f64 && C->getValueType(0) == MVT::i64)
4939         return getConstantFP(APFloat(APFloat::IEEEdouble(), Val), DL, VT);
4940       if (VT == MVT::f128 && C->getValueType(0) == MVT::i128)
4941         return getConstantFP(APFloat(APFloat::IEEEquad(), Val), DL, VT);
4942       break;
4943     case ISD::ABS:
4944       return getConstant(Val.abs(), DL, VT, C->isTargetOpcode(),
4945                          C->isOpaque());
4946     case ISD::BITREVERSE:
4947       return getConstant(Val.reverseBits(), DL, VT, C->isTargetOpcode(),
4948                          C->isOpaque());
4949     case ISD::BSWAP:
4950       return getConstant(Val.byteSwap(), DL, VT, C->isTargetOpcode(),
4951                          C->isOpaque());
4952     case ISD::CTPOP:
4953       return getConstant(Val.countPopulation(), DL, VT, C->isTargetOpcode(),
4954                          C->isOpaque());
4955     case ISD::CTLZ:
4956     case ISD::CTLZ_ZERO_UNDEF:
4957       return getConstant(Val.countLeadingZeros(), DL, VT, C->isTargetOpcode(),
4958                          C->isOpaque());
4959     case ISD::CTTZ:
4960     case ISD::CTTZ_ZERO_UNDEF:
4961       return getConstant(Val.countTrailingZeros(), DL, VT, C->isTargetOpcode(),
4962                          C->isOpaque());
4963     case ISD::FP16_TO_FP: {
4964       bool Ignored;
4965       APFloat FPV(APFloat::IEEEhalf(),
4966                   (Val.getBitWidth() == 16) ? Val : Val.trunc(16));
4967 
4968       // This can return overflow, underflow, or inexact; we don't care.
4969       // FIXME need to be more flexible about rounding mode.
4970       (void)FPV.convert(EVTToAPFloatSemantics(VT),
4971                         APFloat::rmNearestTiesToEven, &Ignored);
4972       return getConstantFP(FPV, DL, VT);
4973     }
4974     case ISD::STEP_VECTOR: {
4975       if (SDValue V = FoldSTEP_VECTOR(DL, VT, Operand, *this))
4976         return V;
4977       break;
4978     }
4979     }
4980   }
4981 
4982   // Constant fold unary operations with a floating point constant operand.
4983   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Operand)) {
4984     APFloat V = C->getValueAPF();    // make copy
4985     switch (Opcode) {
4986     case ISD::FNEG:
4987       V.changeSign();
4988       return getConstantFP(V, DL, VT);
4989     case ISD::FABS:
4990       V.clearSign();
4991       return getConstantFP(V, DL, VT);
4992     case ISD::FCEIL: {
4993       APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardPositive);
4994       if (fs == APFloat::opOK || fs == APFloat::opInexact)
4995         return getConstantFP(V, DL, VT);
4996       break;
4997     }
4998     case ISD::FTRUNC: {
4999       APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardZero);
5000       if (fs == APFloat::opOK || fs == APFloat::opInexact)
5001         return getConstantFP(V, DL, VT);
5002       break;
5003     }
5004     case ISD::FFLOOR: {
5005       APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardNegative);
5006       if (fs == APFloat::opOK || fs == APFloat::opInexact)
5007         return getConstantFP(V, DL, VT);
5008       break;
5009     }
5010     case ISD::FP_EXTEND: {
5011       bool ignored;
5012       // This can return overflow, underflow, or inexact; we don't care.
5013       // FIXME need to be more flexible about rounding mode.
5014       (void)V.convert(EVTToAPFloatSemantics(VT),
5015                       APFloat::rmNearestTiesToEven, &ignored);
5016       return getConstantFP(V, DL, VT);
5017     }
5018     case ISD::FP_TO_SINT:
5019     case ISD::FP_TO_UINT: {
5020       bool ignored;
5021       APSInt IntVal(VT.getSizeInBits(), Opcode == ISD::FP_TO_UINT);
5022       // FIXME need to be more flexible about rounding mode.
5023       APFloat::opStatus s =
5024           V.convertToInteger(IntVal, APFloat::rmTowardZero, &ignored);
5025       if (s == APFloat::opInvalidOp) // inexact is OK, in fact usual
5026         break;
5027       return getConstant(IntVal, DL, VT);
5028     }
5029     case ISD::BITCAST:
5030       if (VT == MVT::i16 && C->getValueType(0) == MVT::f16)
5031         return getConstant((uint16_t)V.bitcastToAPInt().getZExtValue(), DL, VT);
5032       if (VT == MVT::i16 && C->getValueType(0) == MVT::bf16)
5033         return getConstant((uint16_t)V.bitcastToAPInt().getZExtValue(), DL, VT);
5034       if (VT == MVT::i32 && C->getValueType(0) == MVT::f32)
5035         return getConstant((uint32_t)V.bitcastToAPInt().getZExtValue(), DL, VT);
5036       if (VT == MVT::i64 && C->getValueType(0) == MVT::f64)
5037         return getConstant(V.bitcastToAPInt().getZExtValue(), DL, VT);
5038       break;
5039     case ISD::FP_TO_FP16: {
5040       bool Ignored;
5041       // This can return overflow, underflow, or inexact; we don't care.
5042       // FIXME need to be more flexible about rounding mode.
5043       (void)V.convert(APFloat::IEEEhalf(),
5044                       APFloat::rmNearestTiesToEven, &Ignored);
5045       return getConstant(V.bitcastToAPInt().getZExtValue(), DL, VT);
5046     }
5047     }
5048   }
5049 
5050   // Constant fold unary operations with a vector integer or float operand.
5051   switch (Opcode) {
5052   default:
5053     // FIXME: Entirely reasonable to perform folding of other unary
5054     // operations here as the need arises.
5055     break;
5056   case ISD::FNEG:
5057   case ISD::FABS:
5058   case ISD::FCEIL:
5059   case ISD::FTRUNC:
5060   case ISD::FFLOOR:
5061   case ISD::FP_EXTEND:
5062   case ISD::FP_TO_SINT:
5063   case ISD::FP_TO_UINT:
5064   case ISD::TRUNCATE:
5065   case ISD::ANY_EXTEND:
5066   case ISD::ZERO_EXTEND:
5067   case ISD::SIGN_EXTEND:
5068   case ISD::UINT_TO_FP:
5069   case ISD::SINT_TO_FP:
5070   case ISD::ABS:
5071   case ISD::BITREVERSE:
5072   case ISD::BSWAP:
5073   case ISD::CTLZ:
5074   case ISD::CTLZ_ZERO_UNDEF:
5075   case ISD::CTTZ:
5076   case ISD::CTTZ_ZERO_UNDEF:
5077   case ISD::CTPOP: {
5078     SDValue Ops = {Operand};
5079     if (SDValue Fold = FoldConstantArithmetic(Opcode, DL, VT, Ops))
5080       return Fold;
5081   }
5082   }
5083 
5084   unsigned OpOpcode = Operand.getNode()->getOpcode();
5085   switch (Opcode) {
5086   case ISD::STEP_VECTOR:
5087     assert(VT.isScalableVector() &&
5088            "STEP_VECTOR can only be used with scalable types");
5089     assert(OpOpcode == ISD::TargetConstant &&
5090            VT.getVectorElementType() == Operand.getValueType() &&
5091            "Unexpected step operand");
5092     break;
5093   case ISD::FREEZE:
5094     assert(VT == Operand.getValueType() && "Unexpected VT!");
5095     if (isGuaranteedNotToBeUndefOrPoison(Operand))
5096       return Operand;
5097     break;
5098   case ISD::TokenFactor:
5099   case ISD::MERGE_VALUES:
5100   case ISD::CONCAT_VECTORS:
5101     return Operand;         // Factor, merge or concat of one node?  No need.
5102   case ISD::BUILD_VECTOR: {
5103     // Attempt to simplify BUILD_VECTOR.
5104     SDValue Ops[] = {Operand};
5105     if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
5106       return V;
5107     break;
5108   }
5109   case ISD::FP_ROUND: llvm_unreachable("Invalid method to make FP_ROUND node");
5110   case ISD::FP_EXTEND:
5111     assert(VT.isFloatingPoint() &&
5112            Operand.getValueType().isFloatingPoint() && "Invalid FP cast!");
5113     if (Operand.getValueType() == VT) return Operand;  // noop conversion.
5114     assert((!VT.isVector() ||
5115             VT.getVectorElementCount() ==
5116             Operand.getValueType().getVectorElementCount()) &&
5117            "Vector element count mismatch!");
5118     assert(Operand.getValueType().bitsLT(VT) &&
5119            "Invalid fpext node, dst < src!");
5120     if (Operand.isUndef())
5121       return getUNDEF(VT);
5122     break;
5123   case ISD::FP_TO_SINT:
5124   case ISD::FP_TO_UINT:
5125     if (Operand.isUndef())
5126       return getUNDEF(VT);
5127     break;
5128   case ISD::SINT_TO_FP:
5129   case ISD::UINT_TO_FP:
5130     // [us]itofp(undef) = 0, because the result value is bounded.
5131     if (Operand.isUndef())
5132       return getConstantFP(0.0, DL, VT);
5133     break;
5134   case ISD::SIGN_EXTEND:
5135     assert(VT.isInteger() && Operand.getValueType().isInteger() &&
5136            "Invalid SIGN_EXTEND!");
5137     assert(VT.isVector() == Operand.getValueType().isVector() &&
5138            "SIGN_EXTEND result type type should be vector iff the operand "
5139            "type is vector!");
5140     if (Operand.getValueType() == VT) return Operand;   // noop extension
5141     assert((!VT.isVector() ||
5142             VT.getVectorElementCount() ==
5143                 Operand.getValueType().getVectorElementCount()) &&
5144            "Vector element count mismatch!");
5145     assert(Operand.getValueType().bitsLT(VT) &&
5146            "Invalid sext node, dst < src!");
5147     if (OpOpcode == ISD::SIGN_EXTEND || OpOpcode == ISD::ZERO_EXTEND)
5148       return getNode(OpOpcode, DL, VT, Operand.getOperand(0));
5149     if (OpOpcode == ISD::UNDEF)
5150       // sext(undef) = 0, because the top bits will all be the same.
5151       return getConstant(0, DL, VT);
5152     break;
5153   case ISD::ZERO_EXTEND:
5154     assert(VT.isInteger() && Operand.getValueType().isInteger() &&
5155            "Invalid ZERO_EXTEND!");
5156     assert(VT.isVector() == Operand.getValueType().isVector() &&
5157            "ZERO_EXTEND result type type should be vector iff the operand "
5158            "type is vector!");
5159     if (Operand.getValueType() == VT) return Operand;   // noop extension
5160     assert((!VT.isVector() ||
5161             VT.getVectorElementCount() ==
5162                 Operand.getValueType().getVectorElementCount()) &&
5163            "Vector element count mismatch!");
5164     assert(Operand.getValueType().bitsLT(VT) &&
5165            "Invalid zext node, dst < src!");
5166     if (OpOpcode == ISD::ZERO_EXTEND)   // (zext (zext x)) -> (zext x)
5167       return getNode(ISD::ZERO_EXTEND, DL, VT, Operand.getOperand(0));
5168     if (OpOpcode == ISD::UNDEF)
5169       // zext(undef) = 0, because the top bits will be zero.
5170       return getConstant(0, DL, VT);
5171     break;
5172   case ISD::ANY_EXTEND:
5173     assert(VT.isInteger() && Operand.getValueType().isInteger() &&
5174            "Invalid ANY_EXTEND!");
5175     assert(VT.isVector() == Operand.getValueType().isVector() &&
5176            "ANY_EXTEND result type type should be vector iff the operand "
5177            "type is vector!");
5178     if (Operand.getValueType() == VT) return Operand;   // noop extension
5179     assert((!VT.isVector() ||
5180             VT.getVectorElementCount() ==
5181                 Operand.getValueType().getVectorElementCount()) &&
5182            "Vector element count mismatch!");
5183     assert(Operand.getValueType().bitsLT(VT) &&
5184            "Invalid anyext node, dst < src!");
5185 
5186     if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
5187         OpOpcode == ISD::ANY_EXTEND)
5188       // (ext (zext x)) -> (zext x)  and  (ext (sext x)) -> (sext x)
5189       return getNode(OpOpcode, DL, VT, Operand.getOperand(0));
5190     if (OpOpcode == ISD::UNDEF)
5191       return getUNDEF(VT);
5192 
5193     // (ext (trunc x)) -> x
5194     if (OpOpcode == ISD::TRUNCATE) {
5195       SDValue OpOp = Operand.getOperand(0);
5196       if (OpOp.getValueType() == VT) {
5197         transferDbgValues(Operand, OpOp);
5198         return OpOp;
5199       }
5200     }
5201     break;
5202   case ISD::TRUNCATE:
5203     assert(VT.isInteger() && Operand.getValueType().isInteger() &&
5204            "Invalid TRUNCATE!");
5205     assert(VT.isVector() == Operand.getValueType().isVector() &&
5206            "TRUNCATE result type type should be vector iff the operand "
5207            "type is vector!");
5208     if (Operand.getValueType() == VT) return Operand;   // noop truncate
5209     assert((!VT.isVector() ||
5210             VT.getVectorElementCount() ==
5211                 Operand.getValueType().getVectorElementCount()) &&
5212            "Vector element count mismatch!");
5213     assert(Operand.getValueType().bitsGT(VT) &&
5214            "Invalid truncate node, src < dst!");
5215     if (OpOpcode == ISD::TRUNCATE)
5216       return getNode(ISD::TRUNCATE, DL, VT, Operand.getOperand(0));
5217     if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
5218         OpOpcode == ISD::ANY_EXTEND) {
5219       // If the source is smaller than the dest, we still need an extend.
5220       if (Operand.getOperand(0).getValueType().getScalarType()
5221             .bitsLT(VT.getScalarType()))
5222         return getNode(OpOpcode, DL, VT, Operand.getOperand(0));
5223       if (Operand.getOperand(0).getValueType().bitsGT(VT))
5224         return getNode(ISD::TRUNCATE, DL, VT, Operand.getOperand(0));
5225       return Operand.getOperand(0);
5226     }
5227     if (OpOpcode == ISD::UNDEF)
5228       return getUNDEF(VT);
5229     if (OpOpcode == ISD::VSCALE && !NewNodesMustHaveLegalTypes)
5230       return getVScale(DL, VT, Operand.getConstantOperandAPInt(0));
5231     break;
5232   case ISD::ANY_EXTEND_VECTOR_INREG:
5233   case ISD::ZERO_EXTEND_VECTOR_INREG:
5234   case ISD::SIGN_EXTEND_VECTOR_INREG:
5235     assert(VT.isVector() && "This DAG node is restricted to vector types.");
5236     assert(Operand.getValueType().bitsLE(VT) &&
5237            "The input must be the same size or smaller than the result.");
5238     assert(VT.getVectorMinNumElements() <
5239                Operand.getValueType().getVectorMinNumElements() &&
5240            "The destination vector type must have fewer lanes than the input.");
5241     break;
5242   case ISD::ABS:
5243     assert(VT.isInteger() && VT == Operand.getValueType() &&
5244            "Invalid ABS!");
5245     if (OpOpcode == ISD::UNDEF)
5246       return getUNDEF(VT);
5247     break;
5248   case ISD::BSWAP:
5249     assert(VT.isInteger() && VT == Operand.getValueType() &&
5250            "Invalid BSWAP!");
5251     assert((VT.getScalarSizeInBits() % 16 == 0) &&
5252            "BSWAP types must be a multiple of 16 bits!");
5253     if (OpOpcode == ISD::UNDEF)
5254       return getUNDEF(VT);
5255     // bswap(bswap(X)) -> X.
5256     if (OpOpcode == ISD::BSWAP)
5257       return Operand.getOperand(0);
5258     break;
5259   case ISD::BITREVERSE:
5260     assert(VT.isInteger() && VT == Operand.getValueType() &&
5261            "Invalid BITREVERSE!");
5262     if (OpOpcode == ISD::UNDEF)
5263       return getUNDEF(VT);
5264     break;
5265   case ISD::BITCAST:
5266     assert(VT.getSizeInBits() == Operand.getValueSizeInBits() &&
5267            "Cannot BITCAST between types of different sizes!");
5268     if (VT == Operand.getValueType()) return Operand;  // noop conversion.
5269     if (OpOpcode == ISD::BITCAST)  // bitconv(bitconv(x)) -> bitconv(x)
5270       return getNode(ISD::BITCAST, DL, VT, Operand.getOperand(0));
5271     if (OpOpcode == ISD::UNDEF)
5272       return getUNDEF(VT);
5273     break;
5274   case ISD::SCALAR_TO_VECTOR:
5275     assert(VT.isVector() && !Operand.getValueType().isVector() &&
5276            (VT.getVectorElementType() == Operand.getValueType() ||
5277             (VT.getVectorElementType().isInteger() &&
5278              Operand.getValueType().isInteger() &&
5279              VT.getVectorElementType().bitsLE(Operand.getValueType()))) &&
5280            "Illegal SCALAR_TO_VECTOR node!");
5281     if (OpOpcode == ISD::UNDEF)
5282       return getUNDEF(VT);
5283     // scalar_to_vector(extract_vector_elt V, 0) -> V, top bits are undefined.
5284     if (OpOpcode == ISD::EXTRACT_VECTOR_ELT &&
5285         isa<ConstantSDNode>(Operand.getOperand(1)) &&
5286         Operand.getConstantOperandVal(1) == 0 &&
5287         Operand.getOperand(0).getValueType() == VT)
5288       return Operand.getOperand(0);
5289     break;
5290   case ISD::FNEG:
5291     // Negation of an unknown bag of bits is still completely undefined.
5292     if (OpOpcode == ISD::UNDEF)
5293       return getUNDEF(VT);
5294 
5295     if (OpOpcode == ISD::FNEG)  // --X -> X
5296       return Operand.getOperand(0);
5297     break;
5298   case ISD::FABS:
5299     if (OpOpcode == ISD::FNEG)  // abs(-X) -> abs(X)
5300       return getNode(ISD::FABS, DL, VT, Operand.getOperand(0));
5301     break;
5302   case ISD::VSCALE:
5303     assert(VT == Operand.getValueType() && "Unexpected VT!");
5304     break;
5305   case ISD::CTPOP:
5306     if (Operand.getValueType().getScalarType() == MVT::i1)
5307       return Operand;
5308     break;
5309   case ISD::CTLZ:
5310   case ISD::CTTZ:
5311     if (Operand.getValueType().getScalarType() == MVT::i1)
5312       return getNOT(DL, Operand, Operand.getValueType());
5313     break;
5314   case ISD::VECREDUCE_SMIN:
5315   case ISD::VECREDUCE_UMAX:
5316     if (Operand.getValueType().getScalarType() == MVT::i1)
5317       return getNode(ISD::VECREDUCE_OR, DL, VT, Operand);
5318     break;
5319   case ISD::VECREDUCE_SMAX:
5320   case ISD::VECREDUCE_UMIN:
5321     if (Operand.getValueType().getScalarType() == MVT::i1)
5322       return getNode(ISD::VECREDUCE_AND, DL, VT, Operand);
5323     break;
5324   }
5325 
5326   SDNode *N;
5327   SDVTList VTs = getVTList(VT);
5328   SDValue Ops[] = {Operand};
5329   if (VT != MVT::Glue) { // Don't CSE flag producing nodes
5330     FoldingSetNodeID ID;
5331     AddNodeIDNode(ID, Opcode, VTs, Ops);
5332     void *IP = nullptr;
5333     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
5334       E->intersectFlagsWith(Flags);
5335       return SDValue(E, 0);
5336     }
5337 
5338     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
5339     N->setFlags(Flags);
5340     createOperands(N, Ops);
5341     CSEMap.InsertNode(N, IP);
5342   } else {
5343     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
5344     createOperands(N, Ops);
5345   }
5346 
5347   InsertNode(N);
5348   SDValue V = SDValue(N, 0);
5349   NewSDValueDbgMsg(V, "Creating new node: ", this);
5350   return V;
5351 }
5352 
5353 static llvm::Optional<APInt> FoldValue(unsigned Opcode, const APInt &C1,
5354                                        const APInt &C2) {
5355   switch (Opcode) {
5356   case ISD::ADD:  return C1 + C2;
5357   case ISD::SUB:  return C1 - C2;
5358   case ISD::MUL:  return C1 * C2;
5359   case ISD::AND:  return C1 & C2;
5360   case ISD::OR:   return C1 | C2;
5361   case ISD::XOR:  return C1 ^ C2;
5362   case ISD::SHL:  return C1 << C2;
5363   case ISD::SRL:  return C1.lshr(C2);
5364   case ISD::SRA:  return C1.ashr(C2);
5365   case ISD::ROTL: return C1.rotl(C2);
5366   case ISD::ROTR: return C1.rotr(C2);
5367   case ISD::SMIN: return C1.sle(C2) ? C1 : C2;
5368   case ISD::SMAX: return C1.sge(C2) ? C1 : C2;
5369   case ISD::UMIN: return C1.ule(C2) ? C1 : C2;
5370   case ISD::UMAX: return C1.uge(C2) ? C1 : C2;
5371   case ISD::SADDSAT: return C1.sadd_sat(C2);
5372   case ISD::UADDSAT: return C1.uadd_sat(C2);
5373   case ISD::SSUBSAT: return C1.ssub_sat(C2);
5374   case ISD::USUBSAT: return C1.usub_sat(C2);
5375   case ISD::SSHLSAT: return C1.sshl_sat(C2);
5376   case ISD::USHLSAT: return C1.ushl_sat(C2);
5377   case ISD::UDIV:
5378     if (!C2.getBoolValue())
5379       break;
5380     return C1.udiv(C2);
5381   case ISD::UREM:
5382     if (!C2.getBoolValue())
5383       break;
5384     return C1.urem(C2);
5385   case ISD::SDIV:
5386     if (!C2.getBoolValue())
5387       break;
5388     return C1.sdiv(C2);
5389   case ISD::SREM:
5390     if (!C2.getBoolValue())
5391       break;
5392     return C1.srem(C2);
5393   case ISD::MULHS: {
5394     unsigned FullWidth = C1.getBitWidth() * 2;
5395     APInt C1Ext = C1.sext(FullWidth);
5396     APInt C2Ext = C2.sext(FullWidth);
5397     return (C1Ext * C2Ext).extractBits(C1.getBitWidth(), C1.getBitWidth());
5398   }
5399   case ISD::MULHU: {
5400     unsigned FullWidth = C1.getBitWidth() * 2;
5401     APInt C1Ext = C1.zext(FullWidth);
5402     APInt C2Ext = C2.zext(FullWidth);
5403     return (C1Ext * C2Ext).extractBits(C1.getBitWidth(), C1.getBitWidth());
5404   }
5405   case ISD::AVGFLOORS: {
5406     unsigned FullWidth = C1.getBitWidth() + 1;
5407     APInt C1Ext = C1.sext(FullWidth);
5408     APInt C2Ext = C2.sext(FullWidth);
5409     return (C1Ext + C2Ext).extractBits(C1.getBitWidth(), 1);
5410   }
5411   case ISD::AVGFLOORU: {
5412     unsigned FullWidth = C1.getBitWidth() + 1;
5413     APInt C1Ext = C1.zext(FullWidth);
5414     APInt C2Ext = C2.zext(FullWidth);
5415     return (C1Ext + C2Ext).extractBits(C1.getBitWidth(), 1);
5416   }
5417   case ISD::AVGCEILS: {
5418     unsigned FullWidth = C1.getBitWidth() + 1;
5419     APInt C1Ext = C1.sext(FullWidth);
5420     APInt C2Ext = C2.sext(FullWidth);
5421     return (C1Ext + C2Ext + 1).extractBits(C1.getBitWidth(), 1);
5422   }
5423   case ISD::AVGCEILU: {
5424     unsigned FullWidth = C1.getBitWidth() + 1;
5425     APInt C1Ext = C1.zext(FullWidth);
5426     APInt C2Ext = C2.zext(FullWidth);
5427     return (C1Ext + C2Ext + 1).extractBits(C1.getBitWidth(), 1);
5428   }
5429   }
5430   return llvm::None;
5431 }
5432 
5433 SDValue SelectionDAG::FoldSymbolOffset(unsigned Opcode, EVT VT,
5434                                        const GlobalAddressSDNode *GA,
5435                                        const SDNode *N2) {
5436   if (GA->getOpcode() != ISD::GlobalAddress)
5437     return SDValue();
5438   if (!TLI->isOffsetFoldingLegal(GA))
5439     return SDValue();
5440   auto *C2 = dyn_cast<ConstantSDNode>(N2);
5441   if (!C2)
5442     return SDValue();
5443   int64_t Offset = C2->getSExtValue();
5444   switch (Opcode) {
5445   case ISD::ADD: break;
5446   case ISD::SUB: Offset = -uint64_t(Offset); break;
5447   default: return SDValue();
5448   }
5449   return getGlobalAddress(GA->getGlobal(), SDLoc(C2), VT,
5450                           GA->getOffset() + uint64_t(Offset));
5451 }
5452 
5453 bool SelectionDAG::isUndef(unsigned Opcode, ArrayRef<SDValue> Ops) {
5454   switch (Opcode) {
5455   case ISD::SDIV:
5456   case ISD::UDIV:
5457   case ISD::SREM:
5458   case ISD::UREM: {
5459     // If a divisor is zero/undef or any element of a divisor vector is
5460     // zero/undef, the whole op is undef.
5461     assert(Ops.size() == 2 && "Div/rem should have 2 operands");
5462     SDValue Divisor = Ops[1];
5463     if (Divisor.isUndef() || isNullConstant(Divisor))
5464       return true;
5465 
5466     return ISD::isBuildVectorOfConstantSDNodes(Divisor.getNode()) &&
5467            llvm::any_of(Divisor->op_values(),
5468                         [](SDValue V) { return V.isUndef() ||
5469                                         isNullConstant(V); });
5470     // TODO: Handle signed overflow.
5471   }
5472   // TODO: Handle oversized shifts.
5473   default:
5474     return false;
5475   }
5476 }
5477 
5478 SDValue SelectionDAG::FoldConstantArithmetic(unsigned Opcode, const SDLoc &DL,
5479                                              EVT VT, ArrayRef<SDValue> Ops) {
5480   // If the opcode is a target-specific ISD node, there's nothing we can
5481   // do here and the operand rules may not line up with the below, so
5482   // bail early.
5483   // We can't create a scalar CONCAT_VECTORS so skip it. It will break
5484   // for concats involving SPLAT_VECTOR. Concats of BUILD_VECTORS are handled by
5485   // foldCONCAT_VECTORS in getNode before this is called.
5486   if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::CONCAT_VECTORS)
5487     return SDValue();
5488 
5489   unsigned NumOps = Ops.size();
5490   if (NumOps == 0)
5491     return SDValue();
5492 
5493   if (isUndef(Opcode, Ops))
5494     return getUNDEF(VT);
5495 
5496   // Handle binops special cases.
5497   if (NumOps == 2) {
5498     if (SDValue CFP = foldConstantFPMath(Opcode, DL, VT, Ops[0], Ops[1]))
5499       return CFP;
5500 
5501     if (auto *C1 = dyn_cast<ConstantSDNode>(Ops[0])) {
5502       if (auto *C2 = dyn_cast<ConstantSDNode>(Ops[1])) {
5503         if (C1->isOpaque() || C2->isOpaque())
5504           return SDValue();
5505 
5506         Optional<APInt> FoldAttempt =
5507             FoldValue(Opcode, C1->getAPIntValue(), C2->getAPIntValue());
5508         if (!FoldAttempt)
5509           return SDValue();
5510 
5511         SDValue Folded = getConstant(FoldAttempt.getValue(), DL, VT);
5512         assert((!Folded || !VT.isVector()) &&
5513                "Can't fold vectors ops with scalar operands");
5514         return Folded;
5515       }
5516     }
5517 
5518     // fold (add Sym, c) -> Sym+c
5519     if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Ops[0]))
5520       return FoldSymbolOffset(Opcode, VT, GA, Ops[1].getNode());
5521     if (TLI->isCommutativeBinOp(Opcode))
5522       if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Ops[1]))
5523         return FoldSymbolOffset(Opcode, VT, GA, Ops[0].getNode());
5524   }
5525 
5526   // This is for vector folding only from here on.
5527   if (!VT.isVector())
5528     return SDValue();
5529 
5530   ElementCount NumElts = VT.getVectorElementCount();
5531 
5532   // See if we can fold through bitcasted integer ops.
5533   // TODO: Can we handle undef elements?
5534   if (NumOps == 2 && VT.isFixedLengthVector() && VT.isInteger() &&
5535       Ops[0].getValueType() == VT && Ops[1].getValueType() == VT &&
5536       Ops[0].getOpcode() == ISD::BITCAST &&
5537       Ops[1].getOpcode() == ISD::BITCAST) {
5538     SDValue N1 = peekThroughBitcasts(Ops[0]);
5539     SDValue N2 = peekThroughBitcasts(Ops[1]);
5540     auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
5541     auto *BV2 = dyn_cast<BuildVectorSDNode>(N2);
5542     EVT BVVT = N1.getValueType();
5543     if (BV1 && BV2 && BVVT.isInteger() && BVVT == N2.getValueType()) {
5544       bool IsLE = getDataLayout().isLittleEndian();
5545       unsigned EltBits = VT.getScalarSizeInBits();
5546       SmallVector<APInt> RawBits1, RawBits2;
5547       BitVector UndefElts1, UndefElts2;
5548       if (BV1->getConstantRawBits(IsLE, EltBits, RawBits1, UndefElts1) &&
5549           BV2->getConstantRawBits(IsLE, EltBits, RawBits2, UndefElts2) &&
5550           UndefElts1.none() && UndefElts2.none()) {
5551         SmallVector<APInt> RawBits;
5552         for (unsigned I = 0, E = NumElts.getFixedValue(); I != E; ++I) {
5553           Optional<APInt> Fold = FoldValue(Opcode, RawBits1[I], RawBits2[I]);
5554           if (!Fold)
5555             break;
5556           RawBits.push_back(Fold.getValue());
5557         }
5558         if (RawBits.size() == NumElts.getFixedValue()) {
5559           // We have constant folded, but we need to cast this again back to
5560           // the original (possibly legalized) type.
5561           SmallVector<APInt> DstBits;
5562           BitVector DstUndefs;
5563           BuildVectorSDNode::recastRawBits(IsLE, BVVT.getScalarSizeInBits(),
5564                                            DstBits, RawBits, DstUndefs,
5565                                            BitVector(RawBits.size(), false));
5566           EVT BVEltVT = BV1->getOperand(0).getValueType();
5567           unsigned BVEltBits = BVEltVT.getSizeInBits();
5568           SmallVector<SDValue> Ops(DstBits.size(), getUNDEF(BVEltVT));
5569           for (unsigned I = 0, E = DstBits.size(); I != E; ++I) {
5570             if (DstUndefs[I])
5571               continue;
5572             Ops[I] = getConstant(DstBits[I].sextOrSelf(BVEltBits), DL, BVEltVT);
5573           }
5574           return getBitcast(VT, getBuildVector(BVVT, DL, Ops));
5575         }
5576       }
5577     }
5578   }
5579 
5580   // Fold (mul step_vector(C0), C1) to (step_vector(C0 * C1)).
5581   //      (shl step_vector(C0), C1) -> (step_vector(C0 << C1))
5582   if ((Opcode == ISD::MUL || Opcode == ISD::SHL) &&
5583       Ops[0].getOpcode() == ISD::STEP_VECTOR) {
5584     APInt RHSVal;
5585     if (ISD::isConstantSplatVector(Ops[1].getNode(), RHSVal)) {
5586       APInt NewStep = Opcode == ISD::MUL
5587                           ? Ops[0].getConstantOperandAPInt(0) * RHSVal
5588                           : Ops[0].getConstantOperandAPInt(0) << RHSVal;
5589       return getStepVector(DL, VT, NewStep);
5590     }
5591   }
5592 
5593   auto IsScalarOrSameVectorSize = [NumElts](const SDValue &Op) {
5594     return !Op.getValueType().isVector() ||
5595            Op.getValueType().getVectorElementCount() == NumElts;
5596   };
5597 
5598   auto IsBuildVectorSplatVectorOrUndef = [](const SDValue &Op) {
5599     return Op.isUndef() || Op.getOpcode() == ISD::CONDCODE ||
5600            Op.getOpcode() == ISD::BUILD_VECTOR ||
5601            Op.getOpcode() == ISD::SPLAT_VECTOR;
5602   };
5603 
5604   // All operands must be vector types with the same number of elements as
5605   // the result type and must be either UNDEF or a build/splat vector
5606   // or UNDEF scalars.
5607   if (!llvm::all_of(Ops, IsBuildVectorSplatVectorOrUndef) ||
5608       !llvm::all_of(Ops, IsScalarOrSameVectorSize))
5609     return SDValue();
5610 
5611   // If we are comparing vectors, then the result needs to be a i1 boolean that
5612   // is then extended back to the legal result type depending on how booleans
5613   // are represented.
5614   EVT SVT = (Opcode == ISD::SETCC ? MVT::i1 : VT.getScalarType());
5615   ISD::NodeType ExtendCode =
5616       (Opcode == ISD::SETCC && SVT != VT.getScalarType())
5617           ? TargetLowering::getExtendForContent(TLI->getBooleanContents(VT))
5618           : ISD::SIGN_EXTEND;
5619 
5620   // Find legal integer scalar type for constant promotion and
5621   // ensure that its scalar size is at least as large as source.
5622   EVT LegalSVT = VT.getScalarType();
5623   if (NewNodesMustHaveLegalTypes && LegalSVT.isInteger()) {
5624     LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT);
5625     if (LegalSVT.bitsLT(VT.getScalarType()))
5626       return SDValue();
5627   }
5628 
5629   // For scalable vector types we know we're dealing with SPLAT_VECTORs. We
5630   // only have one operand to check. For fixed-length vector types we may have
5631   // a combination of BUILD_VECTOR and SPLAT_VECTOR.
5632   unsigned NumVectorElts = NumElts.isScalable() ? 1 : NumElts.getFixedValue();
5633 
5634   // Constant fold each scalar lane separately.
5635   SmallVector<SDValue, 4> ScalarResults;
5636   for (unsigned I = 0; I != NumVectorElts; I++) {
5637     SmallVector<SDValue, 4> ScalarOps;
5638     for (SDValue Op : Ops) {
5639       EVT InSVT = Op.getValueType().getScalarType();
5640       if (Op.getOpcode() != ISD::BUILD_VECTOR &&
5641           Op.getOpcode() != ISD::SPLAT_VECTOR) {
5642         if (Op.isUndef())
5643           ScalarOps.push_back(getUNDEF(InSVT));
5644         else
5645           ScalarOps.push_back(Op);
5646         continue;
5647       }
5648 
5649       SDValue ScalarOp =
5650           Op.getOperand(Op.getOpcode() == ISD::SPLAT_VECTOR ? 0 : I);
5651       EVT ScalarVT = ScalarOp.getValueType();
5652 
5653       // Build vector (integer) scalar operands may need implicit
5654       // truncation - do this before constant folding.
5655       if (ScalarVT.isInteger() && ScalarVT.bitsGT(InSVT)) {
5656         // Don't create illegally-typed nodes unless they're constants or undef
5657         // - if we fail to constant fold we can't guarantee the (dead) nodes
5658         // we're creating will be cleaned up before being visited for
5659         // legalization.
5660         if (NewNodesMustHaveLegalTypes && !ScalarOp.isUndef() &&
5661             !isa<ConstantSDNode>(ScalarOp) &&
5662             TLI->getTypeAction(*getContext(), InSVT) !=
5663                 TargetLowering::TypeLegal)
5664           return SDValue();
5665         ScalarOp = getNode(ISD::TRUNCATE, DL, InSVT, ScalarOp);
5666       }
5667 
5668       ScalarOps.push_back(ScalarOp);
5669     }
5670 
5671     // Constant fold the scalar operands.
5672     SDValue ScalarResult = getNode(Opcode, DL, SVT, ScalarOps);
5673 
5674     // Legalize the (integer) scalar constant if necessary.
5675     if (LegalSVT != SVT)
5676       ScalarResult = getNode(ExtendCode, DL, LegalSVT, ScalarResult);
5677 
5678     // Scalar folding only succeeded if the result is a constant or UNDEF.
5679     if (!ScalarResult.isUndef() && ScalarResult.getOpcode() != ISD::Constant &&
5680         ScalarResult.getOpcode() != ISD::ConstantFP)
5681       return SDValue();
5682     ScalarResults.push_back(ScalarResult);
5683   }
5684 
5685   SDValue V = NumElts.isScalable() ? getSplatVector(VT, DL, ScalarResults[0])
5686                                    : getBuildVector(VT, DL, ScalarResults);
5687   NewSDValueDbgMsg(V, "New node fold constant vector: ", this);
5688   return V;
5689 }
5690 
5691 SDValue SelectionDAG::foldConstantFPMath(unsigned Opcode, const SDLoc &DL,
5692                                          EVT VT, SDValue N1, SDValue N2) {
5693   // TODO: We don't do any constant folding for strict FP opcodes here, but we
5694   //       should. That will require dealing with a potentially non-default
5695   //       rounding mode, checking the "opStatus" return value from the APFloat
5696   //       math calculations, and possibly other variations.
5697   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1, /*AllowUndefs*/ false);
5698   ConstantFPSDNode *N2CFP = isConstOrConstSplatFP(N2, /*AllowUndefs*/ false);
5699   if (N1CFP && N2CFP) {
5700     APFloat C1 = N1CFP->getValueAPF(); // make copy
5701     const APFloat &C2 = N2CFP->getValueAPF();
5702     switch (Opcode) {
5703     case ISD::FADD:
5704       C1.add(C2, APFloat::rmNearestTiesToEven);
5705       return getConstantFP(C1, DL, VT);
5706     case ISD::FSUB:
5707       C1.subtract(C2, APFloat::rmNearestTiesToEven);
5708       return getConstantFP(C1, DL, VT);
5709     case ISD::FMUL:
5710       C1.multiply(C2, APFloat::rmNearestTiesToEven);
5711       return getConstantFP(C1, DL, VT);
5712     case ISD::FDIV:
5713       C1.divide(C2, APFloat::rmNearestTiesToEven);
5714       return getConstantFP(C1, DL, VT);
5715     case ISD::FREM:
5716       C1.mod(C2);
5717       return getConstantFP(C1, DL, VT);
5718     case ISD::FCOPYSIGN:
5719       C1.copySign(C2);
5720       return getConstantFP(C1, DL, VT);
5721     case ISD::FMINNUM:
5722       return getConstantFP(minnum(C1, C2), DL, VT);
5723     case ISD::FMAXNUM:
5724       return getConstantFP(maxnum(C1, C2), DL, VT);
5725     case ISD::FMINIMUM:
5726       return getConstantFP(minimum(C1, C2), DL, VT);
5727     case ISD::FMAXIMUM:
5728       return getConstantFP(maximum(C1, C2), DL, VT);
5729     default: break;
5730     }
5731   }
5732   if (N1CFP && Opcode == ISD::FP_ROUND) {
5733     APFloat C1 = N1CFP->getValueAPF();    // make copy
5734     bool Unused;
5735     // This can return overflow, underflow, or inexact; we don't care.
5736     // FIXME need to be more flexible about rounding mode.
5737     (void) C1.convert(EVTToAPFloatSemantics(VT), APFloat::rmNearestTiesToEven,
5738                       &Unused);
5739     return getConstantFP(C1, DL, VT);
5740   }
5741 
5742   switch (Opcode) {
5743   case ISD::FSUB:
5744     // -0.0 - undef --> undef (consistent with "fneg undef")
5745     if (ConstantFPSDNode *N1C = isConstOrConstSplatFP(N1, /*AllowUndefs*/ true))
5746       if (N1C && N1C->getValueAPF().isNegZero() && N2.isUndef())
5747         return getUNDEF(VT);
5748     LLVM_FALLTHROUGH;
5749 
5750   case ISD::FADD:
5751   case ISD::FMUL:
5752   case ISD::FDIV:
5753   case ISD::FREM:
5754     // If both operands are undef, the result is undef. If 1 operand is undef,
5755     // the result is NaN. This should match the behavior of the IR optimizer.
5756     if (N1.isUndef() && N2.isUndef())
5757       return getUNDEF(VT);
5758     if (N1.isUndef() || N2.isUndef())
5759       return getConstantFP(APFloat::getNaN(EVTToAPFloatSemantics(VT)), DL, VT);
5760   }
5761   return SDValue();
5762 }
5763 
5764 SDValue SelectionDAG::getAssertAlign(const SDLoc &DL, SDValue Val, Align A) {
5765   assert(Val.getValueType().isInteger() && "Invalid AssertAlign!");
5766 
5767   // There's no need to assert on a byte-aligned pointer. All pointers are at
5768   // least byte aligned.
5769   if (A == Align(1))
5770     return Val;
5771 
5772   FoldingSetNodeID ID;
5773   AddNodeIDNode(ID, ISD::AssertAlign, getVTList(Val.getValueType()), {Val});
5774   ID.AddInteger(A.value());
5775 
5776   void *IP = nullptr;
5777   if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
5778     return SDValue(E, 0);
5779 
5780   auto *N = newSDNode<AssertAlignSDNode>(DL.getIROrder(), DL.getDebugLoc(),
5781                                          Val.getValueType(), A);
5782   createOperands(N, {Val});
5783 
5784   CSEMap.InsertNode(N, IP);
5785   InsertNode(N);
5786 
5787   SDValue V(N, 0);
5788   NewSDValueDbgMsg(V, "Creating new node: ", this);
5789   return V;
5790 }
5791 
5792 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
5793                               SDValue N1, SDValue N2) {
5794   SDNodeFlags Flags;
5795   if (Inserter)
5796     Flags = Inserter->getFlags();
5797   return getNode(Opcode, DL, VT, N1, N2, Flags);
5798 }
5799 
5800 void SelectionDAG::canonicalizeCommutativeBinop(unsigned Opcode, SDValue &N1,
5801                                                 SDValue &N2) const {
5802   if (!TLI->isCommutativeBinOp(Opcode))
5803     return;
5804 
5805   // Canonicalize:
5806   //   binop(const, nonconst) -> binop(nonconst, const)
5807   bool IsN1C = isConstantIntBuildVectorOrConstantInt(N1);
5808   bool IsN2C = isConstantIntBuildVectorOrConstantInt(N2);
5809   bool IsN1CFP = isConstantFPBuildVectorOrConstantFP(N1);
5810   bool IsN2CFP = isConstantFPBuildVectorOrConstantFP(N2);
5811   if ((IsN1C && !IsN2C) || (IsN1CFP && !IsN2CFP))
5812     std::swap(N1, N2);
5813 
5814   // Canonicalize:
5815   //  binop(splat(x), step_vector) -> binop(step_vector, splat(x))
5816   else if (N1.getOpcode() == ISD::SPLAT_VECTOR &&
5817            N2.getOpcode() == ISD::STEP_VECTOR)
5818     std::swap(N1, N2);
5819 }
5820 
5821 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
5822                               SDValue N1, SDValue N2, const SDNodeFlags Flags) {
5823   assert(N1.getOpcode() != ISD::DELETED_NODE &&
5824          N2.getOpcode() != ISD::DELETED_NODE &&
5825          "Operand is DELETED_NODE!");
5826 
5827   canonicalizeCommutativeBinop(Opcode, N1, N2);
5828 
5829   auto *N1C = dyn_cast<ConstantSDNode>(N1);
5830   auto *N2C = dyn_cast<ConstantSDNode>(N2);
5831 
5832   // Don't allow undefs in vector splats - we might be returning N2 when folding
5833   // to zero etc.
5834   ConstantSDNode *N2CV =
5835       isConstOrConstSplat(N2, /*AllowUndefs*/ false, /*AllowTruncation*/ true);
5836 
5837   switch (Opcode) {
5838   default: break;
5839   case ISD::TokenFactor:
5840     assert(VT == MVT::Other && N1.getValueType() == MVT::Other &&
5841            N2.getValueType() == MVT::Other && "Invalid token factor!");
5842     // Fold trivial token factors.
5843     if (N1.getOpcode() == ISD::EntryToken) return N2;
5844     if (N2.getOpcode() == ISD::EntryToken) return N1;
5845     if (N1 == N2) return N1;
5846     break;
5847   case ISD::BUILD_VECTOR: {
5848     // Attempt to simplify BUILD_VECTOR.
5849     SDValue Ops[] = {N1, N2};
5850     if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
5851       return V;
5852     break;
5853   }
5854   case ISD::CONCAT_VECTORS: {
5855     SDValue Ops[] = {N1, N2};
5856     if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this))
5857       return V;
5858     break;
5859   }
5860   case ISD::AND:
5861     assert(VT.isInteger() && "This operator does not apply to FP types!");
5862     assert(N1.getValueType() == N2.getValueType() &&
5863            N1.getValueType() == VT && "Binary operator types must match!");
5864     // (X & 0) -> 0.  This commonly occurs when legalizing i64 values, so it's
5865     // worth handling here.
5866     if (N2CV && N2CV->isZero())
5867       return N2;
5868     if (N2CV && N2CV->isAllOnes()) // X & -1 -> X
5869       return N1;
5870     break;
5871   case ISD::OR:
5872   case ISD::XOR:
5873   case ISD::ADD:
5874   case ISD::SUB:
5875     assert(VT.isInteger() && "This operator does not apply to FP types!");
5876     assert(N1.getValueType() == N2.getValueType() &&
5877            N1.getValueType() == VT && "Binary operator types must match!");
5878     // (X ^|+- 0) -> X.  This commonly occurs when legalizing i64 values, so
5879     // it's worth handling here.
5880     if (N2CV && N2CV->isZero())
5881       return N1;
5882     if ((Opcode == ISD::ADD || Opcode == ISD::SUB) && VT.isVector() &&
5883         VT.getVectorElementType() == MVT::i1)
5884       return getNode(ISD::XOR, DL, VT, N1, N2);
5885     break;
5886   case ISD::MUL:
5887     assert(VT.isInteger() && "This operator does not apply to FP types!");
5888     assert(N1.getValueType() == N2.getValueType() &&
5889            N1.getValueType() == VT && "Binary operator types must match!");
5890     if (VT.isVector() && VT.getVectorElementType() == MVT::i1)
5891       return getNode(ISD::AND, DL, VT, N1, N2);
5892     if (N2C && (N1.getOpcode() == ISD::VSCALE) && Flags.hasNoSignedWrap()) {
5893       const APInt &MulImm = N1->getConstantOperandAPInt(0);
5894       const APInt &N2CImm = N2C->getAPIntValue();
5895       return getVScale(DL, VT, MulImm * N2CImm);
5896     }
5897     break;
5898   case ISD::UDIV:
5899   case ISD::UREM:
5900   case ISD::MULHU:
5901   case ISD::MULHS:
5902   case ISD::SDIV:
5903   case ISD::SREM:
5904   case ISD::SADDSAT:
5905   case ISD::SSUBSAT:
5906   case ISD::UADDSAT:
5907   case ISD::USUBSAT:
5908     assert(VT.isInteger() && "This operator does not apply to FP types!");
5909     assert(N1.getValueType() == N2.getValueType() &&
5910            N1.getValueType() == VT && "Binary operator types must match!");
5911     if (VT.isVector() && VT.getVectorElementType() == MVT::i1) {
5912       // fold (add_sat x, y) -> (or x, y) for bool types.
5913       if (Opcode == ISD::SADDSAT || Opcode == ISD::UADDSAT)
5914         return getNode(ISD::OR, DL, VT, N1, N2);
5915       // fold (sub_sat x, y) -> (and x, ~y) for bool types.
5916       if (Opcode == ISD::SSUBSAT || Opcode == ISD::USUBSAT)
5917         return getNode(ISD::AND, DL, VT, N1, getNOT(DL, N2, VT));
5918     }
5919     break;
5920   case ISD::SMIN:
5921   case ISD::UMAX:
5922     assert(VT.isInteger() && "This operator does not apply to FP types!");
5923     assert(N1.getValueType() == N2.getValueType() &&
5924            N1.getValueType() == VT && "Binary operator types must match!");
5925     if (VT.isVector() && VT.getVectorElementType() == MVT::i1)
5926       return getNode(ISD::OR, DL, VT, N1, N2);
5927     break;
5928   case ISD::SMAX:
5929   case ISD::UMIN:
5930     assert(VT.isInteger() && "This operator does not apply to FP types!");
5931     assert(N1.getValueType() == N2.getValueType() &&
5932            N1.getValueType() == VT && "Binary operator types must match!");
5933     if (VT.isVector() && VT.getVectorElementType() == MVT::i1)
5934       return getNode(ISD::AND, DL, VT, N1, N2);
5935     break;
5936   case ISD::FADD:
5937   case ISD::FSUB:
5938   case ISD::FMUL:
5939   case ISD::FDIV:
5940   case ISD::FREM:
5941     assert(VT.isFloatingPoint() && "This operator only applies to FP types!");
5942     assert(N1.getValueType() == N2.getValueType() &&
5943            N1.getValueType() == VT && "Binary operator types must match!");
5944     if (SDValue V = simplifyFPBinop(Opcode, N1, N2, Flags))
5945       return V;
5946     break;
5947   case ISD::FCOPYSIGN:   // N1 and result must match.  N1/N2 need not match.
5948     assert(N1.getValueType() == VT &&
5949            N1.getValueType().isFloatingPoint() &&
5950            N2.getValueType().isFloatingPoint() &&
5951            "Invalid FCOPYSIGN!");
5952     break;
5953   case ISD::SHL:
5954     if (N2C && (N1.getOpcode() == ISD::VSCALE) && Flags.hasNoSignedWrap()) {
5955       const APInt &MulImm = N1->getConstantOperandAPInt(0);
5956       const APInt &ShiftImm = N2C->getAPIntValue();
5957       return getVScale(DL, VT, MulImm << ShiftImm);
5958     }
5959     LLVM_FALLTHROUGH;
5960   case ISD::SRA:
5961   case ISD::SRL:
5962     if (SDValue V = simplifyShift(N1, N2))
5963       return V;
5964     LLVM_FALLTHROUGH;
5965   case ISD::ROTL:
5966   case ISD::ROTR:
5967     assert(VT == N1.getValueType() &&
5968            "Shift operators return type must be the same as their first arg");
5969     assert(VT.isInteger() && N2.getValueType().isInteger() &&
5970            "Shifts only work on integers");
5971     assert((!VT.isVector() || VT == N2.getValueType()) &&
5972            "Vector shift amounts must be in the same as their first arg");
5973     // Verify that the shift amount VT is big enough to hold valid shift
5974     // amounts.  This catches things like trying to shift an i1024 value by an
5975     // i8, which is easy to fall into in generic code that uses
5976     // TLI.getShiftAmount().
5977     assert(N2.getValueType().getScalarSizeInBits() >=
5978                Log2_32_Ceil(VT.getScalarSizeInBits()) &&
5979            "Invalid use of small shift amount with oversized value!");
5980 
5981     // Always fold shifts of i1 values so the code generator doesn't need to
5982     // handle them.  Since we know the size of the shift has to be less than the
5983     // size of the value, the shift/rotate count is guaranteed to be zero.
5984     if (VT == MVT::i1)
5985       return N1;
5986     if (N2CV && N2CV->isZero())
5987       return N1;
5988     break;
5989   case ISD::FP_ROUND:
5990     assert(VT.isFloatingPoint() &&
5991            N1.getValueType().isFloatingPoint() &&
5992            VT.bitsLE(N1.getValueType()) &&
5993            N2C && (N2C->getZExtValue() == 0 || N2C->getZExtValue() == 1) &&
5994            "Invalid FP_ROUND!");
5995     if (N1.getValueType() == VT) return N1;  // noop conversion.
5996     break;
5997   case ISD::AssertSext:
5998   case ISD::AssertZext: {
5999     EVT EVT = cast<VTSDNode>(N2)->getVT();
6000     assert(VT == N1.getValueType() && "Not an inreg extend!");
6001     assert(VT.isInteger() && EVT.isInteger() &&
6002            "Cannot *_EXTEND_INREG FP types");
6003     assert(!EVT.isVector() &&
6004            "AssertSExt/AssertZExt type should be the vector element type "
6005            "rather than the vector type!");
6006     assert(EVT.bitsLE(VT.getScalarType()) && "Not extending!");
6007     if (VT.getScalarType() == EVT) return N1; // noop assertion.
6008     break;
6009   }
6010   case ISD::SIGN_EXTEND_INREG: {
6011     EVT EVT = cast<VTSDNode>(N2)->getVT();
6012     assert(VT == N1.getValueType() && "Not an inreg extend!");
6013     assert(VT.isInteger() && EVT.isInteger() &&
6014            "Cannot *_EXTEND_INREG FP types");
6015     assert(EVT.isVector() == VT.isVector() &&
6016            "SIGN_EXTEND_INREG type should be vector iff the operand "
6017            "type is vector!");
6018     assert((!EVT.isVector() ||
6019             EVT.getVectorElementCount() == VT.getVectorElementCount()) &&
6020            "Vector element counts must match in SIGN_EXTEND_INREG");
6021     assert(EVT.bitsLE(VT) && "Not extending!");
6022     if (EVT == VT) return N1;  // Not actually extending
6023 
6024     auto SignExtendInReg = [&](APInt Val, llvm::EVT ConstantVT) {
6025       unsigned FromBits = EVT.getScalarSizeInBits();
6026       Val <<= Val.getBitWidth() - FromBits;
6027       Val.ashrInPlace(Val.getBitWidth() - FromBits);
6028       return getConstant(Val, DL, ConstantVT);
6029     };
6030 
6031     if (N1C) {
6032       const APInt &Val = N1C->getAPIntValue();
6033       return SignExtendInReg(Val, VT);
6034     }
6035 
6036     if (ISD::isBuildVectorOfConstantSDNodes(N1.getNode())) {
6037       SmallVector<SDValue, 8> Ops;
6038       llvm::EVT OpVT = N1.getOperand(0).getValueType();
6039       for (int i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
6040         SDValue Op = N1.getOperand(i);
6041         if (Op.isUndef()) {
6042           Ops.push_back(getUNDEF(OpVT));
6043           continue;
6044         }
6045         ConstantSDNode *C = cast<ConstantSDNode>(Op);
6046         APInt Val = C->getAPIntValue();
6047         Ops.push_back(SignExtendInReg(Val, OpVT));
6048       }
6049       return getBuildVector(VT, DL, Ops);
6050     }
6051     break;
6052   }
6053   case ISD::FP_TO_SINT_SAT:
6054   case ISD::FP_TO_UINT_SAT: {
6055     assert(VT.isInteger() && cast<VTSDNode>(N2)->getVT().isInteger() &&
6056            N1.getValueType().isFloatingPoint() && "Invalid FP_TO_*INT_SAT");
6057     assert(N1.getValueType().isVector() == VT.isVector() &&
6058            "FP_TO_*INT_SAT type should be vector iff the operand type is "
6059            "vector!");
6060     assert((!VT.isVector() || VT.getVectorNumElements() ==
6061                                   N1.getValueType().getVectorNumElements()) &&
6062            "Vector element counts must match in FP_TO_*INT_SAT");
6063     assert(!cast<VTSDNode>(N2)->getVT().isVector() &&
6064            "Type to saturate to must be a scalar.");
6065     assert(cast<VTSDNode>(N2)->getVT().bitsLE(VT.getScalarType()) &&
6066            "Not extending!");
6067     break;
6068   }
6069   case ISD::EXTRACT_VECTOR_ELT:
6070     assert(VT.getSizeInBits() >= N1.getValueType().getScalarSizeInBits() &&
6071            "The result of EXTRACT_VECTOR_ELT must be at least as wide as the \
6072              element type of the vector.");
6073 
6074     // Extract from an undefined value or using an undefined index is undefined.
6075     if (N1.isUndef() || N2.isUndef())
6076       return getUNDEF(VT);
6077 
6078     // EXTRACT_VECTOR_ELT of out-of-bounds element is an UNDEF for fixed length
6079     // vectors. For scalable vectors we will provide appropriate support for
6080     // dealing with arbitrary indices.
6081     if (N2C && N1.getValueType().isFixedLengthVector() &&
6082         N2C->getAPIntValue().uge(N1.getValueType().getVectorNumElements()))
6083       return getUNDEF(VT);
6084 
6085     // EXTRACT_VECTOR_ELT of CONCAT_VECTORS is often formed while lowering is
6086     // expanding copies of large vectors from registers. This only works for
6087     // fixed length vectors, since we need to know the exact number of
6088     // elements.
6089     if (N2C && N1.getOperand(0).getValueType().isFixedLengthVector() &&
6090         N1.getOpcode() == ISD::CONCAT_VECTORS && N1.getNumOperands() > 0) {
6091       unsigned Factor =
6092         N1.getOperand(0).getValueType().getVectorNumElements();
6093       return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
6094                      N1.getOperand(N2C->getZExtValue() / Factor),
6095                      getVectorIdxConstant(N2C->getZExtValue() % Factor, DL));
6096     }
6097 
6098     // EXTRACT_VECTOR_ELT of BUILD_VECTOR or SPLAT_VECTOR is often formed while
6099     // lowering is expanding large vector constants.
6100     if (N2C && (N1.getOpcode() == ISD::BUILD_VECTOR ||
6101                 N1.getOpcode() == ISD::SPLAT_VECTOR)) {
6102       assert((N1.getOpcode() != ISD::BUILD_VECTOR ||
6103               N1.getValueType().isFixedLengthVector()) &&
6104              "BUILD_VECTOR used for scalable vectors");
6105       unsigned Index =
6106           N1.getOpcode() == ISD::BUILD_VECTOR ? N2C->getZExtValue() : 0;
6107       SDValue Elt = N1.getOperand(Index);
6108 
6109       if (VT != Elt.getValueType())
6110         // If the vector element type is not legal, the BUILD_VECTOR operands
6111         // are promoted and implicitly truncated, and the result implicitly
6112         // extended. Make that explicit here.
6113         Elt = getAnyExtOrTrunc(Elt, DL, VT);
6114 
6115       return Elt;
6116     }
6117 
6118     // EXTRACT_VECTOR_ELT of INSERT_VECTOR_ELT is often formed when vector
6119     // operations are lowered to scalars.
6120     if (N1.getOpcode() == ISD::INSERT_VECTOR_ELT) {
6121       // If the indices are the same, return the inserted element else
6122       // if the indices are known different, extract the element from
6123       // the original vector.
6124       SDValue N1Op2 = N1.getOperand(2);
6125       ConstantSDNode *N1Op2C = dyn_cast<ConstantSDNode>(N1Op2);
6126 
6127       if (N1Op2C && N2C) {
6128         if (N1Op2C->getZExtValue() == N2C->getZExtValue()) {
6129           if (VT == N1.getOperand(1).getValueType())
6130             return N1.getOperand(1);
6131           return getSExtOrTrunc(N1.getOperand(1), DL, VT);
6132         }
6133         return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0), N2);
6134       }
6135     }
6136 
6137     // EXTRACT_VECTOR_ELT of v1iX EXTRACT_SUBVECTOR could be formed
6138     // when vector types are scalarized and v1iX is legal.
6139     // vextract (v1iX extract_subvector(vNiX, Idx)) -> vextract(vNiX,Idx).
6140     // Here we are completely ignoring the extract element index (N2),
6141     // which is fine for fixed width vectors, since any index other than 0
6142     // is undefined anyway. However, this cannot be ignored for scalable
6143     // vectors - in theory we could support this, but we don't want to do this
6144     // without a profitability check.
6145     if (N1.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
6146         N1.getValueType().isFixedLengthVector() &&
6147         N1.getValueType().getVectorNumElements() == 1) {
6148       return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0),
6149                      N1.getOperand(1));
6150     }
6151     break;
6152   case ISD::EXTRACT_ELEMENT:
6153     assert(N2C && (unsigned)N2C->getZExtValue() < 2 && "Bad EXTRACT_ELEMENT!");
6154     assert(!N1.getValueType().isVector() && !VT.isVector() &&
6155            (N1.getValueType().isInteger() == VT.isInteger()) &&
6156            N1.getValueType() != VT &&
6157            "Wrong types for EXTRACT_ELEMENT!");
6158 
6159     // EXTRACT_ELEMENT of BUILD_PAIR is often formed while legalize is expanding
6160     // 64-bit integers into 32-bit parts.  Instead of building the extract of
6161     // the BUILD_PAIR, only to have legalize rip it apart, just do it now.
6162     if (N1.getOpcode() == ISD::BUILD_PAIR)
6163       return N1.getOperand(N2C->getZExtValue());
6164 
6165     // EXTRACT_ELEMENT of a constant int is also very common.
6166     if (N1C) {
6167       unsigned ElementSize = VT.getSizeInBits();
6168       unsigned Shift = ElementSize * N2C->getZExtValue();
6169       const APInt &Val = N1C->getAPIntValue();
6170       return getConstant(Val.extractBits(ElementSize, Shift), DL, VT);
6171     }
6172     break;
6173   case ISD::EXTRACT_SUBVECTOR: {
6174     EVT N1VT = N1.getValueType();
6175     assert(VT.isVector() && N1VT.isVector() &&
6176            "Extract subvector VTs must be vectors!");
6177     assert(VT.getVectorElementType() == N1VT.getVectorElementType() &&
6178            "Extract subvector VTs must have the same element type!");
6179     assert((VT.isFixedLengthVector() || N1VT.isScalableVector()) &&
6180            "Cannot extract a scalable vector from a fixed length vector!");
6181     assert((VT.isScalableVector() != N1VT.isScalableVector() ||
6182             VT.getVectorMinNumElements() <= N1VT.getVectorMinNumElements()) &&
6183            "Extract subvector must be from larger vector to smaller vector!");
6184     assert(N2C && "Extract subvector index must be a constant");
6185     assert((VT.isScalableVector() != N1VT.isScalableVector() ||
6186             (VT.getVectorMinNumElements() + N2C->getZExtValue()) <=
6187                 N1VT.getVectorMinNumElements()) &&
6188            "Extract subvector overflow!");
6189     assert(N2C->getAPIntValue().getBitWidth() ==
6190                TLI->getVectorIdxTy(getDataLayout()).getFixedSizeInBits() &&
6191            "Constant index for EXTRACT_SUBVECTOR has an invalid size");
6192 
6193     // Trivial extraction.
6194     if (VT == N1VT)
6195       return N1;
6196 
6197     // EXTRACT_SUBVECTOR of an UNDEF is an UNDEF.
6198     if (N1.isUndef())
6199       return getUNDEF(VT);
6200 
6201     // EXTRACT_SUBVECTOR of CONCAT_VECTOR can be simplified if the pieces of
6202     // the concat have the same type as the extract.
6203     if (N1.getOpcode() == ISD::CONCAT_VECTORS && N1.getNumOperands() > 0 &&
6204         VT == N1.getOperand(0).getValueType()) {
6205       unsigned Factor = VT.getVectorMinNumElements();
6206       return N1.getOperand(N2C->getZExtValue() / Factor);
6207     }
6208 
6209     // EXTRACT_SUBVECTOR of INSERT_SUBVECTOR is often created
6210     // during shuffle legalization.
6211     if (N1.getOpcode() == ISD::INSERT_SUBVECTOR && N2 == N1.getOperand(2) &&
6212         VT == N1.getOperand(1).getValueType())
6213       return N1.getOperand(1);
6214     break;
6215   }
6216   }
6217 
6218   // Perform trivial constant folding.
6219   if (SDValue SV = FoldConstantArithmetic(Opcode, DL, VT, {N1, N2}))
6220     return SV;
6221 
6222   // Canonicalize an UNDEF to the RHS, even over a constant.
6223   if (N1.isUndef()) {
6224     if (TLI->isCommutativeBinOp(Opcode)) {
6225       std::swap(N1, N2);
6226     } else {
6227       switch (Opcode) {
6228       case ISD::SUB:
6229         return getUNDEF(VT);     // fold op(undef, arg2) -> undef
6230       case ISD::SIGN_EXTEND_INREG:
6231       case ISD::UDIV:
6232       case ISD::SDIV:
6233       case ISD::UREM:
6234       case ISD::SREM:
6235       case ISD::SSUBSAT:
6236       case ISD::USUBSAT:
6237         return getConstant(0, DL, VT);    // fold op(undef, arg2) -> 0
6238       }
6239     }
6240   }
6241 
6242   // Fold a bunch of operators when the RHS is undef.
6243   if (N2.isUndef()) {
6244     switch (Opcode) {
6245     case ISD::XOR:
6246       if (N1.isUndef())
6247         // Handle undef ^ undef -> 0 special case. This is a common
6248         // idiom (misuse).
6249         return getConstant(0, DL, VT);
6250       LLVM_FALLTHROUGH;
6251     case ISD::ADD:
6252     case ISD::SUB:
6253     case ISD::UDIV:
6254     case ISD::SDIV:
6255     case ISD::UREM:
6256     case ISD::SREM:
6257       return getUNDEF(VT);       // fold op(arg1, undef) -> undef
6258     case ISD::MUL:
6259     case ISD::AND:
6260     case ISD::SSUBSAT:
6261     case ISD::USUBSAT:
6262       return getConstant(0, DL, VT);  // fold op(arg1, undef) -> 0
6263     case ISD::OR:
6264     case ISD::SADDSAT:
6265     case ISD::UADDSAT:
6266       return getAllOnesConstant(DL, VT);
6267     }
6268   }
6269 
6270   // Memoize this node if possible.
6271   SDNode *N;
6272   SDVTList VTs = getVTList(VT);
6273   SDValue Ops[] = {N1, N2};
6274   if (VT != MVT::Glue) {
6275     FoldingSetNodeID ID;
6276     AddNodeIDNode(ID, Opcode, VTs, Ops);
6277     void *IP = nullptr;
6278     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
6279       E->intersectFlagsWith(Flags);
6280       return SDValue(E, 0);
6281     }
6282 
6283     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
6284     N->setFlags(Flags);
6285     createOperands(N, Ops);
6286     CSEMap.InsertNode(N, IP);
6287   } else {
6288     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
6289     createOperands(N, Ops);
6290   }
6291 
6292   InsertNode(N);
6293   SDValue V = SDValue(N, 0);
6294   NewSDValueDbgMsg(V, "Creating new node: ", this);
6295   return V;
6296 }
6297 
6298 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
6299                               SDValue N1, SDValue N2, SDValue N3) {
6300   SDNodeFlags Flags;
6301   if (Inserter)
6302     Flags = Inserter->getFlags();
6303   return getNode(Opcode, DL, VT, N1, N2, N3, Flags);
6304 }
6305 
6306 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
6307                               SDValue N1, SDValue N2, SDValue N3,
6308                               const SDNodeFlags Flags) {
6309   assert(N1.getOpcode() != ISD::DELETED_NODE &&
6310          N2.getOpcode() != ISD::DELETED_NODE &&
6311          N3.getOpcode() != ISD::DELETED_NODE &&
6312          "Operand is DELETED_NODE!");
6313   // Perform various simplifications.
6314   switch (Opcode) {
6315   case ISD::FMA: {
6316     assert(VT.isFloatingPoint() && "This operator only applies to FP types!");
6317     assert(N1.getValueType() == VT && N2.getValueType() == VT &&
6318            N3.getValueType() == VT && "FMA types must match!");
6319     ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6320     ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2);
6321     ConstantFPSDNode *N3CFP = dyn_cast<ConstantFPSDNode>(N3);
6322     if (N1CFP && N2CFP && N3CFP) {
6323       APFloat  V1 = N1CFP->getValueAPF();
6324       const APFloat &V2 = N2CFP->getValueAPF();
6325       const APFloat &V3 = N3CFP->getValueAPF();
6326       V1.fusedMultiplyAdd(V2, V3, APFloat::rmNearestTiesToEven);
6327       return getConstantFP(V1, DL, VT);
6328     }
6329     break;
6330   }
6331   case ISD::BUILD_VECTOR: {
6332     // Attempt to simplify BUILD_VECTOR.
6333     SDValue Ops[] = {N1, N2, N3};
6334     if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
6335       return V;
6336     break;
6337   }
6338   case ISD::CONCAT_VECTORS: {
6339     SDValue Ops[] = {N1, N2, N3};
6340     if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this))
6341       return V;
6342     break;
6343   }
6344   case ISD::SETCC: {
6345     assert(VT.isInteger() && "SETCC result type must be an integer!");
6346     assert(N1.getValueType() == N2.getValueType() &&
6347            "SETCC operands must have the same type!");
6348     assert(VT.isVector() == N1.getValueType().isVector() &&
6349            "SETCC type should be vector iff the operand type is vector!");
6350     assert((!VT.isVector() || VT.getVectorElementCount() ==
6351                                   N1.getValueType().getVectorElementCount()) &&
6352            "SETCC vector element counts must match!");
6353     // Use FoldSetCC to simplify SETCC's.
6354     if (SDValue V = FoldSetCC(VT, N1, N2, cast<CondCodeSDNode>(N3)->get(), DL))
6355       return V;
6356     // Vector constant folding.
6357     SDValue Ops[] = {N1, N2, N3};
6358     if (SDValue V = FoldConstantArithmetic(Opcode, DL, VT, Ops)) {
6359       NewSDValueDbgMsg(V, "New node vector constant folding: ", this);
6360       return V;
6361     }
6362     break;
6363   }
6364   case ISD::SELECT:
6365   case ISD::VSELECT:
6366     if (SDValue V = simplifySelect(N1, N2, N3))
6367       return V;
6368     break;
6369   case ISD::VECTOR_SHUFFLE:
6370     llvm_unreachable("should use getVectorShuffle constructor!");
6371   case ISD::VECTOR_SPLICE: {
6372     if (cast<ConstantSDNode>(N3)->isNullValue())
6373       return N1;
6374     break;
6375   }
6376   case ISD::INSERT_VECTOR_ELT: {
6377     ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3);
6378     // INSERT_VECTOR_ELT into out-of-bounds element is an UNDEF, except
6379     // for scalable vectors where we will generate appropriate code to
6380     // deal with out-of-bounds cases correctly.
6381     if (N3C && N1.getValueType().isFixedLengthVector() &&
6382         N3C->getZExtValue() >= N1.getValueType().getVectorNumElements())
6383       return getUNDEF(VT);
6384 
6385     // Undefined index can be assumed out-of-bounds, so that's UNDEF too.
6386     if (N3.isUndef())
6387       return getUNDEF(VT);
6388 
6389     // If the inserted element is an UNDEF, just use the input vector.
6390     if (N2.isUndef())
6391       return N1;
6392 
6393     break;
6394   }
6395   case ISD::INSERT_SUBVECTOR: {
6396     // Inserting undef into undef is still undef.
6397     if (N1.isUndef() && N2.isUndef())
6398       return getUNDEF(VT);
6399 
6400     EVT N2VT = N2.getValueType();
6401     assert(VT == N1.getValueType() &&
6402            "Dest and insert subvector source types must match!");
6403     assert(VT.isVector() && N2VT.isVector() &&
6404            "Insert subvector VTs must be vectors!");
6405     assert((VT.isScalableVector() || N2VT.isFixedLengthVector()) &&
6406            "Cannot insert a scalable vector into a fixed length vector!");
6407     assert((VT.isScalableVector() != N2VT.isScalableVector() ||
6408             VT.getVectorMinNumElements() >= N2VT.getVectorMinNumElements()) &&
6409            "Insert subvector must be from smaller vector to larger vector!");
6410     assert(isa<ConstantSDNode>(N3) &&
6411            "Insert subvector index must be constant");
6412     assert((VT.isScalableVector() != N2VT.isScalableVector() ||
6413             (N2VT.getVectorMinNumElements() +
6414              cast<ConstantSDNode>(N3)->getZExtValue()) <=
6415                 VT.getVectorMinNumElements()) &&
6416            "Insert subvector overflow!");
6417     assert(cast<ConstantSDNode>(N3)->getAPIntValue().getBitWidth() ==
6418                TLI->getVectorIdxTy(getDataLayout()).getFixedSizeInBits() &&
6419            "Constant index for INSERT_SUBVECTOR has an invalid size");
6420 
6421     // Trivial insertion.
6422     if (VT == N2VT)
6423       return N2;
6424 
6425     // If this is an insert of an extracted vector into an undef vector, we
6426     // can just use the input to the extract.
6427     if (N1.isUndef() && N2.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
6428         N2.getOperand(1) == N3 && N2.getOperand(0).getValueType() == VT)
6429       return N2.getOperand(0);
6430     break;
6431   }
6432   case ISD::BITCAST:
6433     // Fold bit_convert nodes from a type to themselves.
6434     if (N1.getValueType() == VT)
6435       return N1;
6436     break;
6437   }
6438 
6439   // Memoize node if it doesn't produce a flag.
6440   SDNode *N;
6441   SDVTList VTs = getVTList(VT);
6442   SDValue Ops[] = {N1, N2, N3};
6443   if (VT != MVT::Glue) {
6444     FoldingSetNodeID ID;
6445     AddNodeIDNode(ID, Opcode, VTs, Ops);
6446     void *IP = nullptr;
6447     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
6448       E->intersectFlagsWith(Flags);
6449       return SDValue(E, 0);
6450     }
6451 
6452     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
6453     N->setFlags(Flags);
6454     createOperands(N, Ops);
6455     CSEMap.InsertNode(N, IP);
6456   } else {
6457     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
6458     createOperands(N, Ops);
6459   }
6460 
6461   InsertNode(N);
6462   SDValue V = SDValue(N, 0);
6463   NewSDValueDbgMsg(V, "Creating new node: ", this);
6464   return V;
6465 }
6466 
6467 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
6468                               SDValue N1, SDValue N2, SDValue N3, SDValue N4) {
6469   SDValue Ops[] = { N1, N2, N3, N4 };
6470   return getNode(Opcode, DL, VT, Ops);
6471 }
6472 
6473 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
6474                               SDValue N1, SDValue N2, SDValue N3, SDValue N4,
6475                               SDValue N5) {
6476   SDValue Ops[] = { N1, N2, N3, N4, N5 };
6477   return getNode(Opcode, DL, VT, Ops);
6478 }
6479 
6480 /// getStackArgumentTokenFactor - Compute a TokenFactor to force all
6481 /// the incoming stack arguments to be loaded from the stack.
6482 SDValue SelectionDAG::getStackArgumentTokenFactor(SDValue Chain) {
6483   SmallVector<SDValue, 8> ArgChains;
6484 
6485   // Include the original chain at the beginning of the list. When this is
6486   // used by target LowerCall hooks, this helps legalize find the
6487   // CALLSEQ_BEGIN node.
6488   ArgChains.push_back(Chain);
6489 
6490   // Add a chain value for each stack argument.
6491   for (SDNode *U : getEntryNode().getNode()->uses())
6492     if (LoadSDNode *L = dyn_cast<LoadSDNode>(U))
6493       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
6494         if (FI->getIndex() < 0)
6495           ArgChains.push_back(SDValue(L, 1));
6496 
6497   // Build a tokenfactor for all the chains.
6498   return getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains);
6499 }
6500 
6501 /// getMemsetValue - Vectorized representation of the memset value
6502 /// operand.
6503 static SDValue getMemsetValue(SDValue Value, EVT VT, SelectionDAG &DAG,
6504                               const SDLoc &dl) {
6505   assert(!Value.isUndef());
6506 
6507   unsigned NumBits = VT.getScalarSizeInBits();
6508   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
6509     assert(C->getAPIntValue().getBitWidth() == 8);
6510     APInt Val = APInt::getSplat(NumBits, C->getAPIntValue());
6511     if (VT.isInteger()) {
6512       bool IsOpaque = VT.getSizeInBits() > 64 ||
6513           !DAG.getTargetLoweringInfo().isLegalStoreImmediate(C->getSExtValue());
6514       return DAG.getConstant(Val, dl, VT, false, IsOpaque);
6515     }
6516     return DAG.getConstantFP(APFloat(DAG.EVTToAPFloatSemantics(VT), Val), dl,
6517                              VT);
6518   }
6519 
6520   assert(Value.getValueType() == MVT::i8 && "memset with non-byte fill value?");
6521   EVT IntVT = VT.getScalarType();
6522   if (!IntVT.isInteger())
6523     IntVT = EVT::getIntegerVT(*DAG.getContext(), IntVT.getSizeInBits());
6524 
6525   Value = DAG.getNode(ISD::ZERO_EXTEND, dl, IntVT, Value);
6526   if (NumBits > 8) {
6527     // Use a multiplication with 0x010101... to extend the input to the
6528     // required length.
6529     APInt Magic = APInt::getSplat(NumBits, APInt(8, 0x01));
6530     Value = DAG.getNode(ISD::MUL, dl, IntVT, Value,
6531                         DAG.getConstant(Magic, dl, IntVT));
6532   }
6533 
6534   if (VT != Value.getValueType() && !VT.isInteger())
6535     Value = DAG.getBitcast(VT.getScalarType(), Value);
6536   if (VT != Value.getValueType())
6537     Value = DAG.getSplatBuildVector(VT, dl, Value);
6538 
6539   return Value;
6540 }
6541 
6542 /// getMemsetStringVal - Similar to getMemsetValue. Except this is only
6543 /// used when a memcpy is turned into a memset when the source is a constant
6544 /// string ptr.
6545 static SDValue getMemsetStringVal(EVT VT, const SDLoc &dl, SelectionDAG &DAG,
6546                                   const TargetLowering &TLI,
6547                                   const ConstantDataArraySlice &Slice) {
6548   // Handle vector with all elements zero.
6549   if (Slice.Array == nullptr) {
6550     if (VT.isInteger())
6551       return DAG.getConstant(0, dl, VT);
6552     if (VT == MVT::f32 || VT == MVT::f64 || VT == MVT::f128)
6553       return DAG.getConstantFP(0.0, dl, VT);
6554     if (VT.isVector()) {
6555       unsigned NumElts = VT.getVectorNumElements();
6556       MVT EltVT = (VT.getVectorElementType() == MVT::f32) ? MVT::i32 : MVT::i64;
6557       return DAG.getNode(ISD::BITCAST, dl, VT,
6558                          DAG.getConstant(0, dl,
6559                                          EVT::getVectorVT(*DAG.getContext(),
6560                                                           EltVT, NumElts)));
6561     }
6562     llvm_unreachable("Expected type!");
6563   }
6564 
6565   assert(!VT.isVector() && "Can't handle vector type here!");
6566   unsigned NumVTBits = VT.getSizeInBits();
6567   unsigned NumVTBytes = NumVTBits / 8;
6568   unsigned NumBytes = std::min(NumVTBytes, unsigned(Slice.Length));
6569 
6570   APInt Val(NumVTBits, 0);
6571   if (DAG.getDataLayout().isLittleEndian()) {
6572     for (unsigned i = 0; i != NumBytes; ++i)
6573       Val |= (uint64_t)(unsigned char)Slice[i] << i*8;
6574   } else {
6575     for (unsigned i = 0; i != NumBytes; ++i)
6576       Val |= (uint64_t)(unsigned char)Slice[i] << (NumVTBytes-i-1)*8;
6577   }
6578 
6579   // If the "cost" of materializing the integer immediate is less than the cost
6580   // of a load, then it is cost effective to turn the load into the immediate.
6581   Type *Ty = VT.getTypeForEVT(*DAG.getContext());
6582   if (TLI.shouldConvertConstantLoadToIntImm(Val, Ty))
6583     return DAG.getConstant(Val, dl, VT);
6584   return SDValue();
6585 }
6586 
6587 SDValue SelectionDAG::getMemBasePlusOffset(SDValue Base, TypeSize Offset,
6588                                            const SDLoc &DL,
6589                                            const SDNodeFlags Flags) {
6590   EVT VT = Base.getValueType();
6591   SDValue Index;
6592 
6593   if (Offset.isScalable())
6594     Index = getVScale(DL, Base.getValueType(),
6595                       APInt(Base.getValueSizeInBits().getFixedSize(),
6596                             Offset.getKnownMinSize()));
6597   else
6598     Index = getConstant(Offset.getFixedSize(), DL, VT);
6599 
6600   return getMemBasePlusOffset(Base, Index, DL, Flags);
6601 }
6602 
6603 SDValue SelectionDAG::getMemBasePlusOffset(SDValue Ptr, SDValue Offset,
6604                                            const SDLoc &DL,
6605                                            const SDNodeFlags Flags) {
6606   assert(Offset.getValueType().isInteger());
6607   EVT BasePtrVT = Ptr.getValueType();
6608   return getNode(ISD::ADD, DL, BasePtrVT, Ptr, Offset, Flags);
6609 }
6610 
6611 /// Returns true if memcpy source is constant data.
6612 static bool isMemSrcFromConstant(SDValue Src, ConstantDataArraySlice &Slice) {
6613   uint64_t SrcDelta = 0;
6614   GlobalAddressSDNode *G = nullptr;
6615   if (Src.getOpcode() == ISD::GlobalAddress)
6616     G = cast<GlobalAddressSDNode>(Src);
6617   else if (Src.getOpcode() == ISD::ADD &&
6618            Src.getOperand(0).getOpcode() == ISD::GlobalAddress &&
6619            Src.getOperand(1).getOpcode() == ISD::Constant) {
6620     G = cast<GlobalAddressSDNode>(Src.getOperand(0));
6621     SrcDelta = cast<ConstantSDNode>(Src.getOperand(1))->getZExtValue();
6622   }
6623   if (!G)
6624     return false;
6625 
6626   return getConstantDataArrayInfo(G->getGlobal(), Slice, 8,
6627                                   SrcDelta + G->getOffset());
6628 }
6629 
6630 static bool shouldLowerMemFuncForSize(const MachineFunction &MF,
6631                                       SelectionDAG &DAG) {
6632   // On Darwin, -Os means optimize for size without hurting performance, so
6633   // only really optimize for size when -Oz (MinSize) is used.
6634   if (MF.getTarget().getTargetTriple().isOSDarwin())
6635     return MF.getFunction().hasMinSize();
6636   return DAG.shouldOptForSize();
6637 }
6638 
6639 static void chainLoadsAndStoresForMemcpy(SelectionDAG &DAG, const SDLoc &dl,
6640                           SmallVector<SDValue, 32> &OutChains, unsigned From,
6641                           unsigned To, SmallVector<SDValue, 16> &OutLoadChains,
6642                           SmallVector<SDValue, 16> &OutStoreChains) {
6643   assert(OutLoadChains.size() && "Missing loads in memcpy inlining");
6644   assert(OutStoreChains.size() && "Missing stores in memcpy inlining");
6645   SmallVector<SDValue, 16> GluedLoadChains;
6646   for (unsigned i = From; i < To; ++i) {
6647     OutChains.push_back(OutLoadChains[i]);
6648     GluedLoadChains.push_back(OutLoadChains[i]);
6649   }
6650 
6651   // Chain for all loads.
6652   SDValue LoadToken = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
6653                                   GluedLoadChains);
6654 
6655   for (unsigned i = From; i < To; ++i) {
6656     StoreSDNode *ST = dyn_cast<StoreSDNode>(OutStoreChains[i]);
6657     SDValue NewStore = DAG.getTruncStore(LoadToken, dl, ST->getValue(),
6658                                   ST->getBasePtr(), ST->getMemoryVT(),
6659                                   ST->getMemOperand());
6660     OutChains.push_back(NewStore);
6661   }
6662 }
6663 
6664 static SDValue getMemcpyLoadsAndStores(SelectionDAG &DAG, const SDLoc &dl,
6665                                        SDValue Chain, SDValue Dst, SDValue Src,
6666                                        uint64_t Size, Align Alignment,
6667                                        bool isVol, bool AlwaysInline,
6668                                        MachinePointerInfo DstPtrInfo,
6669                                        MachinePointerInfo SrcPtrInfo,
6670                                        const AAMDNodes &AAInfo) {
6671   // Turn a memcpy of undef to nop.
6672   // FIXME: We need to honor volatile even is Src is undef.
6673   if (Src.isUndef())
6674     return Chain;
6675 
6676   // Expand memcpy to a series of load and store ops if the size operand falls
6677   // below a certain threshold.
6678   // TODO: In the AlwaysInline case, if the size is big then generate a loop
6679   // rather than maybe a humongous number of loads and stores.
6680   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6681   const DataLayout &DL = DAG.getDataLayout();
6682   LLVMContext &C = *DAG.getContext();
6683   std::vector<EVT> MemOps;
6684   bool DstAlignCanChange = false;
6685   MachineFunction &MF = DAG.getMachineFunction();
6686   MachineFrameInfo &MFI = MF.getFrameInfo();
6687   bool OptSize = shouldLowerMemFuncForSize(MF, DAG);
6688   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
6689   if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
6690     DstAlignCanChange = true;
6691   MaybeAlign SrcAlign = DAG.InferPtrAlign(Src);
6692   if (!SrcAlign || Alignment > *SrcAlign)
6693     SrcAlign = Alignment;
6694   assert(SrcAlign && "SrcAlign must be set");
6695   ConstantDataArraySlice Slice;
6696   // If marked as volatile, perform a copy even when marked as constant.
6697   bool CopyFromConstant = !isVol && isMemSrcFromConstant(Src, Slice);
6698   bool isZeroConstant = CopyFromConstant && Slice.Array == nullptr;
6699   unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemcpy(OptSize);
6700   const MemOp Op = isZeroConstant
6701                        ? MemOp::Set(Size, DstAlignCanChange, Alignment,
6702                                     /*IsZeroMemset*/ true, isVol)
6703                        : MemOp::Copy(Size, DstAlignCanChange, Alignment,
6704                                      *SrcAlign, isVol, CopyFromConstant);
6705   if (!TLI.findOptimalMemOpLowering(
6706           MemOps, Limit, Op, DstPtrInfo.getAddrSpace(),
6707           SrcPtrInfo.getAddrSpace(), MF.getFunction().getAttributes()))
6708     return SDValue();
6709 
6710   if (DstAlignCanChange) {
6711     Type *Ty = MemOps[0].getTypeForEVT(C);
6712     Align NewAlign = DL.getABITypeAlign(Ty);
6713 
6714     // Don't promote to an alignment that would require dynamic stack
6715     // realignment.
6716     const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
6717     if (!TRI->hasStackRealignment(MF))
6718       while (NewAlign > Alignment && DL.exceedsNaturalStackAlignment(NewAlign))
6719         NewAlign = NewAlign / 2;
6720 
6721     if (NewAlign > Alignment) {
6722       // Give the stack frame object a larger alignment if needed.
6723       if (MFI.getObjectAlign(FI->getIndex()) < NewAlign)
6724         MFI.setObjectAlignment(FI->getIndex(), NewAlign);
6725       Alignment = NewAlign;
6726     }
6727   }
6728 
6729   // Prepare AAInfo for loads/stores after lowering this memcpy.
6730   AAMDNodes NewAAInfo = AAInfo;
6731   NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr;
6732 
6733   MachineMemOperand::Flags MMOFlags =
6734       isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone;
6735   SmallVector<SDValue, 16> OutLoadChains;
6736   SmallVector<SDValue, 16> OutStoreChains;
6737   SmallVector<SDValue, 32> OutChains;
6738   unsigned NumMemOps = MemOps.size();
6739   uint64_t SrcOff = 0, DstOff = 0;
6740   for (unsigned i = 0; i != NumMemOps; ++i) {
6741     EVT VT = MemOps[i];
6742     unsigned VTSize = VT.getSizeInBits() / 8;
6743     SDValue Value, Store;
6744 
6745     if (VTSize > Size) {
6746       // Issuing an unaligned load / store pair  that overlaps with the previous
6747       // pair. Adjust the offset accordingly.
6748       assert(i == NumMemOps-1 && i != 0);
6749       SrcOff -= VTSize - Size;
6750       DstOff -= VTSize - Size;
6751     }
6752 
6753     if (CopyFromConstant &&
6754         (isZeroConstant || (VT.isInteger() && !VT.isVector()))) {
6755       // It's unlikely a store of a vector immediate can be done in a single
6756       // instruction. It would require a load from a constantpool first.
6757       // We only handle zero vectors here.
6758       // FIXME: Handle other cases where store of vector immediate is done in
6759       // a single instruction.
6760       ConstantDataArraySlice SubSlice;
6761       if (SrcOff < Slice.Length) {
6762         SubSlice = Slice;
6763         SubSlice.move(SrcOff);
6764       } else {
6765         // This is an out-of-bounds access and hence UB. Pretend we read zero.
6766         SubSlice.Array = nullptr;
6767         SubSlice.Offset = 0;
6768         SubSlice.Length = VTSize;
6769       }
6770       Value = getMemsetStringVal(VT, dl, DAG, TLI, SubSlice);
6771       if (Value.getNode()) {
6772         Store = DAG.getStore(
6773             Chain, dl, Value,
6774             DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl),
6775             DstPtrInfo.getWithOffset(DstOff), Alignment, MMOFlags, NewAAInfo);
6776         OutChains.push_back(Store);
6777       }
6778     }
6779 
6780     if (!Store.getNode()) {
6781       // The type might not be legal for the target.  This should only happen
6782       // if the type is smaller than a legal type, as on PPC, so the right
6783       // thing to do is generate a LoadExt/StoreTrunc pair.  These simplify
6784       // to Load/Store if NVT==VT.
6785       // FIXME does the case above also need this?
6786       EVT NVT = TLI.getTypeToTransformTo(C, VT);
6787       assert(NVT.bitsGE(VT));
6788 
6789       bool isDereferenceable =
6790         SrcPtrInfo.getWithOffset(SrcOff).isDereferenceable(VTSize, C, DL);
6791       MachineMemOperand::Flags SrcMMOFlags = MMOFlags;
6792       if (isDereferenceable)
6793         SrcMMOFlags |= MachineMemOperand::MODereferenceable;
6794 
6795       Value = DAG.getExtLoad(
6796           ISD::EXTLOAD, dl, NVT, Chain,
6797           DAG.getMemBasePlusOffset(Src, TypeSize::Fixed(SrcOff), dl),
6798           SrcPtrInfo.getWithOffset(SrcOff), VT,
6799           commonAlignment(*SrcAlign, SrcOff), SrcMMOFlags, NewAAInfo);
6800       OutLoadChains.push_back(Value.getValue(1));
6801 
6802       Store = DAG.getTruncStore(
6803           Chain, dl, Value,
6804           DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl),
6805           DstPtrInfo.getWithOffset(DstOff), VT, Alignment, MMOFlags, NewAAInfo);
6806       OutStoreChains.push_back(Store);
6807     }
6808     SrcOff += VTSize;
6809     DstOff += VTSize;
6810     Size -= VTSize;
6811   }
6812 
6813   unsigned GluedLdStLimit = MaxLdStGlue == 0 ?
6814                                 TLI.getMaxGluedStoresPerMemcpy() : MaxLdStGlue;
6815   unsigned NumLdStInMemcpy = OutStoreChains.size();
6816 
6817   if (NumLdStInMemcpy) {
6818     // It may be that memcpy might be converted to memset if it's memcpy
6819     // of constants. In such a case, we won't have loads and stores, but
6820     // just stores. In the absence of loads, there is nothing to gang up.
6821     if ((GluedLdStLimit <= 1) || !EnableMemCpyDAGOpt) {
6822       // If target does not care, just leave as it.
6823       for (unsigned i = 0; i < NumLdStInMemcpy; ++i) {
6824         OutChains.push_back(OutLoadChains[i]);
6825         OutChains.push_back(OutStoreChains[i]);
6826       }
6827     } else {
6828       // Ld/St less than/equal limit set by target.
6829       if (NumLdStInMemcpy <= GluedLdStLimit) {
6830           chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, 0,
6831                                         NumLdStInMemcpy, OutLoadChains,
6832                                         OutStoreChains);
6833       } else {
6834         unsigned NumberLdChain =  NumLdStInMemcpy / GluedLdStLimit;
6835         unsigned RemainingLdStInMemcpy = NumLdStInMemcpy % GluedLdStLimit;
6836         unsigned GlueIter = 0;
6837 
6838         for (unsigned cnt = 0; cnt < NumberLdChain; ++cnt) {
6839           unsigned IndexFrom = NumLdStInMemcpy - GlueIter - GluedLdStLimit;
6840           unsigned IndexTo   = NumLdStInMemcpy - GlueIter;
6841 
6842           chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, IndexFrom, IndexTo,
6843                                        OutLoadChains, OutStoreChains);
6844           GlueIter += GluedLdStLimit;
6845         }
6846 
6847         // Residual ld/st.
6848         if (RemainingLdStInMemcpy) {
6849           chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, 0,
6850                                         RemainingLdStInMemcpy, OutLoadChains,
6851                                         OutStoreChains);
6852         }
6853       }
6854     }
6855   }
6856   return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
6857 }
6858 
6859 static SDValue getMemmoveLoadsAndStores(SelectionDAG &DAG, const SDLoc &dl,
6860                                         SDValue Chain, SDValue Dst, SDValue Src,
6861                                         uint64_t Size, Align Alignment,
6862                                         bool isVol, bool AlwaysInline,
6863                                         MachinePointerInfo DstPtrInfo,
6864                                         MachinePointerInfo SrcPtrInfo,
6865                                         const AAMDNodes &AAInfo) {
6866   // Turn a memmove of undef to nop.
6867   // FIXME: We need to honor volatile even is Src is undef.
6868   if (Src.isUndef())
6869     return Chain;
6870 
6871   // Expand memmove to a series of load and store ops if the size operand falls
6872   // below a certain threshold.
6873   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6874   const DataLayout &DL = DAG.getDataLayout();
6875   LLVMContext &C = *DAG.getContext();
6876   std::vector<EVT> MemOps;
6877   bool DstAlignCanChange = false;
6878   MachineFunction &MF = DAG.getMachineFunction();
6879   MachineFrameInfo &MFI = MF.getFrameInfo();
6880   bool OptSize = shouldLowerMemFuncForSize(MF, DAG);
6881   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
6882   if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
6883     DstAlignCanChange = true;
6884   MaybeAlign SrcAlign = DAG.InferPtrAlign(Src);
6885   if (!SrcAlign || Alignment > *SrcAlign)
6886     SrcAlign = Alignment;
6887   assert(SrcAlign && "SrcAlign must be set");
6888   unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemmove(OptSize);
6889   if (!TLI.findOptimalMemOpLowering(
6890           MemOps, Limit,
6891           MemOp::Copy(Size, DstAlignCanChange, Alignment, *SrcAlign,
6892                       /*IsVolatile*/ true),
6893           DstPtrInfo.getAddrSpace(), SrcPtrInfo.getAddrSpace(),
6894           MF.getFunction().getAttributes()))
6895     return SDValue();
6896 
6897   if (DstAlignCanChange) {
6898     Type *Ty = MemOps[0].getTypeForEVT(C);
6899     Align NewAlign = DL.getABITypeAlign(Ty);
6900     if (NewAlign > Alignment) {
6901       // Give the stack frame object a larger alignment if needed.
6902       if (MFI.getObjectAlign(FI->getIndex()) < NewAlign)
6903         MFI.setObjectAlignment(FI->getIndex(), NewAlign);
6904       Alignment = NewAlign;
6905     }
6906   }
6907 
6908   // Prepare AAInfo for loads/stores after lowering this memmove.
6909   AAMDNodes NewAAInfo = AAInfo;
6910   NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr;
6911 
6912   MachineMemOperand::Flags MMOFlags =
6913       isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone;
6914   uint64_t SrcOff = 0, DstOff = 0;
6915   SmallVector<SDValue, 8> LoadValues;
6916   SmallVector<SDValue, 8> LoadChains;
6917   SmallVector<SDValue, 8> OutChains;
6918   unsigned NumMemOps = MemOps.size();
6919   for (unsigned i = 0; i < NumMemOps; i++) {
6920     EVT VT = MemOps[i];
6921     unsigned VTSize = VT.getSizeInBits() / 8;
6922     SDValue Value;
6923 
6924     bool isDereferenceable =
6925       SrcPtrInfo.getWithOffset(SrcOff).isDereferenceable(VTSize, C, DL);
6926     MachineMemOperand::Flags SrcMMOFlags = MMOFlags;
6927     if (isDereferenceable)
6928       SrcMMOFlags |= MachineMemOperand::MODereferenceable;
6929 
6930     Value = DAG.getLoad(
6931         VT, dl, Chain,
6932         DAG.getMemBasePlusOffset(Src, TypeSize::Fixed(SrcOff), dl),
6933         SrcPtrInfo.getWithOffset(SrcOff), *SrcAlign, SrcMMOFlags, NewAAInfo);
6934     LoadValues.push_back(Value);
6935     LoadChains.push_back(Value.getValue(1));
6936     SrcOff += VTSize;
6937   }
6938   Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
6939   OutChains.clear();
6940   for (unsigned i = 0; i < NumMemOps; i++) {
6941     EVT VT = MemOps[i];
6942     unsigned VTSize = VT.getSizeInBits() / 8;
6943     SDValue Store;
6944 
6945     Store = DAG.getStore(
6946         Chain, dl, LoadValues[i],
6947         DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl),
6948         DstPtrInfo.getWithOffset(DstOff), Alignment, MMOFlags, NewAAInfo);
6949     OutChains.push_back(Store);
6950     DstOff += VTSize;
6951   }
6952 
6953   return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
6954 }
6955 
6956 /// Lower the call to 'memset' intrinsic function into a series of store
6957 /// operations.
6958 ///
6959 /// \param DAG Selection DAG where lowered code is placed.
6960 /// \param dl Link to corresponding IR location.
6961 /// \param Chain Control flow dependency.
6962 /// \param Dst Pointer to destination memory location.
6963 /// \param Src Value of byte to write into the memory.
6964 /// \param Size Number of bytes to write.
6965 /// \param Alignment Alignment of the destination in bytes.
6966 /// \param isVol True if destination is volatile.
6967 /// \param DstPtrInfo IR information on the memory pointer.
6968 /// \returns New head in the control flow, if lowering was successful, empty
6969 /// SDValue otherwise.
6970 ///
6971 /// The function tries to replace 'llvm.memset' intrinsic with several store
6972 /// operations and value calculation code. This is usually profitable for small
6973 /// memory size.
6974 static SDValue getMemsetStores(SelectionDAG &DAG, const SDLoc &dl,
6975                                SDValue Chain, SDValue Dst, SDValue Src,
6976                                uint64_t Size, Align Alignment, bool isVol,
6977                                MachinePointerInfo DstPtrInfo,
6978                                const AAMDNodes &AAInfo) {
6979   // Turn a memset of undef to nop.
6980   // FIXME: We need to honor volatile even is Src is undef.
6981   if (Src.isUndef())
6982     return Chain;
6983 
6984   // Expand memset to a series of load/store ops if the size operand
6985   // falls below a certain threshold.
6986   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6987   std::vector<EVT> MemOps;
6988   bool DstAlignCanChange = false;
6989   MachineFunction &MF = DAG.getMachineFunction();
6990   MachineFrameInfo &MFI = MF.getFrameInfo();
6991   bool OptSize = shouldLowerMemFuncForSize(MF, DAG);
6992   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
6993   if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
6994     DstAlignCanChange = true;
6995   bool IsZeroVal =
6996       isa<ConstantSDNode>(Src) && cast<ConstantSDNode>(Src)->isZero();
6997   if (!TLI.findOptimalMemOpLowering(
6998           MemOps, TLI.getMaxStoresPerMemset(OptSize),
6999           MemOp::Set(Size, DstAlignCanChange, Alignment, IsZeroVal, isVol),
7000           DstPtrInfo.getAddrSpace(), ~0u, MF.getFunction().getAttributes()))
7001     return SDValue();
7002 
7003   if (DstAlignCanChange) {
7004     Type *Ty = MemOps[0].getTypeForEVT(*DAG.getContext());
7005     Align NewAlign = DAG.getDataLayout().getABITypeAlign(Ty);
7006     if (NewAlign > Alignment) {
7007       // Give the stack frame object a larger alignment if needed.
7008       if (MFI.getObjectAlign(FI->getIndex()) < NewAlign)
7009         MFI.setObjectAlignment(FI->getIndex(), NewAlign);
7010       Alignment = NewAlign;
7011     }
7012   }
7013 
7014   SmallVector<SDValue, 8> OutChains;
7015   uint64_t DstOff = 0;
7016   unsigned NumMemOps = MemOps.size();
7017 
7018   // Find the largest store and generate the bit pattern for it.
7019   EVT LargestVT = MemOps[0];
7020   for (unsigned i = 1; i < NumMemOps; i++)
7021     if (MemOps[i].bitsGT(LargestVT))
7022       LargestVT = MemOps[i];
7023   SDValue MemSetValue = getMemsetValue(Src, LargestVT, DAG, dl);
7024 
7025   // Prepare AAInfo for loads/stores after lowering this memset.
7026   AAMDNodes NewAAInfo = AAInfo;
7027   NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr;
7028 
7029   for (unsigned i = 0; i < NumMemOps; i++) {
7030     EVT VT = MemOps[i];
7031     unsigned VTSize = VT.getSizeInBits() / 8;
7032     if (VTSize > Size) {
7033       // Issuing an unaligned load / store pair  that overlaps with the previous
7034       // pair. Adjust the offset accordingly.
7035       assert(i == NumMemOps-1 && i != 0);
7036       DstOff -= VTSize - Size;
7037     }
7038 
7039     // If this store is smaller than the largest store see whether we can get
7040     // the smaller value for free with a truncate.
7041     SDValue Value = MemSetValue;
7042     if (VT.bitsLT(LargestVT)) {
7043       if (!LargestVT.isVector() && !VT.isVector() &&
7044           TLI.isTruncateFree(LargestVT, VT))
7045         Value = DAG.getNode(ISD::TRUNCATE, dl, VT, MemSetValue);
7046       else
7047         Value = getMemsetValue(Src, VT, DAG, dl);
7048     }
7049     assert(Value.getValueType() == VT && "Value with wrong type.");
7050     SDValue Store = DAG.getStore(
7051         Chain, dl, Value,
7052         DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl),
7053         DstPtrInfo.getWithOffset(DstOff), Alignment,
7054         isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone,
7055         NewAAInfo);
7056     OutChains.push_back(Store);
7057     DstOff += VT.getSizeInBits() / 8;
7058     Size -= VTSize;
7059   }
7060 
7061   return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
7062 }
7063 
7064 static void checkAddrSpaceIsValidForLibcall(const TargetLowering *TLI,
7065                                             unsigned AS) {
7066   // Lowering memcpy / memset / memmove intrinsics to calls is only valid if all
7067   // pointer operands can be losslessly bitcasted to pointers of address space 0
7068   if (AS != 0 && !TLI->getTargetMachine().isNoopAddrSpaceCast(AS, 0)) {
7069     report_fatal_error("cannot lower memory intrinsic in address space " +
7070                        Twine(AS));
7071   }
7072 }
7073 
7074 SDValue SelectionDAG::getMemcpy(SDValue Chain, const SDLoc &dl, SDValue Dst,
7075                                 SDValue Src, SDValue Size, Align Alignment,
7076                                 bool isVol, bool AlwaysInline, bool isTailCall,
7077                                 MachinePointerInfo DstPtrInfo,
7078                                 MachinePointerInfo SrcPtrInfo,
7079                                 const AAMDNodes &AAInfo) {
7080   // Check to see if we should lower the memcpy to loads and stores first.
7081   // For cases within the target-specified limits, this is the best choice.
7082   ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
7083   if (ConstantSize) {
7084     // Memcpy with size zero? Just return the original chain.
7085     if (ConstantSize->isZero())
7086       return Chain;
7087 
7088     SDValue Result = getMemcpyLoadsAndStores(
7089         *this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), Alignment,
7090         isVol, false, DstPtrInfo, SrcPtrInfo, AAInfo);
7091     if (Result.getNode())
7092       return Result;
7093   }
7094 
7095   // Then check to see if we should lower the memcpy with target-specific
7096   // code. If the target chooses to do this, this is the next best.
7097   if (TSI) {
7098     SDValue Result = TSI->EmitTargetCodeForMemcpy(
7099         *this, dl, Chain, Dst, Src, Size, Alignment, isVol, AlwaysInline,
7100         DstPtrInfo, SrcPtrInfo);
7101     if (Result.getNode())
7102       return Result;
7103   }
7104 
7105   // If we really need inline code and the target declined to provide it,
7106   // use a (potentially long) sequence of loads and stores.
7107   if (AlwaysInline) {
7108     assert(ConstantSize && "AlwaysInline requires a constant size!");
7109     return getMemcpyLoadsAndStores(*this, dl, Chain, Dst, Src,
7110                                    ConstantSize->getZExtValue(), Alignment,
7111                                    isVol, true, DstPtrInfo, SrcPtrInfo, AAInfo);
7112   }
7113 
7114   checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace());
7115   checkAddrSpaceIsValidForLibcall(TLI, SrcPtrInfo.getAddrSpace());
7116 
7117   // FIXME: If the memcpy is volatile (isVol), lowering it to a plain libc
7118   // memcpy is not guaranteed to be safe. libc memcpys aren't required to
7119   // respect volatile, so they may do things like read or write memory
7120   // beyond the given memory regions. But fixing this isn't easy, and most
7121   // people don't care.
7122 
7123   // Emit a library call.
7124   TargetLowering::ArgListTy Args;
7125   TargetLowering::ArgListEntry Entry;
7126   Entry.Ty = Type::getInt8PtrTy(*getContext());
7127   Entry.Node = Dst; Args.push_back(Entry);
7128   Entry.Node = Src; Args.push_back(Entry);
7129 
7130   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
7131   Entry.Node = Size; Args.push_back(Entry);
7132   // FIXME: pass in SDLoc
7133   TargetLowering::CallLoweringInfo CLI(*this);
7134   CLI.setDebugLoc(dl)
7135       .setChain(Chain)
7136       .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMCPY),
7137                     Dst.getValueType().getTypeForEVT(*getContext()),
7138                     getExternalSymbol(TLI->getLibcallName(RTLIB::MEMCPY),
7139                                       TLI->getPointerTy(getDataLayout())),
7140                     std::move(Args))
7141       .setDiscardResult()
7142       .setTailCall(isTailCall);
7143 
7144   std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
7145   return CallResult.second;
7146 }
7147 
7148 SDValue SelectionDAG::getAtomicMemcpy(SDValue Chain, const SDLoc &dl,
7149                                       SDValue Dst, unsigned DstAlign,
7150                                       SDValue Src, unsigned SrcAlign,
7151                                       SDValue Size, Type *SizeTy,
7152                                       unsigned ElemSz, bool isTailCall,
7153                                       MachinePointerInfo DstPtrInfo,
7154                                       MachinePointerInfo SrcPtrInfo) {
7155   // Emit a library call.
7156   TargetLowering::ArgListTy Args;
7157   TargetLowering::ArgListEntry Entry;
7158   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
7159   Entry.Node = Dst;
7160   Args.push_back(Entry);
7161 
7162   Entry.Node = Src;
7163   Args.push_back(Entry);
7164 
7165   Entry.Ty = SizeTy;
7166   Entry.Node = Size;
7167   Args.push_back(Entry);
7168 
7169   RTLIB::Libcall LibraryCall =
7170       RTLIB::getMEMCPY_ELEMENT_UNORDERED_ATOMIC(ElemSz);
7171   if (LibraryCall == RTLIB::UNKNOWN_LIBCALL)
7172     report_fatal_error("Unsupported element size");
7173 
7174   TargetLowering::CallLoweringInfo CLI(*this);
7175   CLI.setDebugLoc(dl)
7176       .setChain(Chain)
7177       .setLibCallee(TLI->getLibcallCallingConv(LibraryCall),
7178                     Type::getVoidTy(*getContext()),
7179                     getExternalSymbol(TLI->getLibcallName(LibraryCall),
7180                                       TLI->getPointerTy(getDataLayout())),
7181                     std::move(Args))
7182       .setDiscardResult()
7183       .setTailCall(isTailCall);
7184 
7185   std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
7186   return CallResult.second;
7187 }
7188 
7189 SDValue SelectionDAG::getMemmove(SDValue Chain, const SDLoc &dl, SDValue Dst,
7190                                  SDValue Src, SDValue Size, Align Alignment,
7191                                  bool isVol, bool isTailCall,
7192                                  MachinePointerInfo DstPtrInfo,
7193                                  MachinePointerInfo SrcPtrInfo,
7194                                  const AAMDNodes &AAInfo) {
7195   // Check to see if we should lower the memmove to loads and stores first.
7196   // For cases within the target-specified limits, this is the best choice.
7197   ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
7198   if (ConstantSize) {
7199     // Memmove with size zero? Just return the original chain.
7200     if (ConstantSize->isZero())
7201       return Chain;
7202 
7203     SDValue Result = getMemmoveLoadsAndStores(
7204         *this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), Alignment,
7205         isVol, false, DstPtrInfo, SrcPtrInfo, AAInfo);
7206     if (Result.getNode())
7207       return Result;
7208   }
7209 
7210   // Then check to see if we should lower the memmove with target-specific
7211   // code. If the target chooses to do this, this is the next best.
7212   if (TSI) {
7213     SDValue Result =
7214         TSI->EmitTargetCodeForMemmove(*this, dl, Chain, Dst, Src, Size,
7215                                       Alignment, isVol, DstPtrInfo, SrcPtrInfo);
7216     if (Result.getNode())
7217       return Result;
7218   }
7219 
7220   checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace());
7221   checkAddrSpaceIsValidForLibcall(TLI, SrcPtrInfo.getAddrSpace());
7222 
7223   // FIXME: If the memmove is volatile, lowering it to plain libc memmove may
7224   // not be safe.  See memcpy above for more details.
7225 
7226   // Emit a library call.
7227   TargetLowering::ArgListTy Args;
7228   TargetLowering::ArgListEntry Entry;
7229   Entry.Ty = Type::getInt8PtrTy(*getContext());
7230   Entry.Node = Dst; Args.push_back(Entry);
7231   Entry.Node = Src; Args.push_back(Entry);
7232 
7233   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
7234   Entry.Node = Size; Args.push_back(Entry);
7235   // FIXME:  pass in SDLoc
7236   TargetLowering::CallLoweringInfo CLI(*this);
7237   CLI.setDebugLoc(dl)
7238       .setChain(Chain)
7239       .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMMOVE),
7240                     Dst.getValueType().getTypeForEVT(*getContext()),
7241                     getExternalSymbol(TLI->getLibcallName(RTLIB::MEMMOVE),
7242                                       TLI->getPointerTy(getDataLayout())),
7243                     std::move(Args))
7244       .setDiscardResult()
7245       .setTailCall(isTailCall);
7246 
7247   std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
7248   return CallResult.second;
7249 }
7250 
7251 SDValue SelectionDAG::getAtomicMemmove(SDValue Chain, const SDLoc &dl,
7252                                        SDValue Dst, unsigned DstAlign,
7253                                        SDValue Src, unsigned SrcAlign,
7254                                        SDValue Size, Type *SizeTy,
7255                                        unsigned ElemSz, bool isTailCall,
7256                                        MachinePointerInfo DstPtrInfo,
7257                                        MachinePointerInfo SrcPtrInfo) {
7258   // Emit a library call.
7259   TargetLowering::ArgListTy Args;
7260   TargetLowering::ArgListEntry Entry;
7261   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
7262   Entry.Node = Dst;
7263   Args.push_back(Entry);
7264 
7265   Entry.Node = Src;
7266   Args.push_back(Entry);
7267 
7268   Entry.Ty = SizeTy;
7269   Entry.Node = Size;
7270   Args.push_back(Entry);
7271 
7272   RTLIB::Libcall LibraryCall =
7273       RTLIB::getMEMMOVE_ELEMENT_UNORDERED_ATOMIC(ElemSz);
7274   if (LibraryCall == RTLIB::UNKNOWN_LIBCALL)
7275     report_fatal_error("Unsupported element size");
7276 
7277   TargetLowering::CallLoweringInfo CLI(*this);
7278   CLI.setDebugLoc(dl)
7279       .setChain(Chain)
7280       .setLibCallee(TLI->getLibcallCallingConv(LibraryCall),
7281                     Type::getVoidTy(*getContext()),
7282                     getExternalSymbol(TLI->getLibcallName(LibraryCall),
7283                                       TLI->getPointerTy(getDataLayout())),
7284                     std::move(Args))
7285       .setDiscardResult()
7286       .setTailCall(isTailCall);
7287 
7288   std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
7289   return CallResult.second;
7290 }
7291 
7292 SDValue SelectionDAG::getMemset(SDValue Chain, const SDLoc &dl, SDValue Dst,
7293                                 SDValue Src, SDValue Size, Align Alignment,
7294                                 bool isVol, bool isTailCall,
7295                                 MachinePointerInfo DstPtrInfo,
7296                                 const AAMDNodes &AAInfo) {
7297   // Check to see if we should lower the memset to stores first.
7298   // For cases within the target-specified limits, this is the best choice.
7299   ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
7300   if (ConstantSize) {
7301     // Memset with size zero? Just return the original chain.
7302     if (ConstantSize->isZero())
7303       return Chain;
7304 
7305     SDValue Result = getMemsetStores(*this, dl, Chain, Dst, Src,
7306                                      ConstantSize->getZExtValue(), Alignment,
7307                                      isVol, DstPtrInfo, AAInfo);
7308 
7309     if (Result.getNode())
7310       return Result;
7311   }
7312 
7313   // Then check to see if we should lower the memset with target-specific
7314   // code. If the target chooses to do this, this is the next best.
7315   if (TSI) {
7316     SDValue Result = TSI->EmitTargetCodeForMemset(
7317         *this, dl, Chain, Dst, Src, Size, Alignment, isVol, DstPtrInfo);
7318     if (Result.getNode())
7319       return Result;
7320   }
7321 
7322   checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace());
7323 
7324   // Emit a library call.
7325   TargetLowering::ArgListTy Args;
7326   TargetLowering::ArgListEntry Entry;
7327   Entry.Node = Dst; Entry.Ty = Type::getInt8PtrTy(*getContext());
7328   Args.push_back(Entry);
7329   Entry.Node = Src;
7330   Entry.Ty = Src.getValueType().getTypeForEVT(*getContext());
7331   Args.push_back(Entry);
7332   Entry.Node = Size;
7333   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
7334   Args.push_back(Entry);
7335 
7336   // FIXME: pass in SDLoc
7337   TargetLowering::CallLoweringInfo CLI(*this);
7338   CLI.setDebugLoc(dl)
7339       .setChain(Chain)
7340       .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMSET),
7341                     Dst.getValueType().getTypeForEVT(*getContext()),
7342                     getExternalSymbol(TLI->getLibcallName(RTLIB::MEMSET),
7343                                       TLI->getPointerTy(getDataLayout())),
7344                     std::move(Args))
7345       .setDiscardResult()
7346       .setTailCall(isTailCall);
7347 
7348   std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
7349   return CallResult.second;
7350 }
7351 
7352 SDValue SelectionDAG::getAtomicMemset(SDValue Chain, const SDLoc &dl,
7353                                       SDValue Dst, unsigned DstAlign,
7354                                       SDValue Value, SDValue Size, Type *SizeTy,
7355                                       unsigned ElemSz, bool isTailCall,
7356                                       MachinePointerInfo DstPtrInfo) {
7357   // Emit a library call.
7358   TargetLowering::ArgListTy Args;
7359   TargetLowering::ArgListEntry Entry;
7360   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
7361   Entry.Node = Dst;
7362   Args.push_back(Entry);
7363 
7364   Entry.Ty = Type::getInt8Ty(*getContext());
7365   Entry.Node = Value;
7366   Args.push_back(Entry);
7367 
7368   Entry.Ty = SizeTy;
7369   Entry.Node = Size;
7370   Args.push_back(Entry);
7371 
7372   RTLIB::Libcall LibraryCall =
7373       RTLIB::getMEMSET_ELEMENT_UNORDERED_ATOMIC(ElemSz);
7374   if (LibraryCall == RTLIB::UNKNOWN_LIBCALL)
7375     report_fatal_error("Unsupported element size");
7376 
7377   TargetLowering::CallLoweringInfo CLI(*this);
7378   CLI.setDebugLoc(dl)
7379       .setChain(Chain)
7380       .setLibCallee(TLI->getLibcallCallingConv(LibraryCall),
7381                     Type::getVoidTy(*getContext()),
7382                     getExternalSymbol(TLI->getLibcallName(LibraryCall),
7383                                       TLI->getPointerTy(getDataLayout())),
7384                     std::move(Args))
7385       .setDiscardResult()
7386       .setTailCall(isTailCall);
7387 
7388   std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
7389   return CallResult.second;
7390 }
7391 
7392 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
7393                                 SDVTList VTList, ArrayRef<SDValue> Ops,
7394                                 MachineMemOperand *MMO) {
7395   FoldingSetNodeID ID;
7396   ID.AddInteger(MemVT.getRawBits());
7397   AddNodeIDNode(ID, Opcode, VTList, Ops);
7398   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7399   ID.AddInteger(MMO->getFlags());
7400   void* IP = nullptr;
7401   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7402     cast<AtomicSDNode>(E)->refineAlignment(MMO);
7403     return SDValue(E, 0);
7404   }
7405 
7406   auto *N = newSDNode<AtomicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
7407                                     VTList, MemVT, MMO);
7408   createOperands(N, Ops);
7409 
7410   CSEMap.InsertNode(N, IP);
7411   InsertNode(N);
7412   return SDValue(N, 0);
7413 }
7414 
7415 SDValue SelectionDAG::getAtomicCmpSwap(unsigned Opcode, const SDLoc &dl,
7416                                        EVT MemVT, SDVTList VTs, SDValue Chain,
7417                                        SDValue Ptr, SDValue Cmp, SDValue Swp,
7418                                        MachineMemOperand *MMO) {
7419   assert(Opcode == ISD::ATOMIC_CMP_SWAP ||
7420          Opcode == ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS);
7421   assert(Cmp.getValueType() == Swp.getValueType() && "Invalid Atomic Op Types");
7422 
7423   SDValue Ops[] = {Chain, Ptr, Cmp, Swp};
7424   return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
7425 }
7426 
7427 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
7428                                 SDValue Chain, SDValue Ptr, SDValue Val,
7429                                 MachineMemOperand *MMO) {
7430   assert((Opcode == ISD::ATOMIC_LOAD_ADD ||
7431           Opcode == ISD::ATOMIC_LOAD_SUB ||
7432           Opcode == ISD::ATOMIC_LOAD_AND ||
7433           Opcode == ISD::ATOMIC_LOAD_CLR ||
7434           Opcode == ISD::ATOMIC_LOAD_OR ||
7435           Opcode == ISD::ATOMIC_LOAD_XOR ||
7436           Opcode == ISD::ATOMIC_LOAD_NAND ||
7437           Opcode == ISD::ATOMIC_LOAD_MIN ||
7438           Opcode == ISD::ATOMIC_LOAD_MAX ||
7439           Opcode == ISD::ATOMIC_LOAD_UMIN ||
7440           Opcode == ISD::ATOMIC_LOAD_UMAX ||
7441           Opcode == ISD::ATOMIC_LOAD_FADD ||
7442           Opcode == ISD::ATOMIC_LOAD_FSUB ||
7443           Opcode == ISD::ATOMIC_SWAP ||
7444           Opcode == ISD::ATOMIC_STORE) &&
7445          "Invalid Atomic Op");
7446 
7447   EVT VT = Val.getValueType();
7448 
7449   SDVTList VTs = Opcode == ISD::ATOMIC_STORE ? getVTList(MVT::Other) :
7450                                                getVTList(VT, MVT::Other);
7451   SDValue Ops[] = {Chain, Ptr, Val};
7452   return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
7453 }
7454 
7455 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
7456                                 EVT VT, SDValue Chain, SDValue Ptr,
7457                                 MachineMemOperand *MMO) {
7458   assert(Opcode == ISD::ATOMIC_LOAD && "Invalid Atomic Op");
7459 
7460   SDVTList VTs = getVTList(VT, MVT::Other);
7461   SDValue Ops[] = {Chain, Ptr};
7462   return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
7463 }
7464 
7465 /// getMergeValues - Create a MERGE_VALUES node from the given operands.
7466 SDValue SelectionDAG::getMergeValues(ArrayRef<SDValue> Ops, const SDLoc &dl) {
7467   if (Ops.size() == 1)
7468     return Ops[0];
7469 
7470   SmallVector<EVT, 4> VTs;
7471   VTs.reserve(Ops.size());
7472   for (const SDValue &Op : Ops)
7473     VTs.push_back(Op.getValueType());
7474   return getNode(ISD::MERGE_VALUES, dl, getVTList(VTs), Ops);
7475 }
7476 
7477 SDValue SelectionDAG::getMemIntrinsicNode(
7478     unsigned Opcode, const SDLoc &dl, SDVTList VTList, ArrayRef<SDValue> Ops,
7479     EVT MemVT, MachinePointerInfo PtrInfo, Align Alignment,
7480     MachineMemOperand::Flags Flags, uint64_t Size, const AAMDNodes &AAInfo) {
7481   if (!Size && MemVT.isScalableVector())
7482     Size = MemoryLocation::UnknownSize;
7483   else if (!Size)
7484     Size = MemVT.getStoreSize();
7485 
7486   MachineFunction &MF = getMachineFunction();
7487   MachineMemOperand *MMO =
7488       MF.getMachineMemOperand(PtrInfo, Flags, Size, Alignment, AAInfo);
7489 
7490   return getMemIntrinsicNode(Opcode, dl, VTList, Ops, MemVT, MMO);
7491 }
7492 
7493 SDValue SelectionDAG::getMemIntrinsicNode(unsigned Opcode, const SDLoc &dl,
7494                                           SDVTList VTList,
7495                                           ArrayRef<SDValue> Ops, EVT MemVT,
7496                                           MachineMemOperand *MMO) {
7497   assert((Opcode == ISD::INTRINSIC_VOID ||
7498           Opcode == ISD::INTRINSIC_W_CHAIN ||
7499           Opcode == ISD::PREFETCH ||
7500           ((int)Opcode <= std::numeric_limits<int>::max() &&
7501            (int)Opcode >= ISD::FIRST_TARGET_MEMORY_OPCODE)) &&
7502          "Opcode is not a memory-accessing opcode!");
7503 
7504   // Memoize the node unless it returns a flag.
7505   MemIntrinsicSDNode *N;
7506   if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) {
7507     FoldingSetNodeID ID;
7508     AddNodeIDNode(ID, Opcode, VTList, Ops);
7509     ID.AddInteger(getSyntheticNodeSubclassData<MemIntrinsicSDNode>(
7510         Opcode, dl.getIROrder(), VTList, MemVT, MMO));
7511     ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7512     ID.AddInteger(MMO->getFlags());
7513     void *IP = nullptr;
7514     if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7515       cast<MemIntrinsicSDNode>(E)->refineAlignment(MMO);
7516       return SDValue(E, 0);
7517     }
7518 
7519     N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
7520                                       VTList, MemVT, MMO);
7521     createOperands(N, Ops);
7522 
7523   CSEMap.InsertNode(N, IP);
7524   } else {
7525     N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
7526                                       VTList, MemVT, MMO);
7527     createOperands(N, Ops);
7528   }
7529   InsertNode(N);
7530   SDValue V(N, 0);
7531   NewSDValueDbgMsg(V, "Creating new node: ", this);
7532   return V;
7533 }
7534 
7535 SDValue SelectionDAG::getLifetimeNode(bool IsStart, const SDLoc &dl,
7536                                       SDValue Chain, int FrameIndex,
7537                                       int64_t Size, int64_t Offset) {
7538   const unsigned Opcode = IsStart ? ISD::LIFETIME_START : ISD::LIFETIME_END;
7539   const auto VTs = getVTList(MVT::Other);
7540   SDValue Ops[2] = {
7541       Chain,
7542       getFrameIndex(FrameIndex,
7543                     getTargetLoweringInfo().getFrameIndexTy(getDataLayout()),
7544                     true)};
7545 
7546   FoldingSetNodeID ID;
7547   AddNodeIDNode(ID, Opcode, VTs, Ops);
7548   ID.AddInteger(FrameIndex);
7549   ID.AddInteger(Size);
7550   ID.AddInteger(Offset);
7551   void *IP = nullptr;
7552   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
7553     return SDValue(E, 0);
7554 
7555   LifetimeSDNode *N = newSDNode<LifetimeSDNode>(
7556       Opcode, dl.getIROrder(), dl.getDebugLoc(), VTs, Size, Offset);
7557   createOperands(N, Ops);
7558   CSEMap.InsertNode(N, IP);
7559   InsertNode(N);
7560   SDValue V(N, 0);
7561   NewSDValueDbgMsg(V, "Creating new node: ", this);
7562   return V;
7563 }
7564 
7565 SDValue SelectionDAG::getPseudoProbeNode(const SDLoc &Dl, SDValue Chain,
7566                                          uint64_t Guid, uint64_t Index,
7567                                          uint32_t Attr) {
7568   const unsigned Opcode = ISD::PSEUDO_PROBE;
7569   const auto VTs = getVTList(MVT::Other);
7570   SDValue Ops[] = {Chain};
7571   FoldingSetNodeID ID;
7572   AddNodeIDNode(ID, Opcode, VTs, Ops);
7573   ID.AddInteger(Guid);
7574   ID.AddInteger(Index);
7575   void *IP = nullptr;
7576   if (SDNode *E = FindNodeOrInsertPos(ID, Dl, IP))
7577     return SDValue(E, 0);
7578 
7579   auto *N = newSDNode<PseudoProbeSDNode>(
7580       Opcode, Dl.getIROrder(), Dl.getDebugLoc(), VTs, Guid, Index, Attr);
7581   createOperands(N, Ops);
7582   CSEMap.InsertNode(N, IP);
7583   InsertNode(N);
7584   SDValue V(N, 0);
7585   NewSDValueDbgMsg(V, "Creating new node: ", this);
7586   return V;
7587 }
7588 
7589 /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a
7590 /// MachinePointerInfo record from it.  This is particularly useful because the
7591 /// code generator has many cases where it doesn't bother passing in a
7592 /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst".
7593 static MachinePointerInfo InferPointerInfo(const MachinePointerInfo &Info,
7594                                            SelectionDAG &DAG, SDValue Ptr,
7595                                            int64_t Offset = 0) {
7596   // If this is FI+Offset, we can model it.
7597   if (const FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr))
7598     return MachinePointerInfo::getFixedStack(DAG.getMachineFunction(),
7599                                              FI->getIndex(), Offset);
7600 
7601   // If this is (FI+Offset1)+Offset2, we can model it.
7602   if (Ptr.getOpcode() != ISD::ADD ||
7603       !isa<ConstantSDNode>(Ptr.getOperand(1)) ||
7604       !isa<FrameIndexSDNode>(Ptr.getOperand(0)))
7605     return Info;
7606 
7607   int FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
7608   return MachinePointerInfo::getFixedStack(
7609       DAG.getMachineFunction(), FI,
7610       Offset + cast<ConstantSDNode>(Ptr.getOperand(1))->getSExtValue());
7611 }
7612 
7613 /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a
7614 /// MachinePointerInfo record from it.  This is particularly useful because the
7615 /// code generator has many cases where it doesn't bother passing in a
7616 /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst".
7617 static MachinePointerInfo InferPointerInfo(const MachinePointerInfo &Info,
7618                                            SelectionDAG &DAG, SDValue Ptr,
7619                                            SDValue OffsetOp) {
7620   // If the 'Offset' value isn't a constant, we can't handle this.
7621   if (ConstantSDNode *OffsetNode = dyn_cast<ConstantSDNode>(OffsetOp))
7622     return InferPointerInfo(Info, DAG, Ptr, OffsetNode->getSExtValue());
7623   if (OffsetOp.isUndef())
7624     return InferPointerInfo(Info, DAG, Ptr);
7625   return Info;
7626 }
7627 
7628 SDValue SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType,
7629                               EVT VT, const SDLoc &dl, SDValue Chain,
7630                               SDValue Ptr, SDValue Offset,
7631                               MachinePointerInfo PtrInfo, EVT MemVT,
7632                               Align Alignment,
7633                               MachineMemOperand::Flags MMOFlags,
7634                               const AAMDNodes &AAInfo, const MDNode *Ranges) {
7635   assert(Chain.getValueType() == MVT::Other &&
7636         "Invalid chain type");
7637 
7638   MMOFlags |= MachineMemOperand::MOLoad;
7639   assert((MMOFlags & MachineMemOperand::MOStore) == 0);
7640   // If we don't have a PtrInfo, infer the trivial frame index case to simplify
7641   // clients.
7642   if (PtrInfo.V.isNull())
7643     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr, Offset);
7644 
7645   uint64_t Size = MemoryLocation::getSizeOrUnknown(MemVT.getStoreSize());
7646   MachineFunction &MF = getMachineFunction();
7647   MachineMemOperand *MMO = MF.getMachineMemOperand(PtrInfo, MMOFlags, Size,
7648                                                    Alignment, AAInfo, Ranges);
7649   return getLoad(AM, ExtType, VT, dl, Chain, Ptr, Offset, MemVT, MMO);
7650 }
7651 
7652 SDValue SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType,
7653                               EVT VT, const SDLoc &dl, SDValue Chain,
7654                               SDValue Ptr, SDValue Offset, EVT MemVT,
7655                               MachineMemOperand *MMO) {
7656   if (VT == MemVT) {
7657     ExtType = ISD::NON_EXTLOAD;
7658   } else if (ExtType == ISD::NON_EXTLOAD) {
7659     assert(VT == MemVT && "Non-extending load from different memory type!");
7660   } else {
7661     // Extending load.
7662     assert(MemVT.getScalarType().bitsLT(VT.getScalarType()) &&
7663            "Should only be an extending load, not truncating!");
7664     assert(VT.isInteger() == MemVT.isInteger() &&
7665            "Cannot convert from FP to Int or Int -> FP!");
7666     assert(VT.isVector() == MemVT.isVector() &&
7667            "Cannot use an ext load to convert to or from a vector!");
7668     assert((!VT.isVector() ||
7669             VT.getVectorElementCount() == MemVT.getVectorElementCount()) &&
7670            "Cannot use an ext load to change the number of vector elements!");
7671   }
7672 
7673   bool Indexed = AM != ISD::UNINDEXED;
7674   assert((Indexed || Offset.isUndef()) && "Unindexed load with an offset!");
7675 
7676   SDVTList VTs = Indexed ?
7677     getVTList(VT, Ptr.getValueType(), MVT::Other) : getVTList(VT, MVT::Other);
7678   SDValue Ops[] = { Chain, Ptr, Offset };
7679   FoldingSetNodeID ID;
7680   AddNodeIDNode(ID, ISD::LOAD, VTs, Ops);
7681   ID.AddInteger(MemVT.getRawBits());
7682   ID.AddInteger(getSyntheticNodeSubclassData<LoadSDNode>(
7683       dl.getIROrder(), VTs, AM, ExtType, MemVT, MMO));
7684   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7685   ID.AddInteger(MMO->getFlags());
7686   void *IP = nullptr;
7687   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7688     cast<LoadSDNode>(E)->refineAlignment(MMO);
7689     return SDValue(E, 0);
7690   }
7691   auto *N = newSDNode<LoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
7692                                   ExtType, MemVT, MMO);
7693   createOperands(N, Ops);
7694 
7695   CSEMap.InsertNode(N, IP);
7696   InsertNode(N);
7697   SDValue V(N, 0);
7698   NewSDValueDbgMsg(V, "Creating new node: ", this);
7699   return V;
7700 }
7701 
7702 SDValue SelectionDAG::getLoad(EVT VT, const SDLoc &dl, SDValue Chain,
7703                               SDValue Ptr, MachinePointerInfo PtrInfo,
7704                               MaybeAlign Alignment,
7705                               MachineMemOperand::Flags MMOFlags,
7706                               const AAMDNodes &AAInfo, const MDNode *Ranges) {
7707   SDValue Undef = getUNDEF(Ptr.getValueType());
7708   return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
7709                  PtrInfo, VT, Alignment, MMOFlags, AAInfo, Ranges);
7710 }
7711 
7712 SDValue SelectionDAG::getLoad(EVT VT, const SDLoc &dl, SDValue Chain,
7713                               SDValue Ptr, MachineMemOperand *MMO) {
7714   SDValue Undef = getUNDEF(Ptr.getValueType());
7715   return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
7716                  VT, MMO);
7717 }
7718 
7719 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl,
7720                                  EVT VT, SDValue Chain, SDValue Ptr,
7721                                  MachinePointerInfo PtrInfo, EVT MemVT,
7722                                  MaybeAlign Alignment,
7723                                  MachineMemOperand::Flags MMOFlags,
7724                                  const AAMDNodes &AAInfo) {
7725   SDValue Undef = getUNDEF(Ptr.getValueType());
7726   return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, PtrInfo,
7727                  MemVT, Alignment, MMOFlags, AAInfo);
7728 }
7729 
7730 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl,
7731                                  EVT VT, SDValue Chain, SDValue Ptr, EVT MemVT,
7732                                  MachineMemOperand *MMO) {
7733   SDValue Undef = getUNDEF(Ptr.getValueType());
7734   return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef,
7735                  MemVT, MMO);
7736 }
7737 
7738 SDValue SelectionDAG::getIndexedLoad(SDValue OrigLoad, const SDLoc &dl,
7739                                      SDValue Base, SDValue Offset,
7740                                      ISD::MemIndexedMode AM) {
7741   LoadSDNode *LD = cast<LoadSDNode>(OrigLoad);
7742   assert(LD->getOffset().isUndef() && "Load is already a indexed load!");
7743   // Don't propagate the invariant or dereferenceable flags.
7744   auto MMOFlags =
7745       LD->getMemOperand()->getFlags() &
7746       ~(MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable);
7747   return getLoad(AM, LD->getExtensionType(), OrigLoad.getValueType(), dl,
7748                  LD->getChain(), Base, Offset, LD->getPointerInfo(),
7749                  LD->getMemoryVT(), LD->getAlign(), MMOFlags, LD->getAAInfo());
7750 }
7751 
7752 SDValue SelectionDAG::getStore(SDValue Chain, const SDLoc &dl, SDValue Val,
7753                                SDValue Ptr, MachinePointerInfo PtrInfo,
7754                                Align Alignment,
7755                                MachineMemOperand::Flags MMOFlags,
7756                                const AAMDNodes &AAInfo) {
7757   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
7758 
7759   MMOFlags |= MachineMemOperand::MOStore;
7760   assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
7761 
7762   if (PtrInfo.V.isNull())
7763     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
7764 
7765   MachineFunction &MF = getMachineFunction();
7766   uint64_t Size =
7767       MemoryLocation::getSizeOrUnknown(Val.getValueType().getStoreSize());
7768   MachineMemOperand *MMO =
7769       MF.getMachineMemOperand(PtrInfo, MMOFlags, Size, Alignment, AAInfo);
7770   return getStore(Chain, dl, Val, Ptr, MMO);
7771 }
7772 
7773 SDValue SelectionDAG::getStore(SDValue Chain, const SDLoc &dl, SDValue Val,
7774                                SDValue Ptr, MachineMemOperand *MMO) {
7775   assert(Chain.getValueType() == MVT::Other &&
7776         "Invalid chain type");
7777   EVT VT = Val.getValueType();
7778   SDVTList VTs = getVTList(MVT::Other);
7779   SDValue Undef = getUNDEF(Ptr.getValueType());
7780   SDValue Ops[] = { Chain, Val, Ptr, Undef };
7781   FoldingSetNodeID ID;
7782   AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
7783   ID.AddInteger(VT.getRawBits());
7784   ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>(
7785       dl.getIROrder(), VTs, ISD::UNINDEXED, false, VT, MMO));
7786   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7787   ID.AddInteger(MMO->getFlags());
7788   void *IP = nullptr;
7789   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7790     cast<StoreSDNode>(E)->refineAlignment(MMO);
7791     return SDValue(E, 0);
7792   }
7793   auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
7794                                    ISD::UNINDEXED, false, VT, MMO);
7795   createOperands(N, Ops);
7796 
7797   CSEMap.InsertNode(N, IP);
7798   InsertNode(N);
7799   SDValue V(N, 0);
7800   NewSDValueDbgMsg(V, "Creating new node: ", this);
7801   return V;
7802 }
7803 
7804 SDValue SelectionDAG::getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val,
7805                                     SDValue Ptr, MachinePointerInfo PtrInfo,
7806                                     EVT SVT, Align Alignment,
7807                                     MachineMemOperand::Flags MMOFlags,
7808                                     const AAMDNodes &AAInfo) {
7809   assert(Chain.getValueType() == MVT::Other &&
7810         "Invalid chain type");
7811 
7812   MMOFlags |= MachineMemOperand::MOStore;
7813   assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
7814 
7815   if (PtrInfo.V.isNull())
7816     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
7817 
7818   MachineFunction &MF = getMachineFunction();
7819   MachineMemOperand *MMO = MF.getMachineMemOperand(
7820       PtrInfo, MMOFlags, MemoryLocation::getSizeOrUnknown(SVT.getStoreSize()),
7821       Alignment, AAInfo);
7822   return getTruncStore(Chain, dl, Val, Ptr, SVT, MMO);
7823 }
7824 
7825 SDValue SelectionDAG::getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val,
7826                                     SDValue Ptr, EVT SVT,
7827                                     MachineMemOperand *MMO) {
7828   EVT VT = Val.getValueType();
7829 
7830   assert(Chain.getValueType() == MVT::Other &&
7831         "Invalid chain type");
7832   if (VT == SVT)
7833     return getStore(Chain, dl, Val, Ptr, MMO);
7834 
7835   assert(SVT.getScalarType().bitsLT(VT.getScalarType()) &&
7836          "Should only be a truncating store, not extending!");
7837   assert(VT.isInteger() == SVT.isInteger() &&
7838          "Can't do FP-INT conversion!");
7839   assert(VT.isVector() == SVT.isVector() &&
7840          "Cannot use trunc store to convert to or from a vector!");
7841   assert((!VT.isVector() ||
7842           VT.getVectorElementCount() == SVT.getVectorElementCount()) &&
7843          "Cannot use trunc store to change the number of vector elements!");
7844 
7845   SDVTList VTs = getVTList(MVT::Other);
7846   SDValue Undef = getUNDEF(Ptr.getValueType());
7847   SDValue Ops[] = { Chain, Val, Ptr, Undef };
7848   FoldingSetNodeID ID;
7849   AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
7850   ID.AddInteger(SVT.getRawBits());
7851   ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>(
7852       dl.getIROrder(), VTs, ISD::UNINDEXED, true, SVT, MMO));
7853   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7854   ID.AddInteger(MMO->getFlags());
7855   void *IP = nullptr;
7856   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7857     cast<StoreSDNode>(E)->refineAlignment(MMO);
7858     return SDValue(E, 0);
7859   }
7860   auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
7861                                    ISD::UNINDEXED, true, SVT, MMO);
7862   createOperands(N, Ops);
7863 
7864   CSEMap.InsertNode(N, IP);
7865   InsertNode(N);
7866   SDValue V(N, 0);
7867   NewSDValueDbgMsg(V, "Creating new node: ", this);
7868   return V;
7869 }
7870 
7871 SDValue SelectionDAG::getIndexedStore(SDValue OrigStore, const SDLoc &dl,
7872                                       SDValue Base, SDValue Offset,
7873                                       ISD::MemIndexedMode AM) {
7874   StoreSDNode *ST = cast<StoreSDNode>(OrigStore);
7875   assert(ST->getOffset().isUndef() && "Store is already a indexed store!");
7876   SDVTList VTs = getVTList(Base.getValueType(), MVT::Other);
7877   SDValue Ops[] = { ST->getChain(), ST->getValue(), Base, Offset };
7878   FoldingSetNodeID ID;
7879   AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
7880   ID.AddInteger(ST->getMemoryVT().getRawBits());
7881   ID.AddInteger(ST->getRawSubclassData());
7882   ID.AddInteger(ST->getPointerInfo().getAddrSpace());
7883   ID.AddInteger(ST->getMemOperand()->getFlags());
7884   void *IP = nullptr;
7885   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
7886     return SDValue(E, 0);
7887 
7888   auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
7889                                    ST->isTruncatingStore(), ST->getMemoryVT(),
7890                                    ST->getMemOperand());
7891   createOperands(N, Ops);
7892 
7893   CSEMap.InsertNode(N, IP);
7894   InsertNode(N);
7895   SDValue V(N, 0);
7896   NewSDValueDbgMsg(V, "Creating new node: ", this);
7897   return V;
7898 }
7899 
7900 SDValue SelectionDAG::getLoadVP(
7901     ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, EVT VT, const SDLoc &dl,
7902     SDValue Chain, SDValue Ptr, SDValue Offset, SDValue Mask, SDValue EVL,
7903     MachinePointerInfo PtrInfo, EVT MemVT, Align Alignment,
7904     MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo,
7905     const MDNode *Ranges, bool IsExpanding) {
7906   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
7907 
7908   MMOFlags |= MachineMemOperand::MOLoad;
7909   assert((MMOFlags & MachineMemOperand::MOStore) == 0);
7910   // If we don't have a PtrInfo, infer the trivial frame index case to simplify
7911   // clients.
7912   if (PtrInfo.V.isNull())
7913     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr, Offset);
7914 
7915   uint64_t Size = MemoryLocation::getSizeOrUnknown(MemVT.getStoreSize());
7916   MachineFunction &MF = getMachineFunction();
7917   MachineMemOperand *MMO = MF.getMachineMemOperand(PtrInfo, MMOFlags, Size,
7918                                                    Alignment, AAInfo, Ranges);
7919   return getLoadVP(AM, ExtType, VT, dl, Chain, Ptr, Offset, Mask, EVL, MemVT,
7920                    MMO, IsExpanding);
7921 }
7922 
7923 SDValue SelectionDAG::getLoadVP(ISD::MemIndexedMode AM,
7924                                 ISD::LoadExtType ExtType, EVT VT,
7925                                 const SDLoc &dl, SDValue Chain, SDValue Ptr,
7926                                 SDValue Offset, SDValue Mask, SDValue EVL,
7927                                 EVT MemVT, MachineMemOperand *MMO,
7928                                 bool IsExpanding) {
7929   bool Indexed = AM != ISD::UNINDEXED;
7930   assert((Indexed || Offset.isUndef()) && "Unindexed load with an offset!");
7931 
7932   SDVTList VTs = Indexed ? getVTList(VT, Ptr.getValueType(), MVT::Other)
7933                          : getVTList(VT, MVT::Other);
7934   SDValue Ops[] = {Chain, Ptr, Offset, Mask, EVL};
7935   FoldingSetNodeID ID;
7936   AddNodeIDNode(ID, ISD::VP_LOAD, VTs, Ops);
7937   ID.AddInteger(VT.getRawBits());
7938   ID.AddInteger(getSyntheticNodeSubclassData<VPLoadSDNode>(
7939       dl.getIROrder(), VTs, AM, ExtType, IsExpanding, MemVT, MMO));
7940   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7941   ID.AddInteger(MMO->getFlags());
7942   void *IP = nullptr;
7943   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7944     cast<VPLoadSDNode>(E)->refineAlignment(MMO);
7945     return SDValue(E, 0);
7946   }
7947   auto *N = newSDNode<VPLoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
7948                                     ExtType, IsExpanding, MemVT, MMO);
7949   createOperands(N, Ops);
7950 
7951   CSEMap.InsertNode(N, IP);
7952   InsertNode(N);
7953   SDValue V(N, 0);
7954   NewSDValueDbgMsg(V, "Creating new node: ", this);
7955   return V;
7956 }
7957 
7958 SDValue SelectionDAG::getLoadVP(EVT VT, const SDLoc &dl, SDValue Chain,
7959                                 SDValue Ptr, SDValue Mask, SDValue EVL,
7960                                 MachinePointerInfo PtrInfo,
7961                                 MaybeAlign Alignment,
7962                                 MachineMemOperand::Flags MMOFlags,
7963                                 const AAMDNodes &AAInfo, const MDNode *Ranges,
7964                                 bool IsExpanding) {
7965   SDValue Undef = getUNDEF(Ptr.getValueType());
7966   return getLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
7967                    Mask, EVL, PtrInfo, VT, Alignment, MMOFlags, AAInfo, Ranges,
7968                    IsExpanding);
7969 }
7970 
7971 SDValue SelectionDAG::getLoadVP(EVT VT, const SDLoc &dl, SDValue Chain,
7972                                 SDValue Ptr, SDValue Mask, SDValue EVL,
7973                                 MachineMemOperand *MMO, bool IsExpanding) {
7974   SDValue Undef = getUNDEF(Ptr.getValueType());
7975   return getLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
7976                    Mask, EVL, VT, MMO, IsExpanding);
7977 }
7978 
7979 SDValue SelectionDAG::getExtLoadVP(ISD::LoadExtType ExtType, const SDLoc &dl,
7980                                    EVT VT, SDValue Chain, SDValue Ptr,
7981                                    SDValue Mask, SDValue EVL,
7982                                    MachinePointerInfo PtrInfo, EVT MemVT,
7983                                    MaybeAlign Alignment,
7984                                    MachineMemOperand::Flags MMOFlags,
7985                                    const AAMDNodes &AAInfo, bool IsExpanding) {
7986   SDValue Undef = getUNDEF(Ptr.getValueType());
7987   return getLoadVP(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, Mask,
7988                    EVL, PtrInfo, MemVT, Alignment, MMOFlags, AAInfo, nullptr,
7989                    IsExpanding);
7990 }
7991 
7992 SDValue SelectionDAG::getExtLoadVP(ISD::LoadExtType ExtType, const SDLoc &dl,
7993                                    EVT VT, SDValue Chain, SDValue Ptr,
7994                                    SDValue Mask, SDValue EVL, EVT MemVT,
7995                                    MachineMemOperand *MMO, bool IsExpanding) {
7996   SDValue Undef = getUNDEF(Ptr.getValueType());
7997   return getLoadVP(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, Mask,
7998                    EVL, MemVT, MMO, IsExpanding);
7999 }
8000 
8001 SDValue SelectionDAG::getIndexedLoadVP(SDValue OrigLoad, const SDLoc &dl,
8002                                        SDValue Base, SDValue Offset,
8003                                        ISD::MemIndexedMode AM) {
8004   auto *LD = cast<VPLoadSDNode>(OrigLoad);
8005   assert(LD->getOffset().isUndef() && "Load is already a indexed load!");
8006   // Don't propagate the invariant or dereferenceable flags.
8007   auto MMOFlags =
8008       LD->getMemOperand()->getFlags() &
8009       ~(MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable);
8010   return getLoadVP(AM, LD->getExtensionType(), OrigLoad.getValueType(), dl,
8011                    LD->getChain(), Base, Offset, LD->getMask(),
8012                    LD->getVectorLength(), LD->getPointerInfo(),
8013                    LD->getMemoryVT(), LD->getAlign(), MMOFlags, LD->getAAInfo(),
8014                    nullptr, LD->isExpandingLoad());
8015 }
8016 
8017 SDValue SelectionDAG::getStoreVP(SDValue Chain, const SDLoc &dl, SDValue Val,
8018                                  SDValue Ptr, SDValue Offset, SDValue Mask,
8019                                  SDValue EVL, EVT MemVT, MachineMemOperand *MMO,
8020                                  ISD::MemIndexedMode AM, bool IsTruncating,
8021                                  bool IsCompressing) {
8022   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
8023   bool Indexed = AM != ISD::UNINDEXED;
8024   assert((Indexed || Offset.isUndef()) && "Unindexed vp_store with an offset!");
8025   SDVTList VTs = Indexed ? getVTList(Ptr.getValueType(), MVT::Other)
8026                          : getVTList(MVT::Other);
8027   SDValue Ops[] = {Chain, Val, Ptr, Offset, Mask, EVL};
8028   FoldingSetNodeID ID;
8029   AddNodeIDNode(ID, ISD::VP_STORE, VTs, Ops);
8030   ID.AddInteger(MemVT.getRawBits());
8031   ID.AddInteger(getSyntheticNodeSubclassData<VPStoreSDNode>(
8032       dl.getIROrder(), VTs, AM, IsTruncating, IsCompressing, MemVT, MMO));
8033   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8034   ID.AddInteger(MMO->getFlags());
8035   void *IP = nullptr;
8036   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
8037     cast<VPStoreSDNode>(E)->refineAlignment(MMO);
8038     return SDValue(E, 0);
8039   }
8040   auto *N = newSDNode<VPStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
8041                                      IsTruncating, IsCompressing, MemVT, MMO);
8042   createOperands(N, Ops);
8043 
8044   CSEMap.InsertNode(N, IP);
8045   InsertNode(N);
8046   SDValue V(N, 0);
8047   NewSDValueDbgMsg(V, "Creating new node: ", this);
8048   return V;
8049 }
8050 
8051 SDValue SelectionDAG::getTruncStoreVP(SDValue Chain, const SDLoc &dl,
8052                                       SDValue Val, SDValue Ptr, SDValue Mask,
8053                                       SDValue EVL, MachinePointerInfo PtrInfo,
8054                                       EVT SVT, Align Alignment,
8055                                       MachineMemOperand::Flags MMOFlags,
8056                                       const AAMDNodes &AAInfo,
8057                                       bool IsCompressing) {
8058   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
8059 
8060   MMOFlags |= MachineMemOperand::MOStore;
8061   assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
8062 
8063   if (PtrInfo.V.isNull())
8064     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
8065 
8066   MachineFunction &MF = getMachineFunction();
8067   MachineMemOperand *MMO = MF.getMachineMemOperand(
8068       PtrInfo, MMOFlags, MemoryLocation::getSizeOrUnknown(SVT.getStoreSize()),
8069       Alignment, AAInfo);
8070   return getTruncStoreVP(Chain, dl, Val, Ptr, Mask, EVL, SVT, MMO,
8071                          IsCompressing);
8072 }
8073 
8074 SDValue SelectionDAG::getTruncStoreVP(SDValue Chain, const SDLoc &dl,
8075                                       SDValue Val, SDValue Ptr, SDValue Mask,
8076                                       SDValue EVL, EVT SVT,
8077                                       MachineMemOperand *MMO,
8078                                       bool IsCompressing) {
8079   EVT VT = Val.getValueType();
8080 
8081   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
8082   if (VT == SVT)
8083     return getStoreVP(Chain, dl, Val, Ptr, getUNDEF(Ptr.getValueType()), Mask,
8084                       EVL, VT, MMO, ISD::UNINDEXED,
8085                       /*IsTruncating*/ false, IsCompressing);
8086 
8087   assert(SVT.getScalarType().bitsLT(VT.getScalarType()) &&
8088          "Should only be a truncating store, not extending!");
8089   assert(VT.isInteger() == SVT.isInteger() && "Can't do FP-INT conversion!");
8090   assert(VT.isVector() == SVT.isVector() &&
8091          "Cannot use trunc store to convert to or from a vector!");
8092   assert((!VT.isVector() ||
8093           VT.getVectorElementCount() == SVT.getVectorElementCount()) &&
8094          "Cannot use trunc store to change the number of vector elements!");
8095 
8096   SDVTList VTs = getVTList(MVT::Other);
8097   SDValue Undef = getUNDEF(Ptr.getValueType());
8098   SDValue Ops[] = {Chain, Val, Ptr, Undef, Mask, EVL};
8099   FoldingSetNodeID ID;
8100   AddNodeIDNode(ID, ISD::VP_STORE, VTs, Ops);
8101   ID.AddInteger(SVT.getRawBits());
8102   ID.AddInteger(getSyntheticNodeSubclassData<VPStoreSDNode>(
8103       dl.getIROrder(), VTs, ISD::UNINDEXED, true, IsCompressing, SVT, MMO));
8104   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8105   ID.AddInteger(MMO->getFlags());
8106   void *IP = nullptr;
8107   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
8108     cast<VPStoreSDNode>(E)->refineAlignment(MMO);
8109     return SDValue(E, 0);
8110   }
8111   auto *N =
8112       newSDNode<VPStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
8113                                ISD::UNINDEXED, true, IsCompressing, SVT, MMO);
8114   createOperands(N, Ops);
8115 
8116   CSEMap.InsertNode(N, IP);
8117   InsertNode(N);
8118   SDValue V(N, 0);
8119   NewSDValueDbgMsg(V, "Creating new node: ", this);
8120   return V;
8121 }
8122 
8123 SDValue SelectionDAG::getIndexedStoreVP(SDValue OrigStore, const SDLoc &dl,
8124                                         SDValue Base, SDValue Offset,
8125                                         ISD::MemIndexedMode AM) {
8126   auto *ST = cast<VPStoreSDNode>(OrigStore);
8127   assert(ST->getOffset().isUndef() && "Store is already an indexed store!");
8128   SDVTList VTs = getVTList(Base.getValueType(), MVT::Other);
8129   SDValue Ops[] = {ST->getChain(), ST->getValue(), Base,
8130                    Offset,         ST->getMask(),  ST->getVectorLength()};
8131   FoldingSetNodeID ID;
8132   AddNodeIDNode(ID, ISD::VP_STORE, VTs, Ops);
8133   ID.AddInteger(ST->getMemoryVT().getRawBits());
8134   ID.AddInteger(ST->getRawSubclassData());
8135   ID.AddInteger(ST->getPointerInfo().getAddrSpace());
8136   ID.AddInteger(ST->getMemOperand()->getFlags());
8137   void *IP = nullptr;
8138   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
8139     return SDValue(E, 0);
8140 
8141   auto *N = newSDNode<VPStoreSDNode>(
8142       dl.getIROrder(), dl.getDebugLoc(), VTs, AM, ST->isTruncatingStore(),
8143       ST->isCompressingStore(), ST->getMemoryVT(), ST->getMemOperand());
8144   createOperands(N, Ops);
8145 
8146   CSEMap.InsertNode(N, IP);
8147   InsertNode(N);
8148   SDValue V(N, 0);
8149   NewSDValueDbgMsg(V, "Creating new node: ", this);
8150   return V;
8151 }
8152 
8153 SDValue SelectionDAG::getStridedLoadVP(
8154     ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, EVT VT, const SDLoc &DL,
8155     SDValue Chain, SDValue Ptr, SDValue Offset, SDValue Stride, SDValue Mask,
8156     SDValue EVL, MachinePointerInfo PtrInfo, EVT MemVT, Align Alignment,
8157     MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo,
8158     const MDNode *Ranges, bool IsExpanding) {
8159   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
8160 
8161   MMOFlags |= MachineMemOperand::MOLoad;
8162   assert((MMOFlags & MachineMemOperand::MOStore) == 0);
8163   // If we don't have a PtrInfo, infer the trivial frame index case to simplify
8164   // clients.
8165   if (PtrInfo.V.isNull())
8166     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr, Offset);
8167 
8168   uint64_t Size = MemoryLocation::UnknownSize;
8169   MachineFunction &MF = getMachineFunction();
8170   MachineMemOperand *MMO = MF.getMachineMemOperand(PtrInfo, MMOFlags, Size,
8171                                                    Alignment, AAInfo, Ranges);
8172   return getStridedLoadVP(AM, ExtType, VT, DL, Chain, Ptr, Offset, Stride, Mask,
8173                           EVL, MemVT, MMO, IsExpanding);
8174 }
8175 
8176 SDValue SelectionDAG::getStridedLoadVP(
8177     ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, EVT VT, const SDLoc &DL,
8178     SDValue Chain, SDValue Ptr, SDValue Offset, SDValue Stride, SDValue Mask,
8179     SDValue EVL, EVT MemVT, MachineMemOperand *MMO, bool IsExpanding) {
8180   bool Indexed = AM != ISD::UNINDEXED;
8181   assert((Indexed || Offset.isUndef()) && "Unindexed load with an offset!");
8182 
8183   SDValue Ops[] = {Chain, Ptr, Offset, Stride, Mask, EVL};
8184   SDVTList VTs = Indexed ? getVTList(VT, Ptr.getValueType(), MVT::Other)
8185                          : getVTList(VT, MVT::Other);
8186   FoldingSetNodeID ID;
8187   AddNodeIDNode(ID, ISD::EXPERIMENTAL_VP_STRIDED_LOAD, VTs, Ops);
8188   ID.AddInteger(VT.getRawBits());
8189   ID.AddInteger(getSyntheticNodeSubclassData<VPStridedLoadSDNode>(
8190       DL.getIROrder(), VTs, AM, ExtType, IsExpanding, MemVT, MMO));
8191   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8192 
8193   void *IP = nullptr;
8194   if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
8195     cast<VPStridedLoadSDNode>(E)->refineAlignment(MMO);
8196     return SDValue(E, 0);
8197   }
8198 
8199   auto *N =
8200       newSDNode<VPStridedLoadSDNode>(DL.getIROrder(), DL.getDebugLoc(), VTs, AM,
8201                                      ExtType, IsExpanding, MemVT, MMO);
8202   createOperands(N, Ops);
8203   CSEMap.InsertNode(N, IP);
8204   InsertNode(N);
8205   SDValue V(N, 0);
8206   NewSDValueDbgMsg(V, "Creating new node: ", this);
8207   return V;
8208 }
8209 
8210 SDValue SelectionDAG::getStridedLoadVP(
8211     EVT VT, const SDLoc &DL, SDValue Chain, SDValue Ptr, SDValue Stride,
8212     SDValue Mask, SDValue EVL, MachinePointerInfo PtrInfo, MaybeAlign Alignment,
8213     MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo,
8214     const MDNode *Ranges, bool IsExpanding) {
8215   SDValue Undef = getUNDEF(Ptr.getValueType());
8216   return getStridedLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, DL, Chain, Ptr,
8217                           Undef, Stride, Mask, EVL, PtrInfo, VT, Alignment,
8218                           MMOFlags, AAInfo, Ranges, IsExpanding);
8219 }
8220 
8221 SDValue SelectionDAG::getStridedLoadVP(EVT VT, const SDLoc &DL, SDValue Chain,
8222                                        SDValue Ptr, SDValue Stride,
8223                                        SDValue Mask, SDValue EVL,
8224                                        MachineMemOperand *MMO,
8225                                        bool IsExpanding) {
8226   SDValue Undef = getUNDEF(Ptr.getValueType());
8227   return getStridedLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, DL, Chain, Ptr,
8228                           Undef, Stride, Mask, EVL, VT, MMO, IsExpanding);
8229 }
8230 
8231 SDValue SelectionDAG::getExtStridedLoadVP(
8232     ISD::LoadExtType ExtType, const SDLoc &DL, EVT VT, SDValue Chain,
8233     SDValue Ptr, SDValue Stride, SDValue Mask, SDValue EVL,
8234     MachinePointerInfo PtrInfo, EVT MemVT, MaybeAlign Alignment,
8235     MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo,
8236     bool IsExpanding) {
8237   SDValue Undef = getUNDEF(Ptr.getValueType());
8238   return getStridedLoadVP(ISD::UNINDEXED, ExtType, VT, DL, Chain, Ptr, Undef,
8239                           Stride, Mask, EVL, PtrInfo, MemVT, Alignment,
8240                           MMOFlags, AAInfo, nullptr, IsExpanding);
8241 }
8242 
8243 SDValue SelectionDAG::getExtStridedLoadVP(
8244     ISD::LoadExtType ExtType, const SDLoc &DL, EVT VT, SDValue Chain,
8245     SDValue Ptr, SDValue Stride, SDValue Mask, SDValue EVL, EVT MemVT,
8246     MachineMemOperand *MMO, bool IsExpanding) {
8247   SDValue Undef = getUNDEF(Ptr.getValueType());
8248   return getStridedLoadVP(ISD::UNINDEXED, ExtType, VT, DL, Chain, Ptr, Undef,
8249                           Stride, Mask, EVL, MemVT, MMO, IsExpanding);
8250 }
8251 
8252 SDValue SelectionDAG::getIndexedStridedLoadVP(SDValue OrigLoad, const SDLoc &DL,
8253                                               SDValue Base, SDValue Offset,
8254                                               ISD::MemIndexedMode AM) {
8255   auto *SLD = cast<VPStridedLoadSDNode>(OrigLoad);
8256   assert(SLD->getOffset().isUndef() &&
8257          "Strided load is already a indexed load!");
8258   // Don't propagate the invariant or dereferenceable flags.
8259   auto MMOFlags =
8260       SLD->getMemOperand()->getFlags() &
8261       ~(MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable);
8262   return getStridedLoadVP(
8263       AM, SLD->getExtensionType(), OrigLoad.getValueType(), DL, SLD->getChain(),
8264       Base, Offset, SLD->getStride(), SLD->getMask(), SLD->getVectorLength(),
8265       SLD->getPointerInfo(), SLD->getMemoryVT(), SLD->getAlign(), MMOFlags,
8266       SLD->getAAInfo(), nullptr, SLD->isExpandingLoad());
8267 }
8268 
8269 SDValue SelectionDAG::getStridedStoreVP(SDValue Chain, const SDLoc &DL,
8270                                         SDValue Val, SDValue Ptr,
8271                                         SDValue Offset, SDValue Stride,
8272                                         SDValue Mask, SDValue EVL, EVT MemVT,
8273                                         MachineMemOperand *MMO,
8274                                         ISD::MemIndexedMode AM,
8275                                         bool IsTruncating, bool IsCompressing) {
8276   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
8277   bool Indexed = AM != ISD::UNINDEXED;
8278   assert((Indexed || Offset.isUndef()) && "Unindexed vp_store with an offset!");
8279   SDVTList VTs = Indexed ? getVTList(Ptr.getValueType(), MVT::Other)
8280                          : getVTList(MVT::Other);
8281   SDValue Ops[] = {Chain, Val, Ptr, Offset, Stride, Mask, EVL};
8282   FoldingSetNodeID ID;
8283   AddNodeIDNode(ID, ISD::EXPERIMENTAL_VP_STRIDED_STORE, VTs, Ops);
8284   ID.AddInteger(MemVT.getRawBits());
8285   ID.AddInteger(getSyntheticNodeSubclassData<VPStridedStoreSDNode>(
8286       DL.getIROrder(), VTs, AM, IsTruncating, IsCompressing, MemVT, MMO));
8287   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8288   void *IP = nullptr;
8289   if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
8290     cast<VPStridedStoreSDNode>(E)->refineAlignment(MMO);
8291     return SDValue(E, 0);
8292   }
8293   auto *N = newSDNode<VPStridedStoreSDNode>(DL.getIROrder(), DL.getDebugLoc(),
8294                                             VTs, AM, IsTruncating,
8295                                             IsCompressing, MemVT, MMO);
8296   createOperands(N, Ops);
8297 
8298   CSEMap.InsertNode(N, IP);
8299   InsertNode(N);
8300   SDValue V(N, 0);
8301   NewSDValueDbgMsg(V, "Creating new node: ", this);
8302   return V;
8303 }
8304 
8305 SDValue SelectionDAG::getTruncStridedStoreVP(
8306     SDValue Chain, const SDLoc &DL, SDValue Val, SDValue Ptr, SDValue Stride,
8307     SDValue Mask, SDValue EVL, MachinePointerInfo PtrInfo, EVT SVT,
8308     Align Alignment, MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo,
8309     bool IsCompressing) {
8310   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
8311 
8312   MMOFlags |= MachineMemOperand::MOStore;
8313   assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
8314 
8315   if (PtrInfo.V.isNull())
8316     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
8317 
8318   MachineFunction &MF = getMachineFunction();
8319   MachineMemOperand *MMO = MF.getMachineMemOperand(
8320       PtrInfo, MMOFlags, MemoryLocation::UnknownSize, Alignment, AAInfo);
8321   return getTruncStridedStoreVP(Chain, DL, Val, Ptr, Stride, Mask, EVL, SVT,
8322                                 MMO, IsCompressing);
8323 }
8324 
8325 SDValue SelectionDAG::getTruncStridedStoreVP(SDValue Chain, const SDLoc &DL,
8326                                              SDValue Val, SDValue Ptr,
8327                                              SDValue Stride, SDValue Mask,
8328                                              SDValue EVL, EVT SVT,
8329                                              MachineMemOperand *MMO,
8330                                              bool IsCompressing) {
8331   EVT VT = Val.getValueType();
8332 
8333   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
8334   if (VT == SVT)
8335     return getStridedStoreVP(Chain, DL, Val, Ptr, getUNDEF(Ptr.getValueType()),
8336                              Stride, Mask, EVL, VT, MMO, ISD::UNINDEXED,
8337                              /*IsTruncating*/ false, IsCompressing);
8338 
8339   assert(SVT.getScalarType().bitsLT(VT.getScalarType()) &&
8340          "Should only be a truncating store, not extending!");
8341   assert(VT.isInteger() == SVT.isInteger() && "Can't do FP-INT conversion!");
8342   assert(VT.isVector() == SVT.isVector() &&
8343          "Cannot use trunc store to convert to or from a vector!");
8344   assert((!VT.isVector() ||
8345           VT.getVectorElementCount() == SVT.getVectorElementCount()) &&
8346          "Cannot use trunc store to change the number of vector elements!");
8347 
8348   SDVTList VTs = getVTList(MVT::Other);
8349   SDValue Undef = getUNDEF(Ptr.getValueType());
8350   SDValue Ops[] = {Chain, Val, Ptr, Undef, Stride, Mask, EVL};
8351   FoldingSetNodeID ID;
8352   AddNodeIDNode(ID, ISD::EXPERIMENTAL_VP_STRIDED_STORE, VTs, Ops);
8353   ID.AddInteger(SVT.getRawBits());
8354   ID.AddInteger(getSyntheticNodeSubclassData<VPStridedStoreSDNode>(
8355       DL.getIROrder(), VTs, ISD::UNINDEXED, true, IsCompressing, SVT, MMO));
8356   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8357   void *IP = nullptr;
8358   if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
8359     cast<VPStridedStoreSDNode>(E)->refineAlignment(MMO);
8360     return SDValue(E, 0);
8361   }
8362   auto *N = newSDNode<VPStridedStoreSDNode>(DL.getIROrder(), DL.getDebugLoc(),
8363                                             VTs, ISD::UNINDEXED, true,
8364                                             IsCompressing, SVT, MMO);
8365   createOperands(N, Ops);
8366 
8367   CSEMap.InsertNode(N, IP);
8368   InsertNode(N);
8369   SDValue V(N, 0);
8370   NewSDValueDbgMsg(V, "Creating new node: ", this);
8371   return V;
8372 }
8373 
8374 SDValue SelectionDAG::getIndexedStridedStoreVP(SDValue OrigStore,
8375                                                const SDLoc &DL, SDValue Base,
8376                                                SDValue Offset,
8377                                                ISD::MemIndexedMode AM) {
8378   auto *SST = cast<VPStridedStoreSDNode>(OrigStore);
8379   assert(SST->getOffset().isUndef() &&
8380          "Strided store is already an indexed store!");
8381   SDVTList VTs = getVTList(Base.getValueType(), MVT::Other);
8382   SDValue Ops[] = {
8383       SST->getChain(), SST->getValue(),       Base, Offset, SST->getStride(),
8384       SST->getMask(),  SST->getVectorLength()};
8385   FoldingSetNodeID ID;
8386   AddNodeIDNode(ID, ISD::EXPERIMENTAL_VP_STRIDED_STORE, VTs, Ops);
8387   ID.AddInteger(SST->getMemoryVT().getRawBits());
8388   ID.AddInteger(SST->getRawSubclassData());
8389   ID.AddInteger(SST->getPointerInfo().getAddrSpace());
8390   void *IP = nullptr;
8391   if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
8392     return SDValue(E, 0);
8393 
8394   auto *N = newSDNode<VPStridedStoreSDNode>(
8395       DL.getIROrder(), DL.getDebugLoc(), VTs, AM, SST->isTruncatingStore(),
8396       SST->isCompressingStore(), SST->getMemoryVT(), SST->getMemOperand());
8397   createOperands(N, Ops);
8398 
8399   CSEMap.InsertNode(N, IP);
8400   InsertNode(N);
8401   SDValue V(N, 0);
8402   NewSDValueDbgMsg(V, "Creating new node: ", this);
8403   return V;
8404 }
8405 
8406 SDValue SelectionDAG::getGatherVP(SDVTList VTs, EVT VT, const SDLoc &dl,
8407                                   ArrayRef<SDValue> Ops, MachineMemOperand *MMO,
8408                                   ISD::MemIndexType IndexType) {
8409   assert(Ops.size() == 6 && "Incompatible number of operands");
8410 
8411   FoldingSetNodeID ID;
8412   AddNodeIDNode(ID, ISD::VP_GATHER, VTs, Ops);
8413   ID.AddInteger(VT.getRawBits());
8414   ID.AddInteger(getSyntheticNodeSubclassData<VPGatherSDNode>(
8415       dl.getIROrder(), VTs, VT, MMO, IndexType));
8416   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8417   ID.AddInteger(MMO->getFlags());
8418   void *IP = nullptr;
8419   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
8420     cast<VPGatherSDNode>(E)->refineAlignment(MMO);
8421     return SDValue(E, 0);
8422   }
8423 
8424   auto *N = newSDNode<VPGatherSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
8425                                       VT, MMO, IndexType);
8426   createOperands(N, Ops);
8427 
8428   assert(N->getMask().getValueType().getVectorElementCount() ==
8429              N->getValueType(0).getVectorElementCount() &&
8430          "Vector width mismatch between mask and data");
8431   assert(N->getIndex().getValueType().getVectorElementCount().isScalable() ==
8432              N->getValueType(0).getVectorElementCount().isScalable() &&
8433          "Scalable flags of index and data do not match");
8434   assert(ElementCount::isKnownGE(
8435              N->getIndex().getValueType().getVectorElementCount(),
8436              N->getValueType(0).getVectorElementCount()) &&
8437          "Vector width mismatch between index and data");
8438   assert(isa<ConstantSDNode>(N->getScale()) &&
8439          cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() &&
8440          "Scale should be a constant power of 2");
8441 
8442   CSEMap.InsertNode(N, IP);
8443   InsertNode(N);
8444   SDValue V(N, 0);
8445   NewSDValueDbgMsg(V, "Creating new node: ", this);
8446   return V;
8447 }
8448 
8449 SDValue SelectionDAG::getScatterVP(SDVTList VTs, EVT VT, const SDLoc &dl,
8450                                    ArrayRef<SDValue> Ops,
8451                                    MachineMemOperand *MMO,
8452                                    ISD::MemIndexType IndexType) {
8453   assert(Ops.size() == 7 && "Incompatible number of operands");
8454 
8455   FoldingSetNodeID ID;
8456   AddNodeIDNode(ID, ISD::VP_SCATTER, VTs, Ops);
8457   ID.AddInteger(VT.getRawBits());
8458   ID.AddInteger(getSyntheticNodeSubclassData<VPScatterSDNode>(
8459       dl.getIROrder(), VTs, VT, MMO, IndexType));
8460   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8461   ID.AddInteger(MMO->getFlags());
8462   void *IP = nullptr;
8463   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
8464     cast<VPScatterSDNode>(E)->refineAlignment(MMO);
8465     return SDValue(E, 0);
8466   }
8467   auto *N = newSDNode<VPScatterSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
8468                                        VT, MMO, IndexType);
8469   createOperands(N, Ops);
8470 
8471   assert(N->getMask().getValueType().getVectorElementCount() ==
8472              N->getValue().getValueType().getVectorElementCount() &&
8473          "Vector width mismatch between mask and data");
8474   assert(
8475       N->getIndex().getValueType().getVectorElementCount().isScalable() ==
8476           N->getValue().getValueType().getVectorElementCount().isScalable() &&
8477       "Scalable flags of index and data do not match");
8478   assert(ElementCount::isKnownGE(
8479              N->getIndex().getValueType().getVectorElementCount(),
8480              N->getValue().getValueType().getVectorElementCount()) &&
8481          "Vector width mismatch between index and data");
8482   assert(isa<ConstantSDNode>(N->getScale()) &&
8483          cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() &&
8484          "Scale should be a constant power of 2");
8485 
8486   CSEMap.InsertNode(N, IP);
8487   InsertNode(N);
8488   SDValue V(N, 0);
8489   NewSDValueDbgMsg(V, "Creating new node: ", this);
8490   return V;
8491 }
8492 
8493 SDValue SelectionDAG::getMaskedLoad(EVT VT, const SDLoc &dl, SDValue Chain,
8494                                     SDValue Base, SDValue Offset, SDValue Mask,
8495                                     SDValue PassThru, EVT MemVT,
8496                                     MachineMemOperand *MMO,
8497                                     ISD::MemIndexedMode AM,
8498                                     ISD::LoadExtType ExtTy, bool isExpanding) {
8499   bool Indexed = AM != ISD::UNINDEXED;
8500   assert((Indexed || Offset.isUndef()) &&
8501          "Unindexed masked load with an offset!");
8502   SDVTList VTs = Indexed ? getVTList(VT, Base.getValueType(), MVT::Other)
8503                          : getVTList(VT, MVT::Other);
8504   SDValue Ops[] = {Chain, Base, Offset, Mask, PassThru};
8505   FoldingSetNodeID ID;
8506   AddNodeIDNode(ID, ISD::MLOAD, VTs, Ops);
8507   ID.AddInteger(MemVT.getRawBits());
8508   ID.AddInteger(getSyntheticNodeSubclassData<MaskedLoadSDNode>(
8509       dl.getIROrder(), VTs, AM, ExtTy, isExpanding, MemVT, MMO));
8510   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8511   ID.AddInteger(MMO->getFlags());
8512   void *IP = nullptr;
8513   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
8514     cast<MaskedLoadSDNode>(E)->refineAlignment(MMO);
8515     return SDValue(E, 0);
8516   }
8517   auto *N = newSDNode<MaskedLoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
8518                                         AM, ExtTy, isExpanding, MemVT, MMO);
8519   createOperands(N, Ops);
8520 
8521   CSEMap.InsertNode(N, IP);
8522   InsertNode(N);
8523   SDValue V(N, 0);
8524   NewSDValueDbgMsg(V, "Creating new node: ", this);
8525   return V;
8526 }
8527 
8528 SDValue SelectionDAG::getIndexedMaskedLoad(SDValue OrigLoad, const SDLoc &dl,
8529                                            SDValue Base, SDValue Offset,
8530                                            ISD::MemIndexedMode AM) {
8531   MaskedLoadSDNode *LD = cast<MaskedLoadSDNode>(OrigLoad);
8532   assert(LD->getOffset().isUndef() && "Masked load is already a indexed load!");
8533   return getMaskedLoad(OrigLoad.getValueType(), dl, LD->getChain(), Base,
8534                        Offset, LD->getMask(), LD->getPassThru(),
8535                        LD->getMemoryVT(), LD->getMemOperand(), AM,
8536                        LD->getExtensionType(), LD->isExpandingLoad());
8537 }
8538 
8539 SDValue SelectionDAG::getMaskedStore(SDValue Chain, const SDLoc &dl,
8540                                      SDValue Val, SDValue Base, SDValue Offset,
8541                                      SDValue Mask, EVT MemVT,
8542                                      MachineMemOperand *MMO,
8543                                      ISD::MemIndexedMode AM, bool IsTruncating,
8544                                      bool IsCompressing) {
8545   assert(Chain.getValueType() == MVT::Other &&
8546         "Invalid chain type");
8547   bool Indexed = AM != ISD::UNINDEXED;
8548   assert((Indexed || Offset.isUndef()) &&
8549          "Unindexed masked store with an offset!");
8550   SDVTList VTs = Indexed ? getVTList(Base.getValueType(), MVT::Other)
8551                          : getVTList(MVT::Other);
8552   SDValue Ops[] = {Chain, Val, Base, Offset, Mask};
8553   FoldingSetNodeID ID;
8554   AddNodeIDNode(ID, ISD::MSTORE, VTs, Ops);
8555   ID.AddInteger(MemVT.getRawBits());
8556   ID.AddInteger(getSyntheticNodeSubclassData<MaskedStoreSDNode>(
8557       dl.getIROrder(), VTs, AM, IsTruncating, IsCompressing, MemVT, MMO));
8558   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8559   ID.AddInteger(MMO->getFlags());
8560   void *IP = nullptr;
8561   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
8562     cast<MaskedStoreSDNode>(E)->refineAlignment(MMO);
8563     return SDValue(E, 0);
8564   }
8565   auto *N =
8566       newSDNode<MaskedStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
8567                                    IsTruncating, IsCompressing, MemVT, MMO);
8568   createOperands(N, Ops);
8569 
8570   CSEMap.InsertNode(N, IP);
8571   InsertNode(N);
8572   SDValue V(N, 0);
8573   NewSDValueDbgMsg(V, "Creating new node: ", this);
8574   return V;
8575 }
8576 
8577 SDValue SelectionDAG::getIndexedMaskedStore(SDValue OrigStore, const SDLoc &dl,
8578                                             SDValue Base, SDValue Offset,
8579                                             ISD::MemIndexedMode AM) {
8580   MaskedStoreSDNode *ST = cast<MaskedStoreSDNode>(OrigStore);
8581   assert(ST->getOffset().isUndef() &&
8582          "Masked store is already a indexed store!");
8583   return getMaskedStore(ST->getChain(), dl, ST->getValue(), Base, Offset,
8584                         ST->getMask(), ST->getMemoryVT(), ST->getMemOperand(),
8585                         AM, ST->isTruncatingStore(), ST->isCompressingStore());
8586 }
8587 
8588 SDValue SelectionDAG::getMaskedGather(SDVTList VTs, EVT MemVT, const SDLoc &dl,
8589                                       ArrayRef<SDValue> Ops,
8590                                       MachineMemOperand *MMO,
8591                                       ISD::MemIndexType IndexType,
8592                                       ISD::LoadExtType ExtTy) {
8593   assert(Ops.size() == 6 && "Incompatible number of operands");
8594 
8595   FoldingSetNodeID ID;
8596   AddNodeIDNode(ID, ISD::MGATHER, VTs, Ops);
8597   ID.AddInteger(MemVT.getRawBits());
8598   ID.AddInteger(getSyntheticNodeSubclassData<MaskedGatherSDNode>(
8599       dl.getIROrder(), VTs, MemVT, MMO, IndexType, ExtTy));
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<MaskedGatherSDNode>(E)->refineAlignment(MMO);
8605     return SDValue(E, 0);
8606   }
8607 
8608   IndexType = TLI->getCanonicalIndexType(IndexType, MemVT, Ops[4]);
8609   auto *N = newSDNode<MaskedGatherSDNode>(dl.getIROrder(), dl.getDebugLoc(),
8610                                           VTs, MemVT, MMO, IndexType, ExtTy);
8611   createOperands(N, Ops);
8612 
8613   assert(N->getPassThru().getValueType() == N->getValueType(0) &&
8614          "Incompatible type of the PassThru value in MaskedGatherSDNode");
8615   assert(N->getMask().getValueType().getVectorElementCount() ==
8616              N->getValueType(0).getVectorElementCount() &&
8617          "Vector width mismatch between mask and data");
8618   assert(N->getIndex().getValueType().getVectorElementCount().isScalable() ==
8619              N->getValueType(0).getVectorElementCount().isScalable() &&
8620          "Scalable flags of index and data do not match");
8621   assert(ElementCount::isKnownGE(
8622              N->getIndex().getValueType().getVectorElementCount(),
8623              N->getValueType(0).getVectorElementCount()) &&
8624          "Vector width mismatch between index and data");
8625   assert(isa<ConstantSDNode>(N->getScale()) &&
8626          cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() &&
8627          "Scale should be a constant power of 2");
8628 
8629   CSEMap.InsertNode(N, IP);
8630   InsertNode(N);
8631   SDValue V(N, 0);
8632   NewSDValueDbgMsg(V, "Creating new node: ", this);
8633   return V;
8634 }
8635 
8636 SDValue SelectionDAG::getMaskedScatter(SDVTList VTs, EVT MemVT, const SDLoc &dl,
8637                                        ArrayRef<SDValue> Ops,
8638                                        MachineMemOperand *MMO,
8639                                        ISD::MemIndexType IndexType,
8640                                        bool IsTrunc) {
8641   assert(Ops.size() == 6 && "Incompatible number of operands");
8642 
8643   FoldingSetNodeID ID;
8644   AddNodeIDNode(ID, ISD::MSCATTER, VTs, Ops);
8645   ID.AddInteger(MemVT.getRawBits());
8646   ID.AddInteger(getSyntheticNodeSubclassData<MaskedScatterSDNode>(
8647       dl.getIROrder(), VTs, MemVT, MMO, IndexType, IsTrunc));
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<MaskedScatterSDNode>(E)->refineAlignment(MMO);
8653     return SDValue(E, 0);
8654   }
8655 
8656   IndexType = TLI->getCanonicalIndexType(IndexType, MemVT, Ops[4]);
8657   auto *N = newSDNode<MaskedScatterSDNode>(dl.getIROrder(), dl.getDebugLoc(),
8658                                            VTs, MemVT, MMO, IndexType, IsTrunc);
8659   createOperands(N, Ops);
8660 
8661   assert(N->getMask().getValueType().getVectorElementCount() ==
8662              N->getValue().getValueType().getVectorElementCount() &&
8663          "Vector width mismatch between mask and data");
8664   assert(
8665       N->getIndex().getValueType().getVectorElementCount().isScalable() ==
8666           N->getValue().getValueType().getVectorElementCount().isScalable() &&
8667       "Scalable flags of index and data do not match");
8668   assert(ElementCount::isKnownGE(
8669              N->getIndex().getValueType().getVectorElementCount(),
8670              N->getValue().getValueType().getVectorElementCount()) &&
8671          "Vector width mismatch between index and data");
8672   assert(isa<ConstantSDNode>(N->getScale()) &&
8673          cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() &&
8674          "Scale should be a constant power of 2");
8675 
8676   CSEMap.InsertNode(N, IP);
8677   InsertNode(N);
8678   SDValue V(N, 0);
8679   NewSDValueDbgMsg(V, "Creating new node: ", this);
8680   return V;
8681 }
8682 
8683 SDValue SelectionDAG::simplifySelect(SDValue Cond, SDValue T, SDValue F) {
8684   // select undef, T, F --> T (if T is a constant), otherwise F
8685   // select, ?, undef, F --> F
8686   // select, ?, T, undef --> T
8687   if (Cond.isUndef())
8688     return isConstantValueOfAnyType(T) ? T : F;
8689   if (T.isUndef())
8690     return F;
8691   if (F.isUndef())
8692     return T;
8693 
8694   // select true, T, F --> T
8695   // select false, T, F --> F
8696   if (auto *CondC = dyn_cast<ConstantSDNode>(Cond))
8697     return CondC->isZero() ? F : T;
8698 
8699   // TODO: This should simplify VSELECT with constant condition using something
8700   // like this (but check boolean contents to be complete?):
8701   //  if (ISD::isBuildVectorAllOnes(Cond.getNode()))
8702   //    return T;
8703   //  if (ISD::isBuildVectorAllZeros(Cond.getNode()))
8704   //    return F;
8705 
8706   // select ?, T, T --> T
8707   if (T == F)
8708     return T;
8709 
8710   return SDValue();
8711 }
8712 
8713 SDValue SelectionDAG::simplifyShift(SDValue X, SDValue Y) {
8714   // shift undef, Y --> 0 (can always assume that the undef value is 0)
8715   if (X.isUndef())
8716     return getConstant(0, SDLoc(X.getNode()), X.getValueType());
8717   // shift X, undef --> undef (because it may shift by the bitwidth)
8718   if (Y.isUndef())
8719     return getUNDEF(X.getValueType());
8720 
8721   // shift 0, Y --> 0
8722   // shift X, 0 --> X
8723   if (isNullOrNullSplat(X) || isNullOrNullSplat(Y))
8724     return X;
8725 
8726   // shift X, C >= bitwidth(X) --> undef
8727   // All vector elements must be too big (or undef) to avoid partial undefs.
8728   auto isShiftTooBig = [X](ConstantSDNode *Val) {
8729     return !Val || Val->getAPIntValue().uge(X.getScalarValueSizeInBits());
8730   };
8731   if (ISD::matchUnaryPredicate(Y, isShiftTooBig, true))
8732     return getUNDEF(X.getValueType());
8733 
8734   return SDValue();
8735 }
8736 
8737 SDValue SelectionDAG::simplifyFPBinop(unsigned Opcode, SDValue X, SDValue Y,
8738                                       SDNodeFlags Flags) {
8739   // If this operation has 'nnan' or 'ninf' and at least 1 disallowed operand
8740   // (an undef operand can be chosen to be Nan/Inf), then the result of this
8741   // operation is poison. That result can be relaxed to undef.
8742   ConstantFPSDNode *XC = isConstOrConstSplatFP(X, /* AllowUndefs */ true);
8743   ConstantFPSDNode *YC = isConstOrConstSplatFP(Y, /* AllowUndefs */ true);
8744   bool HasNan = (XC && XC->getValueAPF().isNaN()) ||
8745                 (YC && YC->getValueAPF().isNaN());
8746   bool HasInf = (XC && XC->getValueAPF().isInfinity()) ||
8747                 (YC && YC->getValueAPF().isInfinity());
8748 
8749   if (Flags.hasNoNaNs() && (HasNan || X.isUndef() || Y.isUndef()))
8750     return getUNDEF(X.getValueType());
8751 
8752   if (Flags.hasNoInfs() && (HasInf || X.isUndef() || Y.isUndef()))
8753     return getUNDEF(X.getValueType());
8754 
8755   if (!YC)
8756     return SDValue();
8757 
8758   // X + -0.0 --> X
8759   if (Opcode == ISD::FADD)
8760     if (YC->getValueAPF().isNegZero())
8761       return X;
8762 
8763   // X - +0.0 --> X
8764   if (Opcode == ISD::FSUB)
8765     if (YC->getValueAPF().isPosZero())
8766       return X;
8767 
8768   // X * 1.0 --> X
8769   // X / 1.0 --> X
8770   if (Opcode == ISD::FMUL || Opcode == ISD::FDIV)
8771     if (YC->getValueAPF().isExactlyValue(1.0))
8772       return X;
8773 
8774   // X * 0.0 --> 0.0
8775   if (Opcode == ISD::FMUL && Flags.hasNoNaNs() && Flags.hasNoSignedZeros())
8776     if (YC->getValueAPF().isZero())
8777       return getConstantFP(0.0, SDLoc(Y), Y.getValueType());
8778 
8779   return SDValue();
8780 }
8781 
8782 SDValue SelectionDAG::getVAArg(EVT VT, const SDLoc &dl, SDValue Chain,
8783                                SDValue Ptr, SDValue SV, unsigned Align) {
8784   SDValue Ops[] = { Chain, Ptr, SV, getTargetConstant(Align, dl, MVT::i32) };
8785   return getNode(ISD::VAARG, dl, getVTList(VT, MVT::Other), Ops);
8786 }
8787 
8788 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
8789                               ArrayRef<SDUse> Ops) {
8790   switch (Ops.size()) {
8791   case 0: return getNode(Opcode, DL, VT);
8792   case 1: return getNode(Opcode, DL, VT, static_cast<const SDValue>(Ops[0]));
8793   case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1]);
8794   case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2]);
8795   default: break;
8796   }
8797 
8798   // Copy from an SDUse array into an SDValue array for use with
8799   // the regular getNode logic.
8800   SmallVector<SDValue, 8> NewOps(Ops.begin(), Ops.end());
8801   return getNode(Opcode, DL, VT, NewOps);
8802 }
8803 
8804 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
8805                               ArrayRef<SDValue> Ops) {
8806   SDNodeFlags Flags;
8807   if (Inserter)
8808     Flags = Inserter->getFlags();
8809   return getNode(Opcode, DL, VT, Ops, Flags);
8810 }
8811 
8812 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
8813                               ArrayRef<SDValue> Ops, const SDNodeFlags Flags) {
8814   unsigned NumOps = Ops.size();
8815   switch (NumOps) {
8816   case 0: return getNode(Opcode, DL, VT);
8817   case 1: return getNode(Opcode, DL, VT, Ops[0], Flags);
8818   case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Flags);
8819   case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2], Flags);
8820   default: break;
8821   }
8822 
8823 #ifndef NDEBUG
8824   for (auto &Op : Ops)
8825     assert(Op.getOpcode() != ISD::DELETED_NODE &&
8826            "Operand is DELETED_NODE!");
8827 #endif
8828 
8829   switch (Opcode) {
8830   default: break;
8831   case ISD::BUILD_VECTOR:
8832     // Attempt to simplify BUILD_VECTOR.
8833     if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
8834       return V;
8835     break;
8836   case ISD::CONCAT_VECTORS:
8837     if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this))
8838       return V;
8839     break;
8840   case ISD::SELECT_CC:
8841     assert(NumOps == 5 && "SELECT_CC takes 5 operands!");
8842     assert(Ops[0].getValueType() == Ops[1].getValueType() &&
8843            "LHS and RHS of condition must have same type!");
8844     assert(Ops[2].getValueType() == Ops[3].getValueType() &&
8845            "True and False arms of SelectCC must have same type!");
8846     assert(Ops[2].getValueType() == VT &&
8847            "select_cc node must be of same type as true and false value!");
8848     break;
8849   case ISD::BR_CC:
8850     assert(NumOps == 5 && "BR_CC takes 5 operands!");
8851     assert(Ops[2].getValueType() == Ops[3].getValueType() &&
8852            "LHS/RHS of comparison should match types!");
8853     break;
8854   case ISD::VP_ADD:
8855   case ISD::VP_SUB:
8856     // If it is VP_ADD/VP_SUB mask operation then turn it to VP_XOR
8857     if (VT.isVector() && VT.getVectorElementType() == MVT::i1)
8858       Opcode = ISD::VP_XOR;
8859     break;
8860   case ISD::VP_MUL:
8861     // If it is VP_MUL mask operation then turn it to VP_AND
8862     if (VT.isVector() && VT.getVectorElementType() == MVT::i1)
8863       Opcode = ISD::VP_AND;
8864     break;
8865   case ISD::VP_REDUCE_ADD:
8866     // If it is VP_REDUCE_ADD mask operation then turn it to VP_REDUCE_XOR
8867     if (VT == MVT::i1)
8868       Opcode = ISD::VP_REDUCE_XOR;
8869     break;
8870   }
8871 
8872   // Memoize nodes.
8873   SDNode *N;
8874   SDVTList VTs = getVTList(VT);
8875 
8876   if (VT != MVT::Glue) {
8877     FoldingSetNodeID ID;
8878     AddNodeIDNode(ID, Opcode, VTs, Ops);
8879     void *IP = nullptr;
8880 
8881     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
8882       return SDValue(E, 0);
8883 
8884     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
8885     createOperands(N, Ops);
8886 
8887     CSEMap.InsertNode(N, IP);
8888   } else {
8889     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
8890     createOperands(N, Ops);
8891   }
8892 
8893   N->setFlags(Flags);
8894   InsertNode(N);
8895   SDValue V(N, 0);
8896   NewSDValueDbgMsg(V, "Creating new node: ", this);
8897   return V;
8898 }
8899 
8900 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL,
8901                               ArrayRef<EVT> ResultTys, ArrayRef<SDValue> Ops) {
8902   return getNode(Opcode, DL, getVTList(ResultTys), Ops);
8903 }
8904 
8905 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
8906                               ArrayRef<SDValue> Ops) {
8907   SDNodeFlags Flags;
8908   if (Inserter)
8909     Flags = Inserter->getFlags();
8910   return getNode(Opcode, DL, VTList, Ops, Flags);
8911 }
8912 
8913 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
8914                               ArrayRef<SDValue> Ops, const SDNodeFlags Flags) {
8915   if (VTList.NumVTs == 1)
8916     return getNode(Opcode, DL, VTList.VTs[0], Ops);
8917 
8918 #ifndef NDEBUG
8919   for (auto &Op : Ops)
8920     assert(Op.getOpcode() != ISD::DELETED_NODE &&
8921            "Operand is DELETED_NODE!");
8922 #endif
8923 
8924   switch (Opcode) {
8925   case ISD::STRICT_FP_EXTEND:
8926     assert(VTList.NumVTs == 2 && Ops.size() == 2 &&
8927            "Invalid STRICT_FP_EXTEND!");
8928     assert(VTList.VTs[0].isFloatingPoint() &&
8929            Ops[1].getValueType().isFloatingPoint() && "Invalid FP cast!");
8930     assert(VTList.VTs[0].isVector() == Ops[1].getValueType().isVector() &&
8931            "STRICT_FP_EXTEND result type should be vector iff the operand "
8932            "type is vector!");
8933     assert((!VTList.VTs[0].isVector() ||
8934             VTList.VTs[0].getVectorNumElements() ==
8935             Ops[1].getValueType().getVectorNumElements()) &&
8936            "Vector element count mismatch!");
8937     assert(Ops[1].getValueType().bitsLT(VTList.VTs[0]) &&
8938            "Invalid fpext node, dst <= src!");
8939     break;
8940   case ISD::STRICT_FP_ROUND:
8941     assert(VTList.NumVTs == 2 && Ops.size() == 3 && "Invalid STRICT_FP_ROUND!");
8942     assert(VTList.VTs[0].isVector() == Ops[1].getValueType().isVector() &&
8943            "STRICT_FP_ROUND result type should be vector iff the operand "
8944            "type is vector!");
8945     assert((!VTList.VTs[0].isVector() ||
8946             VTList.VTs[0].getVectorNumElements() ==
8947             Ops[1].getValueType().getVectorNumElements()) &&
8948            "Vector element count mismatch!");
8949     assert(VTList.VTs[0].isFloatingPoint() &&
8950            Ops[1].getValueType().isFloatingPoint() &&
8951            VTList.VTs[0].bitsLT(Ops[1].getValueType()) &&
8952            isa<ConstantSDNode>(Ops[2]) &&
8953            (cast<ConstantSDNode>(Ops[2])->getZExtValue() == 0 ||
8954             cast<ConstantSDNode>(Ops[2])->getZExtValue() == 1) &&
8955            "Invalid STRICT_FP_ROUND!");
8956     break;
8957 #if 0
8958   // FIXME: figure out how to safely handle things like
8959   // int foo(int x) { return 1 << (x & 255); }
8960   // int bar() { return foo(256); }
8961   case ISD::SRA_PARTS:
8962   case ISD::SRL_PARTS:
8963   case ISD::SHL_PARTS:
8964     if (N3.getOpcode() == ISD::SIGN_EXTEND_INREG &&
8965         cast<VTSDNode>(N3.getOperand(1))->getVT() != MVT::i1)
8966       return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0));
8967     else if (N3.getOpcode() == ISD::AND)
8968       if (ConstantSDNode *AndRHS = dyn_cast<ConstantSDNode>(N3.getOperand(1))) {
8969         // If the and is only masking out bits that cannot effect the shift,
8970         // eliminate the and.
8971         unsigned NumBits = VT.getScalarSizeInBits()*2;
8972         if ((AndRHS->getValue() & (NumBits-1)) == NumBits-1)
8973           return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0));
8974       }
8975     break;
8976 #endif
8977   }
8978 
8979   // Memoize the node unless it returns a flag.
8980   SDNode *N;
8981   if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) {
8982     FoldingSetNodeID ID;
8983     AddNodeIDNode(ID, Opcode, VTList, Ops);
8984     void *IP = nullptr;
8985     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
8986       return SDValue(E, 0);
8987 
8988     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList);
8989     createOperands(N, Ops);
8990     CSEMap.InsertNode(N, IP);
8991   } else {
8992     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList);
8993     createOperands(N, Ops);
8994   }
8995 
8996   N->setFlags(Flags);
8997   InsertNode(N);
8998   SDValue V(N, 0);
8999   NewSDValueDbgMsg(V, "Creating new node: ", this);
9000   return V;
9001 }
9002 
9003 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL,
9004                               SDVTList VTList) {
9005   return getNode(Opcode, DL, VTList, None);
9006 }
9007 
9008 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
9009                               SDValue N1) {
9010   SDValue Ops[] = { N1 };
9011   return getNode(Opcode, DL, VTList, Ops);
9012 }
9013 
9014 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
9015                               SDValue N1, SDValue N2) {
9016   SDValue Ops[] = { N1, N2 };
9017   return getNode(Opcode, DL, VTList, Ops);
9018 }
9019 
9020 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
9021                               SDValue N1, SDValue N2, SDValue N3) {
9022   SDValue Ops[] = { N1, N2, N3 };
9023   return getNode(Opcode, DL, VTList, Ops);
9024 }
9025 
9026 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
9027                               SDValue N1, SDValue N2, SDValue N3, SDValue N4) {
9028   SDValue Ops[] = { N1, N2, N3, N4 };
9029   return getNode(Opcode, DL, VTList, Ops);
9030 }
9031 
9032 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
9033                               SDValue N1, SDValue N2, SDValue N3, SDValue N4,
9034                               SDValue N5) {
9035   SDValue Ops[] = { N1, N2, N3, N4, N5 };
9036   return getNode(Opcode, DL, VTList, Ops);
9037 }
9038 
9039 SDVTList SelectionDAG::getVTList(EVT VT) {
9040   return makeVTList(SDNode::getValueTypeList(VT), 1);
9041 }
9042 
9043 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2) {
9044   FoldingSetNodeID ID;
9045   ID.AddInteger(2U);
9046   ID.AddInteger(VT1.getRawBits());
9047   ID.AddInteger(VT2.getRawBits());
9048 
9049   void *IP = nullptr;
9050   SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
9051   if (!Result) {
9052     EVT *Array = Allocator.Allocate<EVT>(2);
9053     Array[0] = VT1;
9054     Array[1] = VT2;
9055     Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 2);
9056     VTListMap.InsertNode(Result, IP);
9057   }
9058   return Result->getSDVTList();
9059 }
9060 
9061 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3) {
9062   FoldingSetNodeID ID;
9063   ID.AddInteger(3U);
9064   ID.AddInteger(VT1.getRawBits());
9065   ID.AddInteger(VT2.getRawBits());
9066   ID.AddInteger(VT3.getRawBits());
9067 
9068   void *IP = nullptr;
9069   SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
9070   if (!Result) {
9071     EVT *Array = Allocator.Allocate<EVT>(3);
9072     Array[0] = VT1;
9073     Array[1] = VT2;
9074     Array[2] = VT3;
9075     Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 3);
9076     VTListMap.InsertNode(Result, IP);
9077   }
9078   return Result->getSDVTList();
9079 }
9080 
9081 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3, EVT VT4) {
9082   FoldingSetNodeID ID;
9083   ID.AddInteger(4U);
9084   ID.AddInteger(VT1.getRawBits());
9085   ID.AddInteger(VT2.getRawBits());
9086   ID.AddInteger(VT3.getRawBits());
9087   ID.AddInteger(VT4.getRawBits());
9088 
9089   void *IP = nullptr;
9090   SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
9091   if (!Result) {
9092     EVT *Array = Allocator.Allocate<EVT>(4);
9093     Array[0] = VT1;
9094     Array[1] = VT2;
9095     Array[2] = VT3;
9096     Array[3] = VT4;
9097     Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 4);
9098     VTListMap.InsertNode(Result, IP);
9099   }
9100   return Result->getSDVTList();
9101 }
9102 
9103 SDVTList SelectionDAG::getVTList(ArrayRef<EVT> VTs) {
9104   unsigned NumVTs = VTs.size();
9105   FoldingSetNodeID ID;
9106   ID.AddInteger(NumVTs);
9107   for (unsigned index = 0; index < NumVTs; index++) {
9108     ID.AddInteger(VTs[index].getRawBits());
9109   }
9110 
9111   void *IP = nullptr;
9112   SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
9113   if (!Result) {
9114     EVT *Array = Allocator.Allocate<EVT>(NumVTs);
9115     llvm::copy(VTs, Array);
9116     Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, NumVTs);
9117     VTListMap.InsertNode(Result, IP);
9118   }
9119   return Result->getSDVTList();
9120 }
9121 
9122 
9123 /// UpdateNodeOperands - *Mutate* the specified node in-place to have the
9124 /// specified operands.  If the resultant node already exists in the DAG,
9125 /// this does not modify the specified node, instead it returns the node that
9126 /// already exists.  If the resultant node does not exist in the DAG, the
9127 /// input node is returned.  As a degenerate case, if you specify the same
9128 /// input operands as the node already has, the input node is returned.
9129 SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op) {
9130   assert(N->getNumOperands() == 1 && "Update with wrong number of operands");
9131 
9132   // Check to see if there is no change.
9133   if (Op == N->getOperand(0)) return N;
9134 
9135   // See if the modified node already exists.
9136   void *InsertPos = nullptr;
9137   if (SDNode *Existing = FindModifiedNodeSlot(N, Op, InsertPos))
9138     return Existing;
9139 
9140   // Nope it doesn't.  Remove the node from its current place in the maps.
9141   if (InsertPos)
9142     if (!RemoveNodeFromCSEMaps(N))
9143       InsertPos = nullptr;
9144 
9145   // Now we update the operands.
9146   N->OperandList[0].set(Op);
9147 
9148   updateDivergence(N);
9149   // If this gets put into a CSE map, add it.
9150   if (InsertPos) CSEMap.InsertNode(N, InsertPos);
9151   return N;
9152 }
9153 
9154 SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2) {
9155   assert(N->getNumOperands() == 2 && "Update with wrong number of operands");
9156 
9157   // Check to see if there is no change.
9158   if (Op1 == N->getOperand(0) && Op2 == N->getOperand(1))
9159     return N;   // No operands changed, just return the input node.
9160 
9161   // See if the modified node already exists.
9162   void *InsertPos = nullptr;
9163   if (SDNode *Existing = FindModifiedNodeSlot(N, Op1, Op2, InsertPos))
9164     return Existing;
9165 
9166   // Nope it doesn't.  Remove the node from its current place in the maps.
9167   if (InsertPos)
9168     if (!RemoveNodeFromCSEMaps(N))
9169       InsertPos = nullptr;
9170 
9171   // Now we update the operands.
9172   if (N->OperandList[0] != Op1)
9173     N->OperandList[0].set(Op1);
9174   if (N->OperandList[1] != Op2)
9175     N->OperandList[1].set(Op2);
9176 
9177   updateDivergence(N);
9178   // If this gets put into a CSE map, add it.
9179   if (InsertPos) CSEMap.InsertNode(N, InsertPos);
9180   return N;
9181 }
9182 
9183 SDNode *SelectionDAG::
9184 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2, SDValue Op3) {
9185   SDValue Ops[] = { Op1, Op2, Op3 };
9186   return UpdateNodeOperands(N, Ops);
9187 }
9188 
9189 SDNode *SelectionDAG::
9190 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2,
9191                    SDValue Op3, SDValue Op4) {
9192   SDValue Ops[] = { Op1, Op2, Op3, Op4 };
9193   return UpdateNodeOperands(N, Ops);
9194 }
9195 
9196 SDNode *SelectionDAG::
9197 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2,
9198                    SDValue Op3, SDValue Op4, SDValue Op5) {
9199   SDValue Ops[] = { Op1, Op2, Op3, Op4, Op5 };
9200   return UpdateNodeOperands(N, Ops);
9201 }
9202 
9203 SDNode *SelectionDAG::
9204 UpdateNodeOperands(SDNode *N, ArrayRef<SDValue> Ops) {
9205   unsigned NumOps = Ops.size();
9206   assert(N->getNumOperands() == NumOps &&
9207          "Update with wrong number of operands");
9208 
9209   // If no operands changed just return the input node.
9210   if (std::equal(Ops.begin(), Ops.end(), N->op_begin()))
9211     return N;
9212 
9213   // See if the modified node already exists.
9214   void *InsertPos = nullptr;
9215   if (SDNode *Existing = FindModifiedNodeSlot(N, Ops, InsertPos))
9216     return Existing;
9217 
9218   // Nope it doesn't.  Remove the node from its current place in the maps.
9219   if (InsertPos)
9220     if (!RemoveNodeFromCSEMaps(N))
9221       InsertPos = nullptr;
9222 
9223   // Now we update the operands.
9224   for (unsigned i = 0; i != NumOps; ++i)
9225     if (N->OperandList[i] != Ops[i])
9226       N->OperandList[i].set(Ops[i]);
9227 
9228   updateDivergence(N);
9229   // If this gets put into a CSE map, add it.
9230   if (InsertPos) CSEMap.InsertNode(N, InsertPos);
9231   return N;
9232 }
9233 
9234 /// DropOperands - Release the operands and set this node to have
9235 /// zero operands.
9236 void SDNode::DropOperands() {
9237   // Unlike the code in MorphNodeTo that does this, we don't need to
9238   // watch for dead nodes here.
9239   for (op_iterator I = op_begin(), E = op_end(); I != E; ) {
9240     SDUse &Use = *I++;
9241     Use.set(SDValue());
9242   }
9243 }
9244 
9245 void SelectionDAG::setNodeMemRefs(MachineSDNode *N,
9246                                   ArrayRef<MachineMemOperand *> NewMemRefs) {
9247   if (NewMemRefs.empty()) {
9248     N->clearMemRefs();
9249     return;
9250   }
9251 
9252   // Check if we can avoid allocating by storing a single reference directly.
9253   if (NewMemRefs.size() == 1) {
9254     N->MemRefs = NewMemRefs[0];
9255     N->NumMemRefs = 1;
9256     return;
9257   }
9258 
9259   MachineMemOperand **MemRefsBuffer =
9260       Allocator.template Allocate<MachineMemOperand *>(NewMemRefs.size());
9261   llvm::copy(NewMemRefs, MemRefsBuffer);
9262   N->MemRefs = MemRefsBuffer;
9263   N->NumMemRefs = static_cast<int>(NewMemRefs.size());
9264 }
9265 
9266 /// SelectNodeTo - These are wrappers around MorphNodeTo that accept a
9267 /// machine opcode.
9268 ///
9269 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
9270                                    EVT VT) {
9271   SDVTList VTs = getVTList(VT);
9272   return SelectNodeTo(N, MachineOpc, VTs, None);
9273 }
9274 
9275 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
9276                                    EVT VT, SDValue Op1) {
9277   SDVTList VTs = getVTList(VT);
9278   SDValue Ops[] = { Op1 };
9279   return SelectNodeTo(N, MachineOpc, VTs, Ops);
9280 }
9281 
9282 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
9283                                    EVT VT, SDValue Op1,
9284                                    SDValue Op2) {
9285   SDVTList VTs = getVTList(VT);
9286   SDValue Ops[] = { Op1, Op2 };
9287   return SelectNodeTo(N, MachineOpc, VTs, Ops);
9288 }
9289 
9290 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
9291                                    EVT VT, SDValue Op1,
9292                                    SDValue Op2, SDValue Op3) {
9293   SDVTList VTs = getVTList(VT);
9294   SDValue Ops[] = { Op1, Op2, Op3 };
9295   return SelectNodeTo(N, MachineOpc, VTs, Ops);
9296 }
9297 
9298 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
9299                                    EVT VT, ArrayRef<SDValue> Ops) {
9300   SDVTList VTs = getVTList(VT);
9301   return SelectNodeTo(N, MachineOpc, VTs, Ops);
9302 }
9303 
9304 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
9305                                    EVT VT1, EVT VT2, ArrayRef<SDValue> Ops) {
9306   SDVTList VTs = getVTList(VT1, VT2);
9307   return SelectNodeTo(N, MachineOpc, VTs, Ops);
9308 }
9309 
9310 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
9311                                    EVT VT1, EVT VT2) {
9312   SDVTList VTs = getVTList(VT1, VT2);
9313   return SelectNodeTo(N, MachineOpc, VTs, None);
9314 }
9315 
9316 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
9317                                    EVT VT1, EVT VT2, EVT VT3,
9318                                    ArrayRef<SDValue> Ops) {
9319   SDVTList VTs = getVTList(VT1, VT2, VT3);
9320   return SelectNodeTo(N, MachineOpc, VTs, Ops);
9321 }
9322 
9323 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
9324                                    EVT VT1, EVT VT2,
9325                                    SDValue Op1, SDValue Op2) {
9326   SDVTList VTs = getVTList(VT1, VT2);
9327   SDValue Ops[] = { Op1, Op2 };
9328   return SelectNodeTo(N, MachineOpc, VTs, Ops);
9329 }
9330 
9331 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
9332                                    SDVTList VTs,ArrayRef<SDValue> Ops) {
9333   SDNode *New = MorphNodeTo(N, ~MachineOpc, VTs, Ops);
9334   // Reset the NodeID to -1.
9335   New->setNodeId(-1);
9336   if (New != N) {
9337     ReplaceAllUsesWith(N, New);
9338     RemoveDeadNode(N);
9339   }
9340   return New;
9341 }
9342 
9343 /// UpdateSDLocOnMergeSDNode - If the opt level is -O0 then it throws away
9344 /// the line number information on the merged node since it is not possible to
9345 /// preserve the information that operation is associated with multiple lines.
9346 /// This will make the debugger working better at -O0, were there is a higher
9347 /// probability having other instructions associated with that line.
9348 ///
9349 /// For IROrder, we keep the smaller of the two
9350 SDNode *SelectionDAG::UpdateSDLocOnMergeSDNode(SDNode *N, const SDLoc &OLoc) {
9351   DebugLoc NLoc = N->getDebugLoc();
9352   if (NLoc && OptLevel == CodeGenOpt::None && OLoc.getDebugLoc() != NLoc) {
9353     N->setDebugLoc(DebugLoc());
9354   }
9355   unsigned Order = std::min(N->getIROrder(), OLoc.getIROrder());
9356   N->setIROrder(Order);
9357   return N;
9358 }
9359 
9360 /// MorphNodeTo - This *mutates* the specified node to have the specified
9361 /// return type, opcode, and operands.
9362 ///
9363 /// Note that MorphNodeTo returns the resultant node.  If there is already a
9364 /// node of the specified opcode and operands, it returns that node instead of
9365 /// the current one.  Note that the SDLoc need not be the same.
9366 ///
9367 /// Using MorphNodeTo is faster than creating a new node and swapping it in
9368 /// with ReplaceAllUsesWith both because it often avoids allocating a new
9369 /// node, and because it doesn't require CSE recalculation for any of
9370 /// the node's users.
9371 ///
9372 /// However, note that MorphNodeTo recursively deletes dead nodes from the DAG.
9373 /// As a consequence it isn't appropriate to use from within the DAG combiner or
9374 /// the legalizer which maintain worklists that would need to be updated when
9375 /// deleting things.
9376 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
9377                                   SDVTList VTs, ArrayRef<SDValue> Ops) {
9378   // If an identical node already exists, use it.
9379   void *IP = nullptr;
9380   if (VTs.VTs[VTs.NumVTs-1] != MVT::Glue) {
9381     FoldingSetNodeID ID;
9382     AddNodeIDNode(ID, Opc, VTs, Ops);
9383     if (SDNode *ON = FindNodeOrInsertPos(ID, SDLoc(N), IP))
9384       return UpdateSDLocOnMergeSDNode(ON, SDLoc(N));
9385   }
9386 
9387   if (!RemoveNodeFromCSEMaps(N))
9388     IP = nullptr;
9389 
9390   // Start the morphing.
9391   N->NodeType = Opc;
9392   N->ValueList = VTs.VTs;
9393   N->NumValues = VTs.NumVTs;
9394 
9395   // Clear the operands list, updating used nodes to remove this from their
9396   // use list.  Keep track of any operands that become dead as a result.
9397   SmallPtrSet<SDNode*, 16> DeadNodeSet;
9398   for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) {
9399     SDUse &Use = *I++;
9400     SDNode *Used = Use.getNode();
9401     Use.set(SDValue());
9402     if (Used->use_empty())
9403       DeadNodeSet.insert(Used);
9404   }
9405 
9406   // For MachineNode, initialize the memory references information.
9407   if (MachineSDNode *MN = dyn_cast<MachineSDNode>(N))
9408     MN->clearMemRefs();
9409 
9410   // Swap for an appropriately sized array from the recycler.
9411   removeOperands(N);
9412   createOperands(N, Ops);
9413 
9414   // Delete any nodes that are still dead after adding the uses for the
9415   // new operands.
9416   if (!DeadNodeSet.empty()) {
9417     SmallVector<SDNode *, 16> DeadNodes;
9418     for (SDNode *N : DeadNodeSet)
9419       if (N->use_empty())
9420         DeadNodes.push_back(N);
9421     RemoveDeadNodes(DeadNodes);
9422   }
9423 
9424   if (IP)
9425     CSEMap.InsertNode(N, IP);   // Memoize the new node.
9426   return N;
9427 }
9428 
9429 SDNode* SelectionDAG::mutateStrictFPToFP(SDNode *Node) {
9430   unsigned OrigOpc = Node->getOpcode();
9431   unsigned NewOpc;
9432   switch (OrigOpc) {
9433   default:
9434     llvm_unreachable("mutateStrictFPToFP called with unexpected opcode!");
9435 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN)               \
9436   case ISD::STRICT_##DAGN: NewOpc = ISD::DAGN; break;
9437 #define CMP_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN)               \
9438   case ISD::STRICT_##DAGN: NewOpc = ISD::SETCC; break;
9439 #include "llvm/IR/ConstrainedOps.def"
9440   }
9441 
9442   assert(Node->getNumValues() == 2 && "Unexpected number of results!");
9443 
9444   // We're taking this node out of the chain, so we need to re-link things.
9445   SDValue InputChain = Node->getOperand(0);
9446   SDValue OutputChain = SDValue(Node, 1);
9447   ReplaceAllUsesOfValueWith(OutputChain, InputChain);
9448 
9449   SmallVector<SDValue, 3> Ops;
9450   for (unsigned i = 1, e = Node->getNumOperands(); i != e; ++i)
9451     Ops.push_back(Node->getOperand(i));
9452 
9453   SDVTList VTs = getVTList(Node->getValueType(0));
9454   SDNode *Res = MorphNodeTo(Node, NewOpc, VTs, Ops);
9455 
9456   // MorphNodeTo can operate in two ways: if an existing node with the
9457   // specified operands exists, it can just return it.  Otherwise, it
9458   // updates the node in place to have the requested operands.
9459   if (Res == Node) {
9460     // If we updated the node in place, reset the node ID.  To the isel,
9461     // this should be just like a newly allocated machine node.
9462     Res->setNodeId(-1);
9463   } else {
9464     ReplaceAllUsesWith(Node, Res);
9465     RemoveDeadNode(Node);
9466   }
9467 
9468   return Res;
9469 }
9470 
9471 /// getMachineNode - These are used for target selectors to create a new node
9472 /// with specified return type(s), MachineInstr opcode, and operands.
9473 ///
9474 /// Note that getMachineNode returns the resultant node.  If there is already a
9475 /// node of the specified opcode and operands, it returns that node instead of
9476 /// the current one.
9477 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9478                                             EVT VT) {
9479   SDVTList VTs = getVTList(VT);
9480   return getMachineNode(Opcode, dl, VTs, None);
9481 }
9482 
9483 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9484                                             EVT VT, SDValue Op1) {
9485   SDVTList VTs = getVTList(VT);
9486   SDValue Ops[] = { Op1 };
9487   return getMachineNode(Opcode, dl, VTs, Ops);
9488 }
9489 
9490 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9491                                             EVT VT, SDValue Op1, SDValue Op2) {
9492   SDVTList VTs = getVTList(VT);
9493   SDValue Ops[] = { Op1, Op2 };
9494   return getMachineNode(Opcode, dl, VTs, Ops);
9495 }
9496 
9497 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9498                                             EVT VT, SDValue Op1, SDValue Op2,
9499                                             SDValue Op3) {
9500   SDVTList VTs = getVTList(VT);
9501   SDValue Ops[] = { Op1, Op2, Op3 };
9502   return getMachineNode(Opcode, dl, VTs, Ops);
9503 }
9504 
9505 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9506                                             EVT VT, ArrayRef<SDValue> Ops) {
9507   SDVTList VTs = getVTList(VT);
9508   return getMachineNode(Opcode, dl, VTs, Ops);
9509 }
9510 
9511 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9512                                             EVT VT1, EVT VT2, SDValue Op1,
9513                                             SDValue Op2) {
9514   SDVTList VTs = getVTList(VT1, VT2);
9515   SDValue Ops[] = { Op1, Op2 };
9516   return getMachineNode(Opcode, dl, VTs, Ops);
9517 }
9518 
9519 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9520                                             EVT VT1, EVT VT2, SDValue Op1,
9521                                             SDValue Op2, SDValue Op3) {
9522   SDVTList VTs = getVTList(VT1, VT2);
9523   SDValue Ops[] = { Op1, Op2, Op3 };
9524   return getMachineNode(Opcode, dl, VTs, Ops);
9525 }
9526 
9527 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9528                                             EVT VT1, EVT VT2,
9529                                             ArrayRef<SDValue> Ops) {
9530   SDVTList VTs = getVTList(VT1, VT2);
9531   return getMachineNode(Opcode, dl, VTs, Ops);
9532 }
9533 
9534 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9535                                             EVT VT1, EVT VT2, EVT VT3,
9536                                             SDValue Op1, SDValue Op2) {
9537   SDVTList VTs = getVTList(VT1, VT2, VT3);
9538   SDValue Ops[] = { Op1, Op2 };
9539   return getMachineNode(Opcode, dl, VTs, Ops);
9540 }
9541 
9542 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9543                                             EVT VT1, EVT VT2, EVT VT3,
9544                                             SDValue Op1, SDValue Op2,
9545                                             SDValue Op3) {
9546   SDVTList VTs = getVTList(VT1, VT2, VT3);
9547   SDValue Ops[] = { Op1, Op2, Op3 };
9548   return getMachineNode(Opcode, dl, VTs, Ops);
9549 }
9550 
9551 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9552                                             EVT VT1, EVT VT2, EVT VT3,
9553                                             ArrayRef<SDValue> Ops) {
9554   SDVTList VTs = getVTList(VT1, VT2, VT3);
9555   return getMachineNode(Opcode, dl, VTs, Ops);
9556 }
9557 
9558 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9559                                             ArrayRef<EVT> ResultTys,
9560                                             ArrayRef<SDValue> Ops) {
9561   SDVTList VTs = getVTList(ResultTys);
9562   return getMachineNode(Opcode, dl, VTs, Ops);
9563 }
9564 
9565 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &DL,
9566                                             SDVTList VTs,
9567                                             ArrayRef<SDValue> Ops) {
9568   bool DoCSE = VTs.VTs[VTs.NumVTs-1] != MVT::Glue;
9569   MachineSDNode *N;
9570   void *IP = nullptr;
9571 
9572   if (DoCSE) {
9573     FoldingSetNodeID ID;
9574     AddNodeIDNode(ID, ~Opcode, VTs, Ops);
9575     IP = nullptr;
9576     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
9577       return cast<MachineSDNode>(UpdateSDLocOnMergeSDNode(E, DL));
9578     }
9579   }
9580 
9581   // Allocate a new MachineSDNode.
9582   N = newSDNode<MachineSDNode>(~Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
9583   createOperands(N, Ops);
9584 
9585   if (DoCSE)
9586     CSEMap.InsertNode(N, IP);
9587 
9588   InsertNode(N);
9589   NewSDValueDbgMsg(SDValue(N, 0), "Creating new machine node: ", this);
9590   return N;
9591 }
9592 
9593 /// getTargetExtractSubreg - A convenience function for creating
9594 /// TargetOpcode::EXTRACT_SUBREG nodes.
9595 SDValue SelectionDAG::getTargetExtractSubreg(int SRIdx, const SDLoc &DL, EVT VT,
9596                                              SDValue Operand) {
9597   SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32);
9598   SDNode *Subreg = getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL,
9599                                   VT, Operand, SRIdxVal);
9600   return SDValue(Subreg, 0);
9601 }
9602 
9603 /// getTargetInsertSubreg - A convenience function for creating
9604 /// TargetOpcode::INSERT_SUBREG nodes.
9605 SDValue SelectionDAG::getTargetInsertSubreg(int SRIdx, const SDLoc &DL, EVT VT,
9606                                             SDValue Operand, SDValue Subreg) {
9607   SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32);
9608   SDNode *Result = getMachineNode(TargetOpcode::INSERT_SUBREG, DL,
9609                                   VT, Operand, Subreg, SRIdxVal);
9610   return SDValue(Result, 0);
9611 }
9612 
9613 /// getNodeIfExists - Get the specified node if it's already available, or
9614 /// else return NULL.
9615 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList,
9616                                       ArrayRef<SDValue> Ops) {
9617   SDNodeFlags Flags;
9618   if (Inserter)
9619     Flags = Inserter->getFlags();
9620   return getNodeIfExists(Opcode, VTList, Ops, Flags);
9621 }
9622 
9623 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList,
9624                                       ArrayRef<SDValue> Ops,
9625                                       const SDNodeFlags Flags) {
9626   if (VTList.VTs[VTList.NumVTs - 1] != MVT::Glue) {
9627     FoldingSetNodeID ID;
9628     AddNodeIDNode(ID, Opcode, VTList, Ops);
9629     void *IP = nullptr;
9630     if (SDNode *E = FindNodeOrInsertPos(ID, SDLoc(), IP)) {
9631       E->intersectFlagsWith(Flags);
9632       return E;
9633     }
9634   }
9635   return nullptr;
9636 }
9637 
9638 /// doesNodeExist - Check if a node exists without modifying its flags.
9639 bool SelectionDAG::doesNodeExist(unsigned Opcode, SDVTList VTList,
9640                                  ArrayRef<SDValue> Ops) {
9641   if (VTList.VTs[VTList.NumVTs - 1] != MVT::Glue) {
9642     FoldingSetNodeID ID;
9643     AddNodeIDNode(ID, Opcode, VTList, Ops);
9644     void *IP = nullptr;
9645     if (FindNodeOrInsertPos(ID, SDLoc(), IP))
9646       return true;
9647   }
9648   return false;
9649 }
9650 
9651 /// getDbgValue - Creates a SDDbgValue node.
9652 ///
9653 /// SDNode
9654 SDDbgValue *SelectionDAG::getDbgValue(DIVariable *Var, DIExpression *Expr,
9655                                       SDNode *N, unsigned R, bool IsIndirect,
9656                                       const DebugLoc &DL, unsigned O) {
9657   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
9658          "Expected inlined-at fields to agree");
9659   return new (DbgInfo->getAlloc())
9660       SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromNode(N, R),
9661                  {}, IsIndirect, DL, O,
9662                  /*IsVariadic=*/false);
9663 }
9664 
9665 /// Constant
9666 SDDbgValue *SelectionDAG::getConstantDbgValue(DIVariable *Var,
9667                                               DIExpression *Expr,
9668                                               const Value *C,
9669                                               const DebugLoc &DL, unsigned O) {
9670   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
9671          "Expected inlined-at fields to agree");
9672   return new (DbgInfo->getAlloc())
9673       SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromConst(C), {},
9674                  /*IsIndirect=*/false, DL, O,
9675                  /*IsVariadic=*/false);
9676 }
9677 
9678 /// FrameIndex
9679 SDDbgValue *SelectionDAG::getFrameIndexDbgValue(DIVariable *Var,
9680                                                 DIExpression *Expr, unsigned FI,
9681                                                 bool IsIndirect,
9682                                                 const DebugLoc &DL,
9683                                                 unsigned O) {
9684   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
9685          "Expected inlined-at fields to agree");
9686   return getFrameIndexDbgValue(Var, Expr, FI, {}, IsIndirect, DL, O);
9687 }
9688 
9689 /// FrameIndex with dependencies
9690 SDDbgValue *SelectionDAG::getFrameIndexDbgValue(DIVariable *Var,
9691                                                 DIExpression *Expr, unsigned FI,
9692                                                 ArrayRef<SDNode *> Dependencies,
9693                                                 bool IsIndirect,
9694                                                 const DebugLoc &DL,
9695                                                 unsigned O) {
9696   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
9697          "Expected inlined-at fields to agree");
9698   return new (DbgInfo->getAlloc())
9699       SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromFrameIdx(FI),
9700                  Dependencies, IsIndirect, DL, O,
9701                  /*IsVariadic=*/false);
9702 }
9703 
9704 /// VReg
9705 SDDbgValue *SelectionDAG::getVRegDbgValue(DIVariable *Var, DIExpression *Expr,
9706                                           unsigned VReg, bool IsIndirect,
9707                                           const DebugLoc &DL, unsigned O) {
9708   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
9709          "Expected inlined-at fields to agree");
9710   return new (DbgInfo->getAlloc())
9711       SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromVReg(VReg),
9712                  {}, IsIndirect, DL, O,
9713                  /*IsVariadic=*/false);
9714 }
9715 
9716 SDDbgValue *SelectionDAG::getDbgValueList(DIVariable *Var, DIExpression *Expr,
9717                                           ArrayRef<SDDbgOperand> Locs,
9718                                           ArrayRef<SDNode *> Dependencies,
9719                                           bool IsIndirect, const DebugLoc &DL,
9720                                           unsigned O, bool IsVariadic) {
9721   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
9722          "Expected inlined-at fields to agree");
9723   return new (DbgInfo->getAlloc())
9724       SDDbgValue(DbgInfo->getAlloc(), Var, Expr, Locs, Dependencies, IsIndirect,
9725                  DL, O, IsVariadic);
9726 }
9727 
9728 void SelectionDAG::transferDbgValues(SDValue From, SDValue To,
9729                                      unsigned OffsetInBits, unsigned SizeInBits,
9730                                      bool InvalidateDbg) {
9731   SDNode *FromNode = From.getNode();
9732   SDNode *ToNode = To.getNode();
9733   assert(FromNode && ToNode && "Can't modify dbg values");
9734 
9735   // PR35338
9736   // TODO: assert(From != To && "Redundant dbg value transfer");
9737   // TODO: assert(FromNode != ToNode && "Intranode dbg value transfer");
9738   if (From == To || FromNode == ToNode)
9739     return;
9740 
9741   if (!FromNode->getHasDebugValue())
9742     return;
9743 
9744   SDDbgOperand FromLocOp =
9745       SDDbgOperand::fromNode(From.getNode(), From.getResNo());
9746   SDDbgOperand ToLocOp = SDDbgOperand::fromNode(To.getNode(), To.getResNo());
9747 
9748   SmallVector<SDDbgValue *, 2> ClonedDVs;
9749   for (SDDbgValue *Dbg : GetDbgValues(FromNode)) {
9750     if (Dbg->isInvalidated())
9751       continue;
9752 
9753     // TODO: assert(!Dbg->isInvalidated() && "Transfer of invalid dbg value");
9754 
9755     // Create a new location ops vector that is equal to the old vector, but
9756     // with each instance of FromLocOp replaced with ToLocOp.
9757     bool Changed = false;
9758     auto NewLocOps = Dbg->copyLocationOps();
9759     std::replace_if(
9760         NewLocOps.begin(), NewLocOps.end(),
9761         [&Changed, FromLocOp](const SDDbgOperand &Op) {
9762           bool Match = Op == FromLocOp;
9763           Changed |= Match;
9764           return Match;
9765         },
9766         ToLocOp);
9767     // Ignore this SDDbgValue if we didn't find a matching location.
9768     if (!Changed)
9769       continue;
9770 
9771     DIVariable *Var = Dbg->getVariable();
9772     auto *Expr = Dbg->getExpression();
9773     // If a fragment is requested, update the expression.
9774     if (SizeInBits) {
9775       // When splitting a larger (e.g., sign-extended) value whose
9776       // lower bits are described with an SDDbgValue, do not attempt
9777       // to transfer the SDDbgValue to the upper bits.
9778       if (auto FI = Expr->getFragmentInfo())
9779         if (OffsetInBits + SizeInBits > FI->SizeInBits)
9780           continue;
9781       auto Fragment = DIExpression::createFragmentExpression(Expr, OffsetInBits,
9782                                                              SizeInBits);
9783       if (!Fragment)
9784         continue;
9785       Expr = *Fragment;
9786     }
9787 
9788     auto AdditionalDependencies = Dbg->getAdditionalDependencies();
9789     // Clone the SDDbgValue and move it to To.
9790     SDDbgValue *Clone = getDbgValueList(
9791         Var, Expr, NewLocOps, AdditionalDependencies, Dbg->isIndirect(),
9792         Dbg->getDebugLoc(), std::max(ToNode->getIROrder(), Dbg->getOrder()),
9793         Dbg->isVariadic());
9794     ClonedDVs.push_back(Clone);
9795 
9796     if (InvalidateDbg) {
9797       // Invalidate value and indicate the SDDbgValue should not be emitted.
9798       Dbg->setIsInvalidated();
9799       Dbg->setIsEmitted();
9800     }
9801   }
9802 
9803   for (SDDbgValue *Dbg : ClonedDVs) {
9804     assert(is_contained(Dbg->getSDNodes(), ToNode) &&
9805            "Transferred DbgValues should depend on the new SDNode");
9806     AddDbgValue(Dbg, false);
9807   }
9808 }
9809 
9810 void SelectionDAG::salvageDebugInfo(SDNode &N) {
9811   if (!N.getHasDebugValue())
9812     return;
9813 
9814   SmallVector<SDDbgValue *, 2> ClonedDVs;
9815   for (auto DV : GetDbgValues(&N)) {
9816     if (DV->isInvalidated())
9817       continue;
9818     switch (N.getOpcode()) {
9819     default:
9820       break;
9821     case ISD::ADD:
9822       SDValue N0 = N.getOperand(0);
9823       SDValue N1 = N.getOperand(1);
9824       if (!isConstantIntBuildVectorOrConstantInt(N0) &&
9825           isConstantIntBuildVectorOrConstantInt(N1)) {
9826         uint64_t Offset = N.getConstantOperandVal(1);
9827 
9828         // Rewrite an ADD constant node into a DIExpression. Since we are
9829         // performing arithmetic to compute the variable's *value* in the
9830         // DIExpression, we need to mark the expression with a
9831         // DW_OP_stack_value.
9832         auto *DIExpr = DV->getExpression();
9833         auto NewLocOps = DV->copyLocationOps();
9834         bool Changed = false;
9835         for (size_t i = 0; i < NewLocOps.size(); ++i) {
9836           // We're not given a ResNo to compare against because the whole
9837           // node is going away. We know that any ISD::ADD only has one
9838           // result, so we can assume any node match is using the result.
9839           if (NewLocOps[i].getKind() != SDDbgOperand::SDNODE ||
9840               NewLocOps[i].getSDNode() != &N)
9841             continue;
9842           NewLocOps[i] = SDDbgOperand::fromNode(N0.getNode(), N0.getResNo());
9843           SmallVector<uint64_t, 3> ExprOps;
9844           DIExpression::appendOffset(ExprOps, Offset);
9845           DIExpr = DIExpression::appendOpsToArg(DIExpr, ExprOps, i, true);
9846           Changed = true;
9847         }
9848         (void)Changed;
9849         assert(Changed && "Salvage target doesn't use N");
9850 
9851         auto AdditionalDependencies = DV->getAdditionalDependencies();
9852         SDDbgValue *Clone = getDbgValueList(DV->getVariable(), DIExpr,
9853                                             NewLocOps, AdditionalDependencies,
9854                                             DV->isIndirect(), DV->getDebugLoc(),
9855                                             DV->getOrder(), DV->isVariadic());
9856         ClonedDVs.push_back(Clone);
9857         DV->setIsInvalidated();
9858         DV->setIsEmitted();
9859         LLVM_DEBUG(dbgs() << "SALVAGE: Rewriting";
9860                    N0.getNode()->dumprFull(this);
9861                    dbgs() << " into " << *DIExpr << '\n');
9862       }
9863     }
9864   }
9865 
9866   for (SDDbgValue *Dbg : ClonedDVs) {
9867     assert(!Dbg->getSDNodes().empty() &&
9868            "Salvaged DbgValue should depend on a new SDNode");
9869     AddDbgValue(Dbg, false);
9870   }
9871 }
9872 
9873 /// Creates a SDDbgLabel node.
9874 SDDbgLabel *SelectionDAG::getDbgLabel(DILabel *Label,
9875                                       const DebugLoc &DL, unsigned O) {
9876   assert(cast<DILabel>(Label)->isValidLocationForIntrinsic(DL) &&
9877          "Expected inlined-at fields to agree");
9878   return new (DbgInfo->getAlloc()) SDDbgLabel(Label, DL, O);
9879 }
9880 
9881 namespace {
9882 
9883 /// RAUWUpdateListener - Helper for ReplaceAllUsesWith - When the node
9884 /// pointed to by a use iterator is deleted, increment the use iterator
9885 /// so that it doesn't dangle.
9886 ///
9887 class RAUWUpdateListener : public SelectionDAG::DAGUpdateListener {
9888   SDNode::use_iterator &UI;
9889   SDNode::use_iterator &UE;
9890 
9891   void NodeDeleted(SDNode *N, SDNode *E) override {
9892     // Increment the iterator as needed.
9893     while (UI != UE && N == *UI)
9894       ++UI;
9895   }
9896 
9897 public:
9898   RAUWUpdateListener(SelectionDAG &d,
9899                      SDNode::use_iterator &ui,
9900                      SDNode::use_iterator &ue)
9901     : SelectionDAG::DAGUpdateListener(d), UI(ui), UE(ue) {}
9902 };
9903 
9904 } // end anonymous namespace
9905 
9906 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
9907 /// This can cause recursive merging of nodes in the DAG.
9908 ///
9909 /// This version assumes From has a single result value.
9910 ///
9911 void SelectionDAG::ReplaceAllUsesWith(SDValue FromN, SDValue To) {
9912   SDNode *From = FromN.getNode();
9913   assert(From->getNumValues() == 1 && FromN.getResNo() == 0 &&
9914          "Cannot replace with this method!");
9915   assert(From != To.getNode() && "Cannot replace uses of with self");
9916 
9917   // Preserve Debug Values
9918   transferDbgValues(FromN, To);
9919 
9920   // Iterate over all the existing uses of From. New uses will be added
9921   // to the beginning of the use list, which we avoid visiting.
9922   // This specifically avoids visiting uses of From that arise while the
9923   // replacement is happening, because any such uses would be the result
9924   // of CSE: If an existing node looks like From after one of its operands
9925   // is replaced by To, we don't want to replace of all its users with To
9926   // too. See PR3018 for more info.
9927   SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
9928   RAUWUpdateListener Listener(*this, UI, UE);
9929   while (UI != UE) {
9930     SDNode *User = *UI;
9931 
9932     // This node is about to morph, remove its old self from the CSE maps.
9933     RemoveNodeFromCSEMaps(User);
9934 
9935     // A user can appear in a use list multiple times, and when this
9936     // happens the uses are usually next to each other in the list.
9937     // To help reduce the number of CSE recomputations, process all
9938     // the uses of this user that we can find this way.
9939     do {
9940       SDUse &Use = UI.getUse();
9941       ++UI;
9942       Use.set(To);
9943       if (To->isDivergent() != From->isDivergent())
9944         updateDivergence(User);
9945     } while (UI != UE && *UI == User);
9946     // Now that we have modified User, add it back to the CSE maps.  If it
9947     // already exists there, recursively merge the results together.
9948     AddModifiedNodeToCSEMaps(User);
9949   }
9950 
9951   // If we just RAUW'd the root, take note.
9952   if (FromN == getRoot())
9953     setRoot(To);
9954 }
9955 
9956 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
9957 /// This can cause recursive merging of nodes in the DAG.
9958 ///
9959 /// This version assumes that for each value of From, there is a
9960 /// corresponding value in To in the same position with the same type.
9961 ///
9962 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, SDNode *To) {
9963 #ifndef NDEBUG
9964   for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
9965     assert((!From->hasAnyUseOfValue(i) ||
9966             From->getValueType(i) == To->getValueType(i)) &&
9967            "Cannot use this version of ReplaceAllUsesWith!");
9968 #endif
9969 
9970   // Handle the trivial case.
9971   if (From == To)
9972     return;
9973 
9974   // Preserve Debug Info. Only do this if there's a use.
9975   for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
9976     if (From->hasAnyUseOfValue(i)) {
9977       assert((i < To->getNumValues()) && "Invalid To location");
9978       transferDbgValues(SDValue(From, i), SDValue(To, i));
9979     }
9980 
9981   // Iterate over just the existing users of From. See the comments in
9982   // the ReplaceAllUsesWith above.
9983   SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
9984   RAUWUpdateListener Listener(*this, UI, UE);
9985   while (UI != UE) {
9986     SDNode *User = *UI;
9987 
9988     // This node is about to morph, remove its old self from the CSE maps.
9989     RemoveNodeFromCSEMaps(User);
9990 
9991     // A user can appear in a use list multiple times, and when this
9992     // happens the uses are usually next to each other in the list.
9993     // To help reduce the number of CSE recomputations, process all
9994     // the uses of this user that we can find this way.
9995     do {
9996       SDUse &Use = UI.getUse();
9997       ++UI;
9998       Use.setNode(To);
9999       if (To->isDivergent() != From->isDivergent())
10000         updateDivergence(User);
10001     } while (UI != UE && *UI == User);
10002 
10003     // Now that we have modified User, add it back to the CSE maps.  If it
10004     // already exists there, recursively merge the results together.
10005     AddModifiedNodeToCSEMaps(User);
10006   }
10007 
10008   // If we just RAUW'd the root, take note.
10009   if (From == getRoot().getNode())
10010     setRoot(SDValue(To, getRoot().getResNo()));
10011 }
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 can replace From with any result values.  To must match the
10017 /// number and types of values returned by From.
10018 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, const SDValue *To) {
10019   if (From->getNumValues() == 1)  // Handle the simple case efficiently.
10020     return ReplaceAllUsesWith(SDValue(From, 0), To[0]);
10021 
10022   // Preserve Debug Info.
10023   for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
10024     transferDbgValues(SDValue(From, i), To[i]);
10025 
10026   // Iterate over just the existing users of From. See the comments in
10027   // the ReplaceAllUsesWith above.
10028   SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
10029   RAUWUpdateListener Listener(*this, UI, UE);
10030   while (UI != UE) {
10031     SDNode *User = *UI;
10032 
10033     // This node is about to morph, remove its old self from the CSE maps.
10034     RemoveNodeFromCSEMaps(User);
10035 
10036     // A user can appear in a use list multiple times, and when this happens the
10037     // uses are usually next to each other in the list.  To help reduce the
10038     // number of CSE and divergence recomputations, process all the uses of this
10039     // user that we can find this way.
10040     bool To_IsDivergent = false;
10041     do {
10042       SDUse &Use = UI.getUse();
10043       const SDValue &ToOp = To[Use.getResNo()];
10044       ++UI;
10045       Use.set(ToOp);
10046       To_IsDivergent |= ToOp->isDivergent();
10047     } while (UI != UE && *UI == User);
10048 
10049     if (To_IsDivergent != From->isDivergent())
10050       updateDivergence(User);
10051 
10052     // Now that we have modified User, add it back to the CSE maps.  If it
10053     // already exists there, recursively merge the results together.
10054     AddModifiedNodeToCSEMaps(User);
10055   }
10056 
10057   // If we just RAUW'd the root, take note.
10058   if (From == getRoot().getNode())
10059     setRoot(SDValue(To[getRoot().getResNo()]));
10060 }
10061 
10062 /// ReplaceAllUsesOfValueWith - Replace any uses of From with To, leaving
10063 /// uses of other values produced by From.getNode() alone.  The Deleted
10064 /// vector is handled the same way as for ReplaceAllUsesWith.
10065 void SelectionDAG::ReplaceAllUsesOfValueWith(SDValue From, SDValue To){
10066   // Handle the really simple, really trivial case efficiently.
10067   if (From == To) return;
10068 
10069   // Handle the simple, trivial, case efficiently.
10070   if (From.getNode()->getNumValues() == 1) {
10071     ReplaceAllUsesWith(From, To);
10072     return;
10073   }
10074 
10075   // Preserve Debug Info.
10076   transferDbgValues(From, To);
10077 
10078   // Iterate over just the existing users of From. See the comments in
10079   // the ReplaceAllUsesWith above.
10080   SDNode::use_iterator UI = From.getNode()->use_begin(),
10081                        UE = From.getNode()->use_end();
10082   RAUWUpdateListener Listener(*this, UI, UE);
10083   while (UI != UE) {
10084     SDNode *User = *UI;
10085     bool UserRemovedFromCSEMaps = false;
10086 
10087     // A user can appear in a use list multiple times, and when this
10088     // happens the uses are usually next to each other in the list.
10089     // To help reduce the number of CSE recomputations, process all
10090     // the uses of this user that we can find this way.
10091     do {
10092       SDUse &Use = UI.getUse();
10093 
10094       // Skip uses of different values from the same node.
10095       if (Use.getResNo() != From.getResNo()) {
10096         ++UI;
10097         continue;
10098       }
10099 
10100       // If this node hasn't been modified yet, it's still in the CSE maps,
10101       // so remove its old self from the CSE maps.
10102       if (!UserRemovedFromCSEMaps) {
10103         RemoveNodeFromCSEMaps(User);
10104         UserRemovedFromCSEMaps = true;
10105       }
10106 
10107       ++UI;
10108       Use.set(To);
10109       if (To->isDivergent() != From->isDivergent())
10110         updateDivergence(User);
10111     } while (UI != UE && *UI == User);
10112     // We are iterating over all uses of the From node, so if a use
10113     // doesn't use the specific value, no changes are made.
10114     if (!UserRemovedFromCSEMaps)
10115       continue;
10116 
10117     // Now that we have modified User, add it back to the CSE maps.  If it
10118     // already exists there, recursively merge the results together.
10119     AddModifiedNodeToCSEMaps(User);
10120   }
10121 
10122   // If we just RAUW'd the root, take note.
10123   if (From == getRoot())
10124     setRoot(To);
10125 }
10126 
10127 namespace {
10128 
10129 /// UseMemo - This class is used by SelectionDAG::ReplaceAllUsesOfValuesWith
10130 /// to record information about a use.
10131 struct UseMemo {
10132   SDNode *User;
10133   unsigned Index;
10134   SDUse *Use;
10135 };
10136 
10137 /// operator< - Sort Memos by User.
10138 bool operator<(const UseMemo &L, const UseMemo &R) {
10139   return (intptr_t)L.User < (intptr_t)R.User;
10140 }
10141 
10142 /// RAUOVWUpdateListener - Helper for ReplaceAllUsesOfValuesWith - When the node
10143 /// pointed to by a UseMemo is deleted, set the User to nullptr to indicate that
10144 /// the node already has been taken care of recursively.
10145 class RAUOVWUpdateListener : public SelectionDAG::DAGUpdateListener {
10146   SmallVector<UseMemo, 4> &Uses;
10147 
10148   void NodeDeleted(SDNode *N, SDNode *E) override {
10149     for (UseMemo &Memo : Uses)
10150       if (Memo.User == N)
10151         Memo.User = nullptr;
10152   }
10153 
10154 public:
10155   RAUOVWUpdateListener(SelectionDAG &d, SmallVector<UseMemo, 4> &uses)
10156       : SelectionDAG::DAGUpdateListener(d), Uses(uses) {}
10157 };
10158 
10159 } // end anonymous namespace
10160 
10161 bool SelectionDAG::calculateDivergence(SDNode *N) {
10162   if (TLI->isSDNodeAlwaysUniform(N)) {
10163     assert(!TLI->isSDNodeSourceOfDivergence(N, FLI, DA) &&
10164            "Conflicting divergence information!");
10165     return false;
10166   }
10167   if (TLI->isSDNodeSourceOfDivergence(N, FLI, DA))
10168     return true;
10169   for (auto &Op : N->ops()) {
10170     if (Op.Val.getValueType() != MVT::Other && Op.getNode()->isDivergent())
10171       return true;
10172   }
10173   return false;
10174 }
10175 
10176 void SelectionDAG::updateDivergence(SDNode *N) {
10177   SmallVector<SDNode *, 16> Worklist(1, N);
10178   do {
10179     N = Worklist.pop_back_val();
10180     bool IsDivergent = calculateDivergence(N);
10181     if (N->SDNodeBits.IsDivergent != IsDivergent) {
10182       N->SDNodeBits.IsDivergent = IsDivergent;
10183       llvm::append_range(Worklist, N->uses());
10184     }
10185   } while (!Worklist.empty());
10186 }
10187 
10188 void SelectionDAG::CreateTopologicalOrder(std::vector<SDNode *> &Order) {
10189   DenseMap<SDNode *, unsigned> Degree;
10190   Order.reserve(AllNodes.size());
10191   for (auto &N : allnodes()) {
10192     unsigned NOps = N.getNumOperands();
10193     Degree[&N] = NOps;
10194     if (0 == NOps)
10195       Order.push_back(&N);
10196   }
10197   for (size_t I = 0; I != Order.size(); ++I) {
10198     SDNode *N = Order[I];
10199     for (auto U : N->uses()) {
10200       unsigned &UnsortedOps = Degree[U];
10201       if (0 == --UnsortedOps)
10202         Order.push_back(U);
10203     }
10204   }
10205 }
10206 
10207 #ifndef NDEBUG
10208 void SelectionDAG::VerifyDAGDivergence() {
10209   std::vector<SDNode *> TopoOrder;
10210   CreateTopologicalOrder(TopoOrder);
10211   for (auto *N : TopoOrder) {
10212     assert(calculateDivergence(N) == N->isDivergent() &&
10213            "Divergence bit inconsistency detected");
10214   }
10215 }
10216 #endif
10217 
10218 /// ReplaceAllUsesOfValuesWith - Replace any uses of From with To, leaving
10219 /// uses of other values produced by From.getNode() alone.  The same value
10220 /// may appear in both the From and To list.  The Deleted vector is
10221 /// handled the same way as for ReplaceAllUsesWith.
10222 void SelectionDAG::ReplaceAllUsesOfValuesWith(const SDValue *From,
10223                                               const SDValue *To,
10224                                               unsigned Num){
10225   // Handle the simple, trivial case efficiently.
10226   if (Num == 1)
10227     return ReplaceAllUsesOfValueWith(*From, *To);
10228 
10229   transferDbgValues(*From, *To);
10230 
10231   // Read up all the uses and make records of them. This helps
10232   // processing new uses that are introduced during the
10233   // replacement process.
10234   SmallVector<UseMemo, 4> Uses;
10235   for (unsigned i = 0; i != Num; ++i) {
10236     unsigned FromResNo = From[i].getResNo();
10237     SDNode *FromNode = From[i].getNode();
10238     for (SDNode::use_iterator UI = FromNode->use_begin(),
10239          E = FromNode->use_end(); UI != E; ++UI) {
10240       SDUse &Use = UI.getUse();
10241       if (Use.getResNo() == FromResNo) {
10242         UseMemo Memo = { *UI, i, &Use };
10243         Uses.push_back(Memo);
10244       }
10245     }
10246   }
10247 
10248   // Sort the uses, so that all the uses from a given User are together.
10249   llvm::sort(Uses);
10250   RAUOVWUpdateListener Listener(*this, Uses);
10251 
10252   for (unsigned UseIndex = 0, UseIndexEnd = Uses.size();
10253        UseIndex != UseIndexEnd; ) {
10254     // We know that this user uses some value of From.  If it is the right
10255     // value, update it.
10256     SDNode *User = Uses[UseIndex].User;
10257     // If the node has been deleted by recursive CSE updates when updating
10258     // another node, then just skip this entry.
10259     if (User == nullptr) {
10260       ++UseIndex;
10261       continue;
10262     }
10263 
10264     // This node is about to morph, remove its old self from the CSE maps.
10265     RemoveNodeFromCSEMaps(User);
10266 
10267     // The Uses array is sorted, so all the uses for a given User
10268     // are next to each other in the list.
10269     // To help reduce the number of CSE recomputations, process all
10270     // the uses of this user that we can find this way.
10271     do {
10272       unsigned i = Uses[UseIndex].Index;
10273       SDUse &Use = *Uses[UseIndex].Use;
10274       ++UseIndex;
10275 
10276       Use.set(To[i]);
10277     } while (UseIndex != UseIndexEnd && Uses[UseIndex].User == User);
10278 
10279     // Now that we have modified User, add it back to the CSE maps.  If it
10280     // already exists there, recursively merge the results together.
10281     AddModifiedNodeToCSEMaps(User);
10282   }
10283 }
10284 
10285 /// AssignTopologicalOrder - Assign a unique node id for each node in the DAG
10286 /// based on their topological order. It returns the maximum id and a vector
10287 /// of the SDNodes* in assigned order by reference.
10288 unsigned SelectionDAG::AssignTopologicalOrder() {
10289   unsigned DAGSize = 0;
10290 
10291   // SortedPos tracks the progress of the algorithm. Nodes before it are
10292   // sorted, nodes after it are unsorted. When the algorithm completes
10293   // it is at the end of the list.
10294   allnodes_iterator SortedPos = allnodes_begin();
10295 
10296   // Visit all the nodes. Move nodes with no operands to the front of
10297   // the list immediately. Annotate nodes that do have operands with their
10298   // operand count. Before we do this, the Node Id fields of the nodes
10299   // may contain arbitrary values. After, the Node Id fields for nodes
10300   // before SortedPos will contain the topological sort index, and the
10301   // Node Id fields for nodes At SortedPos and after will contain the
10302   // count of outstanding operands.
10303   for (SDNode &N : llvm::make_early_inc_range(allnodes())) {
10304     checkForCycles(&N, this);
10305     unsigned Degree = N.getNumOperands();
10306     if (Degree == 0) {
10307       // A node with no uses, add it to the result array immediately.
10308       N.setNodeId(DAGSize++);
10309       allnodes_iterator Q(&N);
10310       if (Q != SortedPos)
10311         SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(Q));
10312       assert(SortedPos != AllNodes.end() && "Overran node list");
10313       ++SortedPos;
10314     } else {
10315       // Temporarily use the Node Id as scratch space for the degree count.
10316       N.setNodeId(Degree);
10317     }
10318   }
10319 
10320   // Visit all the nodes. As we iterate, move nodes into sorted order,
10321   // such that by the time the end is reached all nodes will be sorted.
10322   for (SDNode &Node : allnodes()) {
10323     SDNode *N = &Node;
10324     checkForCycles(N, this);
10325     // N is in sorted position, so all its uses have one less operand
10326     // that needs to be sorted.
10327     for (SDNode *P : N->uses()) {
10328       unsigned Degree = P->getNodeId();
10329       assert(Degree != 0 && "Invalid node degree");
10330       --Degree;
10331       if (Degree == 0) {
10332         // All of P's operands are sorted, so P may sorted now.
10333         P->setNodeId(DAGSize++);
10334         if (P->getIterator() != SortedPos)
10335           SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(P));
10336         assert(SortedPos != AllNodes.end() && "Overran node list");
10337         ++SortedPos;
10338       } else {
10339         // Update P's outstanding operand count.
10340         P->setNodeId(Degree);
10341       }
10342     }
10343     if (Node.getIterator() == SortedPos) {
10344 #ifndef NDEBUG
10345       allnodes_iterator I(N);
10346       SDNode *S = &*++I;
10347       dbgs() << "Overran sorted position:\n";
10348       S->dumprFull(this); dbgs() << "\n";
10349       dbgs() << "Checking if this is due to cycles\n";
10350       checkForCycles(this, true);
10351 #endif
10352       llvm_unreachable(nullptr);
10353     }
10354   }
10355 
10356   assert(SortedPos == AllNodes.end() &&
10357          "Topological sort incomplete!");
10358   assert(AllNodes.front().getOpcode() == ISD::EntryToken &&
10359          "First node in topological sort is not the entry token!");
10360   assert(AllNodes.front().getNodeId() == 0 &&
10361          "First node in topological sort has non-zero id!");
10362   assert(AllNodes.front().getNumOperands() == 0 &&
10363          "First node in topological sort has operands!");
10364   assert(AllNodes.back().getNodeId() == (int)DAGSize-1 &&
10365          "Last node in topologic sort has unexpected id!");
10366   assert(AllNodes.back().use_empty() &&
10367          "Last node in topologic sort has users!");
10368   assert(DAGSize == allnodes_size() && "Node count mismatch!");
10369   return DAGSize;
10370 }
10371 
10372 /// AddDbgValue - Add a dbg_value SDNode. If SD is non-null that means the
10373 /// value is produced by SD.
10374 void SelectionDAG::AddDbgValue(SDDbgValue *DB, bool isParameter) {
10375   for (SDNode *SD : DB->getSDNodes()) {
10376     if (!SD)
10377       continue;
10378     assert(DbgInfo->getSDDbgValues(SD).empty() || SD->getHasDebugValue());
10379     SD->setHasDebugValue(true);
10380   }
10381   DbgInfo->add(DB, isParameter);
10382 }
10383 
10384 void SelectionDAG::AddDbgLabel(SDDbgLabel *DB) { DbgInfo->add(DB); }
10385 
10386 SDValue SelectionDAG::makeEquivalentMemoryOrdering(SDValue OldChain,
10387                                                    SDValue NewMemOpChain) {
10388   assert(isa<MemSDNode>(NewMemOpChain) && "Expected a memop node");
10389   assert(NewMemOpChain.getValueType() == MVT::Other && "Expected a token VT");
10390   // The new memory operation must have the same position as the old load in
10391   // terms of memory dependency. Create a TokenFactor for the old load and new
10392   // memory operation and update uses of the old load's output chain to use that
10393   // TokenFactor.
10394   if (OldChain == NewMemOpChain || OldChain.use_empty())
10395     return NewMemOpChain;
10396 
10397   SDValue TokenFactor = getNode(ISD::TokenFactor, SDLoc(OldChain), MVT::Other,
10398                                 OldChain, NewMemOpChain);
10399   ReplaceAllUsesOfValueWith(OldChain, TokenFactor);
10400   UpdateNodeOperands(TokenFactor.getNode(), OldChain, NewMemOpChain);
10401   return TokenFactor;
10402 }
10403 
10404 SDValue SelectionDAG::makeEquivalentMemoryOrdering(LoadSDNode *OldLoad,
10405                                                    SDValue NewMemOp) {
10406   assert(isa<MemSDNode>(NewMemOp.getNode()) && "Expected a memop node");
10407   SDValue OldChain = SDValue(OldLoad, 1);
10408   SDValue NewMemOpChain = NewMemOp.getValue(1);
10409   return makeEquivalentMemoryOrdering(OldChain, NewMemOpChain);
10410 }
10411 
10412 SDValue SelectionDAG::getSymbolFunctionGlobalAddress(SDValue Op,
10413                                                      Function **OutFunction) {
10414   assert(isa<ExternalSymbolSDNode>(Op) && "Node should be an ExternalSymbol");
10415 
10416   auto *Symbol = cast<ExternalSymbolSDNode>(Op)->getSymbol();
10417   auto *Module = MF->getFunction().getParent();
10418   auto *Function = Module->getFunction(Symbol);
10419 
10420   if (OutFunction != nullptr)
10421       *OutFunction = Function;
10422 
10423   if (Function != nullptr) {
10424     auto PtrTy = TLI->getPointerTy(getDataLayout(), Function->getAddressSpace());
10425     return getGlobalAddress(Function, SDLoc(Op), PtrTy);
10426   }
10427 
10428   std::string ErrorStr;
10429   raw_string_ostream ErrorFormatter(ErrorStr);
10430   ErrorFormatter << "Undefined external symbol ";
10431   ErrorFormatter << '"' << Symbol << '"';
10432   report_fatal_error(Twine(ErrorFormatter.str()));
10433 }
10434 
10435 //===----------------------------------------------------------------------===//
10436 //                              SDNode Class
10437 //===----------------------------------------------------------------------===//
10438 
10439 bool llvm::isNullConstant(SDValue V) {
10440   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
10441   return Const != nullptr && Const->isZero();
10442 }
10443 
10444 bool llvm::isNullFPConstant(SDValue V) {
10445   ConstantFPSDNode *Const = dyn_cast<ConstantFPSDNode>(V);
10446   return Const != nullptr && Const->isZero() && !Const->isNegative();
10447 }
10448 
10449 bool llvm::isAllOnesConstant(SDValue V) {
10450   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
10451   return Const != nullptr && Const->isAllOnes();
10452 }
10453 
10454 bool llvm::isOneConstant(SDValue V) {
10455   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
10456   return Const != nullptr && Const->isOne();
10457 }
10458 
10459 bool llvm::isMinSignedConstant(SDValue V) {
10460   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
10461   return Const != nullptr && Const->isMinSignedValue();
10462 }
10463 
10464 SDValue llvm::peekThroughBitcasts(SDValue V) {
10465   while (V.getOpcode() == ISD::BITCAST)
10466     V = V.getOperand(0);
10467   return V;
10468 }
10469 
10470 SDValue llvm::peekThroughOneUseBitcasts(SDValue V) {
10471   while (V.getOpcode() == ISD::BITCAST && V.getOperand(0).hasOneUse())
10472     V = V.getOperand(0);
10473   return V;
10474 }
10475 
10476 SDValue llvm::peekThroughExtractSubvectors(SDValue V) {
10477   while (V.getOpcode() == ISD::EXTRACT_SUBVECTOR)
10478     V = V.getOperand(0);
10479   return V;
10480 }
10481 
10482 bool llvm::isBitwiseNot(SDValue V, bool AllowUndefs) {
10483   if (V.getOpcode() != ISD::XOR)
10484     return false;
10485   V = peekThroughBitcasts(V.getOperand(1));
10486   unsigned NumBits = V.getScalarValueSizeInBits();
10487   ConstantSDNode *C =
10488       isConstOrConstSplat(V, AllowUndefs, /*AllowTruncation*/ true);
10489   return C && (C->getAPIntValue().countTrailingOnes() >= NumBits);
10490 }
10491 
10492 ConstantSDNode *llvm::isConstOrConstSplat(SDValue N, bool AllowUndefs,
10493                                           bool AllowTruncation) {
10494   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
10495     return CN;
10496 
10497   // SplatVectors can truncate their operands. Ignore that case here unless
10498   // AllowTruncation is set.
10499   if (N->getOpcode() == ISD::SPLAT_VECTOR) {
10500     EVT VecEltVT = N->getValueType(0).getVectorElementType();
10501     if (auto *CN = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
10502       EVT CVT = CN->getValueType(0);
10503       assert(CVT.bitsGE(VecEltVT) && "Illegal splat_vector element extension");
10504       if (AllowTruncation || CVT == VecEltVT)
10505         return CN;
10506     }
10507   }
10508 
10509   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
10510     BitVector UndefElements;
10511     ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
10512 
10513     // BuildVectors can truncate their operands. Ignore that case here unless
10514     // AllowTruncation is set.
10515     if (CN && (UndefElements.none() || AllowUndefs)) {
10516       EVT CVT = CN->getValueType(0);
10517       EVT NSVT = N.getValueType().getScalarType();
10518       assert(CVT.bitsGE(NSVT) && "Illegal build vector element extension");
10519       if (AllowTruncation || (CVT == NSVT))
10520         return CN;
10521     }
10522   }
10523 
10524   return nullptr;
10525 }
10526 
10527 ConstantSDNode *llvm::isConstOrConstSplat(SDValue N, const APInt &DemandedElts,
10528                                           bool AllowUndefs,
10529                                           bool AllowTruncation) {
10530   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
10531     return CN;
10532 
10533   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
10534     BitVector UndefElements;
10535     ConstantSDNode *CN = BV->getConstantSplatNode(DemandedElts, &UndefElements);
10536 
10537     // BuildVectors can truncate their operands. Ignore that case here unless
10538     // AllowTruncation is set.
10539     if (CN && (UndefElements.none() || AllowUndefs)) {
10540       EVT CVT = CN->getValueType(0);
10541       EVT NSVT = N.getValueType().getScalarType();
10542       assert(CVT.bitsGE(NSVT) && "Illegal build vector element extension");
10543       if (AllowTruncation || (CVT == NSVT))
10544         return CN;
10545     }
10546   }
10547 
10548   return nullptr;
10549 }
10550 
10551 ConstantFPSDNode *llvm::isConstOrConstSplatFP(SDValue N, bool AllowUndefs) {
10552   if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
10553     return CN;
10554 
10555   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
10556     BitVector UndefElements;
10557     ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements);
10558     if (CN && (UndefElements.none() || AllowUndefs))
10559       return CN;
10560   }
10561 
10562   if (N.getOpcode() == ISD::SPLAT_VECTOR)
10563     if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N.getOperand(0)))
10564       return CN;
10565 
10566   return nullptr;
10567 }
10568 
10569 ConstantFPSDNode *llvm::isConstOrConstSplatFP(SDValue N,
10570                                               const APInt &DemandedElts,
10571                                               bool AllowUndefs) {
10572   if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
10573     return CN;
10574 
10575   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
10576     BitVector UndefElements;
10577     ConstantFPSDNode *CN =
10578         BV->getConstantFPSplatNode(DemandedElts, &UndefElements);
10579     if (CN && (UndefElements.none() || AllowUndefs))
10580       return CN;
10581   }
10582 
10583   return nullptr;
10584 }
10585 
10586 bool llvm::isNullOrNullSplat(SDValue N, bool AllowUndefs) {
10587   // TODO: may want to use peekThroughBitcast() here.
10588   ConstantSDNode *C =
10589       isConstOrConstSplat(N, AllowUndefs, /*AllowTruncation=*/true);
10590   return C && C->isZero();
10591 }
10592 
10593 bool llvm::isOneOrOneSplat(SDValue N, bool AllowUndefs) {
10594   // TODO: may want to use peekThroughBitcast() here.
10595   unsigned BitWidth = N.getScalarValueSizeInBits();
10596   ConstantSDNode *C = isConstOrConstSplat(N, AllowUndefs);
10597   return C && C->isOne() && C->getValueSizeInBits(0) == BitWidth;
10598 }
10599 
10600 bool llvm::isAllOnesOrAllOnesSplat(SDValue N, bool AllowUndefs) {
10601   N = peekThroughBitcasts(N);
10602   unsigned BitWidth = N.getScalarValueSizeInBits();
10603   ConstantSDNode *C = isConstOrConstSplat(N, AllowUndefs);
10604   return C && C->isAllOnes() && C->getValueSizeInBits(0) == BitWidth;
10605 }
10606 
10607 HandleSDNode::~HandleSDNode() {
10608   DropOperands();
10609 }
10610 
10611 GlobalAddressSDNode::GlobalAddressSDNode(unsigned Opc, unsigned Order,
10612                                          const DebugLoc &DL,
10613                                          const GlobalValue *GA, EVT VT,
10614                                          int64_t o, unsigned TF)
10615     : SDNode(Opc, Order, DL, getSDVTList(VT)), Offset(o), TargetFlags(TF) {
10616   TheGlobal = GA;
10617 }
10618 
10619 AddrSpaceCastSDNode::AddrSpaceCastSDNode(unsigned Order, const DebugLoc &dl,
10620                                          EVT VT, unsigned SrcAS,
10621                                          unsigned DestAS)
10622     : SDNode(ISD::ADDRSPACECAST, Order, dl, getSDVTList(VT)),
10623       SrcAddrSpace(SrcAS), DestAddrSpace(DestAS) {}
10624 
10625 MemSDNode::MemSDNode(unsigned Opc, unsigned Order, const DebugLoc &dl,
10626                      SDVTList VTs, EVT memvt, MachineMemOperand *mmo)
10627     : SDNode(Opc, Order, dl, VTs), MemoryVT(memvt), MMO(mmo) {
10628   MemSDNodeBits.IsVolatile = MMO->isVolatile();
10629   MemSDNodeBits.IsNonTemporal = MMO->isNonTemporal();
10630   MemSDNodeBits.IsDereferenceable = MMO->isDereferenceable();
10631   MemSDNodeBits.IsInvariant = MMO->isInvariant();
10632 
10633   // We check here that the size of the memory operand fits within the size of
10634   // the MMO. This is because the MMO might indicate only a possible address
10635   // range instead of specifying the affected memory addresses precisely.
10636   // TODO: Make MachineMemOperands aware of scalable vectors.
10637   assert(memvt.getStoreSize().getKnownMinSize() <= MMO->getSize() &&
10638          "Size mismatch!");
10639 }
10640 
10641 /// Profile - Gather unique data for the node.
10642 ///
10643 void SDNode::Profile(FoldingSetNodeID &ID) const {
10644   AddNodeIDNode(ID, this);
10645 }
10646 
10647 namespace {
10648 
10649   struct EVTArray {
10650     std::vector<EVT> VTs;
10651 
10652     EVTArray() {
10653       VTs.reserve(MVT::VALUETYPE_SIZE);
10654       for (unsigned i = 0; i < MVT::VALUETYPE_SIZE; ++i)
10655         VTs.push_back(MVT((MVT::SimpleValueType)i));
10656     }
10657   };
10658 
10659 } // end anonymous namespace
10660 
10661 static ManagedStatic<std::set<EVT, EVT::compareRawBits>> EVTs;
10662 static ManagedStatic<EVTArray> SimpleVTArray;
10663 static ManagedStatic<sys::SmartMutex<true>> VTMutex;
10664 
10665 /// getValueTypeList - Return a pointer to the specified value type.
10666 ///
10667 const EVT *SDNode::getValueTypeList(EVT VT) {
10668   if (VT.isExtended()) {
10669     sys::SmartScopedLock<true> Lock(*VTMutex);
10670     return &(*EVTs->insert(VT).first);
10671   }
10672   assert(VT.getSimpleVT() < MVT::VALUETYPE_SIZE && "Value type out of range!");
10673   return &SimpleVTArray->VTs[VT.getSimpleVT().SimpleTy];
10674 }
10675 
10676 /// hasNUsesOfValue - Return true if there are exactly NUSES uses of the
10677 /// indicated value.  This method ignores uses of other values defined by this
10678 /// operation.
10679 bool SDNode::hasNUsesOfValue(unsigned NUses, unsigned Value) const {
10680   assert(Value < getNumValues() && "Bad value!");
10681 
10682   // TODO: Only iterate over uses of a given value of the node
10683   for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) {
10684     if (UI.getUse().getResNo() == Value) {
10685       if (NUses == 0)
10686         return false;
10687       --NUses;
10688     }
10689   }
10690 
10691   // Found exactly the right number of uses?
10692   return NUses == 0;
10693 }
10694 
10695 /// hasAnyUseOfValue - Return true if there are any use of the indicated
10696 /// value. This method ignores uses of other values defined by this operation.
10697 bool SDNode::hasAnyUseOfValue(unsigned Value) const {
10698   assert(Value < getNumValues() && "Bad value!");
10699 
10700   for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI)
10701     if (UI.getUse().getResNo() == Value)
10702       return true;
10703 
10704   return false;
10705 }
10706 
10707 /// isOnlyUserOf - Return true if this node is the only use of N.
10708 bool SDNode::isOnlyUserOf(const SDNode *N) const {
10709   bool Seen = false;
10710   for (const SDNode *User : N->uses()) {
10711     if (User == this)
10712       Seen = true;
10713     else
10714       return false;
10715   }
10716 
10717   return Seen;
10718 }
10719 
10720 /// Return true if the only users of N are contained in Nodes.
10721 bool SDNode::areOnlyUsersOf(ArrayRef<const SDNode *> Nodes, const SDNode *N) {
10722   bool Seen = false;
10723   for (const SDNode *User : N->uses()) {
10724     if (llvm::is_contained(Nodes, User))
10725       Seen = true;
10726     else
10727       return false;
10728   }
10729 
10730   return Seen;
10731 }
10732 
10733 /// isOperand - Return true if this node is an operand of N.
10734 bool SDValue::isOperandOf(const SDNode *N) const {
10735   return is_contained(N->op_values(), *this);
10736 }
10737 
10738 bool SDNode::isOperandOf(const SDNode *N) const {
10739   return any_of(N->op_values(),
10740                 [this](SDValue Op) { return this == Op.getNode(); });
10741 }
10742 
10743 /// reachesChainWithoutSideEffects - Return true if this operand (which must
10744 /// be a chain) reaches the specified operand without crossing any
10745 /// side-effecting instructions on any chain path.  In practice, this looks
10746 /// through token factors and non-volatile loads.  In order to remain efficient,
10747 /// this only looks a couple of nodes in, it does not do an exhaustive search.
10748 ///
10749 /// Note that we only need to examine chains when we're searching for
10750 /// side-effects; SelectionDAG requires that all side-effects are represented
10751 /// by chains, even if another operand would force a specific ordering. This
10752 /// constraint is necessary to allow transformations like splitting loads.
10753 bool SDValue::reachesChainWithoutSideEffects(SDValue Dest,
10754                                              unsigned Depth) const {
10755   if (*this == Dest) return true;
10756 
10757   // Don't search too deeply, we just want to be able to see through
10758   // TokenFactor's etc.
10759   if (Depth == 0) return false;
10760 
10761   // If this is a token factor, all inputs to the TF happen in parallel.
10762   if (getOpcode() == ISD::TokenFactor) {
10763     // First, try a shallow search.
10764     if (is_contained((*this)->ops(), Dest)) {
10765       // We found the chain we want as an operand of this TokenFactor.
10766       // Essentially, we reach the chain without side-effects if we could
10767       // serialize the TokenFactor into a simple chain of operations with
10768       // Dest as the last operation. This is automatically true if the
10769       // chain has one use: there are no other ordering constraints.
10770       // If the chain has more than one use, we give up: some other
10771       // use of Dest might force a side-effect between Dest and the current
10772       // node.
10773       if (Dest.hasOneUse())
10774         return true;
10775     }
10776     // Next, try a deep search: check whether every operand of the TokenFactor
10777     // reaches Dest.
10778     return llvm::all_of((*this)->ops(), [=](SDValue Op) {
10779       return Op.reachesChainWithoutSideEffects(Dest, Depth - 1);
10780     });
10781   }
10782 
10783   // Loads don't have side effects, look through them.
10784   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(*this)) {
10785     if (Ld->isUnordered())
10786       return Ld->getChain().reachesChainWithoutSideEffects(Dest, Depth-1);
10787   }
10788   return false;
10789 }
10790 
10791 bool SDNode::hasPredecessor(const SDNode *N) const {
10792   SmallPtrSet<const SDNode *, 32> Visited;
10793   SmallVector<const SDNode *, 16> Worklist;
10794   Worklist.push_back(this);
10795   return hasPredecessorHelper(N, Visited, Worklist);
10796 }
10797 
10798 void SDNode::intersectFlagsWith(const SDNodeFlags Flags) {
10799   this->Flags.intersectWith(Flags);
10800 }
10801 
10802 SDValue
10803 SelectionDAG::matchBinOpReduction(SDNode *Extract, ISD::NodeType &BinOp,
10804                                   ArrayRef<ISD::NodeType> CandidateBinOps,
10805                                   bool AllowPartials) {
10806   // The pattern must end in an extract from index 0.
10807   if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10808       !isNullConstant(Extract->getOperand(1)))
10809     return SDValue();
10810 
10811   // Match against one of the candidate binary ops.
10812   SDValue Op = Extract->getOperand(0);
10813   if (llvm::none_of(CandidateBinOps, [Op](ISD::NodeType BinOp) {
10814         return Op.getOpcode() == unsigned(BinOp);
10815       }))
10816     return SDValue();
10817 
10818   // Floating-point reductions may require relaxed constraints on the final step
10819   // of the reduction because they may reorder intermediate operations.
10820   unsigned CandidateBinOp = Op.getOpcode();
10821   if (Op.getValueType().isFloatingPoint()) {
10822     SDNodeFlags Flags = Op->getFlags();
10823     switch (CandidateBinOp) {
10824     case ISD::FADD:
10825       if (!Flags.hasNoSignedZeros() || !Flags.hasAllowReassociation())
10826         return SDValue();
10827       break;
10828     default:
10829       llvm_unreachable("Unhandled FP opcode for binop reduction");
10830     }
10831   }
10832 
10833   // Matching failed - attempt to see if we did enough stages that a partial
10834   // reduction from a subvector is possible.
10835   auto PartialReduction = [&](SDValue Op, unsigned NumSubElts) {
10836     if (!AllowPartials || !Op)
10837       return SDValue();
10838     EVT OpVT = Op.getValueType();
10839     EVT OpSVT = OpVT.getScalarType();
10840     EVT SubVT = EVT::getVectorVT(*getContext(), OpSVT, NumSubElts);
10841     if (!TLI->isExtractSubvectorCheap(SubVT, OpVT, 0))
10842       return SDValue();
10843     BinOp = (ISD::NodeType)CandidateBinOp;
10844     return getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(Op), SubVT, Op,
10845                    getVectorIdxConstant(0, SDLoc(Op)));
10846   };
10847 
10848   // At each stage, we're looking for something that looks like:
10849   // %s = shufflevector <8 x i32> %op, <8 x i32> undef,
10850   //                    <8 x i32> <i32 2, i32 3, i32 undef, i32 undef,
10851   //                               i32 undef, i32 undef, i32 undef, i32 undef>
10852   // %a = binop <8 x i32> %op, %s
10853   // Where the mask changes according to the stage. E.g. for a 3-stage pyramid,
10854   // we expect something like:
10855   // <4,5,6,7,u,u,u,u>
10856   // <2,3,u,u,u,u,u,u>
10857   // <1,u,u,u,u,u,u,u>
10858   // While a partial reduction match would be:
10859   // <2,3,u,u,u,u,u,u>
10860   // <1,u,u,u,u,u,u,u>
10861   unsigned Stages = Log2_32(Op.getValueType().getVectorNumElements());
10862   SDValue PrevOp;
10863   for (unsigned i = 0; i < Stages; ++i) {
10864     unsigned MaskEnd = (1 << i);
10865 
10866     if (Op.getOpcode() != CandidateBinOp)
10867       return PartialReduction(PrevOp, MaskEnd);
10868 
10869     SDValue Op0 = Op.getOperand(0);
10870     SDValue Op1 = Op.getOperand(1);
10871 
10872     ShuffleVectorSDNode *Shuffle = dyn_cast<ShuffleVectorSDNode>(Op0);
10873     if (Shuffle) {
10874       Op = Op1;
10875     } else {
10876       Shuffle = dyn_cast<ShuffleVectorSDNode>(Op1);
10877       Op = Op0;
10878     }
10879 
10880     // The first operand of the shuffle should be the same as the other operand
10881     // of the binop.
10882     if (!Shuffle || Shuffle->getOperand(0) != Op)
10883       return PartialReduction(PrevOp, MaskEnd);
10884 
10885     // Verify the shuffle has the expected (at this stage of the pyramid) mask.
10886     for (int Index = 0; Index < (int)MaskEnd; ++Index)
10887       if (Shuffle->getMaskElt(Index) != (int)(MaskEnd + Index))
10888         return PartialReduction(PrevOp, MaskEnd);
10889 
10890     PrevOp = Op;
10891   }
10892 
10893   // Handle subvector reductions, which tend to appear after the shuffle
10894   // reduction stages.
10895   while (Op.getOpcode() == CandidateBinOp) {
10896     unsigned NumElts = Op.getValueType().getVectorNumElements();
10897     SDValue Op0 = Op.getOperand(0);
10898     SDValue Op1 = Op.getOperand(1);
10899     if (Op0.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
10900         Op1.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
10901         Op0.getOperand(0) != Op1.getOperand(0))
10902       break;
10903     SDValue Src = Op0.getOperand(0);
10904     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
10905     if (NumSrcElts != (2 * NumElts))
10906       break;
10907     if (!(Op0.getConstantOperandAPInt(1) == 0 &&
10908           Op1.getConstantOperandAPInt(1) == NumElts) &&
10909         !(Op1.getConstantOperandAPInt(1) == 0 &&
10910           Op0.getConstantOperandAPInt(1) == NumElts))
10911       break;
10912     Op = Src;
10913   }
10914 
10915   BinOp = (ISD::NodeType)CandidateBinOp;
10916   return Op;
10917 }
10918 
10919 SDValue SelectionDAG::UnrollVectorOp(SDNode *N, unsigned ResNE) {
10920   assert(N->getNumValues() == 1 &&
10921          "Can't unroll a vector with multiple results!");
10922 
10923   EVT VT = N->getValueType(0);
10924   unsigned NE = VT.getVectorNumElements();
10925   EVT EltVT = VT.getVectorElementType();
10926   SDLoc dl(N);
10927 
10928   SmallVector<SDValue, 8> Scalars;
10929   SmallVector<SDValue, 4> Operands(N->getNumOperands());
10930 
10931   // If ResNE is 0, fully unroll the vector op.
10932   if (ResNE == 0)
10933     ResNE = NE;
10934   else if (NE > ResNE)
10935     NE = ResNE;
10936 
10937   unsigned i;
10938   for (i= 0; i != NE; ++i) {
10939     for (unsigned j = 0, e = N->getNumOperands(); j != e; ++j) {
10940       SDValue Operand = N->getOperand(j);
10941       EVT OperandVT = Operand.getValueType();
10942       if (OperandVT.isVector()) {
10943         // A vector operand; extract a single element.
10944         EVT OperandEltVT = OperandVT.getVectorElementType();
10945         Operands[j] = getNode(ISD::EXTRACT_VECTOR_ELT, dl, OperandEltVT,
10946                               Operand, getVectorIdxConstant(i, dl));
10947       } else {
10948         // A scalar operand; just use it as is.
10949         Operands[j] = Operand;
10950       }
10951     }
10952 
10953     switch (N->getOpcode()) {
10954     default: {
10955       Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands,
10956                                 N->getFlags()));
10957       break;
10958     }
10959     case ISD::VSELECT:
10960       Scalars.push_back(getNode(ISD::SELECT, dl, EltVT, Operands));
10961       break;
10962     case ISD::SHL:
10963     case ISD::SRA:
10964     case ISD::SRL:
10965     case ISD::ROTL:
10966     case ISD::ROTR:
10967       Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands[0],
10968                                getShiftAmountOperand(Operands[0].getValueType(),
10969                                                      Operands[1])));
10970       break;
10971     case ISD::SIGN_EXTEND_INREG: {
10972       EVT ExtVT = cast<VTSDNode>(Operands[1])->getVT().getVectorElementType();
10973       Scalars.push_back(getNode(N->getOpcode(), dl, EltVT,
10974                                 Operands[0],
10975                                 getValueType(ExtVT)));
10976     }
10977     }
10978   }
10979 
10980   for (; i < ResNE; ++i)
10981     Scalars.push_back(getUNDEF(EltVT));
10982 
10983   EVT VecVT = EVT::getVectorVT(*getContext(), EltVT, ResNE);
10984   return getBuildVector(VecVT, dl, Scalars);
10985 }
10986 
10987 std::pair<SDValue, SDValue> SelectionDAG::UnrollVectorOverflowOp(
10988     SDNode *N, unsigned ResNE) {
10989   unsigned Opcode = N->getOpcode();
10990   assert((Opcode == ISD::UADDO || Opcode == ISD::SADDO ||
10991           Opcode == ISD::USUBO || Opcode == ISD::SSUBO ||
10992           Opcode == ISD::UMULO || Opcode == ISD::SMULO) &&
10993          "Expected an overflow opcode");
10994 
10995   EVT ResVT = N->getValueType(0);
10996   EVT OvVT = N->getValueType(1);
10997   EVT ResEltVT = ResVT.getVectorElementType();
10998   EVT OvEltVT = OvVT.getVectorElementType();
10999   SDLoc dl(N);
11000 
11001   // If ResNE is 0, fully unroll the vector op.
11002   unsigned NE = ResVT.getVectorNumElements();
11003   if (ResNE == 0)
11004     ResNE = NE;
11005   else if (NE > ResNE)
11006     NE = ResNE;
11007 
11008   SmallVector<SDValue, 8> LHSScalars;
11009   SmallVector<SDValue, 8> RHSScalars;
11010   ExtractVectorElements(N->getOperand(0), LHSScalars, 0, NE);
11011   ExtractVectorElements(N->getOperand(1), RHSScalars, 0, NE);
11012 
11013   EVT SVT = TLI->getSetCCResultType(getDataLayout(), *getContext(), ResEltVT);
11014   SDVTList VTs = getVTList(ResEltVT, SVT);
11015   SmallVector<SDValue, 8> ResScalars;
11016   SmallVector<SDValue, 8> OvScalars;
11017   for (unsigned i = 0; i < NE; ++i) {
11018     SDValue Res = getNode(Opcode, dl, VTs, LHSScalars[i], RHSScalars[i]);
11019     SDValue Ov =
11020         getSelect(dl, OvEltVT, Res.getValue(1),
11021                   getBoolConstant(true, dl, OvEltVT, ResVT),
11022                   getConstant(0, dl, OvEltVT));
11023 
11024     ResScalars.push_back(Res);
11025     OvScalars.push_back(Ov);
11026   }
11027 
11028   ResScalars.append(ResNE - NE, getUNDEF(ResEltVT));
11029   OvScalars.append(ResNE - NE, getUNDEF(OvEltVT));
11030 
11031   EVT NewResVT = EVT::getVectorVT(*getContext(), ResEltVT, ResNE);
11032   EVT NewOvVT = EVT::getVectorVT(*getContext(), OvEltVT, ResNE);
11033   return std::make_pair(getBuildVector(NewResVT, dl, ResScalars),
11034                         getBuildVector(NewOvVT, dl, OvScalars));
11035 }
11036 
11037 bool SelectionDAG::areNonVolatileConsecutiveLoads(LoadSDNode *LD,
11038                                                   LoadSDNode *Base,
11039                                                   unsigned Bytes,
11040                                                   int Dist) const {
11041   if (LD->isVolatile() || Base->isVolatile())
11042     return false;
11043   // TODO: probably too restrictive for atomics, revisit
11044   if (!LD->isSimple())
11045     return false;
11046   if (LD->isIndexed() || Base->isIndexed())
11047     return false;
11048   if (LD->getChain() != Base->getChain())
11049     return false;
11050   EVT VT = LD->getValueType(0);
11051   if (VT.getSizeInBits() / 8 != Bytes)
11052     return false;
11053 
11054   auto BaseLocDecomp = BaseIndexOffset::match(Base, *this);
11055   auto LocDecomp = BaseIndexOffset::match(LD, *this);
11056 
11057   int64_t Offset = 0;
11058   if (BaseLocDecomp.equalBaseIndex(LocDecomp, *this, Offset))
11059     return (Dist * Bytes == Offset);
11060   return false;
11061 }
11062 
11063 /// InferPtrAlignment - Infer alignment of a load / store address. Return None
11064 /// if it cannot be inferred.
11065 MaybeAlign SelectionDAG::InferPtrAlign(SDValue Ptr) const {
11066   // If this is a GlobalAddress + cst, return the alignment.
11067   const GlobalValue *GV = nullptr;
11068   int64_t GVOffset = 0;
11069   if (TLI->isGAPlusOffset(Ptr.getNode(), GV, GVOffset)) {
11070     unsigned PtrWidth = getDataLayout().getPointerTypeSizeInBits(GV->getType());
11071     KnownBits Known(PtrWidth);
11072     llvm::computeKnownBits(GV, Known, getDataLayout());
11073     unsigned AlignBits = Known.countMinTrailingZeros();
11074     if (AlignBits)
11075       return commonAlignment(Align(1ull << std::min(31U, AlignBits)), GVOffset);
11076   }
11077 
11078   // If this is a direct reference to a stack slot, use information about the
11079   // stack slot's alignment.
11080   int FrameIdx = INT_MIN;
11081   int64_t FrameOffset = 0;
11082   if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr)) {
11083     FrameIdx = FI->getIndex();
11084   } else if (isBaseWithConstantOffset(Ptr) &&
11085              isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
11086     // Handle FI+Cst
11087     FrameIdx = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
11088     FrameOffset = Ptr.getConstantOperandVal(1);
11089   }
11090 
11091   if (FrameIdx != INT_MIN) {
11092     const MachineFrameInfo &MFI = getMachineFunction().getFrameInfo();
11093     return commonAlignment(MFI.getObjectAlign(FrameIdx), FrameOffset);
11094   }
11095 
11096   return None;
11097 }
11098 
11099 /// GetSplitDestVTs - Compute the VTs needed for the low/hi parts of a type
11100 /// which is split (or expanded) into two not necessarily identical pieces.
11101 std::pair<EVT, EVT> SelectionDAG::GetSplitDestVTs(const EVT &VT) const {
11102   // Currently all types are split in half.
11103   EVT LoVT, HiVT;
11104   if (!VT.isVector())
11105     LoVT = HiVT = TLI->getTypeToTransformTo(*getContext(), VT);
11106   else
11107     LoVT = HiVT = VT.getHalfNumVectorElementsVT(*getContext());
11108 
11109   return std::make_pair(LoVT, HiVT);
11110 }
11111 
11112 /// GetDependentSplitDestVTs - Compute the VTs needed for the low/hi parts of a
11113 /// type, dependent on an enveloping VT that has been split into two identical
11114 /// pieces. Sets the HiIsEmpty flag when hi type has zero storage size.
11115 std::pair<EVT, EVT>
11116 SelectionDAG::GetDependentSplitDestVTs(const EVT &VT, const EVT &EnvVT,
11117                                        bool *HiIsEmpty) const {
11118   EVT EltTp = VT.getVectorElementType();
11119   // Examples:
11120   //   custom VL=8  with enveloping VL=8/8 yields 8/0 (hi empty)
11121   //   custom VL=9  with enveloping VL=8/8 yields 8/1
11122   //   custom VL=10 with enveloping VL=8/8 yields 8/2
11123   //   etc.
11124   ElementCount VTNumElts = VT.getVectorElementCount();
11125   ElementCount EnvNumElts = EnvVT.getVectorElementCount();
11126   assert(VTNumElts.isScalable() == EnvNumElts.isScalable() &&
11127          "Mixing fixed width and scalable vectors when enveloping a type");
11128   EVT LoVT, HiVT;
11129   if (VTNumElts.getKnownMinValue() > EnvNumElts.getKnownMinValue()) {
11130     LoVT = EVT::getVectorVT(*getContext(), EltTp, EnvNumElts);
11131     HiVT = EVT::getVectorVT(*getContext(), EltTp, VTNumElts - EnvNumElts);
11132     *HiIsEmpty = false;
11133   } else {
11134     // Flag that hi type has zero storage size, but return split envelop type
11135     // (this would be easier if vector types with zero elements were allowed).
11136     LoVT = EVT::getVectorVT(*getContext(), EltTp, VTNumElts);
11137     HiVT = EVT::getVectorVT(*getContext(), EltTp, EnvNumElts);
11138     *HiIsEmpty = true;
11139   }
11140   return std::make_pair(LoVT, HiVT);
11141 }
11142 
11143 /// SplitVector - Split the vector with EXTRACT_SUBVECTOR and return the
11144 /// low/high part.
11145 std::pair<SDValue, SDValue>
11146 SelectionDAG::SplitVector(const SDValue &N, const SDLoc &DL, const EVT &LoVT,
11147                           const EVT &HiVT) {
11148   assert(LoVT.isScalableVector() == HiVT.isScalableVector() &&
11149          LoVT.isScalableVector() == N.getValueType().isScalableVector() &&
11150          "Splitting vector with an invalid mixture of fixed and scalable "
11151          "vector types");
11152   assert(LoVT.getVectorMinNumElements() + HiVT.getVectorMinNumElements() <=
11153              N.getValueType().getVectorMinNumElements() &&
11154          "More vector elements requested than available!");
11155   SDValue Lo, Hi;
11156   Lo =
11157       getNode(ISD::EXTRACT_SUBVECTOR, DL, LoVT, N, getVectorIdxConstant(0, DL));
11158   // For scalable vectors it is safe to use LoVT.getVectorMinNumElements()
11159   // (rather than having to use ElementCount), because EXTRACT_SUBVECTOR scales
11160   // IDX with the runtime scaling factor of the result vector type. For
11161   // fixed-width result vectors, that runtime scaling factor is 1.
11162   Hi = getNode(ISD::EXTRACT_SUBVECTOR, DL, HiVT, N,
11163                getVectorIdxConstant(LoVT.getVectorMinNumElements(), DL));
11164   return std::make_pair(Lo, Hi);
11165 }
11166 
11167 std::pair<SDValue, SDValue> SelectionDAG::SplitEVL(SDValue N, EVT VecVT,
11168                                                    const SDLoc &DL) {
11169   // Split the vector length parameter.
11170   // %evl -> umin(%evl, %halfnumelts) and usubsat(%evl - %halfnumelts).
11171   EVT VT = N.getValueType();
11172   assert(VecVT.getVectorElementCount().isKnownEven() &&
11173          "Expecting the mask to be an evenly-sized vector");
11174   unsigned HalfMinNumElts = VecVT.getVectorMinNumElements() / 2;
11175   SDValue HalfNumElts =
11176       VecVT.isFixedLengthVector()
11177           ? getConstant(HalfMinNumElts, DL, VT)
11178           : getVScale(DL, VT, APInt(VT.getScalarSizeInBits(), HalfMinNumElts));
11179   SDValue Lo = getNode(ISD::UMIN, DL, VT, N, HalfNumElts);
11180   SDValue Hi = getNode(ISD::USUBSAT, DL, VT, N, HalfNumElts);
11181   return std::make_pair(Lo, Hi);
11182 }
11183 
11184 /// Widen the vector up to the next power of two using INSERT_SUBVECTOR.
11185 SDValue SelectionDAG::WidenVector(const SDValue &N, const SDLoc &DL) {
11186   EVT VT = N.getValueType();
11187   EVT WideVT = EVT::getVectorVT(*getContext(), VT.getVectorElementType(),
11188                                 NextPowerOf2(VT.getVectorNumElements()));
11189   return getNode(ISD::INSERT_SUBVECTOR, DL, WideVT, getUNDEF(WideVT), N,
11190                  getVectorIdxConstant(0, DL));
11191 }
11192 
11193 void SelectionDAG::ExtractVectorElements(SDValue Op,
11194                                          SmallVectorImpl<SDValue> &Args,
11195                                          unsigned Start, unsigned Count,
11196                                          EVT EltVT) {
11197   EVT VT = Op.getValueType();
11198   if (Count == 0)
11199     Count = VT.getVectorNumElements();
11200   if (EltVT == EVT())
11201     EltVT = VT.getVectorElementType();
11202   SDLoc SL(Op);
11203   for (unsigned i = Start, e = Start + Count; i != e; ++i) {
11204     Args.push_back(getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Op,
11205                            getVectorIdxConstant(i, SL)));
11206   }
11207 }
11208 
11209 // getAddressSpace - Return the address space this GlobalAddress belongs to.
11210 unsigned GlobalAddressSDNode::getAddressSpace() const {
11211   return getGlobal()->getType()->getAddressSpace();
11212 }
11213 
11214 Type *ConstantPoolSDNode::getType() const {
11215   if (isMachineConstantPoolEntry())
11216     return Val.MachineCPVal->getType();
11217   return Val.ConstVal->getType();
11218 }
11219 
11220 bool BuildVectorSDNode::isConstantSplat(APInt &SplatValue, APInt &SplatUndef,
11221                                         unsigned &SplatBitSize,
11222                                         bool &HasAnyUndefs,
11223                                         unsigned MinSplatBits,
11224                                         bool IsBigEndian) const {
11225   EVT VT = getValueType(0);
11226   assert(VT.isVector() && "Expected a vector type");
11227   unsigned VecWidth = VT.getSizeInBits();
11228   if (MinSplatBits > VecWidth)
11229     return false;
11230 
11231   // FIXME: The widths are based on this node's type, but build vectors can
11232   // truncate their operands.
11233   SplatValue = APInt(VecWidth, 0);
11234   SplatUndef = APInt(VecWidth, 0);
11235 
11236   // Get the bits. Bits with undefined values (when the corresponding element
11237   // of the vector is an ISD::UNDEF value) are set in SplatUndef and cleared
11238   // in SplatValue. If any of the values are not constant, give up and return
11239   // false.
11240   unsigned int NumOps = getNumOperands();
11241   assert(NumOps > 0 && "isConstantSplat has 0-size build vector");
11242   unsigned EltWidth = VT.getScalarSizeInBits();
11243 
11244   for (unsigned j = 0; j < NumOps; ++j) {
11245     unsigned i = IsBigEndian ? NumOps - 1 - j : j;
11246     SDValue OpVal = getOperand(i);
11247     unsigned BitPos = j * EltWidth;
11248 
11249     if (OpVal.isUndef())
11250       SplatUndef.setBits(BitPos, BitPos + EltWidth);
11251     else if (auto *CN = dyn_cast<ConstantSDNode>(OpVal))
11252       SplatValue.insertBits(CN->getAPIntValue().zextOrTrunc(EltWidth), BitPos);
11253     else if (auto *CN = dyn_cast<ConstantFPSDNode>(OpVal))
11254       SplatValue.insertBits(CN->getValueAPF().bitcastToAPInt(), BitPos);
11255     else
11256       return false;
11257   }
11258 
11259   // The build_vector is all constants or undefs. Find the smallest element
11260   // size that splats the vector.
11261   HasAnyUndefs = (SplatUndef != 0);
11262 
11263   // FIXME: This does not work for vectors with elements less than 8 bits.
11264   while (VecWidth > 8) {
11265     unsigned HalfSize = VecWidth / 2;
11266     APInt HighValue = SplatValue.extractBits(HalfSize, HalfSize);
11267     APInt LowValue = SplatValue.extractBits(HalfSize, 0);
11268     APInt HighUndef = SplatUndef.extractBits(HalfSize, HalfSize);
11269     APInt LowUndef = SplatUndef.extractBits(HalfSize, 0);
11270 
11271     // If the two halves do not match (ignoring undef bits), stop here.
11272     if ((HighValue & ~LowUndef) != (LowValue & ~HighUndef) ||
11273         MinSplatBits > HalfSize)
11274       break;
11275 
11276     SplatValue = HighValue | LowValue;
11277     SplatUndef = HighUndef & LowUndef;
11278 
11279     VecWidth = HalfSize;
11280   }
11281 
11282   SplatBitSize = VecWidth;
11283   return true;
11284 }
11285 
11286 SDValue BuildVectorSDNode::getSplatValue(const APInt &DemandedElts,
11287                                          BitVector *UndefElements) const {
11288   unsigned NumOps = getNumOperands();
11289   if (UndefElements) {
11290     UndefElements->clear();
11291     UndefElements->resize(NumOps);
11292   }
11293   assert(NumOps == DemandedElts.getBitWidth() && "Unexpected vector size");
11294   if (!DemandedElts)
11295     return SDValue();
11296   SDValue Splatted;
11297   for (unsigned i = 0; i != NumOps; ++i) {
11298     if (!DemandedElts[i])
11299       continue;
11300     SDValue Op = getOperand(i);
11301     if (Op.isUndef()) {
11302       if (UndefElements)
11303         (*UndefElements)[i] = true;
11304     } else if (!Splatted) {
11305       Splatted = Op;
11306     } else if (Splatted != Op) {
11307       return SDValue();
11308     }
11309   }
11310 
11311   if (!Splatted) {
11312     unsigned FirstDemandedIdx = DemandedElts.countTrailingZeros();
11313     assert(getOperand(FirstDemandedIdx).isUndef() &&
11314            "Can only have a splat without a constant for all undefs.");
11315     return getOperand(FirstDemandedIdx);
11316   }
11317 
11318   return Splatted;
11319 }
11320 
11321 SDValue BuildVectorSDNode::getSplatValue(BitVector *UndefElements) const {
11322   APInt DemandedElts = APInt::getAllOnes(getNumOperands());
11323   return getSplatValue(DemandedElts, UndefElements);
11324 }
11325 
11326 bool BuildVectorSDNode::getRepeatedSequence(const APInt &DemandedElts,
11327                                             SmallVectorImpl<SDValue> &Sequence,
11328                                             BitVector *UndefElements) const {
11329   unsigned NumOps = getNumOperands();
11330   Sequence.clear();
11331   if (UndefElements) {
11332     UndefElements->clear();
11333     UndefElements->resize(NumOps);
11334   }
11335   assert(NumOps == DemandedElts.getBitWidth() && "Unexpected vector size");
11336   if (!DemandedElts || NumOps < 2 || !isPowerOf2_32(NumOps))
11337     return false;
11338 
11339   // Set the undefs even if we don't find a sequence (like getSplatValue).
11340   if (UndefElements)
11341     for (unsigned I = 0; I != NumOps; ++I)
11342       if (DemandedElts[I] && getOperand(I).isUndef())
11343         (*UndefElements)[I] = true;
11344 
11345   // Iteratively widen the sequence length looking for repetitions.
11346   for (unsigned SeqLen = 1; SeqLen < NumOps; SeqLen *= 2) {
11347     Sequence.append(SeqLen, SDValue());
11348     for (unsigned I = 0; I != NumOps; ++I) {
11349       if (!DemandedElts[I])
11350         continue;
11351       SDValue &SeqOp = Sequence[I % SeqLen];
11352       SDValue Op = getOperand(I);
11353       if (Op.isUndef()) {
11354         if (!SeqOp)
11355           SeqOp = Op;
11356         continue;
11357       }
11358       if (SeqOp && !SeqOp.isUndef() && SeqOp != Op) {
11359         Sequence.clear();
11360         break;
11361       }
11362       SeqOp = Op;
11363     }
11364     if (!Sequence.empty())
11365       return true;
11366   }
11367 
11368   assert(Sequence.empty() && "Failed to empty non-repeating sequence pattern");
11369   return false;
11370 }
11371 
11372 bool BuildVectorSDNode::getRepeatedSequence(SmallVectorImpl<SDValue> &Sequence,
11373                                             BitVector *UndefElements) const {
11374   APInt DemandedElts = APInt::getAllOnes(getNumOperands());
11375   return getRepeatedSequence(DemandedElts, Sequence, UndefElements);
11376 }
11377 
11378 ConstantSDNode *
11379 BuildVectorSDNode::getConstantSplatNode(const APInt &DemandedElts,
11380                                         BitVector *UndefElements) const {
11381   return dyn_cast_or_null<ConstantSDNode>(
11382       getSplatValue(DemandedElts, UndefElements));
11383 }
11384 
11385 ConstantSDNode *
11386 BuildVectorSDNode::getConstantSplatNode(BitVector *UndefElements) const {
11387   return dyn_cast_or_null<ConstantSDNode>(getSplatValue(UndefElements));
11388 }
11389 
11390 ConstantFPSDNode *
11391 BuildVectorSDNode::getConstantFPSplatNode(const APInt &DemandedElts,
11392                                           BitVector *UndefElements) const {
11393   return dyn_cast_or_null<ConstantFPSDNode>(
11394       getSplatValue(DemandedElts, UndefElements));
11395 }
11396 
11397 ConstantFPSDNode *
11398 BuildVectorSDNode::getConstantFPSplatNode(BitVector *UndefElements) const {
11399   return dyn_cast_or_null<ConstantFPSDNode>(getSplatValue(UndefElements));
11400 }
11401 
11402 int32_t
11403 BuildVectorSDNode::getConstantFPSplatPow2ToLog2Int(BitVector *UndefElements,
11404                                                    uint32_t BitWidth) const {
11405   if (ConstantFPSDNode *CN =
11406           dyn_cast_or_null<ConstantFPSDNode>(getSplatValue(UndefElements))) {
11407     bool IsExact;
11408     APSInt IntVal(BitWidth);
11409     const APFloat &APF = CN->getValueAPF();
11410     if (APF.convertToInteger(IntVal, APFloat::rmTowardZero, &IsExact) !=
11411             APFloat::opOK ||
11412         !IsExact)
11413       return -1;
11414 
11415     return IntVal.exactLogBase2();
11416   }
11417   return -1;
11418 }
11419 
11420 bool BuildVectorSDNode::getConstantRawBits(
11421     bool IsLittleEndian, unsigned DstEltSizeInBits,
11422     SmallVectorImpl<APInt> &RawBitElements, BitVector &UndefElements) const {
11423   // Early-out if this contains anything but Undef/Constant/ConstantFP.
11424   if (!isConstant())
11425     return false;
11426 
11427   unsigned NumSrcOps = getNumOperands();
11428   unsigned SrcEltSizeInBits = getValueType(0).getScalarSizeInBits();
11429   assert(((NumSrcOps * SrcEltSizeInBits) % DstEltSizeInBits) == 0 &&
11430          "Invalid bitcast scale");
11431 
11432   // Extract raw src bits.
11433   SmallVector<APInt> SrcBitElements(NumSrcOps,
11434                                     APInt::getNullValue(SrcEltSizeInBits));
11435   BitVector SrcUndeElements(NumSrcOps, false);
11436 
11437   for (unsigned I = 0; I != NumSrcOps; ++I) {
11438     SDValue Op = getOperand(I);
11439     if (Op.isUndef()) {
11440       SrcUndeElements.set(I);
11441       continue;
11442     }
11443     auto *CInt = dyn_cast<ConstantSDNode>(Op);
11444     auto *CFP = dyn_cast<ConstantFPSDNode>(Op);
11445     assert((CInt || CFP) && "Unknown constant");
11446     SrcBitElements[I] =
11447         CInt ? CInt->getAPIntValue().truncOrSelf(SrcEltSizeInBits)
11448              : CFP->getValueAPF().bitcastToAPInt();
11449   }
11450 
11451   // Recast to dst width.
11452   recastRawBits(IsLittleEndian, DstEltSizeInBits, RawBitElements,
11453                 SrcBitElements, UndefElements, SrcUndeElements);
11454   return true;
11455 }
11456 
11457 void BuildVectorSDNode::recastRawBits(bool IsLittleEndian,
11458                                       unsigned DstEltSizeInBits,
11459                                       SmallVectorImpl<APInt> &DstBitElements,
11460                                       ArrayRef<APInt> SrcBitElements,
11461                                       BitVector &DstUndefElements,
11462                                       const BitVector &SrcUndefElements) {
11463   unsigned NumSrcOps = SrcBitElements.size();
11464   unsigned SrcEltSizeInBits = SrcBitElements[0].getBitWidth();
11465   assert(((NumSrcOps * SrcEltSizeInBits) % DstEltSizeInBits) == 0 &&
11466          "Invalid bitcast scale");
11467   assert(NumSrcOps == SrcUndefElements.size() &&
11468          "Vector size mismatch");
11469 
11470   unsigned NumDstOps = (NumSrcOps * SrcEltSizeInBits) / DstEltSizeInBits;
11471   DstUndefElements.clear();
11472   DstUndefElements.resize(NumDstOps, false);
11473   DstBitElements.assign(NumDstOps, APInt::getNullValue(DstEltSizeInBits));
11474 
11475   // Concatenate src elements constant bits together into dst element.
11476   if (SrcEltSizeInBits <= DstEltSizeInBits) {
11477     unsigned Scale = DstEltSizeInBits / SrcEltSizeInBits;
11478     for (unsigned I = 0; I != NumDstOps; ++I) {
11479       DstUndefElements.set(I);
11480       APInt &DstBits = DstBitElements[I];
11481       for (unsigned J = 0; J != Scale; ++J) {
11482         unsigned Idx = (I * Scale) + (IsLittleEndian ? J : (Scale - J - 1));
11483         if (SrcUndefElements[Idx])
11484           continue;
11485         DstUndefElements.reset(I);
11486         const APInt &SrcBits = SrcBitElements[Idx];
11487         assert(SrcBits.getBitWidth() == SrcEltSizeInBits &&
11488                "Illegal constant bitwidths");
11489         DstBits.insertBits(SrcBits, J * SrcEltSizeInBits);
11490       }
11491     }
11492     return;
11493   }
11494 
11495   // Split src element constant bits into dst elements.
11496   unsigned Scale = SrcEltSizeInBits / DstEltSizeInBits;
11497   for (unsigned I = 0; I != NumSrcOps; ++I) {
11498     if (SrcUndefElements[I]) {
11499       DstUndefElements.set(I * Scale, (I + 1) * Scale);
11500       continue;
11501     }
11502     const APInt &SrcBits = SrcBitElements[I];
11503     for (unsigned J = 0; J != Scale; ++J) {
11504       unsigned Idx = (I * Scale) + (IsLittleEndian ? J : (Scale - J - 1));
11505       APInt &DstBits = DstBitElements[Idx];
11506       DstBits = SrcBits.extractBits(DstEltSizeInBits, J * DstEltSizeInBits);
11507     }
11508   }
11509 }
11510 
11511 bool BuildVectorSDNode::isConstant() const {
11512   for (const SDValue &Op : op_values()) {
11513     unsigned Opc = Op.getOpcode();
11514     if (Opc != ISD::UNDEF && Opc != ISD::Constant && Opc != ISD::ConstantFP)
11515       return false;
11516   }
11517   return true;
11518 }
11519 
11520 bool ShuffleVectorSDNode::isSplatMask(const int *Mask, EVT VT) {
11521   // Find the first non-undef value in the shuffle mask.
11522   unsigned i, e;
11523   for (i = 0, e = VT.getVectorNumElements(); i != e && Mask[i] < 0; ++i)
11524     /* search */;
11525 
11526   // If all elements are undefined, this shuffle can be considered a splat
11527   // (although it should eventually get simplified away completely).
11528   if (i == e)
11529     return true;
11530 
11531   // Make sure all remaining elements are either undef or the same as the first
11532   // non-undef value.
11533   for (int Idx = Mask[i]; i != e; ++i)
11534     if (Mask[i] >= 0 && Mask[i] != Idx)
11535       return false;
11536   return true;
11537 }
11538 
11539 // Returns the SDNode if it is a constant integer BuildVector
11540 // or constant integer.
11541 SDNode *SelectionDAG::isConstantIntBuildVectorOrConstantInt(SDValue N) const {
11542   if (isa<ConstantSDNode>(N))
11543     return N.getNode();
11544   if (ISD::isBuildVectorOfConstantSDNodes(N.getNode()))
11545     return N.getNode();
11546   // Treat a GlobalAddress supporting constant offset folding as a
11547   // constant integer.
11548   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N))
11549     if (GA->getOpcode() == ISD::GlobalAddress &&
11550         TLI->isOffsetFoldingLegal(GA))
11551       return GA;
11552   if ((N.getOpcode() == ISD::SPLAT_VECTOR) &&
11553       isa<ConstantSDNode>(N.getOperand(0)))
11554     return N.getNode();
11555   return nullptr;
11556 }
11557 
11558 // Returns the SDNode if it is a constant float BuildVector
11559 // or constant float.
11560 SDNode *SelectionDAG::isConstantFPBuildVectorOrConstantFP(SDValue N) const {
11561   if (isa<ConstantFPSDNode>(N))
11562     return N.getNode();
11563 
11564   if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode()))
11565     return N.getNode();
11566 
11567   if ((N.getOpcode() == ISD::SPLAT_VECTOR) &&
11568       isa<ConstantFPSDNode>(N.getOperand(0)))
11569     return N.getNode();
11570 
11571   return nullptr;
11572 }
11573 
11574 void SelectionDAG::createOperands(SDNode *Node, ArrayRef<SDValue> Vals) {
11575   assert(!Node->OperandList && "Node already has operands");
11576   assert(SDNode::getMaxNumOperands() >= Vals.size() &&
11577          "too many operands to fit into SDNode");
11578   SDUse *Ops = OperandRecycler.allocate(
11579       ArrayRecycler<SDUse>::Capacity::get(Vals.size()), OperandAllocator);
11580 
11581   bool IsDivergent = false;
11582   for (unsigned I = 0; I != Vals.size(); ++I) {
11583     Ops[I].setUser(Node);
11584     Ops[I].setInitial(Vals[I]);
11585     if (Ops[I].Val.getValueType() != MVT::Other) // Skip Chain. It does not carry divergence.
11586       IsDivergent |= Ops[I].getNode()->isDivergent();
11587   }
11588   Node->NumOperands = Vals.size();
11589   Node->OperandList = Ops;
11590   if (!TLI->isSDNodeAlwaysUniform(Node)) {
11591     IsDivergent |= TLI->isSDNodeSourceOfDivergence(Node, FLI, DA);
11592     Node->SDNodeBits.IsDivergent = IsDivergent;
11593   }
11594   checkForCycles(Node);
11595 }
11596 
11597 SDValue SelectionDAG::getTokenFactor(const SDLoc &DL,
11598                                      SmallVectorImpl<SDValue> &Vals) {
11599   size_t Limit = SDNode::getMaxNumOperands();
11600   while (Vals.size() > Limit) {
11601     unsigned SliceIdx = Vals.size() - Limit;
11602     auto ExtractedTFs = ArrayRef<SDValue>(Vals).slice(SliceIdx, Limit);
11603     SDValue NewTF = getNode(ISD::TokenFactor, DL, MVT::Other, ExtractedTFs);
11604     Vals.erase(Vals.begin() + SliceIdx, Vals.end());
11605     Vals.emplace_back(NewTF);
11606   }
11607   return getNode(ISD::TokenFactor, DL, MVT::Other, Vals);
11608 }
11609 
11610 SDValue SelectionDAG::getNeutralElement(unsigned Opcode, const SDLoc &DL,
11611                                         EVT VT, SDNodeFlags Flags) {
11612   switch (Opcode) {
11613   default:
11614     return SDValue();
11615   case ISD::ADD:
11616   case ISD::OR:
11617   case ISD::XOR:
11618   case ISD::UMAX:
11619     return getConstant(0, DL, VT);
11620   case ISD::MUL:
11621     return getConstant(1, DL, VT);
11622   case ISD::AND:
11623   case ISD::UMIN:
11624     return getAllOnesConstant(DL, VT);
11625   case ISD::SMAX:
11626     return getConstant(APInt::getSignedMinValue(VT.getSizeInBits()), DL, VT);
11627   case ISD::SMIN:
11628     return getConstant(APInt::getSignedMaxValue(VT.getSizeInBits()), DL, VT);
11629   case ISD::FADD:
11630     return getConstantFP(-0.0, DL, VT);
11631   case ISD::FMUL:
11632     return getConstantFP(1.0, DL, VT);
11633   case ISD::FMINNUM:
11634   case ISD::FMAXNUM: {
11635     // Neutral element for fminnum is NaN, Inf or FLT_MAX, depending on FMF.
11636     const fltSemantics &Semantics = EVTToAPFloatSemantics(VT);
11637     APFloat NeutralAF = !Flags.hasNoNaNs() ? APFloat::getQNaN(Semantics) :
11638                         !Flags.hasNoInfs() ? APFloat::getInf(Semantics) :
11639                         APFloat::getLargest(Semantics);
11640     if (Opcode == ISD::FMAXNUM)
11641       NeutralAF.changeSign();
11642 
11643     return getConstantFP(NeutralAF, DL, VT);
11644   }
11645   }
11646 }
11647 
11648 #ifndef NDEBUG
11649 static void checkForCyclesHelper(const SDNode *N,
11650                                  SmallPtrSetImpl<const SDNode*> &Visited,
11651                                  SmallPtrSetImpl<const SDNode*> &Checked,
11652                                  const llvm::SelectionDAG *DAG) {
11653   // If this node has already been checked, don't check it again.
11654   if (Checked.count(N))
11655     return;
11656 
11657   // If a node has already been visited on this depth-first walk, reject it as
11658   // a cycle.
11659   if (!Visited.insert(N).second) {
11660     errs() << "Detected cycle in SelectionDAG\n";
11661     dbgs() << "Offending node:\n";
11662     N->dumprFull(DAG); dbgs() << "\n";
11663     abort();
11664   }
11665 
11666   for (const SDValue &Op : N->op_values())
11667     checkForCyclesHelper(Op.getNode(), Visited, Checked, DAG);
11668 
11669   Checked.insert(N);
11670   Visited.erase(N);
11671 }
11672 #endif
11673 
11674 void llvm::checkForCycles(const llvm::SDNode *N,
11675                           const llvm::SelectionDAG *DAG,
11676                           bool force) {
11677 #ifndef NDEBUG
11678   bool check = force;
11679 #ifdef EXPENSIVE_CHECKS
11680   check = true;
11681 #endif  // EXPENSIVE_CHECKS
11682   if (check) {
11683     assert(N && "Checking nonexistent SDNode");
11684     SmallPtrSet<const SDNode*, 32> visited;
11685     SmallPtrSet<const SDNode*, 32> checked;
11686     checkForCyclesHelper(N, visited, checked, DAG);
11687   }
11688 #endif  // !NDEBUG
11689 }
11690 
11691 void llvm::checkForCycles(const llvm::SelectionDAG *DAG, bool force) {
11692   checkForCycles(DAG->getRoot().getNode(), DAG, force);
11693 }
11694