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