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