1 //===- SelectionDAG.cpp - Implement the SelectionDAG data structures ------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This implements the SelectionDAG class.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "llvm/CodeGen/SelectionDAG.h"
14 #include "SDNodeDbgValue.h"
15 #include "llvm/ADT/APFloat.h"
16 #include "llvm/ADT/APInt.h"
17 #include "llvm/ADT/APSInt.h"
18 #include "llvm/ADT/ArrayRef.h"
19 #include "llvm/ADT/BitVector.h"
20 #include "llvm/ADT/FoldingSet.h"
21 #include "llvm/ADT/None.h"
22 #include "llvm/ADT/STLExtras.h"
23 #include "llvm/ADT/SmallPtrSet.h"
24 #include "llvm/ADT/SmallVector.h"
25 #include "llvm/ADT/Triple.h"
26 #include "llvm/ADT/Twine.h"
27 #include "llvm/Analysis/MemoryLocation.h"
28 #include "llvm/Analysis/ValueTracking.h"
29 #include "llvm/CodeGen/Analysis.h"
30 #include "llvm/CodeGen/FunctionLoweringInfo.h"
31 #include "llvm/CodeGen/ISDOpcodes.h"
32 #include "llvm/CodeGen/MachineBasicBlock.h"
33 #include "llvm/CodeGen/MachineConstantPool.h"
34 #include "llvm/CodeGen/MachineFrameInfo.h"
35 #include "llvm/CodeGen/MachineFunction.h"
36 #include "llvm/CodeGen/MachineMemOperand.h"
37 #include "llvm/CodeGen/RuntimeLibcalls.h"
38 #include "llvm/CodeGen/SelectionDAGAddressAnalysis.h"
39 #include "llvm/CodeGen/SelectionDAGNodes.h"
40 #include "llvm/CodeGen/SelectionDAGTargetInfo.h"
41 #include "llvm/CodeGen/TargetFrameLowering.h"
42 #include "llvm/CodeGen/TargetLowering.h"
43 #include "llvm/CodeGen/TargetRegisterInfo.h"
44 #include "llvm/CodeGen/TargetSubtargetInfo.h"
45 #include "llvm/CodeGen/ValueTypes.h"
46 #include "llvm/IR/Constant.h"
47 #include "llvm/IR/Constants.h"
48 #include "llvm/IR/DataLayout.h"
49 #include "llvm/IR/DebugInfoMetadata.h"
50 #include "llvm/IR/DebugLoc.h"
51 #include "llvm/IR/DerivedTypes.h"
52 #include "llvm/IR/Function.h"
53 #include "llvm/IR/GlobalValue.h"
54 #include "llvm/IR/Metadata.h"
55 #include "llvm/IR/Type.h"
56 #include "llvm/Support/Casting.h"
57 #include "llvm/Support/CodeGen.h"
58 #include "llvm/Support/Compiler.h"
59 #include "llvm/Support/Debug.h"
60 #include "llvm/Support/ErrorHandling.h"
61 #include "llvm/Support/KnownBits.h"
62 #include "llvm/Support/MachineValueType.h"
63 #include "llvm/Support/ManagedStatic.h"
64 #include "llvm/Support/MathExtras.h"
65 #include "llvm/Support/Mutex.h"
66 #include "llvm/Support/raw_ostream.h"
67 #include "llvm/Target/TargetMachine.h"
68 #include "llvm/Target/TargetOptions.h"
69 #include "llvm/Transforms/Utils/SizeOpts.h"
70 #include <algorithm>
71 #include <cassert>
72 #include <cstdint>
73 #include <cstdlib>
74 #include <limits>
75 #include <set>
76 #include <string>
77 #include <utility>
78 #include <vector>
79 
80 using namespace llvm;
81 
82 /// makeVTList - Return an instance of the SDVTList struct initialized with the
83 /// specified members.
84 static SDVTList makeVTList(const EVT *VTs, unsigned NumVTs) {
85   SDVTList Res = {VTs, NumVTs};
86   return Res;
87 }
88 
89 // Default null implementations of the callbacks.
90 void SelectionDAG::DAGUpdateListener::NodeDeleted(SDNode*, SDNode*) {}
91 void SelectionDAG::DAGUpdateListener::NodeUpdated(SDNode*) {}
92 void SelectionDAG::DAGUpdateListener::NodeInserted(SDNode *) {}
93 
94 void SelectionDAG::DAGNodeDeletedListener::anchor() {}
95 
96 #define DEBUG_TYPE "selectiondag"
97 
98 static cl::opt<bool> EnableMemCpyDAGOpt("enable-memcpy-dag-opt",
99        cl::Hidden, cl::init(true),
100        cl::desc("Gang up loads and stores generated by inlining of memcpy"));
101 
102 static cl::opt<int> MaxLdStGlue("ldstmemcpy-glue-max",
103        cl::desc("Number limit for gluing ld/st of memcpy."),
104        cl::Hidden, cl::init(0));
105 
106 static void NewSDValueDbgMsg(SDValue V, StringRef Msg, SelectionDAG *G) {
107   LLVM_DEBUG(dbgs() << Msg; V.getNode()->dump(G););
108 }
109 
110 //===----------------------------------------------------------------------===//
111 //                              ConstantFPSDNode Class
112 //===----------------------------------------------------------------------===//
113 
114 /// isExactlyValue - We don't rely on operator== working on double values, as
115 /// it returns true for things that are clearly not equal, like -0.0 and 0.0.
116 /// As such, this method can be used to do an exact bit-for-bit comparison of
117 /// two floating point values.
118 bool ConstantFPSDNode::isExactlyValue(const APFloat& V) const {
119   return getValueAPF().bitwiseIsEqual(V);
120 }
121 
122 bool ConstantFPSDNode::isValueValidForType(EVT VT,
123                                            const APFloat& Val) {
124   assert(VT.isFloatingPoint() && "Can only convert between FP types");
125 
126   // convert modifies in place, so make a copy.
127   APFloat Val2 = APFloat(Val);
128   bool losesInfo;
129   (void) Val2.convert(SelectionDAG::EVTToAPFloatSemantics(VT),
130                       APFloat::rmNearestTiesToEven,
131                       &losesInfo);
132   return !losesInfo;
133 }
134 
135 //===----------------------------------------------------------------------===//
136 //                              ISD Namespace
137 //===----------------------------------------------------------------------===//
138 
139 bool ISD::isConstantSplatVector(const SDNode *N, APInt &SplatVal) {
140   if (N->getOpcode() == ISD::SPLAT_VECTOR) {
141     unsigned EltSize =
142         N->getValueType(0).getVectorElementType().getSizeInBits();
143     if (auto *Op0 = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
144       SplatVal = Op0->getAPIntValue().trunc(EltSize);
145       return true;
146     }
147     if (auto *Op0 = dyn_cast<ConstantFPSDNode>(N->getOperand(0))) {
148       SplatVal = Op0->getValueAPF().bitcastToAPInt().trunc(EltSize);
149       return true;
150     }
151   }
152 
153   auto *BV = dyn_cast<BuildVectorSDNode>(N);
154   if (!BV)
155     return false;
156 
157   APInt SplatUndef;
158   unsigned SplatBitSize;
159   bool HasUndefs;
160   unsigned EltSize = N->getValueType(0).getVectorElementType().getSizeInBits();
161   return BV->isConstantSplat(SplatVal, SplatUndef, SplatBitSize, HasUndefs,
162                              EltSize) &&
163          EltSize == SplatBitSize;
164 }
165 
166 // FIXME: AllOnes and AllZeros duplicate a lot of code. Could these be
167 // specializations of the more general isConstantSplatVector()?
168 
169 bool ISD::isConstantSplatVectorAllOnes(const SDNode *N, bool BuildVectorOnly) {
170   // Look through a bit convert.
171   while (N->getOpcode() == ISD::BITCAST)
172     N = N->getOperand(0).getNode();
173 
174   if (!BuildVectorOnly && N->getOpcode() == ISD::SPLAT_VECTOR) {
175     APInt SplatVal;
176     return isConstantSplatVector(N, SplatVal) && SplatVal.isAllOnes();
177   }
178 
179   if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
180 
181   unsigned i = 0, e = N->getNumOperands();
182 
183   // Skip over all of the undef values.
184   while (i != e && N->getOperand(i).isUndef())
185     ++i;
186 
187   // Do not accept an all-undef vector.
188   if (i == e) return false;
189 
190   // Do not accept build_vectors that aren't all constants or which have non-~0
191   // elements. We have to be a bit careful here, as the type of the constant
192   // may not be the same as the type of the vector elements due to type
193   // legalization (the elements are promoted to a legal type for the target and
194   // a vector of a type may be legal when the base element type is not).
195   // We only want to check enough bits to cover the vector elements, because
196   // we care if the resultant vector is all ones, not whether the individual
197   // constants are.
198   SDValue NotZero = N->getOperand(i);
199   unsigned EltSize = N->getValueType(0).getScalarSizeInBits();
200   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(NotZero)) {
201     if (CN->getAPIntValue().countTrailingOnes() < EltSize)
202       return false;
203   } else if (ConstantFPSDNode *CFPN = dyn_cast<ConstantFPSDNode>(NotZero)) {
204     if (CFPN->getValueAPF().bitcastToAPInt().countTrailingOnes() < EltSize)
205       return false;
206   } else
207     return false;
208 
209   // Okay, we have at least one ~0 value, check to see if the rest match or are
210   // undefs. Even with the above element type twiddling, this should be OK, as
211   // the same type legalization should have applied to all the elements.
212   for (++i; i != e; ++i)
213     if (N->getOperand(i) != NotZero && !N->getOperand(i).isUndef())
214       return false;
215   return true;
216 }
217 
218 bool ISD::isConstantSplatVectorAllZeros(const SDNode *N, bool BuildVectorOnly) {
219   // Look through a bit convert.
220   while (N->getOpcode() == ISD::BITCAST)
221     N = N->getOperand(0).getNode();
222 
223   if (!BuildVectorOnly && N->getOpcode() == ISD::SPLAT_VECTOR) {
224     APInt SplatVal;
225     return isConstantSplatVector(N, SplatVal) && SplatVal.isZero();
226   }
227 
228   if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
229 
230   bool IsAllUndef = true;
231   for (const SDValue &Op : N->op_values()) {
232     if (Op.isUndef())
233       continue;
234     IsAllUndef = false;
235     // Do not accept build_vectors that aren't all constants or which have non-0
236     // elements. We have to be a bit careful here, as the type of the constant
237     // may not be the same as the type of the vector elements due to type
238     // legalization (the elements are promoted to a legal type for the target
239     // and a vector of a type may be legal when the base element type is not).
240     // We only want to check enough bits to cover the vector elements, because
241     // we care if the resultant vector is all zeros, not whether the individual
242     // constants are.
243     unsigned EltSize = N->getValueType(0).getScalarSizeInBits();
244     if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Op)) {
245       if (CN->getAPIntValue().countTrailingZeros() < EltSize)
246         return false;
247     } else if (ConstantFPSDNode *CFPN = dyn_cast<ConstantFPSDNode>(Op)) {
248       if (CFPN->getValueAPF().bitcastToAPInt().countTrailingZeros() < EltSize)
249         return false;
250     } else
251       return false;
252   }
253 
254   // Do not accept an all-undef vector.
255   if (IsAllUndef)
256     return false;
257   return true;
258 }
259 
260 bool ISD::isBuildVectorAllOnes(const SDNode *N) {
261   return isConstantSplatVectorAllOnes(N, /*BuildVectorOnly*/ true);
262 }
263 
264 bool ISD::isBuildVectorAllZeros(const SDNode *N) {
265   return isConstantSplatVectorAllZeros(N, /*BuildVectorOnly*/ true);
266 }
267 
268 bool ISD::isBuildVectorOfConstantSDNodes(const SDNode *N) {
269   if (N->getOpcode() != ISD::BUILD_VECTOR)
270     return false;
271 
272   for (const SDValue &Op : N->op_values()) {
273     if (Op.isUndef())
274       continue;
275     if (!isa<ConstantSDNode>(Op))
276       return false;
277   }
278   return true;
279 }
280 
281 bool ISD::isBuildVectorOfConstantFPSDNodes(const SDNode *N) {
282   if (N->getOpcode() != ISD::BUILD_VECTOR)
283     return false;
284 
285   for (const SDValue &Op : N->op_values()) {
286     if (Op.isUndef())
287       continue;
288     if (!isa<ConstantFPSDNode>(Op))
289       return false;
290   }
291   return true;
292 }
293 
294 bool ISD::allOperandsUndef(const SDNode *N) {
295   // Return false if the node has no operands.
296   // This is "logically inconsistent" with the definition of "all" but
297   // is probably the desired behavior.
298   if (N->getNumOperands() == 0)
299     return false;
300   return all_of(N->op_values(), [](SDValue Op) { return Op.isUndef(); });
301 }
302 
303 bool ISD::matchUnaryPredicate(SDValue Op,
304                               std::function<bool(ConstantSDNode *)> Match,
305                               bool AllowUndefs) {
306   // FIXME: Add support for scalar UNDEF cases?
307   if (auto *Cst = dyn_cast<ConstantSDNode>(Op))
308     return Match(Cst);
309 
310   // FIXME: Add support for vector UNDEF cases?
311   if (ISD::BUILD_VECTOR != Op.getOpcode() &&
312       ISD::SPLAT_VECTOR != Op.getOpcode())
313     return false;
314 
315   EVT SVT = Op.getValueType().getScalarType();
316   for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
317     if (AllowUndefs && Op.getOperand(i).isUndef()) {
318       if (!Match(nullptr))
319         return false;
320       continue;
321     }
322 
323     auto *Cst = dyn_cast<ConstantSDNode>(Op.getOperand(i));
324     if (!Cst || Cst->getValueType(0) != SVT || !Match(Cst))
325       return false;
326   }
327   return true;
328 }
329 
330 bool ISD::matchBinaryPredicate(
331     SDValue LHS, SDValue RHS,
332     std::function<bool(ConstantSDNode *, ConstantSDNode *)> Match,
333     bool AllowUndefs, bool AllowTypeMismatch) {
334   if (!AllowTypeMismatch && LHS.getValueType() != RHS.getValueType())
335     return false;
336 
337   // TODO: Add support for scalar UNDEF cases?
338   if (auto *LHSCst = dyn_cast<ConstantSDNode>(LHS))
339     if (auto *RHSCst = dyn_cast<ConstantSDNode>(RHS))
340       return Match(LHSCst, RHSCst);
341 
342   // TODO: Add support for vector UNDEF cases?
343   if (LHS.getOpcode() != RHS.getOpcode() ||
344       (LHS.getOpcode() != ISD::BUILD_VECTOR &&
345        LHS.getOpcode() != ISD::SPLAT_VECTOR))
346     return false;
347 
348   EVT SVT = LHS.getValueType().getScalarType();
349   for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
350     SDValue LHSOp = LHS.getOperand(i);
351     SDValue RHSOp = RHS.getOperand(i);
352     bool LHSUndef = AllowUndefs && LHSOp.isUndef();
353     bool RHSUndef = AllowUndefs && RHSOp.isUndef();
354     auto *LHSCst = dyn_cast<ConstantSDNode>(LHSOp);
355     auto *RHSCst = dyn_cast<ConstantSDNode>(RHSOp);
356     if ((!LHSCst && !LHSUndef) || (!RHSCst && !RHSUndef))
357       return false;
358     if (!AllowTypeMismatch && (LHSOp.getValueType() != SVT ||
359                                LHSOp.getValueType() != RHSOp.getValueType()))
360       return false;
361     if (!Match(LHSCst, RHSCst))
362       return false;
363   }
364   return true;
365 }
366 
367 ISD::NodeType ISD::getVecReduceBaseOpcode(unsigned VecReduceOpcode) {
368   switch (VecReduceOpcode) {
369   default:
370     llvm_unreachable("Expected VECREDUCE opcode");
371   case ISD::VECREDUCE_FADD:
372   case ISD::VECREDUCE_SEQ_FADD:
373   case ISD::VP_REDUCE_FADD:
374   case ISD::VP_REDUCE_SEQ_FADD:
375     return ISD::FADD;
376   case ISD::VECREDUCE_FMUL:
377   case ISD::VECREDUCE_SEQ_FMUL:
378   case ISD::VP_REDUCE_FMUL:
379   case ISD::VP_REDUCE_SEQ_FMUL:
380     return ISD::FMUL;
381   case ISD::VECREDUCE_ADD:
382   case ISD::VP_REDUCE_ADD:
383     return ISD::ADD;
384   case ISD::VECREDUCE_MUL:
385   case ISD::VP_REDUCE_MUL:
386     return ISD::MUL;
387   case ISD::VECREDUCE_AND:
388   case ISD::VP_REDUCE_AND:
389     return ISD::AND;
390   case ISD::VECREDUCE_OR:
391   case ISD::VP_REDUCE_OR:
392     return ISD::OR;
393   case ISD::VECREDUCE_XOR:
394   case ISD::VP_REDUCE_XOR:
395     return ISD::XOR;
396   case ISD::VECREDUCE_SMAX:
397   case ISD::VP_REDUCE_SMAX:
398     return ISD::SMAX;
399   case ISD::VECREDUCE_SMIN:
400   case ISD::VP_REDUCE_SMIN:
401     return ISD::SMIN;
402   case ISD::VECREDUCE_UMAX:
403   case ISD::VP_REDUCE_UMAX:
404     return ISD::UMAX;
405   case ISD::VECREDUCE_UMIN:
406   case ISD::VP_REDUCE_UMIN:
407     return ISD::UMIN;
408   case ISD::VECREDUCE_FMAX:
409   case ISD::VP_REDUCE_FMAX:
410     return ISD::FMAXNUM;
411   case ISD::VECREDUCE_FMIN:
412   case ISD::VP_REDUCE_FMIN:
413     return ISD::FMINNUM;
414   }
415 }
416 
417 bool ISD::isVPOpcode(unsigned Opcode) {
418   switch (Opcode) {
419   default:
420     return false;
421 #define BEGIN_REGISTER_VP_SDNODE(VPSD, ...)                                    \
422   case ISD::VPSD:                                                              \
423     return true;
424 #include "llvm/IR/VPIntrinsics.def"
425   }
426 }
427 
428 bool ISD::isVPBinaryOp(unsigned Opcode) {
429   switch (Opcode) {
430   default:
431     break;
432 #define BEGIN_REGISTER_VP_SDNODE(VPSD, ...) case ISD::VPSD:
433 #define VP_PROPERTY_BINARYOP return true;
434 #define END_REGISTER_VP_SDNODE(VPSD) break;
435 #include "llvm/IR/VPIntrinsics.def"
436   }
437   return false;
438 }
439 
440 bool ISD::isVPReduction(unsigned Opcode) {
441   switch (Opcode) {
442   default:
443     break;
444 #define BEGIN_REGISTER_VP_SDNODE(VPSD, ...) case ISD::VPSD:
445 #define VP_PROPERTY_REDUCTION(STARTPOS, ...) return true;
446 #define END_REGISTER_VP_SDNODE(VPSD) break;
447 #include "llvm/IR/VPIntrinsics.def"
448   }
449   return false;
450 }
451 
452 /// The operand position of the vector mask.
453 Optional<unsigned> ISD::getVPMaskIdx(unsigned Opcode) {
454   switch (Opcode) {
455   default:
456     return None;
457 #define BEGIN_REGISTER_VP_SDNODE(VPSD, LEGALPOS, TDNAME, MASKPOS, ...)         \
458   case ISD::VPSD:                                                              \
459     return MASKPOS;
460 #include "llvm/IR/VPIntrinsics.def"
461   }
462 }
463 
464 /// The operand position of the explicit vector length parameter.
465 Optional<unsigned> ISD::getVPExplicitVectorLengthIdx(unsigned Opcode) {
466   switch (Opcode) {
467   default:
468     return None;
469 #define BEGIN_REGISTER_VP_SDNODE(VPSD, LEGALPOS, TDNAME, MASKPOS, EVLPOS)      \
470   case ISD::VPSD:                                                              \
471     return EVLPOS;
472 #include "llvm/IR/VPIntrinsics.def"
473   }
474 }
475 
476 ISD::NodeType ISD::getExtForLoadExtType(bool IsFP, ISD::LoadExtType ExtType) {
477   switch (ExtType) {
478   case ISD::EXTLOAD:
479     return IsFP ? ISD::FP_EXTEND : ISD::ANY_EXTEND;
480   case ISD::SEXTLOAD:
481     return ISD::SIGN_EXTEND;
482   case ISD::ZEXTLOAD:
483     return ISD::ZERO_EXTEND;
484   default:
485     break;
486   }
487 
488   llvm_unreachable("Invalid LoadExtType");
489 }
490 
491 ISD::CondCode ISD::getSetCCSwappedOperands(ISD::CondCode Operation) {
492   // To perform this operation, we just need to swap the L and G bits of the
493   // operation.
494   unsigned OldL = (Operation >> 2) & 1;
495   unsigned OldG = (Operation >> 1) & 1;
496   return ISD::CondCode((Operation & ~6) |  // Keep the N, U, E bits
497                        (OldL << 1) |       // New G bit
498                        (OldG << 2));       // New L bit.
499 }
500 
501 static ISD::CondCode getSetCCInverseImpl(ISD::CondCode Op, bool isIntegerLike) {
502   unsigned Operation = Op;
503   if (isIntegerLike)
504     Operation ^= 7;   // Flip L, G, E bits, but not U.
505   else
506     Operation ^= 15;  // Flip all of the condition bits.
507 
508   if (Operation > ISD::SETTRUE2)
509     Operation &= ~8;  // Don't let N and U bits get set.
510 
511   return ISD::CondCode(Operation);
512 }
513 
514 ISD::CondCode ISD::getSetCCInverse(ISD::CondCode Op, EVT Type) {
515   return getSetCCInverseImpl(Op, Type.isInteger());
516 }
517 
518 ISD::CondCode ISD::GlobalISel::getSetCCInverse(ISD::CondCode Op,
519                                                bool isIntegerLike) {
520   return getSetCCInverseImpl(Op, isIntegerLike);
521 }
522 
523 /// For an integer comparison, return 1 if the comparison is a signed operation
524 /// and 2 if the result is an unsigned comparison. Return zero if the operation
525 /// does not depend on the sign of the input (setne and seteq).
526 static int isSignedOp(ISD::CondCode Opcode) {
527   switch (Opcode) {
528   default: llvm_unreachable("Illegal integer setcc operation!");
529   case ISD::SETEQ:
530   case ISD::SETNE: return 0;
531   case ISD::SETLT:
532   case ISD::SETLE:
533   case ISD::SETGT:
534   case ISD::SETGE: return 1;
535   case ISD::SETULT:
536   case ISD::SETULE:
537   case ISD::SETUGT:
538   case ISD::SETUGE: return 2;
539   }
540 }
541 
542 ISD::CondCode ISD::getSetCCOrOperation(ISD::CondCode Op1, ISD::CondCode Op2,
543                                        EVT Type) {
544   bool IsInteger = Type.isInteger();
545   if (IsInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
546     // Cannot fold a signed integer setcc with an unsigned integer setcc.
547     return ISD::SETCC_INVALID;
548 
549   unsigned Op = Op1 | Op2;  // Combine all of the condition bits.
550 
551   // If the N and U bits get set, then the resultant comparison DOES suddenly
552   // care about orderedness, and it is true when ordered.
553   if (Op > ISD::SETTRUE2)
554     Op &= ~16;     // Clear the U bit if the N bit is set.
555 
556   // Canonicalize illegal integer setcc's.
557   if (IsInteger && Op == ISD::SETUNE)  // e.g. SETUGT | SETULT
558     Op = ISD::SETNE;
559 
560   return ISD::CondCode(Op);
561 }
562 
563 ISD::CondCode ISD::getSetCCAndOperation(ISD::CondCode Op1, ISD::CondCode Op2,
564                                         EVT Type) {
565   bool IsInteger = Type.isInteger();
566   if (IsInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
567     // Cannot fold a signed setcc with an unsigned setcc.
568     return ISD::SETCC_INVALID;
569 
570   // Combine all of the condition bits.
571   ISD::CondCode Result = ISD::CondCode(Op1 & Op2);
572 
573   // Canonicalize illegal integer setcc's.
574   if (IsInteger) {
575     switch (Result) {
576     default: break;
577     case ISD::SETUO : Result = ISD::SETFALSE; break;  // SETUGT & SETULT
578     case ISD::SETOEQ:                                 // SETEQ  & SETU[LG]E
579     case ISD::SETUEQ: Result = ISD::SETEQ   ; break;  // SETUGE & SETULE
580     case ISD::SETOLT: Result = ISD::SETULT  ; break;  // SETULT & SETNE
581     case ISD::SETOGT: Result = ISD::SETUGT  ; break;  // SETUGT & SETNE
582     }
583   }
584 
585   return Result;
586 }
587 
588 //===----------------------------------------------------------------------===//
589 //                           SDNode Profile Support
590 //===----------------------------------------------------------------------===//
591 
592 /// AddNodeIDOpcode - Add the node opcode to the NodeID data.
593 static void AddNodeIDOpcode(FoldingSetNodeID &ID, unsigned OpC)  {
594   ID.AddInteger(OpC);
595 }
596 
597 /// AddNodeIDValueTypes - Value type lists are intern'd so we can represent them
598 /// solely with their pointer.
599 static void AddNodeIDValueTypes(FoldingSetNodeID &ID, SDVTList VTList) {
600   ID.AddPointer(VTList.VTs);
601 }
602 
603 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data.
604 static void AddNodeIDOperands(FoldingSetNodeID &ID,
605                               ArrayRef<SDValue> Ops) {
606   for (auto& Op : Ops) {
607     ID.AddPointer(Op.getNode());
608     ID.AddInteger(Op.getResNo());
609   }
610 }
611 
612 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data.
613 static void AddNodeIDOperands(FoldingSetNodeID &ID,
614                               ArrayRef<SDUse> Ops) {
615   for (auto& Op : Ops) {
616     ID.AddPointer(Op.getNode());
617     ID.AddInteger(Op.getResNo());
618   }
619 }
620 
621 static void AddNodeIDNode(FoldingSetNodeID &ID, unsigned short OpC,
622                           SDVTList VTList, ArrayRef<SDValue> OpList) {
623   AddNodeIDOpcode(ID, OpC);
624   AddNodeIDValueTypes(ID, VTList);
625   AddNodeIDOperands(ID, OpList);
626 }
627 
628 /// If this is an SDNode with special info, add this info to the NodeID data.
629 static void AddNodeIDCustom(FoldingSetNodeID &ID, const SDNode *N) {
630   switch (N->getOpcode()) {
631   case ISD::TargetExternalSymbol:
632   case ISD::ExternalSymbol:
633   case ISD::MCSymbol:
634     llvm_unreachable("Should only be used on nodes with operands");
635   default: break;  // Normal nodes don't need extra info.
636   case ISD::TargetConstant:
637   case ISD::Constant: {
638     const ConstantSDNode *C = cast<ConstantSDNode>(N);
639     ID.AddPointer(C->getConstantIntValue());
640     ID.AddBoolean(C->isOpaque());
641     break;
642   }
643   case ISD::TargetConstantFP:
644   case ISD::ConstantFP:
645     ID.AddPointer(cast<ConstantFPSDNode>(N)->getConstantFPValue());
646     break;
647   case ISD::TargetGlobalAddress:
648   case ISD::GlobalAddress:
649   case ISD::TargetGlobalTLSAddress:
650   case ISD::GlobalTLSAddress: {
651     const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(N);
652     ID.AddPointer(GA->getGlobal());
653     ID.AddInteger(GA->getOffset());
654     ID.AddInteger(GA->getTargetFlags());
655     break;
656   }
657   case ISD::BasicBlock:
658     ID.AddPointer(cast<BasicBlockSDNode>(N)->getBasicBlock());
659     break;
660   case ISD::Register:
661     ID.AddInteger(cast<RegisterSDNode>(N)->getReg());
662     break;
663   case ISD::RegisterMask:
664     ID.AddPointer(cast<RegisterMaskSDNode>(N)->getRegMask());
665     break;
666   case ISD::SRCVALUE:
667     ID.AddPointer(cast<SrcValueSDNode>(N)->getValue());
668     break;
669   case ISD::FrameIndex:
670   case ISD::TargetFrameIndex:
671     ID.AddInteger(cast<FrameIndexSDNode>(N)->getIndex());
672     break;
673   case ISD::LIFETIME_START:
674   case ISD::LIFETIME_END:
675     if (cast<LifetimeSDNode>(N)->hasOffset()) {
676       ID.AddInteger(cast<LifetimeSDNode>(N)->getSize());
677       ID.AddInteger(cast<LifetimeSDNode>(N)->getOffset());
678     }
679     break;
680   case ISD::PSEUDO_PROBE:
681     ID.AddInteger(cast<PseudoProbeSDNode>(N)->getGuid());
682     ID.AddInteger(cast<PseudoProbeSDNode>(N)->getIndex());
683     ID.AddInteger(cast<PseudoProbeSDNode>(N)->getAttributes());
684     break;
685   case ISD::JumpTable:
686   case ISD::TargetJumpTable:
687     ID.AddInteger(cast<JumpTableSDNode>(N)->getIndex());
688     ID.AddInteger(cast<JumpTableSDNode>(N)->getTargetFlags());
689     break;
690   case ISD::ConstantPool:
691   case ISD::TargetConstantPool: {
692     const ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(N);
693     ID.AddInteger(CP->getAlign().value());
694     ID.AddInteger(CP->getOffset());
695     if (CP->isMachineConstantPoolEntry())
696       CP->getMachineCPVal()->addSelectionDAGCSEId(ID);
697     else
698       ID.AddPointer(CP->getConstVal());
699     ID.AddInteger(CP->getTargetFlags());
700     break;
701   }
702   case ISD::TargetIndex: {
703     const TargetIndexSDNode *TI = cast<TargetIndexSDNode>(N);
704     ID.AddInteger(TI->getIndex());
705     ID.AddInteger(TI->getOffset());
706     ID.AddInteger(TI->getTargetFlags());
707     break;
708   }
709   case ISD::LOAD: {
710     const LoadSDNode *LD = cast<LoadSDNode>(N);
711     ID.AddInteger(LD->getMemoryVT().getRawBits());
712     ID.AddInteger(LD->getRawSubclassData());
713     ID.AddInteger(LD->getPointerInfo().getAddrSpace());
714     ID.AddInteger(LD->getMemOperand()->getFlags());
715     break;
716   }
717   case ISD::STORE: {
718     const StoreSDNode *ST = cast<StoreSDNode>(N);
719     ID.AddInteger(ST->getMemoryVT().getRawBits());
720     ID.AddInteger(ST->getRawSubclassData());
721     ID.AddInteger(ST->getPointerInfo().getAddrSpace());
722     ID.AddInteger(ST->getMemOperand()->getFlags());
723     break;
724   }
725   case ISD::VP_LOAD: {
726     const VPLoadSDNode *ELD = cast<VPLoadSDNode>(N);
727     ID.AddInteger(ELD->getMemoryVT().getRawBits());
728     ID.AddInteger(ELD->getRawSubclassData());
729     ID.AddInteger(ELD->getPointerInfo().getAddrSpace());
730     ID.AddInteger(ELD->getMemOperand()->getFlags());
731     break;
732   }
733   case ISD::VP_STORE: {
734     const VPStoreSDNode *EST = cast<VPStoreSDNode>(N);
735     ID.AddInteger(EST->getMemoryVT().getRawBits());
736     ID.AddInteger(EST->getRawSubclassData());
737     ID.AddInteger(EST->getPointerInfo().getAddrSpace());
738     ID.AddInteger(EST->getMemOperand()->getFlags());
739     break;
740   }
741   case ISD::EXPERIMENTAL_VP_STRIDED_LOAD: {
742     const VPStridedLoadSDNode *SLD = cast<VPStridedLoadSDNode>(N);
743     ID.AddInteger(SLD->getMemoryVT().getRawBits());
744     ID.AddInteger(SLD->getRawSubclassData());
745     ID.AddInteger(SLD->getPointerInfo().getAddrSpace());
746     break;
747   }
748   case ISD::EXPERIMENTAL_VP_STRIDED_STORE: {
749     const VPStridedStoreSDNode *SST = cast<VPStridedStoreSDNode>(N);
750     ID.AddInteger(SST->getMemoryVT().getRawBits());
751     ID.AddInteger(SST->getRawSubclassData());
752     ID.AddInteger(SST->getPointerInfo().getAddrSpace());
753     break;
754   }
755   case ISD::VP_GATHER: {
756     const VPGatherSDNode *EG = cast<VPGatherSDNode>(N);
757     ID.AddInteger(EG->getMemoryVT().getRawBits());
758     ID.AddInteger(EG->getRawSubclassData());
759     ID.AddInteger(EG->getPointerInfo().getAddrSpace());
760     ID.AddInteger(EG->getMemOperand()->getFlags());
761     break;
762   }
763   case ISD::VP_SCATTER: {
764     const VPScatterSDNode *ES = cast<VPScatterSDNode>(N);
765     ID.AddInteger(ES->getMemoryVT().getRawBits());
766     ID.AddInteger(ES->getRawSubclassData());
767     ID.AddInteger(ES->getPointerInfo().getAddrSpace());
768     ID.AddInteger(ES->getMemOperand()->getFlags());
769     break;
770   }
771   case ISD::MLOAD: {
772     const MaskedLoadSDNode *MLD = cast<MaskedLoadSDNode>(N);
773     ID.AddInteger(MLD->getMemoryVT().getRawBits());
774     ID.AddInteger(MLD->getRawSubclassData());
775     ID.AddInteger(MLD->getPointerInfo().getAddrSpace());
776     ID.AddInteger(MLD->getMemOperand()->getFlags());
777     break;
778   }
779   case ISD::MSTORE: {
780     const MaskedStoreSDNode *MST = cast<MaskedStoreSDNode>(N);
781     ID.AddInteger(MST->getMemoryVT().getRawBits());
782     ID.AddInteger(MST->getRawSubclassData());
783     ID.AddInteger(MST->getPointerInfo().getAddrSpace());
784     ID.AddInteger(MST->getMemOperand()->getFlags());
785     break;
786   }
787   case ISD::MGATHER: {
788     const MaskedGatherSDNode *MG = cast<MaskedGatherSDNode>(N);
789     ID.AddInteger(MG->getMemoryVT().getRawBits());
790     ID.AddInteger(MG->getRawSubclassData());
791     ID.AddInteger(MG->getPointerInfo().getAddrSpace());
792     ID.AddInteger(MG->getMemOperand()->getFlags());
793     break;
794   }
795   case ISD::MSCATTER: {
796     const MaskedScatterSDNode *MS = cast<MaskedScatterSDNode>(N);
797     ID.AddInteger(MS->getMemoryVT().getRawBits());
798     ID.AddInteger(MS->getRawSubclassData());
799     ID.AddInteger(MS->getPointerInfo().getAddrSpace());
800     ID.AddInteger(MS->getMemOperand()->getFlags());
801     break;
802   }
803   case ISD::ATOMIC_CMP_SWAP:
804   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
805   case ISD::ATOMIC_SWAP:
806   case ISD::ATOMIC_LOAD_ADD:
807   case ISD::ATOMIC_LOAD_SUB:
808   case ISD::ATOMIC_LOAD_AND:
809   case ISD::ATOMIC_LOAD_CLR:
810   case ISD::ATOMIC_LOAD_OR:
811   case ISD::ATOMIC_LOAD_XOR:
812   case ISD::ATOMIC_LOAD_NAND:
813   case ISD::ATOMIC_LOAD_MIN:
814   case ISD::ATOMIC_LOAD_MAX:
815   case ISD::ATOMIC_LOAD_UMIN:
816   case ISD::ATOMIC_LOAD_UMAX:
817   case ISD::ATOMIC_LOAD:
818   case ISD::ATOMIC_STORE: {
819     const AtomicSDNode *AT = cast<AtomicSDNode>(N);
820     ID.AddInteger(AT->getMemoryVT().getRawBits());
821     ID.AddInteger(AT->getRawSubclassData());
822     ID.AddInteger(AT->getPointerInfo().getAddrSpace());
823     ID.AddInteger(AT->getMemOperand()->getFlags());
824     break;
825   }
826   case ISD::PREFETCH: {
827     const MemSDNode *PF = cast<MemSDNode>(N);
828     ID.AddInteger(PF->getPointerInfo().getAddrSpace());
829     ID.AddInteger(PF->getMemOperand()->getFlags());
830     break;
831   }
832   case ISD::VECTOR_SHUFFLE: {
833     const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
834     for (unsigned i = 0, e = N->getValueType(0).getVectorNumElements();
835          i != e; ++i)
836       ID.AddInteger(SVN->getMaskElt(i));
837     break;
838   }
839   case ISD::TargetBlockAddress:
840   case ISD::BlockAddress: {
841     const BlockAddressSDNode *BA = cast<BlockAddressSDNode>(N);
842     ID.AddPointer(BA->getBlockAddress());
843     ID.AddInteger(BA->getOffset());
844     ID.AddInteger(BA->getTargetFlags());
845     break;
846   }
847   case ISD::AssertAlign:
848     ID.AddInteger(cast<AssertAlignSDNode>(N)->getAlign().value());
849     break;
850   } // end switch (N->getOpcode())
851 
852   // Target specific memory nodes could also have address spaces and flags
853   // to check.
854   if (N->isTargetMemoryOpcode()) {
855     const MemSDNode *MN = cast<MemSDNode>(N);
856     ID.AddInteger(MN->getPointerInfo().getAddrSpace());
857     ID.AddInteger(MN->getMemOperand()->getFlags());
858   }
859 }
860 
861 /// AddNodeIDNode - Generic routine for adding a nodes info to the NodeID
862 /// data.
863 static void AddNodeIDNode(FoldingSetNodeID &ID, const SDNode *N) {
864   AddNodeIDOpcode(ID, N->getOpcode());
865   // Add the return value info.
866   AddNodeIDValueTypes(ID, N->getVTList());
867   // Add the operand info.
868   AddNodeIDOperands(ID, N->ops());
869 
870   // Handle SDNode leafs with special info.
871   AddNodeIDCustom(ID, N);
872 }
873 
874 //===----------------------------------------------------------------------===//
875 //                              SelectionDAG Class
876 //===----------------------------------------------------------------------===//
877 
878 /// doNotCSE - Return true if CSE should not be performed for this node.
879 static bool doNotCSE(SDNode *N) {
880   if (N->getValueType(0) == MVT::Glue)
881     return true; // Never CSE anything that produces a flag.
882 
883   switch (N->getOpcode()) {
884   default: break;
885   case ISD::HANDLENODE:
886   case ISD::EH_LABEL:
887     return true;   // Never CSE these nodes.
888   }
889 
890   // Check that remaining values produced are not flags.
891   for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
892     if (N->getValueType(i) == MVT::Glue)
893       return true; // Never CSE anything that produces a flag.
894 
895   return false;
896 }
897 
898 /// RemoveDeadNodes - This method deletes all unreachable nodes in the
899 /// SelectionDAG.
900 void SelectionDAG::RemoveDeadNodes() {
901   // Create a dummy node (which is not added to allnodes), that adds a reference
902   // to the root node, preventing it from being deleted.
903   HandleSDNode Dummy(getRoot());
904 
905   SmallVector<SDNode*, 128> DeadNodes;
906 
907   // Add all obviously-dead nodes to the DeadNodes worklist.
908   for (SDNode &Node : allnodes())
909     if (Node.use_empty())
910       DeadNodes.push_back(&Node);
911 
912   RemoveDeadNodes(DeadNodes);
913 
914   // If the root changed (e.g. it was a dead load, update the root).
915   setRoot(Dummy.getValue());
916 }
917 
918 /// RemoveDeadNodes - This method deletes the unreachable nodes in the
919 /// given list, and any nodes that become unreachable as a result.
920 void SelectionDAG::RemoveDeadNodes(SmallVectorImpl<SDNode *> &DeadNodes) {
921 
922   // Process the worklist, deleting the nodes and adding their uses to the
923   // worklist.
924   while (!DeadNodes.empty()) {
925     SDNode *N = DeadNodes.pop_back_val();
926     // Skip to next node if we've already managed to delete the node. This could
927     // happen if replacing a node causes a node previously added to the node to
928     // be deleted.
929     if (N->getOpcode() == ISD::DELETED_NODE)
930       continue;
931 
932     for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
933       DUL->NodeDeleted(N, nullptr);
934 
935     // Take the node out of the appropriate CSE map.
936     RemoveNodeFromCSEMaps(N);
937 
938     // Next, brutally remove the operand list.  This is safe to do, as there are
939     // no cycles in the graph.
940     for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) {
941       SDUse &Use = *I++;
942       SDNode *Operand = Use.getNode();
943       Use.set(SDValue());
944 
945       // Now that we removed this operand, see if there are no uses of it left.
946       if (Operand->use_empty())
947         DeadNodes.push_back(Operand);
948     }
949 
950     DeallocateNode(N);
951   }
952 }
953 
954 void SelectionDAG::RemoveDeadNode(SDNode *N){
955   SmallVector<SDNode*, 16> DeadNodes(1, N);
956 
957   // Create a dummy node that adds a reference to the root node, preventing
958   // it from being deleted.  (This matters if the root is an operand of the
959   // dead node.)
960   HandleSDNode Dummy(getRoot());
961 
962   RemoveDeadNodes(DeadNodes);
963 }
964 
965 void SelectionDAG::DeleteNode(SDNode *N) {
966   // First take this out of the appropriate CSE map.
967   RemoveNodeFromCSEMaps(N);
968 
969   // Finally, remove uses due to operands of this node, remove from the
970   // AllNodes list, and delete the node.
971   DeleteNodeNotInCSEMaps(N);
972 }
973 
974 void SelectionDAG::DeleteNodeNotInCSEMaps(SDNode *N) {
975   assert(N->getIterator() != AllNodes.begin() &&
976          "Cannot delete the entry node!");
977   assert(N->use_empty() && "Cannot delete a node that is not dead!");
978 
979   // Drop all of the operands and decrement used node's use counts.
980   N->DropOperands();
981 
982   DeallocateNode(N);
983 }
984 
985 void SDDbgInfo::add(SDDbgValue *V, bool isParameter) {
986   assert(!(V->isVariadic() && isParameter));
987   if (isParameter)
988     ByvalParmDbgValues.push_back(V);
989   else
990     DbgValues.push_back(V);
991   for (const SDNode *Node : V->getSDNodes())
992     if (Node)
993       DbgValMap[Node].push_back(V);
994 }
995 
996 void SDDbgInfo::erase(const SDNode *Node) {
997   DbgValMapType::iterator I = DbgValMap.find(Node);
998   if (I == DbgValMap.end())
999     return;
1000   for (auto &Val: I->second)
1001     Val->setIsInvalidated();
1002   DbgValMap.erase(I);
1003 }
1004 
1005 void SelectionDAG::DeallocateNode(SDNode *N) {
1006   // If we have operands, deallocate them.
1007   removeOperands(N);
1008 
1009   NodeAllocator.Deallocate(AllNodes.remove(N));
1010 
1011   // Set the opcode to DELETED_NODE to help catch bugs when node
1012   // memory is reallocated.
1013   // FIXME: There are places in SDag that have grown a dependency on the opcode
1014   // value in the released node.
1015   __asan_unpoison_memory_region(&N->NodeType, sizeof(N->NodeType));
1016   N->NodeType = ISD::DELETED_NODE;
1017 
1018   // If any of the SDDbgValue nodes refer to this SDNode, invalidate
1019   // them and forget about that node.
1020   DbgInfo->erase(N);
1021 }
1022 
1023 #ifndef NDEBUG
1024 /// VerifySDNode - Check the given SDNode.  Aborts if it is invalid.
1025 static void VerifySDNode(SDNode *N) {
1026   switch (N->getOpcode()) {
1027   default:
1028     break;
1029   case ISD::BUILD_PAIR: {
1030     EVT VT = N->getValueType(0);
1031     assert(N->getNumValues() == 1 && "Too many results!");
1032     assert(!VT.isVector() && (VT.isInteger() || VT.isFloatingPoint()) &&
1033            "Wrong return type!");
1034     assert(N->getNumOperands() == 2 && "Wrong number of operands!");
1035     assert(N->getOperand(0).getValueType() == N->getOperand(1).getValueType() &&
1036            "Mismatched operand types!");
1037     assert(N->getOperand(0).getValueType().isInteger() == VT.isInteger() &&
1038            "Wrong operand type!");
1039     assert(VT.getSizeInBits() == 2 * N->getOperand(0).getValueSizeInBits() &&
1040            "Wrong return type size");
1041     break;
1042   }
1043   case ISD::BUILD_VECTOR: {
1044     assert(N->getNumValues() == 1 && "Too many results!");
1045     assert(N->getValueType(0).isVector() && "Wrong return type!");
1046     assert(N->getNumOperands() == N->getValueType(0).getVectorNumElements() &&
1047            "Wrong number of operands!");
1048     EVT EltVT = N->getValueType(0).getVectorElementType();
1049     for (const SDUse &Op : N->ops()) {
1050       assert((Op.getValueType() == EltVT ||
1051               (EltVT.isInteger() && Op.getValueType().isInteger() &&
1052                EltVT.bitsLE(Op.getValueType()))) &&
1053              "Wrong operand type!");
1054       assert(Op.getValueType() == N->getOperand(0).getValueType() &&
1055              "Operands must all have the same type");
1056     }
1057     break;
1058   }
1059   }
1060 }
1061 #endif // NDEBUG
1062 
1063 /// Insert a newly allocated node into the DAG.
1064 ///
1065 /// Handles insertion into the all nodes list and CSE map, as well as
1066 /// verification and other common operations when a new node is allocated.
1067 void SelectionDAG::InsertNode(SDNode *N) {
1068   AllNodes.push_back(N);
1069 #ifndef NDEBUG
1070   N->PersistentId = NextPersistentId++;
1071   VerifySDNode(N);
1072 #endif
1073   for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
1074     DUL->NodeInserted(N);
1075 }
1076 
1077 /// RemoveNodeFromCSEMaps - Take the specified node out of the CSE map that
1078 /// correspond to it.  This is useful when we're about to delete or repurpose
1079 /// the node.  We don't want future request for structurally identical nodes
1080 /// to return N anymore.
1081 bool SelectionDAG::RemoveNodeFromCSEMaps(SDNode *N) {
1082   bool Erased = false;
1083   switch (N->getOpcode()) {
1084   case ISD::HANDLENODE: return false;  // noop.
1085   case ISD::CONDCODE:
1086     assert(CondCodeNodes[cast<CondCodeSDNode>(N)->get()] &&
1087            "Cond code doesn't exist!");
1088     Erased = CondCodeNodes[cast<CondCodeSDNode>(N)->get()] != nullptr;
1089     CondCodeNodes[cast<CondCodeSDNode>(N)->get()] = nullptr;
1090     break;
1091   case ISD::ExternalSymbol:
1092     Erased = ExternalSymbols.erase(cast<ExternalSymbolSDNode>(N)->getSymbol());
1093     break;
1094   case ISD::TargetExternalSymbol: {
1095     ExternalSymbolSDNode *ESN = cast<ExternalSymbolSDNode>(N);
1096     Erased = TargetExternalSymbols.erase(std::pair<std::string, unsigned>(
1097         ESN->getSymbol(), ESN->getTargetFlags()));
1098     break;
1099   }
1100   case ISD::MCSymbol: {
1101     auto *MCSN = cast<MCSymbolSDNode>(N);
1102     Erased = MCSymbols.erase(MCSN->getMCSymbol());
1103     break;
1104   }
1105   case ISD::VALUETYPE: {
1106     EVT VT = cast<VTSDNode>(N)->getVT();
1107     if (VT.isExtended()) {
1108       Erased = ExtendedValueTypeNodes.erase(VT);
1109     } else {
1110       Erased = ValueTypeNodes[VT.getSimpleVT().SimpleTy] != nullptr;
1111       ValueTypeNodes[VT.getSimpleVT().SimpleTy] = nullptr;
1112     }
1113     break;
1114   }
1115   default:
1116     // Remove it from the CSE Map.
1117     assert(N->getOpcode() != ISD::DELETED_NODE && "DELETED_NODE in CSEMap!");
1118     assert(N->getOpcode() != ISD::EntryToken && "EntryToken in CSEMap!");
1119     Erased = CSEMap.RemoveNode(N);
1120     break;
1121   }
1122 #ifndef NDEBUG
1123   // Verify that the node was actually in one of the CSE maps, unless it has a
1124   // flag result (which cannot be CSE'd) or is one of the special cases that are
1125   // not subject to CSE.
1126   if (!Erased && N->getValueType(N->getNumValues()-1) != MVT::Glue &&
1127       !N->isMachineOpcode() && !doNotCSE(N)) {
1128     N->dump(this);
1129     dbgs() << "\n";
1130     llvm_unreachable("Node is not in map!");
1131   }
1132 #endif
1133   return Erased;
1134 }
1135 
1136 /// AddModifiedNodeToCSEMaps - The specified node has been removed from the CSE
1137 /// maps and modified in place. Add it back to the CSE maps, unless an identical
1138 /// node already exists, in which case transfer all its users to the existing
1139 /// node. This transfer can potentially trigger recursive merging.
1140 void
1141 SelectionDAG::AddModifiedNodeToCSEMaps(SDNode *N) {
1142   // For node types that aren't CSE'd, just act as if no identical node
1143   // already exists.
1144   if (!doNotCSE(N)) {
1145     SDNode *Existing = CSEMap.GetOrInsertNode(N);
1146     if (Existing != N) {
1147       // If there was already an existing matching node, use ReplaceAllUsesWith
1148       // to replace the dead one with the existing one.  This can cause
1149       // recursive merging of other unrelated nodes down the line.
1150       ReplaceAllUsesWith(N, Existing);
1151 
1152       // N is now dead. Inform the listeners and delete it.
1153       for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
1154         DUL->NodeDeleted(N, Existing);
1155       DeleteNodeNotInCSEMaps(N);
1156       return;
1157     }
1158   }
1159 
1160   // If the node doesn't already exist, we updated it.  Inform listeners.
1161   for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
1162     DUL->NodeUpdated(N);
1163 }
1164 
1165 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
1166 /// were replaced with those specified.  If this node is never memoized,
1167 /// return null, otherwise return a pointer to the slot it would take.  If a
1168 /// node already exists with these operands, the slot will be non-null.
1169 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, SDValue Op,
1170                                            void *&InsertPos) {
1171   if (doNotCSE(N))
1172     return nullptr;
1173 
1174   SDValue Ops[] = { Op };
1175   FoldingSetNodeID ID;
1176   AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops);
1177   AddNodeIDCustom(ID, N);
1178   SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos);
1179   if (Node)
1180     Node->intersectFlagsWith(N->getFlags());
1181   return Node;
1182 }
1183 
1184 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
1185 /// were replaced with those specified.  If this node is never memoized,
1186 /// return null, otherwise return a pointer to the slot it would take.  If a
1187 /// node already exists with these operands, the slot will be non-null.
1188 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N,
1189                                            SDValue Op1, SDValue Op2,
1190                                            void *&InsertPos) {
1191   if (doNotCSE(N))
1192     return nullptr;
1193 
1194   SDValue Ops[] = { Op1, Op2 };
1195   FoldingSetNodeID ID;
1196   AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops);
1197   AddNodeIDCustom(ID, N);
1198   SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos);
1199   if (Node)
1200     Node->intersectFlagsWith(N->getFlags());
1201   return Node;
1202 }
1203 
1204 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
1205 /// were replaced with those specified.  If this node is never memoized,
1206 /// return null, otherwise return a pointer to the slot it would take.  If a
1207 /// node already exists with these operands, the slot will be non-null.
1208 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, ArrayRef<SDValue> Ops,
1209                                            void *&InsertPos) {
1210   if (doNotCSE(N))
1211     return nullptr;
1212 
1213   FoldingSetNodeID ID;
1214   AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops);
1215   AddNodeIDCustom(ID, N);
1216   SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos);
1217   if (Node)
1218     Node->intersectFlagsWith(N->getFlags());
1219   return Node;
1220 }
1221 
1222 Align SelectionDAG::getEVTAlign(EVT VT) const {
1223   Type *Ty = VT == MVT::iPTR ?
1224                    PointerType::get(Type::getInt8Ty(*getContext()), 0) :
1225                    VT.getTypeForEVT(*getContext());
1226 
1227   return getDataLayout().getABITypeAlign(Ty);
1228 }
1229 
1230 // EntryNode could meaningfully have debug info if we can find it...
1231 SelectionDAG::SelectionDAG(const TargetMachine &tm, CodeGenOpt::Level OL)
1232     : TM(tm), OptLevel(OL),
1233       EntryNode(ISD::EntryToken, 0, DebugLoc(), getVTList(MVT::Other)),
1234       Root(getEntryNode()) {
1235   InsertNode(&EntryNode);
1236   DbgInfo = new SDDbgInfo();
1237 }
1238 
1239 void SelectionDAG::init(MachineFunction &NewMF,
1240                         OptimizationRemarkEmitter &NewORE,
1241                         Pass *PassPtr, const TargetLibraryInfo *LibraryInfo,
1242                         LegacyDivergenceAnalysis * Divergence,
1243                         ProfileSummaryInfo *PSIin,
1244                         BlockFrequencyInfo *BFIin) {
1245   MF = &NewMF;
1246   SDAGISelPass = PassPtr;
1247   ORE = &NewORE;
1248   TLI = getSubtarget().getTargetLowering();
1249   TSI = getSubtarget().getSelectionDAGInfo();
1250   LibInfo = LibraryInfo;
1251   Context = &MF->getFunction().getContext();
1252   DA = Divergence;
1253   PSI = PSIin;
1254   BFI = BFIin;
1255 }
1256 
1257 SelectionDAG::~SelectionDAG() {
1258   assert(!UpdateListeners && "Dangling registered DAGUpdateListeners");
1259   allnodes_clear();
1260   OperandRecycler.clear(OperandAllocator);
1261   delete DbgInfo;
1262 }
1263 
1264 bool SelectionDAG::shouldOptForSize() const {
1265   return MF->getFunction().hasOptSize() ||
1266       llvm::shouldOptimizeForSize(FLI->MBB->getBasicBlock(), PSI, BFI);
1267 }
1268 
1269 void SelectionDAG::allnodes_clear() {
1270   assert(&*AllNodes.begin() == &EntryNode);
1271   AllNodes.remove(AllNodes.begin());
1272   while (!AllNodes.empty())
1273     DeallocateNode(&AllNodes.front());
1274 #ifndef NDEBUG
1275   NextPersistentId = 0;
1276 #endif
1277 }
1278 
1279 SDNode *SelectionDAG::FindNodeOrInsertPos(const FoldingSetNodeID &ID,
1280                                           void *&InsertPos) {
1281   SDNode *N = CSEMap.FindNodeOrInsertPos(ID, InsertPos);
1282   if (N) {
1283     switch (N->getOpcode()) {
1284     default: break;
1285     case ISD::Constant:
1286     case ISD::ConstantFP:
1287       llvm_unreachable("Querying for Constant and ConstantFP nodes requires "
1288                        "debug location.  Use another overload.");
1289     }
1290   }
1291   return N;
1292 }
1293 
1294 SDNode *SelectionDAG::FindNodeOrInsertPos(const FoldingSetNodeID &ID,
1295                                           const SDLoc &DL, void *&InsertPos) {
1296   SDNode *N = CSEMap.FindNodeOrInsertPos(ID, InsertPos);
1297   if (N) {
1298     switch (N->getOpcode()) {
1299     case ISD::Constant:
1300     case ISD::ConstantFP:
1301       // Erase debug location from the node if the node is used at several
1302       // different places. Do not propagate one location to all uses as it
1303       // will cause a worse single stepping debugging experience.
1304       if (N->getDebugLoc() != DL.getDebugLoc())
1305         N->setDebugLoc(DebugLoc());
1306       break;
1307     default:
1308       // When the node's point of use is located earlier in the instruction
1309       // sequence than its prior point of use, update its debug info to the
1310       // earlier location.
1311       if (DL.getIROrder() && DL.getIROrder() < N->getIROrder())
1312         N->setDebugLoc(DL.getDebugLoc());
1313       break;
1314     }
1315   }
1316   return N;
1317 }
1318 
1319 void SelectionDAG::clear() {
1320   allnodes_clear();
1321   OperandRecycler.clear(OperandAllocator);
1322   OperandAllocator.Reset();
1323   CSEMap.clear();
1324 
1325   ExtendedValueTypeNodes.clear();
1326   ExternalSymbols.clear();
1327   TargetExternalSymbols.clear();
1328   MCSymbols.clear();
1329   SDCallSiteDbgInfo.clear();
1330   std::fill(CondCodeNodes.begin(), CondCodeNodes.end(),
1331             static_cast<CondCodeSDNode*>(nullptr));
1332   std::fill(ValueTypeNodes.begin(), ValueTypeNodes.end(),
1333             static_cast<SDNode*>(nullptr));
1334 
1335   EntryNode.UseList = nullptr;
1336   InsertNode(&EntryNode);
1337   Root = getEntryNode();
1338   DbgInfo->clear();
1339 }
1340 
1341 SDValue SelectionDAG::getFPExtendOrRound(SDValue Op, const SDLoc &DL, EVT VT) {
1342   return VT.bitsGT(Op.getValueType())
1343              ? getNode(ISD::FP_EXTEND, DL, VT, Op)
1344              : getNode(ISD::FP_ROUND, DL, VT, Op, getIntPtrConstant(0, DL));
1345 }
1346 
1347 std::pair<SDValue, SDValue>
1348 SelectionDAG::getStrictFPExtendOrRound(SDValue Op, SDValue Chain,
1349                                        const SDLoc &DL, EVT VT) {
1350   assert(!VT.bitsEq(Op.getValueType()) &&
1351          "Strict no-op FP extend/round not allowed.");
1352   SDValue Res =
1353       VT.bitsGT(Op.getValueType())
1354           ? getNode(ISD::STRICT_FP_EXTEND, DL, {VT, MVT::Other}, {Chain, Op})
1355           : getNode(ISD::STRICT_FP_ROUND, DL, {VT, MVT::Other},
1356                     {Chain, Op, getIntPtrConstant(0, DL)});
1357 
1358   return std::pair<SDValue, SDValue>(Res, SDValue(Res.getNode(), 1));
1359 }
1360 
1361 SDValue SelectionDAG::getAnyExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
1362   return VT.bitsGT(Op.getValueType()) ?
1363     getNode(ISD::ANY_EXTEND, DL, VT, Op) :
1364     getNode(ISD::TRUNCATE, DL, VT, Op);
1365 }
1366 
1367 SDValue SelectionDAG::getSExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
1368   return VT.bitsGT(Op.getValueType()) ?
1369     getNode(ISD::SIGN_EXTEND, DL, VT, Op) :
1370     getNode(ISD::TRUNCATE, DL, VT, Op);
1371 }
1372 
1373 SDValue SelectionDAG::getZExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
1374   return VT.bitsGT(Op.getValueType()) ?
1375     getNode(ISD::ZERO_EXTEND, DL, VT, Op) :
1376     getNode(ISD::TRUNCATE, DL, VT, Op);
1377 }
1378 
1379 SDValue SelectionDAG::getBoolExtOrTrunc(SDValue Op, const SDLoc &SL, EVT VT,
1380                                         EVT OpVT) {
1381   if (VT.bitsLE(Op.getValueType()))
1382     return getNode(ISD::TRUNCATE, SL, VT, Op);
1383 
1384   TargetLowering::BooleanContent BType = TLI->getBooleanContents(OpVT);
1385   return getNode(TLI->getExtendForContent(BType), SL, VT, Op);
1386 }
1387 
1388 SDValue SelectionDAG::getZeroExtendInReg(SDValue Op, const SDLoc &DL, EVT VT) {
1389   EVT OpVT = Op.getValueType();
1390   assert(VT.isInteger() && OpVT.isInteger() &&
1391          "Cannot getZeroExtendInReg FP types");
1392   assert(VT.isVector() == OpVT.isVector() &&
1393          "getZeroExtendInReg type should be vector iff the operand "
1394          "type is vector!");
1395   assert((!VT.isVector() ||
1396           VT.getVectorElementCount() == OpVT.getVectorElementCount()) &&
1397          "Vector element counts must match in getZeroExtendInReg");
1398   assert(VT.bitsLE(OpVT) && "Not extending!");
1399   if (OpVT == VT)
1400     return Op;
1401   APInt Imm = APInt::getLowBitsSet(OpVT.getScalarSizeInBits(),
1402                                    VT.getScalarSizeInBits());
1403   return getNode(ISD::AND, DL, OpVT, Op, getConstant(Imm, DL, OpVT));
1404 }
1405 
1406 SDValue SelectionDAG::getPtrExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
1407   // Only unsigned pointer semantics are supported right now. In the future this
1408   // might delegate to TLI to check pointer signedness.
1409   return getZExtOrTrunc(Op, DL, VT);
1410 }
1411 
1412 SDValue SelectionDAG::getPtrExtendInReg(SDValue Op, const SDLoc &DL, EVT VT) {
1413   // Only unsigned pointer semantics are supported right now. In the future this
1414   // might delegate to TLI to check pointer signedness.
1415   return getZeroExtendInReg(Op, DL, VT);
1416 }
1417 
1418 /// getNOT - Create a bitwise NOT operation as (XOR Val, -1).
1419 SDValue SelectionDAG::getNOT(const SDLoc &DL, SDValue Val, EVT VT) {
1420   return getNode(ISD::XOR, DL, VT, Val, getAllOnesConstant(DL, VT));
1421 }
1422 
1423 SDValue SelectionDAG::getLogicalNOT(const SDLoc &DL, SDValue Val, EVT VT) {
1424   SDValue TrueValue = getBoolConstant(true, DL, VT, VT);
1425   return getNode(ISD::XOR, DL, VT, Val, TrueValue);
1426 }
1427 
1428 SDValue SelectionDAG::getVPLogicalNOT(const SDLoc &DL, SDValue Val,
1429                                       SDValue Mask, SDValue EVL, EVT VT) {
1430   SDValue TrueValue = getBoolConstant(true, DL, VT, VT);
1431   return getNode(ISD::VP_XOR, DL, VT, Val, TrueValue, Mask, EVL);
1432 }
1433 
1434 SDValue SelectionDAG::getBoolConstant(bool V, const SDLoc &DL, EVT VT,
1435                                       EVT OpVT) {
1436   if (!V)
1437     return getConstant(0, DL, VT);
1438 
1439   switch (TLI->getBooleanContents(OpVT)) {
1440   case TargetLowering::ZeroOrOneBooleanContent:
1441   case TargetLowering::UndefinedBooleanContent:
1442     return getConstant(1, DL, VT);
1443   case TargetLowering::ZeroOrNegativeOneBooleanContent:
1444     return getAllOnesConstant(DL, VT);
1445   }
1446   llvm_unreachable("Unexpected boolean content enum!");
1447 }
1448 
1449 SDValue SelectionDAG::getConstant(uint64_t Val, const SDLoc &DL, EVT VT,
1450                                   bool isT, bool isO) {
1451   EVT EltVT = VT.getScalarType();
1452   assert((EltVT.getSizeInBits() >= 64 ||
1453           (uint64_t)((int64_t)Val >> EltVT.getSizeInBits()) + 1 < 2) &&
1454          "getConstant with a uint64_t value that doesn't fit in the type!");
1455   return getConstant(APInt(EltVT.getSizeInBits(), Val), DL, VT, isT, isO);
1456 }
1457 
1458 SDValue SelectionDAG::getConstant(const APInt &Val, const SDLoc &DL, EVT VT,
1459                                   bool isT, bool isO) {
1460   return getConstant(*ConstantInt::get(*Context, Val), DL, VT, isT, isO);
1461 }
1462 
1463 SDValue SelectionDAG::getConstant(const ConstantInt &Val, const SDLoc &DL,
1464                                   EVT VT, bool isT, bool isO) {
1465   assert(VT.isInteger() && "Cannot create FP integer constant!");
1466 
1467   EVT EltVT = VT.getScalarType();
1468   const ConstantInt *Elt = &Val;
1469 
1470   // In some cases the vector type is legal but the element type is illegal and
1471   // needs to be promoted, for example v8i8 on ARM.  In this case, promote the
1472   // inserted value (the type does not need to match the vector element type).
1473   // Any extra bits introduced will be truncated away.
1474   if (VT.isVector() && TLI->getTypeAction(*getContext(), EltVT) ==
1475                            TargetLowering::TypePromoteInteger) {
1476     EltVT = TLI->getTypeToTransformTo(*getContext(), EltVT);
1477     APInt NewVal = Elt->getValue().zextOrTrunc(EltVT.getSizeInBits());
1478     Elt = ConstantInt::get(*getContext(), NewVal);
1479   }
1480   // In other cases the element type is illegal and needs to be expanded, for
1481   // example v2i64 on MIPS32. In this case, find the nearest legal type, split
1482   // the value into n parts and use a vector type with n-times the elements.
1483   // Then bitcast to the type requested.
1484   // Legalizing constants too early makes the DAGCombiner's job harder so we
1485   // only legalize if the DAG tells us we must produce legal types.
1486   else if (NewNodesMustHaveLegalTypes && VT.isVector() &&
1487            TLI->getTypeAction(*getContext(), EltVT) ==
1488                TargetLowering::TypeExpandInteger) {
1489     const APInt &NewVal = Elt->getValue();
1490     EVT ViaEltVT = TLI->getTypeToTransformTo(*getContext(), EltVT);
1491     unsigned ViaEltSizeInBits = ViaEltVT.getSizeInBits();
1492 
1493     // For scalable vectors, try to use a SPLAT_VECTOR_PARTS node.
1494     if (VT.isScalableVector()) {
1495       assert(EltVT.getSizeInBits() % ViaEltSizeInBits == 0 &&
1496              "Can only handle an even split!");
1497       unsigned Parts = EltVT.getSizeInBits() / ViaEltSizeInBits;
1498 
1499       SmallVector<SDValue, 2> ScalarParts;
1500       for (unsigned i = 0; i != Parts; ++i)
1501         ScalarParts.push_back(getConstant(
1502             NewVal.extractBits(ViaEltSizeInBits, i * ViaEltSizeInBits), DL,
1503             ViaEltVT, isT, isO));
1504 
1505       return getNode(ISD::SPLAT_VECTOR_PARTS, DL, VT, ScalarParts);
1506     }
1507 
1508     unsigned ViaVecNumElts = VT.getSizeInBits() / ViaEltSizeInBits;
1509     EVT ViaVecVT = EVT::getVectorVT(*getContext(), ViaEltVT, ViaVecNumElts);
1510 
1511     // Check the temporary vector is the correct size. If this fails then
1512     // getTypeToTransformTo() probably returned a type whose size (in bits)
1513     // isn't a power-of-2 factor of the requested type size.
1514     assert(ViaVecVT.getSizeInBits() == VT.getSizeInBits());
1515 
1516     SmallVector<SDValue, 2> EltParts;
1517     for (unsigned i = 0; i < ViaVecNumElts / VT.getVectorNumElements(); ++i)
1518       EltParts.push_back(getConstant(
1519           NewVal.extractBits(ViaEltSizeInBits, i * ViaEltSizeInBits), DL,
1520           ViaEltVT, isT, isO));
1521 
1522     // EltParts is currently in little endian order. If we actually want
1523     // big-endian order then reverse it now.
1524     if (getDataLayout().isBigEndian())
1525       std::reverse(EltParts.begin(), EltParts.end());
1526 
1527     // The elements must be reversed when the element order is different
1528     // to the endianness of the elements (because the BITCAST is itself a
1529     // vector shuffle in this situation). However, we do not need any code to
1530     // perform this reversal because getConstant() is producing a vector
1531     // splat.
1532     // This situation occurs in MIPS MSA.
1533 
1534     SmallVector<SDValue, 8> Ops;
1535     for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
1536       llvm::append_range(Ops, EltParts);
1537 
1538     SDValue V =
1539         getNode(ISD::BITCAST, DL, VT, getBuildVector(ViaVecVT, DL, Ops));
1540     return V;
1541   }
1542 
1543   assert(Elt->getBitWidth() == EltVT.getSizeInBits() &&
1544          "APInt size does not match type size!");
1545   unsigned Opc = isT ? ISD::TargetConstant : ISD::Constant;
1546   FoldingSetNodeID ID;
1547   AddNodeIDNode(ID, Opc, getVTList(EltVT), None);
1548   ID.AddPointer(Elt);
1549   ID.AddBoolean(isO);
1550   void *IP = nullptr;
1551   SDNode *N = nullptr;
1552   if ((N = FindNodeOrInsertPos(ID, DL, IP)))
1553     if (!VT.isVector())
1554       return SDValue(N, 0);
1555 
1556   if (!N) {
1557     N = newSDNode<ConstantSDNode>(isT, isO, Elt, EltVT);
1558     CSEMap.InsertNode(N, IP);
1559     InsertNode(N);
1560     NewSDValueDbgMsg(SDValue(N, 0), "Creating constant: ", this);
1561   }
1562 
1563   SDValue Result(N, 0);
1564   if (VT.isScalableVector())
1565     Result = getSplatVector(VT, DL, Result);
1566   else if (VT.isVector())
1567     Result = getSplatBuildVector(VT, DL, Result);
1568 
1569   return Result;
1570 }
1571 
1572 SDValue SelectionDAG::getIntPtrConstant(uint64_t Val, const SDLoc &DL,
1573                                         bool isTarget) {
1574   return getConstant(Val, DL, TLI->getPointerTy(getDataLayout()), isTarget);
1575 }
1576 
1577 SDValue SelectionDAG::getShiftAmountConstant(uint64_t Val, EVT VT,
1578                                              const SDLoc &DL, bool LegalTypes) {
1579   assert(VT.isInteger() && "Shift amount is not an integer type!");
1580   EVT ShiftVT = TLI->getShiftAmountTy(VT, getDataLayout(), LegalTypes);
1581   return getConstant(Val, DL, ShiftVT);
1582 }
1583 
1584 SDValue SelectionDAG::getVectorIdxConstant(uint64_t Val, const SDLoc &DL,
1585                                            bool isTarget) {
1586   return getConstant(Val, DL, TLI->getVectorIdxTy(getDataLayout()), isTarget);
1587 }
1588 
1589 SDValue SelectionDAG::getConstantFP(const APFloat &V, const SDLoc &DL, EVT VT,
1590                                     bool isTarget) {
1591   return getConstantFP(*ConstantFP::get(*getContext(), V), DL, VT, isTarget);
1592 }
1593 
1594 SDValue SelectionDAG::getConstantFP(const ConstantFP &V, const SDLoc &DL,
1595                                     EVT VT, bool isTarget) {
1596   assert(VT.isFloatingPoint() && "Cannot create integer FP constant!");
1597 
1598   EVT EltVT = VT.getScalarType();
1599 
1600   // Do the map lookup using the actual bit pattern for the floating point
1601   // value, so that we don't have problems with 0.0 comparing equal to -0.0, and
1602   // we don't have issues with SNANs.
1603   unsigned Opc = isTarget ? ISD::TargetConstantFP : ISD::ConstantFP;
1604   FoldingSetNodeID ID;
1605   AddNodeIDNode(ID, Opc, getVTList(EltVT), None);
1606   ID.AddPointer(&V);
1607   void *IP = nullptr;
1608   SDNode *N = nullptr;
1609   if ((N = FindNodeOrInsertPos(ID, DL, IP)))
1610     if (!VT.isVector())
1611       return SDValue(N, 0);
1612 
1613   if (!N) {
1614     N = newSDNode<ConstantFPSDNode>(isTarget, &V, EltVT);
1615     CSEMap.InsertNode(N, IP);
1616     InsertNode(N);
1617   }
1618 
1619   SDValue Result(N, 0);
1620   if (VT.isScalableVector())
1621     Result = getSplatVector(VT, DL, Result);
1622   else if (VT.isVector())
1623     Result = getSplatBuildVector(VT, DL, Result);
1624   NewSDValueDbgMsg(Result, "Creating fp constant: ", this);
1625   return Result;
1626 }
1627 
1628 SDValue SelectionDAG::getConstantFP(double Val, const SDLoc &DL, EVT VT,
1629                                     bool isTarget) {
1630   EVT EltVT = VT.getScalarType();
1631   if (EltVT == MVT::f32)
1632     return getConstantFP(APFloat((float)Val), DL, VT, isTarget);
1633   if (EltVT == MVT::f64)
1634     return getConstantFP(APFloat(Val), DL, VT, isTarget);
1635   if (EltVT == MVT::f80 || EltVT == MVT::f128 || EltVT == MVT::ppcf128 ||
1636       EltVT == MVT::f16 || EltVT == MVT::bf16) {
1637     bool Ignored;
1638     APFloat APF = APFloat(Val);
1639     APF.convert(EVTToAPFloatSemantics(EltVT), APFloat::rmNearestTiesToEven,
1640                 &Ignored);
1641     return getConstantFP(APF, DL, VT, isTarget);
1642   }
1643   llvm_unreachable("Unsupported type in getConstantFP");
1644 }
1645 
1646 SDValue SelectionDAG::getGlobalAddress(const GlobalValue *GV, const SDLoc &DL,
1647                                        EVT VT, int64_t Offset, bool isTargetGA,
1648                                        unsigned TargetFlags) {
1649   assert((TargetFlags == 0 || isTargetGA) &&
1650          "Cannot set target flags on target-independent globals");
1651 
1652   // Truncate (with sign-extension) the offset value to the pointer size.
1653   unsigned BitWidth = getDataLayout().getPointerTypeSizeInBits(GV->getType());
1654   if (BitWidth < 64)
1655     Offset = SignExtend64(Offset, BitWidth);
1656 
1657   unsigned Opc;
1658   if (GV->isThreadLocal())
1659     Opc = isTargetGA ? ISD::TargetGlobalTLSAddress : ISD::GlobalTLSAddress;
1660   else
1661     Opc = isTargetGA ? ISD::TargetGlobalAddress : ISD::GlobalAddress;
1662 
1663   FoldingSetNodeID ID;
1664   AddNodeIDNode(ID, Opc, getVTList(VT), None);
1665   ID.AddPointer(GV);
1666   ID.AddInteger(Offset);
1667   ID.AddInteger(TargetFlags);
1668   void *IP = nullptr;
1669   if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
1670     return SDValue(E, 0);
1671 
1672   auto *N = newSDNode<GlobalAddressSDNode>(
1673       Opc, DL.getIROrder(), DL.getDebugLoc(), GV, VT, Offset, TargetFlags);
1674   CSEMap.InsertNode(N, IP);
1675     InsertNode(N);
1676   return SDValue(N, 0);
1677 }
1678 
1679 SDValue SelectionDAG::getFrameIndex(int FI, EVT VT, bool isTarget) {
1680   unsigned Opc = isTarget ? ISD::TargetFrameIndex : ISD::FrameIndex;
1681   FoldingSetNodeID ID;
1682   AddNodeIDNode(ID, Opc, getVTList(VT), None);
1683   ID.AddInteger(FI);
1684   void *IP = nullptr;
1685   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1686     return SDValue(E, 0);
1687 
1688   auto *N = newSDNode<FrameIndexSDNode>(FI, VT, isTarget);
1689   CSEMap.InsertNode(N, IP);
1690   InsertNode(N);
1691   return SDValue(N, 0);
1692 }
1693 
1694 SDValue SelectionDAG::getJumpTable(int JTI, EVT VT, bool isTarget,
1695                                    unsigned TargetFlags) {
1696   assert((TargetFlags == 0 || isTarget) &&
1697          "Cannot set target flags on target-independent jump tables");
1698   unsigned Opc = isTarget ? ISD::TargetJumpTable : ISD::JumpTable;
1699   FoldingSetNodeID ID;
1700   AddNodeIDNode(ID, Opc, getVTList(VT), None);
1701   ID.AddInteger(JTI);
1702   ID.AddInteger(TargetFlags);
1703   void *IP = nullptr;
1704   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1705     return SDValue(E, 0);
1706 
1707   auto *N = newSDNode<JumpTableSDNode>(JTI, VT, isTarget, TargetFlags);
1708   CSEMap.InsertNode(N, IP);
1709   InsertNode(N);
1710   return SDValue(N, 0);
1711 }
1712 
1713 SDValue SelectionDAG::getConstantPool(const Constant *C, EVT VT,
1714                                       MaybeAlign Alignment, int Offset,
1715                                       bool isTarget, unsigned TargetFlags) {
1716   assert((TargetFlags == 0 || isTarget) &&
1717          "Cannot set target flags on target-independent globals");
1718   if (!Alignment)
1719     Alignment = shouldOptForSize()
1720                     ? getDataLayout().getABITypeAlign(C->getType())
1721                     : getDataLayout().getPrefTypeAlign(C->getType());
1722   unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
1723   FoldingSetNodeID ID;
1724   AddNodeIDNode(ID, Opc, getVTList(VT), None);
1725   ID.AddInteger(Alignment->value());
1726   ID.AddInteger(Offset);
1727   ID.AddPointer(C);
1728   ID.AddInteger(TargetFlags);
1729   void *IP = nullptr;
1730   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1731     return SDValue(E, 0);
1732 
1733   auto *N = newSDNode<ConstantPoolSDNode>(isTarget, C, VT, Offset, *Alignment,
1734                                           TargetFlags);
1735   CSEMap.InsertNode(N, IP);
1736   InsertNode(N);
1737   SDValue V = SDValue(N, 0);
1738   NewSDValueDbgMsg(V, "Creating new constant pool: ", this);
1739   return V;
1740 }
1741 
1742 SDValue SelectionDAG::getConstantPool(MachineConstantPoolValue *C, EVT VT,
1743                                       MaybeAlign Alignment, int Offset,
1744                                       bool isTarget, unsigned TargetFlags) {
1745   assert((TargetFlags == 0 || isTarget) &&
1746          "Cannot set target flags on target-independent globals");
1747   if (!Alignment)
1748     Alignment = getDataLayout().getPrefTypeAlign(C->getType());
1749   unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
1750   FoldingSetNodeID ID;
1751   AddNodeIDNode(ID, Opc, getVTList(VT), None);
1752   ID.AddInteger(Alignment->value());
1753   ID.AddInteger(Offset);
1754   C->addSelectionDAGCSEId(ID);
1755   ID.AddInteger(TargetFlags);
1756   void *IP = nullptr;
1757   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1758     return SDValue(E, 0);
1759 
1760   auto *N = newSDNode<ConstantPoolSDNode>(isTarget, C, VT, Offset, *Alignment,
1761                                           TargetFlags);
1762   CSEMap.InsertNode(N, IP);
1763   InsertNode(N);
1764   return SDValue(N, 0);
1765 }
1766 
1767 SDValue SelectionDAG::getTargetIndex(int Index, EVT VT, int64_t Offset,
1768                                      unsigned TargetFlags) {
1769   FoldingSetNodeID ID;
1770   AddNodeIDNode(ID, ISD::TargetIndex, getVTList(VT), None);
1771   ID.AddInteger(Index);
1772   ID.AddInteger(Offset);
1773   ID.AddInteger(TargetFlags);
1774   void *IP = nullptr;
1775   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1776     return SDValue(E, 0);
1777 
1778   auto *N = newSDNode<TargetIndexSDNode>(Index, VT, Offset, TargetFlags);
1779   CSEMap.InsertNode(N, IP);
1780   InsertNode(N);
1781   return SDValue(N, 0);
1782 }
1783 
1784 SDValue SelectionDAG::getBasicBlock(MachineBasicBlock *MBB) {
1785   FoldingSetNodeID ID;
1786   AddNodeIDNode(ID, ISD::BasicBlock, getVTList(MVT::Other), None);
1787   ID.AddPointer(MBB);
1788   void *IP = nullptr;
1789   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1790     return SDValue(E, 0);
1791 
1792   auto *N = newSDNode<BasicBlockSDNode>(MBB);
1793   CSEMap.InsertNode(N, IP);
1794   InsertNode(N);
1795   return SDValue(N, 0);
1796 }
1797 
1798 SDValue SelectionDAG::getValueType(EVT VT) {
1799   if (VT.isSimple() && (unsigned)VT.getSimpleVT().SimpleTy >=
1800       ValueTypeNodes.size())
1801     ValueTypeNodes.resize(VT.getSimpleVT().SimpleTy+1);
1802 
1803   SDNode *&N = VT.isExtended() ?
1804     ExtendedValueTypeNodes[VT] : ValueTypeNodes[VT.getSimpleVT().SimpleTy];
1805 
1806   if (N) return SDValue(N, 0);
1807   N = newSDNode<VTSDNode>(VT);
1808   InsertNode(N);
1809   return SDValue(N, 0);
1810 }
1811 
1812 SDValue SelectionDAG::getExternalSymbol(const char *Sym, EVT VT) {
1813   SDNode *&N = ExternalSymbols[Sym];
1814   if (N) return SDValue(N, 0);
1815   N = newSDNode<ExternalSymbolSDNode>(false, Sym, 0, VT);
1816   InsertNode(N);
1817   return SDValue(N, 0);
1818 }
1819 
1820 SDValue SelectionDAG::getMCSymbol(MCSymbol *Sym, EVT VT) {
1821   SDNode *&N = MCSymbols[Sym];
1822   if (N)
1823     return SDValue(N, 0);
1824   N = newSDNode<MCSymbolSDNode>(Sym, VT);
1825   InsertNode(N);
1826   return SDValue(N, 0);
1827 }
1828 
1829 SDValue SelectionDAG::getTargetExternalSymbol(const char *Sym, EVT VT,
1830                                               unsigned TargetFlags) {
1831   SDNode *&N =
1832       TargetExternalSymbols[std::pair<std::string, unsigned>(Sym, TargetFlags)];
1833   if (N) return SDValue(N, 0);
1834   N = newSDNode<ExternalSymbolSDNode>(true, Sym, TargetFlags, VT);
1835   InsertNode(N);
1836   return SDValue(N, 0);
1837 }
1838 
1839 SDValue SelectionDAG::getCondCode(ISD::CondCode Cond) {
1840   if ((unsigned)Cond >= CondCodeNodes.size())
1841     CondCodeNodes.resize(Cond+1);
1842 
1843   if (!CondCodeNodes[Cond]) {
1844     auto *N = newSDNode<CondCodeSDNode>(Cond);
1845     CondCodeNodes[Cond] = N;
1846     InsertNode(N);
1847   }
1848 
1849   return SDValue(CondCodeNodes[Cond], 0);
1850 }
1851 
1852 SDValue SelectionDAG::getStepVector(const SDLoc &DL, EVT ResVT) {
1853   APInt One(ResVT.getScalarSizeInBits(), 1);
1854   return getStepVector(DL, ResVT, One);
1855 }
1856 
1857 SDValue SelectionDAG::getStepVector(const SDLoc &DL, EVT ResVT, APInt StepVal) {
1858   assert(ResVT.getScalarSizeInBits() == StepVal.getBitWidth());
1859   if (ResVT.isScalableVector())
1860     return getNode(
1861         ISD::STEP_VECTOR, DL, ResVT,
1862         getTargetConstant(StepVal, DL, ResVT.getVectorElementType()));
1863 
1864   SmallVector<SDValue, 16> OpsStepConstants;
1865   for (uint64_t i = 0; i < ResVT.getVectorNumElements(); i++)
1866     OpsStepConstants.push_back(
1867         getConstant(StepVal * i, DL, ResVT.getVectorElementType()));
1868   return getBuildVector(ResVT, DL, OpsStepConstants);
1869 }
1870 
1871 /// Swaps the values of N1 and N2. Swaps all indices in the shuffle mask M that
1872 /// point at N1 to point at N2 and indices that point at N2 to point at N1.
1873 static void commuteShuffle(SDValue &N1, SDValue &N2, MutableArrayRef<int> M) {
1874   std::swap(N1, N2);
1875   ShuffleVectorSDNode::commuteMask(M);
1876 }
1877 
1878 SDValue SelectionDAG::getVectorShuffle(EVT VT, const SDLoc &dl, SDValue N1,
1879                                        SDValue N2, ArrayRef<int> Mask) {
1880   assert(VT.getVectorNumElements() == Mask.size() &&
1881          "Must have the same number of vector elements as mask elements!");
1882   assert(VT == N1.getValueType() && VT == N2.getValueType() &&
1883          "Invalid VECTOR_SHUFFLE");
1884 
1885   // Canonicalize shuffle undef, undef -> undef
1886   if (N1.isUndef() && N2.isUndef())
1887     return getUNDEF(VT);
1888 
1889   // Validate that all indices in Mask are within the range of the elements
1890   // input to the shuffle.
1891   int NElts = Mask.size();
1892   assert(llvm::all_of(Mask,
1893                       [&](int M) { return M < (NElts * 2) && M >= -1; }) &&
1894          "Index out of range");
1895 
1896   // Copy the mask so we can do any needed cleanup.
1897   SmallVector<int, 8> MaskVec(Mask.begin(), Mask.end());
1898 
1899   // Canonicalize shuffle v, v -> v, undef
1900   if (N1 == N2) {
1901     N2 = getUNDEF(VT);
1902     for (int i = 0; i != NElts; ++i)
1903       if (MaskVec[i] >= NElts) MaskVec[i] -= NElts;
1904   }
1905 
1906   // Canonicalize shuffle undef, v -> v, undef.  Commute the shuffle mask.
1907   if (N1.isUndef())
1908     commuteShuffle(N1, N2, MaskVec);
1909 
1910   if (TLI->hasVectorBlend()) {
1911     // If shuffling a splat, try to blend the splat instead. We do this here so
1912     // that even when this arises during lowering we don't have to re-handle it.
1913     auto BlendSplat = [&](BuildVectorSDNode *BV, int Offset) {
1914       BitVector UndefElements;
1915       SDValue Splat = BV->getSplatValue(&UndefElements);
1916       if (!Splat)
1917         return;
1918 
1919       for (int i = 0; i < NElts; ++i) {
1920         if (MaskVec[i] < Offset || MaskVec[i] >= (Offset + NElts))
1921           continue;
1922 
1923         // If this input comes from undef, mark it as such.
1924         if (UndefElements[MaskVec[i] - Offset]) {
1925           MaskVec[i] = -1;
1926           continue;
1927         }
1928 
1929         // If we can blend a non-undef lane, use that instead.
1930         if (!UndefElements[i])
1931           MaskVec[i] = i + Offset;
1932       }
1933     };
1934     if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
1935       BlendSplat(N1BV, 0);
1936     if (auto *N2BV = dyn_cast<BuildVectorSDNode>(N2))
1937       BlendSplat(N2BV, NElts);
1938   }
1939 
1940   // Canonicalize all index into lhs, -> shuffle lhs, undef
1941   // Canonicalize all index into rhs, -> shuffle rhs, undef
1942   bool AllLHS = true, AllRHS = true;
1943   bool N2Undef = N2.isUndef();
1944   for (int i = 0; i != NElts; ++i) {
1945     if (MaskVec[i] >= NElts) {
1946       if (N2Undef)
1947         MaskVec[i] = -1;
1948       else
1949         AllLHS = false;
1950     } else if (MaskVec[i] >= 0) {
1951       AllRHS = false;
1952     }
1953   }
1954   if (AllLHS && AllRHS)
1955     return getUNDEF(VT);
1956   if (AllLHS && !N2Undef)
1957     N2 = getUNDEF(VT);
1958   if (AllRHS) {
1959     N1 = getUNDEF(VT);
1960     commuteShuffle(N1, N2, MaskVec);
1961   }
1962   // Reset our undef status after accounting for the mask.
1963   N2Undef = N2.isUndef();
1964   // Re-check whether both sides ended up undef.
1965   if (N1.isUndef() && N2Undef)
1966     return getUNDEF(VT);
1967 
1968   // If Identity shuffle return that node.
1969   bool Identity = true, AllSame = true;
1970   for (int i = 0; i != NElts; ++i) {
1971     if (MaskVec[i] >= 0 && MaskVec[i] != i) Identity = false;
1972     if (MaskVec[i] != MaskVec[0]) AllSame = false;
1973   }
1974   if (Identity && NElts)
1975     return N1;
1976 
1977   // Shuffling a constant splat doesn't change the result.
1978   if (N2Undef) {
1979     SDValue V = N1;
1980 
1981     // Look through any bitcasts. We check that these don't change the number
1982     // (and size) of elements and just changes their types.
1983     while (V.getOpcode() == ISD::BITCAST)
1984       V = V->getOperand(0);
1985 
1986     // A splat should always show up as a build vector node.
1987     if (auto *BV = dyn_cast<BuildVectorSDNode>(V)) {
1988       BitVector UndefElements;
1989       SDValue Splat = BV->getSplatValue(&UndefElements);
1990       // If this is a splat of an undef, shuffling it is also undef.
1991       if (Splat && Splat.isUndef())
1992         return getUNDEF(VT);
1993 
1994       bool SameNumElts =
1995           V.getValueType().getVectorNumElements() == VT.getVectorNumElements();
1996 
1997       // We only have a splat which can skip shuffles if there is a splatted
1998       // value and no undef lanes rearranged by the shuffle.
1999       if (Splat && UndefElements.none()) {
2000         // Splat of <x, x, ..., x>, return <x, x, ..., x>, provided that the
2001         // number of elements match or the value splatted is a zero constant.
2002         if (SameNumElts)
2003           return N1;
2004         if (auto *C = dyn_cast<ConstantSDNode>(Splat))
2005           if (C->isZero())
2006             return N1;
2007       }
2008 
2009       // If the shuffle itself creates a splat, build the vector directly.
2010       if (AllSame && SameNumElts) {
2011         EVT BuildVT = BV->getValueType(0);
2012         const SDValue &Splatted = BV->getOperand(MaskVec[0]);
2013         SDValue NewBV = getSplatBuildVector(BuildVT, dl, Splatted);
2014 
2015         // We may have jumped through bitcasts, so the type of the
2016         // BUILD_VECTOR may not match the type of the shuffle.
2017         if (BuildVT != VT)
2018           NewBV = getNode(ISD::BITCAST, dl, VT, NewBV);
2019         return NewBV;
2020       }
2021     }
2022   }
2023 
2024   FoldingSetNodeID ID;
2025   SDValue Ops[2] = { N1, N2 };
2026   AddNodeIDNode(ID, ISD::VECTOR_SHUFFLE, getVTList(VT), Ops);
2027   for (int i = 0; i != NElts; ++i)
2028     ID.AddInteger(MaskVec[i]);
2029 
2030   void* IP = nullptr;
2031   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
2032     return SDValue(E, 0);
2033 
2034   // Allocate the mask array for the node out of the BumpPtrAllocator, since
2035   // SDNode doesn't have access to it.  This memory will be "leaked" when
2036   // the node is deallocated, but recovered when the NodeAllocator is released.
2037   int *MaskAlloc = OperandAllocator.Allocate<int>(NElts);
2038   llvm::copy(MaskVec, MaskAlloc);
2039 
2040   auto *N = newSDNode<ShuffleVectorSDNode>(VT, dl.getIROrder(),
2041                                            dl.getDebugLoc(), MaskAlloc);
2042   createOperands(N, Ops);
2043 
2044   CSEMap.InsertNode(N, IP);
2045   InsertNode(N);
2046   SDValue V = SDValue(N, 0);
2047   NewSDValueDbgMsg(V, "Creating new node: ", this);
2048   return V;
2049 }
2050 
2051 SDValue SelectionDAG::getCommutedVectorShuffle(const ShuffleVectorSDNode &SV) {
2052   EVT VT = SV.getValueType(0);
2053   SmallVector<int, 8> MaskVec(SV.getMask().begin(), SV.getMask().end());
2054   ShuffleVectorSDNode::commuteMask(MaskVec);
2055 
2056   SDValue Op0 = SV.getOperand(0);
2057   SDValue Op1 = SV.getOperand(1);
2058   return getVectorShuffle(VT, SDLoc(&SV), Op1, Op0, MaskVec);
2059 }
2060 
2061 SDValue SelectionDAG::getRegister(unsigned RegNo, EVT VT) {
2062   FoldingSetNodeID ID;
2063   AddNodeIDNode(ID, ISD::Register, getVTList(VT), None);
2064   ID.AddInteger(RegNo);
2065   void *IP = nullptr;
2066   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2067     return SDValue(E, 0);
2068 
2069   auto *N = newSDNode<RegisterSDNode>(RegNo, VT);
2070   N->SDNodeBits.IsDivergent = TLI->isSDNodeSourceOfDivergence(N, FLI, DA);
2071   CSEMap.InsertNode(N, IP);
2072   InsertNode(N);
2073   return SDValue(N, 0);
2074 }
2075 
2076 SDValue SelectionDAG::getRegisterMask(const uint32_t *RegMask) {
2077   FoldingSetNodeID ID;
2078   AddNodeIDNode(ID, ISD::RegisterMask, getVTList(MVT::Untyped), None);
2079   ID.AddPointer(RegMask);
2080   void *IP = nullptr;
2081   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2082     return SDValue(E, 0);
2083 
2084   auto *N = newSDNode<RegisterMaskSDNode>(RegMask);
2085   CSEMap.InsertNode(N, IP);
2086   InsertNode(N);
2087   return SDValue(N, 0);
2088 }
2089 
2090 SDValue SelectionDAG::getEHLabel(const SDLoc &dl, SDValue Root,
2091                                  MCSymbol *Label) {
2092   return getLabelNode(ISD::EH_LABEL, dl, Root, Label);
2093 }
2094 
2095 SDValue SelectionDAG::getLabelNode(unsigned Opcode, const SDLoc &dl,
2096                                    SDValue Root, MCSymbol *Label) {
2097   FoldingSetNodeID ID;
2098   SDValue Ops[] = { Root };
2099   AddNodeIDNode(ID, Opcode, getVTList(MVT::Other), Ops);
2100   ID.AddPointer(Label);
2101   void *IP = nullptr;
2102   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2103     return SDValue(E, 0);
2104 
2105   auto *N =
2106       newSDNode<LabelSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(), Label);
2107   createOperands(N, Ops);
2108 
2109   CSEMap.InsertNode(N, IP);
2110   InsertNode(N);
2111   return SDValue(N, 0);
2112 }
2113 
2114 SDValue SelectionDAG::getBlockAddress(const BlockAddress *BA, EVT VT,
2115                                       int64_t Offset, bool isTarget,
2116                                       unsigned TargetFlags) {
2117   unsigned Opc = isTarget ? ISD::TargetBlockAddress : ISD::BlockAddress;
2118 
2119   FoldingSetNodeID ID;
2120   AddNodeIDNode(ID, Opc, getVTList(VT), None);
2121   ID.AddPointer(BA);
2122   ID.AddInteger(Offset);
2123   ID.AddInteger(TargetFlags);
2124   void *IP = nullptr;
2125   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2126     return SDValue(E, 0);
2127 
2128   auto *N = newSDNode<BlockAddressSDNode>(Opc, VT, BA, Offset, TargetFlags);
2129   CSEMap.InsertNode(N, IP);
2130   InsertNode(N);
2131   return SDValue(N, 0);
2132 }
2133 
2134 SDValue SelectionDAG::getSrcValue(const Value *V) {
2135   FoldingSetNodeID ID;
2136   AddNodeIDNode(ID, ISD::SRCVALUE, getVTList(MVT::Other), None);
2137   ID.AddPointer(V);
2138 
2139   void *IP = nullptr;
2140   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2141     return SDValue(E, 0);
2142 
2143   auto *N = newSDNode<SrcValueSDNode>(V);
2144   CSEMap.InsertNode(N, IP);
2145   InsertNode(N);
2146   return SDValue(N, 0);
2147 }
2148 
2149 SDValue SelectionDAG::getMDNode(const MDNode *MD) {
2150   FoldingSetNodeID ID;
2151   AddNodeIDNode(ID, ISD::MDNODE_SDNODE, getVTList(MVT::Other), None);
2152   ID.AddPointer(MD);
2153 
2154   void *IP = nullptr;
2155   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2156     return SDValue(E, 0);
2157 
2158   auto *N = newSDNode<MDNodeSDNode>(MD);
2159   CSEMap.InsertNode(N, IP);
2160   InsertNode(N);
2161   return SDValue(N, 0);
2162 }
2163 
2164 SDValue SelectionDAG::getBitcast(EVT VT, SDValue V) {
2165   if (VT == V.getValueType())
2166     return V;
2167 
2168   return getNode(ISD::BITCAST, SDLoc(V), VT, V);
2169 }
2170 
2171 SDValue SelectionDAG::getAddrSpaceCast(const SDLoc &dl, EVT VT, SDValue Ptr,
2172                                        unsigned SrcAS, unsigned DestAS) {
2173   SDValue Ops[] = {Ptr};
2174   FoldingSetNodeID ID;
2175   AddNodeIDNode(ID, ISD::ADDRSPACECAST, getVTList(VT), Ops);
2176   ID.AddInteger(SrcAS);
2177   ID.AddInteger(DestAS);
2178 
2179   void *IP = nullptr;
2180   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
2181     return SDValue(E, 0);
2182 
2183   auto *N = newSDNode<AddrSpaceCastSDNode>(dl.getIROrder(), dl.getDebugLoc(),
2184                                            VT, SrcAS, DestAS);
2185   createOperands(N, Ops);
2186 
2187   CSEMap.InsertNode(N, IP);
2188   InsertNode(N);
2189   return SDValue(N, 0);
2190 }
2191 
2192 SDValue SelectionDAG::getFreeze(SDValue V) {
2193   return getNode(ISD::FREEZE, SDLoc(V), V.getValueType(), V);
2194 }
2195 
2196 /// getShiftAmountOperand - Return the specified value casted to
2197 /// the target's desired shift amount type.
2198 SDValue SelectionDAG::getShiftAmountOperand(EVT LHSTy, SDValue Op) {
2199   EVT OpTy = Op.getValueType();
2200   EVT ShTy = TLI->getShiftAmountTy(LHSTy, getDataLayout());
2201   if (OpTy == ShTy || OpTy.isVector()) return Op;
2202 
2203   return getZExtOrTrunc(Op, SDLoc(Op), ShTy);
2204 }
2205 
2206 SDValue SelectionDAG::expandVAArg(SDNode *Node) {
2207   SDLoc dl(Node);
2208   const TargetLowering &TLI = getTargetLoweringInfo();
2209   const Value *V = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
2210   EVT VT = Node->getValueType(0);
2211   SDValue Tmp1 = Node->getOperand(0);
2212   SDValue Tmp2 = Node->getOperand(1);
2213   const MaybeAlign MA(Node->getConstantOperandVal(3));
2214 
2215   SDValue VAListLoad = getLoad(TLI.getPointerTy(getDataLayout()), dl, Tmp1,
2216                                Tmp2, MachinePointerInfo(V));
2217   SDValue VAList = VAListLoad;
2218 
2219   if (MA && *MA > TLI.getMinStackArgumentAlignment()) {
2220     VAList = getNode(ISD::ADD, dl, VAList.getValueType(), VAList,
2221                      getConstant(MA->value() - 1, dl, VAList.getValueType()));
2222 
2223     VAList =
2224         getNode(ISD::AND, dl, VAList.getValueType(), VAList,
2225                 getConstant(-(int64_t)MA->value(), dl, VAList.getValueType()));
2226   }
2227 
2228   // Increment the pointer, VAList, to the next vaarg
2229   Tmp1 = getNode(ISD::ADD, dl, VAList.getValueType(), VAList,
2230                  getConstant(getDataLayout().getTypeAllocSize(
2231                                                VT.getTypeForEVT(*getContext())),
2232                              dl, VAList.getValueType()));
2233   // Store the incremented VAList to the legalized pointer
2234   Tmp1 =
2235       getStore(VAListLoad.getValue(1), dl, Tmp1, Tmp2, MachinePointerInfo(V));
2236   // Load the actual argument out of the pointer VAList
2237   return getLoad(VT, dl, Tmp1, VAList, MachinePointerInfo());
2238 }
2239 
2240 SDValue SelectionDAG::expandVACopy(SDNode *Node) {
2241   SDLoc dl(Node);
2242   const TargetLowering &TLI = getTargetLoweringInfo();
2243   // This defaults to loading a pointer from the input and storing it to the
2244   // output, returning the chain.
2245   const Value *VD = cast<SrcValueSDNode>(Node->getOperand(3))->getValue();
2246   const Value *VS = cast<SrcValueSDNode>(Node->getOperand(4))->getValue();
2247   SDValue Tmp1 =
2248       getLoad(TLI.getPointerTy(getDataLayout()), dl, Node->getOperand(0),
2249               Node->getOperand(2), MachinePointerInfo(VS));
2250   return getStore(Tmp1.getValue(1), dl, Tmp1, Node->getOperand(1),
2251                   MachinePointerInfo(VD));
2252 }
2253 
2254 Align SelectionDAG::getReducedAlign(EVT VT, bool UseABI) {
2255   const DataLayout &DL = getDataLayout();
2256   Type *Ty = VT.getTypeForEVT(*getContext());
2257   Align RedAlign = UseABI ? DL.getABITypeAlign(Ty) : DL.getPrefTypeAlign(Ty);
2258 
2259   if (TLI->isTypeLegal(VT) || !VT.isVector())
2260     return RedAlign;
2261 
2262   const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering();
2263   const Align StackAlign = TFI->getStackAlign();
2264 
2265   // See if we can choose a smaller ABI alignment in cases where it's an
2266   // illegal vector type that will get broken down.
2267   if (RedAlign > StackAlign) {
2268     EVT IntermediateVT;
2269     MVT RegisterVT;
2270     unsigned NumIntermediates;
2271     TLI->getVectorTypeBreakdown(*getContext(), VT, IntermediateVT,
2272                                 NumIntermediates, RegisterVT);
2273     Ty = IntermediateVT.getTypeForEVT(*getContext());
2274     Align RedAlign2 = UseABI ? DL.getABITypeAlign(Ty) : DL.getPrefTypeAlign(Ty);
2275     if (RedAlign2 < RedAlign)
2276       RedAlign = RedAlign2;
2277   }
2278 
2279   return RedAlign;
2280 }
2281 
2282 SDValue SelectionDAG::CreateStackTemporary(TypeSize Bytes, Align Alignment) {
2283   MachineFrameInfo &MFI = MF->getFrameInfo();
2284   const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering();
2285   int StackID = 0;
2286   if (Bytes.isScalable())
2287     StackID = TFI->getStackIDForScalableVectors();
2288   // The stack id gives an indication of whether the object is scalable or
2289   // not, so it's safe to pass in the minimum size here.
2290   int FrameIdx = MFI.CreateStackObject(Bytes.getKnownMinSize(), Alignment,
2291                                        false, nullptr, StackID);
2292   return getFrameIndex(FrameIdx, TLI->getFrameIndexTy(getDataLayout()));
2293 }
2294 
2295 SDValue SelectionDAG::CreateStackTemporary(EVT VT, unsigned minAlign) {
2296   Type *Ty = VT.getTypeForEVT(*getContext());
2297   Align StackAlign =
2298       std::max(getDataLayout().getPrefTypeAlign(Ty), Align(minAlign));
2299   return CreateStackTemporary(VT.getStoreSize(), StackAlign);
2300 }
2301 
2302 SDValue SelectionDAG::CreateStackTemporary(EVT VT1, EVT VT2) {
2303   TypeSize VT1Size = VT1.getStoreSize();
2304   TypeSize VT2Size = VT2.getStoreSize();
2305   assert(VT1Size.isScalable() == VT2Size.isScalable() &&
2306          "Don't know how to choose the maximum size when creating a stack "
2307          "temporary");
2308   TypeSize Bytes =
2309       VT1Size.getKnownMinSize() > VT2Size.getKnownMinSize() ? VT1Size : VT2Size;
2310 
2311   Type *Ty1 = VT1.getTypeForEVT(*getContext());
2312   Type *Ty2 = VT2.getTypeForEVT(*getContext());
2313   const DataLayout &DL = getDataLayout();
2314   Align Align = std::max(DL.getPrefTypeAlign(Ty1), DL.getPrefTypeAlign(Ty2));
2315   return CreateStackTemporary(Bytes, Align);
2316 }
2317 
2318 SDValue SelectionDAG::FoldSetCC(EVT VT, SDValue N1, SDValue N2,
2319                                 ISD::CondCode Cond, const SDLoc &dl) {
2320   EVT OpVT = N1.getValueType();
2321 
2322   // These setcc operations always fold.
2323   switch (Cond) {
2324   default: break;
2325   case ISD::SETFALSE:
2326   case ISD::SETFALSE2: return getBoolConstant(false, dl, VT, OpVT);
2327   case ISD::SETTRUE:
2328   case ISD::SETTRUE2: return getBoolConstant(true, dl, VT, OpVT);
2329 
2330   case ISD::SETOEQ:
2331   case ISD::SETOGT:
2332   case ISD::SETOGE:
2333   case ISD::SETOLT:
2334   case ISD::SETOLE:
2335   case ISD::SETONE:
2336   case ISD::SETO:
2337   case ISD::SETUO:
2338   case ISD::SETUEQ:
2339   case ISD::SETUNE:
2340     assert(!OpVT.isInteger() && "Illegal setcc for integer!");
2341     break;
2342   }
2343 
2344   if (OpVT.isInteger()) {
2345     // For EQ and NE, we can always pick a value for the undef to make the
2346     // predicate pass or fail, so we can return undef.
2347     // Matches behavior in llvm::ConstantFoldCompareInstruction.
2348     // icmp eq/ne X, undef -> undef.
2349     if ((N1.isUndef() || N2.isUndef()) &&
2350         (Cond == ISD::SETEQ || Cond == ISD::SETNE))
2351       return getUNDEF(VT);
2352 
2353     // If both operands are undef, we can return undef for int comparison.
2354     // icmp undef, undef -> undef.
2355     if (N1.isUndef() && N2.isUndef())
2356       return getUNDEF(VT);
2357 
2358     // icmp X, X -> true/false
2359     // icmp X, undef -> true/false because undef could be X.
2360     if (N1 == N2)
2361       return getBoolConstant(ISD::isTrueWhenEqual(Cond), dl, VT, OpVT);
2362   }
2363 
2364   if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2)) {
2365     const APInt &C2 = N2C->getAPIntValue();
2366     if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1)) {
2367       const APInt &C1 = N1C->getAPIntValue();
2368 
2369       return getBoolConstant(ICmpInst::compare(C1, C2, getICmpCondCode(Cond)),
2370                              dl, VT, OpVT);
2371     }
2372   }
2373 
2374   auto *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
2375   auto *N2CFP = dyn_cast<ConstantFPSDNode>(N2);
2376 
2377   if (N1CFP && N2CFP) {
2378     APFloat::cmpResult R = N1CFP->getValueAPF().compare(N2CFP->getValueAPF());
2379     switch (Cond) {
2380     default: break;
2381     case ISD::SETEQ:  if (R==APFloat::cmpUnordered)
2382                         return getUNDEF(VT);
2383                       LLVM_FALLTHROUGH;
2384     case ISD::SETOEQ: return getBoolConstant(R==APFloat::cmpEqual, dl, VT,
2385                                              OpVT);
2386     case ISD::SETNE:  if (R==APFloat::cmpUnordered)
2387                         return getUNDEF(VT);
2388                       LLVM_FALLTHROUGH;
2389     case ISD::SETONE: return getBoolConstant(R==APFloat::cmpGreaterThan ||
2390                                              R==APFloat::cmpLessThan, dl, VT,
2391                                              OpVT);
2392     case ISD::SETLT:  if (R==APFloat::cmpUnordered)
2393                         return getUNDEF(VT);
2394                       LLVM_FALLTHROUGH;
2395     case ISD::SETOLT: return getBoolConstant(R==APFloat::cmpLessThan, dl, VT,
2396                                              OpVT);
2397     case ISD::SETGT:  if (R==APFloat::cmpUnordered)
2398                         return getUNDEF(VT);
2399                       LLVM_FALLTHROUGH;
2400     case ISD::SETOGT: return getBoolConstant(R==APFloat::cmpGreaterThan, dl,
2401                                              VT, OpVT);
2402     case ISD::SETLE:  if (R==APFloat::cmpUnordered)
2403                         return getUNDEF(VT);
2404                       LLVM_FALLTHROUGH;
2405     case ISD::SETOLE: return getBoolConstant(R==APFloat::cmpLessThan ||
2406                                              R==APFloat::cmpEqual, dl, VT,
2407                                              OpVT);
2408     case ISD::SETGE:  if (R==APFloat::cmpUnordered)
2409                         return getUNDEF(VT);
2410                       LLVM_FALLTHROUGH;
2411     case ISD::SETOGE: return getBoolConstant(R==APFloat::cmpGreaterThan ||
2412                                          R==APFloat::cmpEqual, dl, VT, OpVT);
2413     case ISD::SETO:   return getBoolConstant(R!=APFloat::cmpUnordered, dl, VT,
2414                                              OpVT);
2415     case ISD::SETUO:  return getBoolConstant(R==APFloat::cmpUnordered, dl, VT,
2416                                              OpVT);
2417     case ISD::SETUEQ: return getBoolConstant(R==APFloat::cmpUnordered ||
2418                                              R==APFloat::cmpEqual, dl, VT,
2419                                              OpVT);
2420     case ISD::SETUNE: return getBoolConstant(R!=APFloat::cmpEqual, dl, VT,
2421                                              OpVT);
2422     case ISD::SETULT: return getBoolConstant(R==APFloat::cmpUnordered ||
2423                                              R==APFloat::cmpLessThan, dl, VT,
2424                                              OpVT);
2425     case ISD::SETUGT: return getBoolConstant(R==APFloat::cmpGreaterThan ||
2426                                              R==APFloat::cmpUnordered, dl, VT,
2427                                              OpVT);
2428     case ISD::SETULE: return getBoolConstant(R!=APFloat::cmpGreaterThan, dl,
2429                                              VT, OpVT);
2430     case ISD::SETUGE: return getBoolConstant(R!=APFloat::cmpLessThan, dl, VT,
2431                                              OpVT);
2432     }
2433   } else if (N1CFP && OpVT.isSimple() && !N2.isUndef()) {
2434     // Ensure that the constant occurs on the RHS.
2435     ISD::CondCode SwappedCond = ISD::getSetCCSwappedOperands(Cond);
2436     if (!TLI->isCondCodeLegal(SwappedCond, OpVT.getSimpleVT()))
2437       return SDValue();
2438     return getSetCC(dl, VT, N2, N1, SwappedCond);
2439   } else if ((N2CFP && N2CFP->getValueAPF().isNaN()) ||
2440              (OpVT.isFloatingPoint() && (N1.isUndef() || N2.isUndef()))) {
2441     // If an operand is known to be a nan (or undef that could be a nan), we can
2442     // fold it.
2443     // Choosing NaN for the undef will always make unordered comparison succeed
2444     // and ordered comparison fails.
2445     // Matches behavior in llvm::ConstantFoldCompareInstruction.
2446     switch (ISD::getUnorderedFlavor(Cond)) {
2447     default:
2448       llvm_unreachable("Unknown flavor!");
2449     case 0: // Known false.
2450       return getBoolConstant(false, dl, VT, OpVT);
2451     case 1: // Known true.
2452       return getBoolConstant(true, dl, VT, OpVT);
2453     case 2: // Undefined.
2454       return getUNDEF(VT);
2455     }
2456   }
2457 
2458   // Could not fold it.
2459   return SDValue();
2460 }
2461 
2462 /// See if the specified operand can be simplified with the knowledge that only
2463 /// the bits specified by DemandedBits are used.
2464 /// TODO: really we should be making this into the DAG equivalent of
2465 /// SimplifyMultipleUseDemandedBits and not generate any new nodes.
2466 SDValue SelectionDAG::GetDemandedBits(SDValue V, const APInt &DemandedBits) {
2467   EVT VT = V.getValueType();
2468 
2469   if (VT.isScalableVector())
2470     return SDValue();
2471 
2472   APInt DemandedElts = VT.isVector()
2473                            ? APInt::getAllOnes(VT.getVectorNumElements())
2474                            : APInt(1, 1);
2475   return GetDemandedBits(V, DemandedBits, DemandedElts);
2476 }
2477 
2478 /// See if the specified operand can be simplified with the knowledge that only
2479 /// the bits specified by DemandedBits are used in the elements specified by
2480 /// DemandedElts.
2481 /// TODO: really we should be making this into the DAG equivalent of
2482 /// SimplifyMultipleUseDemandedBits and not generate any new nodes.
2483 SDValue SelectionDAG::GetDemandedBits(SDValue V, const APInt &DemandedBits,
2484                                       const APInt &DemandedElts) {
2485   switch (V.getOpcode()) {
2486   default:
2487     return TLI->SimplifyMultipleUseDemandedBits(V, DemandedBits, DemandedElts,
2488                                                 *this);
2489   case ISD::Constant: {
2490     const APInt &CVal = cast<ConstantSDNode>(V)->getAPIntValue();
2491     APInt NewVal = CVal & DemandedBits;
2492     if (NewVal != CVal)
2493       return getConstant(NewVal, SDLoc(V), V.getValueType());
2494     break;
2495   }
2496   case ISD::SRL:
2497     // Only look at single-use SRLs.
2498     if (!V.getNode()->hasOneUse())
2499       break;
2500     if (auto *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
2501       // See if we can recursively simplify the LHS.
2502       unsigned Amt = RHSC->getZExtValue();
2503 
2504       // Watch out for shift count overflow though.
2505       if (Amt >= DemandedBits.getBitWidth())
2506         break;
2507       APInt SrcDemandedBits = DemandedBits << Amt;
2508       if (SDValue SimplifyLHS =
2509               GetDemandedBits(V.getOperand(0), SrcDemandedBits))
2510         return getNode(ISD::SRL, SDLoc(V), V.getValueType(), SimplifyLHS,
2511                        V.getOperand(1));
2512     }
2513     break;
2514   }
2515   return SDValue();
2516 }
2517 
2518 /// SignBitIsZero - Return true if the sign bit of Op is known to be zero.  We
2519 /// use this predicate to simplify operations downstream.
2520 bool SelectionDAG::SignBitIsZero(SDValue Op, unsigned Depth) const {
2521   unsigned BitWidth = Op.getScalarValueSizeInBits();
2522   return MaskedValueIsZero(Op, APInt::getSignMask(BitWidth), Depth);
2523 }
2524 
2525 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero.  We use
2526 /// this predicate to simplify operations downstream.  Mask is known to be zero
2527 /// for bits that V cannot have.
2528 bool SelectionDAG::MaskedValueIsZero(SDValue V, const APInt &Mask,
2529                                      unsigned Depth) const {
2530   return Mask.isSubsetOf(computeKnownBits(V, Depth).Zero);
2531 }
2532 
2533 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero in
2534 /// DemandedElts.  We use this predicate to simplify operations downstream.
2535 /// Mask is known to be zero for bits that V cannot have.
2536 bool SelectionDAG::MaskedValueIsZero(SDValue V, const APInt &Mask,
2537                                      const APInt &DemandedElts,
2538                                      unsigned Depth) const {
2539   return Mask.isSubsetOf(computeKnownBits(V, DemandedElts, Depth).Zero);
2540 }
2541 
2542 /// MaskedValueIsAllOnes - Return true if '(Op & Mask) == Mask'.
2543 bool SelectionDAG::MaskedValueIsAllOnes(SDValue V, const APInt &Mask,
2544                                         unsigned Depth) const {
2545   return Mask.isSubsetOf(computeKnownBits(V, Depth).One);
2546 }
2547 
2548 /// isSplatValue - Return true if the vector V has the same value
2549 /// across all DemandedElts. For scalable vectors it does not make
2550 /// sense to specify which elements are demanded or undefined, therefore
2551 /// they are simply ignored.
2552 bool SelectionDAG::isSplatValue(SDValue V, const APInt &DemandedElts,
2553                                 APInt &UndefElts, unsigned Depth) const {
2554   unsigned Opcode = V.getOpcode();
2555   EVT VT = V.getValueType();
2556   assert(VT.isVector() && "Vector type expected");
2557 
2558   if (!VT.isScalableVector() && !DemandedElts)
2559     return false; // No demanded elts, better to assume we don't know anything.
2560 
2561   if (Depth >= MaxRecursionDepth)
2562     return false; // Limit search depth.
2563 
2564   // Deal with some common cases here that work for both fixed and scalable
2565   // vector types.
2566   switch (Opcode) {
2567   case ISD::SPLAT_VECTOR:
2568     UndefElts = V.getOperand(0).isUndef()
2569                     ? APInt::getAllOnes(DemandedElts.getBitWidth())
2570                     : APInt(DemandedElts.getBitWidth(), 0);
2571     return true;
2572   case ISD::ADD:
2573   case ISD::SUB:
2574   case ISD::AND:
2575   case ISD::XOR:
2576   case ISD::OR: {
2577     APInt UndefLHS, UndefRHS;
2578     SDValue LHS = V.getOperand(0);
2579     SDValue RHS = V.getOperand(1);
2580     if (isSplatValue(LHS, DemandedElts, UndefLHS, Depth + 1) &&
2581         isSplatValue(RHS, DemandedElts, UndefRHS, Depth + 1)) {
2582       UndefElts = UndefLHS | UndefRHS;
2583       return true;
2584     }
2585     return false;
2586   }
2587   case ISD::ABS:
2588   case ISD::TRUNCATE:
2589   case ISD::SIGN_EXTEND:
2590   case ISD::ZERO_EXTEND:
2591     return isSplatValue(V.getOperand(0), DemandedElts, UndefElts, Depth + 1);
2592   default:
2593     if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::INTRINSIC_WO_CHAIN ||
2594         Opcode == ISD::INTRINSIC_W_CHAIN || Opcode == ISD::INTRINSIC_VOID)
2595       return TLI->isSplatValueForTargetNode(V, DemandedElts, UndefElts, Depth);
2596     break;
2597 }
2598 
2599   // We don't support other cases than those above for scalable vectors at
2600   // the moment.
2601   if (VT.isScalableVector())
2602     return false;
2603 
2604   unsigned NumElts = VT.getVectorNumElements();
2605   assert(NumElts == DemandedElts.getBitWidth() && "Vector size mismatch");
2606   UndefElts = APInt::getZero(NumElts);
2607 
2608   switch (Opcode) {
2609   case ISD::BUILD_VECTOR: {
2610     SDValue Scl;
2611     for (unsigned i = 0; i != NumElts; ++i) {
2612       SDValue Op = V.getOperand(i);
2613       if (Op.isUndef()) {
2614         UndefElts.setBit(i);
2615         continue;
2616       }
2617       if (!DemandedElts[i])
2618         continue;
2619       if (Scl && Scl != Op)
2620         return false;
2621       Scl = Op;
2622     }
2623     return true;
2624   }
2625   case ISD::VECTOR_SHUFFLE: {
2626     // Check if this is a shuffle node doing a splat or a shuffle of a splat.
2627     APInt DemandedLHS = APInt::getNullValue(NumElts);
2628     APInt DemandedRHS = APInt::getNullValue(NumElts);
2629     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(V)->getMask();
2630     for (int i = 0; i != (int)NumElts; ++i) {
2631       int M = Mask[i];
2632       if (M < 0) {
2633         UndefElts.setBit(i);
2634         continue;
2635       }
2636       if (!DemandedElts[i])
2637         continue;
2638       if (M < (int)NumElts)
2639         DemandedLHS.setBit(M);
2640       else
2641         DemandedRHS.setBit(M - NumElts);
2642     }
2643 
2644     // If we aren't demanding either op, assume there's no splat.
2645     // If we are demanding both ops, assume there's no splat.
2646     if ((DemandedLHS.isZero() && DemandedRHS.isZero()) ||
2647         (!DemandedLHS.isZero() && !DemandedRHS.isZero()))
2648       return false;
2649 
2650     // See if the demanded elts of the source op is a splat or we only demand
2651     // one element, which should always be a splat.
2652     // TODO: Handle source ops splats with undefs.
2653     auto CheckSplatSrc = [&](SDValue Src, const APInt &SrcElts) {
2654       APInt SrcUndefs;
2655       return (SrcElts.countPopulation() == 1) ||
2656              (isSplatValue(Src, SrcElts, SrcUndefs, Depth + 1) &&
2657               (SrcElts & SrcUndefs).isZero());
2658     };
2659     if (!DemandedLHS.isZero())
2660       return CheckSplatSrc(V.getOperand(0), DemandedLHS);
2661     return CheckSplatSrc(V.getOperand(1), DemandedRHS);
2662   }
2663   case ISD::EXTRACT_SUBVECTOR: {
2664     // Offset the demanded elts by the subvector index.
2665     SDValue Src = V.getOperand(0);
2666     // We don't support scalable vectors at the moment.
2667     if (Src.getValueType().isScalableVector())
2668       return false;
2669     uint64_t Idx = V.getConstantOperandVal(1);
2670     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
2671     APInt UndefSrcElts;
2672     APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts).shl(Idx);
2673     if (isSplatValue(Src, DemandedSrcElts, UndefSrcElts, Depth + 1)) {
2674       UndefElts = UndefSrcElts.extractBits(NumElts, Idx);
2675       return true;
2676     }
2677     break;
2678   }
2679   case ISD::ANY_EXTEND_VECTOR_INREG:
2680   case ISD::SIGN_EXTEND_VECTOR_INREG:
2681   case ISD::ZERO_EXTEND_VECTOR_INREG: {
2682     // Widen the demanded elts by the src element count.
2683     SDValue Src = V.getOperand(0);
2684     // We don't support scalable vectors at the moment.
2685     if (Src.getValueType().isScalableVector())
2686       return false;
2687     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
2688     APInt UndefSrcElts;
2689     APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts);
2690     if (isSplatValue(Src, DemandedSrcElts, UndefSrcElts, Depth + 1)) {
2691       UndefElts = UndefSrcElts.trunc(NumElts);
2692       return true;
2693     }
2694     break;
2695   }
2696   case ISD::BITCAST: {
2697     SDValue Src = V.getOperand(0);
2698     EVT SrcVT = Src.getValueType();
2699     unsigned SrcBitWidth = SrcVT.getScalarSizeInBits();
2700     unsigned BitWidth = VT.getScalarSizeInBits();
2701 
2702     // Ignore bitcasts from unsupported types.
2703     // TODO: Add fp support?
2704     if (!SrcVT.isVector() || !SrcVT.isInteger() || !VT.isInteger())
2705       break;
2706 
2707     // Bitcast 'small element' vector to 'large element' vector.
2708     if ((BitWidth % SrcBitWidth) == 0) {
2709       // See if each sub element is a splat.
2710       unsigned Scale = BitWidth / SrcBitWidth;
2711       unsigned NumSrcElts = SrcVT.getVectorNumElements();
2712       APInt ScaledDemandedElts =
2713           APIntOps::ScaleBitMask(DemandedElts, NumSrcElts);
2714       for (unsigned I = 0; I != Scale; ++I) {
2715         APInt SubUndefElts;
2716         APInt SubDemandedElt = APInt::getOneBitSet(Scale, I);
2717         APInt SubDemandedElts = APInt::getSplat(NumSrcElts, SubDemandedElt);
2718         SubDemandedElts &= ScaledDemandedElts;
2719         if (!isSplatValue(Src, SubDemandedElts, SubUndefElts, Depth + 1))
2720           return false;
2721         // TODO: Add support for merging sub undef elements.
2722         if (SubDemandedElts.isSubsetOf(SubUndefElts))
2723           return false;
2724       }
2725       return true;
2726     }
2727     break;
2728   }
2729   }
2730 
2731   return false;
2732 }
2733 
2734 /// Helper wrapper to main isSplatValue function.
2735 bool SelectionDAG::isSplatValue(SDValue V, bool AllowUndefs) const {
2736   EVT VT = V.getValueType();
2737   assert(VT.isVector() && "Vector type expected");
2738 
2739   APInt UndefElts;
2740   APInt DemandedElts;
2741 
2742   // For now we don't support this with scalable vectors.
2743   if (!VT.isScalableVector())
2744     DemandedElts = APInt::getAllOnes(VT.getVectorNumElements());
2745   return isSplatValue(V, DemandedElts, UndefElts) &&
2746          (AllowUndefs || !UndefElts);
2747 }
2748 
2749 SDValue SelectionDAG::getSplatSourceVector(SDValue V, int &SplatIdx) {
2750   V = peekThroughExtractSubvectors(V);
2751 
2752   EVT VT = V.getValueType();
2753   unsigned Opcode = V.getOpcode();
2754   switch (Opcode) {
2755   default: {
2756     APInt UndefElts;
2757     APInt DemandedElts;
2758 
2759     if (!VT.isScalableVector())
2760       DemandedElts = APInt::getAllOnes(VT.getVectorNumElements());
2761 
2762     if (isSplatValue(V, DemandedElts, UndefElts)) {
2763       if (VT.isScalableVector()) {
2764         // DemandedElts and UndefElts are ignored for scalable vectors, since
2765         // the only supported cases are SPLAT_VECTOR nodes.
2766         SplatIdx = 0;
2767       } else {
2768         // Handle case where all demanded elements are UNDEF.
2769         if (DemandedElts.isSubsetOf(UndefElts)) {
2770           SplatIdx = 0;
2771           return getUNDEF(VT);
2772         }
2773         SplatIdx = (UndefElts & DemandedElts).countTrailingOnes();
2774       }
2775       return V;
2776     }
2777     break;
2778   }
2779   case ISD::SPLAT_VECTOR:
2780     SplatIdx = 0;
2781     return V;
2782   case ISD::VECTOR_SHUFFLE: {
2783     if (VT.isScalableVector())
2784       return SDValue();
2785 
2786     // Check if this is a shuffle node doing a splat.
2787     // TODO - remove this and rely purely on SelectionDAG::isSplatValue,
2788     // getTargetVShiftNode currently struggles without the splat source.
2789     auto *SVN = cast<ShuffleVectorSDNode>(V);
2790     if (!SVN->isSplat())
2791       break;
2792     int Idx = SVN->getSplatIndex();
2793     int NumElts = V.getValueType().getVectorNumElements();
2794     SplatIdx = Idx % NumElts;
2795     return V.getOperand(Idx / NumElts);
2796   }
2797   }
2798 
2799   return SDValue();
2800 }
2801 
2802 SDValue SelectionDAG::getSplatValue(SDValue V, bool LegalTypes) {
2803   int SplatIdx;
2804   if (SDValue SrcVector = getSplatSourceVector(V, SplatIdx)) {
2805     EVT SVT = SrcVector.getValueType().getScalarType();
2806     EVT LegalSVT = SVT;
2807     if (LegalTypes && !TLI->isTypeLegal(SVT)) {
2808       if (!SVT.isInteger())
2809         return SDValue();
2810       LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT);
2811       if (LegalSVT.bitsLT(SVT))
2812         return SDValue();
2813     }
2814     return getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(V), LegalSVT, SrcVector,
2815                    getVectorIdxConstant(SplatIdx, SDLoc(V)));
2816   }
2817   return SDValue();
2818 }
2819 
2820 const APInt *
2821 SelectionDAG::getValidShiftAmountConstant(SDValue V,
2822                                           const APInt &DemandedElts) const {
2823   assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL ||
2824           V.getOpcode() == ISD::SRA) &&
2825          "Unknown shift node");
2826   unsigned BitWidth = V.getScalarValueSizeInBits();
2827   if (ConstantSDNode *SA = isConstOrConstSplat(V.getOperand(1), DemandedElts)) {
2828     // Shifting more than the bitwidth is not valid.
2829     const APInt &ShAmt = SA->getAPIntValue();
2830     if (ShAmt.ult(BitWidth))
2831       return &ShAmt;
2832   }
2833   return nullptr;
2834 }
2835 
2836 const APInt *SelectionDAG::getValidMinimumShiftAmountConstant(
2837     SDValue V, const APInt &DemandedElts) const {
2838   assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL ||
2839           V.getOpcode() == ISD::SRA) &&
2840          "Unknown shift node");
2841   if (const APInt *ValidAmt = getValidShiftAmountConstant(V, DemandedElts))
2842     return ValidAmt;
2843   unsigned BitWidth = V.getScalarValueSizeInBits();
2844   auto *BV = dyn_cast<BuildVectorSDNode>(V.getOperand(1));
2845   if (!BV)
2846     return nullptr;
2847   const APInt *MinShAmt = nullptr;
2848   for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
2849     if (!DemandedElts[i])
2850       continue;
2851     auto *SA = dyn_cast<ConstantSDNode>(BV->getOperand(i));
2852     if (!SA)
2853       return nullptr;
2854     // Shifting more than the bitwidth is not valid.
2855     const APInt &ShAmt = SA->getAPIntValue();
2856     if (ShAmt.uge(BitWidth))
2857       return nullptr;
2858     if (MinShAmt && MinShAmt->ule(ShAmt))
2859       continue;
2860     MinShAmt = &ShAmt;
2861   }
2862   return MinShAmt;
2863 }
2864 
2865 const APInt *SelectionDAG::getValidMaximumShiftAmountConstant(
2866     SDValue V, const APInt &DemandedElts) const {
2867   assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL ||
2868           V.getOpcode() == ISD::SRA) &&
2869          "Unknown shift node");
2870   if (const APInt *ValidAmt = getValidShiftAmountConstant(V, DemandedElts))
2871     return ValidAmt;
2872   unsigned BitWidth = V.getScalarValueSizeInBits();
2873   auto *BV = dyn_cast<BuildVectorSDNode>(V.getOperand(1));
2874   if (!BV)
2875     return nullptr;
2876   const APInt *MaxShAmt = nullptr;
2877   for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
2878     if (!DemandedElts[i])
2879       continue;
2880     auto *SA = dyn_cast<ConstantSDNode>(BV->getOperand(i));
2881     if (!SA)
2882       return nullptr;
2883     // Shifting more than the bitwidth is not valid.
2884     const APInt &ShAmt = SA->getAPIntValue();
2885     if (ShAmt.uge(BitWidth))
2886       return nullptr;
2887     if (MaxShAmt && MaxShAmt->uge(ShAmt))
2888       continue;
2889     MaxShAmt = &ShAmt;
2890   }
2891   return MaxShAmt;
2892 }
2893 
2894 /// Determine which bits of Op are known to be either zero or one and return
2895 /// them in Known. For vectors, the known bits are those that are shared by
2896 /// every vector element.
2897 KnownBits SelectionDAG::computeKnownBits(SDValue Op, unsigned Depth) const {
2898   EVT VT = Op.getValueType();
2899 
2900   // TOOD: Until we have a plan for how to represent demanded elements for
2901   // scalable vectors, we can just bail out for now.
2902   if (Op.getValueType().isScalableVector()) {
2903     unsigned BitWidth = Op.getScalarValueSizeInBits();
2904     return KnownBits(BitWidth);
2905   }
2906 
2907   APInt DemandedElts = VT.isVector()
2908                            ? APInt::getAllOnes(VT.getVectorNumElements())
2909                            : APInt(1, 1);
2910   return computeKnownBits(Op, DemandedElts, Depth);
2911 }
2912 
2913 /// Determine which bits of Op are known to be either zero or one and return
2914 /// them in Known. The DemandedElts argument allows us to only collect the known
2915 /// bits that are shared by the requested vector elements.
2916 KnownBits SelectionDAG::computeKnownBits(SDValue Op, const APInt &DemandedElts,
2917                                          unsigned Depth) const {
2918   unsigned BitWidth = Op.getScalarValueSizeInBits();
2919 
2920   KnownBits Known(BitWidth);   // Don't know anything.
2921 
2922   // TOOD: Until we have a plan for how to represent demanded elements for
2923   // scalable vectors, we can just bail out for now.
2924   if (Op.getValueType().isScalableVector())
2925     return Known;
2926 
2927   if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
2928     // We know all of the bits for a constant!
2929     return KnownBits::makeConstant(C->getAPIntValue());
2930   }
2931   if (auto *C = dyn_cast<ConstantFPSDNode>(Op)) {
2932     // We know all of the bits for a constant fp!
2933     return KnownBits::makeConstant(C->getValueAPF().bitcastToAPInt());
2934   }
2935 
2936   if (Depth >= MaxRecursionDepth)
2937     return Known;  // Limit search depth.
2938 
2939   KnownBits Known2;
2940   unsigned NumElts = DemandedElts.getBitWidth();
2941   assert((!Op.getValueType().isVector() ||
2942           NumElts == Op.getValueType().getVectorNumElements()) &&
2943          "Unexpected vector size");
2944 
2945   if (!DemandedElts)
2946     return Known;  // No demanded elts, better to assume we don't know anything.
2947 
2948   unsigned Opcode = Op.getOpcode();
2949   switch (Opcode) {
2950   case ISD::BUILD_VECTOR:
2951     // Collect the known bits that are shared by every demanded vector element.
2952     Known.Zero.setAllBits(); Known.One.setAllBits();
2953     for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
2954       if (!DemandedElts[i])
2955         continue;
2956 
2957       SDValue SrcOp = Op.getOperand(i);
2958       Known2 = computeKnownBits(SrcOp, Depth + 1);
2959 
2960       // BUILD_VECTOR can implicitly truncate sources, we must handle this.
2961       if (SrcOp.getValueSizeInBits() != BitWidth) {
2962         assert(SrcOp.getValueSizeInBits() > BitWidth &&
2963                "Expected BUILD_VECTOR implicit truncation");
2964         Known2 = Known2.trunc(BitWidth);
2965       }
2966 
2967       // Known bits are the values that are shared by every demanded element.
2968       Known = KnownBits::commonBits(Known, Known2);
2969 
2970       // If we don't know any bits, early out.
2971       if (Known.isUnknown())
2972         break;
2973     }
2974     break;
2975   case ISD::VECTOR_SHUFFLE: {
2976     // Collect the known bits that are shared by every vector element referenced
2977     // by the shuffle.
2978     APInt DemandedLHS(NumElts, 0), DemandedRHS(NumElts, 0);
2979     Known.Zero.setAllBits(); Known.One.setAllBits();
2980     const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op);
2981     assert(NumElts == SVN->getMask().size() && "Unexpected vector size");
2982     for (unsigned i = 0; i != NumElts; ++i) {
2983       if (!DemandedElts[i])
2984         continue;
2985 
2986       int M = SVN->getMaskElt(i);
2987       if (M < 0) {
2988         // For UNDEF elements, we don't know anything about the common state of
2989         // the shuffle result.
2990         Known.resetAll();
2991         DemandedLHS.clearAllBits();
2992         DemandedRHS.clearAllBits();
2993         break;
2994       }
2995 
2996       if ((unsigned)M < NumElts)
2997         DemandedLHS.setBit((unsigned)M % NumElts);
2998       else
2999         DemandedRHS.setBit((unsigned)M % NumElts);
3000     }
3001     // Known bits are the values that are shared by every demanded element.
3002     if (!!DemandedLHS) {
3003       SDValue LHS = Op.getOperand(0);
3004       Known2 = computeKnownBits(LHS, DemandedLHS, Depth + 1);
3005       Known = KnownBits::commonBits(Known, Known2);
3006     }
3007     // If we don't know any bits, early out.
3008     if (Known.isUnknown())
3009       break;
3010     if (!!DemandedRHS) {
3011       SDValue RHS = Op.getOperand(1);
3012       Known2 = computeKnownBits(RHS, DemandedRHS, Depth + 1);
3013       Known = KnownBits::commonBits(Known, Known2);
3014     }
3015     break;
3016   }
3017   case ISD::CONCAT_VECTORS: {
3018     // Split DemandedElts and test each of the demanded subvectors.
3019     Known.Zero.setAllBits(); Known.One.setAllBits();
3020     EVT SubVectorVT = Op.getOperand(0).getValueType();
3021     unsigned NumSubVectorElts = SubVectorVT.getVectorNumElements();
3022     unsigned NumSubVectors = Op.getNumOperands();
3023     for (unsigned i = 0; i != NumSubVectors; ++i) {
3024       APInt DemandedSub =
3025           DemandedElts.extractBits(NumSubVectorElts, i * NumSubVectorElts);
3026       if (!!DemandedSub) {
3027         SDValue Sub = Op.getOperand(i);
3028         Known2 = computeKnownBits(Sub, DemandedSub, Depth + 1);
3029         Known = KnownBits::commonBits(Known, Known2);
3030       }
3031       // If we don't know any bits, early out.
3032       if (Known.isUnknown())
3033         break;
3034     }
3035     break;
3036   }
3037   case ISD::INSERT_SUBVECTOR: {
3038     // Demand any elements from the subvector and the remainder from the src its
3039     // inserted into.
3040     SDValue Src = Op.getOperand(0);
3041     SDValue Sub = Op.getOperand(1);
3042     uint64_t Idx = Op.getConstantOperandVal(2);
3043     unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
3044     APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
3045     APInt DemandedSrcElts = DemandedElts;
3046     DemandedSrcElts.insertBits(APInt::getZero(NumSubElts), Idx);
3047 
3048     Known.One.setAllBits();
3049     Known.Zero.setAllBits();
3050     if (!!DemandedSubElts) {
3051       Known = computeKnownBits(Sub, DemandedSubElts, Depth + 1);
3052       if (Known.isUnknown())
3053         break; // early-out.
3054     }
3055     if (!!DemandedSrcElts) {
3056       Known2 = computeKnownBits(Src, DemandedSrcElts, Depth + 1);
3057       Known = KnownBits::commonBits(Known, Known2);
3058     }
3059     break;
3060   }
3061   case ISD::EXTRACT_SUBVECTOR: {
3062     // Offset the demanded elts by the subvector index.
3063     SDValue Src = Op.getOperand(0);
3064     // Bail until we can represent demanded elements for scalable vectors.
3065     if (Src.getValueType().isScalableVector())
3066       break;
3067     uint64_t Idx = Op.getConstantOperandVal(1);
3068     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
3069     APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts).shl(Idx);
3070     Known = computeKnownBits(Src, DemandedSrcElts, Depth + 1);
3071     break;
3072   }
3073   case ISD::SCALAR_TO_VECTOR: {
3074     // We know about scalar_to_vector as much as we know about it source,
3075     // which becomes the first element of otherwise unknown vector.
3076     if (DemandedElts != 1)
3077       break;
3078 
3079     SDValue N0 = Op.getOperand(0);
3080     Known = computeKnownBits(N0, Depth + 1);
3081     if (N0.getValueSizeInBits() != BitWidth)
3082       Known = Known.trunc(BitWidth);
3083 
3084     break;
3085   }
3086   case ISD::BITCAST: {
3087     SDValue N0 = Op.getOperand(0);
3088     EVT SubVT = N0.getValueType();
3089     unsigned SubBitWidth = SubVT.getScalarSizeInBits();
3090 
3091     // Ignore bitcasts from unsupported types.
3092     if (!(SubVT.isInteger() || SubVT.isFloatingPoint()))
3093       break;
3094 
3095     // Fast handling of 'identity' bitcasts.
3096     if (BitWidth == SubBitWidth) {
3097       Known = computeKnownBits(N0, DemandedElts, Depth + 1);
3098       break;
3099     }
3100 
3101     bool IsLE = getDataLayout().isLittleEndian();
3102 
3103     // Bitcast 'small element' vector to 'large element' scalar/vector.
3104     if ((BitWidth % SubBitWidth) == 0) {
3105       assert(N0.getValueType().isVector() && "Expected bitcast from vector");
3106 
3107       // Collect known bits for the (larger) output by collecting the known
3108       // bits from each set of sub elements and shift these into place.
3109       // We need to separately call computeKnownBits for each set of
3110       // sub elements as the knownbits for each is likely to be different.
3111       unsigned SubScale = BitWidth / SubBitWidth;
3112       APInt SubDemandedElts(NumElts * SubScale, 0);
3113       for (unsigned i = 0; i != NumElts; ++i)
3114         if (DemandedElts[i])
3115           SubDemandedElts.setBit(i * SubScale);
3116 
3117       for (unsigned i = 0; i != SubScale; ++i) {
3118         Known2 = computeKnownBits(N0, SubDemandedElts.shl(i),
3119                          Depth + 1);
3120         unsigned Shifts = IsLE ? i : SubScale - 1 - i;
3121         Known.insertBits(Known2, SubBitWidth * Shifts);
3122       }
3123     }
3124 
3125     // Bitcast 'large element' scalar/vector to 'small element' vector.
3126     if ((SubBitWidth % BitWidth) == 0) {
3127       assert(Op.getValueType().isVector() && "Expected bitcast to vector");
3128 
3129       // Collect known bits for the (smaller) output by collecting the known
3130       // bits from the overlapping larger input elements and extracting the
3131       // sub sections we actually care about.
3132       unsigned SubScale = SubBitWidth / BitWidth;
3133       APInt SubDemandedElts =
3134           APIntOps::ScaleBitMask(DemandedElts, NumElts / SubScale);
3135       Known2 = computeKnownBits(N0, SubDemandedElts, Depth + 1);
3136 
3137       Known.Zero.setAllBits(); Known.One.setAllBits();
3138       for (unsigned i = 0; i != NumElts; ++i)
3139         if (DemandedElts[i]) {
3140           unsigned Shifts = IsLE ? i : NumElts - 1 - i;
3141           unsigned Offset = (Shifts % SubScale) * BitWidth;
3142           Known = KnownBits::commonBits(Known,
3143                                         Known2.extractBits(BitWidth, Offset));
3144           // If we don't know any bits, early out.
3145           if (Known.isUnknown())
3146             break;
3147         }
3148     }
3149     break;
3150   }
3151   case ISD::AND:
3152     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3153     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3154 
3155     Known &= Known2;
3156     break;
3157   case ISD::OR:
3158     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3159     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3160 
3161     Known |= Known2;
3162     break;
3163   case ISD::XOR:
3164     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3165     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3166 
3167     Known ^= Known2;
3168     break;
3169   case ISD::MUL: {
3170     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3171     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3172     bool SelfMultiply = Op.getOperand(0) == Op.getOperand(1);
3173     // TODO: SelfMultiply can be poison, but not undef.
3174     if (SelfMultiply)
3175       SelfMultiply &= isGuaranteedNotToBeUndefOrPoison(
3176           Op.getOperand(0), DemandedElts, false, Depth + 1);
3177     Known = KnownBits::mul(Known, Known2, SelfMultiply);
3178     break;
3179   }
3180   case ISD::MULHU: {
3181     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3182     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3183     Known = KnownBits::mulhu(Known, Known2);
3184     break;
3185   }
3186   case ISD::MULHS: {
3187     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3188     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3189     Known = KnownBits::mulhs(Known, Known2);
3190     break;
3191   }
3192   case ISD::UMUL_LOHI: {
3193     assert((Op.getResNo() == 0 || Op.getResNo() == 1) && "Unknown result");
3194     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3195     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3196     bool SelfMultiply = Op.getOperand(0) == Op.getOperand(1);
3197     if (Op.getResNo() == 0)
3198       Known = KnownBits::mul(Known, Known2, SelfMultiply);
3199     else
3200       Known = KnownBits::mulhu(Known, Known2);
3201     break;
3202   }
3203   case ISD::SMUL_LOHI: {
3204     assert((Op.getResNo() == 0 || Op.getResNo() == 1) && "Unknown result");
3205     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3206     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3207     bool SelfMultiply = Op.getOperand(0) == Op.getOperand(1);
3208     if (Op.getResNo() == 0)
3209       Known = KnownBits::mul(Known, Known2, SelfMultiply);
3210     else
3211       Known = KnownBits::mulhs(Known, Known2);
3212     break;
3213   }
3214   case ISD::UDIV: {
3215     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3216     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3217     Known = KnownBits::udiv(Known, Known2);
3218     break;
3219   }
3220   case ISD::AVGCEILU: {
3221     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3222     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3223     Known = Known.zext(BitWidth + 1);
3224     Known2 = Known2.zext(BitWidth + 1);
3225     KnownBits One = KnownBits::makeConstant(APInt(1, 1));
3226     Known = KnownBits::computeForAddCarry(Known, Known2, One);
3227     Known = Known.extractBits(BitWidth, 1);
3228     break;
3229   }
3230   case ISD::SELECT:
3231   case ISD::VSELECT:
3232     Known = computeKnownBits(Op.getOperand(2), DemandedElts, Depth+1);
3233     // If we don't know any bits, early out.
3234     if (Known.isUnknown())
3235       break;
3236     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth+1);
3237 
3238     // Only known if known in both the LHS and RHS.
3239     Known = KnownBits::commonBits(Known, Known2);
3240     break;
3241   case ISD::SELECT_CC:
3242     Known = computeKnownBits(Op.getOperand(3), DemandedElts, Depth+1);
3243     // If we don't know any bits, early out.
3244     if (Known.isUnknown())
3245       break;
3246     Known2 = computeKnownBits(Op.getOperand(2), DemandedElts, Depth+1);
3247 
3248     // Only known if known in both the LHS and RHS.
3249     Known = KnownBits::commonBits(Known, Known2);
3250     break;
3251   case ISD::SMULO:
3252   case ISD::UMULO:
3253     if (Op.getResNo() != 1)
3254       break;
3255     // The boolean result conforms to getBooleanContents.
3256     // If we know the result of a setcc has the top bits zero, use this info.
3257     // We know that we have an integer-based boolean since these operations
3258     // are only available for integer.
3259     if (TLI->getBooleanContents(Op.getValueType().isVector(), false) ==
3260             TargetLowering::ZeroOrOneBooleanContent &&
3261         BitWidth > 1)
3262       Known.Zero.setBitsFrom(1);
3263     break;
3264   case ISD::SETCC:
3265   case ISD::STRICT_FSETCC:
3266   case ISD::STRICT_FSETCCS: {
3267     unsigned OpNo = Op->isStrictFPOpcode() ? 1 : 0;
3268     // If we know the result of a setcc has the top bits zero, use this info.
3269     if (TLI->getBooleanContents(Op.getOperand(OpNo).getValueType()) ==
3270             TargetLowering::ZeroOrOneBooleanContent &&
3271         BitWidth > 1)
3272       Known.Zero.setBitsFrom(1);
3273     break;
3274   }
3275   case ISD::SHL:
3276     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3277     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3278     Known = KnownBits::shl(Known, Known2);
3279 
3280     // Minimum shift low bits are known zero.
3281     if (const APInt *ShMinAmt =
3282             getValidMinimumShiftAmountConstant(Op, DemandedElts))
3283       Known.Zero.setLowBits(ShMinAmt->getZExtValue());
3284     break;
3285   case ISD::SRL:
3286     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3287     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3288     Known = KnownBits::lshr(Known, Known2);
3289 
3290     // Minimum shift high bits are known zero.
3291     if (const APInt *ShMinAmt =
3292             getValidMinimumShiftAmountConstant(Op, DemandedElts))
3293       Known.Zero.setHighBits(ShMinAmt->getZExtValue());
3294     break;
3295   case ISD::SRA:
3296     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3297     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3298     Known = KnownBits::ashr(Known, Known2);
3299     // TODO: Add minimum shift high known sign bits.
3300     break;
3301   case ISD::FSHL:
3302   case ISD::FSHR:
3303     if (ConstantSDNode *C = isConstOrConstSplat(Op.getOperand(2), DemandedElts)) {
3304       unsigned Amt = C->getAPIntValue().urem(BitWidth);
3305 
3306       // For fshl, 0-shift returns the 1st arg.
3307       // For fshr, 0-shift returns the 2nd arg.
3308       if (Amt == 0) {
3309         Known = computeKnownBits(Op.getOperand(Opcode == ISD::FSHL ? 0 : 1),
3310                                  DemandedElts, Depth + 1);
3311         break;
3312       }
3313 
3314       // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW)))
3315       // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW))
3316       Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3317       Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3318       if (Opcode == ISD::FSHL) {
3319         Known.One <<= Amt;
3320         Known.Zero <<= Amt;
3321         Known2.One.lshrInPlace(BitWidth - Amt);
3322         Known2.Zero.lshrInPlace(BitWidth - Amt);
3323       } else {
3324         Known.One <<= BitWidth - Amt;
3325         Known.Zero <<= BitWidth - Amt;
3326         Known2.One.lshrInPlace(Amt);
3327         Known2.Zero.lshrInPlace(Amt);
3328       }
3329       Known.One |= Known2.One;
3330       Known.Zero |= Known2.Zero;
3331     }
3332     break;
3333   case ISD::SIGN_EXTEND_INREG: {
3334     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3335     EVT EVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
3336     Known = Known.sextInReg(EVT.getScalarSizeInBits());
3337     break;
3338   }
3339   case ISD::CTTZ:
3340   case ISD::CTTZ_ZERO_UNDEF: {
3341     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3342     // If we have a known 1, its position is our upper bound.
3343     unsigned PossibleTZ = Known2.countMaxTrailingZeros();
3344     unsigned LowBits = Log2_32(PossibleTZ) + 1;
3345     Known.Zero.setBitsFrom(LowBits);
3346     break;
3347   }
3348   case ISD::CTLZ:
3349   case ISD::CTLZ_ZERO_UNDEF: {
3350     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3351     // If we have a known 1, its position is our upper bound.
3352     unsigned PossibleLZ = Known2.countMaxLeadingZeros();
3353     unsigned LowBits = Log2_32(PossibleLZ) + 1;
3354     Known.Zero.setBitsFrom(LowBits);
3355     break;
3356   }
3357   case ISD::CTPOP: {
3358     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3359     // If we know some of the bits are zero, they can't be one.
3360     unsigned PossibleOnes = Known2.countMaxPopulation();
3361     Known.Zero.setBitsFrom(Log2_32(PossibleOnes) + 1);
3362     break;
3363   }
3364   case ISD::PARITY: {
3365     // Parity returns 0 everywhere but the LSB.
3366     Known.Zero.setBitsFrom(1);
3367     break;
3368   }
3369   case ISD::LOAD: {
3370     LoadSDNode *LD = cast<LoadSDNode>(Op);
3371     const Constant *Cst = TLI->getTargetConstantFromLoad(LD);
3372     if (ISD::isNON_EXTLoad(LD) && Cst) {
3373       // Determine any common known bits from the loaded constant pool value.
3374       Type *CstTy = Cst->getType();
3375       if ((NumElts * BitWidth) == CstTy->getPrimitiveSizeInBits()) {
3376         // If its a vector splat, then we can (quickly) reuse the scalar path.
3377         // NOTE: We assume all elements match and none are UNDEF.
3378         if (CstTy->isVectorTy()) {
3379           if (const Constant *Splat = Cst->getSplatValue()) {
3380             Cst = Splat;
3381             CstTy = Cst->getType();
3382           }
3383         }
3384         // TODO - do we need to handle different bitwidths?
3385         if (CstTy->isVectorTy() && BitWidth == CstTy->getScalarSizeInBits()) {
3386           // Iterate across all vector elements finding common known bits.
3387           Known.One.setAllBits();
3388           Known.Zero.setAllBits();
3389           for (unsigned i = 0; i != NumElts; ++i) {
3390             if (!DemandedElts[i])
3391               continue;
3392             if (Constant *Elt = Cst->getAggregateElement(i)) {
3393               if (auto *CInt = dyn_cast<ConstantInt>(Elt)) {
3394                 const APInt &Value = CInt->getValue();
3395                 Known.One &= Value;
3396                 Known.Zero &= ~Value;
3397                 continue;
3398               }
3399               if (auto *CFP = dyn_cast<ConstantFP>(Elt)) {
3400                 APInt Value = CFP->getValueAPF().bitcastToAPInt();
3401                 Known.One &= Value;
3402                 Known.Zero &= ~Value;
3403                 continue;
3404               }
3405             }
3406             Known.One.clearAllBits();
3407             Known.Zero.clearAllBits();
3408             break;
3409           }
3410         } else if (BitWidth == CstTy->getPrimitiveSizeInBits()) {
3411           if (auto *CInt = dyn_cast<ConstantInt>(Cst)) {
3412             Known = KnownBits::makeConstant(CInt->getValue());
3413           } else if (auto *CFP = dyn_cast<ConstantFP>(Cst)) {
3414             Known =
3415                 KnownBits::makeConstant(CFP->getValueAPF().bitcastToAPInt());
3416           }
3417         }
3418       }
3419     } else if (ISD::isZEXTLoad(Op.getNode()) && Op.getResNo() == 0) {
3420       // If this is a ZEXTLoad and we are looking at the loaded value.
3421       EVT VT = LD->getMemoryVT();
3422       unsigned MemBits = VT.getScalarSizeInBits();
3423       Known.Zero.setBitsFrom(MemBits);
3424     } else if (const MDNode *Ranges = LD->getRanges()) {
3425       if (LD->getExtensionType() == ISD::NON_EXTLOAD)
3426         computeKnownBitsFromRangeMetadata(*Ranges, Known);
3427     }
3428     break;
3429   }
3430   case ISD::ZERO_EXTEND_VECTOR_INREG: {
3431     EVT InVT = Op.getOperand(0).getValueType();
3432     APInt InDemandedElts = DemandedElts.zext(InVT.getVectorNumElements());
3433     Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1);
3434     Known = Known.zext(BitWidth);
3435     break;
3436   }
3437   case ISD::ZERO_EXTEND: {
3438     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3439     Known = Known.zext(BitWidth);
3440     break;
3441   }
3442   case ISD::SIGN_EXTEND_VECTOR_INREG: {
3443     EVT InVT = Op.getOperand(0).getValueType();
3444     APInt InDemandedElts = DemandedElts.zext(InVT.getVectorNumElements());
3445     Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1);
3446     // If the sign bit is known to be zero or one, then sext will extend
3447     // it to the top bits, else it will just zext.
3448     Known = Known.sext(BitWidth);
3449     break;
3450   }
3451   case ISD::SIGN_EXTEND: {
3452     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3453     // If the sign bit is known to be zero or one, then sext will extend
3454     // it to the top bits, else it will just zext.
3455     Known = Known.sext(BitWidth);
3456     break;
3457   }
3458   case ISD::ANY_EXTEND_VECTOR_INREG: {
3459     EVT InVT = Op.getOperand(0).getValueType();
3460     APInt InDemandedElts = DemandedElts.zext(InVT.getVectorNumElements());
3461     Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1);
3462     Known = Known.anyext(BitWidth);
3463     break;
3464   }
3465   case ISD::ANY_EXTEND: {
3466     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3467     Known = Known.anyext(BitWidth);
3468     break;
3469   }
3470   case ISD::TRUNCATE: {
3471     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3472     Known = Known.trunc(BitWidth);
3473     break;
3474   }
3475   case ISD::AssertZext: {
3476     EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
3477     APInt InMask = APInt::getLowBitsSet(BitWidth, VT.getSizeInBits());
3478     Known = computeKnownBits(Op.getOperand(0), Depth+1);
3479     Known.Zero |= (~InMask);
3480     Known.One  &= (~Known.Zero);
3481     break;
3482   }
3483   case ISD::AssertAlign: {
3484     unsigned LogOfAlign = Log2(cast<AssertAlignSDNode>(Op)->getAlign());
3485     assert(LogOfAlign != 0);
3486 
3487     // TODO: Should use maximum with source
3488     // If a node is guaranteed to be aligned, set low zero bits accordingly as
3489     // well as clearing one bits.
3490     Known.Zero.setLowBits(LogOfAlign);
3491     Known.One.clearLowBits(LogOfAlign);
3492     break;
3493   }
3494   case ISD::FGETSIGN:
3495     // All bits are zero except the low bit.
3496     Known.Zero.setBitsFrom(1);
3497     break;
3498   case ISD::USUBO:
3499   case ISD::SSUBO:
3500     if (Op.getResNo() == 1) {
3501       // If we know the result of a setcc has the top bits zero, use this info.
3502       if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) ==
3503               TargetLowering::ZeroOrOneBooleanContent &&
3504           BitWidth > 1)
3505         Known.Zero.setBitsFrom(1);
3506       break;
3507     }
3508     LLVM_FALLTHROUGH;
3509   case ISD::SUB:
3510   case ISD::SUBC: {
3511     assert(Op.getResNo() == 0 &&
3512            "We only compute knownbits for the difference here.");
3513 
3514     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3515     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3516     Known = KnownBits::computeForAddSub(/* Add */ false, /* NSW */ false,
3517                                         Known, Known2);
3518     break;
3519   }
3520   case ISD::UADDO:
3521   case ISD::SADDO:
3522   case ISD::ADDCARRY:
3523     if (Op.getResNo() == 1) {
3524       // If we know the result of a setcc has the top bits zero, use this info.
3525       if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) ==
3526               TargetLowering::ZeroOrOneBooleanContent &&
3527           BitWidth > 1)
3528         Known.Zero.setBitsFrom(1);
3529       break;
3530     }
3531     LLVM_FALLTHROUGH;
3532   case ISD::ADD:
3533   case ISD::ADDC:
3534   case ISD::ADDE: {
3535     assert(Op.getResNo() == 0 && "We only compute knownbits for the sum here.");
3536 
3537     // With ADDE and ADDCARRY, a carry bit may be added in.
3538     KnownBits Carry(1);
3539     if (Opcode == ISD::ADDE)
3540       // Can't track carry from glue, set carry to unknown.
3541       Carry.resetAll();
3542     else if (Opcode == ISD::ADDCARRY)
3543       // TODO: Compute known bits for the carry operand. Not sure if it is worth
3544       // the trouble (how often will we find a known carry bit). And I haven't
3545       // tested this very much yet, but something like this might work:
3546       //   Carry = computeKnownBits(Op.getOperand(2), DemandedElts, Depth + 1);
3547       //   Carry = Carry.zextOrTrunc(1, false);
3548       Carry.resetAll();
3549     else
3550       Carry.setAllZero();
3551 
3552     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3553     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3554     Known = KnownBits::computeForAddCarry(Known, Known2, Carry);
3555     break;
3556   }
3557   case ISD::SREM: {
3558     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3559     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3560     Known = KnownBits::srem(Known, Known2);
3561     break;
3562   }
3563   case ISD::UREM: {
3564     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3565     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3566     Known = KnownBits::urem(Known, Known2);
3567     break;
3568   }
3569   case ISD::EXTRACT_ELEMENT: {
3570     Known = computeKnownBits(Op.getOperand(0), Depth+1);
3571     const unsigned Index = Op.getConstantOperandVal(1);
3572     const unsigned EltBitWidth = Op.getValueSizeInBits();
3573 
3574     // Remove low part of known bits mask
3575     Known.Zero = Known.Zero.getHiBits(Known.getBitWidth() - Index * EltBitWidth);
3576     Known.One = Known.One.getHiBits(Known.getBitWidth() - Index * EltBitWidth);
3577 
3578     // Remove high part of known bit mask
3579     Known = Known.trunc(EltBitWidth);
3580     break;
3581   }
3582   case ISD::EXTRACT_VECTOR_ELT: {
3583     SDValue InVec = Op.getOperand(0);
3584     SDValue EltNo = Op.getOperand(1);
3585     EVT VecVT = InVec.getValueType();
3586     // computeKnownBits not yet implemented for scalable vectors.
3587     if (VecVT.isScalableVector())
3588       break;
3589     const unsigned EltBitWidth = VecVT.getScalarSizeInBits();
3590     const unsigned NumSrcElts = VecVT.getVectorNumElements();
3591 
3592     // If BitWidth > EltBitWidth the value is anyext:ed. So we do not know
3593     // anything about the extended bits.
3594     if (BitWidth > EltBitWidth)
3595       Known = Known.trunc(EltBitWidth);
3596 
3597     // If we know the element index, just demand that vector element, else for
3598     // an unknown element index, ignore DemandedElts and demand them all.
3599     APInt DemandedSrcElts = APInt::getAllOnes(NumSrcElts);
3600     auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
3601     if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts))
3602       DemandedSrcElts =
3603           APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue());
3604 
3605     Known = computeKnownBits(InVec, DemandedSrcElts, Depth + 1);
3606     if (BitWidth > EltBitWidth)
3607       Known = Known.anyext(BitWidth);
3608     break;
3609   }
3610   case ISD::INSERT_VECTOR_ELT: {
3611     // If we know the element index, split the demand between the
3612     // source vector and the inserted element, otherwise assume we need
3613     // the original demanded vector elements and the value.
3614     SDValue InVec = Op.getOperand(0);
3615     SDValue InVal = Op.getOperand(1);
3616     SDValue EltNo = Op.getOperand(2);
3617     bool DemandedVal = true;
3618     APInt DemandedVecElts = DemandedElts;
3619     auto *CEltNo = dyn_cast<ConstantSDNode>(EltNo);
3620     if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) {
3621       unsigned EltIdx = CEltNo->getZExtValue();
3622       DemandedVal = !!DemandedElts[EltIdx];
3623       DemandedVecElts.clearBit(EltIdx);
3624     }
3625     Known.One.setAllBits();
3626     Known.Zero.setAllBits();
3627     if (DemandedVal) {
3628       Known2 = computeKnownBits(InVal, Depth + 1);
3629       Known = KnownBits::commonBits(Known, Known2.zextOrTrunc(BitWidth));
3630     }
3631     if (!!DemandedVecElts) {
3632       Known2 = computeKnownBits(InVec, DemandedVecElts, Depth + 1);
3633       Known = KnownBits::commonBits(Known, Known2);
3634     }
3635     break;
3636   }
3637   case ISD::BITREVERSE: {
3638     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3639     Known = Known2.reverseBits();
3640     break;
3641   }
3642   case ISD::BSWAP: {
3643     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3644     Known = Known2.byteSwap();
3645     break;
3646   }
3647   case ISD::ABS: {
3648     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3649     Known = Known2.abs();
3650     break;
3651   }
3652   case ISD::USUBSAT: {
3653     // The result of usubsat will never be larger than the LHS.
3654     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3655     Known.Zero.setHighBits(Known2.countMinLeadingZeros());
3656     break;
3657   }
3658   case ISD::UMIN: {
3659     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3660     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3661     Known = KnownBits::umin(Known, Known2);
3662     break;
3663   }
3664   case ISD::UMAX: {
3665     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3666     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3667     Known = KnownBits::umax(Known, Known2);
3668     break;
3669   }
3670   case ISD::SMIN:
3671   case ISD::SMAX: {
3672     // If we have a clamp pattern, we know that the number of sign bits will be
3673     // the minimum of the clamp min/max range.
3674     bool IsMax = (Opcode == ISD::SMAX);
3675     ConstantSDNode *CstLow = nullptr, *CstHigh = nullptr;
3676     if ((CstLow = isConstOrConstSplat(Op.getOperand(1), DemandedElts)))
3677       if (Op.getOperand(0).getOpcode() == (IsMax ? ISD::SMIN : ISD::SMAX))
3678         CstHigh =
3679             isConstOrConstSplat(Op.getOperand(0).getOperand(1), DemandedElts);
3680     if (CstLow && CstHigh) {
3681       if (!IsMax)
3682         std::swap(CstLow, CstHigh);
3683 
3684       const APInt &ValueLow = CstLow->getAPIntValue();
3685       const APInt &ValueHigh = CstHigh->getAPIntValue();
3686       if (ValueLow.sle(ValueHigh)) {
3687         unsigned LowSignBits = ValueLow.getNumSignBits();
3688         unsigned HighSignBits = ValueHigh.getNumSignBits();
3689         unsigned MinSignBits = std::min(LowSignBits, HighSignBits);
3690         if (ValueLow.isNegative() && ValueHigh.isNegative()) {
3691           Known.One.setHighBits(MinSignBits);
3692           break;
3693         }
3694         if (ValueLow.isNonNegative() && ValueHigh.isNonNegative()) {
3695           Known.Zero.setHighBits(MinSignBits);
3696           break;
3697         }
3698       }
3699     }
3700     // For SMAX, if CstLow is non-negative we know the result will be
3701     // non-negative and thus all sign bits are 0.
3702     // TODO: There's an equivalent of this for smin with negative constant for
3703     // known ones.
3704     if (IsMax && CstLow) {
3705       const APInt &ValueLow = CstLow->getAPIntValue();
3706       if (ValueLow.isNonNegative()) {
3707         unsigned SignBits = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
3708         Known.Zero.setHighBits(std::min(SignBits, ValueLow.getNumSignBits()));
3709         break;
3710       }
3711     }
3712 
3713     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3714     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3715     if (IsMax)
3716       Known = KnownBits::smax(Known, Known2);
3717     else
3718       Known = KnownBits::smin(Known, Known2);
3719     break;
3720   }
3721   case ISD::FP_TO_UINT_SAT: {
3722     // FP_TO_UINT_SAT produces an unsigned value that fits in the saturating VT.
3723     EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
3724     Known.Zero |= APInt::getBitsSetFrom(BitWidth, VT.getScalarSizeInBits());
3725     break;
3726   }
3727   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
3728     if (Op.getResNo() == 1) {
3729       // The boolean result conforms to getBooleanContents.
3730       // If we know the result of a setcc has the top bits zero, use this info.
3731       // We know that we have an integer-based boolean since these operations
3732       // are only available for integer.
3733       if (TLI->getBooleanContents(Op.getValueType().isVector(), false) ==
3734               TargetLowering::ZeroOrOneBooleanContent &&
3735           BitWidth > 1)
3736         Known.Zero.setBitsFrom(1);
3737       break;
3738     }
3739     LLVM_FALLTHROUGH;
3740   case ISD::ATOMIC_CMP_SWAP:
3741   case ISD::ATOMIC_SWAP:
3742   case ISD::ATOMIC_LOAD_ADD:
3743   case ISD::ATOMIC_LOAD_SUB:
3744   case ISD::ATOMIC_LOAD_AND:
3745   case ISD::ATOMIC_LOAD_CLR:
3746   case ISD::ATOMIC_LOAD_OR:
3747   case ISD::ATOMIC_LOAD_XOR:
3748   case ISD::ATOMIC_LOAD_NAND:
3749   case ISD::ATOMIC_LOAD_MIN:
3750   case ISD::ATOMIC_LOAD_MAX:
3751   case ISD::ATOMIC_LOAD_UMIN:
3752   case ISD::ATOMIC_LOAD_UMAX:
3753   case ISD::ATOMIC_LOAD: {
3754     unsigned MemBits =
3755         cast<AtomicSDNode>(Op)->getMemoryVT().getScalarSizeInBits();
3756     // If we are looking at the loaded value.
3757     if (Op.getResNo() == 0) {
3758       if (TLI->getExtendForAtomicOps() == ISD::ZERO_EXTEND)
3759         Known.Zero.setBitsFrom(MemBits);
3760     }
3761     break;
3762   }
3763   case ISD::FrameIndex:
3764   case ISD::TargetFrameIndex:
3765     TLI->computeKnownBitsForFrameIndex(cast<FrameIndexSDNode>(Op)->getIndex(),
3766                                        Known, getMachineFunction());
3767     break;
3768 
3769   default:
3770     if (Opcode < ISD::BUILTIN_OP_END)
3771       break;
3772     LLVM_FALLTHROUGH;
3773   case ISD::INTRINSIC_WO_CHAIN:
3774   case ISD::INTRINSIC_W_CHAIN:
3775   case ISD::INTRINSIC_VOID:
3776     // Allow the target to implement this method for its nodes.
3777     TLI->computeKnownBitsForTargetNode(Op, Known, DemandedElts, *this, Depth);
3778     break;
3779   }
3780 
3781   assert(!Known.hasConflict() && "Bits known to be one AND zero?");
3782   return Known;
3783 }
3784 
3785 SelectionDAG::OverflowKind SelectionDAG::computeOverflowKind(SDValue N0,
3786                                                              SDValue N1) const {
3787   // X + 0 never overflow
3788   if (isNullConstant(N1))
3789     return OFK_Never;
3790 
3791   KnownBits N1Known = computeKnownBits(N1);
3792   if (N1Known.Zero.getBoolValue()) {
3793     KnownBits N0Known = computeKnownBits(N0);
3794 
3795     bool overflow;
3796     (void)N0Known.getMaxValue().uadd_ov(N1Known.getMaxValue(), overflow);
3797     if (!overflow)
3798       return OFK_Never;
3799   }
3800 
3801   // mulhi + 1 never overflow
3802   if (N0.getOpcode() == ISD::UMUL_LOHI && N0.getResNo() == 1 &&
3803       (N1Known.getMaxValue() & 0x01) == N1Known.getMaxValue())
3804     return OFK_Never;
3805 
3806   if (N1.getOpcode() == ISD::UMUL_LOHI && N1.getResNo() == 1) {
3807     KnownBits N0Known = computeKnownBits(N0);
3808 
3809     if ((N0Known.getMaxValue() & 0x01) == N0Known.getMaxValue())
3810       return OFK_Never;
3811   }
3812 
3813   return OFK_Sometime;
3814 }
3815 
3816 bool SelectionDAG::isKnownToBeAPowerOfTwo(SDValue Val) const {
3817   EVT OpVT = Val.getValueType();
3818   unsigned BitWidth = OpVT.getScalarSizeInBits();
3819 
3820   // Is the constant a known power of 2?
3821   if (ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Val))
3822     return Const->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2();
3823 
3824   // A left-shift of a constant one will have exactly one bit set because
3825   // shifting the bit off the end is undefined.
3826   if (Val.getOpcode() == ISD::SHL) {
3827     auto *C = isConstOrConstSplat(Val.getOperand(0));
3828     if (C && C->getAPIntValue() == 1)
3829       return true;
3830   }
3831 
3832   // Similarly, a logical right-shift of a constant sign-bit will have exactly
3833   // one bit set.
3834   if (Val.getOpcode() == ISD::SRL) {
3835     auto *C = isConstOrConstSplat(Val.getOperand(0));
3836     if (C && C->getAPIntValue().isSignMask())
3837       return true;
3838   }
3839 
3840   // Are all operands of a build vector constant powers of two?
3841   if (Val.getOpcode() == ISD::BUILD_VECTOR)
3842     if (llvm::all_of(Val->ops(), [BitWidth](SDValue E) {
3843           if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(E))
3844             return C->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2();
3845           return false;
3846         }))
3847       return true;
3848 
3849   // Is the operand of a splat vector a constant power of two?
3850   if (Val.getOpcode() == ISD::SPLAT_VECTOR)
3851     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val->getOperand(0)))
3852       if (C->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2())
3853         return true;
3854 
3855   // More could be done here, though the above checks are enough
3856   // to handle some common cases.
3857 
3858   // Fall back to computeKnownBits to catch other known cases.
3859   KnownBits Known = computeKnownBits(Val);
3860   return (Known.countMaxPopulation() == 1) && (Known.countMinPopulation() == 1);
3861 }
3862 
3863 unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, unsigned Depth) const {
3864   EVT VT = Op.getValueType();
3865 
3866   // TODO: Assume we don't know anything for now.
3867   if (VT.isScalableVector())
3868     return 1;
3869 
3870   APInt DemandedElts = VT.isVector()
3871                            ? APInt::getAllOnes(VT.getVectorNumElements())
3872                            : APInt(1, 1);
3873   return ComputeNumSignBits(Op, DemandedElts, Depth);
3874 }
3875 
3876 unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, const APInt &DemandedElts,
3877                                           unsigned Depth) const {
3878   EVT VT = Op.getValueType();
3879   assert((VT.isInteger() || VT.isFloatingPoint()) && "Invalid VT!");
3880   unsigned VTBits = VT.getScalarSizeInBits();
3881   unsigned NumElts = DemandedElts.getBitWidth();
3882   unsigned Tmp, Tmp2;
3883   unsigned FirstAnswer = 1;
3884 
3885   if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
3886     const APInt &Val = C->getAPIntValue();
3887     return Val.getNumSignBits();
3888   }
3889 
3890   if (Depth >= MaxRecursionDepth)
3891     return 1;  // Limit search depth.
3892 
3893   if (!DemandedElts || VT.isScalableVector())
3894     return 1;  // No demanded elts, better to assume we don't know anything.
3895 
3896   unsigned Opcode = Op.getOpcode();
3897   switch (Opcode) {
3898   default: break;
3899   case ISD::AssertSext:
3900     Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
3901     return VTBits-Tmp+1;
3902   case ISD::AssertZext:
3903     Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
3904     return VTBits-Tmp;
3905 
3906   case ISD::BUILD_VECTOR:
3907     Tmp = VTBits;
3908     for (unsigned i = 0, e = Op.getNumOperands(); (i < e) && (Tmp > 1); ++i) {
3909       if (!DemandedElts[i])
3910         continue;
3911 
3912       SDValue SrcOp = Op.getOperand(i);
3913       Tmp2 = ComputeNumSignBits(SrcOp, Depth + 1);
3914 
3915       // BUILD_VECTOR can implicitly truncate sources, we must handle this.
3916       if (SrcOp.getValueSizeInBits() != VTBits) {
3917         assert(SrcOp.getValueSizeInBits() > VTBits &&
3918                "Expected BUILD_VECTOR implicit truncation");
3919         unsigned ExtraBits = SrcOp.getValueSizeInBits() - VTBits;
3920         Tmp2 = (Tmp2 > ExtraBits ? Tmp2 - ExtraBits : 1);
3921       }
3922       Tmp = std::min(Tmp, Tmp2);
3923     }
3924     return Tmp;
3925 
3926   case ISD::VECTOR_SHUFFLE: {
3927     // Collect the minimum number of sign bits that are shared by every vector
3928     // element referenced by the shuffle.
3929     APInt DemandedLHS(NumElts, 0), DemandedRHS(NumElts, 0);
3930     const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op);
3931     assert(NumElts == SVN->getMask().size() && "Unexpected vector size");
3932     for (unsigned i = 0; i != NumElts; ++i) {
3933       int M = SVN->getMaskElt(i);
3934       if (!DemandedElts[i])
3935         continue;
3936       // For UNDEF elements, we don't know anything about the common state of
3937       // the shuffle result.
3938       if (M < 0)
3939         return 1;
3940       if ((unsigned)M < NumElts)
3941         DemandedLHS.setBit((unsigned)M % NumElts);
3942       else
3943         DemandedRHS.setBit((unsigned)M % NumElts);
3944     }
3945     Tmp = std::numeric_limits<unsigned>::max();
3946     if (!!DemandedLHS)
3947       Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedLHS, Depth + 1);
3948     if (!!DemandedRHS) {
3949       Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedRHS, Depth + 1);
3950       Tmp = std::min(Tmp, Tmp2);
3951     }
3952     // If we don't know anything, early out and try computeKnownBits fall-back.
3953     if (Tmp == 1)
3954       break;
3955     assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
3956     return Tmp;
3957   }
3958 
3959   case ISD::BITCAST: {
3960     SDValue N0 = Op.getOperand(0);
3961     EVT SrcVT = N0.getValueType();
3962     unsigned SrcBits = SrcVT.getScalarSizeInBits();
3963 
3964     // Ignore bitcasts from unsupported types..
3965     if (!(SrcVT.isInteger() || SrcVT.isFloatingPoint()))
3966       break;
3967 
3968     // Fast handling of 'identity' bitcasts.
3969     if (VTBits == SrcBits)
3970       return ComputeNumSignBits(N0, DemandedElts, Depth + 1);
3971 
3972     bool IsLE = getDataLayout().isLittleEndian();
3973 
3974     // Bitcast 'large element' scalar/vector to 'small element' vector.
3975     if ((SrcBits % VTBits) == 0) {
3976       assert(VT.isVector() && "Expected bitcast to vector");
3977 
3978       unsigned Scale = SrcBits / VTBits;
3979       APInt SrcDemandedElts =
3980           APIntOps::ScaleBitMask(DemandedElts, NumElts / Scale);
3981 
3982       // Fast case - sign splat can be simply split across the small elements.
3983       Tmp = ComputeNumSignBits(N0, SrcDemandedElts, Depth + 1);
3984       if (Tmp == SrcBits)
3985         return VTBits;
3986 
3987       // Slow case - determine how far the sign extends into each sub-element.
3988       Tmp2 = VTBits;
3989       for (unsigned i = 0; i != NumElts; ++i)
3990         if (DemandedElts[i]) {
3991           unsigned SubOffset = i % Scale;
3992           SubOffset = (IsLE ? ((Scale - 1) - SubOffset) : SubOffset);
3993           SubOffset = SubOffset * VTBits;
3994           if (Tmp <= SubOffset)
3995             return 1;
3996           Tmp2 = std::min(Tmp2, Tmp - SubOffset);
3997         }
3998       return Tmp2;
3999     }
4000     break;
4001   }
4002 
4003   case ISD::FP_TO_SINT_SAT:
4004     // FP_TO_SINT_SAT produces a signed value that fits in the saturating VT.
4005     Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getScalarSizeInBits();
4006     return VTBits - Tmp + 1;
4007   case ISD::SIGN_EXTEND:
4008     Tmp = VTBits - Op.getOperand(0).getScalarValueSizeInBits();
4009     return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1) + Tmp;
4010   case ISD::SIGN_EXTEND_INREG:
4011     // Max of the input and what this extends.
4012     Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getScalarSizeInBits();
4013     Tmp = VTBits-Tmp+1;
4014     Tmp2 = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1);
4015     return std::max(Tmp, Tmp2);
4016   case ISD::SIGN_EXTEND_VECTOR_INREG: {
4017     SDValue Src = Op.getOperand(0);
4018     EVT SrcVT = Src.getValueType();
4019     APInt DemandedSrcElts = DemandedElts.zext(SrcVT.getVectorNumElements());
4020     Tmp = VTBits - SrcVT.getScalarSizeInBits();
4021     return ComputeNumSignBits(Src, DemandedSrcElts, Depth+1) + Tmp;
4022   }
4023   case ISD::SRA:
4024     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
4025     // SRA X, C -> adds C sign bits.
4026     if (const APInt *ShAmt =
4027             getValidMinimumShiftAmountConstant(Op, DemandedElts))
4028       Tmp = std::min<uint64_t>(Tmp + ShAmt->getZExtValue(), VTBits);
4029     return Tmp;
4030   case ISD::SHL:
4031     if (const APInt *ShAmt =
4032             getValidMaximumShiftAmountConstant(Op, DemandedElts)) {
4033       // shl destroys sign bits, ensure it doesn't shift out all sign bits.
4034       Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
4035       if (ShAmt->ult(Tmp))
4036         return Tmp - ShAmt->getZExtValue();
4037     }
4038     break;
4039   case ISD::AND:
4040   case ISD::OR:
4041   case ISD::XOR:    // NOT is handled here.
4042     // Logical binary ops preserve the number of sign bits at the worst.
4043     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1);
4044     if (Tmp != 1) {
4045       Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth+1);
4046       FirstAnswer = std::min(Tmp, Tmp2);
4047       // We computed what we know about the sign bits as our first
4048       // answer. Now proceed to the generic code that uses
4049       // computeKnownBits, and pick whichever answer is better.
4050     }
4051     break;
4052 
4053   case ISD::SELECT:
4054   case ISD::VSELECT:
4055     Tmp = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth+1);
4056     if (Tmp == 1) return 1;  // Early out.
4057     Tmp2 = ComputeNumSignBits(Op.getOperand(2), DemandedElts, Depth+1);
4058     return std::min(Tmp, Tmp2);
4059   case ISD::SELECT_CC:
4060     Tmp = ComputeNumSignBits(Op.getOperand(2), DemandedElts, Depth+1);
4061     if (Tmp == 1) return 1;  // Early out.
4062     Tmp2 = ComputeNumSignBits(Op.getOperand(3), DemandedElts, Depth+1);
4063     return std::min(Tmp, Tmp2);
4064 
4065   case ISD::SMIN:
4066   case ISD::SMAX: {
4067     // If we have a clamp pattern, we know that the number of sign bits will be
4068     // the minimum of the clamp min/max range.
4069     bool IsMax = (Opcode == ISD::SMAX);
4070     ConstantSDNode *CstLow = nullptr, *CstHigh = nullptr;
4071     if ((CstLow = isConstOrConstSplat(Op.getOperand(1), DemandedElts)))
4072       if (Op.getOperand(0).getOpcode() == (IsMax ? ISD::SMIN : ISD::SMAX))
4073         CstHigh =
4074             isConstOrConstSplat(Op.getOperand(0).getOperand(1), DemandedElts);
4075     if (CstLow && CstHigh) {
4076       if (!IsMax)
4077         std::swap(CstLow, CstHigh);
4078       if (CstLow->getAPIntValue().sle(CstHigh->getAPIntValue())) {
4079         Tmp = CstLow->getAPIntValue().getNumSignBits();
4080         Tmp2 = CstHigh->getAPIntValue().getNumSignBits();
4081         return std::min(Tmp, Tmp2);
4082       }
4083     }
4084 
4085     // Fallback - just get the minimum number of sign bits of the operands.
4086     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
4087     if (Tmp == 1)
4088       return 1;  // Early out.
4089     Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
4090     return std::min(Tmp, Tmp2);
4091   }
4092   case ISD::UMIN:
4093   case ISD::UMAX:
4094     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
4095     if (Tmp == 1)
4096       return 1;  // Early out.
4097     Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
4098     return std::min(Tmp, Tmp2);
4099   case ISD::SADDO:
4100   case ISD::UADDO:
4101   case ISD::SSUBO:
4102   case ISD::USUBO:
4103   case ISD::SMULO:
4104   case ISD::UMULO:
4105     if (Op.getResNo() != 1)
4106       break;
4107     // The boolean result conforms to getBooleanContents.  Fall through.
4108     // If setcc returns 0/-1, all bits are sign bits.
4109     // We know that we have an integer-based boolean since these operations
4110     // are only available for integer.
4111     if (TLI->getBooleanContents(VT.isVector(), false) ==
4112         TargetLowering::ZeroOrNegativeOneBooleanContent)
4113       return VTBits;
4114     break;
4115   case ISD::SETCC:
4116   case ISD::STRICT_FSETCC:
4117   case ISD::STRICT_FSETCCS: {
4118     unsigned OpNo = Op->isStrictFPOpcode() ? 1 : 0;
4119     // If setcc returns 0/-1, all bits are sign bits.
4120     if (TLI->getBooleanContents(Op.getOperand(OpNo).getValueType()) ==
4121         TargetLowering::ZeroOrNegativeOneBooleanContent)
4122       return VTBits;
4123     break;
4124   }
4125   case ISD::ROTL:
4126   case ISD::ROTR:
4127     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
4128 
4129     // If we're rotating an 0/-1 value, then it stays an 0/-1 value.
4130     if (Tmp == VTBits)
4131       return VTBits;
4132 
4133     if (ConstantSDNode *C =
4134             isConstOrConstSplat(Op.getOperand(1), DemandedElts)) {
4135       unsigned RotAmt = C->getAPIntValue().urem(VTBits);
4136 
4137       // Handle rotate right by N like a rotate left by 32-N.
4138       if (Opcode == ISD::ROTR)
4139         RotAmt = (VTBits - RotAmt) % VTBits;
4140 
4141       // If we aren't rotating out all of the known-in sign bits, return the
4142       // number that are left.  This handles rotl(sext(x), 1) for example.
4143       if (Tmp > (RotAmt + 1)) return (Tmp - RotAmt);
4144     }
4145     break;
4146   case ISD::ADD:
4147   case ISD::ADDC:
4148     // Add can have at most one carry bit.  Thus we know that the output
4149     // is, at worst, one more bit than the inputs.
4150     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
4151     if (Tmp == 1) return 1; // Early out.
4152 
4153     // Special case decrementing a value (ADD X, -1):
4154     if (ConstantSDNode *CRHS =
4155             isConstOrConstSplat(Op.getOperand(1), DemandedElts))
4156       if (CRHS->isAllOnes()) {
4157         KnownBits Known =
4158             computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4159 
4160         // If the input is known to be 0 or 1, the output is 0/-1, which is all
4161         // sign bits set.
4162         if ((Known.Zero | 1).isAllOnes())
4163           return VTBits;
4164 
4165         // If we are subtracting one from a positive number, there is no carry
4166         // out of the result.
4167         if (Known.isNonNegative())
4168           return Tmp;
4169       }
4170 
4171     Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
4172     if (Tmp2 == 1) return 1; // Early out.
4173     return std::min(Tmp, Tmp2) - 1;
4174   case ISD::SUB:
4175     Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
4176     if (Tmp2 == 1) return 1; // Early out.
4177 
4178     // Handle NEG.
4179     if (ConstantSDNode *CLHS =
4180             isConstOrConstSplat(Op.getOperand(0), DemandedElts))
4181       if (CLHS->isZero()) {
4182         KnownBits Known =
4183             computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4184         // If the input is known to be 0 or 1, the output is 0/-1, which is all
4185         // sign bits set.
4186         if ((Known.Zero | 1).isAllOnes())
4187           return VTBits;
4188 
4189         // If the input is known to be positive (the sign bit is known clear),
4190         // the output of the NEG has the same number of sign bits as the input.
4191         if (Known.isNonNegative())
4192           return Tmp2;
4193 
4194         // Otherwise, we treat this like a SUB.
4195       }
4196 
4197     // Sub can have at most one carry bit.  Thus we know that the output
4198     // is, at worst, one more bit than the inputs.
4199     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
4200     if (Tmp == 1) return 1; // Early out.
4201     return std::min(Tmp, Tmp2) - 1;
4202   case ISD::MUL: {
4203     // The output of the Mul can be at most twice the valid bits in the inputs.
4204     unsigned SignBitsOp0 = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
4205     if (SignBitsOp0 == 1)
4206       break;
4207     unsigned SignBitsOp1 = ComputeNumSignBits(Op.getOperand(1), Depth + 1);
4208     if (SignBitsOp1 == 1)
4209       break;
4210     unsigned OutValidBits =
4211         (VTBits - SignBitsOp0 + 1) + (VTBits - SignBitsOp1 + 1);
4212     return OutValidBits > VTBits ? 1 : VTBits - OutValidBits + 1;
4213   }
4214   case ISD::SREM:
4215     // The sign bit is the LHS's sign bit, except when the result of the
4216     // remainder is zero. The magnitude of the result should be less than or
4217     // equal to the magnitude of the LHS. Therefore, the result should have
4218     // at least as many sign bits as the left hand side.
4219     return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
4220   case ISD::TRUNCATE: {
4221     // Check if the sign bits of source go down as far as the truncated value.
4222     unsigned NumSrcBits = Op.getOperand(0).getScalarValueSizeInBits();
4223     unsigned NumSrcSignBits = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
4224     if (NumSrcSignBits > (NumSrcBits - VTBits))
4225       return NumSrcSignBits - (NumSrcBits - VTBits);
4226     break;
4227   }
4228   case ISD::EXTRACT_ELEMENT: {
4229     const int KnownSign = ComputeNumSignBits(Op.getOperand(0), Depth+1);
4230     const int BitWidth = Op.getValueSizeInBits();
4231     const int Items = Op.getOperand(0).getValueSizeInBits() / BitWidth;
4232 
4233     // Get reverse index (starting from 1), Op1 value indexes elements from
4234     // little end. Sign starts at big end.
4235     const int rIndex = Items - 1 - Op.getConstantOperandVal(1);
4236 
4237     // If the sign portion ends in our element the subtraction gives correct
4238     // result. Otherwise it gives either negative or > bitwidth result
4239     return std::max(std::min(KnownSign - rIndex * BitWidth, BitWidth), 0);
4240   }
4241   case ISD::INSERT_VECTOR_ELT: {
4242     // If we know the element index, split the demand between the
4243     // source vector and the inserted element, otherwise assume we need
4244     // the original demanded vector elements and the value.
4245     SDValue InVec = Op.getOperand(0);
4246     SDValue InVal = Op.getOperand(1);
4247     SDValue EltNo = Op.getOperand(2);
4248     bool DemandedVal = true;
4249     APInt DemandedVecElts = DemandedElts;
4250     auto *CEltNo = dyn_cast<ConstantSDNode>(EltNo);
4251     if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) {
4252       unsigned EltIdx = CEltNo->getZExtValue();
4253       DemandedVal = !!DemandedElts[EltIdx];
4254       DemandedVecElts.clearBit(EltIdx);
4255     }
4256     Tmp = std::numeric_limits<unsigned>::max();
4257     if (DemandedVal) {
4258       // TODO - handle implicit truncation of inserted elements.
4259       if (InVal.getScalarValueSizeInBits() != VTBits)
4260         break;
4261       Tmp2 = ComputeNumSignBits(InVal, Depth + 1);
4262       Tmp = std::min(Tmp, Tmp2);
4263     }
4264     if (!!DemandedVecElts) {
4265       Tmp2 = ComputeNumSignBits(InVec, DemandedVecElts, Depth + 1);
4266       Tmp = std::min(Tmp, Tmp2);
4267     }
4268     assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
4269     return Tmp;
4270   }
4271   case ISD::EXTRACT_VECTOR_ELT: {
4272     SDValue InVec = Op.getOperand(0);
4273     SDValue EltNo = Op.getOperand(1);
4274     EVT VecVT = InVec.getValueType();
4275     // ComputeNumSignBits not yet implemented for scalable vectors.
4276     if (VecVT.isScalableVector())
4277       break;
4278     const unsigned BitWidth = Op.getValueSizeInBits();
4279     const unsigned EltBitWidth = Op.getOperand(0).getScalarValueSizeInBits();
4280     const unsigned NumSrcElts = VecVT.getVectorNumElements();
4281 
4282     // If BitWidth > EltBitWidth the value is anyext:ed, and we do not know
4283     // anything about sign bits. But if the sizes match we can derive knowledge
4284     // about sign bits from the vector operand.
4285     if (BitWidth != EltBitWidth)
4286       break;
4287 
4288     // If we know the element index, just demand that vector element, else for
4289     // an unknown element index, ignore DemandedElts and demand them all.
4290     APInt DemandedSrcElts = APInt::getAllOnes(NumSrcElts);
4291     auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
4292     if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts))
4293       DemandedSrcElts =
4294           APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue());
4295 
4296     return ComputeNumSignBits(InVec, DemandedSrcElts, Depth + 1);
4297   }
4298   case ISD::EXTRACT_SUBVECTOR: {
4299     // Offset the demanded elts by the subvector index.
4300     SDValue Src = Op.getOperand(0);
4301     // Bail until we can represent demanded elements for scalable vectors.
4302     if (Src.getValueType().isScalableVector())
4303       break;
4304     uint64_t Idx = Op.getConstantOperandVal(1);
4305     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
4306     APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts).shl(Idx);
4307     return ComputeNumSignBits(Src, DemandedSrcElts, Depth + 1);
4308   }
4309   case ISD::CONCAT_VECTORS: {
4310     // Determine the minimum number of sign bits across all demanded
4311     // elts of the input vectors. Early out if the result is already 1.
4312     Tmp = std::numeric_limits<unsigned>::max();
4313     EVT SubVectorVT = Op.getOperand(0).getValueType();
4314     unsigned NumSubVectorElts = SubVectorVT.getVectorNumElements();
4315     unsigned NumSubVectors = Op.getNumOperands();
4316     for (unsigned i = 0; (i < NumSubVectors) && (Tmp > 1); ++i) {
4317       APInt DemandedSub =
4318           DemandedElts.extractBits(NumSubVectorElts, i * NumSubVectorElts);
4319       if (!DemandedSub)
4320         continue;
4321       Tmp2 = ComputeNumSignBits(Op.getOperand(i), DemandedSub, Depth + 1);
4322       Tmp = std::min(Tmp, Tmp2);
4323     }
4324     assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
4325     return Tmp;
4326   }
4327   case ISD::INSERT_SUBVECTOR: {
4328     // Demand any elements from the subvector and the remainder from the src its
4329     // inserted into.
4330     SDValue Src = Op.getOperand(0);
4331     SDValue Sub = Op.getOperand(1);
4332     uint64_t Idx = Op.getConstantOperandVal(2);
4333     unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
4334     APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
4335     APInt DemandedSrcElts = DemandedElts;
4336     DemandedSrcElts.insertBits(APInt::getZero(NumSubElts), Idx);
4337 
4338     Tmp = std::numeric_limits<unsigned>::max();
4339     if (!!DemandedSubElts) {
4340       Tmp = ComputeNumSignBits(Sub, DemandedSubElts, Depth + 1);
4341       if (Tmp == 1)
4342         return 1; // early-out
4343     }
4344     if (!!DemandedSrcElts) {
4345       Tmp2 = ComputeNumSignBits(Src, DemandedSrcElts, Depth + 1);
4346       Tmp = std::min(Tmp, Tmp2);
4347     }
4348     assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
4349     return Tmp;
4350   }
4351   case ISD::ATOMIC_CMP_SWAP:
4352   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
4353   case ISD::ATOMIC_SWAP:
4354   case ISD::ATOMIC_LOAD_ADD:
4355   case ISD::ATOMIC_LOAD_SUB:
4356   case ISD::ATOMIC_LOAD_AND:
4357   case ISD::ATOMIC_LOAD_CLR:
4358   case ISD::ATOMIC_LOAD_OR:
4359   case ISD::ATOMIC_LOAD_XOR:
4360   case ISD::ATOMIC_LOAD_NAND:
4361   case ISD::ATOMIC_LOAD_MIN:
4362   case ISD::ATOMIC_LOAD_MAX:
4363   case ISD::ATOMIC_LOAD_UMIN:
4364   case ISD::ATOMIC_LOAD_UMAX:
4365   case ISD::ATOMIC_LOAD: {
4366     Tmp = cast<AtomicSDNode>(Op)->getMemoryVT().getScalarSizeInBits();
4367     // If we are looking at the loaded value.
4368     if (Op.getResNo() == 0) {
4369       if (Tmp == VTBits)
4370         return 1; // early-out
4371       if (TLI->getExtendForAtomicOps() == ISD::SIGN_EXTEND)
4372         return VTBits - Tmp + 1;
4373       if (TLI->getExtendForAtomicOps() == ISD::ZERO_EXTEND)
4374         return VTBits - Tmp;
4375     }
4376     break;
4377   }
4378   }
4379 
4380   // If we are looking at the loaded value of the SDNode.
4381   if (Op.getResNo() == 0) {
4382     // Handle LOADX separately here. EXTLOAD case will fallthrough.
4383     if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
4384       unsigned ExtType = LD->getExtensionType();
4385       switch (ExtType) {
4386       default: break;
4387       case ISD::SEXTLOAD: // e.g. i16->i32 = '17' bits known.
4388         Tmp = LD->getMemoryVT().getScalarSizeInBits();
4389         return VTBits - Tmp + 1;
4390       case ISD::ZEXTLOAD: // e.g. i16->i32 = '16' bits known.
4391         Tmp = LD->getMemoryVT().getScalarSizeInBits();
4392         return VTBits - Tmp;
4393       case ISD::NON_EXTLOAD:
4394         if (const Constant *Cst = TLI->getTargetConstantFromLoad(LD)) {
4395           // We only need to handle vectors - computeKnownBits should handle
4396           // scalar cases.
4397           Type *CstTy = Cst->getType();
4398           if (CstTy->isVectorTy() &&
4399               (NumElts * VTBits) == CstTy->getPrimitiveSizeInBits() &&
4400               VTBits == CstTy->getScalarSizeInBits()) {
4401             Tmp = VTBits;
4402             for (unsigned i = 0; i != NumElts; ++i) {
4403               if (!DemandedElts[i])
4404                 continue;
4405               if (Constant *Elt = Cst->getAggregateElement(i)) {
4406                 if (auto *CInt = dyn_cast<ConstantInt>(Elt)) {
4407                   const APInt &Value = CInt->getValue();
4408                   Tmp = std::min(Tmp, Value.getNumSignBits());
4409                   continue;
4410                 }
4411                 if (auto *CFP = dyn_cast<ConstantFP>(Elt)) {
4412                   APInt Value = CFP->getValueAPF().bitcastToAPInt();
4413                   Tmp = std::min(Tmp, Value.getNumSignBits());
4414                   continue;
4415                 }
4416               }
4417               // Unknown type. Conservatively assume no bits match sign bit.
4418               return 1;
4419             }
4420             return Tmp;
4421           }
4422         }
4423         break;
4424       }
4425     }
4426   }
4427 
4428   // Allow the target to implement this method for its nodes.
4429   if (Opcode >= ISD::BUILTIN_OP_END ||
4430       Opcode == ISD::INTRINSIC_WO_CHAIN ||
4431       Opcode == ISD::INTRINSIC_W_CHAIN ||
4432       Opcode == ISD::INTRINSIC_VOID) {
4433     unsigned NumBits =
4434         TLI->ComputeNumSignBitsForTargetNode(Op, DemandedElts, *this, Depth);
4435     if (NumBits > 1)
4436       FirstAnswer = std::max(FirstAnswer, NumBits);
4437   }
4438 
4439   // Finally, if we can prove that the top bits of the result are 0's or 1's,
4440   // use this information.
4441   KnownBits Known = computeKnownBits(Op, DemandedElts, Depth);
4442   return std::max(FirstAnswer, Known.countMinSignBits());
4443 }
4444 
4445 unsigned SelectionDAG::ComputeMaxSignificantBits(SDValue Op,
4446                                                  unsigned Depth) const {
4447   unsigned SignBits = ComputeNumSignBits(Op, Depth);
4448   return Op.getScalarValueSizeInBits() - SignBits + 1;
4449 }
4450 
4451 unsigned SelectionDAG::ComputeMaxSignificantBits(SDValue Op,
4452                                                  const APInt &DemandedElts,
4453                                                  unsigned Depth) const {
4454   unsigned SignBits = ComputeNumSignBits(Op, DemandedElts, Depth);
4455   return Op.getScalarValueSizeInBits() - SignBits + 1;
4456 }
4457 
4458 bool SelectionDAG::isGuaranteedNotToBeUndefOrPoison(SDValue Op, bool PoisonOnly,
4459                                                     unsigned Depth) const {
4460   // Early out for FREEZE.
4461   if (Op.getOpcode() == ISD::FREEZE)
4462     return true;
4463 
4464   // TODO: Assume we don't know anything for now.
4465   EVT VT = Op.getValueType();
4466   if (VT.isScalableVector())
4467     return false;
4468 
4469   APInt DemandedElts = VT.isVector()
4470                            ? APInt::getAllOnes(VT.getVectorNumElements())
4471                            : APInt(1, 1);
4472   return isGuaranteedNotToBeUndefOrPoison(Op, DemandedElts, PoisonOnly, Depth);
4473 }
4474 
4475 bool SelectionDAG::isGuaranteedNotToBeUndefOrPoison(SDValue Op,
4476                                                     const APInt &DemandedElts,
4477                                                     bool PoisonOnly,
4478                                                     unsigned Depth) const {
4479   unsigned Opcode = Op.getOpcode();
4480 
4481   // Early out for FREEZE.
4482   if (Opcode == ISD::FREEZE)
4483     return true;
4484 
4485   if (Depth >= MaxRecursionDepth)
4486     return false; // Limit search depth.
4487 
4488   if (isIntOrFPConstant(Op))
4489     return true;
4490 
4491   switch (Opcode) {
4492   case ISD::UNDEF:
4493     return PoisonOnly;
4494 
4495   case ISD::BUILD_VECTOR:
4496     // NOTE: BUILD_VECTOR has implicit truncation of wider scalar elements -
4497     // this shouldn't affect the result.
4498     for (unsigned i = 0, e = Op.getNumOperands(); i < e; ++i) {
4499       if (!DemandedElts[i])
4500         continue;
4501       if (!isGuaranteedNotToBeUndefOrPoison(Op.getOperand(i), PoisonOnly,
4502                                             Depth + 1))
4503         return false;
4504     }
4505     return true;
4506 
4507   // TODO: Search for noundef attributes from library functions.
4508 
4509   // TODO: Pointers dereferenced by ISD::LOAD/STORE ops are noundef.
4510 
4511   default:
4512     // Allow the target to implement this method for its nodes.
4513     if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::INTRINSIC_WO_CHAIN ||
4514         Opcode == ISD::INTRINSIC_W_CHAIN || Opcode == ISD::INTRINSIC_VOID)
4515       return TLI->isGuaranteedNotToBeUndefOrPoisonForTargetNode(
4516           Op, DemandedElts, *this, PoisonOnly, Depth);
4517     break;
4518   }
4519 
4520   return false;
4521 }
4522 
4523 bool SelectionDAG::isBaseWithConstantOffset(SDValue Op) const {
4524   if ((Op.getOpcode() != ISD::ADD && Op.getOpcode() != ISD::OR) ||
4525       !isa<ConstantSDNode>(Op.getOperand(1)))
4526     return false;
4527 
4528   if (Op.getOpcode() == ISD::OR &&
4529       !MaskedValueIsZero(Op.getOperand(0), Op.getConstantOperandAPInt(1)))
4530     return false;
4531 
4532   return true;
4533 }
4534 
4535 bool SelectionDAG::isKnownNeverNaN(SDValue Op, bool SNaN, unsigned Depth) const {
4536   // If we're told that NaNs won't happen, assume they won't.
4537   if (getTarget().Options.NoNaNsFPMath || Op->getFlags().hasNoNaNs())
4538     return true;
4539 
4540   if (Depth >= MaxRecursionDepth)
4541     return false; // Limit search depth.
4542 
4543   // TODO: Handle vectors.
4544   // If the value is a constant, we can obviously see if it is a NaN or not.
4545   if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) {
4546     return !C->getValueAPF().isNaN() ||
4547            (SNaN && !C->getValueAPF().isSignaling());
4548   }
4549 
4550   unsigned Opcode = Op.getOpcode();
4551   switch (Opcode) {
4552   case ISD::FADD:
4553   case ISD::FSUB:
4554   case ISD::FMUL:
4555   case ISD::FDIV:
4556   case ISD::FREM:
4557   case ISD::FSIN:
4558   case ISD::FCOS: {
4559     if (SNaN)
4560       return true;
4561     // TODO: Need isKnownNeverInfinity
4562     return false;
4563   }
4564   case ISD::FCANONICALIZE:
4565   case ISD::FEXP:
4566   case ISD::FEXP2:
4567   case ISD::FTRUNC:
4568   case ISD::FFLOOR:
4569   case ISD::FCEIL:
4570   case ISD::FROUND:
4571   case ISD::FROUNDEVEN:
4572   case ISD::FRINT:
4573   case ISD::FNEARBYINT: {
4574     if (SNaN)
4575       return true;
4576     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
4577   }
4578   case ISD::FABS:
4579   case ISD::FNEG:
4580   case ISD::FCOPYSIGN: {
4581     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
4582   }
4583   case ISD::SELECT:
4584     return isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1) &&
4585            isKnownNeverNaN(Op.getOperand(2), SNaN, Depth + 1);
4586   case ISD::FP_EXTEND:
4587   case ISD::FP_ROUND: {
4588     if (SNaN)
4589       return true;
4590     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
4591   }
4592   case ISD::SINT_TO_FP:
4593   case ISD::UINT_TO_FP:
4594     return true;
4595   case ISD::FMA:
4596   case ISD::FMAD: {
4597     if (SNaN)
4598       return true;
4599     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) &&
4600            isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1) &&
4601            isKnownNeverNaN(Op.getOperand(2), SNaN, Depth + 1);
4602   }
4603   case ISD::FSQRT: // Need is known positive
4604   case ISD::FLOG:
4605   case ISD::FLOG2:
4606   case ISD::FLOG10:
4607   case ISD::FPOWI:
4608   case ISD::FPOW: {
4609     if (SNaN)
4610       return true;
4611     // TODO: Refine on operand
4612     return false;
4613   }
4614   case ISD::FMINNUM:
4615   case ISD::FMAXNUM: {
4616     // Only one needs to be known not-nan, since it will be returned if the
4617     // other ends up being one.
4618     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) ||
4619            isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1);
4620   }
4621   case ISD::FMINNUM_IEEE:
4622   case ISD::FMAXNUM_IEEE: {
4623     if (SNaN)
4624       return true;
4625     // This can return a NaN if either operand is an sNaN, or if both operands
4626     // are NaN.
4627     return (isKnownNeverNaN(Op.getOperand(0), false, Depth + 1) &&
4628             isKnownNeverSNaN(Op.getOperand(1), Depth + 1)) ||
4629            (isKnownNeverNaN(Op.getOperand(1), false, Depth + 1) &&
4630             isKnownNeverSNaN(Op.getOperand(0), Depth + 1));
4631   }
4632   case ISD::FMINIMUM:
4633   case ISD::FMAXIMUM: {
4634     // TODO: Does this quiet or return the origina NaN as-is?
4635     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) &&
4636            isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1);
4637   }
4638   case ISD::EXTRACT_VECTOR_ELT: {
4639     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
4640   }
4641   default:
4642     if (Opcode >= ISD::BUILTIN_OP_END ||
4643         Opcode == ISD::INTRINSIC_WO_CHAIN ||
4644         Opcode == ISD::INTRINSIC_W_CHAIN ||
4645         Opcode == ISD::INTRINSIC_VOID) {
4646       return TLI->isKnownNeverNaNForTargetNode(Op, *this, SNaN, Depth);
4647     }
4648 
4649     return false;
4650   }
4651 }
4652 
4653 bool SelectionDAG::isKnownNeverZeroFloat(SDValue Op) const {
4654   assert(Op.getValueType().isFloatingPoint() &&
4655          "Floating point type expected");
4656 
4657   // If the value is a constant, we can obviously see if it is a zero or not.
4658   // TODO: Add BuildVector support.
4659   if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op))
4660     return !C->isZero();
4661   return false;
4662 }
4663 
4664 bool SelectionDAG::isKnownNeverZero(SDValue Op) const {
4665   assert(!Op.getValueType().isFloatingPoint() &&
4666          "Floating point types unsupported - use isKnownNeverZeroFloat");
4667 
4668   // If the value is a constant, we can obviously see if it is a zero or not.
4669   if (ISD::matchUnaryPredicate(Op,
4670                                [](ConstantSDNode *C) { return !C->isZero(); }))
4671     return true;
4672 
4673   // TODO: Recognize more cases here.
4674   switch (Op.getOpcode()) {
4675   default: break;
4676   case ISD::OR:
4677     if (isKnownNeverZero(Op.getOperand(1)) ||
4678         isKnownNeverZero(Op.getOperand(0)))
4679       return true;
4680     break;
4681   }
4682 
4683   return false;
4684 }
4685 
4686 bool SelectionDAG::isEqualTo(SDValue A, SDValue B) const {
4687   // Check the obvious case.
4688   if (A == B) return true;
4689 
4690   // For for negative and positive zero.
4691   if (const ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A))
4692     if (const ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B))
4693       if (CA->isZero() && CB->isZero()) return true;
4694 
4695   // Otherwise they may not be equal.
4696   return false;
4697 }
4698 
4699 // Only bits set in Mask must be negated, other bits may be arbitrary.
4700 SDValue llvm::getBitwiseNotOperand(SDValue V, SDValue Mask, bool AllowUndefs) {
4701   if (isBitwiseNot(V, AllowUndefs))
4702     return V.getOperand(0);
4703 
4704   // Handle any_extend (not (truncate X)) pattern, where Mask only sets
4705   // bits in the non-extended part.
4706   ConstantSDNode *MaskC = isConstOrConstSplat(Mask);
4707   if (!MaskC || V.getOpcode() != ISD::ANY_EXTEND)
4708     return SDValue();
4709   SDValue ExtArg = V.getOperand(0);
4710   if (ExtArg.getScalarValueSizeInBits() >=
4711           MaskC->getAPIntValue().getActiveBits() &&
4712       isBitwiseNot(ExtArg, AllowUndefs) &&
4713       ExtArg.getOperand(0).getOpcode() == ISD::TRUNCATE &&
4714       ExtArg.getOperand(0).getOperand(0).getValueType() == V.getValueType())
4715     return ExtArg.getOperand(0).getOperand(0);
4716   return SDValue();
4717 }
4718 
4719 static bool haveNoCommonBitsSetCommutative(SDValue A, SDValue B) {
4720   // Match masked merge pattern (X & ~M) op (Y & M)
4721   // Including degenerate case (X & ~M) op M
4722   auto MatchNoCommonBitsPattern = [&](SDValue Not, SDValue Mask,
4723                                       SDValue Other) {
4724     if (SDValue NotOperand =
4725             getBitwiseNotOperand(Not, Mask, /* AllowUndefs */ true)) {
4726       if (Other == NotOperand)
4727         return true;
4728       if (Other->getOpcode() == ISD::AND)
4729         return NotOperand == Other->getOperand(0) ||
4730                NotOperand == Other->getOperand(1);
4731     }
4732     return false;
4733   };
4734   if (A->getOpcode() == ISD::AND)
4735     return MatchNoCommonBitsPattern(A->getOperand(0), A->getOperand(1), B) ||
4736            MatchNoCommonBitsPattern(A->getOperand(1), A->getOperand(0), B);
4737   return false;
4738 }
4739 
4740 // FIXME: unify with llvm::haveNoCommonBitsSet.
4741 bool SelectionDAG::haveNoCommonBitsSet(SDValue A, SDValue B) const {
4742   assert(A.getValueType() == B.getValueType() &&
4743          "Values must have the same type");
4744   if (haveNoCommonBitsSetCommutative(A, B) ||
4745       haveNoCommonBitsSetCommutative(B, A))
4746     return true;
4747   return KnownBits::haveNoCommonBitsSet(computeKnownBits(A),
4748                                         computeKnownBits(B));
4749 }
4750 
4751 static SDValue FoldSTEP_VECTOR(const SDLoc &DL, EVT VT, SDValue Step,
4752                                SelectionDAG &DAG) {
4753   if (cast<ConstantSDNode>(Step)->isZero())
4754     return DAG.getConstant(0, DL, VT);
4755 
4756   return SDValue();
4757 }
4758 
4759 static SDValue FoldBUILD_VECTOR(const SDLoc &DL, EVT VT,
4760                                 ArrayRef<SDValue> Ops,
4761                                 SelectionDAG &DAG) {
4762   int NumOps = Ops.size();
4763   assert(NumOps != 0 && "Can't build an empty vector!");
4764   assert(!VT.isScalableVector() &&
4765          "BUILD_VECTOR cannot be used with scalable types");
4766   assert(VT.getVectorNumElements() == (unsigned)NumOps &&
4767          "Incorrect element count in BUILD_VECTOR!");
4768 
4769   // BUILD_VECTOR of UNDEFs is UNDEF.
4770   if (llvm::all_of(Ops, [](SDValue Op) { return Op.isUndef(); }))
4771     return DAG.getUNDEF(VT);
4772 
4773   // BUILD_VECTOR of seq extract/insert from the same vector + type is Identity.
4774   SDValue IdentitySrc;
4775   bool IsIdentity = true;
4776   for (int i = 0; i != NumOps; ++i) {
4777     if (Ops[i].getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
4778         Ops[i].getOperand(0).getValueType() != VT ||
4779         (IdentitySrc && Ops[i].getOperand(0) != IdentitySrc) ||
4780         !isa<ConstantSDNode>(Ops[i].getOperand(1)) ||
4781         cast<ConstantSDNode>(Ops[i].getOperand(1))->getAPIntValue() != i) {
4782       IsIdentity = false;
4783       break;
4784     }
4785     IdentitySrc = Ops[i].getOperand(0);
4786   }
4787   if (IsIdentity)
4788     return IdentitySrc;
4789 
4790   return SDValue();
4791 }
4792 
4793 /// Try to simplify vector concatenation to an input value, undef, or build
4794 /// vector.
4795 static SDValue foldCONCAT_VECTORS(const SDLoc &DL, EVT VT,
4796                                   ArrayRef<SDValue> Ops,
4797                                   SelectionDAG &DAG) {
4798   assert(!Ops.empty() && "Can't concatenate an empty list of vectors!");
4799   assert(llvm::all_of(Ops,
4800                       [Ops](SDValue Op) {
4801                         return Ops[0].getValueType() == Op.getValueType();
4802                       }) &&
4803          "Concatenation of vectors with inconsistent value types!");
4804   assert((Ops[0].getValueType().getVectorElementCount() * Ops.size()) ==
4805              VT.getVectorElementCount() &&
4806          "Incorrect element count in vector concatenation!");
4807 
4808   if (Ops.size() == 1)
4809     return Ops[0];
4810 
4811   // Concat of UNDEFs is UNDEF.
4812   if (llvm::all_of(Ops, [](SDValue Op) { return Op.isUndef(); }))
4813     return DAG.getUNDEF(VT);
4814 
4815   // Scan the operands and look for extract operations from a single source
4816   // that correspond to insertion at the same location via this concatenation:
4817   // concat (extract X, 0*subvec_elts), (extract X, 1*subvec_elts), ...
4818   SDValue IdentitySrc;
4819   bool IsIdentity = true;
4820   for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
4821     SDValue Op = Ops[i];
4822     unsigned IdentityIndex = i * Op.getValueType().getVectorMinNumElements();
4823     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
4824         Op.getOperand(0).getValueType() != VT ||
4825         (IdentitySrc && Op.getOperand(0) != IdentitySrc) ||
4826         Op.getConstantOperandVal(1) != IdentityIndex) {
4827       IsIdentity = false;
4828       break;
4829     }
4830     assert((!IdentitySrc || IdentitySrc == Op.getOperand(0)) &&
4831            "Unexpected identity source vector for concat of extracts");
4832     IdentitySrc = Op.getOperand(0);
4833   }
4834   if (IsIdentity) {
4835     assert(IdentitySrc && "Failed to set source vector of extracts");
4836     return IdentitySrc;
4837   }
4838 
4839   // The code below this point is only designed to work for fixed width
4840   // vectors, so we bail out for now.
4841   if (VT.isScalableVector())
4842     return SDValue();
4843 
4844   // A CONCAT_VECTOR with all UNDEF/BUILD_VECTOR operands can be
4845   // simplified to one big BUILD_VECTOR.
4846   // FIXME: Add support for SCALAR_TO_VECTOR as well.
4847   EVT SVT = VT.getScalarType();
4848   SmallVector<SDValue, 16> Elts;
4849   for (SDValue Op : Ops) {
4850     EVT OpVT = Op.getValueType();
4851     if (Op.isUndef())
4852       Elts.append(OpVT.getVectorNumElements(), DAG.getUNDEF(SVT));
4853     else if (Op.getOpcode() == ISD::BUILD_VECTOR)
4854       Elts.append(Op->op_begin(), Op->op_end());
4855     else
4856       return SDValue();
4857   }
4858 
4859   // BUILD_VECTOR requires all inputs to be of the same type, find the
4860   // maximum type and extend them all.
4861   for (SDValue Op : Elts)
4862     SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
4863 
4864   if (SVT.bitsGT(VT.getScalarType())) {
4865     for (SDValue &Op : Elts) {
4866       if (Op.isUndef())
4867         Op = DAG.getUNDEF(SVT);
4868       else
4869         Op = DAG.getTargetLoweringInfo().isZExtFree(Op.getValueType(), SVT)
4870                  ? DAG.getZExtOrTrunc(Op, DL, SVT)
4871                  : DAG.getSExtOrTrunc(Op, DL, SVT);
4872     }
4873   }
4874 
4875   SDValue V = DAG.getBuildVector(VT, DL, Elts);
4876   NewSDValueDbgMsg(V, "New node fold concat vectors: ", &DAG);
4877   return V;
4878 }
4879 
4880 /// Gets or creates the specified node.
4881 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT) {
4882   FoldingSetNodeID ID;
4883   AddNodeIDNode(ID, Opcode, getVTList(VT), None);
4884   void *IP = nullptr;
4885   if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
4886     return SDValue(E, 0);
4887 
4888   auto *N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(),
4889                               getVTList(VT));
4890   CSEMap.InsertNode(N, IP);
4891 
4892   InsertNode(N);
4893   SDValue V = SDValue(N, 0);
4894   NewSDValueDbgMsg(V, "Creating new node: ", this);
4895   return V;
4896 }
4897 
4898 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
4899                               SDValue Operand) {
4900   SDNodeFlags Flags;
4901   if (Inserter)
4902     Flags = Inserter->getFlags();
4903   return getNode(Opcode, DL, VT, Operand, Flags);
4904 }
4905 
4906 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
4907                               SDValue Operand, const SDNodeFlags Flags) {
4908   assert(Operand.getOpcode() != ISD::DELETED_NODE &&
4909          "Operand is DELETED_NODE!");
4910   // Constant fold unary operations with an integer constant operand. Even
4911   // opaque constant will be folded, because the folding of unary operations
4912   // doesn't create new constants with different values. Nevertheless, the
4913   // opaque flag is preserved during folding to prevent future folding with
4914   // other constants.
4915   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Operand)) {
4916     const APInt &Val = C->getAPIntValue();
4917     switch (Opcode) {
4918     default: break;
4919     case ISD::SIGN_EXTEND:
4920       return getConstant(Val.sextOrTrunc(VT.getSizeInBits()), DL, VT,
4921                          C->isTargetOpcode(), C->isOpaque());
4922     case ISD::TRUNCATE:
4923       if (C->isOpaque())
4924         break;
4925       LLVM_FALLTHROUGH;
4926     case ISD::ZERO_EXTEND:
4927       return getConstant(Val.zextOrTrunc(VT.getSizeInBits()), DL, VT,
4928                          C->isTargetOpcode(), C->isOpaque());
4929     case ISD::ANY_EXTEND:
4930       // Some targets like RISCV prefer to sign extend some types.
4931       if (TLI->isSExtCheaperThanZExt(Operand.getValueType(), VT))
4932         return getConstant(Val.sextOrTrunc(VT.getSizeInBits()), DL, VT,
4933                            C->isTargetOpcode(), C->isOpaque());
4934       return getConstant(Val.zextOrTrunc(VT.getSizeInBits()), DL, VT,
4935                          C->isTargetOpcode(), C->isOpaque());
4936     case ISD::UINT_TO_FP:
4937     case ISD::SINT_TO_FP: {
4938       APFloat apf(EVTToAPFloatSemantics(VT),
4939                   APInt::getZero(VT.getSizeInBits()));
4940       (void)apf.convertFromAPInt(Val,
4941                                  Opcode==ISD::SINT_TO_FP,
4942                                  APFloat::rmNearestTiesToEven);
4943       return getConstantFP(apf, DL, VT);
4944     }
4945     case ISD::BITCAST:
4946       if (VT == MVT::f16 && C->getValueType(0) == MVT::i16)
4947         return getConstantFP(APFloat(APFloat::IEEEhalf(), Val), DL, VT);
4948       if (VT == MVT::f32 && C->getValueType(0) == MVT::i32)
4949         return getConstantFP(APFloat(APFloat::IEEEsingle(), Val), DL, VT);
4950       if (VT == MVT::f64 && C->getValueType(0) == MVT::i64)
4951         return getConstantFP(APFloat(APFloat::IEEEdouble(), Val), DL, VT);
4952       if (VT == MVT::f128 && C->getValueType(0) == MVT::i128)
4953         return getConstantFP(APFloat(APFloat::IEEEquad(), Val), DL, VT);
4954       break;
4955     case ISD::ABS:
4956       return getConstant(Val.abs(), DL, VT, C->isTargetOpcode(),
4957                          C->isOpaque());
4958     case ISD::BITREVERSE:
4959       return getConstant(Val.reverseBits(), DL, VT, C->isTargetOpcode(),
4960                          C->isOpaque());
4961     case ISD::BSWAP:
4962       return getConstant(Val.byteSwap(), DL, VT, C->isTargetOpcode(),
4963                          C->isOpaque());
4964     case ISD::CTPOP:
4965       return getConstant(Val.countPopulation(), DL, VT, C->isTargetOpcode(),
4966                          C->isOpaque());
4967     case ISD::CTLZ:
4968     case ISD::CTLZ_ZERO_UNDEF:
4969       return getConstant(Val.countLeadingZeros(), DL, VT, C->isTargetOpcode(),
4970                          C->isOpaque());
4971     case ISD::CTTZ:
4972     case ISD::CTTZ_ZERO_UNDEF:
4973       return getConstant(Val.countTrailingZeros(), DL, VT, C->isTargetOpcode(),
4974                          C->isOpaque());
4975     case ISD::FP16_TO_FP: {
4976       bool Ignored;
4977       APFloat FPV(APFloat::IEEEhalf(),
4978                   (Val.getBitWidth() == 16) ? Val : Val.trunc(16));
4979 
4980       // This can return overflow, underflow, or inexact; we don't care.
4981       // FIXME need to be more flexible about rounding mode.
4982       (void)FPV.convert(EVTToAPFloatSemantics(VT),
4983                         APFloat::rmNearestTiesToEven, &Ignored);
4984       return getConstantFP(FPV, DL, VT);
4985     }
4986     case ISD::STEP_VECTOR: {
4987       if (SDValue V = FoldSTEP_VECTOR(DL, VT, Operand, *this))
4988         return V;
4989       break;
4990     }
4991     }
4992   }
4993 
4994   // Constant fold unary operations with a floating point constant operand.
4995   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Operand)) {
4996     APFloat V = C->getValueAPF();    // make copy
4997     switch (Opcode) {
4998     case ISD::FNEG:
4999       V.changeSign();
5000       return getConstantFP(V, DL, VT);
5001     case ISD::FABS:
5002       V.clearSign();
5003       return getConstantFP(V, DL, VT);
5004     case ISD::FCEIL: {
5005       APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardPositive);
5006       if (fs == APFloat::opOK || fs == APFloat::opInexact)
5007         return getConstantFP(V, DL, VT);
5008       break;
5009     }
5010     case ISD::FTRUNC: {
5011       APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardZero);
5012       if (fs == APFloat::opOK || fs == APFloat::opInexact)
5013         return getConstantFP(V, DL, VT);
5014       break;
5015     }
5016     case ISD::FFLOOR: {
5017       APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardNegative);
5018       if (fs == APFloat::opOK || fs == APFloat::opInexact)
5019         return getConstantFP(V, DL, VT);
5020       break;
5021     }
5022     case ISD::FP_EXTEND: {
5023       bool ignored;
5024       // This can return overflow, underflow, or inexact; we don't care.
5025       // FIXME need to be more flexible about rounding mode.
5026       (void)V.convert(EVTToAPFloatSemantics(VT),
5027                       APFloat::rmNearestTiesToEven, &ignored);
5028       return getConstantFP(V, DL, VT);
5029     }
5030     case ISD::FP_TO_SINT:
5031     case ISD::FP_TO_UINT: {
5032       bool ignored;
5033       APSInt IntVal(VT.getSizeInBits(), Opcode == ISD::FP_TO_UINT);
5034       // FIXME need to be more flexible about rounding mode.
5035       APFloat::opStatus s =
5036           V.convertToInteger(IntVal, APFloat::rmTowardZero, &ignored);
5037       if (s == APFloat::opInvalidOp) // inexact is OK, in fact usual
5038         break;
5039       return getConstant(IntVal, DL, VT);
5040     }
5041     case ISD::BITCAST:
5042       if (VT == MVT::i16 && C->getValueType(0) == MVT::f16)
5043         return getConstant((uint16_t)V.bitcastToAPInt().getZExtValue(), DL, VT);
5044       if (VT == MVT::i16 && C->getValueType(0) == MVT::bf16)
5045         return getConstant((uint16_t)V.bitcastToAPInt().getZExtValue(), DL, VT);
5046       if (VT == MVT::i32 && C->getValueType(0) == MVT::f32)
5047         return getConstant((uint32_t)V.bitcastToAPInt().getZExtValue(), DL, VT);
5048       if (VT == MVT::i64 && C->getValueType(0) == MVT::f64)
5049         return getConstant(V.bitcastToAPInt().getZExtValue(), DL, VT);
5050       break;
5051     case ISD::FP_TO_FP16: {
5052       bool Ignored;
5053       // This can return overflow, underflow, or inexact; we don't care.
5054       // FIXME need to be more flexible about rounding mode.
5055       (void)V.convert(APFloat::IEEEhalf(),
5056                       APFloat::rmNearestTiesToEven, &Ignored);
5057       return getConstant(V.bitcastToAPInt().getZExtValue(), DL, VT);
5058     }
5059     }
5060   }
5061 
5062   // Constant fold unary operations with a vector integer or float operand.
5063   switch (Opcode) {
5064   default:
5065     // FIXME: Entirely reasonable to perform folding of other unary
5066     // operations here as the need arises.
5067     break;
5068   case ISD::FNEG:
5069   case ISD::FABS:
5070   case ISD::FCEIL:
5071   case ISD::FTRUNC:
5072   case ISD::FFLOOR:
5073   case ISD::FP_EXTEND:
5074   case ISD::FP_TO_SINT:
5075   case ISD::FP_TO_UINT:
5076   case ISD::TRUNCATE:
5077   case ISD::ANY_EXTEND:
5078   case ISD::ZERO_EXTEND:
5079   case ISD::SIGN_EXTEND:
5080   case ISD::UINT_TO_FP:
5081   case ISD::SINT_TO_FP:
5082   case ISD::ABS:
5083   case ISD::BITREVERSE:
5084   case ISD::BSWAP:
5085   case ISD::CTLZ:
5086   case ISD::CTLZ_ZERO_UNDEF:
5087   case ISD::CTTZ:
5088   case ISD::CTTZ_ZERO_UNDEF:
5089   case ISD::CTPOP: {
5090     SDValue Ops = {Operand};
5091     if (SDValue Fold = FoldConstantArithmetic(Opcode, DL, VT, Ops))
5092       return Fold;
5093   }
5094   }
5095 
5096   unsigned OpOpcode = Operand.getNode()->getOpcode();
5097   switch (Opcode) {
5098   case ISD::STEP_VECTOR:
5099     assert(VT.isScalableVector() &&
5100            "STEP_VECTOR can only be used with scalable types");
5101     assert(OpOpcode == ISD::TargetConstant &&
5102            VT.getVectorElementType() == Operand.getValueType() &&
5103            "Unexpected step operand");
5104     break;
5105   case ISD::FREEZE:
5106     assert(VT == Operand.getValueType() && "Unexpected VT!");
5107     if (isGuaranteedNotToBeUndefOrPoison(Operand))
5108       return Operand;
5109     break;
5110   case ISD::TokenFactor:
5111   case ISD::MERGE_VALUES:
5112   case ISD::CONCAT_VECTORS:
5113     return Operand;         // Factor, merge or concat of one node?  No need.
5114   case ISD::BUILD_VECTOR: {
5115     // Attempt to simplify BUILD_VECTOR.
5116     SDValue Ops[] = {Operand};
5117     if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
5118       return V;
5119     break;
5120   }
5121   case ISD::FP_ROUND: llvm_unreachable("Invalid method to make FP_ROUND node");
5122   case ISD::FP_EXTEND:
5123     assert(VT.isFloatingPoint() &&
5124            Operand.getValueType().isFloatingPoint() && "Invalid FP cast!");
5125     if (Operand.getValueType() == VT) return Operand;  // noop conversion.
5126     assert((!VT.isVector() ||
5127             VT.getVectorElementCount() ==
5128             Operand.getValueType().getVectorElementCount()) &&
5129            "Vector element count mismatch!");
5130     assert(Operand.getValueType().bitsLT(VT) &&
5131            "Invalid fpext node, dst < src!");
5132     if (Operand.isUndef())
5133       return getUNDEF(VT);
5134     break;
5135   case ISD::FP_TO_SINT:
5136   case ISD::FP_TO_UINT:
5137     if (Operand.isUndef())
5138       return getUNDEF(VT);
5139     break;
5140   case ISD::SINT_TO_FP:
5141   case ISD::UINT_TO_FP:
5142     // [us]itofp(undef) = 0, because the result value is bounded.
5143     if (Operand.isUndef())
5144       return getConstantFP(0.0, DL, VT);
5145     break;
5146   case ISD::SIGN_EXTEND:
5147     assert(VT.isInteger() && Operand.getValueType().isInteger() &&
5148            "Invalid SIGN_EXTEND!");
5149     assert(VT.isVector() == Operand.getValueType().isVector() &&
5150            "SIGN_EXTEND result type type should be vector iff the operand "
5151            "type is vector!");
5152     if (Operand.getValueType() == VT) return Operand;   // noop extension
5153     assert((!VT.isVector() ||
5154             VT.getVectorElementCount() ==
5155                 Operand.getValueType().getVectorElementCount()) &&
5156            "Vector element count mismatch!");
5157     assert(Operand.getValueType().bitsLT(VT) &&
5158            "Invalid sext node, dst < src!");
5159     if (OpOpcode == ISD::SIGN_EXTEND || OpOpcode == ISD::ZERO_EXTEND)
5160       return getNode(OpOpcode, DL, VT, Operand.getOperand(0));
5161     if (OpOpcode == ISD::UNDEF)
5162       // sext(undef) = 0, because the top bits will all be the same.
5163       return getConstant(0, DL, VT);
5164     break;
5165   case ISD::ZERO_EXTEND:
5166     assert(VT.isInteger() && Operand.getValueType().isInteger() &&
5167            "Invalid ZERO_EXTEND!");
5168     assert(VT.isVector() == Operand.getValueType().isVector() &&
5169            "ZERO_EXTEND result type type should be vector iff the operand "
5170            "type is vector!");
5171     if (Operand.getValueType() == VT) return Operand;   // noop extension
5172     assert((!VT.isVector() ||
5173             VT.getVectorElementCount() ==
5174                 Operand.getValueType().getVectorElementCount()) &&
5175            "Vector element count mismatch!");
5176     assert(Operand.getValueType().bitsLT(VT) &&
5177            "Invalid zext node, dst < src!");
5178     if (OpOpcode == ISD::ZERO_EXTEND)   // (zext (zext x)) -> (zext x)
5179       return getNode(ISD::ZERO_EXTEND, DL, VT, Operand.getOperand(0));
5180     if (OpOpcode == ISD::UNDEF)
5181       // zext(undef) = 0, because the top bits will be zero.
5182       return getConstant(0, DL, VT);
5183     break;
5184   case ISD::ANY_EXTEND:
5185     assert(VT.isInteger() && Operand.getValueType().isInteger() &&
5186            "Invalid ANY_EXTEND!");
5187     assert(VT.isVector() == Operand.getValueType().isVector() &&
5188            "ANY_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 anyext node, dst < src!");
5197 
5198     if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
5199         OpOpcode == ISD::ANY_EXTEND)
5200       // (ext (zext x)) -> (zext x)  and  (ext (sext x)) -> (sext x)
5201       return getNode(OpOpcode, DL, VT, Operand.getOperand(0));
5202     if (OpOpcode == ISD::UNDEF)
5203       return getUNDEF(VT);
5204 
5205     // (ext (trunc x)) -> x
5206     if (OpOpcode == ISD::TRUNCATE) {
5207       SDValue OpOp = Operand.getOperand(0);
5208       if (OpOp.getValueType() == VT) {
5209         transferDbgValues(Operand, OpOp);
5210         return OpOp;
5211       }
5212     }
5213     break;
5214   case ISD::TRUNCATE:
5215     assert(VT.isInteger() && Operand.getValueType().isInteger() &&
5216            "Invalid TRUNCATE!");
5217     assert(VT.isVector() == Operand.getValueType().isVector() &&
5218            "TRUNCATE result type type should be vector iff the operand "
5219            "type is vector!");
5220     if (Operand.getValueType() == VT) return Operand;   // noop truncate
5221     assert((!VT.isVector() ||
5222             VT.getVectorElementCount() ==
5223                 Operand.getValueType().getVectorElementCount()) &&
5224            "Vector element count mismatch!");
5225     assert(Operand.getValueType().bitsGT(VT) &&
5226            "Invalid truncate node, src < dst!");
5227     if (OpOpcode == ISD::TRUNCATE)
5228       return getNode(ISD::TRUNCATE, DL, VT, Operand.getOperand(0));
5229     if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
5230         OpOpcode == ISD::ANY_EXTEND) {
5231       // If the source is smaller than the dest, we still need an extend.
5232       if (Operand.getOperand(0).getValueType().getScalarType()
5233             .bitsLT(VT.getScalarType()))
5234         return getNode(OpOpcode, DL, VT, Operand.getOperand(0));
5235       if (Operand.getOperand(0).getValueType().bitsGT(VT))
5236         return getNode(ISD::TRUNCATE, DL, VT, Operand.getOperand(0));
5237       return Operand.getOperand(0);
5238     }
5239     if (OpOpcode == ISD::UNDEF)
5240       return getUNDEF(VT);
5241     if (OpOpcode == ISD::VSCALE && !NewNodesMustHaveLegalTypes)
5242       return getVScale(DL, VT, Operand.getConstantOperandAPInt(0));
5243     break;
5244   case ISD::ANY_EXTEND_VECTOR_INREG:
5245   case ISD::ZERO_EXTEND_VECTOR_INREG:
5246   case ISD::SIGN_EXTEND_VECTOR_INREG:
5247     assert(VT.isVector() && "This DAG node is restricted to vector types.");
5248     assert(Operand.getValueType().bitsLE(VT) &&
5249            "The input must be the same size or smaller than the result.");
5250     assert(VT.getVectorMinNumElements() <
5251                Operand.getValueType().getVectorMinNumElements() &&
5252            "The destination vector type must have fewer lanes than the input.");
5253     break;
5254   case ISD::ABS:
5255     assert(VT.isInteger() && VT == Operand.getValueType() &&
5256            "Invalid ABS!");
5257     if (OpOpcode == ISD::UNDEF)
5258       return getConstant(0, DL, VT);
5259     break;
5260   case ISD::BSWAP:
5261     assert(VT.isInteger() && VT == Operand.getValueType() &&
5262            "Invalid BSWAP!");
5263     assert((VT.getScalarSizeInBits() % 16 == 0) &&
5264            "BSWAP types must be a multiple of 16 bits!");
5265     if (OpOpcode == ISD::UNDEF)
5266       return getUNDEF(VT);
5267     // bswap(bswap(X)) -> X.
5268     if (OpOpcode == ISD::BSWAP)
5269       return Operand.getOperand(0);
5270     break;
5271   case ISD::BITREVERSE:
5272     assert(VT.isInteger() && VT == Operand.getValueType() &&
5273            "Invalid BITREVERSE!");
5274     if (OpOpcode == ISD::UNDEF)
5275       return getUNDEF(VT);
5276     break;
5277   case ISD::BITCAST:
5278     assert(VT.getSizeInBits() == Operand.getValueSizeInBits() &&
5279            "Cannot BITCAST between types of different sizes!");
5280     if (VT == Operand.getValueType()) return Operand;  // noop conversion.
5281     if (OpOpcode == ISD::BITCAST)  // bitconv(bitconv(x)) -> bitconv(x)
5282       return getNode(ISD::BITCAST, DL, VT, Operand.getOperand(0));
5283     if (OpOpcode == ISD::UNDEF)
5284       return getUNDEF(VT);
5285     break;
5286   case ISD::SCALAR_TO_VECTOR:
5287     assert(VT.isVector() && !Operand.getValueType().isVector() &&
5288            (VT.getVectorElementType() == Operand.getValueType() ||
5289             (VT.getVectorElementType().isInteger() &&
5290              Operand.getValueType().isInteger() &&
5291              VT.getVectorElementType().bitsLE(Operand.getValueType()))) &&
5292            "Illegal SCALAR_TO_VECTOR node!");
5293     if (OpOpcode == ISD::UNDEF)
5294       return getUNDEF(VT);
5295     // scalar_to_vector(extract_vector_elt V, 0) -> V, top bits are undefined.
5296     if (OpOpcode == ISD::EXTRACT_VECTOR_ELT &&
5297         isa<ConstantSDNode>(Operand.getOperand(1)) &&
5298         Operand.getConstantOperandVal(1) == 0 &&
5299         Operand.getOperand(0).getValueType() == VT)
5300       return Operand.getOperand(0);
5301     break;
5302   case ISD::FNEG:
5303     // Negation of an unknown bag of bits is still completely undefined.
5304     if (OpOpcode == ISD::UNDEF)
5305       return getUNDEF(VT);
5306 
5307     if (OpOpcode == ISD::FNEG)  // --X -> X
5308       return Operand.getOperand(0);
5309     break;
5310   case ISD::FABS:
5311     if (OpOpcode == ISD::FNEG)  // abs(-X) -> abs(X)
5312       return getNode(ISD::FABS, DL, VT, Operand.getOperand(0));
5313     break;
5314   case ISD::VSCALE:
5315     assert(VT == Operand.getValueType() && "Unexpected VT!");
5316     break;
5317   case ISD::CTPOP:
5318     if (Operand.getValueType().getScalarType() == MVT::i1)
5319       return Operand;
5320     break;
5321   case ISD::CTLZ:
5322   case ISD::CTTZ:
5323     if (Operand.getValueType().getScalarType() == MVT::i1)
5324       return getNOT(DL, Operand, Operand.getValueType());
5325     break;
5326   case ISD::VECREDUCE_ADD:
5327     if (Operand.getValueType().getScalarType() == MVT::i1)
5328       return getNode(ISD::VECREDUCE_XOR, DL, VT, Operand);
5329     break;
5330   case ISD::VECREDUCE_SMIN:
5331   case ISD::VECREDUCE_UMAX:
5332     if (Operand.getValueType().getScalarType() == MVT::i1)
5333       return getNode(ISD::VECREDUCE_OR, DL, VT, Operand);
5334     break;
5335   case ISD::VECREDUCE_SMAX:
5336   case ISD::VECREDUCE_UMIN:
5337     if (Operand.getValueType().getScalarType() == MVT::i1)
5338       return getNode(ISD::VECREDUCE_AND, DL, VT, Operand);
5339     break;
5340   }
5341 
5342   SDNode *N;
5343   SDVTList VTs = getVTList(VT);
5344   SDValue Ops[] = {Operand};
5345   if (VT != MVT::Glue) { // Don't CSE flag producing nodes
5346     FoldingSetNodeID ID;
5347     AddNodeIDNode(ID, Opcode, VTs, Ops);
5348     void *IP = nullptr;
5349     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
5350       E->intersectFlagsWith(Flags);
5351       return SDValue(E, 0);
5352     }
5353 
5354     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
5355     N->setFlags(Flags);
5356     createOperands(N, Ops);
5357     CSEMap.InsertNode(N, IP);
5358   } else {
5359     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
5360     createOperands(N, Ops);
5361   }
5362 
5363   InsertNode(N);
5364   SDValue V = SDValue(N, 0);
5365   NewSDValueDbgMsg(V, "Creating new node: ", this);
5366   return V;
5367 }
5368 
5369 static llvm::Optional<APInt> FoldValue(unsigned Opcode, const APInt &C1,
5370                                        const APInt &C2) {
5371   switch (Opcode) {
5372   case ISD::ADD:  return C1 + C2;
5373   case ISD::SUB:  return C1 - C2;
5374   case ISD::MUL:  return C1 * C2;
5375   case ISD::AND:  return C1 & C2;
5376   case ISD::OR:   return C1 | C2;
5377   case ISD::XOR:  return C1 ^ C2;
5378   case ISD::SHL:  return C1 << C2;
5379   case ISD::SRL:  return C1.lshr(C2);
5380   case ISD::SRA:  return C1.ashr(C2);
5381   case ISD::ROTL: return C1.rotl(C2);
5382   case ISD::ROTR: return C1.rotr(C2);
5383   case ISD::SMIN: return C1.sle(C2) ? C1 : C2;
5384   case ISD::SMAX: return C1.sge(C2) ? C1 : C2;
5385   case ISD::UMIN: return C1.ule(C2) ? C1 : C2;
5386   case ISD::UMAX: return C1.uge(C2) ? C1 : C2;
5387   case ISD::SADDSAT: return C1.sadd_sat(C2);
5388   case ISD::UADDSAT: return C1.uadd_sat(C2);
5389   case ISD::SSUBSAT: return C1.ssub_sat(C2);
5390   case ISD::USUBSAT: return C1.usub_sat(C2);
5391   case ISD::SSHLSAT: return C1.sshl_sat(C2);
5392   case ISD::USHLSAT: return C1.ushl_sat(C2);
5393   case ISD::UDIV:
5394     if (!C2.getBoolValue())
5395       break;
5396     return C1.udiv(C2);
5397   case ISD::UREM:
5398     if (!C2.getBoolValue())
5399       break;
5400     return C1.urem(C2);
5401   case ISD::SDIV:
5402     if (!C2.getBoolValue())
5403       break;
5404     return C1.sdiv(C2);
5405   case ISD::SREM:
5406     if (!C2.getBoolValue())
5407       break;
5408     return C1.srem(C2);
5409   case ISD::MULHS: {
5410     unsigned FullWidth = C1.getBitWidth() * 2;
5411     APInt C1Ext = C1.sext(FullWidth);
5412     APInt C2Ext = C2.sext(FullWidth);
5413     return (C1Ext * C2Ext).extractBits(C1.getBitWidth(), C1.getBitWidth());
5414   }
5415   case ISD::MULHU: {
5416     unsigned FullWidth = C1.getBitWidth() * 2;
5417     APInt C1Ext = C1.zext(FullWidth);
5418     APInt C2Ext = C2.zext(FullWidth);
5419     return (C1Ext * C2Ext).extractBits(C1.getBitWidth(), C1.getBitWidth());
5420   }
5421   case ISD::AVGFLOORS: {
5422     unsigned FullWidth = C1.getBitWidth() + 1;
5423     APInt C1Ext = C1.sext(FullWidth);
5424     APInt C2Ext = C2.sext(FullWidth);
5425     return (C1Ext + C2Ext).extractBits(C1.getBitWidth(), 1);
5426   }
5427   case ISD::AVGFLOORU: {
5428     unsigned FullWidth = C1.getBitWidth() + 1;
5429     APInt C1Ext = C1.zext(FullWidth);
5430     APInt C2Ext = C2.zext(FullWidth);
5431     return (C1Ext + C2Ext).extractBits(C1.getBitWidth(), 1);
5432   }
5433   case ISD::AVGCEILS: {
5434     unsigned FullWidth = C1.getBitWidth() + 1;
5435     APInt C1Ext = C1.sext(FullWidth);
5436     APInt C2Ext = C2.sext(FullWidth);
5437     return (C1Ext + C2Ext + 1).extractBits(C1.getBitWidth(), 1);
5438   }
5439   case ISD::AVGCEILU: {
5440     unsigned FullWidth = C1.getBitWidth() + 1;
5441     APInt C1Ext = C1.zext(FullWidth);
5442     APInt C2Ext = C2.zext(FullWidth);
5443     return (C1Ext + C2Ext + 1).extractBits(C1.getBitWidth(), 1);
5444   }
5445   }
5446   return llvm::None;
5447 }
5448 
5449 SDValue SelectionDAG::FoldSymbolOffset(unsigned Opcode, EVT VT,
5450                                        const GlobalAddressSDNode *GA,
5451                                        const SDNode *N2) {
5452   if (GA->getOpcode() != ISD::GlobalAddress)
5453     return SDValue();
5454   if (!TLI->isOffsetFoldingLegal(GA))
5455     return SDValue();
5456   auto *C2 = dyn_cast<ConstantSDNode>(N2);
5457   if (!C2)
5458     return SDValue();
5459   int64_t Offset = C2->getSExtValue();
5460   switch (Opcode) {
5461   case ISD::ADD: break;
5462   case ISD::SUB: Offset = -uint64_t(Offset); break;
5463   default: return SDValue();
5464   }
5465   return getGlobalAddress(GA->getGlobal(), SDLoc(C2), VT,
5466                           GA->getOffset() + uint64_t(Offset));
5467 }
5468 
5469 bool SelectionDAG::isUndef(unsigned Opcode, ArrayRef<SDValue> Ops) {
5470   switch (Opcode) {
5471   case ISD::SDIV:
5472   case ISD::UDIV:
5473   case ISD::SREM:
5474   case ISD::UREM: {
5475     // If a divisor is zero/undef or any element of a divisor vector is
5476     // zero/undef, the whole op is undef.
5477     assert(Ops.size() == 2 && "Div/rem should have 2 operands");
5478     SDValue Divisor = Ops[1];
5479     if (Divisor.isUndef() || isNullConstant(Divisor))
5480       return true;
5481 
5482     return ISD::isBuildVectorOfConstantSDNodes(Divisor.getNode()) &&
5483            llvm::any_of(Divisor->op_values(),
5484                         [](SDValue V) { return V.isUndef() ||
5485                                         isNullConstant(V); });
5486     // TODO: Handle signed overflow.
5487   }
5488   // TODO: Handle oversized shifts.
5489   default:
5490     return false;
5491   }
5492 }
5493 
5494 SDValue SelectionDAG::FoldConstantArithmetic(unsigned Opcode, const SDLoc &DL,
5495                                              EVT VT, ArrayRef<SDValue> Ops) {
5496   // If the opcode is a target-specific ISD node, there's nothing we can
5497   // do here and the operand rules may not line up with the below, so
5498   // bail early.
5499   // We can't create a scalar CONCAT_VECTORS so skip it. It will break
5500   // for concats involving SPLAT_VECTOR. Concats of BUILD_VECTORS are handled by
5501   // foldCONCAT_VECTORS in getNode before this is called.
5502   if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::CONCAT_VECTORS)
5503     return SDValue();
5504 
5505   unsigned NumOps = Ops.size();
5506   if (NumOps == 0)
5507     return SDValue();
5508 
5509   if (isUndef(Opcode, Ops))
5510     return getUNDEF(VT);
5511 
5512   // Handle binops special cases.
5513   if (NumOps == 2) {
5514     if (SDValue CFP = foldConstantFPMath(Opcode, DL, VT, Ops[0], Ops[1]))
5515       return CFP;
5516 
5517     if (auto *C1 = dyn_cast<ConstantSDNode>(Ops[0])) {
5518       if (auto *C2 = dyn_cast<ConstantSDNode>(Ops[1])) {
5519         if (C1->isOpaque() || C2->isOpaque())
5520           return SDValue();
5521 
5522         Optional<APInt> FoldAttempt =
5523             FoldValue(Opcode, C1->getAPIntValue(), C2->getAPIntValue());
5524         if (!FoldAttempt)
5525           return SDValue();
5526 
5527         SDValue Folded = getConstant(FoldAttempt.getValue(), DL, VT);
5528         assert((!Folded || !VT.isVector()) &&
5529                "Can't fold vectors ops with scalar operands");
5530         return Folded;
5531       }
5532     }
5533 
5534     // fold (add Sym, c) -> Sym+c
5535     if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Ops[0]))
5536       return FoldSymbolOffset(Opcode, VT, GA, Ops[1].getNode());
5537     if (TLI->isCommutativeBinOp(Opcode))
5538       if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Ops[1]))
5539         return FoldSymbolOffset(Opcode, VT, GA, Ops[0].getNode());
5540   }
5541 
5542   // This is for vector folding only from here on.
5543   if (!VT.isVector())
5544     return SDValue();
5545 
5546   ElementCount NumElts = VT.getVectorElementCount();
5547 
5548   // See if we can fold through bitcasted integer ops.
5549   // TODO: Can we handle undef elements?
5550   if (NumOps == 2 && VT.isFixedLengthVector() && VT.isInteger() &&
5551       Ops[0].getValueType() == VT && Ops[1].getValueType() == VT &&
5552       Ops[0].getOpcode() == ISD::BITCAST &&
5553       Ops[1].getOpcode() == ISD::BITCAST) {
5554     SDValue N1 = peekThroughBitcasts(Ops[0]);
5555     SDValue N2 = peekThroughBitcasts(Ops[1]);
5556     auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
5557     auto *BV2 = dyn_cast<BuildVectorSDNode>(N2);
5558     EVT BVVT = N1.getValueType();
5559     if (BV1 && BV2 && BVVT.isInteger() && BVVT == N2.getValueType()) {
5560       bool IsLE = getDataLayout().isLittleEndian();
5561       unsigned EltBits = VT.getScalarSizeInBits();
5562       SmallVector<APInt> RawBits1, RawBits2;
5563       BitVector UndefElts1, UndefElts2;
5564       if (BV1->getConstantRawBits(IsLE, EltBits, RawBits1, UndefElts1) &&
5565           BV2->getConstantRawBits(IsLE, EltBits, RawBits2, UndefElts2) &&
5566           UndefElts1.none() && UndefElts2.none()) {
5567         SmallVector<APInt> RawBits;
5568         for (unsigned I = 0, E = NumElts.getFixedValue(); I != E; ++I) {
5569           Optional<APInt> Fold = FoldValue(Opcode, RawBits1[I], RawBits2[I]);
5570           if (!Fold)
5571             break;
5572           RawBits.push_back(Fold.getValue());
5573         }
5574         if (RawBits.size() == NumElts.getFixedValue()) {
5575           // We have constant folded, but we need to cast this again back to
5576           // the original (possibly legalized) type.
5577           SmallVector<APInt> DstBits;
5578           BitVector DstUndefs;
5579           BuildVectorSDNode::recastRawBits(IsLE, BVVT.getScalarSizeInBits(),
5580                                            DstBits, RawBits, DstUndefs,
5581                                            BitVector(RawBits.size(), false));
5582           EVT BVEltVT = BV1->getOperand(0).getValueType();
5583           unsigned BVEltBits = BVEltVT.getSizeInBits();
5584           SmallVector<SDValue> Ops(DstBits.size(), getUNDEF(BVEltVT));
5585           for (unsigned I = 0, E = DstBits.size(); I != E; ++I) {
5586             if (DstUndefs[I])
5587               continue;
5588             Ops[I] = getConstant(DstBits[I].sext(BVEltBits), DL, BVEltVT);
5589           }
5590           return getBitcast(VT, getBuildVector(BVVT, DL, Ops));
5591         }
5592       }
5593     }
5594   }
5595 
5596   // Fold (mul step_vector(C0), C1) to (step_vector(C0 * C1)).
5597   //      (shl step_vector(C0), C1) -> (step_vector(C0 << C1))
5598   if ((Opcode == ISD::MUL || Opcode == ISD::SHL) &&
5599       Ops[0].getOpcode() == ISD::STEP_VECTOR) {
5600     APInt RHSVal;
5601     if (ISD::isConstantSplatVector(Ops[1].getNode(), RHSVal)) {
5602       APInt NewStep = Opcode == ISD::MUL
5603                           ? Ops[0].getConstantOperandAPInt(0) * RHSVal
5604                           : Ops[0].getConstantOperandAPInt(0) << RHSVal;
5605       return getStepVector(DL, VT, NewStep);
5606     }
5607   }
5608 
5609   auto IsScalarOrSameVectorSize = [NumElts](const SDValue &Op) {
5610     return !Op.getValueType().isVector() ||
5611            Op.getValueType().getVectorElementCount() == NumElts;
5612   };
5613 
5614   auto IsBuildVectorSplatVectorOrUndef = [](const SDValue &Op) {
5615     return Op.isUndef() || Op.getOpcode() == ISD::CONDCODE ||
5616            Op.getOpcode() == ISD::BUILD_VECTOR ||
5617            Op.getOpcode() == ISD::SPLAT_VECTOR;
5618   };
5619 
5620   // All operands must be vector types with the same number of elements as
5621   // the result type and must be either UNDEF or a build/splat vector
5622   // or UNDEF scalars.
5623   if (!llvm::all_of(Ops, IsBuildVectorSplatVectorOrUndef) ||
5624       !llvm::all_of(Ops, IsScalarOrSameVectorSize))
5625     return SDValue();
5626 
5627   // If we are comparing vectors, then the result needs to be a i1 boolean that
5628   // is then extended back to the legal result type depending on how booleans
5629   // are represented.
5630   EVT SVT = (Opcode == ISD::SETCC ? MVT::i1 : VT.getScalarType());
5631   ISD::NodeType ExtendCode =
5632       (Opcode == ISD::SETCC && SVT != VT.getScalarType())
5633           ? TargetLowering::getExtendForContent(TLI->getBooleanContents(VT))
5634           : ISD::SIGN_EXTEND;
5635 
5636   // Find legal integer scalar type for constant promotion and
5637   // ensure that its scalar size is at least as large as source.
5638   EVT LegalSVT = VT.getScalarType();
5639   if (NewNodesMustHaveLegalTypes && LegalSVT.isInteger()) {
5640     LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT);
5641     if (LegalSVT.bitsLT(VT.getScalarType()))
5642       return SDValue();
5643   }
5644 
5645   // For scalable vector types we know we're dealing with SPLAT_VECTORs. We
5646   // only have one operand to check. For fixed-length vector types we may have
5647   // a combination of BUILD_VECTOR and SPLAT_VECTOR.
5648   unsigned NumVectorElts = NumElts.isScalable() ? 1 : NumElts.getFixedValue();
5649 
5650   // Constant fold each scalar lane separately.
5651   SmallVector<SDValue, 4> ScalarResults;
5652   for (unsigned I = 0; I != NumVectorElts; I++) {
5653     SmallVector<SDValue, 4> ScalarOps;
5654     for (SDValue Op : Ops) {
5655       EVT InSVT = Op.getValueType().getScalarType();
5656       if (Op.getOpcode() != ISD::BUILD_VECTOR &&
5657           Op.getOpcode() != ISD::SPLAT_VECTOR) {
5658         if (Op.isUndef())
5659           ScalarOps.push_back(getUNDEF(InSVT));
5660         else
5661           ScalarOps.push_back(Op);
5662         continue;
5663       }
5664 
5665       SDValue ScalarOp =
5666           Op.getOperand(Op.getOpcode() == ISD::SPLAT_VECTOR ? 0 : I);
5667       EVT ScalarVT = ScalarOp.getValueType();
5668 
5669       // Build vector (integer) scalar operands may need implicit
5670       // truncation - do this before constant folding.
5671       if (ScalarVT.isInteger() && ScalarVT.bitsGT(InSVT)) {
5672         // Don't create illegally-typed nodes unless they're constants or undef
5673         // - if we fail to constant fold we can't guarantee the (dead) nodes
5674         // we're creating will be cleaned up before being visited for
5675         // legalization.
5676         if (NewNodesMustHaveLegalTypes && !ScalarOp.isUndef() &&
5677             !isa<ConstantSDNode>(ScalarOp) &&
5678             TLI->getTypeAction(*getContext(), InSVT) !=
5679                 TargetLowering::TypeLegal)
5680           return SDValue();
5681         ScalarOp = getNode(ISD::TRUNCATE, DL, InSVT, ScalarOp);
5682       }
5683 
5684       ScalarOps.push_back(ScalarOp);
5685     }
5686 
5687     // Constant fold the scalar operands.
5688     SDValue ScalarResult = getNode(Opcode, DL, SVT, ScalarOps);
5689 
5690     // Legalize the (integer) scalar constant if necessary.
5691     if (LegalSVT != SVT)
5692       ScalarResult = getNode(ExtendCode, DL, LegalSVT, ScalarResult);
5693 
5694     // Scalar folding only succeeded if the result is a constant or UNDEF.
5695     if (!ScalarResult.isUndef() && ScalarResult.getOpcode() != ISD::Constant &&
5696         ScalarResult.getOpcode() != ISD::ConstantFP)
5697       return SDValue();
5698     ScalarResults.push_back(ScalarResult);
5699   }
5700 
5701   SDValue V = NumElts.isScalable() ? getSplatVector(VT, DL, ScalarResults[0])
5702                                    : getBuildVector(VT, DL, ScalarResults);
5703   NewSDValueDbgMsg(V, "New node fold constant vector: ", this);
5704   return V;
5705 }
5706 
5707 SDValue SelectionDAG::foldConstantFPMath(unsigned Opcode, const SDLoc &DL,
5708                                          EVT VT, SDValue N1, SDValue N2) {
5709   // TODO: We don't do any constant folding for strict FP opcodes here, but we
5710   //       should. That will require dealing with a potentially non-default
5711   //       rounding mode, checking the "opStatus" return value from the APFloat
5712   //       math calculations, and possibly other variations.
5713   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1, /*AllowUndefs*/ false);
5714   ConstantFPSDNode *N2CFP = isConstOrConstSplatFP(N2, /*AllowUndefs*/ false);
5715   if (N1CFP && N2CFP) {
5716     APFloat C1 = N1CFP->getValueAPF(); // make copy
5717     const APFloat &C2 = N2CFP->getValueAPF();
5718     switch (Opcode) {
5719     case ISD::FADD:
5720       C1.add(C2, APFloat::rmNearestTiesToEven);
5721       return getConstantFP(C1, DL, VT);
5722     case ISD::FSUB:
5723       C1.subtract(C2, APFloat::rmNearestTiesToEven);
5724       return getConstantFP(C1, DL, VT);
5725     case ISD::FMUL:
5726       C1.multiply(C2, APFloat::rmNearestTiesToEven);
5727       return getConstantFP(C1, DL, VT);
5728     case ISD::FDIV:
5729       C1.divide(C2, APFloat::rmNearestTiesToEven);
5730       return getConstantFP(C1, DL, VT);
5731     case ISD::FREM:
5732       C1.mod(C2);
5733       return getConstantFP(C1, DL, VT);
5734     case ISD::FCOPYSIGN:
5735       C1.copySign(C2);
5736       return getConstantFP(C1, DL, VT);
5737     case ISD::FMINNUM:
5738       return getConstantFP(minnum(C1, C2), DL, VT);
5739     case ISD::FMAXNUM:
5740       return getConstantFP(maxnum(C1, C2), DL, VT);
5741     case ISD::FMINIMUM:
5742       return getConstantFP(minimum(C1, C2), DL, VT);
5743     case ISD::FMAXIMUM:
5744       return getConstantFP(maximum(C1, C2), DL, VT);
5745     default: break;
5746     }
5747   }
5748   if (N1CFP && Opcode == ISD::FP_ROUND) {
5749     APFloat C1 = N1CFP->getValueAPF();    // make copy
5750     bool Unused;
5751     // This can return overflow, underflow, or inexact; we don't care.
5752     // FIXME need to be more flexible about rounding mode.
5753     (void) C1.convert(EVTToAPFloatSemantics(VT), APFloat::rmNearestTiesToEven,
5754                       &Unused);
5755     return getConstantFP(C1, DL, VT);
5756   }
5757 
5758   switch (Opcode) {
5759   case ISD::FSUB:
5760     // -0.0 - undef --> undef (consistent with "fneg undef")
5761     if (ConstantFPSDNode *N1C = isConstOrConstSplatFP(N1, /*AllowUndefs*/ true))
5762       if (N1C && N1C->getValueAPF().isNegZero() && N2.isUndef())
5763         return getUNDEF(VT);
5764     LLVM_FALLTHROUGH;
5765 
5766   case ISD::FADD:
5767   case ISD::FMUL:
5768   case ISD::FDIV:
5769   case ISD::FREM:
5770     // If both operands are undef, the result is undef. If 1 operand is undef,
5771     // the result is NaN. This should match the behavior of the IR optimizer.
5772     if (N1.isUndef() && N2.isUndef())
5773       return getUNDEF(VT);
5774     if (N1.isUndef() || N2.isUndef())
5775       return getConstantFP(APFloat::getNaN(EVTToAPFloatSemantics(VT)), DL, VT);
5776   }
5777   return SDValue();
5778 }
5779 
5780 SDValue SelectionDAG::getAssertAlign(const SDLoc &DL, SDValue Val, Align A) {
5781   assert(Val.getValueType().isInteger() && "Invalid AssertAlign!");
5782 
5783   // There's no need to assert on a byte-aligned pointer. All pointers are at
5784   // least byte aligned.
5785   if (A == Align(1))
5786     return Val;
5787 
5788   FoldingSetNodeID ID;
5789   AddNodeIDNode(ID, ISD::AssertAlign, getVTList(Val.getValueType()), {Val});
5790   ID.AddInteger(A.value());
5791 
5792   void *IP = nullptr;
5793   if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
5794     return SDValue(E, 0);
5795 
5796   auto *N = newSDNode<AssertAlignSDNode>(DL.getIROrder(), DL.getDebugLoc(),
5797                                          Val.getValueType(), A);
5798   createOperands(N, {Val});
5799 
5800   CSEMap.InsertNode(N, IP);
5801   InsertNode(N);
5802 
5803   SDValue V(N, 0);
5804   NewSDValueDbgMsg(V, "Creating new node: ", this);
5805   return V;
5806 }
5807 
5808 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
5809                               SDValue N1, SDValue N2) {
5810   SDNodeFlags Flags;
5811   if (Inserter)
5812     Flags = Inserter->getFlags();
5813   return getNode(Opcode, DL, VT, N1, N2, Flags);
5814 }
5815 
5816 void SelectionDAG::canonicalizeCommutativeBinop(unsigned Opcode, SDValue &N1,
5817                                                 SDValue &N2) const {
5818   if (!TLI->isCommutativeBinOp(Opcode))
5819     return;
5820 
5821   // Canonicalize:
5822   //   binop(const, nonconst) -> binop(nonconst, const)
5823   bool IsN1C = isConstantIntBuildVectorOrConstantInt(N1);
5824   bool IsN2C = isConstantIntBuildVectorOrConstantInt(N2);
5825   bool IsN1CFP = isConstantFPBuildVectorOrConstantFP(N1);
5826   bool IsN2CFP = isConstantFPBuildVectorOrConstantFP(N2);
5827   if ((IsN1C && !IsN2C) || (IsN1CFP && !IsN2CFP))
5828     std::swap(N1, N2);
5829 
5830   // Canonicalize:
5831   //  binop(splat(x), step_vector) -> binop(step_vector, splat(x))
5832   else if (N1.getOpcode() == ISD::SPLAT_VECTOR &&
5833            N2.getOpcode() == ISD::STEP_VECTOR)
5834     std::swap(N1, N2);
5835 }
5836 
5837 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
5838                               SDValue N1, SDValue N2, const SDNodeFlags Flags) {
5839   assert(N1.getOpcode() != ISD::DELETED_NODE &&
5840          N2.getOpcode() != ISD::DELETED_NODE &&
5841          "Operand is DELETED_NODE!");
5842 
5843   canonicalizeCommutativeBinop(Opcode, N1, N2);
5844 
5845   auto *N1C = dyn_cast<ConstantSDNode>(N1);
5846   auto *N2C = dyn_cast<ConstantSDNode>(N2);
5847 
5848   // Don't allow undefs in vector splats - we might be returning N2 when folding
5849   // to zero etc.
5850   ConstantSDNode *N2CV =
5851       isConstOrConstSplat(N2, /*AllowUndefs*/ false, /*AllowTruncation*/ true);
5852 
5853   switch (Opcode) {
5854   default: break;
5855   case ISD::TokenFactor:
5856     assert(VT == MVT::Other && N1.getValueType() == MVT::Other &&
5857            N2.getValueType() == MVT::Other && "Invalid token factor!");
5858     // Fold trivial token factors.
5859     if (N1.getOpcode() == ISD::EntryToken) return N2;
5860     if (N2.getOpcode() == ISD::EntryToken) return N1;
5861     if (N1 == N2) return N1;
5862     break;
5863   case ISD::BUILD_VECTOR: {
5864     // Attempt to simplify BUILD_VECTOR.
5865     SDValue Ops[] = {N1, N2};
5866     if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
5867       return V;
5868     break;
5869   }
5870   case ISD::CONCAT_VECTORS: {
5871     SDValue Ops[] = {N1, N2};
5872     if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this))
5873       return V;
5874     break;
5875   }
5876   case ISD::AND:
5877     assert(VT.isInteger() && "This operator does not apply to FP types!");
5878     assert(N1.getValueType() == N2.getValueType() &&
5879            N1.getValueType() == VT && "Binary operator types must match!");
5880     // (X & 0) -> 0.  This commonly occurs when legalizing i64 values, so it's
5881     // worth handling here.
5882     if (N2CV && N2CV->isZero())
5883       return N2;
5884     if (N2CV && N2CV->isAllOnes()) // X & -1 -> X
5885       return N1;
5886     break;
5887   case ISD::OR:
5888   case ISD::XOR:
5889   case ISD::ADD:
5890   case ISD::SUB:
5891     assert(VT.isInteger() && "This operator does not apply to FP types!");
5892     assert(N1.getValueType() == N2.getValueType() &&
5893            N1.getValueType() == VT && "Binary operator types must match!");
5894     // (X ^|+- 0) -> X.  This commonly occurs when legalizing i64 values, so
5895     // it's worth handling here.
5896     if (N2CV && N2CV->isZero())
5897       return N1;
5898     if ((Opcode == ISD::ADD || Opcode == ISD::SUB) && VT.isVector() &&
5899         VT.getVectorElementType() == MVT::i1)
5900       return getNode(ISD::XOR, DL, VT, N1, N2);
5901     break;
5902   case ISD::MUL:
5903     assert(VT.isInteger() && "This operator does not apply to FP types!");
5904     assert(N1.getValueType() == N2.getValueType() &&
5905            N1.getValueType() == VT && "Binary operator types must match!");
5906     if (VT.isVector() && VT.getVectorElementType() == MVT::i1)
5907       return getNode(ISD::AND, DL, VT, N1, N2);
5908     if (N2C && (N1.getOpcode() == ISD::VSCALE) && Flags.hasNoSignedWrap()) {
5909       const APInt &MulImm = N1->getConstantOperandAPInt(0);
5910       const APInt &N2CImm = N2C->getAPIntValue();
5911       return getVScale(DL, VT, MulImm * N2CImm);
5912     }
5913     break;
5914   case ISD::UDIV:
5915   case ISD::UREM:
5916   case ISD::MULHU:
5917   case ISD::MULHS:
5918   case ISD::SDIV:
5919   case ISD::SREM:
5920   case ISD::SADDSAT:
5921   case ISD::SSUBSAT:
5922   case ISD::UADDSAT:
5923   case ISD::USUBSAT:
5924     assert(VT.isInteger() && "This operator does not apply to FP types!");
5925     assert(N1.getValueType() == N2.getValueType() &&
5926            N1.getValueType() == VT && "Binary operator types must match!");
5927     if (VT.isVector() && VT.getVectorElementType() == MVT::i1) {
5928       // fold (add_sat x, y) -> (or x, y) for bool types.
5929       if (Opcode == ISD::SADDSAT || Opcode == ISD::UADDSAT)
5930         return getNode(ISD::OR, DL, VT, N1, N2);
5931       // fold (sub_sat x, y) -> (and x, ~y) for bool types.
5932       if (Opcode == ISD::SSUBSAT || Opcode == ISD::USUBSAT)
5933         return getNode(ISD::AND, DL, VT, N1, getNOT(DL, N2, VT));
5934     }
5935     break;
5936   case ISD::SMIN:
5937   case ISD::UMAX:
5938     assert(VT.isInteger() && "This operator does not apply to FP types!");
5939     assert(N1.getValueType() == N2.getValueType() &&
5940            N1.getValueType() == VT && "Binary operator types must match!");
5941     if (VT.isVector() && VT.getVectorElementType() == MVT::i1)
5942       return getNode(ISD::OR, DL, VT, N1, N2);
5943     break;
5944   case ISD::SMAX:
5945   case ISD::UMIN:
5946     assert(VT.isInteger() && "This operator does not apply to FP types!");
5947     assert(N1.getValueType() == N2.getValueType() &&
5948            N1.getValueType() == VT && "Binary operator types must match!");
5949     if (VT.isVector() && VT.getVectorElementType() == MVT::i1)
5950       return getNode(ISD::AND, DL, VT, N1, N2);
5951     break;
5952   case ISD::FADD:
5953   case ISD::FSUB:
5954   case ISD::FMUL:
5955   case ISD::FDIV:
5956   case ISD::FREM:
5957     assert(VT.isFloatingPoint() && "This operator only applies to FP types!");
5958     assert(N1.getValueType() == N2.getValueType() &&
5959            N1.getValueType() == VT && "Binary operator types must match!");
5960     if (SDValue V = simplifyFPBinop(Opcode, N1, N2, Flags))
5961       return V;
5962     break;
5963   case ISD::FCOPYSIGN:   // N1 and result must match.  N1/N2 need not match.
5964     assert(N1.getValueType() == VT &&
5965            N1.getValueType().isFloatingPoint() &&
5966            N2.getValueType().isFloatingPoint() &&
5967            "Invalid FCOPYSIGN!");
5968     break;
5969   case ISD::SHL:
5970     if (N2C && (N1.getOpcode() == ISD::VSCALE) && Flags.hasNoSignedWrap()) {
5971       const APInt &MulImm = N1->getConstantOperandAPInt(0);
5972       const APInt &ShiftImm = N2C->getAPIntValue();
5973       return getVScale(DL, VT, MulImm << ShiftImm);
5974     }
5975     LLVM_FALLTHROUGH;
5976   case ISD::SRA:
5977   case ISD::SRL:
5978     if (SDValue V = simplifyShift(N1, N2))
5979       return V;
5980     LLVM_FALLTHROUGH;
5981   case ISD::ROTL:
5982   case ISD::ROTR:
5983     assert(VT == N1.getValueType() &&
5984            "Shift operators return type must be the same as their first arg");
5985     assert(VT.isInteger() && N2.getValueType().isInteger() &&
5986            "Shifts only work on integers");
5987     assert((!VT.isVector() || VT == N2.getValueType()) &&
5988            "Vector shift amounts must be in the same as their first arg");
5989     // Verify that the shift amount VT is big enough to hold valid shift
5990     // amounts.  This catches things like trying to shift an i1024 value by an
5991     // i8, which is easy to fall into in generic code that uses
5992     // TLI.getShiftAmount().
5993     assert(N2.getValueType().getScalarSizeInBits() >=
5994                Log2_32_Ceil(VT.getScalarSizeInBits()) &&
5995            "Invalid use of small shift amount with oversized value!");
5996 
5997     // Always fold shifts of i1 values so the code generator doesn't need to
5998     // handle them.  Since we know the size of the shift has to be less than the
5999     // size of the value, the shift/rotate count is guaranteed to be zero.
6000     if (VT == MVT::i1)
6001       return N1;
6002     if (N2CV && N2CV->isZero())
6003       return N1;
6004     break;
6005   case ISD::FP_ROUND:
6006     assert(VT.isFloatingPoint() &&
6007            N1.getValueType().isFloatingPoint() &&
6008            VT.bitsLE(N1.getValueType()) &&
6009            N2C && (N2C->getZExtValue() == 0 || N2C->getZExtValue() == 1) &&
6010            "Invalid FP_ROUND!");
6011     if (N1.getValueType() == VT) return N1;  // noop conversion.
6012     break;
6013   case ISD::AssertSext:
6014   case ISD::AssertZext: {
6015     EVT EVT = cast<VTSDNode>(N2)->getVT();
6016     assert(VT == N1.getValueType() && "Not an inreg extend!");
6017     assert(VT.isInteger() && EVT.isInteger() &&
6018            "Cannot *_EXTEND_INREG FP types");
6019     assert(!EVT.isVector() &&
6020            "AssertSExt/AssertZExt type should be the vector element type "
6021            "rather than the vector type!");
6022     assert(EVT.bitsLE(VT.getScalarType()) && "Not extending!");
6023     if (VT.getScalarType() == EVT) return N1; // noop assertion.
6024     break;
6025   }
6026   case ISD::SIGN_EXTEND_INREG: {
6027     EVT EVT = cast<VTSDNode>(N2)->getVT();
6028     assert(VT == N1.getValueType() && "Not an inreg extend!");
6029     assert(VT.isInteger() && EVT.isInteger() &&
6030            "Cannot *_EXTEND_INREG FP types");
6031     assert(EVT.isVector() == VT.isVector() &&
6032            "SIGN_EXTEND_INREG type should be vector iff the operand "
6033            "type is vector!");
6034     assert((!EVT.isVector() ||
6035             EVT.getVectorElementCount() == VT.getVectorElementCount()) &&
6036            "Vector element counts must match in SIGN_EXTEND_INREG");
6037     assert(EVT.bitsLE(VT) && "Not extending!");
6038     if (EVT == VT) return N1;  // Not actually extending
6039 
6040     auto SignExtendInReg = [&](APInt Val, llvm::EVT ConstantVT) {
6041       unsigned FromBits = EVT.getScalarSizeInBits();
6042       Val <<= Val.getBitWidth() - FromBits;
6043       Val.ashrInPlace(Val.getBitWidth() - FromBits);
6044       return getConstant(Val, DL, ConstantVT);
6045     };
6046 
6047     if (N1C) {
6048       const APInt &Val = N1C->getAPIntValue();
6049       return SignExtendInReg(Val, VT);
6050     }
6051 
6052     if (ISD::isBuildVectorOfConstantSDNodes(N1.getNode())) {
6053       SmallVector<SDValue, 8> Ops;
6054       llvm::EVT OpVT = N1.getOperand(0).getValueType();
6055       for (int i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
6056         SDValue Op = N1.getOperand(i);
6057         if (Op.isUndef()) {
6058           Ops.push_back(getUNDEF(OpVT));
6059           continue;
6060         }
6061         ConstantSDNode *C = cast<ConstantSDNode>(Op);
6062         APInt Val = C->getAPIntValue();
6063         Ops.push_back(SignExtendInReg(Val, OpVT));
6064       }
6065       return getBuildVector(VT, DL, Ops);
6066     }
6067     break;
6068   }
6069   case ISD::FP_TO_SINT_SAT:
6070   case ISD::FP_TO_UINT_SAT: {
6071     assert(VT.isInteger() && cast<VTSDNode>(N2)->getVT().isInteger() &&
6072            N1.getValueType().isFloatingPoint() && "Invalid FP_TO_*INT_SAT");
6073     assert(N1.getValueType().isVector() == VT.isVector() &&
6074            "FP_TO_*INT_SAT type should be vector iff the operand type is "
6075            "vector!");
6076     assert((!VT.isVector() || VT.getVectorNumElements() ==
6077                                   N1.getValueType().getVectorNumElements()) &&
6078            "Vector element counts must match in FP_TO_*INT_SAT");
6079     assert(!cast<VTSDNode>(N2)->getVT().isVector() &&
6080            "Type to saturate to must be a scalar.");
6081     assert(cast<VTSDNode>(N2)->getVT().bitsLE(VT.getScalarType()) &&
6082            "Not extending!");
6083     break;
6084   }
6085   case ISD::EXTRACT_VECTOR_ELT:
6086     assert(VT.getSizeInBits() >= N1.getValueType().getScalarSizeInBits() &&
6087            "The result of EXTRACT_VECTOR_ELT must be at least as wide as the \
6088              element type of the vector.");
6089 
6090     // Extract from an undefined value or using an undefined index is undefined.
6091     if (N1.isUndef() || N2.isUndef())
6092       return getUNDEF(VT);
6093 
6094     // EXTRACT_VECTOR_ELT of out-of-bounds element is an UNDEF for fixed length
6095     // vectors. For scalable vectors we will provide appropriate support for
6096     // dealing with arbitrary indices.
6097     if (N2C && N1.getValueType().isFixedLengthVector() &&
6098         N2C->getAPIntValue().uge(N1.getValueType().getVectorNumElements()))
6099       return getUNDEF(VT);
6100 
6101     // EXTRACT_VECTOR_ELT of CONCAT_VECTORS is often formed while lowering is
6102     // expanding copies of large vectors from registers. This only works for
6103     // fixed length vectors, since we need to know the exact number of
6104     // elements.
6105     if (N2C && N1.getOperand(0).getValueType().isFixedLengthVector() &&
6106         N1.getOpcode() == ISD::CONCAT_VECTORS && N1.getNumOperands() > 0) {
6107       unsigned Factor =
6108         N1.getOperand(0).getValueType().getVectorNumElements();
6109       return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
6110                      N1.getOperand(N2C->getZExtValue() / Factor),
6111                      getVectorIdxConstant(N2C->getZExtValue() % Factor, DL));
6112     }
6113 
6114     // EXTRACT_VECTOR_ELT of BUILD_VECTOR or SPLAT_VECTOR is often formed while
6115     // lowering is expanding large vector constants.
6116     if (N2C && (N1.getOpcode() == ISD::BUILD_VECTOR ||
6117                 N1.getOpcode() == ISD::SPLAT_VECTOR)) {
6118       assert((N1.getOpcode() != ISD::BUILD_VECTOR ||
6119               N1.getValueType().isFixedLengthVector()) &&
6120              "BUILD_VECTOR used for scalable vectors");
6121       unsigned Index =
6122           N1.getOpcode() == ISD::BUILD_VECTOR ? N2C->getZExtValue() : 0;
6123       SDValue Elt = N1.getOperand(Index);
6124 
6125       if (VT != Elt.getValueType())
6126         // If the vector element type is not legal, the BUILD_VECTOR operands
6127         // are promoted and implicitly truncated, and the result implicitly
6128         // extended. Make that explicit here.
6129         Elt = getAnyExtOrTrunc(Elt, DL, VT);
6130 
6131       return Elt;
6132     }
6133 
6134     // EXTRACT_VECTOR_ELT of INSERT_VECTOR_ELT is often formed when vector
6135     // operations are lowered to scalars.
6136     if (N1.getOpcode() == ISD::INSERT_VECTOR_ELT) {
6137       // If the indices are the same, return the inserted element else
6138       // if the indices are known different, extract the element from
6139       // the original vector.
6140       SDValue N1Op2 = N1.getOperand(2);
6141       ConstantSDNode *N1Op2C = dyn_cast<ConstantSDNode>(N1Op2);
6142 
6143       if (N1Op2C && N2C) {
6144         if (N1Op2C->getZExtValue() == N2C->getZExtValue()) {
6145           if (VT == N1.getOperand(1).getValueType())
6146             return N1.getOperand(1);
6147           return getSExtOrTrunc(N1.getOperand(1), DL, VT);
6148         }
6149         return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0), N2);
6150       }
6151     }
6152 
6153     // EXTRACT_VECTOR_ELT of v1iX EXTRACT_SUBVECTOR could be formed
6154     // when vector types are scalarized and v1iX is legal.
6155     // vextract (v1iX extract_subvector(vNiX, Idx)) -> vextract(vNiX,Idx).
6156     // Here we are completely ignoring the extract element index (N2),
6157     // which is fine for fixed width vectors, since any index other than 0
6158     // is undefined anyway. However, this cannot be ignored for scalable
6159     // vectors - in theory we could support this, but we don't want to do this
6160     // without a profitability check.
6161     if (N1.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
6162         N1.getValueType().isFixedLengthVector() &&
6163         N1.getValueType().getVectorNumElements() == 1) {
6164       return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0),
6165                      N1.getOperand(1));
6166     }
6167     break;
6168   case ISD::EXTRACT_ELEMENT:
6169     assert(N2C && (unsigned)N2C->getZExtValue() < 2 && "Bad EXTRACT_ELEMENT!");
6170     assert(!N1.getValueType().isVector() && !VT.isVector() &&
6171            (N1.getValueType().isInteger() == VT.isInteger()) &&
6172            N1.getValueType() != VT &&
6173            "Wrong types for EXTRACT_ELEMENT!");
6174 
6175     // EXTRACT_ELEMENT of BUILD_PAIR is often formed while legalize is expanding
6176     // 64-bit integers into 32-bit parts.  Instead of building the extract of
6177     // the BUILD_PAIR, only to have legalize rip it apart, just do it now.
6178     if (N1.getOpcode() == ISD::BUILD_PAIR)
6179       return N1.getOperand(N2C->getZExtValue());
6180 
6181     // EXTRACT_ELEMENT of a constant int is also very common.
6182     if (N1C) {
6183       unsigned ElementSize = VT.getSizeInBits();
6184       unsigned Shift = ElementSize * N2C->getZExtValue();
6185       const APInt &Val = N1C->getAPIntValue();
6186       return getConstant(Val.extractBits(ElementSize, Shift), DL, VT);
6187     }
6188     break;
6189   case ISD::EXTRACT_SUBVECTOR: {
6190     EVT N1VT = N1.getValueType();
6191     assert(VT.isVector() && N1VT.isVector() &&
6192            "Extract subvector VTs must be vectors!");
6193     assert(VT.getVectorElementType() == N1VT.getVectorElementType() &&
6194            "Extract subvector VTs must have the same element type!");
6195     assert((VT.isFixedLengthVector() || N1VT.isScalableVector()) &&
6196            "Cannot extract a scalable vector from a fixed length vector!");
6197     assert((VT.isScalableVector() != N1VT.isScalableVector() ||
6198             VT.getVectorMinNumElements() <= N1VT.getVectorMinNumElements()) &&
6199            "Extract subvector must be from larger vector to smaller vector!");
6200     assert(N2C && "Extract subvector index must be a constant");
6201     assert((VT.isScalableVector() != N1VT.isScalableVector() ||
6202             (VT.getVectorMinNumElements() + N2C->getZExtValue()) <=
6203                 N1VT.getVectorMinNumElements()) &&
6204            "Extract subvector overflow!");
6205     assert(N2C->getAPIntValue().getBitWidth() ==
6206                TLI->getVectorIdxTy(getDataLayout()).getFixedSizeInBits() &&
6207            "Constant index for EXTRACT_SUBVECTOR has an invalid size");
6208 
6209     // Trivial extraction.
6210     if (VT == N1VT)
6211       return N1;
6212 
6213     // EXTRACT_SUBVECTOR of an UNDEF is an UNDEF.
6214     if (N1.isUndef())
6215       return getUNDEF(VT);
6216 
6217     // EXTRACT_SUBVECTOR of CONCAT_VECTOR can be simplified if the pieces of
6218     // the concat have the same type as the extract.
6219     if (N1.getOpcode() == ISD::CONCAT_VECTORS && N1.getNumOperands() > 0 &&
6220         VT == N1.getOperand(0).getValueType()) {
6221       unsigned Factor = VT.getVectorMinNumElements();
6222       return N1.getOperand(N2C->getZExtValue() / Factor);
6223     }
6224 
6225     // EXTRACT_SUBVECTOR of INSERT_SUBVECTOR is often created
6226     // during shuffle legalization.
6227     if (N1.getOpcode() == ISD::INSERT_SUBVECTOR && N2 == N1.getOperand(2) &&
6228         VT == N1.getOperand(1).getValueType())
6229       return N1.getOperand(1);
6230     break;
6231   }
6232   }
6233 
6234   // Perform trivial constant folding.
6235   if (SDValue SV = FoldConstantArithmetic(Opcode, DL, VT, {N1, N2}))
6236     return SV;
6237 
6238   // Canonicalize an UNDEF to the RHS, even over a constant.
6239   if (N1.isUndef()) {
6240     if (TLI->isCommutativeBinOp(Opcode)) {
6241       std::swap(N1, N2);
6242     } else {
6243       switch (Opcode) {
6244       case ISD::SUB:
6245         return getUNDEF(VT);     // fold op(undef, arg2) -> undef
6246       case ISD::SIGN_EXTEND_INREG:
6247       case ISD::UDIV:
6248       case ISD::SDIV:
6249       case ISD::UREM:
6250       case ISD::SREM:
6251       case ISD::SSUBSAT:
6252       case ISD::USUBSAT:
6253         return getConstant(0, DL, VT);    // fold op(undef, arg2) -> 0
6254       }
6255     }
6256   }
6257 
6258   // Fold a bunch of operators when the RHS is undef.
6259   if (N2.isUndef()) {
6260     switch (Opcode) {
6261     case ISD::XOR:
6262       if (N1.isUndef())
6263         // Handle undef ^ undef -> 0 special case. This is a common
6264         // idiom (misuse).
6265         return getConstant(0, DL, VT);
6266       LLVM_FALLTHROUGH;
6267     case ISD::ADD:
6268     case ISD::SUB:
6269     case ISD::UDIV:
6270     case ISD::SDIV:
6271     case ISD::UREM:
6272     case ISD::SREM:
6273       return getUNDEF(VT);       // fold op(arg1, undef) -> undef
6274     case ISD::MUL:
6275     case ISD::AND:
6276     case ISD::SSUBSAT:
6277     case ISD::USUBSAT:
6278       return getConstant(0, DL, VT);  // fold op(arg1, undef) -> 0
6279     case ISD::OR:
6280     case ISD::SADDSAT:
6281     case ISD::UADDSAT:
6282       return getAllOnesConstant(DL, VT);
6283     }
6284   }
6285 
6286   // Memoize this node if possible.
6287   SDNode *N;
6288   SDVTList VTs = getVTList(VT);
6289   SDValue Ops[] = {N1, N2};
6290   if (VT != MVT::Glue) {
6291     FoldingSetNodeID ID;
6292     AddNodeIDNode(ID, Opcode, VTs, Ops);
6293     void *IP = nullptr;
6294     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
6295       E->intersectFlagsWith(Flags);
6296       return SDValue(E, 0);
6297     }
6298 
6299     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
6300     N->setFlags(Flags);
6301     createOperands(N, Ops);
6302     CSEMap.InsertNode(N, IP);
6303   } else {
6304     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
6305     createOperands(N, Ops);
6306   }
6307 
6308   InsertNode(N);
6309   SDValue V = SDValue(N, 0);
6310   NewSDValueDbgMsg(V, "Creating new node: ", this);
6311   return V;
6312 }
6313 
6314 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
6315                               SDValue N1, SDValue N2, SDValue N3) {
6316   SDNodeFlags Flags;
6317   if (Inserter)
6318     Flags = Inserter->getFlags();
6319   return getNode(Opcode, DL, VT, N1, N2, N3, Flags);
6320 }
6321 
6322 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
6323                               SDValue N1, SDValue N2, SDValue N3,
6324                               const SDNodeFlags Flags) {
6325   assert(N1.getOpcode() != ISD::DELETED_NODE &&
6326          N2.getOpcode() != ISD::DELETED_NODE &&
6327          N3.getOpcode() != ISD::DELETED_NODE &&
6328          "Operand is DELETED_NODE!");
6329   // Perform various simplifications.
6330   switch (Opcode) {
6331   case ISD::FMA: {
6332     assert(VT.isFloatingPoint() && "This operator only applies to FP types!");
6333     assert(N1.getValueType() == VT && N2.getValueType() == VT &&
6334            N3.getValueType() == VT && "FMA types must match!");
6335     ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6336     ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2);
6337     ConstantFPSDNode *N3CFP = dyn_cast<ConstantFPSDNode>(N3);
6338     if (N1CFP && N2CFP && N3CFP) {
6339       APFloat  V1 = N1CFP->getValueAPF();
6340       const APFloat &V2 = N2CFP->getValueAPF();
6341       const APFloat &V3 = N3CFP->getValueAPF();
6342       V1.fusedMultiplyAdd(V2, V3, APFloat::rmNearestTiesToEven);
6343       return getConstantFP(V1, DL, VT);
6344     }
6345     break;
6346   }
6347   case ISD::BUILD_VECTOR: {
6348     // Attempt to simplify BUILD_VECTOR.
6349     SDValue Ops[] = {N1, N2, N3};
6350     if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
6351       return V;
6352     break;
6353   }
6354   case ISD::CONCAT_VECTORS: {
6355     SDValue Ops[] = {N1, N2, N3};
6356     if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this))
6357       return V;
6358     break;
6359   }
6360   case ISD::SETCC: {
6361     assert(VT.isInteger() && "SETCC result type must be an integer!");
6362     assert(N1.getValueType() == N2.getValueType() &&
6363            "SETCC operands must have the same type!");
6364     assert(VT.isVector() == N1.getValueType().isVector() &&
6365            "SETCC type should be vector iff the operand type is vector!");
6366     assert((!VT.isVector() || VT.getVectorElementCount() ==
6367                                   N1.getValueType().getVectorElementCount()) &&
6368            "SETCC vector element counts must match!");
6369     // Use FoldSetCC to simplify SETCC's.
6370     if (SDValue V = FoldSetCC(VT, N1, N2, cast<CondCodeSDNode>(N3)->get(), DL))
6371       return V;
6372     // Vector constant folding.
6373     SDValue Ops[] = {N1, N2, N3};
6374     if (SDValue V = FoldConstantArithmetic(Opcode, DL, VT, Ops)) {
6375       NewSDValueDbgMsg(V, "New node vector constant folding: ", this);
6376       return V;
6377     }
6378     break;
6379   }
6380   case ISD::SELECT:
6381   case ISD::VSELECT:
6382     if (SDValue V = simplifySelect(N1, N2, N3))
6383       return V;
6384     break;
6385   case ISD::VECTOR_SHUFFLE:
6386     llvm_unreachable("should use getVectorShuffle constructor!");
6387   case ISD::VECTOR_SPLICE: {
6388     if (cast<ConstantSDNode>(N3)->isNullValue())
6389       return N1;
6390     break;
6391   }
6392   case ISD::INSERT_VECTOR_ELT: {
6393     ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3);
6394     // INSERT_VECTOR_ELT into out-of-bounds element is an UNDEF, except
6395     // for scalable vectors where we will generate appropriate code to
6396     // deal with out-of-bounds cases correctly.
6397     if (N3C && N1.getValueType().isFixedLengthVector() &&
6398         N3C->getZExtValue() >= N1.getValueType().getVectorNumElements())
6399       return getUNDEF(VT);
6400 
6401     // Undefined index can be assumed out-of-bounds, so that's UNDEF too.
6402     if (N3.isUndef())
6403       return getUNDEF(VT);
6404 
6405     // If the inserted element is an UNDEF, just use the input vector.
6406     if (N2.isUndef())
6407       return N1;
6408 
6409     break;
6410   }
6411   case ISD::INSERT_SUBVECTOR: {
6412     // Inserting undef into undef is still undef.
6413     if (N1.isUndef() && N2.isUndef())
6414       return getUNDEF(VT);
6415 
6416     EVT N2VT = N2.getValueType();
6417     assert(VT == N1.getValueType() &&
6418            "Dest and insert subvector source types must match!");
6419     assert(VT.isVector() && N2VT.isVector() &&
6420            "Insert subvector VTs must be vectors!");
6421     assert((VT.isScalableVector() || N2VT.isFixedLengthVector()) &&
6422            "Cannot insert a scalable vector into a fixed length vector!");
6423     assert((VT.isScalableVector() != N2VT.isScalableVector() ||
6424             VT.getVectorMinNumElements() >= N2VT.getVectorMinNumElements()) &&
6425            "Insert subvector must be from smaller vector to larger vector!");
6426     assert(isa<ConstantSDNode>(N3) &&
6427            "Insert subvector index must be constant");
6428     assert((VT.isScalableVector() != N2VT.isScalableVector() ||
6429             (N2VT.getVectorMinNumElements() +
6430              cast<ConstantSDNode>(N3)->getZExtValue()) <=
6431                 VT.getVectorMinNumElements()) &&
6432            "Insert subvector overflow!");
6433     assert(cast<ConstantSDNode>(N3)->getAPIntValue().getBitWidth() ==
6434                TLI->getVectorIdxTy(getDataLayout()).getFixedSizeInBits() &&
6435            "Constant index for INSERT_SUBVECTOR has an invalid size");
6436 
6437     // Trivial insertion.
6438     if (VT == N2VT)
6439       return N2;
6440 
6441     // If this is an insert of an extracted vector into an undef vector, we
6442     // can just use the input to the extract.
6443     if (N1.isUndef() && N2.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
6444         N2.getOperand(1) == N3 && N2.getOperand(0).getValueType() == VT)
6445       return N2.getOperand(0);
6446     break;
6447   }
6448   case ISD::BITCAST:
6449     // Fold bit_convert nodes from a type to themselves.
6450     if (N1.getValueType() == VT)
6451       return N1;
6452     break;
6453   }
6454 
6455   // Memoize node if it doesn't produce a flag.
6456   SDNode *N;
6457   SDVTList VTs = getVTList(VT);
6458   SDValue Ops[] = {N1, N2, N3};
6459   if (VT != MVT::Glue) {
6460     FoldingSetNodeID ID;
6461     AddNodeIDNode(ID, Opcode, VTs, Ops);
6462     void *IP = nullptr;
6463     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
6464       E->intersectFlagsWith(Flags);
6465       return SDValue(E, 0);
6466     }
6467 
6468     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
6469     N->setFlags(Flags);
6470     createOperands(N, Ops);
6471     CSEMap.InsertNode(N, IP);
6472   } else {
6473     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
6474     createOperands(N, Ops);
6475   }
6476 
6477   InsertNode(N);
6478   SDValue V = SDValue(N, 0);
6479   NewSDValueDbgMsg(V, "Creating new node: ", this);
6480   return V;
6481 }
6482 
6483 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
6484                               SDValue N1, SDValue N2, SDValue N3, SDValue N4) {
6485   SDValue Ops[] = { N1, N2, N3, N4 };
6486   return getNode(Opcode, DL, VT, Ops);
6487 }
6488 
6489 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
6490                               SDValue N1, SDValue N2, SDValue N3, SDValue N4,
6491                               SDValue N5) {
6492   SDValue Ops[] = { N1, N2, N3, N4, N5 };
6493   return getNode(Opcode, DL, VT, Ops);
6494 }
6495 
6496 /// getStackArgumentTokenFactor - Compute a TokenFactor to force all
6497 /// the incoming stack arguments to be loaded from the stack.
6498 SDValue SelectionDAG::getStackArgumentTokenFactor(SDValue Chain) {
6499   SmallVector<SDValue, 8> ArgChains;
6500 
6501   // Include the original chain at the beginning of the list. When this is
6502   // used by target LowerCall hooks, this helps legalize find the
6503   // CALLSEQ_BEGIN node.
6504   ArgChains.push_back(Chain);
6505 
6506   // Add a chain value for each stack argument.
6507   for (SDNode *U : getEntryNode().getNode()->uses())
6508     if (LoadSDNode *L = dyn_cast<LoadSDNode>(U))
6509       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
6510         if (FI->getIndex() < 0)
6511           ArgChains.push_back(SDValue(L, 1));
6512 
6513   // Build a tokenfactor for all the chains.
6514   return getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains);
6515 }
6516 
6517 /// getMemsetValue - Vectorized representation of the memset value
6518 /// operand.
6519 static SDValue getMemsetValue(SDValue Value, EVT VT, SelectionDAG &DAG,
6520                               const SDLoc &dl) {
6521   assert(!Value.isUndef());
6522 
6523   unsigned NumBits = VT.getScalarSizeInBits();
6524   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
6525     assert(C->getAPIntValue().getBitWidth() == 8);
6526     APInt Val = APInt::getSplat(NumBits, C->getAPIntValue());
6527     if (VT.isInteger()) {
6528       bool IsOpaque = VT.getSizeInBits() > 64 ||
6529           !DAG.getTargetLoweringInfo().isLegalStoreImmediate(C->getSExtValue());
6530       return DAG.getConstant(Val, dl, VT, false, IsOpaque);
6531     }
6532     return DAG.getConstantFP(APFloat(DAG.EVTToAPFloatSemantics(VT), Val), dl,
6533                              VT);
6534   }
6535 
6536   assert(Value.getValueType() == MVT::i8 && "memset with non-byte fill value?");
6537   EVT IntVT = VT.getScalarType();
6538   if (!IntVT.isInteger())
6539     IntVT = EVT::getIntegerVT(*DAG.getContext(), IntVT.getSizeInBits());
6540 
6541   Value = DAG.getNode(ISD::ZERO_EXTEND, dl, IntVT, Value);
6542   if (NumBits > 8) {
6543     // Use a multiplication with 0x010101... to extend the input to the
6544     // required length.
6545     APInt Magic = APInt::getSplat(NumBits, APInt(8, 0x01));
6546     Value = DAG.getNode(ISD::MUL, dl, IntVT, Value,
6547                         DAG.getConstant(Magic, dl, IntVT));
6548   }
6549 
6550   if (VT != Value.getValueType() && !VT.isInteger())
6551     Value = DAG.getBitcast(VT.getScalarType(), Value);
6552   if (VT != Value.getValueType())
6553     Value = DAG.getSplatBuildVector(VT, dl, Value);
6554 
6555   return Value;
6556 }
6557 
6558 /// getMemsetStringVal - Similar to getMemsetValue. Except this is only
6559 /// used when a memcpy is turned into a memset when the source is a constant
6560 /// string ptr.
6561 static SDValue getMemsetStringVal(EVT VT, const SDLoc &dl, SelectionDAG &DAG,
6562                                   const TargetLowering &TLI,
6563                                   const ConstantDataArraySlice &Slice) {
6564   // Handle vector with all elements zero.
6565   if (Slice.Array == nullptr) {
6566     if (VT.isInteger())
6567       return DAG.getConstant(0, dl, VT);
6568     if (VT == MVT::f32 || VT == MVT::f64 || VT == MVT::f128)
6569       return DAG.getConstantFP(0.0, dl, VT);
6570     if (VT.isVector()) {
6571       unsigned NumElts = VT.getVectorNumElements();
6572       MVT EltVT = (VT.getVectorElementType() == MVT::f32) ? MVT::i32 : MVT::i64;
6573       return DAG.getNode(ISD::BITCAST, dl, VT,
6574                          DAG.getConstant(0, dl,
6575                                          EVT::getVectorVT(*DAG.getContext(),
6576                                                           EltVT, NumElts)));
6577     }
6578     llvm_unreachable("Expected type!");
6579   }
6580 
6581   assert(!VT.isVector() && "Can't handle vector type here!");
6582   unsigned NumVTBits = VT.getSizeInBits();
6583   unsigned NumVTBytes = NumVTBits / 8;
6584   unsigned NumBytes = std::min(NumVTBytes, unsigned(Slice.Length));
6585 
6586   APInt Val(NumVTBits, 0);
6587   if (DAG.getDataLayout().isLittleEndian()) {
6588     for (unsigned i = 0; i != NumBytes; ++i)
6589       Val |= (uint64_t)(unsigned char)Slice[i] << i*8;
6590   } else {
6591     for (unsigned i = 0; i != NumBytes; ++i)
6592       Val |= (uint64_t)(unsigned char)Slice[i] << (NumVTBytes-i-1)*8;
6593   }
6594 
6595   // If the "cost" of materializing the integer immediate is less than the cost
6596   // of a load, then it is cost effective to turn the load into the immediate.
6597   Type *Ty = VT.getTypeForEVT(*DAG.getContext());
6598   if (TLI.shouldConvertConstantLoadToIntImm(Val, Ty))
6599     return DAG.getConstant(Val, dl, VT);
6600   return SDValue();
6601 }
6602 
6603 SDValue SelectionDAG::getMemBasePlusOffset(SDValue Base, TypeSize Offset,
6604                                            const SDLoc &DL,
6605                                            const SDNodeFlags Flags) {
6606   EVT VT = Base.getValueType();
6607   SDValue Index;
6608 
6609   if (Offset.isScalable())
6610     Index = getVScale(DL, Base.getValueType(),
6611                       APInt(Base.getValueSizeInBits().getFixedSize(),
6612                             Offset.getKnownMinSize()));
6613   else
6614     Index = getConstant(Offset.getFixedSize(), DL, VT);
6615 
6616   return getMemBasePlusOffset(Base, Index, DL, Flags);
6617 }
6618 
6619 SDValue SelectionDAG::getMemBasePlusOffset(SDValue Ptr, SDValue Offset,
6620                                            const SDLoc &DL,
6621                                            const SDNodeFlags Flags) {
6622   assert(Offset.getValueType().isInteger());
6623   EVT BasePtrVT = Ptr.getValueType();
6624   return getNode(ISD::ADD, DL, BasePtrVT, Ptr, Offset, Flags);
6625 }
6626 
6627 /// Returns true if memcpy source is constant data.
6628 static bool isMemSrcFromConstant(SDValue Src, ConstantDataArraySlice &Slice) {
6629   uint64_t SrcDelta = 0;
6630   GlobalAddressSDNode *G = nullptr;
6631   if (Src.getOpcode() == ISD::GlobalAddress)
6632     G = cast<GlobalAddressSDNode>(Src);
6633   else if (Src.getOpcode() == ISD::ADD &&
6634            Src.getOperand(0).getOpcode() == ISD::GlobalAddress &&
6635            Src.getOperand(1).getOpcode() == ISD::Constant) {
6636     G = cast<GlobalAddressSDNode>(Src.getOperand(0));
6637     SrcDelta = cast<ConstantSDNode>(Src.getOperand(1))->getZExtValue();
6638   }
6639   if (!G)
6640     return false;
6641 
6642   return getConstantDataArrayInfo(G->getGlobal(), Slice, 8,
6643                                   SrcDelta + G->getOffset());
6644 }
6645 
6646 static bool shouldLowerMemFuncForSize(const MachineFunction &MF,
6647                                       SelectionDAG &DAG) {
6648   // On Darwin, -Os means optimize for size without hurting performance, so
6649   // only really optimize for size when -Oz (MinSize) is used.
6650   if (MF.getTarget().getTargetTriple().isOSDarwin())
6651     return MF.getFunction().hasMinSize();
6652   return DAG.shouldOptForSize();
6653 }
6654 
6655 static void chainLoadsAndStoresForMemcpy(SelectionDAG &DAG, const SDLoc &dl,
6656                           SmallVector<SDValue, 32> &OutChains, unsigned From,
6657                           unsigned To, SmallVector<SDValue, 16> &OutLoadChains,
6658                           SmallVector<SDValue, 16> &OutStoreChains) {
6659   assert(OutLoadChains.size() && "Missing loads in memcpy inlining");
6660   assert(OutStoreChains.size() && "Missing stores in memcpy inlining");
6661   SmallVector<SDValue, 16> GluedLoadChains;
6662   for (unsigned i = From; i < To; ++i) {
6663     OutChains.push_back(OutLoadChains[i]);
6664     GluedLoadChains.push_back(OutLoadChains[i]);
6665   }
6666 
6667   // Chain for all loads.
6668   SDValue LoadToken = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
6669                                   GluedLoadChains);
6670 
6671   for (unsigned i = From; i < To; ++i) {
6672     StoreSDNode *ST = dyn_cast<StoreSDNode>(OutStoreChains[i]);
6673     SDValue NewStore = DAG.getTruncStore(LoadToken, dl, ST->getValue(),
6674                                   ST->getBasePtr(), ST->getMemoryVT(),
6675                                   ST->getMemOperand());
6676     OutChains.push_back(NewStore);
6677   }
6678 }
6679 
6680 static SDValue getMemcpyLoadsAndStores(SelectionDAG &DAG, const SDLoc &dl,
6681                                        SDValue Chain, SDValue Dst, SDValue Src,
6682                                        uint64_t Size, Align Alignment,
6683                                        bool isVol, bool AlwaysInline,
6684                                        MachinePointerInfo DstPtrInfo,
6685                                        MachinePointerInfo SrcPtrInfo,
6686                                        const AAMDNodes &AAInfo) {
6687   // Turn a memcpy of undef to nop.
6688   // FIXME: We need to honor volatile even is Src is undef.
6689   if (Src.isUndef())
6690     return Chain;
6691 
6692   // Expand memcpy to a series of load and store ops if the size operand falls
6693   // below a certain threshold.
6694   // TODO: In the AlwaysInline case, if the size is big then generate a loop
6695   // rather than maybe a humongous number of loads and stores.
6696   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6697   const DataLayout &DL = DAG.getDataLayout();
6698   LLVMContext &C = *DAG.getContext();
6699   std::vector<EVT> MemOps;
6700   bool DstAlignCanChange = false;
6701   MachineFunction &MF = DAG.getMachineFunction();
6702   MachineFrameInfo &MFI = MF.getFrameInfo();
6703   bool OptSize = shouldLowerMemFuncForSize(MF, DAG);
6704   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
6705   if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
6706     DstAlignCanChange = true;
6707   MaybeAlign SrcAlign = DAG.InferPtrAlign(Src);
6708   if (!SrcAlign || Alignment > *SrcAlign)
6709     SrcAlign = Alignment;
6710   assert(SrcAlign && "SrcAlign must be set");
6711   ConstantDataArraySlice Slice;
6712   // If marked as volatile, perform a copy even when marked as constant.
6713   bool CopyFromConstant = !isVol && isMemSrcFromConstant(Src, Slice);
6714   bool isZeroConstant = CopyFromConstant && Slice.Array == nullptr;
6715   unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemcpy(OptSize);
6716   const MemOp Op = isZeroConstant
6717                        ? MemOp::Set(Size, DstAlignCanChange, Alignment,
6718                                     /*IsZeroMemset*/ true, isVol)
6719                        : MemOp::Copy(Size, DstAlignCanChange, Alignment,
6720                                      *SrcAlign, isVol, CopyFromConstant);
6721   if (!TLI.findOptimalMemOpLowering(
6722           MemOps, Limit, Op, DstPtrInfo.getAddrSpace(),
6723           SrcPtrInfo.getAddrSpace(), MF.getFunction().getAttributes()))
6724     return SDValue();
6725 
6726   if (DstAlignCanChange) {
6727     Type *Ty = MemOps[0].getTypeForEVT(C);
6728     Align NewAlign = DL.getABITypeAlign(Ty);
6729 
6730     // Don't promote to an alignment that would require dynamic stack
6731     // realignment.
6732     const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
6733     if (!TRI->hasStackRealignment(MF))
6734       while (NewAlign > Alignment && DL.exceedsNaturalStackAlignment(NewAlign))
6735         NewAlign = NewAlign / 2;
6736 
6737     if (NewAlign > Alignment) {
6738       // Give the stack frame object a larger alignment if needed.
6739       if (MFI.getObjectAlign(FI->getIndex()) < NewAlign)
6740         MFI.setObjectAlignment(FI->getIndex(), NewAlign);
6741       Alignment = NewAlign;
6742     }
6743   }
6744 
6745   // Prepare AAInfo for loads/stores after lowering this memcpy.
6746   AAMDNodes NewAAInfo = AAInfo;
6747   NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr;
6748 
6749   MachineMemOperand::Flags MMOFlags =
6750       isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone;
6751   SmallVector<SDValue, 16> OutLoadChains;
6752   SmallVector<SDValue, 16> OutStoreChains;
6753   SmallVector<SDValue, 32> OutChains;
6754   unsigned NumMemOps = MemOps.size();
6755   uint64_t SrcOff = 0, DstOff = 0;
6756   for (unsigned i = 0; i != NumMemOps; ++i) {
6757     EVT VT = MemOps[i];
6758     unsigned VTSize = VT.getSizeInBits() / 8;
6759     SDValue Value, Store;
6760 
6761     if (VTSize > Size) {
6762       // Issuing an unaligned load / store pair  that overlaps with the previous
6763       // pair. Adjust the offset accordingly.
6764       assert(i == NumMemOps-1 && i != 0);
6765       SrcOff -= VTSize - Size;
6766       DstOff -= VTSize - Size;
6767     }
6768 
6769     if (CopyFromConstant &&
6770         (isZeroConstant || (VT.isInteger() && !VT.isVector()))) {
6771       // It's unlikely a store of a vector immediate can be done in a single
6772       // instruction. It would require a load from a constantpool first.
6773       // We only handle zero vectors here.
6774       // FIXME: Handle other cases where store of vector immediate is done in
6775       // a single instruction.
6776       ConstantDataArraySlice SubSlice;
6777       if (SrcOff < Slice.Length) {
6778         SubSlice = Slice;
6779         SubSlice.move(SrcOff);
6780       } else {
6781         // This is an out-of-bounds access and hence UB. Pretend we read zero.
6782         SubSlice.Array = nullptr;
6783         SubSlice.Offset = 0;
6784         SubSlice.Length = VTSize;
6785       }
6786       Value = getMemsetStringVal(VT, dl, DAG, TLI, SubSlice);
6787       if (Value.getNode()) {
6788         Store = DAG.getStore(
6789             Chain, dl, Value,
6790             DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl),
6791             DstPtrInfo.getWithOffset(DstOff), Alignment, MMOFlags, NewAAInfo);
6792         OutChains.push_back(Store);
6793       }
6794     }
6795 
6796     if (!Store.getNode()) {
6797       // The type might not be legal for the target.  This should only happen
6798       // if the type is smaller than a legal type, as on PPC, so the right
6799       // thing to do is generate a LoadExt/StoreTrunc pair.  These simplify
6800       // to Load/Store if NVT==VT.
6801       // FIXME does the case above also need this?
6802       EVT NVT = TLI.getTypeToTransformTo(C, VT);
6803       assert(NVT.bitsGE(VT));
6804 
6805       bool isDereferenceable =
6806         SrcPtrInfo.getWithOffset(SrcOff).isDereferenceable(VTSize, C, DL);
6807       MachineMemOperand::Flags SrcMMOFlags = MMOFlags;
6808       if (isDereferenceable)
6809         SrcMMOFlags |= MachineMemOperand::MODereferenceable;
6810 
6811       Value = DAG.getExtLoad(
6812           ISD::EXTLOAD, dl, NVT, Chain,
6813           DAG.getMemBasePlusOffset(Src, TypeSize::Fixed(SrcOff), dl),
6814           SrcPtrInfo.getWithOffset(SrcOff), VT,
6815           commonAlignment(*SrcAlign, SrcOff), SrcMMOFlags, NewAAInfo);
6816       OutLoadChains.push_back(Value.getValue(1));
6817 
6818       Store = DAG.getTruncStore(
6819           Chain, dl, Value,
6820           DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl),
6821           DstPtrInfo.getWithOffset(DstOff), VT, Alignment, MMOFlags, NewAAInfo);
6822       OutStoreChains.push_back(Store);
6823     }
6824     SrcOff += VTSize;
6825     DstOff += VTSize;
6826     Size -= VTSize;
6827   }
6828 
6829   unsigned GluedLdStLimit = MaxLdStGlue == 0 ?
6830                                 TLI.getMaxGluedStoresPerMemcpy() : MaxLdStGlue;
6831   unsigned NumLdStInMemcpy = OutStoreChains.size();
6832 
6833   if (NumLdStInMemcpy) {
6834     // It may be that memcpy might be converted to memset if it's memcpy
6835     // of constants. In such a case, we won't have loads and stores, but
6836     // just stores. In the absence of loads, there is nothing to gang up.
6837     if ((GluedLdStLimit <= 1) || !EnableMemCpyDAGOpt) {
6838       // If target does not care, just leave as it.
6839       for (unsigned i = 0; i < NumLdStInMemcpy; ++i) {
6840         OutChains.push_back(OutLoadChains[i]);
6841         OutChains.push_back(OutStoreChains[i]);
6842       }
6843     } else {
6844       // Ld/St less than/equal limit set by target.
6845       if (NumLdStInMemcpy <= GluedLdStLimit) {
6846           chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, 0,
6847                                         NumLdStInMemcpy, OutLoadChains,
6848                                         OutStoreChains);
6849       } else {
6850         unsigned NumberLdChain =  NumLdStInMemcpy / GluedLdStLimit;
6851         unsigned RemainingLdStInMemcpy = NumLdStInMemcpy % GluedLdStLimit;
6852         unsigned GlueIter = 0;
6853 
6854         for (unsigned cnt = 0; cnt < NumberLdChain; ++cnt) {
6855           unsigned IndexFrom = NumLdStInMemcpy - GlueIter - GluedLdStLimit;
6856           unsigned IndexTo   = NumLdStInMemcpy - GlueIter;
6857 
6858           chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, IndexFrom, IndexTo,
6859                                        OutLoadChains, OutStoreChains);
6860           GlueIter += GluedLdStLimit;
6861         }
6862 
6863         // Residual ld/st.
6864         if (RemainingLdStInMemcpy) {
6865           chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, 0,
6866                                         RemainingLdStInMemcpy, OutLoadChains,
6867                                         OutStoreChains);
6868         }
6869       }
6870     }
6871   }
6872   return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
6873 }
6874 
6875 static SDValue getMemmoveLoadsAndStores(SelectionDAG &DAG, const SDLoc &dl,
6876                                         SDValue Chain, SDValue Dst, SDValue Src,
6877                                         uint64_t Size, Align Alignment,
6878                                         bool isVol, bool AlwaysInline,
6879                                         MachinePointerInfo DstPtrInfo,
6880                                         MachinePointerInfo SrcPtrInfo,
6881                                         const AAMDNodes &AAInfo) {
6882   // Turn a memmove of undef to nop.
6883   // FIXME: We need to honor volatile even is Src is undef.
6884   if (Src.isUndef())
6885     return Chain;
6886 
6887   // Expand memmove to a series of load and store ops if the size operand falls
6888   // below a certain threshold.
6889   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6890   const DataLayout &DL = DAG.getDataLayout();
6891   LLVMContext &C = *DAG.getContext();
6892   std::vector<EVT> MemOps;
6893   bool DstAlignCanChange = false;
6894   MachineFunction &MF = DAG.getMachineFunction();
6895   MachineFrameInfo &MFI = MF.getFrameInfo();
6896   bool OptSize = shouldLowerMemFuncForSize(MF, DAG);
6897   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
6898   if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
6899     DstAlignCanChange = true;
6900   MaybeAlign SrcAlign = DAG.InferPtrAlign(Src);
6901   if (!SrcAlign || Alignment > *SrcAlign)
6902     SrcAlign = Alignment;
6903   assert(SrcAlign && "SrcAlign must be set");
6904   unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemmove(OptSize);
6905   if (!TLI.findOptimalMemOpLowering(
6906           MemOps, Limit,
6907           MemOp::Copy(Size, DstAlignCanChange, Alignment, *SrcAlign,
6908                       /*IsVolatile*/ true),
6909           DstPtrInfo.getAddrSpace(), SrcPtrInfo.getAddrSpace(),
6910           MF.getFunction().getAttributes()))
6911     return SDValue();
6912 
6913   if (DstAlignCanChange) {
6914     Type *Ty = MemOps[0].getTypeForEVT(C);
6915     Align NewAlign = DL.getABITypeAlign(Ty);
6916     if (NewAlign > Alignment) {
6917       // Give the stack frame object a larger alignment if needed.
6918       if (MFI.getObjectAlign(FI->getIndex()) < NewAlign)
6919         MFI.setObjectAlignment(FI->getIndex(), NewAlign);
6920       Alignment = NewAlign;
6921     }
6922   }
6923 
6924   // Prepare AAInfo for loads/stores after lowering this memmove.
6925   AAMDNodes NewAAInfo = AAInfo;
6926   NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr;
6927 
6928   MachineMemOperand::Flags MMOFlags =
6929       isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone;
6930   uint64_t SrcOff = 0, DstOff = 0;
6931   SmallVector<SDValue, 8> LoadValues;
6932   SmallVector<SDValue, 8> LoadChains;
6933   SmallVector<SDValue, 8> OutChains;
6934   unsigned NumMemOps = MemOps.size();
6935   for (unsigned i = 0; i < NumMemOps; i++) {
6936     EVT VT = MemOps[i];
6937     unsigned VTSize = VT.getSizeInBits() / 8;
6938     SDValue Value;
6939 
6940     bool isDereferenceable =
6941       SrcPtrInfo.getWithOffset(SrcOff).isDereferenceable(VTSize, C, DL);
6942     MachineMemOperand::Flags SrcMMOFlags = MMOFlags;
6943     if (isDereferenceable)
6944       SrcMMOFlags |= MachineMemOperand::MODereferenceable;
6945 
6946     Value = DAG.getLoad(
6947         VT, dl, Chain,
6948         DAG.getMemBasePlusOffset(Src, TypeSize::Fixed(SrcOff), dl),
6949         SrcPtrInfo.getWithOffset(SrcOff), *SrcAlign, SrcMMOFlags, NewAAInfo);
6950     LoadValues.push_back(Value);
6951     LoadChains.push_back(Value.getValue(1));
6952     SrcOff += VTSize;
6953   }
6954   Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
6955   OutChains.clear();
6956   for (unsigned i = 0; i < NumMemOps; i++) {
6957     EVT VT = MemOps[i];
6958     unsigned VTSize = VT.getSizeInBits() / 8;
6959     SDValue Store;
6960 
6961     Store = DAG.getStore(
6962         Chain, dl, LoadValues[i],
6963         DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl),
6964         DstPtrInfo.getWithOffset(DstOff), Alignment, MMOFlags, NewAAInfo);
6965     OutChains.push_back(Store);
6966     DstOff += VTSize;
6967   }
6968 
6969   return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
6970 }
6971 
6972 /// Lower the call to 'memset' intrinsic function into a series of store
6973 /// operations.
6974 ///
6975 /// \param DAG Selection DAG where lowered code is placed.
6976 /// \param dl Link to corresponding IR location.
6977 /// \param Chain Control flow dependency.
6978 /// \param Dst Pointer to destination memory location.
6979 /// \param Src Value of byte to write into the memory.
6980 /// \param Size Number of bytes to write.
6981 /// \param Alignment Alignment of the destination in bytes.
6982 /// \param isVol True if destination is volatile.
6983 /// \param DstPtrInfo IR information on the memory pointer.
6984 /// \returns New head in the control flow, if lowering was successful, empty
6985 /// SDValue otherwise.
6986 ///
6987 /// The function tries to replace 'llvm.memset' intrinsic with several store
6988 /// operations and value calculation code. This is usually profitable for small
6989 /// memory size.
6990 static SDValue getMemsetStores(SelectionDAG &DAG, const SDLoc &dl,
6991                                SDValue Chain, SDValue Dst, SDValue Src,
6992                                uint64_t Size, Align Alignment, bool isVol,
6993                                MachinePointerInfo DstPtrInfo,
6994                                const AAMDNodes &AAInfo) {
6995   // Turn a memset of undef to nop.
6996   // FIXME: We need to honor volatile even is Src is undef.
6997   if (Src.isUndef())
6998     return Chain;
6999 
7000   // Expand memset to a series of load/store ops if the size operand
7001   // falls below a certain threshold.
7002   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7003   std::vector<EVT> MemOps;
7004   bool DstAlignCanChange = false;
7005   MachineFunction &MF = DAG.getMachineFunction();
7006   MachineFrameInfo &MFI = MF.getFrameInfo();
7007   bool OptSize = shouldLowerMemFuncForSize(MF, DAG);
7008   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
7009   if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
7010     DstAlignCanChange = true;
7011   bool IsZeroVal =
7012       isa<ConstantSDNode>(Src) && cast<ConstantSDNode>(Src)->isZero();
7013   if (!TLI.findOptimalMemOpLowering(
7014           MemOps, TLI.getMaxStoresPerMemset(OptSize),
7015           MemOp::Set(Size, DstAlignCanChange, Alignment, IsZeroVal, isVol),
7016           DstPtrInfo.getAddrSpace(), ~0u, MF.getFunction().getAttributes()))
7017     return SDValue();
7018 
7019   if (DstAlignCanChange) {
7020     Type *Ty = MemOps[0].getTypeForEVT(*DAG.getContext());
7021     Align NewAlign = DAG.getDataLayout().getABITypeAlign(Ty);
7022     if (NewAlign > Alignment) {
7023       // Give the stack frame object a larger alignment if needed.
7024       if (MFI.getObjectAlign(FI->getIndex()) < NewAlign)
7025         MFI.setObjectAlignment(FI->getIndex(), NewAlign);
7026       Alignment = NewAlign;
7027     }
7028   }
7029 
7030   SmallVector<SDValue, 8> OutChains;
7031   uint64_t DstOff = 0;
7032   unsigned NumMemOps = MemOps.size();
7033 
7034   // Find the largest store and generate the bit pattern for it.
7035   EVT LargestVT = MemOps[0];
7036   for (unsigned i = 1; i < NumMemOps; i++)
7037     if (MemOps[i].bitsGT(LargestVT))
7038       LargestVT = MemOps[i];
7039   SDValue MemSetValue = getMemsetValue(Src, LargestVT, DAG, dl);
7040 
7041   // Prepare AAInfo for loads/stores after lowering this memset.
7042   AAMDNodes NewAAInfo = AAInfo;
7043   NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr;
7044 
7045   for (unsigned i = 0; i < NumMemOps; i++) {
7046     EVT VT = MemOps[i];
7047     unsigned VTSize = VT.getSizeInBits() / 8;
7048     if (VTSize > Size) {
7049       // Issuing an unaligned load / store pair  that overlaps with the previous
7050       // pair. Adjust the offset accordingly.
7051       assert(i == NumMemOps-1 && i != 0);
7052       DstOff -= VTSize - Size;
7053     }
7054 
7055     // If this store is smaller than the largest store see whether we can get
7056     // the smaller value for free with a truncate.
7057     SDValue Value = MemSetValue;
7058     if (VT.bitsLT(LargestVT)) {
7059       if (!LargestVT.isVector() && !VT.isVector() &&
7060           TLI.isTruncateFree(LargestVT, VT))
7061         Value = DAG.getNode(ISD::TRUNCATE, dl, VT, MemSetValue);
7062       else
7063         Value = getMemsetValue(Src, VT, DAG, dl);
7064     }
7065     assert(Value.getValueType() == VT && "Value with wrong type.");
7066     SDValue Store = DAG.getStore(
7067         Chain, dl, Value,
7068         DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl),
7069         DstPtrInfo.getWithOffset(DstOff), Alignment,
7070         isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone,
7071         NewAAInfo);
7072     OutChains.push_back(Store);
7073     DstOff += VT.getSizeInBits() / 8;
7074     Size -= VTSize;
7075   }
7076 
7077   return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
7078 }
7079 
7080 static void checkAddrSpaceIsValidForLibcall(const TargetLowering *TLI,
7081                                             unsigned AS) {
7082   // Lowering memcpy / memset / memmove intrinsics to calls is only valid if all
7083   // pointer operands can be losslessly bitcasted to pointers of address space 0
7084   if (AS != 0 && !TLI->getTargetMachine().isNoopAddrSpaceCast(AS, 0)) {
7085     report_fatal_error("cannot lower memory intrinsic in address space " +
7086                        Twine(AS));
7087   }
7088 }
7089 
7090 SDValue SelectionDAG::getMemcpy(SDValue Chain, const SDLoc &dl, SDValue Dst,
7091                                 SDValue Src, SDValue Size, Align Alignment,
7092                                 bool isVol, bool AlwaysInline, bool isTailCall,
7093                                 MachinePointerInfo DstPtrInfo,
7094                                 MachinePointerInfo SrcPtrInfo,
7095                                 const AAMDNodes &AAInfo) {
7096   // Check to see if we should lower the memcpy to loads and stores first.
7097   // For cases within the target-specified limits, this is the best choice.
7098   ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
7099   if (ConstantSize) {
7100     // Memcpy with size zero? Just return the original chain.
7101     if (ConstantSize->isZero())
7102       return Chain;
7103 
7104     SDValue Result = getMemcpyLoadsAndStores(
7105         *this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), Alignment,
7106         isVol, false, DstPtrInfo, SrcPtrInfo, AAInfo);
7107     if (Result.getNode())
7108       return Result;
7109   }
7110 
7111   // Then check to see if we should lower the memcpy with target-specific
7112   // code. If the target chooses to do this, this is the next best.
7113   if (TSI) {
7114     SDValue Result = TSI->EmitTargetCodeForMemcpy(
7115         *this, dl, Chain, Dst, Src, Size, Alignment, isVol, AlwaysInline,
7116         DstPtrInfo, SrcPtrInfo);
7117     if (Result.getNode())
7118       return Result;
7119   }
7120 
7121   // If we really need inline code and the target declined to provide it,
7122   // use a (potentially long) sequence of loads and stores.
7123   if (AlwaysInline) {
7124     assert(ConstantSize && "AlwaysInline requires a constant size!");
7125     return getMemcpyLoadsAndStores(*this, dl, Chain, Dst, Src,
7126                                    ConstantSize->getZExtValue(), Alignment,
7127                                    isVol, true, DstPtrInfo, SrcPtrInfo, AAInfo);
7128   }
7129 
7130   checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace());
7131   checkAddrSpaceIsValidForLibcall(TLI, SrcPtrInfo.getAddrSpace());
7132 
7133   // FIXME: If the memcpy is volatile (isVol), lowering it to a plain libc
7134   // memcpy is not guaranteed to be safe. libc memcpys aren't required to
7135   // respect volatile, so they may do things like read or write memory
7136   // beyond the given memory regions. But fixing this isn't easy, and most
7137   // people don't care.
7138 
7139   // Emit a library call.
7140   TargetLowering::ArgListTy Args;
7141   TargetLowering::ArgListEntry Entry;
7142   Entry.Ty = Type::getInt8PtrTy(*getContext());
7143   Entry.Node = Dst; Args.push_back(Entry);
7144   Entry.Node = Src; Args.push_back(Entry);
7145 
7146   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
7147   Entry.Node = Size; Args.push_back(Entry);
7148   // FIXME: pass in SDLoc
7149   TargetLowering::CallLoweringInfo CLI(*this);
7150   CLI.setDebugLoc(dl)
7151       .setChain(Chain)
7152       .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMCPY),
7153                     Dst.getValueType().getTypeForEVT(*getContext()),
7154                     getExternalSymbol(TLI->getLibcallName(RTLIB::MEMCPY),
7155                                       TLI->getPointerTy(getDataLayout())),
7156                     std::move(Args))
7157       .setDiscardResult()
7158       .setTailCall(isTailCall);
7159 
7160   std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
7161   return CallResult.second;
7162 }
7163 
7164 SDValue SelectionDAG::getAtomicMemcpy(SDValue Chain, const SDLoc &dl,
7165                                       SDValue Dst, unsigned DstAlign,
7166                                       SDValue Src, unsigned SrcAlign,
7167                                       SDValue Size, Type *SizeTy,
7168                                       unsigned ElemSz, bool isTailCall,
7169                                       MachinePointerInfo DstPtrInfo,
7170                                       MachinePointerInfo SrcPtrInfo) {
7171   // Emit a library call.
7172   TargetLowering::ArgListTy Args;
7173   TargetLowering::ArgListEntry Entry;
7174   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
7175   Entry.Node = Dst;
7176   Args.push_back(Entry);
7177 
7178   Entry.Node = Src;
7179   Args.push_back(Entry);
7180 
7181   Entry.Ty = SizeTy;
7182   Entry.Node = Size;
7183   Args.push_back(Entry);
7184 
7185   RTLIB::Libcall LibraryCall =
7186       RTLIB::getMEMCPY_ELEMENT_UNORDERED_ATOMIC(ElemSz);
7187   if (LibraryCall == RTLIB::UNKNOWN_LIBCALL)
7188     report_fatal_error("Unsupported element size");
7189 
7190   TargetLowering::CallLoweringInfo CLI(*this);
7191   CLI.setDebugLoc(dl)
7192       .setChain(Chain)
7193       .setLibCallee(TLI->getLibcallCallingConv(LibraryCall),
7194                     Type::getVoidTy(*getContext()),
7195                     getExternalSymbol(TLI->getLibcallName(LibraryCall),
7196                                       TLI->getPointerTy(getDataLayout())),
7197                     std::move(Args))
7198       .setDiscardResult()
7199       .setTailCall(isTailCall);
7200 
7201   std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
7202   return CallResult.second;
7203 }
7204 
7205 SDValue SelectionDAG::getMemmove(SDValue Chain, const SDLoc &dl, SDValue Dst,
7206                                  SDValue Src, SDValue Size, Align Alignment,
7207                                  bool isVol, bool isTailCall,
7208                                  MachinePointerInfo DstPtrInfo,
7209                                  MachinePointerInfo SrcPtrInfo,
7210                                  const AAMDNodes &AAInfo) {
7211   // Check to see if we should lower the memmove to loads and stores first.
7212   // For cases within the target-specified limits, this is the best choice.
7213   ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
7214   if (ConstantSize) {
7215     // Memmove with size zero? Just return the original chain.
7216     if (ConstantSize->isZero())
7217       return Chain;
7218 
7219     SDValue Result = getMemmoveLoadsAndStores(
7220         *this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), Alignment,
7221         isVol, false, DstPtrInfo, SrcPtrInfo, AAInfo);
7222     if (Result.getNode())
7223       return Result;
7224   }
7225 
7226   // Then check to see if we should lower the memmove with target-specific
7227   // code. If the target chooses to do this, this is the next best.
7228   if (TSI) {
7229     SDValue Result =
7230         TSI->EmitTargetCodeForMemmove(*this, dl, Chain, Dst, Src, Size,
7231                                       Alignment, isVol, DstPtrInfo, SrcPtrInfo);
7232     if (Result.getNode())
7233       return Result;
7234   }
7235 
7236   checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace());
7237   checkAddrSpaceIsValidForLibcall(TLI, SrcPtrInfo.getAddrSpace());
7238 
7239   // FIXME: If the memmove is volatile, lowering it to plain libc memmove may
7240   // not be safe.  See memcpy above for more details.
7241 
7242   // Emit a library call.
7243   TargetLowering::ArgListTy Args;
7244   TargetLowering::ArgListEntry Entry;
7245   Entry.Ty = Type::getInt8PtrTy(*getContext());
7246   Entry.Node = Dst; Args.push_back(Entry);
7247   Entry.Node = Src; Args.push_back(Entry);
7248 
7249   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
7250   Entry.Node = Size; Args.push_back(Entry);
7251   // FIXME:  pass in SDLoc
7252   TargetLowering::CallLoweringInfo CLI(*this);
7253   CLI.setDebugLoc(dl)
7254       .setChain(Chain)
7255       .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMMOVE),
7256                     Dst.getValueType().getTypeForEVT(*getContext()),
7257                     getExternalSymbol(TLI->getLibcallName(RTLIB::MEMMOVE),
7258                                       TLI->getPointerTy(getDataLayout())),
7259                     std::move(Args))
7260       .setDiscardResult()
7261       .setTailCall(isTailCall);
7262 
7263   std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
7264   return CallResult.second;
7265 }
7266 
7267 SDValue SelectionDAG::getAtomicMemmove(SDValue Chain, const SDLoc &dl,
7268                                        SDValue Dst, unsigned DstAlign,
7269                                        SDValue Src, unsigned SrcAlign,
7270                                        SDValue Size, Type *SizeTy,
7271                                        unsigned ElemSz, bool isTailCall,
7272                                        MachinePointerInfo DstPtrInfo,
7273                                        MachinePointerInfo SrcPtrInfo) {
7274   // Emit a library call.
7275   TargetLowering::ArgListTy Args;
7276   TargetLowering::ArgListEntry Entry;
7277   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
7278   Entry.Node = Dst;
7279   Args.push_back(Entry);
7280 
7281   Entry.Node = Src;
7282   Args.push_back(Entry);
7283 
7284   Entry.Ty = SizeTy;
7285   Entry.Node = Size;
7286   Args.push_back(Entry);
7287 
7288   RTLIB::Libcall LibraryCall =
7289       RTLIB::getMEMMOVE_ELEMENT_UNORDERED_ATOMIC(ElemSz);
7290   if (LibraryCall == RTLIB::UNKNOWN_LIBCALL)
7291     report_fatal_error("Unsupported element size");
7292 
7293   TargetLowering::CallLoweringInfo CLI(*this);
7294   CLI.setDebugLoc(dl)
7295       .setChain(Chain)
7296       .setLibCallee(TLI->getLibcallCallingConv(LibraryCall),
7297                     Type::getVoidTy(*getContext()),
7298                     getExternalSymbol(TLI->getLibcallName(LibraryCall),
7299                                       TLI->getPointerTy(getDataLayout())),
7300                     std::move(Args))
7301       .setDiscardResult()
7302       .setTailCall(isTailCall);
7303 
7304   std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
7305   return CallResult.second;
7306 }
7307 
7308 SDValue SelectionDAG::getMemset(SDValue Chain, const SDLoc &dl, SDValue Dst,
7309                                 SDValue Src, SDValue Size, Align Alignment,
7310                                 bool isVol, bool isTailCall,
7311                                 MachinePointerInfo DstPtrInfo,
7312                                 const AAMDNodes &AAInfo) {
7313   // Check to see if we should lower the memset to stores first.
7314   // For cases within the target-specified limits, this is the best choice.
7315   ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
7316   if (ConstantSize) {
7317     // Memset with size zero? Just return the original chain.
7318     if (ConstantSize->isZero())
7319       return Chain;
7320 
7321     SDValue Result = getMemsetStores(*this, dl, Chain, Dst, Src,
7322                                      ConstantSize->getZExtValue(), Alignment,
7323                                      isVol, DstPtrInfo, AAInfo);
7324 
7325     if (Result.getNode())
7326       return Result;
7327   }
7328 
7329   // Then check to see if we should lower the memset with target-specific
7330   // code. If the target chooses to do this, this is the next best.
7331   if (TSI) {
7332     SDValue Result = TSI->EmitTargetCodeForMemset(
7333         *this, dl, Chain, Dst, Src, Size, Alignment, isVol, DstPtrInfo);
7334     if (Result.getNode())
7335       return Result;
7336   }
7337 
7338   checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace());
7339 
7340   // Emit a library call.
7341   TargetLowering::ArgListTy Args;
7342   TargetLowering::ArgListEntry Entry;
7343   Entry.Node = Dst; Entry.Ty = Type::getInt8PtrTy(*getContext());
7344   Args.push_back(Entry);
7345   Entry.Node = Src;
7346   Entry.Ty = Src.getValueType().getTypeForEVT(*getContext());
7347   Args.push_back(Entry);
7348   Entry.Node = Size;
7349   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
7350   Args.push_back(Entry);
7351 
7352   // FIXME: pass in SDLoc
7353   TargetLowering::CallLoweringInfo CLI(*this);
7354   CLI.setDebugLoc(dl)
7355       .setChain(Chain)
7356       .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMSET),
7357                     Dst.getValueType().getTypeForEVT(*getContext()),
7358                     getExternalSymbol(TLI->getLibcallName(RTLIB::MEMSET),
7359                                       TLI->getPointerTy(getDataLayout())),
7360                     std::move(Args))
7361       .setDiscardResult()
7362       .setTailCall(isTailCall);
7363 
7364   std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
7365   return CallResult.second;
7366 }
7367 
7368 SDValue SelectionDAG::getAtomicMemset(SDValue Chain, const SDLoc &dl,
7369                                       SDValue Dst, unsigned DstAlign,
7370                                       SDValue Value, SDValue Size, Type *SizeTy,
7371                                       unsigned ElemSz, bool isTailCall,
7372                                       MachinePointerInfo DstPtrInfo) {
7373   // Emit a library call.
7374   TargetLowering::ArgListTy Args;
7375   TargetLowering::ArgListEntry Entry;
7376   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
7377   Entry.Node = Dst;
7378   Args.push_back(Entry);
7379 
7380   Entry.Ty = Type::getInt8Ty(*getContext());
7381   Entry.Node = Value;
7382   Args.push_back(Entry);
7383 
7384   Entry.Ty = SizeTy;
7385   Entry.Node = Size;
7386   Args.push_back(Entry);
7387 
7388   RTLIB::Libcall LibraryCall =
7389       RTLIB::getMEMSET_ELEMENT_UNORDERED_ATOMIC(ElemSz);
7390   if (LibraryCall == RTLIB::UNKNOWN_LIBCALL)
7391     report_fatal_error("Unsupported element size");
7392 
7393   TargetLowering::CallLoweringInfo CLI(*this);
7394   CLI.setDebugLoc(dl)
7395       .setChain(Chain)
7396       .setLibCallee(TLI->getLibcallCallingConv(LibraryCall),
7397                     Type::getVoidTy(*getContext()),
7398                     getExternalSymbol(TLI->getLibcallName(LibraryCall),
7399                                       TLI->getPointerTy(getDataLayout())),
7400                     std::move(Args))
7401       .setDiscardResult()
7402       .setTailCall(isTailCall);
7403 
7404   std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
7405   return CallResult.second;
7406 }
7407 
7408 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
7409                                 SDVTList VTList, ArrayRef<SDValue> Ops,
7410                                 MachineMemOperand *MMO) {
7411   FoldingSetNodeID ID;
7412   ID.AddInteger(MemVT.getRawBits());
7413   AddNodeIDNode(ID, Opcode, VTList, Ops);
7414   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7415   ID.AddInteger(MMO->getFlags());
7416   void* IP = nullptr;
7417   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7418     cast<AtomicSDNode>(E)->refineAlignment(MMO);
7419     return SDValue(E, 0);
7420   }
7421 
7422   auto *N = newSDNode<AtomicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
7423                                     VTList, MemVT, MMO);
7424   createOperands(N, Ops);
7425 
7426   CSEMap.InsertNode(N, IP);
7427   InsertNode(N);
7428   return SDValue(N, 0);
7429 }
7430 
7431 SDValue SelectionDAG::getAtomicCmpSwap(unsigned Opcode, const SDLoc &dl,
7432                                        EVT MemVT, SDVTList VTs, SDValue Chain,
7433                                        SDValue Ptr, SDValue Cmp, SDValue Swp,
7434                                        MachineMemOperand *MMO) {
7435   assert(Opcode == ISD::ATOMIC_CMP_SWAP ||
7436          Opcode == ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS);
7437   assert(Cmp.getValueType() == Swp.getValueType() && "Invalid Atomic Op Types");
7438 
7439   SDValue Ops[] = {Chain, Ptr, Cmp, Swp};
7440   return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
7441 }
7442 
7443 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
7444                                 SDValue Chain, SDValue Ptr, SDValue Val,
7445                                 MachineMemOperand *MMO) {
7446   assert((Opcode == ISD::ATOMIC_LOAD_ADD ||
7447           Opcode == ISD::ATOMIC_LOAD_SUB ||
7448           Opcode == ISD::ATOMIC_LOAD_AND ||
7449           Opcode == ISD::ATOMIC_LOAD_CLR ||
7450           Opcode == ISD::ATOMIC_LOAD_OR ||
7451           Opcode == ISD::ATOMIC_LOAD_XOR ||
7452           Opcode == ISD::ATOMIC_LOAD_NAND ||
7453           Opcode == ISD::ATOMIC_LOAD_MIN ||
7454           Opcode == ISD::ATOMIC_LOAD_MAX ||
7455           Opcode == ISD::ATOMIC_LOAD_UMIN ||
7456           Opcode == ISD::ATOMIC_LOAD_UMAX ||
7457           Opcode == ISD::ATOMIC_LOAD_FADD ||
7458           Opcode == ISD::ATOMIC_LOAD_FSUB ||
7459           Opcode == ISD::ATOMIC_SWAP ||
7460           Opcode == ISD::ATOMIC_STORE) &&
7461          "Invalid Atomic Op");
7462 
7463   EVT VT = Val.getValueType();
7464 
7465   SDVTList VTs = Opcode == ISD::ATOMIC_STORE ? getVTList(MVT::Other) :
7466                                                getVTList(VT, MVT::Other);
7467   SDValue Ops[] = {Chain, Ptr, Val};
7468   return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
7469 }
7470 
7471 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
7472                                 EVT VT, SDValue Chain, SDValue Ptr,
7473                                 MachineMemOperand *MMO) {
7474   assert(Opcode == ISD::ATOMIC_LOAD && "Invalid Atomic Op");
7475 
7476   SDVTList VTs = getVTList(VT, MVT::Other);
7477   SDValue Ops[] = {Chain, Ptr};
7478   return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
7479 }
7480 
7481 /// getMergeValues - Create a MERGE_VALUES node from the given operands.
7482 SDValue SelectionDAG::getMergeValues(ArrayRef<SDValue> Ops, const SDLoc &dl) {
7483   if (Ops.size() == 1)
7484     return Ops[0];
7485 
7486   SmallVector<EVT, 4> VTs;
7487   VTs.reserve(Ops.size());
7488   for (const SDValue &Op : Ops)
7489     VTs.push_back(Op.getValueType());
7490   return getNode(ISD::MERGE_VALUES, dl, getVTList(VTs), Ops);
7491 }
7492 
7493 SDValue SelectionDAG::getMemIntrinsicNode(
7494     unsigned Opcode, const SDLoc &dl, SDVTList VTList, ArrayRef<SDValue> Ops,
7495     EVT MemVT, MachinePointerInfo PtrInfo, Align Alignment,
7496     MachineMemOperand::Flags Flags, uint64_t Size, const AAMDNodes &AAInfo) {
7497   if (!Size && MemVT.isScalableVector())
7498     Size = MemoryLocation::UnknownSize;
7499   else if (!Size)
7500     Size = MemVT.getStoreSize();
7501 
7502   MachineFunction &MF = getMachineFunction();
7503   MachineMemOperand *MMO =
7504       MF.getMachineMemOperand(PtrInfo, Flags, Size, Alignment, AAInfo);
7505 
7506   return getMemIntrinsicNode(Opcode, dl, VTList, Ops, MemVT, MMO);
7507 }
7508 
7509 SDValue SelectionDAG::getMemIntrinsicNode(unsigned Opcode, const SDLoc &dl,
7510                                           SDVTList VTList,
7511                                           ArrayRef<SDValue> Ops, EVT MemVT,
7512                                           MachineMemOperand *MMO) {
7513   assert((Opcode == ISD::INTRINSIC_VOID ||
7514           Opcode == ISD::INTRINSIC_W_CHAIN ||
7515           Opcode == ISD::PREFETCH ||
7516           ((int)Opcode <= std::numeric_limits<int>::max() &&
7517            (int)Opcode >= ISD::FIRST_TARGET_MEMORY_OPCODE)) &&
7518          "Opcode is not a memory-accessing opcode!");
7519 
7520   // Memoize the node unless it returns a flag.
7521   MemIntrinsicSDNode *N;
7522   if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) {
7523     FoldingSetNodeID ID;
7524     AddNodeIDNode(ID, Opcode, VTList, Ops);
7525     ID.AddInteger(getSyntheticNodeSubclassData<MemIntrinsicSDNode>(
7526         Opcode, dl.getIROrder(), VTList, MemVT, MMO));
7527     ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7528     ID.AddInteger(MMO->getFlags());
7529     void *IP = nullptr;
7530     if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7531       cast<MemIntrinsicSDNode>(E)->refineAlignment(MMO);
7532       return SDValue(E, 0);
7533     }
7534 
7535     N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
7536                                       VTList, MemVT, MMO);
7537     createOperands(N, Ops);
7538 
7539   CSEMap.InsertNode(N, IP);
7540   } else {
7541     N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
7542                                       VTList, MemVT, MMO);
7543     createOperands(N, Ops);
7544   }
7545   InsertNode(N);
7546   SDValue V(N, 0);
7547   NewSDValueDbgMsg(V, "Creating new node: ", this);
7548   return V;
7549 }
7550 
7551 SDValue SelectionDAG::getLifetimeNode(bool IsStart, const SDLoc &dl,
7552                                       SDValue Chain, int FrameIndex,
7553                                       int64_t Size, int64_t Offset) {
7554   const unsigned Opcode = IsStart ? ISD::LIFETIME_START : ISD::LIFETIME_END;
7555   const auto VTs = getVTList(MVT::Other);
7556   SDValue Ops[2] = {
7557       Chain,
7558       getFrameIndex(FrameIndex,
7559                     getTargetLoweringInfo().getFrameIndexTy(getDataLayout()),
7560                     true)};
7561 
7562   FoldingSetNodeID ID;
7563   AddNodeIDNode(ID, Opcode, VTs, Ops);
7564   ID.AddInteger(FrameIndex);
7565   ID.AddInteger(Size);
7566   ID.AddInteger(Offset);
7567   void *IP = nullptr;
7568   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
7569     return SDValue(E, 0);
7570 
7571   LifetimeSDNode *N = newSDNode<LifetimeSDNode>(
7572       Opcode, dl.getIROrder(), dl.getDebugLoc(), VTs, Size, Offset);
7573   createOperands(N, Ops);
7574   CSEMap.InsertNode(N, IP);
7575   InsertNode(N);
7576   SDValue V(N, 0);
7577   NewSDValueDbgMsg(V, "Creating new node: ", this);
7578   return V;
7579 }
7580 
7581 SDValue SelectionDAG::getPseudoProbeNode(const SDLoc &Dl, SDValue Chain,
7582                                          uint64_t Guid, uint64_t Index,
7583                                          uint32_t Attr) {
7584   const unsigned Opcode = ISD::PSEUDO_PROBE;
7585   const auto VTs = getVTList(MVT::Other);
7586   SDValue Ops[] = {Chain};
7587   FoldingSetNodeID ID;
7588   AddNodeIDNode(ID, Opcode, VTs, Ops);
7589   ID.AddInteger(Guid);
7590   ID.AddInteger(Index);
7591   void *IP = nullptr;
7592   if (SDNode *E = FindNodeOrInsertPos(ID, Dl, IP))
7593     return SDValue(E, 0);
7594 
7595   auto *N = newSDNode<PseudoProbeSDNode>(
7596       Opcode, Dl.getIROrder(), Dl.getDebugLoc(), VTs, Guid, Index, Attr);
7597   createOperands(N, Ops);
7598   CSEMap.InsertNode(N, IP);
7599   InsertNode(N);
7600   SDValue V(N, 0);
7601   NewSDValueDbgMsg(V, "Creating new node: ", this);
7602   return V;
7603 }
7604 
7605 /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a
7606 /// MachinePointerInfo record from it.  This is particularly useful because the
7607 /// code generator has many cases where it doesn't bother passing in a
7608 /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst".
7609 static MachinePointerInfo InferPointerInfo(const MachinePointerInfo &Info,
7610                                            SelectionDAG &DAG, SDValue Ptr,
7611                                            int64_t Offset = 0) {
7612   // If this is FI+Offset, we can model it.
7613   if (const FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr))
7614     return MachinePointerInfo::getFixedStack(DAG.getMachineFunction(),
7615                                              FI->getIndex(), Offset);
7616 
7617   // If this is (FI+Offset1)+Offset2, we can model it.
7618   if (Ptr.getOpcode() != ISD::ADD ||
7619       !isa<ConstantSDNode>(Ptr.getOperand(1)) ||
7620       !isa<FrameIndexSDNode>(Ptr.getOperand(0)))
7621     return Info;
7622 
7623   int FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
7624   return MachinePointerInfo::getFixedStack(
7625       DAG.getMachineFunction(), FI,
7626       Offset + cast<ConstantSDNode>(Ptr.getOperand(1))->getSExtValue());
7627 }
7628 
7629 /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a
7630 /// MachinePointerInfo record from it.  This is particularly useful because the
7631 /// code generator has many cases where it doesn't bother passing in a
7632 /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst".
7633 static MachinePointerInfo InferPointerInfo(const MachinePointerInfo &Info,
7634                                            SelectionDAG &DAG, SDValue Ptr,
7635                                            SDValue OffsetOp) {
7636   // If the 'Offset' value isn't a constant, we can't handle this.
7637   if (ConstantSDNode *OffsetNode = dyn_cast<ConstantSDNode>(OffsetOp))
7638     return InferPointerInfo(Info, DAG, Ptr, OffsetNode->getSExtValue());
7639   if (OffsetOp.isUndef())
7640     return InferPointerInfo(Info, DAG, Ptr);
7641   return Info;
7642 }
7643 
7644 SDValue SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType,
7645                               EVT VT, const SDLoc &dl, SDValue Chain,
7646                               SDValue Ptr, SDValue Offset,
7647                               MachinePointerInfo PtrInfo, EVT MemVT,
7648                               Align Alignment,
7649                               MachineMemOperand::Flags MMOFlags,
7650                               const AAMDNodes &AAInfo, const MDNode *Ranges) {
7651   assert(Chain.getValueType() == MVT::Other &&
7652         "Invalid chain type");
7653 
7654   MMOFlags |= MachineMemOperand::MOLoad;
7655   assert((MMOFlags & MachineMemOperand::MOStore) == 0);
7656   // If we don't have a PtrInfo, infer the trivial frame index case to simplify
7657   // clients.
7658   if (PtrInfo.V.isNull())
7659     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr, Offset);
7660 
7661   uint64_t Size = MemoryLocation::getSizeOrUnknown(MemVT.getStoreSize());
7662   MachineFunction &MF = getMachineFunction();
7663   MachineMemOperand *MMO = MF.getMachineMemOperand(PtrInfo, MMOFlags, Size,
7664                                                    Alignment, AAInfo, Ranges);
7665   return getLoad(AM, ExtType, VT, dl, Chain, Ptr, Offset, MemVT, MMO);
7666 }
7667 
7668 SDValue SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType,
7669                               EVT VT, const SDLoc &dl, SDValue Chain,
7670                               SDValue Ptr, SDValue Offset, EVT MemVT,
7671                               MachineMemOperand *MMO) {
7672   if (VT == MemVT) {
7673     ExtType = ISD::NON_EXTLOAD;
7674   } else if (ExtType == ISD::NON_EXTLOAD) {
7675     assert(VT == MemVT && "Non-extending load from different memory type!");
7676   } else {
7677     // Extending load.
7678     assert(MemVT.getScalarType().bitsLT(VT.getScalarType()) &&
7679            "Should only be an extending load, not truncating!");
7680     assert(VT.isInteger() == MemVT.isInteger() &&
7681            "Cannot convert from FP to Int or Int -> FP!");
7682     assert(VT.isVector() == MemVT.isVector() &&
7683            "Cannot use an ext load to convert to or from a vector!");
7684     assert((!VT.isVector() ||
7685             VT.getVectorElementCount() == MemVT.getVectorElementCount()) &&
7686            "Cannot use an ext load to change the number of vector elements!");
7687   }
7688 
7689   bool Indexed = AM != ISD::UNINDEXED;
7690   assert((Indexed || Offset.isUndef()) && "Unindexed load with an offset!");
7691 
7692   SDVTList VTs = Indexed ?
7693     getVTList(VT, Ptr.getValueType(), MVT::Other) : getVTList(VT, MVT::Other);
7694   SDValue Ops[] = { Chain, Ptr, Offset };
7695   FoldingSetNodeID ID;
7696   AddNodeIDNode(ID, ISD::LOAD, VTs, Ops);
7697   ID.AddInteger(MemVT.getRawBits());
7698   ID.AddInteger(getSyntheticNodeSubclassData<LoadSDNode>(
7699       dl.getIROrder(), VTs, AM, ExtType, MemVT, MMO));
7700   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7701   ID.AddInteger(MMO->getFlags());
7702   void *IP = nullptr;
7703   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7704     cast<LoadSDNode>(E)->refineAlignment(MMO);
7705     return SDValue(E, 0);
7706   }
7707   auto *N = newSDNode<LoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
7708                                   ExtType, MemVT, MMO);
7709   createOperands(N, Ops);
7710 
7711   CSEMap.InsertNode(N, IP);
7712   InsertNode(N);
7713   SDValue V(N, 0);
7714   NewSDValueDbgMsg(V, "Creating new node: ", this);
7715   return V;
7716 }
7717 
7718 SDValue SelectionDAG::getLoad(EVT VT, const SDLoc &dl, SDValue Chain,
7719                               SDValue Ptr, MachinePointerInfo PtrInfo,
7720                               MaybeAlign Alignment,
7721                               MachineMemOperand::Flags MMOFlags,
7722                               const AAMDNodes &AAInfo, const MDNode *Ranges) {
7723   SDValue Undef = getUNDEF(Ptr.getValueType());
7724   return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
7725                  PtrInfo, VT, Alignment, MMOFlags, AAInfo, Ranges);
7726 }
7727 
7728 SDValue SelectionDAG::getLoad(EVT VT, const SDLoc &dl, SDValue Chain,
7729                               SDValue Ptr, MachineMemOperand *MMO) {
7730   SDValue Undef = getUNDEF(Ptr.getValueType());
7731   return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
7732                  VT, MMO);
7733 }
7734 
7735 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl,
7736                                  EVT VT, SDValue Chain, SDValue Ptr,
7737                                  MachinePointerInfo PtrInfo, EVT MemVT,
7738                                  MaybeAlign Alignment,
7739                                  MachineMemOperand::Flags MMOFlags,
7740                                  const AAMDNodes &AAInfo) {
7741   SDValue Undef = getUNDEF(Ptr.getValueType());
7742   return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, PtrInfo,
7743                  MemVT, Alignment, MMOFlags, AAInfo);
7744 }
7745 
7746 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl,
7747                                  EVT VT, SDValue Chain, SDValue Ptr, EVT MemVT,
7748                                  MachineMemOperand *MMO) {
7749   SDValue Undef = getUNDEF(Ptr.getValueType());
7750   return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef,
7751                  MemVT, MMO);
7752 }
7753 
7754 SDValue SelectionDAG::getIndexedLoad(SDValue OrigLoad, const SDLoc &dl,
7755                                      SDValue Base, SDValue Offset,
7756                                      ISD::MemIndexedMode AM) {
7757   LoadSDNode *LD = cast<LoadSDNode>(OrigLoad);
7758   assert(LD->getOffset().isUndef() && "Load is already a indexed load!");
7759   // Don't propagate the invariant or dereferenceable flags.
7760   auto MMOFlags =
7761       LD->getMemOperand()->getFlags() &
7762       ~(MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable);
7763   return getLoad(AM, LD->getExtensionType(), OrigLoad.getValueType(), dl,
7764                  LD->getChain(), Base, Offset, LD->getPointerInfo(),
7765                  LD->getMemoryVT(), LD->getAlign(), MMOFlags, LD->getAAInfo());
7766 }
7767 
7768 SDValue SelectionDAG::getStore(SDValue Chain, const SDLoc &dl, SDValue Val,
7769                                SDValue Ptr, MachinePointerInfo PtrInfo,
7770                                Align Alignment,
7771                                MachineMemOperand::Flags MMOFlags,
7772                                const AAMDNodes &AAInfo) {
7773   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
7774 
7775   MMOFlags |= MachineMemOperand::MOStore;
7776   assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
7777 
7778   if (PtrInfo.V.isNull())
7779     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
7780 
7781   MachineFunction &MF = getMachineFunction();
7782   uint64_t Size =
7783       MemoryLocation::getSizeOrUnknown(Val.getValueType().getStoreSize());
7784   MachineMemOperand *MMO =
7785       MF.getMachineMemOperand(PtrInfo, MMOFlags, Size, Alignment, AAInfo);
7786   return getStore(Chain, dl, Val, Ptr, MMO);
7787 }
7788 
7789 SDValue SelectionDAG::getStore(SDValue Chain, const SDLoc &dl, SDValue Val,
7790                                SDValue Ptr, MachineMemOperand *MMO) {
7791   assert(Chain.getValueType() == MVT::Other &&
7792         "Invalid chain type");
7793   EVT VT = Val.getValueType();
7794   SDVTList VTs = getVTList(MVT::Other);
7795   SDValue Undef = getUNDEF(Ptr.getValueType());
7796   SDValue Ops[] = { Chain, Val, Ptr, Undef };
7797   FoldingSetNodeID ID;
7798   AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
7799   ID.AddInteger(VT.getRawBits());
7800   ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>(
7801       dl.getIROrder(), VTs, ISD::UNINDEXED, false, VT, MMO));
7802   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7803   ID.AddInteger(MMO->getFlags());
7804   void *IP = nullptr;
7805   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7806     cast<StoreSDNode>(E)->refineAlignment(MMO);
7807     return SDValue(E, 0);
7808   }
7809   auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
7810                                    ISD::UNINDEXED, false, VT, MMO);
7811   createOperands(N, Ops);
7812 
7813   CSEMap.InsertNode(N, IP);
7814   InsertNode(N);
7815   SDValue V(N, 0);
7816   NewSDValueDbgMsg(V, "Creating new node: ", this);
7817   return V;
7818 }
7819 
7820 SDValue SelectionDAG::getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val,
7821                                     SDValue Ptr, MachinePointerInfo PtrInfo,
7822                                     EVT SVT, Align Alignment,
7823                                     MachineMemOperand::Flags MMOFlags,
7824                                     const AAMDNodes &AAInfo) {
7825   assert(Chain.getValueType() == MVT::Other &&
7826         "Invalid chain type");
7827 
7828   MMOFlags |= MachineMemOperand::MOStore;
7829   assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
7830 
7831   if (PtrInfo.V.isNull())
7832     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
7833 
7834   MachineFunction &MF = getMachineFunction();
7835   MachineMemOperand *MMO = MF.getMachineMemOperand(
7836       PtrInfo, MMOFlags, MemoryLocation::getSizeOrUnknown(SVT.getStoreSize()),
7837       Alignment, AAInfo);
7838   return getTruncStore(Chain, dl, Val, Ptr, SVT, MMO);
7839 }
7840 
7841 SDValue SelectionDAG::getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val,
7842                                     SDValue Ptr, EVT SVT,
7843                                     MachineMemOperand *MMO) {
7844   EVT VT = Val.getValueType();
7845 
7846   assert(Chain.getValueType() == MVT::Other &&
7847         "Invalid chain type");
7848   if (VT == SVT)
7849     return getStore(Chain, dl, Val, Ptr, MMO);
7850 
7851   assert(SVT.getScalarType().bitsLT(VT.getScalarType()) &&
7852          "Should only be a truncating store, not extending!");
7853   assert(VT.isInteger() == SVT.isInteger() &&
7854          "Can't do FP-INT conversion!");
7855   assert(VT.isVector() == SVT.isVector() &&
7856          "Cannot use trunc store to convert to or from a vector!");
7857   assert((!VT.isVector() ||
7858           VT.getVectorElementCount() == SVT.getVectorElementCount()) &&
7859          "Cannot use trunc store to change the number of vector elements!");
7860 
7861   SDVTList VTs = getVTList(MVT::Other);
7862   SDValue Undef = getUNDEF(Ptr.getValueType());
7863   SDValue Ops[] = { Chain, Val, Ptr, Undef };
7864   FoldingSetNodeID ID;
7865   AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
7866   ID.AddInteger(SVT.getRawBits());
7867   ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>(
7868       dl.getIROrder(), VTs, ISD::UNINDEXED, true, SVT, MMO));
7869   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7870   ID.AddInteger(MMO->getFlags());
7871   void *IP = nullptr;
7872   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7873     cast<StoreSDNode>(E)->refineAlignment(MMO);
7874     return SDValue(E, 0);
7875   }
7876   auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
7877                                    ISD::UNINDEXED, true, SVT, MMO);
7878   createOperands(N, Ops);
7879 
7880   CSEMap.InsertNode(N, IP);
7881   InsertNode(N);
7882   SDValue V(N, 0);
7883   NewSDValueDbgMsg(V, "Creating new node: ", this);
7884   return V;
7885 }
7886 
7887 SDValue SelectionDAG::getIndexedStore(SDValue OrigStore, const SDLoc &dl,
7888                                       SDValue Base, SDValue Offset,
7889                                       ISD::MemIndexedMode AM) {
7890   StoreSDNode *ST = cast<StoreSDNode>(OrigStore);
7891   assert(ST->getOffset().isUndef() && "Store is already a indexed store!");
7892   SDVTList VTs = getVTList(Base.getValueType(), MVT::Other);
7893   SDValue Ops[] = { ST->getChain(), ST->getValue(), Base, Offset };
7894   FoldingSetNodeID ID;
7895   AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
7896   ID.AddInteger(ST->getMemoryVT().getRawBits());
7897   ID.AddInteger(ST->getRawSubclassData());
7898   ID.AddInteger(ST->getPointerInfo().getAddrSpace());
7899   ID.AddInteger(ST->getMemOperand()->getFlags());
7900   void *IP = nullptr;
7901   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
7902     return SDValue(E, 0);
7903 
7904   auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
7905                                    ST->isTruncatingStore(), ST->getMemoryVT(),
7906                                    ST->getMemOperand());
7907   createOperands(N, Ops);
7908 
7909   CSEMap.InsertNode(N, IP);
7910   InsertNode(N);
7911   SDValue V(N, 0);
7912   NewSDValueDbgMsg(V, "Creating new node: ", this);
7913   return V;
7914 }
7915 
7916 SDValue SelectionDAG::getLoadVP(
7917     ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, EVT VT, const SDLoc &dl,
7918     SDValue Chain, SDValue Ptr, SDValue Offset, SDValue Mask, SDValue EVL,
7919     MachinePointerInfo PtrInfo, EVT MemVT, Align Alignment,
7920     MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo,
7921     const MDNode *Ranges, bool IsExpanding) {
7922   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
7923 
7924   MMOFlags |= MachineMemOperand::MOLoad;
7925   assert((MMOFlags & MachineMemOperand::MOStore) == 0);
7926   // If we don't have a PtrInfo, infer the trivial frame index case to simplify
7927   // clients.
7928   if (PtrInfo.V.isNull())
7929     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr, Offset);
7930 
7931   uint64_t Size = MemoryLocation::getSizeOrUnknown(MemVT.getStoreSize());
7932   MachineFunction &MF = getMachineFunction();
7933   MachineMemOperand *MMO = MF.getMachineMemOperand(PtrInfo, MMOFlags, Size,
7934                                                    Alignment, AAInfo, Ranges);
7935   return getLoadVP(AM, ExtType, VT, dl, Chain, Ptr, Offset, Mask, EVL, MemVT,
7936                    MMO, IsExpanding);
7937 }
7938 
7939 SDValue SelectionDAG::getLoadVP(ISD::MemIndexedMode AM,
7940                                 ISD::LoadExtType ExtType, EVT VT,
7941                                 const SDLoc &dl, SDValue Chain, SDValue Ptr,
7942                                 SDValue Offset, SDValue Mask, SDValue EVL,
7943                                 EVT MemVT, MachineMemOperand *MMO,
7944                                 bool IsExpanding) {
7945   bool Indexed = AM != ISD::UNINDEXED;
7946   assert((Indexed || Offset.isUndef()) && "Unindexed load with an offset!");
7947 
7948   SDVTList VTs = Indexed ? getVTList(VT, Ptr.getValueType(), MVT::Other)
7949                          : getVTList(VT, MVT::Other);
7950   SDValue Ops[] = {Chain, Ptr, Offset, Mask, EVL};
7951   FoldingSetNodeID ID;
7952   AddNodeIDNode(ID, ISD::VP_LOAD, VTs, Ops);
7953   ID.AddInteger(VT.getRawBits());
7954   ID.AddInteger(getSyntheticNodeSubclassData<VPLoadSDNode>(
7955       dl.getIROrder(), VTs, AM, ExtType, IsExpanding, MemVT, MMO));
7956   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7957   ID.AddInteger(MMO->getFlags());
7958   void *IP = nullptr;
7959   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7960     cast<VPLoadSDNode>(E)->refineAlignment(MMO);
7961     return SDValue(E, 0);
7962   }
7963   auto *N = newSDNode<VPLoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
7964                                     ExtType, IsExpanding, MemVT, MMO);
7965   createOperands(N, Ops);
7966 
7967   CSEMap.InsertNode(N, IP);
7968   InsertNode(N);
7969   SDValue V(N, 0);
7970   NewSDValueDbgMsg(V, "Creating new node: ", this);
7971   return V;
7972 }
7973 
7974 SDValue SelectionDAG::getLoadVP(EVT VT, const SDLoc &dl, SDValue Chain,
7975                                 SDValue Ptr, SDValue Mask, SDValue EVL,
7976                                 MachinePointerInfo PtrInfo,
7977                                 MaybeAlign Alignment,
7978                                 MachineMemOperand::Flags MMOFlags,
7979                                 const AAMDNodes &AAInfo, const MDNode *Ranges,
7980                                 bool IsExpanding) {
7981   SDValue Undef = getUNDEF(Ptr.getValueType());
7982   return getLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
7983                    Mask, EVL, PtrInfo, VT, Alignment, MMOFlags, AAInfo, Ranges,
7984                    IsExpanding);
7985 }
7986 
7987 SDValue SelectionDAG::getLoadVP(EVT VT, const SDLoc &dl, SDValue Chain,
7988                                 SDValue Ptr, SDValue Mask, SDValue EVL,
7989                                 MachineMemOperand *MMO, bool IsExpanding) {
7990   SDValue Undef = getUNDEF(Ptr.getValueType());
7991   return getLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
7992                    Mask, EVL, VT, MMO, IsExpanding);
7993 }
7994 
7995 SDValue SelectionDAG::getExtLoadVP(ISD::LoadExtType ExtType, const SDLoc &dl,
7996                                    EVT VT, SDValue Chain, SDValue Ptr,
7997                                    SDValue Mask, SDValue EVL,
7998                                    MachinePointerInfo PtrInfo, EVT MemVT,
7999                                    MaybeAlign Alignment,
8000                                    MachineMemOperand::Flags MMOFlags,
8001                                    const AAMDNodes &AAInfo, bool IsExpanding) {
8002   SDValue Undef = getUNDEF(Ptr.getValueType());
8003   return getLoadVP(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, Mask,
8004                    EVL, PtrInfo, MemVT, Alignment, MMOFlags, AAInfo, nullptr,
8005                    IsExpanding);
8006 }
8007 
8008 SDValue SelectionDAG::getExtLoadVP(ISD::LoadExtType ExtType, const SDLoc &dl,
8009                                    EVT VT, SDValue Chain, SDValue Ptr,
8010                                    SDValue Mask, SDValue EVL, EVT MemVT,
8011                                    MachineMemOperand *MMO, bool IsExpanding) {
8012   SDValue Undef = getUNDEF(Ptr.getValueType());
8013   return getLoadVP(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, Mask,
8014                    EVL, MemVT, MMO, IsExpanding);
8015 }
8016 
8017 SDValue SelectionDAG::getIndexedLoadVP(SDValue OrigLoad, const SDLoc &dl,
8018                                        SDValue Base, SDValue Offset,
8019                                        ISD::MemIndexedMode AM) {
8020   auto *LD = cast<VPLoadSDNode>(OrigLoad);
8021   assert(LD->getOffset().isUndef() && "Load is already a indexed load!");
8022   // Don't propagate the invariant or dereferenceable flags.
8023   auto MMOFlags =
8024       LD->getMemOperand()->getFlags() &
8025       ~(MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable);
8026   return getLoadVP(AM, LD->getExtensionType(), OrigLoad.getValueType(), dl,
8027                    LD->getChain(), Base, Offset, LD->getMask(),
8028                    LD->getVectorLength(), LD->getPointerInfo(),
8029                    LD->getMemoryVT(), LD->getAlign(), MMOFlags, LD->getAAInfo(),
8030                    nullptr, LD->isExpandingLoad());
8031 }
8032 
8033 SDValue SelectionDAG::getStoreVP(SDValue Chain, const SDLoc &dl, SDValue Val,
8034                                  SDValue Ptr, SDValue Offset, SDValue Mask,
8035                                  SDValue EVL, EVT MemVT, MachineMemOperand *MMO,
8036                                  ISD::MemIndexedMode AM, bool IsTruncating,
8037                                  bool IsCompressing) {
8038   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
8039   bool Indexed = AM != ISD::UNINDEXED;
8040   assert((Indexed || Offset.isUndef()) && "Unindexed vp_store with an offset!");
8041   SDVTList VTs = Indexed ? getVTList(Ptr.getValueType(), MVT::Other)
8042                          : getVTList(MVT::Other);
8043   SDValue Ops[] = {Chain, Val, Ptr, Offset, Mask, EVL};
8044   FoldingSetNodeID ID;
8045   AddNodeIDNode(ID, ISD::VP_STORE, VTs, Ops);
8046   ID.AddInteger(MemVT.getRawBits());
8047   ID.AddInteger(getSyntheticNodeSubclassData<VPStoreSDNode>(
8048       dl.getIROrder(), VTs, AM, IsTruncating, IsCompressing, MemVT, MMO));
8049   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8050   ID.AddInteger(MMO->getFlags());
8051   void *IP = nullptr;
8052   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
8053     cast<VPStoreSDNode>(E)->refineAlignment(MMO);
8054     return SDValue(E, 0);
8055   }
8056   auto *N = newSDNode<VPStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
8057                                      IsTruncating, IsCompressing, MemVT, MMO);
8058   createOperands(N, Ops);
8059 
8060   CSEMap.InsertNode(N, IP);
8061   InsertNode(N);
8062   SDValue V(N, 0);
8063   NewSDValueDbgMsg(V, "Creating new node: ", this);
8064   return V;
8065 }
8066 
8067 SDValue SelectionDAG::getTruncStoreVP(SDValue Chain, const SDLoc &dl,
8068                                       SDValue Val, SDValue Ptr, SDValue Mask,
8069                                       SDValue EVL, MachinePointerInfo PtrInfo,
8070                                       EVT SVT, Align Alignment,
8071                                       MachineMemOperand::Flags MMOFlags,
8072                                       const AAMDNodes &AAInfo,
8073                                       bool IsCompressing) {
8074   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
8075 
8076   MMOFlags |= MachineMemOperand::MOStore;
8077   assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
8078 
8079   if (PtrInfo.V.isNull())
8080     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
8081 
8082   MachineFunction &MF = getMachineFunction();
8083   MachineMemOperand *MMO = MF.getMachineMemOperand(
8084       PtrInfo, MMOFlags, MemoryLocation::getSizeOrUnknown(SVT.getStoreSize()),
8085       Alignment, AAInfo);
8086   return getTruncStoreVP(Chain, dl, Val, Ptr, Mask, EVL, SVT, MMO,
8087                          IsCompressing);
8088 }
8089 
8090 SDValue SelectionDAG::getTruncStoreVP(SDValue Chain, const SDLoc &dl,
8091                                       SDValue Val, SDValue Ptr, SDValue Mask,
8092                                       SDValue EVL, EVT SVT,
8093                                       MachineMemOperand *MMO,
8094                                       bool IsCompressing) {
8095   EVT VT = Val.getValueType();
8096 
8097   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
8098   if (VT == SVT)
8099     return getStoreVP(Chain, dl, Val, Ptr, getUNDEF(Ptr.getValueType()), Mask,
8100                       EVL, VT, MMO, ISD::UNINDEXED,
8101                       /*IsTruncating*/ false, IsCompressing);
8102 
8103   assert(SVT.getScalarType().bitsLT(VT.getScalarType()) &&
8104          "Should only be a truncating store, not extending!");
8105   assert(VT.isInteger() == SVT.isInteger() && "Can't do FP-INT conversion!");
8106   assert(VT.isVector() == SVT.isVector() &&
8107          "Cannot use trunc store to convert to or from a vector!");
8108   assert((!VT.isVector() ||
8109           VT.getVectorElementCount() == SVT.getVectorElementCount()) &&
8110          "Cannot use trunc store to change the number of vector elements!");
8111 
8112   SDVTList VTs = getVTList(MVT::Other);
8113   SDValue Undef = getUNDEF(Ptr.getValueType());
8114   SDValue Ops[] = {Chain, Val, Ptr, Undef, Mask, EVL};
8115   FoldingSetNodeID ID;
8116   AddNodeIDNode(ID, ISD::VP_STORE, VTs, Ops);
8117   ID.AddInteger(SVT.getRawBits());
8118   ID.AddInteger(getSyntheticNodeSubclassData<VPStoreSDNode>(
8119       dl.getIROrder(), VTs, ISD::UNINDEXED, true, IsCompressing, SVT, MMO));
8120   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8121   ID.AddInteger(MMO->getFlags());
8122   void *IP = nullptr;
8123   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
8124     cast<VPStoreSDNode>(E)->refineAlignment(MMO);
8125     return SDValue(E, 0);
8126   }
8127   auto *N =
8128       newSDNode<VPStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
8129                                ISD::UNINDEXED, true, IsCompressing, SVT, MMO);
8130   createOperands(N, Ops);
8131 
8132   CSEMap.InsertNode(N, IP);
8133   InsertNode(N);
8134   SDValue V(N, 0);
8135   NewSDValueDbgMsg(V, "Creating new node: ", this);
8136   return V;
8137 }
8138 
8139 SDValue SelectionDAG::getIndexedStoreVP(SDValue OrigStore, const SDLoc &dl,
8140                                         SDValue Base, SDValue Offset,
8141                                         ISD::MemIndexedMode AM) {
8142   auto *ST = cast<VPStoreSDNode>(OrigStore);
8143   assert(ST->getOffset().isUndef() && "Store is already an indexed store!");
8144   SDVTList VTs = getVTList(Base.getValueType(), MVT::Other);
8145   SDValue Ops[] = {ST->getChain(), ST->getValue(), Base,
8146                    Offset,         ST->getMask(),  ST->getVectorLength()};
8147   FoldingSetNodeID ID;
8148   AddNodeIDNode(ID, ISD::VP_STORE, VTs, Ops);
8149   ID.AddInteger(ST->getMemoryVT().getRawBits());
8150   ID.AddInteger(ST->getRawSubclassData());
8151   ID.AddInteger(ST->getPointerInfo().getAddrSpace());
8152   ID.AddInteger(ST->getMemOperand()->getFlags());
8153   void *IP = nullptr;
8154   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
8155     return SDValue(E, 0);
8156 
8157   auto *N = newSDNode<VPStoreSDNode>(
8158       dl.getIROrder(), dl.getDebugLoc(), VTs, AM, ST->isTruncatingStore(),
8159       ST->isCompressingStore(), ST->getMemoryVT(), ST->getMemOperand());
8160   createOperands(N, Ops);
8161 
8162   CSEMap.InsertNode(N, IP);
8163   InsertNode(N);
8164   SDValue V(N, 0);
8165   NewSDValueDbgMsg(V, "Creating new node: ", this);
8166   return V;
8167 }
8168 
8169 SDValue SelectionDAG::getStridedLoadVP(
8170     ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, EVT VT, const SDLoc &DL,
8171     SDValue Chain, SDValue Ptr, SDValue Offset, SDValue Stride, SDValue Mask,
8172     SDValue EVL, MachinePointerInfo PtrInfo, EVT MemVT, Align Alignment,
8173     MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo,
8174     const MDNode *Ranges, bool IsExpanding) {
8175   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
8176 
8177   MMOFlags |= MachineMemOperand::MOLoad;
8178   assert((MMOFlags & MachineMemOperand::MOStore) == 0);
8179   // If we don't have a PtrInfo, infer the trivial frame index case to simplify
8180   // clients.
8181   if (PtrInfo.V.isNull())
8182     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr, Offset);
8183 
8184   uint64_t Size = MemoryLocation::UnknownSize;
8185   MachineFunction &MF = getMachineFunction();
8186   MachineMemOperand *MMO = MF.getMachineMemOperand(PtrInfo, MMOFlags, Size,
8187                                                    Alignment, AAInfo, Ranges);
8188   return getStridedLoadVP(AM, ExtType, VT, DL, Chain, Ptr, Offset, Stride, Mask,
8189                           EVL, MemVT, MMO, IsExpanding);
8190 }
8191 
8192 SDValue SelectionDAG::getStridedLoadVP(
8193     ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, EVT VT, const SDLoc &DL,
8194     SDValue Chain, SDValue Ptr, SDValue Offset, SDValue Stride, SDValue Mask,
8195     SDValue EVL, EVT MemVT, MachineMemOperand *MMO, bool IsExpanding) {
8196   bool Indexed = AM != ISD::UNINDEXED;
8197   assert((Indexed || Offset.isUndef()) && "Unindexed load with an offset!");
8198 
8199   SDValue Ops[] = {Chain, Ptr, Offset, Stride, Mask, EVL};
8200   SDVTList VTs = Indexed ? getVTList(VT, Ptr.getValueType(), MVT::Other)
8201                          : getVTList(VT, MVT::Other);
8202   FoldingSetNodeID ID;
8203   AddNodeIDNode(ID, ISD::EXPERIMENTAL_VP_STRIDED_LOAD, VTs, Ops);
8204   ID.AddInteger(VT.getRawBits());
8205   ID.AddInteger(getSyntheticNodeSubclassData<VPStridedLoadSDNode>(
8206       DL.getIROrder(), VTs, AM, ExtType, IsExpanding, MemVT, MMO));
8207   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8208 
8209   void *IP = nullptr;
8210   if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
8211     cast<VPStridedLoadSDNode>(E)->refineAlignment(MMO);
8212     return SDValue(E, 0);
8213   }
8214 
8215   auto *N =
8216       newSDNode<VPStridedLoadSDNode>(DL.getIROrder(), DL.getDebugLoc(), VTs, AM,
8217                                      ExtType, IsExpanding, MemVT, MMO);
8218   createOperands(N, Ops);
8219   CSEMap.InsertNode(N, IP);
8220   InsertNode(N);
8221   SDValue V(N, 0);
8222   NewSDValueDbgMsg(V, "Creating new node: ", this);
8223   return V;
8224 }
8225 
8226 SDValue SelectionDAG::getStridedLoadVP(
8227     EVT VT, const SDLoc &DL, SDValue Chain, SDValue Ptr, SDValue Stride,
8228     SDValue Mask, SDValue EVL, MachinePointerInfo PtrInfo, MaybeAlign Alignment,
8229     MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo,
8230     const MDNode *Ranges, bool IsExpanding) {
8231   SDValue Undef = getUNDEF(Ptr.getValueType());
8232   return getStridedLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, DL, Chain, Ptr,
8233                           Undef, Stride, Mask, EVL, PtrInfo, VT, Alignment,
8234                           MMOFlags, AAInfo, Ranges, IsExpanding);
8235 }
8236 
8237 SDValue SelectionDAG::getStridedLoadVP(EVT VT, const SDLoc &DL, SDValue Chain,
8238                                        SDValue Ptr, SDValue Stride,
8239                                        SDValue Mask, SDValue EVL,
8240                                        MachineMemOperand *MMO,
8241                                        bool IsExpanding) {
8242   SDValue Undef = getUNDEF(Ptr.getValueType());
8243   return getStridedLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, DL, Chain, Ptr,
8244                           Undef, Stride, Mask, EVL, VT, MMO, IsExpanding);
8245 }
8246 
8247 SDValue SelectionDAG::getExtStridedLoadVP(
8248     ISD::LoadExtType ExtType, const SDLoc &DL, EVT VT, SDValue Chain,
8249     SDValue Ptr, SDValue Stride, SDValue Mask, SDValue EVL,
8250     MachinePointerInfo PtrInfo, EVT MemVT, MaybeAlign Alignment,
8251     MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo,
8252     bool IsExpanding) {
8253   SDValue Undef = getUNDEF(Ptr.getValueType());
8254   return getStridedLoadVP(ISD::UNINDEXED, ExtType, VT, DL, Chain, Ptr, Undef,
8255                           Stride, Mask, EVL, PtrInfo, MemVT, Alignment,
8256                           MMOFlags, AAInfo, nullptr, IsExpanding);
8257 }
8258 
8259 SDValue SelectionDAG::getExtStridedLoadVP(
8260     ISD::LoadExtType ExtType, const SDLoc &DL, EVT VT, SDValue Chain,
8261     SDValue Ptr, SDValue Stride, SDValue Mask, SDValue EVL, EVT MemVT,
8262     MachineMemOperand *MMO, bool IsExpanding) {
8263   SDValue Undef = getUNDEF(Ptr.getValueType());
8264   return getStridedLoadVP(ISD::UNINDEXED, ExtType, VT, DL, Chain, Ptr, Undef,
8265                           Stride, Mask, EVL, MemVT, MMO, IsExpanding);
8266 }
8267 
8268 SDValue SelectionDAG::getIndexedStridedLoadVP(SDValue OrigLoad, const SDLoc &DL,
8269                                               SDValue Base, SDValue Offset,
8270                                               ISD::MemIndexedMode AM) {
8271   auto *SLD = cast<VPStridedLoadSDNode>(OrigLoad);
8272   assert(SLD->getOffset().isUndef() &&
8273          "Strided load is already a indexed load!");
8274   // Don't propagate the invariant or dereferenceable flags.
8275   auto MMOFlags =
8276       SLD->getMemOperand()->getFlags() &
8277       ~(MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable);
8278   return getStridedLoadVP(
8279       AM, SLD->getExtensionType(), OrigLoad.getValueType(), DL, SLD->getChain(),
8280       Base, Offset, SLD->getStride(), SLD->getMask(), SLD->getVectorLength(),
8281       SLD->getPointerInfo(), SLD->getMemoryVT(), SLD->getAlign(), MMOFlags,
8282       SLD->getAAInfo(), nullptr, SLD->isExpandingLoad());
8283 }
8284 
8285 SDValue SelectionDAG::getStridedStoreVP(SDValue Chain, const SDLoc &DL,
8286                                         SDValue Val, SDValue Ptr,
8287                                         SDValue Offset, SDValue Stride,
8288                                         SDValue Mask, SDValue EVL, EVT MemVT,
8289                                         MachineMemOperand *MMO,
8290                                         ISD::MemIndexedMode AM,
8291                                         bool IsTruncating, bool IsCompressing) {
8292   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
8293   bool Indexed = AM != ISD::UNINDEXED;
8294   assert((Indexed || Offset.isUndef()) && "Unindexed vp_store with an offset!");
8295   SDVTList VTs = Indexed ? getVTList(Ptr.getValueType(), MVT::Other)
8296                          : getVTList(MVT::Other);
8297   SDValue Ops[] = {Chain, Val, Ptr, Offset, Stride, Mask, EVL};
8298   FoldingSetNodeID ID;
8299   AddNodeIDNode(ID, ISD::EXPERIMENTAL_VP_STRIDED_STORE, VTs, Ops);
8300   ID.AddInteger(MemVT.getRawBits());
8301   ID.AddInteger(getSyntheticNodeSubclassData<VPStridedStoreSDNode>(
8302       DL.getIROrder(), VTs, AM, IsTruncating, IsCompressing, MemVT, MMO));
8303   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8304   void *IP = nullptr;
8305   if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
8306     cast<VPStridedStoreSDNode>(E)->refineAlignment(MMO);
8307     return SDValue(E, 0);
8308   }
8309   auto *N = newSDNode<VPStridedStoreSDNode>(DL.getIROrder(), DL.getDebugLoc(),
8310                                             VTs, AM, IsTruncating,
8311                                             IsCompressing, MemVT, MMO);
8312   createOperands(N, Ops);
8313 
8314   CSEMap.InsertNode(N, IP);
8315   InsertNode(N);
8316   SDValue V(N, 0);
8317   NewSDValueDbgMsg(V, "Creating new node: ", this);
8318   return V;
8319 }
8320 
8321 SDValue SelectionDAG::getTruncStridedStoreVP(
8322     SDValue Chain, const SDLoc &DL, SDValue Val, SDValue Ptr, SDValue Stride,
8323     SDValue Mask, SDValue EVL, MachinePointerInfo PtrInfo, EVT SVT,
8324     Align Alignment, MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo,
8325     bool IsCompressing) {
8326   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
8327 
8328   MMOFlags |= MachineMemOperand::MOStore;
8329   assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
8330 
8331   if (PtrInfo.V.isNull())
8332     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
8333 
8334   MachineFunction &MF = getMachineFunction();
8335   MachineMemOperand *MMO = MF.getMachineMemOperand(
8336       PtrInfo, MMOFlags, MemoryLocation::UnknownSize, Alignment, AAInfo);
8337   return getTruncStridedStoreVP(Chain, DL, Val, Ptr, Stride, Mask, EVL, SVT,
8338                                 MMO, IsCompressing);
8339 }
8340 
8341 SDValue SelectionDAG::getTruncStridedStoreVP(SDValue Chain, const SDLoc &DL,
8342                                              SDValue Val, SDValue Ptr,
8343                                              SDValue Stride, SDValue Mask,
8344                                              SDValue EVL, EVT SVT,
8345                                              MachineMemOperand *MMO,
8346                                              bool IsCompressing) {
8347   EVT VT = Val.getValueType();
8348 
8349   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
8350   if (VT == SVT)
8351     return getStridedStoreVP(Chain, DL, Val, Ptr, getUNDEF(Ptr.getValueType()),
8352                              Stride, Mask, EVL, VT, MMO, ISD::UNINDEXED,
8353                              /*IsTruncating*/ false, IsCompressing);
8354 
8355   assert(SVT.getScalarType().bitsLT(VT.getScalarType()) &&
8356          "Should only be a truncating store, not extending!");
8357   assert(VT.isInteger() == SVT.isInteger() && "Can't do FP-INT conversion!");
8358   assert(VT.isVector() == SVT.isVector() &&
8359          "Cannot use trunc store to convert to or from a vector!");
8360   assert((!VT.isVector() ||
8361           VT.getVectorElementCount() == SVT.getVectorElementCount()) &&
8362          "Cannot use trunc store to change the number of vector elements!");
8363 
8364   SDVTList VTs = getVTList(MVT::Other);
8365   SDValue Undef = getUNDEF(Ptr.getValueType());
8366   SDValue Ops[] = {Chain, Val, Ptr, Undef, Stride, Mask, EVL};
8367   FoldingSetNodeID ID;
8368   AddNodeIDNode(ID, ISD::EXPERIMENTAL_VP_STRIDED_STORE, VTs, Ops);
8369   ID.AddInteger(SVT.getRawBits());
8370   ID.AddInteger(getSyntheticNodeSubclassData<VPStridedStoreSDNode>(
8371       DL.getIROrder(), VTs, ISD::UNINDEXED, true, IsCompressing, SVT, MMO));
8372   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8373   void *IP = nullptr;
8374   if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
8375     cast<VPStridedStoreSDNode>(E)->refineAlignment(MMO);
8376     return SDValue(E, 0);
8377   }
8378   auto *N = newSDNode<VPStridedStoreSDNode>(DL.getIROrder(), DL.getDebugLoc(),
8379                                             VTs, ISD::UNINDEXED, true,
8380                                             IsCompressing, SVT, MMO);
8381   createOperands(N, Ops);
8382 
8383   CSEMap.InsertNode(N, IP);
8384   InsertNode(N);
8385   SDValue V(N, 0);
8386   NewSDValueDbgMsg(V, "Creating new node: ", this);
8387   return V;
8388 }
8389 
8390 SDValue SelectionDAG::getIndexedStridedStoreVP(SDValue OrigStore,
8391                                                const SDLoc &DL, SDValue Base,
8392                                                SDValue Offset,
8393                                                ISD::MemIndexedMode AM) {
8394   auto *SST = cast<VPStridedStoreSDNode>(OrigStore);
8395   assert(SST->getOffset().isUndef() &&
8396          "Strided store is already an indexed store!");
8397   SDVTList VTs = getVTList(Base.getValueType(), MVT::Other);
8398   SDValue Ops[] = {
8399       SST->getChain(), SST->getValue(),       Base, Offset, SST->getStride(),
8400       SST->getMask(),  SST->getVectorLength()};
8401   FoldingSetNodeID ID;
8402   AddNodeIDNode(ID, ISD::EXPERIMENTAL_VP_STRIDED_STORE, VTs, Ops);
8403   ID.AddInteger(SST->getMemoryVT().getRawBits());
8404   ID.AddInteger(SST->getRawSubclassData());
8405   ID.AddInteger(SST->getPointerInfo().getAddrSpace());
8406   void *IP = nullptr;
8407   if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
8408     return SDValue(E, 0);
8409 
8410   auto *N = newSDNode<VPStridedStoreSDNode>(
8411       DL.getIROrder(), DL.getDebugLoc(), VTs, AM, SST->isTruncatingStore(),
8412       SST->isCompressingStore(), SST->getMemoryVT(), SST->getMemOperand());
8413   createOperands(N, Ops);
8414 
8415   CSEMap.InsertNode(N, IP);
8416   InsertNode(N);
8417   SDValue V(N, 0);
8418   NewSDValueDbgMsg(V, "Creating new node: ", this);
8419   return V;
8420 }
8421 
8422 SDValue SelectionDAG::getGatherVP(SDVTList VTs, EVT VT, const SDLoc &dl,
8423                                   ArrayRef<SDValue> Ops, MachineMemOperand *MMO,
8424                                   ISD::MemIndexType IndexType) {
8425   assert(Ops.size() == 6 && "Incompatible number of operands");
8426 
8427   FoldingSetNodeID ID;
8428   AddNodeIDNode(ID, ISD::VP_GATHER, VTs, Ops);
8429   ID.AddInteger(VT.getRawBits());
8430   ID.AddInteger(getSyntheticNodeSubclassData<VPGatherSDNode>(
8431       dl.getIROrder(), VTs, VT, MMO, IndexType));
8432   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8433   ID.AddInteger(MMO->getFlags());
8434   void *IP = nullptr;
8435   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
8436     cast<VPGatherSDNode>(E)->refineAlignment(MMO);
8437     return SDValue(E, 0);
8438   }
8439 
8440   auto *N = newSDNode<VPGatherSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
8441                                       VT, MMO, IndexType);
8442   createOperands(N, Ops);
8443 
8444   assert(N->getMask().getValueType().getVectorElementCount() ==
8445              N->getValueType(0).getVectorElementCount() &&
8446          "Vector width mismatch between mask and data");
8447   assert(N->getIndex().getValueType().getVectorElementCount().isScalable() ==
8448              N->getValueType(0).getVectorElementCount().isScalable() &&
8449          "Scalable flags of index and data do not match");
8450   assert(ElementCount::isKnownGE(
8451              N->getIndex().getValueType().getVectorElementCount(),
8452              N->getValueType(0).getVectorElementCount()) &&
8453          "Vector width mismatch between index and data");
8454   assert(isa<ConstantSDNode>(N->getScale()) &&
8455          cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() &&
8456          "Scale should be a constant power of 2");
8457 
8458   CSEMap.InsertNode(N, IP);
8459   InsertNode(N);
8460   SDValue V(N, 0);
8461   NewSDValueDbgMsg(V, "Creating new node: ", this);
8462   return V;
8463 }
8464 
8465 SDValue SelectionDAG::getScatterVP(SDVTList VTs, EVT VT, const SDLoc &dl,
8466                                    ArrayRef<SDValue> Ops,
8467                                    MachineMemOperand *MMO,
8468                                    ISD::MemIndexType IndexType) {
8469   assert(Ops.size() == 7 && "Incompatible number of operands");
8470 
8471   FoldingSetNodeID ID;
8472   AddNodeIDNode(ID, ISD::VP_SCATTER, VTs, Ops);
8473   ID.AddInteger(VT.getRawBits());
8474   ID.AddInteger(getSyntheticNodeSubclassData<VPScatterSDNode>(
8475       dl.getIROrder(), VTs, VT, MMO, IndexType));
8476   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8477   ID.AddInteger(MMO->getFlags());
8478   void *IP = nullptr;
8479   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
8480     cast<VPScatterSDNode>(E)->refineAlignment(MMO);
8481     return SDValue(E, 0);
8482   }
8483   auto *N = newSDNode<VPScatterSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
8484                                        VT, MMO, IndexType);
8485   createOperands(N, Ops);
8486 
8487   assert(N->getMask().getValueType().getVectorElementCount() ==
8488              N->getValue().getValueType().getVectorElementCount() &&
8489          "Vector width mismatch between mask and data");
8490   assert(
8491       N->getIndex().getValueType().getVectorElementCount().isScalable() ==
8492           N->getValue().getValueType().getVectorElementCount().isScalable() &&
8493       "Scalable flags of index and data do not match");
8494   assert(ElementCount::isKnownGE(
8495              N->getIndex().getValueType().getVectorElementCount(),
8496              N->getValue().getValueType().getVectorElementCount()) &&
8497          "Vector width mismatch between index and data");
8498   assert(isa<ConstantSDNode>(N->getScale()) &&
8499          cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() &&
8500          "Scale should be a constant power of 2");
8501 
8502   CSEMap.InsertNode(N, IP);
8503   InsertNode(N);
8504   SDValue V(N, 0);
8505   NewSDValueDbgMsg(V, "Creating new node: ", this);
8506   return V;
8507 }
8508 
8509 SDValue SelectionDAG::getMaskedLoad(EVT VT, const SDLoc &dl, SDValue Chain,
8510                                     SDValue Base, SDValue Offset, SDValue Mask,
8511                                     SDValue PassThru, EVT MemVT,
8512                                     MachineMemOperand *MMO,
8513                                     ISD::MemIndexedMode AM,
8514                                     ISD::LoadExtType ExtTy, bool isExpanding) {
8515   bool Indexed = AM != ISD::UNINDEXED;
8516   assert((Indexed || Offset.isUndef()) &&
8517          "Unindexed masked load with an offset!");
8518   SDVTList VTs = Indexed ? getVTList(VT, Base.getValueType(), MVT::Other)
8519                          : getVTList(VT, MVT::Other);
8520   SDValue Ops[] = {Chain, Base, Offset, Mask, PassThru};
8521   FoldingSetNodeID ID;
8522   AddNodeIDNode(ID, ISD::MLOAD, VTs, Ops);
8523   ID.AddInteger(MemVT.getRawBits());
8524   ID.AddInteger(getSyntheticNodeSubclassData<MaskedLoadSDNode>(
8525       dl.getIROrder(), VTs, AM, ExtTy, isExpanding, MemVT, MMO));
8526   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8527   ID.AddInteger(MMO->getFlags());
8528   void *IP = nullptr;
8529   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
8530     cast<MaskedLoadSDNode>(E)->refineAlignment(MMO);
8531     return SDValue(E, 0);
8532   }
8533   auto *N = newSDNode<MaskedLoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
8534                                         AM, ExtTy, isExpanding, MemVT, MMO);
8535   createOperands(N, Ops);
8536 
8537   CSEMap.InsertNode(N, IP);
8538   InsertNode(N);
8539   SDValue V(N, 0);
8540   NewSDValueDbgMsg(V, "Creating new node: ", this);
8541   return V;
8542 }
8543 
8544 SDValue SelectionDAG::getIndexedMaskedLoad(SDValue OrigLoad, const SDLoc &dl,
8545                                            SDValue Base, SDValue Offset,
8546                                            ISD::MemIndexedMode AM) {
8547   MaskedLoadSDNode *LD = cast<MaskedLoadSDNode>(OrigLoad);
8548   assert(LD->getOffset().isUndef() && "Masked load is already a indexed load!");
8549   return getMaskedLoad(OrigLoad.getValueType(), dl, LD->getChain(), Base,
8550                        Offset, LD->getMask(), LD->getPassThru(),
8551                        LD->getMemoryVT(), LD->getMemOperand(), AM,
8552                        LD->getExtensionType(), LD->isExpandingLoad());
8553 }
8554 
8555 SDValue SelectionDAG::getMaskedStore(SDValue Chain, const SDLoc &dl,
8556                                      SDValue Val, SDValue Base, SDValue Offset,
8557                                      SDValue Mask, EVT MemVT,
8558                                      MachineMemOperand *MMO,
8559                                      ISD::MemIndexedMode AM, bool IsTruncating,
8560                                      bool IsCompressing) {
8561   assert(Chain.getValueType() == MVT::Other &&
8562         "Invalid chain type");
8563   bool Indexed = AM != ISD::UNINDEXED;
8564   assert((Indexed || Offset.isUndef()) &&
8565          "Unindexed masked store with an offset!");
8566   SDVTList VTs = Indexed ? getVTList(Base.getValueType(), MVT::Other)
8567                          : getVTList(MVT::Other);
8568   SDValue Ops[] = {Chain, Val, Base, Offset, Mask};
8569   FoldingSetNodeID ID;
8570   AddNodeIDNode(ID, ISD::MSTORE, VTs, Ops);
8571   ID.AddInteger(MemVT.getRawBits());
8572   ID.AddInteger(getSyntheticNodeSubclassData<MaskedStoreSDNode>(
8573       dl.getIROrder(), VTs, AM, IsTruncating, IsCompressing, MemVT, MMO));
8574   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8575   ID.AddInteger(MMO->getFlags());
8576   void *IP = nullptr;
8577   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
8578     cast<MaskedStoreSDNode>(E)->refineAlignment(MMO);
8579     return SDValue(E, 0);
8580   }
8581   auto *N =
8582       newSDNode<MaskedStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
8583                                    IsTruncating, IsCompressing, MemVT, MMO);
8584   createOperands(N, Ops);
8585 
8586   CSEMap.InsertNode(N, IP);
8587   InsertNode(N);
8588   SDValue V(N, 0);
8589   NewSDValueDbgMsg(V, "Creating new node: ", this);
8590   return V;
8591 }
8592 
8593 SDValue SelectionDAG::getIndexedMaskedStore(SDValue OrigStore, const SDLoc &dl,
8594                                             SDValue Base, SDValue Offset,
8595                                             ISD::MemIndexedMode AM) {
8596   MaskedStoreSDNode *ST = cast<MaskedStoreSDNode>(OrigStore);
8597   assert(ST->getOffset().isUndef() &&
8598          "Masked store is already a indexed store!");
8599   return getMaskedStore(ST->getChain(), dl, ST->getValue(), Base, Offset,
8600                         ST->getMask(), ST->getMemoryVT(), ST->getMemOperand(),
8601                         AM, ST->isTruncatingStore(), ST->isCompressingStore());
8602 }
8603 
8604 SDValue SelectionDAG::getMaskedGather(SDVTList VTs, EVT MemVT, const SDLoc &dl,
8605                                       ArrayRef<SDValue> Ops,
8606                                       MachineMemOperand *MMO,
8607                                       ISD::MemIndexType IndexType,
8608                                       ISD::LoadExtType ExtTy) {
8609   assert(Ops.size() == 6 && "Incompatible number of operands");
8610 
8611   FoldingSetNodeID ID;
8612   AddNodeIDNode(ID, ISD::MGATHER, VTs, Ops);
8613   ID.AddInteger(MemVT.getRawBits());
8614   ID.AddInteger(getSyntheticNodeSubclassData<MaskedGatherSDNode>(
8615       dl.getIROrder(), VTs, MemVT, MMO, IndexType, ExtTy));
8616   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8617   ID.AddInteger(MMO->getFlags());
8618   void *IP = nullptr;
8619   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
8620     cast<MaskedGatherSDNode>(E)->refineAlignment(MMO);
8621     return SDValue(E, 0);
8622   }
8623 
8624   auto *N = newSDNode<MaskedGatherSDNode>(dl.getIROrder(), dl.getDebugLoc(),
8625                                           VTs, MemVT, MMO, IndexType, ExtTy);
8626   createOperands(N, Ops);
8627 
8628   assert(N->getPassThru().getValueType() == N->getValueType(0) &&
8629          "Incompatible type of the PassThru value in MaskedGatherSDNode");
8630   assert(N->getMask().getValueType().getVectorElementCount() ==
8631              N->getValueType(0).getVectorElementCount() &&
8632          "Vector width mismatch between mask and data");
8633   assert(N->getIndex().getValueType().getVectorElementCount().isScalable() ==
8634              N->getValueType(0).getVectorElementCount().isScalable() &&
8635          "Scalable flags of index and data do not match");
8636   assert(ElementCount::isKnownGE(
8637              N->getIndex().getValueType().getVectorElementCount(),
8638              N->getValueType(0).getVectorElementCount()) &&
8639          "Vector width mismatch between index and data");
8640   assert(isa<ConstantSDNode>(N->getScale()) &&
8641          cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() &&
8642          "Scale should be a constant power of 2");
8643 
8644   CSEMap.InsertNode(N, IP);
8645   InsertNode(N);
8646   SDValue V(N, 0);
8647   NewSDValueDbgMsg(V, "Creating new node: ", this);
8648   return V;
8649 }
8650 
8651 SDValue SelectionDAG::getMaskedScatter(SDVTList VTs, EVT MemVT, const SDLoc &dl,
8652                                        ArrayRef<SDValue> Ops,
8653                                        MachineMemOperand *MMO,
8654                                        ISD::MemIndexType IndexType,
8655                                        bool IsTrunc) {
8656   assert(Ops.size() == 6 && "Incompatible number of operands");
8657 
8658   FoldingSetNodeID ID;
8659   AddNodeIDNode(ID, ISD::MSCATTER, VTs, Ops);
8660   ID.AddInteger(MemVT.getRawBits());
8661   ID.AddInteger(getSyntheticNodeSubclassData<MaskedScatterSDNode>(
8662       dl.getIROrder(), VTs, MemVT, MMO, IndexType, IsTrunc));
8663   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8664   ID.AddInteger(MMO->getFlags());
8665   void *IP = nullptr;
8666   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
8667     cast<MaskedScatterSDNode>(E)->refineAlignment(MMO);
8668     return SDValue(E, 0);
8669   }
8670 
8671   auto *N = newSDNode<MaskedScatterSDNode>(dl.getIROrder(), dl.getDebugLoc(),
8672                                            VTs, MemVT, MMO, IndexType, IsTrunc);
8673   createOperands(N, Ops);
8674 
8675   assert(N->getMask().getValueType().getVectorElementCount() ==
8676              N->getValue().getValueType().getVectorElementCount() &&
8677          "Vector width mismatch between mask and data");
8678   assert(
8679       N->getIndex().getValueType().getVectorElementCount().isScalable() ==
8680           N->getValue().getValueType().getVectorElementCount().isScalable() &&
8681       "Scalable flags of index and data do not match");
8682   assert(ElementCount::isKnownGE(
8683              N->getIndex().getValueType().getVectorElementCount(),
8684              N->getValue().getValueType().getVectorElementCount()) &&
8685          "Vector width mismatch between index and data");
8686   assert(isa<ConstantSDNode>(N->getScale()) &&
8687          cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() &&
8688          "Scale should be a constant power of 2");
8689 
8690   CSEMap.InsertNode(N, IP);
8691   InsertNode(N);
8692   SDValue V(N, 0);
8693   NewSDValueDbgMsg(V, "Creating new node: ", this);
8694   return V;
8695 }
8696 
8697 SDValue SelectionDAG::simplifySelect(SDValue Cond, SDValue T, SDValue F) {
8698   // select undef, T, F --> T (if T is a constant), otherwise F
8699   // select, ?, undef, F --> F
8700   // select, ?, T, undef --> T
8701   if (Cond.isUndef())
8702     return isConstantValueOfAnyType(T) ? T : F;
8703   if (T.isUndef())
8704     return F;
8705   if (F.isUndef())
8706     return T;
8707 
8708   // select true, T, F --> T
8709   // select false, T, F --> F
8710   if (auto *CondC = dyn_cast<ConstantSDNode>(Cond))
8711     return CondC->isZero() ? F : T;
8712 
8713   // TODO: This should simplify VSELECT with constant condition using something
8714   // like this (but check boolean contents to be complete?):
8715   //  if (ISD::isBuildVectorAllOnes(Cond.getNode()))
8716   //    return T;
8717   //  if (ISD::isBuildVectorAllZeros(Cond.getNode()))
8718   //    return F;
8719 
8720   // select ?, T, T --> T
8721   if (T == F)
8722     return T;
8723 
8724   return SDValue();
8725 }
8726 
8727 SDValue SelectionDAG::simplifyShift(SDValue X, SDValue Y) {
8728   // shift undef, Y --> 0 (can always assume that the undef value is 0)
8729   if (X.isUndef())
8730     return getConstant(0, SDLoc(X.getNode()), X.getValueType());
8731   // shift X, undef --> undef (because it may shift by the bitwidth)
8732   if (Y.isUndef())
8733     return getUNDEF(X.getValueType());
8734 
8735   // shift 0, Y --> 0
8736   // shift X, 0 --> X
8737   if (isNullOrNullSplat(X) || isNullOrNullSplat(Y))
8738     return X;
8739 
8740   // shift X, C >= bitwidth(X) --> undef
8741   // All vector elements must be too big (or undef) to avoid partial undefs.
8742   auto isShiftTooBig = [X](ConstantSDNode *Val) {
8743     return !Val || Val->getAPIntValue().uge(X.getScalarValueSizeInBits());
8744   };
8745   if (ISD::matchUnaryPredicate(Y, isShiftTooBig, true))
8746     return getUNDEF(X.getValueType());
8747 
8748   return SDValue();
8749 }
8750 
8751 SDValue SelectionDAG::simplifyFPBinop(unsigned Opcode, SDValue X, SDValue Y,
8752                                       SDNodeFlags Flags) {
8753   // If this operation has 'nnan' or 'ninf' and at least 1 disallowed operand
8754   // (an undef operand can be chosen to be Nan/Inf), then the result of this
8755   // operation is poison. That result can be relaxed to undef.
8756   ConstantFPSDNode *XC = isConstOrConstSplatFP(X, /* AllowUndefs */ true);
8757   ConstantFPSDNode *YC = isConstOrConstSplatFP(Y, /* AllowUndefs */ true);
8758   bool HasNan = (XC && XC->getValueAPF().isNaN()) ||
8759                 (YC && YC->getValueAPF().isNaN());
8760   bool HasInf = (XC && XC->getValueAPF().isInfinity()) ||
8761                 (YC && YC->getValueAPF().isInfinity());
8762 
8763   if (Flags.hasNoNaNs() && (HasNan || X.isUndef() || Y.isUndef()))
8764     return getUNDEF(X.getValueType());
8765 
8766   if (Flags.hasNoInfs() && (HasInf || X.isUndef() || Y.isUndef()))
8767     return getUNDEF(X.getValueType());
8768 
8769   if (!YC)
8770     return SDValue();
8771 
8772   // X + -0.0 --> X
8773   if (Opcode == ISD::FADD)
8774     if (YC->getValueAPF().isNegZero())
8775       return X;
8776 
8777   // X - +0.0 --> X
8778   if (Opcode == ISD::FSUB)
8779     if (YC->getValueAPF().isPosZero())
8780       return X;
8781 
8782   // X * 1.0 --> X
8783   // X / 1.0 --> X
8784   if (Opcode == ISD::FMUL || Opcode == ISD::FDIV)
8785     if (YC->getValueAPF().isExactlyValue(1.0))
8786       return X;
8787 
8788   // X * 0.0 --> 0.0
8789   if (Opcode == ISD::FMUL && Flags.hasNoNaNs() && Flags.hasNoSignedZeros())
8790     if (YC->getValueAPF().isZero())
8791       return getConstantFP(0.0, SDLoc(Y), Y.getValueType());
8792 
8793   return SDValue();
8794 }
8795 
8796 SDValue SelectionDAG::getVAArg(EVT VT, const SDLoc &dl, SDValue Chain,
8797                                SDValue Ptr, SDValue SV, unsigned Align) {
8798   SDValue Ops[] = { Chain, Ptr, SV, getTargetConstant(Align, dl, MVT::i32) };
8799   return getNode(ISD::VAARG, dl, getVTList(VT, MVT::Other), Ops);
8800 }
8801 
8802 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
8803                               ArrayRef<SDUse> Ops) {
8804   switch (Ops.size()) {
8805   case 0: return getNode(Opcode, DL, VT);
8806   case 1: return getNode(Opcode, DL, VT, static_cast<const SDValue>(Ops[0]));
8807   case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1]);
8808   case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2]);
8809   default: break;
8810   }
8811 
8812   // Copy from an SDUse array into an SDValue array for use with
8813   // the regular getNode logic.
8814   SmallVector<SDValue, 8> NewOps(Ops.begin(), Ops.end());
8815   return getNode(Opcode, DL, VT, NewOps);
8816 }
8817 
8818 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
8819                               ArrayRef<SDValue> Ops) {
8820   SDNodeFlags Flags;
8821   if (Inserter)
8822     Flags = Inserter->getFlags();
8823   return getNode(Opcode, DL, VT, Ops, Flags);
8824 }
8825 
8826 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
8827                               ArrayRef<SDValue> Ops, const SDNodeFlags Flags) {
8828   unsigned NumOps = Ops.size();
8829   switch (NumOps) {
8830   case 0: return getNode(Opcode, DL, VT);
8831   case 1: return getNode(Opcode, DL, VT, Ops[0], Flags);
8832   case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Flags);
8833   case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2], Flags);
8834   default: break;
8835   }
8836 
8837 #ifndef NDEBUG
8838   for (auto &Op : Ops)
8839     assert(Op.getOpcode() != ISD::DELETED_NODE &&
8840            "Operand is DELETED_NODE!");
8841 #endif
8842 
8843   switch (Opcode) {
8844   default: break;
8845   case ISD::BUILD_VECTOR:
8846     // Attempt to simplify BUILD_VECTOR.
8847     if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
8848       return V;
8849     break;
8850   case ISD::CONCAT_VECTORS:
8851     if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this))
8852       return V;
8853     break;
8854   case ISD::SELECT_CC:
8855     assert(NumOps == 5 && "SELECT_CC takes 5 operands!");
8856     assert(Ops[0].getValueType() == Ops[1].getValueType() &&
8857            "LHS and RHS of condition must have same type!");
8858     assert(Ops[2].getValueType() == Ops[3].getValueType() &&
8859            "True and False arms of SelectCC must have same type!");
8860     assert(Ops[2].getValueType() == VT &&
8861            "select_cc node must be of same type as true and false value!");
8862     break;
8863   case ISD::BR_CC:
8864     assert(NumOps == 5 && "BR_CC takes 5 operands!");
8865     assert(Ops[2].getValueType() == Ops[3].getValueType() &&
8866            "LHS/RHS of comparison should match types!");
8867     break;
8868   case ISD::VP_ADD:
8869   case ISD::VP_SUB:
8870     // If it is VP_ADD/VP_SUB mask operation then turn it to VP_XOR
8871     if (VT.isVector() && VT.getVectorElementType() == MVT::i1)
8872       Opcode = ISD::VP_XOR;
8873     break;
8874   case ISD::VP_MUL:
8875     // If it is VP_MUL mask operation then turn it to VP_AND
8876     if (VT.isVector() && VT.getVectorElementType() == MVT::i1)
8877       Opcode = ISD::VP_AND;
8878     break;
8879   case ISD::VP_REDUCE_MUL:
8880     // If it is VP_REDUCE_MUL mask operation then turn it to VP_REDUCE_AND
8881     if (VT == MVT::i1)
8882       Opcode = ISD::VP_REDUCE_AND;
8883     break;
8884   case ISD::VP_REDUCE_ADD:
8885     // If it is VP_REDUCE_ADD mask operation then turn it to VP_REDUCE_XOR
8886     if (VT == MVT::i1)
8887       Opcode = ISD::VP_REDUCE_XOR;
8888     break;
8889   case ISD::VP_REDUCE_SMAX:
8890   case ISD::VP_REDUCE_UMIN:
8891     // If it is VP_REDUCE_SMAX/VP_REDUCE_UMIN mask operation then turn it to
8892     // VP_REDUCE_AND.
8893     if (VT == MVT::i1)
8894       Opcode = ISD::VP_REDUCE_AND;
8895     break;
8896   case ISD::VP_REDUCE_SMIN:
8897   case ISD::VP_REDUCE_UMAX:
8898     // If it is VP_REDUCE_SMIN/VP_REDUCE_UMAX mask operation then turn it to
8899     // VP_REDUCE_OR.
8900     if (VT == MVT::i1)
8901       Opcode = ISD::VP_REDUCE_OR;
8902     break;
8903   }
8904 
8905   // Memoize nodes.
8906   SDNode *N;
8907   SDVTList VTs = getVTList(VT);
8908 
8909   if (VT != MVT::Glue) {
8910     FoldingSetNodeID ID;
8911     AddNodeIDNode(ID, Opcode, VTs, Ops);
8912     void *IP = nullptr;
8913 
8914     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
8915       return SDValue(E, 0);
8916 
8917     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
8918     createOperands(N, Ops);
8919 
8920     CSEMap.InsertNode(N, IP);
8921   } else {
8922     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
8923     createOperands(N, Ops);
8924   }
8925 
8926   N->setFlags(Flags);
8927   InsertNode(N);
8928   SDValue V(N, 0);
8929   NewSDValueDbgMsg(V, "Creating new node: ", this);
8930   return V;
8931 }
8932 
8933 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL,
8934                               ArrayRef<EVT> ResultTys, ArrayRef<SDValue> Ops) {
8935   return getNode(Opcode, DL, getVTList(ResultTys), Ops);
8936 }
8937 
8938 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
8939                               ArrayRef<SDValue> Ops) {
8940   SDNodeFlags Flags;
8941   if (Inserter)
8942     Flags = Inserter->getFlags();
8943   return getNode(Opcode, DL, VTList, Ops, Flags);
8944 }
8945 
8946 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
8947                               ArrayRef<SDValue> Ops, const SDNodeFlags Flags) {
8948   if (VTList.NumVTs == 1)
8949     return getNode(Opcode, DL, VTList.VTs[0], Ops, Flags);
8950 
8951 #ifndef NDEBUG
8952   for (auto &Op : Ops)
8953     assert(Op.getOpcode() != ISD::DELETED_NODE &&
8954            "Operand is DELETED_NODE!");
8955 #endif
8956 
8957   switch (Opcode) {
8958   case ISD::STRICT_FP_EXTEND:
8959     assert(VTList.NumVTs == 2 && Ops.size() == 2 &&
8960            "Invalid STRICT_FP_EXTEND!");
8961     assert(VTList.VTs[0].isFloatingPoint() &&
8962            Ops[1].getValueType().isFloatingPoint() && "Invalid FP cast!");
8963     assert(VTList.VTs[0].isVector() == Ops[1].getValueType().isVector() &&
8964            "STRICT_FP_EXTEND result type should be vector iff the operand "
8965            "type is vector!");
8966     assert((!VTList.VTs[0].isVector() ||
8967             VTList.VTs[0].getVectorNumElements() ==
8968             Ops[1].getValueType().getVectorNumElements()) &&
8969            "Vector element count mismatch!");
8970     assert(Ops[1].getValueType().bitsLT(VTList.VTs[0]) &&
8971            "Invalid fpext node, dst <= src!");
8972     break;
8973   case ISD::STRICT_FP_ROUND:
8974     assert(VTList.NumVTs == 2 && Ops.size() == 3 && "Invalid STRICT_FP_ROUND!");
8975     assert(VTList.VTs[0].isVector() == Ops[1].getValueType().isVector() &&
8976            "STRICT_FP_ROUND result type should be vector iff the operand "
8977            "type is vector!");
8978     assert((!VTList.VTs[0].isVector() ||
8979             VTList.VTs[0].getVectorNumElements() ==
8980             Ops[1].getValueType().getVectorNumElements()) &&
8981            "Vector element count mismatch!");
8982     assert(VTList.VTs[0].isFloatingPoint() &&
8983            Ops[1].getValueType().isFloatingPoint() &&
8984            VTList.VTs[0].bitsLT(Ops[1].getValueType()) &&
8985            isa<ConstantSDNode>(Ops[2]) &&
8986            (cast<ConstantSDNode>(Ops[2])->getZExtValue() == 0 ||
8987             cast<ConstantSDNode>(Ops[2])->getZExtValue() == 1) &&
8988            "Invalid STRICT_FP_ROUND!");
8989     break;
8990 #if 0
8991   // FIXME: figure out how to safely handle things like
8992   // int foo(int x) { return 1 << (x & 255); }
8993   // int bar() { return foo(256); }
8994   case ISD::SRA_PARTS:
8995   case ISD::SRL_PARTS:
8996   case ISD::SHL_PARTS:
8997     if (N3.getOpcode() == ISD::SIGN_EXTEND_INREG &&
8998         cast<VTSDNode>(N3.getOperand(1))->getVT() != MVT::i1)
8999       return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0));
9000     else if (N3.getOpcode() == ISD::AND)
9001       if (ConstantSDNode *AndRHS = dyn_cast<ConstantSDNode>(N3.getOperand(1))) {
9002         // If the and is only masking out bits that cannot effect the shift,
9003         // eliminate the and.
9004         unsigned NumBits = VT.getScalarSizeInBits()*2;
9005         if ((AndRHS->getValue() & (NumBits-1)) == NumBits-1)
9006           return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0));
9007       }
9008     break;
9009 #endif
9010   }
9011 
9012   // Memoize the node unless it returns a flag.
9013   SDNode *N;
9014   if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) {
9015     FoldingSetNodeID ID;
9016     AddNodeIDNode(ID, Opcode, VTList, Ops);
9017     void *IP = nullptr;
9018     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
9019       return SDValue(E, 0);
9020 
9021     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList);
9022     createOperands(N, Ops);
9023     CSEMap.InsertNode(N, IP);
9024   } else {
9025     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList);
9026     createOperands(N, Ops);
9027   }
9028 
9029   N->setFlags(Flags);
9030   InsertNode(N);
9031   SDValue V(N, 0);
9032   NewSDValueDbgMsg(V, "Creating new node: ", this);
9033   return V;
9034 }
9035 
9036 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL,
9037                               SDVTList VTList) {
9038   return getNode(Opcode, DL, VTList, None);
9039 }
9040 
9041 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
9042                               SDValue N1) {
9043   SDValue Ops[] = { N1 };
9044   return getNode(Opcode, DL, VTList, Ops);
9045 }
9046 
9047 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
9048                               SDValue N1, SDValue N2) {
9049   SDValue Ops[] = { N1, N2 };
9050   return getNode(Opcode, DL, VTList, Ops);
9051 }
9052 
9053 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
9054                               SDValue N1, SDValue N2, SDValue N3) {
9055   SDValue Ops[] = { N1, N2, N3 };
9056   return getNode(Opcode, DL, VTList, Ops);
9057 }
9058 
9059 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
9060                               SDValue N1, SDValue N2, SDValue N3, SDValue N4) {
9061   SDValue Ops[] = { N1, N2, N3, N4 };
9062   return getNode(Opcode, DL, VTList, Ops);
9063 }
9064 
9065 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
9066                               SDValue N1, SDValue N2, SDValue N3, SDValue N4,
9067                               SDValue N5) {
9068   SDValue Ops[] = { N1, N2, N3, N4, N5 };
9069   return getNode(Opcode, DL, VTList, Ops);
9070 }
9071 
9072 SDVTList SelectionDAG::getVTList(EVT VT) {
9073   return makeVTList(SDNode::getValueTypeList(VT), 1);
9074 }
9075 
9076 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2) {
9077   FoldingSetNodeID ID;
9078   ID.AddInteger(2U);
9079   ID.AddInteger(VT1.getRawBits());
9080   ID.AddInteger(VT2.getRawBits());
9081 
9082   void *IP = nullptr;
9083   SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
9084   if (!Result) {
9085     EVT *Array = Allocator.Allocate<EVT>(2);
9086     Array[0] = VT1;
9087     Array[1] = VT2;
9088     Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 2);
9089     VTListMap.InsertNode(Result, IP);
9090   }
9091   return Result->getSDVTList();
9092 }
9093 
9094 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3) {
9095   FoldingSetNodeID ID;
9096   ID.AddInteger(3U);
9097   ID.AddInteger(VT1.getRawBits());
9098   ID.AddInteger(VT2.getRawBits());
9099   ID.AddInteger(VT3.getRawBits());
9100 
9101   void *IP = nullptr;
9102   SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
9103   if (!Result) {
9104     EVT *Array = Allocator.Allocate<EVT>(3);
9105     Array[0] = VT1;
9106     Array[1] = VT2;
9107     Array[2] = VT3;
9108     Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 3);
9109     VTListMap.InsertNode(Result, IP);
9110   }
9111   return Result->getSDVTList();
9112 }
9113 
9114 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3, EVT VT4) {
9115   FoldingSetNodeID ID;
9116   ID.AddInteger(4U);
9117   ID.AddInteger(VT1.getRawBits());
9118   ID.AddInteger(VT2.getRawBits());
9119   ID.AddInteger(VT3.getRawBits());
9120   ID.AddInteger(VT4.getRawBits());
9121 
9122   void *IP = nullptr;
9123   SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
9124   if (!Result) {
9125     EVT *Array = Allocator.Allocate<EVT>(4);
9126     Array[0] = VT1;
9127     Array[1] = VT2;
9128     Array[2] = VT3;
9129     Array[3] = VT4;
9130     Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 4);
9131     VTListMap.InsertNode(Result, IP);
9132   }
9133   return Result->getSDVTList();
9134 }
9135 
9136 SDVTList SelectionDAG::getVTList(ArrayRef<EVT> VTs) {
9137   unsigned NumVTs = VTs.size();
9138   FoldingSetNodeID ID;
9139   ID.AddInteger(NumVTs);
9140   for (unsigned index = 0; index < NumVTs; index++) {
9141     ID.AddInteger(VTs[index].getRawBits());
9142   }
9143 
9144   void *IP = nullptr;
9145   SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
9146   if (!Result) {
9147     EVT *Array = Allocator.Allocate<EVT>(NumVTs);
9148     llvm::copy(VTs, Array);
9149     Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, NumVTs);
9150     VTListMap.InsertNode(Result, IP);
9151   }
9152   return Result->getSDVTList();
9153 }
9154 
9155 
9156 /// UpdateNodeOperands - *Mutate* the specified node in-place to have the
9157 /// specified operands.  If the resultant node already exists in the DAG,
9158 /// this does not modify the specified node, instead it returns the node that
9159 /// already exists.  If the resultant node does not exist in the DAG, the
9160 /// input node is returned.  As a degenerate case, if you specify the same
9161 /// input operands as the node already has, the input node is returned.
9162 SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op) {
9163   assert(N->getNumOperands() == 1 && "Update with wrong number of operands");
9164 
9165   // Check to see if there is no change.
9166   if (Op == N->getOperand(0)) return N;
9167 
9168   // See if the modified node already exists.
9169   void *InsertPos = nullptr;
9170   if (SDNode *Existing = FindModifiedNodeSlot(N, Op, InsertPos))
9171     return Existing;
9172 
9173   // Nope it doesn't.  Remove the node from its current place in the maps.
9174   if (InsertPos)
9175     if (!RemoveNodeFromCSEMaps(N))
9176       InsertPos = nullptr;
9177 
9178   // Now we update the operands.
9179   N->OperandList[0].set(Op);
9180 
9181   updateDivergence(N);
9182   // If this gets put into a CSE map, add it.
9183   if (InsertPos) CSEMap.InsertNode(N, InsertPos);
9184   return N;
9185 }
9186 
9187 SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2) {
9188   assert(N->getNumOperands() == 2 && "Update with wrong number of operands");
9189 
9190   // Check to see if there is no change.
9191   if (Op1 == N->getOperand(0) && Op2 == N->getOperand(1))
9192     return N;   // No operands changed, just return the input node.
9193 
9194   // See if the modified node already exists.
9195   void *InsertPos = nullptr;
9196   if (SDNode *Existing = FindModifiedNodeSlot(N, Op1, Op2, InsertPos))
9197     return Existing;
9198 
9199   // Nope it doesn't.  Remove the node from its current place in the maps.
9200   if (InsertPos)
9201     if (!RemoveNodeFromCSEMaps(N))
9202       InsertPos = nullptr;
9203 
9204   // Now we update the operands.
9205   if (N->OperandList[0] != Op1)
9206     N->OperandList[0].set(Op1);
9207   if (N->OperandList[1] != Op2)
9208     N->OperandList[1].set(Op2);
9209 
9210   updateDivergence(N);
9211   // If this gets put into a CSE map, add it.
9212   if (InsertPos) CSEMap.InsertNode(N, InsertPos);
9213   return N;
9214 }
9215 
9216 SDNode *SelectionDAG::
9217 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2, SDValue Op3) {
9218   SDValue Ops[] = { Op1, Op2, Op3 };
9219   return UpdateNodeOperands(N, Ops);
9220 }
9221 
9222 SDNode *SelectionDAG::
9223 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2,
9224                    SDValue Op3, SDValue Op4) {
9225   SDValue Ops[] = { Op1, Op2, Op3, Op4 };
9226   return UpdateNodeOperands(N, Ops);
9227 }
9228 
9229 SDNode *SelectionDAG::
9230 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2,
9231                    SDValue Op3, SDValue Op4, SDValue Op5) {
9232   SDValue Ops[] = { Op1, Op2, Op3, Op4, Op5 };
9233   return UpdateNodeOperands(N, Ops);
9234 }
9235 
9236 SDNode *SelectionDAG::
9237 UpdateNodeOperands(SDNode *N, ArrayRef<SDValue> Ops) {
9238   unsigned NumOps = Ops.size();
9239   assert(N->getNumOperands() == NumOps &&
9240          "Update with wrong number of operands");
9241 
9242   // If no operands changed just return the input node.
9243   if (std::equal(Ops.begin(), Ops.end(), N->op_begin()))
9244     return N;
9245 
9246   // See if the modified node already exists.
9247   void *InsertPos = nullptr;
9248   if (SDNode *Existing = FindModifiedNodeSlot(N, Ops, InsertPos))
9249     return Existing;
9250 
9251   // Nope it doesn't.  Remove the node from its current place in the maps.
9252   if (InsertPos)
9253     if (!RemoveNodeFromCSEMaps(N))
9254       InsertPos = nullptr;
9255 
9256   // Now we update the operands.
9257   for (unsigned i = 0; i != NumOps; ++i)
9258     if (N->OperandList[i] != Ops[i])
9259       N->OperandList[i].set(Ops[i]);
9260 
9261   updateDivergence(N);
9262   // If this gets put into a CSE map, add it.
9263   if (InsertPos) CSEMap.InsertNode(N, InsertPos);
9264   return N;
9265 }
9266 
9267 /// DropOperands - Release the operands and set this node to have
9268 /// zero operands.
9269 void SDNode::DropOperands() {
9270   // Unlike the code in MorphNodeTo that does this, we don't need to
9271   // watch for dead nodes here.
9272   for (op_iterator I = op_begin(), E = op_end(); I != E; ) {
9273     SDUse &Use = *I++;
9274     Use.set(SDValue());
9275   }
9276 }
9277 
9278 void SelectionDAG::setNodeMemRefs(MachineSDNode *N,
9279                                   ArrayRef<MachineMemOperand *> NewMemRefs) {
9280   if (NewMemRefs.empty()) {
9281     N->clearMemRefs();
9282     return;
9283   }
9284 
9285   // Check if we can avoid allocating by storing a single reference directly.
9286   if (NewMemRefs.size() == 1) {
9287     N->MemRefs = NewMemRefs[0];
9288     N->NumMemRefs = 1;
9289     return;
9290   }
9291 
9292   MachineMemOperand **MemRefsBuffer =
9293       Allocator.template Allocate<MachineMemOperand *>(NewMemRefs.size());
9294   llvm::copy(NewMemRefs, MemRefsBuffer);
9295   N->MemRefs = MemRefsBuffer;
9296   N->NumMemRefs = static_cast<int>(NewMemRefs.size());
9297 }
9298 
9299 /// SelectNodeTo - These are wrappers around MorphNodeTo that accept a
9300 /// machine opcode.
9301 ///
9302 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
9303                                    EVT VT) {
9304   SDVTList VTs = getVTList(VT);
9305   return SelectNodeTo(N, MachineOpc, VTs, None);
9306 }
9307 
9308 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
9309                                    EVT VT, SDValue Op1) {
9310   SDVTList VTs = getVTList(VT);
9311   SDValue Ops[] = { Op1 };
9312   return SelectNodeTo(N, MachineOpc, VTs, Ops);
9313 }
9314 
9315 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
9316                                    EVT VT, SDValue Op1,
9317                                    SDValue Op2) {
9318   SDVTList VTs = getVTList(VT);
9319   SDValue Ops[] = { Op1, Op2 };
9320   return SelectNodeTo(N, MachineOpc, VTs, Ops);
9321 }
9322 
9323 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
9324                                    EVT VT, SDValue Op1,
9325                                    SDValue Op2, SDValue Op3) {
9326   SDVTList VTs = getVTList(VT);
9327   SDValue Ops[] = { Op1, Op2, Op3 };
9328   return SelectNodeTo(N, MachineOpc, VTs, Ops);
9329 }
9330 
9331 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
9332                                    EVT VT, ArrayRef<SDValue> Ops) {
9333   SDVTList VTs = getVTList(VT);
9334   return SelectNodeTo(N, MachineOpc, VTs, Ops);
9335 }
9336 
9337 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
9338                                    EVT VT1, EVT VT2, ArrayRef<SDValue> Ops) {
9339   SDVTList VTs = getVTList(VT1, VT2);
9340   return SelectNodeTo(N, MachineOpc, VTs, Ops);
9341 }
9342 
9343 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
9344                                    EVT VT1, EVT VT2) {
9345   SDVTList VTs = getVTList(VT1, VT2);
9346   return SelectNodeTo(N, MachineOpc, VTs, None);
9347 }
9348 
9349 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
9350                                    EVT VT1, EVT VT2, EVT VT3,
9351                                    ArrayRef<SDValue> Ops) {
9352   SDVTList VTs = getVTList(VT1, VT2, VT3);
9353   return SelectNodeTo(N, MachineOpc, VTs, Ops);
9354 }
9355 
9356 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
9357                                    EVT VT1, EVT VT2,
9358                                    SDValue Op1, SDValue Op2) {
9359   SDVTList VTs = getVTList(VT1, VT2);
9360   SDValue Ops[] = { Op1, Op2 };
9361   return SelectNodeTo(N, MachineOpc, VTs, Ops);
9362 }
9363 
9364 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
9365                                    SDVTList VTs,ArrayRef<SDValue> Ops) {
9366   SDNode *New = MorphNodeTo(N, ~MachineOpc, VTs, Ops);
9367   // Reset the NodeID to -1.
9368   New->setNodeId(-1);
9369   if (New != N) {
9370     ReplaceAllUsesWith(N, New);
9371     RemoveDeadNode(N);
9372   }
9373   return New;
9374 }
9375 
9376 /// UpdateSDLocOnMergeSDNode - If the opt level is -O0 then it throws away
9377 /// the line number information on the merged node since it is not possible to
9378 /// preserve the information that operation is associated with multiple lines.
9379 /// This will make the debugger working better at -O0, were there is a higher
9380 /// probability having other instructions associated with that line.
9381 ///
9382 /// For IROrder, we keep the smaller of the two
9383 SDNode *SelectionDAG::UpdateSDLocOnMergeSDNode(SDNode *N, const SDLoc &OLoc) {
9384   DebugLoc NLoc = N->getDebugLoc();
9385   if (NLoc && OptLevel == CodeGenOpt::None && OLoc.getDebugLoc() != NLoc) {
9386     N->setDebugLoc(DebugLoc());
9387   }
9388   unsigned Order = std::min(N->getIROrder(), OLoc.getIROrder());
9389   N->setIROrder(Order);
9390   return N;
9391 }
9392 
9393 /// MorphNodeTo - This *mutates* the specified node to have the specified
9394 /// return type, opcode, and operands.
9395 ///
9396 /// Note that MorphNodeTo returns the resultant node.  If there is already a
9397 /// node of the specified opcode and operands, it returns that node instead of
9398 /// the current one.  Note that the SDLoc need not be the same.
9399 ///
9400 /// Using MorphNodeTo is faster than creating a new node and swapping it in
9401 /// with ReplaceAllUsesWith both because it often avoids allocating a new
9402 /// node, and because it doesn't require CSE recalculation for any of
9403 /// the node's users.
9404 ///
9405 /// However, note that MorphNodeTo recursively deletes dead nodes from the DAG.
9406 /// As a consequence it isn't appropriate to use from within the DAG combiner or
9407 /// the legalizer which maintain worklists that would need to be updated when
9408 /// deleting things.
9409 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
9410                                   SDVTList VTs, ArrayRef<SDValue> Ops) {
9411   // If an identical node already exists, use it.
9412   void *IP = nullptr;
9413   if (VTs.VTs[VTs.NumVTs-1] != MVT::Glue) {
9414     FoldingSetNodeID ID;
9415     AddNodeIDNode(ID, Opc, VTs, Ops);
9416     if (SDNode *ON = FindNodeOrInsertPos(ID, SDLoc(N), IP))
9417       return UpdateSDLocOnMergeSDNode(ON, SDLoc(N));
9418   }
9419 
9420   if (!RemoveNodeFromCSEMaps(N))
9421     IP = nullptr;
9422 
9423   // Start the morphing.
9424   N->NodeType = Opc;
9425   N->ValueList = VTs.VTs;
9426   N->NumValues = VTs.NumVTs;
9427 
9428   // Clear the operands list, updating used nodes to remove this from their
9429   // use list.  Keep track of any operands that become dead as a result.
9430   SmallPtrSet<SDNode*, 16> DeadNodeSet;
9431   for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) {
9432     SDUse &Use = *I++;
9433     SDNode *Used = Use.getNode();
9434     Use.set(SDValue());
9435     if (Used->use_empty())
9436       DeadNodeSet.insert(Used);
9437   }
9438 
9439   // For MachineNode, initialize the memory references information.
9440   if (MachineSDNode *MN = dyn_cast<MachineSDNode>(N))
9441     MN->clearMemRefs();
9442 
9443   // Swap for an appropriately sized array from the recycler.
9444   removeOperands(N);
9445   createOperands(N, Ops);
9446 
9447   // Delete any nodes that are still dead after adding the uses for the
9448   // new operands.
9449   if (!DeadNodeSet.empty()) {
9450     SmallVector<SDNode *, 16> DeadNodes;
9451     for (SDNode *N : DeadNodeSet)
9452       if (N->use_empty())
9453         DeadNodes.push_back(N);
9454     RemoveDeadNodes(DeadNodes);
9455   }
9456 
9457   if (IP)
9458     CSEMap.InsertNode(N, IP);   // Memoize the new node.
9459   return N;
9460 }
9461 
9462 SDNode* SelectionDAG::mutateStrictFPToFP(SDNode *Node) {
9463   unsigned OrigOpc = Node->getOpcode();
9464   unsigned NewOpc;
9465   switch (OrigOpc) {
9466   default:
9467     llvm_unreachable("mutateStrictFPToFP called with unexpected opcode!");
9468 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN)               \
9469   case ISD::STRICT_##DAGN: NewOpc = ISD::DAGN; break;
9470 #define CMP_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN)               \
9471   case ISD::STRICT_##DAGN: NewOpc = ISD::SETCC; break;
9472 #include "llvm/IR/ConstrainedOps.def"
9473   }
9474 
9475   assert(Node->getNumValues() == 2 && "Unexpected number of results!");
9476 
9477   // We're taking this node out of the chain, so we need to re-link things.
9478   SDValue InputChain = Node->getOperand(0);
9479   SDValue OutputChain = SDValue(Node, 1);
9480   ReplaceAllUsesOfValueWith(OutputChain, InputChain);
9481 
9482   SmallVector<SDValue, 3> Ops;
9483   for (unsigned i = 1, e = Node->getNumOperands(); i != e; ++i)
9484     Ops.push_back(Node->getOperand(i));
9485 
9486   SDVTList VTs = getVTList(Node->getValueType(0));
9487   SDNode *Res = MorphNodeTo(Node, NewOpc, VTs, Ops);
9488 
9489   // MorphNodeTo can operate in two ways: if an existing node with the
9490   // specified operands exists, it can just return it.  Otherwise, it
9491   // updates the node in place to have the requested operands.
9492   if (Res == Node) {
9493     // If we updated the node in place, reset the node ID.  To the isel,
9494     // this should be just like a newly allocated machine node.
9495     Res->setNodeId(-1);
9496   } else {
9497     ReplaceAllUsesWith(Node, Res);
9498     RemoveDeadNode(Node);
9499   }
9500 
9501   return Res;
9502 }
9503 
9504 /// getMachineNode - These are used for target selectors to create a new node
9505 /// with specified return type(s), MachineInstr opcode, and operands.
9506 ///
9507 /// Note that getMachineNode returns the resultant node.  If there is already a
9508 /// node of the specified opcode and operands, it returns that node instead of
9509 /// the current one.
9510 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9511                                             EVT VT) {
9512   SDVTList VTs = getVTList(VT);
9513   return getMachineNode(Opcode, dl, VTs, None);
9514 }
9515 
9516 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9517                                             EVT VT, SDValue Op1) {
9518   SDVTList VTs = getVTList(VT);
9519   SDValue Ops[] = { Op1 };
9520   return getMachineNode(Opcode, dl, VTs, Ops);
9521 }
9522 
9523 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9524                                             EVT VT, SDValue Op1, SDValue Op2) {
9525   SDVTList VTs = getVTList(VT);
9526   SDValue Ops[] = { Op1, Op2 };
9527   return getMachineNode(Opcode, dl, VTs, Ops);
9528 }
9529 
9530 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9531                                             EVT VT, SDValue Op1, SDValue Op2,
9532                                             SDValue Op3) {
9533   SDVTList VTs = getVTList(VT);
9534   SDValue Ops[] = { Op1, Op2, Op3 };
9535   return getMachineNode(Opcode, dl, VTs, Ops);
9536 }
9537 
9538 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9539                                             EVT VT, ArrayRef<SDValue> Ops) {
9540   SDVTList VTs = getVTList(VT);
9541   return getMachineNode(Opcode, dl, VTs, Ops);
9542 }
9543 
9544 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9545                                             EVT VT1, EVT VT2, SDValue Op1,
9546                                             SDValue Op2) {
9547   SDVTList VTs = getVTList(VT1, VT2);
9548   SDValue Ops[] = { Op1, Op2 };
9549   return getMachineNode(Opcode, dl, VTs, Ops);
9550 }
9551 
9552 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9553                                             EVT VT1, EVT VT2, SDValue Op1,
9554                                             SDValue Op2, SDValue Op3) {
9555   SDVTList VTs = getVTList(VT1, VT2);
9556   SDValue Ops[] = { Op1, Op2, Op3 };
9557   return getMachineNode(Opcode, dl, VTs, Ops);
9558 }
9559 
9560 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9561                                             EVT VT1, EVT VT2,
9562                                             ArrayRef<SDValue> Ops) {
9563   SDVTList VTs = getVTList(VT1, VT2);
9564   return getMachineNode(Opcode, dl, VTs, Ops);
9565 }
9566 
9567 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9568                                             EVT VT1, EVT VT2, EVT VT3,
9569                                             SDValue Op1, SDValue Op2) {
9570   SDVTList VTs = getVTList(VT1, VT2, VT3);
9571   SDValue Ops[] = { Op1, Op2 };
9572   return getMachineNode(Opcode, dl, VTs, Ops);
9573 }
9574 
9575 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9576                                             EVT VT1, EVT VT2, EVT VT3,
9577                                             SDValue Op1, SDValue Op2,
9578                                             SDValue Op3) {
9579   SDVTList VTs = getVTList(VT1, VT2, VT3);
9580   SDValue Ops[] = { Op1, Op2, Op3 };
9581   return getMachineNode(Opcode, dl, VTs, Ops);
9582 }
9583 
9584 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9585                                             EVT VT1, EVT VT2, EVT VT3,
9586                                             ArrayRef<SDValue> Ops) {
9587   SDVTList VTs = getVTList(VT1, VT2, VT3);
9588   return getMachineNode(Opcode, dl, VTs, Ops);
9589 }
9590 
9591 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9592                                             ArrayRef<EVT> ResultTys,
9593                                             ArrayRef<SDValue> Ops) {
9594   SDVTList VTs = getVTList(ResultTys);
9595   return getMachineNode(Opcode, dl, VTs, Ops);
9596 }
9597 
9598 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &DL,
9599                                             SDVTList VTs,
9600                                             ArrayRef<SDValue> Ops) {
9601   bool DoCSE = VTs.VTs[VTs.NumVTs-1] != MVT::Glue;
9602   MachineSDNode *N;
9603   void *IP = nullptr;
9604 
9605   if (DoCSE) {
9606     FoldingSetNodeID ID;
9607     AddNodeIDNode(ID, ~Opcode, VTs, Ops);
9608     IP = nullptr;
9609     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
9610       return cast<MachineSDNode>(UpdateSDLocOnMergeSDNode(E, DL));
9611     }
9612   }
9613 
9614   // Allocate a new MachineSDNode.
9615   N = newSDNode<MachineSDNode>(~Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
9616   createOperands(N, Ops);
9617 
9618   if (DoCSE)
9619     CSEMap.InsertNode(N, IP);
9620 
9621   InsertNode(N);
9622   NewSDValueDbgMsg(SDValue(N, 0), "Creating new machine node: ", this);
9623   return N;
9624 }
9625 
9626 /// getTargetExtractSubreg - A convenience function for creating
9627 /// TargetOpcode::EXTRACT_SUBREG nodes.
9628 SDValue SelectionDAG::getTargetExtractSubreg(int SRIdx, const SDLoc &DL, EVT VT,
9629                                              SDValue Operand) {
9630   SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32);
9631   SDNode *Subreg = getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL,
9632                                   VT, Operand, SRIdxVal);
9633   return SDValue(Subreg, 0);
9634 }
9635 
9636 /// getTargetInsertSubreg - A convenience function for creating
9637 /// TargetOpcode::INSERT_SUBREG nodes.
9638 SDValue SelectionDAG::getTargetInsertSubreg(int SRIdx, const SDLoc &DL, EVT VT,
9639                                             SDValue Operand, SDValue Subreg) {
9640   SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32);
9641   SDNode *Result = getMachineNode(TargetOpcode::INSERT_SUBREG, DL,
9642                                   VT, Operand, Subreg, SRIdxVal);
9643   return SDValue(Result, 0);
9644 }
9645 
9646 /// getNodeIfExists - Get the specified node if it's already available, or
9647 /// else return NULL.
9648 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList,
9649                                       ArrayRef<SDValue> Ops) {
9650   SDNodeFlags Flags;
9651   if (Inserter)
9652     Flags = Inserter->getFlags();
9653   return getNodeIfExists(Opcode, VTList, Ops, Flags);
9654 }
9655 
9656 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList,
9657                                       ArrayRef<SDValue> Ops,
9658                                       const SDNodeFlags Flags) {
9659   if (VTList.VTs[VTList.NumVTs - 1] != MVT::Glue) {
9660     FoldingSetNodeID ID;
9661     AddNodeIDNode(ID, Opcode, VTList, Ops);
9662     void *IP = nullptr;
9663     if (SDNode *E = FindNodeOrInsertPos(ID, SDLoc(), IP)) {
9664       E->intersectFlagsWith(Flags);
9665       return E;
9666     }
9667   }
9668   return nullptr;
9669 }
9670 
9671 /// doesNodeExist - Check if a node exists without modifying its flags.
9672 bool SelectionDAG::doesNodeExist(unsigned Opcode, SDVTList VTList,
9673                                  ArrayRef<SDValue> Ops) {
9674   if (VTList.VTs[VTList.NumVTs - 1] != MVT::Glue) {
9675     FoldingSetNodeID ID;
9676     AddNodeIDNode(ID, Opcode, VTList, Ops);
9677     void *IP = nullptr;
9678     if (FindNodeOrInsertPos(ID, SDLoc(), IP))
9679       return true;
9680   }
9681   return false;
9682 }
9683 
9684 /// getDbgValue - Creates a SDDbgValue node.
9685 ///
9686 /// SDNode
9687 SDDbgValue *SelectionDAG::getDbgValue(DIVariable *Var, DIExpression *Expr,
9688                                       SDNode *N, unsigned R, bool IsIndirect,
9689                                       const DebugLoc &DL, unsigned O) {
9690   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
9691          "Expected inlined-at fields to agree");
9692   return new (DbgInfo->getAlloc())
9693       SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromNode(N, R),
9694                  {}, IsIndirect, DL, O,
9695                  /*IsVariadic=*/false);
9696 }
9697 
9698 /// Constant
9699 SDDbgValue *SelectionDAG::getConstantDbgValue(DIVariable *Var,
9700                                               DIExpression *Expr,
9701                                               const Value *C,
9702                                               const DebugLoc &DL, unsigned O) {
9703   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
9704          "Expected inlined-at fields to agree");
9705   return new (DbgInfo->getAlloc())
9706       SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromConst(C), {},
9707                  /*IsIndirect=*/false, DL, O,
9708                  /*IsVariadic=*/false);
9709 }
9710 
9711 /// FrameIndex
9712 SDDbgValue *SelectionDAG::getFrameIndexDbgValue(DIVariable *Var,
9713                                                 DIExpression *Expr, unsigned FI,
9714                                                 bool IsIndirect,
9715                                                 const DebugLoc &DL,
9716                                                 unsigned O) {
9717   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
9718          "Expected inlined-at fields to agree");
9719   return getFrameIndexDbgValue(Var, Expr, FI, {}, IsIndirect, DL, O);
9720 }
9721 
9722 /// FrameIndex with dependencies
9723 SDDbgValue *SelectionDAG::getFrameIndexDbgValue(DIVariable *Var,
9724                                                 DIExpression *Expr, unsigned FI,
9725                                                 ArrayRef<SDNode *> Dependencies,
9726                                                 bool IsIndirect,
9727                                                 const DebugLoc &DL,
9728                                                 unsigned O) {
9729   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
9730          "Expected inlined-at fields to agree");
9731   return new (DbgInfo->getAlloc())
9732       SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromFrameIdx(FI),
9733                  Dependencies, IsIndirect, DL, O,
9734                  /*IsVariadic=*/false);
9735 }
9736 
9737 /// VReg
9738 SDDbgValue *SelectionDAG::getVRegDbgValue(DIVariable *Var, DIExpression *Expr,
9739                                           unsigned VReg, bool IsIndirect,
9740                                           const DebugLoc &DL, unsigned O) {
9741   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
9742          "Expected inlined-at fields to agree");
9743   return new (DbgInfo->getAlloc())
9744       SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromVReg(VReg),
9745                  {}, IsIndirect, DL, O,
9746                  /*IsVariadic=*/false);
9747 }
9748 
9749 SDDbgValue *SelectionDAG::getDbgValueList(DIVariable *Var, DIExpression *Expr,
9750                                           ArrayRef<SDDbgOperand> Locs,
9751                                           ArrayRef<SDNode *> Dependencies,
9752                                           bool IsIndirect, const DebugLoc &DL,
9753                                           unsigned O, bool IsVariadic) {
9754   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
9755          "Expected inlined-at fields to agree");
9756   return new (DbgInfo->getAlloc())
9757       SDDbgValue(DbgInfo->getAlloc(), Var, Expr, Locs, Dependencies, IsIndirect,
9758                  DL, O, IsVariadic);
9759 }
9760 
9761 void SelectionDAG::transferDbgValues(SDValue From, SDValue To,
9762                                      unsigned OffsetInBits, unsigned SizeInBits,
9763                                      bool InvalidateDbg) {
9764   SDNode *FromNode = From.getNode();
9765   SDNode *ToNode = To.getNode();
9766   assert(FromNode && ToNode && "Can't modify dbg values");
9767 
9768   // PR35338
9769   // TODO: assert(From != To && "Redundant dbg value transfer");
9770   // TODO: assert(FromNode != ToNode && "Intranode dbg value transfer");
9771   if (From == To || FromNode == ToNode)
9772     return;
9773 
9774   if (!FromNode->getHasDebugValue())
9775     return;
9776 
9777   SDDbgOperand FromLocOp =
9778       SDDbgOperand::fromNode(From.getNode(), From.getResNo());
9779   SDDbgOperand ToLocOp = SDDbgOperand::fromNode(To.getNode(), To.getResNo());
9780 
9781   SmallVector<SDDbgValue *, 2> ClonedDVs;
9782   for (SDDbgValue *Dbg : GetDbgValues(FromNode)) {
9783     if (Dbg->isInvalidated())
9784       continue;
9785 
9786     // TODO: assert(!Dbg->isInvalidated() && "Transfer of invalid dbg value");
9787 
9788     // Create a new location ops vector that is equal to the old vector, but
9789     // with each instance of FromLocOp replaced with ToLocOp.
9790     bool Changed = false;
9791     auto NewLocOps = Dbg->copyLocationOps();
9792     std::replace_if(
9793         NewLocOps.begin(), NewLocOps.end(),
9794         [&Changed, FromLocOp](const SDDbgOperand &Op) {
9795           bool Match = Op == FromLocOp;
9796           Changed |= Match;
9797           return Match;
9798         },
9799         ToLocOp);
9800     // Ignore this SDDbgValue if we didn't find a matching location.
9801     if (!Changed)
9802       continue;
9803 
9804     DIVariable *Var = Dbg->getVariable();
9805     auto *Expr = Dbg->getExpression();
9806     // If a fragment is requested, update the expression.
9807     if (SizeInBits) {
9808       // When splitting a larger (e.g., sign-extended) value whose
9809       // lower bits are described with an SDDbgValue, do not attempt
9810       // to transfer the SDDbgValue to the upper bits.
9811       if (auto FI = Expr->getFragmentInfo())
9812         if (OffsetInBits + SizeInBits > FI->SizeInBits)
9813           continue;
9814       auto Fragment = DIExpression::createFragmentExpression(Expr, OffsetInBits,
9815                                                              SizeInBits);
9816       if (!Fragment)
9817         continue;
9818       Expr = *Fragment;
9819     }
9820 
9821     auto AdditionalDependencies = Dbg->getAdditionalDependencies();
9822     // Clone the SDDbgValue and move it to To.
9823     SDDbgValue *Clone = getDbgValueList(
9824         Var, Expr, NewLocOps, AdditionalDependencies, Dbg->isIndirect(),
9825         Dbg->getDebugLoc(), std::max(ToNode->getIROrder(), Dbg->getOrder()),
9826         Dbg->isVariadic());
9827     ClonedDVs.push_back(Clone);
9828 
9829     if (InvalidateDbg) {
9830       // Invalidate value and indicate the SDDbgValue should not be emitted.
9831       Dbg->setIsInvalidated();
9832       Dbg->setIsEmitted();
9833     }
9834   }
9835 
9836   for (SDDbgValue *Dbg : ClonedDVs) {
9837     assert(is_contained(Dbg->getSDNodes(), ToNode) &&
9838            "Transferred DbgValues should depend on the new SDNode");
9839     AddDbgValue(Dbg, false);
9840   }
9841 }
9842 
9843 void SelectionDAG::salvageDebugInfo(SDNode &N) {
9844   if (!N.getHasDebugValue())
9845     return;
9846 
9847   SmallVector<SDDbgValue *, 2> ClonedDVs;
9848   for (auto DV : GetDbgValues(&N)) {
9849     if (DV->isInvalidated())
9850       continue;
9851     switch (N.getOpcode()) {
9852     default:
9853       break;
9854     case ISD::ADD:
9855       SDValue N0 = N.getOperand(0);
9856       SDValue N1 = N.getOperand(1);
9857       if (!isConstantIntBuildVectorOrConstantInt(N0) &&
9858           isConstantIntBuildVectorOrConstantInt(N1)) {
9859         uint64_t Offset = N.getConstantOperandVal(1);
9860 
9861         // Rewrite an ADD constant node into a DIExpression. Since we are
9862         // performing arithmetic to compute the variable's *value* in the
9863         // DIExpression, we need to mark the expression with a
9864         // DW_OP_stack_value.
9865         auto *DIExpr = DV->getExpression();
9866         auto NewLocOps = DV->copyLocationOps();
9867         bool Changed = false;
9868         for (size_t i = 0; i < NewLocOps.size(); ++i) {
9869           // We're not given a ResNo to compare against because the whole
9870           // node is going away. We know that any ISD::ADD only has one
9871           // result, so we can assume any node match is using the result.
9872           if (NewLocOps[i].getKind() != SDDbgOperand::SDNODE ||
9873               NewLocOps[i].getSDNode() != &N)
9874             continue;
9875           NewLocOps[i] = SDDbgOperand::fromNode(N0.getNode(), N0.getResNo());
9876           SmallVector<uint64_t, 3> ExprOps;
9877           DIExpression::appendOffset(ExprOps, Offset);
9878           DIExpr = DIExpression::appendOpsToArg(DIExpr, ExprOps, i, true);
9879           Changed = true;
9880         }
9881         (void)Changed;
9882         assert(Changed && "Salvage target doesn't use N");
9883 
9884         auto AdditionalDependencies = DV->getAdditionalDependencies();
9885         SDDbgValue *Clone = getDbgValueList(DV->getVariable(), DIExpr,
9886                                             NewLocOps, AdditionalDependencies,
9887                                             DV->isIndirect(), DV->getDebugLoc(),
9888                                             DV->getOrder(), DV->isVariadic());
9889         ClonedDVs.push_back(Clone);
9890         DV->setIsInvalidated();
9891         DV->setIsEmitted();
9892         LLVM_DEBUG(dbgs() << "SALVAGE: Rewriting";
9893                    N0.getNode()->dumprFull(this);
9894                    dbgs() << " into " << *DIExpr << '\n');
9895       }
9896     }
9897   }
9898 
9899   for (SDDbgValue *Dbg : ClonedDVs) {
9900     assert(!Dbg->getSDNodes().empty() &&
9901            "Salvaged DbgValue should depend on a new SDNode");
9902     AddDbgValue(Dbg, false);
9903   }
9904 }
9905 
9906 /// Creates a SDDbgLabel node.
9907 SDDbgLabel *SelectionDAG::getDbgLabel(DILabel *Label,
9908                                       const DebugLoc &DL, unsigned O) {
9909   assert(cast<DILabel>(Label)->isValidLocationForIntrinsic(DL) &&
9910          "Expected inlined-at fields to agree");
9911   return new (DbgInfo->getAlloc()) SDDbgLabel(Label, DL, O);
9912 }
9913 
9914 namespace {
9915 
9916 /// RAUWUpdateListener - Helper for ReplaceAllUsesWith - When the node
9917 /// pointed to by a use iterator is deleted, increment the use iterator
9918 /// so that it doesn't dangle.
9919 ///
9920 class RAUWUpdateListener : public SelectionDAG::DAGUpdateListener {
9921   SDNode::use_iterator &UI;
9922   SDNode::use_iterator &UE;
9923 
9924   void NodeDeleted(SDNode *N, SDNode *E) override {
9925     // Increment the iterator as needed.
9926     while (UI != UE && N == *UI)
9927       ++UI;
9928   }
9929 
9930 public:
9931   RAUWUpdateListener(SelectionDAG &d,
9932                      SDNode::use_iterator &ui,
9933                      SDNode::use_iterator &ue)
9934     : SelectionDAG::DAGUpdateListener(d), UI(ui), UE(ue) {}
9935 };
9936 
9937 } // end anonymous namespace
9938 
9939 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
9940 /// This can cause recursive merging of nodes in the DAG.
9941 ///
9942 /// This version assumes From has a single result value.
9943 ///
9944 void SelectionDAG::ReplaceAllUsesWith(SDValue FromN, SDValue To) {
9945   SDNode *From = FromN.getNode();
9946   assert(From->getNumValues() == 1 && FromN.getResNo() == 0 &&
9947          "Cannot replace with this method!");
9948   assert(From != To.getNode() && "Cannot replace uses of with self");
9949 
9950   // Preserve Debug Values
9951   transferDbgValues(FromN, To);
9952 
9953   // Iterate over all the existing uses of From. New uses will be added
9954   // to the beginning of the use list, which we avoid visiting.
9955   // This specifically avoids visiting uses of From that arise while the
9956   // replacement is happening, because any such uses would be the result
9957   // of CSE: If an existing node looks like From after one of its operands
9958   // is replaced by To, we don't want to replace of all its users with To
9959   // too. See PR3018 for more info.
9960   SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
9961   RAUWUpdateListener Listener(*this, UI, UE);
9962   while (UI != UE) {
9963     SDNode *User = *UI;
9964 
9965     // This node is about to morph, remove its old self from the CSE maps.
9966     RemoveNodeFromCSEMaps(User);
9967 
9968     // A user can appear in a use list multiple times, and when this
9969     // happens the uses are usually next to each other in the list.
9970     // To help reduce the number of CSE recomputations, process all
9971     // the uses of this user that we can find this way.
9972     do {
9973       SDUse &Use = UI.getUse();
9974       ++UI;
9975       Use.set(To);
9976       if (To->isDivergent() != From->isDivergent())
9977         updateDivergence(User);
9978     } while (UI != UE && *UI == User);
9979     // Now that we have modified User, add it back to the CSE maps.  If it
9980     // already exists there, recursively merge the results together.
9981     AddModifiedNodeToCSEMaps(User);
9982   }
9983 
9984   // If we just RAUW'd the root, take note.
9985   if (FromN == getRoot())
9986     setRoot(To);
9987 }
9988 
9989 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
9990 /// This can cause recursive merging of nodes in the DAG.
9991 ///
9992 /// This version assumes that for each value of From, there is a
9993 /// corresponding value in To in the same position with the same type.
9994 ///
9995 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, SDNode *To) {
9996 #ifndef NDEBUG
9997   for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
9998     assert((!From->hasAnyUseOfValue(i) ||
9999             From->getValueType(i) == To->getValueType(i)) &&
10000            "Cannot use this version of ReplaceAllUsesWith!");
10001 #endif
10002 
10003   // Handle the trivial case.
10004   if (From == To)
10005     return;
10006 
10007   // Preserve Debug Info. Only do this if there's a use.
10008   for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
10009     if (From->hasAnyUseOfValue(i)) {
10010       assert((i < To->getNumValues()) && "Invalid To location");
10011       transferDbgValues(SDValue(From, i), SDValue(To, i));
10012     }
10013 
10014   // Iterate over just the existing users of From. See the comments in
10015   // the ReplaceAllUsesWith above.
10016   SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
10017   RAUWUpdateListener Listener(*this, UI, UE);
10018   while (UI != UE) {
10019     SDNode *User = *UI;
10020 
10021     // This node is about to morph, remove its old self from the CSE maps.
10022     RemoveNodeFromCSEMaps(User);
10023 
10024     // A user can appear in a use list multiple times, and when this
10025     // happens the uses are usually next to each other in the list.
10026     // To help reduce the number of CSE recomputations, process all
10027     // the uses of this user that we can find this way.
10028     do {
10029       SDUse &Use = UI.getUse();
10030       ++UI;
10031       Use.setNode(To);
10032       if (To->isDivergent() != From->isDivergent())
10033         updateDivergence(User);
10034     } while (UI != UE && *UI == User);
10035 
10036     // Now that we have modified User, add it back to the CSE maps.  If it
10037     // already exists there, recursively merge the results together.
10038     AddModifiedNodeToCSEMaps(User);
10039   }
10040 
10041   // If we just RAUW'd the root, take note.
10042   if (From == getRoot().getNode())
10043     setRoot(SDValue(To, getRoot().getResNo()));
10044 }
10045 
10046 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
10047 /// This can cause recursive merging of nodes in the DAG.
10048 ///
10049 /// This version can replace From with any result values.  To must match the
10050 /// number and types of values returned by From.
10051 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, const SDValue *To) {
10052   if (From->getNumValues() == 1)  // Handle the simple case efficiently.
10053     return ReplaceAllUsesWith(SDValue(From, 0), To[0]);
10054 
10055   // Preserve Debug Info.
10056   for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
10057     transferDbgValues(SDValue(From, i), To[i]);
10058 
10059   // Iterate over just the existing users of From. See the comments in
10060   // the ReplaceAllUsesWith above.
10061   SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
10062   RAUWUpdateListener Listener(*this, UI, UE);
10063   while (UI != UE) {
10064     SDNode *User = *UI;
10065 
10066     // This node is about to morph, remove its old self from the CSE maps.
10067     RemoveNodeFromCSEMaps(User);
10068 
10069     // A user can appear in a use list multiple times, and when this happens the
10070     // uses are usually next to each other in the list.  To help reduce the
10071     // number of CSE and divergence recomputations, process all the uses of this
10072     // user that we can find this way.
10073     bool To_IsDivergent = false;
10074     do {
10075       SDUse &Use = UI.getUse();
10076       const SDValue &ToOp = To[Use.getResNo()];
10077       ++UI;
10078       Use.set(ToOp);
10079       To_IsDivergent |= ToOp->isDivergent();
10080     } while (UI != UE && *UI == User);
10081 
10082     if (To_IsDivergent != From->isDivergent())
10083       updateDivergence(User);
10084 
10085     // Now that we have modified User, add it back to the CSE maps.  If it
10086     // already exists there, recursively merge the results together.
10087     AddModifiedNodeToCSEMaps(User);
10088   }
10089 
10090   // If we just RAUW'd the root, take note.
10091   if (From == getRoot().getNode())
10092     setRoot(SDValue(To[getRoot().getResNo()]));
10093 }
10094 
10095 /// ReplaceAllUsesOfValueWith - Replace any uses of From with To, leaving
10096 /// uses of other values produced by From.getNode() alone.  The Deleted
10097 /// vector is handled the same way as for ReplaceAllUsesWith.
10098 void SelectionDAG::ReplaceAllUsesOfValueWith(SDValue From, SDValue To){
10099   // Handle the really simple, really trivial case efficiently.
10100   if (From == To) return;
10101 
10102   // Handle the simple, trivial, case efficiently.
10103   if (From.getNode()->getNumValues() == 1) {
10104     ReplaceAllUsesWith(From, To);
10105     return;
10106   }
10107 
10108   // Preserve Debug Info.
10109   transferDbgValues(From, To);
10110 
10111   // Iterate over just the existing users of From. See the comments in
10112   // the ReplaceAllUsesWith above.
10113   SDNode::use_iterator UI = From.getNode()->use_begin(),
10114                        UE = From.getNode()->use_end();
10115   RAUWUpdateListener Listener(*this, UI, UE);
10116   while (UI != UE) {
10117     SDNode *User = *UI;
10118     bool UserRemovedFromCSEMaps = false;
10119 
10120     // A user can appear in a use list multiple times, and when this
10121     // happens the uses are usually next to each other in the list.
10122     // To help reduce the number of CSE recomputations, process all
10123     // the uses of this user that we can find this way.
10124     do {
10125       SDUse &Use = UI.getUse();
10126 
10127       // Skip uses of different values from the same node.
10128       if (Use.getResNo() != From.getResNo()) {
10129         ++UI;
10130         continue;
10131       }
10132 
10133       // If this node hasn't been modified yet, it's still in the CSE maps,
10134       // so remove its old self from the CSE maps.
10135       if (!UserRemovedFromCSEMaps) {
10136         RemoveNodeFromCSEMaps(User);
10137         UserRemovedFromCSEMaps = true;
10138       }
10139 
10140       ++UI;
10141       Use.set(To);
10142       if (To->isDivergent() != From->isDivergent())
10143         updateDivergence(User);
10144     } while (UI != UE && *UI == User);
10145     // We are iterating over all uses of the From node, so if a use
10146     // doesn't use the specific value, no changes are made.
10147     if (!UserRemovedFromCSEMaps)
10148       continue;
10149 
10150     // Now that we have modified User, add it back to the CSE maps.  If it
10151     // already exists there, recursively merge the results together.
10152     AddModifiedNodeToCSEMaps(User);
10153   }
10154 
10155   // If we just RAUW'd the root, take note.
10156   if (From == getRoot())
10157     setRoot(To);
10158 }
10159 
10160 namespace {
10161 
10162 /// UseMemo - This class is used by SelectionDAG::ReplaceAllUsesOfValuesWith
10163 /// to record information about a use.
10164 struct UseMemo {
10165   SDNode *User;
10166   unsigned Index;
10167   SDUse *Use;
10168 };
10169 
10170 /// operator< - Sort Memos by User.
10171 bool operator<(const UseMemo &L, const UseMemo &R) {
10172   return (intptr_t)L.User < (intptr_t)R.User;
10173 }
10174 
10175 /// RAUOVWUpdateListener - Helper for ReplaceAllUsesOfValuesWith - When the node
10176 /// pointed to by a UseMemo is deleted, set the User to nullptr to indicate that
10177 /// the node already has been taken care of recursively.
10178 class RAUOVWUpdateListener : public SelectionDAG::DAGUpdateListener {
10179   SmallVector<UseMemo, 4> &Uses;
10180 
10181   void NodeDeleted(SDNode *N, SDNode *E) override {
10182     for (UseMemo &Memo : Uses)
10183       if (Memo.User == N)
10184         Memo.User = nullptr;
10185   }
10186 
10187 public:
10188   RAUOVWUpdateListener(SelectionDAG &d, SmallVector<UseMemo, 4> &uses)
10189       : SelectionDAG::DAGUpdateListener(d), Uses(uses) {}
10190 };
10191 
10192 } // end anonymous namespace
10193 
10194 bool SelectionDAG::calculateDivergence(SDNode *N) {
10195   if (TLI->isSDNodeAlwaysUniform(N)) {
10196     assert(!TLI->isSDNodeSourceOfDivergence(N, FLI, DA) &&
10197            "Conflicting divergence information!");
10198     return false;
10199   }
10200   if (TLI->isSDNodeSourceOfDivergence(N, FLI, DA))
10201     return true;
10202   for (auto &Op : N->ops()) {
10203     if (Op.Val.getValueType() != MVT::Other && Op.getNode()->isDivergent())
10204       return true;
10205   }
10206   return false;
10207 }
10208 
10209 void SelectionDAG::updateDivergence(SDNode *N) {
10210   SmallVector<SDNode *, 16> Worklist(1, N);
10211   do {
10212     N = Worklist.pop_back_val();
10213     bool IsDivergent = calculateDivergence(N);
10214     if (N->SDNodeBits.IsDivergent != IsDivergent) {
10215       N->SDNodeBits.IsDivergent = IsDivergent;
10216       llvm::append_range(Worklist, N->uses());
10217     }
10218   } while (!Worklist.empty());
10219 }
10220 
10221 void SelectionDAG::CreateTopologicalOrder(std::vector<SDNode *> &Order) {
10222   DenseMap<SDNode *, unsigned> Degree;
10223   Order.reserve(AllNodes.size());
10224   for (auto &N : allnodes()) {
10225     unsigned NOps = N.getNumOperands();
10226     Degree[&N] = NOps;
10227     if (0 == NOps)
10228       Order.push_back(&N);
10229   }
10230   for (size_t I = 0; I != Order.size(); ++I) {
10231     SDNode *N = Order[I];
10232     for (auto U : N->uses()) {
10233       unsigned &UnsortedOps = Degree[U];
10234       if (0 == --UnsortedOps)
10235         Order.push_back(U);
10236     }
10237   }
10238 }
10239 
10240 #ifndef NDEBUG
10241 void SelectionDAG::VerifyDAGDivergence() {
10242   std::vector<SDNode *> TopoOrder;
10243   CreateTopologicalOrder(TopoOrder);
10244   for (auto *N : TopoOrder) {
10245     assert(calculateDivergence(N) == N->isDivergent() &&
10246            "Divergence bit inconsistency detected");
10247   }
10248 }
10249 #endif
10250 
10251 /// ReplaceAllUsesOfValuesWith - Replace any uses of From with To, leaving
10252 /// uses of other values produced by From.getNode() alone.  The same value
10253 /// may appear in both the From and To list.  The Deleted vector is
10254 /// handled the same way as for ReplaceAllUsesWith.
10255 void SelectionDAG::ReplaceAllUsesOfValuesWith(const SDValue *From,
10256                                               const SDValue *To,
10257                                               unsigned Num){
10258   // Handle the simple, trivial case efficiently.
10259   if (Num == 1)
10260     return ReplaceAllUsesOfValueWith(*From, *To);
10261 
10262   transferDbgValues(*From, *To);
10263 
10264   // Read up all the uses and make records of them. This helps
10265   // processing new uses that are introduced during the
10266   // replacement process.
10267   SmallVector<UseMemo, 4> Uses;
10268   for (unsigned i = 0; i != Num; ++i) {
10269     unsigned FromResNo = From[i].getResNo();
10270     SDNode *FromNode = From[i].getNode();
10271     for (SDNode::use_iterator UI = FromNode->use_begin(),
10272          E = FromNode->use_end(); UI != E; ++UI) {
10273       SDUse &Use = UI.getUse();
10274       if (Use.getResNo() == FromResNo) {
10275         UseMemo Memo = { *UI, i, &Use };
10276         Uses.push_back(Memo);
10277       }
10278     }
10279   }
10280 
10281   // Sort the uses, so that all the uses from a given User are together.
10282   llvm::sort(Uses);
10283   RAUOVWUpdateListener Listener(*this, Uses);
10284 
10285   for (unsigned UseIndex = 0, UseIndexEnd = Uses.size();
10286        UseIndex != UseIndexEnd; ) {
10287     // We know that this user uses some value of From.  If it is the right
10288     // value, update it.
10289     SDNode *User = Uses[UseIndex].User;
10290     // If the node has been deleted by recursive CSE updates when updating
10291     // another node, then just skip this entry.
10292     if (User == nullptr) {
10293       ++UseIndex;
10294       continue;
10295     }
10296 
10297     // This node is about to morph, remove its old self from the CSE maps.
10298     RemoveNodeFromCSEMaps(User);
10299 
10300     // The Uses array is sorted, so all the uses for a given User
10301     // are next to each other in the list.
10302     // To help reduce the number of CSE recomputations, process all
10303     // the uses of this user that we can find this way.
10304     do {
10305       unsigned i = Uses[UseIndex].Index;
10306       SDUse &Use = *Uses[UseIndex].Use;
10307       ++UseIndex;
10308 
10309       Use.set(To[i]);
10310     } while (UseIndex != UseIndexEnd && Uses[UseIndex].User == User);
10311 
10312     // Now that we have modified User, add it back to the CSE maps.  If it
10313     // already exists there, recursively merge the results together.
10314     AddModifiedNodeToCSEMaps(User);
10315   }
10316 }
10317 
10318 /// AssignTopologicalOrder - Assign a unique node id for each node in the DAG
10319 /// based on their topological order. It returns the maximum id and a vector
10320 /// of the SDNodes* in assigned order by reference.
10321 unsigned SelectionDAG::AssignTopologicalOrder() {
10322   unsigned DAGSize = 0;
10323 
10324   // SortedPos tracks the progress of the algorithm. Nodes before it are
10325   // sorted, nodes after it are unsorted. When the algorithm completes
10326   // it is at the end of the list.
10327   allnodes_iterator SortedPos = allnodes_begin();
10328 
10329   // Visit all the nodes. Move nodes with no operands to the front of
10330   // the list immediately. Annotate nodes that do have operands with their
10331   // operand count. Before we do this, the Node Id fields of the nodes
10332   // may contain arbitrary values. After, the Node Id fields for nodes
10333   // before SortedPos will contain the topological sort index, and the
10334   // Node Id fields for nodes At SortedPos and after will contain the
10335   // count of outstanding operands.
10336   for (SDNode &N : llvm::make_early_inc_range(allnodes())) {
10337     checkForCycles(&N, this);
10338     unsigned Degree = N.getNumOperands();
10339     if (Degree == 0) {
10340       // A node with no uses, add it to the result array immediately.
10341       N.setNodeId(DAGSize++);
10342       allnodes_iterator Q(&N);
10343       if (Q != SortedPos)
10344         SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(Q));
10345       assert(SortedPos != AllNodes.end() && "Overran node list");
10346       ++SortedPos;
10347     } else {
10348       // Temporarily use the Node Id as scratch space for the degree count.
10349       N.setNodeId(Degree);
10350     }
10351   }
10352 
10353   // Visit all the nodes. As we iterate, move nodes into sorted order,
10354   // such that by the time the end is reached all nodes will be sorted.
10355   for (SDNode &Node : allnodes()) {
10356     SDNode *N = &Node;
10357     checkForCycles(N, this);
10358     // N is in sorted position, so all its uses have one less operand
10359     // that needs to be sorted.
10360     for (SDNode *P : N->uses()) {
10361       unsigned Degree = P->getNodeId();
10362       assert(Degree != 0 && "Invalid node degree");
10363       --Degree;
10364       if (Degree == 0) {
10365         // All of P's operands are sorted, so P may sorted now.
10366         P->setNodeId(DAGSize++);
10367         if (P->getIterator() != SortedPos)
10368           SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(P));
10369         assert(SortedPos != AllNodes.end() && "Overran node list");
10370         ++SortedPos;
10371       } else {
10372         // Update P's outstanding operand count.
10373         P->setNodeId(Degree);
10374       }
10375     }
10376     if (Node.getIterator() == SortedPos) {
10377 #ifndef NDEBUG
10378       allnodes_iterator I(N);
10379       SDNode *S = &*++I;
10380       dbgs() << "Overran sorted position:\n";
10381       S->dumprFull(this); dbgs() << "\n";
10382       dbgs() << "Checking if this is due to cycles\n";
10383       checkForCycles(this, true);
10384 #endif
10385       llvm_unreachable(nullptr);
10386     }
10387   }
10388 
10389   assert(SortedPos == AllNodes.end() &&
10390          "Topological sort incomplete!");
10391   assert(AllNodes.front().getOpcode() == ISD::EntryToken &&
10392          "First node in topological sort is not the entry token!");
10393   assert(AllNodes.front().getNodeId() == 0 &&
10394          "First node in topological sort has non-zero id!");
10395   assert(AllNodes.front().getNumOperands() == 0 &&
10396          "First node in topological sort has operands!");
10397   assert(AllNodes.back().getNodeId() == (int)DAGSize-1 &&
10398          "Last node in topologic sort has unexpected id!");
10399   assert(AllNodes.back().use_empty() &&
10400          "Last node in topologic sort has users!");
10401   assert(DAGSize == allnodes_size() && "Node count mismatch!");
10402   return DAGSize;
10403 }
10404 
10405 /// AddDbgValue - Add a dbg_value SDNode. If SD is non-null that means the
10406 /// value is produced by SD.
10407 void SelectionDAG::AddDbgValue(SDDbgValue *DB, bool isParameter) {
10408   for (SDNode *SD : DB->getSDNodes()) {
10409     if (!SD)
10410       continue;
10411     assert(DbgInfo->getSDDbgValues(SD).empty() || SD->getHasDebugValue());
10412     SD->setHasDebugValue(true);
10413   }
10414   DbgInfo->add(DB, isParameter);
10415 }
10416 
10417 void SelectionDAG::AddDbgLabel(SDDbgLabel *DB) { DbgInfo->add(DB); }
10418 
10419 SDValue SelectionDAG::makeEquivalentMemoryOrdering(SDValue OldChain,
10420                                                    SDValue NewMemOpChain) {
10421   assert(isa<MemSDNode>(NewMemOpChain) && "Expected a memop node");
10422   assert(NewMemOpChain.getValueType() == MVT::Other && "Expected a token VT");
10423   // The new memory operation must have the same position as the old load in
10424   // terms of memory dependency. Create a TokenFactor for the old load and new
10425   // memory operation and update uses of the old load's output chain to use that
10426   // TokenFactor.
10427   if (OldChain == NewMemOpChain || OldChain.use_empty())
10428     return NewMemOpChain;
10429 
10430   SDValue TokenFactor = getNode(ISD::TokenFactor, SDLoc(OldChain), MVT::Other,
10431                                 OldChain, NewMemOpChain);
10432   ReplaceAllUsesOfValueWith(OldChain, TokenFactor);
10433   UpdateNodeOperands(TokenFactor.getNode(), OldChain, NewMemOpChain);
10434   return TokenFactor;
10435 }
10436 
10437 SDValue SelectionDAG::makeEquivalentMemoryOrdering(LoadSDNode *OldLoad,
10438                                                    SDValue NewMemOp) {
10439   assert(isa<MemSDNode>(NewMemOp.getNode()) && "Expected a memop node");
10440   SDValue OldChain = SDValue(OldLoad, 1);
10441   SDValue NewMemOpChain = NewMemOp.getValue(1);
10442   return makeEquivalentMemoryOrdering(OldChain, NewMemOpChain);
10443 }
10444 
10445 SDValue SelectionDAG::getSymbolFunctionGlobalAddress(SDValue Op,
10446                                                      Function **OutFunction) {
10447   assert(isa<ExternalSymbolSDNode>(Op) && "Node should be an ExternalSymbol");
10448 
10449   auto *Symbol = cast<ExternalSymbolSDNode>(Op)->getSymbol();
10450   auto *Module = MF->getFunction().getParent();
10451   auto *Function = Module->getFunction(Symbol);
10452 
10453   if (OutFunction != nullptr)
10454       *OutFunction = Function;
10455 
10456   if (Function != nullptr) {
10457     auto PtrTy = TLI->getPointerTy(getDataLayout(), Function->getAddressSpace());
10458     return getGlobalAddress(Function, SDLoc(Op), PtrTy);
10459   }
10460 
10461   std::string ErrorStr;
10462   raw_string_ostream ErrorFormatter(ErrorStr);
10463   ErrorFormatter << "Undefined external symbol ";
10464   ErrorFormatter << '"' << Symbol << '"';
10465   report_fatal_error(Twine(ErrorFormatter.str()));
10466 }
10467 
10468 //===----------------------------------------------------------------------===//
10469 //                              SDNode Class
10470 //===----------------------------------------------------------------------===//
10471 
10472 bool llvm::isNullConstant(SDValue V) {
10473   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
10474   return Const != nullptr && Const->isZero();
10475 }
10476 
10477 bool llvm::isNullFPConstant(SDValue V) {
10478   ConstantFPSDNode *Const = dyn_cast<ConstantFPSDNode>(V);
10479   return Const != nullptr && Const->isZero() && !Const->isNegative();
10480 }
10481 
10482 bool llvm::isAllOnesConstant(SDValue V) {
10483   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
10484   return Const != nullptr && Const->isAllOnes();
10485 }
10486 
10487 bool llvm::isOneConstant(SDValue V) {
10488   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
10489   return Const != nullptr && Const->isOne();
10490 }
10491 
10492 bool llvm::isMinSignedConstant(SDValue V) {
10493   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
10494   return Const != nullptr && Const->isMinSignedValue();
10495 }
10496 
10497 SDValue llvm::peekThroughBitcasts(SDValue V) {
10498   while (V.getOpcode() == ISD::BITCAST)
10499     V = V.getOperand(0);
10500   return V;
10501 }
10502 
10503 SDValue llvm::peekThroughOneUseBitcasts(SDValue V) {
10504   while (V.getOpcode() == ISD::BITCAST && V.getOperand(0).hasOneUse())
10505     V = V.getOperand(0);
10506   return V;
10507 }
10508 
10509 SDValue llvm::peekThroughExtractSubvectors(SDValue V) {
10510   while (V.getOpcode() == ISD::EXTRACT_SUBVECTOR)
10511     V = V.getOperand(0);
10512   return V;
10513 }
10514 
10515 bool llvm::isBitwiseNot(SDValue V, bool AllowUndefs) {
10516   if (V.getOpcode() != ISD::XOR)
10517     return false;
10518   V = peekThroughBitcasts(V.getOperand(1));
10519   unsigned NumBits = V.getScalarValueSizeInBits();
10520   ConstantSDNode *C =
10521       isConstOrConstSplat(V, AllowUndefs, /*AllowTruncation*/ true);
10522   return C && (C->getAPIntValue().countTrailingOnes() >= NumBits);
10523 }
10524 
10525 ConstantSDNode *llvm::isConstOrConstSplat(SDValue N, bool AllowUndefs,
10526                                           bool AllowTruncation) {
10527   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
10528     return CN;
10529 
10530   // SplatVectors can truncate their operands. Ignore that case here unless
10531   // AllowTruncation is set.
10532   if (N->getOpcode() == ISD::SPLAT_VECTOR) {
10533     EVT VecEltVT = N->getValueType(0).getVectorElementType();
10534     if (auto *CN = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
10535       EVT CVT = CN->getValueType(0);
10536       assert(CVT.bitsGE(VecEltVT) && "Illegal splat_vector element extension");
10537       if (AllowTruncation || CVT == VecEltVT)
10538         return CN;
10539     }
10540   }
10541 
10542   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
10543     BitVector UndefElements;
10544     ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
10545 
10546     // BuildVectors can truncate their operands. Ignore that case here unless
10547     // AllowTruncation is set.
10548     if (CN && (UndefElements.none() || AllowUndefs)) {
10549       EVT CVT = CN->getValueType(0);
10550       EVT NSVT = N.getValueType().getScalarType();
10551       assert(CVT.bitsGE(NSVT) && "Illegal build vector element extension");
10552       if (AllowTruncation || (CVT == NSVT))
10553         return CN;
10554     }
10555   }
10556 
10557   return nullptr;
10558 }
10559 
10560 ConstantSDNode *llvm::isConstOrConstSplat(SDValue N, const APInt &DemandedElts,
10561                                           bool AllowUndefs,
10562                                           bool AllowTruncation) {
10563   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
10564     return CN;
10565 
10566   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
10567     BitVector UndefElements;
10568     ConstantSDNode *CN = BV->getConstantSplatNode(DemandedElts, &UndefElements);
10569 
10570     // BuildVectors can truncate their operands. Ignore that case here unless
10571     // AllowTruncation is set.
10572     if (CN && (UndefElements.none() || AllowUndefs)) {
10573       EVT CVT = CN->getValueType(0);
10574       EVT NSVT = N.getValueType().getScalarType();
10575       assert(CVT.bitsGE(NSVT) && "Illegal build vector element extension");
10576       if (AllowTruncation || (CVT == NSVT))
10577         return CN;
10578     }
10579   }
10580 
10581   return nullptr;
10582 }
10583 
10584 ConstantFPSDNode *llvm::isConstOrConstSplatFP(SDValue N, bool AllowUndefs) {
10585   if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
10586     return CN;
10587 
10588   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
10589     BitVector UndefElements;
10590     ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements);
10591     if (CN && (UndefElements.none() || AllowUndefs))
10592       return CN;
10593   }
10594 
10595   if (N.getOpcode() == ISD::SPLAT_VECTOR)
10596     if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N.getOperand(0)))
10597       return CN;
10598 
10599   return nullptr;
10600 }
10601 
10602 ConstantFPSDNode *llvm::isConstOrConstSplatFP(SDValue N,
10603                                               const APInt &DemandedElts,
10604                                               bool AllowUndefs) {
10605   if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
10606     return CN;
10607 
10608   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
10609     BitVector UndefElements;
10610     ConstantFPSDNode *CN =
10611         BV->getConstantFPSplatNode(DemandedElts, &UndefElements);
10612     if (CN && (UndefElements.none() || AllowUndefs))
10613       return CN;
10614   }
10615 
10616   return nullptr;
10617 }
10618 
10619 bool llvm::isNullOrNullSplat(SDValue N, bool AllowUndefs) {
10620   // TODO: may want to use peekThroughBitcast() here.
10621   ConstantSDNode *C =
10622       isConstOrConstSplat(N, AllowUndefs, /*AllowTruncation=*/true);
10623   return C && C->isZero();
10624 }
10625 
10626 bool llvm::isOneOrOneSplat(SDValue N, bool AllowUndefs) {
10627   // TODO: may want to use peekThroughBitcast() here.
10628   unsigned BitWidth = N.getScalarValueSizeInBits();
10629   ConstantSDNode *C = isConstOrConstSplat(N, AllowUndefs);
10630   return C && C->isOne() && C->getValueSizeInBits(0) == BitWidth;
10631 }
10632 
10633 bool llvm::isAllOnesOrAllOnesSplat(SDValue N, bool AllowUndefs) {
10634   N = peekThroughBitcasts(N);
10635   unsigned BitWidth = N.getScalarValueSizeInBits();
10636   ConstantSDNode *C = isConstOrConstSplat(N, AllowUndefs);
10637   return C && C->isAllOnes() && C->getValueSizeInBits(0) == BitWidth;
10638 }
10639 
10640 HandleSDNode::~HandleSDNode() {
10641   DropOperands();
10642 }
10643 
10644 GlobalAddressSDNode::GlobalAddressSDNode(unsigned Opc, unsigned Order,
10645                                          const DebugLoc &DL,
10646                                          const GlobalValue *GA, EVT VT,
10647                                          int64_t o, unsigned TF)
10648     : SDNode(Opc, Order, DL, getSDVTList(VT)), Offset(o), TargetFlags(TF) {
10649   TheGlobal = GA;
10650 }
10651 
10652 AddrSpaceCastSDNode::AddrSpaceCastSDNode(unsigned Order, const DebugLoc &dl,
10653                                          EVT VT, unsigned SrcAS,
10654                                          unsigned DestAS)
10655     : SDNode(ISD::ADDRSPACECAST, Order, dl, getSDVTList(VT)),
10656       SrcAddrSpace(SrcAS), DestAddrSpace(DestAS) {}
10657 
10658 MemSDNode::MemSDNode(unsigned Opc, unsigned Order, const DebugLoc &dl,
10659                      SDVTList VTs, EVT memvt, MachineMemOperand *mmo)
10660     : SDNode(Opc, Order, dl, VTs), MemoryVT(memvt), MMO(mmo) {
10661   MemSDNodeBits.IsVolatile = MMO->isVolatile();
10662   MemSDNodeBits.IsNonTemporal = MMO->isNonTemporal();
10663   MemSDNodeBits.IsDereferenceable = MMO->isDereferenceable();
10664   MemSDNodeBits.IsInvariant = MMO->isInvariant();
10665 
10666   // We check here that the size of the memory operand fits within the size of
10667   // the MMO. This is because the MMO might indicate only a possible address
10668   // range instead of specifying the affected memory addresses precisely.
10669   // TODO: Make MachineMemOperands aware of scalable vectors.
10670   assert(memvt.getStoreSize().getKnownMinSize() <= MMO->getSize() &&
10671          "Size mismatch!");
10672 }
10673 
10674 /// Profile - Gather unique data for the node.
10675 ///
10676 void SDNode::Profile(FoldingSetNodeID &ID) const {
10677   AddNodeIDNode(ID, this);
10678 }
10679 
10680 namespace {
10681 
10682   struct EVTArray {
10683     std::vector<EVT> VTs;
10684 
10685     EVTArray() {
10686       VTs.reserve(MVT::VALUETYPE_SIZE);
10687       for (unsigned i = 0; i < MVT::VALUETYPE_SIZE; ++i)
10688         VTs.push_back(MVT((MVT::SimpleValueType)i));
10689     }
10690   };
10691 
10692 } // end anonymous namespace
10693 
10694 static ManagedStatic<std::set<EVT, EVT::compareRawBits>> EVTs;
10695 static ManagedStatic<EVTArray> SimpleVTArray;
10696 static ManagedStatic<sys::SmartMutex<true>> VTMutex;
10697 
10698 /// getValueTypeList - Return a pointer to the specified value type.
10699 ///
10700 const EVT *SDNode::getValueTypeList(EVT VT) {
10701   if (VT.isExtended()) {
10702     sys::SmartScopedLock<true> Lock(*VTMutex);
10703     return &(*EVTs->insert(VT).first);
10704   }
10705   assert(VT.getSimpleVT() < MVT::VALUETYPE_SIZE && "Value type out of range!");
10706   return &SimpleVTArray->VTs[VT.getSimpleVT().SimpleTy];
10707 }
10708 
10709 /// hasNUsesOfValue - Return true if there are exactly NUSES uses of the
10710 /// indicated value.  This method ignores uses of other values defined by this
10711 /// operation.
10712 bool SDNode::hasNUsesOfValue(unsigned NUses, unsigned Value) const {
10713   assert(Value < getNumValues() && "Bad value!");
10714 
10715   // TODO: Only iterate over uses of a given value of the node
10716   for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) {
10717     if (UI.getUse().getResNo() == Value) {
10718       if (NUses == 0)
10719         return false;
10720       --NUses;
10721     }
10722   }
10723 
10724   // Found exactly the right number of uses?
10725   return NUses == 0;
10726 }
10727 
10728 /// hasAnyUseOfValue - Return true if there are any use of the indicated
10729 /// value. This method ignores uses of other values defined by this operation.
10730 bool SDNode::hasAnyUseOfValue(unsigned Value) const {
10731   assert(Value < getNumValues() && "Bad value!");
10732 
10733   for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI)
10734     if (UI.getUse().getResNo() == Value)
10735       return true;
10736 
10737   return false;
10738 }
10739 
10740 /// isOnlyUserOf - Return true if this node is the only use of N.
10741 bool SDNode::isOnlyUserOf(const SDNode *N) const {
10742   bool Seen = false;
10743   for (const SDNode *User : N->uses()) {
10744     if (User == this)
10745       Seen = true;
10746     else
10747       return false;
10748   }
10749 
10750   return Seen;
10751 }
10752 
10753 /// Return true if the only users of N are contained in Nodes.
10754 bool SDNode::areOnlyUsersOf(ArrayRef<const SDNode *> Nodes, const SDNode *N) {
10755   bool Seen = false;
10756   for (const SDNode *User : N->uses()) {
10757     if (llvm::is_contained(Nodes, User))
10758       Seen = true;
10759     else
10760       return false;
10761   }
10762 
10763   return Seen;
10764 }
10765 
10766 /// isOperand - Return true if this node is an operand of N.
10767 bool SDValue::isOperandOf(const SDNode *N) const {
10768   return is_contained(N->op_values(), *this);
10769 }
10770 
10771 bool SDNode::isOperandOf(const SDNode *N) const {
10772   return any_of(N->op_values(),
10773                 [this](SDValue Op) { return this == Op.getNode(); });
10774 }
10775 
10776 /// reachesChainWithoutSideEffects - Return true if this operand (which must
10777 /// be a chain) reaches the specified operand without crossing any
10778 /// side-effecting instructions on any chain path.  In practice, this looks
10779 /// through token factors and non-volatile loads.  In order to remain efficient,
10780 /// this only looks a couple of nodes in, it does not do an exhaustive search.
10781 ///
10782 /// Note that we only need to examine chains when we're searching for
10783 /// side-effects; SelectionDAG requires that all side-effects are represented
10784 /// by chains, even if another operand would force a specific ordering. This
10785 /// constraint is necessary to allow transformations like splitting loads.
10786 bool SDValue::reachesChainWithoutSideEffects(SDValue Dest,
10787                                              unsigned Depth) const {
10788   if (*this == Dest) return true;
10789 
10790   // Don't search too deeply, we just want to be able to see through
10791   // TokenFactor's etc.
10792   if (Depth == 0) return false;
10793 
10794   // If this is a token factor, all inputs to the TF happen in parallel.
10795   if (getOpcode() == ISD::TokenFactor) {
10796     // First, try a shallow search.
10797     if (is_contained((*this)->ops(), Dest)) {
10798       // We found the chain we want as an operand of this TokenFactor.
10799       // Essentially, we reach the chain without side-effects if we could
10800       // serialize the TokenFactor into a simple chain of operations with
10801       // Dest as the last operation. This is automatically true if the
10802       // chain has one use: there are no other ordering constraints.
10803       // If the chain has more than one use, we give up: some other
10804       // use of Dest might force a side-effect between Dest and the current
10805       // node.
10806       if (Dest.hasOneUse())
10807         return true;
10808     }
10809     // Next, try a deep search: check whether every operand of the TokenFactor
10810     // reaches Dest.
10811     return llvm::all_of((*this)->ops(), [=](SDValue Op) {
10812       return Op.reachesChainWithoutSideEffects(Dest, Depth - 1);
10813     });
10814   }
10815 
10816   // Loads don't have side effects, look through them.
10817   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(*this)) {
10818     if (Ld->isUnordered())
10819       return Ld->getChain().reachesChainWithoutSideEffects(Dest, Depth-1);
10820   }
10821   return false;
10822 }
10823 
10824 bool SDNode::hasPredecessor(const SDNode *N) const {
10825   SmallPtrSet<const SDNode *, 32> Visited;
10826   SmallVector<const SDNode *, 16> Worklist;
10827   Worklist.push_back(this);
10828   return hasPredecessorHelper(N, Visited, Worklist);
10829 }
10830 
10831 void SDNode::intersectFlagsWith(const SDNodeFlags Flags) {
10832   this->Flags.intersectWith(Flags);
10833 }
10834 
10835 SDValue
10836 SelectionDAG::matchBinOpReduction(SDNode *Extract, ISD::NodeType &BinOp,
10837                                   ArrayRef<ISD::NodeType> CandidateBinOps,
10838                                   bool AllowPartials) {
10839   // The pattern must end in an extract from index 0.
10840   if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10841       !isNullConstant(Extract->getOperand(1)))
10842     return SDValue();
10843 
10844   // Match against one of the candidate binary ops.
10845   SDValue Op = Extract->getOperand(0);
10846   if (llvm::none_of(CandidateBinOps, [Op](ISD::NodeType BinOp) {
10847         return Op.getOpcode() == unsigned(BinOp);
10848       }))
10849     return SDValue();
10850 
10851   // Floating-point reductions may require relaxed constraints on the final step
10852   // of the reduction because they may reorder intermediate operations.
10853   unsigned CandidateBinOp = Op.getOpcode();
10854   if (Op.getValueType().isFloatingPoint()) {
10855     SDNodeFlags Flags = Op->getFlags();
10856     switch (CandidateBinOp) {
10857     case ISD::FADD:
10858       if (!Flags.hasNoSignedZeros() || !Flags.hasAllowReassociation())
10859         return SDValue();
10860       break;
10861     default:
10862       llvm_unreachable("Unhandled FP opcode for binop reduction");
10863     }
10864   }
10865 
10866   // Matching failed - attempt to see if we did enough stages that a partial
10867   // reduction from a subvector is possible.
10868   auto PartialReduction = [&](SDValue Op, unsigned NumSubElts) {
10869     if (!AllowPartials || !Op)
10870       return SDValue();
10871     EVT OpVT = Op.getValueType();
10872     EVT OpSVT = OpVT.getScalarType();
10873     EVT SubVT = EVT::getVectorVT(*getContext(), OpSVT, NumSubElts);
10874     if (!TLI->isExtractSubvectorCheap(SubVT, OpVT, 0))
10875       return SDValue();
10876     BinOp = (ISD::NodeType)CandidateBinOp;
10877     return getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(Op), SubVT, Op,
10878                    getVectorIdxConstant(0, SDLoc(Op)));
10879   };
10880 
10881   // At each stage, we're looking for something that looks like:
10882   // %s = shufflevector <8 x i32> %op, <8 x i32> undef,
10883   //                    <8 x i32> <i32 2, i32 3, i32 undef, i32 undef,
10884   //                               i32 undef, i32 undef, i32 undef, i32 undef>
10885   // %a = binop <8 x i32> %op, %s
10886   // Where the mask changes according to the stage. E.g. for a 3-stage pyramid,
10887   // we expect something like:
10888   // <4,5,6,7,u,u,u,u>
10889   // <2,3,u,u,u,u,u,u>
10890   // <1,u,u,u,u,u,u,u>
10891   // While a partial reduction match would be:
10892   // <2,3,u,u,u,u,u,u>
10893   // <1,u,u,u,u,u,u,u>
10894   unsigned Stages = Log2_32(Op.getValueType().getVectorNumElements());
10895   SDValue PrevOp;
10896   for (unsigned i = 0; i < Stages; ++i) {
10897     unsigned MaskEnd = (1 << i);
10898 
10899     if (Op.getOpcode() != CandidateBinOp)
10900       return PartialReduction(PrevOp, MaskEnd);
10901 
10902     SDValue Op0 = Op.getOperand(0);
10903     SDValue Op1 = Op.getOperand(1);
10904 
10905     ShuffleVectorSDNode *Shuffle = dyn_cast<ShuffleVectorSDNode>(Op0);
10906     if (Shuffle) {
10907       Op = Op1;
10908     } else {
10909       Shuffle = dyn_cast<ShuffleVectorSDNode>(Op1);
10910       Op = Op0;
10911     }
10912 
10913     // The first operand of the shuffle should be the same as the other operand
10914     // of the binop.
10915     if (!Shuffle || Shuffle->getOperand(0) != Op)
10916       return PartialReduction(PrevOp, MaskEnd);
10917 
10918     // Verify the shuffle has the expected (at this stage of the pyramid) mask.
10919     for (int Index = 0; Index < (int)MaskEnd; ++Index)
10920       if (Shuffle->getMaskElt(Index) != (int)(MaskEnd + Index))
10921         return PartialReduction(PrevOp, MaskEnd);
10922 
10923     PrevOp = Op;
10924   }
10925 
10926   // Handle subvector reductions, which tend to appear after the shuffle
10927   // reduction stages.
10928   while (Op.getOpcode() == CandidateBinOp) {
10929     unsigned NumElts = Op.getValueType().getVectorNumElements();
10930     SDValue Op0 = Op.getOperand(0);
10931     SDValue Op1 = Op.getOperand(1);
10932     if (Op0.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
10933         Op1.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
10934         Op0.getOperand(0) != Op1.getOperand(0))
10935       break;
10936     SDValue Src = Op0.getOperand(0);
10937     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
10938     if (NumSrcElts != (2 * NumElts))
10939       break;
10940     if (!(Op0.getConstantOperandAPInt(1) == 0 &&
10941           Op1.getConstantOperandAPInt(1) == NumElts) &&
10942         !(Op1.getConstantOperandAPInt(1) == 0 &&
10943           Op0.getConstantOperandAPInt(1) == NumElts))
10944       break;
10945     Op = Src;
10946   }
10947 
10948   BinOp = (ISD::NodeType)CandidateBinOp;
10949   return Op;
10950 }
10951 
10952 SDValue SelectionDAG::UnrollVectorOp(SDNode *N, unsigned ResNE) {
10953   assert(N->getNumValues() == 1 &&
10954          "Can't unroll a vector with multiple results!");
10955 
10956   EVT VT = N->getValueType(0);
10957   unsigned NE = VT.getVectorNumElements();
10958   EVT EltVT = VT.getVectorElementType();
10959   SDLoc dl(N);
10960 
10961   SmallVector<SDValue, 8> Scalars;
10962   SmallVector<SDValue, 4> Operands(N->getNumOperands());
10963 
10964   // If ResNE is 0, fully unroll the vector op.
10965   if (ResNE == 0)
10966     ResNE = NE;
10967   else if (NE > ResNE)
10968     NE = ResNE;
10969 
10970   unsigned i;
10971   for (i= 0; i != NE; ++i) {
10972     for (unsigned j = 0, e = N->getNumOperands(); j != e; ++j) {
10973       SDValue Operand = N->getOperand(j);
10974       EVT OperandVT = Operand.getValueType();
10975       if (OperandVT.isVector()) {
10976         // A vector operand; extract a single element.
10977         EVT OperandEltVT = OperandVT.getVectorElementType();
10978         Operands[j] = getNode(ISD::EXTRACT_VECTOR_ELT, dl, OperandEltVT,
10979                               Operand, getVectorIdxConstant(i, dl));
10980       } else {
10981         // A scalar operand; just use it as is.
10982         Operands[j] = Operand;
10983       }
10984     }
10985 
10986     switch (N->getOpcode()) {
10987     default: {
10988       Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands,
10989                                 N->getFlags()));
10990       break;
10991     }
10992     case ISD::VSELECT:
10993       Scalars.push_back(getNode(ISD::SELECT, dl, EltVT, Operands));
10994       break;
10995     case ISD::SHL:
10996     case ISD::SRA:
10997     case ISD::SRL:
10998     case ISD::ROTL:
10999     case ISD::ROTR:
11000       Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands[0],
11001                                getShiftAmountOperand(Operands[0].getValueType(),
11002                                                      Operands[1])));
11003       break;
11004     case ISD::SIGN_EXTEND_INREG: {
11005       EVT ExtVT = cast<VTSDNode>(Operands[1])->getVT().getVectorElementType();
11006       Scalars.push_back(getNode(N->getOpcode(), dl, EltVT,
11007                                 Operands[0],
11008                                 getValueType(ExtVT)));
11009     }
11010     }
11011   }
11012 
11013   for (; i < ResNE; ++i)
11014     Scalars.push_back(getUNDEF(EltVT));
11015 
11016   EVT VecVT = EVT::getVectorVT(*getContext(), EltVT, ResNE);
11017   return getBuildVector(VecVT, dl, Scalars);
11018 }
11019 
11020 std::pair<SDValue, SDValue> SelectionDAG::UnrollVectorOverflowOp(
11021     SDNode *N, unsigned ResNE) {
11022   unsigned Opcode = N->getOpcode();
11023   assert((Opcode == ISD::UADDO || Opcode == ISD::SADDO ||
11024           Opcode == ISD::USUBO || Opcode == ISD::SSUBO ||
11025           Opcode == ISD::UMULO || Opcode == ISD::SMULO) &&
11026          "Expected an overflow opcode");
11027 
11028   EVT ResVT = N->getValueType(0);
11029   EVT OvVT = N->getValueType(1);
11030   EVT ResEltVT = ResVT.getVectorElementType();
11031   EVT OvEltVT = OvVT.getVectorElementType();
11032   SDLoc dl(N);
11033 
11034   // If ResNE is 0, fully unroll the vector op.
11035   unsigned NE = ResVT.getVectorNumElements();
11036   if (ResNE == 0)
11037     ResNE = NE;
11038   else if (NE > ResNE)
11039     NE = ResNE;
11040 
11041   SmallVector<SDValue, 8> LHSScalars;
11042   SmallVector<SDValue, 8> RHSScalars;
11043   ExtractVectorElements(N->getOperand(0), LHSScalars, 0, NE);
11044   ExtractVectorElements(N->getOperand(1), RHSScalars, 0, NE);
11045 
11046   EVT SVT = TLI->getSetCCResultType(getDataLayout(), *getContext(), ResEltVT);
11047   SDVTList VTs = getVTList(ResEltVT, SVT);
11048   SmallVector<SDValue, 8> ResScalars;
11049   SmallVector<SDValue, 8> OvScalars;
11050   for (unsigned i = 0; i < NE; ++i) {
11051     SDValue Res = getNode(Opcode, dl, VTs, LHSScalars[i], RHSScalars[i]);
11052     SDValue Ov =
11053         getSelect(dl, OvEltVT, Res.getValue(1),
11054                   getBoolConstant(true, dl, OvEltVT, ResVT),
11055                   getConstant(0, dl, OvEltVT));
11056 
11057     ResScalars.push_back(Res);
11058     OvScalars.push_back(Ov);
11059   }
11060 
11061   ResScalars.append(ResNE - NE, getUNDEF(ResEltVT));
11062   OvScalars.append(ResNE - NE, getUNDEF(OvEltVT));
11063 
11064   EVT NewResVT = EVT::getVectorVT(*getContext(), ResEltVT, ResNE);
11065   EVT NewOvVT = EVT::getVectorVT(*getContext(), OvEltVT, ResNE);
11066   return std::make_pair(getBuildVector(NewResVT, dl, ResScalars),
11067                         getBuildVector(NewOvVT, dl, OvScalars));
11068 }
11069 
11070 bool SelectionDAG::areNonVolatileConsecutiveLoads(LoadSDNode *LD,
11071                                                   LoadSDNode *Base,
11072                                                   unsigned Bytes,
11073                                                   int Dist) const {
11074   if (LD->isVolatile() || Base->isVolatile())
11075     return false;
11076   // TODO: probably too restrictive for atomics, revisit
11077   if (!LD->isSimple())
11078     return false;
11079   if (LD->isIndexed() || Base->isIndexed())
11080     return false;
11081   if (LD->getChain() != Base->getChain())
11082     return false;
11083   EVT VT = LD->getValueType(0);
11084   if (VT.getSizeInBits() / 8 != Bytes)
11085     return false;
11086 
11087   auto BaseLocDecomp = BaseIndexOffset::match(Base, *this);
11088   auto LocDecomp = BaseIndexOffset::match(LD, *this);
11089 
11090   int64_t Offset = 0;
11091   if (BaseLocDecomp.equalBaseIndex(LocDecomp, *this, Offset))
11092     return (Dist * Bytes == Offset);
11093   return false;
11094 }
11095 
11096 /// InferPtrAlignment - Infer alignment of a load / store address. Return None
11097 /// if it cannot be inferred.
11098 MaybeAlign SelectionDAG::InferPtrAlign(SDValue Ptr) const {
11099   // If this is a GlobalAddress + cst, return the alignment.
11100   const GlobalValue *GV = nullptr;
11101   int64_t GVOffset = 0;
11102   if (TLI->isGAPlusOffset(Ptr.getNode(), GV, GVOffset)) {
11103     unsigned PtrWidth = getDataLayout().getPointerTypeSizeInBits(GV->getType());
11104     KnownBits Known(PtrWidth);
11105     llvm::computeKnownBits(GV, Known, getDataLayout());
11106     unsigned AlignBits = Known.countMinTrailingZeros();
11107     if (AlignBits)
11108       return commonAlignment(Align(1ull << std::min(31U, AlignBits)), GVOffset);
11109   }
11110 
11111   // If this is a direct reference to a stack slot, use information about the
11112   // stack slot's alignment.
11113   int FrameIdx = INT_MIN;
11114   int64_t FrameOffset = 0;
11115   if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr)) {
11116     FrameIdx = FI->getIndex();
11117   } else if (isBaseWithConstantOffset(Ptr) &&
11118              isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
11119     // Handle FI+Cst
11120     FrameIdx = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
11121     FrameOffset = Ptr.getConstantOperandVal(1);
11122   }
11123 
11124   if (FrameIdx != INT_MIN) {
11125     const MachineFrameInfo &MFI = getMachineFunction().getFrameInfo();
11126     return commonAlignment(MFI.getObjectAlign(FrameIdx), FrameOffset);
11127   }
11128 
11129   return None;
11130 }
11131 
11132 /// GetSplitDestVTs - Compute the VTs needed for the low/hi parts of a type
11133 /// which is split (or expanded) into two not necessarily identical pieces.
11134 std::pair<EVT, EVT> SelectionDAG::GetSplitDestVTs(const EVT &VT) const {
11135   // Currently all types are split in half.
11136   EVT LoVT, HiVT;
11137   if (!VT.isVector())
11138     LoVT = HiVT = TLI->getTypeToTransformTo(*getContext(), VT);
11139   else
11140     LoVT = HiVT = VT.getHalfNumVectorElementsVT(*getContext());
11141 
11142   return std::make_pair(LoVT, HiVT);
11143 }
11144 
11145 /// GetDependentSplitDestVTs - Compute the VTs needed for the low/hi parts of a
11146 /// type, dependent on an enveloping VT that has been split into two identical
11147 /// pieces. Sets the HiIsEmpty flag when hi type has zero storage size.
11148 std::pair<EVT, EVT>
11149 SelectionDAG::GetDependentSplitDestVTs(const EVT &VT, const EVT &EnvVT,
11150                                        bool *HiIsEmpty) const {
11151   EVT EltTp = VT.getVectorElementType();
11152   // Examples:
11153   //   custom VL=8  with enveloping VL=8/8 yields 8/0 (hi empty)
11154   //   custom VL=9  with enveloping VL=8/8 yields 8/1
11155   //   custom VL=10 with enveloping VL=8/8 yields 8/2
11156   //   etc.
11157   ElementCount VTNumElts = VT.getVectorElementCount();
11158   ElementCount EnvNumElts = EnvVT.getVectorElementCount();
11159   assert(VTNumElts.isScalable() == EnvNumElts.isScalable() &&
11160          "Mixing fixed width and scalable vectors when enveloping a type");
11161   EVT LoVT, HiVT;
11162   if (VTNumElts.getKnownMinValue() > EnvNumElts.getKnownMinValue()) {
11163     LoVT = EVT::getVectorVT(*getContext(), EltTp, EnvNumElts);
11164     HiVT = EVT::getVectorVT(*getContext(), EltTp, VTNumElts - EnvNumElts);
11165     *HiIsEmpty = false;
11166   } else {
11167     // Flag that hi type has zero storage size, but return split envelop type
11168     // (this would be easier if vector types with zero elements were allowed).
11169     LoVT = EVT::getVectorVT(*getContext(), EltTp, VTNumElts);
11170     HiVT = EVT::getVectorVT(*getContext(), EltTp, EnvNumElts);
11171     *HiIsEmpty = true;
11172   }
11173   return std::make_pair(LoVT, HiVT);
11174 }
11175 
11176 /// SplitVector - Split the vector with EXTRACT_SUBVECTOR and return the
11177 /// low/high part.
11178 std::pair<SDValue, SDValue>
11179 SelectionDAG::SplitVector(const SDValue &N, const SDLoc &DL, const EVT &LoVT,
11180                           const EVT &HiVT) {
11181   assert(LoVT.isScalableVector() == HiVT.isScalableVector() &&
11182          LoVT.isScalableVector() == N.getValueType().isScalableVector() &&
11183          "Splitting vector with an invalid mixture of fixed and scalable "
11184          "vector types");
11185   assert(LoVT.getVectorMinNumElements() + HiVT.getVectorMinNumElements() <=
11186              N.getValueType().getVectorMinNumElements() &&
11187          "More vector elements requested than available!");
11188   SDValue Lo, Hi;
11189   Lo =
11190       getNode(ISD::EXTRACT_SUBVECTOR, DL, LoVT, N, getVectorIdxConstant(0, DL));
11191   // For scalable vectors it is safe to use LoVT.getVectorMinNumElements()
11192   // (rather than having to use ElementCount), because EXTRACT_SUBVECTOR scales
11193   // IDX with the runtime scaling factor of the result vector type. For
11194   // fixed-width result vectors, that runtime scaling factor is 1.
11195   Hi = getNode(ISD::EXTRACT_SUBVECTOR, DL, HiVT, N,
11196                getVectorIdxConstant(LoVT.getVectorMinNumElements(), DL));
11197   return std::make_pair(Lo, Hi);
11198 }
11199 
11200 std::pair<SDValue, SDValue> SelectionDAG::SplitEVL(SDValue N, EVT VecVT,
11201                                                    const SDLoc &DL) {
11202   // Split the vector length parameter.
11203   // %evl -> umin(%evl, %halfnumelts) and usubsat(%evl - %halfnumelts).
11204   EVT VT = N.getValueType();
11205   assert(VecVT.getVectorElementCount().isKnownEven() &&
11206          "Expecting the mask to be an evenly-sized vector");
11207   unsigned HalfMinNumElts = VecVT.getVectorMinNumElements() / 2;
11208   SDValue HalfNumElts =
11209       VecVT.isFixedLengthVector()
11210           ? getConstant(HalfMinNumElts, DL, VT)
11211           : getVScale(DL, VT, APInt(VT.getScalarSizeInBits(), HalfMinNumElts));
11212   SDValue Lo = getNode(ISD::UMIN, DL, VT, N, HalfNumElts);
11213   SDValue Hi = getNode(ISD::USUBSAT, DL, VT, N, HalfNumElts);
11214   return std::make_pair(Lo, Hi);
11215 }
11216 
11217 /// Widen the vector up to the next power of two using INSERT_SUBVECTOR.
11218 SDValue SelectionDAG::WidenVector(const SDValue &N, const SDLoc &DL) {
11219   EVT VT = N.getValueType();
11220   EVT WideVT = EVT::getVectorVT(*getContext(), VT.getVectorElementType(),
11221                                 NextPowerOf2(VT.getVectorNumElements()));
11222   return getNode(ISD::INSERT_SUBVECTOR, DL, WideVT, getUNDEF(WideVT), N,
11223                  getVectorIdxConstant(0, DL));
11224 }
11225 
11226 void SelectionDAG::ExtractVectorElements(SDValue Op,
11227                                          SmallVectorImpl<SDValue> &Args,
11228                                          unsigned Start, unsigned Count,
11229                                          EVT EltVT) {
11230   EVT VT = Op.getValueType();
11231   if (Count == 0)
11232     Count = VT.getVectorNumElements();
11233   if (EltVT == EVT())
11234     EltVT = VT.getVectorElementType();
11235   SDLoc SL(Op);
11236   for (unsigned i = Start, e = Start + Count; i != e; ++i) {
11237     Args.push_back(getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Op,
11238                            getVectorIdxConstant(i, SL)));
11239   }
11240 }
11241 
11242 // getAddressSpace - Return the address space this GlobalAddress belongs to.
11243 unsigned GlobalAddressSDNode::getAddressSpace() const {
11244   return getGlobal()->getType()->getAddressSpace();
11245 }
11246 
11247 Type *ConstantPoolSDNode::getType() const {
11248   if (isMachineConstantPoolEntry())
11249     return Val.MachineCPVal->getType();
11250   return Val.ConstVal->getType();
11251 }
11252 
11253 bool BuildVectorSDNode::isConstantSplat(APInt &SplatValue, APInt &SplatUndef,
11254                                         unsigned &SplatBitSize,
11255                                         bool &HasAnyUndefs,
11256                                         unsigned MinSplatBits,
11257                                         bool IsBigEndian) const {
11258   EVT VT = getValueType(0);
11259   assert(VT.isVector() && "Expected a vector type");
11260   unsigned VecWidth = VT.getSizeInBits();
11261   if (MinSplatBits > VecWidth)
11262     return false;
11263 
11264   // FIXME: The widths are based on this node's type, but build vectors can
11265   // truncate their operands.
11266   SplatValue = APInt(VecWidth, 0);
11267   SplatUndef = APInt(VecWidth, 0);
11268 
11269   // Get the bits. Bits with undefined values (when the corresponding element
11270   // of the vector is an ISD::UNDEF value) are set in SplatUndef and cleared
11271   // in SplatValue. If any of the values are not constant, give up and return
11272   // false.
11273   unsigned int NumOps = getNumOperands();
11274   assert(NumOps > 0 && "isConstantSplat has 0-size build vector");
11275   unsigned EltWidth = VT.getScalarSizeInBits();
11276 
11277   for (unsigned j = 0; j < NumOps; ++j) {
11278     unsigned i = IsBigEndian ? NumOps - 1 - j : j;
11279     SDValue OpVal = getOperand(i);
11280     unsigned BitPos = j * EltWidth;
11281 
11282     if (OpVal.isUndef())
11283       SplatUndef.setBits(BitPos, BitPos + EltWidth);
11284     else if (auto *CN = dyn_cast<ConstantSDNode>(OpVal))
11285       SplatValue.insertBits(CN->getAPIntValue().zextOrTrunc(EltWidth), BitPos);
11286     else if (auto *CN = dyn_cast<ConstantFPSDNode>(OpVal))
11287       SplatValue.insertBits(CN->getValueAPF().bitcastToAPInt(), BitPos);
11288     else
11289       return false;
11290   }
11291 
11292   // The build_vector is all constants or undefs. Find the smallest element
11293   // size that splats the vector.
11294   HasAnyUndefs = (SplatUndef != 0);
11295 
11296   // FIXME: This does not work for vectors with elements less than 8 bits.
11297   while (VecWidth > 8) {
11298     unsigned HalfSize = VecWidth / 2;
11299     APInt HighValue = SplatValue.extractBits(HalfSize, HalfSize);
11300     APInt LowValue = SplatValue.extractBits(HalfSize, 0);
11301     APInt HighUndef = SplatUndef.extractBits(HalfSize, HalfSize);
11302     APInt LowUndef = SplatUndef.extractBits(HalfSize, 0);
11303 
11304     // If the two halves do not match (ignoring undef bits), stop here.
11305     if ((HighValue & ~LowUndef) != (LowValue & ~HighUndef) ||
11306         MinSplatBits > HalfSize)
11307       break;
11308 
11309     SplatValue = HighValue | LowValue;
11310     SplatUndef = HighUndef & LowUndef;
11311 
11312     VecWidth = HalfSize;
11313   }
11314 
11315   SplatBitSize = VecWidth;
11316   return true;
11317 }
11318 
11319 SDValue BuildVectorSDNode::getSplatValue(const APInt &DemandedElts,
11320                                          BitVector *UndefElements) const {
11321   unsigned NumOps = getNumOperands();
11322   if (UndefElements) {
11323     UndefElements->clear();
11324     UndefElements->resize(NumOps);
11325   }
11326   assert(NumOps == DemandedElts.getBitWidth() && "Unexpected vector size");
11327   if (!DemandedElts)
11328     return SDValue();
11329   SDValue Splatted;
11330   for (unsigned i = 0; i != NumOps; ++i) {
11331     if (!DemandedElts[i])
11332       continue;
11333     SDValue Op = getOperand(i);
11334     if (Op.isUndef()) {
11335       if (UndefElements)
11336         (*UndefElements)[i] = true;
11337     } else if (!Splatted) {
11338       Splatted = Op;
11339     } else if (Splatted != Op) {
11340       return SDValue();
11341     }
11342   }
11343 
11344   if (!Splatted) {
11345     unsigned FirstDemandedIdx = DemandedElts.countTrailingZeros();
11346     assert(getOperand(FirstDemandedIdx).isUndef() &&
11347            "Can only have a splat without a constant for all undefs.");
11348     return getOperand(FirstDemandedIdx);
11349   }
11350 
11351   return Splatted;
11352 }
11353 
11354 SDValue BuildVectorSDNode::getSplatValue(BitVector *UndefElements) const {
11355   APInt DemandedElts = APInt::getAllOnes(getNumOperands());
11356   return getSplatValue(DemandedElts, UndefElements);
11357 }
11358 
11359 bool BuildVectorSDNode::getRepeatedSequence(const APInt &DemandedElts,
11360                                             SmallVectorImpl<SDValue> &Sequence,
11361                                             BitVector *UndefElements) const {
11362   unsigned NumOps = getNumOperands();
11363   Sequence.clear();
11364   if (UndefElements) {
11365     UndefElements->clear();
11366     UndefElements->resize(NumOps);
11367   }
11368   assert(NumOps == DemandedElts.getBitWidth() && "Unexpected vector size");
11369   if (!DemandedElts || NumOps < 2 || !isPowerOf2_32(NumOps))
11370     return false;
11371 
11372   // Set the undefs even if we don't find a sequence (like getSplatValue).
11373   if (UndefElements)
11374     for (unsigned I = 0; I != NumOps; ++I)
11375       if (DemandedElts[I] && getOperand(I).isUndef())
11376         (*UndefElements)[I] = true;
11377 
11378   // Iteratively widen the sequence length looking for repetitions.
11379   for (unsigned SeqLen = 1; SeqLen < NumOps; SeqLen *= 2) {
11380     Sequence.append(SeqLen, SDValue());
11381     for (unsigned I = 0; I != NumOps; ++I) {
11382       if (!DemandedElts[I])
11383         continue;
11384       SDValue &SeqOp = Sequence[I % SeqLen];
11385       SDValue Op = getOperand(I);
11386       if (Op.isUndef()) {
11387         if (!SeqOp)
11388           SeqOp = Op;
11389         continue;
11390       }
11391       if (SeqOp && !SeqOp.isUndef() && SeqOp != Op) {
11392         Sequence.clear();
11393         break;
11394       }
11395       SeqOp = Op;
11396     }
11397     if (!Sequence.empty())
11398       return true;
11399   }
11400 
11401   assert(Sequence.empty() && "Failed to empty non-repeating sequence pattern");
11402   return false;
11403 }
11404 
11405 bool BuildVectorSDNode::getRepeatedSequence(SmallVectorImpl<SDValue> &Sequence,
11406                                             BitVector *UndefElements) const {
11407   APInt DemandedElts = APInt::getAllOnes(getNumOperands());
11408   return getRepeatedSequence(DemandedElts, Sequence, UndefElements);
11409 }
11410 
11411 ConstantSDNode *
11412 BuildVectorSDNode::getConstantSplatNode(const APInt &DemandedElts,
11413                                         BitVector *UndefElements) const {
11414   return dyn_cast_or_null<ConstantSDNode>(
11415       getSplatValue(DemandedElts, UndefElements));
11416 }
11417 
11418 ConstantSDNode *
11419 BuildVectorSDNode::getConstantSplatNode(BitVector *UndefElements) const {
11420   return dyn_cast_or_null<ConstantSDNode>(getSplatValue(UndefElements));
11421 }
11422 
11423 ConstantFPSDNode *
11424 BuildVectorSDNode::getConstantFPSplatNode(const APInt &DemandedElts,
11425                                           BitVector *UndefElements) const {
11426   return dyn_cast_or_null<ConstantFPSDNode>(
11427       getSplatValue(DemandedElts, UndefElements));
11428 }
11429 
11430 ConstantFPSDNode *
11431 BuildVectorSDNode::getConstantFPSplatNode(BitVector *UndefElements) const {
11432   return dyn_cast_or_null<ConstantFPSDNode>(getSplatValue(UndefElements));
11433 }
11434 
11435 int32_t
11436 BuildVectorSDNode::getConstantFPSplatPow2ToLog2Int(BitVector *UndefElements,
11437                                                    uint32_t BitWidth) const {
11438   if (ConstantFPSDNode *CN =
11439           dyn_cast_or_null<ConstantFPSDNode>(getSplatValue(UndefElements))) {
11440     bool IsExact;
11441     APSInt IntVal(BitWidth);
11442     const APFloat &APF = CN->getValueAPF();
11443     if (APF.convertToInteger(IntVal, APFloat::rmTowardZero, &IsExact) !=
11444             APFloat::opOK ||
11445         !IsExact)
11446       return -1;
11447 
11448     return IntVal.exactLogBase2();
11449   }
11450   return -1;
11451 }
11452 
11453 bool BuildVectorSDNode::getConstantRawBits(
11454     bool IsLittleEndian, unsigned DstEltSizeInBits,
11455     SmallVectorImpl<APInt> &RawBitElements, BitVector &UndefElements) const {
11456   // Early-out if this contains anything but Undef/Constant/ConstantFP.
11457   if (!isConstant())
11458     return false;
11459 
11460   unsigned NumSrcOps = getNumOperands();
11461   unsigned SrcEltSizeInBits = getValueType(0).getScalarSizeInBits();
11462   assert(((NumSrcOps * SrcEltSizeInBits) % DstEltSizeInBits) == 0 &&
11463          "Invalid bitcast scale");
11464 
11465   // Extract raw src bits.
11466   SmallVector<APInt> SrcBitElements(NumSrcOps,
11467                                     APInt::getNullValue(SrcEltSizeInBits));
11468   BitVector SrcUndeElements(NumSrcOps, false);
11469 
11470   for (unsigned I = 0; I != NumSrcOps; ++I) {
11471     SDValue Op = getOperand(I);
11472     if (Op.isUndef()) {
11473       SrcUndeElements.set(I);
11474       continue;
11475     }
11476     auto *CInt = dyn_cast<ConstantSDNode>(Op);
11477     auto *CFP = dyn_cast<ConstantFPSDNode>(Op);
11478     assert((CInt || CFP) && "Unknown constant");
11479     SrcBitElements[I] = CInt ? CInt->getAPIntValue().trunc(SrcEltSizeInBits)
11480                              : CFP->getValueAPF().bitcastToAPInt();
11481   }
11482 
11483   // Recast to dst width.
11484   recastRawBits(IsLittleEndian, DstEltSizeInBits, RawBitElements,
11485                 SrcBitElements, UndefElements, SrcUndeElements);
11486   return true;
11487 }
11488 
11489 void BuildVectorSDNode::recastRawBits(bool IsLittleEndian,
11490                                       unsigned DstEltSizeInBits,
11491                                       SmallVectorImpl<APInt> &DstBitElements,
11492                                       ArrayRef<APInt> SrcBitElements,
11493                                       BitVector &DstUndefElements,
11494                                       const BitVector &SrcUndefElements) {
11495   unsigned NumSrcOps = SrcBitElements.size();
11496   unsigned SrcEltSizeInBits = SrcBitElements[0].getBitWidth();
11497   assert(((NumSrcOps * SrcEltSizeInBits) % DstEltSizeInBits) == 0 &&
11498          "Invalid bitcast scale");
11499   assert(NumSrcOps == SrcUndefElements.size() &&
11500          "Vector size mismatch");
11501 
11502   unsigned NumDstOps = (NumSrcOps * SrcEltSizeInBits) / DstEltSizeInBits;
11503   DstUndefElements.clear();
11504   DstUndefElements.resize(NumDstOps, false);
11505   DstBitElements.assign(NumDstOps, APInt::getNullValue(DstEltSizeInBits));
11506 
11507   // Concatenate src elements constant bits together into dst element.
11508   if (SrcEltSizeInBits <= DstEltSizeInBits) {
11509     unsigned Scale = DstEltSizeInBits / SrcEltSizeInBits;
11510     for (unsigned I = 0; I != NumDstOps; ++I) {
11511       DstUndefElements.set(I);
11512       APInt &DstBits = DstBitElements[I];
11513       for (unsigned J = 0; J != Scale; ++J) {
11514         unsigned Idx = (I * Scale) + (IsLittleEndian ? J : (Scale - J - 1));
11515         if (SrcUndefElements[Idx])
11516           continue;
11517         DstUndefElements.reset(I);
11518         const APInt &SrcBits = SrcBitElements[Idx];
11519         assert(SrcBits.getBitWidth() == SrcEltSizeInBits &&
11520                "Illegal constant bitwidths");
11521         DstBits.insertBits(SrcBits, J * SrcEltSizeInBits);
11522       }
11523     }
11524     return;
11525   }
11526 
11527   // Split src element constant bits into dst elements.
11528   unsigned Scale = SrcEltSizeInBits / DstEltSizeInBits;
11529   for (unsigned I = 0; I != NumSrcOps; ++I) {
11530     if (SrcUndefElements[I]) {
11531       DstUndefElements.set(I * Scale, (I + 1) * Scale);
11532       continue;
11533     }
11534     const APInt &SrcBits = SrcBitElements[I];
11535     for (unsigned J = 0; J != Scale; ++J) {
11536       unsigned Idx = (I * Scale) + (IsLittleEndian ? J : (Scale - J - 1));
11537       APInt &DstBits = DstBitElements[Idx];
11538       DstBits = SrcBits.extractBits(DstEltSizeInBits, J * DstEltSizeInBits);
11539     }
11540   }
11541 }
11542 
11543 bool BuildVectorSDNode::isConstant() const {
11544   for (const SDValue &Op : op_values()) {
11545     unsigned Opc = Op.getOpcode();
11546     if (Opc != ISD::UNDEF && Opc != ISD::Constant && Opc != ISD::ConstantFP)
11547       return false;
11548   }
11549   return true;
11550 }
11551 
11552 bool ShuffleVectorSDNode::isSplatMask(const int *Mask, EVT VT) {
11553   // Find the first non-undef value in the shuffle mask.
11554   unsigned i, e;
11555   for (i = 0, e = VT.getVectorNumElements(); i != e && Mask[i] < 0; ++i)
11556     /* search */;
11557 
11558   // If all elements are undefined, this shuffle can be considered a splat
11559   // (although it should eventually get simplified away completely).
11560   if (i == e)
11561     return true;
11562 
11563   // Make sure all remaining elements are either undef or the same as the first
11564   // non-undef value.
11565   for (int Idx = Mask[i]; i != e; ++i)
11566     if (Mask[i] >= 0 && Mask[i] != Idx)
11567       return false;
11568   return true;
11569 }
11570 
11571 // Returns the SDNode if it is a constant integer BuildVector
11572 // or constant integer.
11573 SDNode *SelectionDAG::isConstantIntBuildVectorOrConstantInt(SDValue N) const {
11574   if (isa<ConstantSDNode>(N))
11575     return N.getNode();
11576   if (ISD::isBuildVectorOfConstantSDNodes(N.getNode()))
11577     return N.getNode();
11578   // Treat a GlobalAddress supporting constant offset folding as a
11579   // constant integer.
11580   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N))
11581     if (GA->getOpcode() == ISD::GlobalAddress &&
11582         TLI->isOffsetFoldingLegal(GA))
11583       return GA;
11584   if ((N.getOpcode() == ISD::SPLAT_VECTOR) &&
11585       isa<ConstantSDNode>(N.getOperand(0)))
11586     return N.getNode();
11587   return nullptr;
11588 }
11589 
11590 // Returns the SDNode if it is a constant float BuildVector
11591 // or constant float.
11592 SDNode *SelectionDAG::isConstantFPBuildVectorOrConstantFP(SDValue N) const {
11593   if (isa<ConstantFPSDNode>(N))
11594     return N.getNode();
11595 
11596   if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode()))
11597     return N.getNode();
11598 
11599   if ((N.getOpcode() == ISD::SPLAT_VECTOR) &&
11600       isa<ConstantFPSDNode>(N.getOperand(0)))
11601     return N.getNode();
11602 
11603   return nullptr;
11604 }
11605 
11606 void SelectionDAG::createOperands(SDNode *Node, ArrayRef<SDValue> Vals) {
11607   assert(!Node->OperandList && "Node already has operands");
11608   assert(SDNode::getMaxNumOperands() >= Vals.size() &&
11609          "too many operands to fit into SDNode");
11610   SDUse *Ops = OperandRecycler.allocate(
11611       ArrayRecycler<SDUse>::Capacity::get(Vals.size()), OperandAllocator);
11612 
11613   bool IsDivergent = false;
11614   for (unsigned I = 0; I != Vals.size(); ++I) {
11615     Ops[I].setUser(Node);
11616     Ops[I].setInitial(Vals[I]);
11617     if (Ops[I].Val.getValueType() != MVT::Other) // Skip Chain. It does not carry divergence.
11618       IsDivergent |= Ops[I].getNode()->isDivergent();
11619   }
11620   Node->NumOperands = Vals.size();
11621   Node->OperandList = Ops;
11622   if (!TLI->isSDNodeAlwaysUniform(Node)) {
11623     IsDivergent |= TLI->isSDNodeSourceOfDivergence(Node, FLI, DA);
11624     Node->SDNodeBits.IsDivergent = IsDivergent;
11625   }
11626   checkForCycles(Node);
11627 }
11628 
11629 SDValue SelectionDAG::getTokenFactor(const SDLoc &DL,
11630                                      SmallVectorImpl<SDValue> &Vals) {
11631   size_t Limit = SDNode::getMaxNumOperands();
11632   while (Vals.size() > Limit) {
11633     unsigned SliceIdx = Vals.size() - Limit;
11634     auto ExtractedTFs = ArrayRef<SDValue>(Vals).slice(SliceIdx, Limit);
11635     SDValue NewTF = getNode(ISD::TokenFactor, DL, MVT::Other, ExtractedTFs);
11636     Vals.erase(Vals.begin() + SliceIdx, Vals.end());
11637     Vals.emplace_back(NewTF);
11638   }
11639   return getNode(ISD::TokenFactor, DL, MVT::Other, Vals);
11640 }
11641 
11642 SDValue SelectionDAG::getNeutralElement(unsigned Opcode, const SDLoc &DL,
11643                                         EVT VT, SDNodeFlags Flags) {
11644   switch (Opcode) {
11645   default:
11646     return SDValue();
11647   case ISD::ADD:
11648   case ISD::OR:
11649   case ISD::XOR:
11650   case ISD::UMAX:
11651     return getConstant(0, DL, VT);
11652   case ISD::MUL:
11653     return getConstant(1, DL, VT);
11654   case ISD::AND:
11655   case ISD::UMIN:
11656     return getAllOnesConstant(DL, VT);
11657   case ISD::SMAX:
11658     return getConstant(APInt::getSignedMinValue(VT.getSizeInBits()), DL, VT);
11659   case ISD::SMIN:
11660     return getConstant(APInt::getSignedMaxValue(VT.getSizeInBits()), DL, VT);
11661   case ISD::FADD:
11662     return getConstantFP(-0.0, DL, VT);
11663   case ISD::FMUL:
11664     return getConstantFP(1.0, DL, VT);
11665   case ISD::FMINNUM:
11666   case ISD::FMAXNUM: {
11667     // Neutral element for fminnum is NaN, Inf or FLT_MAX, depending on FMF.
11668     const fltSemantics &Semantics = EVTToAPFloatSemantics(VT);
11669     APFloat NeutralAF = !Flags.hasNoNaNs() ? APFloat::getQNaN(Semantics) :
11670                         !Flags.hasNoInfs() ? APFloat::getInf(Semantics) :
11671                         APFloat::getLargest(Semantics);
11672     if (Opcode == ISD::FMAXNUM)
11673       NeutralAF.changeSign();
11674 
11675     return getConstantFP(NeutralAF, DL, VT);
11676   }
11677   }
11678 }
11679 
11680 #ifndef NDEBUG
11681 static void checkForCyclesHelper(const SDNode *N,
11682                                  SmallPtrSetImpl<const SDNode*> &Visited,
11683                                  SmallPtrSetImpl<const SDNode*> &Checked,
11684                                  const llvm::SelectionDAG *DAG) {
11685   // If this node has already been checked, don't check it again.
11686   if (Checked.count(N))
11687     return;
11688 
11689   // If a node has already been visited on this depth-first walk, reject it as
11690   // a cycle.
11691   if (!Visited.insert(N).second) {
11692     errs() << "Detected cycle in SelectionDAG\n";
11693     dbgs() << "Offending node:\n";
11694     N->dumprFull(DAG); dbgs() << "\n";
11695     abort();
11696   }
11697 
11698   for (const SDValue &Op : N->op_values())
11699     checkForCyclesHelper(Op.getNode(), Visited, Checked, DAG);
11700 
11701   Checked.insert(N);
11702   Visited.erase(N);
11703 }
11704 #endif
11705 
11706 void llvm::checkForCycles(const llvm::SDNode *N,
11707                           const llvm::SelectionDAG *DAG,
11708                           bool force) {
11709 #ifndef NDEBUG
11710   bool check = force;
11711 #ifdef EXPENSIVE_CHECKS
11712   check = true;
11713 #endif  // EXPENSIVE_CHECKS
11714   if (check) {
11715     assert(N && "Checking nonexistent SDNode");
11716     SmallPtrSet<const SDNode*, 32> visited;
11717     SmallPtrSet<const SDNode*, 32> checked;
11718     checkForCyclesHelper(N, visited, checked, DAG);
11719   }
11720 #endif  // !NDEBUG
11721 }
11722 
11723 void llvm::checkForCycles(const llvm::SelectionDAG *DAG, bool force) {
11724   checkForCycles(DAG->getRoot().getNode(), DAG, force);
11725 }
11726