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