1 //===- SelectionDAG.cpp - Implement the SelectionDAG data structures ------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This implements the SelectionDAG class.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "llvm/CodeGen/SelectionDAG.h"
14 #include "SDNodeDbgValue.h"
15 #include "llvm/ADT/APFloat.h"
16 #include "llvm/ADT/APInt.h"
17 #include "llvm/ADT/APSInt.h"
18 #include "llvm/ADT/ArrayRef.h"
19 #include "llvm/ADT/BitVector.h"
20 #include "llvm/ADT/FoldingSet.h"
21 #include "llvm/ADT/None.h"
22 #include "llvm/ADT/STLExtras.h"
23 #include "llvm/ADT/SmallPtrSet.h"
24 #include "llvm/ADT/SmallVector.h"
25 #include "llvm/ADT/Triple.h"
26 #include "llvm/ADT/Twine.h"
27 #include "llvm/Analysis/MemoryLocation.h"
28 #include "llvm/Analysis/ValueTracking.h"
29 #include "llvm/CodeGen/Analysis.h"
30 #include "llvm/CodeGen/FunctionLoweringInfo.h"
31 #include "llvm/CodeGen/ISDOpcodes.h"
32 #include "llvm/CodeGen/MachineBasicBlock.h"
33 #include "llvm/CodeGen/MachineConstantPool.h"
34 #include "llvm/CodeGen/MachineFrameInfo.h"
35 #include "llvm/CodeGen/MachineFunction.h"
36 #include "llvm/CodeGen/MachineMemOperand.h"
37 #include "llvm/CodeGen/RuntimeLibcalls.h"
38 #include "llvm/CodeGen/SelectionDAGAddressAnalysis.h"
39 #include "llvm/CodeGen/SelectionDAGNodes.h"
40 #include "llvm/CodeGen/SelectionDAGTargetInfo.h"
41 #include "llvm/CodeGen/TargetFrameLowering.h"
42 #include "llvm/CodeGen/TargetLowering.h"
43 #include "llvm/CodeGen/TargetRegisterInfo.h"
44 #include "llvm/CodeGen/TargetSubtargetInfo.h"
45 #include "llvm/CodeGen/ValueTypes.h"
46 #include "llvm/IR/Constant.h"
47 #include "llvm/IR/Constants.h"
48 #include "llvm/IR/DataLayout.h"
49 #include "llvm/IR/DebugInfoMetadata.h"
50 #include "llvm/IR/DebugLoc.h"
51 #include "llvm/IR/DerivedTypes.h"
52 #include "llvm/IR/Function.h"
53 #include "llvm/IR/GlobalValue.h"
54 #include "llvm/IR/Metadata.h"
55 #include "llvm/IR/Type.h"
56 #include "llvm/Support/Casting.h"
57 #include "llvm/Support/CodeGen.h"
58 #include "llvm/Support/Compiler.h"
59 #include "llvm/Support/Debug.h"
60 #include "llvm/Support/ErrorHandling.h"
61 #include "llvm/Support/KnownBits.h"
62 #include "llvm/Support/MachineValueType.h"
63 #include "llvm/Support/ManagedStatic.h"
64 #include "llvm/Support/MathExtras.h"
65 #include "llvm/Support/Mutex.h"
66 #include "llvm/Support/raw_ostream.h"
67 #include "llvm/Target/TargetMachine.h"
68 #include "llvm/Target/TargetOptions.h"
69 #include "llvm/Transforms/Utils/SizeOpts.h"
70 #include <algorithm>
71 #include <cassert>
72 #include <cstdint>
73 #include <cstdlib>
74 #include <limits>
75 #include <set>
76 #include <string>
77 #include <utility>
78 #include <vector>
79 
80 using namespace llvm;
81 
82 /// makeVTList - Return an instance of the SDVTList struct initialized with the
83 /// specified members.
84 static SDVTList makeVTList(const EVT *VTs, unsigned NumVTs) {
85   SDVTList Res = {VTs, NumVTs};
86   return Res;
87 }
88 
89 // Default null implementations of the callbacks.
90 void SelectionDAG::DAGUpdateListener::NodeDeleted(SDNode*, SDNode*) {}
91 void SelectionDAG::DAGUpdateListener::NodeUpdated(SDNode*) {}
92 void SelectionDAG::DAGUpdateListener::NodeInserted(SDNode *) {}
93 
94 void SelectionDAG::DAGNodeDeletedListener::anchor() {}
95 
96 #define DEBUG_TYPE "selectiondag"
97 
98 static cl::opt<bool> EnableMemCpyDAGOpt("enable-memcpy-dag-opt",
99        cl::Hidden, cl::init(true),
100        cl::desc("Gang up loads and stores generated by inlining of memcpy"));
101 
102 static cl::opt<int> MaxLdStGlue("ldstmemcpy-glue-max",
103        cl::desc("Number limit for gluing ld/st of memcpy."),
104        cl::Hidden, cl::init(0));
105 
106 static void NewSDValueDbgMsg(SDValue V, StringRef Msg, SelectionDAG *G) {
107   LLVM_DEBUG(dbgs() << Msg; V.getNode()->dump(G););
108 }
109 
110 //===----------------------------------------------------------------------===//
111 //                              ConstantFPSDNode Class
112 //===----------------------------------------------------------------------===//
113 
114 /// isExactlyValue - We don't rely on operator== working on double values, as
115 /// it returns true for things that are clearly not equal, like -0.0 and 0.0.
116 /// As such, this method can be used to do an exact bit-for-bit comparison of
117 /// two floating point values.
118 bool ConstantFPSDNode::isExactlyValue(const APFloat& V) const {
119   return getValueAPF().bitwiseIsEqual(V);
120 }
121 
122 bool ConstantFPSDNode::isValueValidForType(EVT VT,
123                                            const APFloat& Val) {
124   assert(VT.isFloatingPoint() && "Can only convert between FP types");
125 
126   // convert modifies in place, so make a copy.
127   APFloat Val2 = APFloat(Val);
128   bool losesInfo;
129   (void) Val2.convert(SelectionDAG::EVTToAPFloatSemantics(VT),
130                       APFloat::rmNearestTiesToEven,
131                       &losesInfo);
132   return !losesInfo;
133 }
134 
135 //===----------------------------------------------------------------------===//
136 //                              ISD Namespace
137 //===----------------------------------------------------------------------===//
138 
139 bool ISD::isConstantSplatVector(const SDNode *N, APInt &SplatVal) {
140   if (N->getOpcode() == ISD::SPLAT_VECTOR) {
141     unsigned EltSize =
142         N->getValueType(0).getVectorElementType().getSizeInBits();
143     if (auto *Op0 = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
144       SplatVal = Op0->getAPIntValue().trunc(EltSize);
145       return true;
146     }
147     if (auto *Op0 = dyn_cast<ConstantFPSDNode>(N->getOperand(0))) {
148       SplatVal = Op0->getValueAPF().bitcastToAPInt().trunc(EltSize);
149       return true;
150     }
151   }
152 
153   auto *BV = dyn_cast<BuildVectorSDNode>(N);
154   if (!BV)
155     return false;
156 
157   APInt SplatUndef;
158   unsigned SplatBitSize;
159   bool HasUndefs;
160   unsigned EltSize = N->getValueType(0).getVectorElementType().getSizeInBits();
161   return BV->isConstantSplat(SplatVal, SplatUndef, SplatBitSize, HasUndefs,
162                              EltSize) &&
163          EltSize == SplatBitSize;
164 }
165 
166 // FIXME: AllOnes and AllZeros duplicate a lot of code. Could these be
167 // specializations of the more general isConstantSplatVector()?
168 
169 bool ISD::isConstantSplatVectorAllOnes(const SDNode *N, bool BuildVectorOnly) {
170   // Look through a bit convert.
171   while (N->getOpcode() == ISD::BITCAST)
172     N = N->getOperand(0).getNode();
173 
174   if (!BuildVectorOnly && N->getOpcode() == ISD::SPLAT_VECTOR) {
175     APInt SplatVal;
176     return isConstantSplatVector(N, SplatVal) && SplatVal.isAllOnes();
177   }
178 
179   if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
180 
181   unsigned i = 0, e = N->getNumOperands();
182 
183   // Skip over all of the undef values.
184   while (i != e && N->getOperand(i).isUndef())
185     ++i;
186 
187   // Do not accept an all-undef vector.
188   if (i == e) return false;
189 
190   // Do not accept build_vectors that aren't all constants or which have non-~0
191   // elements. We have to be a bit careful here, as the type of the constant
192   // may not be the same as the type of the vector elements due to type
193   // legalization (the elements are promoted to a legal type for the target and
194   // a vector of a type may be legal when the base element type is not).
195   // We only want to check enough bits to cover the vector elements, because
196   // we care if the resultant vector is all ones, not whether the individual
197   // constants are.
198   SDValue NotZero = N->getOperand(i);
199   unsigned EltSize = N->getValueType(0).getScalarSizeInBits();
200   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(NotZero)) {
201     if (CN->getAPIntValue().countTrailingOnes() < EltSize)
202       return false;
203   } else if (ConstantFPSDNode *CFPN = dyn_cast<ConstantFPSDNode>(NotZero)) {
204     if (CFPN->getValueAPF().bitcastToAPInt().countTrailingOnes() < EltSize)
205       return false;
206   } else
207     return false;
208 
209   // Okay, we have at least one ~0 value, check to see if the rest match or are
210   // undefs. Even with the above element type twiddling, this should be OK, as
211   // the same type legalization should have applied to all the elements.
212   for (++i; i != e; ++i)
213     if (N->getOperand(i) != NotZero && !N->getOperand(i).isUndef())
214       return false;
215   return true;
216 }
217 
218 bool ISD::isConstantSplatVectorAllZeros(const SDNode *N, bool BuildVectorOnly) {
219   // Look through a bit convert.
220   while (N->getOpcode() == ISD::BITCAST)
221     N = N->getOperand(0).getNode();
222 
223   if (!BuildVectorOnly && N->getOpcode() == ISD::SPLAT_VECTOR) {
224     APInt SplatVal;
225     return isConstantSplatVector(N, SplatVal) && SplatVal.isZero();
226   }
227 
228   if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
229 
230   bool IsAllUndef = true;
231   for (const SDValue &Op : N->op_values()) {
232     if (Op.isUndef())
233       continue;
234     IsAllUndef = false;
235     // Do not accept build_vectors that aren't all constants or which have non-0
236     // elements. We have to be a bit careful here, as the type of the constant
237     // may not be the same as the type of the vector elements due to type
238     // legalization (the elements are promoted to a legal type for the target
239     // and a vector of a type may be legal when the base element type is not).
240     // We only want to check enough bits to cover the vector elements, because
241     // we care if the resultant vector is all zeros, not whether the individual
242     // constants are.
243     unsigned EltSize = N->getValueType(0).getScalarSizeInBits();
244     if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Op)) {
245       if (CN->getAPIntValue().countTrailingZeros() < EltSize)
246         return false;
247     } else if (ConstantFPSDNode *CFPN = dyn_cast<ConstantFPSDNode>(Op)) {
248       if (CFPN->getValueAPF().bitcastToAPInt().countTrailingZeros() < EltSize)
249         return false;
250     } else
251       return false;
252   }
253 
254   // Do not accept an all-undef vector.
255   if (IsAllUndef)
256     return false;
257   return true;
258 }
259 
260 bool ISD::isBuildVectorAllOnes(const SDNode *N) {
261   return isConstantSplatVectorAllOnes(N, /*BuildVectorOnly*/ true);
262 }
263 
264 bool ISD::isBuildVectorAllZeros(const SDNode *N) {
265   return isConstantSplatVectorAllZeros(N, /*BuildVectorOnly*/ true);
266 }
267 
268 bool ISD::isBuildVectorOfConstantSDNodes(const SDNode *N) {
269   if (N->getOpcode() != ISD::BUILD_VECTOR)
270     return false;
271 
272   for (const SDValue &Op : N->op_values()) {
273     if (Op.isUndef())
274       continue;
275     if (!isa<ConstantSDNode>(Op))
276       return false;
277   }
278   return true;
279 }
280 
281 bool ISD::isBuildVectorOfConstantFPSDNodes(const SDNode *N) {
282   if (N->getOpcode() != ISD::BUILD_VECTOR)
283     return false;
284 
285   for (const SDValue &Op : N->op_values()) {
286     if (Op.isUndef())
287       continue;
288     if (!isa<ConstantFPSDNode>(Op))
289       return false;
290   }
291   return true;
292 }
293 
294 bool ISD::allOperandsUndef(const SDNode *N) {
295   // Return false if the node has no operands.
296   // This is "logically inconsistent" with the definition of "all" but
297   // is probably the desired behavior.
298   if (N->getNumOperands() == 0)
299     return false;
300   return all_of(N->op_values(), [](SDValue Op) { return Op.isUndef(); });
301 }
302 
303 bool ISD::matchUnaryPredicate(SDValue Op,
304                               std::function<bool(ConstantSDNode *)> Match,
305                               bool AllowUndefs) {
306   // FIXME: Add support for scalar UNDEF cases?
307   if (auto *Cst = dyn_cast<ConstantSDNode>(Op))
308     return Match(Cst);
309 
310   // FIXME: Add support for vector UNDEF cases?
311   if (ISD::BUILD_VECTOR != Op.getOpcode() &&
312       ISD::SPLAT_VECTOR != Op.getOpcode())
313     return false;
314 
315   EVT SVT = Op.getValueType().getScalarType();
316   for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
317     if (AllowUndefs && Op.getOperand(i).isUndef()) {
318       if (!Match(nullptr))
319         return false;
320       continue;
321     }
322 
323     auto *Cst = dyn_cast<ConstantSDNode>(Op.getOperand(i));
324     if (!Cst || Cst->getValueType(0) != SVT || !Match(Cst))
325       return false;
326   }
327   return true;
328 }
329 
330 bool ISD::matchBinaryPredicate(
331     SDValue LHS, SDValue RHS,
332     std::function<bool(ConstantSDNode *, ConstantSDNode *)> Match,
333     bool AllowUndefs, bool AllowTypeMismatch) {
334   if (!AllowTypeMismatch && LHS.getValueType() != RHS.getValueType())
335     return false;
336 
337   // TODO: Add support for scalar UNDEF cases?
338   if (auto *LHSCst = dyn_cast<ConstantSDNode>(LHS))
339     if (auto *RHSCst = dyn_cast<ConstantSDNode>(RHS))
340       return Match(LHSCst, RHSCst);
341 
342   // TODO: Add support for vector UNDEF cases?
343   if (LHS.getOpcode() != RHS.getOpcode() ||
344       (LHS.getOpcode() != ISD::BUILD_VECTOR &&
345        LHS.getOpcode() != ISD::SPLAT_VECTOR))
346     return false;
347 
348   EVT SVT = LHS.getValueType().getScalarType();
349   for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
350     SDValue LHSOp = LHS.getOperand(i);
351     SDValue RHSOp = RHS.getOperand(i);
352     bool LHSUndef = AllowUndefs && LHSOp.isUndef();
353     bool RHSUndef = AllowUndefs && RHSOp.isUndef();
354     auto *LHSCst = dyn_cast<ConstantSDNode>(LHSOp);
355     auto *RHSCst = dyn_cast<ConstantSDNode>(RHSOp);
356     if ((!LHSCst && !LHSUndef) || (!RHSCst && !RHSUndef))
357       return false;
358     if (!AllowTypeMismatch && (LHSOp.getValueType() != SVT ||
359                                LHSOp.getValueType() != RHSOp.getValueType()))
360       return false;
361     if (!Match(LHSCst, RHSCst))
362       return false;
363   }
364   return true;
365 }
366 
367 ISD::NodeType ISD::getVecReduceBaseOpcode(unsigned VecReduceOpcode) {
368   switch (VecReduceOpcode) {
369   default:
370     llvm_unreachable("Expected VECREDUCE opcode");
371   case ISD::VECREDUCE_FADD:
372   case ISD::VECREDUCE_SEQ_FADD:
373   case ISD::VP_REDUCE_FADD:
374   case ISD::VP_REDUCE_SEQ_FADD:
375     return ISD::FADD;
376   case ISD::VECREDUCE_FMUL:
377   case ISD::VECREDUCE_SEQ_FMUL:
378   case ISD::VP_REDUCE_FMUL:
379   case ISD::VP_REDUCE_SEQ_FMUL:
380     return ISD::FMUL;
381   case ISD::VECREDUCE_ADD:
382   case ISD::VP_REDUCE_ADD:
383     return ISD::ADD;
384   case ISD::VECREDUCE_MUL:
385   case ISD::VP_REDUCE_MUL:
386     return ISD::MUL;
387   case ISD::VECREDUCE_AND:
388   case ISD::VP_REDUCE_AND:
389     return ISD::AND;
390   case ISD::VECREDUCE_OR:
391   case ISD::VP_REDUCE_OR:
392     return ISD::OR;
393   case ISD::VECREDUCE_XOR:
394   case ISD::VP_REDUCE_XOR:
395     return ISD::XOR;
396   case ISD::VECREDUCE_SMAX:
397   case ISD::VP_REDUCE_SMAX:
398     return ISD::SMAX;
399   case ISD::VECREDUCE_SMIN:
400   case ISD::VP_REDUCE_SMIN:
401     return ISD::SMIN;
402   case ISD::VECREDUCE_UMAX:
403   case ISD::VP_REDUCE_UMAX:
404     return ISD::UMAX;
405   case ISD::VECREDUCE_UMIN:
406   case ISD::VP_REDUCE_UMIN:
407     return ISD::UMIN;
408   case ISD::VECREDUCE_FMAX:
409   case ISD::VP_REDUCE_FMAX:
410     return ISD::FMAXNUM;
411   case ISD::VECREDUCE_FMIN:
412   case ISD::VP_REDUCE_FMIN:
413     return ISD::FMINNUM;
414   }
415 }
416 
417 bool ISD::isVPOpcode(unsigned Opcode) {
418   switch (Opcode) {
419   default:
420     return false;
421 #define BEGIN_REGISTER_VP_SDNODE(VPSD, ...)                                    \
422   case ISD::VPSD:                                                              \
423     return true;
424 #include "llvm/IR/VPIntrinsics.def"
425   }
426 }
427 
428 bool ISD::isVPBinaryOp(unsigned Opcode) {
429   switch (Opcode) {
430   default:
431     break;
432 #define BEGIN_REGISTER_VP_SDNODE(VPSD, ...) case ISD::VPSD:
433 #define VP_PROPERTY_BINARYOP return true;
434 #define END_REGISTER_VP_SDNODE(VPSD) break;
435 #include "llvm/IR/VPIntrinsics.def"
436   }
437   return false;
438 }
439 
440 bool ISD::isVPReduction(unsigned Opcode) {
441   switch (Opcode) {
442   default:
443     break;
444 #define BEGIN_REGISTER_VP_SDNODE(VPSD, ...) case ISD::VPSD:
445 #define VP_PROPERTY_REDUCTION(STARTPOS, ...) return true;
446 #define END_REGISTER_VP_SDNODE(VPSD) break;
447 #include "llvm/IR/VPIntrinsics.def"
448   }
449   return false;
450 }
451 
452 /// The operand position of the vector mask.
453 Optional<unsigned> ISD::getVPMaskIdx(unsigned Opcode) {
454   switch (Opcode) {
455   default:
456     return None;
457 #define BEGIN_REGISTER_VP_SDNODE(VPSD, LEGALPOS, TDNAME, MASKPOS, ...)         \
458   case ISD::VPSD:                                                              \
459     return MASKPOS;
460 #include "llvm/IR/VPIntrinsics.def"
461   }
462 }
463 
464 /// The operand position of the explicit vector length parameter.
465 Optional<unsigned> ISD::getVPExplicitVectorLengthIdx(unsigned Opcode) {
466   switch (Opcode) {
467   default:
468     return None;
469 #define BEGIN_REGISTER_VP_SDNODE(VPSD, LEGALPOS, TDNAME, MASKPOS, EVLPOS)      \
470   case ISD::VPSD:                                                              \
471     return EVLPOS;
472 #include "llvm/IR/VPIntrinsics.def"
473   }
474 }
475 
476 ISD::NodeType ISD::getExtForLoadExtType(bool IsFP, ISD::LoadExtType ExtType) {
477   switch (ExtType) {
478   case ISD::EXTLOAD:
479     return IsFP ? ISD::FP_EXTEND : ISD::ANY_EXTEND;
480   case ISD::SEXTLOAD:
481     return ISD::SIGN_EXTEND;
482   case ISD::ZEXTLOAD:
483     return ISD::ZERO_EXTEND;
484   default:
485     break;
486   }
487 
488   llvm_unreachable("Invalid LoadExtType");
489 }
490 
491 ISD::CondCode ISD::getSetCCSwappedOperands(ISD::CondCode Operation) {
492   // To perform this operation, we just need to swap the L and G bits of the
493   // operation.
494   unsigned OldL = (Operation >> 2) & 1;
495   unsigned OldG = (Operation >> 1) & 1;
496   return ISD::CondCode((Operation & ~6) |  // Keep the N, U, E bits
497                        (OldL << 1) |       // New G bit
498                        (OldG << 2));       // New L bit.
499 }
500 
501 static ISD::CondCode getSetCCInverseImpl(ISD::CondCode Op, bool isIntegerLike) {
502   unsigned Operation = Op;
503   if (isIntegerLike)
504     Operation ^= 7;   // Flip L, G, E bits, but not U.
505   else
506     Operation ^= 15;  // Flip all of the condition bits.
507 
508   if (Operation > ISD::SETTRUE2)
509     Operation &= ~8;  // Don't let N and U bits get set.
510 
511   return ISD::CondCode(Operation);
512 }
513 
514 ISD::CondCode ISD::getSetCCInverse(ISD::CondCode Op, EVT Type) {
515   return getSetCCInverseImpl(Op, Type.isInteger());
516 }
517 
518 ISD::CondCode ISD::GlobalISel::getSetCCInverse(ISD::CondCode Op,
519                                                bool isIntegerLike) {
520   return getSetCCInverseImpl(Op, isIntegerLike);
521 }
522 
523 /// For an integer comparison, return 1 if the comparison is a signed operation
524 /// and 2 if the result is an unsigned comparison. Return zero if the operation
525 /// does not depend on the sign of the input (setne and seteq).
526 static int isSignedOp(ISD::CondCode Opcode) {
527   switch (Opcode) {
528   default: llvm_unreachable("Illegal integer setcc operation!");
529   case ISD::SETEQ:
530   case ISD::SETNE: return 0;
531   case ISD::SETLT:
532   case ISD::SETLE:
533   case ISD::SETGT:
534   case ISD::SETGE: return 1;
535   case ISD::SETULT:
536   case ISD::SETULE:
537   case ISD::SETUGT:
538   case ISD::SETUGE: return 2;
539   }
540 }
541 
542 ISD::CondCode ISD::getSetCCOrOperation(ISD::CondCode Op1, ISD::CondCode Op2,
543                                        EVT Type) {
544   bool IsInteger = Type.isInteger();
545   if (IsInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
546     // Cannot fold a signed integer setcc with an unsigned integer setcc.
547     return ISD::SETCC_INVALID;
548 
549   unsigned Op = Op1 | Op2;  // Combine all of the condition bits.
550 
551   // If the N and U bits get set, then the resultant comparison DOES suddenly
552   // care about orderedness, and it is true when ordered.
553   if (Op > ISD::SETTRUE2)
554     Op &= ~16;     // Clear the U bit if the N bit is set.
555 
556   // Canonicalize illegal integer setcc's.
557   if (IsInteger && Op == ISD::SETUNE)  // e.g. SETUGT | SETULT
558     Op = ISD::SETNE;
559 
560   return ISD::CondCode(Op);
561 }
562 
563 ISD::CondCode ISD::getSetCCAndOperation(ISD::CondCode Op1, ISD::CondCode Op2,
564                                         EVT Type) {
565   bool IsInteger = Type.isInteger();
566   if (IsInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
567     // Cannot fold a signed setcc with an unsigned setcc.
568     return ISD::SETCC_INVALID;
569 
570   // Combine all of the condition bits.
571   ISD::CondCode Result = ISD::CondCode(Op1 & Op2);
572 
573   // Canonicalize illegal integer setcc's.
574   if (IsInteger) {
575     switch (Result) {
576     default: break;
577     case ISD::SETUO : Result = ISD::SETFALSE; break;  // SETUGT & SETULT
578     case ISD::SETOEQ:                                 // SETEQ  & SETU[LG]E
579     case ISD::SETUEQ: Result = ISD::SETEQ   ; break;  // SETUGE & SETULE
580     case ISD::SETOLT: Result = ISD::SETULT  ; break;  // SETULT & SETNE
581     case ISD::SETOGT: Result = ISD::SETUGT  ; break;  // SETUGT & SETNE
582     }
583   }
584 
585   return Result;
586 }
587 
588 //===----------------------------------------------------------------------===//
589 //                           SDNode Profile Support
590 //===----------------------------------------------------------------------===//
591 
592 /// AddNodeIDOpcode - Add the node opcode to the NodeID data.
593 static void AddNodeIDOpcode(FoldingSetNodeID &ID, unsigned OpC)  {
594   ID.AddInteger(OpC);
595 }
596 
597 /// AddNodeIDValueTypes - Value type lists are intern'd so we can represent them
598 /// solely with their pointer.
599 static void AddNodeIDValueTypes(FoldingSetNodeID &ID, SDVTList VTList) {
600   ID.AddPointer(VTList.VTs);
601 }
602 
603 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data.
604 static void AddNodeIDOperands(FoldingSetNodeID &ID,
605                               ArrayRef<SDValue> Ops) {
606   for (auto& Op : Ops) {
607     ID.AddPointer(Op.getNode());
608     ID.AddInteger(Op.getResNo());
609   }
610 }
611 
612 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data.
613 static void AddNodeIDOperands(FoldingSetNodeID &ID,
614                               ArrayRef<SDUse> Ops) {
615   for (auto& Op : Ops) {
616     ID.AddPointer(Op.getNode());
617     ID.AddInteger(Op.getResNo());
618   }
619 }
620 
621 static void AddNodeIDNode(FoldingSetNodeID &ID, unsigned short OpC,
622                           SDVTList VTList, ArrayRef<SDValue> OpList) {
623   AddNodeIDOpcode(ID, OpC);
624   AddNodeIDValueTypes(ID, VTList);
625   AddNodeIDOperands(ID, OpList);
626 }
627 
628 /// If this is an SDNode with special info, add this info to the NodeID data.
629 static void AddNodeIDCustom(FoldingSetNodeID &ID, const SDNode *N) {
630   switch (N->getOpcode()) {
631   case ISD::TargetExternalSymbol:
632   case ISD::ExternalSymbol:
633   case ISD::MCSymbol:
634     llvm_unreachable("Should only be used on nodes with operands");
635   default: break;  // Normal nodes don't need extra info.
636   case ISD::TargetConstant:
637   case ISD::Constant: {
638     const ConstantSDNode *C = cast<ConstantSDNode>(N);
639     ID.AddPointer(C->getConstantIntValue());
640     ID.AddBoolean(C->isOpaque());
641     break;
642   }
643   case ISD::TargetConstantFP:
644   case ISD::ConstantFP:
645     ID.AddPointer(cast<ConstantFPSDNode>(N)->getConstantFPValue());
646     break;
647   case ISD::TargetGlobalAddress:
648   case ISD::GlobalAddress:
649   case ISD::TargetGlobalTLSAddress:
650   case ISD::GlobalTLSAddress: {
651     const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(N);
652     ID.AddPointer(GA->getGlobal());
653     ID.AddInteger(GA->getOffset());
654     ID.AddInteger(GA->getTargetFlags());
655     break;
656   }
657   case ISD::BasicBlock:
658     ID.AddPointer(cast<BasicBlockSDNode>(N)->getBasicBlock());
659     break;
660   case ISD::Register:
661     ID.AddInteger(cast<RegisterSDNode>(N)->getReg());
662     break;
663   case ISD::RegisterMask:
664     ID.AddPointer(cast<RegisterMaskSDNode>(N)->getRegMask());
665     break;
666   case ISD::SRCVALUE:
667     ID.AddPointer(cast<SrcValueSDNode>(N)->getValue());
668     break;
669   case ISD::FrameIndex:
670   case ISD::TargetFrameIndex:
671     ID.AddInteger(cast<FrameIndexSDNode>(N)->getIndex());
672     break;
673   case ISD::LIFETIME_START:
674   case ISD::LIFETIME_END:
675     if (cast<LifetimeSDNode>(N)->hasOffset()) {
676       ID.AddInteger(cast<LifetimeSDNode>(N)->getSize());
677       ID.AddInteger(cast<LifetimeSDNode>(N)->getOffset());
678     }
679     break;
680   case ISD::PSEUDO_PROBE:
681     ID.AddInteger(cast<PseudoProbeSDNode>(N)->getGuid());
682     ID.AddInteger(cast<PseudoProbeSDNode>(N)->getIndex());
683     ID.AddInteger(cast<PseudoProbeSDNode>(N)->getAttributes());
684     break;
685   case ISD::JumpTable:
686   case ISD::TargetJumpTable:
687     ID.AddInteger(cast<JumpTableSDNode>(N)->getIndex());
688     ID.AddInteger(cast<JumpTableSDNode>(N)->getTargetFlags());
689     break;
690   case ISD::ConstantPool:
691   case ISD::TargetConstantPool: {
692     const ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(N);
693     ID.AddInteger(CP->getAlign().value());
694     ID.AddInteger(CP->getOffset());
695     if (CP->isMachineConstantPoolEntry())
696       CP->getMachineCPVal()->addSelectionDAGCSEId(ID);
697     else
698       ID.AddPointer(CP->getConstVal());
699     ID.AddInteger(CP->getTargetFlags());
700     break;
701   }
702   case ISD::TargetIndex: {
703     const TargetIndexSDNode *TI = cast<TargetIndexSDNode>(N);
704     ID.AddInteger(TI->getIndex());
705     ID.AddInteger(TI->getOffset());
706     ID.AddInteger(TI->getTargetFlags());
707     break;
708   }
709   case ISD::LOAD: {
710     const LoadSDNode *LD = cast<LoadSDNode>(N);
711     ID.AddInteger(LD->getMemoryVT().getRawBits());
712     ID.AddInteger(LD->getRawSubclassData());
713     ID.AddInteger(LD->getPointerInfo().getAddrSpace());
714     ID.AddInteger(LD->getMemOperand()->getFlags());
715     break;
716   }
717   case ISD::STORE: {
718     const StoreSDNode *ST = cast<StoreSDNode>(N);
719     ID.AddInteger(ST->getMemoryVT().getRawBits());
720     ID.AddInteger(ST->getRawSubclassData());
721     ID.AddInteger(ST->getPointerInfo().getAddrSpace());
722     ID.AddInteger(ST->getMemOperand()->getFlags());
723     break;
724   }
725   case ISD::VP_LOAD: {
726     const VPLoadSDNode *ELD = cast<VPLoadSDNode>(N);
727     ID.AddInteger(ELD->getMemoryVT().getRawBits());
728     ID.AddInteger(ELD->getRawSubclassData());
729     ID.AddInteger(ELD->getPointerInfo().getAddrSpace());
730     ID.AddInteger(ELD->getMemOperand()->getFlags());
731     break;
732   }
733   case ISD::VP_STORE: {
734     const VPStoreSDNode *EST = cast<VPStoreSDNode>(N);
735     ID.AddInteger(EST->getMemoryVT().getRawBits());
736     ID.AddInteger(EST->getRawSubclassData());
737     ID.AddInteger(EST->getPointerInfo().getAddrSpace());
738     ID.AddInteger(EST->getMemOperand()->getFlags());
739     break;
740   }
741   case ISD::EXPERIMENTAL_VP_STRIDED_LOAD: {
742     const VPStridedLoadSDNode *SLD = cast<VPStridedLoadSDNode>(N);
743     ID.AddInteger(SLD->getMemoryVT().getRawBits());
744     ID.AddInteger(SLD->getRawSubclassData());
745     ID.AddInteger(SLD->getPointerInfo().getAddrSpace());
746     break;
747   }
748   case ISD::EXPERIMENTAL_VP_STRIDED_STORE: {
749     const VPStridedStoreSDNode *SST = cast<VPStridedStoreSDNode>(N);
750     ID.AddInteger(SST->getMemoryVT().getRawBits());
751     ID.AddInteger(SST->getRawSubclassData());
752     ID.AddInteger(SST->getPointerInfo().getAddrSpace());
753     break;
754   }
755   case ISD::VP_GATHER: {
756     const VPGatherSDNode *EG = cast<VPGatherSDNode>(N);
757     ID.AddInteger(EG->getMemoryVT().getRawBits());
758     ID.AddInteger(EG->getRawSubclassData());
759     ID.AddInteger(EG->getPointerInfo().getAddrSpace());
760     ID.AddInteger(EG->getMemOperand()->getFlags());
761     break;
762   }
763   case ISD::VP_SCATTER: {
764     const VPScatterSDNode *ES = cast<VPScatterSDNode>(N);
765     ID.AddInteger(ES->getMemoryVT().getRawBits());
766     ID.AddInteger(ES->getRawSubclassData());
767     ID.AddInteger(ES->getPointerInfo().getAddrSpace());
768     ID.AddInteger(ES->getMemOperand()->getFlags());
769     break;
770   }
771   case ISD::MLOAD: {
772     const MaskedLoadSDNode *MLD = cast<MaskedLoadSDNode>(N);
773     ID.AddInteger(MLD->getMemoryVT().getRawBits());
774     ID.AddInteger(MLD->getRawSubclassData());
775     ID.AddInteger(MLD->getPointerInfo().getAddrSpace());
776     ID.AddInteger(MLD->getMemOperand()->getFlags());
777     break;
778   }
779   case ISD::MSTORE: {
780     const MaskedStoreSDNode *MST = cast<MaskedStoreSDNode>(N);
781     ID.AddInteger(MST->getMemoryVT().getRawBits());
782     ID.AddInteger(MST->getRawSubclassData());
783     ID.AddInteger(MST->getPointerInfo().getAddrSpace());
784     ID.AddInteger(MST->getMemOperand()->getFlags());
785     break;
786   }
787   case ISD::MGATHER: {
788     const MaskedGatherSDNode *MG = cast<MaskedGatherSDNode>(N);
789     ID.AddInteger(MG->getMemoryVT().getRawBits());
790     ID.AddInteger(MG->getRawSubclassData());
791     ID.AddInteger(MG->getPointerInfo().getAddrSpace());
792     ID.AddInteger(MG->getMemOperand()->getFlags());
793     break;
794   }
795   case ISD::MSCATTER: {
796     const MaskedScatterSDNode *MS = cast<MaskedScatterSDNode>(N);
797     ID.AddInteger(MS->getMemoryVT().getRawBits());
798     ID.AddInteger(MS->getRawSubclassData());
799     ID.AddInteger(MS->getPointerInfo().getAddrSpace());
800     ID.AddInteger(MS->getMemOperand()->getFlags());
801     break;
802   }
803   case ISD::ATOMIC_CMP_SWAP:
804   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
805   case ISD::ATOMIC_SWAP:
806   case ISD::ATOMIC_LOAD_ADD:
807   case ISD::ATOMIC_LOAD_SUB:
808   case ISD::ATOMIC_LOAD_AND:
809   case ISD::ATOMIC_LOAD_CLR:
810   case ISD::ATOMIC_LOAD_OR:
811   case ISD::ATOMIC_LOAD_XOR:
812   case ISD::ATOMIC_LOAD_NAND:
813   case ISD::ATOMIC_LOAD_MIN:
814   case ISD::ATOMIC_LOAD_MAX:
815   case ISD::ATOMIC_LOAD_UMIN:
816   case ISD::ATOMIC_LOAD_UMAX:
817   case ISD::ATOMIC_LOAD:
818   case ISD::ATOMIC_STORE: {
819     const AtomicSDNode *AT = cast<AtomicSDNode>(N);
820     ID.AddInteger(AT->getMemoryVT().getRawBits());
821     ID.AddInteger(AT->getRawSubclassData());
822     ID.AddInteger(AT->getPointerInfo().getAddrSpace());
823     ID.AddInteger(AT->getMemOperand()->getFlags());
824     break;
825   }
826   case ISD::PREFETCH: {
827     const MemSDNode *PF = cast<MemSDNode>(N);
828     ID.AddInteger(PF->getPointerInfo().getAddrSpace());
829     ID.AddInteger(PF->getMemOperand()->getFlags());
830     break;
831   }
832   case ISD::VECTOR_SHUFFLE: {
833     const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
834     for (unsigned i = 0, e = N->getValueType(0).getVectorNumElements();
835          i != e; ++i)
836       ID.AddInteger(SVN->getMaskElt(i));
837     break;
838   }
839   case ISD::TargetBlockAddress:
840   case ISD::BlockAddress: {
841     const BlockAddressSDNode *BA = cast<BlockAddressSDNode>(N);
842     ID.AddPointer(BA->getBlockAddress());
843     ID.AddInteger(BA->getOffset());
844     ID.AddInteger(BA->getTargetFlags());
845     break;
846   }
847   case ISD::AssertAlign:
848     ID.AddInteger(cast<AssertAlignSDNode>(N)->getAlign().value());
849     break;
850   } // end switch (N->getOpcode())
851 
852   // Target specific memory nodes could also have address spaces and flags
853   // to check.
854   if (N->isTargetMemoryOpcode()) {
855     const MemSDNode *MN = cast<MemSDNode>(N);
856     ID.AddInteger(MN->getPointerInfo().getAddrSpace());
857     ID.AddInteger(MN->getMemOperand()->getFlags());
858   }
859 }
860 
861 /// AddNodeIDNode - Generic routine for adding a nodes info to the NodeID
862 /// data.
863 static void AddNodeIDNode(FoldingSetNodeID &ID, const SDNode *N) {
864   AddNodeIDOpcode(ID, N->getOpcode());
865   // Add the return value info.
866   AddNodeIDValueTypes(ID, N->getVTList());
867   // Add the operand info.
868   AddNodeIDOperands(ID, N->ops());
869 
870   // Handle SDNode leafs with special info.
871   AddNodeIDCustom(ID, N);
872 }
873 
874 //===----------------------------------------------------------------------===//
875 //                              SelectionDAG Class
876 //===----------------------------------------------------------------------===//
877 
878 /// doNotCSE - Return true if CSE should not be performed for this node.
879 static bool doNotCSE(SDNode *N) {
880   if (N->getValueType(0) == MVT::Glue)
881     return true; // Never CSE anything that produces a flag.
882 
883   switch (N->getOpcode()) {
884   default: break;
885   case ISD::HANDLENODE:
886   case ISD::EH_LABEL:
887     return true;   // Never CSE these nodes.
888   }
889 
890   // Check that remaining values produced are not flags.
891   for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
892     if (N->getValueType(i) == MVT::Glue)
893       return true; // Never CSE anything that produces a flag.
894 
895   return false;
896 }
897 
898 /// RemoveDeadNodes - This method deletes all unreachable nodes in the
899 /// SelectionDAG.
900 void SelectionDAG::RemoveDeadNodes() {
901   // Create a dummy node (which is not added to allnodes), that adds a reference
902   // to the root node, preventing it from being deleted.
903   HandleSDNode Dummy(getRoot());
904 
905   SmallVector<SDNode*, 128> DeadNodes;
906 
907   // Add all obviously-dead nodes to the DeadNodes worklist.
908   for (SDNode &Node : allnodes())
909     if (Node.use_empty())
910       DeadNodes.push_back(&Node);
911 
912   RemoveDeadNodes(DeadNodes);
913 
914   // If the root changed (e.g. it was a dead load, update the root).
915   setRoot(Dummy.getValue());
916 }
917 
918 /// RemoveDeadNodes - This method deletes the unreachable nodes in the
919 /// given list, and any nodes that become unreachable as a result.
920 void SelectionDAG::RemoveDeadNodes(SmallVectorImpl<SDNode *> &DeadNodes) {
921 
922   // Process the worklist, deleting the nodes and adding their uses to the
923   // worklist.
924   while (!DeadNodes.empty()) {
925     SDNode *N = DeadNodes.pop_back_val();
926     // Skip to next node if we've already managed to delete the node. This could
927     // happen if replacing a node causes a node previously added to the node to
928     // be deleted.
929     if (N->getOpcode() == ISD::DELETED_NODE)
930       continue;
931 
932     for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
933       DUL->NodeDeleted(N, nullptr);
934 
935     // Take the node out of the appropriate CSE map.
936     RemoveNodeFromCSEMaps(N);
937 
938     // Next, brutally remove the operand list.  This is safe to do, as there are
939     // no cycles in the graph.
940     for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) {
941       SDUse &Use = *I++;
942       SDNode *Operand = Use.getNode();
943       Use.set(SDValue());
944 
945       // Now that we removed this operand, see if there are no uses of it left.
946       if (Operand->use_empty())
947         DeadNodes.push_back(Operand);
948     }
949 
950     DeallocateNode(N);
951   }
952 }
953 
954 void SelectionDAG::RemoveDeadNode(SDNode *N){
955   SmallVector<SDNode*, 16> DeadNodes(1, N);
956 
957   // Create a dummy node that adds a reference to the root node, preventing
958   // it from being deleted.  (This matters if the root is an operand of the
959   // dead node.)
960   HandleSDNode Dummy(getRoot());
961 
962   RemoveDeadNodes(DeadNodes);
963 }
964 
965 void SelectionDAG::DeleteNode(SDNode *N) {
966   // First take this out of the appropriate CSE map.
967   RemoveNodeFromCSEMaps(N);
968 
969   // Finally, remove uses due to operands of this node, remove from the
970   // AllNodes list, and delete the node.
971   DeleteNodeNotInCSEMaps(N);
972 }
973 
974 void SelectionDAG::DeleteNodeNotInCSEMaps(SDNode *N) {
975   assert(N->getIterator() != AllNodes.begin() &&
976          "Cannot delete the entry node!");
977   assert(N->use_empty() && "Cannot delete a node that is not dead!");
978 
979   // Drop all of the operands and decrement used node's use counts.
980   N->DropOperands();
981 
982   DeallocateNode(N);
983 }
984 
985 void SDDbgInfo::add(SDDbgValue *V, bool isParameter) {
986   assert(!(V->isVariadic() && isParameter));
987   if (isParameter)
988     ByvalParmDbgValues.push_back(V);
989   else
990     DbgValues.push_back(V);
991   for (const SDNode *Node : V->getSDNodes())
992     if (Node)
993       DbgValMap[Node].push_back(V);
994 }
995 
996 void SDDbgInfo::erase(const SDNode *Node) {
997   DbgValMapType::iterator I = DbgValMap.find(Node);
998   if (I == DbgValMap.end())
999     return;
1000   for (auto &Val: I->second)
1001     Val->setIsInvalidated();
1002   DbgValMap.erase(I);
1003 }
1004 
1005 void SelectionDAG::DeallocateNode(SDNode *N) {
1006   // If we have operands, deallocate them.
1007   removeOperands(N);
1008 
1009   NodeAllocator.Deallocate(AllNodes.remove(N));
1010 
1011   // Set the opcode to DELETED_NODE to help catch bugs when node
1012   // memory is reallocated.
1013   // FIXME: There are places in SDag that have grown a dependency on the opcode
1014   // value in the released node.
1015   __asan_unpoison_memory_region(&N->NodeType, sizeof(N->NodeType));
1016   N->NodeType = ISD::DELETED_NODE;
1017 
1018   // If any of the SDDbgValue nodes refer to this SDNode, invalidate
1019   // them and forget about that node.
1020   DbgInfo->erase(N);
1021 }
1022 
1023 #ifndef NDEBUG
1024 /// VerifySDNode - Check the given SDNode.  Aborts if it is invalid.
1025 static void VerifySDNode(SDNode *N) {
1026   switch (N->getOpcode()) {
1027   default:
1028     break;
1029   case ISD::BUILD_PAIR: {
1030     EVT VT = N->getValueType(0);
1031     assert(N->getNumValues() == 1 && "Too many results!");
1032     assert(!VT.isVector() && (VT.isInteger() || VT.isFloatingPoint()) &&
1033            "Wrong return type!");
1034     assert(N->getNumOperands() == 2 && "Wrong number of operands!");
1035     assert(N->getOperand(0).getValueType() == N->getOperand(1).getValueType() &&
1036            "Mismatched operand types!");
1037     assert(N->getOperand(0).getValueType().isInteger() == VT.isInteger() &&
1038            "Wrong operand type!");
1039     assert(VT.getSizeInBits() == 2 * N->getOperand(0).getValueSizeInBits() &&
1040            "Wrong return type size");
1041     break;
1042   }
1043   case ISD::BUILD_VECTOR: {
1044     assert(N->getNumValues() == 1 && "Too many results!");
1045     assert(N->getValueType(0).isVector() && "Wrong return type!");
1046     assert(N->getNumOperands() == N->getValueType(0).getVectorNumElements() &&
1047            "Wrong number of operands!");
1048     EVT EltVT = N->getValueType(0).getVectorElementType();
1049     for (const SDUse &Op : N->ops()) {
1050       assert((Op.getValueType() == EltVT ||
1051               (EltVT.isInteger() && Op.getValueType().isInteger() &&
1052                EltVT.bitsLE(Op.getValueType()))) &&
1053              "Wrong operand type!");
1054       assert(Op.getValueType() == N->getOperand(0).getValueType() &&
1055              "Operands must all have the same type");
1056     }
1057     break;
1058   }
1059   }
1060 }
1061 #endif // NDEBUG
1062 
1063 /// Insert a newly allocated node into the DAG.
1064 ///
1065 /// Handles insertion into the all nodes list and CSE map, as well as
1066 /// verification and other common operations when a new node is allocated.
1067 void SelectionDAG::InsertNode(SDNode *N) {
1068   AllNodes.push_back(N);
1069 #ifndef NDEBUG
1070   N->PersistentId = NextPersistentId++;
1071   VerifySDNode(N);
1072 #endif
1073   for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
1074     DUL->NodeInserted(N);
1075 }
1076 
1077 /// RemoveNodeFromCSEMaps - Take the specified node out of the CSE map that
1078 /// correspond to it.  This is useful when we're about to delete or repurpose
1079 /// the node.  We don't want future request for structurally identical nodes
1080 /// to return N anymore.
1081 bool SelectionDAG::RemoveNodeFromCSEMaps(SDNode *N) {
1082   bool Erased = false;
1083   switch (N->getOpcode()) {
1084   case ISD::HANDLENODE: return false;  // noop.
1085   case ISD::CONDCODE:
1086     assert(CondCodeNodes[cast<CondCodeSDNode>(N)->get()] &&
1087            "Cond code doesn't exist!");
1088     Erased = CondCodeNodes[cast<CondCodeSDNode>(N)->get()] != nullptr;
1089     CondCodeNodes[cast<CondCodeSDNode>(N)->get()] = nullptr;
1090     break;
1091   case ISD::ExternalSymbol:
1092     Erased = ExternalSymbols.erase(cast<ExternalSymbolSDNode>(N)->getSymbol());
1093     break;
1094   case ISD::TargetExternalSymbol: {
1095     ExternalSymbolSDNode *ESN = cast<ExternalSymbolSDNode>(N);
1096     Erased = TargetExternalSymbols.erase(std::pair<std::string, unsigned>(
1097         ESN->getSymbol(), ESN->getTargetFlags()));
1098     break;
1099   }
1100   case ISD::MCSymbol: {
1101     auto *MCSN = cast<MCSymbolSDNode>(N);
1102     Erased = MCSymbols.erase(MCSN->getMCSymbol());
1103     break;
1104   }
1105   case ISD::VALUETYPE: {
1106     EVT VT = cast<VTSDNode>(N)->getVT();
1107     if (VT.isExtended()) {
1108       Erased = ExtendedValueTypeNodes.erase(VT);
1109     } else {
1110       Erased = ValueTypeNodes[VT.getSimpleVT().SimpleTy] != nullptr;
1111       ValueTypeNodes[VT.getSimpleVT().SimpleTy] = nullptr;
1112     }
1113     break;
1114   }
1115   default:
1116     // Remove it from the CSE Map.
1117     assert(N->getOpcode() != ISD::DELETED_NODE && "DELETED_NODE in CSEMap!");
1118     assert(N->getOpcode() != ISD::EntryToken && "EntryToken in CSEMap!");
1119     Erased = CSEMap.RemoveNode(N);
1120     break;
1121   }
1122 #ifndef NDEBUG
1123   // Verify that the node was actually in one of the CSE maps, unless it has a
1124   // flag result (which cannot be CSE'd) or is one of the special cases that are
1125   // not subject to CSE.
1126   if (!Erased && N->getValueType(N->getNumValues()-1) != MVT::Glue &&
1127       !N->isMachineOpcode() && !doNotCSE(N)) {
1128     N->dump(this);
1129     dbgs() << "\n";
1130     llvm_unreachable("Node is not in map!");
1131   }
1132 #endif
1133   return Erased;
1134 }
1135 
1136 /// AddModifiedNodeToCSEMaps - The specified node has been removed from the CSE
1137 /// maps and modified in place. Add it back to the CSE maps, unless an identical
1138 /// node already exists, in which case transfer all its users to the existing
1139 /// node. This transfer can potentially trigger recursive merging.
1140 void
1141 SelectionDAG::AddModifiedNodeToCSEMaps(SDNode *N) {
1142   // For node types that aren't CSE'd, just act as if no identical node
1143   // already exists.
1144   if (!doNotCSE(N)) {
1145     SDNode *Existing = CSEMap.GetOrInsertNode(N);
1146     if (Existing != N) {
1147       // If there was already an existing matching node, use ReplaceAllUsesWith
1148       // to replace the dead one with the existing one.  This can cause
1149       // recursive merging of other unrelated nodes down the line.
1150       ReplaceAllUsesWith(N, Existing);
1151 
1152       // N is now dead. Inform the listeners and delete it.
1153       for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
1154         DUL->NodeDeleted(N, Existing);
1155       DeleteNodeNotInCSEMaps(N);
1156       return;
1157     }
1158   }
1159 
1160   // If the node doesn't already exist, we updated it.  Inform listeners.
1161   for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
1162     DUL->NodeUpdated(N);
1163 }
1164 
1165 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
1166 /// were replaced with those specified.  If this node is never memoized,
1167 /// return null, otherwise return a pointer to the slot it would take.  If a
1168 /// node already exists with these operands, the slot will be non-null.
1169 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, SDValue Op,
1170                                            void *&InsertPos) {
1171   if (doNotCSE(N))
1172     return nullptr;
1173 
1174   SDValue Ops[] = { Op };
1175   FoldingSetNodeID ID;
1176   AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops);
1177   AddNodeIDCustom(ID, N);
1178   SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos);
1179   if (Node)
1180     Node->intersectFlagsWith(N->getFlags());
1181   return Node;
1182 }
1183 
1184 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
1185 /// were replaced with those specified.  If this node is never memoized,
1186 /// return null, otherwise return a pointer to the slot it would take.  If a
1187 /// node already exists with these operands, the slot will be non-null.
1188 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N,
1189                                            SDValue Op1, SDValue Op2,
1190                                            void *&InsertPos) {
1191   if (doNotCSE(N))
1192     return nullptr;
1193 
1194   SDValue Ops[] = { Op1, Op2 };
1195   FoldingSetNodeID ID;
1196   AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops);
1197   AddNodeIDCustom(ID, N);
1198   SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos);
1199   if (Node)
1200     Node->intersectFlagsWith(N->getFlags());
1201   return Node;
1202 }
1203 
1204 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
1205 /// were replaced with those specified.  If this node is never memoized,
1206 /// return null, otherwise return a pointer to the slot it would take.  If a
1207 /// node already exists with these operands, the slot will be non-null.
1208 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, ArrayRef<SDValue> Ops,
1209                                            void *&InsertPos) {
1210   if (doNotCSE(N))
1211     return nullptr;
1212 
1213   FoldingSetNodeID ID;
1214   AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops);
1215   AddNodeIDCustom(ID, N);
1216   SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos);
1217   if (Node)
1218     Node->intersectFlagsWith(N->getFlags());
1219   return Node;
1220 }
1221 
1222 Align SelectionDAG::getEVTAlign(EVT VT) const {
1223   Type *Ty = VT == MVT::iPTR ?
1224                    PointerType::get(Type::getInt8Ty(*getContext()), 0) :
1225                    VT.getTypeForEVT(*getContext());
1226 
1227   return getDataLayout().getABITypeAlign(Ty);
1228 }
1229 
1230 // EntryNode could meaningfully have debug info if we can find it...
1231 SelectionDAG::SelectionDAG(const TargetMachine &tm, CodeGenOpt::Level OL)
1232     : TM(tm), OptLevel(OL),
1233       EntryNode(ISD::EntryToken, 0, DebugLoc(), getVTList(MVT::Other)),
1234       Root(getEntryNode()) {
1235   InsertNode(&EntryNode);
1236   DbgInfo = new SDDbgInfo();
1237 }
1238 
1239 void SelectionDAG::init(MachineFunction &NewMF,
1240                         OptimizationRemarkEmitter &NewORE,
1241                         Pass *PassPtr, const TargetLibraryInfo *LibraryInfo,
1242                         LegacyDivergenceAnalysis * Divergence,
1243                         ProfileSummaryInfo *PSIin,
1244                         BlockFrequencyInfo *BFIin) {
1245   MF = &NewMF;
1246   SDAGISelPass = PassPtr;
1247   ORE = &NewORE;
1248   TLI = getSubtarget().getTargetLowering();
1249   TSI = getSubtarget().getSelectionDAGInfo();
1250   LibInfo = LibraryInfo;
1251   Context = &MF->getFunction().getContext();
1252   DA = Divergence;
1253   PSI = PSIin;
1254   BFI = BFIin;
1255 }
1256 
1257 SelectionDAG::~SelectionDAG() {
1258   assert(!UpdateListeners && "Dangling registered DAGUpdateListeners");
1259   allnodes_clear();
1260   OperandRecycler.clear(OperandAllocator);
1261   delete DbgInfo;
1262 }
1263 
1264 bool SelectionDAG::shouldOptForSize() const {
1265   return MF->getFunction().hasOptSize() ||
1266       llvm::shouldOptimizeForSize(FLI->MBB->getBasicBlock(), PSI, BFI);
1267 }
1268 
1269 void SelectionDAG::allnodes_clear() {
1270   assert(&*AllNodes.begin() == &EntryNode);
1271   AllNodes.remove(AllNodes.begin());
1272   while (!AllNodes.empty())
1273     DeallocateNode(&AllNodes.front());
1274 #ifndef NDEBUG
1275   NextPersistentId = 0;
1276 #endif
1277 }
1278 
1279 SDNode *SelectionDAG::FindNodeOrInsertPos(const FoldingSetNodeID &ID,
1280                                           void *&InsertPos) {
1281   SDNode *N = CSEMap.FindNodeOrInsertPos(ID, InsertPos);
1282   if (N) {
1283     switch (N->getOpcode()) {
1284     default: break;
1285     case ISD::Constant:
1286     case ISD::ConstantFP:
1287       llvm_unreachable("Querying for Constant and ConstantFP nodes requires "
1288                        "debug location.  Use another overload.");
1289     }
1290   }
1291   return N;
1292 }
1293 
1294 SDNode *SelectionDAG::FindNodeOrInsertPos(const FoldingSetNodeID &ID,
1295                                           const SDLoc &DL, void *&InsertPos) {
1296   SDNode *N = CSEMap.FindNodeOrInsertPos(ID, InsertPos);
1297   if (N) {
1298     switch (N->getOpcode()) {
1299     case ISD::Constant:
1300     case ISD::ConstantFP:
1301       // Erase debug location from the node if the node is used at several
1302       // different places. Do not propagate one location to all uses as it
1303       // will cause a worse single stepping debugging experience.
1304       if (N->getDebugLoc() != DL.getDebugLoc())
1305         N->setDebugLoc(DebugLoc());
1306       break;
1307     default:
1308       // When the node's point of use is located earlier in the instruction
1309       // sequence than its prior point of use, update its debug info to the
1310       // earlier location.
1311       if (DL.getIROrder() && DL.getIROrder() < N->getIROrder())
1312         N->setDebugLoc(DL.getDebugLoc());
1313       break;
1314     }
1315   }
1316   return N;
1317 }
1318 
1319 void SelectionDAG::clear() {
1320   allnodes_clear();
1321   OperandRecycler.clear(OperandAllocator);
1322   OperandAllocator.Reset();
1323   CSEMap.clear();
1324 
1325   ExtendedValueTypeNodes.clear();
1326   ExternalSymbols.clear();
1327   TargetExternalSymbols.clear();
1328   MCSymbols.clear();
1329   SDCallSiteDbgInfo.clear();
1330   std::fill(CondCodeNodes.begin(), CondCodeNodes.end(),
1331             static_cast<CondCodeSDNode*>(nullptr));
1332   std::fill(ValueTypeNodes.begin(), ValueTypeNodes.end(),
1333             static_cast<SDNode*>(nullptr));
1334 
1335   EntryNode.UseList = nullptr;
1336   InsertNode(&EntryNode);
1337   Root = getEntryNode();
1338   DbgInfo->clear();
1339 }
1340 
1341 SDValue SelectionDAG::getFPExtendOrRound(SDValue Op, const SDLoc &DL, EVT VT) {
1342   return VT.bitsGT(Op.getValueType())
1343              ? getNode(ISD::FP_EXTEND, DL, VT, Op)
1344              : getNode(ISD::FP_ROUND, DL, VT, Op, getIntPtrConstant(0, DL));
1345 }
1346 
1347 std::pair<SDValue, SDValue>
1348 SelectionDAG::getStrictFPExtendOrRound(SDValue Op, SDValue Chain,
1349                                        const SDLoc &DL, EVT VT) {
1350   assert(!VT.bitsEq(Op.getValueType()) &&
1351          "Strict no-op FP extend/round not allowed.");
1352   SDValue Res =
1353       VT.bitsGT(Op.getValueType())
1354           ? getNode(ISD::STRICT_FP_EXTEND, DL, {VT, MVT::Other}, {Chain, Op})
1355           : getNode(ISD::STRICT_FP_ROUND, DL, {VT, MVT::Other},
1356                     {Chain, Op, getIntPtrConstant(0, DL)});
1357 
1358   return std::pair<SDValue, SDValue>(Res, SDValue(Res.getNode(), 1));
1359 }
1360 
1361 SDValue SelectionDAG::getAnyExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
1362   return VT.bitsGT(Op.getValueType()) ?
1363     getNode(ISD::ANY_EXTEND, DL, VT, Op) :
1364     getNode(ISD::TRUNCATE, DL, VT, Op);
1365 }
1366 
1367 SDValue SelectionDAG::getSExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
1368   return VT.bitsGT(Op.getValueType()) ?
1369     getNode(ISD::SIGN_EXTEND, DL, VT, Op) :
1370     getNode(ISD::TRUNCATE, DL, VT, Op);
1371 }
1372 
1373 SDValue SelectionDAG::getZExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
1374   return VT.bitsGT(Op.getValueType()) ?
1375     getNode(ISD::ZERO_EXTEND, DL, VT, Op) :
1376     getNode(ISD::TRUNCATE, DL, VT, Op);
1377 }
1378 
1379 SDValue SelectionDAG::getBoolExtOrTrunc(SDValue Op, const SDLoc &SL, EVT VT,
1380                                         EVT OpVT) {
1381   if (VT.bitsLE(Op.getValueType()))
1382     return getNode(ISD::TRUNCATE, SL, VT, Op);
1383 
1384   TargetLowering::BooleanContent BType = TLI->getBooleanContents(OpVT);
1385   return getNode(TLI->getExtendForContent(BType), SL, VT, Op);
1386 }
1387 
1388 SDValue SelectionDAG::getZeroExtendInReg(SDValue Op, const SDLoc &DL, EVT VT) {
1389   EVT OpVT = Op.getValueType();
1390   assert(VT.isInteger() && OpVT.isInteger() &&
1391          "Cannot getZeroExtendInReg FP types");
1392   assert(VT.isVector() == OpVT.isVector() &&
1393          "getZeroExtendInReg type should be vector iff the operand "
1394          "type is vector!");
1395   assert((!VT.isVector() ||
1396           VT.getVectorElementCount() == OpVT.getVectorElementCount()) &&
1397          "Vector element counts must match in getZeroExtendInReg");
1398   assert(VT.bitsLE(OpVT) && "Not extending!");
1399   if (OpVT == VT)
1400     return Op;
1401   APInt Imm = APInt::getLowBitsSet(OpVT.getScalarSizeInBits(),
1402                                    VT.getScalarSizeInBits());
1403   return getNode(ISD::AND, DL, OpVT, Op, getConstant(Imm, DL, OpVT));
1404 }
1405 
1406 SDValue SelectionDAG::getPtrExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
1407   // Only unsigned pointer semantics are supported right now. In the future this
1408   // might delegate to TLI to check pointer signedness.
1409   return getZExtOrTrunc(Op, DL, VT);
1410 }
1411 
1412 SDValue SelectionDAG::getPtrExtendInReg(SDValue Op, const SDLoc &DL, EVT VT) {
1413   // Only unsigned pointer semantics are supported right now. In the future this
1414   // might delegate to TLI to check pointer signedness.
1415   return getZeroExtendInReg(Op, DL, VT);
1416 }
1417 
1418 /// getNOT - Create a bitwise NOT operation as (XOR Val, -1).
1419 SDValue SelectionDAG::getNOT(const SDLoc &DL, SDValue Val, EVT VT) {
1420   return getNode(ISD::XOR, DL, VT, Val, getAllOnesConstant(DL, VT));
1421 }
1422 
1423 SDValue SelectionDAG::getLogicalNOT(const SDLoc &DL, SDValue Val, EVT VT) {
1424   SDValue TrueValue = getBoolConstant(true, DL, VT, VT);
1425   return getNode(ISD::XOR, DL, VT, Val, TrueValue);
1426 }
1427 
1428 SDValue SelectionDAG::getVPLogicalNOT(const SDLoc &DL, SDValue Val,
1429                                       SDValue Mask, SDValue EVL, EVT VT) {
1430   SDValue TrueValue = getBoolConstant(true, DL, VT, VT);
1431   return getNode(ISD::VP_XOR, DL, VT, Val, TrueValue, Mask, EVL);
1432 }
1433 
1434 SDValue SelectionDAG::getBoolConstant(bool V, const SDLoc &DL, EVT VT,
1435                                       EVT OpVT) {
1436   if (!V)
1437     return getConstant(0, DL, VT);
1438 
1439   switch (TLI->getBooleanContents(OpVT)) {
1440   case TargetLowering::ZeroOrOneBooleanContent:
1441   case TargetLowering::UndefinedBooleanContent:
1442     return getConstant(1, DL, VT);
1443   case TargetLowering::ZeroOrNegativeOneBooleanContent:
1444     return getAllOnesConstant(DL, VT);
1445   }
1446   llvm_unreachable("Unexpected boolean content enum!");
1447 }
1448 
1449 SDValue SelectionDAG::getConstant(uint64_t Val, const SDLoc &DL, EVT VT,
1450                                   bool isT, bool isO) {
1451   EVT EltVT = VT.getScalarType();
1452   assert((EltVT.getSizeInBits() >= 64 ||
1453           (uint64_t)((int64_t)Val >> EltVT.getSizeInBits()) + 1 < 2) &&
1454          "getConstant with a uint64_t value that doesn't fit in the type!");
1455   return getConstant(APInt(EltVT.getSizeInBits(), Val), DL, VT, isT, isO);
1456 }
1457 
1458 SDValue SelectionDAG::getConstant(const APInt &Val, const SDLoc &DL, EVT VT,
1459                                   bool isT, bool isO) {
1460   return getConstant(*ConstantInt::get(*Context, Val), DL, VT, isT, isO);
1461 }
1462 
1463 SDValue SelectionDAG::getConstant(const ConstantInt &Val, const SDLoc &DL,
1464                                   EVT VT, bool isT, bool isO) {
1465   assert(VT.isInteger() && "Cannot create FP integer constant!");
1466 
1467   EVT EltVT = VT.getScalarType();
1468   const ConstantInt *Elt = &Val;
1469 
1470   // In some cases the vector type is legal but the element type is illegal and
1471   // needs to be promoted, for example v8i8 on ARM.  In this case, promote the
1472   // inserted value (the type does not need to match the vector element type).
1473   // Any extra bits introduced will be truncated away.
1474   if (VT.isVector() && TLI->getTypeAction(*getContext(), EltVT) ==
1475                            TargetLowering::TypePromoteInteger) {
1476     EltVT = TLI->getTypeToTransformTo(*getContext(), EltVT);
1477     APInt NewVal = Elt->getValue().zextOrTrunc(EltVT.getSizeInBits());
1478     Elt = ConstantInt::get(*getContext(), NewVal);
1479   }
1480   // In other cases the element type is illegal and needs to be expanded, for
1481   // example v2i64 on MIPS32. In this case, find the nearest legal type, split
1482   // the value into n parts and use a vector type with n-times the elements.
1483   // Then bitcast to the type requested.
1484   // Legalizing constants too early makes the DAGCombiner's job harder so we
1485   // only legalize if the DAG tells us we must produce legal types.
1486   else if (NewNodesMustHaveLegalTypes && VT.isVector() &&
1487            TLI->getTypeAction(*getContext(), EltVT) ==
1488                TargetLowering::TypeExpandInteger) {
1489     const APInt &NewVal = Elt->getValue();
1490     EVT ViaEltVT = TLI->getTypeToTransformTo(*getContext(), EltVT);
1491     unsigned ViaEltSizeInBits = ViaEltVT.getSizeInBits();
1492 
1493     // For scalable vectors, try to use a SPLAT_VECTOR_PARTS node.
1494     if (VT.isScalableVector()) {
1495       assert(EltVT.getSizeInBits() % ViaEltSizeInBits == 0 &&
1496              "Can only handle an even split!");
1497       unsigned Parts = EltVT.getSizeInBits() / ViaEltSizeInBits;
1498 
1499       SmallVector<SDValue, 2> ScalarParts;
1500       for (unsigned i = 0; i != Parts; ++i)
1501         ScalarParts.push_back(getConstant(
1502             NewVal.extractBits(ViaEltSizeInBits, i * ViaEltSizeInBits), DL,
1503             ViaEltVT, isT, isO));
1504 
1505       return getNode(ISD::SPLAT_VECTOR_PARTS, DL, VT, ScalarParts);
1506     }
1507 
1508     unsigned ViaVecNumElts = VT.getSizeInBits() / ViaEltSizeInBits;
1509     EVT ViaVecVT = EVT::getVectorVT(*getContext(), ViaEltVT, ViaVecNumElts);
1510 
1511     // Check the temporary vector is the correct size. If this fails then
1512     // getTypeToTransformTo() probably returned a type whose size (in bits)
1513     // isn't a power-of-2 factor of the requested type size.
1514     assert(ViaVecVT.getSizeInBits() == VT.getSizeInBits());
1515 
1516     SmallVector<SDValue, 2> EltParts;
1517     for (unsigned i = 0; i < ViaVecNumElts / VT.getVectorNumElements(); ++i)
1518       EltParts.push_back(getConstant(
1519           NewVal.extractBits(ViaEltSizeInBits, i * ViaEltSizeInBits), DL,
1520           ViaEltVT, isT, isO));
1521 
1522     // EltParts is currently in little endian order. If we actually want
1523     // big-endian order then reverse it now.
1524     if (getDataLayout().isBigEndian())
1525       std::reverse(EltParts.begin(), EltParts.end());
1526 
1527     // The elements must be reversed when the element order is different
1528     // to the endianness of the elements (because the BITCAST is itself a
1529     // vector shuffle in this situation). However, we do not need any code to
1530     // perform this reversal because getConstant() is producing a vector
1531     // splat.
1532     // This situation occurs in MIPS MSA.
1533 
1534     SmallVector<SDValue, 8> Ops;
1535     for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
1536       llvm::append_range(Ops, EltParts);
1537 
1538     SDValue V =
1539         getNode(ISD::BITCAST, DL, VT, getBuildVector(ViaVecVT, DL, Ops));
1540     return V;
1541   }
1542 
1543   assert(Elt->getBitWidth() == EltVT.getSizeInBits() &&
1544          "APInt size does not match type size!");
1545   unsigned Opc = isT ? ISD::TargetConstant : ISD::Constant;
1546   FoldingSetNodeID ID;
1547   AddNodeIDNode(ID, Opc, getVTList(EltVT), None);
1548   ID.AddPointer(Elt);
1549   ID.AddBoolean(isO);
1550   void *IP = nullptr;
1551   SDNode *N = nullptr;
1552   if ((N = FindNodeOrInsertPos(ID, DL, IP)))
1553     if (!VT.isVector())
1554       return SDValue(N, 0);
1555 
1556   if (!N) {
1557     N = newSDNode<ConstantSDNode>(isT, isO, Elt, EltVT);
1558     CSEMap.InsertNode(N, IP);
1559     InsertNode(N);
1560     NewSDValueDbgMsg(SDValue(N, 0), "Creating constant: ", this);
1561   }
1562 
1563   SDValue Result(N, 0);
1564   if (VT.isScalableVector())
1565     Result = getSplatVector(VT, DL, Result);
1566   else if (VT.isVector())
1567     Result = getSplatBuildVector(VT, DL, Result);
1568 
1569   return Result;
1570 }
1571 
1572 SDValue SelectionDAG::getIntPtrConstant(uint64_t Val, const SDLoc &DL,
1573                                         bool isTarget) {
1574   return getConstant(Val, DL, TLI->getPointerTy(getDataLayout()), isTarget);
1575 }
1576 
1577 SDValue SelectionDAG::getShiftAmountConstant(uint64_t Val, EVT VT,
1578                                              const SDLoc &DL, bool LegalTypes) {
1579   assert(VT.isInteger() && "Shift amount is not an integer type!");
1580   EVT ShiftVT = TLI->getShiftAmountTy(VT, getDataLayout(), LegalTypes);
1581   return getConstant(Val, DL, ShiftVT);
1582 }
1583 
1584 SDValue SelectionDAG::getVectorIdxConstant(uint64_t Val, const SDLoc &DL,
1585                                            bool isTarget) {
1586   return getConstant(Val, DL, TLI->getVectorIdxTy(getDataLayout()), isTarget);
1587 }
1588 
1589 SDValue SelectionDAG::getConstantFP(const APFloat &V, const SDLoc &DL, EVT VT,
1590                                     bool isTarget) {
1591   return getConstantFP(*ConstantFP::get(*getContext(), V), DL, VT, isTarget);
1592 }
1593 
1594 SDValue SelectionDAG::getConstantFP(const ConstantFP &V, const SDLoc &DL,
1595                                     EVT VT, bool isTarget) {
1596   assert(VT.isFloatingPoint() && "Cannot create integer FP constant!");
1597 
1598   EVT EltVT = VT.getScalarType();
1599 
1600   // Do the map lookup using the actual bit pattern for the floating point
1601   // value, so that we don't have problems with 0.0 comparing equal to -0.0, and
1602   // we don't have issues with SNANs.
1603   unsigned Opc = isTarget ? ISD::TargetConstantFP : ISD::ConstantFP;
1604   FoldingSetNodeID ID;
1605   AddNodeIDNode(ID, Opc, getVTList(EltVT), None);
1606   ID.AddPointer(&V);
1607   void *IP = nullptr;
1608   SDNode *N = nullptr;
1609   if ((N = FindNodeOrInsertPos(ID, DL, IP)))
1610     if (!VT.isVector())
1611       return SDValue(N, 0);
1612 
1613   if (!N) {
1614     N = newSDNode<ConstantFPSDNode>(isTarget, &V, EltVT);
1615     CSEMap.InsertNode(N, IP);
1616     InsertNode(N);
1617   }
1618 
1619   SDValue Result(N, 0);
1620   if (VT.isScalableVector())
1621     Result = getSplatVector(VT, DL, Result);
1622   else if (VT.isVector())
1623     Result = getSplatBuildVector(VT, DL, Result);
1624   NewSDValueDbgMsg(Result, "Creating fp constant: ", this);
1625   return Result;
1626 }
1627 
1628 SDValue SelectionDAG::getConstantFP(double Val, const SDLoc &DL, EVT VT,
1629                                     bool isTarget) {
1630   EVT EltVT = VT.getScalarType();
1631   if (EltVT == MVT::f32)
1632     return getConstantFP(APFloat((float)Val), DL, VT, isTarget);
1633   if (EltVT == MVT::f64)
1634     return getConstantFP(APFloat(Val), DL, VT, isTarget);
1635   if (EltVT == MVT::f80 || EltVT == MVT::f128 || EltVT == MVT::ppcf128 ||
1636       EltVT == MVT::f16 || EltVT == MVT::bf16) {
1637     bool Ignored;
1638     APFloat APF = APFloat(Val);
1639     APF.convert(EVTToAPFloatSemantics(EltVT), APFloat::rmNearestTiesToEven,
1640                 &Ignored);
1641     return getConstantFP(APF, DL, VT, isTarget);
1642   }
1643   llvm_unreachable("Unsupported type in getConstantFP");
1644 }
1645 
1646 SDValue SelectionDAG::getGlobalAddress(const GlobalValue *GV, const SDLoc &DL,
1647                                        EVT VT, int64_t Offset, bool isTargetGA,
1648                                        unsigned TargetFlags) {
1649   assert((TargetFlags == 0 || isTargetGA) &&
1650          "Cannot set target flags on target-independent globals");
1651 
1652   // Truncate (with sign-extension) the offset value to the pointer size.
1653   unsigned BitWidth = getDataLayout().getPointerTypeSizeInBits(GV->getType());
1654   if (BitWidth < 64)
1655     Offset = SignExtend64(Offset, BitWidth);
1656 
1657   unsigned Opc;
1658   if (GV->isThreadLocal())
1659     Opc = isTargetGA ? ISD::TargetGlobalTLSAddress : ISD::GlobalTLSAddress;
1660   else
1661     Opc = isTargetGA ? ISD::TargetGlobalAddress : ISD::GlobalAddress;
1662 
1663   FoldingSetNodeID ID;
1664   AddNodeIDNode(ID, Opc, getVTList(VT), None);
1665   ID.AddPointer(GV);
1666   ID.AddInteger(Offset);
1667   ID.AddInteger(TargetFlags);
1668   void *IP = nullptr;
1669   if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
1670     return SDValue(E, 0);
1671 
1672   auto *N = newSDNode<GlobalAddressSDNode>(
1673       Opc, DL.getIROrder(), DL.getDebugLoc(), GV, VT, Offset, TargetFlags);
1674   CSEMap.InsertNode(N, IP);
1675     InsertNode(N);
1676   return SDValue(N, 0);
1677 }
1678 
1679 SDValue SelectionDAG::getFrameIndex(int FI, EVT VT, bool isTarget) {
1680   unsigned Opc = isTarget ? ISD::TargetFrameIndex : ISD::FrameIndex;
1681   FoldingSetNodeID ID;
1682   AddNodeIDNode(ID, Opc, getVTList(VT), None);
1683   ID.AddInteger(FI);
1684   void *IP = nullptr;
1685   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1686     return SDValue(E, 0);
1687 
1688   auto *N = newSDNode<FrameIndexSDNode>(FI, VT, isTarget);
1689   CSEMap.InsertNode(N, IP);
1690   InsertNode(N);
1691   return SDValue(N, 0);
1692 }
1693 
1694 SDValue SelectionDAG::getJumpTable(int JTI, EVT VT, bool isTarget,
1695                                    unsigned TargetFlags) {
1696   assert((TargetFlags == 0 || isTarget) &&
1697          "Cannot set target flags on target-independent jump tables");
1698   unsigned Opc = isTarget ? ISD::TargetJumpTable : ISD::JumpTable;
1699   FoldingSetNodeID ID;
1700   AddNodeIDNode(ID, Opc, getVTList(VT), None);
1701   ID.AddInteger(JTI);
1702   ID.AddInteger(TargetFlags);
1703   void *IP = nullptr;
1704   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1705     return SDValue(E, 0);
1706 
1707   auto *N = newSDNode<JumpTableSDNode>(JTI, VT, isTarget, TargetFlags);
1708   CSEMap.InsertNode(N, IP);
1709   InsertNode(N);
1710   return SDValue(N, 0);
1711 }
1712 
1713 SDValue SelectionDAG::getConstantPool(const Constant *C, EVT VT,
1714                                       MaybeAlign Alignment, int Offset,
1715                                       bool isTarget, unsigned TargetFlags) {
1716   assert((TargetFlags == 0 || isTarget) &&
1717          "Cannot set target flags on target-independent globals");
1718   if (!Alignment)
1719     Alignment = shouldOptForSize()
1720                     ? getDataLayout().getABITypeAlign(C->getType())
1721                     : getDataLayout().getPrefTypeAlign(C->getType());
1722   unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
1723   FoldingSetNodeID ID;
1724   AddNodeIDNode(ID, Opc, getVTList(VT), None);
1725   ID.AddInteger(Alignment->value());
1726   ID.AddInteger(Offset);
1727   ID.AddPointer(C);
1728   ID.AddInteger(TargetFlags);
1729   void *IP = nullptr;
1730   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1731     return SDValue(E, 0);
1732 
1733   auto *N = newSDNode<ConstantPoolSDNode>(isTarget, C, VT, Offset, *Alignment,
1734                                           TargetFlags);
1735   CSEMap.InsertNode(N, IP);
1736   InsertNode(N);
1737   SDValue V = SDValue(N, 0);
1738   NewSDValueDbgMsg(V, "Creating new constant pool: ", this);
1739   return V;
1740 }
1741 
1742 SDValue SelectionDAG::getConstantPool(MachineConstantPoolValue *C, EVT VT,
1743                                       MaybeAlign Alignment, int Offset,
1744                                       bool isTarget, unsigned TargetFlags) {
1745   assert((TargetFlags == 0 || isTarget) &&
1746          "Cannot set target flags on target-independent globals");
1747   if (!Alignment)
1748     Alignment = getDataLayout().getPrefTypeAlign(C->getType());
1749   unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
1750   FoldingSetNodeID ID;
1751   AddNodeIDNode(ID, Opc, getVTList(VT), None);
1752   ID.AddInteger(Alignment->value());
1753   ID.AddInteger(Offset);
1754   C->addSelectionDAGCSEId(ID);
1755   ID.AddInteger(TargetFlags);
1756   void *IP = nullptr;
1757   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1758     return SDValue(E, 0);
1759 
1760   auto *N = newSDNode<ConstantPoolSDNode>(isTarget, C, VT, Offset, *Alignment,
1761                                           TargetFlags);
1762   CSEMap.InsertNode(N, IP);
1763   InsertNode(N);
1764   return SDValue(N, 0);
1765 }
1766 
1767 SDValue SelectionDAG::getTargetIndex(int Index, EVT VT, int64_t Offset,
1768                                      unsigned TargetFlags) {
1769   FoldingSetNodeID ID;
1770   AddNodeIDNode(ID, ISD::TargetIndex, getVTList(VT), None);
1771   ID.AddInteger(Index);
1772   ID.AddInteger(Offset);
1773   ID.AddInteger(TargetFlags);
1774   void *IP = nullptr;
1775   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1776     return SDValue(E, 0);
1777 
1778   auto *N = newSDNode<TargetIndexSDNode>(Index, VT, Offset, TargetFlags);
1779   CSEMap.InsertNode(N, IP);
1780   InsertNode(N);
1781   return SDValue(N, 0);
1782 }
1783 
1784 SDValue SelectionDAG::getBasicBlock(MachineBasicBlock *MBB) {
1785   FoldingSetNodeID ID;
1786   AddNodeIDNode(ID, ISD::BasicBlock, getVTList(MVT::Other), None);
1787   ID.AddPointer(MBB);
1788   void *IP = nullptr;
1789   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1790     return SDValue(E, 0);
1791 
1792   auto *N = newSDNode<BasicBlockSDNode>(MBB);
1793   CSEMap.InsertNode(N, IP);
1794   InsertNode(N);
1795   return SDValue(N, 0);
1796 }
1797 
1798 SDValue SelectionDAG::getValueType(EVT VT) {
1799   if (VT.isSimple() && (unsigned)VT.getSimpleVT().SimpleTy >=
1800       ValueTypeNodes.size())
1801     ValueTypeNodes.resize(VT.getSimpleVT().SimpleTy+1);
1802 
1803   SDNode *&N = VT.isExtended() ?
1804     ExtendedValueTypeNodes[VT] : ValueTypeNodes[VT.getSimpleVT().SimpleTy];
1805 
1806   if (N) return SDValue(N, 0);
1807   N = newSDNode<VTSDNode>(VT);
1808   InsertNode(N);
1809   return SDValue(N, 0);
1810 }
1811 
1812 SDValue SelectionDAG::getExternalSymbol(const char *Sym, EVT VT) {
1813   SDNode *&N = ExternalSymbols[Sym];
1814   if (N) return SDValue(N, 0);
1815   N = newSDNode<ExternalSymbolSDNode>(false, Sym, 0, VT);
1816   InsertNode(N);
1817   return SDValue(N, 0);
1818 }
1819 
1820 SDValue SelectionDAG::getMCSymbol(MCSymbol *Sym, EVT VT) {
1821   SDNode *&N = MCSymbols[Sym];
1822   if (N)
1823     return SDValue(N, 0);
1824   N = newSDNode<MCSymbolSDNode>(Sym, VT);
1825   InsertNode(N);
1826   return SDValue(N, 0);
1827 }
1828 
1829 SDValue SelectionDAG::getTargetExternalSymbol(const char *Sym, EVT VT,
1830                                               unsigned TargetFlags) {
1831   SDNode *&N =
1832       TargetExternalSymbols[std::pair<std::string, unsigned>(Sym, TargetFlags)];
1833   if (N) return SDValue(N, 0);
1834   N = newSDNode<ExternalSymbolSDNode>(true, Sym, TargetFlags, VT);
1835   InsertNode(N);
1836   return SDValue(N, 0);
1837 }
1838 
1839 SDValue SelectionDAG::getCondCode(ISD::CondCode Cond) {
1840   if ((unsigned)Cond >= CondCodeNodes.size())
1841     CondCodeNodes.resize(Cond+1);
1842 
1843   if (!CondCodeNodes[Cond]) {
1844     auto *N = newSDNode<CondCodeSDNode>(Cond);
1845     CondCodeNodes[Cond] = N;
1846     InsertNode(N);
1847   }
1848 
1849   return SDValue(CondCodeNodes[Cond], 0);
1850 }
1851 
1852 SDValue SelectionDAG::getStepVector(const SDLoc &DL, EVT ResVT) {
1853   APInt One(ResVT.getScalarSizeInBits(), 1);
1854   return getStepVector(DL, ResVT, One);
1855 }
1856 
1857 SDValue SelectionDAG::getStepVector(const SDLoc &DL, EVT ResVT, APInt StepVal) {
1858   assert(ResVT.getScalarSizeInBits() == StepVal.getBitWidth());
1859   if (ResVT.isScalableVector())
1860     return getNode(
1861         ISD::STEP_VECTOR, DL, ResVT,
1862         getTargetConstant(StepVal, DL, ResVT.getVectorElementType()));
1863 
1864   SmallVector<SDValue, 16> OpsStepConstants;
1865   for (uint64_t i = 0; i < ResVT.getVectorNumElements(); i++)
1866     OpsStepConstants.push_back(
1867         getConstant(StepVal * i, DL, ResVT.getVectorElementType()));
1868   return getBuildVector(ResVT, DL, OpsStepConstants);
1869 }
1870 
1871 /// Swaps the values of N1 and N2. Swaps all indices in the shuffle mask M that
1872 /// point at N1 to point at N2 and indices that point at N2 to point at N1.
1873 static void commuteShuffle(SDValue &N1, SDValue &N2, MutableArrayRef<int> M) {
1874   std::swap(N1, N2);
1875   ShuffleVectorSDNode::commuteMask(M);
1876 }
1877 
1878 SDValue SelectionDAG::getVectorShuffle(EVT VT, const SDLoc &dl, SDValue N1,
1879                                        SDValue N2, ArrayRef<int> Mask) {
1880   assert(VT.getVectorNumElements() == Mask.size() &&
1881          "Must have the same number of vector elements as mask elements!");
1882   assert(VT == N1.getValueType() && VT == N2.getValueType() &&
1883          "Invalid VECTOR_SHUFFLE");
1884 
1885   // Canonicalize shuffle undef, undef -> undef
1886   if (N1.isUndef() && N2.isUndef())
1887     return getUNDEF(VT);
1888 
1889   // Validate that all indices in Mask are within the range of the elements
1890   // input to the shuffle.
1891   int NElts = Mask.size();
1892   assert(llvm::all_of(Mask,
1893                       [&](int M) { return M < (NElts * 2) && M >= -1; }) &&
1894          "Index out of range");
1895 
1896   // Copy the mask so we can do any needed cleanup.
1897   SmallVector<int, 8> MaskVec(Mask.begin(), Mask.end());
1898 
1899   // Canonicalize shuffle v, v -> v, undef
1900   if (N1 == N2) {
1901     N2 = getUNDEF(VT);
1902     for (int i = 0; i != NElts; ++i)
1903       if (MaskVec[i] >= NElts) MaskVec[i] -= NElts;
1904   }
1905 
1906   // Canonicalize shuffle undef, v -> v, undef.  Commute the shuffle mask.
1907   if (N1.isUndef())
1908     commuteShuffle(N1, N2, MaskVec);
1909 
1910   if (TLI->hasVectorBlend()) {
1911     // If shuffling a splat, try to blend the splat instead. We do this here so
1912     // that even when this arises during lowering we don't have to re-handle it.
1913     auto BlendSplat = [&](BuildVectorSDNode *BV, int Offset) {
1914       BitVector UndefElements;
1915       SDValue Splat = BV->getSplatValue(&UndefElements);
1916       if (!Splat)
1917         return;
1918 
1919       for (int i = 0; i < NElts; ++i) {
1920         if (MaskVec[i] < Offset || MaskVec[i] >= (Offset + NElts))
1921           continue;
1922 
1923         // If this input comes from undef, mark it as such.
1924         if (UndefElements[MaskVec[i] - Offset]) {
1925           MaskVec[i] = -1;
1926           continue;
1927         }
1928 
1929         // If we can blend a non-undef lane, use that instead.
1930         if (!UndefElements[i])
1931           MaskVec[i] = i + Offset;
1932       }
1933     };
1934     if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
1935       BlendSplat(N1BV, 0);
1936     if (auto *N2BV = dyn_cast<BuildVectorSDNode>(N2))
1937       BlendSplat(N2BV, NElts);
1938   }
1939 
1940   // Canonicalize all index into lhs, -> shuffle lhs, undef
1941   // Canonicalize all index into rhs, -> shuffle rhs, undef
1942   bool AllLHS = true, AllRHS = true;
1943   bool N2Undef = N2.isUndef();
1944   for (int i = 0; i != NElts; ++i) {
1945     if (MaskVec[i] >= NElts) {
1946       if (N2Undef)
1947         MaskVec[i] = -1;
1948       else
1949         AllLHS = false;
1950     } else if (MaskVec[i] >= 0) {
1951       AllRHS = false;
1952     }
1953   }
1954   if (AllLHS && AllRHS)
1955     return getUNDEF(VT);
1956   if (AllLHS && !N2Undef)
1957     N2 = getUNDEF(VT);
1958   if (AllRHS) {
1959     N1 = getUNDEF(VT);
1960     commuteShuffle(N1, N2, MaskVec);
1961   }
1962   // Reset our undef status after accounting for the mask.
1963   N2Undef = N2.isUndef();
1964   // Re-check whether both sides ended up undef.
1965   if (N1.isUndef() && N2Undef)
1966     return getUNDEF(VT);
1967 
1968   // If Identity shuffle return that node.
1969   bool Identity = true, AllSame = true;
1970   for (int i = 0; i != NElts; ++i) {
1971     if (MaskVec[i] >= 0 && MaskVec[i] != i) Identity = false;
1972     if (MaskVec[i] != MaskVec[0]) AllSame = false;
1973   }
1974   if (Identity && NElts)
1975     return N1;
1976 
1977   // Shuffling a constant splat doesn't change the result.
1978   if (N2Undef) {
1979     SDValue V = N1;
1980 
1981     // Look through any bitcasts. We check that these don't change the number
1982     // (and size) of elements and just changes their types.
1983     while (V.getOpcode() == ISD::BITCAST)
1984       V = V->getOperand(0);
1985 
1986     // A splat should always show up as a build vector node.
1987     if (auto *BV = dyn_cast<BuildVectorSDNode>(V)) {
1988       BitVector UndefElements;
1989       SDValue Splat = BV->getSplatValue(&UndefElements);
1990       // If this is a splat of an undef, shuffling it is also undef.
1991       if (Splat && Splat.isUndef())
1992         return getUNDEF(VT);
1993 
1994       bool SameNumElts =
1995           V.getValueType().getVectorNumElements() == VT.getVectorNumElements();
1996 
1997       // We only have a splat which can skip shuffles if there is a splatted
1998       // value and no undef lanes rearranged by the shuffle.
1999       if (Splat && UndefElements.none()) {
2000         // Splat of <x, x, ..., x>, return <x, x, ..., x>, provided that the
2001         // number of elements match or the value splatted is a zero constant.
2002         if (SameNumElts)
2003           return N1;
2004         if (auto *C = dyn_cast<ConstantSDNode>(Splat))
2005           if (C->isZero())
2006             return N1;
2007       }
2008 
2009       // If the shuffle itself creates a splat, build the vector directly.
2010       if (AllSame && SameNumElts) {
2011         EVT BuildVT = BV->getValueType(0);
2012         const SDValue &Splatted = BV->getOperand(MaskVec[0]);
2013         SDValue NewBV = getSplatBuildVector(BuildVT, dl, Splatted);
2014 
2015         // We may have jumped through bitcasts, so the type of the
2016         // BUILD_VECTOR may not match the type of the shuffle.
2017         if (BuildVT != VT)
2018           NewBV = getNode(ISD::BITCAST, dl, VT, NewBV);
2019         return NewBV;
2020       }
2021     }
2022   }
2023 
2024   FoldingSetNodeID ID;
2025   SDValue Ops[2] = { N1, N2 };
2026   AddNodeIDNode(ID, ISD::VECTOR_SHUFFLE, getVTList(VT), Ops);
2027   for (int i = 0; i != NElts; ++i)
2028     ID.AddInteger(MaskVec[i]);
2029 
2030   void* IP = nullptr;
2031   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
2032     return SDValue(E, 0);
2033 
2034   // Allocate the mask array for the node out of the BumpPtrAllocator, since
2035   // SDNode doesn't have access to it.  This memory will be "leaked" when
2036   // the node is deallocated, but recovered when the NodeAllocator is released.
2037   int *MaskAlloc = OperandAllocator.Allocate<int>(NElts);
2038   llvm::copy(MaskVec, MaskAlloc);
2039 
2040   auto *N = newSDNode<ShuffleVectorSDNode>(VT, dl.getIROrder(),
2041                                            dl.getDebugLoc(), MaskAlloc);
2042   createOperands(N, Ops);
2043 
2044   CSEMap.InsertNode(N, IP);
2045   InsertNode(N);
2046   SDValue V = SDValue(N, 0);
2047   NewSDValueDbgMsg(V, "Creating new node: ", this);
2048   return V;
2049 }
2050 
2051 SDValue SelectionDAG::getCommutedVectorShuffle(const ShuffleVectorSDNode &SV) {
2052   EVT VT = SV.getValueType(0);
2053   SmallVector<int, 8> MaskVec(SV.getMask().begin(), SV.getMask().end());
2054   ShuffleVectorSDNode::commuteMask(MaskVec);
2055 
2056   SDValue Op0 = SV.getOperand(0);
2057   SDValue Op1 = SV.getOperand(1);
2058   return getVectorShuffle(VT, SDLoc(&SV), Op1, Op0, MaskVec);
2059 }
2060 
2061 SDValue SelectionDAG::getRegister(unsigned RegNo, EVT VT) {
2062   FoldingSetNodeID ID;
2063   AddNodeIDNode(ID, ISD::Register, getVTList(VT), None);
2064   ID.AddInteger(RegNo);
2065   void *IP = nullptr;
2066   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2067     return SDValue(E, 0);
2068 
2069   auto *N = newSDNode<RegisterSDNode>(RegNo, VT);
2070   N->SDNodeBits.IsDivergent = TLI->isSDNodeSourceOfDivergence(N, FLI, DA);
2071   CSEMap.InsertNode(N, IP);
2072   InsertNode(N);
2073   return SDValue(N, 0);
2074 }
2075 
2076 SDValue SelectionDAG::getRegisterMask(const uint32_t *RegMask) {
2077   FoldingSetNodeID ID;
2078   AddNodeIDNode(ID, ISD::RegisterMask, getVTList(MVT::Untyped), None);
2079   ID.AddPointer(RegMask);
2080   void *IP = nullptr;
2081   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2082     return SDValue(E, 0);
2083 
2084   auto *N = newSDNode<RegisterMaskSDNode>(RegMask);
2085   CSEMap.InsertNode(N, IP);
2086   InsertNode(N);
2087   return SDValue(N, 0);
2088 }
2089 
2090 SDValue SelectionDAG::getEHLabel(const SDLoc &dl, SDValue Root,
2091                                  MCSymbol *Label) {
2092   return getLabelNode(ISD::EH_LABEL, dl, Root, Label);
2093 }
2094 
2095 SDValue SelectionDAG::getLabelNode(unsigned Opcode, const SDLoc &dl,
2096                                    SDValue Root, MCSymbol *Label) {
2097   FoldingSetNodeID ID;
2098   SDValue Ops[] = { Root };
2099   AddNodeIDNode(ID, Opcode, getVTList(MVT::Other), Ops);
2100   ID.AddPointer(Label);
2101   void *IP = nullptr;
2102   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2103     return SDValue(E, 0);
2104 
2105   auto *N =
2106       newSDNode<LabelSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(), Label);
2107   createOperands(N, Ops);
2108 
2109   CSEMap.InsertNode(N, IP);
2110   InsertNode(N);
2111   return SDValue(N, 0);
2112 }
2113 
2114 SDValue SelectionDAG::getBlockAddress(const BlockAddress *BA, EVT VT,
2115                                       int64_t Offset, bool isTarget,
2116                                       unsigned TargetFlags) {
2117   unsigned Opc = isTarget ? ISD::TargetBlockAddress : ISD::BlockAddress;
2118 
2119   FoldingSetNodeID ID;
2120   AddNodeIDNode(ID, Opc, getVTList(VT), None);
2121   ID.AddPointer(BA);
2122   ID.AddInteger(Offset);
2123   ID.AddInteger(TargetFlags);
2124   void *IP = nullptr;
2125   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2126     return SDValue(E, 0);
2127 
2128   auto *N = newSDNode<BlockAddressSDNode>(Opc, VT, BA, Offset, TargetFlags);
2129   CSEMap.InsertNode(N, IP);
2130   InsertNode(N);
2131   return SDValue(N, 0);
2132 }
2133 
2134 SDValue SelectionDAG::getSrcValue(const Value *V) {
2135   FoldingSetNodeID ID;
2136   AddNodeIDNode(ID, ISD::SRCVALUE, getVTList(MVT::Other), None);
2137   ID.AddPointer(V);
2138 
2139   void *IP = nullptr;
2140   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2141     return SDValue(E, 0);
2142 
2143   auto *N = newSDNode<SrcValueSDNode>(V);
2144   CSEMap.InsertNode(N, IP);
2145   InsertNode(N);
2146   return SDValue(N, 0);
2147 }
2148 
2149 SDValue SelectionDAG::getMDNode(const MDNode *MD) {
2150   FoldingSetNodeID ID;
2151   AddNodeIDNode(ID, ISD::MDNODE_SDNODE, getVTList(MVT::Other), None);
2152   ID.AddPointer(MD);
2153 
2154   void *IP = nullptr;
2155   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2156     return SDValue(E, 0);
2157 
2158   auto *N = newSDNode<MDNodeSDNode>(MD);
2159   CSEMap.InsertNode(N, IP);
2160   InsertNode(N);
2161   return SDValue(N, 0);
2162 }
2163 
2164 SDValue SelectionDAG::getBitcast(EVT VT, SDValue V) {
2165   if (VT == V.getValueType())
2166     return V;
2167 
2168   return getNode(ISD::BITCAST, SDLoc(V), VT, V);
2169 }
2170 
2171 SDValue SelectionDAG::getAddrSpaceCast(const SDLoc &dl, EVT VT, SDValue Ptr,
2172                                        unsigned SrcAS, unsigned DestAS) {
2173   SDValue Ops[] = {Ptr};
2174   FoldingSetNodeID ID;
2175   AddNodeIDNode(ID, ISD::ADDRSPACECAST, getVTList(VT), Ops);
2176   ID.AddInteger(SrcAS);
2177   ID.AddInteger(DestAS);
2178 
2179   void *IP = nullptr;
2180   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
2181     return SDValue(E, 0);
2182 
2183   auto *N = newSDNode<AddrSpaceCastSDNode>(dl.getIROrder(), dl.getDebugLoc(),
2184                                            VT, SrcAS, DestAS);
2185   createOperands(N, Ops);
2186 
2187   CSEMap.InsertNode(N, IP);
2188   InsertNode(N);
2189   return SDValue(N, 0);
2190 }
2191 
2192 SDValue SelectionDAG::getFreeze(SDValue V) {
2193   return getNode(ISD::FREEZE, SDLoc(V), V.getValueType(), V);
2194 }
2195 
2196 /// getShiftAmountOperand - Return the specified value casted to
2197 /// the target's desired shift amount type.
2198 SDValue SelectionDAG::getShiftAmountOperand(EVT LHSTy, SDValue Op) {
2199   EVT OpTy = Op.getValueType();
2200   EVT ShTy = TLI->getShiftAmountTy(LHSTy, getDataLayout());
2201   if (OpTy == ShTy || OpTy.isVector()) return Op;
2202 
2203   return getZExtOrTrunc(Op, SDLoc(Op), ShTy);
2204 }
2205 
2206 SDValue SelectionDAG::expandVAArg(SDNode *Node) {
2207   SDLoc dl(Node);
2208   const TargetLowering &TLI = getTargetLoweringInfo();
2209   const Value *V = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
2210   EVT VT = Node->getValueType(0);
2211   SDValue Tmp1 = Node->getOperand(0);
2212   SDValue Tmp2 = Node->getOperand(1);
2213   const MaybeAlign MA(Node->getConstantOperandVal(3));
2214 
2215   SDValue VAListLoad = getLoad(TLI.getPointerTy(getDataLayout()), dl, Tmp1,
2216                                Tmp2, MachinePointerInfo(V));
2217   SDValue VAList = VAListLoad;
2218 
2219   if (MA && *MA > TLI.getMinStackArgumentAlignment()) {
2220     VAList = getNode(ISD::ADD, dl, VAList.getValueType(), VAList,
2221                      getConstant(MA->value() - 1, dl, VAList.getValueType()));
2222 
2223     VAList =
2224         getNode(ISD::AND, dl, VAList.getValueType(), VAList,
2225                 getConstant(-(int64_t)MA->value(), dl, VAList.getValueType()));
2226   }
2227 
2228   // Increment the pointer, VAList, to the next vaarg
2229   Tmp1 = getNode(ISD::ADD, dl, VAList.getValueType(), VAList,
2230                  getConstant(getDataLayout().getTypeAllocSize(
2231                                                VT.getTypeForEVT(*getContext())),
2232                              dl, VAList.getValueType()));
2233   // Store the incremented VAList to the legalized pointer
2234   Tmp1 =
2235       getStore(VAListLoad.getValue(1), dl, Tmp1, Tmp2, MachinePointerInfo(V));
2236   // Load the actual argument out of the pointer VAList
2237   return getLoad(VT, dl, Tmp1, VAList, MachinePointerInfo());
2238 }
2239 
2240 SDValue SelectionDAG::expandVACopy(SDNode *Node) {
2241   SDLoc dl(Node);
2242   const TargetLowering &TLI = getTargetLoweringInfo();
2243   // This defaults to loading a pointer from the input and storing it to the
2244   // output, returning the chain.
2245   const Value *VD = cast<SrcValueSDNode>(Node->getOperand(3))->getValue();
2246   const Value *VS = cast<SrcValueSDNode>(Node->getOperand(4))->getValue();
2247   SDValue Tmp1 =
2248       getLoad(TLI.getPointerTy(getDataLayout()), dl, Node->getOperand(0),
2249               Node->getOperand(2), MachinePointerInfo(VS));
2250   return getStore(Tmp1.getValue(1), dl, Tmp1, Node->getOperand(1),
2251                   MachinePointerInfo(VD));
2252 }
2253 
2254 Align SelectionDAG::getReducedAlign(EVT VT, bool UseABI) {
2255   const DataLayout &DL = getDataLayout();
2256   Type *Ty = VT.getTypeForEVT(*getContext());
2257   Align RedAlign = UseABI ? DL.getABITypeAlign(Ty) : DL.getPrefTypeAlign(Ty);
2258 
2259   if (TLI->isTypeLegal(VT) || !VT.isVector())
2260     return RedAlign;
2261 
2262   const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering();
2263   const Align StackAlign = TFI->getStackAlign();
2264 
2265   // See if we can choose a smaller ABI alignment in cases where it's an
2266   // illegal vector type that will get broken down.
2267   if (RedAlign > StackAlign) {
2268     EVT IntermediateVT;
2269     MVT RegisterVT;
2270     unsigned NumIntermediates;
2271     TLI->getVectorTypeBreakdown(*getContext(), VT, IntermediateVT,
2272                                 NumIntermediates, RegisterVT);
2273     Ty = IntermediateVT.getTypeForEVT(*getContext());
2274     Align RedAlign2 = UseABI ? DL.getABITypeAlign(Ty) : DL.getPrefTypeAlign(Ty);
2275     if (RedAlign2 < RedAlign)
2276       RedAlign = RedAlign2;
2277   }
2278 
2279   return RedAlign;
2280 }
2281 
2282 SDValue SelectionDAG::CreateStackTemporary(TypeSize Bytes, Align Alignment) {
2283   MachineFrameInfo &MFI = MF->getFrameInfo();
2284   const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering();
2285   int StackID = 0;
2286   if (Bytes.isScalable())
2287     StackID = TFI->getStackIDForScalableVectors();
2288   // The stack id gives an indication of whether the object is scalable or
2289   // not, so it's safe to pass in the minimum size here.
2290   int FrameIdx = MFI.CreateStackObject(Bytes.getKnownMinSize(), Alignment,
2291                                        false, nullptr, StackID);
2292   return getFrameIndex(FrameIdx, TLI->getFrameIndexTy(getDataLayout()));
2293 }
2294 
2295 SDValue SelectionDAG::CreateStackTemporary(EVT VT, unsigned minAlign) {
2296   Type *Ty = VT.getTypeForEVT(*getContext());
2297   Align StackAlign =
2298       std::max(getDataLayout().getPrefTypeAlign(Ty), Align(minAlign));
2299   return CreateStackTemporary(VT.getStoreSize(), StackAlign);
2300 }
2301 
2302 SDValue SelectionDAG::CreateStackTemporary(EVT VT1, EVT VT2) {
2303   TypeSize VT1Size = VT1.getStoreSize();
2304   TypeSize VT2Size = VT2.getStoreSize();
2305   assert(VT1Size.isScalable() == VT2Size.isScalable() &&
2306          "Don't know how to choose the maximum size when creating a stack "
2307          "temporary");
2308   TypeSize Bytes =
2309       VT1Size.getKnownMinSize() > VT2Size.getKnownMinSize() ? VT1Size : VT2Size;
2310 
2311   Type *Ty1 = VT1.getTypeForEVT(*getContext());
2312   Type *Ty2 = VT2.getTypeForEVT(*getContext());
2313   const DataLayout &DL = getDataLayout();
2314   Align Align = std::max(DL.getPrefTypeAlign(Ty1), DL.getPrefTypeAlign(Ty2));
2315   return CreateStackTemporary(Bytes, Align);
2316 }
2317 
2318 SDValue SelectionDAG::FoldSetCC(EVT VT, SDValue N1, SDValue N2,
2319                                 ISD::CondCode Cond, const SDLoc &dl) {
2320   EVT OpVT = N1.getValueType();
2321 
2322   // These setcc operations always fold.
2323   switch (Cond) {
2324   default: break;
2325   case ISD::SETFALSE:
2326   case ISD::SETFALSE2: return getBoolConstant(false, dl, VT, OpVT);
2327   case ISD::SETTRUE:
2328   case ISD::SETTRUE2: return getBoolConstant(true, dl, VT, OpVT);
2329 
2330   case ISD::SETOEQ:
2331   case ISD::SETOGT:
2332   case ISD::SETOGE:
2333   case ISD::SETOLT:
2334   case ISD::SETOLE:
2335   case ISD::SETONE:
2336   case ISD::SETO:
2337   case ISD::SETUO:
2338   case ISD::SETUEQ:
2339   case ISD::SETUNE:
2340     assert(!OpVT.isInteger() && "Illegal setcc for integer!");
2341     break;
2342   }
2343 
2344   if (OpVT.isInteger()) {
2345     // For EQ and NE, we can always pick a value for the undef to make the
2346     // predicate pass or fail, so we can return undef.
2347     // Matches behavior in llvm::ConstantFoldCompareInstruction.
2348     // icmp eq/ne X, undef -> undef.
2349     if ((N1.isUndef() || N2.isUndef()) &&
2350         (Cond == ISD::SETEQ || Cond == ISD::SETNE))
2351       return getUNDEF(VT);
2352 
2353     // If both operands are undef, we can return undef for int comparison.
2354     // icmp undef, undef -> undef.
2355     if (N1.isUndef() && N2.isUndef())
2356       return getUNDEF(VT);
2357 
2358     // icmp X, X -> true/false
2359     // icmp X, undef -> true/false because undef could be X.
2360     if (N1 == N2)
2361       return getBoolConstant(ISD::isTrueWhenEqual(Cond), dl, VT, OpVT);
2362   }
2363 
2364   if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2)) {
2365     const APInt &C2 = N2C->getAPIntValue();
2366     if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1)) {
2367       const APInt &C1 = N1C->getAPIntValue();
2368 
2369       return getBoolConstant(ICmpInst::compare(C1, C2, getICmpCondCode(Cond)),
2370                              dl, VT, OpVT);
2371     }
2372   }
2373 
2374   auto *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
2375   auto *N2CFP = dyn_cast<ConstantFPSDNode>(N2);
2376 
2377   if (N1CFP && N2CFP) {
2378     APFloat::cmpResult R = N1CFP->getValueAPF().compare(N2CFP->getValueAPF());
2379     switch (Cond) {
2380     default: break;
2381     case ISD::SETEQ:  if (R==APFloat::cmpUnordered)
2382                         return getUNDEF(VT);
2383                       LLVM_FALLTHROUGH;
2384     case ISD::SETOEQ: return getBoolConstant(R==APFloat::cmpEqual, dl, VT,
2385                                              OpVT);
2386     case ISD::SETNE:  if (R==APFloat::cmpUnordered)
2387                         return getUNDEF(VT);
2388                       LLVM_FALLTHROUGH;
2389     case ISD::SETONE: return getBoolConstant(R==APFloat::cmpGreaterThan ||
2390                                              R==APFloat::cmpLessThan, dl, VT,
2391                                              OpVT);
2392     case ISD::SETLT:  if (R==APFloat::cmpUnordered)
2393                         return getUNDEF(VT);
2394                       LLVM_FALLTHROUGH;
2395     case ISD::SETOLT: return getBoolConstant(R==APFloat::cmpLessThan, dl, VT,
2396                                              OpVT);
2397     case ISD::SETGT:  if (R==APFloat::cmpUnordered)
2398                         return getUNDEF(VT);
2399                       LLVM_FALLTHROUGH;
2400     case ISD::SETOGT: return getBoolConstant(R==APFloat::cmpGreaterThan, dl,
2401                                              VT, OpVT);
2402     case ISD::SETLE:  if (R==APFloat::cmpUnordered)
2403                         return getUNDEF(VT);
2404                       LLVM_FALLTHROUGH;
2405     case ISD::SETOLE: return getBoolConstant(R==APFloat::cmpLessThan ||
2406                                              R==APFloat::cmpEqual, dl, VT,
2407                                              OpVT);
2408     case ISD::SETGE:  if (R==APFloat::cmpUnordered)
2409                         return getUNDEF(VT);
2410                       LLVM_FALLTHROUGH;
2411     case ISD::SETOGE: return getBoolConstant(R==APFloat::cmpGreaterThan ||
2412                                          R==APFloat::cmpEqual, dl, VT, OpVT);
2413     case ISD::SETO:   return getBoolConstant(R!=APFloat::cmpUnordered, dl, VT,
2414                                              OpVT);
2415     case ISD::SETUO:  return getBoolConstant(R==APFloat::cmpUnordered, dl, VT,
2416                                              OpVT);
2417     case ISD::SETUEQ: return getBoolConstant(R==APFloat::cmpUnordered ||
2418                                              R==APFloat::cmpEqual, dl, VT,
2419                                              OpVT);
2420     case ISD::SETUNE: return getBoolConstant(R!=APFloat::cmpEqual, dl, VT,
2421                                              OpVT);
2422     case ISD::SETULT: return getBoolConstant(R==APFloat::cmpUnordered ||
2423                                              R==APFloat::cmpLessThan, dl, VT,
2424                                              OpVT);
2425     case ISD::SETUGT: return getBoolConstant(R==APFloat::cmpGreaterThan ||
2426                                              R==APFloat::cmpUnordered, dl, VT,
2427                                              OpVT);
2428     case ISD::SETULE: return getBoolConstant(R!=APFloat::cmpGreaterThan, dl,
2429                                              VT, OpVT);
2430     case ISD::SETUGE: return getBoolConstant(R!=APFloat::cmpLessThan, dl, VT,
2431                                              OpVT);
2432     }
2433   } else if (N1CFP && OpVT.isSimple() && !N2.isUndef()) {
2434     // Ensure that the constant occurs on the RHS.
2435     ISD::CondCode SwappedCond = ISD::getSetCCSwappedOperands(Cond);
2436     if (!TLI->isCondCodeLegal(SwappedCond, OpVT.getSimpleVT()))
2437       return SDValue();
2438     return getSetCC(dl, VT, N2, N1, SwappedCond);
2439   } else if ((N2CFP && N2CFP->getValueAPF().isNaN()) ||
2440              (OpVT.isFloatingPoint() && (N1.isUndef() || N2.isUndef()))) {
2441     // If an operand is known to be a nan (or undef that could be a nan), we can
2442     // fold it.
2443     // Choosing NaN for the undef will always make unordered comparison succeed
2444     // and ordered comparison fails.
2445     // Matches behavior in llvm::ConstantFoldCompareInstruction.
2446     switch (ISD::getUnorderedFlavor(Cond)) {
2447     default:
2448       llvm_unreachable("Unknown flavor!");
2449     case 0: // Known false.
2450       return getBoolConstant(false, dl, VT, OpVT);
2451     case 1: // Known true.
2452       return getBoolConstant(true, dl, VT, OpVT);
2453     case 2: // Undefined.
2454       return getUNDEF(VT);
2455     }
2456   }
2457 
2458   // Could not fold it.
2459   return SDValue();
2460 }
2461 
2462 /// See if the specified operand can be simplified with the knowledge that only
2463 /// the bits specified by DemandedBits are used.
2464 /// TODO: really we should be making this into the DAG equivalent of
2465 /// SimplifyMultipleUseDemandedBits and not generate any new nodes.
2466 SDValue SelectionDAG::GetDemandedBits(SDValue V, const APInt &DemandedBits) {
2467   EVT VT = V.getValueType();
2468 
2469   if (VT.isScalableVector())
2470     return SDValue();
2471 
2472   APInt DemandedElts = VT.isVector()
2473                            ? APInt::getAllOnes(VT.getVectorNumElements())
2474                            : APInt(1, 1);
2475   return GetDemandedBits(V, DemandedBits, DemandedElts);
2476 }
2477 
2478 /// See if the specified operand can be simplified with the knowledge that only
2479 /// the bits specified by DemandedBits are used in the elements specified by
2480 /// DemandedElts.
2481 /// TODO: really we should be making this into the DAG equivalent of
2482 /// SimplifyMultipleUseDemandedBits and not generate any new nodes.
2483 SDValue SelectionDAG::GetDemandedBits(SDValue V, const APInt &DemandedBits,
2484                                       const APInt &DemandedElts) {
2485   switch (V.getOpcode()) {
2486   default:
2487     return TLI->SimplifyMultipleUseDemandedBits(V, DemandedBits, DemandedElts,
2488                                                 *this);
2489   case ISD::Constant: {
2490     const APInt &CVal = cast<ConstantSDNode>(V)->getAPIntValue();
2491     APInt NewVal = CVal & DemandedBits;
2492     if (NewVal != CVal)
2493       return getConstant(NewVal, SDLoc(V), V.getValueType());
2494     break;
2495   }
2496   case ISD::SRL:
2497     // Only look at single-use SRLs.
2498     if (!V.getNode()->hasOneUse())
2499       break;
2500     if (auto *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
2501       // See if we can recursively simplify the LHS.
2502       unsigned Amt = RHSC->getZExtValue();
2503 
2504       // Watch out for shift count overflow though.
2505       if (Amt >= DemandedBits.getBitWidth())
2506         break;
2507       APInt SrcDemandedBits = DemandedBits << Amt;
2508       if (SDValue SimplifyLHS =
2509               GetDemandedBits(V.getOperand(0), SrcDemandedBits))
2510         return getNode(ISD::SRL, SDLoc(V), V.getValueType(), SimplifyLHS,
2511                        V.getOperand(1));
2512     }
2513     break;
2514   }
2515   return SDValue();
2516 }
2517 
2518 /// SignBitIsZero - Return true if the sign bit of Op is known to be zero.  We
2519 /// use this predicate to simplify operations downstream.
2520 bool SelectionDAG::SignBitIsZero(SDValue Op, unsigned Depth) const {
2521   unsigned BitWidth = Op.getScalarValueSizeInBits();
2522   return MaskedValueIsZero(Op, APInt::getSignMask(BitWidth), Depth);
2523 }
2524 
2525 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero.  We use
2526 /// this predicate to simplify operations downstream.  Mask is known to be zero
2527 /// for bits that V cannot have.
2528 bool SelectionDAG::MaskedValueIsZero(SDValue V, const APInt &Mask,
2529                                      unsigned Depth) const {
2530   return Mask.isSubsetOf(computeKnownBits(V, Depth).Zero);
2531 }
2532 
2533 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero in
2534 /// DemandedElts.  We use this predicate to simplify operations downstream.
2535 /// Mask is known to be zero for bits that V cannot have.
2536 bool SelectionDAG::MaskedValueIsZero(SDValue V, const APInt &Mask,
2537                                      const APInt &DemandedElts,
2538                                      unsigned Depth) const {
2539   return Mask.isSubsetOf(computeKnownBits(V, DemandedElts, Depth).Zero);
2540 }
2541 
2542 /// MaskedValueIsAllOnes - Return true if '(Op & Mask) == Mask'.
2543 bool SelectionDAG::MaskedValueIsAllOnes(SDValue V, const APInt &Mask,
2544                                         unsigned Depth) const {
2545   return Mask.isSubsetOf(computeKnownBits(V, Depth).One);
2546 }
2547 
2548 /// isSplatValue - Return true if the vector V has the same value
2549 /// across all DemandedElts. For scalable vectors it does not make
2550 /// sense to specify which elements are demanded or undefined, therefore
2551 /// they are simply ignored.
2552 bool SelectionDAG::isSplatValue(SDValue V, const APInt &DemandedElts,
2553                                 APInt &UndefElts, unsigned Depth) const {
2554   unsigned Opcode = V.getOpcode();
2555   EVT VT = V.getValueType();
2556   assert(VT.isVector() && "Vector type expected");
2557 
2558   if (!VT.isScalableVector() && !DemandedElts)
2559     return false; // No demanded elts, better to assume we don't know anything.
2560 
2561   if (Depth >= MaxRecursionDepth)
2562     return false; // Limit search depth.
2563 
2564   // Deal with some common cases here that work for both fixed and scalable
2565   // vector types.
2566   switch (Opcode) {
2567   case ISD::SPLAT_VECTOR:
2568     UndefElts = V.getOperand(0).isUndef()
2569                     ? APInt::getAllOnes(DemandedElts.getBitWidth())
2570                     : APInt(DemandedElts.getBitWidth(), 0);
2571     return true;
2572   case ISD::ADD:
2573   case ISD::SUB:
2574   case ISD::AND:
2575   case ISD::XOR:
2576   case ISD::OR: {
2577     APInt UndefLHS, UndefRHS;
2578     SDValue LHS = V.getOperand(0);
2579     SDValue RHS = V.getOperand(1);
2580     if (isSplatValue(LHS, DemandedElts, UndefLHS, Depth + 1) &&
2581         isSplatValue(RHS, DemandedElts, UndefRHS, Depth + 1)) {
2582       UndefElts = UndefLHS | UndefRHS;
2583       return true;
2584     }
2585     return false;
2586   }
2587   case ISD::ABS:
2588   case ISD::TRUNCATE:
2589   case ISD::SIGN_EXTEND:
2590   case ISD::ZERO_EXTEND:
2591     return isSplatValue(V.getOperand(0), DemandedElts, UndefElts, Depth + 1);
2592   default:
2593     if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::INTRINSIC_WO_CHAIN ||
2594         Opcode == ISD::INTRINSIC_W_CHAIN || Opcode == ISD::INTRINSIC_VOID)
2595       return TLI->isSplatValueForTargetNode(V, DemandedElts, UndefElts, Depth);
2596     break;
2597 }
2598 
2599   // We don't support other cases than those above for scalable vectors at
2600   // the moment.
2601   if (VT.isScalableVector())
2602     return false;
2603 
2604   unsigned NumElts = VT.getVectorNumElements();
2605   assert(NumElts == DemandedElts.getBitWidth() && "Vector size mismatch");
2606   UndefElts = APInt::getZero(NumElts);
2607 
2608   switch (Opcode) {
2609   case ISD::BUILD_VECTOR: {
2610     SDValue Scl;
2611     for (unsigned i = 0; i != NumElts; ++i) {
2612       SDValue Op = V.getOperand(i);
2613       if (Op.isUndef()) {
2614         UndefElts.setBit(i);
2615         continue;
2616       }
2617       if (!DemandedElts[i])
2618         continue;
2619       if (Scl && Scl != Op)
2620         return false;
2621       Scl = Op;
2622     }
2623     return true;
2624   }
2625   case ISD::VECTOR_SHUFFLE: {
2626     // Check if this is a shuffle node doing a splat or a shuffle of a splat.
2627     APInt DemandedLHS = APInt::getNullValue(NumElts);
2628     APInt DemandedRHS = APInt::getNullValue(NumElts);
2629     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(V)->getMask();
2630     for (int i = 0; i != (int)NumElts; ++i) {
2631       int M = Mask[i];
2632       if (M < 0) {
2633         UndefElts.setBit(i);
2634         continue;
2635       }
2636       if (!DemandedElts[i])
2637         continue;
2638       if (M < (int)NumElts)
2639         DemandedLHS.setBit(M);
2640       else
2641         DemandedRHS.setBit(M - NumElts);
2642     }
2643 
2644     // If we aren't demanding either op, assume there's no splat.
2645     // If we are demanding both ops, assume there's no splat.
2646     if ((DemandedLHS.isZero() && DemandedRHS.isZero()) ||
2647         (!DemandedLHS.isZero() && !DemandedRHS.isZero()))
2648       return false;
2649 
2650     // See if the demanded elts of the source op is a splat or we only demand
2651     // one element, which should always be a splat.
2652     // TODO: Handle source ops splats with undefs.
2653     auto CheckSplatSrc = [&](SDValue Src, const APInt &SrcElts) {
2654       APInt SrcUndefs;
2655       return (SrcElts.countPopulation() == 1) ||
2656              (isSplatValue(Src, SrcElts, SrcUndefs, Depth + 1) &&
2657               (SrcElts & SrcUndefs).isZero());
2658     };
2659     if (!DemandedLHS.isZero())
2660       return CheckSplatSrc(V.getOperand(0), DemandedLHS);
2661     return CheckSplatSrc(V.getOperand(1), DemandedRHS);
2662   }
2663   case ISD::EXTRACT_SUBVECTOR: {
2664     // Offset the demanded elts by the subvector index.
2665     SDValue Src = V.getOperand(0);
2666     // We don't support scalable vectors at the moment.
2667     if (Src.getValueType().isScalableVector())
2668       return false;
2669     uint64_t Idx = V.getConstantOperandVal(1);
2670     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
2671     APInt UndefSrcElts;
2672     APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts).shl(Idx);
2673     if (isSplatValue(Src, DemandedSrcElts, UndefSrcElts, Depth + 1)) {
2674       UndefElts = UndefSrcElts.extractBits(NumElts, Idx);
2675       return true;
2676     }
2677     break;
2678   }
2679   case ISD::ANY_EXTEND_VECTOR_INREG:
2680   case ISD::SIGN_EXTEND_VECTOR_INREG:
2681   case ISD::ZERO_EXTEND_VECTOR_INREG: {
2682     // Widen the demanded elts by the src element count.
2683     SDValue Src = V.getOperand(0);
2684     // We don't support scalable vectors at the moment.
2685     if (Src.getValueType().isScalableVector())
2686       return false;
2687     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
2688     APInt UndefSrcElts;
2689     APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts);
2690     if (isSplatValue(Src, DemandedSrcElts, UndefSrcElts, Depth + 1)) {
2691       UndefElts = UndefSrcElts.trunc(NumElts);
2692       return true;
2693     }
2694     break;
2695   }
2696   case ISD::BITCAST: {
2697     SDValue Src = V.getOperand(0);
2698     EVT SrcVT = Src.getValueType();
2699     unsigned SrcBitWidth = SrcVT.getScalarSizeInBits();
2700     unsigned BitWidth = VT.getScalarSizeInBits();
2701 
2702     // Ignore bitcasts from unsupported types.
2703     // TODO: Add fp support?
2704     if (!SrcVT.isVector() || !SrcVT.isInteger() || !VT.isInteger())
2705       break;
2706 
2707     // Bitcast 'small element' vector to 'large element' vector.
2708     if ((BitWidth % SrcBitWidth) == 0) {
2709       // See if each sub element is a splat.
2710       unsigned Scale = BitWidth / SrcBitWidth;
2711       unsigned NumSrcElts = SrcVT.getVectorNumElements();
2712       APInt ScaledDemandedElts =
2713           APIntOps::ScaleBitMask(DemandedElts, NumSrcElts);
2714       for (unsigned I = 0; I != Scale; ++I) {
2715         APInt SubUndefElts;
2716         APInt SubDemandedElt = APInt::getOneBitSet(Scale, I);
2717         APInt SubDemandedElts = APInt::getSplat(NumSrcElts, SubDemandedElt);
2718         SubDemandedElts &= ScaledDemandedElts;
2719         if (!isSplatValue(Src, SubDemandedElts, SubUndefElts, Depth + 1))
2720           return false;
2721         UndefElts |= APIntOps::ScaleBitMask(SubUndefElts, NumElts);
2722       }
2723       return true;
2724     }
2725     break;
2726   }
2727   }
2728 
2729   return false;
2730 }
2731 
2732 /// Helper wrapper to main isSplatValue function.
2733 bool SelectionDAG::isSplatValue(SDValue V, bool AllowUndefs) const {
2734   EVT VT = V.getValueType();
2735   assert(VT.isVector() && "Vector type expected");
2736 
2737   APInt UndefElts;
2738   APInt DemandedElts;
2739 
2740   // For now we don't support this with scalable vectors.
2741   if (!VT.isScalableVector())
2742     DemandedElts = APInt::getAllOnes(VT.getVectorNumElements());
2743   return isSplatValue(V, DemandedElts, UndefElts) &&
2744          (AllowUndefs || !UndefElts);
2745 }
2746 
2747 SDValue SelectionDAG::getSplatSourceVector(SDValue V, int &SplatIdx) {
2748   V = peekThroughExtractSubvectors(V);
2749 
2750   EVT VT = V.getValueType();
2751   unsigned Opcode = V.getOpcode();
2752   switch (Opcode) {
2753   default: {
2754     APInt UndefElts;
2755     APInt DemandedElts;
2756 
2757     if (!VT.isScalableVector())
2758       DemandedElts = APInt::getAllOnes(VT.getVectorNumElements());
2759 
2760     if (isSplatValue(V, DemandedElts, UndefElts)) {
2761       if (VT.isScalableVector()) {
2762         // DemandedElts and UndefElts are ignored for scalable vectors, since
2763         // the only supported cases are SPLAT_VECTOR nodes.
2764         SplatIdx = 0;
2765       } else {
2766         // Handle case where all demanded elements are UNDEF.
2767         if (DemandedElts.isSubsetOf(UndefElts)) {
2768           SplatIdx = 0;
2769           return getUNDEF(VT);
2770         }
2771         SplatIdx = (UndefElts & DemandedElts).countTrailingOnes();
2772       }
2773       return V;
2774     }
2775     break;
2776   }
2777   case ISD::SPLAT_VECTOR:
2778     SplatIdx = 0;
2779     return V;
2780   case ISD::VECTOR_SHUFFLE: {
2781     if (VT.isScalableVector())
2782       return SDValue();
2783 
2784     // Check if this is a shuffle node doing a splat.
2785     // TODO - remove this and rely purely on SelectionDAG::isSplatValue,
2786     // getTargetVShiftNode currently struggles without the splat source.
2787     auto *SVN = cast<ShuffleVectorSDNode>(V);
2788     if (!SVN->isSplat())
2789       break;
2790     int Idx = SVN->getSplatIndex();
2791     int NumElts = V.getValueType().getVectorNumElements();
2792     SplatIdx = Idx % NumElts;
2793     return V.getOperand(Idx / NumElts);
2794   }
2795   }
2796 
2797   return SDValue();
2798 }
2799 
2800 SDValue SelectionDAG::getSplatValue(SDValue V, bool LegalTypes) {
2801   int SplatIdx;
2802   if (SDValue SrcVector = getSplatSourceVector(V, SplatIdx)) {
2803     EVT SVT = SrcVector.getValueType().getScalarType();
2804     EVT LegalSVT = SVT;
2805     if (LegalTypes && !TLI->isTypeLegal(SVT)) {
2806       if (!SVT.isInteger())
2807         return SDValue();
2808       LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT);
2809       if (LegalSVT.bitsLT(SVT))
2810         return SDValue();
2811     }
2812     return getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(V), LegalSVT, SrcVector,
2813                    getVectorIdxConstant(SplatIdx, SDLoc(V)));
2814   }
2815   return SDValue();
2816 }
2817 
2818 const APInt *
2819 SelectionDAG::getValidShiftAmountConstant(SDValue V,
2820                                           const APInt &DemandedElts) const {
2821   assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL ||
2822           V.getOpcode() == ISD::SRA) &&
2823          "Unknown shift node");
2824   unsigned BitWidth = V.getScalarValueSizeInBits();
2825   if (ConstantSDNode *SA = isConstOrConstSplat(V.getOperand(1), DemandedElts)) {
2826     // Shifting more than the bitwidth is not valid.
2827     const APInt &ShAmt = SA->getAPIntValue();
2828     if (ShAmt.ult(BitWidth))
2829       return &ShAmt;
2830   }
2831   return nullptr;
2832 }
2833 
2834 const APInt *SelectionDAG::getValidMinimumShiftAmountConstant(
2835     SDValue V, const APInt &DemandedElts) const {
2836   assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL ||
2837           V.getOpcode() == ISD::SRA) &&
2838          "Unknown shift node");
2839   if (const APInt *ValidAmt = getValidShiftAmountConstant(V, DemandedElts))
2840     return ValidAmt;
2841   unsigned BitWidth = V.getScalarValueSizeInBits();
2842   auto *BV = dyn_cast<BuildVectorSDNode>(V.getOperand(1));
2843   if (!BV)
2844     return nullptr;
2845   const APInt *MinShAmt = nullptr;
2846   for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
2847     if (!DemandedElts[i])
2848       continue;
2849     auto *SA = dyn_cast<ConstantSDNode>(BV->getOperand(i));
2850     if (!SA)
2851       return nullptr;
2852     // Shifting more than the bitwidth is not valid.
2853     const APInt &ShAmt = SA->getAPIntValue();
2854     if (ShAmt.uge(BitWidth))
2855       return nullptr;
2856     if (MinShAmt && MinShAmt->ule(ShAmt))
2857       continue;
2858     MinShAmt = &ShAmt;
2859   }
2860   return MinShAmt;
2861 }
2862 
2863 const APInt *SelectionDAG::getValidMaximumShiftAmountConstant(
2864     SDValue V, const APInt &DemandedElts) const {
2865   assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL ||
2866           V.getOpcode() == ISD::SRA) &&
2867          "Unknown shift node");
2868   if (const APInt *ValidAmt = getValidShiftAmountConstant(V, DemandedElts))
2869     return ValidAmt;
2870   unsigned BitWidth = V.getScalarValueSizeInBits();
2871   auto *BV = dyn_cast<BuildVectorSDNode>(V.getOperand(1));
2872   if (!BV)
2873     return nullptr;
2874   const APInt *MaxShAmt = nullptr;
2875   for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
2876     if (!DemandedElts[i])
2877       continue;
2878     auto *SA = dyn_cast<ConstantSDNode>(BV->getOperand(i));
2879     if (!SA)
2880       return nullptr;
2881     // Shifting more than the bitwidth is not valid.
2882     const APInt &ShAmt = SA->getAPIntValue();
2883     if (ShAmt.uge(BitWidth))
2884       return nullptr;
2885     if (MaxShAmt && MaxShAmt->uge(ShAmt))
2886       continue;
2887     MaxShAmt = &ShAmt;
2888   }
2889   return MaxShAmt;
2890 }
2891 
2892 /// Determine which bits of Op are known to be either zero or one and return
2893 /// them in Known. For vectors, the known bits are those that are shared by
2894 /// every vector element.
2895 KnownBits SelectionDAG::computeKnownBits(SDValue Op, unsigned Depth) const {
2896   EVT VT = Op.getValueType();
2897 
2898   // TOOD: Until we have a plan for how to represent demanded elements for
2899   // scalable vectors, we can just bail out for now.
2900   if (Op.getValueType().isScalableVector()) {
2901     unsigned BitWidth = Op.getScalarValueSizeInBits();
2902     return KnownBits(BitWidth);
2903   }
2904 
2905   APInt DemandedElts = VT.isVector()
2906                            ? APInt::getAllOnes(VT.getVectorNumElements())
2907                            : APInt(1, 1);
2908   return computeKnownBits(Op, DemandedElts, Depth);
2909 }
2910 
2911 /// Determine which bits of Op are known to be either zero or one and return
2912 /// them in Known. The DemandedElts argument allows us to only collect the known
2913 /// bits that are shared by the requested vector elements.
2914 KnownBits SelectionDAG::computeKnownBits(SDValue Op, const APInt &DemandedElts,
2915                                          unsigned Depth) const {
2916   unsigned BitWidth = Op.getScalarValueSizeInBits();
2917 
2918   KnownBits Known(BitWidth);   // Don't know anything.
2919 
2920   // TOOD: Until we have a plan for how to represent demanded elements for
2921   // scalable vectors, we can just bail out for now.
2922   if (Op.getValueType().isScalableVector())
2923     return Known;
2924 
2925   if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
2926     // We know all of the bits for a constant!
2927     return KnownBits::makeConstant(C->getAPIntValue());
2928   }
2929   if (auto *C = dyn_cast<ConstantFPSDNode>(Op)) {
2930     // We know all of the bits for a constant fp!
2931     return KnownBits::makeConstant(C->getValueAPF().bitcastToAPInt());
2932   }
2933 
2934   if (Depth >= MaxRecursionDepth)
2935     return Known;  // Limit search depth.
2936 
2937   KnownBits Known2;
2938   unsigned NumElts = DemandedElts.getBitWidth();
2939   assert((!Op.getValueType().isVector() ||
2940           NumElts == Op.getValueType().getVectorNumElements()) &&
2941          "Unexpected vector size");
2942 
2943   if (!DemandedElts)
2944     return Known;  // No demanded elts, better to assume we don't know anything.
2945 
2946   unsigned Opcode = Op.getOpcode();
2947   switch (Opcode) {
2948   case ISD::BUILD_VECTOR:
2949     // Collect the known bits that are shared by every demanded vector element.
2950     Known.Zero.setAllBits(); Known.One.setAllBits();
2951     for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
2952       if (!DemandedElts[i])
2953         continue;
2954 
2955       SDValue SrcOp = Op.getOperand(i);
2956       Known2 = computeKnownBits(SrcOp, Depth + 1);
2957 
2958       // BUILD_VECTOR can implicitly truncate sources, we must handle this.
2959       if (SrcOp.getValueSizeInBits() != BitWidth) {
2960         assert(SrcOp.getValueSizeInBits() > BitWidth &&
2961                "Expected BUILD_VECTOR implicit truncation");
2962         Known2 = Known2.trunc(BitWidth);
2963       }
2964 
2965       // Known bits are the values that are shared by every demanded element.
2966       Known = KnownBits::commonBits(Known, Known2);
2967 
2968       // If we don't know any bits, early out.
2969       if (Known.isUnknown())
2970         break;
2971     }
2972     break;
2973   case ISD::VECTOR_SHUFFLE: {
2974     // Collect the known bits that are shared by every vector element referenced
2975     // by the shuffle.
2976     APInt DemandedLHS(NumElts, 0), DemandedRHS(NumElts, 0);
2977     Known.Zero.setAllBits(); Known.One.setAllBits();
2978     const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op);
2979     assert(NumElts == SVN->getMask().size() && "Unexpected vector size");
2980     for (unsigned i = 0; i != NumElts; ++i) {
2981       if (!DemandedElts[i])
2982         continue;
2983 
2984       int M = SVN->getMaskElt(i);
2985       if (M < 0) {
2986         // For UNDEF elements, we don't know anything about the common state of
2987         // the shuffle result.
2988         Known.resetAll();
2989         DemandedLHS.clearAllBits();
2990         DemandedRHS.clearAllBits();
2991         break;
2992       }
2993 
2994       if ((unsigned)M < NumElts)
2995         DemandedLHS.setBit((unsigned)M % NumElts);
2996       else
2997         DemandedRHS.setBit((unsigned)M % NumElts);
2998     }
2999     // Known bits are the values that are shared by every demanded element.
3000     if (!!DemandedLHS) {
3001       SDValue LHS = Op.getOperand(0);
3002       Known2 = computeKnownBits(LHS, DemandedLHS, Depth + 1);
3003       Known = KnownBits::commonBits(Known, Known2);
3004     }
3005     // If we don't know any bits, early out.
3006     if (Known.isUnknown())
3007       break;
3008     if (!!DemandedRHS) {
3009       SDValue RHS = Op.getOperand(1);
3010       Known2 = computeKnownBits(RHS, DemandedRHS, Depth + 1);
3011       Known = KnownBits::commonBits(Known, Known2);
3012     }
3013     break;
3014   }
3015   case ISD::CONCAT_VECTORS: {
3016     // Split DemandedElts and test each of the demanded subvectors.
3017     Known.Zero.setAllBits(); Known.One.setAllBits();
3018     EVT SubVectorVT = Op.getOperand(0).getValueType();
3019     unsigned NumSubVectorElts = SubVectorVT.getVectorNumElements();
3020     unsigned NumSubVectors = Op.getNumOperands();
3021     for (unsigned i = 0; i != NumSubVectors; ++i) {
3022       APInt DemandedSub =
3023           DemandedElts.extractBits(NumSubVectorElts, i * NumSubVectorElts);
3024       if (!!DemandedSub) {
3025         SDValue Sub = Op.getOperand(i);
3026         Known2 = computeKnownBits(Sub, DemandedSub, Depth + 1);
3027         Known = KnownBits::commonBits(Known, Known2);
3028       }
3029       // If we don't know any bits, early out.
3030       if (Known.isUnknown())
3031         break;
3032     }
3033     break;
3034   }
3035   case ISD::INSERT_SUBVECTOR: {
3036     // Demand any elements from the subvector and the remainder from the src its
3037     // inserted into.
3038     SDValue Src = Op.getOperand(0);
3039     SDValue Sub = Op.getOperand(1);
3040     uint64_t Idx = Op.getConstantOperandVal(2);
3041     unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
3042     APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
3043     APInt DemandedSrcElts = DemandedElts;
3044     DemandedSrcElts.insertBits(APInt::getZero(NumSubElts), Idx);
3045 
3046     Known.One.setAllBits();
3047     Known.Zero.setAllBits();
3048     if (!!DemandedSubElts) {
3049       Known = computeKnownBits(Sub, DemandedSubElts, Depth + 1);
3050       if (Known.isUnknown())
3051         break; // early-out.
3052     }
3053     if (!!DemandedSrcElts) {
3054       Known2 = computeKnownBits(Src, DemandedSrcElts, Depth + 1);
3055       Known = KnownBits::commonBits(Known, Known2);
3056     }
3057     break;
3058   }
3059   case ISD::EXTRACT_SUBVECTOR: {
3060     // Offset the demanded elts by the subvector index.
3061     SDValue Src = Op.getOperand(0);
3062     // Bail until we can represent demanded elements for scalable vectors.
3063     if (Src.getValueType().isScalableVector())
3064       break;
3065     uint64_t Idx = Op.getConstantOperandVal(1);
3066     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
3067     APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts).shl(Idx);
3068     Known = computeKnownBits(Src, DemandedSrcElts, Depth + 1);
3069     break;
3070   }
3071   case ISD::SCALAR_TO_VECTOR: {
3072     // We know about scalar_to_vector as much as we know about it source,
3073     // which becomes the first element of otherwise unknown vector.
3074     if (DemandedElts != 1)
3075       break;
3076 
3077     SDValue N0 = Op.getOperand(0);
3078     Known = computeKnownBits(N0, Depth + 1);
3079     if (N0.getValueSizeInBits() != BitWidth)
3080       Known = Known.trunc(BitWidth);
3081 
3082     break;
3083   }
3084   case ISD::BITCAST: {
3085     SDValue N0 = Op.getOperand(0);
3086     EVT SubVT = N0.getValueType();
3087     unsigned SubBitWidth = SubVT.getScalarSizeInBits();
3088 
3089     // Ignore bitcasts from unsupported types.
3090     if (!(SubVT.isInteger() || SubVT.isFloatingPoint()))
3091       break;
3092 
3093     // Fast handling of 'identity' bitcasts.
3094     if (BitWidth == SubBitWidth) {
3095       Known = computeKnownBits(N0, DemandedElts, Depth + 1);
3096       break;
3097     }
3098 
3099     bool IsLE = getDataLayout().isLittleEndian();
3100 
3101     // Bitcast 'small element' vector to 'large element' scalar/vector.
3102     if ((BitWidth % SubBitWidth) == 0) {
3103       assert(N0.getValueType().isVector() && "Expected bitcast from vector");
3104 
3105       // Collect known bits for the (larger) output by collecting the known
3106       // bits from each set of sub elements and shift these into place.
3107       // We need to separately call computeKnownBits for each set of
3108       // sub elements as the knownbits for each is likely to be different.
3109       unsigned SubScale = BitWidth / SubBitWidth;
3110       APInt SubDemandedElts(NumElts * SubScale, 0);
3111       for (unsigned i = 0; i != NumElts; ++i)
3112         if (DemandedElts[i])
3113           SubDemandedElts.setBit(i * SubScale);
3114 
3115       for (unsigned i = 0; i != SubScale; ++i) {
3116         Known2 = computeKnownBits(N0, SubDemandedElts.shl(i),
3117                          Depth + 1);
3118         unsigned Shifts = IsLE ? i : SubScale - 1 - i;
3119         Known.insertBits(Known2, SubBitWidth * Shifts);
3120       }
3121     }
3122 
3123     // Bitcast 'large element' scalar/vector to 'small element' vector.
3124     if ((SubBitWidth % BitWidth) == 0) {
3125       assert(Op.getValueType().isVector() && "Expected bitcast to vector");
3126 
3127       // Collect known bits for the (smaller) output by collecting the known
3128       // bits from the overlapping larger input elements and extracting the
3129       // sub sections we actually care about.
3130       unsigned SubScale = SubBitWidth / BitWidth;
3131       APInt SubDemandedElts =
3132           APIntOps::ScaleBitMask(DemandedElts, NumElts / SubScale);
3133       Known2 = computeKnownBits(N0, SubDemandedElts, Depth + 1);
3134 
3135       Known.Zero.setAllBits(); Known.One.setAllBits();
3136       for (unsigned i = 0; i != NumElts; ++i)
3137         if (DemandedElts[i]) {
3138           unsigned Shifts = IsLE ? i : NumElts - 1 - i;
3139           unsigned Offset = (Shifts % SubScale) * BitWidth;
3140           Known = KnownBits::commonBits(Known,
3141                                         Known2.extractBits(BitWidth, Offset));
3142           // If we don't know any bits, early out.
3143           if (Known.isUnknown())
3144             break;
3145         }
3146     }
3147     break;
3148   }
3149   case ISD::AND:
3150     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3151     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3152 
3153     Known &= Known2;
3154     break;
3155   case ISD::OR:
3156     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3157     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3158 
3159     Known |= Known2;
3160     break;
3161   case ISD::XOR:
3162     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3163     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3164 
3165     Known ^= Known2;
3166     break;
3167   case ISD::MUL: {
3168     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3169     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3170     bool SelfMultiply = Op.getOperand(0) == Op.getOperand(1);
3171     // TODO: SelfMultiply can be poison, but not undef.
3172     if (SelfMultiply)
3173       SelfMultiply &= isGuaranteedNotToBeUndefOrPoison(
3174           Op.getOperand(0), DemandedElts, false, Depth + 1);
3175     Known = KnownBits::mul(Known, Known2, SelfMultiply);
3176 
3177     // If the multiplication is known not to overflow, the product of a number
3178     // with itself is non-negative. Only do this if we didn't already computed
3179     // the opposite value for the sign bit.
3180     if (Op->getFlags().hasNoSignedWrap() &&
3181         Op.getOperand(0) == Op.getOperand(1) &&
3182         !Known.isNegative())
3183       Known.makeNonNegative();
3184     break;
3185   }
3186   case ISD::MULHU: {
3187     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3188     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3189     Known = KnownBits::mulhu(Known, Known2);
3190     break;
3191   }
3192   case ISD::MULHS: {
3193     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3194     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3195     Known = KnownBits::mulhs(Known, Known2);
3196     break;
3197   }
3198   case ISD::UMUL_LOHI: {
3199     assert((Op.getResNo() == 0 || Op.getResNo() == 1) && "Unknown result");
3200     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3201     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3202     bool SelfMultiply = Op.getOperand(0) == Op.getOperand(1);
3203     if (Op.getResNo() == 0)
3204       Known = KnownBits::mul(Known, Known2, SelfMultiply);
3205     else
3206       Known = KnownBits::mulhu(Known, Known2);
3207     break;
3208   }
3209   case ISD::SMUL_LOHI: {
3210     assert((Op.getResNo() == 0 || Op.getResNo() == 1) && "Unknown result");
3211     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3212     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3213     bool SelfMultiply = Op.getOperand(0) == Op.getOperand(1);
3214     if (Op.getResNo() == 0)
3215       Known = KnownBits::mul(Known, Known2, SelfMultiply);
3216     else
3217       Known = KnownBits::mulhs(Known, Known2);
3218     break;
3219   }
3220   case ISD::UDIV: {
3221     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3222     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3223     Known = KnownBits::udiv(Known, Known2);
3224     break;
3225   }
3226   case ISD::AVGCEILU: {
3227     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3228     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3229     Known = Known.zext(BitWidth + 1);
3230     Known2 = Known2.zext(BitWidth + 1);
3231     KnownBits One = KnownBits::makeConstant(APInt(1, 1));
3232     Known = KnownBits::computeForAddCarry(Known, Known2, One);
3233     Known = Known.extractBits(BitWidth, 1);
3234     break;
3235   }
3236   case ISD::SELECT:
3237   case ISD::VSELECT:
3238     Known = computeKnownBits(Op.getOperand(2), DemandedElts, Depth+1);
3239     // If we don't know any bits, early out.
3240     if (Known.isUnknown())
3241       break;
3242     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth+1);
3243 
3244     // Only known if known in both the LHS and RHS.
3245     Known = KnownBits::commonBits(Known, Known2);
3246     break;
3247   case ISD::SELECT_CC:
3248     Known = computeKnownBits(Op.getOperand(3), DemandedElts, Depth+1);
3249     // If we don't know any bits, early out.
3250     if (Known.isUnknown())
3251       break;
3252     Known2 = computeKnownBits(Op.getOperand(2), DemandedElts, Depth+1);
3253 
3254     // Only known if known in both the LHS and RHS.
3255     Known = KnownBits::commonBits(Known, Known2);
3256     break;
3257   case ISD::SMULO:
3258   case ISD::UMULO:
3259     if (Op.getResNo() != 1)
3260       break;
3261     // The boolean result conforms to getBooleanContents.
3262     // If we know the result of a setcc has the top bits zero, use this info.
3263     // We know that we have an integer-based boolean since these operations
3264     // are only available for integer.
3265     if (TLI->getBooleanContents(Op.getValueType().isVector(), false) ==
3266             TargetLowering::ZeroOrOneBooleanContent &&
3267         BitWidth > 1)
3268       Known.Zero.setBitsFrom(1);
3269     break;
3270   case ISD::SETCC:
3271   case ISD::STRICT_FSETCC:
3272   case ISD::STRICT_FSETCCS: {
3273     unsigned OpNo = Op->isStrictFPOpcode() ? 1 : 0;
3274     // If we know the result of a setcc has the top bits zero, use this info.
3275     if (TLI->getBooleanContents(Op.getOperand(OpNo).getValueType()) ==
3276             TargetLowering::ZeroOrOneBooleanContent &&
3277         BitWidth > 1)
3278       Known.Zero.setBitsFrom(1);
3279     break;
3280   }
3281   case ISD::SHL:
3282     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3283     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3284     Known = KnownBits::shl(Known, Known2);
3285 
3286     // Minimum shift low bits are known zero.
3287     if (const APInt *ShMinAmt =
3288             getValidMinimumShiftAmountConstant(Op, DemandedElts))
3289       Known.Zero.setLowBits(ShMinAmt->getZExtValue());
3290     break;
3291   case ISD::SRL:
3292     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3293     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3294     Known = KnownBits::lshr(Known, Known2);
3295 
3296     // Minimum shift high bits are known zero.
3297     if (const APInt *ShMinAmt =
3298             getValidMinimumShiftAmountConstant(Op, DemandedElts))
3299       Known.Zero.setHighBits(ShMinAmt->getZExtValue());
3300     break;
3301   case ISD::SRA:
3302     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3303     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3304     Known = KnownBits::ashr(Known, Known2);
3305     // TODO: Add minimum shift high known sign bits.
3306     break;
3307   case ISD::FSHL:
3308   case ISD::FSHR:
3309     if (ConstantSDNode *C = isConstOrConstSplat(Op.getOperand(2), DemandedElts)) {
3310       unsigned Amt = C->getAPIntValue().urem(BitWidth);
3311 
3312       // For fshl, 0-shift returns the 1st arg.
3313       // For fshr, 0-shift returns the 2nd arg.
3314       if (Amt == 0) {
3315         Known = computeKnownBits(Op.getOperand(Opcode == ISD::FSHL ? 0 : 1),
3316                                  DemandedElts, Depth + 1);
3317         break;
3318       }
3319 
3320       // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW)))
3321       // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW))
3322       Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3323       Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3324       if (Opcode == ISD::FSHL) {
3325         Known.One <<= Amt;
3326         Known.Zero <<= Amt;
3327         Known2.One.lshrInPlace(BitWidth - Amt);
3328         Known2.Zero.lshrInPlace(BitWidth - Amt);
3329       } else {
3330         Known.One <<= BitWidth - Amt;
3331         Known.Zero <<= BitWidth - Amt;
3332         Known2.One.lshrInPlace(Amt);
3333         Known2.Zero.lshrInPlace(Amt);
3334       }
3335       Known.One |= Known2.One;
3336       Known.Zero |= Known2.Zero;
3337     }
3338     break;
3339   case ISD::SIGN_EXTEND_INREG: {
3340     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3341     EVT EVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
3342     Known = Known.sextInReg(EVT.getScalarSizeInBits());
3343     break;
3344   }
3345   case ISD::CTTZ:
3346   case ISD::CTTZ_ZERO_UNDEF: {
3347     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3348     // If we have a known 1, its position is our upper bound.
3349     unsigned PossibleTZ = Known2.countMaxTrailingZeros();
3350     unsigned LowBits = Log2_32(PossibleTZ) + 1;
3351     Known.Zero.setBitsFrom(LowBits);
3352     break;
3353   }
3354   case ISD::CTLZ:
3355   case ISD::CTLZ_ZERO_UNDEF: {
3356     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3357     // If we have a known 1, its position is our upper bound.
3358     unsigned PossibleLZ = Known2.countMaxLeadingZeros();
3359     unsigned LowBits = Log2_32(PossibleLZ) + 1;
3360     Known.Zero.setBitsFrom(LowBits);
3361     break;
3362   }
3363   case ISD::CTPOP: {
3364     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3365     // If we know some of the bits are zero, they can't be one.
3366     unsigned PossibleOnes = Known2.countMaxPopulation();
3367     Known.Zero.setBitsFrom(Log2_32(PossibleOnes) + 1);
3368     break;
3369   }
3370   case ISD::PARITY: {
3371     // Parity returns 0 everywhere but the LSB.
3372     Known.Zero.setBitsFrom(1);
3373     break;
3374   }
3375   case ISD::LOAD: {
3376     LoadSDNode *LD = cast<LoadSDNode>(Op);
3377     const Constant *Cst = TLI->getTargetConstantFromLoad(LD);
3378     if (ISD::isNON_EXTLoad(LD) && Cst) {
3379       // Determine any common known bits from the loaded constant pool value.
3380       Type *CstTy = Cst->getType();
3381       if ((NumElts * BitWidth) == CstTy->getPrimitiveSizeInBits()) {
3382         // If its a vector splat, then we can (quickly) reuse the scalar path.
3383         // NOTE: We assume all elements match and none are UNDEF.
3384         if (CstTy->isVectorTy()) {
3385           if (const Constant *Splat = Cst->getSplatValue()) {
3386             Cst = Splat;
3387             CstTy = Cst->getType();
3388           }
3389         }
3390         // TODO - do we need to handle different bitwidths?
3391         if (CstTy->isVectorTy() && BitWidth == CstTy->getScalarSizeInBits()) {
3392           // Iterate across all vector elements finding common known bits.
3393           Known.One.setAllBits();
3394           Known.Zero.setAllBits();
3395           for (unsigned i = 0; i != NumElts; ++i) {
3396             if (!DemandedElts[i])
3397               continue;
3398             if (Constant *Elt = Cst->getAggregateElement(i)) {
3399               if (auto *CInt = dyn_cast<ConstantInt>(Elt)) {
3400                 const APInt &Value = CInt->getValue();
3401                 Known.One &= Value;
3402                 Known.Zero &= ~Value;
3403                 continue;
3404               }
3405               if (auto *CFP = dyn_cast<ConstantFP>(Elt)) {
3406                 APInt Value = CFP->getValueAPF().bitcastToAPInt();
3407                 Known.One &= Value;
3408                 Known.Zero &= ~Value;
3409                 continue;
3410               }
3411             }
3412             Known.One.clearAllBits();
3413             Known.Zero.clearAllBits();
3414             break;
3415           }
3416         } else if (BitWidth == CstTy->getPrimitiveSizeInBits()) {
3417           if (auto *CInt = dyn_cast<ConstantInt>(Cst)) {
3418             Known = KnownBits::makeConstant(CInt->getValue());
3419           } else if (auto *CFP = dyn_cast<ConstantFP>(Cst)) {
3420             Known =
3421                 KnownBits::makeConstant(CFP->getValueAPF().bitcastToAPInt());
3422           }
3423         }
3424       }
3425     } else if (ISD::isZEXTLoad(Op.getNode()) && Op.getResNo() == 0) {
3426       // If this is a ZEXTLoad and we are looking at the loaded value.
3427       EVT VT = LD->getMemoryVT();
3428       unsigned MemBits = VT.getScalarSizeInBits();
3429       Known.Zero.setBitsFrom(MemBits);
3430     } else if (const MDNode *Ranges = LD->getRanges()) {
3431       if (LD->getExtensionType() == ISD::NON_EXTLOAD)
3432         computeKnownBitsFromRangeMetadata(*Ranges, Known);
3433     }
3434     break;
3435   }
3436   case ISD::ZERO_EXTEND_VECTOR_INREG: {
3437     EVT InVT = Op.getOperand(0).getValueType();
3438     APInt InDemandedElts = DemandedElts.zext(InVT.getVectorNumElements());
3439     Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1);
3440     Known = Known.zext(BitWidth);
3441     break;
3442   }
3443   case ISD::ZERO_EXTEND: {
3444     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3445     Known = Known.zext(BitWidth);
3446     break;
3447   }
3448   case ISD::SIGN_EXTEND_VECTOR_INREG: {
3449     EVT InVT = Op.getOperand(0).getValueType();
3450     APInt InDemandedElts = DemandedElts.zext(InVT.getVectorNumElements());
3451     Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1);
3452     // If the sign bit is known to be zero or one, then sext will extend
3453     // it to the top bits, else it will just zext.
3454     Known = Known.sext(BitWidth);
3455     break;
3456   }
3457   case ISD::SIGN_EXTEND: {
3458     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3459     // If the sign bit is known to be zero or one, then sext will extend
3460     // it to the top bits, else it will just zext.
3461     Known = Known.sext(BitWidth);
3462     break;
3463   }
3464   case ISD::ANY_EXTEND_VECTOR_INREG: {
3465     EVT InVT = Op.getOperand(0).getValueType();
3466     APInt InDemandedElts = DemandedElts.zext(InVT.getVectorNumElements());
3467     Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1);
3468     Known = Known.anyext(BitWidth);
3469     break;
3470   }
3471   case ISD::ANY_EXTEND: {
3472     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3473     Known = Known.anyext(BitWidth);
3474     break;
3475   }
3476   case ISD::TRUNCATE: {
3477     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3478     Known = Known.trunc(BitWidth);
3479     break;
3480   }
3481   case ISD::AssertZext: {
3482     EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
3483     APInt InMask = APInt::getLowBitsSet(BitWidth, VT.getSizeInBits());
3484     Known = computeKnownBits(Op.getOperand(0), Depth+1);
3485     Known.Zero |= (~InMask);
3486     Known.One  &= (~Known.Zero);
3487     break;
3488   }
3489   case ISD::AssertAlign: {
3490     unsigned LogOfAlign = Log2(cast<AssertAlignSDNode>(Op)->getAlign());
3491     assert(LogOfAlign != 0);
3492 
3493     // TODO: Should use maximum with source
3494     // If a node is guaranteed to be aligned, set low zero bits accordingly as
3495     // well as clearing one bits.
3496     Known.Zero.setLowBits(LogOfAlign);
3497     Known.One.clearLowBits(LogOfAlign);
3498     break;
3499   }
3500   case ISD::FGETSIGN:
3501     // All bits are zero except the low bit.
3502     Known.Zero.setBitsFrom(1);
3503     break;
3504   case ISD::USUBO:
3505   case ISD::SSUBO:
3506     if (Op.getResNo() == 1) {
3507       // If we know the result of a setcc has the top bits zero, use this info.
3508       if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) ==
3509               TargetLowering::ZeroOrOneBooleanContent &&
3510           BitWidth > 1)
3511         Known.Zero.setBitsFrom(1);
3512       break;
3513     }
3514     LLVM_FALLTHROUGH;
3515   case ISD::SUB:
3516   case ISD::SUBC: {
3517     assert(Op.getResNo() == 0 &&
3518            "We only compute knownbits for the difference here.");
3519 
3520     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3521     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3522     Known = KnownBits::computeForAddSub(/* Add */ false, /* NSW */ false,
3523                                         Known, Known2);
3524     break;
3525   }
3526   case ISD::UADDO:
3527   case ISD::SADDO:
3528   case ISD::ADDCARRY:
3529     if (Op.getResNo() == 1) {
3530       // If we know the result of a setcc has the top bits zero, use this info.
3531       if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) ==
3532               TargetLowering::ZeroOrOneBooleanContent &&
3533           BitWidth > 1)
3534         Known.Zero.setBitsFrom(1);
3535       break;
3536     }
3537     LLVM_FALLTHROUGH;
3538   case ISD::ADD:
3539   case ISD::ADDC:
3540   case ISD::ADDE: {
3541     assert(Op.getResNo() == 0 && "We only compute knownbits for the sum here.");
3542 
3543     // With ADDE and ADDCARRY, a carry bit may be added in.
3544     KnownBits Carry(1);
3545     if (Opcode == ISD::ADDE)
3546       // Can't track carry from glue, set carry to unknown.
3547       Carry.resetAll();
3548     else if (Opcode == ISD::ADDCARRY)
3549       // TODO: Compute known bits for the carry operand. Not sure if it is worth
3550       // the trouble (how often will we find a known carry bit). And I haven't
3551       // tested this very much yet, but something like this might work:
3552       //   Carry = computeKnownBits(Op.getOperand(2), DemandedElts, Depth + 1);
3553       //   Carry = Carry.zextOrTrunc(1, false);
3554       Carry.resetAll();
3555     else
3556       Carry.setAllZero();
3557 
3558     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3559     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3560     Known = KnownBits::computeForAddCarry(Known, Known2, Carry);
3561     break;
3562   }
3563   case ISD::SREM: {
3564     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3565     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3566     Known = KnownBits::srem(Known, Known2);
3567     break;
3568   }
3569   case ISD::UREM: {
3570     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3571     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3572     Known = KnownBits::urem(Known, Known2);
3573     break;
3574   }
3575   case ISD::EXTRACT_ELEMENT: {
3576     Known = computeKnownBits(Op.getOperand(0), Depth+1);
3577     const unsigned Index = Op.getConstantOperandVal(1);
3578     const unsigned EltBitWidth = Op.getValueSizeInBits();
3579 
3580     // Remove low part of known bits mask
3581     Known.Zero = Known.Zero.getHiBits(Known.getBitWidth() - Index * EltBitWidth);
3582     Known.One = Known.One.getHiBits(Known.getBitWidth() - Index * EltBitWidth);
3583 
3584     // Remove high part of known bit mask
3585     Known = Known.trunc(EltBitWidth);
3586     break;
3587   }
3588   case ISD::EXTRACT_VECTOR_ELT: {
3589     SDValue InVec = Op.getOperand(0);
3590     SDValue EltNo = Op.getOperand(1);
3591     EVT VecVT = InVec.getValueType();
3592     // computeKnownBits not yet implemented for scalable vectors.
3593     if (VecVT.isScalableVector())
3594       break;
3595     const unsigned EltBitWidth = VecVT.getScalarSizeInBits();
3596     const unsigned NumSrcElts = VecVT.getVectorNumElements();
3597 
3598     // If BitWidth > EltBitWidth the value is anyext:ed. So we do not know
3599     // anything about the extended bits.
3600     if (BitWidth > EltBitWidth)
3601       Known = Known.trunc(EltBitWidth);
3602 
3603     // If we know the element index, just demand that vector element, else for
3604     // an unknown element index, ignore DemandedElts and demand them all.
3605     APInt DemandedSrcElts = APInt::getAllOnes(NumSrcElts);
3606     auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
3607     if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts))
3608       DemandedSrcElts =
3609           APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue());
3610 
3611     Known = computeKnownBits(InVec, DemandedSrcElts, Depth + 1);
3612     if (BitWidth > EltBitWidth)
3613       Known = Known.anyext(BitWidth);
3614     break;
3615   }
3616   case ISD::INSERT_VECTOR_ELT: {
3617     // If we know the element index, split the demand between the
3618     // source vector and the inserted element, otherwise assume we need
3619     // the original demanded vector elements and the value.
3620     SDValue InVec = Op.getOperand(0);
3621     SDValue InVal = Op.getOperand(1);
3622     SDValue EltNo = Op.getOperand(2);
3623     bool DemandedVal = true;
3624     APInt DemandedVecElts = DemandedElts;
3625     auto *CEltNo = dyn_cast<ConstantSDNode>(EltNo);
3626     if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) {
3627       unsigned EltIdx = CEltNo->getZExtValue();
3628       DemandedVal = !!DemandedElts[EltIdx];
3629       DemandedVecElts.clearBit(EltIdx);
3630     }
3631     Known.One.setAllBits();
3632     Known.Zero.setAllBits();
3633     if (DemandedVal) {
3634       Known2 = computeKnownBits(InVal, Depth + 1);
3635       Known = KnownBits::commonBits(Known, Known2.zextOrTrunc(BitWidth));
3636     }
3637     if (!!DemandedVecElts) {
3638       Known2 = computeKnownBits(InVec, DemandedVecElts, Depth + 1);
3639       Known = KnownBits::commonBits(Known, Known2);
3640     }
3641     break;
3642   }
3643   case ISD::BITREVERSE: {
3644     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3645     Known = Known2.reverseBits();
3646     break;
3647   }
3648   case ISD::BSWAP: {
3649     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3650     Known = Known2.byteSwap();
3651     break;
3652   }
3653   case ISD::ABS: {
3654     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3655     Known = Known2.abs();
3656     break;
3657   }
3658   case ISD::USUBSAT: {
3659     // The result of usubsat will never be larger than the LHS.
3660     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3661     Known.Zero.setHighBits(Known2.countMinLeadingZeros());
3662     break;
3663   }
3664   case ISD::UMIN: {
3665     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3666     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3667     Known = KnownBits::umin(Known, Known2);
3668     break;
3669   }
3670   case ISD::UMAX: {
3671     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3672     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3673     Known = KnownBits::umax(Known, Known2);
3674     break;
3675   }
3676   case ISD::SMIN:
3677   case ISD::SMAX: {
3678     // If we have a clamp pattern, we know that the number of sign bits will be
3679     // the minimum of the clamp min/max range.
3680     bool IsMax = (Opcode == ISD::SMAX);
3681     ConstantSDNode *CstLow = nullptr, *CstHigh = nullptr;
3682     if ((CstLow = isConstOrConstSplat(Op.getOperand(1), DemandedElts)))
3683       if (Op.getOperand(0).getOpcode() == (IsMax ? ISD::SMIN : ISD::SMAX))
3684         CstHigh =
3685             isConstOrConstSplat(Op.getOperand(0).getOperand(1), DemandedElts);
3686     if (CstLow && CstHigh) {
3687       if (!IsMax)
3688         std::swap(CstLow, CstHigh);
3689 
3690       const APInt &ValueLow = CstLow->getAPIntValue();
3691       const APInt &ValueHigh = CstHigh->getAPIntValue();
3692       if (ValueLow.sle(ValueHigh)) {
3693         unsigned LowSignBits = ValueLow.getNumSignBits();
3694         unsigned HighSignBits = ValueHigh.getNumSignBits();
3695         unsigned MinSignBits = std::min(LowSignBits, HighSignBits);
3696         if (ValueLow.isNegative() && ValueHigh.isNegative()) {
3697           Known.One.setHighBits(MinSignBits);
3698           break;
3699         }
3700         if (ValueLow.isNonNegative() && ValueHigh.isNonNegative()) {
3701           Known.Zero.setHighBits(MinSignBits);
3702           break;
3703         }
3704       }
3705     }
3706 
3707     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3708     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3709     if (IsMax)
3710       Known = KnownBits::smax(Known, Known2);
3711     else
3712       Known = KnownBits::smin(Known, Known2);
3713 
3714     // For SMAX, if CstLow is non-negative we know the result will be
3715     // non-negative and thus all sign bits are 0.
3716     // TODO: There's an equivalent of this for smin with negative constant for
3717     // known ones.
3718     if (IsMax && CstLow) {
3719       const APInt &ValueLow = CstLow->getAPIntValue();
3720       if (ValueLow.isNonNegative()) {
3721         unsigned SignBits = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
3722         Known.Zero.setHighBits(std::min(SignBits, ValueLow.getNumSignBits()));
3723       }
3724     }
3725 
3726     break;
3727   }
3728   case ISD::FP_TO_UINT_SAT: {
3729     // FP_TO_UINT_SAT produces an unsigned value that fits in the saturating VT.
3730     EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
3731     Known.Zero |= APInt::getBitsSetFrom(BitWidth, VT.getScalarSizeInBits());
3732     break;
3733   }
3734   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
3735     if (Op.getResNo() == 1) {
3736       // The boolean result conforms to getBooleanContents.
3737       // If we know the result of a setcc has the top bits zero, use this info.
3738       // We know that we have an integer-based boolean since these operations
3739       // are only available for integer.
3740       if (TLI->getBooleanContents(Op.getValueType().isVector(), false) ==
3741               TargetLowering::ZeroOrOneBooleanContent &&
3742           BitWidth > 1)
3743         Known.Zero.setBitsFrom(1);
3744       break;
3745     }
3746     LLVM_FALLTHROUGH;
3747   case ISD::ATOMIC_CMP_SWAP:
3748   case ISD::ATOMIC_SWAP:
3749   case ISD::ATOMIC_LOAD_ADD:
3750   case ISD::ATOMIC_LOAD_SUB:
3751   case ISD::ATOMIC_LOAD_AND:
3752   case ISD::ATOMIC_LOAD_CLR:
3753   case ISD::ATOMIC_LOAD_OR:
3754   case ISD::ATOMIC_LOAD_XOR:
3755   case ISD::ATOMIC_LOAD_NAND:
3756   case ISD::ATOMIC_LOAD_MIN:
3757   case ISD::ATOMIC_LOAD_MAX:
3758   case ISD::ATOMIC_LOAD_UMIN:
3759   case ISD::ATOMIC_LOAD_UMAX:
3760   case ISD::ATOMIC_LOAD: {
3761     unsigned MemBits =
3762         cast<AtomicSDNode>(Op)->getMemoryVT().getScalarSizeInBits();
3763     // If we are looking at the loaded value.
3764     if (Op.getResNo() == 0) {
3765       if (TLI->getExtendForAtomicOps() == ISD::ZERO_EXTEND)
3766         Known.Zero.setBitsFrom(MemBits);
3767     }
3768     break;
3769   }
3770   case ISD::FrameIndex:
3771   case ISD::TargetFrameIndex:
3772     TLI->computeKnownBitsForFrameIndex(cast<FrameIndexSDNode>(Op)->getIndex(),
3773                                        Known, getMachineFunction());
3774     break;
3775 
3776   default:
3777     if (Opcode < ISD::BUILTIN_OP_END)
3778       break;
3779     LLVM_FALLTHROUGH;
3780   case ISD::INTRINSIC_WO_CHAIN:
3781   case ISD::INTRINSIC_W_CHAIN:
3782   case ISD::INTRINSIC_VOID:
3783     // Allow the target to implement this method for its nodes.
3784     TLI->computeKnownBitsForTargetNode(Op, Known, DemandedElts, *this, Depth);
3785     break;
3786   }
3787 
3788   assert(!Known.hasConflict() && "Bits known to be one AND zero?");
3789   return Known;
3790 }
3791 
3792 SelectionDAG::OverflowKind SelectionDAG::computeOverflowKind(SDValue N0,
3793                                                              SDValue N1) const {
3794   // X + 0 never overflow
3795   if (isNullConstant(N1))
3796     return OFK_Never;
3797 
3798   KnownBits N1Known = computeKnownBits(N1);
3799   if (N1Known.Zero.getBoolValue()) {
3800     KnownBits N0Known = computeKnownBits(N0);
3801 
3802     bool overflow;
3803     (void)N0Known.getMaxValue().uadd_ov(N1Known.getMaxValue(), overflow);
3804     if (!overflow)
3805       return OFK_Never;
3806   }
3807 
3808   // mulhi + 1 never overflow
3809   if (N0.getOpcode() == ISD::UMUL_LOHI && N0.getResNo() == 1 &&
3810       (N1Known.getMaxValue() & 0x01) == N1Known.getMaxValue())
3811     return OFK_Never;
3812 
3813   if (N1.getOpcode() == ISD::UMUL_LOHI && N1.getResNo() == 1) {
3814     KnownBits N0Known = computeKnownBits(N0);
3815 
3816     if ((N0Known.getMaxValue() & 0x01) == N0Known.getMaxValue())
3817       return OFK_Never;
3818   }
3819 
3820   return OFK_Sometime;
3821 }
3822 
3823 bool SelectionDAG::isKnownToBeAPowerOfTwo(SDValue Val) const {
3824   EVT OpVT = Val.getValueType();
3825   unsigned BitWidth = OpVT.getScalarSizeInBits();
3826 
3827   // Is the constant a known power of 2?
3828   if (ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Val))
3829     return Const->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2();
3830 
3831   // A left-shift of a constant one will have exactly one bit set because
3832   // shifting the bit off the end is undefined.
3833   if (Val.getOpcode() == ISD::SHL) {
3834     auto *C = isConstOrConstSplat(Val.getOperand(0));
3835     if (C && C->getAPIntValue() == 1)
3836       return true;
3837   }
3838 
3839   // Similarly, a logical right-shift of a constant sign-bit will have exactly
3840   // one bit set.
3841   if (Val.getOpcode() == ISD::SRL) {
3842     auto *C = isConstOrConstSplat(Val.getOperand(0));
3843     if (C && C->getAPIntValue().isSignMask())
3844       return true;
3845   }
3846 
3847   // Are all operands of a build vector constant powers of two?
3848   if (Val.getOpcode() == ISD::BUILD_VECTOR)
3849     if (llvm::all_of(Val->ops(), [BitWidth](SDValue E) {
3850           if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(E))
3851             return C->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2();
3852           return false;
3853         }))
3854       return true;
3855 
3856   // Is the operand of a splat vector a constant power of two?
3857   if (Val.getOpcode() == ISD::SPLAT_VECTOR)
3858     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val->getOperand(0)))
3859       if (C->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2())
3860         return true;
3861 
3862   // More could be done here, though the above checks are enough
3863   // to handle some common cases.
3864 
3865   // Fall back to computeKnownBits to catch other known cases.
3866   KnownBits Known = computeKnownBits(Val);
3867   return (Known.countMaxPopulation() == 1) && (Known.countMinPopulation() == 1);
3868 }
3869 
3870 unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, unsigned Depth) const {
3871   EVT VT = Op.getValueType();
3872 
3873   // TODO: Assume we don't know anything for now.
3874   if (VT.isScalableVector())
3875     return 1;
3876 
3877   APInt DemandedElts = VT.isVector()
3878                            ? APInt::getAllOnes(VT.getVectorNumElements())
3879                            : APInt(1, 1);
3880   return ComputeNumSignBits(Op, DemandedElts, Depth);
3881 }
3882 
3883 unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, const APInt &DemandedElts,
3884                                           unsigned Depth) const {
3885   EVT VT = Op.getValueType();
3886   assert((VT.isInteger() || VT.isFloatingPoint()) && "Invalid VT!");
3887   unsigned VTBits = VT.getScalarSizeInBits();
3888   unsigned NumElts = DemandedElts.getBitWidth();
3889   unsigned Tmp, Tmp2;
3890   unsigned FirstAnswer = 1;
3891 
3892   if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
3893     const APInt &Val = C->getAPIntValue();
3894     return Val.getNumSignBits();
3895   }
3896 
3897   if (Depth >= MaxRecursionDepth)
3898     return 1;  // Limit search depth.
3899 
3900   if (!DemandedElts || VT.isScalableVector())
3901     return 1;  // No demanded elts, better to assume we don't know anything.
3902 
3903   unsigned Opcode = Op.getOpcode();
3904   switch (Opcode) {
3905   default: break;
3906   case ISD::AssertSext:
3907     Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
3908     return VTBits-Tmp+1;
3909   case ISD::AssertZext:
3910     Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
3911     return VTBits-Tmp;
3912 
3913   case ISD::BUILD_VECTOR:
3914     Tmp = VTBits;
3915     for (unsigned i = 0, e = Op.getNumOperands(); (i < e) && (Tmp > 1); ++i) {
3916       if (!DemandedElts[i])
3917         continue;
3918 
3919       SDValue SrcOp = Op.getOperand(i);
3920       Tmp2 = ComputeNumSignBits(SrcOp, Depth + 1);
3921 
3922       // BUILD_VECTOR can implicitly truncate sources, we must handle this.
3923       if (SrcOp.getValueSizeInBits() != VTBits) {
3924         assert(SrcOp.getValueSizeInBits() > VTBits &&
3925                "Expected BUILD_VECTOR implicit truncation");
3926         unsigned ExtraBits = SrcOp.getValueSizeInBits() - VTBits;
3927         Tmp2 = (Tmp2 > ExtraBits ? Tmp2 - ExtraBits : 1);
3928       }
3929       Tmp = std::min(Tmp, Tmp2);
3930     }
3931     return Tmp;
3932 
3933   case ISD::VECTOR_SHUFFLE: {
3934     // Collect the minimum number of sign bits that are shared by every vector
3935     // element referenced by the shuffle.
3936     APInt DemandedLHS(NumElts, 0), DemandedRHS(NumElts, 0);
3937     const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op);
3938     assert(NumElts == SVN->getMask().size() && "Unexpected vector size");
3939     for (unsigned i = 0; i != NumElts; ++i) {
3940       int M = SVN->getMaskElt(i);
3941       if (!DemandedElts[i])
3942         continue;
3943       // For UNDEF elements, we don't know anything about the common state of
3944       // the shuffle result.
3945       if (M < 0)
3946         return 1;
3947       if ((unsigned)M < NumElts)
3948         DemandedLHS.setBit((unsigned)M % NumElts);
3949       else
3950         DemandedRHS.setBit((unsigned)M % NumElts);
3951     }
3952     Tmp = std::numeric_limits<unsigned>::max();
3953     if (!!DemandedLHS)
3954       Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedLHS, Depth + 1);
3955     if (!!DemandedRHS) {
3956       Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedRHS, Depth + 1);
3957       Tmp = std::min(Tmp, Tmp2);
3958     }
3959     // If we don't know anything, early out and try computeKnownBits fall-back.
3960     if (Tmp == 1)
3961       break;
3962     assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
3963     return Tmp;
3964   }
3965 
3966   case ISD::BITCAST: {
3967     SDValue N0 = Op.getOperand(0);
3968     EVT SrcVT = N0.getValueType();
3969     unsigned SrcBits = SrcVT.getScalarSizeInBits();
3970 
3971     // Ignore bitcasts from unsupported types..
3972     if (!(SrcVT.isInteger() || SrcVT.isFloatingPoint()))
3973       break;
3974 
3975     // Fast handling of 'identity' bitcasts.
3976     if (VTBits == SrcBits)
3977       return ComputeNumSignBits(N0, DemandedElts, Depth + 1);
3978 
3979     bool IsLE = getDataLayout().isLittleEndian();
3980 
3981     // Bitcast 'large element' scalar/vector to 'small element' vector.
3982     if ((SrcBits % VTBits) == 0) {
3983       assert(VT.isVector() && "Expected bitcast to vector");
3984 
3985       unsigned Scale = SrcBits / VTBits;
3986       APInt SrcDemandedElts =
3987           APIntOps::ScaleBitMask(DemandedElts, NumElts / Scale);
3988 
3989       // Fast case - sign splat can be simply split across the small elements.
3990       Tmp = ComputeNumSignBits(N0, SrcDemandedElts, Depth + 1);
3991       if (Tmp == SrcBits)
3992         return VTBits;
3993 
3994       // Slow case - determine how far the sign extends into each sub-element.
3995       Tmp2 = VTBits;
3996       for (unsigned i = 0; i != NumElts; ++i)
3997         if (DemandedElts[i]) {
3998           unsigned SubOffset = i % Scale;
3999           SubOffset = (IsLE ? ((Scale - 1) - SubOffset) : SubOffset);
4000           SubOffset = SubOffset * VTBits;
4001           if (Tmp <= SubOffset)
4002             return 1;
4003           Tmp2 = std::min(Tmp2, Tmp - SubOffset);
4004         }
4005       return Tmp2;
4006     }
4007     break;
4008   }
4009 
4010   case ISD::FP_TO_SINT_SAT:
4011     // FP_TO_SINT_SAT produces a signed value that fits in the saturating VT.
4012     Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getScalarSizeInBits();
4013     return VTBits - Tmp + 1;
4014   case ISD::SIGN_EXTEND:
4015     Tmp = VTBits - Op.getOperand(0).getScalarValueSizeInBits();
4016     return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1) + Tmp;
4017   case ISD::SIGN_EXTEND_INREG:
4018     // Max of the input and what this extends.
4019     Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getScalarSizeInBits();
4020     Tmp = VTBits-Tmp+1;
4021     Tmp2 = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1);
4022     return std::max(Tmp, Tmp2);
4023   case ISD::SIGN_EXTEND_VECTOR_INREG: {
4024     SDValue Src = Op.getOperand(0);
4025     EVT SrcVT = Src.getValueType();
4026     APInt DemandedSrcElts = DemandedElts.zext(SrcVT.getVectorNumElements());
4027     Tmp = VTBits - SrcVT.getScalarSizeInBits();
4028     return ComputeNumSignBits(Src, DemandedSrcElts, Depth+1) + Tmp;
4029   }
4030   case ISD::SRA:
4031     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
4032     // SRA X, C -> adds C sign bits.
4033     if (const APInt *ShAmt =
4034             getValidMinimumShiftAmountConstant(Op, DemandedElts))
4035       Tmp = std::min<uint64_t>(Tmp + ShAmt->getZExtValue(), VTBits);
4036     return Tmp;
4037   case ISD::SHL:
4038     if (const APInt *ShAmt =
4039             getValidMaximumShiftAmountConstant(Op, DemandedElts)) {
4040       // shl destroys sign bits, ensure it doesn't shift out all sign bits.
4041       Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
4042       if (ShAmt->ult(Tmp))
4043         return Tmp - ShAmt->getZExtValue();
4044     }
4045     break;
4046   case ISD::AND:
4047   case ISD::OR:
4048   case ISD::XOR:    // NOT is handled here.
4049     // Logical binary ops preserve the number of sign bits at the worst.
4050     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1);
4051     if (Tmp != 1) {
4052       Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth+1);
4053       FirstAnswer = std::min(Tmp, Tmp2);
4054       // We computed what we know about the sign bits as our first
4055       // answer. Now proceed to the generic code that uses
4056       // computeKnownBits, and pick whichever answer is better.
4057     }
4058     break;
4059 
4060   case ISD::SELECT:
4061   case ISD::VSELECT:
4062     Tmp = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth+1);
4063     if (Tmp == 1) return 1;  // Early out.
4064     Tmp2 = ComputeNumSignBits(Op.getOperand(2), DemandedElts, Depth+1);
4065     return std::min(Tmp, Tmp2);
4066   case ISD::SELECT_CC:
4067     Tmp = ComputeNumSignBits(Op.getOperand(2), DemandedElts, Depth+1);
4068     if (Tmp == 1) return 1;  // Early out.
4069     Tmp2 = ComputeNumSignBits(Op.getOperand(3), DemandedElts, Depth+1);
4070     return std::min(Tmp, Tmp2);
4071 
4072   case ISD::SMIN:
4073   case ISD::SMAX: {
4074     // If we have a clamp pattern, we know that the number of sign bits will be
4075     // the minimum of the clamp min/max range.
4076     bool IsMax = (Opcode == ISD::SMAX);
4077     ConstantSDNode *CstLow = nullptr, *CstHigh = nullptr;
4078     if ((CstLow = isConstOrConstSplat(Op.getOperand(1), DemandedElts)))
4079       if (Op.getOperand(0).getOpcode() == (IsMax ? ISD::SMIN : ISD::SMAX))
4080         CstHigh =
4081             isConstOrConstSplat(Op.getOperand(0).getOperand(1), DemandedElts);
4082     if (CstLow && CstHigh) {
4083       if (!IsMax)
4084         std::swap(CstLow, CstHigh);
4085       if (CstLow->getAPIntValue().sle(CstHigh->getAPIntValue())) {
4086         Tmp = CstLow->getAPIntValue().getNumSignBits();
4087         Tmp2 = CstHigh->getAPIntValue().getNumSignBits();
4088         return std::min(Tmp, Tmp2);
4089       }
4090     }
4091 
4092     // Fallback - just get the minimum number of sign bits of the operands.
4093     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
4094     if (Tmp == 1)
4095       return 1;  // Early out.
4096     Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
4097     return std::min(Tmp, Tmp2);
4098   }
4099   case ISD::UMIN:
4100   case ISD::UMAX:
4101     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
4102     if (Tmp == 1)
4103       return 1;  // Early out.
4104     Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
4105     return std::min(Tmp, Tmp2);
4106   case ISD::SADDO:
4107   case ISD::UADDO:
4108   case ISD::SSUBO:
4109   case ISD::USUBO:
4110   case ISD::SMULO:
4111   case ISD::UMULO:
4112     if (Op.getResNo() != 1)
4113       break;
4114     // The boolean result conforms to getBooleanContents.  Fall through.
4115     // If setcc returns 0/-1, all bits are sign bits.
4116     // We know that we have an integer-based boolean since these operations
4117     // are only available for integer.
4118     if (TLI->getBooleanContents(VT.isVector(), false) ==
4119         TargetLowering::ZeroOrNegativeOneBooleanContent)
4120       return VTBits;
4121     break;
4122   case ISD::SETCC:
4123   case ISD::STRICT_FSETCC:
4124   case ISD::STRICT_FSETCCS: {
4125     unsigned OpNo = Op->isStrictFPOpcode() ? 1 : 0;
4126     // If setcc returns 0/-1, all bits are sign bits.
4127     if (TLI->getBooleanContents(Op.getOperand(OpNo).getValueType()) ==
4128         TargetLowering::ZeroOrNegativeOneBooleanContent)
4129       return VTBits;
4130     break;
4131   }
4132   case ISD::ROTL:
4133   case ISD::ROTR:
4134     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
4135 
4136     // If we're rotating an 0/-1 value, then it stays an 0/-1 value.
4137     if (Tmp == VTBits)
4138       return VTBits;
4139 
4140     if (ConstantSDNode *C =
4141             isConstOrConstSplat(Op.getOperand(1), DemandedElts)) {
4142       unsigned RotAmt = C->getAPIntValue().urem(VTBits);
4143 
4144       // Handle rotate right by N like a rotate left by 32-N.
4145       if (Opcode == ISD::ROTR)
4146         RotAmt = (VTBits - RotAmt) % VTBits;
4147 
4148       // If we aren't rotating out all of the known-in sign bits, return the
4149       // number that are left.  This handles rotl(sext(x), 1) for example.
4150       if (Tmp > (RotAmt + 1)) return (Tmp - RotAmt);
4151     }
4152     break;
4153   case ISD::ADD:
4154   case ISD::ADDC:
4155     // Add can have at most one carry bit.  Thus we know that the output
4156     // is, at worst, one more bit than the inputs.
4157     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
4158     if (Tmp == 1) return 1; // Early out.
4159 
4160     // Special case decrementing a value (ADD X, -1):
4161     if (ConstantSDNode *CRHS =
4162             isConstOrConstSplat(Op.getOperand(1), DemandedElts))
4163       if (CRHS->isAllOnes()) {
4164         KnownBits Known =
4165             computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4166 
4167         // If the input is known to be 0 or 1, the output is 0/-1, which is all
4168         // sign bits set.
4169         if ((Known.Zero | 1).isAllOnes())
4170           return VTBits;
4171 
4172         // If we are subtracting one from a positive number, there is no carry
4173         // out of the result.
4174         if (Known.isNonNegative())
4175           return Tmp;
4176       }
4177 
4178     Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
4179     if (Tmp2 == 1) return 1; // Early out.
4180     return std::min(Tmp, Tmp2) - 1;
4181   case ISD::SUB:
4182     Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
4183     if (Tmp2 == 1) return 1; // Early out.
4184 
4185     // Handle NEG.
4186     if (ConstantSDNode *CLHS =
4187             isConstOrConstSplat(Op.getOperand(0), DemandedElts))
4188       if (CLHS->isZero()) {
4189         KnownBits Known =
4190             computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4191         // If the input is known to be 0 or 1, the output is 0/-1, which is all
4192         // sign bits set.
4193         if ((Known.Zero | 1).isAllOnes())
4194           return VTBits;
4195 
4196         // If the input is known to be positive (the sign bit is known clear),
4197         // the output of the NEG has the same number of sign bits as the input.
4198         if (Known.isNonNegative())
4199           return Tmp2;
4200 
4201         // Otherwise, we treat this like a SUB.
4202       }
4203 
4204     // Sub can have at most one carry bit.  Thus we know that the output
4205     // is, at worst, one more bit than the inputs.
4206     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
4207     if (Tmp == 1) return 1; // Early out.
4208     return std::min(Tmp, Tmp2) - 1;
4209   case ISD::MUL: {
4210     // The output of the Mul can be at most twice the valid bits in the inputs.
4211     unsigned SignBitsOp0 = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
4212     if (SignBitsOp0 == 1)
4213       break;
4214     unsigned SignBitsOp1 = ComputeNumSignBits(Op.getOperand(1), Depth + 1);
4215     if (SignBitsOp1 == 1)
4216       break;
4217     unsigned OutValidBits =
4218         (VTBits - SignBitsOp0 + 1) + (VTBits - SignBitsOp1 + 1);
4219     return OutValidBits > VTBits ? 1 : VTBits - OutValidBits + 1;
4220   }
4221   case ISD::SREM:
4222     // The sign bit is the LHS's sign bit, except when the result of the
4223     // remainder is zero. The magnitude of the result should be less than or
4224     // equal to the magnitude of the LHS. Therefore, the result should have
4225     // at least as many sign bits as the left hand side.
4226     return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
4227   case ISD::TRUNCATE: {
4228     // Check if the sign bits of source go down as far as the truncated value.
4229     unsigned NumSrcBits = Op.getOperand(0).getScalarValueSizeInBits();
4230     unsigned NumSrcSignBits = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
4231     if (NumSrcSignBits > (NumSrcBits - VTBits))
4232       return NumSrcSignBits - (NumSrcBits - VTBits);
4233     break;
4234   }
4235   case ISD::EXTRACT_ELEMENT: {
4236     const int KnownSign = ComputeNumSignBits(Op.getOperand(0), Depth+1);
4237     const int BitWidth = Op.getValueSizeInBits();
4238     const int Items = Op.getOperand(0).getValueSizeInBits() / BitWidth;
4239 
4240     // Get reverse index (starting from 1), Op1 value indexes elements from
4241     // little end. Sign starts at big end.
4242     const int rIndex = Items - 1 - Op.getConstantOperandVal(1);
4243 
4244     // If the sign portion ends in our element the subtraction gives correct
4245     // result. Otherwise it gives either negative or > bitwidth result
4246     return std::max(std::min(KnownSign - rIndex * BitWidth, BitWidth), 0);
4247   }
4248   case ISD::INSERT_VECTOR_ELT: {
4249     // If we know the element index, split the demand between the
4250     // source vector and the inserted element, otherwise assume we need
4251     // the original demanded vector elements and the value.
4252     SDValue InVec = Op.getOperand(0);
4253     SDValue InVal = Op.getOperand(1);
4254     SDValue EltNo = Op.getOperand(2);
4255     bool DemandedVal = true;
4256     APInt DemandedVecElts = DemandedElts;
4257     auto *CEltNo = dyn_cast<ConstantSDNode>(EltNo);
4258     if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) {
4259       unsigned EltIdx = CEltNo->getZExtValue();
4260       DemandedVal = !!DemandedElts[EltIdx];
4261       DemandedVecElts.clearBit(EltIdx);
4262     }
4263     Tmp = std::numeric_limits<unsigned>::max();
4264     if (DemandedVal) {
4265       // TODO - handle implicit truncation of inserted elements.
4266       if (InVal.getScalarValueSizeInBits() != VTBits)
4267         break;
4268       Tmp2 = ComputeNumSignBits(InVal, Depth + 1);
4269       Tmp = std::min(Tmp, Tmp2);
4270     }
4271     if (!!DemandedVecElts) {
4272       Tmp2 = ComputeNumSignBits(InVec, DemandedVecElts, Depth + 1);
4273       Tmp = std::min(Tmp, Tmp2);
4274     }
4275     assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
4276     return Tmp;
4277   }
4278   case ISD::EXTRACT_VECTOR_ELT: {
4279     SDValue InVec = Op.getOperand(0);
4280     SDValue EltNo = Op.getOperand(1);
4281     EVT VecVT = InVec.getValueType();
4282     // ComputeNumSignBits not yet implemented for scalable vectors.
4283     if (VecVT.isScalableVector())
4284       break;
4285     const unsigned BitWidth = Op.getValueSizeInBits();
4286     const unsigned EltBitWidth = Op.getOperand(0).getScalarValueSizeInBits();
4287     const unsigned NumSrcElts = VecVT.getVectorNumElements();
4288 
4289     // If BitWidth > EltBitWidth the value is anyext:ed, and we do not know
4290     // anything about sign bits. But if the sizes match we can derive knowledge
4291     // about sign bits from the vector operand.
4292     if (BitWidth != EltBitWidth)
4293       break;
4294 
4295     // If we know the element index, just demand that vector element, else for
4296     // an unknown element index, ignore DemandedElts and demand them all.
4297     APInt DemandedSrcElts = APInt::getAllOnes(NumSrcElts);
4298     auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
4299     if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts))
4300       DemandedSrcElts =
4301           APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue());
4302 
4303     return ComputeNumSignBits(InVec, DemandedSrcElts, Depth + 1);
4304   }
4305   case ISD::EXTRACT_SUBVECTOR: {
4306     // Offset the demanded elts by the subvector index.
4307     SDValue Src = Op.getOperand(0);
4308     // Bail until we can represent demanded elements for scalable vectors.
4309     if (Src.getValueType().isScalableVector())
4310       break;
4311     uint64_t Idx = Op.getConstantOperandVal(1);
4312     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
4313     APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts).shl(Idx);
4314     return ComputeNumSignBits(Src, DemandedSrcElts, Depth + 1);
4315   }
4316   case ISD::CONCAT_VECTORS: {
4317     // Determine the minimum number of sign bits across all demanded
4318     // elts of the input vectors. Early out if the result is already 1.
4319     Tmp = std::numeric_limits<unsigned>::max();
4320     EVT SubVectorVT = Op.getOperand(0).getValueType();
4321     unsigned NumSubVectorElts = SubVectorVT.getVectorNumElements();
4322     unsigned NumSubVectors = Op.getNumOperands();
4323     for (unsigned i = 0; (i < NumSubVectors) && (Tmp > 1); ++i) {
4324       APInt DemandedSub =
4325           DemandedElts.extractBits(NumSubVectorElts, i * NumSubVectorElts);
4326       if (!DemandedSub)
4327         continue;
4328       Tmp2 = ComputeNumSignBits(Op.getOperand(i), DemandedSub, Depth + 1);
4329       Tmp = std::min(Tmp, Tmp2);
4330     }
4331     assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
4332     return Tmp;
4333   }
4334   case ISD::INSERT_SUBVECTOR: {
4335     // Demand any elements from the subvector and the remainder from the src its
4336     // inserted into.
4337     SDValue Src = Op.getOperand(0);
4338     SDValue Sub = Op.getOperand(1);
4339     uint64_t Idx = Op.getConstantOperandVal(2);
4340     unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
4341     APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
4342     APInt DemandedSrcElts = DemandedElts;
4343     DemandedSrcElts.insertBits(APInt::getZero(NumSubElts), Idx);
4344 
4345     Tmp = std::numeric_limits<unsigned>::max();
4346     if (!!DemandedSubElts) {
4347       Tmp = ComputeNumSignBits(Sub, DemandedSubElts, Depth + 1);
4348       if (Tmp == 1)
4349         return 1; // early-out
4350     }
4351     if (!!DemandedSrcElts) {
4352       Tmp2 = ComputeNumSignBits(Src, DemandedSrcElts, Depth + 1);
4353       Tmp = std::min(Tmp, Tmp2);
4354     }
4355     assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
4356     return Tmp;
4357   }
4358   case ISD::ATOMIC_CMP_SWAP:
4359   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
4360   case ISD::ATOMIC_SWAP:
4361   case ISD::ATOMIC_LOAD_ADD:
4362   case ISD::ATOMIC_LOAD_SUB:
4363   case ISD::ATOMIC_LOAD_AND:
4364   case ISD::ATOMIC_LOAD_CLR:
4365   case ISD::ATOMIC_LOAD_OR:
4366   case ISD::ATOMIC_LOAD_XOR:
4367   case ISD::ATOMIC_LOAD_NAND:
4368   case ISD::ATOMIC_LOAD_MIN:
4369   case ISD::ATOMIC_LOAD_MAX:
4370   case ISD::ATOMIC_LOAD_UMIN:
4371   case ISD::ATOMIC_LOAD_UMAX:
4372   case ISD::ATOMIC_LOAD: {
4373     Tmp = cast<AtomicSDNode>(Op)->getMemoryVT().getScalarSizeInBits();
4374     // If we are looking at the loaded value.
4375     if (Op.getResNo() == 0) {
4376       if (Tmp == VTBits)
4377         return 1; // early-out
4378       if (TLI->getExtendForAtomicOps() == ISD::SIGN_EXTEND)
4379         return VTBits - Tmp + 1;
4380       if (TLI->getExtendForAtomicOps() == ISD::ZERO_EXTEND)
4381         return VTBits - Tmp;
4382     }
4383     break;
4384   }
4385   }
4386 
4387   // If we are looking at the loaded value of the SDNode.
4388   if (Op.getResNo() == 0) {
4389     // Handle LOADX separately here. EXTLOAD case will fallthrough.
4390     if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
4391       unsigned ExtType = LD->getExtensionType();
4392       switch (ExtType) {
4393       default: break;
4394       case ISD::SEXTLOAD: // e.g. i16->i32 = '17' bits known.
4395         Tmp = LD->getMemoryVT().getScalarSizeInBits();
4396         return VTBits - Tmp + 1;
4397       case ISD::ZEXTLOAD: // e.g. i16->i32 = '16' bits known.
4398         Tmp = LD->getMemoryVT().getScalarSizeInBits();
4399         return VTBits - Tmp;
4400       case ISD::NON_EXTLOAD:
4401         if (const Constant *Cst = TLI->getTargetConstantFromLoad(LD)) {
4402           // We only need to handle vectors - computeKnownBits should handle
4403           // scalar cases.
4404           Type *CstTy = Cst->getType();
4405           if (CstTy->isVectorTy() &&
4406               (NumElts * VTBits) == CstTy->getPrimitiveSizeInBits() &&
4407               VTBits == CstTy->getScalarSizeInBits()) {
4408             Tmp = VTBits;
4409             for (unsigned i = 0; i != NumElts; ++i) {
4410               if (!DemandedElts[i])
4411                 continue;
4412               if (Constant *Elt = Cst->getAggregateElement(i)) {
4413                 if (auto *CInt = dyn_cast<ConstantInt>(Elt)) {
4414                   const APInt &Value = CInt->getValue();
4415                   Tmp = std::min(Tmp, Value.getNumSignBits());
4416                   continue;
4417                 }
4418                 if (auto *CFP = dyn_cast<ConstantFP>(Elt)) {
4419                   APInt Value = CFP->getValueAPF().bitcastToAPInt();
4420                   Tmp = std::min(Tmp, Value.getNumSignBits());
4421                   continue;
4422                 }
4423               }
4424               // Unknown type. Conservatively assume no bits match sign bit.
4425               return 1;
4426             }
4427             return Tmp;
4428           }
4429         }
4430         break;
4431       }
4432     }
4433   }
4434 
4435   // Allow the target to implement this method for its nodes.
4436   if (Opcode >= ISD::BUILTIN_OP_END ||
4437       Opcode == ISD::INTRINSIC_WO_CHAIN ||
4438       Opcode == ISD::INTRINSIC_W_CHAIN ||
4439       Opcode == ISD::INTRINSIC_VOID) {
4440     unsigned NumBits =
4441         TLI->ComputeNumSignBitsForTargetNode(Op, DemandedElts, *this, Depth);
4442     if (NumBits > 1)
4443       FirstAnswer = std::max(FirstAnswer, NumBits);
4444   }
4445 
4446   // Finally, if we can prove that the top bits of the result are 0's or 1's,
4447   // use this information.
4448   KnownBits Known = computeKnownBits(Op, DemandedElts, Depth);
4449   return std::max(FirstAnswer, Known.countMinSignBits());
4450 }
4451 
4452 unsigned SelectionDAG::ComputeMaxSignificantBits(SDValue Op,
4453                                                  unsigned Depth) const {
4454   unsigned SignBits = ComputeNumSignBits(Op, Depth);
4455   return Op.getScalarValueSizeInBits() - SignBits + 1;
4456 }
4457 
4458 unsigned SelectionDAG::ComputeMaxSignificantBits(SDValue Op,
4459                                                  const APInt &DemandedElts,
4460                                                  unsigned Depth) const {
4461   unsigned SignBits = ComputeNumSignBits(Op, DemandedElts, Depth);
4462   return Op.getScalarValueSizeInBits() - SignBits + 1;
4463 }
4464 
4465 bool SelectionDAG::isGuaranteedNotToBeUndefOrPoison(SDValue Op, bool PoisonOnly,
4466                                                     unsigned Depth) const {
4467   // Early out for FREEZE.
4468   if (Op.getOpcode() == ISD::FREEZE)
4469     return true;
4470 
4471   // TODO: Assume we don't know anything for now.
4472   EVT VT = Op.getValueType();
4473   if (VT.isScalableVector())
4474     return false;
4475 
4476   APInt DemandedElts = VT.isVector()
4477                            ? APInt::getAllOnes(VT.getVectorNumElements())
4478                            : APInt(1, 1);
4479   return isGuaranteedNotToBeUndefOrPoison(Op, DemandedElts, PoisonOnly, Depth);
4480 }
4481 
4482 bool SelectionDAG::isGuaranteedNotToBeUndefOrPoison(SDValue Op,
4483                                                     const APInt &DemandedElts,
4484                                                     bool PoisonOnly,
4485                                                     unsigned Depth) const {
4486   unsigned Opcode = Op.getOpcode();
4487 
4488   // Early out for FREEZE.
4489   if (Opcode == ISD::FREEZE)
4490     return true;
4491 
4492   if (Depth >= MaxRecursionDepth)
4493     return false; // Limit search depth.
4494 
4495   if (isIntOrFPConstant(Op))
4496     return true;
4497 
4498   switch (Opcode) {
4499   case ISD::UNDEF:
4500     return PoisonOnly;
4501 
4502   case ISD::BUILD_VECTOR:
4503     // NOTE: BUILD_VECTOR has implicit truncation of wider scalar elements -
4504     // this shouldn't affect the result.
4505     for (unsigned i = 0, e = Op.getNumOperands(); i < e; ++i) {
4506       if (!DemandedElts[i])
4507         continue;
4508       if (!isGuaranteedNotToBeUndefOrPoison(Op.getOperand(i), PoisonOnly,
4509                                             Depth + 1))
4510         return false;
4511     }
4512     return true;
4513 
4514   // TODO: Search for noundef attributes from library functions.
4515 
4516   // TODO: Pointers dereferenced by ISD::LOAD/STORE ops are noundef.
4517 
4518   default:
4519     // Allow the target to implement this method for its nodes.
4520     if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::INTRINSIC_WO_CHAIN ||
4521         Opcode == ISD::INTRINSIC_W_CHAIN || Opcode == ISD::INTRINSIC_VOID)
4522       return TLI->isGuaranteedNotToBeUndefOrPoisonForTargetNode(
4523           Op, DemandedElts, *this, PoisonOnly, Depth);
4524     break;
4525   }
4526 
4527   return false;
4528 }
4529 
4530 bool SelectionDAG::isBaseWithConstantOffset(SDValue Op) const {
4531   if ((Op.getOpcode() != ISD::ADD && Op.getOpcode() != ISD::OR) ||
4532       !isa<ConstantSDNode>(Op.getOperand(1)))
4533     return false;
4534 
4535   if (Op.getOpcode() == ISD::OR &&
4536       !MaskedValueIsZero(Op.getOperand(0), Op.getConstantOperandAPInt(1)))
4537     return false;
4538 
4539   return true;
4540 }
4541 
4542 bool SelectionDAG::isKnownNeverNaN(SDValue Op, bool SNaN, unsigned Depth) const {
4543   // If we're told that NaNs won't happen, assume they won't.
4544   if (getTarget().Options.NoNaNsFPMath || Op->getFlags().hasNoNaNs())
4545     return true;
4546 
4547   if (Depth >= MaxRecursionDepth)
4548     return false; // Limit search depth.
4549 
4550   // TODO: Handle vectors.
4551   // If the value is a constant, we can obviously see if it is a NaN or not.
4552   if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) {
4553     return !C->getValueAPF().isNaN() ||
4554            (SNaN && !C->getValueAPF().isSignaling());
4555   }
4556 
4557   unsigned Opcode = Op.getOpcode();
4558   switch (Opcode) {
4559   case ISD::FADD:
4560   case ISD::FSUB:
4561   case ISD::FMUL:
4562   case ISD::FDIV:
4563   case ISD::FREM:
4564   case ISD::FSIN:
4565   case ISD::FCOS: {
4566     if (SNaN)
4567       return true;
4568     // TODO: Need isKnownNeverInfinity
4569     return false;
4570   }
4571   case ISD::FCANONICALIZE:
4572   case ISD::FEXP:
4573   case ISD::FEXP2:
4574   case ISD::FTRUNC:
4575   case ISD::FFLOOR:
4576   case ISD::FCEIL:
4577   case ISD::FROUND:
4578   case ISD::FROUNDEVEN:
4579   case ISD::FRINT:
4580   case ISD::FNEARBYINT: {
4581     if (SNaN)
4582       return true;
4583     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
4584   }
4585   case ISD::FABS:
4586   case ISD::FNEG:
4587   case ISD::FCOPYSIGN: {
4588     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
4589   }
4590   case ISD::SELECT:
4591     return isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1) &&
4592            isKnownNeverNaN(Op.getOperand(2), SNaN, Depth + 1);
4593   case ISD::FP_EXTEND:
4594   case ISD::FP_ROUND: {
4595     if (SNaN)
4596       return true;
4597     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
4598   }
4599   case ISD::SINT_TO_FP:
4600   case ISD::UINT_TO_FP:
4601     return true;
4602   case ISD::FMA:
4603   case ISD::FMAD: {
4604     if (SNaN)
4605       return true;
4606     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) &&
4607            isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1) &&
4608            isKnownNeverNaN(Op.getOperand(2), SNaN, Depth + 1);
4609   }
4610   case ISD::FSQRT: // Need is known positive
4611   case ISD::FLOG:
4612   case ISD::FLOG2:
4613   case ISD::FLOG10:
4614   case ISD::FPOWI:
4615   case ISD::FPOW: {
4616     if (SNaN)
4617       return true;
4618     // TODO: Refine on operand
4619     return false;
4620   }
4621   case ISD::FMINNUM:
4622   case ISD::FMAXNUM: {
4623     // Only one needs to be known not-nan, since it will be returned if the
4624     // other ends up being one.
4625     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) ||
4626            isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1);
4627   }
4628   case ISD::FMINNUM_IEEE:
4629   case ISD::FMAXNUM_IEEE: {
4630     if (SNaN)
4631       return true;
4632     // This can return a NaN if either operand is an sNaN, or if both operands
4633     // are NaN.
4634     return (isKnownNeverNaN(Op.getOperand(0), false, Depth + 1) &&
4635             isKnownNeverSNaN(Op.getOperand(1), Depth + 1)) ||
4636            (isKnownNeverNaN(Op.getOperand(1), false, Depth + 1) &&
4637             isKnownNeverSNaN(Op.getOperand(0), Depth + 1));
4638   }
4639   case ISD::FMINIMUM:
4640   case ISD::FMAXIMUM: {
4641     // TODO: Does this quiet or return the origina NaN as-is?
4642     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) &&
4643            isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1);
4644   }
4645   case ISD::EXTRACT_VECTOR_ELT: {
4646     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
4647   }
4648   default:
4649     if (Opcode >= ISD::BUILTIN_OP_END ||
4650         Opcode == ISD::INTRINSIC_WO_CHAIN ||
4651         Opcode == ISD::INTRINSIC_W_CHAIN ||
4652         Opcode == ISD::INTRINSIC_VOID) {
4653       return TLI->isKnownNeverNaNForTargetNode(Op, *this, SNaN, Depth);
4654     }
4655 
4656     return false;
4657   }
4658 }
4659 
4660 bool SelectionDAG::isKnownNeverZeroFloat(SDValue Op) const {
4661   assert(Op.getValueType().isFloatingPoint() &&
4662          "Floating point type expected");
4663 
4664   // If the value is a constant, we can obviously see if it is a zero or not.
4665   // TODO: Add BuildVector support.
4666   if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op))
4667     return !C->isZero();
4668   return false;
4669 }
4670 
4671 bool SelectionDAG::isKnownNeverZero(SDValue Op) const {
4672   assert(!Op.getValueType().isFloatingPoint() &&
4673          "Floating point types unsupported - use isKnownNeverZeroFloat");
4674 
4675   // If the value is a constant, we can obviously see if it is a zero or not.
4676   if (ISD::matchUnaryPredicate(Op,
4677                                [](ConstantSDNode *C) { return !C->isZero(); }))
4678     return true;
4679 
4680   // TODO: Recognize more cases here.
4681   switch (Op.getOpcode()) {
4682   default: break;
4683   case ISD::OR:
4684     if (isKnownNeverZero(Op.getOperand(1)) ||
4685         isKnownNeverZero(Op.getOperand(0)))
4686       return true;
4687     break;
4688   }
4689 
4690   return false;
4691 }
4692 
4693 bool SelectionDAG::isEqualTo(SDValue A, SDValue B) const {
4694   // Check the obvious case.
4695   if (A == B) return true;
4696 
4697   // For for negative and positive zero.
4698   if (const ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A))
4699     if (const ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B))
4700       if (CA->isZero() && CB->isZero()) return true;
4701 
4702   // Otherwise they may not be equal.
4703   return false;
4704 }
4705 
4706 // Only bits set in Mask must be negated, other bits may be arbitrary.
4707 SDValue llvm::getBitwiseNotOperand(SDValue V, SDValue Mask, bool AllowUndefs) {
4708   if (isBitwiseNot(V, AllowUndefs))
4709     return V.getOperand(0);
4710 
4711   // Handle any_extend (not (truncate X)) pattern, where Mask only sets
4712   // bits in the non-extended part.
4713   ConstantSDNode *MaskC = isConstOrConstSplat(Mask);
4714   if (!MaskC || V.getOpcode() != ISD::ANY_EXTEND)
4715     return SDValue();
4716   SDValue ExtArg = V.getOperand(0);
4717   if (ExtArg.getScalarValueSizeInBits() >=
4718           MaskC->getAPIntValue().getActiveBits() &&
4719       isBitwiseNot(ExtArg, AllowUndefs) &&
4720       ExtArg.getOperand(0).getOpcode() == ISD::TRUNCATE &&
4721       ExtArg.getOperand(0).getOperand(0).getValueType() == V.getValueType())
4722     return ExtArg.getOperand(0).getOperand(0);
4723   return SDValue();
4724 }
4725 
4726 static bool haveNoCommonBitsSetCommutative(SDValue A, SDValue B) {
4727   // Match masked merge pattern (X & ~M) op (Y & M)
4728   // Including degenerate case (X & ~M) op M
4729   auto MatchNoCommonBitsPattern = [&](SDValue Not, SDValue Mask,
4730                                       SDValue Other) {
4731     if (SDValue NotOperand =
4732             getBitwiseNotOperand(Not, Mask, /* AllowUndefs */ true)) {
4733       if (Other == NotOperand)
4734         return true;
4735       if (Other->getOpcode() == ISD::AND)
4736         return NotOperand == Other->getOperand(0) ||
4737                NotOperand == Other->getOperand(1);
4738     }
4739     return false;
4740   };
4741   if (A->getOpcode() == ISD::AND)
4742     return MatchNoCommonBitsPattern(A->getOperand(0), A->getOperand(1), B) ||
4743            MatchNoCommonBitsPattern(A->getOperand(1), A->getOperand(0), B);
4744   return false;
4745 }
4746 
4747 // FIXME: unify with llvm::haveNoCommonBitsSet.
4748 bool SelectionDAG::haveNoCommonBitsSet(SDValue A, SDValue B) const {
4749   assert(A.getValueType() == B.getValueType() &&
4750          "Values must have the same type");
4751   if (haveNoCommonBitsSetCommutative(A, B) ||
4752       haveNoCommonBitsSetCommutative(B, A))
4753     return true;
4754   return KnownBits::haveNoCommonBitsSet(computeKnownBits(A),
4755                                         computeKnownBits(B));
4756 }
4757 
4758 static SDValue FoldSTEP_VECTOR(const SDLoc &DL, EVT VT, SDValue Step,
4759                                SelectionDAG &DAG) {
4760   if (cast<ConstantSDNode>(Step)->isZero())
4761     return DAG.getConstant(0, DL, VT);
4762 
4763   return SDValue();
4764 }
4765 
4766 static SDValue FoldBUILD_VECTOR(const SDLoc &DL, EVT VT,
4767                                 ArrayRef<SDValue> Ops,
4768                                 SelectionDAG &DAG) {
4769   int NumOps = Ops.size();
4770   assert(NumOps != 0 && "Can't build an empty vector!");
4771   assert(!VT.isScalableVector() &&
4772          "BUILD_VECTOR cannot be used with scalable types");
4773   assert(VT.getVectorNumElements() == (unsigned)NumOps &&
4774          "Incorrect element count in BUILD_VECTOR!");
4775 
4776   // BUILD_VECTOR of UNDEFs is UNDEF.
4777   if (llvm::all_of(Ops, [](SDValue Op) { return Op.isUndef(); }))
4778     return DAG.getUNDEF(VT);
4779 
4780   // BUILD_VECTOR of seq extract/insert from the same vector + type is Identity.
4781   SDValue IdentitySrc;
4782   bool IsIdentity = true;
4783   for (int i = 0; i != NumOps; ++i) {
4784     if (Ops[i].getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
4785         Ops[i].getOperand(0).getValueType() != VT ||
4786         (IdentitySrc && Ops[i].getOperand(0) != IdentitySrc) ||
4787         !isa<ConstantSDNode>(Ops[i].getOperand(1)) ||
4788         cast<ConstantSDNode>(Ops[i].getOperand(1))->getAPIntValue() != i) {
4789       IsIdentity = false;
4790       break;
4791     }
4792     IdentitySrc = Ops[i].getOperand(0);
4793   }
4794   if (IsIdentity)
4795     return IdentitySrc;
4796 
4797   return SDValue();
4798 }
4799 
4800 /// Try to simplify vector concatenation to an input value, undef, or build
4801 /// vector.
4802 static SDValue foldCONCAT_VECTORS(const SDLoc &DL, EVT VT,
4803                                   ArrayRef<SDValue> Ops,
4804                                   SelectionDAG &DAG) {
4805   assert(!Ops.empty() && "Can't concatenate an empty list of vectors!");
4806   assert(llvm::all_of(Ops,
4807                       [Ops](SDValue Op) {
4808                         return Ops[0].getValueType() == Op.getValueType();
4809                       }) &&
4810          "Concatenation of vectors with inconsistent value types!");
4811   assert((Ops[0].getValueType().getVectorElementCount() * Ops.size()) ==
4812              VT.getVectorElementCount() &&
4813          "Incorrect element count in vector concatenation!");
4814 
4815   if (Ops.size() == 1)
4816     return Ops[0];
4817 
4818   // Concat of UNDEFs is UNDEF.
4819   if (llvm::all_of(Ops, [](SDValue Op) { return Op.isUndef(); }))
4820     return DAG.getUNDEF(VT);
4821 
4822   // Scan the operands and look for extract operations from a single source
4823   // that correspond to insertion at the same location via this concatenation:
4824   // concat (extract X, 0*subvec_elts), (extract X, 1*subvec_elts), ...
4825   SDValue IdentitySrc;
4826   bool IsIdentity = true;
4827   for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
4828     SDValue Op = Ops[i];
4829     unsigned IdentityIndex = i * Op.getValueType().getVectorMinNumElements();
4830     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
4831         Op.getOperand(0).getValueType() != VT ||
4832         (IdentitySrc && Op.getOperand(0) != IdentitySrc) ||
4833         Op.getConstantOperandVal(1) != IdentityIndex) {
4834       IsIdentity = false;
4835       break;
4836     }
4837     assert((!IdentitySrc || IdentitySrc == Op.getOperand(0)) &&
4838            "Unexpected identity source vector for concat of extracts");
4839     IdentitySrc = Op.getOperand(0);
4840   }
4841   if (IsIdentity) {
4842     assert(IdentitySrc && "Failed to set source vector of extracts");
4843     return IdentitySrc;
4844   }
4845 
4846   // The code below this point is only designed to work for fixed width
4847   // vectors, so we bail out for now.
4848   if (VT.isScalableVector())
4849     return SDValue();
4850 
4851   // A CONCAT_VECTOR with all UNDEF/BUILD_VECTOR operands can be
4852   // simplified to one big BUILD_VECTOR.
4853   // FIXME: Add support for SCALAR_TO_VECTOR as well.
4854   EVT SVT = VT.getScalarType();
4855   SmallVector<SDValue, 16> Elts;
4856   for (SDValue Op : Ops) {
4857     EVT OpVT = Op.getValueType();
4858     if (Op.isUndef())
4859       Elts.append(OpVT.getVectorNumElements(), DAG.getUNDEF(SVT));
4860     else if (Op.getOpcode() == ISD::BUILD_VECTOR)
4861       Elts.append(Op->op_begin(), Op->op_end());
4862     else
4863       return SDValue();
4864   }
4865 
4866   // BUILD_VECTOR requires all inputs to be of the same type, find the
4867   // maximum type and extend them all.
4868   for (SDValue Op : Elts)
4869     SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
4870 
4871   if (SVT.bitsGT(VT.getScalarType())) {
4872     for (SDValue &Op : Elts) {
4873       if (Op.isUndef())
4874         Op = DAG.getUNDEF(SVT);
4875       else
4876         Op = DAG.getTargetLoweringInfo().isZExtFree(Op.getValueType(), SVT)
4877                  ? DAG.getZExtOrTrunc(Op, DL, SVT)
4878                  : DAG.getSExtOrTrunc(Op, DL, SVT);
4879     }
4880   }
4881 
4882   SDValue V = DAG.getBuildVector(VT, DL, Elts);
4883   NewSDValueDbgMsg(V, "New node fold concat vectors: ", &DAG);
4884   return V;
4885 }
4886 
4887 /// Gets or creates the specified node.
4888 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT) {
4889   FoldingSetNodeID ID;
4890   AddNodeIDNode(ID, Opcode, getVTList(VT), None);
4891   void *IP = nullptr;
4892   if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
4893     return SDValue(E, 0);
4894 
4895   auto *N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(),
4896                               getVTList(VT));
4897   CSEMap.InsertNode(N, IP);
4898 
4899   InsertNode(N);
4900   SDValue V = SDValue(N, 0);
4901   NewSDValueDbgMsg(V, "Creating new node: ", this);
4902   return V;
4903 }
4904 
4905 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
4906                               SDValue Operand) {
4907   SDNodeFlags Flags;
4908   if (Inserter)
4909     Flags = Inserter->getFlags();
4910   return getNode(Opcode, DL, VT, Operand, Flags);
4911 }
4912 
4913 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
4914                               SDValue Operand, const SDNodeFlags Flags) {
4915   assert(Operand.getOpcode() != ISD::DELETED_NODE &&
4916          "Operand is DELETED_NODE!");
4917   // Constant fold unary operations with an integer constant operand. Even
4918   // opaque constant will be folded, because the folding of unary operations
4919   // doesn't create new constants with different values. Nevertheless, the
4920   // opaque flag is preserved during folding to prevent future folding with
4921   // other constants.
4922   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Operand)) {
4923     const APInt &Val = C->getAPIntValue();
4924     switch (Opcode) {
4925     default: break;
4926     case ISD::SIGN_EXTEND:
4927       return getConstant(Val.sextOrTrunc(VT.getSizeInBits()), DL, VT,
4928                          C->isTargetOpcode(), C->isOpaque());
4929     case ISD::TRUNCATE:
4930       if (C->isOpaque())
4931         break;
4932       LLVM_FALLTHROUGH;
4933     case ISD::ZERO_EXTEND:
4934       return getConstant(Val.zextOrTrunc(VT.getSizeInBits()), DL, VT,
4935                          C->isTargetOpcode(), C->isOpaque());
4936     case ISD::ANY_EXTEND:
4937       // Some targets like RISCV prefer to sign extend some types.
4938       if (TLI->isSExtCheaperThanZExt(Operand.getValueType(), VT))
4939         return getConstant(Val.sextOrTrunc(VT.getSizeInBits()), DL, VT,
4940                            C->isTargetOpcode(), C->isOpaque());
4941       return getConstant(Val.zextOrTrunc(VT.getSizeInBits()), DL, VT,
4942                          C->isTargetOpcode(), C->isOpaque());
4943     case ISD::UINT_TO_FP:
4944     case ISD::SINT_TO_FP: {
4945       APFloat apf(EVTToAPFloatSemantics(VT),
4946                   APInt::getZero(VT.getSizeInBits()));
4947       (void)apf.convertFromAPInt(Val,
4948                                  Opcode==ISD::SINT_TO_FP,
4949                                  APFloat::rmNearestTiesToEven);
4950       return getConstantFP(apf, DL, VT);
4951     }
4952     case ISD::BITCAST:
4953       if (VT == MVT::f16 && C->getValueType(0) == MVT::i16)
4954         return getConstantFP(APFloat(APFloat::IEEEhalf(), Val), DL, VT);
4955       if (VT == MVT::f32 && C->getValueType(0) == MVT::i32)
4956         return getConstantFP(APFloat(APFloat::IEEEsingle(), Val), DL, VT);
4957       if (VT == MVT::f64 && C->getValueType(0) == MVT::i64)
4958         return getConstantFP(APFloat(APFloat::IEEEdouble(), Val), DL, VT);
4959       if (VT == MVT::f128 && C->getValueType(0) == MVT::i128)
4960         return getConstantFP(APFloat(APFloat::IEEEquad(), Val), DL, VT);
4961       break;
4962     case ISD::ABS:
4963       return getConstant(Val.abs(), DL, VT, C->isTargetOpcode(),
4964                          C->isOpaque());
4965     case ISD::BITREVERSE:
4966       return getConstant(Val.reverseBits(), DL, VT, C->isTargetOpcode(),
4967                          C->isOpaque());
4968     case ISD::BSWAP:
4969       return getConstant(Val.byteSwap(), DL, VT, C->isTargetOpcode(),
4970                          C->isOpaque());
4971     case ISD::CTPOP:
4972       return getConstant(Val.countPopulation(), DL, VT, C->isTargetOpcode(),
4973                          C->isOpaque());
4974     case ISD::CTLZ:
4975     case ISD::CTLZ_ZERO_UNDEF:
4976       return getConstant(Val.countLeadingZeros(), DL, VT, C->isTargetOpcode(),
4977                          C->isOpaque());
4978     case ISD::CTTZ:
4979     case ISD::CTTZ_ZERO_UNDEF:
4980       return getConstant(Val.countTrailingZeros(), DL, VT, C->isTargetOpcode(),
4981                          C->isOpaque());
4982     case ISD::FP16_TO_FP: {
4983       bool Ignored;
4984       APFloat FPV(APFloat::IEEEhalf(),
4985                   (Val.getBitWidth() == 16) ? Val : Val.trunc(16));
4986 
4987       // This can return overflow, underflow, or inexact; we don't care.
4988       // FIXME need to be more flexible about rounding mode.
4989       (void)FPV.convert(EVTToAPFloatSemantics(VT),
4990                         APFloat::rmNearestTiesToEven, &Ignored);
4991       return getConstantFP(FPV, DL, VT);
4992     }
4993     case ISD::STEP_VECTOR: {
4994       if (SDValue V = FoldSTEP_VECTOR(DL, VT, Operand, *this))
4995         return V;
4996       break;
4997     }
4998     }
4999   }
5000 
5001   // Constant fold unary operations with a floating point constant operand.
5002   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Operand)) {
5003     APFloat V = C->getValueAPF();    // make copy
5004     switch (Opcode) {
5005     case ISD::FNEG:
5006       V.changeSign();
5007       return getConstantFP(V, DL, VT);
5008     case ISD::FABS:
5009       V.clearSign();
5010       return getConstantFP(V, DL, VT);
5011     case ISD::FCEIL: {
5012       APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardPositive);
5013       if (fs == APFloat::opOK || fs == APFloat::opInexact)
5014         return getConstantFP(V, DL, VT);
5015       break;
5016     }
5017     case ISD::FTRUNC: {
5018       APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardZero);
5019       if (fs == APFloat::opOK || fs == APFloat::opInexact)
5020         return getConstantFP(V, DL, VT);
5021       break;
5022     }
5023     case ISD::FFLOOR: {
5024       APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardNegative);
5025       if (fs == APFloat::opOK || fs == APFloat::opInexact)
5026         return getConstantFP(V, DL, VT);
5027       break;
5028     }
5029     case ISD::FP_EXTEND: {
5030       bool ignored;
5031       // This can return overflow, underflow, or inexact; we don't care.
5032       // FIXME need to be more flexible about rounding mode.
5033       (void)V.convert(EVTToAPFloatSemantics(VT),
5034                       APFloat::rmNearestTiesToEven, &ignored);
5035       return getConstantFP(V, DL, VT);
5036     }
5037     case ISD::FP_TO_SINT:
5038     case ISD::FP_TO_UINT: {
5039       bool ignored;
5040       APSInt IntVal(VT.getSizeInBits(), Opcode == ISD::FP_TO_UINT);
5041       // FIXME need to be more flexible about rounding mode.
5042       APFloat::opStatus s =
5043           V.convertToInteger(IntVal, APFloat::rmTowardZero, &ignored);
5044       if (s == APFloat::opInvalidOp) // inexact is OK, in fact usual
5045         break;
5046       return getConstant(IntVal, DL, VT);
5047     }
5048     case ISD::BITCAST:
5049       if (VT == MVT::i16 && C->getValueType(0) == MVT::f16)
5050         return getConstant((uint16_t)V.bitcastToAPInt().getZExtValue(), DL, VT);
5051       if (VT == MVT::i16 && C->getValueType(0) == MVT::bf16)
5052         return getConstant((uint16_t)V.bitcastToAPInt().getZExtValue(), DL, VT);
5053       if (VT == MVT::i32 && C->getValueType(0) == MVT::f32)
5054         return getConstant((uint32_t)V.bitcastToAPInt().getZExtValue(), DL, VT);
5055       if (VT == MVT::i64 && C->getValueType(0) == MVT::f64)
5056         return getConstant(V.bitcastToAPInt().getZExtValue(), DL, VT);
5057       break;
5058     case ISD::FP_TO_FP16: {
5059       bool Ignored;
5060       // This can return overflow, underflow, or inexact; we don't care.
5061       // FIXME need to be more flexible about rounding mode.
5062       (void)V.convert(APFloat::IEEEhalf(),
5063                       APFloat::rmNearestTiesToEven, &Ignored);
5064       return getConstant(V.bitcastToAPInt().getZExtValue(), DL, VT);
5065     }
5066     }
5067   }
5068 
5069   // Constant fold unary operations with a vector integer or float operand.
5070   switch (Opcode) {
5071   default:
5072     // FIXME: Entirely reasonable to perform folding of other unary
5073     // operations here as the need arises.
5074     break;
5075   case ISD::FNEG:
5076   case ISD::FABS:
5077   case ISD::FCEIL:
5078   case ISD::FTRUNC:
5079   case ISD::FFLOOR:
5080   case ISD::FP_EXTEND:
5081   case ISD::FP_TO_SINT:
5082   case ISD::FP_TO_UINT:
5083   case ISD::TRUNCATE:
5084   case ISD::ANY_EXTEND:
5085   case ISD::ZERO_EXTEND:
5086   case ISD::SIGN_EXTEND:
5087   case ISD::UINT_TO_FP:
5088   case ISD::SINT_TO_FP:
5089   case ISD::ABS:
5090   case ISD::BITREVERSE:
5091   case ISD::BSWAP:
5092   case ISD::CTLZ:
5093   case ISD::CTLZ_ZERO_UNDEF:
5094   case ISD::CTTZ:
5095   case ISD::CTTZ_ZERO_UNDEF:
5096   case ISD::CTPOP: {
5097     SDValue Ops = {Operand};
5098     if (SDValue Fold = FoldConstantArithmetic(Opcode, DL, VT, Ops))
5099       return Fold;
5100   }
5101   }
5102 
5103   unsigned OpOpcode = Operand.getNode()->getOpcode();
5104   switch (Opcode) {
5105   case ISD::STEP_VECTOR:
5106     assert(VT.isScalableVector() &&
5107            "STEP_VECTOR can only be used with scalable types");
5108     assert(OpOpcode == ISD::TargetConstant &&
5109            VT.getVectorElementType() == Operand.getValueType() &&
5110            "Unexpected step operand");
5111     break;
5112   case ISD::FREEZE:
5113     assert(VT == Operand.getValueType() && "Unexpected VT!");
5114     if (isGuaranteedNotToBeUndefOrPoison(Operand))
5115       return Operand;
5116     break;
5117   case ISD::TokenFactor:
5118   case ISD::MERGE_VALUES:
5119   case ISD::CONCAT_VECTORS:
5120     return Operand;         // Factor, merge or concat of one node?  No need.
5121   case ISD::BUILD_VECTOR: {
5122     // Attempt to simplify BUILD_VECTOR.
5123     SDValue Ops[] = {Operand};
5124     if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
5125       return V;
5126     break;
5127   }
5128   case ISD::FP_ROUND: llvm_unreachable("Invalid method to make FP_ROUND node");
5129   case ISD::FP_EXTEND:
5130     assert(VT.isFloatingPoint() &&
5131            Operand.getValueType().isFloatingPoint() && "Invalid FP cast!");
5132     if (Operand.getValueType() == VT) return Operand;  // noop conversion.
5133     assert((!VT.isVector() ||
5134             VT.getVectorElementCount() ==
5135             Operand.getValueType().getVectorElementCount()) &&
5136            "Vector element count mismatch!");
5137     assert(Operand.getValueType().bitsLT(VT) &&
5138            "Invalid fpext node, dst < src!");
5139     if (Operand.isUndef())
5140       return getUNDEF(VT);
5141     break;
5142   case ISD::FP_TO_SINT:
5143   case ISD::FP_TO_UINT:
5144     if (Operand.isUndef())
5145       return getUNDEF(VT);
5146     break;
5147   case ISD::SINT_TO_FP:
5148   case ISD::UINT_TO_FP:
5149     // [us]itofp(undef) = 0, because the result value is bounded.
5150     if (Operand.isUndef())
5151       return getConstantFP(0.0, DL, VT);
5152     break;
5153   case ISD::SIGN_EXTEND:
5154     assert(VT.isInteger() && Operand.getValueType().isInteger() &&
5155            "Invalid SIGN_EXTEND!");
5156     assert(VT.isVector() == Operand.getValueType().isVector() &&
5157            "SIGN_EXTEND result type type should be vector iff the operand "
5158            "type is vector!");
5159     if (Operand.getValueType() == VT) return Operand;   // noop extension
5160     assert((!VT.isVector() ||
5161             VT.getVectorElementCount() ==
5162                 Operand.getValueType().getVectorElementCount()) &&
5163            "Vector element count mismatch!");
5164     assert(Operand.getValueType().bitsLT(VT) &&
5165            "Invalid sext node, dst < src!");
5166     if (OpOpcode == ISD::SIGN_EXTEND || OpOpcode == ISD::ZERO_EXTEND)
5167       return getNode(OpOpcode, DL, VT, Operand.getOperand(0));
5168     if (OpOpcode == ISD::UNDEF)
5169       // sext(undef) = 0, because the top bits will all be the same.
5170       return getConstant(0, DL, VT);
5171     break;
5172   case ISD::ZERO_EXTEND:
5173     assert(VT.isInteger() && Operand.getValueType().isInteger() &&
5174            "Invalid ZERO_EXTEND!");
5175     assert(VT.isVector() == Operand.getValueType().isVector() &&
5176            "ZERO_EXTEND result type type should be vector iff the operand "
5177            "type is vector!");
5178     if (Operand.getValueType() == VT) return Operand;   // noop extension
5179     assert((!VT.isVector() ||
5180             VT.getVectorElementCount() ==
5181                 Operand.getValueType().getVectorElementCount()) &&
5182            "Vector element count mismatch!");
5183     assert(Operand.getValueType().bitsLT(VT) &&
5184            "Invalid zext node, dst < src!");
5185     if (OpOpcode == ISD::ZERO_EXTEND)   // (zext (zext x)) -> (zext x)
5186       return getNode(ISD::ZERO_EXTEND, DL, VT, Operand.getOperand(0));
5187     if (OpOpcode == ISD::UNDEF)
5188       // zext(undef) = 0, because the top bits will be zero.
5189       return getConstant(0, DL, VT);
5190     break;
5191   case ISD::ANY_EXTEND:
5192     assert(VT.isInteger() && Operand.getValueType().isInteger() &&
5193            "Invalid ANY_EXTEND!");
5194     assert(VT.isVector() == Operand.getValueType().isVector() &&
5195            "ANY_EXTEND result type type should be vector iff the operand "
5196            "type is vector!");
5197     if (Operand.getValueType() == VT) return Operand;   // noop extension
5198     assert((!VT.isVector() ||
5199             VT.getVectorElementCount() ==
5200                 Operand.getValueType().getVectorElementCount()) &&
5201            "Vector element count mismatch!");
5202     assert(Operand.getValueType().bitsLT(VT) &&
5203            "Invalid anyext node, dst < src!");
5204 
5205     if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
5206         OpOpcode == ISD::ANY_EXTEND)
5207       // (ext (zext x)) -> (zext x)  and  (ext (sext x)) -> (sext x)
5208       return getNode(OpOpcode, DL, VT, Operand.getOperand(0));
5209     if (OpOpcode == ISD::UNDEF)
5210       return getUNDEF(VT);
5211 
5212     // (ext (trunc x)) -> x
5213     if (OpOpcode == ISD::TRUNCATE) {
5214       SDValue OpOp = Operand.getOperand(0);
5215       if (OpOp.getValueType() == VT) {
5216         transferDbgValues(Operand, OpOp);
5217         return OpOp;
5218       }
5219     }
5220     break;
5221   case ISD::TRUNCATE:
5222     assert(VT.isInteger() && Operand.getValueType().isInteger() &&
5223            "Invalid TRUNCATE!");
5224     assert(VT.isVector() == Operand.getValueType().isVector() &&
5225            "TRUNCATE result type type should be vector iff the operand "
5226            "type is vector!");
5227     if (Operand.getValueType() == VT) return Operand;   // noop truncate
5228     assert((!VT.isVector() ||
5229             VT.getVectorElementCount() ==
5230                 Operand.getValueType().getVectorElementCount()) &&
5231            "Vector element count mismatch!");
5232     assert(Operand.getValueType().bitsGT(VT) &&
5233            "Invalid truncate node, src < dst!");
5234     if (OpOpcode == ISD::TRUNCATE)
5235       return getNode(ISD::TRUNCATE, DL, VT, Operand.getOperand(0));
5236     if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
5237         OpOpcode == ISD::ANY_EXTEND) {
5238       // If the source is smaller than the dest, we still need an extend.
5239       if (Operand.getOperand(0).getValueType().getScalarType()
5240             .bitsLT(VT.getScalarType()))
5241         return getNode(OpOpcode, DL, VT, Operand.getOperand(0));
5242       if (Operand.getOperand(0).getValueType().bitsGT(VT))
5243         return getNode(ISD::TRUNCATE, DL, VT, Operand.getOperand(0));
5244       return Operand.getOperand(0);
5245     }
5246     if (OpOpcode == ISD::UNDEF)
5247       return getUNDEF(VT);
5248     if (OpOpcode == ISD::VSCALE && !NewNodesMustHaveLegalTypes)
5249       return getVScale(DL, VT, Operand.getConstantOperandAPInt(0));
5250     break;
5251   case ISD::ANY_EXTEND_VECTOR_INREG:
5252   case ISD::ZERO_EXTEND_VECTOR_INREG:
5253   case ISD::SIGN_EXTEND_VECTOR_INREG:
5254     assert(VT.isVector() && "This DAG node is restricted to vector types.");
5255     assert(Operand.getValueType().bitsLE(VT) &&
5256            "The input must be the same size or smaller than the result.");
5257     assert(VT.getVectorMinNumElements() <
5258                Operand.getValueType().getVectorMinNumElements() &&
5259            "The destination vector type must have fewer lanes than the input.");
5260     break;
5261   case ISD::ABS:
5262     assert(VT.isInteger() && VT == Operand.getValueType() &&
5263            "Invalid ABS!");
5264     if (OpOpcode == ISD::UNDEF)
5265       return getConstant(0, DL, VT);
5266     break;
5267   case ISD::BSWAP:
5268     assert(VT.isInteger() && VT == Operand.getValueType() &&
5269            "Invalid BSWAP!");
5270     assert((VT.getScalarSizeInBits() % 16 == 0) &&
5271            "BSWAP types must be a multiple of 16 bits!");
5272     if (OpOpcode == ISD::UNDEF)
5273       return getUNDEF(VT);
5274     // bswap(bswap(X)) -> X.
5275     if (OpOpcode == ISD::BSWAP)
5276       return Operand.getOperand(0);
5277     break;
5278   case ISD::BITREVERSE:
5279     assert(VT.isInteger() && VT == Operand.getValueType() &&
5280            "Invalid BITREVERSE!");
5281     if (OpOpcode == ISD::UNDEF)
5282       return getUNDEF(VT);
5283     break;
5284   case ISD::BITCAST:
5285     assert(VT.getSizeInBits() == Operand.getValueSizeInBits() &&
5286            "Cannot BITCAST between types of different sizes!");
5287     if (VT == Operand.getValueType()) return Operand;  // noop conversion.
5288     if (OpOpcode == ISD::BITCAST)  // bitconv(bitconv(x)) -> bitconv(x)
5289       return getNode(ISD::BITCAST, DL, VT, Operand.getOperand(0));
5290     if (OpOpcode == ISD::UNDEF)
5291       return getUNDEF(VT);
5292     break;
5293   case ISD::SCALAR_TO_VECTOR:
5294     assert(VT.isVector() && !Operand.getValueType().isVector() &&
5295            (VT.getVectorElementType() == Operand.getValueType() ||
5296             (VT.getVectorElementType().isInteger() &&
5297              Operand.getValueType().isInteger() &&
5298              VT.getVectorElementType().bitsLE(Operand.getValueType()))) &&
5299            "Illegal SCALAR_TO_VECTOR node!");
5300     if (OpOpcode == ISD::UNDEF)
5301       return getUNDEF(VT);
5302     // scalar_to_vector(extract_vector_elt V, 0) -> V, top bits are undefined.
5303     if (OpOpcode == ISD::EXTRACT_VECTOR_ELT &&
5304         isa<ConstantSDNode>(Operand.getOperand(1)) &&
5305         Operand.getConstantOperandVal(1) == 0 &&
5306         Operand.getOperand(0).getValueType() == VT)
5307       return Operand.getOperand(0);
5308     break;
5309   case ISD::FNEG:
5310     // Negation of an unknown bag of bits is still completely undefined.
5311     if (OpOpcode == ISD::UNDEF)
5312       return getUNDEF(VT);
5313 
5314     if (OpOpcode == ISD::FNEG)  // --X -> X
5315       return Operand.getOperand(0);
5316     break;
5317   case ISD::FABS:
5318     if (OpOpcode == ISD::FNEG)  // abs(-X) -> abs(X)
5319       return getNode(ISD::FABS, DL, VT, Operand.getOperand(0));
5320     break;
5321   case ISD::VSCALE:
5322     assert(VT == Operand.getValueType() && "Unexpected VT!");
5323     break;
5324   case ISD::CTPOP:
5325     if (Operand.getValueType().getScalarType() == MVT::i1)
5326       return Operand;
5327     break;
5328   case ISD::CTLZ:
5329   case ISD::CTTZ:
5330     if (Operand.getValueType().getScalarType() == MVT::i1)
5331       return getNOT(DL, Operand, Operand.getValueType());
5332     break;
5333   case ISD::VECREDUCE_ADD:
5334     if (Operand.getValueType().getScalarType() == MVT::i1)
5335       return getNode(ISD::VECREDUCE_XOR, DL, VT, Operand);
5336     break;
5337   case ISD::VECREDUCE_SMIN:
5338   case ISD::VECREDUCE_UMAX:
5339     if (Operand.getValueType().getScalarType() == MVT::i1)
5340       return getNode(ISD::VECREDUCE_OR, DL, VT, Operand);
5341     break;
5342   case ISD::VECREDUCE_SMAX:
5343   case ISD::VECREDUCE_UMIN:
5344     if (Operand.getValueType().getScalarType() == MVT::i1)
5345       return getNode(ISD::VECREDUCE_AND, DL, VT, Operand);
5346     break;
5347   }
5348 
5349   SDNode *N;
5350   SDVTList VTs = getVTList(VT);
5351   SDValue Ops[] = {Operand};
5352   if (VT != MVT::Glue) { // Don't CSE flag producing nodes
5353     FoldingSetNodeID ID;
5354     AddNodeIDNode(ID, Opcode, VTs, Ops);
5355     void *IP = nullptr;
5356     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
5357       E->intersectFlagsWith(Flags);
5358       return SDValue(E, 0);
5359     }
5360 
5361     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
5362     N->setFlags(Flags);
5363     createOperands(N, Ops);
5364     CSEMap.InsertNode(N, IP);
5365   } else {
5366     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
5367     createOperands(N, Ops);
5368   }
5369 
5370   InsertNode(N);
5371   SDValue V = SDValue(N, 0);
5372   NewSDValueDbgMsg(V, "Creating new node: ", this);
5373   return V;
5374 }
5375 
5376 static llvm::Optional<APInt> FoldValue(unsigned Opcode, const APInt &C1,
5377                                        const APInt &C2) {
5378   switch (Opcode) {
5379   case ISD::ADD:  return C1 + C2;
5380   case ISD::SUB:  return C1 - C2;
5381   case ISD::MUL:  return C1 * C2;
5382   case ISD::AND:  return C1 & C2;
5383   case ISD::OR:   return C1 | C2;
5384   case ISD::XOR:  return C1 ^ C2;
5385   case ISD::SHL:  return C1 << C2;
5386   case ISD::SRL:  return C1.lshr(C2);
5387   case ISD::SRA:  return C1.ashr(C2);
5388   case ISD::ROTL: return C1.rotl(C2);
5389   case ISD::ROTR: return C1.rotr(C2);
5390   case ISD::SMIN: return C1.sle(C2) ? C1 : C2;
5391   case ISD::SMAX: return C1.sge(C2) ? C1 : C2;
5392   case ISD::UMIN: return C1.ule(C2) ? C1 : C2;
5393   case ISD::UMAX: return C1.uge(C2) ? C1 : C2;
5394   case ISD::SADDSAT: return C1.sadd_sat(C2);
5395   case ISD::UADDSAT: return C1.uadd_sat(C2);
5396   case ISD::SSUBSAT: return C1.ssub_sat(C2);
5397   case ISD::USUBSAT: return C1.usub_sat(C2);
5398   case ISD::SSHLSAT: return C1.sshl_sat(C2);
5399   case ISD::USHLSAT: return C1.ushl_sat(C2);
5400   case ISD::UDIV:
5401     if (!C2.getBoolValue())
5402       break;
5403     return C1.udiv(C2);
5404   case ISD::UREM:
5405     if (!C2.getBoolValue())
5406       break;
5407     return C1.urem(C2);
5408   case ISD::SDIV:
5409     if (!C2.getBoolValue())
5410       break;
5411     return C1.sdiv(C2);
5412   case ISD::SREM:
5413     if (!C2.getBoolValue())
5414       break;
5415     return C1.srem(C2);
5416   case ISD::MULHS: {
5417     unsigned FullWidth = C1.getBitWidth() * 2;
5418     APInt C1Ext = C1.sext(FullWidth);
5419     APInt C2Ext = C2.sext(FullWidth);
5420     return (C1Ext * C2Ext).extractBits(C1.getBitWidth(), C1.getBitWidth());
5421   }
5422   case ISD::MULHU: {
5423     unsigned FullWidth = C1.getBitWidth() * 2;
5424     APInt C1Ext = C1.zext(FullWidth);
5425     APInt C2Ext = C2.zext(FullWidth);
5426     return (C1Ext * C2Ext).extractBits(C1.getBitWidth(), C1.getBitWidth());
5427   }
5428   case ISD::AVGFLOORS: {
5429     unsigned FullWidth = C1.getBitWidth() + 1;
5430     APInt C1Ext = C1.sext(FullWidth);
5431     APInt C2Ext = C2.sext(FullWidth);
5432     return (C1Ext + C2Ext).extractBits(C1.getBitWidth(), 1);
5433   }
5434   case ISD::AVGFLOORU: {
5435     unsigned FullWidth = C1.getBitWidth() + 1;
5436     APInt C1Ext = C1.zext(FullWidth);
5437     APInt C2Ext = C2.zext(FullWidth);
5438     return (C1Ext + C2Ext).extractBits(C1.getBitWidth(), 1);
5439   }
5440   case ISD::AVGCEILS: {
5441     unsigned FullWidth = C1.getBitWidth() + 1;
5442     APInt C1Ext = C1.sext(FullWidth);
5443     APInt C2Ext = C2.sext(FullWidth);
5444     return (C1Ext + C2Ext + 1).extractBits(C1.getBitWidth(), 1);
5445   }
5446   case ISD::AVGCEILU: {
5447     unsigned FullWidth = C1.getBitWidth() + 1;
5448     APInt C1Ext = C1.zext(FullWidth);
5449     APInt C2Ext = C2.zext(FullWidth);
5450     return (C1Ext + C2Ext + 1).extractBits(C1.getBitWidth(), 1);
5451   }
5452   }
5453   return llvm::None;
5454 }
5455 
5456 SDValue SelectionDAG::FoldSymbolOffset(unsigned Opcode, EVT VT,
5457                                        const GlobalAddressSDNode *GA,
5458                                        const SDNode *N2) {
5459   if (GA->getOpcode() != ISD::GlobalAddress)
5460     return SDValue();
5461   if (!TLI->isOffsetFoldingLegal(GA))
5462     return SDValue();
5463   auto *C2 = dyn_cast<ConstantSDNode>(N2);
5464   if (!C2)
5465     return SDValue();
5466   int64_t Offset = C2->getSExtValue();
5467   switch (Opcode) {
5468   case ISD::ADD: break;
5469   case ISD::SUB: Offset = -uint64_t(Offset); break;
5470   default: return SDValue();
5471   }
5472   return getGlobalAddress(GA->getGlobal(), SDLoc(C2), VT,
5473                           GA->getOffset() + uint64_t(Offset));
5474 }
5475 
5476 bool SelectionDAG::isUndef(unsigned Opcode, ArrayRef<SDValue> Ops) {
5477   switch (Opcode) {
5478   case ISD::SDIV:
5479   case ISD::UDIV:
5480   case ISD::SREM:
5481   case ISD::UREM: {
5482     // If a divisor is zero/undef or any element of a divisor vector is
5483     // zero/undef, the whole op is undef.
5484     assert(Ops.size() == 2 && "Div/rem should have 2 operands");
5485     SDValue Divisor = Ops[1];
5486     if (Divisor.isUndef() || isNullConstant(Divisor))
5487       return true;
5488 
5489     return ISD::isBuildVectorOfConstantSDNodes(Divisor.getNode()) &&
5490            llvm::any_of(Divisor->op_values(),
5491                         [](SDValue V) { return V.isUndef() ||
5492                                         isNullConstant(V); });
5493     // TODO: Handle signed overflow.
5494   }
5495   // TODO: Handle oversized shifts.
5496   default:
5497     return false;
5498   }
5499 }
5500 
5501 SDValue SelectionDAG::FoldConstantArithmetic(unsigned Opcode, const SDLoc &DL,
5502                                              EVT VT, ArrayRef<SDValue> Ops) {
5503   // If the opcode is a target-specific ISD node, there's nothing we can
5504   // do here and the operand rules may not line up with the below, so
5505   // bail early.
5506   // We can't create a scalar CONCAT_VECTORS so skip it. It will break
5507   // for concats involving SPLAT_VECTOR. Concats of BUILD_VECTORS are handled by
5508   // foldCONCAT_VECTORS in getNode before this is called.
5509   if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::CONCAT_VECTORS)
5510     return SDValue();
5511 
5512   unsigned NumOps = Ops.size();
5513   if (NumOps == 0)
5514     return SDValue();
5515 
5516   if (isUndef(Opcode, Ops))
5517     return getUNDEF(VT);
5518 
5519   // Handle binops special cases.
5520   if (NumOps == 2) {
5521     if (SDValue CFP = foldConstantFPMath(Opcode, DL, VT, Ops[0], Ops[1]))
5522       return CFP;
5523 
5524     if (auto *C1 = dyn_cast<ConstantSDNode>(Ops[0])) {
5525       if (auto *C2 = dyn_cast<ConstantSDNode>(Ops[1])) {
5526         if (C1->isOpaque() || C2->isOpaque())
5527           return SDValue();
5528 
5529         Optional<APInt> FoldAttempt =
5530             FoldValue(Opcode, C1->getAPIntValue(), C2->getAPIntValue());
5531         if (!FoldAttempt)
5532           return SDValue();
5533 
5534         SDValue Folded = getConstant(FoldAttempt.getValue(), DL, VT);
5535         assert((!Folded || !VT.isVector()) &&
5536                "Can't fold vectors ops with scalar operands");
5537         return Folded;
5538       }
5539     }
5540 
5541     // fold (add Sym, c) -> Sym+c
5542     if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Ops[0]))
5543       return FoldSymbolOffset(Opcode, VT, GA, Ops[1].getNode());
5544     if (TLI->isCommutativeBinOp(Opcode))
5545       if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Ops[1]))
5546         return FoldSymbolOffset(Opcode, VT, GA, Ops[0].getNode());
5547   }
5548 
5549   // This is for vector folding only from here on.
5550   if (!VT.isVector())
5551     return SDValue();
5552 
5553   ElementCount NumElts = VT.getVectorElementCount();
5554 
5555   // See if we can fold through bitcasted integer ops.
5556   // TODO: Can we handle undef elements?
5557   if (NumOps == 2 && VT.isFixedLengthVector() && VT.isInteger() &&
5558       Ops[0].getValueType() == VT && Ops[1].getValueType() == VT &&
5559       Ops[0].getOpcode() == ISD::BITCAST &&
5560       Ops[1].getOpcode() == ISD::BITCAST) {
5561     SDValue N1 = peekThroughBitcasts(Ops[0]);
5562     SDValue N2 = peekThroughBitcasts(Ops[1]);
5563     auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
5564     auto *BV2 = dyn_cast<BuildVectorSDNode>(N2);
5565     EVT BVVT = N1.getValueType();
5566     if (BV1 && BV2 && BVVT.isInteger() && BVVT == N2.getValueType()) {
5567       bool IsLE = getDataLayout().isLittleEndian();
5568       unsigned EltBits = VT.getScalarSizeInBits();
5569       SmallVector<APInt> RawBits1, RawBits2;
5570       BitVector UndefElts1, UndefElts2;
5571       if (BV1->getConstantRawBits(IsLE, EltBits, RawBits1, UndefElts1) &&
5572           BV2->getConstantRawBits(IsLE, EltBits, RawBits2, UndefElts2) &&
5573           UndefElts1.none() && UndefElts2.none()) {
5574         SmallVector<APInt> RawBits;
5575         for (unsigned I = 0, E = NumElts.getFixedValue(); I != E; ++I) {
5576           Optional<APInt> Fold = FoldValue(Opcode, RawBits1[I], RawBits2[I]);
5577           if (!Fold)
5578             break;
5579           RawBits.push_back(Fold.getValue());
5580         }
5581         if (RawBits.size() == NumElts.getFixedValue()) {
5582           // We have constant folded, but we need to cast this again back to
5583           // the original (possibly legalized) type.
5584           SmallVector<APInt> DstBits;
5585           BitVector DstUndefs;
5586           BuildVectorSDNode::recastRawBits(IsLE, BVVT.getScalarSizeInBits(),
5587                                            DstBits, RawBits, DstUndefs,
5588                                            BitVector(RawBits.size(), false));
5589           EVT BVEltVT = BV1->getOperand(0).getValueType();
5590           unsigned BVEltBits = BVEltVT.getSizeInBits();
5591           SmallVector<SDValue> Ops(DstBits.size(), getUNDEF(BVEltVT));
5592           for (unsigned I = 0, E = DstBits.size(); I != E; ++I) {
5593             if (DstUndefs[I])
5594               continue;
5595             Ops[I] = getConstant(DstBits[I].sext(BVEltBits), DL, BVEltVT);
5596           }
5597           return getBitcast(VT, getBuildVector(BVVT, DL, Ops));
5598         }
5599       }
5600     }
5601   }
5602 
5603   // Fold (mul step_vector(C0), C1) to (step_vector(C0 * C1)).
5604   //      (shl step_vector(C0), C1) -> (step_vector(C0 << C1))
5605   if ((Opcode == ISD::MUL || Opcode == ISD::SHL) &&
5606       Ops[0].getOpcode() == ISD::STEP_VECTOR) {
5607     APInt RHSVal;
5608     if (ISD::isConstantSplatVector(Ops[1].getNode(), RHSVal)) {
5609       APInt NewStep = Opcode == ISD::MUL
5610                           ? Ops[0].getConstantOperandAPInt(0) * RHSVal
5611                           : Ops[0].getConstantOperandAPInt(0) << RHSVal;
5612       return getStepVector(DL, VT, NewStep);
5613     }
5614   }
5615 
5616   auto IsScalarOrSameVectorSize = [NumElts](const SDValue &Op) {
5617     return !Op.getValueType().isVector() ||
5618            Op.getValueType().getVectorElementCount() == NumElts;
5619   };
5620 
5621   auto IsBuildVectorSplatVectorOrUndef = [](const SDValue &Op) {
5622     return Op.isUndef() || Op.getOpcode() == ISD::CONDCODE ||
5623            Op.getOpcode() == ISD::BUILD_VECTOR ||
5624            Op.getOpcode() == ISD::SPLAT_VECTOR;
5625   };
5626 
5627   // All operands must be vector types with the same number of elements as
5628   // the result type and must be either UNDEF or a build/splat vector
5629   // or UNDEF scalars.
5630   if (!llvm::all_of(Ops, IsBuildVectorSplatVectorOrUndef) ||
5631       !llvm::all_of(Ops, IsScalarOrSameVectorSize))
5632     return SDValue();
5633 
5634   // If we are comparing vectors, then the result needs to be a i1 boolean that
5635   // is then extended back to the legal result type depending on how booleans
5636   // are represented.
5637   EVT SVT = (Opcode == ISD::SETCC ? MVT::i1 : VT.getScalarType());
5638   ISD::NodeType ExtendCode =
5639       (Opcode == ISD::SETCC && SVT != VT.getScalarType())
5640           ? TargetLowering::getExtendForContent(TLI->getBooleanContents(VT))
5641           : ISD::SIGN_EXTEND;
5642 
5643   // Find legal integer scalar type for constant promotion and
5644   // ensure that its scalar size is at least as large as source.
5645   EVT LegalSVT = VT.getScalarType();
5646   if (NewNodesMustHaveLegalTypes && LegalSVT.isInteger()) {
5647     LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT);
5648     if (LegalSVT.bitsLT(VT.getScalarType()))
5649       return SDValue();
5650   }
5651 
5652   // For scalable vector types we know we're dealing with SPLAT_VECTORs. We
5653   // only have one operand to check. For fixed-length vector types we may have
5654   // a combination of BUILD_VECTOR and SPLAT_VECTOR.
5655   unsigned NumVectorElts = NumElts.isScalable() ? 1 : NumElts.getFixedValue();
5656 
5657   // Constant fold each scalar lane separately.
5658   SmallVector<SDValue, 4> ScalarResults;
5659   for (unsigned I = 0; I != NumVectorElts; I++) {
5660     SmallVector<SDValue, 4> ScalarOps;
5661     for (SDValue Op : Ops) {
5662       EVT InSVT = Op.getValueType().getScalarType();
5663       if (Op.getOpcode() != ISD::BUILD_VECTOR &&
5664           Op.getOpcode() != ISD::SPLAT_VECTOR) {
5665         if (Op.isUndef())
5666           ScalarOps.push_back(getUNDEF(InSVT));
5667         else
5668           ScalarOps.push_back(Op);
5669         continue;
5670       }
5671 
5672       SDValue ScalarOp =
5673           Op.getOperand(Op.getOpcode() == ISD::SPLAT_VECTOR ? 0 : I);
5674       EVT ScalarVT = ScalarOp.getValueType();
5675 
5676       // Build vector (integer) scalar operands may need implicit
5677       // truncation - do this before constant folding.
5678       if (ScalarVT.isInteger() && ScalarVT.bitsGT(InSVT)) {
5679         // Don't create illegally-typed nodes unless they're constants or undef
5680         // - if we fail to constant fold we can't guarantee the (dead) nodes
5681         // we're creating will be cleaned up before being visited for
5682         // legalization.
5683         if (NewNodesMustHaveLegalTypes && !ScalarOp.isUndef() &&
5684             !isa<ConstantSDNode>(ScalarOp) &&
5685             TLI->getTypeAction(*getContext(), InSVT) !=
5686                 TargetLowering::TypeLegal)
5687           return SDValue();
5688         ScalarOp = getNode(ISD::TRUNCATE, DL, InSVT, ScalarOp);
5689       }
5690 
5691       ScalarOps.push_back(ScalarOp);
5692     }
5693 
5694     // Constant fold the scalar operands.
5695     SDValue ScalarResult = getNode(Opcode, DL, SVT, ScalarOps);
5696 
5697     // Legalize the (integer) scalar constant if necessary.
5698     if (LegalSVT != SVT)
5699       ScalarResult = getNode(ExtendCode, DL, LegalSVT, ScalarResult);
5700 
5701     // Scalar folding only succeeded if the result is a constant or UNDEF.
5702     if (!ScalarResult.isUndef() && ScalarResult.getOpcode() != ISD::Constant &&
5703         ScalarResult.getOpcode() != ISD::ConstantFP)
5704       return SDValue();
5705     ScalarResults.push_back(ScalarResult);
5706   }
5707 
5708   SDValue V = NumElts.isScalable() ? getSplatVector(VT, DL, ScalarResults[0])
5709                                    : getBuildVector(VT, DL, ScalarResults);
5710   NewSDValueDbgMsg(V, "New node fold constant vector: ", this);
5711   return V;
5712 }
5713 
5714 SDValue SelectionDAG::foldConstantFPMath(unsigned Opcode, const SDLoc &DL,
5715                                          EVT VT, SDValue N1, SDValue N2) {
5716   // TODO: We don't do any constant folding for strict FP opcodes here, but we
5717   //       should. That will require dealing with a potentially non-default
5718   //       rounding mode, checking the "opStatus" return value from the APFloat
5719   //       math calculations, and possibly other variations.
5720   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1, /*AllowUndefs*/ false);
5721   ConstantFPSDNode *N2CFP = isConstOrConstSplatFP(N2, /*AllowUndefs*/ false);
5722   if (N1CFP && N2CFP) {
5723     APFloat C1 = N1CFP->getValueAPF(); // make copy
5724     const APFloat &C2 = N2CFP->getValueAPF();
5725     switch (Opcode) {
5726     case ISD::FADD:
5727       C1.add(C2, APFloat::rmNearestTiesToEven);
5728       return getConstantFP(C1, DL, VT);
5729     case ISD::FSUB:
5730       C1.subtract(C2, APFloat::rmNearestTiesToEven);
5731       return getConstantFP(C1, DL, VT);
5732     case ISD::FMUL:
5733       C1.multiply(C2, APFloat::rmNearestTiesToEven);
5734       return getConstantFP(C1, DL, VT);
5735     case ISD::FDIV:
5736       C1.divide(C2, APFloat::rmNearestTiesToEven);
5737       return getConstantFP(C1, DL, VT);
5738     case ISD::FREM:
5739       C1.mod(C2);
5740       return getConstantFP(C1, DL, VT);
5741     case ISD::FCOPYSIGN:
5742       C1.copySign(C2);
5743       return getConstantFP(C1, DL, VT);
5744     case ISD::FMINNUM:
5745       return getConstantFP(minnum(C1, C2), DL, VT);
5746     case ISD::FMAXNUM:
5747       return getConstantFP(maxnum(C1, C2), DL, VT);
5748     case ISD::FMINIMUM:
5749       return getConstantFP(minimum(C1, C2), DL, VT);
5750     case ISD::FMAXIMUM:
5751       return getConstantFP(maximum(C1, C2), DL, VT);
5752     default: break;
5753     }
5754   }
5755   if (N1CFP && Opcode == ISD::FP_ROUND) {
5756     APFloat C1 = N1CFP->getValueAPF();    // make copy
5757     bool Unused;
5758     // This can return overflow, underflow, or inexact; we don't care.
5759     // FIXME need to be more flexible about rounding mode.
5760     (void) C1.convert(EVTToAPFloatSemantics(VT), APFloat::rmNearestTiesToEven,
5761                       &Unused);
5762     return getConstantFP(C1, DL, VT);
5763   }
5764 
5765   switch (Opcode) {
5766   case ISD::FSUB:
5767     // -0.0 - undef --> undef (consistent with "fneg undef")
5768     if (ConstantFPSDNode *N1C = isConstOrConstSplatFP(N1, /*AllowUndefs*/ true))
5769       if (N1C && N1C->getValueAPF().isNegZero() && N2.isUndef())
5770         return getUNDEF(VT);
5771     LLVM_FALLTHROUGH;
5772 
5773   case ISD::FADD:
5774   case ISD::FMUL:
5775   case ISD::FDIV:
5776   case ISD::FREM:
5777     // If both operands are undef, the result is undef. If 1 operand is undef,
5778     // the result is NaN. This should match the behavior of the IR optimizer.
5779     if (N1.isUndef() && N2.isUndef())
5780       return getUNDEF(VT);
5781     if (N1.isUndef() || N2.isUndef())
5782       return getConstantFP(APFloat::getNaN(EVTToAPFloatSemantics(VT)), DL, VT);
5783   }
5784   return SDValue();
5785 }
5786 
5787 SDValue SelectionDAG::getAssertAlign(const SDLoc &DL, SDValue Val, Align A) {
5788   assert(Val.getValueType().isInteger() && "Invalid AssertAlign!");
5789 
5790   // There's no need to assert on a byte-aligned pointer. All pointers are at
5791   // least byte aligned.
5792   if (A == Align(1))
5793     return Val;
5794 
5795   FoldingSetNodeID ID;
5796   AddNodeIDNode(ID, ISD::AssertAlign, getVTList(Val.getValueType()), {Val});
5797   ID.AddInteger(A.value());
5798 
5799   void *IP = nullptr;
5800   if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
5801     return SDValue(E, 0);
5802 
5803   auto *N = newSDNode<AssertAlignSDNode>(DL.getIROrder(), DL.getDebugLoc(),
5804                                          Val.getValueType(), A);
5805   createOperands(N, {Val});
5806 
5807   CSEMap.InsertNode(N, IP);
5808   InsertNode(N);
5809 
5810   SDValue V(N, 0);
5811   NewSDValueDbgMsg(V, "Creating new node: ", this);
5812   return V;
5813 }
5814 
5815 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
5816                               SDValue N1, SDValue N2) {
5817   SDNodeFlags Flags;
5818   if (Inserter)
5819     Flags = Inserter->getFlags();
5820   return getNode(Opcode, DL, VT, N1, N2, Flags);
5821 }
5822 
5823 void SelectionDAG::canonicalizeCommutativeBinop(unsigned Opcode, SDValue &N1,
5824                                                 SDValue &N2) const {
5825   if (!TLI->isCommutativeBinOp(Opcode))
5826     return;
5827 
5828   // Canonicalize:
5829   //   binop(const, nonconst) -> binop(nonconst, const)
5830   bool IsN1C = isConstantIntBuildVectorOrConstantInt(N1);
5831   bool IsN2C = isConstantIntBuildVectorOrConstantInt(N2);
5832   bool IsN1CFP = isConstantFPBuildVectorOrConstantFP(N1);
5833   bool IsN2CFP = isConstantFPBuildVectorOrConstantFP(N2);
5834   if ((IsN1C && !IsN2C) || (IsN1CFP && !IsN2CFP))
5835     std::swap(N1, N2);
5836 
5837   // Canonicalize:
5838   //  binop(splat(x), step_vector) -> binop(step_vector, splat(x))
5839   else if (N1.getOpcode() == ISD::SPLAT_VECTOR &&
5840            N2.getOpcode() == ISD::STEP_VECTOR)
5841     std::swap(N1, N2);
5842 }
5843 
5844 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
5845                               SDValue N1, SDValue N2, const SDNodeFlags Flags) {
5846   assert(N1.getOpcode() != ISD::DELETED_NODE &&
5847          N2.getOpcode() != ISD::DELETED_NODE &&
5848          "Operand is DELETED_NODE!");
5849 
5850   canonicalizeCommutativeBinop(Opcode, N1, N2);
5851 
5852   auto *N1C = dyn_cast<ConstantSDNode>(N1);
5853   auto *N2C = dyn_cast<ConstantSDNode>(N2);
5854 
5855   // Don't allow undefs in vector splats - we might be returning N2 when folding
5856   // to zero etc.
5857   ConstantSDNode *N2CV =
5858       isConstOrConstSplat(N2, /*AllowUndefs*/ false, /*AllowTruncation*/ true);
5859 
5860   switch (Opcode) {
5861   default: break;
5862   case ISD::TokenFactor:
5863     assert(VT == MVT::Other && N1.getValueType() == MVT::Other &&
5864            N2.getValueType() == MVT::Other && "Invalid token factor!");
5865     // Fold trivial token factors.
5866     if (N1.getOpcode() == ISD::EntryToken) return N2;
5867     if (N2.getOpcode() == ISD::EntryToken) return N1;
5868     if (N1 == N2) return N1;
5869     break;
5870   case ISD::BUILD_VECTOR: {
5871     // Attempt to simplify BUILD_VECTOR.
5872     SDValue Ops[] = {N1, N2};
5873     if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
5874       return V;
5875     break;
5876   }
5877   case ISD::CONCAT_VECTORS: {
5878     SDValue Ops[] = {N1, N2};
5879     if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this))
5880       return V;
5881     break;
5882   }
5883   case ISD::AND:
5884     assert(VT.isInteger() && "This operator does not apply to FP types!");
5885     assert(N1.getValueType() == N2.getValueType() &&
5886            N1.getValueType() == VT && "Binary operator types must match!");
5887     // (X & 0) -> 0.  This commonly occurs when legalizing i64 values, so it's
5888     // worth handling here.
5889     if (N2CV && N2CV->isZero())
5890       return N2;
5891     if (N2CV && N2CV->isAllOnes()) // X & -1 -> X
5892       return N1;
5893     break;
5894   case ISD::OR:
5895   case ISD::XOR:
5896   case ISD::ADD:
5897   case ISD::SUB:
5898     assert(VT.isInteger() && "This operator does not apply to FP types!");
5899     assert(N1.getValueType() == N2.getValueType() &&
5900            N1.getValueType() == VT && "Binary operator types must match!");
5901     // (X ^|+- 0) -> X.  This commonly occurs when legalizing i64 values, so
5902     // it's worth handling here.
5903     if (N2CV && N2CV->isZero())
5904       return N1;
5905     if ((Opcode == ISD::ADD || Opcode == ISD::SUB) && VT.isVector() &&
5906         VT.getVectorElementType() == MVT::i1)
5907       return getNode(ISD::XOR, DL, VT, N1, N2);
5908     break;
5909   case ISD::MUL:
5910     assert(VT.isInteger() && "This operator does not apply to FP types!");
5911     assert(N1.getValueType() == N2.getValueType() &&
5912            N1.getValueType() == VT && "Binary operator types must match!");
5913     if (VT.isVector() && VT.getVectorElementType() == MVT::i1)
5914       return getNode(ISD::AND, DL, VT, N1, N2);
5915     if (N2C && (N1.getOpcode() == ISD::VSCALE) && Flags.hasNoSignedWrap()) {
5916       const APInt &MulImm = N1->getConstantOperandAPInt(0);
5917       const APInt &N2CImm = N2C->getAPIntValue();
5918       return getVScale(DL, VT, MulImm * N2CImm);
5919     }
5920     break;
5921   case ISD::UDIV:
5922   case ISD::UREM:
5923   case ISD::MULHU:
5924   case ISD::MULHS:
5925   case ISD::SDIV:
5926   case ISD::SREM:
5927   case ISD::SADDSAT:
5928   case ISD::SSUBSAT:
5929   case ISD::UADDSAT:
5930   case ISD::USUBSAT:
5931     assert(VT.isInteger() && "This operator does not apply to FP types!");
5932     assert(N1.getValueType() == N2.getValueType() &&
5933            N1.getValueType() == VT && "Binary operator types must match!");
5934     if (VT.isVector() && VT.getVectorElementType() == MVT::i1) {
5935       // fold (add_sat x, y) -> (or x, y) for bool types.
5936       if (Opcode == ISD::SADDSAT || Opcode == ISD::UADDSAT)
5937         return getNode(ISD::OR, DL, VT, N1, N2);
5938       // fold (sub_sat x, y) -> (and x, ~y) for bool types.
5939       if (Opcode == ISD::SSUBSAT || Opcode == ISD::USUBSAT)
5940         return getNode(ISD::AND, DL, VT, N1, getNOT(DL, N2, VT));
5941     }
5942     break;
5943   case ISD::SMIN:
5944   case ISD::UMAX:
5945     assert(VT.isInteger() && "This operator does not apply to FP types!");
5946     assert(N1.getValueType() == N2.getValueType() &&
5947            N1.getValueType() == VT && "Binary operator types must match!");
5948     if (VT.isVector() && VT.getVectorElementType() == MVT::i1)
5949       return getNode(ISD::OR, DL, VT, N1, N2);
5950     break;
5951   case ISD::SMAX:
5952   case ISD::UMIN:
5953     assert(VT.isInteger() && "This operator does not apply to FP types!");
5954     assert(N1.getValueType() == N2.getValueType() &&
5955            N1.getValueType() == VT && "Binary operator types must match!");
5956     if (VT.isVector() && VT.getVectorElementType() == MVT::i1)
5957       return getNode(ISD::AND, DL, VT, N1, N2);
5958     break;
5959   case ISD::FADD:
5960   case ISD::FSUB:
5961   case ISD::FMUL:
5962   case ISD::FDIV:
5963   case ISD::FREM:
5964     assert(VT.isFloatingPoint() && "This operator only applies to FP types!");
5965     assert(N1.getValueType() == N2.getValueType() &&
5966            N1.getValueType() == VT && "Binary operator types must match!");
5967     if (SDValue V = simplifyFPBinop(Opcode, N1, N2, Flags))
5968       return V;
5969     break;
5970   case ISD::FCOPYSIGN:   // N1 and result must match.  N1/N2 need not match.
5971     assert(N1.getValueType() == VT &&
5972            N1.getValueType().isFloatingPoint() &&
5973            N2.getValueType().isFloatingPoint() &&
5974            "Invalid FCOPYSIGN!");
5975     break;
5976   case ISD::SHL:
5977     if (N2C && (N1.getOpcode() == ISD::VSCALE) && Flags.hasNoSignedWrap()) {
5978       const APInt &MulImm = N1->getConstantOperandAPInt(0);
5979       const APInt &ShiftImm = N2C->getAPIntValue();
5980       return getVScale(DL, VT, MulImm << ShiftImm);
5981     }
5982     LLVM_FALLTHROUGH;
5983   case ISD::SRA:
5984   case ISD::SRL:
5985     if (SDValue V = simplifyShift(N1, N2))
5986       return V;
5987     LLVM_FALLTHROUGH;
5988   case ISD::ROTL:
5989   case ISD::ROTR:
5990     assert(VT == N1.getValueType() &&
5991            "Shift operators return type must be the same as their first arg");
5992     assert(VT.isInteger() && N2.getValueType().isInteger() &&
5993            "Shifts only work on integers");
5994     assert((!VT.isVector() || VT == N2.getValueType()) &&
5995            "Vector shift amounts must be in the same as their first arg");
5996     // Verify that the shift amount VT is big enough to hold valid shift
5997     // amounts.  This catches things like trying to shift an i1024 value by an
5998     // i8, which is easy to fall into in generic code that uses
5999     // TLI.getShiftAmount().
6000     assert(N2.getValueType().getScalarSizeInBits() >=
6001                Log2_32_Ceil(VT.getScalarSizeInBits()) &&
6002            "Invalid use of small shift amount with oversized value!");
6003 
6004     // Always fold shifts of i1 values so the code generator doesn't need to
6005     // handle them.  Since we know the size of the shift has to be less than the
6006     // size of the value, the shift/rotate count is guaranteed to be zero.
6007     if (VT == MVT::i1)
6008       return N1;
6009     if (N2CV && N2CV->isZero())
6010       return N1;
6011     break;
6012   case ISD::FP_ROUND:
6013     assert(VT.isFloatingPoint() &&
6014            N1.getValueType().isFloatingPoint() &&
6015            VT.bitsLE(N1.getValueType()) &&
6016            N2C && (N2C->getZExtValue() == 0 || N2C->getZExtValue() == 1) &&
6017            "Invalid FP_ROUND!");
6018     if (N1.getValueType() == VT) return N1;  // noop conversion.
6019     break;
6020   case ISD::AssertSext:
6021   case ISD::AssertZext: {
6022     EVT EVT = cast<VTSDNode>(N2)->getVT();
6023     assert(VT == N1.getValueType() && "Not an inreg extend!");
6024     assert(VT.isInteger() && EVT.isInteger() &&
6025            "Cannot *_EXTEND_INREG FP types");
6026     assert(!EVT.isVector() &&
6027            "AssertSExt/AssertZExt type should be the vector element type "
6028            "rather than the vector type!");
6029     assert(EVT.bitsLE(VT.getScalarType()) && "Not extending!");
6030     if (VT.getScalarType() == EVT) return N1; // noop assertion.
6031     break;
6032   }
6033   case ISD::SIGN_EXTEND_INREG: {
6034     EVT EVT = cast<VTSDNode>(N2)->getVT();
6035     assert(VT == N1.getValueType() && "Not an inreg extend!");
6036     assert(VT.isInteger() && EVT.isInteger() &&
6037            "Cannot *_EXTEND_INREG FP types");
6038     assert(EVT.isVector() == VT.isVector() &&
6039            "SIGN_EXTEND_INREG type should be vector iff the operand "
6040            "type is vector!");
6041     assert((!EVT.isVector() ||
6042             EVT.getVectorElementCount() == VT.getVectorElementCount()) &&
6043            "Vector element counts must match in SIGN_EXTEND_INREG");
6044     assert(EVT.bitsLE(VT) && "Not extending!");
6045     if (EVT == VT) return N1;  // Not actually extending
6046 
6047     auto SignExtendInReg = [&](APInt Val, llvm::EVT ConstantVT) {
6048       unsigned FromBits = EVT.getScalarSizeInBits();
6049       Val <<= Val.getBitWidth() - FromBits;
6050       Val.ashrInPlace(Val.getBitWidth() - FromBits);
6051       return getConstant(Val, DL, ConstantVT);
6052     };
6053 
6054     if (N1C) {
6055       const APInt &Val = N1C->getAPIntValue();
6056       return SignExtendInReg(Val, VT);
6057     }
6058 
6059     if (ISD::isBuildVectorOfConstantSDNodes(N1.getNode())) {
6060       SmallVector<SDValue, 8> Ops;
6061       llvm::EVT OpVT = N1.getOperand(0).getValueType();
6062       for (int i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
6063         SDValue Op = N1.getOperand(i);
6064         if (Op.isUndef()) {
6065           Ops.push_back(getUNDEF(OpVT));
6066           continue;
6067         }
6068         ConstantSDNode *C = cast<ConstantSDNode>(Op);
6069         APInt Val = C->getAPIntValue();
6070         Ops.push_back(SignExtendInReg(Val, OpVT));
6071       }
6072       return getBuildVector(VT, DL, Ops);
6073     }
6074     break;
6075   }
6076   case ISD::FP_TO_SINT_SAT:
6077   case ISD::FP_TO_UINT_SAT: {
6078     assert(VT.isInteger() && cast<VTSDNode>(N2)->getVT().isInteger() &&
6079            N1.getValueType().isFloatingPoint() && "Invalid FP_TO_*INT_SAT");
6080     assert(N1.getValueType().isVector() == VT.isVector() &&
6081            "FP_TO_*INT_SAT type should be vector iff the operand type is "
6082            "vector!");
6083     assert((!VT.isVector() || VT.getVectorNumElements() ==
6084                                   N1.getValueType().getVectorNumElements()) &&
6085            "Vector element counts must match in FP_TO_*INT_SAT");
6086     assert(!cast<VTSDNode>(N2)->getVT().isVector() &&
6087            "Type to saturate to must be a scalar.");
6088     assert(cast<VTSDNode>(N2)->getVT().bitsLE(VT.getScalarType()) &&
6089            "Not extending!");
6090     break;
6091   }
6092   case ISD::EXTRACT_VECTOR_ELT:
6093     assert(VT.getSizeInBits() >= N1.getValueType().getScalarSizeInBits() &&
6094            "The result of EXTRACT_VECTOR_ELT must be at least as wide as the \
6095              element type of the vector.");
6096 
6097     // Extract from an undefined value or using an undefined index is undefined.
6098     if (N1.isUndef() || N2.isUndef())
6099       return getUNDEF(VT);
6100 
6101     // EXTRACT_VECTOR_ELT of out-of-bounds element is an UNDEF for fixed length
6102     // vectors. For scalable vectors we will provide appropriate support for
6103     // dealing with arbitrary indices.
6104     if (N2C && N1.getValueType().isFixedLengthVector() &&
6105         N2C->getAPIntValue().uge(N1.getValueType().getVectorNumElements()))
6106       return getUNDEF(VT);
6107 
6108     // EXTRACT_VECTOR_ELT of CONCAT_VECTORS is often formed while lowering is
6109     // expanding copies of large vectors from registers. This only works for
6110     // fixed length vectors, since we need to know the exact number of
6111     // elements.
6112     if (N2C && N1.getOperand(0).getValueType().isFixedLengthVector() &&
6113         N1.getOpcode() == ISD::CONCAT_VECTORS && N1.getNumOperands() > 0) {
6114       unsigned Factor =
6115         N1.getOperand(0).getValueType().getVectorNumElements();
6116       return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
6117                      N1.getOperand(N2C->getZExtValue() / Factor),
6118                      getVectorIdxConstant(N2C->getZExtValue() % Factor, DL));
6119     }
6120 
6121     // EXTRACT_VECTOR_ELT of BUILD_VECTOR or SPLAT_VECTOR is often formed while
6122     // lowering is expanding large vector constants.
6123     if (N2C && (N1.getOpcode() == ISD::BUILD_VECTOR ||
6124                 N1.getOpcode() == ISD::SPLAT_VECTOR)) {
6125       assert((N1.getOpcode() != ISD::BUILD_VECTOR ||
6126               N1.getValueType().isFixedLengthVector()) &&
6127              "BUILD_VECTOR used for scalable vectors");
6128       unsigned Index =
6129           N1.getOpcode() == ISD::BUILD_VECTOR ? N2C->getZExtValue() : 0;
6130       SDValue Elt = N1.getOperand(Index);
6131 
6132       if (VT != Elt.getValueType())
6133         // If the vector element type is not legal, the BUILD_VECTOR operands
6134         // are promoted and implicitly truncated, and the result implicitly
6135         // extended. Make that explicit here.
6136         Elt = getAnyExtOrTrunc(Elt, DL, VT);
6137 
6138       return Elt;
6139     }
6140 
6141     // EXTRACT_VECTOR_ELT of INSERT_VECTOR_ELT is often formed when vector
6142     // operations are lowered to scalars.
6143     if (N1.getOpcode() == ISD::INSERT_VECTOR_ELT) {
6144       // If the indices are the same, return the inserted element else
6145       // if the indices are known different, extract the element from
6146       // the original vector.
6147       SDValue N1Op2 = N1.getOperand(2);
6148       ConstantSDNode *N1Op2C = dyn_cast<ConstantSDNode>(N1Op2);
6149 
6150       if (N1Op2C && N2C) {
6151         if (N1Op2C->getZExtValue() == N2C->getZExtValue()) {
6152           if (VT == N1.getOperand(1).getValueType())
6153             return N1.getOperand(1);
6154           return getSExtOrTrunc(N1.getOperand(1), DL, VT);
6155         }
6156         return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0), N2);
6157       }
6158     }
6159 
6160     // EXTRACT_VECTOR_ELT of v1iX EXTRACT_SUBVECTOR could be formed
6161     // when vector types are scalarized and v1iX is legal.
6162     // vextract (v1iX extract_subvector(vNiX, Idx)) -> vextract(vNiX,Idx).
6163     // Here we are completely ignoring the extract element index (N2),
6164     // which is fine for fixed width vectors, since any index other than 0
6165     // is undefined anyway. However, this cannot be ignored for scalable
6166     // vectors - in theory we could support this, but we don't want to do this
6167     // without a profitability check.
6168     if (N1.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
6169         N1.getValueType().isFixedLengthVector() &&
6170         N1.getValueType().getVectorNumElements() == 1) {
6171       return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0),
6172                      N1.getOperand(1));
6173     }
6174     break;
6175   case ISD::EXTRACT_ELEMENT:
6176     assert(N2C && (unsigned)N2C->getZExtValue() < 2 && "Bad EXTRACT_ELEMENT!");
6177     assert(!N1.getValueType().isVector() && !VT.isVector() &&
6178            (N1.getValueType().isInteger() == VT.isInteger()) &&
6179            N1.getValueType() != VT &&
6180            "Wrong types for EXTRACT_ELEMENT!");
6181 
6182     // EXTRACT_ELEMENT of BUILD_PAIR is often formed while legalize is expanding
6183     // 64-bit integers into 32-bit parts.  Instead of building the extract of
6184     // the BUILD_PAIR, only to have legalize rip it apart, just do it now.
6185     if (N1.getOpcode() == ISD::BUILD_PAIR)
6186       return N1.getOperand(N2C->getZExtValue());
6187 
6188     // EXTRACT_ELEMENT of a constant int is also very common.
6189     if (N1C) {
6190       unsigned ElementSize = VT.getSizeInBits();
6191       unsigned Shift = ElementSize * N2C->getZExtValue();
6192       const APInt &Val = N1C->getAPIntValue();
6193       return getConstant(Val.extractBits(ElementSize, Shift), DL, VT);
6194     }
6195     break;
6196   case ISD::EXTRACT_SUBVECTOR: {
6197     EVT N1VT = N1.getValueType();
6198     assert(VT.isVector() && N1VT.isVector() &&
6199            "Extract subvector VTs must be vectors!");
6200     assert(VT.getVectorElementType() == N1VT.getVectorElementType() &&
6201            "Extract subvector VTs must have the same element type!");
6202     assert((VT.isFixedLengthVector() || N1VT.isScalableVector()) &&
6203            "Cannot extract a scalable vector from a fixed length vector!");
6204     assert((VT.isScalableVector() != N1VT.isScalableVector() ||
6205             VT.getVectorMinNumElements() <= N1VT.getVectorMinNumElements()) &&
6206            "Extract subvector must be from larger vector to smaller vector!");
6207     assert(N2C && "Extract subvector index must be a constant");
6208     assert((VT.isScalableVector() != N1VT.isScalableVector() ||
6209             (VT.getVectorMinNumElements() + N2C->getZExtValue()) <=
6210                 N1VT.getVectorMinNumElements()) &&
6211            "Extract subvector overflow!");
6212     assert(N2C->getAPIntValue().getBitWidth() ==
6213                TLI->getVectorIdxTy(getDataLayout()).getFixedSizeInBits() &&
6214            "Constant index for EXTRACT_SUBVECTOR has an invalid size");
6215 
6216     // Trivial extraction.
6217     if (VT == N1VT)
6218       return N1;
6219 
6220     // EXTRACT_SUBVECTOR of an UNDEF is an UNDEF.
6221     if (N1.isUndef())
6222       return getUNDEF(VT);
6223 
6224     // EXTRACT_SUBVECTOR of CONCAT_VECTOR can be simplified if the pieces of
6225     // the concat have the same type as the extract.
6226     if (N1.getOpcode() == ISD::CONCAT_VECTORS && N1.getNumOperands() > 0 &&
6227         VT == N1.getOperand(0).getValueType()) {
6228       unsigned Factor = VT.getVectorMinNumElements();
6229       return N1.getOperand(N2C->getZExtValue() / Factor);
6230     }
6231 
6232     // EXTRACT_SUBVECTOR of INSERT_SUBVECTOR is often created
6233     // during shuffle legalization.
6234     if (N1.getOpcode() == ISD::INSERT_SUBVECTOR && N2 == N1.getOperand(2) &&
6235         VT == N1.getOperand(1).getValueType())
6236       return N1.getOperand(1);
6237     break;
6238   }
6239   }
6240 
6241   // Perform trivial constant folding.
6242   if (SDValue SV = FoldConstantArithmetic(Opcode, DL, VT, {N1, N2}))
6243     return SV;
6244 
6245   // Canonicalize an UNDEF to the RHS, even over a constant.
6246   if (N1.isUndef()) {
6247     if (TLI->isCommutativeBinOp(Opcode)) {
6248       std::swap(N1, N2);
6249     } else {
6250       switch (Opcode) {
6251       case ISD::SUB:
6252         return getUNDEF(VT);     // fold op(undef, arg2) -> undef
6253       case ISD::SIGN_EXTEND_INREG:
6254       case ISD::UDIV:
6255       case ISD::SDIV:
6256       case ISD::UREM:
6257       case ISD::SREM:
6258       case ISD::SSUBSAT:
6259       case ISD::USUBSAT:
6260         return getConstant(0, DL, VT);    // fold op(undef, arg2) -> 0
6261       }
6262     }
6263   }
6264 
6265   // Fold a bunch of operators when the RHS is undef.
6266   if (N2.isUndef()) {
6267     switch (Opcode) {
6268     case ISD::XOR:
6269       if (N1.isUndef())
6270         // Handle undef ^ undef -> 0 special case. This is a common
6271         // idiom (misuse).
6272         return getConstant(0, DL, VT);
6273       LLVM_FALLTHROUGH;
6274     case ISD::ADD:
6275     case ISD::SUB:
6276     case ISD::UDIV:
6277     case ISD::SDIV:
6278     case ISD::UREM:
6279     case ISD::SREM:
6280       return getUNDEF(VT);       // fold op(arg1, undef) -> undef
6281     case ISD::MUL:
6282     case ISD::AND:
6283     case ISD::SSUBSAT:
6284     case ISD::USUBSAT:
6285       return getConstant(0, DL, VT);  // fold op(arg1, undef) -> 0
6286     case ISD::OR:
6287     case ISD::SADDSAT:
6288     case ISD::UADDSAT:
6289       return getAllOnesConstant(DL, VT);
6290     }
6291   }
6292 
6293   // Memoize this node if possible.
6294   SDNode *N;
6295   SDVTList VTs = getVTList(VT);
6296   SDValue Ops[] = {N1, N2};
6297   if (VT != MVT::Glue) {
6298     FoldingSetNodeID ID;
6299     AddNodeIDNode(ID, Opcode, VTs, Ops);
6300     void *IP = nullptr;
6301     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
6302       E->intersectFlagsWith(Flags);
6303       return SDValue(E, 0);
6304     }
6305 
6306     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
6307     N->setFlags(Flags);
6308     createOperands(N, Ops);
6309     CSEMap.InsertNode(N, IP);
6310   } else {
6311     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
6312     createOperands(N, Ops);
6313   }
6314 
6315   InsertNode(N);
6316   SDValue V = SDValue(N, 0);
6317   NewSDValueDbgMsg(V, "Creating new node: ", this);
6318   return V;
6319 }
6320 
6321 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
6322                               SDValue N1, SDValue N2, SDValue N3) {
6323   SDNodeFlags Flags;
6324   if (Inserter)
6325     Flags = Inserter->getFlags();
6326   return getNode(Opcode, DL, VT, N1, N2, N3, Flags);
6327 }
6328 
6329 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
6330                               SDValue N1, SDValue N2, SDValue N3,
6331                               const SDNodeFlags Flags) {
6332   assert(N1.getOpcode() != ISD::DELETED_NODE &&
6333          N2.getOpcode() != ISD::DELETED_NODE &&
6334          N3.getOpcode() != ISD::DELETED_NODE &&
6335          "Operand is DELETED_NODE!");
6336   // Perform various simplifications.
6337   switch (Opcode) {
6338   case ISD::FMA: {
6339     assert(VT.isFloatingPoint() && "This operator only applies to FP types!");
6340     assert(N1.getValueType() == VT && N2.getValueType() == VT &&
6341            N3.getValueType() == VT && "FMA types must match!");
6342     ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6343     ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2);
6344     ConstantFPSDNode *N3CFP = dyn_cast<ConstantFPSDNode>(N3);
6345     if (N1CFP && N2CFP && N3CFP) {
6346       APFloat  V1 = N1CFP->getValueAPF();
6347       const APFloat &V2 = N2CFP->getValueAPF();
6348       const APFloat &V3 = N3CFP->getValueAPF();
6349       V1.fusedMultiplyAdd(V2, V3, APFloat::rmNearestTiesToEven);
6350       return getConstantFP(V1, DL, VT);
6351     }
6352     break;
6353   }
6354   case ISD::BUILD_VECTOR: {
6355     // Attempt to simplify BUILD_VECTOR.
6356     SDValue Ops[] = {N1, N2, N3};
6357     if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
6358       return V;
6359     break;
6360   }
6361   case ISD::CONCAT_VECTORS: {
6362     SDValue Ops[] = {N1, N2, N3};
6363     if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this))
6364       return V;
6365     break;
6366   }
6367   case ISD::SETCC: {
6368     assert(VT.isInteger() && "SETCC result type must be an integer!");
6369     assert(N1.getValueType() == N2.getValueType() &&
6370            "SETCC operands must have the same type!");
6371     assert(VT.isVector() == N1.getValueType().isVector() &&
6372            "SETCC type should be vector iff the operand type is vector!");
6373     assert((!VT.isVector() || VT.getVectorElementCount() ==
6374                                   N1.getValueType().getVectorElementCount()) &&
6375            "SETCC vector element counts must match!");
6376     // Use FoldSetCC to simplify SETCC's.
6377     if (SDValue V = FoldSetCC(VT, N1, N2, cast<CondCodeSDNode>(N3)->get(), DL))
6378       return V;
6379     // Vector constant folding.
6380     SDValue Ops[] = {N1, N2, N3};
6381     if (SDValue V = FoldConstantArithmetic(Opcode, DL, VT, Ops)) {
6382       NewSDValueDbgMsg(V, "New node vector constant folding: ", this);
6383       return V;
6384     }
6385     break;
6386   }
6387   case ISD::SELECT:
6388   case ISD::VSELECT:
6389     if (SDValue V = simplifySelect(N1, N2, N3))
6390       return V;
6391     break;
6392   case ISD::VECTOR_SHUFFLE:
6393     llvm_unreachable("should use getVectorShuffle constructor!");
6394   case ISD::VECTOR_SPLICE: {
6395     if (cast<ConstantSDNode>(N3)->isNullValue())
6396       return N1;
6397     break;
6398   }
6399   case ISD::INSERT_VECTOR_ELT: {
6400     ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3);
6401     // INSERT_VECTOR_ELT into out-of-bounds element is an UNDEF, except
6402     // for scalable vectors where we will generate appropriate code to
6403     // deal with out-of-bounds cases correctly.
6404     if (N3C && N1.getValueType().isFixedLengthVector() &&
6405         N3C->getZExtValue() >= N1.getValueType().getVectorNumElements())
6406       return getUNDEF(VT);
6407 
6408     // Undefined index can be assumed out-of-bounds, so that's UNDEF too.
6409     if (N3.isUndef())
6410       return getUNDEF(VT);
6411 
6412     // If the inserted element is an UNDEF, just use the input vector.
6413     if (N2.isUndef())
6414       return N1;
6415 
6416     break;
6417   }
6418   case ISD::INSERT_SUBVECTOR: {
6419     // Inserting undef into undef is still undef.
6420     if (N1.isUndef() && N2.isUndef())
6421       return getUNDEF(VT);
6422 
6423     EVT N2VT = N2.getValueType();
6424     assert(VT == N1.getValueType() &&
6425            "Dest and insert subvector source types must match!");
6426     assert(VT.isVector() && N2VT.isVector() &&
6427            "Insert subvector VTs must be vectors!");
6428     assert((VT.isScalableVector() || N2VT.isFixedLengthVector()) &&
6429            "Cannot insert a scalable vector into a fixed length vector!");
6430     assert((VT.isScalableVector() != N2VT.isScalableVector() ||
6431             VT.getVectorMinNumElements() >= N2VT.getVectorMinNumElements()) &&
6432            "Insert subvector must be from smaller vector to larger vector!");
6433     assert(isa<ConstantSDNode>(N3) &&
6434            "Insert subvector index must be constant");
6435     assert((VT.isScalableVector() != N2VT.isScalableVector() ||
6436             (N2VT.getVectorMinNumElements() +
6437              cast<ConstantSDNode>(N3)->getZExtValue()) <=
6438                 VT.getVectorMinNumElements()) &&
6439            "Insert subvector overflow!");
6440     assert(cast<ConstantSDNode>(N3)->getAPIntValue().getBitWidth() ==
6441                TLI->getVectorIdxTy(getDataLayout()).getFixedSizeInBits() &&
6442            "Constant index for INSERT_SUBVECTOR has an invalid size");
6443 
6444     // Trivial insertion.
6445     if (VT == N2VT)
6446       return N2;
6447 
6448     // If this is an insert of an extracted vector into an undef vector, we
6449     // can just use the input to the extract.
6450     if (N1.isUndef() && N2.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
6451         N2.getOperand(1) == N3 && N2.getOperand(0).getValueType() == VT)
6452       return N2.getOperand(0);
6453     break;
6454   }
6455   case ISD::BITCAST:
6456     // Fold bit_convert nodes from a type to themselves.
6457     if (N1.getValueType() == VT)
6458       return N1;
6459     break;
6460   }
6461 
6462   // Memoize node if it doesn't produce a flag.
6463   SDNode *N;
6464   SDVTList VTs = getVTList(VT);
6465   SDValue Ops[] = {N1, N2, N3};
6466   if (VT != MVT::Glue) {
6467     FoldingSetNodeID ID;
6468     AddNodeIDNode(ID, Opcode, VTs, Ops);
6469     void *IP = nullptr;
6470     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
6471       E->intersectFlagsWith(Flags);
6472       return SDValue(E, 0);
6473     }
6474 
6475     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
6476     N->setFlags(Flags);
6477     createOperands(N, Ops);
6478     CSEMap.InsertNode(N, IP);
6479   } else {
6480     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
6481     createOperands(N, Ops);
6482   }
6483 
6484   InsertNode(N);
6485   SDValue V = SDValue(N, 0);
6486   NewSDValueDbgMsg(V, "Creating new node: ", this);
6487   return V;
6488 }
6489 
6490 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
6491                               SDValue N1, SDValue N2, SDValue N3, SDValue N4) {
6492   SDValue Ops[] = { N1, N2, N3, N4 };
6493   return getNode(Opcode, DL, VT, Ops);
6494 }
6495 
6496 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
6497                               SDValue N1, SDValue N2, SDValue N3, SDValue N4,
6498                               SDValue N5) {
6499   SDValue Ops[] = { N1, N2, N3, N4, N5 };
6500   return getNode(Opcode, DL, VT, Ops);
6501 }
6502 
6503 /// getStackArgumentTokenFactor - Compute a TokenFactor to force all
6504 /// the incoming stack arguments to be loaded from the stack.
6505 SDValue SelectionDAG::getStackArgumentTokenFactor(SDValue Chain) {
6506   SmallVector<SDValue, 8> ArgChains;
6507 
6508   // Include the original chain at the beginning of the list. When this is
6509   // used by target LowerCall hooks, this helps legalize find the
6510   // CALLSEQ_BEGIN node.
6511   ArgChains.push_back(Chain);
6512 
6513   // Add a chain value for each stack argument.
6514   for (SDNode *U : getEntryNode().getNode()->uses())
6515     if (LoadSDNode *L = dyn_cast<LoadSDNode>(U))
6516       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
6517         if (FI->getIndex() < 0)
6518           ArgChains.push_back(SDValue(L, 1));
6519 
6520   // Build a tokenfactor for all the chains.
6521   return getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains);
6522 }
6523 
6524 /// getMemsetValue - Vectorized representation of the memset value
6525 /// operand.
6526 static SDValue getMemsetValue(SDValue Value, EVT VT, SelectionDAG &DAG,
6527                               const SDLoc &dl) {
6528   assert(!Value.isUndef());
6529 
6530   unsigned NumBits = VT.getScalarSizeInBits();
6531   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
6532     assert(C->getAPIntValue().getBitWidth() == 8);
6533     APInt Val = APInt::getSplat(NumBits, C->getAPIntValue());
6534     if (VT.isInteger()) {
6535       bool IsOpaque = VT.getSizeInBits() > 64 ||
6536           !DAG.getTargetLoweringInfo().isLegalStoreImmediate(C->getSExtValue());
6537       return DAG.getConstant(Val, dl, VT, false, IsOpaque);
6538     }
6539     return DAG.getConstantFP(APFloat(DAG.EVTToAPFloatSemantics(VT), Val), dl,
6540                              VT);
6541   }
6542 
6543   assert(Value.getValueType() == MVT::i8 && "memset with non-byte fill value?");
6544   EVT IntVT = VT.getScalarType();
6545   if (!IntVT.isInteger())
6546     IntVT = EVT::getIntegerVT(*DAG.getContext(), IntVT.getSizeInBits());
6547 
6548   Value = DAG.getNode(ISD::ZERO_EXTEND, dl, IntVT, Value);
6549   if (NumBits > 8) {
6550     // Use a multiplication with 0x010101... to extend the input to the
6551     // required length.
6552     APInt Magic = APInt::getSplat(NumBits, APInt(8, 0x01));
6553     Value = DAG.getNode(ISD::MUL, dl, IntVT, Value,
6554                         DAG.getConstant(Magic, dl, IntVT));
6555   }
6556 
6557   if (VT != Value.getValueType() && !VT.isInteger())
6558     Value = DAG.getBitcast(VT.getScalarType(), Value);
6559   if (VT != Value.getValueType())
6560     Value = DAG.getSplatBuildVector(VT, dl, Value);
6561 
6562   return Value;
6563 }
6564 
6565 /// getMemsetStringVal - Similar to getMemsetValue. Except this is only
6566 /// used when a memcpy is turned into a memset when the source is a constant
6567 /// string ptr.
6568 static SDValue getMemsetStringVal(EVT VT, const SDLoc &dl, SelectionDAG &DAG,
6569                                   const TargetLowering &TLI,
6570                                   const ConstantDataArraySlice &Slice) {
6571   // Handle vector with all elements zero.
6572   if (Slice.Array == nullptr) {
6573     if (VT.isInteger())
6574       return DAG.getConstant(0, dl, VT);
6575     if (VT == MVT::f32 || VT == MVT::f64 || VT == MVT::f128)
6576       return DAG.getConstantFP(0.0, dl, VT);
6577     if (VT.isVector()) {
6578       unsigned NumElts = VT.getVectorNumElements();
6579       MVT EltVT = (VT.getVectorElementType() == MVT::f32) ? MVT::i32 : MVT::i64;
6580       return DAG.getNode(ISD::BITCAST, dl, VT,
6581                          DAG.getConstant(0, dl,
6582                                          EVT::getVectorVT(*DAG.getContext(),
6583                                                           EltVT, NumElts)));
6584     }
6585     llvm_unreachable("Expected type!");
6586   }
6587 
6588   assert(!VT.isVector() && "Can't handle vector type here!");
6589   unsigned NumVTBits = VT.getSizeInBits();
6590   unsigned NumVTBytes = NumVTBits / 8;
6591   unsigned NumBytes = std::min(NumVTBytes, unsigned(Slice.Length));
6592 
6593   APInt Val(NumVTBits, 0);
6594   if (DAG.getDataLayout().isLittleEndian()) {
6595     for (unsigned i = 0; i != NumBytes; ++i)
6596       Val |= (uint64_t)(unsigned char)Slice[i] << i*8;
6597   } else {
6598     for (unsigned i = 0; i != NumBytes; ++i)
6599       Val |= (uint64_t)(unsigned char)Slice[i] << (NumVTBytes-i-1)*8;
6600   }
6601 
6602   // If the "cost" of materializing the integer immediate is less than the cost
6603   // of a load, then it is cost effective to turn the load into the immediate.
6604   Type *Ty = VT.getTypeForEVT(*DAG.getContext());
6605   if (TLI.shouldConvertConstantLoadToIntImm(Val, Ty))
6606     return DAG.getConstant(Val, dl, VT);
6607   return SDValue();
6608 }
6609 
6610 SDValue SelectionDAG::getMemBasePlusOffset(SDValue Base, TypeSize Offset,
6611                                            const SDLoc &DL,
6612                                            const SDNodeFlags Flags) {
6613   EVT VT = Base.getValueType();
6614   SDValue Index;
6615 
6616   if (Offset.isScalable())
6617     Index = getVScale(DL, Base.getValueType(),
6618                       APInt(Base.getValueSizeInBits().getFixedSize(),
6619                             Offset.getKnownMinSize()));
6620   else
6621     Index = getConstant(Offset.getFixedSize(), DL, VT);
6622 
6623   return getMemBasePlusOffset(Base, Index, DL, Flags);
6624 }
6625 
6626 SDValue SelectionDAG::getMemBasePlusOffset(SDValue Ptr, SDValue Offset,
6627                                            const SDLoc &DL,
6628                                            const SDNodeFlags Flags) {
6629   assert(Offset.getValueType().isInteger());
6630   EVT BasePtrVT = Ptr.getValueType();
6631   return getNode(ISD::ADD, DL, BasePtrVT, Ptr, Offset, Flags);
6632 }
6633 
6634 /// Returns true if memcpy source is constant data.
6635 static bool isMemSrcFromConstant(SDValue Src, ConstantDataArraySlice &Slice) {
6636   uint64_t SrcDelta = 0;
6637   GlobalAddressSDNode *G = nullptr;
6638   if (Src.getOpcode() == ISD::GlobalAddress)
6639     G = cast<GlobalAddressSDNode>(Src);
6640   else if (Src.getOpcode() == ISD::ADD &&
6641            Src.getOperand(0).getOpcode() == ISD::GlobalAddress &&
6642            Src.getOperand(1).getOpcode() == ISD::Constant) {
6643     G = cast<GlobalAddressSDNode>(Src.getOperand(0));
6644     SrcDelta = cast<ConstantSDNode>(Src.getOperand(1))->getZExtValue();
6645   }
6646   if (!G)
6647     return false;
6648 
6649   return getConstantDataArrayInfo(G->getGlobal(), Slice, 8,
6650                                   SrcDelta + G->getOffset());
6651 }
6652 
6653 static bool shouldLowerMemFuncForSize(const MachineFunction &MF,
6654                                       SelectionDAG &DAG) {
6655   // On Darwin, -Os means optimize for size without hurting performance, so
6656   // only really optimize for size when -Oz (MinSize) is used.
6657   if (MF.getTarget().getTargetTriple().isOSDarwin())
6658     return MF.getFunction().hasMinSize();
6659   return DAG.shouldOptForSize();
6660 }
6661 
6662 static void chainLoadsAndStoresForMemcpy(SelectionDAG &DAG, const SDLoc &dl,
6663                           SmallVector<SDValue, 32> &OutChains, unsigned From,
6664                           unsigned To, SmallVector<SDValue, 16> &OutLoadChains,
6665                           SmallVector<SDValue, 16> &OutStoreChains) {
6666   assert(OutLoadChains.size() && "Missing loads in memcpy inlining");
6667   assert(OutStoreChains.size() && "Missing stores in memcpy inlining");
6668   SmallVector<SDValue, 16> GluedLoadChains;
6669   for (unsigned i = From; i < To; ++i) {
6670     OutChains.push_back(OutLoadChains[i]);
6671     GluedLoadChains.push_back(OutLoadChains[i]);
6672   }
6673 
6674   // Chain for all loads.
6675   SDValue LoadToken = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
6676                                   GluedLoadChains);
6677 
6678   for (unsigned i = From; i < To; ++i) {
6679     StoreSDNode *ST = dyn_cast<StoreSDNode>(OutStoreChains[i]);
6680     SDValue NewStore = DAG.getTruncStore(LoadToken, dl, ST->getValue(),
6681                                   ST->getBasePtr(), ST->getMemoryVT(),
6682                                   ST->getMemOperand());
6683     OutChains.push_back(NewStore);
6684   }
6685 }
6686 
6687 static SDValue getMemcpyLoadsAndStores(SelectionDAG &DAG, const SDLoc &dl,
6688                                        SDValue Chain, SDValue Dst, SDValue Src,
6689                                        uint64_t Size, Align Alignment,
6690                                        bool isVol, bool AlwaysInline,
6691                                        MachinePointerInfo DstPtrInfo,
6692                                        MachinePointerInfo SrcPtrInfo,
6693                                        const AAMDNodes &AAInfo) {
6694   // Turn a memcpy of undef to nop.
6695   // FIXME: We need to honor volatile even is Src is undef.
6696   if (Src.isUndef())
6697     return Chain;
6698 
6699   // Expand memcpy to a series of load and store ops if the size operand falls
6700   // below a certain threshold.
6701   // TODO: In the AlwaysInline case, if the size is big then generate a loop
6702   // rather than maybe a humongous number of loads and stores.
6703   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6704   const DataLayout &DL = DAG.getDataLayout();
6705   LLVMContext &C = *DAG.getContext();
6706   std::vector<EVT> MemOps;
6707   bool DstAlignCanChange = false;
6708   MachineFunction &MF = DAG.getMachineFunction();
6709   MachineFrameInfo &MFI = MF.getFrameInfo();
6710   bool OptSize = shouldLowerMemFuncForSize(MF, DAG);
6711   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
6712   if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
6713     DstAlignCanChange = true;
6714   MaybeAlign SrcAlign = DAG.InferPtrAlign(Src);
6715   if (!SrcAlign || Alignment > *SrcAlign)
6716     SrcAlign = Alignment;
6717   assert(SrcAlign && "SrcAlign must be set");
6718   ConstantDataArraySlice Slice;
6719   // If marked as volatile, perform a copy even when marked as constant.
6720   bool CopyFromConstant = !isVol && isMemSrcFromConstant(Src, Slice);
6721   bool isZeroConstant = CopyFromConstant && Slice.Array == nullptr;
6722   unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemcpy(OptSize);
6723   const MemOp Op = isZeroConstant
6724                        ? MemOp::Set(Size, DstAlignCanChange, Alignment,
6725                                     /*IsZeroMemset*/ true, isVol)
6726                        : MemOp::Copy(Size, DstAlignCanChange, Alignment,
6727                                      *SrcAlign, isVol, CopyFromConstant);
6728   if (!TLI.findOptimalMemOpLowering(
6729           MemOps, Limit, Op, DstPtrInfo.getAddrSpace(),
6730           SrcPtrInfo.getAddrSpace(), MF.getFunction().getAttributes()))
6731     return SDValue();
6732 
6733   if (DstAlignCanChange) {
6734     Type *Ty = MemOps[0].getTypeForEVT(C);
6735     Align NewAlign = DL.getABITypeAlign(Ty);
6736 
6737     // Don't promote to an alignment that would require dynamic stack
6738     // realignment.
6739     const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
6740     if (!TRI->hasStackRealignment(MF))
6741       while (NewAlign > Alignment && DL.exceedsNaturalStackAlignment(NewAlign))
6742         NewAlign = NewAlign / 2;
6743 
6744     if (NewAlign > Alignment) {
6745       // Give the stack frame object a larger alignment if needed.
6746       if (MFI.getObjectAlign(FI->getIndex()) < NewAlign)
6747         MFI.setObjectAlignment(FI->getIndex(), NewAlign);
6748       Alignment = NewAlign;
6749     }
6750   }
6751 
6752   // Prepare AAInfo for loads/stores after lowering this memcpy.
6753   AAMDNodes NewAAInfo = AAInfo;
6754   NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr;
6755 
6756   MachineMemOperand::Flags MMOFlags =
6757       isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone;
6758   SmallVector<SDValue, 16> OutLoadChains;
6759   SmallVector<SDValue, 16> OutStoreChains;
6760   SmallVector<SDValue, 32> OutChains;
6761   unsigned NumMemOps = MemOps.size();
6762   uint64_t SrcOff = 0, DstOff = 0;
6763   for (unsigned i = 0; i != NumMemOps; ++i) {
6764     EVT VT = MemOps[i];
6765     unsigned VTSize = VT.getSizeInBits() / 8;
6766     SDValue Value, Store;
6767 
6768     if (VTSize > Size) {
6769       // Issuing an unaligned load / store pair  that overlaps with the previous
6770       // pair. Adjust the offset accordingly.
6771       assert(i == NumMemOps-1 && i != 0);
6772       SrcOff -= VTSize - Size;
6773       DstOff -= VTSize - Size;
6774     }
6775 
6776     if (CopyFromConstant &&
6777         (isZeroConstant || (VT.isInteger() && !VT.isVector()))) {
6778       // It's unlikely a store of a vector immediate can be done in a single
6779       // instruction. It would require a load from a constantpool first.
6780       // We only handle zero vectors here.
6781       // FIXME: Handle other cases where store of vector immediate is done in
6782       // a single instruction.
6783       ConstantDataArraySlice SubSlice;
6784       if (SrcOff < Slice.Length) {
6785         SubSlice = Slice;
6786         SubSlice.move(SrcOff);
6787       } else {
6788         // This is an out-of-bounds access and hence UB. Pretend we read zero.
6789         SubSlice.Array = nullptr;
6790         SubSlice.Offset = 0;
6791         SubSlice.Length = VTSize;
6792       }
6793       Value = getMemsetStringVal(VT, dl, DAG, TLI, SubSlice);
6794       if (Value.getNode()) {
6795         Store = DAG.getStore(
6796             Chain, dl, Value,
6797             DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl),
6798             DstPtrInfo.getWithOffset(DstOff), Alignment, MMOFlags, NewAAInfo);
6799         OutChains.push_back(Store);
6800       }
6801     }
6802 
6803     if (!Store.getNode()) {
6804       // The type might not be legal for the target.  This should only happen
6805       // if the type is smaller than a legal type, as on PPC, so the right
6806       // thing to do is generate a LoadExt/StoreTrunc pair.  These simplify
6807       // to Load/Store if NVT==VT.
6808       // FIXME does the case above also need this?
6809       EVT NVT = TLI.getTypeToTransformTo(C, VT);
6810       assert(NVT.bitsGE(VT));
6811 
6812       bool isDereferenceable =
6813         SrcPtrInfo.getWithOffset(SrcOff).isDereferenceable(VTSize, C, DL);
6814       MachineMemOperand::Flags SrcMMOFlags = MMOFlags;
6815       if (isDereferenceable)
6816         SrcMMOFlags |= MachineMemOperand::MODereferenceable;
6817 
6818       Value = DAG.getExtLoad(
6819           ISD::EXTLOAD, dl, NVT, Chain,
6820           DAG.getMemBasePlusOffset(Src, TypeSize::Fixed(SrcOff), dl),
6821           SrcPtrInfo.getWithOffset(SrcOff), VT,
6822           commonAlignment(*SrcAlign, SrcOff), SrcMMOFlags, NewAAInfo);
6823       OutLoadChains.push_back(Value.getValue(1));
6824 
6825       Store = DAG.getTruncStore(
6826           Chain, dl, Value,
6827           DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl),
6828           DstPtrInfo.getWithOffset(DstOff), VT, Alignment, MMOFlags, NewAAInfo);
6829       OutStoreChains.push_back(Store);
6830     }
6831     SrcOff += VTSize;
6832     DstOff += VTSize;
6833     Size -= VTSize;
6834   }
6835 
6836   unsigned GluedLdStLimit = MaxLdStGlue == 0 ?
6837                                 TLI.getMaxGluedStoresPerMemcpy() : MaxLdStGlue;
6838   unsigned NumLdStInMemcpy = OutStoreChains.size();
6839 
6840   if (NumLdStInMemcpy) {
6841     // It may be that memcpy might be converted to memset if it's memcpy
6842     // of constants. In such a case, we won't have loads and stores, but
6843     // just stores. In the absence of loads, there is nothing to gang up.
6844     if ((GluedLdStLimit <= 1) || !EnableMemCpyDAGOpt) {
6845       // If target does not care, just leave as it.
6846       for (unsigned i = 0; i < NumLdStInMemcpy; ++i) {
6847         OutChains.push_back(OutLoadChains[i]);
6848         OutChains.push_back(OutStoreChains[i]);
6849       }
6850     } else {
6851       // Ld/St less than/equal limit set by target.
6852       if (NumLdStInMemcpy <= GluedLdStLimit) {
6853           chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, 0,
6854                                         NumLdStInMemcpy, OutLoadChains,
6855                                         OutStoreChains);
6856       } else {
6857         unsigned NumberLdChain =  NumLdStInMemcpy / GluedLdStLimit;
6858         unsigned RemainingLdStInMemcpy = NumLdStInMemcpy % GluedLdStLimit;
6859         unsigned GlueIter = 0;
6860 
6861         for (unsigned cnt = 0; cnt < NumberLdChain; ++cnt) {
6862           unsigned IndexFrom = NumLdStInMemcpy - GlueIter - GluedLdStLimit;
6863           unsigned IndexTo   = NumLdStInMemcpy - GlueIter;
6864 
6865           chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, IndexFrom, IndexTo,
6866                                        OutLoadChains, OutStoreChains);
6867           GlueIter += GluedLdStLimit;
6868         }
6869 
6870         // Residual ld/st.
6871         if (RemainingLdStInMemcpy) {
6872           chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, 0,
6873                                         RemainingLdStInMemcpy, OutLoadChains,
6874                                         OutStoreChains);
6875         }
6876       }
6877     }
6878   }
6879   return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
6880 }
6881 
6882 static SDValue getMemmoveLoadsAndStores(SelectionDAG &DAG, const SDLoc &dl,
6883                                         SDValue Chain, SDValue Dst, SDValue Src,
6884                                         uint64_t Size, Align Alignment,
6885                                         bool isVol, bool AlwaysInline,
6886                                         MachinePointerInfo DstPtrInfo,
6887                                         MachinePointerInfo SrcPtrInfo,
6888                                         const AAMDNodes &AAInfo) {
6889   // Turn a memmove of undef to nop.
6890   // FIXME: We need to honor volatile even is Src is undef.
6891   if (Src.isUndef())
6892     return Chain;
6893 
6894   // Expand memmove to a series of load and store ops if the size operand falls
6895   // below a certain threshold.
6896   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6897   const DataLayout &DL = DAG.getDataLayout();
6898   LLVMContext &C = *DAG.getContext();
6899   std::vector<EVT> MemOps;
6900   bool DstAlignCanChange = false;
6901   MachineFunction &MF = DAG.getMachineFunction();
6902   MachineFrameInfo &MFI = MF.getFrameInfo();
6903   bool OptSize = shouldLowerMemFuncForSize(MF, DAG);
6904   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
6905   if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
6906     DstAlignCanChange = true;
6907   MaybeAlign SrcAlign = DAG.InferPtrAlign(Src);
6908   if (!SrcAlign || Alignment > *SrcAlign)
6909     SrcAlign = Alignment;
6910   assert(SrcAlign && "SrcAlign must be set");
6911   unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemmove(OptSize);
6912   if (!TLI.findOptimalMemOpLowering(
6913           MemOps, Limit,
6914           MemOp::Copy(Size, DstAlignCanChange, Alignment, *SrcAlign,
6915                       /*IsVolatile*/ true),
6916           DstPtrInfo.getAddrSpace(), SrcPtrInfo.getAddrSpace(),
6917           MF.getFunction().getAttributes()))
6918     return SDValue();
6919 
6920   if (DstAlignCanChange) {
6921     Type *Ty = MemOps[0].getTypeForEVT(C);
6922     Align NewAlign = DL.getABITypeAlign(Ty);
6923     if (NewAlign > Alignment) {
6924       // Give the stack frame object a larger alignment if needed.
6925       if (MFI.getObjectAlign(FI->getIndex()) < NewAlign)
6926         MFI.setObjectAlignment(FI->getIndex(), NewAlign);
6927       Alignment = NewAlign;
6928     }
6929   }
6930 
6931   // Prepare AAInfo for loads/stores after lowering this memmove.
6932   AAMDNodes NewAAInfo = AAInfo;
6933   NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr;
6934 
6935   MachineMemOperand::Flags MMOFlags =
6936       isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone;
6937   uint64_t SrcOff = 0, DstOff = 0;
6938   SmallVector<SDValue, 8> LoadValues;
6939   SmallVector<SDValue, 8> LoadChains;
6940   SmallVector<SDValue, 8> OutChains;
6941   unsigned NumMemOps = MemOps.size();
6942   for (unsigned i = 0; i < NumMemOps; i++) {
6943     EVT VT = MemOps[i];
6944     unsigned VTSize = VT.getSizeInBits() / 8;
6945     SDValue Value;
6946 
6947     bool isDereferenceable =
6948       SrcPtrInfo.getWithOffset(SrcOff).isDereferenceable(VTSize, C, DL);
6949     MachineMemOperand::Flags SrcMMOFlags = MMOFlags;
6950     if (isDereferenceable)
6951       SrcMMOFlags |= MachineMemOperand::MODereferenceable;
6952 
6953     Value = DAG.getLoad(
6954         VT, dl, Chain,
6955         DAG.getMemBasePlusOffset(Src, TypeSize::Fixed(SrcOff), dl),
6956         SrcPtrInfo.getWithOffset(SrcOff), *SrcAlign, SrcMMOFlags, NewAAInfo);
6957     LoadValues.push_back(Value);
6958     LoadChains.push_back(Value.getValue(1));
6959     SrcOff += VTSize;
6960   }
6961   Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
6962   OutChains.clear();
6963   for (unsigned i = 0; i < NumMemOps; i++) {
6964     EVT VT = MemOps[i];
6965     unsigned VTSize = VT.getSizeInBits() / 8;
6966     SDValue Store;
6967 
6968     Store = DAG.getStore(
6969         Chain, dl, LoadValues[i],
6970         DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl),
6971         DstPtrInfo.getWithOffset(DstOff), Alignment, MMOFlags, NewAAInfo);
6972     OutChains.push_back(Store);
6973     DstOff += VTSize;
6974   }
6975 
6976   return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
6977 }
6978 
6979 /// Lower the call to 'memset' intrinsic function into a series of store
6980 /// operations.
6981 ///
6982 /// \param DAG Selection DAG where lowered code is placed.
6983 /// \param dl Link to corresponding IR location.
6984 /// \param Chain Control flow dependency.
6985 /// \param Dst Pointer to destination memory location.
6986 /// \param Src Value of byte to write into the memory.
6987 /// \param Size Number of bytes to write.
6988 /// \param Alignment Alignment of the destination in bytes.
6989 /// \param isVol True if destination is volatile.
6990 /// \param DstPtrInfo IR information on the memory pointer.
6991 /// \returns New head in the control flow, if lowering was successful, empty
6992 /// SDValue otherwise.
6993 ///
6994 /// The function tries to replace 'llvm.memset' intrinsic with several store
6995 /// operations and value calculation code. This is usually profitable for small
6996 /// memory size.
6997 static SDValue getMemsetStores(SelectionDAG &DAG, const SDLoc &dl,
6998                                SDValue Chain, SDValue Dst, SDValue Src,
6999                                uint64_t Size, Align Alignment, bool isVol,
7000                                MachinePointerInfo DstPtrInfo,
7001                                const AAMDNodes &AAInfo) {
7002   // Turn a memset of undef to nop.
7003   // FIXME: We need to honor volatile even is Src is undef.
7004   if (Src.isUndef())
7005     return Chain;
7006 
7007   // Expand memset to a series of load/store ops if the size operand
7008   // falls below a certain threshold.
7009   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7010   std::vector<EVT> MemOps;
7011   bool DstAlignCanChange = false;
7012   MachineFunction &MF = DAG.getMachineFunction();
7013   MachineFrameInfo &MFI = MF.getFrameInfo();
7014   bool OptSize = shouldLowerMemFuncForSize(MF, DAG);
7015   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
7016   if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
7017     DstAlignCanChange = true;
7018   bool IsZeroVal =
7019       isa<ConstantSDNode>(Src) && cast<ConstantSDNode>(Src)->isZero();
7020   if (!TLI.findOptimalMemOpLowering(
7021           MemOps, TLI.getMaxStoresPerMemset(OptSize),
7022           MemOp::Set(Size, DstAlignCanChange, Alignment, IsZeroVal, isVol),
7023           DstPtrInfo.getAddrSpace(), ~0u, MF.getFunction().getAttributes()))
7024     return SDValue();
7025 
7026   if (DstAlignCanChange) {
7027     Type *Ty = MemOps[0].getTypeForEVT(*DAG.getContext());
7028     Align NewAlign = DAG.getDataLayout().getABITypeAlign(Ty);
7029     if (NewAlign > Alignment) {
7030       // Give the stack frame object a larger alignment if needed.
7031       if (MFI.getObjectAlign(FI->getIndex()) < NewAlign)
7032         MFI.setObjectAlignment(FI->getIndex(), NewAlign);
7033       Alignment = NewAlign;
7034     }
7035   }
7036 
7037   SmallVector<SDValue, 8> OutChains;
7038   uint64_t DstOff = 0;
7039   unsigned NumMemOps = MemOps.size();
7040 
7041   // Find the largest store and generate the bit pattern for it.
7042   EVT LargestVT = MemOps[0];
7043   for (unsigned i = 1; i < NumMemOps; i++)
7044     if (MemOps[i].bitsGT(LargestVT))
7045       LargestVT = MemOps[i];
7046   SDValue MemSetValue = getMemsetValue(Src, LargestVT, DAG, dl);
7047 
7048   // Prepare AAInfo for loads/stores after lowering this memset.
7049   AAMDNodes NewAAInfo = AAInfo;
7050   NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr;
7051 
7052   for (unsigned i = 0; i < NumMemOps; i++) {
7053     EVT VT = MemOps[i];
7054     unsigned VTSize = VT.getSizeInBits() / 8;
7055     if (VTSize > Size) {
7056       // Issuing an unaligned load / store pair  that overlaps with the previous
7057       // pair. Adjust the offset accordingly.
7058       assert(i == NumMemOps-1 && i != 0);
7059       DstOff -= VTSize - Size;
7060     }
7061 
7062     // If this store is smaller than the largest store see whether we can get
7063     // the smaller value for free with a truncate.
7064     SDValue Value = MemSetValue;
7065     if (VT.bitsLT(LargestVT)) {
7066       if (!LargestVT.isVector() && !VT.isVector() &&
7067           TLI.isTruncateFree(LargestVT, VT))
7068         Value = DAG.getNode(ISD::TRUNCATE, dl, VT, MemSetValue);
7069       else
7070         Value = getMemsetValue(Src, VT, DAG, dl);
7071     }
7072     assert(Value.getValueType() == VT && "Value with wrong type.");
7073     SDValue Store = DAG.getStore(
7074         Chain, dl, Value,
7075         DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl),
7076         DstPtrInfo.getWithOffset(DstOff), Alignment,
7077         isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone,
7078         NewAAInfo);
7079     OutChains.push_back(Store);
7080     DstOff += VT.getSizeInBits() / 8;
7081     Size -= VTSize;
7082   }
7083 
7084   return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
7085 }
7086 
7087 static void checkAddrSpaceIsValidForLibcall(const TargetLowering *TLI,
7088                                             unsigned AS) {
7089   // Lowering memcpy / memset / memmove intrinsics to calls is only valid if all
7090   // pointer operands can be losslessly bitcasted to pointers of address space 0
7091   if (AS != 0 && !TLI->getTargetMachine().isNoopAddrSpaceCast(AS, 0)) {
7092     report_fatal_error("cannot lower memory intrinsic in address space " +
7093                        Twine(AS));
7094   }
7095 }
7096 
7097 SDValue SelectionDAG::getMemcpy(SDValue Chain, const SDLoc &dl, SDValue Dst,
7098                                 SDValue Src, SDValue Size, Align Alignment,
7099                                 bool isVol, bool AlwaysInline, bool isTailCall,
7100                                 MachinePointerInfo DstPtrInfo,
7101                                 MachinePointerInfo SrcPtrInfo,
7102                                 const AAMDNodes &AAInfo) {
7103   // Check to see if we should lower the memcpy to loads and stores first.
7104   // For cases within the target-specified limits, this is the best choice.
7105   ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
7106   if (ConstantSize) {
7107     // Memcpy with size zero? Just return the original chain.
7108     if (ConstantSize->isZero())
7109       return Chain;
7110 
7111     SDValue Result = getMemcpyLoadsAndStores(
7112         *this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), Alignment,
7113         isVol, false, DstPtrInfo, SrcPtrInfo, AAInfo);
7114     if (Result.getNode())
7115       return Result;
7116   }
7117 
7118   // Then check to see if we should lower the memcpy with target-specific
7119   // code. If the target chooses to do this, this is the next best.
7120   if (TSI) {
7121     SDValue Result = TSI->EmitTargetCodeForMemcpy(
7122         *this, dl, Chain, Dst, Src, Size, Alignment, isVol, AlwaysInline,
7123         DstPtrInfo, SrcPtrInfo);
7124     if (Result.getNode())
7125       return Result;
7126   }
7127 
7128   // If we really need inline code and the target declined to provide it,
7129   // use a (potentially long) sequence of loads and stores.
7130   if (AlwaysInline) {
7131     assert(ConstantSize && "AlwaysInline requires a constant size!");
7132     return getMemcpyLoadsAndStores(*this, dl, Chain, Dst, Src,
7133                                    ConstantSize->getZExtValue(), Alignment,
7134                                    isVol, true, DstPtrInfo, SrcPtrInfo, AAInfo);
7135   }
7136 
7137   checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace());
7138   checkAddrSpaceIsValidForLibcall(TLI, SrcPtrInfo.getAddrSpace());
7139 
7140   // FIXME: If the memcpy is volatile (isVol), lowering it to a plain libc
7141   // memcpy is not guaranteed to be safe. libc memcpys aren't required to
7142   // respect volatile, so they may do things like read or write memory
7143   // beyond the given memory regions. But fixing this isn't easy, and most
7144   // people don't care.
7145 
7146   // Emit a library call.
7147   TargetLowering::ArgListTy Args;
7148   TargetLowering::ArgListEntry Entry;
7149   Entry.Ty = Type::getInt8PtrTy(*getContext());
7150   Entry.Node = Dst; Args.push_back(Entry);
7151   Entry.Node = Src; Args.push_back(Entry);
7152 
7153   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
7154   Entry.Node = Size; Args.push_back(Entry);
7155   // FIXME: pass in SDLoc
7156   TargetLowering::CallLoweringInfo CLI(*this);
7157   CLI.setDebugLoc(dl)
7158       .setChain(Chain)
7159       .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMCPY),
7160                     Dst.getValueType().getTypeForEVT(*getContext()),
7161                     getExternalSymbol(TLI->getLibcallName(RTLIB::MEMCPY),
7162                                       TLI->getPointerTy(getDataLayout())),
7163                     std::move(Args))
7164       .setDiscardResult()
7165       .setTailCall(isTailCall);
7166 
7167   std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
7168   return CallResult.second;
7169 }
7170 
7171 SDValue SelectionDAG::getAtomicMemcpy(SDValue Chain, const SDLoc &dl,
7172                                       SDValue Dst, unsigned DstAlign,
7173                                       SDValue Src, unsigned SrcAlign,
7174                                       SDValue Size, Type *SizeTy,
7175                                       unsigned ElemSz, 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, unsigned DstAlign,
7276                                        SDValue Src, unsigned SrcAlign,
7277                                        SDValue Size, Type *SizeTy,
7278                                        unsigned ElemSz, bool isTailCall,
7279                                        MachinePointerInfo DstPtrInfo,
7280                                        MachinePointerInfo SrcPtrInfo) {
7281   // Emit a library call.
7282   TargetLowering::ArgListTy Args;
7283   TargetLowering::ArgListEntry Entry;
7284   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
7285   Entry.Node = Dst;
7286   Args.push_back(Entry);
7287 
7288   Entry.Node = Src;
7289   Args.push_back(Entry);
7290 
7291   Entry.Ty = SizeTy;
7292   Entry.Node = Size;
7293   Args.push_back(Entry);
7294 
7295   RTLIB::Libcall LibraryCall =
7296       RTLIB::getMEMMOVE_ELEMENT_UNORDERED_ATOMIC(ElemSz);
7297   if (LibraryCall == RTLIB::UNKNOWN_LIBCALL)
7298     report_fatal_error("Unsupported element size");
7299 
7300   TargetLowering::CallLoweringInfo CLI(*this);
7301   CLI.setDebugLoc(dl)
7302       .setChain(Chain)
7303       .setLibCallee(TLI->getLibcallCallingConv(LibraryCall),
7304                     Type::getVoidTy(*getContext()),
7305                     getExternalSymbol(TLI->getLibcallName(LibraryCall),
7306                                       TLI->getPointerTy(getDataLayout())),
7307                     std::move(Args))
7308       .setDiscardResult()
7309       .setTailCall(isTailCall);
7310 
7311   std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
7312   return CallResult.second;
7313 }
7314 
7315 SDValue SelectionDAG::getMemset(SDValue Chain, const SDLoc &dl, SDValue Dst,
7316                                 SDValue Src, SDValue Size, Align Alignment,
7317                                 bool isVol, bool isTailCall,
7318                                 MachinePointerInfo DstPtrInfo,
7319                                 const AAMDNodes &AAInfo) {
7320   // Check to see if we should lower the memset to stores first.
7321   // For cases within the target-specified limits, this is the best choice.
7322   ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
7323   if (ConstantSize) {
7324     // Memset with size zero? Just return the original chain.
7325     if (ConstantSize->isZero())
7326       return Chain;
7327 
7328     SDValue Result = getMemsetStores(*this, dl, Chain, Dst, Src,
7329                                      ConstantSize->getZExtValue(), Alignment,
7330                                      isVol, DstPtrInfo, AAInfo);
7331 
7332     if (Result.getNode())
7333       return Result;
7334   }
7335 
7336   // Then check to see if we should lower the memset with target-specific
7337   // code. If the target chooses to do this, this is the next best.
7338   if (TSI) {
7339     SDValue Result = TSI->EmitTargetCodeForMemset(
7340         *this, dl, Chain, Dst, Src, Size, Alignment, isVol, DstPtrInfo);
7341     if (Result.getNode())
7342       return Result;
7343   }
7344 
7345   checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace());
7346 
7347   // Emit a library call.
7348   auto &Ctx = *getContext();
7349   const auto& DL = getDataLayout();
7350 
7351   TargetLowering::CallLoweringInfo CLI(*this);
7352   // FIXME: pass in SDLoc
7353   CLI.setDebugLoc(dl).setChain(Chain);
7354 
7355   ConstantSDNode *ConstantSrc = dyn_cast<ConstantSDNode>(Src);
7356   const bool SrcIsZero = ConstantSrc && ConstantSrc->isZero();
7357   const char *BzeroName = getTargetLoweringInfo().getLibcallName(RTLIB::BZERO);
7358 
7359   // Helper function to create an Entry from Node and Type.
7360   const auto CreateEntry = [](SDValue Node, Type *Ty) {
7361     TargetLowering::ArgListEntry Entry;
7362     Entry.Node = Node;
7363     Entry.Ty = Ty;
7364     return Entry;
7365   };
7366 
7367   // If zeroing out and bzero is present, use it.
7368   if (SrcIsZero && BzeroName) {
7369     TargetLowering::ArgListTy Args;
7370     Args.push_back(CreateEntry(Dst, Type::getInt8PtrTy(Ctx)));
7371     Args.push_back(CreateEntry(Size, DL.getIntPtrType(Ctx)));
7372     CLI.setLibCallee(
7373         TLI->getLibcallCallingConv(RTLIB::BZERO), Type::getVoidTy(Ctx),
7374         getExternalSymbol(BzeroName, TLI->getPointerTy(DL)), std::move(Args));
7375   } else {
7376     TargetLowering::ArgListTy Args;
7377     Args.push_back(CreateEntry(Dst, Type::getInt8PtrTy(Ctx)));
7378     Args.push_back(CreateEntry(Src, Src.getValueType().getTypeForEVT(Ctx)));
7379     Args.push_back(CreateEntry(Size, DL.getIntPtrType(Ctx)));
7380     CLI.setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMSET),
7381                      Dst.getValueType().getTypeForEVT(Ctx),
7382                      getExternalSymbol(TLI->getLibcallName(RTLIB::MEMSET),
7383                                        TLI->getPointerTy(DL)),
7384                      std::move(Args));
7385   }
7386 
7387   CLI.setDiscardResult().setTailCall(isTailCall);
7388 
7389   std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
7390   return CallResult.second;
7391 }
7392 
7393 SDValue SelectionDAG::getAtomicMemset(SDValue Chain, const SDLoc &dl,
7394                                       SDValue Dst, unsigned DstAlign,
7395                                       SDValue Value, SDValue Size, Type *SizeTy,
7396                                       unsigned ElemSz, bool isTailCall,
7397                                       MachinePointerInfo DstPtrInfo) {
7398   // Emit a library call.
7399   TargetLowering::ArgListTy Args;
7400   TargetLowering::ArgListEntry Entry;
7401   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
7402   Entry.Node = Dst;
7403   Args.push_back(Entry);
7404 
7405   Entry.Ty = Type::getInt8Ty(*getContext());
7406   Entry.Node = Value;
7407   Args.push_back(Entry);
7408 
7409   Entry.Ty = SizeTy;
7410   Entry.Node = Size;
7411   Args.push_back(Entry);
7412 
7413   RTLIB::Libcall LibraryCall =
7414       RTLIB::getMEMSET_ELEMENT_UNORDERED_ATOMIC(ElemSz);
7415   if (LibraryCall == RTLIB::UNKNOWN_LIBCALL)
7416     report_fatal_error("Unsupported element size");
7417 
7418   TargetLowering::CallLoweringInfo CLI(*this);
7419   CLI.setDebugLoc(dl)
7420       .setChain(Chain)
7421       .setLibCallee(TLI->getLibcallCallingConv(LibraryCall),
7422                     Type::getVoidTy(*getContext()),
7423                     getExternalSymbol(TLI->getLibcallName(LibraryCall),
7424                                       TLI->getPointerTy(getDataLayout())),
7425                     std::move(Args))
7426       .setDiscardResult()
7427       .setTailCall(isTailCall);
7428 
7429   std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
7430   return CallResult.second;
7431 }
7432 
7433 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
7434                                 SDVTList VTList, ArrayRef<SDValue> Ops,
7435                                 MachineMemOperand *MMO) {
7436   FoldingSetNodeID ID;
7437   ID.AddInteger(MemVT.getRawBits());
7438   AddNodeIDNode(ID, Opcode, VTList, Ops);
7439   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7440   ID.AddInteger(MMO->getFlags());
7441   void* IP = nullptr;
7442   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7443     cast<AtomicSDNode>(E)->refineAlignment(MMO);
7444     return SDValue(E, 0);
7445   }
7446 
7447   auto *N = newSDNode<AtomicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
7448                                     VTList, MemVT, MMO);
7449   createOperands(N, Ops);
7450 
7451   CSEMap.InsertNode(N, IP);
7452   InsertNode(N);
7453   return SDValue(N, 0);
7454 }
7455 
7456 SDValue SelectionDAG::getAtomicCmpSwap(unsigned Opcode, const SDLoc &dl,
7457                                        EVT MemVT, SDVTList VTs, SDValue Chain,
7458                                        SDValue Ptr, SDValue Cmp, SDValue Swp,
7459                                        MachineMemOperand *MMO) {
7460   assert(Opcode == ISD::ATOMIC_CMP_SWAP ||
7461          Opcode == ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS);
7462   assert(Cmp.getValueType() == Swp.getValueType() && "Invalid Atomic Op Types");
7463 
7464   SDValue Ops[] = {Chain, Ptr, Cmp, Swp};
7465   return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
7466 }
7467 
7468 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
7469                                 SDValue Chain, SDValue Ptr, SDValue Val,
7470                                 MachineMemOperand *MMO) {
7471   assert((Opcode == ISD::ATOMIC_LOAD_ADD ||
7472           Opcode == ISD::ATOMIC_LOAD_SUB ||
7473           Opcode == ISD::ATOMIC_LOAD_AND ||
7474           Opcode == ISD::ATOMIC_LOAD_CLR ||
7475           Opcode == ISD::ATOMIC_LOAD_OR ||
7476           Opcode == ISD::ATOMIC_LOAD_XOR ||
7477           Opcode == ISD::ATOMIC_LOAD_NAND ||
7478           Opcode == ISD::ATOMIC_LOAD_MIN ||
7479           Opcode == ISD::ATOMIC_LOAD_MAX ||
7480           Opcode == ISD::ATOMIC_LOAD_UMIN ||
7481           Opcode == ISD::ATOMIC_LOAD_UMAX ||
7482           Opcode == ISD::ATOMIC_LOAD_FADD ||
7483           Opcode == ISD::ATOMIC_LOAD_FSUB ||
7484           Opcode == ISD::ATOMIC_SWAP ||
7485           Opcode == ISD::ATOMIC_STORE) &&
7486          "Invalid Atomic Op");
7487 
7488   EVT VT = Val.getValueType();
7489 
7490   SDVTList VTs = Opcode == ISD::ATOMIC_STORE ? getVTList(MVT::Other) :
7491                                                getVTList(VT, MVT::Other);
7492   SDValue Ops[] = {Chain, Ptr, Val};
7493   return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
7494 }
7495 
7496 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
7497                                 EVT VT, SDValue Chain, SDValue Ptr,
7498                                 MachineMemOperand *MMO) {
7499   assert(Opcode == ISD::ATOMIC_LOAD && "Invalid Atomic Op");
7500 
7501   SDVTList VTs = getVTList(VT, MVT::Other);
7502   SDValue Ops[] = {Chain, Ptr};
7503   return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
7504 }
7505 
7506 /// getMergeValues - Create a MERGE_VALUES node from the given operands.
7507 SDValue SelectionDAG::getMergeValues(ArrayRef<SDValue> Ops, const SDLoc &dl) {
7508   if (Ops.size() == 1)
7509     return Ops[0];
7510 
7511   SmallVector<EVT, 4> VTs;
7512   VTs.reserve(Ops.size());
7513   for (const SDValue &Op : Ops)
7514     VTs.push_back(Op.getValueType());
7515   return getNode(ISD::MERGE_VALUES, dl, getVTList(VTs), Ops);
7516 }
7517 
7518 SDValue SelectionDAG::getMemIntrinsicNode(
7519     unsigned Opcode, const SDLoc &dl, SDVTList VTList, ArrayRef<SDValue> Ops,
7520     EVT MemVT, MachinePointerInfo PtrInfo, Align Alignment,
7521     MachineMemOperand::Flags Flags, uint64_t Size, const AAMDNodes &AAInfo) {
7522   if (!Size && MemVT.isScalableVector())
7523     Size = MemoryLocation::UnknownSize;
7524   else if (!Size)
7525     Size = MemVT.getStoreSize();
7526 
7527   MachineFunction &MF = getMachineFunction();
7528   MachineMemOperand *MMO =
7529       MF.getMachineMemOperand(PtrInfo, Flags, Size, Alignment, AAInfo);
7530 
7531   return getMemIntrinsicNode(Opcode, dl, VTList, Ops, MemVT, MMO);
7532 }
7533 
7534 SDValue SelectionDAG::getMemIntrinsicNode(unsigned Opcode, const SDLoc &dl,
7535                                           SDVTList VTList,
7536                                           ArrayRef<SDValue> Ops, EVT MemVT,
7537                                           MachineMemOperand *MMO) {
7538   assert((Opcode == ISD::INTRINSIC_VOID ||
7539           Opcode == ISD::INTRINSIC_W_CHAIN ||
7540           Opcode == ISD::PREFETCH ||
7541           ((int)Opcode <= std::numeric_limits<int>::max() &&
7542            (int)Opcode >= ISD::FIRST_TARGET_MEMORY_OPCODE)) &&
7543          "Opcode is not a memory-accessing opcode!");
7544 
7545   // Memoize the node unless it returns a flag.
7546   MemIntrinsicSDNode *N;
7547   if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) {
7548     FoldingSetNodeID ID;
7549     AddNodeIDNode(ID, Opcode, VTList, Ops);
7550     ID.AddInteger(getSyntheticNodeSubclassData<MemIntrinsicSDNode>(
7551         Opcode, dl.getIROrder(), VTList, MemVT, MMO));
7552     ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7553     ID.AddInteger(MMO->getFlags());
7554     void *IP = nullptr;
7555     if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7556       cast<MemIntrinsicSDNode>(E)->refineAlignment(MMO);
7557       return SDValue(E, 0);
7558     }
7559 
7560     N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
7561                                       VTList, MemVT, MMO);
7562     createOperands(N, Ops);
7563 
7564   CSEMap.InsertNode(N, IP);
7565   } else {
7566     N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
7567                                       VTList, MemVT, MMO);
7568     createOperands(N, Ops);
7569   }
7570   InsertNode(N);
7571   SDValue V(N, 0);
7572   NewSDValueDbgMsg(V, "Creating new node: ", this);
7573   return V;
7574 }
7575 
7576 SDValue SelectionDAG::getLifetimeNode(bool IsStart, const SDLoc &dl,
7577                                       SDValue Chain, int FrameIndex,
7578                                       int64_t Size, int64_t Offset) {
7579   const unsigned Opcode = IsStart ? ISD::LIFETIME_START : ISD::LIFETIME_END;
7580   const auto VTs = getVTList(MVT::Other);
7581   SDValue Ops[2] = {
7582       Chain,
7583       getFrameIndex(FrameIndex,
7584                     getTargetLoweringInfo().getFrameIndexTy(getDataLayout()),
7585                     true)};
7586 
7587   FoldingSetNodeID ID;
7588   AddNodeIDNode(ID, Opcode, VTs, Ops);
7589   ID.AddInteger(FrameIndex);
7590   ID.AddInteger(Size);
7591   ID.AddInteger(Offset);
7592   void *IP = nullptr;
7593   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
7594     return SDValue(E, 0);
7595 
7596   LifetimeSDNode *N = newSDNode<LifetimeSDNode>(
7597       Opcode, dl.getIROrder(), dl.getDebugLoc(), VTs, Size, Offset);
7598   createOperands(N, Ops);
7599   CSEMap.InsertNode(N, IP);
7600   InsertNode(N);
7601   SDValue V(N, 0);
7602   NewSDValueDbgMsg(V, "Creating new node: ", this);
7603   return V;
7604 }
7605 
7606 SDValue SelectionDAG::getPseudoProbeNode(const SDLoc &Dl, SDValue Chain,
7607                                          uint64_t Guid, uint64_t Index,
7608                                          uint32_t Attr) {
7609   const unsigned Opcode = ISD::PSEUDO_PROBE;
7610   const auto VTs = getVTList(MVT::Other);
7611   SDValue Ops[] = {Chain};
7612   FoldingSetNodeID ID;
7613   AddNodeIDNode(ID, Opcode, VTs, Ops);
7614   ID.AddInteger(Guid);
7615   ID.AddInteger(Index);
7616   void *IP = nullptr;
7617   if (SDNode *E = FindNodeOrInsertPos(ID, Dl, IP))
7618     return SDValue(E, 0);
7619 
7620   auto *N = newSDNode<PseudoProbeSDNode>(
7621       Opcode, Dl.getIROrder(), Dl.getDebugLoc(), VTs, Guid, Index, Attr);
7622   createOperands(N, Ops);
7623   CSEMap.InsertNode(N, IP);
7624   InsertNode(N);
7625   SDValue V(N, 0);
7626   NewSDValueDbgMsg(V, "Creating new node: ", this);
7627   return V;
7628 }
7629 
7630 /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a
7631 /// MachinePointerInfo record from it.  This is particularly useful because the
7632 /// code generator has many cases where it doesn't bother passing in a
7633 /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst".
7634 static MachinePointerInfo InferPointerInfo(const MachinePointerInfo &Info,
7635                                            SelectionDAG &DAG, SDValue Ptr,
7636                                            int64_t Offset = 0) {
7637   // If this is FI+Offset, we can model it.
7638   if (const FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr))
7639     return MachinePointerInfo::getFixedStack(DAG.getMachineFunction(),
7640                                              FI->getIndex(), Offset);
7641 
7642   // If this is (FI+Offset1)+Offset2, we can model it.
7643   if (Ptr.getOpcode() != ISD::ADD ||
7644       !isa<ConstantSDNode>(Ptr.getOperand(1)) ||
7645       !isa<FrameIndexSDNode>(Ptr.getOperand(0)))
7646     return Info;
7647 
7648   int FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
7649   return MachinePointerInfo::getFixedStack(
7650       DAG.getMachineFunction(), FI,
7651       Offset + cast<ConstantSDNode>(Ptr.getOperand(1))->getSExtValue());
7652 }
7653 
7654 /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a
7655 /// MachinePointerInfo record from it.  This is particularly useful because the
7656 /// code generator has many cases where it doesn't bother passing in a
7657 /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst".
7658 static MachinePointerInfo InferPointerInfo(const MachinePointerInfo &Info,
7659                                            SelectionDAG &DAG, SDValue Ptr,
7660                                            SDValue OffsetOp) {
7661   // If the 'Offset' value isn't a constant, we can't handle this.
7662   if (ConstantSDNode *OffsetNode = dyn_cast<ConstantSDNode>(OffsetOp))
7663     return InferPointerInfo(Info, DAG, Ptr, OffsetNode->getSExtValue());
7664   if (OffsetOp.isUndef())
7665     return InferPointerInfo(Info, DAG, Ptr);
7666   return Info;
7667 }
7668 
7669 SDValue SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType,
7670                               EVT VT, const SDLoc &dl, SDValue Chain,
7671                               SDValue Ptr, SDValue Offset,
7672                               MachinePointerInfo PtrInfo, EVT MemVT,
7673                               Align Alignment,
7674                               MachineMemOperand::Flags MMOFlags,
7675                               const AAMDNodes &AAInfo, const MDNode *Ranges) {
7676   assert(Chain.getValueType() == MVT::Other &&
7677         "Invalid chain type");
7678 
7679   MMOFlags |= MachineMemOperand::MOLoad;
7680   assert((MMOFlags & MachineMemOperand::MOStore) == 0);
7681   // If we don't have a PtrInfo, infer the trivial frame index case to simplify
7682   // clients.
7683   if (PtrInfo.V.isNull())
7684     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr, Offset);
7685 
7686   uint64_t Size = MemoryLocation::getSizeOrUnknown(MemVT.getStoreSize());
7687   MachineFunction &MF = getMachineFunction();
7688   MachineMemOperand *MMO = MF.getMachineMemOperand(PtrInfo, MMOFlags, Size,
7689                                                    Alignment, AAInfo, Ranges);
7690   return getLoad(AM, ExtType, VT, dl, Chain, Ptr, Offset, MemVT, MMO);
7691 }
7692 
7693 SDValue SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType,
7694                               EVT VT, const SDLoc &dl, SDValue Chain,
7695                               SDValue Ptr, SDValue Offset, EVT MemVT,
7696                               MachineMemOperand *MMO) {
7697   if (VT == MemVT) {
7698     ExtType = ISD::NON_EXTLOAD;
7699   } else if (ExtType == ISD::NON_EXTLOAD) {
7700     assert(VT == MemVT && "Non-extending load from different memory type!");
7701   } else {
7702     // Extending load.
7703     assert(MemVT.getScalarType().bitsLT(VT.getScalarType()) &&
7704            "Should only be an extending load, not truncating!");
7705     assert(VT.isInteger() == MemVT.isInteger() &&
7706            "Cannot convert from FP to Int or Int -> FP!");
7707     assert(VT.isVector() == MemVT.isVector() &&
7708            "Cannot use an ext load to convert to or from a vector!");
7709     assert((!VT.isVector() ||
7710             VT.getVectorElementCount() == MemVT.getVectorElementCount()) &&
7711            "Cannot use an ext load to change the number of vector elements!");
7712   }
7713 
7714   bool Indexed = AM != ISD::UNINDEXED;
7715   assert((Indexed || Offset.isUndef()) && "Unindexed load with an offset!");
7716 
7717   SDVTList VTs = Indexed ?
7718     getVTList(VT, Ptr.getValueType(), MVT::Other) : getVTList(VT, MVT::Other);
7719   SDValue Ops[] = { Chain, Ptr, Offset };
7720   FoldingSetNodeID ID;
7721   AddNodeIDNode(ID, ISD::LOAD, VTs, Ops);
7722   ID.AddInteger(MemVT.getRawBits());
7723   ID.AddInteger(getSyntheticNodeSubclassData<LoadSDNode>(
7724       dl.getIROrder(), VTs, AM, ExtType, MemVT, MMO));
7725   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7726   ID.AddInteger(MMO->getFlags());
7727   void *IP = nullptr;
7728   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7729     cast<LoadSDNode>(E)->refineAlignment(MMO);
7730     return SDValue(E, 0);
7731   }
7732   auto *N = newSDNode<LoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
7733                                   ExtType, MemVT, MMO);
7734   createOperands(N, Ops);
7735 
7736   CSEMap.InsertNode(N, IP);
7737   InsertNode(N);
7738   SDValue V(N, 0);
7739   NewSDValueDbgMsg(V, "Creating new node: ", this);
7740   return V;
7741 }
7742 
7743 SDValue SelectionDAG::getLoad(EVT VT, const SDLoc &dl, SDValue Chain,
7744                               SDValue Ptr, MachinePointerInfo PtrInfo,
7745                               MaybeAlign Alignment,
7746                               MachineMemOperand::Flags MMOFlags,
7747                               const AAMDNodes &AAInfo, const MDNode *Ranges) {
7748   SDValue Undef = getUNDEF(Ptr.getValueType());
7749   return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
7750                  PtrInfo, VT, Alignment, MMOFlags, AAInfo, Ranges);
7751 }
7752 
7753 SDValue SelectionDAG::getLoad(EVT VT, const SDLoc &dl, SDValue Chain,
7754                               SDValue Ptr, MachineMemOperand *MMO) {
7755   SDValue Undef = getUNDEF(Ptr.getValueType());
7756   return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
7757                  VT, MMO);
7758 }
7759 
7760 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl,
7761                                  EVT VT, SDValue Chain, SDValue Ptr,
7762                                  MachinePointerInfo PtrInfo, EVT MemVT,
7763                                  MaybeAlign Alignment,
7764                                  MachineMemOperand::Flags MMOFlags,
7765                                  const AAMDNodes &AAInfo) {
7766   SDValue Undef = getUNDEF(Ptr.getValueType());
7767   return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, PtrInfo,
7768                  MemVT, Alignment, MMOFlags, AAInfo);
7769 }
7770 
7771 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl,
7772                                  EVT VT, SDValue Chain, SDValue Ptr, EVT MemVT,
7773                                  MachineMemOperand *MMO) {
7774   SDValue Undef = getUNDEF(Ptr.getValueType());
7775   return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef,
7776                  MemVT, MMO);
7777 }
7778 
7779 SDValue SelectionDAG::getIndexedLoad(SDValue OrigLoad, const SDLoc &dl,
7780                                      SDValue Base, SDValue Offset,
7781                                      ISD::MemIndexedMode AM) {
7782   LoadSDNode *LD = cast<LoadSDNode>(OrigLoad);
7783   assert(LD->getOffset().isUndef() && "Load is already a indexed load!");
7784   // Don't propagate the invariant or dereferenceable flags.
7785   auto MMOFlags =
7786       LD->getMemOperand()->getFlags() &
7787       ~(MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable);
7788   return getLoad(AM, LD->getExtensionType(), OrigLoad.getValueType(), dl,
7789                  LD->getChain(), Base, Offset, LD->getPointerInfo(),
7790                  LD->getMemoryVT(), LD->getAlign(), MMOFlags, LD->getAAInfo());
7791 }
7792 
7793 SDValue SelectionDAG::getStore(SDValue Chain, const SDLoc &dl, SDValue Val,
7794                                SDValue Ptr, MachinePointerInfo PtrInfo,
7795                                Align Alignment,
7796                                MachineMemOperand::Flags MMOFlags,
7797                                const AAMDNodes &AAInfo) {
7798   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
7799 
7800   MMOFlags |= MachineMemOperand::MOStore;
7801   assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
7802 
7803   if (PtrInfo.V.isNull())
7804     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
7805 
7806   MachineFunction &MF = getMachineFunction();
7807   uint64_t Size =
7808       MemoryLocation::getSizeOrUnknown(Val.getValueType().getStoreSize());
7809   MachineMemOperand *MMO =
7810       MF.getMachineMemOperand(PtrInfo, MMOFlags, Size, Alignment, AAInfo);
7811   return getStore(Chain, dl, Val, Ptr, MMO);
7812 }
7813 
7814 SDValue SelectionDAG::getStore(SDValue Chain, const SDLoc &dl, SDValue Val,
7815                                SDValue Ptr, MachineMemOperand *MMO) {
7816   assert(Chain.getValueType() == MVT::Other &&
7817         "Invalid chain type");
7818   EVT VT = Val.getValueType();
7819   SDVTList VTs = getVTList(MVT::Other);
7820   SDValue Undef = getUNDEF(Ptr.getValueType());
7821   SDValue Ops[] = { Chain, Val, Ptr, Undef };
7822   FoldingSetNodeID ID;
7823   AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
7824   ID.AddInteger(VT.getRawBits());
7825   ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>(
7826       dl.getIROrder(), VTs, ISD::UNINDEXED, false, VT, MMO));
7827   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7828   ID.AddInteger(MMO->getFlags());
7829   void *IP = nullptr;
7830   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7831     cast<StoreSDNode>(E)->refineAlignment(MMO);
7832     return SDValue(E, 0);
7833   }
7834   auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
7835                                    ISD::UNINDEXED, false, VT, MMO);
7836   createOperands(N, Ops);
7837 
7838   CSEMap.InsertNode(N, IP);
7839   InsertNode(N);
7840   SDValue V(N, 0);
7841   NewSDValueDbgMsg(V, "Creating new node: ", this);
7842   return V;
7843 }
7844 
7845 SDValue SelectionDAG::getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val,
7846                                     SDValue Ptr, MachinePointerInfo PtrInfo,
7847                                     EVT SVT, Align Alignment,
7848                                     MachineMemOperand::Flags MMOFlags,
7849                                     const AAMDNodes &AAInfo) {
7850   assert(Chain.getValueType() == MVT::Other &&
7851         "Invalid chain type");
7852 
7853   MMOFlags |= MachineMemOperand::MOStore;
7854   assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
7855 
7856   if (PtrInfo.V.isNull())
7857     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
7858 
7859   MachineFunction &MF = getMachineFunction();
7860   MachineMemOperand *MMO = MF.getMachineMemOperand(
7861       PtrInfo, MMOFlags, MemoryLocation::getSizeOrUnknown(SVT.getStoreSize()),
7862       Alignment, AAInfo);
7863   return getTruncStore(Chain, dl, Val, Ptr, SVT, MMO);
7864 }
7865 
7866 SDValue SelectionDAG::getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val,
7867                                     SDValue Ptr, EVT SVT,
7868                                     MachineMemOperand *MMO) {
7869   EVT VT = Val.getValueType();
7870 
7871   assert(Chain.getValueType() == MVT::Other &&
7872         "Invalid chain type");
7873   if (VT == SVT)
7874     return getStore(Chain, dl, Val, Ptr, MMO);
7875 
7876   assert(SVT.getScalarType().bitsLT(VT.getScalarType()) &&
7877          "Should only be a truncating store, not extending!");
7878   assert(VT.isInteger() == SVT.isInteger() &&
7879          "Can't do FP-INT conversion!");
7880   assert(VT.isVector() == SVT.isVector() &&
7881          "Cannot use trunc store to convert to or from a vector!");
7882   assert((!VT.isVector() ||
7883           VT.getVectorElementCount() == SVT.getVectorElementCount()) &&
7884          "Cannot use trunc store to change the number of vector elements!");
7885 
7886   SDVTList VTs = getVTList(MVT::Other);
7887   SDValue Undef = getUNDEF(Ptr.getValueType());
7888   SDValue Ops[] = { Chain, Val, Ptr, Undef };
7889   FoldingSetNodeID ID;
7890   AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
7891   ID.AddInteger(SVT.getRawBits());
7892   ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>(
7893       dl.getIROrder(), VTs, ISD::UNINDEXED, true, SVT, MMO));
7894   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7895   ID.AddInteger(MMO->getFlags());
7896   void *IP = nullptr;
7897   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7898     cast<StoreSDNode>(E)->refineAlignment(MMO);
7899     return SDValue(E, 0);
7900   }
7901   auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
7902                                    ISD::UNINDEXED, true, SVT, MMO);
7903   createOperands(N, Ops);
7904 
7905   CSEMap.InsertNode(N, IP);
7906   InsertNode(N);
7907   SDValue V(N, 0);
7908   NewSDValueDbgMsg(V, "Creating new node: ", this);
7909   return V;
7910 }
7911 
7912 SDValue SelectionDAG::getIndexedStore(SDValue OrigStore, const SDLoc &dl,
7913                                       SDValue Base, SDValue Offset,
7914                                       ISD::MemIndexedMode AM) {
7915   StoreSDNode *ST = cast<StoreSDNode>(OrigStore);
7916   assert(ST->getOffset().isUndef() && "Store is already a indexed store!");
7917   SDVTList VTs = getVTList(Base.getValueType(), MVT::Other);
7918   SDValue Ops[] = { ST->getChain(), ST->getValue(), Base, Offset };
7919   FoldingSetNodeID ID;
7920   AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
7921   ID.AddInteger(ST->getMemoryVT().getRawBits());
7922   ID.AddInteger(ST->getRawSubclassData());
7923   ID.AddInteger(ST->getPointerInfo().getAddrSpace());
7924   ID.AddInteger(ST->getMemOperand()->getFlags());
7925   void *IP = nullptr;
7926   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
7927     return SDValue(E, 0);
7928 
7929   auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
7930                                    ST->isTruncatingStore(), ST->getMemoryVT(),
7931                                    ST->getMemOperand());
7932   createOperands(N, Ops);
7933 
7934   CSEMap.InsertNode(N, IP);
7935   InsertNode(N);
7936   SDValue V(N, 0);
7937   NewSDValueDbgMsg(V, "Creating new node: ", this);
7938   return V;
7939 }
7940 
7941 SDValue SelectionDAG::getLoadVP(
7942     ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, EVT VT, const SDLoc &dl,
7943     SDValue Chain, SDValue Ptr, SDValue Offset, SDValue Mask, SDValue EVL,
7944     MachinePointerInfo PtrInfo, EVT MemVT, Align Alignment,
7945     MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo,
7946     const MDNode *Ranges, bool IsExpanding) {
7947   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
7948 
7949   MMOFlags |= MachineMemOperand::MOLoad;
7950   assert((MMOFlags & MachineMemOperand::MOStore) == 0);
7951   // If we don't have a PtrInfo, infer the trivial frame index case to simplify
7952   // clients.
7953   if (PtrInfo.V.isNull())
7954     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr, Offset);
7955 
7956   uint64_t Size = MemoryLocation::getSizeOrUnknown(MemVT.getStoreSize());
7957   MachineFunction &MF = getMachineFunction();
7958   MachineMemOperand *MMO = MF.getMachineMemOperand(PtrInfo, MMOFlags, Size,
7959                                                    Alignment, AAInfo, Ranges);
7960   return getLoadVP(AM, ExtType, VT, dl, Chain, Ptr, Offset, Mask, EVL, MemVT,
7961                    MMO, IsExpanding);
7962 }
7963 
7964 SDValue SelectionDAG::getLoadVP(ISD::MemIndexedMode AM,
7965                                 ISD::LoadExtType ExtType, EVT VT,
7966                                 const SDLoc &dl, SDValue Chain, SDValue Ptr,
7967                                 SDValue Offset, SDValue Mask, SDValue EVL,
7968                                 EVT MemVT, MachineMemOperand *MMO,
7969                                 bool IsExpanding) {
7970   bool Indexed = AM != ISD::UNINDEXED;
7971   assert((Indexed || Offset.isUndef()) && "Unindexed load with an offset!");
7972 
7973   SDVTList VTs = Indexed ? getVTList(VT, Ptr.getValueType(), MVT::Other)
7974                          : getVTList(VT, MVT::Other);
7975   SDValue Ops[] = {Chain, Ptr, Offset, Mask, EVL};
7976   FoldingSetNodeID ID;
7977   AddNodeIDNode(ID, ISD::VP_LOAD, VTs, Ops);
7978   ID.AddInteger(VT.getRawBits());
7979   ID.AddInteger(getSyntheticNodeSubclassData<VPLoadSDNode>(
7980       dl.getIROrder(), VTs, AM, ExtType, IsExpanding, MemVT, MMO));
7981   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7982   ID.AddInteger(MMO->getFlags());
7983   void *IP = nullptr;
7984   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7985     cast<VPLoadSDNode>(E)->refineAlignment(MMO);
7986     return SDValue(E, 0);
7987   }
7988   auto *N = newSDNode<VPLoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
7989                                     ExtType, IsExpanding, MemVT, MMO);
7990   createOperands(N, Ops);
7991 
7992   CSEMap.InsertNode(N, IP);
7993   InsertNode(N);
7994   SDValue V(N, 0);
7995   NewSDValueDbgMsg(V, "Creating new node: ", this);
7996   return V;
7997 }
7998 
7999 SDValue SelectionDAG::getLoadVP(EVT VT, const SDLoc &dl, SDValue Chain,
8000                                 SDValue Ptr, SDValue Mask, SDValue EVL,
8001                                 MachinePointerInfo PtrInfo,
8002                                 MaybeAlign Alignment,
8003                                 MachineMemOperand::Flags MMOFlags,
8004                                 const AAMDNodes &AAInfo, const MDNode *Ranges,
8005                                 bool IsExpanding) {
8006   SDValue Undef = getUNDEF(Ptr.getValueType());
8007   return getLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
8008                    Mask, EVL, PtrInfo, VT, Alignment, MMOFlags, AAInfo, Ranges,
8009                    IsExpanding);
8010 }
8011 
8012 SDValue SelectionDAG::getLoadVP(EVT VT, const SDLoc &dl, SDValue Chain,
8013                                 SDValue Ptr, SDValue Mask, SDValue EVL,
8014                                 MachineMemOperand *MMO, bool IsExpanding) {
8015   SDValue Undef = getUNDEF(Ptr.getValueType());
8016   return getLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
8017                    Mask, EVL, VT, MMO, IsExpanding);
8018 }
8019 
8020 SDValue SelectionDAG::getExtLoadVP(ISD::LoadExtType ExtType, const SDLoc &dl,
8021                                    EVT VT, SDValue Chain, SDValue Ptr,
8022                                    SDValue Mask, SDValue EVL,
8023                                    MachinePointerInfo PtrInfo, EVT MemVT,
8024                                    MaybeAlign Alignment,
8025                                    MachineMemOperand::Flags MMOFlags,
8026                                    const AAMDNodes &AAInfo, bool IsExpanding) {
8027   SDValue Undef = getUNDEF(Ptr.getValueType());
8028   return getLoadVP(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, Mask,
8029                    EVL, PtrInfo, MemVT, Alignment, MMOFlags, AAInfo, nullptr,
8030                    IsExpanding);
8031 }
8032 
8033 SDValue SelectionDAG::getExtLoadVP(ISD::LoadExtType ExtType, const SDLoc &dl,
8034                                    EVT VT, SDValue Chain, SDValue Ptr,
8035                                    SDValue Mask, SDValue EVL, EVT MemVT,
8036                                    MachineMemOperand *MMO, bool IsExpanding) {
8037   SDValue Undef = getUNDEF(Ptr.getValueType());
8038   return getLoadVP(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, Mask,
8039                    EVL, MemVT, MMO, IsExpanding);
8040 }
8041 
8042 SDValue SelectionDAG::getIndexedLoadVP(SDValue OrigLoad, const SDLoc &dl,
8043                                        SDValue Base, SDValue Offset,
8044                                        ISD::MemIndexedMode AM) {
8045   auto *LD = cast<VPLoadSDNode>(OrigLoad);
8046   assert(LD->getOffset().isUndef() && "Load is already a indexed load!");
8047   // Don't propagate the invariant or dereferenceable flags.
8048   auto MMOFlags =
8049       LD->getMemOperand()->getFlags() &
8050       ~(MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable);
8051   return getLoadVP(AM, LD->getExtensionType(), OrigLoad.getValueType(), dl,
8052                    LD->getChain(), Base, Offset, LD->getMask(),
8053                    LD->getVectorLength(), LD->getPointerInfo(),
8054                    LD->getMemoryVT(), LD->getAlign(), MMOFlags, LD->getAAInfo(),
8055                    nullptr, LD->isExpandingLoad());
8056 }
8057 
8058 SDValue SelectionDAG::getStoreVP(SDValue Chain, const SDLoc &dl, SDValue Val,
8059                                  SDValue Ptr, SDValue Offset, SDValue Mask,
8060                                  SDValue EVL, EVT MemVT, MachineMemOperand *MMO,
8061                                  ISD::MemIndexedMode AM, bool IsTruncating,
8062                                  bool IsCompressing) {
8063   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
8064   bool Indexed = AM != ISD::UNINDEXED;
8065   assert((Indexed || Offset.isUndef()) && "Unindexed vp_store with an offset!");
8066   SDVTList VTs = Indexed ? getVTList(Ptr.getValueType(), MVT::Other)
8067                          : getVTList(MVT::Other);
8068   SDValue Ops[] = {Chain, Val, Ptr, Offset, Mask, EVL};
8069   FoldingSetNodeID ID;
8070   AddNodeIDNode(ID, ISD::VP_STORE, VTs, Ops);
8071   ID.AddInteger(MemVT.getRawBits());
8072   ID.AddInteger(getSyntheticNodeSubclassData<VPStoreSDNode>(
8073       dl.getIROrder(), VTs, AM, IsTruncating, IsCompressing, MemVT, MMO));
8074   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8075   ID.AddInteger(MMO->getFlags());
8076   void *IP = nullptr;
8077   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
8078     cast<VPStoreSDNode>(E)->refineAlignment(MMO);
8079     return SDValue(E, 0);
8080   }
8081   auto *N = newSDNode<VPStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
8082                                      IsTruncating, IsCompressing, MemVT, MMO);
8083   createOperands(N, Ops);
8084 
8085   CSEMap.InsertNode(N, IP);
8086   InsertNode(N);
8087   SDValue V(N, 0);
8088   NewSDValueDbgMsg(V, "Creating new node: ", this);
8089   return V;
8090 }
8091 
8092 SDValue SelectionDAG::getTruncStoreVP(SDValue Chain, const SDLoc &dl,
8093                                       SDValue Val, SDValue Ptr, SDValue Mask,
8094                                       SDValue EVL, MachinePointerInfo PtrInfo,
8095                                       EVT SVT, Align Alignment,
8096                                       MachineMemOperand::Flags MMOFlags,
8097                                       const AAMDNodes &AAInfo,
8098                                       bool IsCompressing) {
8099   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
8100 
8101   MMOFlags |= MachineMemOperand::MOStore;
8102   assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
8103 
8104   if (PtrInfo.V.isNull())
8105     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
8106 
8107   MachineFunction &MF = getMachineFunction();
8108   MachineMemOperand *MMO = MF.getMachineMemOperand(
8109       PtrInfo, MMOFlags, MemoryLocation::getSizeOrUnknown(SVT.getStoreSize()),
8110       Alignment, AAInfo);
8111   return getTruncStoreVP(Chain, dl, Val, Ptr, Mask, EVL, SVT, MMO,
8112                          IsCompressing);
8113 }
8114 
8115 SDValue SelectionDAG::getTruncStoreVP(SDValue Chain, const SDLoc &dl,
8116                                       SDValue Val, SDValue Ptr, SDValue Mask,
8117                                       SDValue EVL, EVT SVT,
8118                                       MachineMemOperand *MMO,
8119                                       bool IsCompressing) {
8120   EVT VT = Val.getValueType();
8121 
8122   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
8123   if (VT == SVT)
8124     return getStoreVP(Chain, dl, Val, Ptr, getUNDEF(Ptr.getValueType()), Mask,
8125                       EVL, VT, MMO, ISD::UNINDEXED,
8126                       /*IsTruncating*/ false, IsCompressing);
8127 
8128   assert(SVT.getScalarType().bitsLT(VT.getScalarType()) &&
8129          "Should only be a truncating store, not extending!");
8130   assert(VT.isInteger() == SVT.isInteger() && "Can't do FP-INT conversion!");
8131   assert(VT.isVector() == SVT.isVector() &&
8132          "Cannot use trunc store to convert to or from a vector!");
8133   assert((!VT.isVector() ||
8134           VT.getVectorElementCount() == SVT.getVectorElementCount()) &&
8135          "Cannot use trunc store to change the number of vector elements!");
8136 
8137   SDVTList VTs = getVTList(MVT::Other);
8138   SDValue Undef = getUNDEF(Ptr.getValueType());
8139   SDValue Ops[] = {Chain, Val, Ptr, Undef, Mask, EVL};
8140   FoldingSetNodeID ID;
8141   AddNodeIDNode(ID, ISD::VP_STORE, VTs, Ops);
8142   ID.AddInteger(SVT.getRawBits());
8143   ID.AddInteger(getSyntheticNodeSubclassData<VPStoreSDNode>(
8144       dl.getIROrder(), VTs, ISD::UNINDEXED, true, IsCompressing, SVT, MMO));
8145   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8146   ID.AddInteger(MMO->getFlags());
8147   void *IP = nullptr;
8148   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
8149     cast<VPStoreSDNode>(E)->refineAlignment(MMO);
8150     return SDValue(E, 0);
8151   }
8152   auto *N =
8153       newSDNode<VPStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
8154                                ISD::UNINDEXED, true, IsCompressing, SVT, MMO);
8155   createOperands(N, Ops);
8156 
8157   CSEMap.InsertNode(N, IP);
8158   InsertNode(N);
8159   SDValue V(N, 0);
8160   NewSDValueDbgMsg(V, "Creating new node: ", this);
8161   return V;
8162 }
8163 
8164 SDValue SelectionDAG::getIndexedStoreVP(SDValue OrigStore, const SDLoc &dl,
8165                                         SDValue Base, SDValue Offset,
8166                                         ISD::MemIndexedMode AM) {
8167   auto *ST = cast<VPStoreSDNode>(OrigStore);
8168   assert(ST->getOffset().isUndef() && "Store is already an indexed store!");
8169   SDVTList VTs = getVTList(Base.getValueType(), MVT::Other);
8170   SDValue Ops[] = {ST->getChain(), ST->getValue(), Base,
8171                    Offset,         ST->getMask(),  ST->getVectorLength()};
8172   FoldingSetNodeID ID;
8173   AddNodeIDNode(ID, ISD::VP_STORE, VTs, Ops);
8174   ID.AddInteger(ST->getMemoryVT().getRawBits());
8175   ID.AddInteger(ST->getRawSubclassData());
8176   ID.AddInteger(ST->getPointerInfo().getAddrSpace());
8177   ID.AddInteger(ST->getMemOperand()->getFlags());
8178   void *IP = nullptr;
8179   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
8180     return SDValue(E, 0);
8181 
8182   auto *N = newSDNode<VPStoreSDNode>(
8183       dl.getIROrder(), dl.getDebugLoc(), VTs, AM, ST->isTruncatingStore(),
8184       ST->isCompressingStore(), ST->getMemoryVT(), ST->getMemOperand());
8185   createOperands(N, Ops);
8186 
8187   CSEMap.InsertNode(N, IP);
8188   InsertNode(N);
8189   SDValue V(N, 0);
8190   NewSDValueDbgMsg(V, "Creating new node: ", this);
8191   return V;
8192 }
8193 
8194 SDValue SelectionDAG::getStridedLoadVP(
8195     ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, EVT VT, const SDLoc &DL,
8196     SDValue Chain, SDValue Ptr, SDValue Offset, SDValue Stride, SDValue Mask,
8197     SDValue EVL, MachinePointerInfo PtrInfo, EVT MemVT, Align Alignment,
8198     MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo,
8199     const MDNode *Ranges, bool IsExpanding) {
8200   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
8201 
8202   MMOFlags |= MachineMemOperand::MOLoad;
8203   assert((MMOFlags & MachineMemOperand::MOStore) == 0);
8204   // If we don't have a PtrInfo, infer the trivial frame index case to simplify
8205   // clients.
8206   if (PtrInfo.V.isNull())
8207     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr, Offset);
8208 
8209   uint64_t Size = MemoryLocation::UnknownSize;
8210   MachineFunction &MF = getMachineFunction();
8211   MachineMemOperand *MMO = MF.getMachineMemOperand(PtrInfo, MMOFlags, Size,
8212                                                    Alignment, AAInfo, Ranges);
8213   return getStridedLoadVP(AM, ExtType, VT, DL, Chain, Ptr, Offset, Stride, Mask,
8214                           EVL, MemVT, MMO, IsExpanding);
8215 }
8216 
8217 SDValue SelectionDAG::getStridedLoadVP(
8218     ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, EVT VT, const SDLoc &DL,
8219     SDValue Chain, SDValue Ptr, SDValue Offset, SDValue Stride, SDValue Mask,
8220     SDValue EVL, EVT MemVT, MachineMemOperand *MMO, bool IsExpanding) {
8221   bool Indexed = AM != ISD::UNINDEXED;
8222   assert((Indexed || Offset.isUndef()) && "Unindexed load with an offset!");
8223 
8224   SDValue Ops[] = {Chain, Ptr, Offset, Stride, Mask, EVL};
8225   SDVTList VTs = Indexed ? getVTList(VT, Ptr.getValueType(), MVT::Other)
8226                          : getVTList(VT, MVT::Other);
8227   FoldingSetNodeID ID;
8228   AddNodeIDNode(ID, ISD::EXPERIMENTAL_VP_STRIDED_LOAD, VTs, Ops);
8229   ID.AddInteger(VT.getRawBits());
8230   ID.AddInteger(getSyntheticNodeSubclassData<VPStridedLoadSDNode>(
8231       DL.getIROrder(), VTs, AM, ExtType, IsExpanding, MemVT, MMO));
8232   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8233 
8234   void *IP = nullptr;
8235   if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
8236     cast<VPStridedLoadSDNode>(E)->refineAlignment(MMO);
8237     return SDValue(E, 0);
8238   }
8239 
8240   auto *N =
8241       newSDNode<VPStridedLoadSDNode>(DL.getIROrder(), DL.getDebugLoc(), VTs, AM,
8242                                      ExtType, IsExpanding, MemVT, MMO);
8243   createOperands(N, Ops);
8244   CSEMap.InsertNode(N, IP);
8245   InsertNode(N);
8246   SDValue V(N, 0);
8247   NewSDValueDbgMsg(V, "Creating new node: ", this);
8248   return V;
8249 }
8250 
8251 SDValue SelectionDAG::getStridedLoadVP(
8252     EVT VT, const SDLoc &DL, SDValue Chain, SDValue Ptr, SDValue Stride,
8253     SDValue Mask, SDValue EVL, MachinePointerInfo PtrInfo, MaybeAlign Alignment,
8254     MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo,
8255     const MDNode *Ranges, bool IsExpanding) {
8256   SDValue Undef = getUNDEF(Ptr.getValueType());
8257   return getStridedLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, DL, Chain, Ptr,
8258                           Undef, Stride, Mask, EVL, PtrInfo, VT, Alignment,
8259                           MMOFlags, AAInfo, Ranges, IsExpanding);
8260 }
8261 
8262 SDValue SelectionDAG::getStridedLoadVP(EVT VT, const SDLoc &DL, SDValue Chain,
8263                                        SDValue Ptr, SDValue Stride,
8264                                        SDValue Mask, SDValue EVL,
8265                                        MachineMemOperand *MMO,
8266                                        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, VT, MMO, IsExpanding);
8270 }
8271 
8272 SDValue SelectionDAG::getExtStridedLoadVP(
8273     ISD::LoadExtType ExtType, const SDLoc &DL, EVT VT, SDValue Chain,
8274     SDValue Ptr, SDValue Stride, SDValue Mask, SDValue EVL,
8275     MachinePointerInfo PtrInfo, EVT MemVT, MaybeAlign Alignment,
8276     MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo,
8277     bool IsExpanding) {
8278   SDValue Undef = getUNDEF(Ptr.getValueType());
8279   return getStridedLoadVP(ISD::UNINDEXED, ExtType, VT, DL, Chain, Ptr, Undef,
8280                           Stride, Mask, EVL, PtrInfo, MemVT, Alignment,
8281                           MMOFlags, AAInfo, nullptr, IsExpanding);
8282 }
8283 
8284 SDValue SelectionDAG::getExtStridedLoadVP(
8285     ISD::LoadExtType ExtType, const SDLoc &DL, EVT VT, SDValue Chain,
8286     SDValue Ptr, SDValue Stride, SDValue Mask, SDValue EVL, EVT MemVT,
8287     MachineMemOperand *MMO, bool IsExpanding) {
8288   SDValue Undef = getUNDEF(Ptr.getValueType());
8289   return getStridedLoadVP(ISD::UNINDEXED, ExtType, VT, DL, Chain, Ptr, Undef,
8290                           Stride, Mask, EVL, MemVT, MMO, IsExpanding);
8291 }
8292 
8293 SDValue SelectionDAG::getIndexedStridedLoadVP(SDValue OrigLoad, const SDLoc &DL,
8294                                               SDValue Base, SDValue Offset,
8295                                               ISD::MemIndexedMode AM) {
8296   auto *SLD = cast<VPStridedLoadSDNode>(OrigLoad);
8297   assert(SLD->getOffset().isUndef() &&
8298          "Strided load is already a indexed load!");
8299   // Don't propagate the invariant or dereferenceable flags.
8300   auto MMOFlags =
8301       SLD->getMemOperand()->getFlags() &
8302       ~(MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable);
8303   return getStridedLoadVP(
8304       AM, SLD->getExtensionType(), OrigLoad.getValueType(), DL, SLD->getChain(),
8305       Base, Offset, SLD->getStride(), SLD->getMask(), SLD->getVectorLength(),
8306       SLD->getPointerInfo(), SLD->getMemoryVT(), SLD->getAlign(), MMOFlags,
8307       SLD->getAAInfo(), nullptr, SLD->isExpandingLoad());
8308 }
8309 
8310 SDValue SelectionDAG::getStridedStoreVP(SDValue Chain, const SDLoc &DL,
8311                                         SDValue Val, SDValue Ptr,
8312                                         SDValue Offset, SDValue Stride,
8313                                         SDValue Mask, SDValue EVL, EVT MemVT,
8314                                         MachineMemOperand *MMO,
8315                                         ISD::MemIndexedMode AM,
8316                                         bool IsTruncating, bool IsCompressing) {
8317   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
8318   bool Indexed = AM != ISD::UNINDEXED;
8319   assert((Indexed || Offset.isUndef()) && "Unindexed vp_store with an offset!");
8320   SDVTList VTs = Indexed ? getVTList(Ptr.getValueType(), MVT::Other)
8321                          : getVTList(MVT::Other);
8322   SDValue Ops[] = {Chain, Val, Ptr, Offset, Stride, Mask, EVL};
8323   FoldingSetNodeID ID;
8324   AddNodeIDNode(ID, ISD::EXPERIMENTAL_VP_STRIDED_STORE, VTs, Ops);
8325   ID.AddInteger(MemVT.getRawBits());
8326   ID.AddInteger(getSyntheticNodeSubclassData<VPStridedStoreSDNode>(
8327       DL.getIROrder(), VTs, AM, IsTruncating, IsCompressing, MemVT, MMO));
8328   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8329   void *IP = nullptr;
8330   if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
8331     cast<VPStridedStoreSDNode>(E)->refineAlignment(MMO);
8332     return SDValue(E, 0);
8333   }
8334   auto *N = newSDNode<VPStridedStoreSDNode>(DL.getIROrder(), DL.getDebugLoc(),
8335                                             VTs, AM, IsTruncating,
8336                                             IsCompressing, MemVT, MMO);
8337   createOperands(N, Ops);
8338 
8339   CSEMap.InsertNode(N, IP);
8340   InsertNode(N);
8341   SDValue V(N, 0);
8342   NewSDValueDbgMsg(V, "Creating new node: ", this);
8343   return V;
8344 }
8345 
8346 SDValue SelectionDAG::getTruncStridedStoreVP(
8347     SDValue Chain, const SDLoc &DL, SDValue Val, SDValue Ptr, SDValue Stride,
8348     SDValue Mask, SDValue EVL, MachinePointerInfo PtrInfo, EVT SVT,
8349     Align Alignment, MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo,
8350     bool IsCompressing) {
8351   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
8352 
8353   MMOFlags |= MachineMemOperand::MOStore;
8354   assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
8355 
8356   if (PtrInfo.V.isNull())
8357     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
8358 
8359   MachineFunction &MF = getMachineFunction();
8360   MachineMemOperand *MMO = MF.getMachineMemOperand(
8361       PtrInfo, MMOFlags, MemoryLocation::UnknownSize, Alignment, AAInfo);
8362   return getTruncStridedStoreVP(Chain, DL, Val, Ptr, Stride, Mask, EVL, SVT,
8363                                 MMO, IsCompressing);
8364 }
8365 
8366 SDValue SelectionDAG::getTruncStridedStoreVP(SDValue Chain, const SDLoc &DL,
8367                                              SDValue Val, SDValue Ptr,
8368                                              SDValue Stride, SDValue Mask,
8369                                              SDValue EVL, EVT SVT,
8370                                              MachineMemOperand *MMO,
8371                                              bool IsCompressing) {
8372   EVT VT = Val.getValueType();
8373 
8374   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
8375   if (VT == SVT)
8376     return getStridedStoreVP(Chain, DL, Val, Ptr, getUNDEF(Ptr.getValueType()),
8377                              Stride, Mask, EVL, VT, MMO, ISD::UNINDEXED,
8378                              /*IsTruncating*/ false, IsCompressing);
8379 
8380   assert(SVT.getScalarType().bitsLT(VT.getScalarType()) &&
8381          "Should only be a truncating store, not extending!");
8382   assert(VT.isInteger() == SVT.isInteger() && "Can't do FP-INT conversion!");
8383   assert(VT.isVector() == SVT.isVector() &&
8384          "Cannot use trunc store to convert to or from a vector!");
8385   assert((!VT.isVector() ||
8386           VT.getVectorElementCount() == SVT.getVectorElementCount()) &&
8387          "Cannot use trunc store to change the number of vector elements!");
8388 
8389   SDVTList VTs = getVTList(MVT::Other);
8390   SDValue Undef = getUNDEF(Ptr.getValueType());
8391   SDValue Ops[] = {Chain, Val, Ptr, Undef, Stride, Mask, EVL};
8392   FoldingSetNodeID ID;
8393   AddNodeIDNode(ID, ISD::EXPERIMENTAL_VP_STRIDED_STORE, VTs, Ops);
8394   ID.AddInteger(SVT.getRawBits());
8395   ID.AddInteger(getSyntheticNodeSubclassData<VPStridedStoreSDNode>(
8396       DL.getIROrder(), VTs, ISD::UNINDEXED, true, IsCompressing, SVT, MMO));
8397   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8398   void *IP = nullptr;
8399   if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
8400     cast<VPStridedStoreSDNode>(E)->refineAlignment(MMO);
8401     return SDValue(E, 0);
8402   }
8403   auto *N = newSDNode<VPStridedStoreSDNode>(DL.getIROrder(), DL.getDebugLoc(),
8404                                             VTs, ISD::UNINDEXED, true,
8405                                             IsCompressing, SVT, MMO);
8406   createOperands(N, Ops);
8407 
8408   CSEMap.InsertNode(N, IP);
8409   InsertNode(N);
8410   SDValue V(N, 0);
8411   NewSDValueDbgMsg(V, "Creating new node: ", this);
8412   return V;
8413 }
8414 
8415 SDValue SelectionDAG::getIndexedStridedStoreVP(SDValue OrigStore,
8416                                                const SDLoc &DL, SDValue Base,
8417                                                SDValue Offset,
8418                                                ISD::MemIndexedMode AM) {
8419   auto *SST = cast<VPStridedStoreSDNode>(OrigStore);
8420   assert(SST->getOffset().isUndef() &&
8421          "Strided store is already an indexed store!");
8422   SDVTList VTs = getVTList(Base.getValueType(), MVT::Other);
8423   SDValue Ops[] = {
8424       SST->getChain(), SST->getValue(),       Base, Offset, SST->getStride(),
8425       SST->getMask(),  SST->getVectorLength()};
8426   FoldingSetNodeID ID;
8427   AddNodeIDNode(ID, ISD::EXPERIMENTAL_VP_STRIDED_STORE, VTs, Ops);
8428   ID.AddInteger(SST->getMemoryVT().getRawBits());
8429   ID.AddInteger(SST->getRawSubclassData());
8430   ID.AddInteger(SST->getPointerInfo().getAddrSpace());
8431   void *IP = nullptr;
8432   if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
8433     return SDValue(E, 0);
8434 
8435   auto *N = newSDNode<VPStridedStoreSDNode>(
8436       DL.getIROrder(), DL.getDebugLoc(), VTs, AM, SST->isTruncatingStore(),
8437       SST->isCompressingStore(), SST->getMemoryVT(), SST->getMemOperand());
8438   createOperands(N, Ops);
8439 
8440   CSEMap.InsertNode(N, IP);
8441   InsertNode(N);
8442   SDValue V(N, 0);
8443   NewSDValueDbgMsg(V, "Creating new node: ", this);
8444   return V;
8445 }
8446 
8447 SDValue SelectionDAG::getGatherVP(SDVTList VTs, EVT VT, const SDLoc &dl,
8448                                   ArrayRef<SDValue> Ops, MachineMemOperand *MMO,
8449                                   ISD::MemIndexType IndexType) {
8450   assert(Ops.size() == 6 && "Incompatible number of operands");
8451 
8452   FoldingSetNodeID ID;
8453   AddNodeIDNode(ID, ISD::VP_GATHER, VTs, Ops);
8454   ID.AddInteger(VT.getRawBits());
8455   ID.AddInteger(getSyntheticNodeSubclassData<VPGatherSDNode>(
8456       dl.getIROrder(), VTs, VT, MMO, IndexType));
8457   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8458   ID.AddInteger(MMO->getFlags());
8459   void *IP = nullptr;
8460   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
8461     cast<VPGatherSDNode>(E)->refineAlignment(MMO);
8462     return SDValue(E, 0);
8463   }
8464 
8465   auto *N = newSDNode<VPGatherSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
8466                                       VT, MMO, IndexType);
8467   createOperands(N, Ops);
8468 
8469   assert(N->getMask().getValueType().getVectorElementCount() ==
8470              N->getValueType(0).getVectorElementCount() &&
8471          "Vector width mismatch between mask and data");
8472   assert(N->getIndex().getValueType().getVectorElementCount().isScalable() ==
8473              N->getValueType(0).getVectorElementCount().isScalable() &&
8474          "Scalable flags of index and data do not match");
8475   assert(ElementCount::isKnownGE(
8476              N->getIndex().getValueType().getVectorElementCount(),
8477              N->getValueType(0).getVectorElementCount()) &&
8478          "Vector width mismatch between index and data");
8479   assert(isa<ConstantSDNode>(N->getScale()) &&
8480          cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() &&
8481          "Scale should be a constant power of 2");
8482 
8483   CSEMap.InsertNode(N, IP);
8484   InsertNode(N);
8485   SDValue V(N, 0);
8486   NewSDValueDbgMsg(V, "Creating new node: ", this);
8487   return V;
8488 }
8489 
8490 SDValue SelectionDAG::getScatterVP(SDVTList VTs, EVT VT, const SDLoc &dl,
8491                                    ArrayRef<SDValue> Ops,
8492                                    MachineMemOperand *MMO,
8493                                    ISD::MemIndexType IndexType) {
8494   assert(Ops.size() == 7 && "Incompatible number of operands");
8495 
8496   FoldingSetNodeID ID;
8497   AddNodeIDNode(ID, ISD::VP_SCATTER, VTs, Ops);
8498   ID.AddInteger(VT.getRawBits());
8499   ID.AddInteger(getSyntheticNodeSubclassData<VPScatterSDNode>(
8500       dl.getIROrder(), VTs, VT, MMO, IndexType));
8501   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8502   ID.AddInteger(MMO->getFlags());
8503   void *IP = nullptr;
8504   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
8505     cast<VPScatterSDNode>(E)->refineAlignment(MMO);
8506     return SDValue(E, 0);
8507   }
8508   auto *N = newSDNode<VPScatterSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
8509                                        VT, MMO, IndexType);
8510   createOperands(N, Ops);
8511 
8512   assert(N->getMask().getValueType().getVectorElementCount() ==
8513              N->getValue().getValueType().getVectorElementCount() &&
8514          "Vector width mismatch between mask and data");
8515   assert(
8516       N->getIndex().getValueType().getVectorElementCount().isScalable() ==
8517           N->getValue().getValueType().getVectorElementCount().isScalable() &&
8518       "Scalable flags of index and data do not match");
8519   assert(ElementCount::isKnownGE(
8520              N->getIndex().getValueType().getVectorElementCount(),
8521              N->getValue().getValueType().getVectorElementCount()) &&
8522          "Vector width mismatch between index and data");
8523   assert(isa<ConstantSDNode>(N->getScale()) &&
8524          cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() &&
8525          "Scale should be a constant power of 2");
8526 
8527   CSEMap.InsertNode(N, IP);
8528   InsertNode(N);
8529   SDValue V(N, 0);
8530   NewSDValueDbgMsg(V, "Creating new node: ", this);
8531   return V;
8532 }
8533 
8534 SDValue SelectionDAG::getMaskedLoad(EVT VT, const SDLoc &dl, SDValue Chain,
8535                                     SDValue Base, SDValue Offset, SDValue Mask,
8536                                     SDValue PassThru, EVT MemVT,
8537                                     MachineMemOperand *MMO,
8538                                     ISD::MemIndexedMode AM,
8539                                     ISD::LoadExtType ExtTy, bool isExpanding) {
8540   bool Indexed = AM != ISD::UNINDEXED;
8541   assert((Indexed || Offset.isUndef()) &&
8542          "Unindexed masked load with an offset!");
8543   SDVTList VTs = Indexed ? getVTList(VT, Base.getValueType(), MVT::Other)
8544                          : getVTList(VT, MVT::Other);
8545   SDValue Ops[] = {Chain, Base, Offset, Mask, PassThru};
8546   FoldingSetNodeID ID;
8547   AddNodeIDNode(ID, ISD::MLOAD, VTs, Ops);
8548   ID.AddInteger(MemVT.getRawBits());
8549   ID.AddInteger(getSyntheticNodeSubclassData<MaskedLoadSDNode>(
8550       dl.getIROrder(), VTs, AM, ExtTy, isExpanding, MemVT, MMO));
8551   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8552   ID.AddInteger(MMO->getFlags());
8553   void *IP = nullptr;
8554   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
8555     cast<MaskedLoadSDNode>(E)->refineAlignment(MMO);
8556     return SDValue(E, 0);
8557   }
8558   auto *N = newSDNode<MaskedLoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
8559                                         AM, ExtTy, isExpanding, MemVT, MMO);
8560   createOperands(N, Ops);
8561 
8562   CSEMap.InsertNode(N, IP);
8563   InsertNode(N);
8564   SDValue V(N, 0);
8565   NewSDValueDbgMsg(V, "Creating new node: ", this);
8566   return V;
8567 }
8568 
8569 SDValue SelectionDAG::getIndexedMaskedLoad(SDValue OrigLoad, const SDLoc &dl,
8570                                            SDValue Base, SDValue Offset,
8571                                            ISD::MemIndexedMode AM) {
8572   MaskedLoadSDNode *LD = cast<MaskedLoadSDNode>(OrigLoad);
8573   assert(LD->getOffset().isUndef() && "Masked load is already a indexed load!");
8574   return getMaskedLoad(OrigLoad.getValueType(), dl, LD->getChain(), Base,
8575                        Offset, LD->getMask(), LD->getPassThru(),
8576                        LD->getMemoryVT(), LD->getMemOperand(), AM,
8577                        LD->getExtensionType(), LD->isExpandingLoad());
8578 }
8579 
8580 SDValue SelectionDAG::getMaskedStore(SDValue Chain, const SDLoc &dl,
8581                                      SDValue Val, SDValue Base, SDValue Offset,
8582                                      SDValue Mask, EVT MemVT,
8583                                      MachineMemOperand *MMO,
8584                                      ISD::MemIndexedMode AM, bool IsTruncating,
8585                                      bool IsCompressing) {
8586   assert(Chain.getValueType() == MVT::Other &&
8587         "Invalid chain type");
8588   bool Indexed = AM != ISD::UNINDEXED;
8589   assert((Indexed || Offset.isUndef()) &&
8590          "Unindexed masked store with an offset!");
8591   SDVTList VTs = Indexed ? getVTList(Base.getValueType(), MVT::Other)
8592                          : getVTList(MVT::Other);
8593   SDValue Ops[] = {Chain, Val, Base, Offset, Mask};
8594   FoldingSetNodeID ID;
8595   AddNodeIDNode(ID, ISD::MSTORE, VTs, Ops);
8596   ID.AddInteger(MemVT.getRawBits());
8597   ID.AddInteger(getSyntheticNodeSubclassData<MaskedStoreSDNode>(
8598       dl.getIROrder(), VTs, AM, IsTruncating, IsCompressing, MemVT, MMO));
8599   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8600   ID.AddInteger(MMO->getFlags());
8601   void *IP = nullptr;
8602   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
8603     cast<MaskedStoreSDNode>(E)->refineAlignment(MMO);
8604     return SDValue(E, 0);
8605   }
8606   auto *N =
8607       newSDNode<MaskedStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
8608                                    IsTruncating, IsCompressing, MemVT, MMO);
8609   createOperands(N, Ops);
8610 
8611   CSEMap.InsertNode(N, IP);
8612   InsertNode(N);
8613   SDValue V(N, 0);
8614   NewSDValueDbgMsg(V, "Creating new node: ", this);
8615   return V;
8616 }
8617 
8618 SDValue SelectionDAG::getIndexedMaskedStore(SDValue OrigStore, const SDLoc &dl,
8619                                             SDValue Base, SDValue Offset,
8620                                             ISD::MemIndexedMode AM) {
8621   MaskedStoreSDNode *ST = cast<MaskedStoreSDNode>(OrigStore);
8622   assert(ST->getOffset().isUndef() &&
8623          "Masked store is already a indexed store!");
8624   return getMaskedStore(ST->getChain(), dl, ST->getValue(), Base, Offset,
8625                         ST->getMask(), ST->getMemoryVT(), ST->getMemOperand(),
8626                         AM, ST->isTruncatingStore(), ST->isCompressingStore());
8627 }
8628 
8629 SDValue SelectionDAG::getMaskedGather(SDVTList VTs, EVT MemVT, const SDLoc &dl,
8630                                       ArrayRef<SDValue> Ops,
8631                                       MachineMemOperand *MMO,
8632                                       ISD::MemIndexType IndexType,
8633                                       ISD::LoadExtType ExtTy) {
8634   assert(Ops.size() == 6 && "Incompatible number of operands");
8635 
8636   FoldingSetNodeID ID;
8637   AddNodeIDNode(ID, ISD::MGATHER, VTs, Ops);
8638   ID.AddInteger(MemVT.getRawBits());
8639   ID.AddInteger(getSyntheticNodeSubclassData<MaskedGatherSDNode>(
8640       dl.getIROrder(), VTs, MemVT, MMO, IndexType, ExtTy));
8641   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8642   ID.AddInteger(MMO->getFlags());
8643   void *IP = nullptr;
8644   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
8645     cast<MaskedGatherSDNode>(E)->refineAlignment(MMO);
8646     return SDValue(E, 0);
8647   }
8648 
8649   auto *N = newSDNode<MaskedGatherSDNode>(dl.getIROrder(), dl.getDebugLoc(),
8650                                           VTs, MemVT, MMO, IndexType, ExtTy);
8651   createOperands(N, Ops);
8652 
8653   assert(N->getPassThru().getValueType() == N->getValueType(0) &&
8654          "Incompatible type of the PassThru value in MaskedGatherSDNode");
8655   assert(N->getMask().getValueType().getVectorElementCount() ==
8656              N->getValueType(0).getVectorElementCount() &&
8657          "Vector width mismatch between mask and data");
8658   assert(N->getIndex().getValueType().getVectorElementCount().isScalable() ==
8659              N->getValueType(0).getVectorElementCount().isScalable() &&
8660          "Scalable flags of index and data do not match");
8661   assert(ElementCount::isKnownGE(
8662              N->getIndex().getValueType().getVectorElementCount(),
8663              N->getValueType(0).getVectorElementCount()) &&
8664          "Vector width mismatch between index and data");
8665   assert(isa<ConstantSDNode>(N->getScale()) &&
8666          cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() &&
8667          "Scale should be a constant power of 2");
8668 
8669   CSEMap.InsertNode(N, IP);
8670   InsertNode(N);
8671   SDValue V(N, 0);
8672   NewSDValueDbgMsg(V, "Creating new node: ", this);
8673   return V;
8674 }
8675 
8676 SDValue SelectionDAG::getMaskedScatter(SDVTList VTs, EVT MemVT, const SDLoc &dl,
8677                                        ArrayRef<SDValue> Ops,
8678                                        MachineMemOperand *MMO,
8679                                        ISD::MemIndexType IndexType,
8680                                        bool IsTrunc) {
8681   assert(Ops.size() == 6 && "Incompatible number of operands");
8682 
8683   FoldingSetNodeID ID;
8684   AddNodeIDNode(ID, ISD::MSCATTER, VTs, Ops);
8685   ID.AddInteger(MemVT.getRawBits());
8686   ID.AddInteger(getSyntheticNodeSubclassData<MaskedScatterSDNode>(
8687       dl.getIROrder(), VTs, MemVT, MMO, IndexType, IsTrunc));
8688   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8689   ID.AddInteger(MMO->getFlags());
8690   void *IP = nullptr;
8691   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
8692     cast<MaskedScatterSDNode>(E)->refineAlignment(MMO);
8693     return SDValue(E, 0);
8694   }
8695 
8696   auto *N = newSDNode<MaskedScatterSDNode>(dl.getIROrder(), dl.getDebugLoc(),
8697                                            VTs, MemVT, MMO, IndexType, IsTrunc);
8698   createOperands(N, Ops);
8699 
8700   assert(N->getMask().getValueType().getVectorElementCount() ==
8701              N->getValue().getValueType().getVectorElementCount() &&
8702          "Vector width mismatch between mask and data");
8703   assert(
8704       N->getIndex().getValueType().getVectorElementCount().isScalable() ==
8705           N->getValue().getValueType().getVectorElementCount().isScalable() &&
8706       "Scalable flags of index and data do not match");
8707   assert(ElementCount::isKnownGE(
8708              N->getIndex().getValueType().getVectorElementCount(),
8709              N->getValue().getValueType().getVectorElementCount()) &&
8710          "Vector width mismatch between index and data");
8711   assert(isa<ConstantSDNode>(N->getScale()) &&
8712          cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() &&
8713          "Scale should be a constant power of 2");
8714 
8715   CSEMap.InsertNode(N, IP);
8716   InsertNode(N);
8717   SDValue V(N, 0);
8718   NewSDValueDbgMsg(V, "Creating new node: ", this);
8719   return V;
8720 }
8721 
8722 SDValue SelectionDAG::simplifySelect(SDValue Cond, SDValue T, SDValue F) {
8723   // select undef, T, F --> T (if T is a constant), otherwise F
8724   // select, ?, undef, F --> F
8725   // select, ?, T, undef --> T
8726   if (Cond.isUndef())
8727     return isConstantValueOfAnyType(T) ? T : F;
8728   if (T.isUndef())
8729     return F;
8730   if (F.isUndef())
8731     return T;
8732 
8733   // select true, T, F --> T
8734   // select false, T, F --> F
8735   if (auto *CondC = dyn_cast<ConstantSDNode>(Cond))
8736     return CondC->isZero() ? F : T;
8737 
8738   // TODO: This should simplify VSELECT with constant condition using something
8739   // like this (but check boolean contents to be complete?):
8740   //  if (ISD::isBuildVectorAllOnes(Cond.getNode()))
8741   //    return T;
8742   //  if (ISD::isBuildVectorAllZeros(Cond.getNode()))
8743   //    return F;
8744 
8745   // select ?, T, T --> T
8746   if (T == F)
8747     return T;
8748 
8749   return SDValue();
8750 }
8751 
8752 SDValue SelectionDAG::simplifyShift(SDValue X, SDValue Y) {
8753   // shift undef, Y --> 0 (can always assume that the undef value is 0)
8754   if (X.isUndef())
8755     return getConstant(0, SDLoc(X.getNode()), X.getValueType());
8756   // shift X, undef --> undef (because it may shift by the bitwidth)
8757   if (Y.isUndef())
8758     return getUNDEF(X.getValueType());
8759 
8760   // shift 0, Y --> 0
8761   // shift X, 0 --> X
8762   if (isNullOrNullSplat(X) || isNullOrNullSplat(Y))
8763     return X;
8764 
8765   // shift X, C >= bitwidth(X) --> undef
8766   // All vector elements must be too big (or undef) to avoid partial undefs.
8767   auto isShiftTooBig = [X](ConstantSDNode *Val) {
8768     return !Val || Val->getAPIntValue().uge(X.getScalarValueSizeInBits());
8769   };
8770   if (ISD::matchUnaryPredicate(Y, isShiftTooBig, true))
8771     return getUNDEF(X.getValueType());
8772 
8773   return SDValue();
8774 }
8775 
8776 SDValue SelectionDAG::simplifyFPBinop(unsigned Opcode, SDValue X, SDValue Y,
8777                                       SDNodeFlags Flags) {
8778   // If this operation has 'nnan' or 'ninf' and at least 1 disallowed operand
8779   // (an undef operand can be chosen to be Nan/Inf), then the result of this
8780   // operation is poison. That result can be relaxed to undef.
8781   ConstantFPSDNode *XC = isConstOrConstSplatFP(X, /* AllowUndefs */ true);
8782   ConstantFPSDNode *YC = isConstOrConstSplatFP(Y, /* AllowUndefs */ true);
8783   bool HasNan = (XC && XC->getValueAPF().isNaN()) ||
8784                 (YC && YC->getValueAPF().isNaN());
8785   bool HasInf = (XC && XC->getValueAPF().isInfinity()) ||
8786                 (YC && YC->getValueAPF().isInfinity());
8787 
8788   if (Flags.hasNoNaNs() && (HasNan || X.isUndef() || Y.isUndef()))
8789     return getUNDEF(X.getValueType());
8790 
8791   if (Flags.hasNoInfs() && (HasInf || X.isUndef() || Y.isUndef()))
8792     return getUNDEF(X.getValueType());
8793 
8794   if (!YC)
8795     return SDValue();
8796 
8797   // X + -0.0 --> X
8798   if (Opcode == ISD::FADD)
8799     if (YC->getValueAPF().isNegZero())
8800       return X;
8801 
8802   // X - +0.0 --> X
8803   if (Opcode == ISD::FSUB)
8804     if (YC->getValueAPF().isPosZero())
8805       return X;
8806 
8807   // X * 1.0 --> X
8808   // X / 1.0 --> X
8809   if (Opcode == ISD::FMUL || Opcode == ISD::FDIV)
8810     if (YC->getValueAPF().isExactlyValue(1.0))
8811       return X;
8812 
8813   // X * 0.0 --> 0.0
8814   if (Opcode == ISD::FMUL && Flags.hasNoNaNs() && Flags.hasNoSignedZeros())
8815     if (YC->getValueAPF().isZero())
8816       return getConstantFP(0.0, SDLoc(Y), Y.getValueType());
8817 
8818   return SDValue();
8819 }
8820 
8821 SDValue SelectionDAG::getVAArg(EVT VT, const SDLoc &dl, SDValue Chain,
8822                                SDValue Ptr, SDValue SV, unsigned Align) {
8823   SDValue Ops[] = { Chain, Ptr, SV, getTargetConstant(Align, dl, MVT::i32) };
8824   return getNode(ISD::VAARG, dl, getVTList(VT, MVT::Other), Ops);
8825 }
8826 
8827 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
8828                               ArrayRef<SDUse> Ops) {
8829   switch (Ops.size()) {
8830   case 0: return getNode(Opcode, DL, VT);
8831   case 1: return getNode(Opcode, DL, VT, static_cast<const SDValue>(Ops[0]));
8832   case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1]);
8833   case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2]);
8834   default: break;
8835   }
8836 
8837   // Copy from an SDUse array into an SDValue array for use with
8838   // the regular getNode logic.
8839   SmallVector<SDValue, 8> NewOps(Ops.begin(), Ops.end());
8840   return getNode(Opcode, DL, VT, NewOps);
8841 }
8842 
8843 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
8844                               ArrayRef<SDValue> Ops) {
8845   SDNodeFlags Flags;
8846   if (Inserter)
8847     Flags = Inserter->getFlags();
8848   return getNode(Opcode, DL, VT, Ops, Flags);
8849 }
8850 
8851 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
8852                               ArrayRef<SDValue> Ops, const SDNodeFlags Flags) {
8853   unsigned NumOps = Ops.size();
8854   switch (NumOps) {
8855   case 0: return getNode(Opcode, DL, VT);
8856   case 1: return getNode(Opcode, DL, VT, Ops[0], Flags);
8857   case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Flags);
8858   case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2], Flags);
8859   default: break;
8860   }
8861 
8862 #ifndef NDEBUG
8863   for (auto &Op : Ops)
8864     assert(Op.getOpcode() != ISD::DELETED_NODE &&
8865            "Operand is DELETED_NODE!");
8866 #endif
8867 
8868   switch (Opcode) {
8869   default: break;
8870   case ISD::BUILD_VECTOR:
8871     // Attempt to simplify BUILD_VECTOR.
8872     if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
8873       return V;
8874     break;
8875   case ISD::CONCAT_VECTORS:
8876     if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this))
8877       return V;
8878     break;
8879   case ISD::SELECT_CC:
8880     assert(NumOps == 5 && "SELECT_CC takes 5 operands!");
8881     assert(Ops[0].getValueType() == Ops[1].getValueType() &&
8882            "LHS and RHS of condition must have same type!");
8883     assert(Ops[2].getValueType() == Ops[3].getValueType() &&
8884            "True and False arms of SelectCC must have same type!");
8885     assert(Ops[2].getValueType() == VT &&
8886            "select_cc node must be of same type as true and false value!");
8887     break;
8888   case ISD::BR_CC:
8889     assert(NumOps == 5 && "BR_CC takes 5 operands!");
8890     assert(Ops[2].getValueType() == Ops[3].getValueType() &&
8891            "LHS/RHS of comparison should match types!");
8892     break;
8893   case ISD::VP_ADD:
8894   case ISD::VP_SUB:
8895     // If it is VP_ADD/VP_SUB mask operation then turn it to VP_XOR
8896     if (VT.isVector() && VT.getVectorElementType() == MVT::i1)
8897       Opcode = ISD::VP_XOR;
8898     break;
8899   case ISD::VP_MUL:
8900     // If it is VP_MUL mask operation then turn it to VP_AND
8901     if (VT.isVector() && VT.getVectorElementType() == MVT::i1)
8902       Opcode = ISD::VP_AND;
8903     break;
8904   case ISD::VP_REDUCE_MUL:
8905     // If it is VP_REDUCE_MUL mask operation then turn it to VP_REDUCE_AND
8906     if (VT == MVT::i1)
8907       Opcode = ISD::VP_REDUCE_AND;
8908     break;
8909   case ISD::VP_REDUCE_ADD:
8910     // If it is VP_REDUCE_ADD mask operation then turn it to VP_REDUCE_XOR
8911     if (VT == MVT::i1)
8912       Opcode = ISD::VP_REDUCE_XOR;
8913     break;
8914   case ISD::VP_REDUCE_SMAX:
8915   case ISD::VP_REDUCE_UMIN:
8916     // If it is VP_REDUCE_SMAX/VP_REDUCE_UMIN mask operation then turn it to
8917     // VP_REDUCE_AND.
8918     if (VT == MVT::i1)
8919       Opcode = ISD::VP_REDUCE_AND;
8920     break;
8921   case ISD::VP_REDUCE_SMIN:
8922   case ISD::VP_REDUCE_UMAX:
8923     // If it is VP_REDUCE_SMIN/VP_REDUCE_UMAX mask operation then turn it to
8924     // VP_REDUCE_OR.
8925     if (VT == MVT::i1)
8926       Opcode = ISD::VP_REDUCE_OR;
8927     break;
8928   }
8929 
8930   // Memoize nodes.
8931   SDNode *N;
8932   SDVTList VTs = getVTList(VT);
8933 
8934   if (VT != MVT::Glue) {
8935     FoldingSetNodeID ID;
8936     AddNodeIDNode(ID, Opcode, VTs, Ops);
8937     void *IP = nullptr;
8938 
8939     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
8940       return SDValue(E, 0);
8941 
8942     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
8943     createOperands(N, Ops);
8944 
8945     CSEMap.InsertNode(N, IP);
8946   } else {
8947     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
8948     createOperands(N, Ops);
8949   }
8950 
8951   N->setFlags(Flags);
8952   InsertNode(N);
8953   SDValue V(N, 0);
8954   NewSDValueDbgMsg(V, "Creating new node: ", this);
8955   return V;
8956 }
8957 
8958 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL,
8959                               ArrayRef<EVT> ResultTys, ArrayRef<SDValue> Ops) {
8960   return getNode(Opcode, DL, getVTList(ResultTys), Ops);
8961 }
8962 
8963 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
8964                               ArrayRef<SDValue> Ops) {
8965   SDNodeFlags Flags;
8966   if (Inserter)
8967     Flags = Inserter->getFlags();
8968   return getNode(Opcode, DL, VTList, Ops, Flags);
8969 }
8970 
8971 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
8972                               ArrayRef<SDValue> Ops, const SDNodeFlags Flags) {
8973   if (VTList.NumVTs == 1)
8974     return getNode(Opcode, DL, VTList.VTs[0], Ops, Flags);
8975 
8976 #ifndef NDEBUG
8977   for (auto &Op : Ops)
8978     assert(Op.getOpcode() != ISD::DELETED_NODE &&
8979            "Operand is DELETED_NODE!");
8980 #endif
8981 
8982   switch (Opcode) {
8983   case ISD::STRICT_FP_EXTEND:
8984     assert(VTList.NumVTs == 2 && Ops.size() == 2 &&
8985            "Invalid STRICT_FP_EXTEND!");
8986     assert(VTList.VTs[0].isFloatingPoint() &&
8987            Ops[1].getValueType().isFloatingPoint() && "Invalid FP cast!");
8988     assert(VTList.VTs[0].isVector() == Ops[1].getValueType().isVector() &&
8989            "STRICT_FP_EXTEND result type should be vector iff the operand "
8990            "type is vector!");
8991     assert((!VTList.VTs[0].isVector() ||
8992             VTList.VTs[0].getVectorNumElements() ==
8993             Ops[1].getValueType().getVectorNumElements()) &&
8994            "Vector element count mismatch!");
8995     assert(Ops[1].getValueType().bitsLT(VTList.VTs[0]) &&
8996            "Invalid fpext node, dst <= src!");
8997     break;
8998   case ISD::STRICT_FP_ROUND:
8999     assert(VTList.NumVTs == 2 && Ops.size() == 3 && "Invalid STRICT_FP_ROUND!");
9000     assert(VTList.VTs[0].isVector() == Ops[1].getValueType().isVector() &&
9001            "STRICT_FP_ROUND result type should be vector iff the operand "
9002            "type is vector!");
9003     assert((!VTList.VTs[0].isVector() ||
9004             VTList.VTs[0].getVectorNumElements() ==
9005             Ops[1].getValueType().getVectorNumElements()) &&
9006            "Vector element count mismatch!");
9007     assert(VTList.VTs[0].isFloatingPoint() &&
9008            Ops[1].getValueType().isFloatingPoint() &&
9009            VTList.VTs[0].bitsLT(Ops[1].getValueType()) &&
9010            isa<ConstantSDNode>(Ops[2]) &&
9011            (cast<ConstantSDNode>(Ops[2])->getZExtValue() == 0 ||
9012             cast<ConstantSDNode>(Ops[2])->getZExtValue() == 1) &&
9013            "Invalid STRICT_FP_ROUND!");
9014     break;
9015 #if 0
9016   // FIXME: figure out how to safely handle things like
9017   // int foo(int x) { return 1 << (x & 255); }
9018   // int bar() { return foo(256); }
9019   case ISD::SRA_PARTS:
9020   case ISD::SRL_PARTS:
9021   case ISD::SHL_PARTS:
9022     if (N3.getOpcode() == ISD::SIGN_EXTEND_INREG &&
9023         cast<VTSDNode>(N3.getOperand(1))->getVT() != MVT::i1)
9024       return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0));
9025     else if (N3.getOpcode() == ISD::AND)
9026       if (ConstantSDNode *AndRHS = dyn_cast<ConstantSDNode>(N3.getOperand(1))) {
9027         // If the and is only masking out bits that cannot effect the shift,
9028         // eliminate the and.
9029         unsigned NumBits = VT.getScalarSizeInBits()*2;
9030         if ((AndRHS->getValue() & (NumBits-1)) == NumBits-1)
9031           return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0));
9032       }
9033     break;
9034 #endif
9035   }
9036 
9037   // Memoize the node unless it returns a flag.
9038   SDNode *N;
9039   if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) {
9040     FoldingSetNodeID ID;
9041     AddNodeIDNode(ID, Opcode, VTList, Ops);
9042     void *IP = nullptr;
9043     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
9044       return SDValue(E, 0);
9045 
9046     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList);
9047     createOperands(N, Ops);
9048     CSEMap.InsertNode(N, IP);
9049   } else {
9050     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList);
9051     createOperands(N, Ops);
9052   }
9053 
9054   N->setFlags(Flags);
9055   InsertNode(N);
9056   SDValue V(N, 0);
9057   NewSDValueDbgMsg(V, "Creating new node: ", this);
9058   return V;
9059 }
9060 
9061 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL,
9062                               SDVTList VTList) {
9063   return getNode(Opcode, DL, VTList, None);
9064 }
9065 
9066 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
9067                               SDValue N1) {
9068   SDValue Ops[] = { N1 };
9069   return getNode(Opcode, DL, VTList, Ops);
9070 }
9071 
9072 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
9073                               SDValue N1, SDValue N2) {
9074   SDValue Ops[] = { N1, N2 };
9075   return getNode(Opcode, DL, VTList, Ops);
9076 }
9077 
9078 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
9079                               SDValue N1, SDValue N2, SDValue N3) {
9080   SDValue Ops[] = { N1, N2, N3 };
9081   return getNode(Opcode, DL, VTList, Ops);
9082 }
9083 
9084 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
9085                               SDValue N1, SDValue N2, SDValue N3, SDValue N4) {
9086   SDValue Ops[] = { N1, N2, N3, N4 };
9087   return getNode(Opcode, DL, VTList, Ops);
9088 }
9089 
9090 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
9091                               SDValue N1, SDValue N2, SDValue N3, SDValue N4,
9092                               SDValue N5) {
9093   SDValue Ops[] = { N1, N2, N3, N4, N5 };
9094   return getNode(Opcode, DL, VTList, Ops);
9095 }
9096 
9097 SDVTList SelectionDAG::getVTList(EVT VT) {
9098   return makeVTList(SDNode::getValueTypeList(VT), 1);
9099 }
9100 
9101 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2) {
9102   FoldingSetNodeID ID;
9103   ID.AddInteger(2U);
9104   ID.AddInteger(VT1.getRawBits());
9105   ID.AddInteger(VT2.getRawBits());
9106 
9107   void *IP = nullptr;
9108   SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
9109   if (!Result) {
9110     EVT *Array = Allocator.Allocate<EVT>(2);
9111     Array[0] = VT1;
9112     Array[1] = VT2;
9113     Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 2);
9114     VTListMap.InsertNode(Result, IP);
9115   }
9116   return Result->getSDVTList();
9117 }
9118 
9119 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3) {
9120   FoldingSetNodeID ID;
9121   ID.AddInteger(3U);
9122   ID.AddInteger(VT1.getRawBits());
9123   ID.AddInteger(VT2.getRawBits());
9124   ID.AddInteger(VT3.getRawBits());
9125 
9126   void *IP = nullptr;
9127   SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
9128   if (!Result) {
9129     EVT *Array = Allocator.Allocate<EVT>(3);
9130     Array[0] = VT1;
9131     Array[1] = VT2;
9132     Array[2] = VT3;
9133     Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 3);
9134     VTListMap.InsertNode(Result, IP);
9135   }
9136   return Result->getSDVTList();
9137 }
9138 
9139 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3, EVT VT4) {
9140   FoldingSetNodeID ID;
9141   ID.AddInteger(4U);
9142   ID.AddInteger(VT1.getRawBits());
9143   ID.AddInteger(VT2.getRawBits());
9144   ID.AddInteger(VT3.getRawBits());
9145   ID.AddInteger(VT4.getRawBits());
9146 
9147   void *IP = nullptr;
9148   SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
9149   if (!Result) {
9150     EVT *Array = Allocator.Allocate<EVT>(4);
9151     Array[0] = VT1;
9152     Array[1] = VT2;
9153     Array[2] = VT3;
9154     Array[3] = VT4;
9155     Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 4);
9156     VTListMap.InsertNode(Result, IP);
9157   }
9158   return Result->getSDVTList();
9159 }
9160 
9161 SDVTList SelectionDAG::getVTList(ArrayRef<EVT> VTs) {
9162   unsigned NumVTs = VTs.size();
9163   FoldingSetNodeID ID;
9164   ID.AddInteger(NumVTs);
9165   for (unsigned index = 0; index < NumVTs; index++) {
9166     ID.AddInteger(VTs[index].getRawBits());
9167   }
9168 
9169   void *IP = nullptr;
9170   SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
9171   if (!Result) {
9172     EVT *Array = Allocator.Allocate<EVT>(NumVTs);
9173     llvm::copy(VTs, Array);
9174     Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, NumVTs);
9175     VTListMap.InsertNode(Result, IP);
9176   }
9177   return Result->getSDVTList();
9178 }
9179 
9180 
9181 /// UpdateNodeOperands - *Mutate* the specified node in-place to have the
9182 /// specified operands.  If the resultant node already exists in the DAG,
9183 /// this does not modify the specified node, instead it returns the node that
9184 /// already exists.  If the resultant node does not exist in the DAG, the
9185 /// input node is returned.  As a degenerate case, if you specify the same
9186 /// input operands as the node already has, the input node is returned.
9187 SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op) {
9188   assert(N->getNumOperands() == 1 && "Update with wrong number of operands");
9189 
9190   // Check to see if there is no change.
9191   if (Op == N->getOperand(0)) return N;
9192 
9193   // See if the modified node already exists.
9194   void *InsertPos = nullptr;
9195   if (SDNode *Existing = FindModifiedNodeSlot(N, Op, InsertPos))
9196     return Existing;
9197 
9198   // Nope it doesn't.  Remove the node from its current place in the maps.
9199   if (InsertPos)
9200     if (!RemoveNodeFromCSEMaps(N))
9201       InsertPos = nullptr;
9202 
9203   // Now we update the operands.
9204   N->OperandList[0].set(Op);
9205 
9206   updateDivergence(N);
9207   // If this gets put into a CSE map, add it.
9208   if (InsertPos) CSEMap.InsertNode(N, InsertPos);
9209   return N;
9210 }
9211 
9212 SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2) {
9213   assert(N->getNumOperands() == 2 && "Update with wrong number of operands");
9214 
9215   // Check to see if there is no change.
9216   if (Op1 == N->getOperand(0) && Op2 == N->getOperand(1))
9217     return N;   // No operands changed, just return the input node.
9218 
9219   // See if the modified node already exists.
9220   void *InsertPos = nullptr;
9221   if (SDNode *Existing = FindModifiedNodeSlot(N, Op1, Op2, InsertPos))
9222     return Existing;
9223 
9224   // Nope it doesn't.  Remove the node from its current place in the maps.
9225   if (InsertPos)
9226     if (!RemoveNodeFromCSEMaps(N))
9227       InsertPos = nullptr;
9228 
9229   // Now we update the operands.
9230   if (N->OperandList[0] != Op1)
9231     N->OperandList[0].set(Op1);
9232   if (N->OperandList[1] != Op2)
9233     N->OperandList[1].set(Op2);
9234 
9235   updateDivergence(N);
9236   // If this gets put into a CSE map, add it.
9237   if (InsertPos) CSEMap.InsertNode(N, InsertPos);
9238   return N;
9239 }
9240 
9241 SDNode *SelectionDAG::
9242 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2, SDValue Op3) {
9243   SDValue Ops[] = { Op1, Op2, Op3 };
9244   return UpdateNodeOperands(N, Ops);
9245 }
9246 
9247 SDNode *SelectionDAG::
9248 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2,
9249                    SDValue Op3, SDValue Op4) {
9250   SDValue Ops[] = { Op1, Op2, Op3, Op4 };
9251   return UpdateNodeOperands(N, Ops);
9252 }
9253 
9254 SDNode *SelectionDAG::
9255 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2,
9256                    SDValue Op3, SDValue Op4, SDValue Op5) {
9257   SDValue Ops[] = { Op1, Op2, Op3, Op4, Op5 };
9258   return UpdateNodeOperands(N, Ops);
9259 }
9260 
9261 SDNode *SelectionDAG::
9262 UpdateNodeOperands(SDNode *N, ArrayRef<SDValue> Ops) {
9263   unsigned NumOps = Ops.size();
9264   assert(N->getNumOperands() == NumOps &&
9265          "Update with wrong number of operands");
9266 
9267   // If no operands changed just return the input node.
9268   if (std::equal(Ops.begin(), Ops.end(), N->op_begin()))
9269     return N;
9270 
9271   // See if the modified node already exists.
9272   void *InsertPos = nullptr;
9273   if (SDNode *Existing = FindModifiedNodeSlot(N, Ops, InsertPos))
9274     return Existing;
9275 
9276   // Nope it doesn't.  Remove the node from its current place in the maps.
9277   if (InsertPos)
9278     if (!RemoveNodeFromCSEMaps(N))
9279       InsertPos = nullptr;
9280 
9281   // Now we update the operands.
9282   for (unsigned i = 0; i != NumOps; ++i)
9283     if (N->OperandList[i] != Ops[i])
9284       N->OperandList[i].set(Ops[i]);
9285 
9286   updateDivergence(N);
9287   // If this gets put into a CSE map, add it.
9288   if (InsertPos) CSEMap.InsertNode(N, InsertPos);
9289   return N;
9290 }
9291 
9292 /// DropOperands - Release the operands and set this node to have
9293 /// zero operands.
9294 void SDNode::DropOperands() {
9295   // Unlike the code in MorphNodeTo that does this, we don't need to
9296   // watch for dead nodes here.
9297   for (op_iterator I = op_begin(), E = op_end(); I != E; ) {
9298     SDUse &Use = *I++;
9299     Use.set(SDValue());
9300   }
9301 }
9302 
9303 void SelectionDAG::setNodeMemRefs(MachineSDNode *N,
9304                                   ArrayRef<MachineMemOperand *> NewMemRefs) {
9305   if (NewMemRefs.empty()) {
9306     N->clearMemRefs();
9307     return;
9308   }
9309 
9310   // Check if we can avoid allocating by storing a single reference directly.
9311   if (NewMemRefs.size() == 1) {
9312     N->MemRefs = NewMemRefs[0];
9313     N->NumMemRefs = 1;
9314     return;
9315   }
9316 
9317   MachineMemOperand **MemRefsBuffer =
9318       Allocator.template Allocate<MachineMemOperand *>(NewMemRefs.size());
9319   llvm::copy(NewMemRefs, MemRefsBuffer);
9320   N->MemRefs = MemRefsBuffer;
9321   N->NumMemRefs = static_cast<int>(NewMemRefs.size());
9322 }
9323 
9324 /// SelectNodeTo - These are wrappers around MorphNodeTo that accept a
9325 /// machine opcode.
9326 ///
9327 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
9328                                    EVT VT) {
9329   SDVTList VTs = getVTList(VT);
9330   return SelectNodeTo(N, MachineOpc, VTs, None);
9331 }
9332 
9333 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
9334                                    EVT VT, SDValue Op1) {
9335   SDVTList VTs = getVTList(VT);
9336   SDValue Ops[] = { Op1 };
9337   return SelectNodeTo(N, MachineOpc, VTs, Ops);
9338 }
9339 
9340 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
9341                                    EVT VT, SDValue Op1,
9342                                    SDValue Op2) {
9343   SDVTList VTs = getVTList(VT);
9344   SDValue Ops[] = { Op1, Op2 };
9345   return SelectNodeTo(N, MachineOpc, VTs, Ops);
9346 }
9347 
9348 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
9349                                    EVT VT, SDValue Op1,
9350                                    SDValue Op2, SDValue Op3) {
9351   SDVTList VTs = getVTList(VT);
9352   SDValue Ops[] = { Op1, Op2, Op3 };
9353   return SelectNodeTo(N, MachineOpc, VTs, Ops);
9354 }
9355 
9356 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
9357                                    EVT VT, ArrayRef<SDValue> Ops) {
9358   SDVTList VTs = getVTList(VT);
9359   return SelectNodeTo(N, MachineOpc, VTs, Ops);
9360 }
9361 
9362 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
9363                                    EVT VT1, EVT VT2, ArrayRef<SDValue> Ops) {
9364   SDVTList VTs = getVTList(VT1, VT2);
9365   return SelectNodeTo(N, MachineOpc, VTs, Ops);
9366 }
9367 
9368 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
9369                                    EVT VT1, EVT VT2) {
9370   SDVTList VTs = getVTList(VT1, VT2);
9371   return SelectNodeTo(N, MachineOpc, VTs, None);
9372 }
9373 
9374 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
9375                                    EVT VT1, EVT VT2, EVT VT3,
9376                                    ArrayRef<SDValue> Ops) {
9377   SDVTList VTs = getVTList(VT1, VT2, VT3);
9378   return SelectNodeTo(N, MachineOpc, VTs, Ops);
9379 }
9380 
9381 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
9382                                    EVT VT1, EVT VT2,
9383                                    SDValue Op1, SDValue Op2) {
9384   SDVTList VTs = getVTList(VT1, VT2);
9385   SDValue Ops[] = { Op1, Op2 };
9386   return SelectNodeTo(N, MachineOpc, VTs, Ops);
9387 }
9388 
9389 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
9390                                    SDVTList VTs,ArrayRef<SDValue> Ops) {
9391   SDNode *New = MorphNodeTo(N, ~MachineOpc, VTs, Ops);
9392   // Reset the NodeID to -1.
9393   New->setNodeId(-1);
9394   if (New != N) {
9395     ReplaceAllUsesWith(N, New);
9396     RemoveDeadNode(N);
9397   }
9398   return New;
9399 }
9400 
9401 /// UpdateSDLocOnMergeSDNode - If the opt level is -O0 then it throws away
9402 /// the line number information on the merged node since it is not possible to
9403 /// preserve the information that operation is associated with multiple lines.
9404 /// This will make the debugger working better at -O0, were there is a higher
9405 /// probability having other instructions associated with that line.
9406 ///
9407 /// For IROrder, we keep the smaller of the two
9408 SDNode *SelectionDAG::UpdateSDLocOnMergeSDNode(SDNode *N, const SDLoc &OLoc) {
9409   DebugLoc NLoc = N->getDebugLoc();
9410   if (NLoc && OptLevel == CodeGenOpt::None && OLoc.getDebugLoc() != NLoc) {
9411     N->setDebugLoc(DebugLoc());
9412   }
9413   unsigned Order = std::min(N->getIROrder(), OLoc.getIROrder());
9414   N->setIROrder(Order);
9415   return N;
9416 }
9417 
9418 /// MorphNodeTo - This *mutates* the specified node to have the specified
9419 /// return type, opcode, and operands.
9420 ///
9421 /// Note that MorphNodeTo returns the resultant node.  If there is already a
9422 /// node of the specified opcode and operands, it returns that node instead of
9423 /// the current one.  Note that the SDLoc need not be the same.
9424 ///
9425 /// Using MorphNodeTo is faster than creating a new node and swapping it in
9426 /// with ReplaceAllUsesWith both because it often avoids allocating a new
9427 /// node, and because it doesn't require CSE recalculation for any of
9428 /// the node's users.
9429 ///
9430 /// However, note that MorphNodeTo recursively deletes dead nodes from the DAG.
9431 /// As a consequence it isn't appropriate to use from within the DAG combiner or
9432 /// the legalizer which maintain worklists that would need to be updated when
9433 /// deleting things.
9434 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
9435                                   SDVTList VTs, ArrayRef<SDValue> Ops) {
9436   // If an identical node already exists, use it.
9437   void *IP = nullptr;
9438   if (VTs.VTs[VTs.NumVTs-1] != MVT::Glue) {
9439     FoldingSetNodeID ID;
9440     AddNodeIDNode(ID, Opc, VTs, Ops);
9441     if (SDNode *ON = FindNodeOrInsertPos(ID, SDLoc(N), IP))
9442       return UpdateSDLocOnMergeSDNode(ON, SDLoc(N));
9443   }
9444 
9445   if (!RemoveNodeFromCSEMaps(N))
9446     IP = nullptr;
9447 
9448   // Start the morphing.
9449   N->NodeType = Opc;
9450   N->ValueList = VTs.VTs;
9451   N->NumValues = VTs.NumVTs;
9452 
9453   // Clear the operands list, updating used nodes to remove this from their
9454   // use list.  Keep track of any operands that become dead as a result.
9455   SmallPtrSet<SDNode*, 16> DeadNodeSet;
9456   for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) {
9457     SDUse &Use = *I++;
9458     SDNode *Used = Use.getNode();
9459     Use.set(SDValue());
9460     if (Used->use_empty())
9461       DeadNodeSet.insert(Used);
9462   }
9463 
9464   // For MachineNode, initialize the memory references information.
9465   if (MachineSDNode *MN = dyn_cast<MachineSDNode>(N))
9466     MN->clearMemRefs();
9467 
9468   // Swap for an appropriately sized array from the recycler.
9469   removeOperands(N);
9470   createOperands(N, Ops);
9471 
9472   // Delete any nodes that are still dead after adding the uses for the
9473   // new operands.
9474   if (!DeadNodeSet.empty()) {
9475     SmallVector<SDNode *, 16> DeadNodes;
9476     for (SDNode *N : DeadNodeSet)
9477       if (N->use_empty())
9478         DeadNodes.push_back(N);
9479     RemoveDeadNodes(DeadNodes);
9480   }
9481 
9482   if (IP)
9483     CSEMap.InsertNode(N, IP);   // Memoize the new node.
9484   return N;
9485 }
9486 
9487 SDNode* SelectionDAG::mutateStrictFPToFP(SDNode *Node) {
9488   unsigned OrigOpc = Node->getOpcode();
9489   unsigned NewOpc;
9490   switch (OrigOpc) {
9491   default:
9492     llvm_unreachable("mutateStrictFPToFP called with unexpected opcode!");
9493 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN)               \
9494   case ISD::STRICT_##DAGN: NewOpc = ISD::DAGN; break;
9495 #define CMP_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN)               \
9496   case ISD::STRICT_##DAGN: NewOpc = ISD::SETCC; break;
9497 #include "llvm/IR/ConstrainedOps.def"
9498   }
9499 
9500   assert(Node->getNumValues() == 2 && "Unexpected number of results!");
9501 
9502   // We're taking this node out of the chain, so we need to re-link things.
9503   SDValue InputChain = Node->getOperand(0);
9504   SDValue OutputChain = SDValue(Node, 1);
9505   ReplaceAllUsesOfValueWith(OutputChain, InputChain);
9506 
9507   SmallVector<SDValue, 3> Ops;
9508   for (unsigned i = 1, e = Node->getNumOperands(); i != e; ++i)
9509     Ops.push_back(Node->getOperand(i));
9510 
9511   SDVTList VTs = getVTList(Node->getValueType(0));
9512   SDNode *Res = MorphNodeTo(Node, NewOpc, VTs, Ops);
9513 
9514   // MorphNodeTo can operate in two ways: if an existing node with the
9515   // specified operands exists, it can just return it.  Otherwise, it
9516   // updates the node in place to have the requested operands.
9517   if (Res == Node) {
9518     // If we updated the node in place, reset the node ID.  To the isel,
9519     // this should be just like a newly allocated machine node.
9520     Res->setNodeId(-1);
9521   } else {
9522     ReplaceAllUsesWith(Node, Res);
9523     RemoveDeadNode(Node);
9524   }
9525 
9526   return Res;
9527 }
9528 
9529 /// getMachineNode - These are used for target selectors to create a new node
9530 /// with specified return type(s), MachineInstr opcode, and operands.
9531 ///
9532 /// Note that getMachineNode returns the resultant node.  If there is already a
9533 /// node of the specified opcode and operands, it returns that node instead of
9534 /// the current one.
9535 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9536                                             EVT VT) {
9537   SDVTList VTs = getVTList(VT);
9538   return getMachineNode(Opcode, dl, VTs, None);
9539 }
9540 
9541 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9542                                             EVT VT, SDValue Op1) {
9543   SDVTList VTs = getVTList(VT);
9544   SDValue Ops[] = { Op1 };
9545   return getMachineNode(Opcode, dl, VTs, Ops);
9546 }
9547 
9548 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9549                                             EVT VT, SDValue Op1, SDValue Op2) {
9550   SDVTList VTs = getVTList(VT);
9551   SDValue Ops[] = { Op1, Op2 };
9552   return getMachineNode(Opcode, dl, VTs, Ops);
9553 }
9554 
9555 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9556                                             EVT VT, SDValue Op1, SDValue Op2,
9557                                             SDValue Op3) {
9558   SDVTList VTs = getVTList(VT);
9559   SDValue Ops[] = { Op1, Op2, Op3 };
9560   return getMachineNode(Opcode, dl, VTs, Ops);
9561 }
9562 
9563 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9564                                             EVT VT, ArrayRef<SDValue> Ops) {
9565   SDVTList VTs = getVTList(VT);
9566   return getMachineNode(Opcode, dl, VTs, Ops);
9567 }
9568 
9569 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9570                                             EVT VT1, EVT VT2, SDValue Op1,
9571                                             SDValue Op2) {
9572   SDVTList VTs = getVTList(VT1, VT2);
9573   SDValue Ops[] = { Op1, Op2 };
9574   return getMachineNode(Opcode, dl, VTs, Ops);
9575 }
9576 
9577 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9578                                             EVT VT1, EVT VT2, SDValue Op1,
9579                                             SDValue Op2, SDValue Op3) {
9580   SDVTList VTs = getVTList(VT1, VT2);
9581   SDValue Ops[] = { Op1, Op2, Op3 };
9582   return getMachineNode(Opcode, dl, VTs, Ops);
9583 }
9584 
9585 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9586                                             EVT VT1, EVT VT2,
9587                                             ArrayRef<SDValue> Ops) {
9588   SDVTList VTs = getVTList(VT1, VT2);
9589   return getMachineNode(Opcode, dl, VTs, Ops);
9590 }
9591 
9592 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9593                                             EVT VT1, EVT VT2, EVT VT3,
9594                                             SDValue Op1, SDValue Op2) {
9595   SDVTList VTs = getVTList(VT1, VT2, VT3);
9596   SDValue Ops[] = { Op1, Op2 };
9597   return getMachineNode(Opcode, dl, VTs, Ops);
9598 }
9599 
9600 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9601                                             EVT VT1, EVT VT2, EVT VT3,
9602                                             SDValue Op1, SDValue Op2,
9603                                             SDValue Op3) {
9604   SDVTList VTs = getVTList(VT1, VT2, VT3);
9605   SDValue Ops[] = { Op1, Op2, Op3 };
9606   return getMachineNode(Opcode, dl, VTs, Ops);
9607 }
9608 
9609 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9610                                             EVT VT1, EVT VT2, EVT VT3,
9611                                             ArrayRef<SDValue> Ops) {
9612   SDVTList VTs = getVTList(VT1, VT2, VT3);
9613   return getMachineNode(Opcode, dl, VTs, Ops);
9614 }
9615 
9616 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9617                                             ArrayRef<EVT> ResultTys,
9618                                             ArrayRef<SDValue> Ops) {
9619   SDVTList VTs = getVTList(ResultTys);
9620   return getMachineNode(Opcode, dl, VTs, Ops);
9621 }
9622 
9623 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &DL,
9624                                             SDVTList VTs,
9625                                             ArrayRef<SDValue> Ops) {
9626   bool DoCSE = VTs.VTs[VTs.NumVTs-1] != MVT::Glue;
9627   MachineSDNode *N;
9628   void *IP = nullptr;
9629 
9630   if (DoCSE) {
9631     FoldingSetNodeID ID;
9632     AddNodeIDNode(ID, ~Opcode, VTs, Ops);
9633     IP = nullptr;
9634     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
9635       return cast<MachineSDNode>(UpdateSDLocOnMergeSDNode(E, DL));
9636     }
9637   }
9638 
9639   // Allocate a new MachineSDNode.
9640   N = newSDNode<MachineSDNode>(~Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
9641   createOperands(N, Ops);
9642 
9643   if (DoCSE)
9644     CSEMap.InsertNode(N, IP);
9645 
9646   InsertNode(N);
9647   NewSDValueDbgMsg(SDValue(N, 0), "Creating new machine node: ", this);
9648   return N;
9649 }
9650 
9651 /// getTargetExtractSubreg - A convenience function for creating
9652 /// TargetOpcode::EXTRACT_SUBREG nodes.
9653 SDValue SelectionDAG::getTargetExtractSubreg(int SRIdx, const SDLoc &DL, EVT VT,
9654                                              SDValue Operand) {
9655   SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32);
9656   SDNode *Subreg = getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL,
9657                                   VT, Operand, SRIdxVal);
9658   return SDValue(Subreg, 0);
9659 }
9660 
9661 /// getTargetInsertSubreg - A convenience function for creating
9662 /// TargetOpcode::INSERT_SUBREG nodes.
9663 SDValue SelectionDAG::getTargetInsertSubreg(int SRIdx, const SDLoc &DL, EVT VT,
9664                                             SDValue Operand, SDValue Subreg) {
9665   SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32);
9666   SDNode *Result = getMachineNode(TargetOpcode::INSERT_SUBREG, DL,
9667                                   VT, Operand, Subreg, SRIdxVal);
9668   return SDValue(Result, 0);
9669 }
9670 
9671 /// getNodeIfExists - Get the specified node if it's already available, or
9672 /// else return NULL.
9673 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList,
9674                                       ArrayRef<SDValue> Ops) {
9675   SDNodeFlags Flags;
9676   if (Inserter)
9677     Flags = Inserter->getFlags();
9678   return getNodeIfExists(Opcode, VTList, Ops, Flags);
9679 }
9680 
9681 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList,
9682                                       ArrayRef<SDValue> Ops,
9683                                       const SDNodeFlags Flags) {
9684   if (VTList.VTs[VTList.NumVTs - 1] != MVT::Glue) {
9685     FoldingSetNodeID ID;
9686     AddNodeIDNode(ID, Opcode, VTList, Ops);
9687     void *IP = nullptr;
9688     if (SDNode *E = FindNodeOrInsertPos(ID, SDLoc(), IP)) {
9689       E->intersectFlagsWith(Flags);
9690       return E;
9691     }
9692   }
9693   return nullptr;
9694 }
9695 
9696 /// doesNodeExist - Check if a node exists without modifying its flags.
9697 bool SelectionDAG::doesNodeExist(unsigned Opcode, SDVTList VTList,
9698                                  ArrayRef<SDValue> Ops) {
9699   if (VTList.VTs[VTList.NumVTs - 1] != MVT::Glue) {
9700     FoldingSetNodeID ID;
9701     AddNodeIDNode(ID, Opcode, VTList, Ops);
9702     void *IP = nullptr;
9703     if (FindNodeOrInsertPos(ID, SDLoc(), IP))
9704       return true;
9705   }
9706   return false;
9707 }
9708 
9709 /// getDbgValue - Creates a SDDbgValue node.
9710 ///
9711 /// SDNode
9712 SDDbgValue *SelectionDAG::getDbgValue(DIVariable *Var, DIExpression *Expr,
9713                                       SDNode *N, unsigned R, bool IsIndirect,
9714                                       const DebugLoc &DL, unsigned O) {
9715   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
9716          "Expected inlined-at fields to agree");
9717   return new (DbgInfo->getAlloc())
9718       SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromNode(N, R),
9719                  {}, IsIndirect, DL, O,
9720                  /*IsVariadic=*/false);
9721 }
9722 
9723 /// Constant
9724 SDDbgValue *SelectionDAG::getConstantDbgValue(DIVariable *Var,
9725                                               DIExpression *Expr,
9726                                               const Value *C,
9727                                               const DebugLoc &DL, unsigned O) {
9728   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
9729          "Expected inlined-at fields to agree");
9730   return new (DbgInfo->getAlloc())
9731       SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromConst(C), {},
9732                  /*IsIndirect=*/false, DL, O,
9733                  /*IsVariadic=*/false);
9734 }
9735 
9736 /// FrameIndex
9737 SDDbgValue *SelectionDAG::getFrameIndexDbgValue(DIVariable *Var,
9738                                                 DIExpression *Expr, unsigned FI,
9739                                                 bool IsIndirect,
9740                                                 const DebugLoc &DL,
9741                                                 unsigned O) {
9742   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
9743          "Expected inlined-at fields to agree");
9744   return getFrameIndexDbgValue(Var, Expr, FI, {}, IsIndirect, DL, O);
9745 }
9746 
9747 /// FrameIndex with dependencies
9748 SDDbgValue *SelectionDAG::getFrameIndexDbgValue(DIVariable *Var,
9749                                                 DIExpression *Expr, unsigned FI,
9750                                                 ArrayRef<SDNode *> Dependencies,
9751                                                 bool IsIndirect,
9752                                                 const DebugLoc &DL,
9753                                                 unsigned O) {
9754   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
9755          "Expected inlined-at fields to agree");
9756   return new (DbgInfo->getAlloc())
9757       SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromFrameIdx(FI),
9758                  Dependencies, IsIndirect, DL, O,
9759                  /*IsVariadic=*/false);
9760 }
9761 
9762 /// VReg
9763 SDDbgValue *SelectionDAG::getVRegDbgValue(DIVariable *Var, DIExpression *Expr,
9764                                           unsigned VReg, bool IsIndirect,
9765                                           const DebugLoc &DL, unsigned O) {
9766   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
9767          "Expected inlined-at fields to agree");
9768   return new (DbgInfo->getAlloc())
9769       SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromVReg(VReg),
9770                  {}, IsIndirect, DL, O,
9771                  /*IsVariadic=*/false);
9772 }
9773 
9774 SDDbgValue *SelectionDAG::getDbgValueList(DIVariable *Var, DIExpression *Expr,
9775                                           ArrayRef<SDDbgOperand> Locs,
9776                                           ArrayRef<SDNode *> Dependencies,
9777                                           bool IsIndirect, const DebugLoc &DL,
9778                                           unsigned O, bool IsVariadic) {
9779   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
9780          "Expected inlined-at fields to agree");
9781   return new (DbgInfo->getAlloc())
9782       SDDbgValue(DbgInfo->getAlloc(), Var, Expr, Locs, Dependencies, IsIndirect,
9783                  DL, O, IsVariadic);
9784 }
9785 
9786 void SelectionDAG::transferDbgValues(SDValue From, SDValue To,
9787                                      unsigned OffsetInBits, unsigned SizeInBits,
9788                                      bool InvalidateDbg) {
9789   SDNode *FromNode = From.getNode();
9790   SDNode *ToNode = To.getNode();
9791   assert(FromNode && ToNode && "Can't modify dbg values");
9792 
9793   // PR35338
9794   // TODO: assert(From != To && "Redundant dbg value transfer");
9795   // TODO: assert(FromNode != ToNode && "Intranode dbg value transfer");
9796   if (From == To || FromNode == ToNode)
9797     return;
9798 
9799   if (!FromNode->getHasDebugValue())
9800     return;
9801 
9802   SDDbgOperand FromLocOp =
9803       SDDbgOperand::fromNode(From.getNode(), From.getResNo());
9804   SDDbgOperand ToLocOp = SDDbgOperand::fromNode(To.getNode(), To.getResNo());
9805 
9806   SmallVector<SDDbgValue *, 2> ClonedDVs;
9807   for (SDDbgValue *Dbg : GetDbgValues(FromNode)) {
9808     if (Dbg->isInvalidated())
9809       continue;
9810 
9811     // TODO: assert(!Dbg->isInvalidated() && "Transfer of invalid dbg value");
9812 
9813     // Create a new location ops vector that is equal to the old vector, but
9814     // with each instance of FromLocOp replaced with ToLocOp.
9815     bool Changed = false;
9816     auto NewLocOps = Dbg->copyLocationOps();
9817     std::replace_if(
9818         NewLocOps.begin(), NewLocOps.end(),
9819         [&Changed, FromLocOp](const SDDbgOperand &Op) {
9820           bool Match = Op == FromLocOp;
9821           Changed |= Match;
9822           return Match;
9823         },
9824         ToLocOp);
9825     // Ignore this SDDbgValue if we didn't find a matching location.
9826     if (!Changed)
9827       continue;
9828 
9829     DIVariable *Var = Dbg->getVariable();
9830     auto *Expr = Dbg->getExpression();
9831     // If a fragment is requested, update the expression.
9832     if (SizeInBits) {
9833       // When splitting a larger (e.g., sign-extended) value whose
9834       // lower bits are described with an SDDbgValue, do not attempt
9835       // to transfer the SDDbgValue to the upper bits.
9836       if (auto FI = Expr->getFragmentInfo())
9837         if (OffsetInBits + SizeInBits > FI->SizeInBits)
9838           continue;
9839       auto Fragment = DIExpression::createFragmentExpression(Expr, OffsetInBits,
9840                                                              SizeInBits);
9841       if (!Fragment)
9842         continue;
9843       Expr = *Fragment;
9844     }
9845 
9846     auto AdditionalDependencies = Dbg->getAdditionalDependencies();
9847     // Clone the SDDbgValue and move it to To.
9848     SDDbgValue *Clone = getDbgValueList(
9849         Var, Expr, NewLocOps, AdditionalDependencies, Dbg->isIndirect(),
9850         Dbg->getDebugLoc(), std::max(ToNode->getIROrder(), Dbg->getOrder()),
9851         Dbg->isVariadic());
9852     ClonedDVs.push_back(Clone);
9853 
9854     if (InvalidateDbg) {
9855       // Invalidate value and indicate the SDDbgValue should not be emitted.
9856       Dbg->setIsInvalidated();
9857       Dbg->setIsEmitted();
9858     }
9859   }
9860 
9861   for (SDDbgValue *Dbg : ClonedDVs) {
9862     assert(is_contained(Dbg->getSDNodes(), ToNode) &&
9863            "Transferred DbgValues should depend on the new SDNode");
9864     AddDbgValue(Dbg, false);
9865   }
9866 }
9867 
9868 void SelectionDAG::salvageDebugInfo(SDNode &N) {
9869   if (!N.getHasDebugValue())
9870     return;
9871 
9872   SmallVector<SDDbgValue *, 2> ClonedDVs;
9873   for (auto DV : GetDbgValues(&N)) {
9874     if (DV->isInvalidated())
9875       continue;
9876     switch (N.getOpcode()) {
9877     default:
9878       break;
9879     case ISD::ADD:
9880       SDValue N0 = N.getOperand(0);
9881       SDValue N1 = N.getOperand(1);
9882       if (!isConstantIntBuildVectorOrConstantInt(N0) &&
9883           isConstantIntBuildVectorOrConstantInt(N1)) {
9884         uint64_t Offset = N.getConstantOperandVal(1);
9885 
9886         // Rewrite an ADD constant node into a DIExpression. Since we are
9887         // performing arithmetic to compute the variable's *value* in the
9888         // DIExpression, we need to mark the expression with a
9889         // DW_OP_stack_value.
9890         auto *DIExpr = DV->getExpression();
9891         auto NewLocOps = DV->copyLocationOps();
9892         bool Changed = false;
9893         for (size_t i = 0; i < NewLocOps.size(); ++i) {
9894           // We're not given a ResNo to compare against because the whole
9895           // node is going away. We know that any ISD::ADD only has one
9896           // result, so we can assume any node match is using the result.
9897           if (NewLocOps[i].getKind() != SDDbgOperand::SDNODE ||
9898               NewLocOps[i].getSDNode() != &N)
9899             continue;
9900           NewLocOps[i] = SDDbgOperand::fromNode(N0.getNode(), N0.getResNo());
9901           SmallVector<uint64_t, 3> ExprOps;
9902           DIExpression::appendOffset(ExprOps, Offset);
9903           DIExpr = DIExpression::appendOpsToArg(DIExpr, ExprOps, i, true);
9904           Changed = true;
9905         }
9906         (void)Changed;
9907         assert(Changed && "Salvage target doesn't use N");
9908 
9909         auto AdditionalDependencies = DV->getAdditionalDependencies();
9910         SDDbgValue *Clone = getDbgValueList(DV->getVariable(), DIExpr,
9911                                             NewLocOps, AdditionalDependencies,
9912                                             DV->isIndirect(), DV->getDebugLoc(),
9913                                             DV->getOrder(), DV->isVariadic());
9914         ClonedDVs.push_back(Clone);
9915         DV->setIsInvalidated();
9916         DV->setIsEmitted();
9917         LLVM_DEBUG(dbgs() << "SALVAGE: Rewriting";
9918                    N0.getNode()->dumprFull(this);
9919                    dbgs() << " into " << *DIExpr << '\n');
9920       }
9921     }
9922   }
9923 
9924   for (SDDbgValue *Dbg : ClonedDVs) {
9925     assert(!Dbg->getSDNodes().empty() &&
9926            "Salvaged DbgValue should depend on a new SDNode");
9927     AddDbgValue(Dbg, false);
9928   }
9929 }
9930 
9931 /// Creates a SDDbgLabel node.
9932 SDDbgLabel *SelectionDAG::getDbgLabel(DILabel *Label,
9933                                       const DebugLoc &DL, unsigned O) {
9934   assert(cast<DILabel>(Label)->isValidLocationForIntrinsic(DL) &&
9935          "Expected inlined-at fields to agree");
9936   return new (DbgInfo->getAlloc()) SDDbgLabel(Label, DL, O);
9937 }
9938 
9939 namespace {
9940 
9941 /// RAUWUpdateListener - Helper for ReplaceAllUsesWith - When the node
9942 /// pointed to by a use iterator is deleted, increment the use iterator
9943 /// so that it doesn't dangle.
9944 ///
9945 class RAUWUpdateListener : public SelectionDAG::DAGUpdateListener {
9946   SDNode::use_iterator &UI;
9947   SDNode::use_iterator &UE;
9948 
9949   void NodeDeleted(SDNode *N, SDNode *E) override {
9950     // Increment the iterator as needed.
9951     while (UI != UE && N == *UI)
9952       ++UI;
9953   }
9954 
9955 public:
9956   RAUWUpdateListener(SelectionDAG &d,
9957                      SDNode::use_iterator &ui,
9958                      SDNode::use_iterator &ue)
9959     : SelectionDAG::DAGUpdateListener(d), UI(ui), UE(ue) {}
9960 };
9961 
9962 } // end anonymous namespace
9963 
9964 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
9965 /// This can cause recursive merging of nodes in the DAG.
9966 ///
9967 /// This version assumes From has a single result value.
9968 ///
9969 void SelectionDAG::ReplaceAllUsesWith(SDValue FromN, SDValue To) {
9970   SDNode *From = FromN.getNode();
9971   assert(From->getNumValues() == 1 && FromN.getResNo() == 0 &&
9972          "Cannot replace with this method!");
9973   assert(From != To.getNode() && "Cannot replace uses of with self");
9974 
9975   // Preserve Debug Values
9976   transferDbgValues(FromN, To);
9977 
9978   // Iterate over all the existing uses of From. New uses will be added
9979   // to the beginning of the use list, which we avoid visiting.
9980   // This specifically avoids visiting uses of From that arise while the
9981   // replacement is happening, because any such uses would be the result
9982   // of CSE: If an existing node looks like From after one of its operands
9983   // is replaced by To, we don't want to replace of all its users with To
9984   // too. See PR3018 for more info.
9985   SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
9986   RAUWUpdateListener Listener(*this, UI, UE);
9987   while (UI != UE) {
9988     SDNode *User = *UI;
9989 
9990     // This node is about to morph, remove its old self from the CSE maps.
9991     RemoveNodeFromCSEMaps(User);
9992 
9993     // A user can appear in a use list multiple times, and when this
9994     // happens the uses are usually next to each other in the list.
9995     // To help reduce the number of CSE recomputations, process all
9996     // the uses of this user that we can find this way.
9997     do {
9998       SDUse &Use = UI.getUse();
9999       ++UI;
10000       Use.set(To);
10001       if (To->isDivergent() != From->isDivergent())
10002         updateDivergence(User);
10003     } while (UI != UE && *UI == User);
10004     // Now that we have modified User, add it back to the CSE maps.  If it
10005     // already exists there, recursively merge the results together.
10006     AddModifiedNodeToCSEMaps(User);
10007   }
10008 
10009   // If we just RAUW'd the root, take note.
10010   if (FromN == getRoot())
10011     setRoot(To);
10012 }
10013 
10014 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
10015 /// This can cause recursive merging of nodes in the DAG.
10016 ///
10017 /// This version assumes that for each value of From, there is a
10018 /// corresponding value in To in the same position with the same type.
10019 ///
10020 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, SDNode *To) {
10021 #ifndef NDEBUG
10022   for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
10023     assert((!From->hasAnyUseOfValue(i) ||
10024             From->getValueType(i) == To->getValueType(i)) &&
10025            "Cannot use this version of ReplaceAllUsesWith!");
10026 #endif
10027 
10028   // Handle the trivial case.
10029   if (From == To)
10030     return;
10031 
10032   // Preserve Debug Info. Only do this if there's a use.
10033   for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
10034     if (From->hasAnyUseOfValue(i)) {
10035       assert((i < To->getNumValues()) && "Invalid To location");
10036       transferDbgValues(SDValue(From, i), SDValue(To, i));
10037     }
10038 
10039   // Iterate over just the existing users of From. See the comments in
10040   // the ReplaceAllUsesWith above.
10041   SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
10042   RAUWUpdateListener Listener(*this, UI, UE);
10043   while (UI != UE) {
10044     SDNode *User = *UI;
10045 
10046     // This node is about to morph, remove its old self from the CSE maps.
10047     RemoveNodeFromCSEMaps(User);
10048 
10049     // A user can appear in a use list multiple times, and when this
10050     // happens the uses are usually next to each other in the list.
10051     // To help reduce the number of CSE recomputations, process all
10052     // the uses of this user that we can find this way.
10053     do {
10054       SDUse &Use = UI.getUse();
10055       ++UI;
10056       Use.setNode(To);
10057       if (To->isDivergent() != From->isDivergent())
10058         updateDivergence(User);
10059     } while (UI != UE && *UI == User);
10060 
10061     // Now that we have modified User, add it back to the CSE maps.  If it
10062     // already exists there, recursively merge the results together.
10063     AddModifiedNodeToCSEMaps(User);
10064   }
10065 
10066   // If we just RAUW'd the root, take note.
10067   if (From == getRoot().getNode())
10068     setRoot(SDValue(To, getRoot().getResNo()));
10069 }
10070 
10071 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
10072 /// This can cause recursive merging of nodes in the DAG.
10073 ///
10074 /// This version can replace From with any result values.  To must match the
10075 /// number and types of values returned by From.
10076 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, const SDValue *To) {
10077   if (From->getNumValues() == 1)  // Handle the simple case efficiently.
10078     return ReplaceAllUsesWith(SDValue(From, 0), To[0]);
10079 
10080   // Preserve Debug Info.
10081   for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
10082     transferDbgValues(SDValue(From, i), To[i]);
10083 
10084   // Iterate over just the existing users of From. See the comments in
10085   // the ReplaceAllUsesWith above.
10086   SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
10087   RAUWUpdateListener Listener(*this, UI, UE);
10088   while (UI != UE) {
10089     SDNode *User = *UI;
10090 
10091     // This node is about to morph, remove its old self from the CSE maps.
10092     RemoveNodeFromCSEMaps(User);
10093 
10094     // A user can appear in a use list multiple times, and when this happens the
10095     // uses are usually next to each other in the list.  To help reduce the
10096     // number of CSE and divergence recomputations, process all the uses of this
10097     // user that we can find this way.
10098     bool To_IsDivergent = false;
10099     do {
10100       SDUse &Use = UI.getUse();
10101       const SDValue &ToOp = To[Use.getResNo()];
10102       ++UI;
10103       Use.set(ToOp);
10104       To_IsDivergent |= ToOp->isDivergent();
10105     } while (UI != UE && *UI == User);
10106 
10107     if (To_IsDivergent != From->isDivergent())
10108       updateDivergence(User);
10109 
10110     // Now that we have modified User, add it back to the CSE maps.  If it
10111     // already exists there, recursively merge the results together.
10112     AddModifiedNodeToCSEMaps(User);
10113   }
10114 
10115   // If we just RAUW'd the root, take note.
10116   if (From == getRoot().getNode())
10117     setRoot(SDValue(To[getRoot().getResNo()]));
10118 }
10119 
10120 /// ReplaceAllUsesOfValueWith - Replace any uses of From with To, leaving
10121 /// uses of other values produced by From.getNode() alone.  The Deleted
10122 /// vector is handled the same way as for ReplaceAllUsesWith.
10123 void SelectionDAG::ReplaceAllUsesOfValueWith(SDValue From, SDValue To){
10124   // Handle the really simple, really trivial case efficiently.
10125   if (From == To) return;
10126 
10127   // Handle the simple, trivial, case efficiently.
10128   if (From.getNode()->getNumValues() == 1) {
10129     ReplaceAllUsesWith(From, To);
10130     return;
10131   }
10132 
10133   // Preserve Debug Info.
10134   transferDbgValues(From, To);
10135 
10136   // Iterate over just the existing users of From. See the comments in
10137   // the ReplaceAllUsesWith above.
10138   SDNode::use_iterator UI = From.getNode()->use_begin(),
10139                        UE = From.getNode()->use_end();
10140   RAUWUpdateListener Listener(*this, UI, UE);
10141   while (UI != UE) {
10142     SDNode *User = *UI;
10143     bool UserRemovedFromCSEMaps = false;
10144 
10145     // A user can appear in a use list multiple times, and when this
10146     // happens the uses are usually next to each other in the list.
10147     // To help reduce the number of CSE recomputations, process all
10148     // the uses of this user that we can find this way.
10149     do {
10150       SDUse &Use = UI.getUse();
10151 
10152       // Skip uses of different values from the same node.
10153       if (Use.getResNo() != From.getResNo()) {
10154         ++UI;
10155         continue;
10156       }
10157 
10158       // If this node hasn't been modified yet, it's still in the CSE maps,
10159       // so remove its old self from the CSE maps.
10160       if (!UserRemovedFromCSEMaps) {
10161         RemoveNodeFromCSEMaps(User);
10162         UserRemovedFromCSEMaps = true;
10163       }
10164 
10165       ++UI;
10166       Use.set(To);
10167       if (To->isDivergent() != From->isDivergent())
10168         updateDivergence(User);
10169     } while (UI != UE && *UI == User);
10170     // We are iterating over all uses of the From node, so if a use
10171     // doesn't use the specific value, no changes are made.
10172     if (!UserRemovedFromCSEMaps)
10173       continue;
10174 
10175     // Now that we have modified User, add it back to the CSE maps.  If it
10176     // already exists there, recursively merge the results together.
10177     AddModifiedNodeToCSEMaps(User);
10178   }
10179 
10180   // If we just RAUW'd the root, take note.
10181   if (From == getRoot())
10182     setRoot(To);
10183 }
10184 
10185 namespace {
10186 
10187 /// UseMemo - This class is used by SelectionDAG::ReplaceAllUsesOfValuesWith
10188 /// to record information about a use.
10189 struct UseMemo {
10190   SDNode *User;
10191   unsigned Index;
10192   SDUse *Use;
10193 };
10194 
10195 /// operator< - Sort Memos by User.
10196 bool operator<(const UseMemo &L, const UseMemo &R) {
10197   return (intptr_t)L.User < (intptr_t)R.User;
10198 }
10199 
10200 /// RAUOVWUpdateListener - Helper for ReplaceAllUsesOfValuesWith - When the node
10201 /// pointed to by a UseMemo is deleted, set the User to nullptr to indicate that
10202 /// the node already has been taken care of recursively.
10203 class RAUOVWUpdateListener : public SelectionDAG::DAGUpdateListener {
10204   SmallVector<UseMemo, 4> &Uses;
10205 
10206   void NodeDeleted(SDNode *N, SDNode *E) override {
10207     for (UseMemo &Memo : Uses)
10208       if (Memo.User == N)
10209         Memo.User = nullptr;
10210   }
10211 
10212 public:
10213   RAUOVWUpdateListener(SelectionDAG &d, SmallVector<UseMemo, 4> &uses)
10214       : SelectionDAG::DAGUpdateListener(d), Uses(uses) {}
10215 };
10216 
10217 } // end anonymous namespace
10218 
10219 bool SelectionDAG::calculateDivergence(SDNode *N) {
10220   if (TLI->isSDNodeAlwaysUniform(N)) {
10221     assert(!TLI->isSDNodeSourceOfDivergence(N, FLI, DA) &&
10222            "Conflicting divergence information!");
10223     return false;
10224   }
10225   if (TLI->isSDNodeSourceOfDivergence(N, FLI, DA))
10226     return true;
10227   for (auto &Op : N->ops()) {
10228     if (Op.Val.getValueType() != MVT::Other && Op.getNode()->isDivergent())
10229       return true;
10230   }
10231   return false;
10232 }
10233 
10234 void SelectionDAG::updateDivergence(SDNode *N) {
10235   SmallVector<SDNode *, 16> Worklist(1, N);
10236   do {
10237     N = Worklist.pop_back_val();
10238     bool IsDivergent = calculateDivergence(N);
10239     if (N->SDNodeBits.IsDivergent != IsDivergent) {
10240       N->SDNodeBits.IsDivergent = IsDivergent;
10241       llvm::append_range(Worklist, N->uses());
10242     }
10243   } while (!Worklist.empty());
10244 }
10245 
10246 void SelectionDAG::CreateTopologicalOrder(std::vector<SDNode *> &Order) {
10247   DenseMap<SDNode *, unsigned> Degree;
10248   Order.reserve(AllNodes.size());
10249   for (auto &N : allnodes()) {
10250     unsigned NOps = N.getNumOperands();
10251     Degree[&N] = NOps;
10252     if (0 == NOps)
10253       Order.push_back(&N);
10254   }
10255   for (size_t I = 0; I != Order.size(); ++I) {
10256     SDNode *N = Order[I];
10257     for (auto U : N->uses()) {
10258       unsigned &UnsortedOps = Degree[U];
10259       if (0 == --UnsortedOps)
10260         Order.push_back(U);
10261     }
10262   }
10263 }
10264 
10265 #ifndef NDEBUG
10266 void SelectionDAG::VerifyDAGDivergence() {
10267   std::vector<SDNode *> TopoOrder;
10268   CreateTopologicalOrder(TopoOrder);
10269   for (auto *N : TopoOrder) {
10270     assert(calculateDivergence(N) == N->isDivergent() &&
10271            "Divergence bit inconsistency detected");
10272   }
10273 }
10274 #endif
10275 
10276 /// ReplaceAllUsesOfValuesWith - Replace any uses of From with To, leaving
10277 /// uses of other values produced by From.getNode() alone.  The same value
10278 /// may appear in both the From and To list.  The Deleted vector is
10279 /// handled the same way as for ReplaceAllUsesWith.
10280 void SelectionDAG::ReplaceAllUsesOfValuesWith(const SDValue *From,
10281                                               const SDValue *To,
10282                                               unsigned Num){
10283   // Handle the simple, trivial case efficiently.
10284   if (Num == 1)
10285     return ReplaceAllUsesOfValueWith(*From, *To);
10286 
10287   transferDbgValues(*From, *To);
10288 
10289   // Read up all the uses and make records of them. This helps
10290   // processing new uses that are introduced during the
10291   // replacement process.
10292   SmallVector<UseMemo, 4> Uses;
10293   for (unsigned i = 0; i != Num; ++i) {
10294     unsigned FromResNo = From[i].getResNo();
10295     SDNode *FromNode = From[i].getNode();
10296     for (SDNode::use_iterator UI = FromNode->use_begin(),
10297          E = FromNode->use_end(); UI != E; ++UI) {
10298       SDUse &Use = UI.getUse();
10299       if (Use.getResNo() == FromResNo) {
10300         UseMemo Memo = { *UI, i, &Use };
10301         Uses.push_back(Memo);
10302       }
10303     }
10304   }
10305 
10306   // Sort the uses, so that all the uses from a given User are together.
10307   llvm::sort(Uses);
10308   RAUOVWUpdateListener Listener(*this, Uses);
10309 
10310   for (unsigned UseIndex = 0, UseIndexEnd = Uses.size();
10311        UseIndex != UseIndexEnd; ) {
10312     // We know that this user uses some value of From.  If it is the right
10313     // value, update it.
10314     SDNode *User = Uses[UseIndex].User;
10315     // If the node has been deleted by recursive CSE updates when updating
10316     // another node, then just skip this entry.
10317     if (User == nullptr) {
10318       ++UseIndex;
10319       continue;
10320     }
10321 
10322     // This node is about to morph, remove its old self from the CSE maps.
10323     RemoveNodeFromCSEMaps(User);
10324 
10325     // The Uses array is sorted, so all the uses for a given User
10326     // are next to each other in the list.
10327     // To help reduce the number of CSE recomputations, process all
10328     // the uses of this user that we can find this way.
10329     do {
10330       unsigned i = Uses[UseIndex].Index;
10331       SDUse &Use = *Uses[UseIndex].Use;
10332       ++UseIndex;
10333 
10334       Use.set(To[i]);
10335     } while (UseIndex != UseIndexEnd && Uses[UseIndex].User == User);
10336 
10337     // Now that we have modified User, add it back to the CSE maps.  If it
10338     // already exists there, recursively merge the results together.
10339     AddModifiedNodeToCSEMaps(User);
10340   }
10341 }
10342 
10343 /// AssignTopologicalOrder - Assign a unique node id for each node in the DAG
10344 /// based on their topological order. It returns the maximum id and a vector
10345 /// of the SDNodes* in assigned order by reference.
10346 unsigned SelectionDAG::AssignTopologicalOrder() {
10347   unsigned DAGSize = 0;
10348 
10349   // SortedPos tracks the progress of the algorithm. Nodes before it are
10350   // sorted, nodes after it are unsorted. When the algorithm completes
10351   // it is at the end of the list.
10352   allnodes_iterator SortedPos = allnodes_begin();
10353 
10354   // Visit all the nodes. Move nodes with no operands to the front of
10355   // the list immediately. Annotate nodes that do have operands with their
10356   // operand count. Before we do this, the Node Id fields of the nodes
10357   // may contain arbitrary values. After, the Node Id fields for nodes
10358   // before SortedPos will contain the topological sort index, and the
10359   // Node Id fields for nodes At SortedPos and after will contain the
10360   // count of outstanding operands.
10361   for (SDNode &N : llvm::make_early_inc_range(allnodes())) {
10362     checkForCycles(&N, this);
10363     unsigned Degree = N.getNumOperands();
10364     if (Degree == 0) {
10365       // A node with no uses, add it to the result array immediately.
10366       N.setNodeId(DAGSize++);
10367       allnodes_iterator Q(&N);
10368       if (Q != SortedPos)
10369         SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(Q));
10370       assert(SortedPos != AllNodes.end() && "Overran node list");
10371       ++SortedPos;
10372     } else {
10373       // Temporarily use the Node Id as scratch space for the degree count.
10374       N.setNodeId(Degree);
10375     }
10376   }
10377 
10378   // Visit all the nodes. As we iterate, move nodes into sorted order,
10379   // such that by the time the end is reached all nodes will be sorted.
10380   for (SDNode &Node : allnodes()) {
10381     SDNode *N = &Node;
10382     checkForCycles(N, this);
10383     // N is in sorted position, so all its uses have one less operand
10384     // that needs to be sorted.
10385     for (SDNode *P : N->uses()) {
10386       unsigned Degree = P->getNodeId();
10387       assert(Degree != 0 && "Invalid node degree");
10388       --Degree;
10389       if (Degree == 0) {
10390         // All of P's operands are sorted, so P may sorted now.
10391         P->setNodeId(DAGSize++);
10392         if (P->getIterator() != SortedPos)
10393           SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(P));
10394         assert(SortedPos != AllNodes.end() && "Overran node list");
10395         ++SortedPos;
10396       } else {
10397         // Update P's outstanding operand count.
10398         P->setNodeId(Degree);
10399       }
10400     }
10401     if (Node.getIterator() == SortedPos) {
10402 #ifndef NDEBUG
10403       allnodes_iterator I(N);
10404       SDNode *S = &*++I;
10405       dbgs() << "Overran sorted position:\n";
10406       S->dumprFull(this); dbgs() << "\n";
10407       dbgs() << "Checking if this is due to cycles\n";
10408       checkForCycles(this, true);
10409 #endif
10410       llvm_unreachable(nullptr);
10411     }
10412   }
10413 
10414   assert(SortedPos == AllNodes.end() &&
10415          "Topological sort incomplete!");
10416   assert(AllNodes.front().getOpcode() == ISD::EntryToken &&
10417          "First node in topological sort is not the entry token!");
10418   assert(AllNodes.front().getNodeId() == 0 &&
10419          "First node in topological sort has non-zero id!");
10420   assert(AllNodes.front().getNumOperands() == 0 &&
10421          "First node in topological sort has operands!");
10422   assert(AllNodes.back().getNodeId() == (int)DAGSize-1 &&
10423          "Last node in topologic sort has unexpected id!");
10424   assert(AllNodes.back().use_empty() &&
10425          "Last node in topologic sort has users!");
10426   assert(DAGSize == allnodes_size() && "Node count mismatch!");
10427   return DAGSize;
10428 }
10429 
10430 /// AddDbgValue - Add a dbg_value SDNode. If SD is non-null that means the
10431 /// value is produced by SD.
10432 void SelectionDAG::AddDbgValue(SDDbgValue *DB, bool isParameter) {
10433   for (SDNode *SD : DB->getSDNodes()) {
10434     if (!SD)
10435       continue;
10436     assert(DbgInfo->getSDDbgValues(SD).empty() || SD->getHasDebugValue());
10437     SD->setHasDebugValue(true);
10438   }
10439   DbgInfo->add(DB, isParameter);
10440 }
10441 
10442 void SelectionDAG::AddDbgLabel(SDDbgLabel *DB) { DbgInfo->add(DB); }
10443 
10444 SDValue SelectionDAG::makeEquivalentMemoryOrdering(SDValue OldChain,
10445                                                    SDValue NewMemOpChain) {
10446   assert(isa<MemSDNode>(NewMemOpChain) && "Expected a memop node");
10447   assert(NewMemOpChain.getValueType() == MVT::Other && "Expected a token VT");
10448   // The new memory operation must have the same position as the old load in
10449   // terms of memory dependency. Create a TokenFactor for the old load and new
10450   // memory operation and update uses of the old load's output chain to use that
10451   // TokenFactor.
10452   if (OldChain == NewMemOpChain || OldChain.use_empty())
10453     return NewMemOpChain;
10454 
10455   SDValue TokenFactor = getNode(ISD::TokenFactor, SDLoc(OldChain), MVT::Other,
10456                                 OldChain, NewMemOpChain);
10457   ReplaceAllUsesOfValueWith(OldChain, TokenFactor);
10458   UpdateNodeOperands(TokenFactor.getNode(), OldChain, NewMemOpChain);
10459   return TokenFactor;
10460 }
10461 
10462 SDValue SelectionDAG::makeEquivalentMemoryOrdering(LoadSDNode *OldLoad,
10463                                                    SDValue NewMemOp) {
10464   assert(isa<MemSDNode>(NewMemOp.getNode()) && "Expected a memop node");
10465   SDValue OldChain = SDValue(OldLoad, 1);
10466   SDValue NewMemOpChain = NewMemOp.getValue(1);
10467   return makeEquivalentMemoryOrdering(OldChain, NewMemOpChain);
10468 }
10469 
10470 SDValue SelectionDAG::getSymbolFunctionGlobalAddress(SDValue Op,
10471                                                      Function **OutFunction) {
10472   assert(isa<ExternalSymbolSDNode>(Op) && "Node should be an ExternalSymbol");
10473 
10474   auto *Symbol = cast<ExternalSymbolSDNode>(Op)->getSymbol();
10475   auto *Module = MF->getFunction().getParent();
10476   auto *Function = Module->getFunction(Symbol);
10477 
10478   if (OutFunction != nullptr)
10479       *OutFunction = Function;
10480 
10481   if (Function != nullptr) {
10482     auto PtrTy = TLI->getPointerTy(getDataLayout(), Function->getAddressSpace());
10483     return getGlobalAddress(Function, SDLoc(Op), PtrTy);
10484   }
10485 
10486   std::string ErrorStr;
10487   raw_string_ostream ErrorFormatter(ErrorStr);
10488   ErrorFormatter << "Undefined external symbol ";
10489   ErrorFormatter << '"' << Symbol << '"';
10490   report_fatal_error(Twine(ErrorFormatter.str()));
10491 }
10492 
10493 //===----------------------------------------------------------------------===//
10494 //                              SDNode Class
10495 //===----------------------------------------------------------------------===//
10496 
10497 bool llvm::isNullConstant(SDValue V) {
10498   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
10499   return Const != nullptr && Const->isZero();
10500 }
10501 
10502 bool llvm::isNullFPConstant(SDValue V) {
10503   ConstantFPSDNode *Const = dyn_cast<ConstantFPSDNode>(V);
10504   return Const != nullptr && Const->isZero() && !Const->isNegative();
10505 }
10506 
10507 bool llvm::isAllOnesConstant(SDValue V) {
10508   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
10509   return Const != nullptr && Const->isAllOnes();
10510 }
10511 
10512 bool llvm::isOneConstant(SDValue V) {
10513   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
10514   return Const != nullptr && Const->isOne();
10515 }
10516 
10517 bool llvm::isMinSignedConstant(SDValue V) {
10518   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
10519   return Const != nullptr && Const->isMinSignedValue();
10520 }
10521 
10522 SDValue llvm::peekThroughBitcasts(SDValue V) {
10523   while (V.getOpcode() == ISD::BITCAST)
10524     V = V.getOperand(0);
10525   return V;
10526 }
10527 
10528 SDValue llvm::peekThroughOneUseBitcasts(SDValue V) {
10529   while (V.getOpcode() == ISD::BITCAST && V.getOperand(0).hasOneUse())
10530     V = V.getOperand(0);
10531   return V;
10532 }
10533 
10534 SDValue llvm::peekThroughExtractSubvectors(SDValue V) {
10535   while (V.getOpcode() == ISD::EXTRACT_SUBVECTOR)
10536     V = V.getOperand(0);
10537   return V;
10538 }
10539 
10540 bool llvm::isBitwiseNot(SDValue V, bool AllowUndefs) {
10541   if (V.getOpcode() != ISD::XOR)
10542     return false;
10543   V = peekThroughBitcasts(V.getOperand(1));
10544   unsigned NumBits = V.getScalarValueSizeInBits();
10545   ConstantSDNode *C =
10546       isConstOrConstSplat(V, AllowUndefs, /*AllowTruncation*/ true);
10547   return C && (C->getAPIntValue().countTrailingOnes() >= NumBits);
10548 }
10549 
10550 ConstantSDNode *llvm::isConstOrConstSplat(SDValue N, bool AllowUndefs,
10551                                           bool AllowTruncation) {
10552   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
10553     return CN;
10554 
10555   // SplatVectors can truncate their operands. Ignore that case here unless
10556   // AllowTruncation is set.
10557   if (N->getOpcode() == ISD::SPLAT_VECTOR) {
10558     EVT VecEltVT = N->getValueType(0).getVectorElementType();
10559     if (auto *CN = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
10560       EVT CVT = CN->getValueType(0);
10561       assert(CVT.bitsGE(VecEltVT) && "Illegal splat_vector element extension");
10562       if (AllowTruncation || CVT == VecEltVT)
10563         return CN;
10564     }
10565   }
10566 
10567   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
10568     BitVector UndefElements;
10569     ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
10570 
10571     // BuildVectors can truncate their operands. Ignore that case here unless
10572     // AllowTruncation is set.
10573     if (CN && (UndefElements.none() || AllowUndefs)) {
10574       EVT CVT = CN->getValueType(0);
10575       EVT NSVT = N.getValueType().getScalarType();
10576       assert(CVT.bitsGE(NSVT) && "Illegal build vector element extension");
10577       if (AllowTruncation || (CVT == NSVT))
10578         return CN;
10579     }
10580   }
10581 
10582   return nullptr;
10583 }
10584 
10585 ConstantSDNode *llvm::isConstOrConstSplat(SDValue N, const APInt &DemandedElts,
10586                                           bool AllowUndefs,
10587                                           bool AllowTruncation) {
10588   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
10589     return CN;
10590 
10591   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
10592     BitVector UndefElements;
10593     ConstantSDNode *CN = BV->getConstantSplatNode(DemandedElts, &UndefElements);
10594 
10595     // BuildVectors can truncate their operands. Ignore that case here unless
10596     // AllowTruncation is set.
10597     if (CN && (UndefElements.none() || AllowUndefs)) {
10598       EVT CVT = CN->getValueType(0);
10599       EVT NSVT = N.getValueType().getScalarType();
10600       assert(CVT.bitsGE(NSVT) && "Illegal build vector element extension");
10601       if (AllowTruncation || (CVT == NSVT))
10602         return CN;
10603     }
10604   }
10605 
10606   return nullptr;
10607 }
10608 
10609 ConstantFPSDNode *llvm::isConstOrConstSplatFP(SDValue N, bool AllowUndefs) {
10610   if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
10611     return CN;
10612 
10613   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
10614     BitVector UndefElements;
10615     ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements);
10616     if (CN && (UndefElements.none() || AllowUndefs))
10617       return CN;
10618   }
10619 
10620   if (N.getOpcode() == ISD::SPLAT_VECTOR)
10621     if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N.getOperand(0)))
10622       return CN;
10623 
10624   return nullptr;
10625 }
10626 
10627 ConstantFPSDNode *llvm::isConstOrConstSplatFP(SDValue N,
10628                                               const APInt &DemandedElts,
10629                                               bool AllowUndefs) {
10630   if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
10631     return CN;
10632 
10633   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
10634     BitVector UndefElements;
10635     ConstantFPSDNode *CN =
10636         BV->getConstantFPSplatNode(DemandedElts, &UndefElements);
10637     if (CN && (UndefElements.none() || AllowUndefs))
10638       return CN;
10639   }
10640 
10641   return nullptr;
10642 }
10643 
10644 bool llvm::isNullOrNullSplat(SDValue N, bool AllowUndefs) {
10645   // TODO: may want to use peekThroughBitcast() here.
10646   ConstantSDNode *C =
10647       isConstOrConstSplat(N, AllowUndefs, /*AllowTruncation=*/true);
10648   return C && C->isZero();
10649 }
10650 
10651 bool llvm::isOneOrOneSplat(SDValue N, bool AllowUndefs) {
10652   // TODO: may want to use peekThroughBitcast() here.
10653   unsigned BitWidth = N.getScalarValueSizeInBits();
10654   ConstantSDNode *C = isConstOrConstSplat(N, AllowUndefs);
10655   return C && C->isOne() && C->getValueSizeInBits(0) == BitWidth;
10656 }
10657 
10658 bool llvm::isAllOnesOrAllOnesSplat(SDValue N, bool AllowUndefs) {
10659   N = peekThroughBitcasts(N);
10660   unsigned BitWidth = N.getScalarValueSizeInBits();
10661   ConstantSDNode *C = isConstOrConstSplat(N, AllowUndefs);
10662   return C && C->isAllOnes() && C->getValueSizeInBits(0) == BitWidth;
10663 }
10664 
10665 HandleSDNode::~HandleSDNode() {
10666   DropOperands();
10667 }
10668 
10669 GlobalAddressSDNode::GlobalAddressSDNode(unsigned Opc, unsigned Order,
10670                                          const DebugLoc &DL,
10671                                          const GlobalValue *GA, EVT VT,
10672                                          int64_t o, unsigned TF)
10673     : SDNode(Opc, Order, DL, getSDVTList(VT)), Offset(o), TargetFlags(TF) {
10674   TheGlobal = GA;
10675 }
10676 
10677 AddrSpaceCastSDNode::AddrSpaceCastSDNode(unsigned Order, const DebugLoc &dl,
10678                                          EVT VT, unsigned SrcAS,
10679                                          unsigned DestAS)
10680     : SDNode(ISD::ADDRSPACECAST, Order, dl, getSDVTList(VT)),
10681       SrcAddrSpace(SrcAS), DestAddrSpace(DestAS) {}
10682 
10683 MemSDNode::MemSDNode(unsigned Opc, unsigned Order, const DebugLoc &dl,
10684                      SDVTList VTs, EVT memvt, MachineMemOperand *mmo)
10685     : SDNode(Opc, Order, dl, VTs), MemoryVT(memvt), MMO(mmo) {
10686   MemSDNodeBits.IsVolatile = MMO->isVolatile();
10687   MemSDNodeBits.IsNonTemporal = MMO->isNonTemporal();
10688   MemSDNodeBits.IsDereferenceable = MMO->isDereferenceable();
10689   MemSDNodeBits.IsInvariant = MMO->isInvariant();
10690 
10691   // We check here that the size of the memory operand fits within the size of
10692   // the MMO. This is because the MMO might indicate only a possible address
10693   // range instead of specifying the affected memory addresses precisely.
10694   // TODO: Make MachineMemOperands aware of scalable vectors.
10695   assert(memvt.getStoreSize().getKnownMinSize() <= MMO->getSize() &&
10696          "Size mismatch!");
10697 }
10698 
10699 /// Profile - Gather unique data for the node.
10700 ///
10701 void SDNode::Profile(FoldingSetNodeID &ID) const {
10702   AddNodeIDNode(ID, this);
10703 }
10704 
10705 namespace {
10706 
10707   struct EVTArray {
10708     std::vector<EVT> VTs;
10709 
10710     EVTArray() {
10711       VTs.reserve(MVT::VALUETYPE_SIZE);
10712       for (unsigned i = 0; i < MVT::VALUETYPE_SIZE; ++i)
10713         VTs.push_back(MVT((MVT::SimpleValueType)i));
10714     }
10715   };
10716 
10717 } // end anonymous namespace
10718 
10719 static ManagedStatic<std::set<EVT, EVT::compareRawBits>> EVTs;
10720 static ManagedStatic<EVTArray> SimpleVTArray;
10721 static ManagedStatic<sys::SmartMutex<true>> VTMutex;
10722 
10723 /// getValueTypeList - Return a pointer to the specified value type.
10724 ///
10725 const EVT *SDNode::getValueTypeList(EVT VT) {
10726   if (VT.isExtended()) {
10727     sys::SmartScopedLock<true> Lock(*VTMutex);
10728     return &(*EVTs->insert(VT).first);
10729   }
10730   assert(VT.getSimpleVT() < MVT::VALUETYPE_SIZE && "Value type out of range!");
10731   return &SimpleVTArray->VTs[VT.getSimpleVT().SimpleTy];
10732 }
10733 
10734 /// hasNUsesOfValue - Return true if there are exactly NUSES uses of the
10735 /// indicated value.  This method ignores uses of other values defined by this
10736 /// operation.
10737 bool SDNode::hasNUsesOfValue(unsigned NUses, unsigned Value) const {
10738   assert(Value < getNumValues() && "Bad value!");
10739 
10740   // TODO: Only iterate over uses of a given value of the node
10741   for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) {
10742     if (UI.getUse().getResNo() == Value) {
10743       if (NUses == 0)
10744         return false;
10745       --NUses;
10746     }
10747   }
10748 
10749   // Found exactly the right number of uses?
10750   return NUses == 0;
10751 }
10752 
10753 /// hasAnyUseOfValue - Return true if there are any use of the indicated
10754 /// value. This method ignores uses of other values defined by this operation.
10755 bool SDNode::hasAnyUseOfValue(unsigned Value) const {
10756   assert(Value < getNumValues() && "Bad value!");
10757 
10758   for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI)
10759     if (UI.getUse().getResNo() == Value)
10760       return true;
10761 
10762   return false;
10763 }
10764 
10765 /// isOnlyUserOf - Return true if this node is the only use of N.
10766 bool SDNode::isOnlyUserOf(const SDNode *N) const {
10767   bool Seen = false;
10768   for (const SDNode *User : N->uses()) {
10769     if (User == this)
10770       Seen = true;
10771     else
10772       return false;
10773   }
10774 
10775   return Seen;
10776 }
10777 
10778 /// Return true if the only users of N are contained in Nodes.
10779 bool SDNode::areOnlyUsersOf(ArrayRef<const SDNode *> Nodes, const SDNode *N) {
10780   bool Seen = false;
10781   for (const SDNode *User : N->uses()) {
10782     if (llvm::is_contained(Nodes, User))
10783       Seen = true;
10784     else
10785       return false;
10786   }
10787 
10788   return Seen;
10789 }
10790 
10791 /// isOperand - Return true if this node is an operand of N.
10792 bool SDValue::isOperandOf(const SDNode *N) const {
10793   return is_contained(N->op_values(), *this);
10794 }
10795 
10796 bool SDNode::isOperandOf(const SDNode *N) const {
10797   return any_of(N->op_values(),
10798                 [this](SDValue Op) { return this == Op.getNode(); });
10799 }
10800 
10801 /// reachesChainWithoutSideEffects - Return true if this operand (which must
10802 /// be a chain) reaches the specified operand without crossing any
10803 /// side-effecting instructions on any chain path.  In practice, this looks
10804 /// through token factors and non-volatile loads.  In order to remain efficient,
10805 /// this only looks a couple of nodes in, it does not do an exhaustive search.
10806 ///
10807 /// Note that we only need to examine chains when we're searching for
10808 /// side-effects; SelectionDAG requires that all side-effects are represented
10809 /// by chains, even if another operand would force a specific ordering. This
10810 /// constraint is necessary to allow transformations like splitting loads.
10811 bool SDValue::reachesChainWithoutSideEffects(SDValue Dest,
10812                                              unsigned Depth) const {
10813   if (*this == Dest) return true;
10814 
10815   // Don't search too deeply, we just want to be able to see through
10816   // TokenFactor's etc.
10817   if (Depth == 0) return false;
10818 
10819   // If this is a token factor, all inputs to the TF happen in parallel.
10820   if (getOpcode() == ISD::TokenFactor) {
10821     // First, try a shallow search.
10822     if (is_contained((*this)->ops(), Dest)) {
10823       // We found the chain we want as an operand of this TokenFactor.
10824       // Essentially, we reach the chain without side-effects if we could
10825       // serialize the TokenFactor into a simple chain of operations with
10826       // Dest as the last operation. This is automatically true if the
10827       // chain has one use: there are no other ordering constraints.
10828       // If the chain has more than one use, we give up: some other
10829       // use of Dest might force a side-effect between Dest and the current
10830       // node.
10831       if (Dest.hasOneUse())
10832         return true;
10833     }
10834     // Next, try a deep search: check whether every operand of the TokenFactor
10835     // reaches Dest.
10836     return llvm::all_of((*this)->ops(), [=](SDValue Op) {
10837       return Op.reachesChainWithoutSideEffects(Dest, Depth - 1);
10838     });
10839   }
10840 
10841   // Loads don't have side effects, look through them.
10842   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(*this)) {
10843     if (Ld->isUnordered())
10844       return Ld->getChain().reachesChainWithoutSideEffects(Dest, Depth-1);
10845   }
10846   return false;
10847 }
10848 
10849 bool SDNode::hasPredecessor(const SDNode *N) const {
10850   SmallPtrSet<const SDNode *, 32> Visited;
10851   SmallVector<const SDNode *, 16> Worklist;
10852   Worklist.push_back(this);
10853   return hasPredecessorHelper(N, Visited, Worklist);
10854 }
10855 
10856 void SDNode::intersectFlagsWith(const SDNodeFlags Flags) {
10857   this->Flags.intersectWith(Flags);
10858 }
10859 
10860 SDValue
10861 SelectionDAG::matchBinOpReduction(SDNode *Extract, ISD::NodeType &BinOp,
10862                                   ArrayRef<ISD::NodeType> CandidateBinOps,
10863                                   bool AllowPartials) {
10864   // The pattern must end in an extract from index 0.
10865   if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10866       !isNullConstant(Extract->getOperand(1)))
10867     return SDValue();
10868 
10869   // Match against one of the candidate binary ops.
10870   SDValue Op = Extract->getOperand(0);
10871   if (llvm::none_of(CandidateBinOps, [Op](ISD::NodeType BinOp) {
10872         return Op.getOpcode() == unsigned(BinOp);
10873       }))
10874     return SDValue();
10875 
10876   // Floating-point reductions may require relaxed constraints on the final step
10877   // of the reduction because they may reorder intermediate operations.
10878   unsigned CandidateBinOp = Op.getOpcode();
10879   if (Op.getValueType().isFloatingPoint()) {
10880     SDNodeFlags Flags = Op->getFlags();
10881     switch (CandidateBinOp) {
10882     case ISD::FADD:
10883       if (!Flags.hasNoSignedZeros() || !Flags.hasAllowReassociation())
10884         return SDValue();
10885       break;
10886     default:
10887       llvm_unreachable("Unhandled FP opcode for binop reduction");
10888     }
10889   }
10890 
10891   // Matching failed - attempt to see if we did enough stages that a partial
10892   // reduction from a subvector is possible.
10893   auto PartialReduction = [&](SDValue Op, unsigned NumSubElts) {
10894     if (!AllowPartials || !Op)
10895       return SDValue();
10896     EVT OpVT = Op.getValueType();
10897     EVT OpSVT = OpVT.getScalarType();
10898     EVT SubVT = EVT::getVectorVT(*getContext(), OpSVT, NumSubElts);
10899     if (!TLI->isExtractSubvectorCheap(SubVT, OpVT, 0))
10900       return SDValue();
10901     BinOp = (ISD::NodeType)CandidateBinOp;
10902     return getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(Op), SubVT, Op,
10903                    getVectorIdxConstant(0, SDLoc(Op)));
10904   };
10905 
10906   // At each stage, we're looking for something that looks like:
10907   // %s = shufflevector <8 x i32> %op, <8 x i32> undef,
10908   //                    <8 x i32> <i32 2, i32 3, i32 undef, i32 undef,
10909   //                               i32 undef, i32 undef, i32 undef, i32 undef>
10910   // %a = binop <8 x i32> %op, %s
10911   // Where the mask changes according to the stage. E.g. for a 3-stage pyramid,
10912   // we expect something like:
10913   // <4,5,6,7,u,u,u,u>
10914   // <2,3,u,u,u,u,u,u>
10915   // <1,u,u,u,u,u,u,u>
10916   // While a partial reduction match would be:
10917   // <2,3,u,u,u,u,u,u>
10918   // <1,u,u,u,u,u,u,u>
10919   unsigned Stages = Log2_32(Op.getValueType().getVectorNumElements());
10920   SDValue PrevOp;
10921   for (unsigned i = 0; i < Stages; ++i) {
10922     unsigned MaskEnd = (1 << i);
10923 
10924     if (Op.getOpcode() != CandidateBinOp)
10925       return PartialReduction(PrevOp, MaskEnd);
10926 
10927     SDValue Op0 = Op.getOperand(0);
10928     SDValue Op1 = Op.getOperand(1);
10929 
10930     ShuffleVectorSDNode *Shuffle = dyn_cast<ShuffleVectorSDNode>(Op0);
10931     if (Shuffle) {
10932       Op = Op1;
10933     } else {
10934       Shuffle = dyn_cast<ShuffleVectorSDNode>(Op1);
10935       Op = Op0;
10936     }
10937 
10938     // The first operand of the shuffle should be the same as the other operand
10939     // of the binop.
10940     if (!Shuffle || Shuffle->getOperand(0) != Op)
10941       return PartialReduction(PrevOp, MaskEnd);
10942 
10943     // Verify the shuffle has the expected (at this stage of the pyramid) mask.
10944     for (int Index = 0; Index < (int)MaskEnd; ++Index)
10945       if (Shuffle->getMaskElt(Index) != (int)(MaskEnd + Index))
10946         return PartialReduction(PrevOp, MaskEnd);
10947 
10948     PrevOp = Op;
10949   }
10950 
10951   // Handle subvector reductions, which tend to appear after the shuffle
10952   // reduction stages.
10953   while (Op.getOpcode() == CandidateBinOp) {
10954     unsigned NumElts = Op.getValueType().getVectorNumElements();
10955     SDValue Op0 = Op.getOperand(0);
10956     SDValue Op1 = Op.getOperand(1);
10957     if (Op0.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
10958         Op1.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
10959         Op0.getOperand(0) != Op1.getOperand(0))
10960       break;
10961     SDValue Src = Op0.getOperand(0);
10962     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
10963     if (NumSrcElts != (2 * NumElts))
10964       break;
10965     if (!(Op0.getConstantOperandAPInt(1) == 0 &&
10966           Op1.getConstantOperandAPInt(1) == NumElts) &&
10967         !(Op1.getConstantOperandAPInt(1) == 0 &&
10968           Op0.getConstantOperandAPInt(1) == NumElts))
10969       break;
10970     Op = Src;
10971   }
10972 
10973   BinOp = (ISD::NodeType)CandidateBinOp;
10974   return Op;
10975 }
10976 
10977 SDValue SelectionDAG::UnrollVectorOp(SDNode *N, unsigned ResNE) {
10978   assert(N->getNumValues() == 1 &&
10979          "Can't unroll a vector with multiple results!");
10980 
10981   EVT VT = N->getValueType(0);
10982   unsigned NE = VT.getVectorNumElements();
10983   EVT EltVT = VT.getVectorElementType();
10984   SDLoc dl(N);
10985 
10986   SmallVector<SDValue, 8> Scalars;
10987   SmallVector<SDValue, 4> Operands(N->getNumOperands());
10988 
10989   // If ResNE is 0, fully unroll the vector op.
10990   if (ResNE == 0)
10991     ResNE = NE;
10992   else if (NE > ResNE)
10993     NE = ResNE;
10994 
10995   unsigned i;
10996   for (i= 0; i != NE; ++i) {
10997     for (unsigned j = 0, e = N->getNumOperands(); j != e; ++j) {
10998       SDValue Operand = N->getOperand(j);
10999       EVT OperandVT = Operand.getValueType();
11000       if (OperandVT.isVector()) {
11001         // A vector operand; extract a single element.
11002         EVT OperandEltVT = OperandVT.getVectorElementType();
11003         Operands[j] = getNode(ISD::EXTRACT_VECTOR_ELT, dl, OperandEltVT,
11004                               Operand, getVectorIdxConstant(i, dl));
11005       } else {
11006         // A scalar operand; just use it as is.
11007         Operands[j] = Operand;
11008       }
11009     }
11010 
11011     switch (N->getOpcode()) {
11012     default: {
11013       Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands,
11014                                 N->getFlags()));
11015       break;
11016     }
11017     case ISD::VSELECT:
11018       Scalars.push_back(getNode(ISD::SELECT, dl, EltVT, Operands));
11019       break;
11020     case ISD::SHL:
11021     case ISD::SRA:
11022     case ISD::SRL:
11023     case ISD::ROTL:
11024     case ISD::ROTR:
11025       Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands[0],
11026                                getShiftAmountOperand(Operands[0].getValueType(),
11027                                                      Operands[1])));
11028       break;
11029     case ISD::SIGN_EXTEND_INREG: {
11030       EVT ExtVT = cast<VTSDNode>(Operands[1])->getVT().getVectorElementType();
11031       Scalars.push_back(getNode(N->getOpcode(), dl, EltVT,
11032                                 Operands[0],
11033                                 getValueType(ExtVT)));
11034     }
11035     }
11036   }
11037 
11038   for (; i < ResNE; ++i)
11039     Scalars.push_back(getUNDEF(EltVT));
11040 
11041   EVT VecVT = EVT::getVectorVT(*getContext(), EltVT, ResNE);
11042   return getBuildVector(VecVT, dl, Scalars);
11043 }
11044 
11045 std::pair<SDValue, SDValue> SelectionDAG::UnrollVectorOverflowOp(
11046     SDNode *N, unsigned ResNE) {
11047   unsigned Opcode = N->getOpcode();
11048   assert((Opcode == ISD::UADDO || Opcode == ISD::SADDO ||
11049           Opcode == ISD::USUBO || Opcode == ISD::SSUBO ||
11050           Opcode == ISD::UMULO || Opcode == ISD::SMULO) &&
11051          "Expected an overflow opcode");
11052 
11053   EVT ResVT = N->getValueType(0);
11054   EVT OvVT = N->getValueType(1);
11055   EVT ResEltVT = ResVT.getVectorElementType();
11056   EVT OvEltVT = OvVT.getVectorElementType();
11057   SDLoc dl(N);
11058 
11059   // If ResNE is 0, fully unroll the vector op.
11060   unsigned NE = ResVT.getVectorNumElements();
11061   if (ResNE == 0)
11062     ResNE = NE;
11063   else if (NE > ResNE)
11064     NE = ResNE;
11065 
11066   SmallVector<SDValue, 8> LHSScalars;
11067   SmallVector<SDValue, 8> RHSScalars;
11068   ExtractVectorElements(N->getOperand(0), LHSScalars, 0, NE);
11069   ExtractVectorElements(N->getOperand(1), RHSScalars, 0, NE);
11070 
11071   EVT SVT = TLI->getSetCCResultType(getDataLayout(), *getContext(), ResEltVT);
11072   SDVTList VTs = getVTList(ResEltVT, SVT);
11073   SmallVector<SDValue, 8> ResScalars;
11074   SmallVector<SDValue, 8> OvScalars;
11075   for (unsigned i = 0; i < NE; ++i) {
11076     SDValue Res = getNode(Opcode, dl, VTs, LHSScalars[i], RHSScalars[i]);
11077     SDValue Ov =
11078         getSelect(dl, OvEltVT, Res.getValue(1),
11079                   getBoolConstant(true, dl, OvEltVT, ResVT),
11080                   getConstant(0, dl, OvEltVT));
11081 
11082     ResScalars.push_back(Res);
11083     OvScalars.push_back(Ov);
11084   }
11085 
11086   ResScalars.append(ResNE - NE, getUNDEF(ResEltVT));
11087   OvScalars.append(ResNE - NE, getUNDEF(OvEltVT));
11088 
11089   EVT NewResVT = EVT::getVectorVT(*getContext(), ResEltVT, ResNE);
11090   EVT NewOvVT = EVT::getVectorVT(*getContext(), OvEltVT, ResNE);
11091   return std::make_pair(getBuildVector(NewResVT, dl, ResScalars),
11092                         getBuildVector(NewOvVT, dl, OvScalars));
11093 }
11094 
11095 bool SelectionDAG::areNonVolatileConsecutiveLoads(LoadSDNode *LD,
11096                                                   LoadSDNode *Base,
11097                                                   unsigned Bytes,
11098                                                   int Dist) const {
11099   if (LD->isVolatile() || Base->isVolatile())
11100     return false;
11101   // TODO: probably too restrictive for atomics, revisit
11102   if (!LD->isSimple())
11103     return false;
11104   if (LD->isIndexed() || Base->isIndexed())
11105     return false;
11106   if (LD->getChain() != Base->getChain())
11107     return false;
11108   EVT VT = LD->getValueType(0);
11109   if (VT.getSizeInBits() / 8 != Bytes)
11110     return false;
11111 
11112   auto BaseLocDecomp = BaseIndexOffset::match(Base, *this);
11113   auto LocDecomp = BaseIndexOffset::match(LD, *this);
11114 
11115   int64_t Offset = 0;
11116   if (BaseLocDecomp.equalBaseIndex(LocDecomp, *this, Offset))
11117     return (Dist * Bytes == Offset);
11118   return false;
11119 }
11120 
11121 /// InferPtrAlignment - Infer alignment of a load / store address. Return None
11122 /// if it cannot be inferred.
11123 MaybeAlign SelectionDAG::InferPtrAlign(SDValue Ptr) const {
11124   // If this is a GlobalAddress + cst, return the alignment.
11125   const GlobalValue *GV = nullptr;
11126   int64_t GVOffset = 0;
11127   if (TLI->isGAPlusOffset(Ptr.getNode(), GV, GVOffset)) {
11128     unsigned PtrWidth = getDataLayout().getPointerTypeSizeInBits(GV->getType());
11129     KnownBits Known(PtrWidth);
11130     llvm::computeKnownBits(GV, Known, getDataLayout());
11131     unsigned AlignBits = Known.countMinTrailingZeros();
11132     if (AlignBits)
11133       return commonAlignment(Align(1ull << std::min(31U, AlignBits)), GVOffset);
11134   }
11135 
11136   // If this is a direct reference to a stack slot, use information about the
11137   // stack slot's alignment.
11138   int FrameIdx = INT_MIN;
11139   int64_t FrameOffset = 0;
11140   if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr)) {
11141     FrameIdx = FI->getIndex();
11142   } else if (isBaseWithConstantOffset(Ptr) &&
11143              isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
11144     // Handle FI+Cst
11145     FrameIdx = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
11146     FrameOffset = Ptr.getConstantOperandVal(1);
11147   }
11148 
11149   if (FrameIdx != INT_MIN) {
11150     const MachineFrameInfo &MFI = getMachineFunction().getFrameInfo();
11151     return commonAlignment(MFI.getObjectAlign(FrameIdx), FrameOffset);
11152   }
11153 
11154   return None;
11155 }
11156 
11157 /// GetSplitDestVTs - Compute the VTs needed for the low/hi parts of a type
11158 /// which is split (or expanded) into two not necessarily identical pieces.
11159 std::pair<EVT, EVT> SelectionDAG::GetSplitDestVTs(const EVT &VT) const {
11160   // Currently all types are split in half.
11161   EVT LoVT, HiVT;
11162   if (!VT.isVector())
11163     LoVT = HiVT = TLI->getTypeToTransformTo(*getContext(), VT);
11164   else
11165     LoVT = HiVT = VT.getHalfNumVectorElementsVT(*getContext());
11166 
11167   return std::make_pair(LoVT, HiVT);
11168 }
11169 
11170 /// GetDependentSplitDestVTs - Compute the VTs needed for the low/hi parts of a
11171 /// type, dependent on an enveloping VT that has been split into two identical
11172 /// pieces. Sets the HiIsEmpty flag when hi type has zero storage size.
11173 std::pair<EVT, EVT>
11174 SelectionDAG::GetDependentSplitDestVTs(const EVT &VT, const EVT &EnvVT,
11175                                        bool *HiIsEmpty) const {
11176   EVT EltTp = VT.getVectorElementType();
11177   // Examples:
11178   //   custom VL=8  with enveloping VL=8/8 yields 8/0 (hi empty)
11179   //   custom VL=9  with enveloping VL=8/8 yields 8/1
11180   //   custom VL=10 with enveloping VL=8/8 yields 8/2
11181   //   etc.
11182   ElementCount VTNumElts = VT.getVectorElementCount();
11183   ElementCount EnvNumElts = EnvVT.getVectorElementCount();
11184   assert(VTNumElts.isScalable() == EnvNumElts.isScalable() &&
11185          "Mixing fixed width and scalable vectors when enveloping a type");
11186   EVT LoVT, HiVT;
11187   if (VTNumElts.getKnownMinValue() > EnvNumElts.getKnownMinValue()) {
11188     LoVT = EVT::getVectorVT(*getContext(), EltTp, EnvNumElts);
11189     HiVT = EVT::getVectorVT(*getContext(), EltTp, VTNumElts - EnvNumElts);
11190     *HiIsEmpty = false;
11191   } else {
11192     // Flag that hi type has zero storage size, but return split envelop type
11193     // (this would be easier if vector types with zero elements were allowed).
11194     LoVT = EVT::getVectorVT(*getContext(), EltTp, VTNumElts);
11195     HiVT = EVT::getVectorVT(*getContext(), EltTp, EnvNumElts);
11196     *HiIsEmpty = true;
11197   }
11198   return std::make_pair(LoVT, HiVT);
11199 }
11200 
11201 /// SplitVector - Split the vector with EXTRACT_SUBVECTOR and return the
11202 /// low/high part.
11203 std::pair<SDValue, SDValue>
11204 SelectionDAG::SplitVector(const SDValue &N, const SDLoc &DL, const EVT &LoVT,
11205                           const EVT &HiVT) {
11206   assert(LoVT.isScalableVector() == HiVT.isScalableVector() &&
11207          LoVT.isScalableVector() == N.getValueType().isScalableVector() &&
11208          "Splitting vector with an invalid mixture of fixed and scalable "
11209          "vector types");
11210   assert(LoVT.getVectorMinNumElements() + HiVT.getVectorMinNumElements() <=
11211              N.getValueType().getVectorMinNumElements() &&
11212          "More vector elements requested than available!");
11213   SDValue Lo, Hi;
11214   Lo =
11215       getNode(ISD::EXTRACT_SUBVECTOR, DL, LoVT, N, getVectorIdxConstant(0, DL));
11216   // For scalable vectors it is safe to use LoVT.getVectorMinNumElements()
11217   // (rather than having to use ElementCount), because EXTRACT_SUBVECTOR scales
11218   // IDX with the runtime scaling factor of the result vector type. For
11219   // fixed-width result vectors, that runtime scaling factor is 1.
11220   Hi = getNode(ISD::EXTRACT_SUBVECTOR, DL, HiVT, N,
11221                getVectorIdxConstant(LoVT.getVectorMinNumElements(), DL));
11222   return std::make_pair(Lo, Hi);
11223 }
11224 
11225 std::pair<SDValue, SDValue> SelectionDAG::SplitEVL(SDValue N, EVT VecVT,
11226                                                    const SDLoc &DL) {
11227   // Split the vector length parameter.
11228   // %evl -> umin(%evl, %halfnumelts) and usubsat(%evl - %halfnumelts).
11229   EVT VT = N.getValueType();
11230   assert(VecVT.getVectorElementCount().isKnownEven() &&
11231          "Expecting the mask to be an evenly-sized vector");
11232   unsigned HalfMinNumElts = VecVT.getVectorMinNumElements() / 2;
11233   SDValue HalfNumElts =
11234       VecVT.isFixedLengthVector()
11235           ? getConstant(HalfMinNumElts, DL, VT)
11236           : getVScale(DL, VT, APInt(VT.getScalarSizeInBits(), HalfMinNumElts));
11237   SDValue Lo = getNode(ISD::UMIN, DL, VT, N, HalfNumElts);
11238   SDValue Hi = getNode(ISD::USUBSAT, DL, VT, N, HalfNumElts);
11239   return std::make_pair(Lo, Hi);
11240 }
11241 
11242 /// Widen the vector up to the next power of two using INSERT_SUBVECTOR.
11243 SDValue SelectionDAG::WidenVector(const SDValue &N, const SDLoc &DL) {
11244   EVT VT = N.getValueType();
11245   EVT WideVT = EVT::getVectorVT(*getContext(), VT.getVectorElementType(),
11246                                 NextPowerOf2(VT.getVectorNumElements()));
11247   return getNode(ISD::INSERT_SUBVECTOR, DL, WideVT, getUNDEF(WideVT), N,
11248                  getVectorIdxConstant(0, DL));
11249 }
11250 
11251 void SelectionDAG::ExtractVectorElements(SDValue Op,
11252                                          SmallVectorImpl<SDValue> &Args,
11253                                          unsigned Start, unsigned Count,
11254                                          EVT EltVT) {
11255   EVT VT = Op.getValueType();
11256   if (Count == 0)
11257     Count = VT.getVectorNumElements();
11258   if (EltVT == EVT())
11259     EltVT = VT.getVectorElementType();
11260   SDLoc SL(Op);
11261   for (unsigned i = Start, e = Start + Count; i != e; ++i) {
11262     Args.push_back(getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Op,
11263                            getVectorIdxConstant(i, SL)));
11264   }
11265 }
11266 
11267 // getAddressSpace - Return the address space this GlobalAddress belongs to.
11268 unsigned GlobalAddressSDNode::getAddressSpace() const {
11269   return getGlobal()->getType()->getAddressSpace();
11270 }
11271 
11272 Type *ConstantPoolSDNode::getType() const {
11273   if (isMachineConstantPoolEntry())
11274     return Val.MachineCPVal->getType();
11275   return Val.ConstVal->getType();
11276 }
11277 
11278 bool BuildVectorSDNode::isConstantSplat(APInt &SplatValue, APInt &SplatUndef,
11279                                         unsigned &SplatBitSize,
11280                                         bool &HasAnyUndefs,
11281                                         unsigned MinSplatBits,
11282                                         bool IsBigEndian) const {
11283   EVT VT = getValueType(0);
11284   assert(VT.isVector() && "Expected a vector type");
11285   unsigned VecWidth = VT.getSizeInBits();
11286   if (MinSplatBits > VecWidth)
11287     return false;
11288 
11289   // FIXME: The widths are based on this node's type, but build vectors can
11290   // truncate their operands.
11291   SplatValue = APInt(VecWidth, 0);
11292   SplatUndef = APInt(VecWidth, 0);
11293 
11294   // Get the bits. Bits with undefined values (when the corresponding element
11295   // of the vector is an ISD::UNDEF value) are set in SplatUndef and cleared
11296   // in SplatValue. If any of the values are not constant, give up and return
11297   // false.
11298   unsigned int NumOps = getNumOperands();
11299   assert(NumOps > 0 && "isConstantSplat has 0-size build vector");
11300   unsigned EltWidth = VT.getScalarSizeInBits();
11301 
11302   for (unsigned j = 0; j < NumOps; ++j) {
11303     unsigned i = IsBigEndian ? NumOps - 1 - j : j;
11304     SDValue OpVal = getOperand(i);
11305     unsigned BitPos = j * EltWidth;
11306 
11307     if (OpVal.isUndef())
11308       SplatUndef.setBits(BitPos, BitPos + EltWidth);
11309     else if (auto *CN = dyn_cast<ConstantSDNode>(OpVal))
11310       SplatValue.insertBits(CN->getAPIntValue().zextOrTrunc(EltWidth), BitPos);
11311     else if (auto *CN = dyn_cast<ConstantFPSDNode>(OpVal))
11312       SplatValue.insertBits(CN->getValueAPF().bitcastToAPInt(), BitPos);
11313     else
11314       return false;
11315   }
11316 
11317   // The build_vector is all constants or undefs. Find the smallest element
11318   // size that splats the vector.
11319   HasAnyUndefs = (SplatUndef != 0);
11320 
11321   // FIXME: This does not work for vectors with elements less than 8 bits.
11322   while (VecWidth > 8) {
11323     unsigned HalfSize = VecWidth / 2;
11324     APInt HighValue = SplatValue.extractBits(HalfSize, HalfSize);
11325     APInt LowValue = SplatValue.extractBits(HalfSize, 0);
11326     APInt HighUndef = SplatUndef.extractBits(HalfSize, HalfSize);
11327     APInt LowUndef = SplatUndef.extractBits(HalfSize, 0);
11328 
11329     // If the two halves do not match (ignoring undef bits), stop here.
11330     if ((HighValue & ~LowUndef) != (LowValue & ~HighUndef) ||
11331         MinSplatBits > HalfSize)
11332       break;
11333 
11334     SplatValue = HighValue | LowValue;
11335     SplatUndef = HighUndef & LowUndef;
11336 
11337     VecWidth = HalfSize;
11338   }
11339 
11340   SplatBitSize = VecWidth;
11341   return true;
11342 }
11343 
11344 SDValue BuildVectorSDNode::getSplatValue(const APInt &DemandedElts,
11345                                          BitVector *UndefElements) const {
11346   unsigned NumOps = getNumOperands();
11347   if (UndefElements) {
11348     UndefElements->clear();
11349     UndefElements->resize(NumOps);
11350   }
11351   assert(NumOps == DemandedElts.getBitWidth() && "Unexpected vector size");
11352   if (!DemandedElts)
11353     return SDValue();
11354   SDValue Splatted;
11355   for (unsigned i = 0; i != NumOps; ++i) {
11356     if (!DemandedElts[i])
11357       continue;
11358     SDValue Op = getOperand(i);
11359     if (Op.isUndef()) {
11360       if (UndefElements)
11361         (*UndefElements)[i] = true;
11362     } else if (!Splatted) {
11363       Splatted = Op;
11364     } else if (Splatted != Op) {
11365       return SDValue();
11366     }
11367   }
11368 
11369   if (!Splatted) {
11370     unsigned FirstDemandedIdx = DemandedElts.countTrailingZeros();
11371     assert(getOperand(FirstDemandedIdx).isUndef() &&
11372            "Can only have a splat without a constant for all undefs.");
11373     return getOperand(FirstDemandedIdx);
11374   }
11375 
11376   return Splatted;
11377 }
11378 
11379 SDValue BuildVectorSDNode::getSplatValue(BitVector *UndefElements) const {
11380   APInt DemandedElts = APInt::getAllOnes(getNumOperands());
11381   return getSplatValue(DemandedElts, UndefElements);
11382 }
11383 
11384 bool BuildVectorSDNode::getRepeatedSequence(const APInt &DemandedElts,
11385                                             SmallVectorImpl<SDValue> &Sequence,
11386                                             BitVector *UndefElements) const {
11387   unsigned NumOps = getNumOperands();
11388   Sequence.clear();
11389   if (UndefElements) {
11390     UndefElements->clear();
11391     UndefElements->resize(NumOps);
11392   }
11393   assert(NumOps == DemandedElts.getBitWidth() && "Unexpected vector size");
11394   if (!DemandedElts || NumOps < 2 || !isPowerOf2_32(NumOps))
11395     return false;
11396 
11397   // Set the undefs even if we don't find a sequence (like getSplatValue).
11398   if (UndefElements)
11399     for (unsigned I = 0; I != NumOps; ++I)
11400       if (DemandedElts[I] && getOperand(I).isUndef())
11401         (*UndefElements)[I] = true;
11402 
11403   // Iteratively widen the sequence length looking for repetitions.
11404   for (unsigned SeqLen = 1; SeqLen < NumOps; SeqLen *= 2) {
11405     Sequence.append(SeqLen, SDValue());
11406     for (unsigned I = 0; I != NumOps; ++I) {
11407       if (!DemandedElts[I])
11408         continue;
11409       SDValue &SeqOp = Sequence[I % SeqLen];
11410       SDValue Op = getOperand(I);
11411       if (Op.isUndef()) {
11412         if (!SeqOp)
11413           SeqOp = Op;
11414         continue;
11415       }
11416       if (SeqOp && !SeqOp.isUndef() && SeqOp != Op) {
11417         Sequence.clear();
11418         break;
11419       }
11420       SeqOp = Op;
11421     }
11422     if (!Sequence.empty())
11423       return true;
11424   }
11425 
11426   assert(Sequence.empty() && "Failed to empty non-repeating sequence pattern");
11427   return false;
11428 }
11429 
11430 bool BuildVectorSDNode::getRepeatedSequence(SmallVectorImpl<SDValue> &Sequence,
11431                                             BitVector *UndefElements) const {
11432   APInt DemandedElts = APInt::getAllOnes(getNumOperands());
11433   return getRepeatedSequence(DemandedElts, Sequence, UndefElements);
11434 }
11435 
11436 ConstantSDNode *
11437 BuildVectorSDNode::getConstantSplatNode(const APInt &DemandedElts,
11438                                         BitVector *UndefElements) const {
11439   return dyn_cast_or_null<ConstantSDNode>(
11440       getSplatValue(DemandedElts, UndefElements));
11441 }
11442 
11443 ConstantSDNode *
11444 BuildVectorSDNode::getConstantSplatNode(BitVector *UndefElements) const {
11445   return dyn_cast_or_null<ConstantSDNode>(getSplatValue(UndefElements));
11446 }
11447 
11448 ConstantFPSDNode *
11449 BuildVectorSDNode::getConstantFPSplatNode(const APInt &DemandedElts,
11450                                           BitVector *UndefElements) const {
11451   return dyn_cast_or_null<ConstantFPSDNode>(
11452       getSplatValue(DemandedElts, UndefElements));
11453 }
11454 
11455 ConstantFPSDNode *
11456 BuildVectorSDNode::getConstantFPSplatNode(BitVector *UndefElements) const {
11457   return dyn_cast_or_null<ConstantFPSDNode>(getSplatValue(UndefElements));
11458 }
11459 
11460 int32_t
11461 BuildVectorSDNode::getConstantFPSplatPow2ToLog2Int(BitVector *UndefElements,
11462                                                    uint32_t BitWidth) const {
11463   if (ConstantFPSDNode *CN =
11464           dyn_cast_or_null<ConstantFPSDNode>(getSplatValue(UndefElements))) {
11465     bool IsExact;
11466     APSInt IntVal(BitWidth);
11467     const APFloat &APF = CN->getValueAPF();
11468     if (APF.convertToInteger(IntVal, APFloat::rmTowardZero, &IsExact) !=
11469             APFloat::opOK ||
11470         !IsExact)
11471       return -1;
11472 
11473     return IntVal.exactLogBase2();
11474   }
11475   return -1;
11476 }
11477 
11478 bool BuildVectorSDNode::getConstantRawBits(
11479     bool IsLittleEndian, unsigned DstEltSizeInBits,
11480     SmallVectorImpl<APInt> &RawBitElements, BitVector &UndefElements) const {
11481   // Early-out if this contains anything but Undef/Constant/ConstantFP.
11482   if (!isConstant())
11483     return false;
11484 
11485   unsigned NumSrcOps = getNumOperands();
11486   unsigned SrcEltSizeInBits = getValueType(0).getScalarSizeInBits();
11487   assert(((NumSrcOps * SrcEltSizeInBits) % DstEltSizeInBits) == 0 &&
11488          "Invalid bitcast scale");
11489 
11490   // Extract raw src bits.
11491   SmallVector<APInt> SrcBitElements(NumSrcOps,
11492                                     APInt::getNullValue(SrcEltSizeInBits));
11493   BitVector SrcUndeElements(NumSrcOps, false);
11494 
11495   for (unsigned I = 0; I != NumSrcOps; ++I) {
11496     SDValue Op = getOperand(I);
11497     if (Op.isUndef()) {
11498       SrcUndeElements.set(I);
11499       continue;
11500     }
11501     auto *CInt = dyn_cast<ConstantSDNode>(Op);
11502     auto *CFP = dyn_cast<ConstantFPSDNode>(Op);
11503     assert((CInt || CFP) && "Unknown constant");
11504     SrcBitElements[I] = CInt ? CInt->getAPIntValue().trunc(SrcEltSizeInBits)
11505                              : CFP->getValueAPF().bitcastToAPInt();
11506   }
11507 
11508   // Recast to dst width.
11509   recastRawBits(IsLittleEndian, DstEltSizeInBits, RawBitElements,
11510                 SrcBitElements, UndefElements, SrcUndeElements);
11511   return true;
11512 }
11513 
11514 void BuildVectorSDNode::recastRawBits(bool IsLittleEndian,
11515                                       unsigned DstEltSizeInBits,
11516                                       SmallVectorImpl<APInt> &DstBitElements,
11517                                       ArrayRef<APInt> SrcBitElements,
11518                                       BitVector &DstUndefElements,
11519                                       const BitVector &SrcUndefElements) {
11520   unsigned NumSrcOps = SrcBitElements.size();
11521   unsigned SrcEltSizeInBits = SrcBitElements[0].getBitWidth();
11522   assert(((NumSrcOps * SrcEltSizeInBits) % DstEltSizeInBits) == 0 &&
11523          "Invalid bitcast scale");
11524   assert(NumSrcOps == SrcUndefElements.size() &&
11525          "Vector size mismatch");
11526 
11527   unsigned NumDstOps = (NumSrcOps * SrcEltSizeInBits) / DstEltSizeInBits;
11528   DstUndefElements.clear();
11529   DstUndefElements.resize(NumDstOps, false);
11530   DstBitElements.assign(NumDstOps, APInt::getNullValue(DstEltSizeInBits));
11531 
11532   // Concatenate src elements constant bits together into dst element.
11533   if (SrcEltSizeInBits <= DstEltSizeInBits) {
11534     unsigned Scale = DstEltSizeInBits / SrcEltSizeInBits;
11535     for (unsigned I = 0; I != NumDstOps; ++I) {
11536       DstUndefElements.set(I);
11537       APInt &DstBits = DstBitElements[I];
11538       for (unsigned J = 0; J != Scale; ++J) {
11539         unsigned Idx = (I * Scale) + (IsLittleEndian ? J : (Scale - J - 1));
11540         if (SrcUndefElements[Idx])
11541           continue;
11542         DstUndefElements.reset(I);
11543         const APInt &SrcBits = SrcBitElements[Idx];
11544         assert(SrcBits.getBitWidth() == SrcEltSizeInBits &&
11545                "Illegal constant bitwidths");
11546         DstBits.insertBits(SrcBits, J * SrcEltSizeInBits);
11547       }
11548     }
11549     return;
11550   }
11551 
11552   // Split src element constant bits into dst elements.
11553   unsigned Scale = SrcEltSizeInBits / DstEltSizeInBits;
11554   for (unsigned I = 0; I != NumSrcOps; ++I) {
11555     if (SrcUndefElements[I]) {
11556       DstUndefElements.set(I * Scale, (I + 1) * Scale);
11557       continue;
11558     }
11559     const APInt &SrcBits = SrcBitElements[I];
11560     for (unsigned J = 0; J != Scale; ++J) {
11561       unsigned Idx = (I * Scale) + (IsLittleEndian ? J : (Scale - J - 1));
11562       APInt &DstBits = DstBitElements[Idx];
11563       DstBits = SrcBits.extractBits(DstEltSizeInBits, J * DstEltSizeInBits);
11564     }
11565   }
11566 }
11567 
11568 bool BuildVectorSDNode::isConstant() const {
11569   for (const SDValue &Op : op_values()) {
11570     unsigned Opc = Op.getOpcode();
11571     if (Opc != ISD::UNDEF && Opc != ISD::Constant && Opc != ISD::ConstantFP)
11572       return false;
11573   }
11574   return true;
11575 }
11576 
11577 bool ShuffleVectorSDNode::isSplatMask(const int *Mask, EVT VT) {
11578   // Find the first non-undef value in the shuffle mask.
11579   unsigned i, e;
11580   for (i = 0, e = VT.getVectorNumElements(); i != e && Mask[i] < 0; ++i)
11581     /* search */;
11582 
11583   // If all elements are undefined, this shuffle can be considered a splat
11584   // (although it should eventually get simplified away completely).
11585   if (i == e)
11586     return true;
11587 
11588   // Make sure all remaining elements are either undef or the same as the first
11589   // non-undef value.
11590   for (int Idx = Mask[i]; i != e; ++i)
11591     if (Mask[i] >= 0 && Mask[i] != Idx)
11592       return false;
11593   return true;
11594 }
11595 
11596 // Returns the SDNode if it is a constant integer BuildVector
11597 // or constant integer.
11598 SDNode *SelectionDAG::isConstantIntBuildVectorOrConstantInt(SDValue N) const {
11599   if (isa<ConstantSDNode>(N))
11600     return N.getNode();
11601   if (ISD::isBuildVectorOfConstantSDNodes(N.getNode()))
11602     return N.getNode();
11603   // Treat a GlobalAddress supporting constant offset folding as a
11604   // constant integer.
11605   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N))
11606     if (GA->getOpcode() == ISD::GlobalAddress &&
11607         TLI->isOffsetFoldingLegal(GA))
11608       return GA;
11609   if ((N.getOpcode() == ISD::SPLAT_VECTOR) &&
11610       isa<ConstantSDNode>(N.getOperand(0)))
11611     return N.getNode();
11612   return nullptr;
11613 }
11614 
11615 // Returns the SDNode if it is a constant float BuildVector
11616 // or constant float.
11617 SDNode *SelectionDAG::isConstantFPBuildVectorOrConstantFP(SDValue N) const {
11618   if (isa<ConstantFPSDNode>(N))
11619     return N.getNode();
11620 
11621   if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode()))
11622     return N.getNode();
11623 
11624   if ((N.getOpcode() == ISD::SPLAT_VECTOR) &&
11625       isa<ConstantFPSDNode>(N.getOperand(0)))
11626     return N.getNode();
11627 
11628   return nullptr;
11629 }
11630 
11631 void SelectionDAG::createOperands(SDNode *Node, ArrayRef<SDValue> Vals) {
11632   assert(!Node->OperandList && "Node already has operands");
11633   assert(SDNode::getMaxNumOperands() >= Vals.size() &&
11634          "too many operands to fit into SDNode");
11635   SDUse *Ops = OperandRecycler.allocate(
11636       ArrayRecycler<SDUse>::Capacity::get(Vals.size()), OperandAllocator);
11637 
11638   bool IsDivergent = false;
11639   for (unsigned I = 0; I != Vals.size(); ++I) {
11640     Ops[I].setUser(Node);
11641     Ops[I].setInitial(Vals[I]);
11642     if (Ops[I].Val.getValueType() != MVT::Other) // Skip Chain. It does not carry divergence.
11643       IsDivergent |= Ops[I].getNode()->isDivergent();
11644   }
11645   Node->NumOperands = Vals.size();
11646   Node->OperandList = Ops;
11647   if (!TLI->isSDNodeAlwaysUniform(Node)) {
11648     IsDivergent |= TLI->isSDNodeSourceOfDivergence(Node, FLI, DA);
11649     Node->SDNodeBits.IsDivergent = IsDivergent;
11650   }
11651   checkForCycles(Node);
11652 }
11653 
11654 SDValue SelectionDAG::getTokenFactor(const SDLoc &DL,
11655                                      SmallVectorImpl<SDValue> &Vals) {
11656   size_t Limit = SDNode::getMaxNumOperands();
11657   while (Vals.size() > Limit) {
11658     unsigned SliceIdx = Vals.size() - Limit;
11659     auto ExtractedTFs = ArrayRef<SDValue>(Vals).slice(SliceIdx, Limit);
11660     SDValue NewTF = getNode(ISD::TokenFactor, DL, MVT::Other, ExtractedTFs);
11661     Vals.erase(Vals.begin() + SliceIdx, Vals.end());
11662     Vals.emplace_back(NewTF);
11663   }
11664   return getNode(ISD::TokenFactor, DL, MVT::Other, Vals);
11665 }
11666 
11667 SDValue SelectionDAG::getNeutralElement(unsigned Opcode, const SDLoc &DL,
11668                                         EVT VT, SDNodeFlags Flags) {
11669   switch (Opcode) {
11670   default:
11671     return SDValue();
11672   case ISD::ADD:
11673   case ISD::OR:
11674   case ISD::XOR:
11675   case ISD::UMAX:
11676     return getConstant(0, DL, VT);
11677   case ISD::MUL:
11678     return getConstant(1, DL, VT);
11679   case ISD::AND:
11680   case ISD::UMIN:
11681     return getAllOnesConstant(DL, VT);
11682   case ISD::SMAX:
11683     return getConstant(APInt::getSignedMinValue(VT.getSizeInBits()), DL, VT);
11684   case ISD::SMIN:
11685     return getConstant(APInt::getSignedMaxValue(VT.getSizeInBits()), DL, VT);
11686   case ISD::FADD:
11687     return getConstantFP(-0.0, DL, VT);
11688   case ISD::FMUL:
11689     return getConstantFP(1.0, DL, VT);
11690   case ISD::FMINNUM:
11691   case ISD::FMAXNUM: {
11692     // Neutral element for fminnum is NaN, Inf or FLT_MAX, depending on FMF.
11693     const fltSemantics &Semantics = EVTToAPFloatSemantics(VT);
11694     APFloat NeutralAF = !Flags.hasNoNaNs() ? APFloat::getQNaN(Semantics) :
11695                         !Flags.hasNoInfs() ? APFloat::getInf(Semantics) :
11696                         APFloat::getLargest(Semantics);
11697     if (Opcode == ISD::FMAXNUM)
11698       NeutralAF.changeSign();
11699 
11700     return getConstantFP(NeutralAF, DL, VT);
11701   }
11702   }
11703 }
11704 
11705 #ifndef NDEBUG
11706 static void checkForCyclesHelper(const SDNode *N,
11707                                  SmallPtrSetImpl<const SDNode*> &Visited,
11708                                  SmallPtrSetImpl<const SDNode*> &Checked,
11709                                  const llvm::SelectionDAG *DAG) {
11710   // If this node has already been checked, don't check it again.
11711   if (Checked.count(N))
11712     return;
11713 
11714   // If a node has already been visited on this depth-first walk, reject it as
11715   // a cycle.
11716   if (!Visited.insert(N).second) {
11717     errs() << "Detected cycle in SelectionDAG\n";
11718     dbgs() << "Offending node:\n";
11719     N->dumprFull(DAG); dbgs() << "\n";
11720     abort();
11721   }
11722 
11723   for (const SDValue &Op : N->op_values())
11724     checkForCyclesHelper(Op.getNode(), Visited, Checked, DAG);
11725 
11726   Checked.insert(N);
11727   Visited.erase(N);
11728 }
11729 #endif
11730 
11731 void llvm::checkForCycles(const llvm::SDNode *N,
11732                           const llvm::SelectionDAG *DAG,
11733                           bool force) {
11734 #ifndef NDEBUG
11735   bool check = force;
11736 #ifdef EXPENSIVE_CHECKS
11737   check = true;
11738 #endif  // EXPENSIVE_CHECKS
11739   if (check) {
11740     assert(N && "Checking nonexistent SDNode");
11741     SmallPtrSet<const SDNode*, 32> visited;
11742     SmallPtrSet<const SDNode*, 32> checked;
11743     checkForCyclesHelper(N, visited, checked, DAG);
11744   }
11745 #endif  // !NDEBUG
11746 }
11747 
11748 void llvm::checkForCycles(const llvm::SelectionDAG *DAG, bool force) {
11749   checkForCycles(DAG->getRoot().getNode(), DAG, force);
11750 }
11751