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/BlockFrequencyInfo.h"
28 #include "llvm/Analysis/MemoryLocation.h"
29 #include "llvm/Analysis/ProfileSummaryInfo.h"
30 #include "llvm/Analysis/ValueTracking.h"
31 #include "llvm/CodeGen/Analysis.h"
32 #include "llvm/CodeGen/FunctionLoweringInfo.h"
33 #include "llvm/CodeGen/ISDOpcodes.h"
34 #include "llvm/CodeGen/MachineBasicBlock.h"
35 #include "llvm/CodeGen/MachineConstantPool.h"
36 #include "llvm/CodeGen/MachineFrameInfo.h"
37 #include "llvm/CodeGen/MachineFunction.h"
38 #include "llvm/CodeGen/MachineMemOperand.h"
39 #include "llvm/CodeGen/RuntimeLibcalls.h"
40 #include "llvm/CodeGen/SelectionDAGAddressAnalysis.h"
41 #include "llvm/CodeGen/SelectionDAGNodes.h"
42 #include "llvm/CodeGen/SelectionDAGTargetInfo.h"
43 #include "llvm/CodeGen/TargetFrameLowering.h"
44 #include "llvm/CodeGen/TargetLowering.h"
45 #include "llvm/CodeGen/TargetRegisterInfo.h"
46 #include "llvm/CodeGen/TargetSubtargetInfo.h"
47 #include "llvm/CodeGen/ValueTypes.h"
48 #include "llvm/IR/Constant.h"
49 #include "llvm/IR/Constants.h"
50 #include "llvm/IR/DataLayout.h"
51 #include "llvm/IR/DebugInfoMetadata.h"
52 #include "llvm/IR/DebugLoc.h"
53 #include "llvm/IR/DerivedTypes.h"
54 #include "llvm/IR/Function.h"
55 #include "llvm/IR/GlobalValue.h"
56 #include "llvm/IR/Metadata.h"
57 #include "llvm/IR/Type.h"
58 #include "llvm/IR/Value.h"
59 #include "llvm/Support/Casting.h"
60 #include "llvm/Support/CodeGen.h"
61 #include "llvm/Support/Compiler.h"
62 #include "llvm/Support/Debug.h"
63 #include "llvm/Support/ErrorHandling.h"
64 #include "llvm/Support/KnownBits.h"
65 #include "llvm/Support/MachineValueType.h"
66 #include "llvm/Support/ManagedStatic.h"
67 #include "llvm/Support/MathExtras.h"
68 #include "llvm/Support/Mutex.h"
69 #include "llvm/Support/raw_ostream.h"
70 #include "llvm/Target/TargetMachine.h"
71 #include "llvm/Target/TargetOptions.h"
72 #include "llvm/Transforms/Utils/SizeOpts.h"
73 #include <algorithm>
74 #include <cassert>
75 #include <cstdint>
76 #include <cstdlib>
77 #include <limits>
78 #include <set>
79 #include <string>
80 #include <utility>
81 #include <vector>
82 
83 using namespace llvm;
84 
85 /// makeVTList - Return an instance of the SDVTList struct initialized with the
86 /// specified members.
87 static SDVTList makeVTList(const EVT *VTs, unsigned NumVTs) {
88   SDVTList Res = {VTs, NumVTs};
89   return Res;
90 }
91 
92 // Default null implementations of the callbacks.
93 void SelectionDAG::DAGUpdateListener::NodeDeleted(SDNode*, SDNode*) {}
94 void SelectionDAG::DAGUpdateListener::NodeUpdated(SDNode*) {}
95 void SelectionDAG::DAGUpdateListener::NodeInserted(SDNode *) {}
96 
97 void SelectionDAG::DAGNodeDeletedListener::anchor() {}
98 
99 #define DEBUG_TYPE "selectiondag"
100 
101 static cl::opt<bool> EnableMemCpyDAGOpt("enable-memcpy-dag-opt",
102        cl::Hidden, cl::init(true),
103        cl::desc("Gang up loads and stores generated by inlining of memcpy"));
104 
105 static cl::opt<int> MaxLdStGlue("ldstmemcpy-glue-max",
106        cl::desc("Number limit for gluing ld/st of memcpy."),
107        cl::Hidden, cl::init(0));
108 
109 static void NewSDValueDbgMsg(SDValue V, StringRef Msg, SelectionDAG *G) {
110   LLVM_DEBUG(dbgs() << Msg; V.getNode()->dump(G););
111 }
112 
113 //===----------------------------------------------------------------------===//
114 //                              ConstantFPSDNode Class
115 //===----------------------------------------------------------------------===//
116 
117 /// isExactlyValue - We don't rely on operator== working on double values, as
118 /// it returns true for things that are clearly not equal, like -0.0 and 0.0.
119 /// As such, this method can be used to do an exact bit-for-bit comparison of
120 /// two floating point values.
121 bool ConstantFPSDNode::isExactlyValue(const APFloat& V) const {
122   return getValueAPF().bitwiseIsEqual(V);
123 }
124 
125 bool ConstantFPSDNode::isValueValidForType(EVT VT,
126                                            const APFloat& Val) {
127   assert(VT.isFloatingPoint() && "Can only convert between FP types");
128 
129   // convert modifies in place, so make a copy.
130   APFloat Val2 = APFloat(Val);
131   bool losesInfo;
132   (void) Val2.convert(SelectionDAG::EVTToAPFloatSemantics(VT),
133                       APFloat::rmNearestTiesToEven,
134                       &losesInfo);
135   return !losesInfo;
136 }
137 
138 //===----------------------------------------------------------------------===//
139 //                              ISD Namespace
140 //===----------------------------------------------------------------------===//
141 
142 bool ISD::isConstantSplatVector(const SDNode *N, APInt &SplatVal) {
143   if (N->getOpcode() == ISD::SPLAT_VECTOR) {
144     unsigned EltSize =
145         N->getValueType(0).getVectorElementType().getSizeInBits();
146     if (auto *Op0 = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
147       SplatVal = Op0->getAPIntValue().truncOrSelf(EltSize);
148       return true;
149     }
150     if (auto *Op0 = dyn_cast<ConstantFPSDNode>(N->getOperand(0))) {
151       SplatVal = Op0->getValueAPF().bitcastToAPInt().truncOrSelf(EltSize);
152       return true;
153     }
154   }
155 
156   auto *BV = dyn_cast<BuildVectorSDNode>(N);
157   if (!BV)
158     return false;
159 
160   APInt SplatUndef;
161   unsigned SplatBitSize;
162   bool HasUndefs;
163   unsigned EltSize = N->getValueType(0).getVectorElementType().getSizeInBits();
164   return BV->isConstantSplat(SplatVal, SplatUndef, SplatBitSize, HasUndefs,
165                              EltSize) &&
166          EltSize == SplatBitSize;
167 }
168 
169 // FIXME: AllOnes and AllZeros duplicate a lot of code. Could these be
170 // specializations of the more general isConstantSplatVector()?
171 
172 bool ISD::isConstantSplatVectorAllOnes(const SDNode *N, bool BuildVectorOnly) {
173   // Look through a bit convert.
174   while (N->getOpcode() == ISD::BITCAST)
175     N = N->getOperand(0).getNode();
176 
177   if (!BuildVectorOnly && N->getOpcode() == ISD::SPLAT_VECTOR) {
178     APInt SplatVal;
179     return isConstantSplatVector(N, SplatVal) && SplatVal.isAllOnes();
180   }
181 
182   if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
183 
184   unsigned i = 0, e = N->getNumOperands();
185 
186   // Skip over all of the undef values.
187   while (i != e && N->getOperand(i).isUndef())
188     ++i;
189 
190   // Do not accept an all-undef vector.
191   if (i == e) return false;
192 
193   // Do not accept build_vectors that aren't all constants or which have non-~0
194   // elements. We have to be a bit careful here, as the type of the constant
195   // may not be the same as the type of the vector elements due to type
196   // legalization (the elements are promoted to a legal type for the target and
197   // a vector of a type may be legal when the base element type is not).
198   // We only want to check enough bits to cover the vector elements, because
199   // we care if the resultant vector is all ones, not whether the individual
200   // constants are.
201   SDValue NotZero = N->getOperand(i);
202   unsigned EltSize = N->getValueType(0).getScalarSizeInBits();
203   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(NotZero)) {
204     if (CN->getAPIntValue().countTrailingOnes() < EltSize)
205       return false;
206   } else if (ConstantFPSDNode *CFPN = dyn_cast<ConstantFPSDNode>(NotZero)) {
207     if (CFPN->getValueAPF().bitcastToAPInt().countTrailingOnes() < EltSize)
208       return false;
209   } else
210     return false;
211 
212   // Okay, we have at least one ~0 value, check to see if the rest match or are
213   // undefs. Even with the above element type twiddling, this should be OK, as
214   // the same type legalization should have applied to all the elements.
215   for (++i; i != e; ++i)
216     if (N->getOperand(i) != NotZero && !N->getOperand(i).isUndef())
217       return false;
218   return true;
219 }
220 
221 bool ISD::isConstantSplatVectorAllZeros(const SDNode *N, bool BuildVectorOnly) {
222   // Look through a bit convert.
223   while (N->getOpcode() == ISD::BITCAST)
224     N = N->getOperand(0).getNode();
225 
226   if (!BuildVectorOnly && N->getOpcode() == ISD::SPLAT_VECTOR) {
227     APInt SplatVal;
228     return isConstantSplatVector(N, SplatVal) && SplatVal.isZero();
229   }
230 
231   if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
232 
233   bool IsAllUndef = true;
234   for (const SDValue &Op : N->op_values()) {
235     if (Op.isUndef())
236       continue;
237     IsAllUndef = false;
238     // Do not accept build_vectors that aren't all constants or which have non-0
239     // elements. We have to be a bit careful here, as the type of the constant
240     // may not be the same as the type of the vector elements due to type
241     // legalization (the elements are promoted to a legal type for the target
242     // and a vector of a type may be legal when the base element type is not).
243     // We only want to check enough bits to cover the vector elements, because
244     // we care if the resultant vector is all zeros, not whether the individual
245     // constants are.
246     unsigned EltSize = N->getValueType(0).getScalarSizeInBits();
247     if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Op)) {
248       if (CN->getAPIntValue().countTrailingZeros() < EltSize)
249         return false;
250     } else if (ConstantFPSDNode *CFPN = dyn_cast<ConstantFPSDNode>(Op)) {
251       if (CFPN->getValueAPF().bitcastToAPInt().countTrailingZeros() < EltSize)
252         return false;
253     } else
254       return false;
255   }
256 
257   // Do not accept an all-undef vector.
258   if (IsAllUndef)
259     return false;
260   return true;
261 }
262 
263 bool ISD::isBuildVectorAllOnes(const SDNode *N) {
264   return isConstantSplatVectorAllOnes(N, /*BuildVectorOnly*/ true);
265 }
266 
267 bool ISD::isBuildVectorAllZeros(const SDNode *N) {
268   return isConstantSplatVectorAllZeros(N, /*BuildVectorOnly*/ true);
269 }
270 
271 bool ISD::isBuildVectorOfConstantSDNodes(const SDNode *N) {
272   if (N->getOpcode() != ISD::BUILD_VECTOR)
273     return false;
274 
275   for (const SDValue &Op : N->op_values()) {
276     if (Op.isUndef())
277       continue;
278     if (!isa<ConstantSDNode>(Op))
279       return false;
280   }
281   return true;
282 }
283 
284 bool ISD::isBuildVectorOfConstantFPSDNodes(const SDNode *N) {
285   if (N->getOpcode() != ISD::BUILD_VECTOR)
286     return false;
287 
288   for (const SDValue &Op : N->op_values()) {
289     if (Op.isUndef())
290       continue;
291     if (!isa<ConstantFPSDNode>(Op))
292       return false;
293   }
294   return true;
295 }
296 
297 bool ISD::allOperandsUndef(const SDNode *N) {
298   // Return false if the node has no operands.
299   // This is "logically inconsistent" with the definition of "all" but
300   // is probably the desired behavior.
301   if (N->getNumOperands() == 0)
302     return false;
303   return all_of(N->op_values(), [](SDValue Op) { return Op.isUndef(); });
304 }
305 
306 bool ISD::matchUnaryPredicate(SDValue Op,
307                               std::function<bool(ConstantSDNode *)> Match,
308                               bool AllowUndefs) {
309   // FIXME: Add support for scalar UNDEF cases?
310   if (auto *Cst = dyn_cast<ConstantSDNode>(Op))
311     return Match(Cst);
312 
313   // FIXME: Add support for vector UNDEF cases?
314   if (ISD::BUILD_VECTOR != Op.getOpcode() &&
315       ISD::SPLAT_VECTOR != Op.getOpcode())
316     return false;
317 
318   EVT SVT = Op.getValueType().getScalarType();
319   for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
320     if (AllowUndefs && Op.getOperand(i).isUndef()) {
321       if (!Match(nullptr))
322         return false;
323       continue;
324     }
325 
326     auto *Cst = dyn_cast<ConstantSDNode>(Op.getOperand(i));
327     if (!Cst || Cst->getValueType(0) != SVT || !Match(Cst))
328       return false;
329   }
330   return true;
331 }
332 
333 bool ISD::matchBinaryPredicate(
334     SDValue LHS, SDValue RHS,
335     std::function<bool(ConstantSDNode *, ConstantSDNode *)> Match,
336     bool AllowUndefs, bool AllowTypeMismatch) {
337   if (!AllowTypeMismatch && LHS.getValueType() != RHS.getValueType())
338     return false;
339 
340   // TODO: Add support for scalar UNDEF cases?
341   if (auto *LHSCst = dyn_cast<ConstantSDNode>(LHS))
342     if (auto *RHSCst = dyn_cast<ConstantSDNode>(RHS))
343       return Match(LHSCst, RHSCst);
344 
345   // TODO: Add support for vector UNDEF cases?
346   if (LHS.getOpcode() != RHS.getOpcode() ||
347       (LHS.getOpcode() != ISD::BUILD_VECTOR &&
348        LHS.getOpcode() != ISD::SPLAT_VECTOR))
349     return false;
350 
351   EVT SVT = LHS.getValueType().getScalarType();
352   for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
353     SDValue LHSOp = LHS.getOperand(i);
354     SDValue RHSOp = RHS.getOperand(i);
355     bool LHSUndef = AllowUndefs && LHSOp.isUndef();
356     bool RHSUndef = AllowUndefs && RHSOp.isUndef();
357     auto *LHSCst = dyn_cast<ConstantSDNode>(LHSOp);
358     auto *RHSCst = dyn_cast<ConstantSDNode>(RHSOp);
359     if ((!LHSCst && !LHSUndef) || (!RHSCst && !RHSUndef))
360       return false;
361     if (!AllowTypeMismatch && (LHSOp.getValueType() != SVT ||
362                                LHSOp.getValueType() != RHSOp.getValueType()))
363       return false;
364     if (!Match(LHSCst, RHSCst))
365       return false;
366   }
367   return true;
368 }
369 
370 ISD::NodeType ISD::getVecReduceBaseOpcode(unsigned VecReduceOpcode) {
371   switch (VecReduceOpcode) {
372   default:
373     llvm_unreachable("Expected VECREDUCE opcode");
374   case ISD::VECREDUCE_FADD:
375   case ISD::VECREDUCE_SEQ_FADD:
376   case ISD::VP_REDUCE_FADD:
377   case ISD::VP_REDUCE_SEQ_FADD:
378     return ISD::FADD;
379   case ISD::VECREDUCE_FMUL:
380   case ISD::VECREDUCE_SEQ_FMUL:
381   case ISD::VP_REDUCE_FMUL:
382   case ISD::VP_REDUCE_SEQ_FMUL:
383     return ISD::FMUL;
384   case ISD::VECREDUCE_ADD:
385   case ISD::VP_REDUCE_ADD:
386     return ISD::ADD;
387   case ISD::VECREDUCE_MUL:
388   case ISD::VP_REDUCE_MUL:
389     return ISD::MUL;
390   case ISD::VECREDUCE_AND:
391   case ISD::VP_REDUCE_AND:
392     return ISD::AND;
393   case ISD::VECREDUCE_OR:
394   case ISD::VP_REDUCE_OR:
395     return ISD::OR;
396   case ISD::VECREDUCE_XOR:
397   case ISD::VP_REDUCE_XOR:
398     return ISD::XOR;
399   case ISD::VECREDUCE_SMAX:
400   case ISD::VP_REDUCE_SMAX:
401     return ISD::SMAX;
402   case ISD::VECREDUCE_SMIN:
403   case ISD::VP_REDUCE_SMIN:
404     return ISD::SMIN;
405   case ISD::VECREDUCE_UMAX:
406   case ISD::VP_REDUCE_UMAX:
407     return ISD::UMAX;
408   case ISD::VECREDUCE_UMIN:
409   case ISD::VP_REDUCE_UMIN:
410     return ISD::UMIN;
411   case ISD::VECREDUCE_FMAX:
412   case ISD::VP_REDUCE_FMAX:
413     return ISD::FMAXNUM;
414   case ISD::VECREDUCE_FMIN:
415   case ISD::VP_REDUCE_FMIN:
416     return ISD::FMINNUM;
417   }
418 }
419 
420 bool ISD::isVPOpcode(unsigned Opcode) {
421   switch (Opcode) {
422   default:
423     return false;
424 #define BEGIN_REGISTER_VP_SDNODE(VPSD, ...)                                    \
425   case ISD::VPSD:                                                              \
426     return true;
427 #include "llvm/IR/VPIntrinsics.def"
428   }
429 }
430 
431 bool ISD::isVPBinaryOp(unsigned Opcode) {
432   switch (Opcode) {
433   default:
434     break;
435 #define BEGIN_REGISTER_VP_SDNODE(VPSD, ...) case ISD::VPSD:
436 #define VP_PROPERTY_BINARYOP return true;
437 #define END_REGISTER_VP_SDNODE(VPSD) break;
438 #include "llvm/IR/VPIntrinsics.def"
439   }
440   return false;
441 }
442 
443 bool ISD::isVPReduction(unsigned Opcode) {
444   switch (Opcode) {
445   default:
446     break;
447 #define BEGIN_REGISTER_VP_SDNODE(VPSD, ...) case ISD::VPSD:
448 #define VP_PROPERTY_REDUCTION(STARTPOS, ...) return true;
449 #define END_REGISTER_VP_SDNODE(VPSD) break;
450 #include "llvm/IR/VPIntrinsics.def"
451   }
452   return false;
453 }
454 
455 /// The operand position of the vector mask.
456 Optional<unsigned> ISD::getVPMaskIdx(unsigned Opcode) {
457   switch (Opcode) {
458   default:
459     return None;
460 #define BEGIN_REGISTER_VP_SDNODE(VPSD, LEGALPOS, TDNAME, MASKPOS, ...)         \
461   case ISD::VPSD:                                                              \
462     return MASKPOS;
463 #include "llvm/IR/VPIntrinsics.def"
464   }
465 }
466 
467 /// The operand position of the explicit vector length parameter.
468 Optional<unsigned> ISD::getVPExplicitVectorLengthIdx(unsigned Opcode) {
469   switch (Opcode) {
470   default:
471     return None;
472 #define BEGIN_REGISTER_VP_SDNODE(VPSD, LEGALPOS, TDNAME, MASKPOS, EVLPOS)      \
473   case ISD::VPSD:                                                              \
474     return EVLPOS;
475 #include "llvm/IR/VPIntrinsics.def"
476   }
477 }
478 
479 ISD::NodeType ISD::getExtForLoadExtType(bool IsFP, ISD::LoadExtType ExtType) {
480   switch (ExtType) {
481   case ISD::EXTLOAD:
482     return IsFP ? ISD::FP_EXTEND : ISD::ANY_EXTEND;
483   case ISD::SEXTLOAD:
484     return ISD::SIGN_EXTEND;
485   case ISD::ZEXTLOAD:
486     return ISD::ZERO_EXTEND;
487   default:
488     break;
489   }
490 
491   llvm_unreachable("Invalid LoadExtType");
492 }
493 
494 ISD::CondCode ISD::getSetCCSwappedOperands(ISD::CondCode Operation) {
495   // To perform this operation, we just need to swap the L and G bits of the
496   // operation.
497   unsigned OldL = (Operation >> 2) & 1;
498   unsigned OldG = (Operation >> 1) & 1;
499   return ISD::CondCode((Operation & ~6) |  // Keep the N, U, E bits
500                        (OldL << 1) |       // New G bit
501                        (OldG << 2));       // New L bit.
502 }
503 
504 static ISD::CondCode getSetCCInverseImpl(ISD::CondCode Op, bool isIntegerLike) {
505   unsigned Operation = Op;
506   if (isIntegerLike)
507     Operation ^= 7;   // Flip L, G, E bits, but not U.
508   else
509     Operation ^= 15;  // Flip all of the condition bits.
510 
511   if (Operation > ISD::SETTRUE2)
512     Operation &= ~8;  // Don't let N and U bits get set.
513 
514   return ISD::CondCode(Operation);
515 }
516 
517 ISD::CondCode ISD::getSetCCInverse(ISD::CondCode Op, EVT Type) {
518   return getSetCCInverseImpl(Op, Type.isInteger());
519 }
520 
521 ISD::CondCode ISD::GlobalISel::getSetCCInverse(ISD::CondCode Op,
522                                                bool isIntegerLike) {
523   return getSetCCInverseImpl(Op, isIntegerLike);
524 }
525 
526 /// For an integer comparison, return 1 if the comparison is a signed operation
527 /// and 2 if the result is an unsigned comparison. Return zero if the operation
528 /// does not depend on the sign of the input (setne and seteq).
529 static int isSignedOp(ISD::CondCode Opcode) {
530   switch (Opcode) {
531   default: llvm_unreachable("Illegal integer setcc operation!");
532   case ISD::SETEQ:
533   case ISD::SETNE: return 0;
534   case ISD::SETLT:
535   case ISD::SETLE:
536   case ISD::SETGT:
537   case ISD::SETGE: return 1;
538   case ISD::SETULT:
539   case ISD::SETULE:
540   case ISD::SETUGT:
541   case ISD::SETUGE: return 2;
542   }
543 }
544 
545 ISD::CondCode ISD::getSetCCOrOperation(ISD::CondCode Op1, ISD::CondCode Op2,
546                                        EVT Type) {
547   bool IsInteger = Type.isInteger();
548   if (IsInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
549     // Cannot fold a signed integer setcc with an unsigned integer setcc.
550     return ISD::SETCC_INVALID;
551 
552   unsigned Op = Op1 | Op2;  // Combine all of the condition bits.
553 
554   // If the N and U bits get set, then the resultant comparison DOES suddenly
555   // care about orderedness, and it is true when ordered.
556   if (Op > ISD::SETTRUE2)
557     Op &= ~16;     // Clear the U bit if the N bit is set.
558 
559   // Canonicalize illegal integer setcc's.
560   if (IsInteger && Op == ISD::SETUNE)  // e.g. SETUGT | SETULT
561     Op = ISD::SETNE;
562 
563   return ISD::CondCode(Op);
564 }
565 
566 ISD::CondCode ISD::getSetCCAndOperation(ISD::CondCode Op1, ISD::CondCode Op2,
567                                         EVT Type) {
568   bool IsInteger = Type.isInteger();
569   if (IsInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
570     // Cannot fold a signed setcc with an unsigned setcc.
571     return ISD::SETCC_INVALID;
572 
573   // Combine all of the condition bits.
574   ISD::CondCode Result = ISD::CondCode(Op1 & Op2);
575 
576   // Canonicalize illegal integer setcc's.
577   if (IsInteger) {
578     switch (Result) {
579     default: break;
580     case ISD::SETUO : Result = ISD::SETFALSE; break;  // SETUGT & SETULT
581     case ISD::SETOEQ:                                 // SETEQ  & SETU[LG]E
582     case ISD::SETUEQ: Result = ISD::SETEQ   ; break;  // SETUGE & SETULE
583     case ISD::SETOLT: Result = ISD::SETULT  ; break;  // SETULT & SETNE
584     case ISD::SETOGT: Result = ISD::SETUGT  ; break;  // SETUGT & SETNE
585     }
586   }
587 
588   return Result;
589 }
590 
591 //===----------------------------------------------------------------------===//
592 //                           SDNode Profile Support
593 //===----------------------------------------------------------------------===//
594 
595 /// AddNodeIDOpcode - Add the node opcode to the NodeID data.
596 static void AddNodeIDOpcode(FoldingSetNodeID &ID, unsigned OpC)  {
597   ID.AddInteger(OpC);
598 }
599 
600 /// AddNodeIDValueTypes - Value type lists are intern'd so we can represent them
601 /// solely with their pointer.
602 static void AddNodeIDValueTypes(FoldingSetNodeID &ID, SDVTList VTList) {
603   ID.AddPointer(VTList.VTs);
604 }
605 
606 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data.
607 static void AddNodeIDOperands(FoldingSetNodeID &ID,
608                               ArrayRef<SDValue> Ops) {
609   for (auto& Op : Ops) {
610     ID.AddPointer(Op.getNode());
611     ID.AddInteger(Op.getResNo());
612   }
613 }
614 
615 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data.
616 static void AddNodeIDOperands(FoldingSetNodeID &ID,
617                               ArrayRef<SDUse> Ops) {
618   for (auto& Op : Ops) {
619     ID.AddPointer(Op.getNode());
620     ID.AddInteger(Op.getResNo());
621   }
622 }
623 
624 static void AddNodeIDNode(FoldingSetNodeID &ID, unsigned short OpC,
625                           SDVTList VTList, ArrayRef<SDValue> OpList) {
626   AddNodeIDOpcode(ID, OpC);
627   AddNodeIDValueTypes(ID, VTList);
628   AddNodeIDOperands(ID, OpList);
629 }
630 
631 /// If this is an SDNode with special info, add this info to the NodeID data.
632 static void AddNodeIDCustom(FoldingSetNodeID &ID, const SDNode *N) {
633   switch (N->getOpcode()) {
634   case ISD::TargetExternalSymbol:
635   case ISD::ExternalSymbol:
636   case ISD::MCSymbol:
637     llvm_unreachable("Should only be used on nodes with operands");
638   default: break;  // Normal nodes don't need extra info.
639   case ISD::TargetConstant:
640   case ISD::Constant: {
641     const ConstantSDNode *C = cast<ConstantSDNode>(N);
642     ID.AddPointer(C->getConstantIntValue());
643     ID.AddBoolean(C->isOpaque());
644     break;
645   }
646   case ISD::TargetConstantFP:
647   case ISD::ConstantFP:
648     ID.AddPointer(cast<ConstantFPSDNode>(N)->getConstantFPValue());
649     break;
650   case ISD::TargetGlobalAddress:
651   case ISD::GlobalAddress:
652   case ISD::TargetGlobalTLSAddress:
653   case ISD::GlobalTLSAddress: {
654     const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(N);
655     ID.AddPointer(GA->getGlobal());
656     ID.AddInteger(GA->getOffset());
657     ID.AddInteger(GA->getTargetFlags());
658     break;
659   }
660   case ISD::BasicBlock:
661     ID.AddPointer(cast<BasicBlockSDNode>(N)->getBasicBlock());
662     break;
663   case ISD::Register:
664     ID.AddInteger(cast<RegisterSDNode>(N)->getReg());
665     break;
666   case ISD::RegisterMask:
667     ID.AddPointer(cast<RegisterMaskSDNode>(N)->getRegMask());
668     break;
669   case ISD::SRCVALUE:
670     ID.AddPointer(cast<SrcValueSDNode>(N)->getValue());
671     break;
672   case ISD::FrameIndex:
673   case ISD::TargetFrameIndex:
674     ID.AddInteger(cast<FrameIndexSDNode>(N)->getIndex());
675     break;
676   case ISD::LIFETIME_START:
677   case ISD::LIFETIME_END:
678     if (cast<LifetimeSDNode>(N)->hasOffset()) {
679       ID.AddInteger(cast<LifetimeSDNode>(N)->getSize());
680       ID.AddInteger(cast<LifetimeSDNode>(N)->getOffset());
681     }
682     break;
683   case ISD::PSEUDO_PROBE:
684     ID.AddInteger(cast<PseudoProbeSDNode>(N)->getGuid());
685     ID.AddInteger(cast<PseudoProbeSDNode>(N)->getIndex());
686     ID.AddInteger(cast<PseudoProbeSDNode>(N)->getAttributes());
687     break;
688   case ISD::JumpTable:
689   case ISD::TargetJumpTable:
690     ID.AddInteger(cast<JumpTableSDNode>(N)->getIndex());
691     ID.AddInteger(cast<JumpTableSDNode>(N)->getTargetFlags());
692     break;
693   case ISD::ConstantPool:
694   case ISD::TargetConstantPool: {
695     const ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(N);
696     ID.AddInteger(CP->getAlign().value());
697     ID.AddInteger(CP->getOffset());
698     if (CP->isMachineConstantPoolEntry())
699       CP->getMachineCPVal()->addSelectionDAGCSEId(ID);
700     else
701       ID.AddPointer(CP->getConstVal());
702     ID.AddInteger(CP->getTargetFlags());
703     break;
704   }
705   case ISD::TargetIndex: {
706     const TargetIndexSDNode *TI = cast<TargetIndexSDNode>(N);
707     ID.AddInteger(TI->getIndex());
708     ID.AddInteger(TI->getOffset());
709     ID.AddInteger(TI->getTargetFlags());
710     break;
711   }
712   case ISD::LOAD: {
713     const LoadSDNode *LD = cast<LoadSDNode>(N);
714     ID.AddInteger(LD->getMemoryVT().getRawBits());
715     ID.AddInteger(LD->getRawSubclassData());
716     ID.AddInteger(LD->getPointerInfo().getAddrSpace());
717     ID.AddInteger(LD->getMemOperand()->getFlags());
718     break;
719   }
720   case ISD::STORE: {
721     const StoreSDNode *ST = cast<StoreSDNode>(N);
722     ID.AddInteger(ST->getMemoryVT().getRawBits());
723     ID.AddInteger(ST->getRawSubclassData());
724     ID.AddInteger(ST->getPointerInfo().getAddrSpace());
725     ID.AddInteger(ST->getMemOperand()->getFlags());
726     break;
727   }
728   case ISD::VP_LOAD: {
729     const VPLoadSDNode *ELD = cast<VPLoadSDNode>(N);
730     ID.AddInteger(ELD->getMemoryVT().getRawBits());
731     ID.AddInteger(ELD->getRawSubclassData());
732     ID.AddInteger(ELD->getPointerInfo().getAddrSpace());
733     ID.AddInteger(ELD->getMemOperand()->getFlags());
734     break;
735   }
736   case ISD::VP_STORE: {
737     const VPStoreSDNode *EST = cast<VPStoreSDNode>(N);
738     ID.AddInteger(EST->getMemoryVT().getRawBits());
739     ID.AddInteger(EST->getRawSubclassData());
740     ID.AddInteger(EST->getPointerInfo().getAddrSpace());
741     ID.AddInteger(EST->getMemOperand()->getFlags());
742     break;
743   }
744   case ISD::VP_GATHER: {
745     const VPGatherSDNode *EG = cast<VPGatherSDNode>(N);
746     ID.AddInteger(EG->getMemoryVT().getRawBits());
747     ID.AddInteger(EG->getRawSubclassData());
748     ID.AddInteger(EG->getPointerInfo().getAddrSpace());
749     ID.AddInteger(EG->getMemOperand()->getFlags());
750     break;
751   }
752   case ISD::VP_SCATTER: {
753     const VPScatterSDNode *ES = cast<VPScatterSDNode>(N);
754     ID.AddInteger(ES->getMemoryVT().getRawBits());
755     ID.AddInteger(ES->getRawSubclassData());
756     ID.AddInteger(ES->getPointerInfo().getAddrSpace());
757     ID.AddInteger(ES->getMemOperand()->getFlags());
758     break;
759   }
760   case ISD::MLOAD: {
761     const MaskedLoadSDNode *MLD = cast<MaskedLoadSDNode>(N);
762     ID.AddInteger(MLD->getMemoryVT().getRawBits());
763     ID.AddInteger(MLD->getRawSubclassData());
764     ID.AddInteger(MLD->getPointerInfo().getAddrSpace());
765     ID.AddInteger(MLD->getMemOperand()->getFlags());
766     break;
767   }
768   case ISD::MSTORE: {
769     const MaskedStoreSDNode *MST = cast<MaskedStoreSDNode>(N);
770     ID.AddInteger(MST->getMemoryVT().getRawBits());
771     ID.AddInteger(MST->getRawSubclassData());
772     ID.AddInteger(MST->getPointerInfo().getAddrSpace());
773     ID.AddInteger(MST->getMemOperand()->getFlags());
774     break;
775   }
776   case ISD::MGATHER: {
777     const MaskedGatherSDNode *MG = cast<MaskedGatherSDNode>(N);
778     ID.AddInteger(MG->getMemoryVT().getRawBits());
779     ID.AddInteger(MG->getRawSubclassData());
780     ID.AddInteger(MG->getPointerInfo().getAddrSpace());
781     ID.AddInteger(MG->getMemOperand()->getFlags());
782     break;
783   }
784   case ISD::MSCATTER: {
785     const MaskedScatterSDNode *MS = cast<MaskedScatterSDNode>(N);
786     ID.AddInteger(MS->getMemoryVT().getRawBits());
787     ID.AddInteger(MS->getRawSubclassData());
788     ID.AddInteger(MS->getPointerInfo().getAddrSpace());
789     ID.AddInteger(MS->getMemOperand()->getFlags());
790     break;
791   }
792   case ISD::ATOMIC_CMP_SWAP:
793   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
794   case ISD::ATOMIC_SWAP:
795   case ISD::ATOMIC_LOAD_ADD:
796   case ISD::ATOMIC_LOAD_SUB:
797   case ISD::ATOMIC_LOAD_AND:
798   case ISD::ATOMIC_LOAD_CLR:
799   case ISD::ATOMIC_LOAD_OR:
800   case ISD::ATOMIC_LOAD_XOR:
801   case ISD::ATOMIC_LOAD_NAND:
802   case ISD::ATOMIC_LOAD_MIN:
803   case ISD::ATOMIC_LOAD_MAX:
804   case ISD::ATOMIC_LOAD_UMIN:
805   case ISD::ATOMIC_LOAD_UMAX:
806   case ISD::ATOMIC_LOAD:
807   case ISD::ATOMIC_STORE: {
808     const AtomicSDNode *AT = cast<AtomicSDNode>(N);
809     ID.AddInteger(AT->getMemoryVT().getRawBits());
810     ID.AddInteger(AT->getRawSubclassData());
811     ID.AddInteger(AT->getPointerInfo().getAddrSpace());
812     ID.AddInteger(AT->getMemOperand()->getFlags());
813     break;
814   }
815   case ISD::PREFETCH: {
816     const MemSDNode *PF = cast<MemSDNode>(N);
817     ID.AddInteger(PF->getPointerInfo().getAddrSpace());
818     ID.AddInteger(PF->getMemOperand()->getFlags());
819     break;
820   }
821   case ISD::VECTOR_SHUFFLE: {
822     const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
823     for (unsigned i = 0, e = N->getValueType(0).getVectorNumElements();
824          i != e; ++i)
825       ID.AddInteger(SVN->getMaskElt(i));
826     break;
827   }
828   case ISD::TargetBlockAddress:
829   case ISD::BlockAddress: {
830     const BlockAddressSDNode *BA = cast<BlockAddressSDNode>(N);
831     ID.AddPointer(BA->getBlockAddress());
832     ID.AddInteger(BA->getOffset());
833     ID.AddInteger(BA->getTargetFlags());
834     break;
835   }
836   } // end switch (N->getOpcode())
837 
838   // Target specific memory nodes could also have address spaces and flags
839   // to check.
840   if (N->isTargetMemoryOpcode()) {
841     const MemSDNode *MN = cast<MemSDNode>(N);
842     ID.AddInteger(MN->getPointerInfo().getAddrSpace());
843     ID.AddInteger(MN->getMemOperand()->getFlags());
844   }
845 }
846 
847 /// AddNodeIDNode - Generic routine for adding a nodes info to the NodeID
848 /// data.
849 static void AddNodeIDNode(FoldingSetNodeID &ID, const SDNode *N) {
850   AddNodeIDOpcode(ID, N->getOpcode());
851   // Add the return value info.
852   AddNodeIDValueTypes(ID, N->getVTList());
853   // Add the operand info.
854   AddNodeIDOperands(ID, N->ops());
855 
856   // Handle SDNode leafs with special info.
857   AddNodeIDCustom(ID, N);
858 }
859 
860 //===----------------------------------------------------------------------===//
861 //                              SelectionDAG Class
862 //===----------------------------------------------------------------------===//
863 
864 /// doNotCSE - Return true if CSE should not be performed for this node.
865 static bool doNotCSE(SDNode *N) {
866   if (N->getValueType(0) == MVT::Glue)
867     return true; // Never CSE anything that produces a flag.
868 
869   switch (N->getOpcode()) {
870   default: break;
871   case ISD::HANDLENODE:
872   case ISD::EH_LABEL:
873     return true;   // Never CSE these nodes.
874   }
875 
876   // Check that remaining values produced are not flags.
877   for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
878     if (N->getValueType(i) == MVT::Glue)
879       return true; // Never CSE anything that produces a flag.
880 
881   return false;
882 }
883 
884 /// RemoveDeadNodes - This method deletes all unreachable nodes in the
885 /// SelectionDAG.
886 void SelectionDAG::RemoveDeadNodes() {
887   // Create a dummy node (which is not added to allnodes), that adds a reference
888   // to the root node, preventing it from being deleted.
889   HandleSDNode Dummy(getRoot());
890 
891   SmallVector<SDNode*, 128> DeadNodes;
892 
893   // Add all obviously-dead nodes to the DeadNodes worklist.
894   for (SDNode &Node : allnodes())
895     if (Node.use_empty())
896       DeadNodes.push_back(&Node);
897 
898   RemoveDeadNodes(DeadNodes);
899 
900   // If the root changed (e.g. it was a dead load, update the root).
901   setRoot(Dummy.getValue());
902 }
903 
904 /// RemoveDeadNodes - This method deletes the unreachable nodes in the
905 /// given list, and any nodes that become unreachable as a result.
906 void SelectionDAG::RemoveDeadNodes(SmallVectorImpl<SDNode *> &DeadNodes) {
907 
908   // Process the worklist, deleting the nodes and adding their uses to the
909   // worklist.
910   while (!DeadNodes.empty()) {
911     SDNode *N = DeadNodes.pop_back_val();
912     // Skip to next node if we've already managed to delete the node. This could
913     // happen if replacing a node causes a node previously added to the node to
914     // be deleted.
915     if (N->getOpcode() == ISD::DELETED_NODE)
916       continue;
917 
918     for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
919       DUL->NodeDeleted(N, nullptr);
920 
921     // Take the node out of the appropriate CSE map.
922     RemoveNodeFromCSEMaps(N);
923 
924     // Next, brutally remove the operand list.  This is safe to do, as there are
925     // no cycles in the graph.
926     for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) {
927       SDUse &Use = *I++;
928       SDNode *Operand = Use.getNode();
929       Use.set(SDValue());
930 
931       // Now that we removed this operand, see if there are no uses of it left.
932       if (Operand->use_empty())
933         DeadNodes.push_back(Operand);
934     }
935 
936     DeallocateNode(N);
937   }
938 }
939 
940 void SelectionDAG::RemoveDeadNode(SDNode *N){
941   SmallVector<SDNode*, 16> DeadNodes(1, N);
942 
943   // Create a dummy node that adds a reference to the root node, preventing
944   // it from being deleted.  (This matters if the root is an operand of the
945   // dead node.)
946   HandleSDNode Dummy(getRoot());
947 
948   RemoveDeadNodes(DeadNodes);
949 }
950 
951 void SelectionDAG::DeleteNode(SDNode *N) {
952   // First take this out of the appropriate CSE map.
953   RemoveNodeFromCSEMaps(N);
954 
955   // Finally, remove uses due to operands of this node, remove from the
956   // AllNodes list, and delete the node.
957   DeleteNodeNotInCSEMaps(N);
958 }
959 
960 void SelectionDAG::DeleteNodeNotInCSEMaps(SDNode *N) {
961   assert(N->getIterator() != AllNodes.begin() &&
962          "Cannot delete the entry node!");
963   assert(N->use_empty() && "Cannot delete a node that is not dead!");
964 
965   // Drop all of the operands and decrement used node's use counts.
966   N->DropOperands();
967 
968   DeallocateNode(N);
969 }
970 
971 void SDDbgInfo::add(SDDbgValue *V, bool isParameter) {
972   assert(!(V->isVariadic() && isParameter));
973   if (isParameter)
974     ByvalParmDbgValues.push_back(V);
975   else
976     DbgValues.push_back(V);
977   for (const SDNode *Node : V->getSDNodes())
978     if (Node)
979       DbgValMap[Node].push_back(V);
980 }
981 
982 void SDDbgInfo::erase(const SDNode *Node) {
983   DbgValMapType::iterator I = DbgValMap.find(Node);
984   if (I == DbgValMap.end())
985     return;
986   for (auto &Val: I->second)
987     Val->setIsInvalidated();
988   DbgValMap.erase(I);
989 }
990 
991 void SelectionDAG::DeallocateNode(SDNode *N) {
992   // If we have operands, deallocate them.
993   removeOperands(N);
994 
995   NodeAllocator.Deallocate(AllNodes.remove(N));
996 
997   // Set the opcode to DELETED_NODE to help catch bugs when node
998   // memory is reallocated.
999   // FIXME: There are places in SDag that have grown a dependency on the opcode
1000   // value in the released node.
1001   __asan_unpoison_memory_region(&N->NodeType, sizeof(N->NodeType));
1002   N->NodeType = ISD::DELETED_NODE;
1003 
1004   // If any of the SDDbgValue nodes refer to this SDNode, invalidate
1005   // them and forget about that node.
1006   DbgInfo->erase(N);
1007 }
1008 
1009 #ifndef NDEBUG
1010 /// VerifySDNode - Check the given SDNode.  Aborts if it is invalid.
1011 static void VerifySDNode(SDNode *N) {
1012   switch (N->getOpcode()) {
1013   default:
1014     break;
1015   case ISD::BUILD_PAIR: {
1016     EVT VT = N->getValueType(0);
1017     assert(N->getNumValues() == 1 && "Too many results!");
1018     assert(!VT.isVector() && (VT.isInteger() || VT.isFloatingPoint()) &&
1019            "Wrong return type!");
1020     assert(N->getNumOperands() == 2 && "Wrong number of operands!");
1021     assert(N->getOperand(0).getValueType() == N->getOperand(1).getValueType() &&
1022            "Mismatched operand types!");
1023     assert(N->getOperand(0).getValueType().isInteger() == VT.isInteger() &&
1024            "Wrong operand type!");
1025     assert(VT.getSizeInBits() == 2 * N->getOperand(0).getValueSizeInBits() &&
1026            "Wrong return type size");
1027     break;
1028   }
1029   case ISD::BUILD_VECTOR: {
1030     assert(N->getNumValues() == 1 && "Too many results!");
1031     assert(N->getValueType(0).isVector() && "Wrong return type!");
1032     assert(N->getNumOperands() == N->getValueType(0).getVectorNumElements() &&
1033            "Wrong number of operands!");
1034     EVT EltVT = N->getValueType(0).getVectorElementType();
1035     for (const SDUse &Op : N->ops()) {
1036       assert((Op.getValueType() == EltVT ||
1037               (EltVT.isInteger() && Op.getValueType().isInteger() &&
1038                EltVT.bitsLE(Op.getValueType()))) &&
1039              "Wrong operand type!");
1040       assert(Op.getValueType() == N->getOperand(0).getValueType() &&
1041              "Operands must all have the same type");
1042     }
1043     break;
1044   }
1045   }
1046 }
1047 #endif // NDEBUG
1048 
1049 /// Insert a newly allocated node into the DAG.
1050 ///
1051 /// Handles insertion into the all nodes list and CSE map, as well as
1052 /// verification and other common operations when a new node is allocated.
1053 void SelectionDAG::InsertNode(SDNode *N) {
1054   AllNodes.push_back(N);
1055 #ifndef NDEBUG
1056   N->PersistentId = NextPersistentId++;
1057   VerifySDNode(N);
1058 #endif
1059   for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
1060     DUL->NodeInserted(N);
1061 }
1062 
1063 /// RemoveNodeFromCSEMaps - Take the specified node out of the CSE map that
1064 /// correspond to it.  This is useful when we're about to delete or repurpose
1065 /// the node.  We don't want future request for structurally identical nodes
1066 /// to return N anymore.
1067 bool SelectionDAG::RemoveNodeFromCSEMaps(SDNode *N) {
1068   bool Erased = false;
1069   switch (N->getOpcode()) {
1070   case ISD::HANDLENODE: return false;  // noop.
1071   case ISD::CONDCODE:
1072     assert(CondCodeNodes[cast<CondCodeSDNode>(N)->get()] &&
1073            "Cond code doesn't exist!");
1074     Erased = CondCodeNodes[cast<CondCodeSDNode>(N)->get()] != nullptr;
1075     CondCodeNodes[cast<CondCodeSDNode>(N)->get()] = nullptr;
1076     break;
1077   case ISD::ExternalSymbol:
1078     Erased = ExternalSymbols.erase(cast<ExternalSymbolSDNode>(N)->getSymbol());
1079     break;
1080   case ISD::TargetExternalSymbol: {
1081     ExternalSymbolSDNode *ESN = cast<ExternalSymbolSDNode>(N);
1082     Erased = TargetExternalSymbols.erase(std::pair<std::string, unsigned>(
1083         ESN->getSymbol(), ESN->getTargetFlags()));
1084     break;
1085   }
1086   case ISD::MCSymbol: {
1087     auto *MCSN = cast<MCSymbolSDNode>(N);
1088     Erased = MCSymbols.erase(MCSN->getMCSymbol());
1089     break;
1090   }
1091   case ISD::VALUETYPE: {
1092     EVT VT = cast<VTSDNode>(N)->getVT();
1093     if (VT.isExtended()) {
1094       Erased = ExtendedValueTypeNodes.erase(VT);
1095     } else {
1096       Erased = ValueTypeNodes[VT.getSimpleVT().SimpleTy] != nullptr;
1097       ValueTypeNodes[VT.getSimpleVT().SimpleTy] = nullptr;
1098     }
1099     break;
1100   }
1101   default:
1102     // Remove it from the CSE Map.
1103     assert(N->getOpcode() != ISD::DELETED_NODE && "DELETED_NODE in CSEMap!");
1104     assert(N->getOpcode() != ISD::EntryToken && "EntryToken in CSEMap!");
1105     Erased = CSEMap.RemoveNode(N);
1106     break;
1107   }
1108 #ifndef NDEBUG
1109   // Verify that the node was actually in one of the CSE maps, unless it has a
1110   // flag result (which cannot be CSE'd) or is one of the special cases that are
1111   // not subject to CSE.
1112   if (!Erased && N->getValueType(N->getNumValues()-1) != MVT::Glue &&
1113       !N->isMachineOpcode() && !doNotCSE(N)) {
1114     N->dump(this);
1115     dbgs() << "\n";
1116     llvm_unreachable("Node is not in map!");
1117   }
1118 #endif
1119   return Erased;
1120 }
1121 
1122 /// AddModifiedNodeToCSEMaps - The specified node has been removed from the CSE
1123 /// maps and modified in place. Add it back to the CSE maps, unless an identical
1124 /// node already exists, in which case transfer all its users to the existing
1125 /// node. This transfer can potentially trigger recursive merging.
1126 void
1127 SelectionDAG::AddModifiedNodeToCSEMaps(SDNode *N) {
1128   // For node types that aren't CSE'd, just act as if no identical node
1129   // already exists.
1130   if (!doNotCSE(N)) {
1131     SDNode *Existing = CSEMap.GetOrInsertNode(N);
1132     if (Existing != N) {
1133       // If there was already an existing matching node, use ReplaceAllUsesWith
1134       // to replace the dead one with the existing one.  This can cause
1135       // recursive merging of other unrelated nodes down the line.
1136       ReplaceAllUsesWith(N, Existing);
1137 
1138       // N is now dead. Inform the listeners and delete it.
1139       for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
1140         DUL->NodeDeleted(N, Existing);
1141       DeleteNodeNotInCSEMaps(N);
1142       return;
1143     }
1144   }
1145 
1146   // If the node doesn't already exist, we updated it.  Inform listeners.
1147   for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
1148     DUL->NodeUpdated(N);
1149 }
1150 
1151 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
1152 /// were replaced with those specified.  If this node is never memoized,
1153 /// return null, otherwise return a pointer to the slot it would take.  If a
1154 /// node already exists with these operands, the slot will be non-null.
1155 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, SDValue Op,
1156                                            void *&InsertPos) {
1157   if (doNotCSE(N))
1158     return nullptr;
1159 
1160   SDValue Ops[] = { Op };
1161   FoldingSetNodeID ID;
1162   AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops);
1163   AddNodeIDCustom(ID, N);
1164   SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos);
1165   if (Node)
1166     Node->intersectFlagsWith(N->getFlags());
1167   return Node;
1168 }
1169 
1170 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
1171 /// were replaced with those specified.  If this node is never memoized,
1172 /// return null, otherwise return a pointer to the slot it would take.  If a
1173 /// node already exists with these operands, the slot will be non-null.
1174 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N,
1175                                            SDValue Op1, SDValue Op2,
1176                                            void *&InsertPos) {
1177   if (doNotCSE(N))
1178     return nullptr;
1179 
1180   SDValue Ops[] = { Op1, Op2 };
1181   FoldingSetNodeID ID;
1182   AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops);
1183   AddNodeIDCustom(ID, N);
1184   SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos);
1185   if (Node)
1186     Node->intersectFlagsWith(N->getFlags());
1187   return Node;
1188 }
1189 
1190 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
1191 /// were replaced with those specified.  If this node is never memoized,
1192 /// return null, otherwise return a pointer to the slot it would take.  If a
1193 /// node already exists with these operands, the slot will be non-null.
1194 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, ArrayRef<SDValue> Ops,
1195                                            void *&InsertPos) {
1196   if (doNotCSE(N))
1197     return nullptr;
1198 
1199   FoldingSetNodeID ID;
1200   AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops);
1201   AddNodeIDCustom(ID, N);
1202   SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos);
1203   if (Node)
1204     Node->intersectFlagsWith(N->getFlags());
1205   return Node;
1206 }
1207 
1208 Align SelectionDAG::getEVTAlign(EVT VT) const {
1209   Type *Ty = VT == MVT::iPTR ?
1210                    PointerType::get(Type::getInt8Ty(*getContext()), 0) :
1211                    VT.getTypeForEVT(*getContext());
1212 
1213   return getDataLayout().getABITypeAlign(Ty);
1214 }
1215 
1216 // EntryNode could meaningfully have debug info if we can find it...
1217 SelectionDAG::SelectionDAG(const TargetMachine &tm, CodeGenOpt::Level OL)
1218     : TM(tm), OptLevel(OL),
1219       EntryNode(ISD::EntryToken, 0, DebugLoc(), getVTList(MVT::Other)),
1220       Root(getEntryNode()) {
1221   InsertNode(&EntryNode);
1222   DbgInfo = new SDDbgInfo();
1223 }
1224 
1225 void SelectionDAG::init(MachineFunction &NewMF,
1226                         OptimizationRemarkEmitter &NewORE,
1227                         Pass *PassPtr, const TargetLibraryInfo *LibraryInfo,
1228                         LegacyDivergenceAnalysis * Divergence,
1229                         ProfileSummaryInfo *PSIin,
1230                         BlockFrequencyInfo *BFIin) {
1231   MF = &NewMF;
1232   SDAGISelPass = PassPtr;
1233   ORE = &NewORE;
1234   TLI = getSubtarget().getTargetLowering();
1235   TSI = getSubtarget().getSelectionDAGInfo();
1236   LibInfo = LibraryInfo;
1237   Context = &MF->getFunction().getContext();
1238   DA = Divergence;
1239   PSI = PSIin;
1240   BFI = BFIin;
1241 }
1242 
1243 SelectionDAG::~SelectionDAG() {
1244   assert(!UpdateListeners && "Dangling registered DAGUpdateListeners");
1245   allnodes_clear();
1246   OperandRecycler.clear(OperandAllocator);
1247   delete DbgInfo;
1248 }
1249 
1250 bool SelectionDAG::shouldOptForSize() const {
1251   return MF->getFunction().hasOptSize() ||
1252       llvm::shouldOptimizeForSize(FLI->MBB->getBasicBlock(), PSI, BFI);
1253 }
1254 
1255 void SelectionDAG::allnodes_clear() {
1256   assert(&*AllNodes.begin() == &EntryNode);
1257   AllNodes.remove(AllNodes.begin());
1258   while (!AllNodes.empty())
1259     DeallocateNode(&AllNodes.front());
1260 #ifndef NDEBUG
1261   NextPersistentId = 0;
1262 #endif
1263 }
1264 
1265 SDNode *SelectionDAG::FindNodeOrInsertPos(const FoldingSetNodeID &ID,
1266                                           void *&InsertPos) {
1267   SDNode *N = CSEMap.FindNodeOrInsertPos(ID, InsertPos);
1268   if (N) {
1269     switch (N->getOpcode()) {
1270     default: break;
1271     case ISD::Constant:
1272     case ISD::ConstantFP:
1273       llvm_unreachable("Querying for Constant and ConstantFP nodes requires "
1274                        "debug location.  Use another overload.");
1275     }
1276   }
1277   return N;
1278 }
1279 
1280 SDNode *SelectionDAG::FindNodeOrInsertPos(const FoldingSetNodeID &ID,
1281                                           const SDLoc &DL, void *&InsertPos) {
1282   SDNode *N = CSEMap.FindNodeOrInsertPos(ID, InsertPos);
1283   if (N) {
1284     switch (N->getOpcode()) {
1285     case ISD::Constant:
1286     case ISD::ConstantFP:
1287       // Erase debug location from the node if the node is used at several
1288       // different places. Do not propagate one location to all uses as it
1289       // will cause a worse single stepping debugging experience.
1290       if (N->getDebugLoc() != DL.getDebugLoc())
1291         N->setDebugLoc(DebugLoc());
1292       break;
1293     default:
1294       // When the node's point of use is located earlier in the instruction
1295       // sequence than its prior point of use, update its debug info to the
1296       // earlier location.
1297       if (DL.getIROrder() && DL.getIROrder() < N->getIROrder())
1298         N->setDebugLoc(DL.getDebugLoc());
1299       break;
1300     }
1301   }
1302   return N;
1303 }
1304 
1305 void SelectionDAG::clear() {
1306   allnodes_clear();
1307   OperandRecycler.clear(OperandAllocator);
1308   OperandAllocator.Reset();
1309   CSEMap.clear();
1310 
1311   ExtendedValueTypeNodes.clear();
1312   ExternalSymbols.clear();
1313   TargetExternalSymbols.clear();
1314   MCSymbols.clear();
1315   SDCallSiteDbgInfo.clear();
1316   std::fill(CondCodeNodes.begin(), CondCodeNodes.end(),
1317             static_cast<CondCodeSDNode*>(nullptr));
1318   std::fill(ValueTypeNodes.begin(), ValueTypeNodes.end(),
1319             static_cast<SDNode*>(nullptr));
1320 
1321   EntryNode.UseList = nullptr;
1322   InsertNode(&EntryNode);
1323   Root = getEntryNode();
1324   DbgInfo->clear();
1325 }
1326 
1327 SDValue SelectionDAG::getFPExtendOrRound(SDValue Op, const SDLoc &DL, EVT VT) {
1328   return VT.bitsGT(Op.getValueType())
1329              ? getNode(ISD::FP_EXTEND, DL, VT, Op)
1330              : getNode(ISD::FP_ROUND, DL, VT, Op, getIntPtrConstant(0, DL));
1331 }
1332 
1333 std::pair<SDValue, SDValue>
1334 SelectionDAG::getStrictFPExtendOrRound(SDValue Op, SDValue Chain,
1335                                        const SDLoc &DL, EVT VT) {
1336   assert(!VT.bitsEq(Op.getValueType()) &&
1337          "Strict no-op FP extend/round not allowed.");
1338   SDValue Res =
1339       VT.bitsGT(Op.getValueType())
1340           ? getNode(ISD::STRICT_FP_EXTEND, DL, {VT, MVT::Other}, {Chain, Op})
1341           : getNode(ISD::STRICT_FP_ROUND, DL, {VT, MVT::Other},
1342                     {Chain, Op, getIntPtrConstant(0, DL)});
1343 
1344   return std::pair<SDValue, SDValue>(Res, SDValue(Res.getNode(), 1));
1345 }
1346 
1347 SDValue SelectionDAG::getAnyExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
1348   return VT.bitsGT(Op.getValueType()) ?
1349     getNode(ISD::ANY_EXTEND, DL, VT, Op) :
1350     getNode(ISD::TRUNCATE, DL, VT, Op);
1351 }
1352 
1353 SDValue SelectionDAG::getSExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
1354   return VT.bitsGT(Op.getValueType()) ?
1355     getNode(ISD::SIGN_EXTEND, DL, VT, Op) :
1356     getNode(ISD::TRUNCATE, DL, VT, Op);
1357 }
1358 
1359 SDValue SelectionDAG::getZExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
1360   return VT.bitsGT(Op.getValueType()) ?
1361     getNode(ISD::ZERO_EXTEND, DL, VT, Op) :
1362     getNode(ISD::TRUNCATE, DL, VT, Op);
1363 }
1364 
1365 SDValue SelectionDAG::getBoolExtOrTrunc(SDValue Op, const SDLoc &SL, EVT VT,
1366                                         EVT OpVT) {
1367   if (VT.bitsLE(Op.getValueType()))
1368     return getNode(ISD::TRUNCATE, SL, VT, Op);
1369 
1370   TargetLowering::BooleanContent BType = TLI->getBooleanContents(OpVT);
1371   return getNode(TLI->getExtendForContent(BType), SL, VT, Op);
1372 }
1373 
1374 SDValue SelectionDAG::getZeroExtendInReg(SDValue Op, const SDLoc &DL, EVT VT) {
1375   EVT OpVT = Op.getValueType();
1376   assert(VT.isInteger() && OpVT.isInteger() &&
1377          "Cannot getZeroExtendInReg FP types");
1378   assert(VT.isVector() == OpVT.isVector() &&
1379          "getZeroExtendInReg type should be vector iff the operand "
1380          "type is vector!");
1381   assert((!VT.isVector() ||
1382           VT.getVectorElementCount() == OpVT.getVectorElementCount()) &&
1383          "Vector element counts must match in getZeroExtendInReg");
1384   assert(VT.bitsLE(OpVT) && "Not extending!");
1385   if (OpVT == VT)
1386     return Op;
1387   APInt Imm = APInt::getLowBitsSet(OpVT.getScalarSizeInBits(),
1388                                    VT.getScalarSizeInBits());
1389   return getNode(ISD::AND, DL, OpVT, Op, getConstant(Imm, DL, OpVT));
1390 }
1391 
1392 SDValue SelectionDAG::getPtrExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
1393   // Only unsigned pointer semantics are supported right now. In the future this
1394   // might delegate to TLI to check pointer signedness.
1395   return getZExtOrTrunc(Op, DL, VT);
1396 }
1397 
1398 SDValue SelectionDAG::getPtrExtendInReg(SDValue Op, const SDLoc &DL, EVT VT) {
1399   // Only unsigned pointer semantics are supported right now. In the future this
1400   // might delegate to TLI to check pointer signedness.
1401   return getZeroExtendInReg(Op, DL, VT);
1402 }
1403 
1404 /// getNOT - Create a bitwise NOT operation as (XOR Val, -1).
1405 SDValue SelectionDAG::getNOT(const SDLoc &DL, SDValue Val, EVT VT) {
1406   return getNode(ISD::XOR, DL, VT, Val, getAllOnesConstant(DL, VT));
1407 }
1408 
1409 SDValue SelectionDAG::getLogicalNOT(const SDLoc &DL, SDValue Val, EVT VT) {
1410   SDValue TrueValue = getBoolConstant(true, DL, VT, VT);
1411   return getNode(ISD::XOR, DL, VT, Val, TrueValue);
1412 }
1413 
1414 SDValue SelectionDAG::getBoolConstant(bool V, const SDLoc &DL, EVT VT,
1415                                       EVT OpVT) {
1416   if (!V)
1417     return getConstant(0, DL, VT);
1418 
1419   switch (TLI->getBooleanContents(OpVT)) {
1420   case TargetLowering::ZeroOrOneBooleanContent:
1421   case TargetLowering::UndefinedBooleanContent:
1422     return getConstant(1, DL, VT);
1423   case TargetLowering::ZeroOrNegativeOneBooleanContent:
1424     return getAllOnesConstant(DL, VT);
1425   }
1426   llvm_unreachable("Unexpected boolean content enum!");
1427 }
1428 
1429 SDValue SelectionDAG::getConstant(uint64_t Val, const SDLoc &DL, EVT VT,
1430                                   bool isT, bool isO) {
1431   EVT EltVT = VT.getScalarType();
1432   assert((EltVT.getSizeInBits() >= 64 ||
1433           (uint64_t)((int64_t)Val >> EltVT.getSizeInBits()) + 1 < 2) &&
1434          "getConstant with a uint64_t value that doesn't fit in the type!");
1435   return getConstant(APInt(EltVT.getSizeInBits(), Val), DL, VT, isT, isO);
1436 }
1437 
1438 SDValue SelectionDAG::getConstant(const APInt &Val, const SDLoc &DL, EVT VT,
1439                                   bool isT, bool isO) {
1440   return getConstant(*ConstantInt::get(*Context, Val), DL, VT, isT, isO);
1441 }
1442 
1443 SDValue SelectionDAG::getConstant(const ConstantInt &Val, const SDLoc &DL,
1444                                   EVT VT, bool isT, bool isO) {
1445   assert(VT.isInteger() && "Cannot create FP integer constant!");
1446 
1447   EVT EltVT = VT.getScalarType();
1448   const ConstantInt *Elt = &Val;
1449 
1450   // In some cases the vector type is legal but the element type is illegal and
1451   // needs to be promoted, for example v8i8 on ARM.  In this case, promote the
1452   // inserted value (the type does not need to match the vector element type).
1453   // Any extra bits introduced will be truncated away.
1454   if (VT.isVector() && TLI->getTypeAction(*getContext(), EltVT) ==
1455                            TargetLowering::TypePromoteInteger) {
1456     EltVT = TLI->getTypeToTransformTo(*getContext(), EltVT);
1457     APInt NewVal = Elt->getValue().zextOrTrunc(EltVT.getSizeInBits());
1458     Elt = ConstantInt::get(*getContext(), NewVal);
1459   }
1460   // In other cases the element type is illegal and needs to be expanded, for
1461   // example v2i64 on MIPS32. In this case, find the nearest legal type, split
1462   // the value into n parts and use a vector type with n-times the elements.
1463   // Then bitcast to the type requested.
1464   // Legalizing constants too early makes the DAGCombiner's job harder so we
1465   // only legalize if the DAG tells us we must produce legal types.
1466   else if (NewNodesMustHaveLegalTypes && VT.isVector() &&
1467            TLI->getTypeAction(*getContext(), EltVT) ==
1468                TargetLowering::TypeExpandInteger) {
1469     const APInt &NewVal = Elt->getValue();
1470     EVT ViaEltVT = TLI->getTypeToTransformTo(*getContext(), EltVT);
1471     unsigned ViaEltSizeInBits = ViaEltVT.getSizeInBits();
1472 
1473     // For scalable vectors, try to use a SPLAT_VECTOR_PARTS node.
1474     if (VT.isScalableVector()) {
1475       assert(EltVT.getSizeInBits() % ViaEltSizeInBits == 0 &&
1476              "Can only handle an even split!");
1477       unsigned Parts = EltVT.getSizeInBits() / ViaEltSizeInBits;
1478 
1479       SmallVector<SDValue, 2> ScalarParts;
1480       for (unsigned i = 0; i != Parts; ++i)
1481         ScalarParts.push_back(getConstant(
1482             NewVal.extractBits(ViaEltSizeInBits, i * ViaEltSizeInBits), DL,
1483             ViaEltVT, isT, isO));
1484 
1485       return getNode(ISD::SPLAT_VECTOR_PARTS, DL, VT, ScalarParts);
1486     }
1487 
1488     unsigned ViaVecNumElts = VT.getSizeInBits() / ViaEltSizeInBits;
1489     EVT ViaVecVT = EVT::getVectorVT(*getContext(), ViaEltVT, ViaVecNumElts);
1490 
1491     // Check the temporary vector is the correct size. If this fails then
1492     // getTypeToTransformTo() probably returned a type whose size (in bits)
1493     // isn't a power-of-2 factor of the requested type size.
1494     assert(ViaVecVT.getSizeInBits() == VT.getSizeInBits());
1495 
1496     SmallVector<SDValue, 2> EltParts;
1497     for (unsigned i = 0; i < ViaVecNumElts / VT.getVectorNumElements(); ++i)
1498       EltParts.push_back(getConstant(
1499           NewVal.extractBits(ViaEltSizeInBits, i * ViaEltSizeInBits), DL,
1500           ViaEltVT, isT, isO));
1501 
1502     // EltParts is currently in little endian order. If we actually want
1503     // big-endian order then reverse it now.
1504     if (getDataLayout().isBigEndian())
1505       std::reverse(EltParts.begin(), EltParts.end());
1506 
1507     // The elements must be reversed when the element order is different
1508     // to the endianness of the elements (because the BITCAST is itself a
1509     // vector shuffle in this situation). However, we do not need any code to
1510     // perform this reversal because getConstant() is producing a vector
1511     // splat.
1512     // This situation occurs in MIPS MSA.
1513 
1514     SmallVector<SDValue, 8> Ops;
1515     for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
1516       llvm::append_range(Ops, EltParts);
1517 
1518     SDValue V =
1519         getNode(ISD::BITCAST, DL, VT, getBuildVector(ViaVecVT, DL, Ops));
1520     return V;
1521   }
1522 
1523   assert(Elt->getBitWidth() == EltVT.getSizeInBits() &&
1524          "APInt size does not match type size!");
1525   unsigned Opc = isT ? ISD::TargetConstant : ISD::Constant;
1526   FoldingSetNodeID ID;
1527   AddNodeIDNode(ID, Opc, getVTList(EltVT), None);
1528   ID.AddPointer(Elt);
1529   ID.AddBoolean(isO);
1530   void *IP = nullptr;
1531   SDNode *N = nullptr;
1532   if ((N = FindNodeOrInsertPos(ID, DL, IP)))
1533     if (!VT.isVector())
1534       return SDValue(N, 0);
1535 
1536   if (!N) {
1537     N = newSDNode<ConstantSDNode>(isT, isO, Elt, EltVT);
1538     CSEMap.InsertNode(N, IP);
1539     InsertNode(N);
1540     NewSDValueDbgMsg(SDValue(N, 0), "Creating constant: ", this);
1541   }
1542 
1543   SDValue Result(N, 0);
1544   if (VT.isScalableVector())
1545     Result = getSplatVector(VT, DL, Result);
1546   else if (VT.isVector())
1547     Result = getSplatBuildVector(VT, DL, Result);
1548 
1549   return Result;
1550 }
1551 
1552 SDValue SelectionDAG::getIntPtrConstant(uint64_t Val, const SDLoc &DL,
1553                                         bool isTarget) {
1554   return getConstant(Val, DL, TLI->getPointerTy(getDataLayout()), isTarget);
1555 }
1556 
1557 SDValue SelectionDAG::getShiftAmountConstant(uint64_t Val, EVT VT,
1558                                              const SDLoc &DL, bool LegalTypes) {
1559   assert(VT.isInteger() && "Shift amount is not an integer type!");
1560   EVT ShiftVT = TLI->getShiftAmountTy(VT, getDataLayout(), LegalTypes);
1561   return getConstant(Val, DL, ShiftVT);
1562 }
1563 
1564 SDValue SelectionDAG::getVectorIdxConstant(uint64_t Val, const SDLoc &DL,
1565                                            bool isTarget) {
1566   return getConstant(Val, DL, TLI->getVectorIdxTy(getDataLayout()), isTarget);
1567 }
1568 
1569 SDValue SelectionDAG::getConstantFP(const APFloat &V, const SDLoc &DL, EVT VT,
1570                                     bool isTarget) {
1571   return getConstantFP(*ConstantFP::get(*getContext(), V), DL, VT, isTarget);
1572 }
1573 
1574 SDValue SelectionDAG::getConstantFP(const ConstantFP &V, const SDLoc &DL,
1575                                     EVT VT, bool isTarget) {
1576   assert(VT.isFloatingPoint() && "Cannot create integer FP constant!");
1577 
1578   EVT EltVT = VT.getScalarType();
1579 
1580   // Do the map lookup using the actual bit pattern for the floating point
1581   // value, so that we don't have problems with 0.0 comparing equal to -0.0, and
1582   // we don't have issues with SNANs.
1583   unsigned Opc = isTarget ? ISD::TargetConstantFP : ISD::ConstantFP;
1584   FoldingSetNodeID ID;
1585   AddNodeIDNode(ID, Opc, getVTList(EltVT), None);
1586   ID.AddPointer(&V);
1587   void *IP = nullptr;
1588   SDNode *N = nullptr;
1589   if ((N = FindNodeOrInsertPos(ID, DL, IP)))
1590     if (!VT.isVector())
1591       return SDValue(N, 0);
1592 
1593   if (!N) {
1594     N = newSDNode<ConstantFPSDNode>(isTarget, &V, EltVT);
1595     CSEMap.InsertNode(N, IP);
1596     InsertNode(N);
1597   }
1598 
1599   SDValue Result(N, 0);
1600   if (VT.isScalableVector())
1601     Result = getSplatVector(VT, DL, Result);
1602   else if (VT.isVector())
1603     Result = getSplatBuildVector(VT, DL, Result);
1604   NewSDValueDbgMsg(Result, "Creating fp constant: ", this);
1605   return Result;
1606 }
1607 
1608 SDValue SelectionDAG::getConstantFP(double Val, const SDLoc &DL, EVT VT,
1609                                     bool isTarget) {
1610   EVT EltVT = VT.getScalarType();
1611   if (EltVT == MVT::f32)
1612     return getConstantFP(APFloat((float)Val), DL, VT, isTarget);
1613   if (EltVT == MVT::f64)
1614     return getConstantFP(APFloat(Val), DL, VT, isTarget);
1615   if (EltVT == MVT::f80 || EltVT == MVT::f128 || EltVT == MVT::ppcf128 ||
1616       EltVT == MVT::f16 || EltVT == MVT::bf16) {
1617     bool Ignored;
1618     APFloat APF = APFloat(Val);
1619     APF.convert(EVTToAPFloatSemantics(EltVT), APFloat::rmNearestTiesToEven,
1620                 &Ignored);
1621     return getConstantFP(APF, DL, VT, isTarget);
1622   }
1623   llvm_unreachable("Unsupported type in getConstantFP");
1624 }
1625 
1626 SDValue SelectionDAG::getGlobalAddress(const GlobalValue *GV, const SDLoc &DL,
1627                                        EVT VT, int64_t Offset, bool isTargetGA,
1628                                        unsigned TargetFlags) {
1629   assert((TargetFlags == 0 || isTargetGA) &&
1630          "Cannot set target flags on target-independent globals");
1631 
1632   // Truncate (with sign-extension) the offset value to the pointer size.
1633   unsigned BitWidth = getDataLayout().getPointerTypeSizeInBits(GV->getType());
1634   if (BitWidth < 64)
1635     Offset = SignExtend64(Offset, BitWidth);
1636 
1637   unsigned Opc;
1638   if (GV->isThreadLocal())
1639     Opc = isTargetGA ? ISD::TargetGlobalTLSAddress : ISD::GlobalTLSAddress;
1640   else
1641     Opc = isTargetGA ? ISD::TargetGlobalAddress : ISD::GlobalAddress;
1642 
1643   FoldingSetNodeID ID;
1644   AddNodeIDNode(ID, Opc, getVTList(VT), None);
1645   ID.AddPointer(GV);
1646   ID.AddInteger(Offset);
1647   ID.AddInteger(TargetFlags);
1648   void *IP = nullptr;
1649   if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
1650     return SDValue(E, 0);
1651 
1652   auto *N = newSDNode<GlobalAddressSDNode>(
1653       Opc, DL.getIROrder(), DL.getDebugLoc(), GV, VT, Offset, TargetFlags);
1654   CSEMap.InsertNode(N, IP);
1655     InsertNode(N);
1656   return SDValue(N, 0);
1657 }
1658 
1659 SDValue SelectionDAG::getFrameIndex(int FI, EVT VT, bool isTarget) {
1660   unsigned Opc = isTarget ? ISD::TargetFrameIndex : ISD::FrameIndex;
1661   FoldingSetNodeID ID;
1662   AddNodeIDNode(ID, Opc, getVTList(VT), None);
1663   ID.AddInteger(FI);
1664   void *IP = nullptr;
1665   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1666     return SDValue(E, 0);
1667 
1668   auto *N = newSDNode<FrameIndexSDNode>(FI, VT, isTarget);
1669   CSEMap.InsertNode(N, IP);
1670   InsertNode(N);
1671   return SDValue(N, 0);
1672 }
1673 
1674 SDValue SelectionDAG::getJumpTable(int JTI, EVT VT, bool isTarget,
1675                                    unsigned TargetFlags) {
1676   assert((TargetFlags == 0 || isTarget) &&
1677          "Cannot set target flags on target-independent jump tables");
1678   unsigned Opc = isTarget ? ISD::TargetJumpTable : ISD::JumpTable;
1679   FoldingSetNodeID ID;
1680   AddNodeIDNode(ID, Opc, getVTList(VT), None);
1681   ID.AddInteger(JTI);
1682   ID.AddInteger(TargetFlags);
1683   void *IP = nullptr;
1684   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1685     return SDValue(E, 0);
1686 
1687   auto *N = newSDNode<JumpTableSDNode>(JTI, VT, isTarget, TargetFlags);
1688   CSEMap.InsertNode(N, IP);
1689   InsertNode(N);
1690   return SDValue(N, 0);
1691 }
1692 
1693 SDValue SelectionDAG::getConstantPool(const Constant *C, EVT VT,
1694                                       MaybeAlign Alignment, int Offset,
1695                                       bool isTarget, unsigned TargetFlags) {
1696   assert((TargetFlags == 0 || isTarget) &&
1697          "Cannot set target flags on target-independent globals");
1698   if (!Alignment)
1699     Alignment = shouldOptForSize()
1700                     ? getDataLayout().getABITypeAlign(C->getType())
1701                     : getDataLayout().getPrefTypeAlign(C->getType());
1702   unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
1703   FoldingSetNodeID ID;
1704   AddNodeIDNode(ID, Opc, getVTList(VT), None);
1705   ID.AddInteger(Alignment->value());
1706   ID.AddInteger(Offset);
1707   ID.AddPointer(C);
1708   ID.AddInteger(TargetFlags);
1709   void *IP = nullptr;
1710   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1711     return SDValue(E, 0);
1712 
1713   auto *N = newSDNode<ConstantPoolSDNode>(isTarget, C, VT, Offset, *Alignment,
1714                                           TargetFlags);
1715   CSEMap.InsertNode(N, IP);
1716   InsertNode(N);
1717   SDValue V = SDValue(N, 0);
1718   NewSDValueDbgMsg(V, "Creating new constant pool: ", this);
1719   return V;
1720 }
1721 
1722 SDValue SelectionDAG::getConstantPool(MachineConstantPoolValue *C, EVT VT,
1723                                       MaybeAlign Alignment, int Offset,
1724                                       bool isTarget, unsigned TargetFlags) {
1725   assert((TargetFlags == 0 || isTarget) &&
1726          "Cannot set target flags on target-independent globals");
1727   if (!Alignment)
1728     Alignment = getDataLayout().getPrefTypeAlign(C->getType());
1729   unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
1730   FoldingSetNodeID ID;
1731   AddNodeIDNode(ID, Opc, getVTList(VT), None);
1732   ID.AddInteger(Alignment->value());
1733   ID.AddInteger(Offset);
1734   C->addSelectionDAGCSEId(ID);
1735   ID.AddInteger(TargetFlags);
1736   void *IP = nullptr;
1737   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1738     return SDValue(E, 0);
1739 
1740   auto *N = newSDNode<ConstantPoolSDNode>(isTarget, C, VT, Offset, *Alignment,
1741                                           TargetFlags);
1742   CSEMap.InsertNode(N, IP);
1743   InsertNode(N);
1744   return SDValue(N, 0);
1745 }
1746 
1747 SDValue SelectionDAG::getTargetIndex(int Index, EVT VT, int64_t Offset,
1748                                      unsigned TargetFlags) {
1749   FoldingSetNodeID ID;
1750   AddNodeIDNode(ID, ISD::TargetIndex, getVTList(VT), None);
1751   ID.AddInteger(Index);
1752   ID.AddInteger(Offset);
1753   ID.AddInteger(TargetFlags);
1754   void *IP = nullptr;
1755   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1756     return SDValue(E, 0);
1757 
1758   auto *N = newSDNode<TargetIndexSDNode>(Index, VT, Offset, TargetFlags);
1759   CSEMap.InsertNode(N, IP);
1760   InsertNode(N);
1761   return SDValue(N, 0);
1762 }
1763 
1764 SDValue SelectionDAG::getBasicBlock(MachineBasicBlock *MBB) {
1765   FoldingSetNodeID ID;
1766   AddNodeIDNode(ID, ISD::BasicBlock, getVTList(MVT::Other), None);
1767   ID.AddPointer(MBB);
1768   void *IP = nullptr;
1769   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1770     return SDValue(E, 0);
1771 
1772   auto *N = newSDNode<BasicBlockSDNode>(MBB);
1773   CSEMap.InsertNode(N, IP);
1774   InsertNode(N);
1775   return SDValue(N, 0);
1776 }
1777 
1778 SDValue SelectionDAG::getValueType(EVT VT) {
1779   if (VT.isSimple() && (unsigned)VT.getSimpleVT().SimpleTy >=
1780       ValueTypeNodes.size())
1781     ValueTypeNodes.resize(VT.getSimpleVT().SimpleTy+1);
1782 
1783   SDNode *&N = VT.isExtended() ?
1784     ExtendedValueTypeNodes[VT] : ValueTypeNodes[VT.getSimpleVT().SimpleTy];
1785 
1786   if (N) return SDValue(N, 0);
1787   N = newSDNode<VTSDNode>(VT);
1788   InsertNode(N);
1789   return SDValue(N, 0);
1790 }
1791 
1792 SDValue SelectionDAG::getExternalSymbol(const char *Sym, EVT VT) {
1793   SDNode *&N = ExternalSymbols[Sym];
1794   if (N) return SDValue(N, 0);
1795   N = newSDNode<ExternalSymbolSDNode>(false, Sym, 0, VT);
1796   InsertNode(N);
1797   return SDValue(N, 0);
1798 }
1799 
1800 SDValue SelectionDAG::getMCSymbol(MCSymbol *Sym, EVT VT) {
1801   SDNode *&N = MCSymbols[Sym];
1802   if (N)
1803     return SDValue(N, 0);
1804   N = newSDNode<MCSymbolSDNode>(Sym, VT);
1805   InsertNode(N);
1806   return SDValue(N, 0);
1807 }
1808 
1809 SDValue SelectionDAG::getTargetExternalSymbol(const char *Sym, EVT VT,
1810                                               unsigned TargetFlags) {
1811   SDNode *&N =
1812       TargetExternalSymbols[std::pair<std::string, unsigned>(Sym, TargetFlags)];
1813   if (N) return SDValue(N, 0);
1814   N = newSDNode<ExternalSymbolSDNode>(true, Sym, TargetFlags, VT);
1815   InsertNode(N);
1816   return SDValue(N, 0);
1817 }
1818 
1819 SDValue SelectionDAG::getCondCode(ISD::CondCode Cond) {
1820   if ((unsigned)Cond >= CondCodeNodes.size())
1821     CondCodeNodes.resize(Cond+1);
1822 
1823   if (!CondCodeNodes[Cond]) {
1824     auto *N = newSDNode<CondCodeSDNode>(Cond);
1825     CondCodeNodes[Cond] = N;
1826     InsertNode(N);
1827   }
1828 
1829   return SDValue(CondCodeNodes[Cond], 0);
1830 }
1831 
1832 SDValue SelectionDAG::getStepVector(const SDLoc &DL, EVT ResVT) {
1833   APInt One(ResVT.getScalarSizeInBits(), 1);
1834   return getStepVector(DL, ResVT, One);
1835 }
1836 
1837 SDValue SelectionDAG::getStepVector(const SDLoc &DL, EVT ResVT, APInt StepVal) {
1838   assert(ResVT.getScalarSizeInBits() == StepVal.getBitWidth());
1839   if (ResVT.isScalableVector())
1840     return getNode(
1841         ISD::STEP_VECTOR, DL, ResVT,
1842         getTargetConstant(StepVal, DL, ResVT.getVectorElementType()));
1843 
1844   SmallVector<SDValue, 16> OpsStepConstants;
1845   for (uint64_t i = 0; i < ResVT.getVectorNumElements(); i++)
1846     OpsStepConstants.push_back(
1847         getConstant(StepVal * i, DL, ResVT.getVectorElementType()));
1848   return getBuildVector(ResVT, DL, OpsStepConstants);
1849 }
1850 
1851 /// Swaps the values of N1 and N2. Swaps all indices in the shuffle mask M that
1852 /// point at N1 to point at N2 and indices that point at N2 to point at N1.
1853 static void commuteShuffle(SDValue &N1, SDValue &N2, MutableArrayRef<int> M) {
1854   std::swap(N1, N2);
1855   ShuffleVectorSDNode::commuteMask(M);
1856 }
1857 
1858 SDValue SelectionDAG::getVectorShuffle(EVT VT, const SDLoc &dl, SDValue N1,
1859                                        SDValue N2, ArrayRef<int> Mask) {
1860   assert(VT.getVectorNumElements() == Mask.size() &&
1861          "Must have the same number of vector elements as mask elements!");
1862   assert(VT == N1.getValueType() && VT == N2.getValueType() &&
1863          "Invalid VECTOR_SHUFFLE");
1864 
1865   // Canonicalize shuffle undef, undef -> undef
1866   if (N1.isUndef() && N2.isUndef())
1867     return getUNDEF(VT);
1868 
1869   // Validate that all indices in Mask are within the range of the elements
1870   // input to the shuffle.
1871   int NElts = Mask.size();
1872   assert(llvm::all_of(Mask,
1873                       [&](int M) { return M < (NElts * 2) && M >= -1; }) &&
1874          "Index out of range");
1875 
1876   // Copy the mask so we can do any needed cleanup.
1877   SmallVector<int, 8> MaskVec(Mask.begin(), Mask.end());
1878 
1879   // Canonicalize shuffle v, v -> v, undef
1880   if (N1 == N2) {
1881     N2 = getUNDEF(VT);
1882     for (int i = 0; i != NElts; ++i)
1883       if (MaskVec[i] >= NElts) MaskVec[i] -= NElts;
1884   }
1885 
1886   // Canonicalize shuffle undef, v -> v, undef.  Commute the shuffle mask.
1887   if (N1.isUndef())
1888     commuteShuffle(N1, N2, MaskVec);
1889 
1890   if (TLI->hasVectorBlend()) {
1891     // If shuffling a splat, try to blend the splat instead. We do this here so
1892     // that even when this arises during lowering we don't have to re-handle it.
1893     auto BlendSplat = [&](BuildVectorSDNode *BV, int Offset) {
1894       BitVector UndefElements;
1895       SDValue Splat = BV->getSplatValue(&UndefElements);
1896       if (!Splat)
1897         return;
1898 
1899       for (int i = 0; i < NElts; ++i) {
1900         if (MaskVec[i] < Offset || MaskVec[i] >= (Offset + NElts))
1901           continue;
1902 
1903         // If this input comes from undef, mark it as such.
1904         if (UndefElements[MaskVec[i] - Offset]) {
1905           MaskVec[i] = -1;
1906           continue;
1907         }
1908 
1909         // If we can blend a non-undef lane, use that instead.
1910         if (!UndefElements[i])
1911           MaskVec[i] = i + Offset;
1912       }
1913     };
1914     if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
1915       BlendSplat(N1BV, 0);
1916     if (auto *N2BV = dyn_cast<BuildVectorSDNode>(N2))
1917       BlendSplat(N2BV, NElts);
1918   }
1919 
1920   // Canonicalize all index into lhs, -> shuffle lhs, undef
1921   // Canonicalize all index into rhs, -> shuffle rhs, undef
1922   bool AllLHS = true, AllRHS = true;
1923   bool N2Undef = N2.isUndef();
1924   for (int i = 0; i != NElts; ++i) {
1925     if (MaskVec[i] >= NElts) {
1926       if (N2Undef)
1927         MaskVec[i] = -1;
1928       else
1929         AllLHS = false;
1930     } else if (MaskVec[i] >= 0) {
1931       AllRHS = false;
1932     }
1933   }
1934   if (AllLHS && AllRHS)
1935     return getUNDEF(VT);
1936   if (AllLHS && !N2Undef)
1937     N2 = getUNDEF(VT);
1938   if (AllRHS) {
1939     N1 = getUNDEF(VT);
1940     commuteShuffle(N1, N2, MaskVec);
1941   }
1942   // Reset our undef status after accounting for the mask.
1943   N2Undef = N2.isUndef();
1944   // Re-check whether both sides ended up undef.
1945   if (N1.isUndef() && N2Undef)
1946     return getUNDEF(VT);
1947 
1948   // If Identity shuffle return that node.
1949   bool Identity = true, AllSame = true;
1950   for (int i = 0; i != NElts; ++i) {
1951     if (MaskVec[i] >= 0 && MaskVec[i] != i) Identity = false;
1952     if (MaskVec[i] != MaskVec[0]) AllSame = false;
1953   }
1954   if (Identity && NElts)
1955     return N1;
1956 
1957   // Shuffling a constant splat doesn't change the result.
1958   if (N2Undef) {
1959     SDValue V = N1;
1960 
1961     // Look through any bitcasts. We check that these don't change the number
1962     // (and size) of elements and just changes their types.
1963     while (V.getOpcode() == ISD::BITCAST)
1964       V = V->getOperand(0);
1965 
1966     // A splat should always show up as a build vector node.
1967     if (auto *BV = dyn_cast<BuildVectorSDNode>(V)) {
1968       BitVector UndefElements;
1969       SDValue Splat = BV->getSplatValue(&UndefElements);
1970       // If this is a splat of an undef, shuffling it is also undef.
1971       if (Splat && Splat.isUndef())
1972         return getUNDEF(VT);
1973 
1974       bool SameNumElts =
1975           V.getValueType().getVectorNumElements() == VT.getVectorNumElements();
1976 
1977       // We only have a splat which can skip shuffles if there is a splatted
1978       // value and no undef lanes rearranged by the shuffle.
1979       if (Splat && UndefElements.none()) {
1980         // Splat of <x, x, ..., x>, return <x, x, ..., x>, provided that the
1981         // number of elements match or the value splatted is a zero constant.
1982         if (SameNumElts)
1983           return N1;
1984         if (auto *C = dyn_cast<ConstantSDNode>(Splat))
1985           if (C->isZero())
1986             return N1;
1987       }
1988 
1989       // If the shuffle itself creates a splat, build the vector directly.
1990       if (AllSame && SameNumElts) {
1991         EVT BuildVT = BV->getValueType(0);
1992         const SDValue &Splatted = BV->getOperand(MaskVec[0]);
1993         SDValue NewBV = getSplatBuildVector(BuildVT, dl, Splatted);
1994 
1995         // We may have jumped through bitcasts, so the type of the
1996         // BUILD_VECTOR may not match the type of the shuffle.
1997         if (BuildVT != VT)
1998           NewBV = getNode(ISD::BITCAST, dl, VT, NewBV);
1999         return NewBV;
2000       }
2001     }
2002   }
2003 
2004   FoldingSetNodeID ID;
2005   SDValue Ops[2] = { N1, N2 };
2006   AddNodeIDNode(ID, ISD::VECTOR_SHUFFLE, getVTList(VT), Ops);
2007   for (int i = 0; i != NElts; ++i)
2008     ID.AddInteger(MaskVec[i]);
2009 
2010   void* IP = nullptr;
2011   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
2012     return SDValue(E, 0);
2013 
2014   // Allocate the mask array for the node out of the BumpPtrAllocator, since
2015   // SDNode doesn't have access to it.  This memory will be "leaked" when
2016   // the node is deallocated, but recovered when the NodeAllocator is released.
2017   int *MaskAlloc = OperandAllocator.Allocate<int>(NElts);
2018   llvm::copy(MaskVec, MaskAlloc);
2019 
2020   auto *N = newSDNode<ShuffleVectorSDNode>(VT, dl.getIROrder(),
2021                                            dl.getDebugLoc(), MaskAlloc);
2022   createOperands(N, Ops);
2023 
2024   CSEMap.InsertNode(N, IP);
2025   InsertNode(N);
2026   SDValue V = SDValue(N, 0);
2027   NewSDValueDbgMsg(V, "Creating new node: ", this);
2028   return V;
2029 }
2030 
2031 SDValue SelectionDAG::getCommutedVectorShuffle(const ShuffleVectorSDNode &SV) {
2032   EVT VT = SV.getValueType(0);
2033   SmallVector<int, 8> MaskVec(SV.getMask().begin(), SV.getMask().end());
2034   ShuffleVectorSDNode::commuteMask(MaskVec);
2035 
2036   SDValue Op0 = SV.getOperand(0);
2037   SDValue Op1 = SV.getOperand(1);
2038   return getVectorShuffle(VT, SDLoc(&SV), Op1, Op0, MaskVec);
2039 }
2040 
2041 SDValue SelectionDAG::getRegister(unsigned RegNo, EVT VT) {
2042   FoldingSetNodeID ID;
2043   AddNodeIDNode(ID, ISD::Register, getVTList(VT), None);
2044   ID.AddInteger(RegNo);
2045   void *IP = nullptr;
2046   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2047     return SDValue(E, 0);
2048 
2049   auto *N = newSDNode<RegisterSDNode>(RegNo, VT);
2050   N->SDNodeBits.IsDivergent = TLI->isSDNodeSourceOfDivergence(N, FLI, DA);
2051   CSEMap.InsertNode(N, IP);
2052   InsertNode(N);
2053   return SDValue(N, 0);
2054 }
2055 
2056 SDValue SelectionDAG::getRegisterMask(const uint32_t *RegMask) {
2057   FoldingSetNodeID ID;
2058   AddNodeIDNode(ID, ISD::RegisterMask, getVTList(MVT::Untyped), None);
2059   ID.AddPointer(RegMask);
2060   void *IP = nullptr;
2061   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2062     return SDValue(E, 0);
2063 
2064   auto *N = newSDNode<RegisterMaskSDNode>(RegMask);
2065   CSEMap.InsertNode(N, IP);
2066   InsertNode(N);
2067   return SDValue(N, 0);
2068 }
2069 
2070 SDValue SelectionDAG::getEHLabel(const SDLoc &dl, SDValue Root,
2071                                  MCSymbol *Label) {
2072   return getLabelNode(ISD::EH_LABEL, dl, Root, Label);
2073 }
2074 
2075 SDValue SelectionDAG::getLabelNode(unsigned Opcode, const SDLoc &dl,
2076                                    SDValue Root, MCSymbol *Label) {
2077   FoldingSetNodeID ID;
2078   SDValue Ops[] = { Root };
2079   AddNodeIDNode(ID, Opcode, getVTList(MVT::Other), Ops);
2080   ID.AddPointer(Label);
2081   void *IP = nullptr;
2082   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2083     return SDValue(E, 0);
2084 
2085   auto *N =
2086       newSDNode<LabelSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(), Label);
2087   createOperands(N, Ops);
2088 
2089   CSEMap.InsertNode(N, IP);
2090   InsertNode(N);
2091   return SDValue(N, 0);
2092 }
2093 
2094 SDValue SelectionDAG::getBlockAddress(const BlockAddress *BA, EVT VT,
2095                                       int64_t Offset, bool isTarget,
2096                                       unsigned TargetFlags) {
2097   unsigned Opc = isTarget ? ISD::TargetBlockAddress : ISD::BlockAddress;
2098 
2099   FoldingSetNodeID ID;
2100   AddNodeIDNode(ID, Opc, getVTList(VT), None);
2101   ID.AddPointer(BA);
2102   ID.AddInteger(Offset);
2103   ID.AddInteger(TargetFlags);
2104   void *IP = nullptr;
2105   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2106     return SDValue(E, 0);
2107 
2108   auto *N = newSDNode<BlockAddressSDNode>(Opc, VT, BA, Offset, TargetFlags);
2109   CSEMap.InsertNode(N, IP);
2110   InsertNode(N);
2111   return SDValue(N, 0);
2112 }
2113 
2114 SDValue SelectionDAG::getSrcValue(const Value *V) {
2115   FoldingSetNodeID ID;
2116   AddNodeIDNode(ID, ISD::SRCVALUE, getVTList(MVT::Other), None);
2117   ID.AddPointer(V);
2118 
2119   void *IP = nullptr;
2120   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2121     return SDValue(E, 0);
2122 
2123   auto *N = newSDNode<SrcValueSDNode>(V);
2124   CSEMap.InsertNode(N, IP);
2125   InsertNode(N);
2126   return SDValue(N, 0);
2127 }
2128 
2129 SDValue SelectionDAG::getMDNode(const MDNode *MD) {
2130   FoldingSetNodeID ID;
2131   AddNodeIDNode(ID, ISD::MDNODE_SDNODE, getVTList(MVT::Other), None);
2132   ID.AddPointer(MD);
2133 
2134   void *IP = nullptr;
2135   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2136     return SDValue(E, 0);
2137 
2138   auto *N = newSDNode<MDNodeSDNode>(MD);
2139   CSEMap.InsertNode(N, IP);
2140   InsertNode(N);
2141   return SDValue(N, 0);
2142 }
2143 
2144 SDValue SelectionDAG::getBitcast(EVT VT, SDValue V) {
2145   if (VT == V.getValueType())
2146     return V;
2147 
2148   return getNode(ISD::BITCAST, SDLoc(V), VT, V);
2149 }
2150 
2151 SDValue SelectionDAG::getAddrSpaceCast(const SDLoc &dl, EVT VT, SDValue Ptr,
2152                                        unsigned SrcAS, unsigned DestAS) {
2153   SDValue Ops[] = {Ptr};
2154   FoldingSetNodeID ID;
2155   AddNodeIDNode(ID, ISD::ADDRSPACECAST, getVTList(VT), Ops);
2156   ID.AddInteger(SrcAS);
2157   ID.AddInteger(DestAS);
2158 
2159   void *IP = nullptr;
2160   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
2161     return SDValue(E, 0);
2162 
2163   auto *N = newSDNode<AddrSpaceCastSDNode>(dl.getIROrder(), dl.getDebugLoc(),
2164                                            VT, SrcAS, DestAS);
2165   createOperands(N, Ops);
2166 
2167   CSEMap.InsertNode(N, IP);
2168   InsertNode(N);
2169   return SDValue(N, 0);
2170 }
2171 
2172 SDValue SelectionDAG::getFreeze(SDValue V) {
2173   return getNode(ISD::FREEZE, SDLoc(V), V.getValueType(), V);
2174 }
2175 
2176 /// getShiftAmountOperand - Return the specified value casted to
2177 /// the target's desired shift amount type.
2178 SDValue SelectionDAG::getShiftAmountOperand(EVT LHSTy, SDValue Op) {
2179   EVT OpTy = Op.getValueType();
2180   EVT ShTy = TLI->getShiftAmountTy(LHSTy, getDataLayout());
2181   if (OpTy == ShTy || OpTy.isVector()) return Op;
2182 
2183   return getZExtOrTrunc(Op, SDLoc(Op), ShTy);
2184 }
2185 
2186 SDValue SelectionDAG::expandVAArg(SDNode *Node) {
2187   SDLoc dl(Node);
2188   const TargetLowering &TLI = getTargetLoweringInfo();
2189   const Value *V = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
2190   EVT VT = Node->getValueType(0);
2191   SDValue Tmp1 = Node->getOperand(0);
2192   SDValue Tmp2 = Node->getOperand(1);
2193   const MaybeAlign MA(Node->getConstantOperandVal(3));
2194 
2195   SDValue VAListLoad = getLoad(TLI.getPointerTy(getDataLayout()), dl, Tmp1,
2196                                Tmp2, MachinePointerInfo(V));
2197   SDValue VAList = VAListLoad;
2198 
2199   if (MA && *MA > TLI.getMinStackArgumentAlignment()) {
2200     VAList = getNode(ISD::ADD, dl, VAList.getValueType(), VAList,
2201                      getConstant(MA->value() - 1, dl, VAList.getValueType()));
2202 
2203     VAList =
2204         getNode(ISD::AND, dl, VAList.getValueType(), VAList,
2205                 getConstant(-(int64_t)MA->value(), dl, VAList.getValueType()));
2206   }
2207 
2208   // Increment the pointer, VAList, to the next vaarg
2209   Tmp1 = getNode(ISD::ADD, dl, VAList.getValueType(), VAList,
2210                  getConstant(getDataLayout().getTypeAllocSize(
2211                                                VT.getTypeForEVT(*getContext())),
2212                              dl, VAList.getValueType()));
2213   // Store the incremented VAList to the legalized pointer
2214   Tmp1 =
2215       getStore(VAListLoad.getValue(1), dl, Tmp1, Tmp2, MachinePointerInfo(V));
2216   // Load the actual argument out of the pointer VAList
2217   return getLoad(VT, dl, Tmp1, VAList, MachinePointerInfo());
2218 }
2219 
2220 SDValue SelectionDAG::expandVACopy(SDNode *Node) {
2221   SDLoc dl(Node);
2222   const TargetLowering &TLI = getTargetLoweringInfo();
2223   // This defaults to loading a pointer from the input and storing it to the
2224   // output, returning the chain.
2225   const Value *VD = cast<SrcValueSDNode>(Node->getOperand(3))->getValue();
2226   const Value *VS = cast<SrcValueSDNode>(Node->getOperand(4))->getValue();
2227   SDValue Tmp1 =
2228       getLoad(TLI.getPointerTy(getDataLayout()), dl, Node->getOperand(0),
2229               Node->getOperand(2), MachinePointerInfo(VS));
2230   return getStore(Tmp1.getValue(1), dl, Tmp1, Node->getOperand(1),
2231                   MachinePointerInfo(VD));
2232 }
2233 
2234 Align SelectionDAG::getReducedAlign(EVT VT, bool UseABI) {
2235   const DataLayout &DL = getDataLayout();
2236   Type *Ty = VT.getTypeForEVT(*getContext());
2237   Align RedAlign = UseABI ? DL.getABITypeAlign(Ty) : DL.getPrefTypeAlign(Ty);
2238 
2239   if (TLI->isTypeLegal(VT) || !VT.isVector())
2240     return RedAlign;
2241 
2242   const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering();
2243   const Align StackAlign = TFI->getStackAlign();
2244 
2245   // See if we can choose a smaller ABI alignment in cases where it's an
2246   // illegal vector type that will get broken down.
2247   if (RedAlign > StackAlign) {
2248     EVT IntermediateVT;
2249     MVT RegisterVT;
2250     unsigned NumIntermediates;
2251     TLI->getVectorTypeBreakdown(*getContext(), VT, IntermediateVT,
2252                                 NumIntermediates, RegisterVT);
2253     Ty = IntermediateVT.getTypeForEVT(*getContext());
2254     Align RedAlign2 = UseABI ? DL.getABITypeAlign(Ty) : DL.getPrefTypeAlign(Ty);
2255     if (RedAlign2 < RedAlign)
2256       RedAlign = RedAlign2;
2257   }
2258 
2259   return RedAlign;
2260 }
2261 
2262 SDValue SelectionDAG::CreateStackTemporary(TypeSize Bytes, Align Alignment) {
2263   MachineFrameInfo &MFI = MF->getFrameInfo();
2264   const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering();
2265   int StackID = 0;
2266   if (Bytes.isScalable())
2267     StackID = TFI->getStackIDForScalableVectors();
2268   // The stack id gives an indication of whether the object is scalable or
2269   // not, so it's safe to pass in the minimum size here.
2270   int FrameIdx = MFI.CreateStackObject(Bytes.getKnownMinSize(), Alignment,
2271                                        false, nullptr, StackID);
2272   return getFrameIndex(FrameIdx, TLI->getFrameIndexTy(getDataLayout()));
2273 }
2274 
2275 SDValue SelectionDAG::CreateStackTemporary(EVT VT, unsigned minAlign) {
2276   Type *Ty = VT.getTypeForEVT(*getContext());
2277   Align StackAlign =
2278       std::max(getDataLayout().getPrefTypeAlign(Ty), Align(minAlign));
2279   return CreateStackTemporary(VT.getStoreSize(), StackAlign);
2280 }
2281 
2282 SDValue SelectionDAG::CreateStackTemporary(EVT VT1, EVT VT2) {
2283   TypeSize VT1Size = VT1.getStoreSize();
2284   TypeSize VT2Size = VT2.getStoreSize();
2285   assert(VT1Size.isScalable() == VT2Size.isScalable() &&
2286          "Don't know how to choose the maximum size when creating a stack "
2287          "temporary");
2288   TypeSize Bytes =
2289       VT1Size.getKnownMinSize() > VT2Size.getKnownMinSize() ? VT1Size : VT2Size;
2290 
2291   Type *Ty1 = VT1.getTypeForEVT(*getContext());
2292   Type *Ty2 = VT2.getTypeForEVT(*getContext());
2293   const DataLayout &DL = getDataLayout();
2294   Align Align = std::max(DL.getPrefTypeAlign(Ty1), DL.getPrefTypeAlign(Ty2));
2295   return CreateStackTemporary(Bytes, Align);
2296 }
2297 
2298 SDValue SelectionDAG::FoldSetCC(EVT VT, SDValue N1, SDValue N2,
2299                                 ISD::CondCode Cond, const SDLoc &dl) {
2300   EVT OpVT = N1.getValueType();
2301 
2302   // These setcc operations always fold.
2303   switch (Cond) {
2304   default: break;
2305   case ISD::SETFALSE:
2306   case ISD::SETFALSE2: return getBoolConstant(false, dl, VT, OpVT);
2307   case ISD::SETTRUE:
2308   case ISD::SETTRUE2: return getBoolConstant(true, dl, VT, OpVT);
2309 
2310   case ISD::SETOEQ:
2311   case ISD::SETOGT:
2312   case ISD::SETOGE:
2313   case ISD::SETOLT:
2314   case ISD::SETOLE:
2315   case ISD::SETONE:
2316   case ISD::SETO:
2317   case ISD::SETUO:
2318   case ISD::SETUEQ:
2319   case ISD::SETUNE:
2320     assert(!OpVT.isInteger() && "Illegal setcc for integer!");
2321     break;
2322   }
2323 
2324   if (OpVT.isInteger()) {
2325     // For EQ and NE, we can always pick a value for the undef to make the
2326     // predicate pass or fail, so we can return undef.
2327     // Matches behavior in llvm::ConstantFoldCompareInstruction.
2328     // icmp eq/ne X, undef -> undef.
2329     if ((N1.isUndef() || N2.isUndef()) &&
2330         (Cond == ISD::SETEQ || Cond == ISD::SETNE))
2331       return getUNDEF(VT);
2332 
2333     // If both operands are undef, we can return undef for int comparison.
2334     // icmp undef, undef -> undef.
2335     if (N1.isUndef() && N2.isUndef())
2336       return getUNDEF(VT);
2337 
2338     // icmp X, X -> true/false
2339     // icmp X, undef -> true/false because undef could be X.
2340     if (N1 == N2)
2341       return getBoolConstant(ISD::isTrueWhenEqual(Cond), dl, VT, OpVT);
2342   }
2343 
2344   if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2)) {
2345     const APInt &C2 = N2C->getAPIntValue();
2346     if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1)) {
2347       const APInt &C1 = N1C->getAPIntValue();
2348 
2349       return getBoolConstant(ICmpInst::compare(C1, C2, getICmpCondCode(Cond)),
2350                              dl, VT, OpVT);
2351     }
2352   }
2353 
2354   auto *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
2355   auto *N2CFP = dyn_cast<ConstantFPSDNode>(N2);
2356 
2357   if (N1CFP && N2CFP) {
2358     APFloat::cmpResult R = N1CFP->getValueAPF().compare(N2CFP->getValueAPF());
2359     switch (Cond) {
2360     default: break;
2361     case ISD::SETEQ:  if (R==APFloat::cmpUnordered)
2362                         return getUNDEF(VT);
2363                       LLVM_FALLTHROUGH;
2364     case ISD::SETOEQ: return getBoolConstant(R==APFloat::cmpEqual, dl, VT,
2365                                              OpVT);
2366     case ISD::SETNE:  if (R==APFloat::cmpUnordered)
2367                         return getUNDEF(VT);
2368                       LLVM_FALLTHROUGH;
2369     case ISD::SETONE: return getBoolConstant(R==APFloat::cmpGreaterThan ||
2370                                              R==APFloat::cmpLessThan, dl, VT,
2371                                              OpVT);
2372     case ISD::SETLT:  if (R==APFloat::cmpUnordered)
2373                         return getUNDEF(VT);
2374                       LLVM_FALLTHROUGH;
2375     case ISD::SETOLT: return getBoolConstant(R==APFloat::cmpLessThan, dl, VT,
2376                                              OpVT);
2377     case ISD::SETGT:  if (R==APFloat::cmpUnordered)
2378                         return getUNDEF(VT);
2379                       LLVM_FALLTHROUGH;
2380     case ISD::SETOGT: return getBoolConstant(R==APFloat::cmpGreaterThan, dl,
2381                                              VT, OpVT);
2382     case ISD::SETLE:  if (R==APFloat::cmpUnordered)
2383                         return getUNDEF(VT);
2384                       LLVM_FALLTHROUGH;
2385     case ISD::SETOLE: return getBoolConstant(R==APFloat::cmpLessThan ||
2386                                              R==APFloat::cmpEqual, dl, VT,
2387                                              OpVT);
2388     case ISD::SETGE:  if (R==APFloat::cmpUnordered)
2389                         return getUNDEF(VT);
2390                       LLVM_FALLTHROUGH;
2391     case ISD::SETOGE: return getBoolConstant(R==APFloat::cmpGreaterThan ||
2392                                          R==APFloat::cmpEqual, dl, VT, OpVT);
2393     case ISD::SETO:   return getBoolConstant(R!=APFloat::cmpUnordered, dl, VT,
2394                                              OpVT);
2395     case ISD::SETUO:  return getBoolConstant(R==APFloat::cmpUnordered, dl, VT,
2396                                              OpVT);
2397     case ISD::SETUEQ: return getBoolConstant(R==APFloat::cmpUnordered ||
2398                                              R==APFloat::cmpEqual, dl, VT,
2399                                              OpVT);
2400     case ISD::SETUNE: return getBoolConstant(R!=APFloat::cmpEqual, dl, VT,
2401                                              OpVT);
2402     case ISD::SETULT: return getBoolConstant(R==APFloat::cmpUnordered ||
2403                                              R==APFloat::cmpLessThan, dl, VT,
2404                                              OpVT);
2405     case ISD::SETUGT: return getBoolConstant(R==APFloat::cmpGreaterThan ||
2406                                              R==APFloat::cmpUnordered, dl, VT,
2407                                              OpVT);
2408     case ISD::SETULE: return getBoolConstant(R!=APFloat::cmpGreaterThan, dl,
2409                                              VT, OpVT);
2410     case ISD::SETUGE: return getBoolConstant(R!=APFloat::cmpLessThan, dl, VT,
2411                                              OpVT);
2412     }
2413   } else if (N1CFP && OpVT.isSimple() && !N2.isUndef()) {
2414     // Ensure that the constant occurs on the RHS.
2415     ISD::CondCode SwappedCond = ISD::getSetCCSwappedOperands(Cond);
2416     if (!TLI->isCondCodeLegal(SwappedCond, OpVT.getSimpleVT()))
2417       return SDValue();
2418     return getSetCC(dl, VT, N2, N1, SwappedCond);
2419   } else if ((N2CFP && N2CFP->getValueAPF().isNaN()) ||
2420              (OpVT.isFloatingPoint() && (N1.isUndef() || N2.isUndef()))) {
2421     // If an operand is known to be a nan (or undef that could be a nan), we can
2422     // fold it.
2423     // Choosing NaN for the undef will always make unordered comparison succeed
2424     // and ordered comparison fails.
2425     // Matches behavior in llvm::ConstantFoldCompareInstruction.
2426     switch (ISD::getUnorderedFlavor(Cond)) {
2427     default:
2428       llvm_unreachable("Unknown flavor!");
2429     case 0: // Known false.
2430       return getBoolConstant(false, dl, VT, OpVT);
2431     case 1: // Known true.
2432       return getBoolConstant(true, dl, VT, OpVT);
2433     case 2: // Undefined.
2434       return getUNDEF(VT);
2435     }
2436   }
2437 
2438   // Could not fold it.
2439   return SDValue();
2440 }
2441 
2442 /// See if the specified operand can be simplified with the knowledge that only
2443 /// the bits specified by DemandedBits are used.
2444 /// TODO: really we should be making this into the DAG equivalent of
2445 /// SimplifyMultipleUseDemandedBits and not generate any new nodes.
2446 SDValue SelectionDAG::GetDemandedBits(SDValue V, const APInt &DemandedBits) {
2447   EVT VT = V.getValueType();
2448 
2449   if (VT.isScalableVector())
2450     return SDValue();
2451 
2452   APInt DemandedElts = VT.isVector()
2453                            ? APInt::getAllOnes(VT.getVectorNumElements())
2454                            : APInt(1, 1);
2455   return GetDemandedBits(V, DemandedBits, DemandedElts);
2456 }
2457 
2458 /// See if the specified operand can be simplified with the knowledge that only
2459 /// the bits specified by DemandedBits are used in the elements specified by
2460 /// DemandedElts.
2461 /// TODO: really we should be making this into the DAG equivalent of
2462 /// SimplifyMultipleUseDemandedBits and not generate any new nodes.
2463 SDValue SelectionDAG::GetDemandedBits(SDValue V, const APInt &DemandedBits,
2464                                       const APInt &DemandedElts) {
2465   switch (V.getOpcode()) {
2466   default:
2467     return TLI->SimplifyMultipleUseDemandedBits(V, DemandedBits, DemandedElts,
2468                                                 *this);
2469   case ISD::Constant: {
2470     const APInt &CVal = cast<ConstantSDNode>(V)->getAPIntValue();
2471     APInt NewVal = CVal & DemandedBits;
2472     if (NewVal != CVal)
2473       return getConstant(NewVal, SDLoc(V), V.getValueType());
2474     break;
2475   }
2476   case ISD::SRL:
2477     // Only look at single-use SRLs.
2478     if (!V.getNode()->hasOneUse())
2479       break;
2480     if (auto *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
2481       // See if we can recursively simplify the LHS.
2482       unsigned Amt = RHSC->getZExtValue();
2483 
2484       // Watch out for shift count overflow though.
2485       if (Amt >= DemandedBits.getBitWidth())
2486         break;
2487       APInt SrcDemandedBits = DemandedBits << Amt;
2488       if (SDValue SimplifyLHS =
2489               GetDemandedBits(V.getOperand(0), SrcDemandedBits))
2490         return getNode(ISD::SRL, SDLoc(V), V.getValueType(), SimplifyLHS,
2491                        V.getOperand(1));
2492     }
2493     break;
2494   }
2495   return SDValue();
2496 }
2497 
2498 /// SignBitIsZero - Return true if the sign bit of Op is known to be zero.  We
2499 /// use this predicate to simplify operations downstream.
2500 bool SelectionDAG::SignBitIsZero(SDValue Op, unsigned Depth) const {
2501   unsigned BitWidth = Op.getScalarValueSizeInBits();
2502   return MaskedValueIsZero(Op, APInt::getSignMask(BitWidth), Depth);
2503 }
2504 
2505 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero.  We use
2506 /// this predicate to simplify operations downstream.  Mask is known to be zero
2507 /// for bits that V cannot have.
2508 bool SelectionDAG::MaskedValueIsZero(SDValue V, const APInt &Mask,
2509                                      unsigned Depth) const {
2510   return Mask.isSubsetOf(computeKnownBits(V, Depth).Zero);
2511 }
2512 
2513 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero in
2514 /// DemandedElts.  We use this predicate to simplify operations downstream.
2515 /// Mask is known to be zero for bits that V cannot have.
2516 bool SelectionDAG::MaskedValueIsZero(SDValue V, const APInt &Mask,
2517                                      const APInt &DemandedElts,
2518                                      unsigned Depth) const {
2519   return Mask.isSubsetOf(computeKnownBits(V, DemandedElts, Depth).Zero);
2520 }
2521 
2522 /// MaskedValueIsAllOnes - Return true if '(Op & Mask) == Mask'.
2523 bool SelectionDAG::MaskedValueIsAllOnes(SDValue V, const APInt &Mask,
2524                                         unsigned Depth) const {
2525   return Mask.isSubsetOf(computeKnownBits(V, Depth).One);
2526 }
2527 
2528 /// isSplatValue - Return true if the vector V has the same value
2529 /// across all DemandedElts. For scalable vectors it does not make
2530 /// sense to specify which elements are demanded or undefined, therefore
2531 /// they are simply ignored.
2532 bool SelectionDAG::isSplatValue(SDValue V, const APInt &DemandedElts,
2533                                 APInt &UndefElts, unsigned Depth) const {
2534   unsigned Opcode = V.getOpcode();
2535   EVT VT = V.getValueType();
2536   assert(VT.isVector() && "Vector type expected");
2537 
2538   if (!VT.isScalableVector() && !DemandedElts)
2539     return false; // No demanded elts, better to assume we don't know anything.
2540 
2541   if (Depth >= MaxRecursionDepth)
2542     return false; // Limit search depth.
2543 
2544   // Deal with some common cases here that work for both fixed and scalable
2545   // vector types.
2546   switch (Opcode) {
2547   case ISD::SPLAT_VECTOR:
2548     UndefElts = V.getOperand(0).isUndef()
2549                     ? APInt::getAllOnes(DemandedElts.getBitWidth())
2550                     : APInt(DemandedElts.getBitWidth(), 0);
2551     return true;
2552   case ISD::ADD:
2553   case ISD::SUB:
2554   case ISD::AND:
2555   case ISD::XOR:
2556   case ISD::OR: {
2557     APInt UndefLHS, UndefRHS;
2558     SDValue LHS = V.getOperand(0);
2559     SDValue RHS = V.getOperand(1);
2560     if (isSplatValue(LHS, DemandedElts, UndefLHS, Depth + 1) &&
2561         isSplatValue(RHS, DemandedElts, UndefRHS, Depth + 1)) {
2562       UndefElts = UndefLHS | UndefRHS;
2563       return true;
2564     }
2565     return false;
2566   }
2567   case ISD::ABS:
2568   case ISD::TRUNCATE:
2569   case ISD::SIGN_EXTEND:
2570   case ISD::ZERO_EXTEND:
2571     return isSplatValue(V.getOperand(0), DemandedElts, UndefElts, Depth + 1);
2572   default:
2573     if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::INTRINSIC_WO_CHAIN ||
2574         Opcode == ISD::INTRINSIC_W_CHAIN || Opcode == ISD::INTRINSIC_VOID)
2575       return TLI->isSplatValueForTargetNode(V, DemandedElts, UndefElts, Depth);
2576     break;
2577 }
2578 
2579   // We don't support other cases than those above for scalable vectors at
2580   // the moment.
2581   if (VT.isScalableVector())
2582     return false;
2583 
2584   unsigned NumElts = VT.getVectorNumElements();
2585   assert(NumElts == DemandedElts.getBitWidth() && "Vector size mismatch");
2586   UndefElts = APInt::getZero(NumElts);
2587 
2588   switch (Opcode) {
2589   case ISD::BUILD_VECTOR: {
2590     SDValue Scl;
2591     for (unsigned i = 0; i != NumElts; ++i) {
2592       SDValue Op = V.getOperand(i);
2593       if (Op.isUndef()) {
2594         UndefElts.setBit(i);
2595         continue;
2596       }
2597       if (!DemandedElts[i])
2598         continue;
2599       if (Scl && Scl != Op)
2600         return false;
2601       Scl = Op;
2602     }
2603     return true;
2604   }
2605   case ISD::VECTOR_SHUFFLE: {
2606     // Check if this is a shuffle node doing a splat or a shuffle of a splat.
2607     APInt DemandedLHS = APInt::getNullValue(NumElts);
2608     APInt DemandedRHS = APInt::getNullValue(NumElts);
2609     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(V)->getMask();
2610     for (int i = 0; i != (int)NumElts; ++i) {
2611       int M = Mask[i];
2612       if (M < 0) {
2613         UndefElts.setBit(i);
2614         continue;
2615       }
2616       if (!DemandedElts[i])
2617         continue;
2618       if (M < (int)NumElts)
2619         DemandedLHS.setBit(M);
2620       else
2621         DemandedRHS.setBit(M - NumElts);
2622     }
2623 
2624     // If we aren't demanding either op, assume there's no splat.
2625     // If we are demanding both ops, assume there's no splat.
2626     if ((DemandedLHS.isZero() && DemandedRHS.isZero()) ||
2627         (!DemandedLHS.isZero() && !DemandedRHS.isZero()))
2628       return false;
2629 
2630     // See if the demanded elts of the source op is a splat or we only demand
2631     // one element, which should always be a splat.
2632     // TODO: Handle source ops splats with undefs.
2633     auto CheckSplatSrc = [&](SDValue Src, const APInt &SrcElts) {
2634       APInt SrcUndefs;
2635       return (SrcElts.countPopulation() == 1) ||
2636              (isSplatValue(Src, SrcElts, SrcUndefs, Depth + 1) &&
2637               (SrcElts & SrcUndefs).isZero());
2638     };
2639     if (!DemandedLHS.isZero())
2640       return CheckSplatSrc(V.getOperand(0), DemandedLHS);
2641     return CheckSplatSrc(V.getOperand(1), DemandedRHS);
2642   }
2643   case ISD::EXTRACT_SUBVECTOR: {
2644     // Offset the demanded elts by the subvector index.
2645     SDValue Src = V.getOperand(0);
2646     // We don't support scalable vectors at the moment.
2647     if (Src.getValueType().isScalableVector())
2648       return false;
2649     uint64_t Idx = V.getConstantOperandVal(1);
2650     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
2651     APInt UndefSrcElts;
2652     APInt DemandedSrcElts = DemandedElts.zextOrSelf(NumSrcElts).shl(Idx);
2653     if (isSplatValue(Src, DemandedSrcElts, UndefSrcElts, Depth + 1)) {
2654       UndefElts = UndefSrcElts.extractBits(NumElts, Idx);
2655       return true;
2656     }
2657     break;
2658   }
2659   case ISD::ANY_EXTEND_VECTOR_INREG:
2660   case ISD::SIGN_EXTEND_VECTOR_INREG:
2661   case ISD::ZERO_EXTEND_VECTOR_INREG: {
2662     // Widen the demanded elts by the src element count.
2663     SDValue Src = V.getOperand(0);
2664     // We don't support scalable vectors at the moment.
2665     if (Src.getValueType().isScalableVector())
2666       return false;
2667     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
2668     APInt UndefSrcElts;
2669     APInt DemandedSrcElts = DemandedElts.zextOrSelf(NumSrcElts);
2670     if (isSplatValue(Src, DemandedSrcElts, UndefSrcElts, Depth + 1)) {
2671       UndefElts = UndefSrcElts.truncOrSelf(NumElts);
2672       return true;
2673     }
2674     break;
2675   }
2676   case ISD::BITCAST: {
2677     SDValue Src = V.getOperand(0);
2678     EVT SrcVT = Src.getValueType();
2679     unsigned SrcBitWidth = SrcVT.getScalarSizeInBits();
2680     unsigned BitWidth = VT.getScalarSizeInBits();
2681 
2682     // Ignore bitcasts from unsupported types.
2683     // TODO: Add fp support?
2684     if (!SrcVT.isVector() || !SrcVT.isInteger() || !VT.isInteger())
2685       break;
2686 
2687     // Bitcast 'small element' vector to 'large element' vector.
2688     if ((BitWidth % SrcBitWidth) == 0) {
2689       // See if each sub element is a splat.
2690       unsigned Scale = BitWidth / SrcBitWidth;
2691       unsigned NumSrcElts = SrcVT.getVectorNumElements();
2692       APInt ScaledDemandedElts =
2693           APIntOps::ScaleBitMask(DemandedElts, NumSrcElts);
2694       for (unsigned I = 0; I != Scale; ++I) {
2695         APInt SubUndefElts;
2696         APInt SubDemandedElt = APInt::getOneBitSet(Scale, I);
2697         APInt SubDemandedElts = APInt::getSplat(NumSrcElts, SubDemandedElt);
2698         SubDemandedElts &= ScaledDemandedElts;
2699         if (!isSplatValue(Src, SubDemandedElts, SubUndefElts, Depth + 1))
2700           return false;
2701         // TODO: Add support for merging sub undef elements.
2702         if (SubDemandedElts.isSubsetOf(SubUndefElts))
2703           return false;
2704       }
2705       return true;
2706     }
2707     break;
2708   }
2709   }
2710 
2711   return false;
2712 }
2713 
2714 /// Helper wrapper to main isSplatValue function.
2715 bool SelectionDAG::isSplatValue(SDValue V, bool AllowUndefs) const {
2716   EVT VT = V.getValueType();
2717   assert(VT.isVector() && "Vector type expected");
2718 
2719   APInt UndefElts;
2720   APInt DemandedElts;
2721 
2722   // For now we don't support this with scalable vectors.
2723   if (!VT.isScalableVector())
2724     DemandedElts = APInt::getAllOnes(VT.getVectorNumElements());
2725   return isSplatValue(V, DemandedElts, UndefElts) &&
2726          (AllowUndefs || !UndefElts);
2727 }
2728 
2729 SDValue SelectionDAG::getSplatSourceVector(SDValue V, int &SplatIdx) {
2730   V = peekThroughExtractSubvectors(V);
2731 
2732   EVT VT = V.getValueType();
2733   unsigned Opcode = V.getOpcode();
2734   switch (Opcode) {
2735   default: {
2736     APInt UndefElts;
2737     APInt DemandedElts;
2738 
2739     if (!VT.isScalableVector())
2740       DemandedElts = APInt::getAllOnes(VT.getVectorNumElements());
2741 
2742     if (isSplatValue(V, DemandedElts, UndefElts)) {
2743       if (VT.isScalableVector()) {
2744         // DemandedElts and UndefElts are ignored for scalable vectors, since
2745         // the only supported cases are SPLAT_VECTOR nodes.
2746         SplatIdx = 0;
2747       } else {
2748         // Handle case where all demanded elements are UNDEF.
2749         if (DemandedElts.isSubsetOf(UndefElts)) {
2750           SplatIdx = 0;
2751           return getUNDEF(VT);
2752         }
2753         SplatIdx = (UndefElts & DemandedElts).countTrailingOnes();
2754       }
2755       return V;
2756     }
2757     break;
2758   }
2759   case ISD::SPLAT_VECTOR:
2760     SplatIdx = 0;
2761     return V;
2762   case ISD::VECTOR_SHUFFLE: {
2763     if (VT.isScalableVector())
2764       return SDValue();
2765 
2766     // Check if this is a shuffle node doing a splat.
2767     // TODO - remove this and rely purely on SelectionDAG::isSplatValue,
2768     // getTargetVShiftNode currently struggles without the splat source.
2769     auto *SVN = cast<ShuffleVectorSDNode>(V);
2770     if (!SVN->isSplat())
2771       break;
2772     int Idx = SVN->getSplatIndex();
2773     int NumElts = V.getValueType().getVectorNumElements();
2774     SplatIdx = Idx % NumElts;
2775     return V.getOperand(Idx / NumElts);
2776   }
2777   }
2778 
2779   return SDValue();
2780 }
2781 
2782 SDValue SelectionDAG::getSplatValue(SDValue V, bool LegalTypes) {
2783   int SplatIdx;
2784   if (SDValue SrcVector = getSplatSourceVector(V, SplatIdx)) {
2785     EVT SVT = SrcVector.getValueType().getScalarType();
2786     EVT LegalSVT = SVT;
2787     if (LegalTypes && !TLI->isTypeLegal(SVT)) {
2788       if (!SVT.isInteger())
2789         return SDValue();
2790       LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT);
2791       if (LegalSVT.bitsLT(SVT))
2792         return SDValue();
2793     }
2794     return getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(V), LegalSVT, SrcVector,
2795                    getVectorIdxConstant(SplatIdx, SDLoc(V)));
2796   }
2797   return SDValue();
2798 }
2799 
2800 const APInt *
2801 SelectionDAG::getValidShiftAmountConstant(SDValue V,
2802                                           const APInt &DemandedElts) const {
2803   assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL ||
2804           V.getOpcode() == ISD::SRA) &&
2805          "Unknown shift node");
2806   unsigned BitWidth = V.getScalarValueSizeInBits();
2807   if (ConstantSDNode *SA = isConstOrConstSplat(V.getOperand(1), DemandedElts)) {
2808     // Shifting more than the bitwidth is not valid.
2809     const APInt &ShAmt = SA->getAPIntValue();
2810     if (ShAmt.ult(BitWidth))
2811       return &ShAmt;
2812   }
2813   return nullptr;
2814 }
2815 
2816 const APInt *SelectionDAG::getValidMinimumShiftAmountConstant(
2817     SDValue V, const APInt &DemandedElts) const {
2818   assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL ||
2819           V.getOpcode() == ISD::SRA) &&
2820          "Unknown shift node");
2821   if (const APInt *ValidAmt = getValidShiftAmountConstant(V, DemandedElts))
2822     return ValidAmt;
2823   unsigned BitWidth = V.getScalarValueSizeInBits();
2824   auto *BV = dyn_cast<BuildVectorSDNode>(V.getOperand(1));
2825   if (!BV)
2826     return nullptr;
2827   const APInt *MinShAmt = nullptr;
2828   for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
2829     if (!DemandedElts[i])
2830       continue;
2831     auto *SA = dyn_cast<ConstantSDNode>(BV->getOperand(i));
2832     if (!SA)
2833       return nullptr;
2834     // Shifting more than the bitwidth is not valid.
2835     const APInt &ShAmt = SA->getAPIntValue();
2836     if (ShAmt.uge(BitWidth))
2837       return nullptr;
2838     if (MinShAmt && MinShAmt->ule(ShAmt))
2839       continue;
2840     MinShAmt = &ShAmt;
2841   }
2842   return MinShAmt;
2843 }
2844 
2845 const APInt *SelectionDAG::getValidMaximumShiftAmountConstant(
2846     SDValue V, const APInt &DemandedElts) const {
2847   assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL ||
2848           V.getOpcode() == ISD::SRA) &&
2849          "Unknown shift node");
2850   if (const APInt *ValidAmt = getValidShiftAmountConstant(V, DemandedElts))
2851     return ValidAmt;
2852   unsigned BitWidth = V.getScalarValueSizeInBits();
2853   auto *BV = dyn_cast<BuildVectorSDNode>(V.getOperand(1));
2854   if (!BV)
2855     return nullptr;
2856   const APInt *MaxShAmt = nullptr;
2857   for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
2858     if (!DemandedElts[i])
2859       continue;
2860     auto *SA = dyn_cast<ConstantSDNode>(BV->getOperand(i));
2861     if (!SA)
2862       return nullptr;
2863     // Shifting more than the bitwidth is not valid.
2864     const APInt &ShAmt = SA->getAPIntValue();
2865     if (ShAmt.uge(BitWidth))
2866       return nullptr;
2867     if (MaxShAmt && MaxShAmt->uge(ShAmt))
2868       continue;
2869     MaxShAmt = &ShAmt;
2870   }
2871   return MaxShAmt;
2872 }
2873 
2874 /// Determine which bits of Op are known to be either zero or one and return
2875 /// them in Known. For vectors, the known bits are those that are shared by
2876 /// every vector element.
2877 KnownBits SelectionDAG::computeKnownBits(SDValue Op, unsigned Depth) const {
2878   EVT VT = Op.getValueType();
2879 
2880   // TOOD: Until we have a plan for how to represent demanded elements for
2881   // scalable vectors, we can just bail out for now.
2882   if (Op.getValueType().isScalableVector()) {
2883     unsigned BitWidth = Op.getScalarValueSizeInBits();
2884     return KnownBits(BitWidth);
2885   }
2886 
2887   APInt DemandedElts = VT.isVector()
2888                            ? APInt::getAllOnes(VT.getVectorNumElements())
2889                            : APInt(1, 1);
2890   return computeKnownBits(Op, DemandedElts, Depth);
2891 }
2892 
2893 /// Determine which bits of Op are known to be either zero or one and return
2894 /// them in Known. The DemandedElts argument allows us to only collect the known
2895 /// bits that are shared by the requested vector elements.
2896 KnownBits SelectionDAG::computeKnownBits(SDValue Op, const APInt &DemandedElts,
2897                                          unsigned Depth) const {
2898   unsigned BitWidth = Op.getScalarValueSizeInBits();
2899 
2900   KnownBits Known(BitWidth);   // Don't know anything.
2901 
2902   // TOOD: Until we have a plan for how to represent demanded elements for
2903   // scalable vectors, we can just bail out for now.
2904   if (Op.getValueType().isScalableVector())
2905     return Known;
2906 
2907   if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
2908     // We know all of the bits for a constant!
2909     return KnownBits::makeConstant(C->getAPIntValue());
2910   }
2911   if (auto *C = dyn_cast<ConstantFPSDNode>(Op)) {
2912     // We know all of the bits for a constant fp!
2913     return KnownBits::makeConstant(C->getValueAPF().bitcastToAPInt());
2914   }
2915 
2916   if (Depth >= MaxRecursionDepth)
2917     return Known;  // Limit search depth.
2918 
2919   KnownBits Known2;
2920   unsigned NumElts = DemandedElts.getBitWidth();
2921   assert((!Op.getValueType().isVector() ||
2922           NumElts == Op.getValueType().getVectorNumElements()) &&
2923          "Unexpected vector size");
2924 
2925   if (!DemandedElts)
2926     return Known;  // No demanded elts, better to assume we don't know anything.
2927 
2928   unsigned Opcode = Op.getOpcode();
2929   switch (Opcode) {
2930   case ISD::BUILD_VECTOR:
2931     // Collect the known bits that are shared by every demanded vector element.
2932     Known.Zero.setAllBits(); Known.One.setAllBits();
2933     for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
2934       if (!DemandedElts[i])
2935         continue;
2936 
2937       SDValue SrcOp = Op.getOperand(i);
2938       Known2 = computeKnownBits(SrcOp, Depth + 1);
2939 
2940       // BUILD_VECTOR can implicitly truncate sources, we must handle this.
2941       if (SrcOp.getValueSizeInBits() != BitWidth) {
2942         assert(SrcOp.getValueSizeInBits() > BitWidth &&
2943                "Expected BUILD_VECTOR implicit truncation");
2944         Known2 = Known2.trunc(BitWidth);
2945       }
2946 
2947       // Known bits are the values that are shared by every demanded element.
2948       Known = KnownBits::commonBits(Known, Known2);
2949 
2950       // If we don't know any bits, early out.
2951       if (Known.isUnknown())
2952         break;
2953     }
2954     break;
2955   case ISD::VECTOR_SHUFFLE: {
2956     // Collect the known bits that are shared by every vector element referenced
2957     // by the shuffle.
2958     APInt DemandedLHS(NumElts, 0), DemandedRHS(NumElts, 0);
2959     Known.Zero.setAllBits(); Known.One.setAllBits();
2960     const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op);
2961     assert(NumElts == SVN->getMask().size() && "Unexpected vector size");
2962     for (unsigned i = 0; i != NumElts; ++i) {
2963       if (!DemandedElts[i])
2964         continue;
2965 
2966       int M = SVN->getMaskElt(i);
2967       if (M < 0) {
2968         // For UNDEF elements, we don't know anything about the common state of
2969         // the shuffle result.
2970         Known.resetAll();
2971         DemandedLHS.clearAllBits();
2972         DemandedRHS.clearAllBits();
2973         break;
2974       }
2975 
2976       if ((unsigned)M < NumElts)
2977         DemandedLHS.setBit((unsigned)M % NumElts);
2978       else
2979         DemandedRHS.setBit((unsigned)M % NumElts);
2980     }
2981     // Known bits are the values that are shared by every demanded element.
2982     if (!!DemandedLHS) {
2983       SDValue LHS = Op.getOperand(0);
2984       Known2 = computeKnownBits(LHS, DemandedLHS, Depth + 1);
2985       Known = KnownBits::commonBits(Known, Known2);
2986     }
2987     // If we don't know any bits, early out.
2988     if (Known.isUnknown())
2989       break;
2990     if (!!DemandedRHS) {
2991       SDValue RHS = Op.getOperand(1);
2992       Known2 = computeKnownBits(RHS, DemandedRHS, Depth + 1);
2993       Known = KnownBits::commonBits(Known, Known2);
2994     }
2995     break;
2996   }
2997   case ISD::CONCAT_VECTORS: {
2998     // Split DemandedElts and test each of the demanded subvectors.
2999     Known.Zero.setAllBits(); Known.One.setAllBits();
3000     EVT SubVectorVT = Op.getOperand(0).getValueType();
3001     unsigned NumSubVectorElts = SubVectorVT.getVectorNumElements();
3002     unsigned NumSubVectors = Op.getNumOperands();
3003     for (unsigned i = 0; i != NumSubVectors; ++i) {
3004       APInt DemandedSub =
3005           DemandedElts.extractBits(NumSubVectorElts, i * NumSubVectorElts);
3006       if (!!DemandedSub) {
3007         SDValue Sub = Op.getOperand(i);
3008         Known2 = computeKnownBits(Sub, DemandedSub, Depth + 1);
3009         Known = KnownBits::commonBits(Known, Known2);
3010       }
3011       // If we don't know any bits, early out.
3012       if (Known.isUnknown())
3013         break;
3014     }
3015     break;
3016   }
3017   case ISD::INSERT_SUBVECTOR: {
3018     // Demand any elements from the subvector and the remainder from the src its
3019     // inserted into.
3020     SDValue Src = Op.getOperand(0);
3021     SDValue Sub = Op.getOperand(1);
3022     uint64_t Idx = Op.getConstantOperandVal(2);
3023     unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
3024     APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
3025     APInt DemandedSrcElts = DemandedElts;
3026     DemandedSrcElts.insertBits(APInt::getZero(NumSubElts), Idx);
3027 
3028     Known.One.setAllBits();
3029     Known.Zero.setAllBits();
3030     if (!!DemandedSubElts) {
3031       Known = computeKnownBits(Sub, DemandedSubElts, Depth + 1);
3032       if (Known.isUnknown())
3033         break; // early-out.
3034     }
3035     if (!!DemandedSrcElts) {
3036       Known2 = computeKnownBits(Src, DemandedSrcElts, Depth + 1);
3037       Known = KnownBits::commonBits(Known, Known2);
3038     }
3039     break;
3040   }
3041   case ISD::EXTRACT_SUBVECTOR: {
3042     // Offset the demanded elts by the subvector index.
3043     SDValue Src = Op.getOperand(0);
3044     // Bail until we can represent demanded elements for scalable vectors.
3045     if (Src.getValueType().isScalableVector())
3046       break;
3047     uint64_t Idx = Op.getConstantOperandVal(1);
3048     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
3049     APInt DemandedSrcElts = DemandedElts.zextOrSelf(NumSrcElts).shl(Idx);
3050     Known = computeKnownBits(Src, DemandedSrcElts, Depth + 1);
3051     break;
3052   }
3053   case ISD::SCALAR_TO_VECTOR: {
3054     // We know about scalar_to_vector as much as we know about it source,
3055     // which becomes the first element of otherwise unknown vector.
3056     if (DemandedElts != 1)
3057       break;
3058 
3059     SDValue N0 = Op.getOperand(0);
3060     Known = computeKnownBits(N0, Depth + 1);
3061     if (N0.getValueSizeInBits() != BitWidth)
3062       Known = Known.trunc(BitWidth);
3063 
3064     break;
3065   }
3066   case ISD::BITCAST: {
3067     SDValue N0 = Op.getOperand(0);
3068     EVT SubVT = N0.getValueType();
3069     unsigned SubBitWidth = SubVT.getScalarSizeInBits();
3070 
3071     // Ignore bitcasts from unsupported types.
3072     if (!(SubVT.isInteger() || SubVT.isFloatingPoint()))
3073       break;
3074 
3075     // Fast handling of 'identity' bitcasts.
3076     if (BitWidth == SubBitWidth) {
3077       Known = computeKnownBits(N0, DemandedElts, Depth + 1);
3078       break;
3079     }
3080 
3081     bool IsLE = getDataLayout().isLittleEndian();
3082 
3083     // Bitcast 'small element' vector to 'large element' scalar/vector.
3084     if ((BitWidth % SubBitWidth) == 0) {
3085       assert(N0.getValueType().isVector() && "Expected bitcast from vector");
3086 
3087       // Collect known bits for the (larger) output by collecting the known
3088       // bits from each set of sub elements and shift these into place.
3089       // We need to separately call computeKnownBits for each set of
3090       // sub elements as the knownbits for each is likely to be different.
3091       unsigned SubScale = BitWidth / SubBitWidth;
3092       APInt SubDemandedElts(NumElts * SubScale, 0);
3093       for (unsigned i = 0; i != NumElts; ++i)
3094         if (DemandedElts[i])
3095           SubDemandedElts.setBit(i * SubScale);
3096 
3097       for (unsigned i = 0; i != SubScale; ++i) {
3098         Known2 = computeKnownBits(N0, SubDemandedElts.shl(i),
3099                          Depth + 1);
3100         unsigned Shifts = IsLE ? i : SubScale - 1 - i;
3101         Known.insertBits(Known2, SubBitWidth * Shifts);
3102       }
3103     }
3104 
3105     // Bitcast 'large element' scalar/vector to 'small element' vector.
3106     if ((SubBitWidth % BitWidth) == 0) {
3107       assert(Op.getValueType().isVector() && "Expected bitcast to vector");
3108 
3109       // Collect known bits for the (smaller) output by collecting the known
3110       // bits from the overlapping larger input elements and extracting the
3111       // sub sections we actually care about.
3112       unsigned SubScale = SubBitWidth / BitWidth;
3113       APInt SubDemandedElts =
3114           APIntOps::ScaleBitMask(DemandedElts, NumElts / SubScale);
3115       Known2 = computeKnownBits(N0, SubDemandedElts, Depth + 1);
3116 
3117       Known.Zero.setAllBits(); Known.One.setAllBits();
3118       for (unsigned i = 0; i != NumElts; ++i)
3119         if (DemandedElts[i]) {
3120           unsigned Shifts = IsLE ? i : NumElts - 1 - i;
3121           unsigned Offset = (Shifts % SubScale) * BitWidth;
3122           Known = KnownBits::commonBits(Known,
3123                                         Known2.extractBits(BitWidth, Offset));
3124           // If we don't know any bits, early out.
3125           if (Known.isUnknown())
3126             break;
3127         }
3128     }
3129     break;
3130   }
3131   case ISD::AND:
3132     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3133     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3134 
3135     Known &= Known2;
3136     break;
3137   case ISD::OR:
3138     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3139     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3140 
3141     Known |= Known2;
3142     break;
3143   case ISD::XOR:
3144     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3145     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3146 
3147     Known ^= Known2;
3148     break;
3149   case ISD::MUL: {
3150     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3151     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3152     bool SelfMultiply = Op.getOperand(0) == Op.getOperand(1);
3153     // TODO: SelfMultiply can be poison, but not undef.
3154     if (SelfMultiply)
3155       SelfMultiply &= isGuaranteedNotToBeUndefOrPoison(
3156           Op.getOperand(0), DemandedElts, false, Depth + 1);
3157     Known = KnownBits::mul(Known, Known2, SelfMultiply);
3158     break;
3159   }
3160   case ISD::MULHU: {
3161     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3162     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3163     Known = KnownBits::mulhu(Known, Known2);
3164     break;
3165   }
3166   case ISD::MULHS: {
3167     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3168     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3169     Known = KnownBits::mulhs(Known, Known2);
3170     break;
3171   }
3172   case ISD::UMUL_LOHI: {
3173     assert((Op.getResNo() == 0 || Op.getResNo() == 1) && "Unknown result");
3174     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3175     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3176     bool SelfMultiply = Op.getOperand(0) == Op.getOperand(1);
3177     if (Op.getResNo() == 0)
3178       Known = KnownBits::mul(Known, Known2, SelfMultiply);
3179     else
3180       Known = KnownBits::mulhu(Known, Known2);
3181     break;
3182   }
3183   case ISD::SMUL_LOHI: {
3184     assert((Op.getResNo() == 0 || Op.getResNo() == 1) && "Unknown result");
3185     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3186     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3187     bool SelfMultiply = Op.getOperand(0) == Op.getOperand(1);
3188     if (Op.getResNo() == 0)
3189       Known = KnownBits::mul(Known, Known2, SelfMultiply);
3190     else
3191       Known = KnownBits::mulhs(Known, Known2);
3192     break;
3193   }
3194   case ISD::UDIV: {
3195     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3196     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3197     Known = KnownBits::udiv(Known, Known2);
3198     break;
3199   }
3200   case ISD::AVGCEILU: {
3201     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3202     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3203     Known = Known.zext(BitWidth + 1);
3204     Known2 = Known2.zext(BitWidth + 1);
3205     KnownBits One = KnownBits::makeConstant(APInt(1, 1));
3206     Known = KnownBits::computeForAddCarry(Known, Known2, One);
3207     Known = Known.extractBits(BitWidth, 1);
3208     break;
3209   }
3210   case ISD::SELECT:
3211   case ISD::VSELECT:
3212     Known = computeKnownBits(Op.getOperand(2), DemandedElts, Depth+1);
3213     // If we don't know any bits, early out.
3214     if (Known.isUnknown())
3215       break;
3216     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth+1);
3217 
3218     // Only known if known in both the LHS and RHS.
3219     Known = KnownBits::commonBits(Known, Known2);
3220     break;
3221   case ISD::SELECT_CC:
3222     Known = computeKnownBits(Op.getOperand(3), DemandedElts, Depth+1);
3223     // If we don't know any bits, early out.
3224     if (Known.isUnknown())
3225       break;
3226     Known2 = computeKnownBits(Op.getOperand(2), DemandedElts, Depth+1);
3227 
3228     // Only known if known in both the LHS and RHS.
3229     Known = KnownBits::commonBits(Known, Known2);
3230     break;
3231   case ISD::SMULO:
3232   case ISD::UMULO:
3233     if (Op.getResNo() != 1)
3234       break;
3235     // The boolean result conforms to getBooleanContents.
3236     // If we know the result of a setcc has the top bits zero, use this info.
3237     // We know that we have an integer-based boolean since these operations
3238     // are only available for integer.
3239     if (TLI->getBooleanContents(Op.getValueType().isVector(), false) ==
3240             TargetLowering::ZeroOrOneBooleanContent &&
3241         BitWidth > 1)
3242       Known.Zero.setBitsFrom(1);
3243     break;
3244   case ISD::SETCC:
3245   case ISD::STRICT_FSETCC:
3246   case ISD::STRICT_FSETCCS: {
3247     unsigned OpNo = Op->isStrictFPOpcode() ? 1 : 0;
3248     // If we know the result of a setcc has the top bits zero, use this info.
3249     if (TLI->getBooleanContents(Op.getOperand(OpNo).getValueType()) ==
3250             TargetLowering::ZeroOrOneBooleanContent &&
3251         BitWidth > 1)
3252       Known.Zero.setBitsFrom(1);
3253     break;
3254   }
3255   case ISD::SHL:
3256     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3257     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3258     Known = KnownBits::shl(Known, Known2);
3259 
3260     // Minimum shift low bits are known zero.
3261     if (const APInt *ShMinAmt =
3262             getValidMinimumShiftAmountConstant(Op, DemandedElts))
3263       Known.Zero.setLowBits(ShMinAmt->getZExtValue());
3264     break;
3265   case ISD::SRL:
3266     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3267     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3268     Known = KnownBits::lshr(Known, Known2);
3269 
3270     // Minimum shift high bits are known zero.
3271     if (const APInt *ShMinAmt =
3272             getValidMinimumShiftAmountConstant(Op, DemandedElts))
3273       Known.Zero.setHighBits(ShMinAmt->getZExtValue());
3274     break;
3275   case ISD::SRA:
3276     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3277     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3278     Known = KnownBits::ashr(Known, Known2);
3279     // TODO: Add minimum shift high known sign bits.
3280     break;
3281   case ISD::FSHL:
3282   case ISD::FSHR:
3283     if (ConstantSDNode *C = isConstOrConstSplat(Op.getOperand(2), DemandedElts)) {
3284       unsigned Amt = C->getAPIntValue().urem(BitWidth);
3285 
3286       // For fshl, 0-shift returns the 1st arg.
3287       // For fshr, 0-shift returns the 2nd arg.
3288       if (Amt == 0) {
3289         Known = computeKnownBits(Op.getOperand(Opcode == ISD::FSHL ? 0 : 1),
3290                                  DemandedElts, Depth + 1);
3291         break;
3292       }
3293 
3294       // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW)))
3295       // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW))
3296       Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3297       Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3298       if (Opcode == ISD::FSHL) {
3299         Known.One <<= Amt;
3300         Known.Zero <<= Amt;
3301         Known2.One.lshrInPlace(BitWidth - Amt);
3302         Known2.Zero.lshrInPlace(BitWidth - Amt);
3303       } else {
3304         Known.One <<= BitWidth - Amt;
3305         Known.Zero <<= BitWidth - Amt;
3306         Known2.One.lshrInPlace(Amt);
3307         Known2.Zero.lshrInPlace(Amt);
3308       }
3309       Known.One |= Known2.One;
3310       Known.Zero |= Known2.Zero;
3311     }
3312     break;
3313   case ISD::SIGN_EXTEND_INREG: {
3314     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3315     EVT EVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
3316     Known = Known.sextInReg(EVT.getScalarSizeInBits());
3317     break;
3318   }
3319   case ISD::CTTZ:
3320   case ISD::CTTZ_ZERO_UNDEF: {
3321     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3322     // If we have a known 1, its position is our upper bound.
3323     unsigned PossibleTZ = Known2.countMaxTrailingZeros();
3324     unsigned LowBits = Log2_32(PossibleTZ) + 1;
3325     Known.Zero.setBitsFrom(LowBits);
3326     break;
3327   }
3328   case ISD::CTLZ:
3329   case ISD::CTLZ_ZERO_UNDEF: {
3330     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3331     // If we have a known 1, its position is our upper bound.
3332     unsigned PossibleLZ = Known2.countMaxLeadingZeros();
3333     unsigned LowBits = Log2_32(PossibleLZ) + 1;
3334     Known.Zero.setBitsFrom(LowBits);
3335     break;
3336   }
3337   case ISD::CTPOP: {
3338     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3339     // If we know some of the bits are zero, they can't be one.
3340     unsigned PossibleOnes = Known2.countMaxPopulation();
3341     Known.Zero.setBitsFrom(Log2_32(PossibleOnes) + 1);
3342     break;
3343   }
3344   case ISD::PARITY: {
3345     // Parity returns 0 everywhere but the LSB.
3346     Known.Zero.setBitsFrom(1);
3347     break;
3348   }
3349   case ISD::LOAD: {
3350     LoadSDNode *LD = cast<LoadSDNode>(Op);
3351     const Constant *Cst = TLI->getTargetConstantFromLoad(LD);
3352     if (ISD::isNON_EXTLoad(LD) && Cst) {
3353       // Determine any common known bits from the loaded constant pool value.
3354       Type *CstTy = Cst->getType();
3355       if ((NumElts * BitWidth) == CstTy->getPrimitiveSizeInBits()) {
3356         // If its a vector splat, then we can (quickly) reuse the scalar path.
3357         // NOTE: We assume all elements match and none are UNDEF.
3358         if (CstTy->isVectorTy()) {
3359           if (const Constant *Splat = Cst->getSplatValue()) {
3360             Cst = Splat;
3361             CstTy = Cst->getType();
3362           }
3363         }
3364         // TODO - do we need to handle different bitwidths?
3365         if (CstTy->isVectorTy() && BitWidth == CstTy->getScalarSizeInBits()) {
3366           // Iterate across all vector elements finding common known bits.
3367           Known.One.setAllBits();
3368           Known.Zero.setAllBits();
3369           for (unsigned i = 0; i != NumElts; ++i) {
3370             if (!DemandedElts[i])
3371               continue;
3372             if (Constant *Elt = Cst->getAggregateElement(i)) {
3373               if (auto *CInt = dyn_cast<ConstantInt>(Elt)) {
3374                 const APInt &Value = CInt->getValue();
3375                 Known.One &= Value;
3376                 Known.Zero &= ~Value;
3377                 continue;
3378               }
3379               if (auto *CFP = dyn_cast<ConstantFP>(Elt)) {
3380                 APInt Value = CFP->getValueAPF().bitcastToAPInt();
3381                 Known.One &= Value;
3382                 Known.Zero &= ~Value;
3383                 continue;
3384               }
3385             }
3386             Known.One.clearAllBits();
3387             Known.Zero.clearAllBits();
3388             break;
3389           }
3390         } else if (BitWidth == CstTy->getPrimitiveSizeInBits()) {
3391           if (auto *CInt = dyn_cast<ConstantInt>(Cst)) {
3392             Known = KnownBits::makeConstant(CInt->getValue());
3393           } else if (auto *CFP = dyn_cast<ConstantFP>(Cst)) {
3394             Known =
3395                 KnownBits::makeConstant(CFP->getValueAPF().bitcastToAPInt());
3396           }
3397         }
3398       }
3399     } else if (ISD::isZEXTLoad(Op.getNode()) && Op.getResNo() == 0) {
3400       // If this is a ZEXTLoad and we are looking at the loaded value.
3401       EVT VT = LD->getMemoryVT();
3402       unsigned MemBits = VT.getScalarSizeInBits();
3403       Known.Zero.setBitsFrom(MemBits);
3404     } else if (const MDNode *Ranges = LD->getRanges()) {
3405       if (LD->getExtensionType() == ISD::NON_EXTLOAD)
3406         computeKnownBitsFromRangeMetadata(*Ranges, Known);
3407     }
3408     break;
3409   }
3410   case ISD::ZERO_EXTEND_VECTOR_INREG: {
3411     EVT InVT = Op.getOperand(0).getValueType();
3412     APInt InDemandedElts = DemandedElts.zextOrSelf(InVT.getVectorNumElements());
3413     Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1);
3414     Known = Known.zext(BitWidth);
3415     break;
3416   }
3417   case ISD::ZERO_EXTEND: {
3418     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3419     Known = Known.zext(BitWidth);
3420     break;
3421   }
3422   case ISD::SIGN_EXTEND_VECTOR_INREG: {
3423     EVT InVT = Op.getOperand(0).getValueType();
3424     APInt InDemandedElts = DemandedElts.zextOrSelf(InVT.getVectorNumElements());
3425     Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1);
3426     // If the sign bit is known to be zero or one, then sext will extend
3427     // it to the top bits, else it will just zext.
3428     Known = Known.sext(BitWidth);
3429     break;
3430   }
3431   case ISD::SIGN_EXTEND: {
3432     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3433     // If the sign bit is known to be zero or one, then sext will extend
3434     // it to the top bits, else it will just zext.
3435     Known = Known.sext(BitWidth);
3436     break;
3437   }
3438   case ISD::ANY_EXTEND_VECTOR_INREG: {
3439     EVT InVT = Op.getOperand(0).getValueType();
3440     APInt InDemandedElts = DemandedElts.zextOrSelf(InVT.getVectorNumElements());
3441     Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1);
3442     Known = Known.anyext(BitWidth);
3443     break;
3444   }
3445   case ISD::ANY_EXTEND: {
3446     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3447     Known = Known.anyext(BitWidth);
3448     break;
3449   }
3450   case ISD::TRUNCATE: {
3451     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3452     Known = Known.trunc(BitWidth);
3453     break;
3454   }
3455   case ISD::AssertZext: {
3456     EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
3457     APInt InMask = APInt::getLowBitsSet(BitWidth, VT.getSizeInBits());
3458     Known = computeKnownBits(Op.getOperand(0), Depth+1);
3459     Known.Zero |= (~InMask);
3460     Known.One  &= (~Known.Zero);
3461     break;
3462   }
3463   case ISD::AssertAlign: {
3464     unsigned LogOfAlign = Log2(cast<AssertAlignSDNode>(Op)->getAlign());
3465     assert(LogOfAlign != 0);
3466 
3467     // TODO: Should use maximum with source
3468     // If a node is guaranteed to be aligned, set low zero bits accordingly as
3469     // well as clearing one bits.
3470     Known.Zero.setLowBits(LogOfAlign);
3471     Known.One.clearLowBits(LogOfAlign);
3472     break;
3473   }
3474   case ISD::FGETSIGN:
3475     // All bits are zero except the low bit.
3476     Known.Zero.setBitsFrom(1);
3477     break;
3478   case ISD::USUBO:
3479   case ISD::SSUBO:
3480     if (Op.getResNo() == 1) {
3481       // If we know the result of a setcc has the top bits zero, use this info.
3482       if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) ==
3483               TargetLowering::ZeroOrOneBooleanContent &&
3484           BitWidth > 1)
3485         Known.Zero.setBitsFrom(1);
3486       break;
3487     }
3488     LLVM_FALLTHROUGH;
3489   case ISD::SUB:
3490   case ISD::SUBC: {
3491     assert(Op.getResNo() == 0 &&
3492            "We only compute knownbits for the difference here.");
3493 
3494     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3495     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3496     Known = KnownBits::computeForAddSub(/* Add */ false, /* NSW */ false,
3497                                         Known, Known2);
3498     break;
3499   }
3500   case ISD::UADDO:
3501   case ISD::SADDO:
3502   case ISD::ADDCARRY:
3503     if (Op.getResNo() == 1) {
3504       // If we know the result of a setcc has the top bits zero, use this info.
3505       if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) ==
3506               TargetLowering::ZeroOrOneBooleanContent &&
3507           BitWidth > 1)
3508         Known.Zero.setBitsFrom(1);
3509       break;
3510     }
3511     LLVM_FALLTHROUGH;
3512   case ISD::ADD:
3513   case ISD::ADDC:
3514   case ISD::ADDE: {
3515     assert(Op.getResNo() == 0 && "We only compute knownbits for the sum here.");
3516 
3517     // With ADDE and ADDCARRY, a carry bit may be added in.
3518     KnownBits Carry(1);
3519     if (Opcode == ISD::ADDE)
3520       // Can't track carry from glue, set carry to unknown.
3521       Carry.resetAll();
3522     else if (Opcode == ISD::ADDCARRY)
3523       // TODO: Compute known bits for the carry operand. Not sure if it is worth
3524       // the trouble (how often will we find a known carry bit). And I haven't
3525       // tested this very much yet, but something like this might work:
3526       //   Carry = computeKnownBits(Op.getOperand(2), DemandedElts, Depth + 1);
3527       //   Carry = Carry.zextOrTrunc(1, false);
3528       Carry.resetAll();
3529     else
3530       Carry.setAllZero();
3531 
3532     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3533     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3534     Known = KnownBits::computeForAddCarry(Known, Known2, Carry);
3535     break;
3536   }
3537   case ISD::SREM: {
3538     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3539     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3540     Known = KnownBits::srem(Known, Known2);
3541     break;
3542   }
3543   case ISD::UREM: {
3544     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3545     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3546     Known = KnownBits::urem(Known, Known2);
3547     break;
3548   }
3549   case ISD::EXTRACT_ELEMENT: {
3550     Known = computeKnownBits(Op.getOperand(0), Depth+1);
3551     const unsigned Index = Op.getConstantOperandVal(1);
3552     const unsigned EltBitWidth = Op.getValueSizeInBits();
3553 
3554     // Remove low part of known bits mask
3555     Known.Zero = Known.Zero.getHiBits(Known.getBitWidth() - Index * EltBitWidth);
3556     Known.One = Known.One.getHiBits(Known.getBitWidth() - Index * EltBitWidth);
3557 
3558     // Remove high part of known bit mask
3559     Known = Known.trunc(EltBitWidth);
3560     break;
3561   }
3562   case ISD::EXTRACT_VECTOR_ELT: {
3563     SDValue InVec = Op.getOperand(0);
3564     SDValue EltNo = Op.getOperand(1);
3565     EVT VecVT = InVec.getValueType();
3566     // computeKnownBits not yet implemented for scalable vectors.
3567     if (VecVT.isScalableVector())
3568       break;
3569     const unsigned EltBitWidth = VecVT.getScalarSizeInBits();
3570     const unsigned NumSrcElts = VecVT.getVectorNumElements();
3571 
3572     // If BitWidth > EltBitWidth the value is anyext:ed. So we do not know
3573     // anything about the extended bits.
3574     if (BitWidth > EltBitWidth)
3575       Known = Known.trunc(EltBitWidth);
3576 
3577     // If we know the element index, just demand that vector element, else for
3578     // an unknown element index, ignore DemandedElts and demand them all.
3579     APInt DemandedSrcElts = APInt::getAllOnes(NumSrcElts);
3580     auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
3581     if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts))
3582       DemandedSrcElts =
3583           APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue());
3584 
3585     Known = computeKnownBits(InVec, DemandedSrcElts, Depth + 1);
3586     if (BitWidth > EltBitWidth)
3587       Known = Known.anyext(BitWidth);
3588     break;
3589   }
3590   case ISD::INSERT_VECTOR_ELT: {
3591     // If we know the element index, split the demand between the
3592     // source vector and the inserted element, otherwise assume we need
3593     // the original demanded vector elements and the value.
3594     SDValue InVec = Op.getOperand(0);
3595     SDValue InVal = Op.getOperand(1);
3596     SDValue EltNo = Op.getOperand(2);
3597     bool DemandedVal = true;
3598     APInt DemandedVecElts = DemandedElts;
3599     auto *CEltNo = dyn_cast<ConstantSDNode>(EltNo);
3600     if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) {
3601       unsigned EltIdx = CEltNo->getZExtValue();
3602       DemandedVal = !!DemandedElts[EltIdx];
3603       DemandedVecElts.clearBit(EltIdx);
3604     }
3605     Known.One.setAllBits();
3606     Known.Zero.setAllBits();
3607     if (DemandedVal) {
3608       Known2 = computeKnownBits(InVal, Depth + 1);
3609       Known = KnownBits::commonBits(Known, Known2.zextOrTrunc(BitWidth));
3610     }
3611     if (!!DemandedVecElts) {
3612       Known2 = computeKnownBits(InVec, DemandedVecElts, Depth + 1);
3613       Known = KnownBits::commonBits(Known, Known2);
3614     }
3615     break;
3616   }
3617   case ISD::BITREVERSE: {
3618     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3619     Known = Known2.reverseBits();
3620     break;
3621   }
3622   case ISD::BSWAP: {
3623     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3624     Known = Known2.byteSwap();
3625     break;
3626   }
3627   case ISD::ABS: {
3628     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3629     Known = Known2.abs();
3630     break;
3631   }
3632   case ISD::USUBSAT: {
3633     // The result of usubsat will never be larger than the LHS.
3634     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3635     Known.Zero.setHighBits(Known2.countMinLeadingZeros());
3636     break;
3637   }
3638   case ISD::UMIN: {
3639     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3640     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3641     Known = KnownBits::umin(Known, Known2);
3642     break;
3643   }
3644   case ISD::UMAX: {
3645     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3646     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3647     Known = KnownBits::umax(Known, Known2);
3648     break;
3649   }
3650   case ISD::SMIN:
3651   case ISD::SMAX: {
3652     // If we have a clamp pattern, we know that the number of sign bits will be
3653     // the minimum of the clamp min/max range.
3654     bool IsMax = (Opcode == ISD::SMAX);
3655     ConstantSDNode *CstLow = nullptr, *CstHigh = nullptr;
3656     if ((CstLow = isConstOrConstSplat(Op.getOperand(1), DemandedElts)))
3657       if (Op.getOperand(0).getOpcode() == (IsMax ? ISD::SMIN : ISD::SMAX))
3658         CstHigh =
3659             isConstOrConstSplat(Op.getOperand(0).getOperand(1), DemandedElts);
3660     if (CstLow && CstHigh) {
3661       if (!IsMax)
3662         std::swap(CstLow, CstHigh);
3663 
3664       const APInt &ValueLow = CstLow->getAPIntValue();
3665       const APInt &ValueHigh = CstHigh->getAPIntValue();
3666       if (ValueLow.sle(ValueHigh)) {
3667         unsigned LowSignBits = ValueLow.getNumSignBits();
3668         unsigned HighSignBits = ValueHigh.getNumSignBits();
3669         unsigned MinSignBits = std::min(LowSignBits, HighSignBits);
3670         if (ValueLow.isNegative() && ValueHigh.isNegative()) {
3671           Known.One.setHighBits(MinSignBits);
3672           break;
3673         }
3674         if (ValueLow.isNonNegative() && ValueHigh.isNonNegative()) {
3675           Known.Zero.setHighBits(MinSignBits);
3676           break;
3677         }
3678       }
3679     }
3680 
3681     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3682     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3683     if (IsMax)
3684       Known = KnownBits::smax(Known, Known2);
3685     else
3686       Known = KnownBits::smin(Known, Known2);
3687     break;
3688   }
3689   case ISD::FP_TO_UINT_SAT: {
3690     // FP_TO_UINT_SAT produces an unsigned value that fits in the saturating VT.
3691     EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
3692     Known.Zero |= APInt::getBitsSetFrom(BitWidth, VT.getScalarSizeInBits());
3693     break;
3694   }
3695   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
3696     if (Op.getResNo() == 1) {
3697       // The boolean result conforms to getBooleanContents.
3698       // If we know the result of a setcc has the top bits zero, use this info.
3699       // We know that we have an integer-based boolean since these operations
3700       // are only available for integer.
3701       if (TLI->getBooleanContents(Op.getValueType().isVector(), false) ==
3702               TargetLowering::ZeroOrOneBooleanContent &&
3703           BitWidth > 1)
3704         Known.Zero.setBitsFrom(1);
3705       break;
3706     }
3707     LLVM_FALLTHROUGH;
3708   case ISD::ATOMIC_CMP_SWAP:
3709   case ISD::ATOMIC_SWAP:
3710   case ISD::ATOMIC_LOAD_ADD:
3711   case ISD::ATOMIC_LOAD_SUB:
3712   case ISD::ATOMIC_LOAD_AND:
3713   case ISD::ATOMIC_LOAD_CLR:
3714   case ISD::ATOMIC_LOAD_OR:
3715   case ISD::ATOMIC_LOAD_XOR:
3716   case ISD::ATOMIC_LOAD_NAND:
3717   case ISD::ATOMIC_LOAD_MIN:
3718   case ISD::ATOMIC_LOAD_MAX:
3719   case ISD::ATOMIC_LOAD_UMIN:
3720   case ISD::ATOMIC_LOAD_UMAX:
3721   case ISD::ATOMIC_LOAD: {
3722     unsigned MemBits =
3723         cast<AtomicSDNode>(Op)->getMemoryVT().getScalarSizeInBits();
3724     // If we are looking at the loaded value.
3725     if (Op.getResNo() == 0) {
3726       if (TLI->getExtendForAtomicOps() == ISD::ZERO_EXTEND)
3727         Known.Zero.setBitsFrom(MemBits);
3728     }
3729     break;
3730   }
3731   case ISD::FrameIndex:
3732   case ISD::TargetFrameIndex:
3733     TLI->computeKnownBitsForFrameIndex(cast<FrameIndexSDNode>(Op)->getIndex(),
3734                                        Known, getMachineFunction());
3735     break;
3736 
3737   default:
3738     if (Opcode < ISD::BUILTIN_OP_END)
3739       break;
3740     LLVM_FALLTHROUGH;
3741   case ISD::INTRINSIC_WO_CHAIN:
3742   case ISD::INTRINSIC_W_CHAIN:
3743   case ISD::INTRINSIC_VOID:
3744     // Allow the target to implement this method for its nodes.
3745     TLI->computeKnownBitsForTargetNode(Op, Known, DemandedElts, *this, Depth);
3746     break;
3747   }
3748 
3749   assert(!Known.hasConflict() && "Bits known to be one AND zero?");
3750   return Known;
3751 }
3752 
3753 SelectionDAG::OverflowKind SelectionDAG::computeOverflowKind(SDValue N0,
3754                                                              SDValue N1) const {
3755   // X + 0 never overflow
3756   if (isNullConstant(N1))
3757     return OFK_Never;
3758 
3759   KnownBits N1Known = computeKnownBits(N1);
3760   if (N1Known.Zero.getBoolValue()) {
3761     KnownBits N0Known = computeKnownBits(N0);
3762 
3763     bool overflow;
3764     (void)N0Known.getMaxValue().uadd_ov(N1Known.getMaxValue(), overflow);
3765     if (!overflow)
3766       return OFK_Never;
3767   }
3768 
3769   // mulhi + 1 never overflow
3770   if (N0.getOpcode() == ISD::UMUL_LOHI && N0.getResNo() == 1 &&
3771       (N1Known.getMaxValue() & 0x01) == N1Known.getMaxValue())
3772     return OFK_Never;
3773 
3774   if (N1.getOpcode() == ISD::UMUL_LOHI && N1.getResNo() == 1) {
3775     KnownBits N0Known = computeKnownBits(N0);
3776 
3777     if ((N0Known.getMaxValue() & 0x01) == N0Known.getMaxValue())
3778       return OFK_Never;
3779   }
3780 
3781   return OFK_Sometime;
3782 }
3783 
3784 bool SelectionDAG::isKnownToBeAPowerOfTwo(SDValue Val) const {
3785   EVT OpVT = Val.getValueType();
3786   unsigned BitWidth = OpVT.getScalarSizeInBits();
3787 
3788   // Is the constant a known power of 2?
3789   if (ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Val))
3790     return Const->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2();
3791 
3792   // A left-shift of a constant one will have exactly one bit set because
3793   // shifting the bit off the end is undefined.
3794   if (Val.getOpcode() == ISD::SHL) {
3795     auto *C = isConstOrConstSplat(Val.getOperand(0));
3796     if (C && C->getAPIntValue() == 1)
3797       return true;
3798   }
3799 
3800   // Similarly, a logical right-shift of a constant sign-bit will have exactly
3801   // one bit set.
3802   if (Val.getOpcode() == ISD::SRL) {
3803     auto *C = isConstOrConstSplat(Val.getOperand(0));
3804     if (C && C->getAPIntValue().isSignMask())
3805       return true;
3806   }
3807 
3808   // Are all operands of a build vector constant powers of two?
3809   if (Val.getOpcode() == ISD::BUILD_VECTOR)
3810     if (llvm::all_of(Val->ops(), [BitWidth](SDValue E) {
3811           if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(E))
3812             return C->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2();
3813           return false;
3814         }))
3815       return true;
3816 
3817   // Is the operand of a splat vector a constant power of two?
3818   if (Val.getOpcode() == ISD::SPLAT_VECTOR)
3819     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val->getOperand(0)))
3820       if (C->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2())
3821         return true;
3822 
3823   // More could be done here, though the above checks are enough
3824   // to handle some common cases.
3825 
3826   // Fall back to computeKnownBits to catch other known cases.
3827   KnownBits Known = computeKnownBits(Val);
3828   return (Known.countMaxPopulation() == 1) && (Known.countMinPopulation() == 1);
3829 }
3830 
3831 unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, unsigned Depth) const {
3832   EVT VT = Op.getValueType();
3833 
3834   // TODO: Assume we don't know anything for now.
3835   if (VT.isScalableVector())
3836     return 1;
3837 
3838   APInt DemandedElts = VT.isVector()
3839                            ? APInt::getAllOnes(VT.getVectorNumElements())
3840                            : APInt(1, 1);
3841   return ComputeNumSignBits(Op, DemandedElts, Depth);
3842 }
3843 
3844 unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, const APInt &DemandedElts,
3845                                           unsigned Depth) const {
3846   EVT VT = Op.getValueType();
3847   assert((VT.isInteger() || VT.isFloatingPoint()) && "Invalid VT!");
3848   unsigned VTBits = VT.getScalarSizeInBits();
3849   unsigned NumElts = DemandedElts.getBitWidth();
3850   unsigned Tmp, Tmp2;
3851   unsigned FirstAnswer = 1;
3852 
3853   if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
3854     const APInt &Val = C->getAPIntValue();
3855     return Val.getNumSignBits();
3856   }
3857 
3858   if (Depth >= MaxRecursionDepth)
3859     return 1;  // Limit search depth.
3860 
3861   if (!DemandedElts || VT.isScalableVector())
3862     return 1;  // No demanded elts, better to assume we don't know anything.
3863 
3864   unsigned Opcode = Op.getOpcode();
3865   switch (Opcode) {
3866   default: break;
3867   case ISD::AssertSext:
3868     Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
3869     return VTBits-Tmp+1;
3870   case ISD::AssertZext:
3871     Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
3872     return VTBits-Tmp;
3873 
3874   case ISD::BUILD_VECTOR:
3875     Tmp = VTBits;
3876     for (unsigned i = 0, e = Op.getNumOperands(); (i < e) && (Tmp > 1); ++i) {
3877       if (!DemandedElts[i])
3878         continue;
3879 
3880       SDValue SrcOp = Op.getOperand(i);
3881       Tmp2 = ComputeNumSignBits(SrcOp, Depth + 1);
3882 
3883       // BUILD_VECTOR can implicitly truncate sources, we must handle this.
3884       if (SrcOp.getValueSizeInBits() != VTBits) {
3885         assert(SrcOp.getValueSizeInBits() > VTBits &&
3886                "Expected BUILD_VECTOR implicit truncation");
3887         unsigned ExtraBits = SrcOp.getValueSizeInBits() - VTBits;
3888         Tmp2 = (Tmp2 > ExtraBits ? Tmp2 - ExtraBits : 1);
3889       }
3890       Tmp = std::min(Tmp, Tmp2);
3891     }
3892     return Tmp;
3893 
3894   case ISD::VECTOR_SHUFFLE: {
3895     // Collect the minimum number of sign bits that are shared by every vector
3896     // element referenced by the shuffle.
3897     APInt DemandedLHS(NumElts, 0), DemandedRHS(NumElts, 0);
3898     const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op);
3899     assert(NumElts == SVN->getMask().size() && "Unexpected vector size");
3900     for (unsigned i = 0; i != NumElts; ++i) {
3901       int M = SVN->getMaskElt(i);
3902       if (!DemandedElts[i])
3903         continue;
3904       // For UNDEF elements, we don't know anything about the common state of
3905       // the shuffle result.
3906       if (M < 0)
3907         return 1;
3908       if ((unsigned)M < NumElts)
3909         DemandedLHS.setBit((unsigned)M % NumElts);
3910       else
3911         DemandedRHS.setBit((unsigned)M % NumElts);
3912     }
3913     Tmp = std::numeric_limits<unsigned>::max();
3914     if (!!DemandedLHS)
3915       Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedLHS, Depth + 1);
3916     if (!!DemandedRHS) {
3917       Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedRHS, Depth + 1);
3918       Tmp = std::min(Tmp, Tmp2);
3919     }
3920     // If we don't know anything, early out and try computeKnownBits fall-back.
3921     if (Tmp == 1)
3922       break;
3923     assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
3924     return Tmp;
3925   }
3926 
3927   case ISD::BITCAST: {
3928     SDValue N0 = Op.getOperand(0);
3929     EVT SrcVT = N0.getValueType();
3930     unsigned SrcBits = SrcVT.getScalarSizeInBits();
3931 
3932     // Ignore bitcasts from unsupported types..
3933     if (!(SrcVT.isInteger() || SrcVT.isFloatingPoint()))
3934       break;
3935 
3936     // Fast handling of 'identity' bitcasts.
3937     if (VTBits == SrcBits)
3938       return ComputeNumSignBits(N0, DemandedElts, Depth + 1);
3939 
3940     bool IsLE = getDataLayout().isLittleEndian();
3941 
3942     // Bitcast 'large element' scalar/vector to 'small element' vector.
3943     if ((SrcBits % VTBits) == 0) {
3944       assert(VT.isVector() && "Expected bitcast to vector");
3945 
3946       unsigned Scale = SrcBits / VTBits;
3947       APInt SrcDemandedElts =
3948           APIntOps::ScaleBitMask(DemandedElts, NumElts / Scale);
3949 
3950       // Fast case - sign splat can be simply split across the small elements.
3951       Tmp = ComputeNumSignBits(N0, SrcDemandedElts, Depth + 1);
3952       if (Tmp == SrcBits)
3953         return VTBits;
3954 
3955       // Slow case - determine how far the sign extends into each sub-element.
3956       Tmp2 = VTBits;
3957       for (unsigned i = 0; i != NumElts; ++i)
3958         if (DemandedElts[i]) {
3959           unsigned SubOffset = i % Scale;
3960           SubOffset = (IsLE ? ((Scale - 1) - SubOffset) : SubOffset);
3961           SubOffset = SubOffset * VTBits;
3962           if (Tmp <= SubOffset)
3963             return 1;
3964           Tmp2 = std::min(Tmp2, Tmp - SubOffset);
3965         }
3966       return Tmp2;
3967     }
3968     break;
3969   }
3970 
3971   case ISD::FP_TO_SINT_SAT:
3972     // FP_TO_SINT_SAT produces a signed value that fits in the saturating VT.
3973     Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getScalarSizeInBits();
3974     return VTBits - Tmp + 1;
3975   case ISD::SIGN_EXTEND:
3976     Tmp = VTBits - Op.getOperand(0).getScalarValueSizeInBits();
3977     return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1) + Tmp;
3978   case ISD::SIGN_EXTEND_INREG:
3979     // Max of the input and what this extends.
3980     Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getScalarSizeInBits();
3981     Tmp = VTBits-Tmp+1;
3982     Tmp2 = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1);
3983     return std::max(Tmp, Tmp2);
3984   case ISD::SIGN_EXTEND_VECTOR_INREG: {
3985     SDValue Src = Op.getOperand(0);
3986     EVT SrcVT = Src.getValueType();
3987     APInt DemandedSrcElts = DemandedElts.zextOrSelf(SrcVT.getVectorNumElements());
3988     Tmp = VTBits - SrcVT.getScalarSizeInBits();
3989     return ComputeNumSignBits(Src, DemandedSrcElts, Depth+1) + Tmp;
3990   }
3991   case ISD::SRA:
3992     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
3993     // SRA X, C -> adds C sign bits.
3994     if (const APInt *ShAmt =
3995             getValidMinimumShiftAmountConstant(Op, DemandedElts))
3996       Tmp = std::min<uint64_t>(Tmp + ShAmt->getZExtValue(), VTBits);
3997     return Tmp;
3998   case ISD::SHL:
3999     if (const APInt *ShAmt =
4000             getValidMaximumShiftAmountConstant(Op, DemandedElts)) {
4001       // shl destroys sign bits, ensure it doesn't shift out all sign bits.
4002       Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
4003       if (ShAmt->ult(Tmp))
4004         return Tmp - ShAmt->getZExtValue();
4005     }
4006     break;
4007   case ISD::AND:
4008   case ISD::OR:
4009   case ISD::XOR:    // NOT is handled here.
4010     // Logical binary ops preserve the number of sign bits at the worst.
4011     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1);
4012     if (Tmp != 1) {
4013       Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth+1);
4014       FirstAnswer = std::min(Tmp, Tmp2);
4015       // We computed what we know about the sign bits as our first
4016       // answer. Now proceed to the generic code that uses
4017       // computeKnownBits, and pick whichever answer is better.
4018     }
4019     break;
4020 
4021   case ISD::SELECT:
4022   case ISD::VSELECT:
4023     Tmp = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth+1);
4024     if (Tmp == 1) return 1;  // Early out.
4025     Tmp2 = ComputeNumSignBits(Op.getOperand(2), DemandedElts, Depth+1);
4026     return std::min(Tmp, Tmp2);
4027   case ISD::SELECT_CC:
4028     Tmp = ComputeNumSignBits(Op.getOperand(2), DemandedElts, Depth+1);
4029     if (Tmp == 1) return 1;  // Early out.
4030     Tmp2 = ComputeNumSignBits(Op.getOperand(3), DemandedElts, Depth+1);
4031     return std::min(Tmp, Tmp2);
4032 
4033   case ISD::SMIN:
4034   case ISD::SMAX: {
4035     // If we have a clamp pattern, we know that the number of sign bits will be
4036     // the minimum of the clamp min/max range.
4037     bool IsMax = (Opcode == ISD::SMAX);
4038     ConstantSDNode *CstLow = nullptr, *CstHigh = nullptr;
4039     if ((CstLow = isConstOrConstSplat(Op.getOperand(1), DemandedElts)))
4040       if (Op.getOperand(0).getOpcode() == (IsMax ? ISD::SMIN : ISD::SMAX))
4041         CstHigh =
4042             isConstOrConstSplat(Op.getOperand(0).getOperand(1), DemandedElts);
4043     if (CstLow && CstHigh) {
4044       if (!IsMax)
4045         std::swap(CstLow, CstHigh);
4046       if (CstLow->getAPIntValue().sle(CstHigh->getAPIntValue())) {
4047         Tmp = CstLow->getAPIntValue().getNumSignBits();
4048         Tmp2 = CstHigh->getAPIntValue().getNumSignBits();
4049         return std::min(Tmp, Tmp2);
4050       }
4051     }
4052 
4053     // Fallback - just get the minimum number of sign bits of the operands.
4054     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
4055     if (Tmp == 1)
4056       return 1;  // Early out.
4057     Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
4058     return std::min(Tmp, Tmp2);
4059   }
4060   case ISD::UMIN:
4061   case ISD::UMAX:
4062     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
4063     if (Tmp == 1)
4064       return 1;  // Early out.
4065     Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
4066     return std::min(Tmp, Tmp2);
4067   case ISD::SADDO:
4068   case ISD::UADDO:
4069   case ISD::SSUBO:
4070   case ISD::USUBO:
4071   case ISD::SMULO:
4072   case ISD::UMULO:
4073     if (Op.getResNo() != 1)
4074       break;
4075     // The boolean result conforms to getBooleanContents.  Fall through.
4076     // If setcc returns 0/-1, all bits are sign bits.
4077     // We know that we have an integer-based boolean since these operations
4078     // are only available for integer.
4079     if (TLI->getBooleanContents(VT.isVector(), false) ==
4080         TargetLowering::ZeroOrNegativeOneBooleanContent)
4081       return VTBits;
4082     break;
4083   case ISD::SETCC:
4084   case ISD::STRICT_FSETCC:
4085   case ISD::STRICT_FSETCCS: {
4086     unsigned OpNo = Op->isStrictFPOpcode() ? 1 : 0;
4087     // If setcc returns 0/-1, all bits are sign bits.
4088     if (TLI->getBooleanContents(Op.getOperand(OpNo).getValueType()) ==
4089         TargetLowering::ZeroOrNegativeOneBooleanContent)
4090       return VTBits;
4091     break;
4092   }
4093   case ISD::ROTL:
4094   case ISD::ROTR:
4095     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
4096 
4097     // If we're rotating an 0/-1 value, then it stays an 0/-1 value.
4098     if (Tmp == VTBits)
4099       return VTBits;
4100 
4101     if (ConstantSDNode *C =
4102             isConstOrConstSplat(Op.getOperand(1), DemandedElts)) {
4103       unsigned RotAmt = C->getAPIntValue().urem(VTBits);
4104 
4105       // Handle rotate right by N like a rotate left by 32-N.
4106       if (Opcode == ISD::ROTR)
4107         RotAmt = (VTBits - RotAmt) % VTBits;
4108 
4109       // If we aren't rotating out all of the known-in sign bits, return the
4110       // number that are left.  This handles rotl(sext(x), 1) for example.
4111       if (Tmp > (RotAmt + 1)) return (Tmp - RotAmt);
4112     }
4113     break;
4114   case ISD::ADD:
4115   case ISD::ADDC:
4116     // Add can have at most one carry bit.  Thus we know that the output
4117     // is, at worst, one more bit than the inputs.
4118     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
4119     if (Tmp == 1) return 1; // Early out.
4120 
4121     // Special case decrementing a value (ADD X, -1):
4122     if (ConstantSDNode *CRHS =
4123             isConstOrConstSplat(Op.getOperand(1), DemandedElts))
4124       if (CRHS->isAllOnes()) {
4125         KnownBits Known =
4126             computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4127 
4128         // If the input is known to be 0 or 1, the output is 0/-1, which is all
4129         // sign bits set.
4130         if ((Known.Zero | 1).isAllOnes())
4131           return VTBits;
4132 
4133         // If we are subtracting one from a positive number, there is no carry
4134         // out of the result.
4135         if (Known.isNonNegative())
4136           return Tmp;
4137       }
4138 
4139     Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
4140     if (Tmp2 == 1) return 1; // Early out.
4141     return std::min(Tmp, Tmp2) - 1;
4142   case ISD::SUB:
4143     Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
4144     if (Tmp2 == 1) return 1; // Early out.
4145 
4146     // Handle NEG.
4147     if (ConstantSDNode *CLHS =
4148             isConstOrConstSplat(Op.getOperand(0), DemandedElts))
4149       if (CLHS->isZero()) {
4150         KnownBits Known =
4151             computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4152         // If the input is known to be 0 or 1, the output is 0/-1, which is all
4153         // sign bits set.
4154         if ((Known.Zero | 1).isAllOnes())
4155           return VTBits;
4156 
4157         // If the input is known to be positive (the sign bit is known clear),
4158         // the output of the NEG has the same number of sign bits as the input.
4159         if (Known.isNonNegative())
4160           return Tmp2;
4161 
4162         // Otherwise, we treat this like a SUB.
4163       }
4164 
4165     // Sub can have at most one carry bit.  Thus we know that the output
4166     // is, at worst, one more bit than the inputs.
4167     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
4168     if (Tmp == 1) return 1; // Early out.
4169     return std::min(Tmp, Tmp2) - 1;
4170   case ISD::MUL: {
4171     // The output of the Mul can be at most twice the valid bits in the inputs.
4172     unsigned SignBitsOp0 = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
4173     if (SignBitsOp0 == 1)
4174       break;
4175     unsigned SignBitsOp1 = ComputeNumSignBits(Op.getOperand(1), Depth + 1);
4176     if (SignBitsOp1 == 1)
4177       break;
4178     unsigned OutValidBits =
4179         (VTBits - SignBitsOp0 + 1) + (VTBits - SignBitsOp1 + 1);
4180     return OutValidBits > VTBits ? 1 : VTBits - OutValidBits + 1;
4181   }
4182   case ISD::SREM:
4183     // The sign bit is the LHS's sign bit, except when the result of the
4184     // remainder is zero. The magnitude of the result should be less than or
4185     // equal to the magnitude of the LHS. Therefore, the result should have
4186     // at least as many sign bits as the left hand side.
4187     return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
4188   case ISD::TRUNCATE: {
4189     // Check if the sign bits of source go down as far as the truncated value.
4190     unsigned NumSrcBits = Op.getOperand(0).getScalarValueSizeInBits();
4191     unsigned NumSrcSignBits = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
4192     if (NumSrcSignBits > (NumSrcBits - VTBits))
4193       return NumSrcSignBits - (NumSrcBits - VTBits);
4194     break;
4195   }
4196   case ISD::EXTRACT_ELEMENT: {
4197     const int KnownSign = ComputeNumSignBits(Op.getOperand(0), Depth+1);
4198     const int BitWidth = Op.getValueSizeInBits();
4199     const int Items = Op.getOperand(0).getValueSizeInBits() / BitWidth;
4200 
4201     // Get reverse index (starting from 1), Op1 value indexes elements from
4202     // little end. Sign starts at big end.
4203     const int rIndex = Items - 1 - Op.getConstantOperandVal(1);
4204 
4205     // If the sign portion ends in our element the subtraction gives correct
4206     // result. Otherwise it gives either negative or > bitwidth result
4207     return std::max(std::min(KnownSign - rIndex * BitWidth, BitWidth), 0);
4208   }
4209   case ISD::INSERT_VECTOR_ELT: {
4210     // If we know the element index, split the demand between the
4211     // source vector and the inserted element, otherwise assume we need
4212     // the original demanded vector elements and the value.
4213     SDValue InVec = Op.getOperand(0);
4214     SDValue InVal = Op.getOperand(1);
4215     SDValue EltNo = Op.getOperand(2);
4216     bool DemandedVal = true;
4217     APInt DemandedVecElts = DemandedElts;
4218     auto *CEltNo = dyn_cast<ConstantSDNode>(EltNo);
4219     if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) {
4220       unsigned EltIdx = CEltNo->getZExtValue();
4221       DemandedVal = !!DemandedElts[EltIdx];
4222       DemandedVecElts.clearBit(EltIdx);
4223     }
4224     Tmp = std::numeric_limits<unsigned>::max();
4225     if (DemandedVal) {
4226       // TODO - handle implicit truncation of inserted elements.
4227       if (InVal.getScalarValueSizeInBits() != VTBits)
4228         break;
4229       Tmp2 = ComputeNumSignBits(InVal, Depth + 1);
4230       Tmp = std::min(Tmp, Tmp2);
4231     }
4232     if (!!DemandedVecElts) {
4233       Tmp2 = ComputeNumSignBits(InVec, DemandedVecElts, Depth + 1);
4234       Tmp = std::min(Tmp, Tmp2);
4235     }
4236     assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
4237     return Tmp;
4238   }
4239   case ISD::EXTRACT_VECTOR_ELT: {
4240     SDValue InVec = Op.getOperand(0);
4241     SDValue EltNo = Op.getOperand(1);
4242     EVT VecVT = InVec.getValueType();
4243     // ComputeNumSignBits not yet implemented for scalable vectors.
4244     if (VecVT.isScalableVector())
4245       break;
4246     const unsigned BitWidth = Op.getValueSizeInBits();
4247     const unsigned EltBitWidth = Op.getOperand(0).getScalarValueSizeInBits();
4248     const unsigned NumSrcElts = VecVT.getVectorNumElements();
4249 
4250     // If BitWidth > EltBitWidth the value is anyext:ed, and we do not know
4251     // anything about sign bits. But if the sizes match we can derive knowledge
4252     // about sign bits from the vector operand.
4253     if (BitWidth != EltBitWidth)
4254       break;
4255 
4256     // If we know the element index, just demand that vector element, else for
4257     // an unknown element index, ignore DemandedElts and demand them all.
4258     APInt DemandedSrcElts = APInt::getAllOnes(NumSrcElts);
4259     auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
4260     if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts))
4261       DemandedSrcElts =
4262           APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue());
4263 
4264     return ComputeNumSignBits(InVec, DemandedSrcElts, Depth + 1);
4265   }
4266   case ISD::EXTRACT_SUBVECTOR: {
4267     // Offset the demanded elts by the subvector index.
4268     SDValue Src = Op.getOperand(0);
4269     // Bail until we can represent demanded elements for scalable vectors.
4270     if (Src.getValueType().isScalableVector())
4271       break;
4272     uint64_t Idx = Op.getConstantOperandVal(1);
4273     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
4274     APInt DemandedSrcElts = DemandedElts.zextOrSelf(NumSrcElts).shl(Idx);
4275     return ComputeNumSignBits(Src, DemandedSrcElts, Depth + 1);
4276   }
4277   case ISD::CONCAT_VECTORS: {
4278     // Determine the minimum number of sign bits across all demanded
4279     // elts of the input vectors. Early out if the result is already 1.
4280     Tmp = std::numeric_limits<unsigned>::max();
4281     EVT SubVectorVT = Op.getOperand(0).getValueType();
4282     unsigned NumSubVectorElts = SubVectorVT.getVectorNumElements();
4283     unsigned NumSubVectors = Op.getNumOperands();
4284     for (unsigned i = 0; (i < NumSubVectors) && (Tmp > 1); ++i) {
4285       APInt DemandedSub =
4286           DemandedElts.extractBits(NumSubVectorElts, i * NumSubVectorElts);
4287       if (!DemandedSub)
4288         continue;
4289       Tmp2 = ComputeNumSignBits(Op.getOperand(i), DemandedSub, Depth + 1);
4290       Tmp = std::min(Tmp, Tmp2);
4291     }
4292     assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
4293     return Tmp;
4294   }
4295   case ISD::INSERT_SUBVECTOR: {
4296     // Demand any elements from the subvector and the remainder from the src its
4297     // inserted into.
4298     SDValue Src = Op.getOperand(0);
4299     SDValue Sub = Op.getOperand(1);
4300     uint64_t Idx = Op.getConstantOperandVal(2);
4301     unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
4302     APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
4303     APInt DemandedSrcElts = DemandedElts;
4304     DemandedSrcElts.insertBits(APInt::getZero(NumSubElts), Idx);
4305 
4306     Tmp = std::numeric_limits<unsigned>::max();
4307     if (!!DemandedSubElts) {
4308       Tmp = ComputeNumSignBits(Sub, DemandedSubElts, Depth + 1);
4309       if (Tmp == 1)
4310         return 1; // early-out
4311     }
4312     if (!!DemandedSrcElts) {
4313       Tmp2 = ComputeNumSignBits(Src, DemandedSrcElts, Depth + 1);
4314       Tmp = std::min(Tmp, Tmp2);
4315     }
4316     assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
4317     return Tmp;
4318   }
4319   case ISD::ATOMIC_CMP_SWAP:
4320   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
4321   case ISD::ATOMIC_SWAP:
4322   case ISD::ATOMIC_LOAD_ADD:
4323   case ISD::ATOMIC_LOAD_SUB:
4324   case ISD::ATOMIC_LOAD_AND:
4325   case ISD::ATOMIC_LOAD_CLR:
4326   case ISD::ATOMIC_LOAD_OR:
4327   case ISD::ATOMIC_LOAD_XOR:
4328   case ISD::ATOMIC_LOAD_NAND:
4329   case ISD::ATOMIC_LOAD_MIN:
4330   case ISD::ATOMIC_LOAD_MAX:
4331   case ISD::ATOMIC_LOAD_UMIN:
4332   case ISD::ATOMIC_LOAD_UMAX:
4333   case ISD::ATOMIC_LOAD: {
4334     Tmp = cast<AtomicSDNode>(Op)->getMemoryVT().getScalarSizeInBits();
4335     // If we are looking at the loaded value.
4336     if (Op.getResNo() == 0) {
4337       if (Tmp == VTBits)
4338         return 1; // early-out
4339       if (TLI->getExtendForAtomicOps() == ISD::SIGN_EXTEND)
4340         return VTBits - Tmp + 1;
4341       if (TLI->getExtendForAtomicOps() == ISD::ZERO_EXTEND)
4342         return VTBits - Tmp;
4343     }
4344     break;
4345   }
4346   }
4347 
4348   // If we are looking at the loaded value of the SDNode.
4349   if (Op.getResNo() == 0) {
4350     // Handle LOADX separately here. EXTLOAD case will fallthrough.
4351     if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
4352       unsigned ExtType = LD->getExtensionType();
4353       switch (ExtType) {
4354       default: break;
4355       case ISD::SEXTLOAD: // e.g. i16->i32 = '17' bits known.
4356         Tmp = LD->getMemoryVT().getScalarSizeInBits();
4357         return VTBits - Tmp + 1;
4358       case ISD::ZEXTLOAD: // e.g. i16->i32 = '16' bits known.
4359         Tmp = LD->getMemoryVT().getScalarSizeInBits();
4360         return VTBits - Tmp;
4361       case ISD::NON_EXTLOAD:
4362         if (const Constant *Cst = TLI->getTargetConstantFromLoad(LD)) {
4363           // We only need to handle vectors - computeKnownBits should handle
4364           // scalar cases.
4365           Type *CstTy = Cst->getType();
4366           if (CstTy->isVectorTy() &&
4367               (NumElts * VTBits) == CstTy->getPrimitiveSizeInBits() &&
4368               VTBits == CstTy->getScalarSizeInBits()) {
4369             Tmp = VTBits;
4370             for (unsigned i = 0; i != NumElts; ++i) {
4371               if (!DemandedElts[i])
4372                 continue;
4373               if (Constant *Elt = Cst->getAggregateElement(i)) {
4374                 if (auto *CInt = dyn_cast<ConstantInt>(Elt)) {
4375                   const APInt &Value = CInt->getValue();
4376                   Tmp = std::min(Tmp, Value.getNumSignBits());
4377                   continue;
4378                 }
4379                 if (auto *CFP = dyn_cast<ConstantFP>(Elt)) {
4380                   APInt Value = CFP->getValueAPF().bitcastToAPInt();
4381                   Tmp = std::min(Tmp, Value.getNumSignBits());
4382                   continue;
4383                 }
4384               }
4385               // Unknown type. Conservatively assume no bits match sign bit.
4386               return 1;
4387             }
4388             return Tmp;
4389           }
4390         }
4391         break;
4392       }
4393     }
4394   }
4395 
4396   // Allow the target to implement this method for its nodes.
4397   if (Opcode >= ISD::BUILTIN_OP_END ||
4398       Opcode == ISD::INTRINSIC_WO_CHAIN ||
4399       Opcode == ISD::INTRINSIC_W_CHAIN ||
4400       Opcode == ISD::INTRINSIC_VOID) {
4401     unsigned NumBits =
4402         TLI->ComputeNumSignBitsForTargetNode(Op, DemandedElts, *this, Depth);
4403     if (NumBits > 1)
4404       FirstAnswer = std::max(FirstAnswer, NumBits);
4405   }
4406 
4407   // Finally, if we can prove that the top bits of the result are 0's or 1's,
4408   // use this information.
4409   KnownBits Known = computeKnownBits(Op, DemandedElts, Depth);
4410   return std::max(FirstAnswer, Known.countMinSignBits());
4411 }
4412 
4413 unsigned SelectionDAG::ComputeMaxSignificantBits(SDValue Op,
4414                                                  unsigned Depth) const {
4415   unsigned SignBits = ComputeNumSignBits(Op, Depth);
4416   return Op.getScalarValueSizeInBits() - SignBits + 1;
4417 }
4418 
4419 unsigned SelectionDAG::ComputeMaxSignificantBits(SDValue Op,
4420                                                  const APInt &DemandedElts,
4421                                                  unsigned Depth) const {
4422   unsigned SignBits = ComputeNumSignBits(Op, DemandedElts, Depth);
4423   return Op.getScalarValueSizeInBits() - SignBits + 1;
4424 }
4425 
4426 bool SelectionDAG::isGuaranteedNotToBeUndefOrPoison(SDValue Op, bool PoisonOnly,
4427                                                     unsigned Depth) const {
4428   // Early out for FREEZE.
4429   if (Op.getOpcode() == ISD::FREEZE)
4430     return true;
4431 
4432   // TODO: Assume we don't know anything for now.
4433   EVT VT = Op.getValueType();
4434   if (VT.isScalableVector())
4435     return false;
4436 
4437   APInt DemandedElts = VT.isVector()
4438                            ? APInt::getAllOnes(VT.getVectorNumElements())
4439                            : APInt(1, 1);
4440   return isGuaranteedNotToBeUndefOrPoison(Op, DemandedElts, PoisonOnly, Depth);
4441 }
4442 
4443 bool SelectionDAG::isGuaranteedNotToBeUndefOrPoison(SDValue Op,
4444                                                     const APInt &DemandedElts,
4445                                                     bool PoisonOnly,
4446                                                     unsigned Depth) const {
4447   unsigned Opcode = Op.getOpcode();
4448 
4449   // Early out for FREEZE.
4450   if (Opcode == ISD::FREEZE)
4451     return true;
4452 
4453   if (Depth >= MaxRecursionDepth)
4454     return false; // Limit search depth.
4455 
4456   if (isIntOrFPConstant(Op))
4457     return true;
4458 
4459   switch (Opcode) {
4460   case ISD::UNDEF:
4461     return PoisonOnly;
4462 
4463   case ISD::BUILD_VECTOR:
4464     // NOTE: BUILD_VECTOR has implicit truncation of wider scalar elements -
4465     // this shouldn't affect the result.
4466     for (unsigned i = 0, e = Op.getNumOperands(); i < e; ++i) {
4467       if (!DemandedElts[i])
4468         continue;
4469       if (!isGuaranteedNotToBeUndefOrPoison(Op.getOperand(i), PoisonOnly,
4470                                             Depth + 1))
4471         return false;
4472     }
4473     return true;
4474 
4475   // TODO: Search for noundef attributes from library functions.
4476 
4477   // TODO: Pointers dereferenced by ISD::LOAD/STORE ops are noundef.
4478 
4479   default:
4480     // Allow the target to implement this method for its nodes.
4481     if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::INTRINSIC_WO_CHAIN ||
4482         Opcode == ISD::INTRINSIC_W_CHAIN || Opcode == ISD::INTRINSIC_VOID)
4483       return TLI->isGuaranteedNotToBeUndefOrPoisonForTargetNode(
4484           Op, DemandedElts, *this, PoisonOnly, Depth);
4485     break;
4486   }
4487 
4488   return false;
4489 }
4490 
4491 bool SelectionDAG::isBaseWithConstantOffset(SDValue Op) const {
4492   if ((Op.getOpcode() != ISD::ADD && Op.getOpcode() != ISD::OR) ||
4493       !isa<ConstantSDNode>(Op.getOperand(1)))
4494     return false;
4495 
4496   if (Op.getOpcode() == ISD::OR &&
4497       !MaskedValueIsZero(Op.getOperand(0), Op.getConstantOperandAPInt(1)))
4498     return false;
4499 
4500   return true;
4501 }
4502 
4503 bool SelectionDAG::isKnownNeverNaN(SDValue Op, bool SNaN, unsigned Depth) const {
4504   // If we're told that NaNs won't happen, assume they won't.
4505   if (getTarget().Options.NoNaNsFPMath || Op->getFlags().hasNoNaNs())
4506     return true;
4507 
4508   if (Depth >= MaxRecursionDepth)
4509     return false; // Limit search depth.
4510 
4511   // TODO: Handle vectors.
4512   // If the value is a constant, we can obviously see if it is a NaN or not.
4513   if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) {
4514     return !C->getValueAPF().isNaN() ||
4515            (SNaN && !C->getValueAPF().isSignaling());
4516   }
4517 
4518   unsigned Opcode = Op.getOpcode();
4519   switch (Opcode) {
4520   case ISD::FADD:
4521   case ISD::FSUB:
4522   case ISD::FMUL:
4523   case ISD::FDIV:
4524   case ISD::FREM:
4525   case ISD::FSIN:
4526   case ISD::FCOS: {
4527     if (SNaN)
4528       return true;
4529     // TODO: Need isKnownNeverInfinity
4530     return false;
4531   }
4532   case ISD::FCANONICALIZE:
4533   case ISD::FEXP:
4534   case ISD::FEXP2:
4535   case ISD::FTRUNC:
4536   case ISD::FFLOOR:
4537   case ISD::FCEIL:
4538   case ISD::FROUND:
4539   case ISD::FROUNDEVEN:
4540   case ISD::FRINT:
4541   case ISD::FNEARBYINT: {
4542     if (SNaN)
4543       return true;
4544     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
4545   }
4546   case ISD::FABS:
4547   case ISD::FNEG:
4548   case ISD::FCOPYSIGN: {
4549     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
4550   }
4551   case ISD::SELECT:
4552     return isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1) &&
4553            isKnownNeverNaN(Op.getOperand(2), SNaN, Depth + 1);
4554   case ISD::FP_EXTEND:
4555   case ISD::FP_ROUND: {
4556     if (SNaN)
4557       return true;
4558     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
4559   }
4560   case ISD::SINT_TO_FP:
4561   case ISD::UINT_TO_FP:
4562     return true;
4563   case ISD::FMA:
4564   case ISD::FMAD: {
4565     if (SNaN)
4566       return true;
4567     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) &&
4568            isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1) &&
4569            isKnownNeverNaN(Op.getOperand(2), SNaN, Depth + 1);
4570   }
4571   case ISD::FSQRT: // Need is known positive
4572   case ISD::FLOG:
4573   case ISD::FLOG2:
4574   case ISD::FLOG10:
4575   case ISD::FPOWI:
4576   case ISD::FPOW: {
4577     if (SNaN)
4578       return true;
4579     // TODO: Refine on operand
4580     return false;
4581   }
4582   case ISD::FMINNUM:
4583   case ISD::FMAXNUM: {
4584     // Only one needs to be known not-nan, since it will be returned if the
4585     // other ends up being one.
4586     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) ||
4587            isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1);
4588   }
4589   case ISD::FMINNUM_IEEE:
4590   case ISD::FMAXNUM_IEEE: {
4591     if (SNaN)
4592       return true;
4593     // This can return a NaN if either operand is an sNaN, or if both operands
4594     // are NaN.
4595     return (isKnownNeverNaN(Op.getOperand(0), false, Depth + 1) &&
4596             isKnownNeverSNaN(Op.getOperand(1), Depth + 1)) ||
4597            (isKnownNeverNaN(Op.getOperand(1), false, Depth + 1) &&
4598             isKnownNeverSNaN(Op.getOperand(0), Depth + 1));
4599   }
4600   case ISD::FMINIMUM:
4601   case ISD::FMAXIMUM: {
4602     // TODO: Does this quiet or return the origina NaN as-is?
4603     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) &&
4604            isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1);
4605   }
4606   case ISD::EXTRACT_VECTOR_ELT: {
4607     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
4608   }
4609   default:
4610     if (Opcode >= ISD::BUILTIN_OP_END ||
4611         Opcode == ISD::INTRINSIC_WO_CHAIN ||
4612         Opcode == ISD::INTRINSIC_W_CHAIN ||
4613         Opcode == ISD::INTRINSIC_VOID) {
4614       return TLI->isKnownNeverNaNForTargetNode(Op, *this, SNaN, Depth);
4615     }
4616 
4617     return false;
4618   }
4619 }
4620 
4621 bool SelectionDAG::isKnownNeverZeroFloat(SDValue Op) const {
4622   assert(Op.getValueType().isFloatingPoint() &&
4623          "Floating point type expected");
4624 
4625   // If the value is a constant, we can obviously see if it is a zero or not.
4626   // TODO: Add BuildVector support.
4627   if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op))
4628     return !C->isZero();
4629   return false;
4630 }
4631 
4632 bool SelectionDAG::isKnownNeverZero(SDValue Op) const {
4633   assert(!Op.getValueType().isFloatingPoint() &&
4634          "Floating point types unsupported - use isKnownNeverZeroFloat");
4635 
4636   // If the value is a constant, we can obviously see if it is a zero or not.
4637   if (ISD::matchUnaryPredicate(Op,
4638                                [](ConstantSDNode *C) { return !C->isZero(); }))
4639     return true;
4640 
4641   // TODO: Recognize more cases here.
4642   switch (Op.getOpcode()) {
4643   default: break;
4644   case ISD::OR:
4645     if (isKnownNeverZero(Op.getOperand(1)) ||
4646         isKnownNeverZero(Op.getOperand(0)))
4647       return true;
4648     break;
4649   }
4650 
4651   return false;
4652 }
4653 
4654 bool SelectionDAG::isEqualTo(SDValue A, SDValue B) const {
4655   // Check the obvious case.
4656   if (A == B) return true;
4657 
4658   // For for negative and positive zero.
4659   if (const ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A))
4660     if (const ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B))
4661       if (CA->isZero() && CB->isZero()) return true;
4662 
4663   // Otherwise they may not be equal.
4664   return false;
4665 }
4666 
4667 // FIXME: unify with llvm::haveNoCommonBitsSet.
4668 bool SelectionDAG::haveNoCommonBitsSet(SDValue A, SDValue B) const {
4669   assert(A.getValueType() == B.getValueType() &&
4670          "Values must have the same type");
4671   // Match masked merge pattern (X & ~M) op (Y & M)
4672   if (A->getOpcode() == ISD::AND && B->getOpcode() == ISD::AND) {
4673     auto MatchNoCommonBitsPattern = [&](SDValue NotM, SDValue And) {
4674       if (isBitwiseNot(NotM, true)) {
4675         SDValue NotOperand = NotM->getOperand(0);
4676         return NotOperand == And->getOperand(0) ||
4677                NotOperand == And->getOperand(1);
4678       }
4679       return false;
4680     };
4681     if (MatchNoCommonBitsPattern(A->getOperand(0), B) ||
4682         MatchNoCommonBitsPattern(A->getOperand(1), B) ||
4683         MatchNoCommonBitsPattern(B->getOperand(0), A) ||
4684         MatchNoCommonBitsPattern(B->getOperand(1), A))
4685       return true;
4686   }
4687   return KnownBits::haveNoCommonBitsSet(computeKnownBits(A),
4688                                         computeKnownBits(B));
4689 }
4690 
4691 static SDValue FoldSTEP_VECTOR(const SDLoc &DL, EVT VT, SDValue Step,
4692                                SelectionDAG &DAG) {
4693   if (cast<ConstantSDNode>(Step)->isZero())
4694     return DAG.getConstant(0, DL, VT);
4695 
4696   return SDValue();
4697 }
4698 
4699 static SDValue FoldBUILD_VECTOR(const SDLoc &DL, EVT VT,
4700                                 ArrayRef<SDValue> Ops,
4701                                 SelectionDAG &DAG) {
4702   int NumOps = Ops.size();
4703   assert(NumOps != 0 && "Can't build an empty vector!");
4704   assert(!VT.isScalableVector() &&
4705          "BUILD_VECTOR cannot be used with scalable types");
4706   assert(VT.getVectorNumElements() == (unsigned)NumOps &&
4707          "Incorrect element count in BUILD_VECTOR!");
4708 
4709   // BUILD_VECTOR of UNDEFs is UNDEF.
4710   if (llvm::all_of(Ops, [](SDValue Op) { return Op.isUndef(); }))
4711     return DAG.getUNDEF(VT);
4712 
4713   // BUILD_VECTOR of seq extract/insert from the same vector + type is Identity.
4714   SDValue IdentitySrc;
4715   bool IsIdentity = true;
4716   for (int i = 0; i != NumOps; ++i) {
4717     if (Ops[i].getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
4718         Ops[i].getOperand(0).getValueType() != VT ||
4719         (IdentitySrc && Ops[i].getOperand(0) != IdentitySrc) ||
4720         !isa<ConstantSDNode>(Ops[i].getOperand(1)) ||
4721         cast<ConstantSDNode>(Ops[i].getOperand(1))->getAPIntValue() != i) {
4722       IsIdentity = false;
4723       break;
4724     }
4725     IdentitySrc = Ops[i].getOperand(0);
4726   }
4727   if (IsIdentity)
4728     return IdentitySrc;
4729 
4730   return SDValue();
4731 }
4732 
4733 /// Try to simplify vector concatenation to an input value, undef, or build
4734 /// vector.
4735 static SDValue foldCONCAT_VECTORS(const SDLoc &DL, EVT VT,
4736                                   ArrayRef<SDValue> Ops,
4737                                   SelectionDAG &DAG) {
4738   assert(!Ops.empty() && "Can't concatenate an empty list of vectors!");
4739   assert(llvm::all_of(Ops,
4740                       [Ops](SDValue Op) {
4741                         return Ops[0].getValueType() == Op.getValueType();
4742                       }) &&
4743          "Concatenation of vectors with inconsistent value types!");
4744   assert((Ops[0].getValueType().getVectorElementCount() * Ops.size()) ==
4745              VT.getVectorElementCount() &&
4746          "Incorrect element count in vector concatenation!");
4747 
4748   if (Ops.size() == 1)
4749     return Ops[0];
4750 
4751   // Concat of UNDEFs is UNDEF.
4752   if (llvm::all_of(Ops, [](SDValue Op) { return Op.isUndef(); }))
4753     return DAG.getUNDEF(VT);
4754 
4755   // Scan the operands and look for extract operations from a single source
4756   // that correspond to insertion at the same location via this concatenation:
4757   // concat (extract X, 0*subvec_elts), (extract X, 1*subvec_elts), ...
4758   SDValue IdentitySrc;
4759   bool IsIdentity = true;
4760   for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
4761     SDValue Op = Ops[i];
4762     unsigned IdentityIndex = i * Op.getValueType().getVectorMinNumElements();
4763     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
4764         Op.getOperand(0).getValueType() != VT ||
4765         (IdentitySrc && Op.getOperand(0) != IdentitySrc) ||
4766         Op.getConstantOperandVal(1) != IdentityIndex) {
4767       IsIdentity = false;
4768       break;
4769     }
4770     assert((!IdentitySrc || IdentitySrc == Op.getOperand(0)) &&
4771            "Unexpected identity source vector for concat of extracts");
4772     IdentitySrc = Op.getOperand(0);
4773   }
4774   if (IsIdentity) {
4775     assert(IdentitySrc && "Failed to set source vector of extracts");
4776     return IdentitySrc;
4777   }
4778 
4779   // The code below this point is only designed to work for fixed width
4780   // vectors, so we bail out for now.
4781   if (VT.isScalableVector())
4782     return SDValue();
4783 
4784   // A CONCAT_VECTOR with all UNDEF/BUILD_VECTOR operands can be
4785   // simplified to one big BUILD_VECTOR.
4786   // FIXME: Add support for SCALAR_TO_VECTOR as well.
4787   EVT SVT = VT.getScalarType();
4788   SmallVector<SDValue, 16> Elts;
4789   for (SDValue Op : Ops) {
4790     EVT OpVT = Op.getValueType();
4791     if (Op.isUndef())
4792       Elts.append(OpVT.getVectorNumElements(), DAG.getUNDEF(SVT));
4793     else if (Op.getOpcode() == ISD::BUILD_VECTOR)
4794       Elts.append(Op->op_begin(), Op->op_end());
4795     else
4796       return SDValue();
4797   }
4798 
4799   // BUILD_VECTOR requires all inputs to be of the same type, find the
4800   // maximum type and extend them all.
4801   for (SDValue Op : Elts)
4802     SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
4803 
4804   if (SVT.bitsGT(VT.getScalarType())) {
4805     for (SDValue &Op : Elts) {
4806       if (Op.isUndef())
4807         Op = DAG.getUNDEF(SVT);
4808       else
4809         Op = DAG.getTargetLoweringInfo().isZExtFree(Op.getValueType(), SVT)
4810                  ? DAG.getZExtOrTrunc(Op, DL, SVT)
4811                  : DAG.getSExtOrTrunc(Op, DL, SVT);
4812     }
4813   }
4814 
4815   SDValue V = DAG.getBuildVector(VT, DL, Elts);
4816   NewSDValueDbgMsg(V, "New node fold concat vectors: ", &DAG);
4817   return V;
4818 }
4819 
4820 /// Gets or creates the specified node.
4821 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT) {
4822   FoldingSetNodeID ID;
4823   AddNodeIDNode(ID, Opcode, getVTList(VT), None);
4824   void *IP = nullptr;
4825   if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
4826     return SDValue(E, 0);
4827 
4828   auto *N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(),
4829                               getVTList(VT));
4830   CSEMap.InsertNode(N, IP);
4831 
4832   InsertNode(N);
4833   SDValue V = SDValue(N, 0);
4834   NewSDValueDbgMsg(V, "Creating new node: ", this);
4835   return V;
4836 }
4837 
4838 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
4839                               SDValue Operand) {
4840   SDNodeFlags Flags;
4841   if (Inserter)
4842     Flags = Inserter->getFlags();
4843   return getNode(Opcode, DL, VT, Operand, Flags);
4844 }
4845 
4846 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
4847                               SDValue Operand, const SDNodeFlags Flags) {
4848   assert(Operand.getOpcode() != ISD::DELETED_NODE &&
4849          "Operand is DELETED_NODE!");
4850   // Constant fold unary operations with an integer constant operand. Even
4851   // opaque constant will be folded, because the folding of unary operations
4852   // doesn't create new constants with different values. Nevertheless, the
4853   // opaque flag is preserved during folding to prevent future folding with
4854   // other constants.
4855   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Operand)) {
4856     const APInt &Val = C->getAPIntValue();
4857     switch (Opcode) {
4858     default: break;
4859     case ISD::SIGN_EXTEND:
4860       return getConstant(Val.sextOrTrunc(VT.getSizeInBits()), DL, VT,
4861                          C->isTargetOpcode(), C->isOpaque());
4862     case ISD::TRUNCATE:
4863       if (C->isOpaque())
4864         break;
4865       LLVM_FALLTHROUGH;
4866     case ISD::ZERO_EXTEND:
4867       return getConstant(Val.zextOrTrunc(VT.getSizeInBits()), DL, VT,
4868                          C->isTargetOpcode(), C->isOpaque());
4869     case ISD::ANY_EXTEND:
4870       // Some targets like RISCV prefer to sign extend some types.
4871       if (TLI->isSExtCheaperThanZExt(Operand.getValueType(), VT))
4872         return getConstant(Val.sextOrTrunc(VT.getSizeInBits()), DL, VT,
4873                            C->isTargetOpcode(), C->isOpaque());
4874       return getConstant(Val.zextOrTrunc(VT.getSizeInBits()), DL, VT,
4875                          C->isTargetOpcode(), C->isOpaque());
4876     case ISD::UINT_TO_FP:
4877     case ISD::SINT_TO_FP: {
4878       APFloat apf(EVTToAPFloatSemantics(VT),
4879                   APInt::getZero(VT.getSizeInBits()));
4880       (void)apf.convertFromAPInt(Val,
4881                                  Opcode==ISD::SINT_TO_FP,
4882                                  APFloat::rmNearestTiesToEven);
4883       return getConstantFP(apf, DL, VT);
4884     }
4885     case ISD::BITCAST:
4886       if (VT == MVT::f16 && C->getValueType(0) == MVT::i16)
4887         return getConstantFP(APFloat(APFloat::IEEEhalf(), Val), DL, VT);
4888       if (VT == MVT::f32 && C->getValueType(0) == MVT::i32)
4889         return getConstantFP(APFloat(APFloat::IEEEsingle(), Val), DL, VT);
4890       if (VT == MVT::f64 && C->getValueType(0) == MVT::i64)
4891         return getConstantFP(APFloat(APFloat::IEEEdouble(), Val), DL, VT);
4892       if (VT == MVT::f128 && C->getValueType(0) == MVT::i128)
4893         return getConstantFP(APFloat(APFloat::IEEEquad(), Val), DL, VT);
4894       break;
4895     case ISD::ABS:
4896       return getConstant(Val.abs(), DL, VT, C->isTargetOpcode(),
4897                          C->isOpaque());
4898     case ISD::BITREVERSE:
4899       return getConstant(Val.reverseBits(), DL, VT, C->isTargetOpcode(),
4900                          C->isOpaque());
4901     case ISD::BSWAP:
4902       return getConstant(Val.byteSwap(), DL, VT, C->isTargetOpcode(),
4903                          C->isOpaque());
4904     case ISD::CTPOP:
4905       return getConstant(Val.countPopulation(), DL, VT, C->isTargetOpcode(),
4906                          C->isOpaque());
4907     case ISD::CTLZ:
4908     case ISD::CTLZ_ZERO_UNDEF:
4909       return getConstant(Val.countLeadingZeros(), DL, VT, C->isTargetOpcode(),
4910                          C->isOpaque());
4911     case ISD::CTTZ:
4912     case ISD::CTTZ_ZERO_UNDEF:
4913       return getConstant(Val.countTrailingZeros(), DL, VT, C->isTargetOpcode(),
4914                          C->isOpaque());
4915     case ISD::FP16_TO_FP: {
4916       bool Ignored;
4917       APFloat FPV(APFloat::IEEEhalf(),
4918                   (Val.getBitWidth() == 16) ? Val : Val.trunc(16));
4919 
4920       // This can return overflow, underflow, or inexact; we don't care.
4921       // FIXME need to be more flexible about rounding mode.
4922       (void)FPV.convert(EVTToAPFloatSemantics(VT),
4923                         APFloat::rmNearestTiesToEven, &Ignored);
4924       return getConstantFP(FPV, DL, VT);
4925     }
4926     case ISD::STEP_VECTOR: {
4927       if (SDValue V = FoldSTEP_VECTOR(DL, VT, Operand, *this))
4928         return V;
4929       break;
4930     }
4931     }
4932   }
4933 
4934   // Constant fold unary operations with a floating point constant operand.
4935   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Operand)) {
4936     APFloat V = C->getValueAPF();    // make copy
4937     switch (Opcode) {
4938     case ISD::FNEG:
4939       V.changeSign();
4940       return getConstantFP(V, DL, VT);
4941     case ISD::FABS:
4942       V.clearSign();
4943       return getConstantFP(V, DL, VT);
4944     case ISD::FCEIL: {
4945       APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardPositive);
4946       if (fs == APFloat::opOK || fs == APFloat::opInexact)
4947         return getConstantFP(V, DL, VT);
4948       break;
4949     }
4950     case ISD::FTRUNC: {
4951       APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardZero);
4952       if (fs == APFloat::opOK || fs == APFloat::opInexact)
4953         return getConstantFP(V, DL, VT);
4954       break;
4955     }
4956     case ISD::FFLOOR: {
4957       APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardNegative);
4958       if (fs == APFloat::opOK || fs == APFloat::opInexact)
4959         return getConstantFP(V, DL, VT);
4960       break;
4961     }
4962     case ISD::FP_EXTEND: {
4963       bool ignored;
4964       // This can return overflow, underflow, or inexact; we don't care.
4965       // FIXME need to be more flexible about rounding mode.
4966       (void)V.convert(EVTToAPFloatSemantics(VT),
4967                       APFloat::rmNearestTiesToEven, &ignored);
4968       return getConstantFP(V, DL, VT);
4969     }
4970     case ISD::FP_TO_SINT:
4971     case ISD::FP_TO_UINT: {
4972       bool ignored;
4973       APSInt IntVal(VT.getSizeInBits(), Opcode == ISD::FP_TO_UINT);
4974       // FIXME need to be more flexible about rounding mode.
4975       APFloat::opStatus s =
4976           V.convertToInteger(IntVal, APFloat::rmTowardZero, &ignored);
4977       if (s == APFloat::opInvalidOp) // inexact is OK, in fact usual
4978         break;
4979       return getConstant(IntVal, DL, VT);
4980     }
4981     case ISD::BITCAST:
4982       if (VT == MVT::i16 && C->getValueType(0) == MVT::f16)
4983         return getConstant((uint16_t)V.bitcastToAPInt().getZExtValue(), DL, VT);
4984       if (VT == MVT::i16 && C->getValueType(0) == MVT::bf16)
4985         return getConstant((uint16_t)V.bitcastToAPInt().getZExtValue(), DL, VT);
4986       if (VT == MVT::i32 && C->getValueType(0) == MVT::f32)
4987         return getConstant((uint32_t)V.bitcastToAPInt().getZExtValue(), DL, VT);
4988       if (VT == MVT::i64 && C->getValueType(0) == MVT::f64)
4989         return getConstant(V.bitcastToAPInt().getZExtValue(), DL, VT);
4990       break;
4991     case ISD::FP_TO_FP16: {
4992       bool Ignored;
4993       // This can return overflow, underflow, or inexact; we don't care.
4994       // FIXME need to be more flexible about rounding mode.
4995       (void)V.convert(APFloat::IEEEhalf(),
4996                       APFloat::rmNearestTiesToEven, &Ignored);
4997       return getConstant(V.bitcastToAPInt().getZExtValue(), DL, VT);
4998     }
4999     }
5000   }
5001 
5002   // Constant fold unary operations with a vector integer or float operand.
5003   switch (Opcode) {
5004   default:
5005     // FIXME: Entirely reasonable to perform folding of other unary
5006     // operations here as the need arises.
5007     break;
5008   case ISD::FNEG:
5009   case ISD::FABS:
5010   case ISD::FCEIL:
5011   case ISD::FTRUNC:
5012   case ISD::FFLOOR:
5013   case ISD::FP_EXTEND:
5014   case ISD::FP_TO_SINT:
5015   case ISD::FP_TO_UINT:
5016   case ISD::TRUNCATE:
5017   case ISD::ANY_EXTEND:
5018   case ISD::ZERO_EXTEND:
5019   case ISD::SIGN_EXTEND:
5020   case ISD::UINT_TO_FP:
5021   case ISD::SINT_TO_FP:
5022   case ISD::ABS:
5023   case ISD::BITREVERSE:
5024   case ISD::BSWAP:
5025   case ISD::CTLZ:
5026   case ISD::CTLZ_ZERO_UNDEF:
5027   case ISD::CTTZ:
5028   case ISD::CTTZ_ZERO_UNDEF:
5029   case ISD::CTPOP: {
5030     SDValue Ops = {Operand};
5031     if (SDValue Fold = FoldConstantArithmetic(Opcode, DL, VT, Ops))
5032       return Fold;
5033   }
5034   }
5035 
5036   unsigned OpOpcode = Operand.getNode()->getOpcode();
5037   switch (Opcode) {
5038   case ISD::STEP_VECTOR:
5039     assert(VT.isScalableVector() &&
5040            "STEP_VECTOR can only be used with scalable types");
5041     assert(OpOpcode == ISD::TargetConstant &&
5042            VT.getVectorElementType() == Operand.getValueType() &&
5043            "Unexpected step operand");
5044     break;
5045   case ISD::FREEZE:
5046     assert(VT == Operand.getValueType() && "Unexpected VT!");
5047     break;
5048   case ISD::TokenFactor:
5049   case ISD::MERGE_VALUES:
5050   case ISD::CONCAT_VECTORS:
5051     return Operand;         // Factor, merge or concat of one node?  No need.
5052   case ISD::BUILD_VECTOR: {
5053     // Attempt to simplify BUILD_VECTOR.
5054     SDValue Ops[] = {Operand};
5055     if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
5056       return V;
5057     break;
5058   }
5059   case ISD::FP_ROUND: llvm_unreachable("Invalid method to make FP_ROUND node");
5060   case ISD::FP_EXTEND:
5061     assert(VT.isFloatingPoint() &&
5062            Operand.getValueType().isFloatingPoint() && "Invalid FP cast!");
5063     if (Operand.getValueType() == VT) return Operand;  // noop conversion.
5064     assert((!VT.isVector() ||
5065             VT.getVectorElementCount() ==
5066             Operand.getValueType().getVectorElementCount()) &&
5067            "Vector element count mismatch!");
5068     assert(Operand.getValueType().bitsLT(VT) &&
5069            "Invalid fpext node, dst < src!");
5070     if (Operand.isUndef())
5071       return getUNDEF(VT);
5072     break;
5073   case ISD::FP_TO_SINT:
5074   case ISD::FP_TO_UINT:
5075     if (Operand.isUndef())
5076       return getUNDEF(VT);
5077     break;
5078   case ISD::SINT_TO_FP:
5079   case ISD::UINT_TO_FP:
5080     // [us]itofp(undef) = 0, because the result value is bounded.
5081     if (Operand.isUndef())
5082       return getConstantFP(0.0, DL, VT);
5083     break;
5084   case ISD::SIGN_EXTEND:
5085     assert(VT.isInteger() && Operand.getValueType().isInteger() &&
5086            "Invalid SIGN_EXTEND!");
5087     assert(VT.isVector() == Operand.getValueType().isVector() &&
5088            "SIGN_EXTEND result type type should be vector iff the operand "
5089            "type is vector!");
5090     if (Operand.getValueType() == VT) return Operand;   // noop extension
5091     assert((!VT.isVector() ||
5092             VT.getVectorElementCount() ==
5093                 Operand.getValueType().getVectorElementCount()) &&
5094            "Vector element count mismatch!");
5095     assert(Operand.getValueType().bitsLT(VT) &&
5096            "Invalid sext node, dst < src!");
5097     if (OpOpcode == ISD::SIGN_EXTEND || OpOpcode == ISD::ZERO_EXTEND)
5098       return getNode(OpOpcode, DL, VT, Operand.getOperand(0));
5099     if (OpOpcode == ISD::UNDEF)
5100       // sext(undef) = 0, because the top bits will all be the same.
5101       return getConstant(0, DL, VT);
5102     break;
5103   case ISD::ZERO_EXTEND:
5104     assert(VT.isInteger() && Operand.getValueType().isInteger() &&
5105            "Invalid ZERO_EXTEND!");
5106     assert(VT.isVector() == Operand.getValueType().isVector() &&
5107            "ZERO_EXTEND result type type should be vector iff the operand "
5108            "type is vector!");
5109     if (Operand.getValueType() == VT) return Operand;   // noop extension
5110     assert((!VT.isVector() ||
5111             VT.getVectorElementCount() ==
5112                 Operand.getValueType().getVectorElementCount()) &&
5113            "Vector element count mismatch!");
5114     assert(Operand.getValueType().bitsLT(VT) &&
5115            "Invalid zext node, dst < src!");
5116     if (OpOpcode == ISD::ZERO_EXTEND)   // (zext (zext x)) -> (zext x)
5117       return getNode(ISD::ZERO_EXTEND, DL, VT, Operand.getOperand(0));
5118     if (OpOpcode == ISD::UNDEF)
5119       // zext(undef) = 0, because the top bits will be zero.
5120       return getConstant(0, DL, VT);
5121     break;
5122   case ISD::ANY_EXTEND:
5123     assert(VT.isInteger() && Operand.getValueType().isInteger() &&
5124            "Invalid ANY_EXTEND!");
5125     assert(VT.isVector() == Operand.getValueType().isVector() &&
5126            "ANY_EXTEND result type type should be vector iff the operand "
5127            "type is vector!");
5128     if (Operand.getValueType() == VT) return Operand;   // noop extension
5129     assert((!VT.isVector() ||
5130             VT.getVectorElementCount() ==
5131                 Operand.getValueType().getVectorElementCount()) &&
5132            "Vector element count mismatch!");
5133     assert(Operand.getValueType().bitsLT(VT) &&
5134            "Invalid anyext node, dst < src!");
5135 
5136     if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
5137         OpOpcode == ISD::ANY_EXTEND)
5138       // (ext (zext x)) -> (zext x)  and  (ext (sext x)) -> (sext x)
5139       return getNode(OpOpcode, DL, VT, Operand.getOperand(0));
5140     if (OpOpcode == ISD::UNDEF)
5141       return getUNDEF(VT);
5142 
5143     // (ext (trunc x)) -> x
5144     if (OpOpcode == ISD::TRUNCATE) {
5145       SDValue OpOp = Operand.getOperand(0);
5146       if (OpOp.getValueType() == VT) {
5147         transferDbgValues(Operand, OpOp);
5148         return OpOp;
5149       }
5150     }
5151     break;
5152   case ISD::TRUNCATE:
5153     assert(VT.isInteger() && Operand.getValueType().isInteger() &&
5154            "Invalid TRUNCATE!");
5155     assert(VT.isVector() == Operand.getValueType().isVector() &&
5156            "TRUNCATE result type type should be vector iff the operand "
5157            "type is vector!");
5158     if (Operand.getValueType() == VT) return Operand;   // noop truncate
5159     assert((!VT.isVector() ||
5160             VT.getVectorElementCount() ==
5161                 Operand.getValueType().getVectorElementCount()) &&
5162            "Vector element count mismatch!");
5163     assert(Operand.getValueType().bitsGT(VT) &&
5164            "Invalid truncate node, src < dst!");
5165     if (OpOpcode == ISD::TRUNCATE)
5166       return getNode(ISD::TRUNCATE, DL, VT, Operand.getOperand(0));
5167     if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
5168         OpOpcode == ISD::ANY_EXTEND) {
5169       // If the source is smaller than the dest, we still need an extend.
5170       if (Operand.getOperand(0).getValueType().getScalarType()
5171             .bitsLT(VT.getScalarType()))
5172         return getNode(OpOpcode, DL, VT, Operand.getOperand(0));
5173       if (Operand.getOperand(0).getValueType().bitsGT(VT))
5174         return getNode(ISD::TRUNCATE, DL, VT, Operand.getOperand(0));
5175       return Operand.getOperand(0);
5176     }
5177     if (OpOpcode == ISD::UNDEF)
5178       return getUNDEF(VT);
5179     if (OpOpcode == ISD::VSCALE && !NewNodesMustHaveLegalTypes)
5180       return getVScale(DL, VT, Operand.getConstantOperandAPInt(0));
5181     break;
5182   case ISD::ANY_EXTEND_VECTOR_INREG:
5183   case ISD::ZERO_EXTEND_VECTOR_INREG:
5184   case ISD::SIGN_EXTEND_VECTOR_INREG:
5185     assert(VT.isVector() && "This DAG node is restricted to vector types.");
5186     assert(Operand.getValueType().bitsLE(VT) &&
5187            "The input must be the same size or smaller than the result.");
5188     assert(VT.getVectorMinNumElements() <
5189                Operand.getValueType().getVectorMinNumElements() &&
5190            "The destination vector type must have fewer lanes than the input.");
5191     break;
5192   case ISD::ABS:
5193     assert(VT.isInteger() && VT == Operand.getValueType() &&
5194            "Invalid ABS!");
5195     if (OpOpcode == ISD::UNDEF)
5196       return getUNDEF(VT);
5197     break;
5198   case ISD::BSWAP:
5199     assert(VT.isInteger() && VT == Operand.getValueType() &&
5200            "Invalid BSWAP!");
5201     assert((VT.getScalarSizeInBits() % 16 == 0) &&
5202            "BSWAP types must be a multiple of 16 bits!");
5203     if (OpOpcode == ISD::UNDEF)
5204       return getUNDEF(VT);
5205     // bswap(bswap(X)) -> X.
5206     if (OpOpcode == ISD::BSWAP)
5207       return Operand.getOperand(0);
5208     break;
5209   case ISD::BITREVERSE:
5210     assert(VT.isInteger() && VT == Operand.getValueType() &&
5211            "Invalid BITREVERSE!");
5212     if (OpOpcode == ISD::UNDEF)
5213       return getUNDEF(VT);
5214     break;
5215   case ISD::BITCAST:
5216     assert(VT.getSizeInBits() == Operand.getValueSizeInBits() &&
5217            "Cannot BITCAST between types of different sizes!");
5218     if (VT == Operand.getValueType()) return Operand;  // noop conversion.
5219     if (OpOpcode == ISD::BITCAST)  // bitconv(bitconv(x)) -> bitconv(x)
5220       return getNode(ISD::BITCAST, DL, VT, Operand.getOperand(0));
5221     if (OpOpcode == ISD::UNDEF)
5222       return getUNDEF(VT);
5223     break;
5224   case ISD::SCALAR_TO_VECTOR:
5225     assert(VT.isVector() && !Operand.getValueType().isVector() &&
5226            (VT.getVectorElementType() == Operand.getValueType() ||
5227             (VT.getVectorElementType().isInteger() &&
5228              Operand.getValueType().isInteger() &&
5229              VT.getVectorElementType().bitsLE(Operand.getValueType()))) &&
5230            "Illegal SCALAR_TO_VECTOR node!");
5231     if (OpOpcode == ISD::UNDEF)
5232       return getUNDEF(VT);
5233     // scalar_to_vector(extract_vector_elt V, 0) -> V, top bits are undefined.
5234     if (OpOpcode == ISD::EXTRACT_VECTOR_ELT &&
5235         isa<ConstantSDNode>(Operand.getOperand(1)) &&
5236         Operand.getConstantOperandVal(1) == 0 &&
5237         Operand.getOperand(0).getValueType() == VT)
5238       return Operand.getOperand(0);
5239     break;
5240   case ISD::FNEG:
5241     // Negation of an unknown bag of bits is still completely undefined.
5242     if (OpOpcode == ISD::UNDEF)
5243       return getUNDEF(VT);
5244 
5245     if (OpOpcode == ISD::FNEG)  // --X -> X
5246       return Operand.getOperand(0);
5247     break;
5248   case ISD::FABS:
5249     if (OpOpcode == ISD::FNEG)  // abs(-X) -> abs(X)
5250       return getNode(ISD::FABS, DL, VT, Operand.getOperand(0));
5251     break;
5252   case ISD::VSCALE:
5253     assert(VT == Operand.getValueType() && "Unexpected VT!");
5254     break;
5255   case ISD::CTPOP:
5256     if (Operand.getValueType().getScalarType() == MVT::i1)
5257       return Operand;
5258     break;
5259   case ISD::CTLZ:
5260   case ISD::CTTZ:
5261     if (Operand.getValueType().getScalarType() == MVT::i1)
5262       return getNOT(DL, Operand, Operand.getValueType());
5263     break;
5264   case ISD::VECREDUCE_SMIN:
5265   case ISD::VECREDUCE_UMAX:
5266     if (Operand.getValueType().getScalarType() == MVT::i1)
5267       return getNode(ISD::VECREDUCE_OR, DL, VT, Operand);
5268     break;
5269   case ISD::VECREDUCE_SMAX:
5270   case ISD::VECREDUCE_UMIN:
5271     if (Operand.getValueType().getScalarType() == MVT::i1)
5272       return getNode(ISD::VECREDUCE_AND, DL, VT, Operand);
5273     break;
5274   }
5275 
5276   SDNode *N;
5277   SDVTList VTs = getVTList(VT);
5278   SDValue Ops[] = {Operand};
5279   if (VT != MVT::Glue) { // Don't CSE flag producing nodes
5280     FoldingSetNodeID ID;
5281     AddNodeIDNode(ID, Opcode, VTs, Ops);
5282     void *IP = nullptr;
5283     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
5284       E->intersectFlagsWith(Flags);
5285       return SDValue(E, 0);
5286     }
5287 
5288     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
5289     N->setFlags(Flags);
5290     createOperands(N, Ops);
5291     CSEMap.InsertNode(N, IP);
5292   } else {
5293     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
5294     createOperands(N, Ops);
5295   }
5296 
5297   InsertNode(N);
5298   SDValue V = SDValue(N, 0);
5299   NewSDValueDbgMsg(V, "Creating new node: ", this);
5300   return V;
5301 }
5302 
5303 static llvm::Optional<APInt> FoldValue(unsigned Opcode, const APInt &C1,
5304                                        const APInt &C2) {
5305   switch (Opcode) {
5306   case ISD::ADD:  return C1 + C2;
5307   case ISD::SUB:  return C1 - C2;
5308   case ISD::MUL:  return C1 * C2;
5309   case ISD::AND:  return C1 & C2;
5310   case ISD::OR:   return C1 | C2;
5311   case ISD::XOR:  return C1 ^ C2;
5312   case ISD::SHL:  return C1 << C2;
5313   case ISD::SRL:  return C1.lshr(C2);
5314   case ISD::SRA:  return C1.ashr(C2);
5315   case ISD::ROTL: return C1.rotl(C2);
5316   case ISD::ROTR: return C1.rotr(C2);
5317   case ISD::SMIN: return C1.sle(C2) ? C1 : C2;
5318   case ISD::SMAX: return C1.sge(C2) ? C1 : C2;
5319   case ISD::UMIN: return C1.ule(C2) ? C1 : C2;
5320   case ISD::UMAX: return C1.uge(C2) ? C1 : C2;
5321   case ISD::SADDSAT: return C1.sadd_sat(C2);
5322   case ISD::UADDSAT: return C1.uadd_sat(C2);
5323   case ISD::SSUBSAT: return C1.ssub_sat(C2);
5324   case ISD::USUBSAT: return C1.usub_sat(C2);
5325   case ISD::SSHLSAT: return C1.sshl_sat(C2);
5326   case ISD::USHLSAT: return C1.ushl_sat(C2);
5327   case ISD::UDIV:
5328     if (!C2.getBoolValue())
5329       break;
5330     return C1.udiv(C2);
5331   case ISD::UREM:
5332     if (!C2.getBoolValue())
5333       break;
5334     return C1.urem(C2);
5335   case ISD::SDIV:
5336     if (!C2.getBoolValue())
5337       break;
5338     return C1.sdiv(C2);
5339   case ISD::SREM:
5340     if (!C2.getBoolValue())
5341       break;
5342     return C1.srem(C2);
5343   case ISD::MULHS: {
5344     unsigned FullWidth = C1.getBitWidth() * 2;
5345     APInt C1Ext = C1.sext(FullWidth);
5346     APInt C2Ext = C2.sext(FullWidth);
5347     return (C1Ext * C2Ext).extractBits(C1.getBitWidth(), C1.getBitWidth());
5348   }
5349   case ISD::MULHU: {
5350     unsigned FullWidth = C1.getBitWidth() * 2;
5351     APInt C1Ext = C1.zext(FullWidth);
5352     APInt C2Ext = C2.zext(FullWidth);
5353     return (C1Ext * C2Ext).extractBits(C1.getBitWidth(), C1.getBitWidth());
5354   }
5355   case ISD::AVGFLOORS: {
5356     unsigned FullWidth = C1.getBitWidth() + 1;
5357     APInt C1Ext = C1.sext(FullWidth);
5358     APInt C2Ext = C2.sext(FullWidth);
5359     return (C1Ext + C2Ext).extractBits(C1.getBitWidth(), 1);
5360   }
5361   case ISD::AVGFLOORU: {
5362     unsigned FullWidth = C1.getBitWidth() + 1;
5363     APInt C1Ext = C1.zext(FullWidth);
5364     APInt C2Ext = C2.zext(FullWidth);
5365     return (C1Ext + C2Ext).extractBits(C1.getBitWidth(), 1);
5366   }
5367   case ISD::AVGCEILS: {
5368     unsigned FullWidth = C1.getBitWidth() + 1;
5369     APInt C1Ext = C1.sext(FullWidth);
5370     APInt C2Ext = C2.sext(FullWidth);
5371     return (C1Ext + C2Ext + 1).extractBits(C1.getBitWidth(), 1);
5372   }
5373   case ISD::AVGCEILU: {
5374     unsigned FullWidth = C1.getBitWidth() + 1;
5375     APInt C1Ext = C1.zext(FullWidth);
5376     APInt C2Ext = C2.zext(FullWidth);
5377     return (C1Ext + C2Ext + 1).extractBits(C1.getBitWidth(), 1);
5378   }
5379   }
5380   return llvm::None;
5381 }
5382 
5383 SDValue SelectionDAG::FoldSymbolOffset(unsigned Opcode, EVT VT,
5384                                        const GlobalAddressSDNode *GA,
5385                                        const SDNode *N2) {
5386   if (GA->getOpcode() != ISD::GlobalAddress)
5387     return SDValue();
5388   if (!TLI->isOffsetFoldingLegal(GA))
5389     return SDValue();
5390   auto *C2 = dyn_cast<ConstantSDNode>(N2);
5391   if (!C2)
5392     return SDValue();
5393   int64_t Offset = C2->getSExtValue();
5394   switch (Opcode) {
5395   case ISD::ADD: break;
5396   case ISD::SUB: Offset = -uint64_t(Offset); break;
5397   default: return SDValue();
5398   }
5399   return getGlobalAddress(GA->getGlobal(), SDLoc(C2), VT,
5400                           GA->getOffset() + uint64_t(Offset));
5401 }
5402 
5403 bool SelectionDAG::isUndef(unsigned Opcode, ArrayRef<SDValue> Ops) {
5404   switch (Opcode) {
5405   case ISD::SDIV:
5406   case ISD::UDIV:
5407   case ISD::SREM:
5408   case ISD::UREM: {
5409     // If a divisor is zero/undef or any element of a divisor vector is
5410     // zero/undef, the whole op is undef.
5411     assert(Ops.size() == 2 && "Div/rem should have 2 operands");
5412     SDValue Divisor = Ops[1];
5413     if (Divisor.isUndef() || isNullConstant(Divisor))
5414       return true;
5415 
5416     return ISD::isBuildVectorOfConstantSDNodes(Divisor.getNode()) &&
5417            llvm::any_of(Divisor->op_values(),
5418                         [](SDValue V) { return V.isUndef() ||
5419                                         isNullConstant(V); });
5420     // TODO: Handle signed overflow.
5421   }
5422   // TODO: Handle oversized shifts.
5423   default:
5424     return false;
5425   }
5426 }
5427 
5428 SDValue SelectionDAG::FoldConstantArithmetic(unsigned Opcode, const SDLoc &DL,
5429                                              EVT VT, ArrayRef<SDValue> Ops) {
5430   // If the opcode is a target-specific ISD node, there's nothing we can
5431   // do here and the operand rules may not line up with the below, so
5432   // bail early.
5433   // We can't create a scalar CONCAT_VECTORS so skip it. It will break
5434   // for concats involving SPLAT_VECTOR. Concats of BUILD_VECTORS are handled by
5435   // foldCONCAT_VECTORS in getNode before this is called.
5436   if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::CONCAT_VECTORS)
5437     return SDValue();
5438 
5439   unsigned NumOps = Ops.size();
5440   if (NumOps == 0)
5441     return SDValue();
5442 
5443   if (isUndef(Opcode, Ops))
5444     return getUNDEF(VT);
5445 
5446   // Handle binops special cases.
5447   if (NumOps == 2) {
5448     if (SDValue CFP = foldConstantFPMath(Opcode, DL, VT, Ops[0], Ops[1]))
5449       return CFP;
5450 
5451     if (auto *C1 = dyn_cast<ConstantSDNode>(Ops[0])) {
5452       if (auto *C2 = dyn_cast<ConstantSDNode>(Ops[1])) {
5453         if (C1->isOpaque() || C2->isOpaque())
5454           return SDValue();
5455 
5456         Optional<APInt> FoldAttempt =
5457             FoldValue(Opcode, C1->getAPIntValue(), C2->getAPIntValue());
5458         if (!FoldAttempt)
5459           return SDValue();
5460 
5461         SDValue Folded = getConstant(FoldAttempt.getValue(), DL, VT);
5462         assert((!Folded || !VT.isVector()) &&
5463                "Can't fold vectors ops with scalar operands");
5464         return Folded;
5465       }
5466     }
5467 
5468     // fold (add Sym, c) -> Sym+c
5469     if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Ops[0]))
5470       return FoldSymbolOffset(Opcode, VT, GA, Ops[1].getNode());
5471     if (TLI->isCommutativeBinOp(Opcode))
5472       if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Ops[1]))
5473         return FoldSymbolOffset(Opcode, VT, GA, Ops[0].getNode());
5474   }
5475 
5476   // This is for vector folding only from here on.
5477   if (!VT.isVector())
5478     return SDValue();
5479 
5480   ElementCount NumElts = VT.getVectorElementCount();
5481 
5482   // See if we can fold through bitcasted integer ops.
5483   // TODO: Can we handle undef elements?
5484   if (NumOps == 2 && VT.isFixedLengthVector() && VT.isInteger() &&
5485       Ops[0].getValueType() == VT && Ops[1].getValueType() == VT &&
5486       Ops[0].getOpcode() == ISD::BITCAST &&
5487       Ops[1].getOpcode() == ISD::BITCAST) {
5488     SDValue N1 = peekThroughBitcasts(Ops[0]);
5489     SDValue N2 = peekThroughBitcasts(Ops[1]);
5490     auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
5491     auto *BV2 = dyn_cast<BuildVectorSDNode>(N2);
5492     EVT BVVT = N1.getValueType();
5493     if (BV1 && BV2 && BVVT.isInteger() && BVVT == N2.getValueType()) {
5494       bool IsLE = getDataLayout().isLittleEndian();
5495       unsigned EltBits = VT.getScalarSizeInBits();
5496       SmallVector<APInt> RawBits1, RawBits2;
5497       BitVector UndefElts1, UndefElts2;
5498       if (BV1->getConstantRawBits(IsLE, EltBits, RawBits1, UndefElts1) &&
5499           BV2->getConstantRawBits(IsLE, EltBits, RawBits2, UndefElts2) &&
5500           UndefElts1.none() && UndefElts2.none()) {
5501         SmallVector<APInt> RawBits;
5502         for (unsigned I = 0, E = NumElts.getFixedValue(); I != E; ++I) {
5503           Optional<APInt> Fold = FoldValue(Opcode, RawBits1[I], RawBits2[I]);
5504           if (!Fold)
5505             break;
5506           RawBits.push_back(Fold.getValue());
5507         }
5508         if (RawBits.size() == NumElts.getFixedValue()) {
5509           // We have constant folded, but we need to cast this again back to
5510           // the original (possibly legalized) type.
5511           SmallVector<APInt> DstBits;
5512           BitVector DstUndefs;
5513           BuildVectorSDNode::recastRawBits(IsLE, BVVT.getScalarSizeInBits(),
5514                                            DstBits, RawBits, DstUndefs,
5515                                            BitVector(RawBits.size(), false));
5516           EVT BVEltVT = BV1->getOperand(0).getValueType();
5517           unsigned BVEltBits = BVEltVT.getSizeInBits();
5518           SmallVector<SDValue> Ops(DstBits.size(), getUNDEF(BVEltVT));
5519           for (unsigned I = 0, E = DstBits.size(); I != E; ++I) {
5520             if (DstUndefs[I])
5521               continue;
5522             Ops[I] = getConstant(DstBits[I].sextOrSelf(BVEltBits), DL, BVEltVT);
5523           }
5524           return getBitcast(VT, getBuildVector(BVVT, DL, Ops));
5525         }
5526       }
5527     }
5528   }
5529 
5530   // Fold (mul step_vector(C0), C1) to (step_vector(C0 * C1)).
5531   //      (shl step_vector(C0), C1) -> (step_vector(C0 << C1))
5532   if ((Opcode == ISD::MUL || Opcode == ISD::SHL) &&
5533       Ops[0].getOpcode() == ISD::STEP_VECTOR) {
5534     APInt RHSVal;
5535     if (ISD::isConstantSplatVector(Ops[1].getNode(), RHSVal)) {
5536       APInt NewStep = Opcode == ISD::MUL
5537                           ? Ops[0].getConstantOperandAPInt(0) * RHSVal
5538                           : Ops[0].getConstantOperandAPInt(0) << RHSVal;
5539       return getStepVector(DL, VT, NewStep);
5540     }
5541   }
5542 
5543   auto IsScalarOrSameVectorSize = [NumElts](const SDValue &Op) {
5544     return !Op.getValueType().isVector() ||
5545            Op.getValueType().getVectorElementCount() == NumElts;
5546   };
5547 
5548   auto IsBuildVectorSplatVectorOrUndef = [](const SDValue &Op) {
5549     return Op.isUndef() || Op.getOpcode() == ISD::CONDCODE ||
5550            Op.getOpcode() == ISD::BUILD_VECTOR ||
5551            Op.getOpcode() == ISD::SPLAT_VECTOR;
5552   };
5553 
5554   // All operands must be vector types with the same number of elements as
5555   // the result type and must be either UNDEF or a build/splat vector
5556   // or UNDEF scalars.
5557   if (!llvm::all_of(Ops, IsBuildVectorSplatVectorOrUndef) ||
5558       !llvm::all_of(Ops, IsScalarOrSameVectorSize))
5559     return SDValue();
5560 
5561   // If we are comparing vectors, then the result needs to be a i1 boolean
5562   // that is then sign-extended back to the legal result type.
5563   EVT SVT = (Opcode == ISD::SETCC ? MVT::i1 : VT.getScalarType());
5564 
5565   // Find legal integer scalar type for constant promotion and
5566   // ensure that its scalar size is at least as large as source.
5567   EVT LegalSVT = VT.getScalarType();
5568   if (NewNodesMustHaveLegalTypes && LegalSVT.isInteger()) {
5569     LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT);
5570     if (LegalSVT.bitsLT(VT.getScalarType()))
5571       return SDValue();
5572   }
5573 
5574   // For scalable vector types we know we're dealing with SPLAT_VECTORs. We
5575   // only have one operand to check. For fixed-length vector types we may have
5576   // a combination of BUILD_VECTOR and SPLAT_VECTOR.
5577   unsigned NumVectorElts = NumElts.isScalable() ? 1 : NumElts.getFixedValue();
5578 
5579   // Constant fold each scalar lane separately.
5580   SmallVector<SDValue, 4> ScalarResults;
5581   for (unsigned I = 0; I != NumVectorElts; I++) {
5582     SmallVector<SDValue, 4> ScalarOps;
5583     for (SDValue Op : Ops) {
5584       EVT InSVT = Op.getValueType().getScalarType();
5585       if (Op.getOpcode() != ISD::BUILD_VECTOR &&
5586           Op.getOpcode() != ISD::SPLAT_VECTOR) {
5587         if (Op.isUndef())
5588           ScalarOps.push_back(getUNDEF(InSVT));
5589         else
5590           ScalarOps.push_back(Op);
5591         continue;
5592       }
5593 
5594       SDValue ScalarOp =
5595           Op.getOperand(Op.getOpcode() == ISD::SPLAT_VECTOR ? 0 : I);
5596       EVT ScalarVT = ScalarOp.getValueType();
5597 
5598       // Build vector (integer) scalar operands may need implicit
5599       // truncation - do this before constant folding.
5600       if (ScalarVT.isInteger() && ScalarVT.bitsGT(InSVT))
5601         ScalarOp = getNode(ISD::TRUNCATE, DL, InSVT, ScalarOp);
5602 
5603       ScalarOps.push_back(ScalarOp);
5604     }
5605 
5606     // Constant fold the scalar operands.
5607     SDValue ScalarResult = getNode(Opcode, DL, SVT, ScalarOps);
5608 
5609     // Legalize the (integer) scalar constant if necessary.
5610     if (LegalSVT != SVT)
5611       ScalarResult = getNode(ISD::SIGN_EXTEND, DL, LegalSVT, ScalarResult);
5612 
5613     // Scalar folding only succeeded if the result is a constant or UNDEF.
5614     if (!ScalarResult.isUndef() && ScalarResult.getOpcode() != ISD::Constant &&
5615         ScalarResult.getOpcode() != ISD::ConstantFP)
5616       return SDValue();
5617     ScalarResults.push_back(ScalarResult);
5618   }
5619 
5620   SDValue V = NumElts.isScalable() ? getSplatVector(VT, DL, ScalarResults[0])
5621                                    : getBuildVector(VT, DL, ScalarResults);
5622   NewSDValueDbgMsg(V, "New node fold constant vector: ", this);
5623   return V;
5624 }
5625 
5626 SDValue SelectionDAG::foldConstantFPMath(unsigned Opcode, const SDLoc &DL,
5627                                          EVT VT, SDValue N1, SDValue N2) {
5628   // TODO: We don't do any constant folding for strict FP opcodes here, but we
5629   //       should. That will require dealing with a potentially non-default
5630   //       rounding mode, checking the "opStatus" return value from the APFloat
5631   //       math calculations, and possibly other variations.
5632   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1, /*AllowUndefs*/ false);
5633   ConstantFPSDNode *N2CFP = isConstOrConstSplatFP(N2, /*AllowUndefs*/ false);
5634   if (N1CFP && N2CFP) {
5635     APFloat C1 = N1CFP->getValueAPF(); // make copy
5636     const APFloat &C2 = N2CFP->getValueAPF();
5637     switch (Opcode) {
5638     case ISD::FADD:
5639       C1.add(C2, APFloat::rmNearestTiesToEven);
5640       return getConstantFP(C1, DL, VT);
5641     case ISD::FSUB:
5642       C1.subtract(C2, APFloat::rmNearestTiesToEven);
5643       return getConstantFP(C1, DL, VT);
5644     case ISD::FMUL:
5645       C1.multiply(C2, APFloat::rmNearestTiesToEven);
5646       return getConstantFP(C1, DL, VT);
5647     case ISD::FDIV:
5648       C1.divide(C2, APFloat::rmNearestTiesToEven);
5649       return getConstantFP(C1, DL, VT);
5650     case ISD::FREM:
5651       C1.mod(C2);
5652       return getConstantFP(C1, DL, VT);
5653     case ISD::FCOPYSIGN:
5654       C1.copySign(C2);
5655       return getConstantFP(C1, DL, VT);
5656     case ISD::FMINNUM:
5657       return getConstantFP(minnum(C1, C2), DL, VT);
5658     case ISD::FMAXNUM:
5659       return getConstantFP(maxnum(C1, C2), DL, VT);
5660     case ISD::FMINIMUM:
5661       return getConstantFP(minimum(C1, C2), DL, VT);
5662     case ISD::FMAXIMUM:
5663       return getConstantFP(maximum(C1, C2), DL, VT);
5664     default: break;
5665     }
5666   }
5667   if (N1CFP && Opcode == ISD::FP_ROUND) {
5668     APFloat C1 = N1CFP->getValueAPF();    // make copy
5669     bool Unused;
5670     // This can return overflow, underflow, or inexact; we don't care.
5671     // FIXME need to be more flexible about rounding mode.
5672     (void) C1.convert(EVTToAPFloatSemantics(VT), APFloat::rmNearestTiesToEven,
5673                       &Unused);
5674     return getConstantFP(C1, DL, VT);
5675   }
5676 
5677   switch (Opcode) {
5678   case ISD::FSUB:
5679     // -0.0 - undef --> undef (consistent with "fneg undef")
5680     if (ConstantFPSDNode *N1C = isConstOrConstSplatFP(N1, /*AllowUndefs*/ true))
5681       if (N1C && N1C->getValueAPF().isNegZero() && N2.isUndef())
5682         return getUNDEF(VT);
5683     LLVM_FALLTHROUGH;
5684 
5685   case ISD::FADD:
5686   case ISD::FMUL:
5687   case ISD::FDIV:
5688   case ISD::FREM:
5689     // If both operands are undef, the result is undef. If 1 operand is undef,
5690     // the result is NaN. This should match the behavior of the IR optimizer.
5691     if (N1.isUndef() && N2.isUndef())
5692       return getUNDEF(VT);
5693     if (N1.isUndef() || N2.isUndef())
5694       return getConstantFP(APFloat::getNaN(EVTToAPFloatSemantics(VT)), DL, VT);
5695   }
5696   return SDValue();
5697 }
5698 
5699 SDValue SelectionDAG::getAssertAlign(const SDLoc &DL, SDValue Val, Align A) {
5700   assert(Val.getValueType().isInteger() && "Invalid AssertAlign!");
5701 
5702   // There's no need to assert on a byte-aligned pointer. All pointers are at
5703   // least byte aligned.
5704   if (A == Align(1))
5705     return Val;
5706 
5707   FoldingSetNodeID ID;
5708   AddNodeIDNode(ID, ISD::AssertAlign, getVTList(Val.getValueType()), {Val});
5709   ID.AddInteger(A.value());
5710 
5711   void *IP = nullptr;
5712   if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
5713     return SDValue(E, 0);
5714 
5715   auto *N = newSDNode<AssertAlignSDNode>(DL.getIROrder(), DL.getDebugLoc(),
5716                                          Val.getValueType(), A);
5717   createOperands(N, {Val});
5718 
5719   CSEMap.InsertNode(N, IP);
5720   InsertNode(N);
5721 
5722   SDValue V(N, 0);
5723   NewSDValueDbgMsg(V, "Creating new node: ", this);
5724   return V;
5725 }
5726 
5727 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
5728                               SDValue N1, SDValue N2) {
5729   SDNodeFlags Flags;
5730   if (Inserter)
5731     Flags = Inserter->getFlags();
5732   return getNode(Opcode, DL, VT, N1, N2, Flags);
5733 }
5734 
5735 void SelectionDAG::canonicalizeCommutativeBinop(unsigned Opcode, SDValue &N1,
5736                                                 SDValue &N2) const {
5737   if (!TLI->isCommutativeBinOp(Opcode))
5738     return;
5739 
5740   // Canonicalize:
5741   //   binop(const, nonconst) -> binop(nonconst, const)
5742   bool IsN1C = isConstantIntBuildVectorOrConstantInt(N1);
5743   bool IsN2C = isConstantIntBuildVectorOrConstantInt(N2);
5744   bool IsN1CFP = isConstantFPBuildVectorOrConstantFP(N1);
5745   bool IsN2CFP = isConstantFPBuildVectorOrConstantFP(N2);
5746   if ((IsN1C && !IsN2C) || (IsN1CFP && !IsN2CFP))
5747     std::swap(N1, N2);
5748 
5749   // Canonicalize:
5750   //  binop(splat(x), step_vector) -> binop(step_vector, splat(x))
5751   else if (N1.getOpcode() == ISD::SPLAT_VECTOR &&
5752            N2.getOpcode() == ISD::STEP_VECTOR)
5753     std::swap(N1, N2);
5754 }
5755 
5756 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
5757                               SDValue N1, SDValue N2, const SDNodeFlags Flags) {
5758   assert(N1.getOpcode() != ISD::DELETED_NODE &&
5759          N2.getOpcode() != ISD::DELETED_NODE &&
5760          "Operand is DELETED_NODE!");
5761 
5762   canonicalizeCommutativeBinop(Opcode, N1, N2);
5763 
5764   auto *N1C = dyn_cast<ConstantSDNode>(N1);
5765   auto *N2C = dyn_cast<ConstantSDNode>(N2);
5766 
5767   // Don't allow undefs in vector splats - we might be returning N2 when folding
5768   // to zero etc.
5769   ConstantSDNode *N2CV =
5770       isConstOrConstSplat(N2, /*AllowUndefs*/ false, /*AllowTruncation*/ true);
5771 
5772   switch (Opcode) {
5773   default: break;
5774   case ISD::TokenFactor:
5775     assert(VT == MVT::Other && N1.getValueType() == MVT::Other &&
5776            N2.getValueType() == MVT::Other && "Invalid token factor!");
5777     // Fold trivial token factors.
5778     if (N1.getOpcode() == ISD::EntryToken) return N2;
5779     if (N2.getOpcode() == ISD::EntryToken) return N1;
5780     if (N1 == N2) return N1;
5781     break;
5782   case ISD::BUILD_VECTOR: {
5783     // Attempt to simplify BUILD_VECTOR.
5784     SDValue Ops[] = {N1, N2};
5785     if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
5786       return V;
5787     break;
5788   }
5789   case ISD::CONCAT_VECTORS: {
5790     SDValue Ops[] = {N1, N2};
5791     if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this))
5792       return V;
5793     break;
5794   }
5795   case ISD::AND:
5796     assert(VT.isInteger() && "This operator does not apply to FP types!");
5797     assert(N1.getValueType() == N2.getValueType() &&
5798            N1.getValueType() == VT && "Binary operator types must match!");
5799     // (X & 0) -> 0.  This commonly occurs when legalizing i64 values, so it's
5800     // worth handling here.
5801     if (N2CV && N2CV->isZero())
5802       return N2;
5803     if (N2CV && N2CV->isAllOnes()) // X & -1 -> X
5804       return N1;
5805     break;
5806   case ISD::OR:
5807   case ISD::XOR:
5808   case ISD::ADD:
5809   case ISD::SUB:
5810     assert(VT.isInteger() && "This operator does not apply to FP types!");
5811     assert(N1.getValueType() == N2.getValueType() &&
5812            N1.getValueType() == VT && "Binary operator types must match!");
5813     // (X ^|+- 0) -> X.  This commonly occurs when legalizing i64 values, so
5814     // it's worth handling here.
5815     if (N2CV && N2CV->isZero())
5816       return N1;
5817     if ((Opcode == ISD::ADD || Opcode == ISD::SUB) && VT.isVector() &&
5818         VT.getVectorElementType() == MVT::i1)
5819       return getNode(ISD::XOR, DL, VT, N1, N2);
5820     break;
5821   case ISD::MUL:
5822     assert(VT.isInteger() && "This operator does not apply to FP types!");
5823     assert(N1.getValueType() == N2.getValueType() &&
5824            N1.getValueType() == VT && "Binary operator types must match!");
5825     if (VT.isVector() && VT.getVectorElementType() == MVT::i1)
5826       return getNode(ISD::AND, DL, VT, N1, N2);
5827     if (N2C && (N1.getOpcode() == ISD::VSCALE) && Flags.hasNoSignedWrap()) {
5828       const APInt &MulImm = N1->getConstantOperandAPInt(0);
5829       const APInt &N2CImm = N2C->getAPIntValue();
5830       return getVScale(DL, VT, MulImm * N2CImm);
5831     }
5832     break;
5833   case ISD::UDIV:
5834   case ISD::UREM:
5835   case ISD::MULHU:
5836   case ISD::MULHS:
5837   case ISD::SDIV:
5838   case ISD::SREM:
5839   case ISD::SADDSAT:
5840   case ISD::SSUBSAT:
5841   case ISD::UADDSAT:
5842   case ISD::USUBSAT:
5843     assert(VT.isInteger() && "This operator does not apply to FP types!");
5844     assert(N1.getValueType() == N2.getValueType() &&
5845            N1.getValueType() == VT && "Binary operator types must match!");
5846     if (VT.isVector() && VT.getVectorElementType() == MVT::i1) {
5847       // fold (add_sat x, y) -> (or x, y) for bool types.
5848       if (Opcode == ISD::SADDSAT || Opcode == ISD::UADDSAT)
5849         return getNode(ISD::OR, DL, VT, N1, N2);
5850       // fold (sub_sat x, y) -> (and x, ~y) for bool types.
5851       if (Opcode == ISD::SSUBSAT || Opcode == ISD::USUBSAT)
5852         return getNode(ISD::AND, DL, VT, N1, getNOT(DL, N2, VT));
5853     }
5854     break;
5855   case ISD::SMIN:
5856   case ISD::UMAX:
5857     assert(VT.isInteger() && "This operator does not apply to FP types!");
5858     assert(N1.getValueType() == N2.getValueType() &&
5859            N1.getValueType() == VT && "Binary operator types must match!");
5860     if (VT.isVector() && VT.getVectorElementType() == MVT::i1)
5861       return getNode(ISD::OR, DL, VT, N1, N2);
5862     break;
5863   case ISD::SMAX:
5864   case ISD::UMIN:
5865     assert(VT.isInteger() && "This operator does not apply to FP types!");
5866     assert(N1.getValueType() == N2.getValueType() &&
5867            N1.getValueType() == VT && "Binary operator types must match!");
5868     if (VT.isVector() && VT.getVectorElementType() == MVT::i1)
5869       return getNode(ISD::AND, DL, VT, N1, N2);
5870     break;
5871   case ISD::FADD:
5872   case ISD::FSUB:
5873   case ISD::FMUL:
5874   case ISD::FDIV:
5875   case ISD::FREM:
5876     assert(VT.isFloatingPoint() && "This operator only applies to FP types!");
5877     assert(N1.getValueType() == N2.getValueType() &&
5878            N1.getValueType() == VT && "Binary operator types must match!");
5879     if (SDValue V = simplifyFPBinop(Opcode, N1, N2, Flags))
5880       return V;
5881     break;
5882   case ISD::FCOPYSIGN:   // N1 and result must match.  N1/N2 need not match.
5883     assert(N1.getValueType() == VT &&
5884            N1.getValueType().isFloatingPoint() &&
5885            N2.getValueType().isFloatingPoint() &&
5886            "Invalid FCOPYSIGN!");
5887     break;
5888   case ISD::SHL:
5889     if (N2C && (N1.getOpcode() == ISD::VSCALE) && Flags.hasNoSignedWrap()) {
5890       const APInt &MulImm = N1->getConstantOperandAPInt(0);
5891       const APInt &ShiftImm = N2C->getAPIntValue();
5892       return getVScale(DL, VT, MulImm << ShiftImm);
5893     }
5894     LLVM_FALLTHROUGH;
5895   case ISD::SRA:
5896   case ISD::SRL:
5897     if (SDValue V = simplifyShift(N1, N2))
5898       return V;
5899     LLVM_FALLTHROUGH;
5900   case ISD::ROTL:
5901   case ISD::ROTR:
5902     assert(VT == N1.getValueType() &&
5903            "Shift operators return type must be the same as their first arg");
5904     assert(VT.isInteger() && N2.getValueType().isInteger() &&
5905            "Shifts only work on integers");
5906     assert((!VT.isVector() || VT == N2.getValueType()) &&
5907            "Vector shift amounts must be in the same as their first arg");
5908     // Verify that the shift amount VT is big enough to hold valid shift
5909     // amounts.  This catches things like trying to shift an i1024 value by an
5910     // i8, which is easy to fall into in generic code that uses
5911     // TLI.getShiftAmount().
5912     assert(N2.getValueType().getScalarSizeInBits() >=
5913                Log2_32_Ceil(VT.getScalarSizeInBits()) &&
5914            "Invalid use of small shift amount with oversized value!");
5915 
5916     // Always fold shifts of i1 values so the code generator doesn't need to
5917     // handle them.  Since we know the size of the shift has to be less than the
5918     // size of the value, the shift/rotate count is guaranteed to be zero.
5919     if (VT == MVT::i1)
5920       return N1;
5921     if (N2CV && N2CV->isZero())
5922       return N1;
5923     break;
5924   case ISD::FP_ROUND:
5925     assert(VT.isFloatingPoint() &&
5926            N1.getValueType().isFloatingPoint() &&
5927            VT.bitsLE(N1.getValueType()) &&
5928            N2C && (N2C->getZExtValue() == 0 || N2C->getZExtValue() == 1) &&
5929            "Invalid FP_ROUND!");
5930     if (N1.getValueType() == VT) return N1;  // noop conversion.
5931     break;
5932   case ISD::AssertSext:
5933   case ISD::AssertZext: {
5934     EVT EVT = cast<VTSDNode>(N2)->getVT();
5935     assert(VT == N1.getValueType() && "Not an inreg extend!");
5936     assert(VT.isInteger() && EVT.isInteger() &&
5937            "Cannot *_EXTEND_INREG FP types");
5938     assert(!EVT.isVector() &&
5939            "AssertSExt/AssertZExt type should be the vector element type "
5940            "rather than the vector type!");
5941     assert(EVT.bitsLE(VT.getScalarType()) && "Not extending!");
5942     if (VT.getScalarType() == EVT) return N1; // noop assertion.
5943     break;
5944   }
5945   case ISD::SIGN_EXTEND_INREG: {
5946     EVT EVT = cast<VTSDNode>(N2)->getVT();
5947     assert(VT == N1.getValueType() && "Not an inreg extend!");
5948     assert(VT.isInteger() && EVT.isInteger() &&
5949            "Cannot *_EXTEND_INREG FP types");
5950     assert(EVT.isVector() == VT.isVector() &&
5951            "SIGN_EXTEND_INREG type should be vector iff the operand "
5952            "type is vector!");
5953     assert((!EVT.isVector() ||
5954             EVT.getVectorElementCount() == VT.getVectorElementCount()) &&
5955            "Vector element counts must match in SIGN_EXTEND_INREG");
5956     assert(EVT.bitsLE(VT) && "Not extending!");
5957     if (EVT == VT) return N1;  // Not actually extending
5958 
5959     auto SignExtendInReg = [&](APInt Val, llvm::EVT ConstantVT) {
5960       unsigned FromBits = EVT.getScalarSizeInBits();
5961       Val <<= Val.getBitWidth() - FromBits;
5962       Val.ashrInPlace(Val.getBitWidth() - FromBits);
5963       return getConstant(Val, DL, ConstantVT);
5964     };
5965 
5966     if (N1C) {
5967       const APInt &Val = N1C->getAPIntValue();
5968       return SignExtendInReg(Val, VT);
5969     }
5970 
5971     if (ISD::isBuildVectorOfConstantSDNodes(N1.getNode())) {
5972       SmallVector<SDValue, 8> Ops;
5973       llvm::EVT OpVT = N1.getOperand(0).getValueType();
5974       for (int i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
5975         SDValue Op = N1.getOperand(i);
5976         if (Op.isUndef()) {
5977           Ops.push_back(getUNDEF(OpVT));
5978           continue;
5979         }
5980         ConstantSDNode *C = cast<ConstantSDNode>(Op);
5981         APInt Val = C->getAPIntValue();
5982         Ops.push_back(SignExtendInReg(Val, OpVT));
5983       }
5984       return getBuildVector(VT, DL, Ops);
5985     }
5986     break;
5987   }
5988   case ISD::FP_TO_SINT_SAT:
5989   case ISD::FP_TO_UINT_SAT: {
5990     assert(VT.isInteger() && cast<VTSDNode>(N2)->getVT().isInteger() &&
5991            N1.getValueType().isFloatingPoint() && "Invalid FP_TO_*INT_SAT");
5992     assert(N1.getValueType().isVector() == VT.isVector() &&
5993            "FP_TO_*INT_SAT type should be vector iff the operand type is "
5994            "vector!");
5995     assert((!VT.isVector() || VT.getVectorNumElements() ==
5996                                   N1.getValueType().getVectorNumElements()) &&
5997            "Vector element counts must match in FP_TO_*INT_SAT");
5998     assert(!cast<VTSDNode>(N2)->getVT().isVector() &&
5999            "Type to saturate to must be a scalar.");
6000     assert(cast<VTSDNode>(N2)->getVT().bitsLE(VT.getScalarType()) &&
6001            "Not extending!");
6002     break;
6003   }
6004   case ISD::EXTRACT_VECTOR_ELT:
6005     assert(VT.getSizeInBits() >= N1.getValueType().getScalarSizeInBits() &&
6006            "The result of EXTRACT_VECTOR_ELT must be at least as wide as the \
6007              element type of the vector.");
6008 
6009     // Extract from an undefined value or using an undefined index is undefined.
6010     if (N1.isUndef() || N2.isUndef())
6011       return getUNDEF(VT);
6012 
6013     // EXTRACT_VECTOR_ELT of out-of-bounds element is an UNDEF for fixed length
6014     // vectors. For scalable vectors we will provide appropriate support for
6015     // dealing with arbitrary indices.
6016     if (N2C && N1.getValueType().isFixedLengthVector() &&
6017         N2C->getAPIntValue().uge(N1.getValueType().getVectorNumElements()))
6018       return getUNDEF(VT);
6019 
6020     // EXTRACT_VECTOR_ELT of CONCAT_VECTORS is often formed while lowering is
6021     // expanding copies of large vectors from registers. This only works for
6022     // fixed length vectors, since we need to know the exact number of
6023     // elements.
6024     if (N2C && N1.getOperand(0).getValueType().isFixedLengthVector() &&
6025         N1.getOpcode() == ISD::CONCAT_VECTORS && N1.getNumOperands() > 0) {
6026       unsigned Factor =
6027         N1.getOperand(0).getValueType().getVectorNumElements();
6028       return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
6029                      N1.getOperand(N2C->getZExtValue() / Factor),
6030                      getVectorIdxConstant(N2C->getZExtValue() % Factor, DL));
6031     }
6032 
6033     // EXTRACT_VECTOR_ELT of BUILD_VECTOR or SPLAT_VECTOR is often formed while
6034     // lowering is expanding large vector constants.
6035     if (N2C && (N1.getOpcode() == ISD::BUILD_VECTOR ||
6036                 N1.getOpcode() == ISD::SPLAT_VECTOR)) {
6037       assert((N1.getOpcode() != ISD::BUILD_VECTOR ||
6038               N1.getValueType().isFixedLengthVector()) &&
6039              "BUILD_VECTOR used for scalable vectors");
6040       unsigned Index =
6041           N1.getOpcode() == ISD::BUILD_VECTOR ? N2C->getZExtValue() : 0;
6042       SDValue Elt = N1.getOperand(Index);
6043 
6044       if (VT != Elt.getValueType())
6045         // If the vector element type is not legal, the BUILD_VECTOR operands
6046         // are promoted and implicitly truncated, and the result implicitly
6047         // extended. Make that explicit here.
6048         Elt = getAnyExtOrTrunc(Elt, DL, VT);
6049 
6050       return Elt;
6051     }
6052 
6053     // EXTRACT_VECTOR_ELT of INSERT_VECTOR_ELT is often formed when vector
6054     // operations are lowered to scalars.
6055     if (N1.getOpcode() == ISD::INSERT_VECTOR_ELT) {
6056       // If the indices are the same, return the inserted element else
6057       // if the indices are known different, extract the element from
6058       // the original vector.
6059       SDValue N1Op2 = N1.getOperand(2);
6060       ConstantSDNode *N1Op2C = dyn_cast<ConstantSDNode>(N1Op2);
6061 
6062       if (N1Op2C && N2C) {
6063         if (N1Op2C->getZExtValue() == N2C->getZExtValue()) {
6064           if (VT == N1.getOperand(1).getValueType())
6065             return N1.getOperand(1);
6066           return getSExtOrTrunc(N1.getOperand(1), DL, VT);
6067         }
6068         return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0), N2);
6069       }
6070     }
6071 
6072     // EXTRACT_VECTOR_ELT of v1iX EXTRACT_SUBVECTOR could be formed
6073     // when vector types are scalarized and v1iX is legal.
6074     // vextract (v1iX extract_subvector(vNiX, Idx)) -> vextract(vNiX,Idx).
6075     // Here we are completely ignoring the extract element index (N2),
6076     // which is fine for fixed width vectors, since any index other than 0
6077     // is undefined anyway. However, this cannot be ignored for scalable
6078     // vectors - in theory we could support this, but we don't want to do this
6079     // without a profitability check.
6080     if (N1.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
6081         N1.getValueType().isFixedLengthVector() &&
6082         N1.getValueType().getVectorNumElements() == 1) {
6083       return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0),
6084                      N1.getOperand(1));
6085     }
6086     break;
6087   case ISD::EXTRACT_ELEMENT:
6088     assert(N2C && (unsigned)N2C->getZExtValue() < 2 && "Bad EXTRACT_ELEMENT!");
6089     assert(!N1.getValueType().isVector() && !VT.isVector() &&
6090            (N1.getValueType().isInteger() == VT.isInteger()) &&
6091            N1.getValueType() != VT &&
6092            "Wrong types for EXTRACT_ELEMENT!");
6093 
6094     // EXTRACT_ELEMENT of BUILD_PAIR is often formed while legalize is expanding
6095     // 64-bit integers into 32-bit parts.  Instead of building the extract of
6096     // the BUILD_PAIR, only to have legalize rip it apart, just do it now.
6097     if (N1.getOpcode() == ISD::BUILD_PAIR)
6098       return N1.getOperand(N2C->getZExtValue());
6099 
6100     // EXTRACT_ELEMENT of a constant int is also very common.
6101     if (N1C) {
6102       unsigned ElementSize = VT.getSizeInBits();
6103       unsigned Shift = ElementSize * N2C->getZExtValue();
6104       const APInt &Val = N1C->getAPIntValue();
6105       return getConstant(Val.extractBits(ElementSize, Shift), DL, VT);
6106     }
6107     break;
6108   case ISD::EXTRACT_SUBVECTOR: {
6109     EVT N1VT = N1.getValueType();
6110     assert(VT.isVector() && N1VT.isVector() &&
6111            "Extract subvector VTs must be vectors!");
6112     assert(VT.getVectorElementType() == N1VT.getVectorElementType() &&
6113            "Extract subvector VTs must have the same element type!");
6114     assert((VT.isFixedLengthVector() || N1VT.isScalableVector()) &&
6115            "Cannot extract a scalable vector from a fixed length vector!");
6116     assert((VT.isScalableVector() != N1VT.isScalableVector() ||
6117             VT.getVectorMinNumElements() <= N1VT.getVectorMinNumElements()) &&
6118            "Extract subvector must be from larger vector to smaller vector!");
6119     assert(N2C && "Extract subvector index must be a constant");
6120     assert((VT.isScalableVector() != N1VT.isScalableVector() ||
6121             (VT.getVectorMinNumElements() + N2C->getZExtValue()) <=
6122                 N1VT.getVectorMinNumElements()) &&
6123            "Extract subvector overflow!");
6124     assert(N2C->getAPIntValue().getBitWidth() ==
6125                TLI->getVectorIdxTy(getDataLayout()).getFixedSizeInBits() &&
6126            "Constant index for EXTRACT_SUBVECTOR has an invalid size");
6127 
6128     // Trivial extraction.
6129     if (VT == N1VT)
6130       return N1;
6131 
6132     // EXTRACT_SUBVECTOR of an UNDEF is an UNDEF.
6133     if (N1.isUndef())
6134       return getUNDEF(VT);
6135 
6136     // EXTRACT_SUBVECTOR of CONCAT_VECTOR can be simplified if the pieces of
6137     // the concat have the same type as the extract.
6138     if (N1.getOpcode() == ISD::CONCAT_VECTORS && N1.getNumOperands() > 0 &&
6139         VT == N1.getOperand(0).getValueType()) {
6140       unsigned Factor = VT.getVectorMinNumElements();
6141       return N1.getOperand(N2C->getZExtValue() / Factor);
6142     }
6143 
6144     // EXTRACT_SUBVECTOR of INSERT_SUBVECTOR is often created
6145     // during shuffle legalization.
6146     if (N1.getOpcode() == ISD::INSERT_SUBVECTOR && N2 == N1.getOperand(2) &&
6147         VT == N1.getOperand(1).getValueType())
6148       return N1.getOperand(1);
6149     break;
6150   }
6151   }
6152 
6153   // Perform trivial constant folding.
6154   if (SDValue SV = FoldConstantArithmetic(Opcode, DL, VT, {N1, N2}))
6155     return SV;
6156 
6157   // Canonicalize an UNDEF to the RHS, even over a constant.
6158   if (N1.isUndef()) {
6159     if (TLI->isCommutativeBinOp(Opcode)) {
6160       std::swap(N1, N2);
6161     } else {
6162       switch (Opcode) {
6163       case ISD::SIGN_EXTEND_INREG:
6164       case ISD::SUB:
6165         return getUNDEF(VT);     // fold op(undef, arg2) -> undef
6166       case ISD::UDIV:
6167       case ISD::SDIV:
6168       case ISD::UREM:
6169       case ISD::SREM:
6170       case ISD::SSUBSAT:
6171       case ISD::USUBSAT:
6172         return getConstant(0, DL, VT);    // fold op(undef, arg2) -> 0
6173       }
6174     }
6175   }
6176 
6177   // Fold a bunch of operators when the RHS is undef.
6178   if (N2.isUndef()) {
6179     switch (Opcode) {
6180     case ISD::XOR:
6181       if (N1.isUndef())
6182         // Handle undef ^ undef -> 0 special case. This is a common
6183         // idiom (misuse).
6184         return getConstant(0, DL, VT);
6185       LLVM_FALLTHROUGH;
6186     case ISD::ADD:
6187     case ISD::SUB:
6188     case ISD::UDIV:
6189     case ISD::SDIV:
6190     case ISD::UREM:
6191     case ISD::SREM:
6192       return getUNDEF(VT);       // fold op(arg1, undef) -> undef
6193     case ISD::MUL:
6194     case ISD::AND:
6195     case ISD::SSUBSAT:
6196     case ISD::USUBSAT:
6197       return getConstant(0, DL, VT);  // fold op(arg1, undef) -> 0
6198     case ISD::OR:
6199     case ISD::SADDSAT:
6200     case ISD::UADDSAT:
6201       return getAllOnesConstant(DL, VT);
6202     }
6203   }
6204 
6205   // Memoize this node if possible.
6206   SDNode *N;
6207   SDVTList VTs = getVTList(VT);
6208   SDValue Ops[] = {N1, N2};
6209   if (VT != MVT::Glue) {
6210     FoldingSetNodeID ID;
6211     AddNodeIDNode(ID, Opcode, VTs, Ops);
6212     void *IP = nullptr;
6213     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
6214       E->intersectFlagsWith(Flags);
6215       return SDValue(E, 0);
6216     }
6217 
6218     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
6219     N->setFlags(Flags);
6220     createOperands(N, Ops);
6221     CSEMap.InsertNode(N, IP);
6222   } else {
6223     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
6224     createOperands(N, Ops);
6225   }
6226 
6227   InsertNode(N);
6228   SDValue V = SDValue(N, 0);
6229   NewSDValueDbgMsg(V, "Creating new node: ", this);
6230   return V;
6231 }
6232 
6233 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
6234                               SDValue N1, SDValue N2, SDValue N3) {
6235   SDNodeFlags Flags;
6236   if (Inserter)
6237     Flags = Inserter->getFlags();
6238   return getNode(Opcode, DL, VT, N1, N2, N3, Flags);
6239 }
6240 
6241 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
6242                               SDValue N1, SDValue N2, SDValue N3,
6243                               const SDNodeFlags Flags) {
6244   assert(N1.getOpcode() != ISD::DELETED_NODE &&
6245          N2.getOpcode() != ISD::DELETED_NODE &&
6246          N3.getOpcode() != ISD::DELETED_NODE &&
6247          "Operand is DELETED_NODE!");
6248   // Perform various simplifications.
6249   switch (Opcode) {
6250   case ISD::FMA: {
6251     assert(VT.isFloatingPoint() && "This operator only applies to FP types!");
6252     assert(N1.getValueType() == VT && N2.getValueType() == VT &&
6253            N3.getValueType() == VT && "FMA types must match!");
6254     ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6255     ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2);
6256     ConstantFPSDNode *N3CFP = dyn_cast<ConstantFPSDNode>(N3);
6257     if (N1CFP && N2CFP && N3CFP) {
6258       APFloat  V1 = N1CFP->getValueAPF();
6259       const APFloat &V2 = N2CFP->getValueAPF();
6260       const APFloat &V3 = N3CFP->getValueAPF();
6261       V1.fusedMultiplyAdd(V2, V3, APFloat::rmNearestTiesToEven);
6262       return getConstantFP(V1, DL, VT);
6263     }
6264     break;
6265   }
6266   case ISD::BUILD_VECTOR: {
6267     // Attempt to simplify BUILD_VECTOR.
6268     SDValue Ops[] = {N1, N2, N3};
6269     if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
6270       return V;
6271     break;
6272   }
6273   case ISD::CONCAT_VECTORS: {
6274     SDValue Ops[] = {N1, N2, N3};
6275     if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this))
6276       return V;
6277     break;
6278   }
6279   case ISD::SETCC: {
6280     assert(VT.isInteger() && "SETCC result type must be an integer!");
6281     assert(N1.getValueType() == N2.getValueType() &&
6282            "SETCC operands must have the same type!");
6283     assert(VT.isVector() == N1.getValueType().isVector() &&
6284            "SETCC type should be vector iff the operand type is vector!");
6285     assert((!VT.isVector() || VT.getVectorElementCount() ==
6286                                   N1.getValueType().getVectorElementCount()) &&
6287            "SETCC vector element counts must match!");
6288     // Use FoldSetCC to simplify SETCC's.
6289     if (SDValue V = FoldSetCC(VT, N1, N2, cast<CondCodeSDNode>(N3)->get(), DL))
6290       return V;
6291     // Vector constant folding.
6292     SDValue Ops[] = {N1, N2, N3};
6293     if (SDValue V = FoldConstantArithmetic(Opcode, DL, VT, Ops)) {
6294       NewSDValueDbgMsg(V, "New node vector constant folding: ", this);
6295       return V;
6296     }
6297     break;
6298   }
6299   case ISD::SELECT:
6300   case ISD::VSELECT:
6301     if (SDValue V = simplifySelect(N1, N2, N3))
6302       return V;
6303     break;
6304   case ISD::VECTOR_SHUFFLE:
6305     llvm_unreachable("should use getVectorShuffle constructor!");
6306   case ISD::VECTOR_SPLICE: {
6307     if (cast<ConstantSDNode>(N3)->isNullValue())
6308       return N1;
6309     break;
6310   }
6311   case ISD::INSERT_VECTOR_ELT: {
6312     ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3);
6313     // INSERT_VECTOR_ELT into out-of-bounds element is an UNDEF, except
6314     // for scalable vectors where we will generate appropriate code to
6315     // deal with out-of-bounds cases correctly.
6316     if (N3C && N1.getValueType().isFixedLengthVector() &&
6317         N3C->getZExtValue() >= N1.getValueType().getVectorNumElements())
6318       return getUNDEF(VT);
6319 
6320     // Undefined index can be assumed out-of-bounds, so that's UNDEF too.
6321     if (N3.isUndef())
6322       return getUNDEF(VT);
6323 
6324     // If the inserted element is an UNDEF, just use the input vector.
6325     if (N2.isUndef())
6326       return N1;
6327 
6328     break;
6329   }
6330   case ISD::INSERT_SUBVECTOR: {
6331     // Inserting undef into undef is still undef.
6332     if (N1.isUndef() && N2.isUndef())
6333       return getUNDEF(VT);
6334 
6335     EVT N2VT = N2.getValueType();
6336     assert(VT == N1.getValueType() &&
6337            "Dest and insert subvector source types must match!");
6338     assert(VT.isVector() && N2VT.isVector() &&
6339            "Insert subvector VTs must be vectors!");
6340     assert((VT.isScalableVector() || N2VT.isFixedLengthVector()) &&
6341            "Cannot insert a scalable vector into a fixed length vector!");
6342     assert((VT.isScalableVector() != N2VT.isScalableVector() ||
6343             VT.getVectorMinNumElements() >= N2VT.getVectorMinNumElements()) &&
6344            "Insert subvector must be from smaller vector to larger vector!");
6345     assert(isa<ConstantSDNode>(N3) &&
6346            "Insert subvector index must be constant");
6347     assert((VT.isScalableVector() != N2VT.isScalableVector() ||
6348             (N2VT.getVectorMinNumElements() +
6349              cast<ConstantSDNode>(N3)->getZExtValue()) <=
6350                 VT.getVectorMinNumElements()) &&
6351            "Insert subvector overflow!");
6352     assert(cast<ConstantSDNode>(N3)->getAPIntValue().getBitWidth() ==
6353                TLI->getVectorIdxTy(getDataLayout()).getFixedSizeInBits() &&
6354            "Constant index for INSERT_SUBVECTOR has an invalid size");
6355 
6356     // Trivial insertion.
6357     if (VT == N2VT)
6358       return N2;
6359 
6360     // If this is an insert of an extracted vector into an undef vector, we
6361     // can just use the input to the extract.
6362     if (N1.isUndef() && N2.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
6363         N2.getOperand(1) == N3 && N2.getOperand(0).getValueType() == VT)
6364       return N2.getOperand(0);
6365     break;
6366   }
6367   case ISD::BITCAST:
6368     // Fold bit_convert nodes from a type to themselves.
6369     if (N1.getValueType() == VT)
6370       return N1;
6371     break;
6372   }
6373 
6374   // Memoize node if it doesn't produce a flag.
6375   SDNode *N;
6376   SDVTList VTs = getVTList(VT);
6377   SDValue Ops[] = {N1, N2, N3};
6378   if (VT != MVT::Glue) {
6379     FoldingSetNodeID ID;
6380     AddNodeIDNode(ID, Opcode, VTs, Ops);
6381     void *IP = nullptr;
6382     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
6383       E->intersectFlagsWith(Flags);
6384       return SDValue(E, 0);
6385     }
6386 
6387     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
6388     N->setFlags(Flags);
6389     createOperands(N, Ops);
6390     CSEMap.InsertNode(N, IP);
6391   } else {
6392     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
6393     createOperands(N, Ops);
6394   }
6395 
6396   InsertNode(N);
6397   SDValue V = SDValue(N, 0);
6398   NewSDValueDbgMsg(V, "Creating new node: ", this);
6399   return V;
6400 }
6401 
6402 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
6403                               SDValue N1, SDValue N2, SDValue N3, SDValue N4) {
6404   SDValue Ops[] = { N1, N2, N3, N4 };
6405   return getNode(Opcode, DL, VT, Ops);
6406 }
6407 
6408 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
6409                               SDValue N1, SDValue N2, SDValue N3, SDValue N4,
6410                               SDValue N5) {
6411   SDValue Ops[] = { N1, N2, N3, N4, N5 };
6412   return getNode(Opcode, DL, VT, Ops);
6413 }
6414 
6415 /// getStackArgumentTokenFactor - Compute a TokenFactor to force all
6416 /// the incoming stack arguments to be loaded from the stack.
6417 SDValue SelectionDAG::getStackArgumentTokenFactor(SDValue Chain) {
6418   SmallVector<SDValue, 8> ArgChains;
6419 
6420   // Include the original chain at the beginning of the list. When this is
6421   // used by target LowerCall hooks, this helps legalize find the
6422   // CALLSEQ_BEGIN node.
6423   ArgChains.push_back(Chain);
6424 
6425   // Add a chain value for each stack argument.
6426   for (SDNode *U : getEntryNode().getNode()->uses())
6427     if (LoadSDNode *L = dyn_cast<LoadSDNode>(U))
6428       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
6429         if (FI->getIndex() < 0)
6430           ArgChains.push_back(SDValue(L, 1));
6431 
6432   // Build a tokenfactor for all the chains.
6433   return getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains);
6434 }
6435 
6436 /// getMemsetValue - Vectorized representation of the memset value
6437 /// operand.
6438 static SDValue getMemsetValue(SDValue Value, EVT VT, SelectionDAG &DAG,
6439                               const SDLoc &dl) {
6440   assert(!Value.isUndef());
6441 
6442   unsigned NumBits = VT.getScalarSizeInBits();
6443   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
6444     assert(C->getAPIntValue().getBitWidth() == 8);
6445     APInt Val = APInt::getSplat(NumBits, C->getAPIntValue());
6446     if (VT.isInteger()) {
6447       bool IsOpaque = VT.getSizeInBits() > 64 ||
6448           !DAG.getTargetLoweringInfo().isLegalStoreImmediate(C->getSExtValue());
6449       return DAG.getConstant(Val, dl, VT, false, IsOpaque);
6450     }
6451     return DAG.getConstantFP(APFloat(DAG.EVTToAPFloatSemantics(VT), Val), dl,
6452                              VT);
6453   }
6454 
6455   assert(Value.getValueType() == MVT::i8 && "memset with non-byte fill value?");
6456   EVT IntVT = VT.getScalarType();
6457   if (!IntVT.isInteger())
6458     IntVT = EVT::getIntegerVT(*DAG.getContext(), IntVT.getSizeInBits());
6459 
6460   Value = DAG.getNode(ISD::ZERO_EXTEND, dl, IntVT, Value);
6461   if (NumBits > 8) {
6462     // Use a multiplication with 0x010101... to extend the input to the
6463     // required length.
6464     APInt Magic = APInt::getSplat(NumBits, APInt(8, 0x01));
6465     Value = DAG.getNode(ISD::MUL, dl, IntVT, Value,
6466                         DAG.getConstant(Magic, dl, IntVT));
6467   }
6468 
6469   if (VT != Value.getValueType() && !VT.isInteger())
6470     Value = DAG.getBitcast(VT.getScalarType(), Value);
6471   if (VT != Value.getValueType())
6472     Value = DAG.getSplatBuildVector(VT, dl, Value);
6473 
6474   return Value;
6475 }
6476 
6477 /// getMemsetStringVal - Similar to getMemsetValue. Except this is only
6478 /// used when a memcpy is turned into a memset when the source is a constant
6479 /// string ptr.
6480 static SDValue getMemsetStringVal(EVT VT, const SDLoc &dl, SelectionDAG &DAG,
6481                                   const TargetLowering &TLI,
6482                                   const ConstantDataArraySlice &Slice) {
6483   // Handle vector with all elements zero.
6484   if (Slice.Array == nullptr) {
6485     if (VT.isInteger())
6486       return DAG.getConstant(0, dl, VT);
6487     if (VT == MVT::f32 || VT == MVT::f64 || VT == MVT::f128)
6488       return DAG.getConstantFP(0.0, dl, VT);
6489     if (VT.isVector()) {
6490       unsigned NumElts = VT.getVectorNumElements();
6491       MVT EltVT = (VT.getVectorElementType() == MVT::f32) ? MVT::i32 : MVT::i64;
6492       return DAG.getNode(ISD::BITCAST, dl, VT,
6493                          DAG.getConstant(0, dl,
6494                                          EVT::getVectorVT(*DAG.getContext(),
6495                                                           EltVT, NumElts)));
6496     }
6497     llvm_unreachable("Expected type!");
6498   }
6499 
6500   assert(!VT.isVector() && "Can't handle vector type here!");
6501   unsigned NumVTBits = VT.getSizeInBits();
6502   unsigned NumVTBytes = NumVTBits / 8;
6503   unsigned NumBytes = std::min(NumVTBytes, unsigned(Slice.Length));
6504 
6505   APInt Val(NumVTBits, 0);
6506   if (DAG.getDataLayout().isLittleEndian()) {
6507     for (unsigned i = 0; i != NumBytes; ++i)
6508       Val |= (uint64_t)(unsigned char)Slice[i] << i*8;
6509   } else {
6510     for (unsigned i = 0; i != NumBytes; ++i)
6511       Val |= (uint64_t)(unsigned char)Slice[i] << (NumVTBytes-i-1)*8;
6512   }
6513 
6514   // If the "cost" of materializing the integer immediate is less than the cost
6515   // of a load, then it is cost effective to turn the load into the immediate.
6516   Type *Ty = VT.getTypeForEVT(*DAG.getContext());
6517   if (TLI.shouldConvertConstantLoadToIntImm(Val, Ty))
6518     return DAG.getConstant(Val, dl, VT);
6519   return SDValue();
6520 }
6521 
6522 SDValue SelectionDAG::getMemBasePlusOffset(SDValue Base, TypeSize Offset,
6523                                            const SDLoc &DL,
6524                                            const SDNodeFlags Flags) {
6525   EVT VT = Base.getValueType();
6526   SDValue Index;
6527 
6528   if (Offset.isScalable())
6529     Index = getVScale(DL, Base.getValueType(),
6530                       APInt(Base.getValueSizeInBits().getFixedSize(),
6531                             Offset.getKnownMinSize()));
6532   else
6533     Index = getConstant(Offset.getFixedSize(), DL, VT);
6534 
6535   return getMemBasePlusOffset(Base, Index, DL, Flags);
6536 }
6537 
6538 SDValue SelectionDAG::getMemBasePlusOffset(SDValue Ptr, SDValue Offset,
6539                                            const SDLoc &DL,
6540                                            const SDNodeFlags Flags) {
6541   assert(Offset.getValueType().isInteger());
6542   EVT BasePtrVT = Ptr.getValueType();
6543   return getNode(ISD::ADD, DL, BasePtrVT, Ptr, Offset, Flags);
6544 }
6545 
6546 /// Returns true if memcpy source is constant data.
6547 static bool isMemSrcFromConstant(SDValue Src, ConstantDataArraySlice &Slice) {
6548   uint64_t SrcDelta = 0;
6549   GlobalAddressSDNode *G = nullptr;
6550   if (Src.getOpcode() == ISD::GlobalAddress)
6551     G = cast<GlobalAddressSDNode>(Src);
6552   else if (Src.getOpcode() == ISD::ADD &&
6553            Src.getOperand(0).getOpcode() == ISD::GlobalAddress &&
6554            Src.getOperand(1).getOpcode() == ISD::Constant) {
6555     G = cast<GlobalAddressSDNode>(Src.getOperand(0));
6556     SrcDelta = cast<ConstantSDNode>(Src.getOperand(1))->getZExtValue();
6557   }
6558   if (!G)
6559     return false;
6560 
6561   return getConstantDataArrayInfo(G->getGlobal(), Slice, 8,
6562                                   SrcDelta + G->getOffset());
6563 }
6564 
6565 static bool shouldLowerMemFuncForSize(const MachineFunction &MF,
6566                                       SelectionDAG &DAG) {
6567   // On Darwin, -Os means optimize for size without hurting performance, so
6568   // only really optimize for size when -Oz (MinSize) is used.
6569   if (MF.getTarget().getTargetTriple().isOSDarwin())
6570     return MF.getFunction().hasMinSize();
6571   return DAG.shouldOptForSize();
6572 }
6573 
6574 static void chainLoadsAndStoresForMemcpy(SelectionDAG &DAG, const SDLoc &dl,
6575                           SmallVector<SDValue, 32> &OutChains, unsigned From,
6576                           unsigned To, SmallVector<SDValue, 16> &OutLoadChains,
6577                           SmallVector<SDValue, 16> &OutStoreChains) {
6578   assert(OutLoadChains.size() && "Missing loads in memcpy inlining");
6579   assert(OutStoreChains.size() && "Missing stores in memcpy inlining");
6580   SmallVector<SDValue, 16> GluedLoadChains;
6581   for (unsigned i = From; i < To; ++i) {
6582     OutChains.push_back(OutLoadChains[i]);
6583     GluedLoadChains.push_back(OutLoadChains[i]);
6584   }
6585 
6586   // Chain for all loads.
6587   SDValue LoadToken = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
6588                                   GluedLoadChains);
6589 
6590   for (unsigned i = From; i < To; ++i) {
6591     StoreSDNode *ST = dyn_cast<StoreSDNode>(OutStoreChains[i]);
6592     SDValue NewStore = DAG.getTruncStore(LoadToken, dl, ST->getValue(),
6593                                   ST->getBasePtr(), ST->getMemoryVT(),
6594                                   ST->getMemOperand());
6595     OutChains.push_back(NewStore);
6596   }
6597 }
6598 
6599 static SDValue getMemcpyLoadsAndStores(SelectionDAG &DAG, const SDLoc &dl,
6600                                        SDValue Chain, SDValue Dst, SDValue Src,
6601                                        uint64_t Size, Align Alignment,
6602                                        bool isVol, bool AlwaysInline,
6603                                        MachinePointerInfo DstPtrInfo,
6604                                        MachinePointerInfo SrcPtrInfo,
6605                                        const AAMDNodes &AAInfo) {
6606   // Turn a memcpy of undef to nop.
6607   // FIXME: We need to honor volatile even is Src is undef.
6608   if (Src.isUndef())
6609     return Chain;
6610 
6611   // Expand memcpy to a series of load and store ops if the size operand falls
6612   // below a certain threshold.
6613   // TODO: In the AlwaysInline case, if the size is big then generate a loop
6614   // rather than maybe a humongous number of loads and stores.
6615   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6616   const DataLayout &DL = DAG.getDataLayout();
6617   LLVMContext &C = *DAG.getContext();
6618   std::vector<EVT> MemOps;
6619   bool DstAlignCanChange = false;
6620   MachineFunction &MF = DAG.getMachineFunction();
6621   MachineFrameInfo &MFI = MF.getFrameInfo();
6622   bool OptSize = shouldLowerMemFuncForSize(MF, DAG);
6623   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
6624   if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
6625     DstAlignCanChange = true;
6626   MaybeAlign SrcAlign = DAG.InferPtrAlign(Src);
6627   if (!SrcAlign || Alignment > *SrcAlign)
6628     SrcAlign = Alignment;
6629   assert(SrcAlign && "SrcAlign must be set");
6630   ConstantDataArraySlice Slice;
6631   // If marked as volatile, perform a copy even when marked as constant.
6632   bool CopyFromConstant = !isVol && isMemSrcFromConstant(Src, Slice);
6633   bool isZeroConstant = CopyFromConstant && Slice.Array == nullptr;
6634   unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemcpy(OptSize);
6635   const MemOp Op = isZeroConstant
6636                        ? MemOp::Set(Size, DstAlignCanChange, Alignment,
6637                                     /*IsZeroMemset*/ true, isVol)
6638                        : MemOp::Copy(Size, DstAlignCanChange, Alignment,
6639                                      *SrcAlign, isVol, CopyFromConstant);
6640   if (!TLI.findOptimalMemOpLowering(
6641           MemOps, Limit, Op, DstPtrInfo.getAddrSpace(),
6642           SrcPtrInfo.getAddrSpace(), MF.getFunction().getAttributes()))
6643     return SDValue();
6644 
6645   if (DstAlignCanChange) {
6646     Type *Ty = MemOps[0].getTypeForEVT(C);
6647     Align NewAlign = DL.getABITypeAlign(Ty);
6648 
6649     // Don't promote to an alignment that would require dynamic stack
6650     // realignment.
6651     const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
6652     if (!TRI->hasStackRealignment(MF))
6653       while (NewAlign > Alignment && DL.exceedsNaturalStackAlignment(NewAlign))
6654         NewAlign = NewAlign / 2;
6655 
6656     if (NewAlign > Alignment) {
6657       // Give the stack frame object a larger alignment if needed.
6658       if (MFI.getObjectAlign(FI->getIndex()) < NewAlign)
6659         MFI.setObjectAlignment(FI->getIndex(), NewAlign);
6660       Alignment = NewAlign;
6661     }
6662   }
6663 
6664   // Prepare AAInfo for loads/stores after lowering this memcpy.
6665   AAMDNodes NewAAInfo = AAInfo;
6666   NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr;
6667 
6668   MachineMemOperand::Flags MMOFlags =
6669       isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone;
6670   SmallVector<SDValue, 16> OutLoadChains;
6671   SmallVector<SDValue, 16> OutStoreChains;
6672   SmallVector<SDValue, 32> OutChains;
6673   unsigned NumMemOps = MemOps.size();
6674   uint64_t SrcOff = 0, DstOff = 0;
6675   for (unsigned i = 0; i != NumMemOps; ++i) {
6676     EVT VT = MemOps[i];
6677     unsigned VTSize = VT.getSizeInBits() / 8;
6678     SDValue Value, Store;
6679 
6680     if (VTSize > Size) {
6681       // Issuing an unaligned load / store pair  that overlaps with the previous
6682       // pair. Adjust the offset accordingly.
6683       assert(i == NumMemOps-1 && i != 0);
6684       SrcOff -= VTSize - Size;
6685       DstOff -= VTSize - Size;
6686     }
6687 
6688     if (CopyFromConstant &&
6689         (isZeroConstant || (VT.isInteger() && !VT.isVector()))) {
6690       // It's unlikely a store of a vector immediate can be done in a single
6691       // instruction. It would require a load from a constantpool first.
6692       // We only handle zero vectors here.
6693       // FIXME: Handle other cases where store of vector immediate is done in
6694       // a single instruction.
6695       ConstantDataArraySlice SubSlice;
6696       if (SrcOff < Slice.Length) {
6697         SubSlice = Slice;
6698         SubSlice.move(SrcOff);
6699       } else {
6700         // This is an out-of-bounds access and hence UB. Pretend we read zero.
6701         SubSlice.Array = nullptr;
6702         SubSlice.Offset = 0;
6703         SubSlice.Length = VTSize;
6704       }
6705       Value = getMemsetStringVal(VT, dl, DAG, TLI, SubSlice);
6706       if (Value.getNode()) {
6707         Store = DAG.getStore(
6708             Chain, dl, Value,
6709             DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl),
6710             DstPtrInfo.getWithOffset(DstOff), Alignment, MMOFlags, NewAAInfo);
6711         OutChains.push_back(Store);
6712       }
6713     }
6714 
6715     if (!Store.getNode()) {
6716       // The type might not be legal for the target.  This should only happen
6717       // if the type is smaller than a legal type, as on PPC, so the right
6718       // thing to do is generate a LoadExt/StoreTrunc pair.  These simplify
6719       // to Load/Store if NVT==VT.
6720       // FIXME does the case above also need this?
6721       EVT NVT = TLI.getTypeToTransformTo(C, VT);
6722       assert(NVT.bitsGE(VT));
6723 
6724       bool isDereferenceable =
6725         SrcPtrInfo.getWithOffset(SrcOff).isDereferenceable(VTSize, C, DL);
6726       MachineMemOperand::Flags SrcMMOFlags = MMOFlags;
6727       if (isDereferenceable)
6728         SrcMMOFlags |= MachineMemOperand::MODereferenceable;
6729 
6730       Value = DAG.getExtLoad(
6731           ISD::EXTLOAD, dl, NVT, Chain,
6732           DAG.getMemBasePlusOffset(Src, TypeSize::Fixed(SrcOff), dl),
6733           SrcPtrInfo.getWithOffset(SrcOff), VT,
6734           commonAlignment(*SrcAlign, SrcOff), SrcMMOFlags, NewAAInfo);
6735       OutLoadChains.push_back(Value.getValue(1));
6736 
6737       Store = DAG.getTruncStore(
6738           Chain, dl, Value,
6739           DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl),
6740           DstPtrInfo.getWithOffset(DstOff), VT, Alignment, MMOFlags, NewAAInfo);
6741       OutStoreChains.push_back(Store);
6742     }
6743     SrcOff += VTSize;
6744     DstOff += VTSize;
6745     Size -= VTSize;
6746   }
6747 
6748   unsigned GluedLdStLimit = MaxLdStGlue == 0 ?
6749                                 TLI.getMaxGluedStoresPerMemcpy() : MaxLdStGlue;
6750   unsigned NumLdStInMemcpy = OutStoreChains.size();
6751 
6752   if (NumLdStInMemcpy) {
6753     // It may be that memcpy might be converted to memset if it's memcpy
6754     // of constants. In such a case, we won't have loads and stores, but
6755     // just stores. In the absence of loads, there is nothing to gang up.
6756     if ((GluedLdStLimit <= 1) || !EnableMemCpyDAGOpt) {
6757       // If target does not care, just leave as it.
6758       for (unsigned i = 0; i < NumLdStInMemcpy; ++i) {
6759         OutChains.push_back(OutLoadChains[i]);
6760         OutChains.push_back(OutStoreChains[i]);
6761       }
6762     } else {
6763       // Ld/St less than/equal limit set by target.
6764       if (NumLdStInMemcpy <= GluedLdStLimit) {
6765           chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, 0,
6766                                         NumLdStInMemcpy, OutLoadChains,
6767                                         OutStoreChains);
6768       } else {
6769         unsigned NumberLdChain =  NumLdStInMemcpy / GluedLdStLimit;
6770         unsigned RemainingLdStInMemcpy = NumLdStInMemcpy % GluedLdStLimit;
6771         unsigned GlueIter = 0;
6772 
6773         for (unsigned cnt = 0; cnt < NumberLdChain; ++cnt) {
6774           unsigned IndexFrom = NumLdStInMemcpy - GlueIter - GluedLdStLimit;
6775           unsigned IndexTo   = NumLdStInMemcpy - GlueIter;
6776 
6777           chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, IndexFrom, IndexTo,
6778                                        OutLoadChains, OutStoreChains);
6779           GlueIter += GluedLdStLimit;
6780         }
6781 
6782         // Residual ld/st.
6783         if (RemainingLdStInMemcpy) {
6784           chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, 0,
6785                                         RemainingLdStInMemcpy, OutLoadChains,
6786                                         OutStoreChains);
6787         }
6788       }
6789     }
6790   }
6791   return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
6792 }
6793 
6794 static SDValue getMemmoveLoadsAndStores(SelectionDAG &DAG, const SDLoc &dl,
6795                                         SDValue Chain, SDValue Dst, SDValue Src,
6796                                         uint64_t Size, Align Alignment,
6797                                         bool isVol, bool AlwaysInline,
6798                                         MachinePointerInfo DstPtrInfo,
6799                                         MachinePointerInfo SrcPtrInfo,
6800                                         const AAMDNodes &AAInfo) {
6801   // Turn a memmove of undef to nop.
6802   // FIXME: We need to honor volatile even is Src is undef.
6803   if (Src.isUndef())
6804     return Chain;
6805 
6806   // Expand memmove to a series of load and store ops if the size operand falls
6807   // below a certain threshold.
6808   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6809   const DataLayout &DL = DAG.getDataLayout();
6810   LLVMContext &C = *DAG.getContext();
6811   std::vector<EVT> MemOps;
6812   bool DstAlignCanChange = false;
6813   MachineFunction &MF = DAG.getMachineFunction();
6814   MachineFrameInfo &MFI = MF.getFrameInfo();
6815   bool OptSize = shouldLowerMemFuncForSize(MF, DAG);
6816   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
6817   if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
6818     DstAlignCanChange = true;
6819   MaybeAlign SrcAlign = DAG.InferPtrAlign(Src);
6820   if (!SrcAlign || Alignment > *SrcAlign)
6821     SrcAlign = Alignment;
6822   assert(SrcAlign && "SrcAlign must be set");
6823   unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemmove(OptSize);
6824   if (!TLI.findOptimalMemOpLowering(
6825           MemOps, Limit,
6826           MemOp::Copy(Size, DstAlignCanChange, Alignment, *SrcAlign,
6827                       /*IsVolatile*/ true),
6828           DstPtrInfo.getAddrSpace(), SrcPtrInfo.getAddrSpace(),
6829           MF.getFunction().getAttributes()))
6830     return SDValue();
6831 
6832   if (DstAlignCanChange) {
6833     Type *Ty = MemOps[0].getTypeForEVT(C);
6834     Align NewAlign = DL.getABITypeAlign(Ty);
6835     if (NewAlign > Alignment) {
6836       // Give the stack frame object a larger alignment if needed.
6837       if (MFI.getObjectAlign(FI->getIndex()) < NewAlign)
6838         MFI.setObjectAlignment(FI->getIndex(), NewAlign);
6839       Alignment = NewAlign;
6840     }
6841   }
6842 
6843   // Prepare AAInfo for loads/stores after lowering this memmove.
6844   AAMDNodes NewAAInfo = AAInfo;
6845   NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr;
6846 
6847   MachineMemOperand::Flags MMOFlags =
6848       isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone;
6849   uint64_t SrcOff = 0, DstOff = 0;
6850   SmallVector<SDValue, 8> LoadValues;
6851   SmallVector<SDValue, 8> LoadChains;
6852   SmallVector<SDValue, 8> OutChains;
6853   unsigned NumMemOps = MemOps.size();
6854   for (unsigned i = 0; i < NumMemOps; i++) {
6855     EVT VT = MemOps[i];
6856     unsigned VTSize = VT.getSizeInBits() / 8;
6857     SDValue Value;
6858 
6859     bool isDereferenceable =
6860       SrcPtrInfo.getWithOffset(SrcOff).isDereferenceable(VTSize, C, DL);
6861     MachineMemOperand::Flags SrcMMOFlags = MMOFlags;
6862     if (isDereferenceable)
6863       SrcMMOFlags |= MachineMemOperand::MODereferenceable;
6864 
6865     Value = DAG.getLoad(
6866         VT, dl, Chain,
6867         DAG.getMemBasePlusOffset(Src, TypeSize::Fixed(SrcOff), dl),
6868         SrcPtrInfo.getWithOffset(SrcOff), *SrcAlign, SrcMMOFlags, NewAAInfo);
6869     LoadValues.push_back(Value);
6870     LoadChains.push_back(Value.getValue(1));
6871     SrcOff += VTSize;
6872   }
6873   Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
6874   OutChains.clear();
6875   for (unsigned i = 0; i < NumMemOps; i++) {
6876     EVT VT = MemOps[i];
6877     unsigned VTSize = VT.getSizeInBits() / 8;
6878     SDValue Store;
6879 
6880     Store = DAG.getStore(
6881         Chain, dl, LoadValues[i],
6882         DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl),
6883         DstPtrInfo.getWithOffset(DstOff), Alignment, MMOFlags, NewAAInfo);
6884     OutChains.push_back(Store);
6885     DstOff += VTSize;
6886   }
6887 
6888   return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
6889 }
6890 
6891 /// Lower the call to 'memset' intrinsic function into a series of store
6892 /// operations.
6893 ///
6894 /// \param DAG Selection DAG where lowered code is placed.
6895 /// \param dl Link to corresponding IR location.
6896 /// \param Chain Control flow dependency.
6897 /// \param Dst Pointer to destination memory location.
6898 /// \param Src Value of byte to write into the memory.
6899 /// \param Size Number of bytes to write.
6900 /// \param Alignment Alignment of the destination in bytes.
6901 /// \param isVol True if destination is volatile.
6902 /// \param DstPtrInfo IR information on the memory pointer.
6903 /// \returns New head in the control flow, if lowering was successful, empty
6904 /// SDValue otherwise.
6905 ///
6906 /// The function tries to replace 'llvm.memset' intrinsic with several store
6907 /// operations and value calculation code. This is usually profitable for small
6908 /// memory size.
6909 static SDValue getMemsetStores(SelectionDAG &DAG, const SDLoc &dl,
6910                                SDValue Chain, SDValue Dst, SDValue Src,
6911                                uint64_t Size, Align Alignment, bool isVol,
6912                                MachinePointerInfo DstPtrInfo,
6913                                const AAMDNodes &AAInfo) {
6914   // Turn a memset of undef to nop.
6915   // FIXME: We need to honor volatile even is Src is undef.
6916   if (Src.isUndef())
6917     return Chain;
6918 
6919   // Expand memset to a series of load/store ops if the size operand
6920   // falls below a certain threshold.
6921   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6922   std::vector<EVT> MemOps;
6923   bool DstAlignCanChange = false;
6924   MachineFunction &MF = DAG.getMachineFunction();
6925   MachineFrameInfo &MFI = MF.getFrameInfo();
6926   bool OptSize = shouldLowerMemFuncForSize(MF, DAG);
6927   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
6928   if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
6929     DstAlignCanChange = true;
6930   bool IsZeroVal =
6931       isa<ConstantSDNode>(Src) && cast<ConstantSDNode>(Src)->isZero();
6932   if (!TLI.findOptimalMemOpLowering(
6933           MemOps, TLI.getMaxStoresPerMemset(OptSize),
6934           MemOp::Set(Size, DstAlignCanChange, Alignment, IsZeroVal, isVol),
6935           DstPtrInfo.getAddrSpace(), ~0u, MF.getFunction().getAttributes()))
6936     return SDValue();
6937 
6938   if (DstAlignCanChange) {
6939     Type *Ty = MemOps[0].getTypeForEVT(*DAG.getContext());
6940     Align NewAlign = DAG.getDataLayout().getABITypeAlign(Ty);
6941     if (NewAlign > Alignment) {
6942       // Give the stack frame object a larger alignment if needed.
6943       if (MFI.getObjectAlign(FI->getIndex()) < NewAlign)
6944         MFI.setObjectAlignment(FI->getIndex(), NewAlign);
6945       Alignment = NewAlign;
6946     }
6947   }
6948 
6949   SmallVector<SDValue, 8> OutChains;
6950   uint64_t DstOff = 0;
6951   unsigned NumMemOps = MemOps.size();
6952 
6953   // Find the largest store and generate the bit pattern for it.
6954   EVT LargestVT = MemOps[0];
6955   for (unsigned i = 1; i < NumMemOps; i++)
6956     if (MemOps[i].bitsGT(LargestVT))
6957       LargestVT = MemOps[i];
6958   SDValue MemSetValue = getMemsetValue(Src, LargestVT, DAG, dl);
6959 
6960   // Prepare AAInfo for loads/stores after lowering this memset.
6961   AAMDNodes NewAAInfo = AAInfo;
6962   NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr;
6963 
6964   for (unsigned i = 0; i < NumMemOps; i++) {
6965     EVT VT = MemOps[i];
6966     unsigned VTSize = VT.getSizeInBits() / 8;
6967     if (VTSize > Size) {
6968       // Issuing an unaligned load / store pair  that overlaps with the previous
6969       // pair. Adjust the offset accordingly.
6970       assert(i == NumMemOps-1 && i != 0);
6971       DstOff -= VTSize - Size;
6972     }
6973 
6974     // If this store is smaller than the largest store see whether we can get
6975     // the smaller value for free with a truncate.
6976     SDValue Value = MemSetValue;
6977     if (VT.bitsLT(LargestVT)) {
6978       if (!LargestVT.isVector() && !VT.isVector() &&
6979           TLI.isTruncateFree(LargestVT, VT))
6980         Value = DAG.getNode(ISD::TRUNCATE, dl, VT, MemSetValue);
6981       else
6982         Value = getMemsetValue(Src, VT, DAG, dl);
6983     }
6984     assert(Value.getValueType() == VT && "Value with wrong type.");
6985     SDValue Store = DAG.getStore(
6986         Chain, dl, Value,
6987         DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl),
6988         DstPtrInfo.getWithOffset(DstOff), Alignment,
6989         isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone,
6990         NewAAInfo);
6991     OutChains.push_back(Store);
6992     DstOff += VT.getSizeInBits() / 8;
6993     Size -= VTSize;
6994   }
6995 
6996   return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
6997 }
6998 
6999 static void checkAddrSpaceIsValidForLibcall(const TargetLowering *TLI,
7000                                             unsigned AS) {
7001   // Lowering memcpy / memset / memmove intrinsics to calls is only valid if all
7002   // pointer operands can be losslessly bitcasted to pointers of address space 0
7003   if (AS != 0 && !TLI->getTargetMachine().isNoopAddrSpaceCast(AS, 0)) {
7004     report_fatal_error("cannot lower memory intrinsic in address space " +
7005                        Twine(AS));
7006   }
7007 }
7008 
7009 SDValue SelectionDAG::getMemcpy(SDValue Chain, const SDLoc &dl, SDValue Dst,
7010                                 SDValue Src, SDValue Size, Align Alignment,
7011                                 bool isVol, bool AlwaysInline, bool isTailCall,
7012                                 MachinePointerInfo DstPtrInfo,
7013                                 MachinePointerInfo SrcPtrInfo,
7014                                 const AAMDNodes &AAInfo) {
7015   // Check to see if we should lower the memcpy to loads and stores first.
7016   // For cases within the target-specified limits, this is the best choice.
7017   ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
7018   if (ConstantSize) {
7019     // Memcpy with size zero? Just return the original chain.
7020     if (ConstantSize->isZero())
7021       return Chain;
7022 
7023     SDValue Result = getMemcpyLoadsAndStores(
7024         *this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), Alignment,
7025         isVol, false, DstPtrInfo, SrcPtrInfo, AAInfo);
7026     if (Result.getNode())
7027       return Result;
7028   }
7029 
7030   // Then check to see if we should lower the memcpy with target-specific
7031   // code. If the target chooses to do this, this is the next best.
7032   if (TSI) {
7033     SDValue Result = TSI->EmitTargetCodeForMemcpy(
7034         *this, dl, Chain, Dst, Src, Size, Alignment, isVol, AlwaysInline,
7035         DstPtrInfo, SrcPtrInfo);
7036     if (Result.getNode())
7037       return Result;
7038   }
7039 
7040   // If we really need inline code and the target declined to provide it,
7041   // use a (potentially long) sequence of loads and stores.
7042   if (AlwaysInline) {
7043     assert(ConstantSize && "AlwaysInline requires a constant size!");
7044     return getMemcpyLoadsAndStores(*this, dl, Chain, Dst, Src,
7045                                    ConstantSize->getZExtValue(), Alignment,
7046                                    isVol, true, DstPtrInfo, SrcPtrInfo, AAInfo);
7047   }
7048 
7049   checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace());
7050   checkAddrSpaceIsValidForLibcall(TLI, SrcPtrInfo.getAddrSpace());
7051 
7052   // FIXME: If the memcpy is volatile (isVol), lowering it to a plain libc
7053   // memcpy is not guaranteed to be safe. libc memcpys aren't required to
7054   // respect volatile, so they may do things like read or write memory
7055   // beyond the given memory regions. But fixing this isn't easy, and most
7056   // people don't care.
7057 
7058   // Emit a library call.
7059   TargetLowering::ArgListTy Args;
7060   TargetLowering::ArgListEntry Entry;
7061   Entry.Ty = Type::getInt8PtrTy(*getContext());
7062   Entry.Node = Dst; Args.push_back(Entry);
7063   Entry.Node = Src; Args.push_back(Entry);
7064 
7065   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
7066   Entry.Node = Size; Args.push_back(Entry);
7067   // FIXME: pass in SDLoc
7068   TargetLowering::CallLoweringInfo CLI(*this);
7069   CLI.setDebugLoc(dl)
7070       .setChain(Chain)
7071       .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMCPY),
7072                     Dst.getValueType().getTypeForEVT(*getContext()),
7073                     getExternalSymbol(TLI->getLibcallName(RTLIB::MEMCPY),
7074                                       TLI->getPointerTy(getDataLayout())),
7075                     std::move(Args))
7076       .setDiscardResult()
7077       .setTailCall(isTailCall);
7078 
7079   std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
7080   return CallResult.second;
7081 }
7082 
7083 SDValue SelectionDAG::getAtomicMemcpy(SDValue Chain, const SDLoc &dl,
7084                                       SDValue Dst, unsigned DstAlign,
7085                                       SDValue Src, unsigned SrcAlign,
7086                                       SDValue Size, Type *SizeTy,
7087                                       unsigned ElemSz, bool isTailCall,
7088                                       MachinePointerInfo DstPtrInfo,
7089                                       MachinePointerInfo SrcPtrInfo) {
7090   // Emit a library call.
7091   TargetLowering::ArgListTy Args;
7092   TargetLowering::ArgListEntry Entry;
7093   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
7094   Entry.Node = Dst;
7095   Args.push_back(Entry);
7096 
7097   Entry.Node = Src;
7098   Args.push_back(Entry);
7099 
7100   Entry.Ty = SizeTy;
7101   Entry.Node = Size;
7102   Args.push_back(Entry);
7103 
7104   RTLIB::Libcall LibraryCall =
7105       RTLIB::getMEMCPY_ELEMENT_UNORDERED_ATOMIC(ElemSz);
7106   if (LibraryCall == RTLIB::UNKNOWN_LIBCALL)
7107     report_fatal_error("Unsupported element size");
7108 
7109   TargetLowering::CallLoweringInfo CLI(*this);
7110   CLI.setDebugLoc(dl)
7111       .setChain(Chain)
7112       .setLibCallee(TLI->getLibcallCallingConv(LibraryCall),
7113                     Type::getVoidTy(*getContext()),
7114                     getExternalSymbol(TLI->getLibcallName(LibraryCall),
7115                                       TLI->getPointerTy(getDataLayout())),
7116                     std::move(Args))
7117       .setDiscardResult()
7118       .setTailCall(isTailCall);
7119 
7120   std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
7121   return CallResult.second;
7122 }
7123 
7124 SDValue SelectionDAG::getMemmove(SDValue Chain, const SDLoc &dl, SDValue Dst,
7125                                  SDValue Src, SDValue Size, Align Alignment,
7126                                  bool isVol, bool isTailCall,
7127                                  MachinePointerInfo DstPtrInfo,
7128                                  MachinePointerInfo SrcPtrInfo,
7129                                  const AAMDNodes &AAInfo) {
7130   // Check to see if we should lower the memmove to loads and stores first.
7131   // For cases within the target-specified limits, this is the best choice.
7132   ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
7133   if (ConstantSize) {
7134     // Memmove with size zero? Just return the original chain.
7135     if (ConstantSize->isZero())
7136       return Chain;
7137 
7138     SDValue Result = getMemmoveLoadsAndStores(
7139         *this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), Alignment,
7140         isVol, false, DstPtrInfo, SrcPtrInfo, AAInfo);
7141     if (Result.getNode())
7142       return Result;
7143   }
7144 
7145   // Then check to see if we should lower the memmove with target-specific
7146   // code. If the target chooses to do this, this is the next best.
7147   if (TSI) {
7148     SDValue Result =
7149         TSI->EmitTargetCodeForMemmove(*this, dl, Chain, Dst, Src, Size,
7150                                       Alignment, isVol, DstPtrInfo, SrcPtrInfo);
7151     if (Result.getNode())
7152       return Result;
7153   }
7154 
7155   checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace());
7156   checkAddrSpaceIsValidForLibcall(TLI, SrcPtrInfo.getAddrSpace());
7157 
7158   // FIXME: If the memmove is volatile, lowering it to plain libc memmove may
7159   // not be safe.  See memcpy above for more details.
7160 
7161   // Emit a library call.
7162   TargetLowering::ArgListTy Args;
7163   TargetLowering::ArgListEntry Entry;
7164   Entry.Ty = Type::getInt8PtrTy(*getContext());
7165   Entry.Node = Dst; Args.push_back(Entry);
7166   Entry.Node = Src; Args.push_back(Entry);
7167 
7168   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
7169   Entry.Node = Size; Args.push_back(Entry);
7170   // FIXME:  pass in SDLoc
7171   TargetLowering::CallLoweringInfo CLI(*this);
7172   CLI.setDebugLoc(dl)
7173       .setChain(Chain)
7174       .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMMOVE),
7175                     Dst.getValueType().getTypeForEVT(*getContext()),
7176                     getExternalSymbol(TLI->getLibcallName(RTLIB::MEMMOVE),
7177                                       TLI->getPointerTy(getDataLayout())),
7178                     std::move(Args))
7179       .setDiscardResult()
7180       .setTailCall(isTailCall);
7181 
7182   std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
7183   return CallResult.second;
7184 }
7185 
7186 SDValue SelectionDAG::getAtomicMemmove(SDValue Chain, const SDLoc &dl,
7187                                        SDValue Dst, unsigned DstAlign,
7188                                        SDValue Src, unsigned SrcAlign,
7189                                        SDValue Size, Type *SizeTy,
7190                                        unsigned ElemSz, bool isTailCall,
7191                                        MachinePointerInfo DstPtrInfo,
7192                                        MachinePointerInfo SrcPtrInfo) {
7193   // Emit a library call.
7194   TargetLowering::ArgListTy Args;
7195   TargetLowering::ArgListEntry Entry;
7196   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
7197   Entry.Node = Dst;
7198   Args.push_back(Entry);
7199 
7200   Entry.Node = Src;
7201   Args.push_back(Entry);
7202 
7203   Entry.Ty = SizeTy;
7204   Entry.Node = Size;
7205   Args.push_back(Entry);
7206 
7207   RTLIB::Libcall LibraryCall =
7208       RTLIB::getMEMMOVE_ELEMENT_UNORDERED_ATOMIC(ElemSz);
7209   if (LibraryCall == RTLIB::UNKNOWN_LIBCALL)
7210     report_fatal_error("Unsupported element size");
7211 
7212   TargetLowering::CallLoweringInfo CLI(*this);
7213   CLI.setDebugLoc(dl)
7214       .setChain(Chain)
7215       .setLibCallee(TLI->getLibcallCallingConv(LibraryCall),
7216                     Type::getVoidTy(*getContext()),
7217                     getExternalSymbol(TLI->getLibcallName(LibraryCall),
7218                                       TLI->getPointerTy(getDataLayout())),
7219                     std::move(Args))
7220       .setDiscardResult()
7221       .setTailCall(isTailCall);
7222 
7223   std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
7224   return CallResult.second;
7225 }
7226 
7227 SDValue SelectionDAG::getMemset(SDValue Chain, const SDLoc &dl, SDValue Dst,
7228                                 SDValue Src, SDValue Size, Align Alignment,
7229                                 bool isVol, bool isTailCall,
7230                                 MachinePointerInfo DstPtrInfo,
7231                                 const AAMDNodes &AAInfo) {
7232   // Check to see if we should lower the memset to stores first.
7233   // For cases within the target-specified limits, this is the best choice.
7234   ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
7235   if (ConstantSize) {
7236     // Memset with size zero? Just return the original chain.
7237     if (ConstantSize->isZero())
7238       return Chain;
7239 
7240     SDValue Result = getMemsetStores(*this, dl, Chain, Dst, Src,
7241                                      ConstantSize->getZExtValue(), Alignment,
7242                                      isVol, DstPtrInfo, AAInfo);
7243 
7244     if (Result.getNode())
7245       return Result;
7246   }
7247 
7248   // Then check to see if we should lower the memset with target-specific
7249   // code. If the target chooses to do this, this is the next best.
7250   if (TSI) {
7251     SDValue Result = TSI->EmitTargetCodeForMemset(
7252         *this, dl, Chain, Dst, Src, Size, Alignment, isVol, DstPtrInfo);
7253     if (Result.getNode())
7254       return Result;
7255   }
7256 
7257   checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace());
7258 
7259   // Emit a library call.
7260   TargetLowering::ArgListTy Args;
7261   TargetLowering::ArgListEntry Entry;
7262   Entry.Node = Dst; Entry.Ty = Type::getInt8PtrTy(*getContext());
7263   Args.push_back(Entry);
7264   Entry.Node = Src;
7265   Entry.Ty = Src.getValueType().getTypeForEVT(*getContext());
7266   Args.push_back(Entry);
7267   Entry.Node = Size;
7268   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
7269   Args.push_back(Entry);
7270 
7271   // FIXME: pass in SDLoc
7272   TargetLowering::CallLoweringInfo CLI(*this);
7273   CLI.setDebugLoc(dl)
7274       .setChain(Chain)
7275       .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMSET),
7276                     Dst.getValueType().getTypeForEVT(*getContext()),
7277                     getExternalSymbol(TLI->getLibcallName(RTLIB::MEMSET),
7278                                       TLI->getPointerTy(getDataLayout())),
7279                     std::move(Args))
7280       .setDiscardResult()
7281       .setTailCall(isTailCall);
7282 
7283   std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
7284   return CallResult.second;
7285 }
7286 
7287 SDValue SelectionDAG::getAtomicMemset(SDValue Chain, const SDLoc &dl,
7288                                       SDValue Dst, unsigned DstAlign,
7289                                       SDValue Value, SDValue Size, Type *SizeTy,
7290                                       unsigned ElemSz, bool isTailCall,
7291                                       MachinePointerInfo DstPtrInfo) {
7292   // Emit a library call.
7293   TargetLowering::ArgListTy Args;
7294   TargetLowering::ArgListEntry Entry;
7295   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
7296   Entry.Node = Dst;
7297   Args.push_back(Entry);
7298 
7299   Entry.Ty = Type::getInt8Ty(*getContext());
7300   Entry.Node = Value;
7301   Args.push_back(Entry);
7302 
7303   Entry.Ty = SizeTy;
7304   Entry.Node = Size;
7305   Args.push_back(Entry);
7306 
7307   RTLIB::Libcall LibraryCall =
7308       RTLIB::getMEMSET_ELEMENT_UNORDERED_ATOMIC(ElemSz);
7309   if (LibraryCall == RTLIB::UNKNOWN_LIBCALL)
7310     report_fatal_error("Unsupported element size");
7311 
7312   TargetLowering::CallLoweringInfo CLI(*this);
7313   CLI.setDebugLoc(dl)
7314       .setChain(Chain)
7315       .setLibCallee(TLI->getLibcallCallingConv(LibraryCall),
7316                     Type::getVoidTy(*getContext()),
7317                     getExternalSymbol(TLI->getLibcallName(LibraryCall),
7318                                       TLI->getPointerTy(getDataLayout())),
7319                     std::move(Args))
7320       .setDiscardResult()
7321       .setTailCall(isTailCall);
7322 
7323   std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
7324   return CallResult.second;
7325 }
7326 
7327 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
7328                                 SDVTList VTList, ArrayRef<SDValue> Ops,
7329                                 MachineMemOperand *MMO) {
7330   FoldingSetNodeID ID;
7331   ID.AddInteger(MemVT.getRawBits());
7332   AddNodeIDNode(ID, Opcode, VTList, Ops);
7333   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7334   ID.AddInteger(MMO->getFlags());
7335   void* IP = nullptr;
7336   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7337     cast<AtomicSDNode>(E)->refineAlignment(MMO);
7338     return SDValue(E, 0);
7339   }
7340 
7341   auto *N = newSDNode<AtomicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
7342                                     VTList, MemVT, MMO);
7343   createOperands(N, Ops);
7344 
7345   CSEMap.InsertNode(N, IP);
7346   InsertNode(N);
7347   return SDValue(N, 0);
7348 }
7349 
7350 SDValue SelectionDAG::getAtomicCmpSwap(unsigned Opcode, const SDLoc &dl,
7351                                        EVT MemVT, SDVTList VTs, SDValue Chain,
7352                                        SDValue Ptr, SDValue Cmp, SDValue Swp,
7353                                        MachineMemOperand *MMO) {
7354   assert(Opcode == ISD::ATOMIC_CMP_SWAP ||
7355          Opcode == ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS);
7356   assert(Cmp.getValueType() == Swp.getValueType() && "Invalid Atomic Op Types");
7357 
7358   SDValue Ops[] = {Chain, Ptr, Cmp, Swp};
7359   return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
7360 }
7361 
7362 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
7363                                 SDValue Chain, SDValue Ptr, SDValue Val,
7364                                 MachineMemOperand *MMO) {
7365   assert((Opcode == ISD::ATOMIC_LOAD_ADD ||
7366           Opcode == ISD::ATOMIC_LOAD_SUB ||
7367           Opcode == ISD::ATOMIC_LOAD_AND ||
7368           Opcode == ISD::ATOMIC_LOAD_CLR ||
7369           Opcode == ISD::ATOMIC_LOAD_OR ||
7370           Opcode == ISD::ATOMIC_LOAD_XOR ||
7371           Opcode == ISD::ATOMIC_LOAD_NAND ||
7372           Opcode == ISD::ATOMIC_LOAD_MIN ||
7373           Opcode == ISD::ATOMIC_LOAD_MAX ||
7374           Opcode == ISD::ATOMIC_LOAD_UMIN ||
7375           Opcode == ISD::ATOMIC_LOAD_UMAX ||
7376           Opcode == ISD::ATOMIC_LOAD_FADD ||
7377           Opcode == ISD::ATOMIC_LOAD_FSUB ||
7378           Opcode == ISD::ATOMIC_SWAP ||
7379           Opcode == ISD::ATOMIC_STORE) &&
7380          "Invalid Atomic Op");
7381 
7382   EVT VT = Val.getValueType();
7383 
7384   SDVTList VTs = Opcode == ISD::ATOMIC_STORE ? getVTList(MVT::Other) :
7385                                                getVTList(VT, MVT::Other);
7386   SDValue Ops[] = {Chain, Ptr, Val};
7387   return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
7388 }
7389 
7390 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
7391                                 EVT VT, SDValue Chain, SDValue Ptr,
7392                                 MachineMemOperand *MMO) {
7393   assert(Opcode == ISD::ATOMIC_LOAD && "Invalid Atomic Op");
7394 
7395   SDVTList VTs = getVTList(VT, MVT::Other);
7396   SDValue Ops[] = {Chain, Ptr};
7397   return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
7398 }
7399 
7400 /// getMergeValues - Create a MERGE_VALUES node from the given operands.
7401 SDValue SelectionDAG::getMergeValues(ArrayRef<SDValue> Ops, const SDLoc &dl) {
7402   if (Ops.size() == 1)
7403     return Ops[0];
7404 
7405   SmallVector<EVT, 4> VTs;
7406   VTs.reserve(Ops.size());
7407   for (const SDValue &Op : Ops)
7408     VTs.push_back(Op.getValueType());
7409   return getNode(ISD::MERGE_VALUES, dl, getVTList(VTs), Ops);
7410 }
7411 
7412 SDValue SelectionDAG::getMemIntrinsicNode(
7413     unsigned Opcode, const SDLoc &dl, SDVTList VTList, ArrayRef<SDValue> Ops,
7414     EVT MemVT, MachinePointerInfo PtrInfo, Align Alignment,
7415     MachineMemOperand::Flags Flags, uint64_t Size, const AAMDNodes &AAInfo) {
7416   if (!Size && MemVT.isScalableVector())
7417     Size = MemoryLocation::UnknownSize;
7418   else if (!Size)
7419     Size = MemVT.getStoreSize();
7420 
7421   MachineFunction &MF = getMachineFunction();
7422   MachineMemOperand *MMO =
7423       MF.getMachineMemOperand(PtrInfo, Flags, Size, Alignment, AAInfo);
7424 
7425   return getMemIntrinsicNode(Opcode, dl, VTList, Ops, MemVT, MMO);
7426 }
7427 
7428 SDValue SelectionDAG::getMemIntrinsicNode(unsigned Opcode, const SDLoc &dl,
7429                                           SDVTList VTList,
7430                                           ArrayRef<SDValue> Ops, EVT MemVT,
7431                                           MachineMemOperand *MMO) {
7432   assert((Opcode == ISD::INTRINSIC_VOID ||
7433           Opcode == ISD::INTRINSIC_W_CHAIN ||
7434           Opcode == ISD::PREFETCH ||
7435           ((int)Opcode <= std::numeric_limits<int>::max() &&
7436            (int)Opcode >= ISD::FIRST_TARGET_MEMORY_OPCODE)) &&
7437          "Opcode is not a memory-accessing opcode!");
7438 
7439   // Memoize the node unless it returns a flag.
7440   MemIntrinsicSDNode *N;
7441   if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) {
7442     FoldingSetNodeID ID;
7443     AddNodeIDNode(ID, Opcode, VTList, Ops);
7444     ID.AddInteger(getSyntheticNodeSubclassData<MemIntrinsicSDNode>(
7445         Opcode, dl.getIROrder(), VTList, MemVT, MMO));
7446     ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7447     ID.AddInteger(MMO->getFlags());
7448     void *IP = nullptr;
7449     if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7450       cast<MemIntrinsicSDNode>(E)->refineAlignment(MMO);
7451       return SDValue(E, 0);
7452     }
7453 
7454     N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
7455                                       VTList, MemVT, MMO);
7456     createOperands(N, Ops);
7457 
7458   CSEMap.InsertNode(N, IP);
7459   } else {
7460     N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
7461                                       VTList, MemVT, MMO);
7462     createOperands(N, Ops);
7463   }
7464   InsertNode(N);
7465   SDValue V(N, 0);
7466   NewSDValueDbgMsg(V, "Creating new node: ", this);
7467   return V;
7468 }
7469 
7470 SDValue SelectionDAG::getLifetimeNode(bool IsStart, const SDLoc &dl,
7471                                       SDValue Chain, int FrameIndex,
7472                                       int64_t Size, int64_t Offset) {
7473   const unsigned Opcode = IsStart ? ISD::LIFETIME_START : ISD::LIFETIME_END;
7474   const auto VTs = getVTList(MVT::Other);
7475   SDValue Ops[2] = {
7476       Chain,
7477       getFrameIndex(FrameIndex,
7478                     getTargetLoweringInfo().getFrameIndexTy(getDataLayout()),
7479                     true)};
7480 
7481   FoldingSetNodeID ID;
7482   AddNodeIDNode(ID, Opcode, VTs, Ops);
7483   ID.AddInteger(FrameIndex);
7484   ID.AddInteger(Size);
7485   ID.AddInteger(Offset);
7486   void *IP = nullptr;
7487   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
7488     return SDValue(E, 0);
7489 
7490   LifetimeSDNode *N = newSDNode<LifetimeSDNode>(
7491       Opcode, dl.getIROrder(), dl.getDebugLoc(), VTs, Size, Offset);
7492   createOperands(N, Ops);
7493   CSEMap.InsertNode(N, IP);
7494   InsertNode(N);
7495   SDValue V(N, 0);
7496   NewSDValueDbgMsg(V, "Creating new node: ", this);
7497   return V;
7498 }
7499 
7500 SDValue SelectionDAG::getPseudoProbeNode(const SDLoc &Dl, SDValue Chain,
7501                                          uint64_t Guid, uint64_t Index,
7502                                          uint32_t Attr) {
7503   const unsigned Opcode = ISD::PSEUDO_PROBE;
7504   const auto VTs = getVTList(MVT::Other);
7505   SDValue Ops[] = {Chain};
7506   FoldingSetNodeID ID;
7507   AddNodeIDNode(ID, Opcode, VTs, Ops);
7508   ID.AddInteger(Guid);
7509   ID.AddInteger(Index);
7510   void *IP = nullptr;
7511   if (SDNode *E = FindNodeOrInsertPos(ID, Dl, IP))
7512     return SDValue(E, 0);
7513 
7514   auto *N = newSDNode<PseudoProbeSDNode>(
7515       Opcode, Dl.getIROrder(), Dl.getDebugLoc(), VTs, Guid, Index, Attr);
7516   createOperands(N, Ops);
7517   CSEMap.InsertNode(N, IP);
7518   InsertNode(N);
7519   SDValue V(N, 0);
7520   NewSDValueDbgMsg(V, "Creating new node: ", this);
7521   return V;
7522 }
7523 
7524 /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a
7525 /// MachinePointerInfo record from it.  This is particularly useful because the
7526 /// code generator has many cases where it doesn't bother passing in a
7527 /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst".
7528 static MachinePointerInfo InferPointerInfo(const MachinePointerInfo &Info,
7529                                            SelectionDAG &DAG, SDValue Ptr,
7530                                            int64_t Offset = 0) {
7531   // If this is FI+Offset, we can model it.
7532   if (const FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr))
7533     return MachinePointerInfo::getFixedStack(DAG.getMachineFunction(),
7534                                              FI->getIndex(), Offset);
7535 
7536   // If this is (FI+Offset1)+Offset2, we can model it.
7537   if (Ptr.getOpcode() != ISD::ADD ||
7538       !isa<ConstantSDNode>(Ptr.getOperand(1)) ||
7539       !isa<FrameIndexSDNode>(Ptr.getOperand(0)))
7540     return Info;
7541 
7542   int FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
7543   return MachinePointerInfo::getFixedStack(
7544       DAG.getMachineFunction(), FI,
7545       Offset + cast<ConstantSDNode>(Ptr.getOperand(1))->getSExtValue());
7546 }
7547 
7548 /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a
7549 /// MachinePointerInfo record from it.  This is particularly useful because the
7550 /// code generator has many cases where it doesn't bother passing in a
7551 /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst".
7552 static MachinePointerInfo InferPointerInfo(const MachinePointerInfo &Info,
7553                                            SelectionDAG &DAG, SDValue Ptr,
7554                                            SDValue OffsetOp) {
7555   // If the 'Offset' value isn't a constant, we can't handle this.
7556   if (ConstantSDNode *OffsetNode = dyn_cast<ConstantSDNode>(OffsetOp))
7557     return InferPointerInfo(Info, DAG, Ptr, OffsetNode->getSExtValue());
7558   if (OffsetOp.isUndef())
7559     return InferPointerInfo(Info, DAG, Ptr);
7560   return Info;
7561 }
7562 
7563 SDValue SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType,
7564                               EVT VT, const SDLoc &dl, SDValue Chain,
7565                               SDValue Ptr, SDValue Offset,
7566                               MachinePointerInfo PtrInfo, EVT MemVT,
7567                               Align Alignment,
7568                               MachineMemOperand::Flags MMOFlags,
7569                               const AAMDNodes &AAInfo, const MDNode *Ranges) {
7570   assert(Chain.getValueType() == MVT::Other &&
7571         "Invalid chain type");
7572 
7573   MMOFlags |= MachineMemOperand::MOLoad;
7574   assert((MMOFlags & MachineMemOperand::MOStore) == 0);
7575   // If we don't have a PtrInfo, infer the trivial frame index case to simplify
7576   // clients.
7577   if (PtrInfo.V.isNull())
7578     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr, Offset);
7579 
7580   uint64_t Size = MemoryLocation::getSizeOrUnknown(MemVT.getStoreSize());
7581   MachineFunction &MF = getMachineFunction();
7582   MachineMemOperand *MMO = MF.getMachineMemOperand(PtrInfo, MMOFlags, Size,
7583                                                    Alignment, AAInfo, Ranges);
7584   return getLoad(AM, ExtType, VT, dl, Chain, Ptr, Offset, MemVT, MMO);
7585 }
7586 
7587 SDValue SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType,
7588                               EVT VT, const SDLoc &dl, SDValue Chain,
7589                               SDValue Ptr, SDValue Offset, EVT MemVT,
7590                               MachineMemOperand *MMO) {
7591   if (VT == MemVT) {
7592     ExtType = ISD::NON_EXTLOAD;
7593   } else if (ExtType == ISD::NON_EXTLOAD) {
7594     assert(VT == MemVT && "Non-extending load from different memory type!");
7595   } else {
7596     // Extending load.
7597     assert(MemVT.getScalarType().bitsLT(VT.getScalarType()) &&
7598            "Should only be an extending load, not truncating!");
7599     assert(VT.isInteger() == MemVT.isInteger() &&
7600            "Cannot convert from FP to Int or Int -> FP!");
7601     assert(VT.isVector() == MemVT.isVector() &&
7602            "Cannot use an ext load to convert to or from a vector!");
7603     assert((!VT.isVector() ||
7604             VT.getVectorElementCount() == MemVT.getVectorElementCount()) &&
7605            "Cannot use an ext load to change the number of vector elements!");
7606   }
7607 
7608   bool Indexed = AM != ISD::UNINDEXED;
7609   assert((Indexed || Offset.isUndef()) && "Unindexed load with an offset!");
7610 
7611   SDVTList VTs = Indexed ?
7612     getVTList(VT, Ptr.getValueType(), MVT::Other) : getVTList(VT, MVT::Other);
7613   SDValue Ops[] = { Chain, Ptr, Offset };
7614   FoldingSetNodeID ID;
7615   AddNodeIDNode(ID, ISD::LOAD, VTs, Ops);
7616   ID.AddInteger(MemVT.getRawBits());
7617   ID.AddInteger(getSyntheticNodeSubclassData<LoadSDNode>(
7618       dl.getIROrder(), VTs, AM, ExtType, MemVT, MMO));
7619   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7620   ID.AddInteger(MMO->getFlags());
7621   void *IP = nullptr;
7622   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7623     cast<LoadSDNode>(E)->refineAlignment(MMO);
7624     return SDValue(E, 0);
7625   }
7626   auto *N = newSDNode<LoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
7627                                   ExtType, MemVT, MMO);
7628   createOperands(N, Ops);
7629 
7630   CSEMap.InsertNode(N, IP);
7631   InsertNode(N);
7632   SDValue V(N, 0);
7633   NewSDValueDbgMsg(V, "Creating new node: ", this);
7634   return V;
7635 }
7636 
7637 SDValue SelectionDAG::getLoad(EVT VT, const SDLoc &dl, SDValue Chain,
7638                               SDValue Ptr, MachinePointerInfo PtrInfo,
7639                               MaybeAlign Alignment,
7640                               MachineMemOperand::Flags MMOFlags,
7641                               const AAMDNodes &AAInfo, const MDNode *Ranges) {
7642   SDValue Undef = getUNDEF(Ptr.getValueType());
7643   return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
7644                  PtrInfo, VT, Alignment, MMOFlags, AAInfo, Ranges);
7645 }
7646 
7647 SDValue SelectionDAG::getLoad(EVT VT, const SDLoc &dl, SDValue Chain,
7648                               SDValue Ptr, MachineMemOperand *MMO) {
7649   SDValue Undef = getUNDEF(Ptr.getValueType());
7650   return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
7651                  VT, MMO);
7652 }
7653 
7654 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl,
7655                                  EVT VT, SDValue Chain, SDValue Ptr,
7656                                  MachinePointerInfo PtrInfo, EVT MemVT,
7657                                  MaybeAlign Alignment,
7658                                  MachineMemOperand::Flags MMOFlags,
7659                                  const AAMDNodes &AAInfo) {
7660   SDValue Undef = getUNDEF(Ptr.getValueType());
7661   return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, PtrInfo,
7662                  MemVT, Alignment, MMOFlags, AAInfo);
7663 }
7664 
7665 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl,
7666                                  EVT VT, SDValue Chain, SDValue Ptr, EVT MemVT,
7667                                  MachineMemOperand *MMO) {
7668   SDValue Undef = getUNDEF(Ptr.getValueType());
7669   return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef,
7670                  MemVT, MMO);
7671 }
7672 
7673 SDValue SelectionDAG::getIndexedLoad(SDValue OrigLoad, const SDLoc &dl,
7674                                      SDValue Base, SDValue Offset,
7675                                      ISD::MemIndexedMode AM) {
7676   LoadSDNode *LD = cast<LoadSDNode>(OrigLoad);
7677   assert(LD->getOffset().isUndef() && "Load is already a indexed load!");
7678   // Don't propagate the invariant or dereferenceable flags.
7679   auto MMOFlags =
7680       LD->getMemOperand()->getFlags() &
7681       ~(MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable);
7682   return getLoad(AM, LD->getExtensionType(), OrigLoad.getValueType(), dl,
7683                  LD->getChain(), Base, Offset, LD->getPointerInfo(),
7684                  LD->getMemoryVT(), LD->getAlign(), MMOFlags, LD->getAAInfo());
7685 }
7686 
7687 SDValue SelectionDAG::getStore(SDValue Chain, const SDLoc &dl, SDValue Val,
7688                                SDValue Ptr, MachinePointerInfo PtrInfo,
7689                                Align Alignment,
7690                                MachineMemOperand::Flags MMOFlags,
7691                                const AAMDNodes &AAInfo) {
7692   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
7693 
7694   MMOFlags |= MachineMemOperand::MOStore;
7695   assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
7696 
7697   if (PtrInfo.V.isNull())
7698     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
7699 
7700   MachineFunction &MF = getMachineFunction();
7701   uint64_t Size =
7702       MemoryLocation::getSizeOrUnknown(Val.getValueType().getStoreSize());
7703   MachineMemOperand *MMO =
7704       MF.getMachineMemOperand(PtrInfo, MMOFlags, Size, Alignment, AAInfo);
7705   return getStore(Chain, dl, Val, Ptr, MMO);
7706 }
7707 
7708 SDValue SelectionDAG::getStore(SDValue Chain, const SDLoc &dl, SDValue Val,
7709                                SDValue Ptr, MachineMemOperand *MMO) {
7710   assert(Chain.getValueType() == MVT::Other &&
7711         "Invalid chain type");
7712   EVT VT = Val.getValueType();
7713   SDVTList VTs = getVTList(MVT::Other);
7714   SDValue Undef = getUNDEF(Ptr.getValueType());
7715   SDValue Ops[] = { Chain, Val, Ptr, Undef };
7716   FoldingSetNodeID ID;
7717   AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
7718   ID.AddInteger(VT.getRawBits());
7719   ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>(
7720       dl.getIROrder(), VTs, ISD::UNINDEXED, false, VT, MMO));
7721   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7722   ID.AddInteger(MMO->getFlags());
7723   void *IP = nullptr;
7724   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7725     cast<StoreSDNode>(E)->refineAlignment(MMO);
7726     return SDValue(E, 0);
7727   }
7728   auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
7729                                    ISD::UNINDEXED, false, VT, MMO);
7730   createOperands(N, Ops);
7731 
7732   CSEMap.InsertNode(N, IP);
7733   InsertNode(N);
7734   SDValue V(N, 0);
7735   NewSDValueDbgMsg(V, "Creating new node: ", this);
7736   return V;
7737 }
7738 
7739 SDValue SelectionDAG::getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val,
7740                                     SDValue Ptr, MachinePointerInfo PtrInfo,
7741                                     EVT SVT, Align Alignment,
7742                                     MachineMemOperand::Flags MMOFlags,
7743                                     const AAMDNodes &AAInfo) {
7744   assert(Chain.getValueType() == MVT::Other &&
7745         "Invalid chain type");
7746 
7747   MMOFlags |= MachineMemOperand::MOStore;
7748   assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
7749 
7750   if (PtrInfo.V.isNull())
7751     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
7752 
7753   MachineFunction &MF = getMachineFunction();
7754   MachineMemOperand *MMO = MF.getMachineMemOperand(
7755       PtrInfo, MMOFlags, MemoryLocation::getSizeOrUnknown(SVT.getStoreSize()),
7756       Alignment, AAInfo);
7757   return getTruncStore(Chain, dl, Val, Ptr, SVT, MMO);
7758 }
7759 
7760 SDValue SelectionDAG::getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val,
7761                                     SDValue Ptr, EVT SVT,
7762                                     MachineMemOperand *MMO) {
7763   EVT VT = Val.getValueType();
7764 
7765   assert(Chain.getValueType() == MVT::Other &&
7766         "Invalid chain type");
7767   if (VT == SVT)
7768     return getStore(Chain, dl, Val, Ptr, MMO);
7769 
7770   assert(SVT.getScalarType().bitsLT(VT.getScalarType()) &&
7771          "Should only be a truncating store, not extending!");
7772   assert(VT.isInteger() == SVT.isInteger() &&
7773          "Can't do FP-INT conversion!");
7774   assert(VT.isVector() == SVT.isVector() &&
7775          "Cannot use trunc store to convert to or from a vector!");
7776   assert((!VT.isVector() ||
7777           VT.getVectorElementCount() == SVT.getVectorElementCount()) &&
7778          "Cannot use trunc store to change the number of vector elements!");
7779 
7780   SDVTList VTs = getVTList(MVT::Other);
7781   SDValue Undef = getUNDEF(Ptr.getValueType());
7782   SDValue Ops[] = { Chain, Val, Ptr, Undef };
7783   FoldingSetNodeID ID;
7784   AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
7785   ID.AddInteger(SVT.getRawBits());
7786   ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>(
7787       dl.getIROrder(), VTs, ISD::UNINDEXED, true, SVT, MMO));
7788   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7789   ID.AddInteger(MMO->getFlags());
7790   void *IP = nullptr;
7791   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7792     cast<StoreSDNode>(E)->refineAlignment(MMO);
7793     return SDValue(E, 0);
7794   }
7795   auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
7796                                    ISD::UNINDEXED, true, SVT, MMO);
7797   createOperands(N, Ops);
7798 
7799   CSEMap.InsertNode(N, IP);
7800   InsertNode(N);
7801   SDValue V(N, 0);
7802   NewSDValueDbgMsg(V, "Creating new node: ", this);
7803   return V;
7804 }
7805 
7806 SDValue SelectionDAG::getIndexedStore(SDValue OrigStore, const SDLoc &dl,
7807                                       SDValue Base, SDValue Offset,
7808                                       ISD::MemIndexedMode AM) {
7809   StoreSDNode *ST = cast<StoreSDNode>(OrigStore);
7810   assert(ST->getOffset().isUndef() && "Store is already a indexed store!");
7811   SDVTList VTs = getVTList(Base.getValueType(), MVT::Other);
7812   SDValue Ops[] = { ST->getChain(), ST->getValue(), Base, Offset };
7813   FoldingSetNodeID ID;
7814   AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
7815   ID.AddInteger(ST->getMemoryVT().getRawBits());
7816   ID.AddInteger(ST->getRawSubclassData());
7817   ID.AddInteger(ST->getPointerInfo().getAddrSpace());
7818   ID.AddInteger(ST->getMemOperand()->getFlags());
7819   void *IP = nullptr;
7820   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
7821     return SDValue(E, 0);
7822 
7823   auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
7824                                    ST->isTruncatingStore(), ST->getMemoryVT(),
7825                                    ST->getMemOperand());
7826   createOperands(N, Ops);
7827 
7828   CSEMap.InsertNode(N, IP);
7829   InsertNode(N);
7830   SDValue V(N, 0);
7831   NewSDValueDbgMsg(V, "Creating new node: ", this);
7832   return V;
7833 }
7834 
7835 SDValue SelectionDAG::getLoadVP(
7836     ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, EVT VT, const SDLoc &dl,
7837     SDValue Chain, SDValue Ptr, SDValue Offset, SDValue Mask, SDValue EVL,
7838     MachinePointerInfo PtrInfo, EVT MemVT, Align Alignment,
7839     MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo,
7840     const MDNode *Ranges, bool IsExpanding) {
7841   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
7842 
7843   MMOFlags |= MachineMemOperand::MOLoad;
7844   assert((MMOFlags & MachineMemOperand::MOStore) == 0);
7845   // If we don't have a PtrInfo, infer the trivial frame index case to simplify
7846   // clients.
7847   if (PtrInfo.V.isNull())
7848     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr, Offset);
7849 
7850   uint64_t Size = MemoryLocation::getSizeOrUnknown(MemVT.getStoreSize());
7851   MachineFunction &MF = getMachineFunction();
7852   MachineMemOperand *MMO = MF.getMachineMemOperand(PtrInfo, MMOFlags, Size,
7853                                                    Alignment, AAInfo, Ranges);
7854   return getLoadVP(AM, ExtType, VT, dl, Chain, Ptr, Offset, Mask, EVL, MemVT,
7855                    MMO, IsExpanding);
7856 }
7857 
7858 SDValue SelectionDAG::getLoadVP(ISD::MemIndexedMode AM,
7859                                 ISD::LoadExtType ExtType, EVT VT,
7860                                 const SDLoc &dl, SDValue Chain, SDValue Ptr,
7861                                 SDValue Offset, SDValue Mask, SDValue EVL,
7862                                 EVT MemVT, MachineMemOperand *MMO,
7863                                 bool IsExpanding) {
7864   bool Indexed = AM != ISD::UNINDEXED;
7865   assert((Indexed || Offset.isUndef()) && "Unindexed load with an offset!");
7866 
7867   SDVTList VTs = Indexed ? getVTList(VT, Ptr.getValueType(), MVT::Other)
7868                          : getVTList(VT, MVT::Other);
7869   SDValue Ops[] = {Chain, Ptr, Offset, Mask, EVL};
7870   FoldingSetNodeID ID;
7871   AddNodeIDNode(ID, ISD::VP_LOAD, VTs, Ops);
7872   ID.AddInteger(VT.getRawBits());
7873   ID.AddInteger(getSyntheticNodeSubclassData<VPLoadSDNode>(
7874       dl.getIROrder(), VTs, AM, ExtType, IsExpanding, MemVT, MMO));
7875   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7876   ID.AddInteger(MMO->getFlags());
7877   void *IP = nullptr;
7878   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7879     cast<VPLoadSDNode>(E)->refineAlignment(MMO);
7880     return SDValue(E, 0);
7881   }
7882   auto *N = newSDNode<VPLoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
7883                                     ExtType, IsExpanding, MemVT, MMO);
7884   createOperands(N, Ops);
7885 
7886   CSEMap.InsertNode(N, IP);
7887   InsertNode(N);
7888   SDValue V(N, 0);
7889   NewSDValueDbgMsg(V, "Creating new node: ", this);
7890   return V;
7891 }
7892 
7893 SDValue SelectionDAG::getLoadVP(EVT VT, const SDLoc &dl, SDValue Chain,
7894                                 SDValue Ptr, SDValue Mask, SDValue EVL,
7895                                 MachinePointerInfo PtrInfo,
7896                                 MaybeAlign Alignment,
7897                                 MachineMemOperand::Flags MMOFlags,
7898                                 const AAMDNodes &AAInfo, const MDNode *Ranges,
7899                                 bool IsExpanding) {
7900   SDValue Undef = getUNDEF(Ptr.getValueType());
7901   return getLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
7902                    Mask, EVL, PtrInfo, VT, Alignment, MMOFlags, AAInfo, Ranges,
7903                    IsExpanding);
7904 }
7905 
7906 SDValue SelectionDAG::getLoadVP(EVT VT, const SDLoc &dl, SDValue Chain,
7907                                 SDValue Ptr, SDValue Mask, SDValue EVL,
7908                                 MachineMemOperand *MMO, bool IsExpanding) {
7909   SDValue Undef = getUNDEF(Ptr.getValueType());
7910   return getLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
7911                    Mask, EVL, VT, MMO, IsExpanding);
7912 }
7913 
7914 SDValue SelectionDAG::getExtLoadVP(ISD::LoadExtType ExtType, const SDLoc &dl,
7915                                    EVT VT, SDValue Chain, SDValue Ptr,
7916                                    SDValue Mask, SDValue EVL,
7917                                    MachinePointerInfo PtrInfo, EVT MemVT,
7918                                    MaybeAlign Alignment,
7919                                    MachineMemOperand::Flags MMOFlags,
7920                                    const AAMDNodes &AAInfo, bool IsExpanding) {
7921   SDValue Undef = getUNDEF(Ptr.getValueType());
7922   return getLoadVP(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, Mask,
7923                    EVL, PtrInfo, MemVT, Alignment, MMOFlags, AAInfo, nullptr,
7924                    IsExpanding);
7925 }
7926 
7927 SDValue SelectionDAG::getExtLoadVP(ISD::LoadExtType ExtType, const SDLoc &dl,
7928                                    EVT VT, SDValue Chain, SDValue Ptr,
7929                                    SDValue Mask, SDValue EVL, EVT MemVT,
7930                                    MachineMemOperand *MMO, bool IsExpanding) {
7931   SDValue Undef = getUNDEF(Ptr.getValueType());
7932   return getLoadVP(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, Mask,
7933                    EVL, MemVT, MMO, IsExpanding);
7934 }
7935 
7936 SDValue SelectionDAG::getIndexedLoadVP(SDValue OrigLoad, const SDLoc &dl,
7937                                        SDValue Base, SDValue Offset,
7938                                        ISD::MemIndexedMode AM) {
7939   auto *LD = cast<VPLoadSDNode>(OrigLoad);
7940   assert(LD->getOffset().isUndef() && "Load is already a indexed load!");
7941   // Don't propagate the invariant or dereferenceable flags.
7942   auto MMOFlags =
7943       LD->getMemOperand()->getFlags() &
7944       ~(MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable);
7945   return getLoadVP(AM, LD->getExtensionType(), OrigLoad.getValueType(), dl,
7946                    LD->getChain(), Base, Offset, LD->getMask(),
7947                    LD->getVectorLength(), LD->getPointerInfo(),
7948                    LD->getMemoryVT(), LD->getAlign(), MMOFlags, LD->getAAInfo(),
7949                    nullptr, LD->isExpandingLoad());
7950 }
7951 
7952 SDValue SelectionDAG::getStoreVP(SDValue Chain, const SDLoc &dl, SDValue Val,
7953                                  SDValue Ptr, SDValue Offset, SDValue Mask,
7954                                  SDValue EVL, EVT MemVT, MachineMemOperand *MMO,
7955                                  ISD::MemIndexedMode AM, bool IsTruncating,
7956                                  bool IsCompressing) {
7957   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
7958   bool Indexed = AM != ISD::UNINDEXED;
7959   assert((Indexed || Offset.isUndef()) && "Unindexed vp_store with an offset!");
7960   SDVTList VTs = Indexed ? getVTList(Ptr.getValueType(), MVT::Other)
7961                          : getVTList(MVT::Other);
7962   SDValue Ops[] = {Chain, Val, Ptr, Offset, Mask, EVL};
7963   FoldingSetNodeID ID;
7964   AddNodeIDNode(ID, ISD::VP_STORE, VTs, Ops);
7965   ID.AddInteger(MemVT.getRawBits());
7966   ID.AddInteger(getSyntheticNodeSubclassData<VPStoreSDNode>(
7967       dl.getIROrder(), VTs, AM, IsTruncating, IsCompressing, MemVT, MMO));
7968   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7969   ID.AddInteger(MMO->getFlags());
7970   void *IP = nullptr;
7971   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7972     cast<VPStoreSDNode>(E)->refineAlignment(MMO);
7973     return SDValue(E, 0);
7974   }
7975   auto *N = newSDNode<VPStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
7976                                      IsTruncating, IsCompressing, MemVT, MMO);
7977   createOperands(N, Ops);
7978 
7979   CSEMap.InsertNode(N, IP);
7980   InsertNode(N);
7981   SDValue V(N, 0);
7982   NewSDValueDbgMsg(V, "Creating new node: ", this);
7983   return V;
7984 }
7985 
7986 SDValue SelectionDAG::getTruncStoreVP(SDValue Chain, const SDLoc &dl,
7987                                       SDValue Val, SDValue Ptr, SDValue Mask,
7988                                       SDValue EVL, MachinePointerInfo PtrInfo,
7989                                       EVT SVT, Align Alignment,
7990                                       MachineMemOperand::Flags MMOFlags,
7991                                       const AAMDNodes &AAInfo,
7992                                       bool IsCompressing) {
7993   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
7994 
7995   MMOFlags |= MachineMemOperand::MOStore;
7996   assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
7997 
7998   if (PtrInfo.V.isNull())
7999     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
8000 
8001   MachineFunction &MF = getMachineFunction();
8002   MachineMemOperand *MMO = MF.getMachineMemOperand(
8003       PtrInfo, MMOFlags, MemoryLocation::getSizeOrUnknown(SVT.getStoreSize()),
8004       Alignment, AAInfo);
8005   return getTruncStoreVP(Chain, dl, Val, Ptr, Mask, EVL, SVT, MMO,
8006                          IsCompressing);
8007 }
8008 
8009 SDValue SelectionDAG::getTruncStoreVP(SDValue Chain, const SDLoc &dl,
8010                                       SDValue Val, SDValue Ptr, SDValue Mask,
8011                                       SDValue EVL, EVT SVT,
8012                                       MachineMemOperand *MMO,
8013                                       bool IsCompressing) {
8014   EVT VT = Val.getValueType();
8015 
8016   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
8017   if (VT == SVT)
8018     return getStoreVP(Chain, dl, Val, Ptr, getUNDEF(Ptr.getValueType()), Mask,
8019                       EVL, VT, MMO, ISD::UNINDEXED,
8020                       /*IsTruncating*/ false, IsCompressing);
8021 
8022   assert(SVT.getScalarType().bitsLT(VT.getScalarType()) &&
8023          "Should only be a truncating store, not extending!");
8024   assert(VT.isInteger() == SVT.isInteger() && "Can't do FP-INT conversion!");
8025   assert(VT.isVector() == SVT.isVector() &&
8026          "Cannot use trunc store to convert to or from a vector!");
8027   assert((!VT.isVector() ||
8028           VT.getVectorElementCount() == SVT.getVectorElementCount()) &&
8029          "Cannot use trunc store to change the number of vector elements!");
8030 
8031   SDVTList VTs = getVTList(MVT::Other);
8032   SDValue Undef = getUNDEF(Ptr.getValueType());
8033   SDValue Ops[] = {Chain, Val, Ptr, Undef, Mask, EVL};
8034   FoldingSetNodeID ID;
8035   AddNodeIDNode(ID, ISD::VP_STORE, VTs, Ops);
8036   ID.AddInteger(SVT.getRawBits());
8037   ID.AddInteger(getSyntheticNodeSubclassData<VPStoreSDNode>(
8038       dl.getIROrder(), VTs, ISD::UNINDEXED, true, IsCompressing, SVT, MMO));
8039   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8040   ID.AddInteger(MMO->getFlags());
8041   void *IP = nullptr;
8042   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
8043     cast<VPStoreSDNode>(E)->refineAlignment(MMO);
8044     return SDValue(E, 0);
8045   }
8046   auto *N =
8047       newSDNode<VPStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
8048                                ISD::UNINDEXED, true, IsCompressing, SVT, MMO);
8049   createOperands(N, Ops);
8050 
8051   CSEMap.InsertNode(N, IP);
8052   InsertNode(N);
8053   SDValue V(N, 0);
8054   NewSDValueDbgMsg(V, "Creating new node: ", this);
8055   return V;
8056 }
8057 
8058 SDValue SelectionDAG::getIndexedStoreVP(SDValue OrigStore, const SDLoc &dl,
8059                                         SDValue Base, SDValue Offset,
8060                                         ISD::MemIndexedMode AM) {
8061   auto *ST = cast<VPStoreSDNode>(OrigStore);
8062   assert(ST->getOffset().isUndef() && "Store is already an indexed store!");
8063   SDVTList VTs = getVTList(Base.getValueType(), MVT::Other);
8064   SDValue Ops[] = {ST->getChain(), ST->getValue(), Base,
8065                    Offset,         ST->getMask(),  ST->getVectorLength()};
8066   FoldingSetNodeID ID;
8067   AddNodeIDNode(ID, ISD::VP_STORE, VTs, Ops);
8068   ID.AddInteger(ST->getMemoryVT().getRawBits());
8069   ID.AddInteger(ST->getRawSubclassData());
8070   ID.AddInteger(ST->getPointerInfo().getAddrSpace());
8071   ID.AddInteger(ST->getMemOperand()->getFlags());
8072   void *IP = nullptr;
8073   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
8074     return SDValue(E, 0);
8075 
8076   auto *N = newSDNode<VPStoreSDNode>(
8077       dl.getIROrder(), dl.getDebugLoc(), VTs, AM, ST->isTruncatingStore(),
8078       ST->isCompressingStore(), ST->getMemoryVT(), ST->getMemOperand());
8079   createOperands(N, Ops);
8080 
8081   CSEMap.InsertNode(N, IP);
8082   InsertNode(N);
8083   SDValue V(N, 0);
8084   NewSDValueDbgMsg(V, "Creating new node: ", this);
8085   return V;
8086 }
8087 
8088 SDValue SelectionDAG::getGatherVP(SDVTList VTs, EVT VT, const SDLoc &dl,
8089                                   ArrayRef<SDValue> Ops, MachineMemOperand *MMO,
8090                                   ISD::MemIndexType IndexType) {
8091   assert(Ops.size() == 6 && "Incompatible number of operands");
8092 
8093   FoldingSetNodeID ID;
8094   AddNodeIDNode(ID, ISD::VP_GATHER, VTs, Ops);
8095   ID.AddInteger(VT.getRawBits());
8096   ID.AddInteger(getSyntheticNodeSubclassData<VPGatherSDNode>(
8097       dl.getIROrder(), VTs, VT, MMO, IndexType));
8098   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8099   ID.AddInteger(MMO->getFlags());
8100   void *IP = nullptr;
8101   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
8102     cast<VPGatherSDNode>(E)->refineAlignment(MMO);
8103     return SDValue(E, 0);
8104   }
8105 
8106   auto *N = newSDNode<VPGatherSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
8107                                       VT, MMO, IndexType);
8108   createOperands(N, Ops);
8109 
8110   assert(N->getMask().getValueType().getVectorElementCount() ==
8111              N->getValueType(0).getVectorElementCount() &&
8112          "Vector width mismatch between mask and data");
8113   assert(N->getIndex().getValueType().getVectorElementCount().isScalable() ==
8114              N->getValueType(0).getVectorElementCount().isScalable() &&
8115          "Scalable flags of index and data do not match");
8116   assert(ElementCount::isKnownGE(
8117              N->getIndex().getValueType().getVectorElementCount(),
8118              N->getValueType(0).getVectorElementCount()) &&
8119          "Vector width mismatch between index and data");
8120   assert(isa<ConstantSDNode>(N->getScale()) &&
8121          cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() &&
8122          "Scale should be a constant power of 2");
8123 
8124   CSEMap.InsertNode(N, IP);
8125   InsertNode(N);
8126   SDValue V(N, 0);
8127   NewSDValueDbgMsg(V, "Creating new node: ", this);
8128   return V;
8129 }
8130 
8131 SDValue SelectionDAG::getScatterVP(SDVTList VTs, EVT VT, const SDLoc &dl,
8132                                    ArrayRef<SDValue> Ops,
8133                                    MachineMemOperand *MMO,
8134                                    ISD::MemIndexType IndexType) {
8135   assert(Ops.size() == 7 && "Incompatible number of operands");
8136 
8137   FoldingSetNodeID ID;
8138   AddNodeIDNode(ID, ISD::VP_SCATTER, VTs, Ops);
8139   ID.AddInteger(VT.getRawBits());
8140   ID.AddInteger(getSyntheticNodeSubclassData<VPScatterSDNode>(
8141       dl.getIROrder(), VTs, VT, MMO, IndexType));
8142   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8143   ID.AddInteger(MMO->getFlags());
8144   void *IP = nullptr;
8145   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
8146     cast<VPScatterSDNode>(E)->refineAlignment(MMO);
8147     return SDValue(E, 0);
8148   }
8149   auto *N = newSDNode<VPScatterSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
8150                                        VT, MMO, IndexType);
8151   createOperands(N, Ops);
8152 
8153   assert(N->getMask().getValueType().getVectorElementCount() ==
8154              N->getValue().getValueType().getVectorElementCount() &&
8155          "Vector width mismatch between mask and data");
8156   assert(
8157       N->getIndex().getValueType().getVectorElementCount().isScalable() ==
8158           N->getValue().getValueType().getVectorElementCount().isScalable() &&
8159       "Scalable flags of index and data do not match");
8160   assert(ElementCount::isKnownGE(
8161              N->getIndex().getValueType().getVectorElementCount(),
8162              N->getValue().getValueType().getVectorElementCount()) &&
8163          "Vector width mismatch between index and data");
8164   assert(isa<ConstantSDNode>(N->getScale()) &&
8165          cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() &&
8166          "Scale should be a constant power of 2");
8167 
8168   CSEMap.InsertNode(N, IP);
8169   InsertNode(N);
8170   SDValue V(N, 0);
8171   NewSDValueDbgMsg(V, "Creating new node: ", this);
8172   return V;
8173 }
8174 
8175 SDValue SelectionDAG::getMaskedLoad(EVT VT, const SDLoc &dl, SDValue Chain,
8176                                     SDValue Base, SDValue Offset, SDValue Mask,
8177                                     SDValue PassThru, EVT MemVT,
8178                                     MachineMemOperand *MMO,
8179                                     ISD::MemIndexedMode AM,
8180                                     ISD::LoadExtType ExtTy, bool isExpanding) {
8181   bool Indexed = AM != ISD::UNINDEXED;
8182   assert((Indexed || Offset.isUndef()) &&
8183          "Unindexed masked load with an offset!");
8184   SDVTList VTs = Indexed ? getVTList(VT, Base.getValueType(), MVT::Other)
8185                          : getVTList(VT, MVT::Other);
8186   SDValue Ops[] = {Chain, Base, Offset, Mask, PassThru};
8187   FoldingSetNodeID ID;
8188   AddNodeIDNode(ID, ISD::MLOAD, VTs, Ops);
8189   ID.AddInteger(MemVT.getRawBits());
8190   ID.AddInteger(getSyntheticNodeSubclassData<MaskedLoadSDNode>(
8191       dl.getIROrder(), VTs, AM, ExtTy, isExpanding, MemVT, MMO));
8192   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8193   ID.AddInteger(MMO->getFlags());
8194   void *IP = nullptr;
8195   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
8196     cast<MaskedLoadSDNode>(E)->refineAlignment(MMO);
8197     return SDValue(E, 0);
8198   }
8199   auto *N = newSDNode<MaskedLoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
8200                                         AM, ExtTy, isExpanding, MemVT, MMO);
8201   createOperands(N, Ops);
8202 
8203   CSEMap.InsertNode(N, IP);
8204   InsertNode(N);
8205   SDValue V(N, 0);
8206   NewSDValueDbgMsg(V, "Creating new node: ", this);
8207   return V;
8208 }
8209 
8210 SDValue SelectionDAG::getIndexedMaskedLoad(SDValue OrigLoad, const SDLoc &dl,
8211                                            SDValue Base, SDValue Offset,
8212                                            ISD::MemIndexedMode AM) {
8213   MaskedLoadSDNode *LD = cast<MaskedLoadSDNode>(OrigLoad);
8214   assert(LD->getOffset().isUndef() && "Masked load is already a indexed load!");
8215   return getMaskedLoad(OrigLoad.getValueType(), dl, LD->getChain(), Base,
8216                        Offset, LD->getMask(), LD->getPassThru(),
8217                        LD->getMemoryVT(), LD->getMemOperand(), AM,
8218                        LD->getExtensionType(), LD->isExpandingLoad());
8219 }
8220 
8221 SDValue SelectionDAG::getMaskedStore(SDValue Chain, const SDLoc &dl,
8222                                      SDValue Val, SDValue Base, SDValue Offset,
8223                                      SDValue Mask, EVT MemVT,
8224                                      MachineMemOperand *MMO,
8225                                      ISD::MemIndexedMode AM, bool IsTruncating,
8226                                      bool IsCompressing) {
8227   assert(Chain.getValueType() == MVT::Other &&
8228         "Invalid chain type");
8229   bool Indexed = AM != ISD::UNINDEXED;
8230   assert((Indexed || Offset.isUndef()) &&
8231          "Unindexed masked store with an offset!");
8232   SDVTList VTs = Indexed ? getVTList(Base.getValueType(), MVT::Other)
8233                          : getVTList(MVT::Other);
8234   SDValue Ops[] = {Chain, Val, Base, Offset, Mask};
8235   FoldingSetNodeID ID;
8236   AddNodeIDNode(ID, ISD::MSTORE, VTs, Ops);
8237   ID.AddInteger(MemVT.getRawBits());
8238   ID.AddInteger(getSyntheticNodeSubclassData<MaskedStoreSDNode>(
8239       dl.getIROrder(), VTs, AM, IsTruncating, IsCompressing, MemVT, MMO));
8240   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8241   ID.AddInteger(MMO->getFlags());
8242   void *IP = nullptr;
8243   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
8244     cast<MaskedStoreSDNode>(E)->refineAlignment(MMO);
8245     return SDValue(E, 0);
8246   }
8247   auto *N =
8248       newSDNode<MaskedStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
8249                                    IsTruncating, IsCompressing, MemVT, MMO);
8250   createOperands(N, Ops);
8251 
8252   CSEMap.InsertNode(N, IP);
8253   InsertNode(N);
8254   SDValue V(N, 0);
8255   NewSDValueDbgMsg(V, "Creating new node: ", this);
8256   return V;
8257 }
8258 
8259 SDValue SelectionDAG::getIndexedMaskedStore(SDValue OrigStore, const SDLoc &dl,
8260                                             SDValue Base, SDValue Offset,
8261                                             ISD::MemIndexedMode AM) {
8262   MaskedStoreSDNode *ST = cast<MaskedStoreSDNode>(OrigStore);
8263   assert(ST->getOffset().isUndef() &&
8264          "Masked store is already a indexed store!");
8265   return getMaskedStore(ST->getChain(), dl, ST->getValue(), Base, Offset,
8266                         ST->getMask(), ST->getMemoryVT(), ST->getMemOperand(),
8267                         AM, ST->isTruncatingStore(), ST->isCompressingStore());
8268 }
8269 
8270 SDValue SelectionDAG::getMaskedGather(SDVTList VTs, EVT MemVT, const SDLoc &dl,
8271                                       ArrayRef<SDValue> Ops,
8272                                       MachineMemOperand *MMO,
8273                                       ISD::MemIndexType IndexType,
8274                                       ISD::LoadExtType ExtTy) {
8275   assert(Ops.size() == 6 && "Incompatible number of operands");
8276 
8277   FoldingSetNodeID ID;
8278   AddNodeIDNode(ID, ISD::MGATHER, VTs, Ops);
8279   ID.AddInteger(MemVT.getRawBits());
8280   ID.AddInteger(getSyntheticNodeSubclassData<MaskedGatherSDNode>(
8281       dl.getIROrder(), VTs, MemVT, MMO, IndexType, ExtTy));
8282   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8283   ID.AddInteger(MMO->getFlags());
8284   void *IP = nullptr;
8285   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
8286     cast<MaskedGatherSDNode>(E)->refineAlignment(MMO);
8287     return SDValue(E, 0);
8288   }
8289 
8290   IndexType = TLI->getCanonicalIndexType(IndexType, MemVT, Ops[4]);
8291   auto *N = newSDNode<MaskedGatherSDNode>(dl.getIROrder(), dl.getDebugLoc(),
8292                                           VTs, MemVT, MMO, IndexType, ExtTy);
8293   createOperands(N, Ops);
8294 
8295   assert(N->getPassThru().getValueType() == N->getValueType(0) &&
8296          "Incompatible type of the PassThru value in MaskedGatherSDNode");
8297   assert(N->getMask().getValueType().getVectorElementCount() ==
8298              N->getValueType(0).getVectorElementCount() &&
8299          "Vector width mismatch between mask and data");
8300   assert(N->getIndex().getValueType().getVectorElementCount().isScalable() ==
8301              N->getValueType(0).getVectorElementCount().isScalable() &&
8302          "Scalable flags of index and data do not match");
8303   assert(ElementCount::isKnownGE(
8304              N->getIndex().getValueType().getVectorElementCount(),
8305              N->getValueType(0).getVectorElementCount()) &&
8306          "Vector width mismatch between index and data");
8307   assert(isa<ConstantSDNode>(N->getScale()) &&
8308          cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() &&
8309          "Scale should be a constant power of 2");
8310 
8311   CSEMap.InsertNode(N, IP);
8312   InsertNode(N);
8313   SDValue V(N, 0);
8314   NewSDValueDbgMsg(V, "Creating new node: ", this);
8315   return V;
8316 }
8317 
8318 SDValue SelectionDAG::getMaskedScatter(SDVTList VTs, EVT MemVT, const SDLoc &dl,
8319                                        ArrayRef<SDValue> Ops,
8320                                        MachineMemOperand *MMO,
8321                                        ISD::MemIndexType IndexType,
8322                                        bool IsTrunc) {
8323   assert(Ops.size() == 6 && "Incompatible number of operands");
8324 
8325   FoldingSetNodeID ID;
8326   AddNodeIDNode(ID, ISD::MSCATTER, VTs, Ops);
8327   ID.AddInteger(MemVT.getRawBits());
8328   ID.AddInteger(getSyntheticNodeSubclassData<MaskedScatterSDNode>(
8329       dl.getIROrder(), VTs, MemVT, MMO, IndexType, IsTrunc));
8330   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8331   ID.AddInteger(MMO->getFlags());
8332   void *IP = nullptr;
8333   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
8334     cast<MaskedScatterSDNode>(E)->refineAlignment(MMO);
8335     return SDValue(E, 0);
8336   }
8337 
8338   IndexType = TLI->getCanonicalIndexType(IndexType, MemVT, Ops[4]);
8339   auto *N = newSDNode<MaskedScatterSDNode>(dl.getIROrder(), dl.getDebugLoc(),
8340                                            VTs, MemVT, MMO, IndexType, IsTrunc);
8341   createOperands(N, Ops);
8342 
8343   assert(N->getMask().getValueType().getVectorElementCount() ==
8344              N->getValue().getValueType().getVectorElementCount() &&
8345          "Vector width mismatch between mask and data");
8346   assert(
8347       N->getIndex().getValueType().getVectorElementCount().isScalable() ==
8348           N->getValue().getValueType().getVectorElementCount().isScalable() &&
8349       "Scalable flags of index and data do not match");
8350   assert(ElementCount::isKnownGE(
8351              N->getIndex().getValueType().getVectorElementCount(),
8352              N->getValue().getValueType().getVectorElementCount()) &&
8353          "Vector width mismatch between index and data");
8354   assert(isa<ConstantSDNode>(N->getScale()) &&
8355          cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() &&
8356          "Scale should be a constant power of 2");
8357 
8358   CSEMap.InsertNode(N, IP);
8359   InsertNode(N);
8360   SDValue V(N, 0);
8361   NewSDValueDbgMsg(V, "Creating new node: ", this);
8362   return V;
8363 }
8364 
8365 SDValue SelectionDAG::simplifySelect(SDValue Cond, SDValue T, SDValue F) {
8366   // select undef, T, F --> T (if T is a constant), otherwise F
8367   // select, ?, undef, F --> F
8368   // select, ?, T, undef --> T
8369   if (Cond.isUndef())
8370     return isConstantValueOfAnyType(T) ? T : F;
8371   if (T.isUndef())
8372     return F;
8373   if (F.isUndef())
8374     return T;
8375 
8376   // select true, T, F --> T
8377   // select false, T, F --> F
8378   if (auto *CondC = dyn_cast<ConstantSDNode>(Cond))
8379     return CondC->isZero() ? F : T;
8380 
8381   // TODO: This should simplify VSELECT with constant condition using something
8382   // like this (but check boolean contents to be complete?):
8383   //  if (ISD::isBuildVectorAllOnes(Cond.getNode()))
8384   //    return T;
8385   //  if (ISD::isBuildVectorAllZeros(Cond.getNode()))
8386   //    return F;
8387 
8388   // select ?, T, T --> T
8389   if (T == F)
8390     return T;
8391 
8392   return SDValue();
8393 }
8394 
8395 SDValue SelectionDAG::simplifyShift(SDValue X, SDValue Y) {
8396   // shift undef, Y --> 0 (can always assume that the undef value is 0)
8397   if (X.isUndef())
8398     return getConstant(0, SDLoc(X.getNode()), X.getValueType());
8399   // shift X, undef --> undef (because it may shift by the bitwidth)
8400   if (Y.isUndef())
8401     return getUNDEF(X.getValueType());
8402 
8403   // shift 0, Y --> 0
8404   // shift X, 0 --> X
8405   if (isNullOrNullSplat(X) || isNullOrNullSplat(Y))
8406     return X;
8407 
8408   // shift X, C >= bitwidth(X) --> undef
8409   // All vector elements must be too big (or undef) to avoid partial undefs.
8410   auto isShiftTooBig = [X](ConstantSDNode *Val) {
8411     return !Val || Val->getAPIntValue().uge(X.getScalarValueSizeInBits());
8412   };
8413   if (ISD::matchUnaryPredicate(Y, isShiftTooBig, true))
8414     return getUNDEF(X.getValueType());
8415 
8416   return SDValue();
8417 }
8418 
8419 SDValue SelectionDAG::simplifyFPBinop(unsigned Opcode, SDValue X, SDValue Y,
8420                                       SDNodeFlags Flags) {
8421   // If this operation has 'nnan' or 'ninf' and at least 1 disallowed operand
8422   // (an undef operand can be chosen to be Nan/Inf), then the result of this
8423   // operation is poison. That result can be relaxed to undef.
8424   ConstantFPSDNode *XC = isConstOrConstSplatFP(X, /* AllowUndefs */ true);
8425   ConstantFPSDNode *YC = isConstOrConstSplatFP(Y, /* AllowUndefs */ true);
8426   bool HasNan = (XC && XC->getValueAPF().isNaN()) ||
8427                 (YC && YC->getValueAPF().isNaN());
8428   bool HasInf = (XC && XC->getValueAPF().isInfinity()) ||
8429                 (YC && YC->getValueAPF().isInfinity());
8430 
8431   if (Flags.hasNoNaNs() && (HasNan || X.isUndef() || Y.isUndef()))
8432     return getUNDEF(X.getValueType());
8433 
8434   if (Flags.hasNoInfs() && (HasInf || X.isUndef() || Y.isUndef()))
8435     return getUNDEF(X.getValueType());
8436 
8437   if (!YC)
8438     return SDValue();
8439 
8440   // X + -0.0 --> X
8441   if (Opcode == ISD::FADD)
8442     if (YC->getValueAPF().isNegZero())
8443       return X;
8444 
8445   // X - +0.0 --> X
8446   if (Opcode == ISD::FSUB)
8447     if (YC->getValueAPF().isPosZero())
8448       return X;
8449 
8450   // X * 1.0 --> X
8451   // X / 1.0 --> X
8452   if (Opcode == ISD::FMUL || Opcode == ISD::FDIV)
8453     if (YC->getValueAPF().isExactlyValue(1.0))
8454       return X;
8455 
8456   // X * 0.0 --> 0.0
8457   if (Opcode == ISD::FMUL && Flags.hasNoNaNs() && Flags.hasNoSignedZeros())
8458     if (YC->getValueAPF().isZero())
8459       return getConstantFP(0.0, SDLoc(Y), Y.getValueType());
8460 
8461   return SDValue();
8462 }
8463 
8464 SDValue SelectionDAG::getVAArg(EVT VT, const SDLoc &dl, SDValue Chain,
8465                                SDValue Ptr, SDValue SV, unsigned Align) {
8466   SDValue Ops[] = { Chain, Ptr, SV, getTargetConstant(Align, dl, MVT::i32) };
8467   return getNode(ISD::VAARG, dl, getVTList(VT, MVT::Other), Ops);
8468 }
8469 
8470 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
8471                               ArrayRef<SDUse> Ops) {
8472   switch (Ops.size()) {
8473   case 0: return getNode(Opcode, DL, VT);
8474   case 1: return getNode(Opcode, DL, VT, static_cast<const SDValue>(Ops[0]));
8475   case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1]);
8476   case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2]);
8477   default: break;
8478   }
8479 
8480   // Copy from an SDUse array into an SDValue array for use with
8481   // the regular getNode logic.
8482   SmallVector<SDValue, 8> NewOps(Ops.begin(), Ops.end());
8483   return getNode(Opcode, DL, VT, NewOps);
8484 }
8485 
8486 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
8487                               ArrayRef<SDValue> Ops) {
8488   SDNodeFlags Flags;
8489   if (Inserter)
8490     Flags = Inserter->getFlags();
8491   return getNode(Opcode, DL, VT, Ops, Flags);
8492 }
8493 
8494 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
8495                               ArrayRef<SDValue> Ops, const SDNodeFlags Flags) {
8496   unsigned NumOps = Ops.size();
8497   switch (NumOps) {
8498   case 0: return getNode(Opcode, DL, VT);
8499   case 1: return getNode(Opcode, DL, VT, Ops[0], Flags);
8500   case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Flags);
8501   case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2], Flags);
8502   default: break;
8503   }
8504 
8505 #ifndef NDEBUG
8506   for (auto &Op : Ops)
8507     assert(Op.getOpcode() != ISD::DELETED_NODE &&
8508            "Operand is DELETED_NODE!");
8509 #endif
8510 
8511   switch (Opcode) {
8512   default: break;
8513   case ISD::BUILD_VECTOR:
8514     // Attempt to simplify BUILD_VECTOR.
8515     if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
8516       return V;
8517     break;
8518   case ISD::CONCAT_VECTORS:
8519     if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this))
8520       return V;
8521     break;
8522   case ISD::SELECT_CC:
8523     assert(NumOps == 5 && "SELECT_CC takes 5 operands!");
8524     assert(Ops[0].getValueType() == Ops[1].getValueType() &&
8525            "LHS and RHS of condition must have same type!");
8526     assert(Ops[2].getValueType() == Ops[3].getValueType() &&
8527            "True and False arms of SelectCC must have same type!");
8528     assert(Ops[2].getValueType() == VT &&
8529            "select_cc node must be of same type as true and false value!");
8530     break;
8531   case ISD::BR_CC:
8532     assert(NumOps == 5 && "BR_CC takes 5 operands!");
8533     assert(Ops[2].getValueType() == Ops[3].getValueType() &&
8534            "LHS/RHS of comparison should match types!");
8535     break;
8536   }
8537 
8538   // Memoize nodes.
8539   SDNode *N;
8540   SDVTList VTs = getVTList(VT);
8541 
8542   if (VT != MVT::Glue) {
8543     FoldingSetNodeID ID;
8544     AddNodeIDNode(ID, Opcode, VTs, Ops);
8545     void *IP = nullptr;
8546 
8547     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
8548       return SDValue(E, 0);
8549 
8550     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
8551     createOperands(N, Ops);
8552 
8553     CSEMap.InsertNode(N, IP);
8554   } else {
8555     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
8556     createOperands(N, Ops);
8557   }
8558 
8559   N->setFlags(Flags);
8560   InsertNode(N);
8561   SDValue V(N, 0);
8562   NewSDValueDbgMsg(V, "Creating new node: ", this);
8563   return V;
8564 }
8565 
8566 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL,
8567                               ArrayRef<EVT> ResultTys, ArrayRef<SDValue> Ops) {
8568   return getNode(Opcode, DL, getVTList(ResultTys), Ops);
8569 }
8570 
8571 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
8572                               ArrayRef<SDValue> Ops) {
8573   SDNodeFlags Flags;
8574   if (Inserter)
8575     Flags = Inserter->getFlags();
8576   return getNode(Opcode, DL, VTList, Ops, Flags);
8577 }
8578 
8579 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
8580                               ArrayRef<SDValue> Ops, const SDNodeFlags Flags) {
8581   if (VTList.NumVTs == 1)
8582     return getNode(Opcode, DL, VTList.VTs[0], Ops);
8583 
8584 #ifndef NDEBUG
8585   for (auto &Op : Ops)
8586     assert(Op.getOpcode() != ISD::DELETED_NODE &&
8587            "Operand is DELETED_NODE!");
8588 #endif
8589 
8590   switch (Opcode) {
8591   case ISD::STRICT_FP_EXTEND:
8592     assert(VTList.NumVTs == 2 && Ops.size() == 2 &&
8593            "Invalid STRICT_FP_EXTEND!");
8594     assert(VTList.VTs[0].isFloatingPoint() &&
8595            Ops[1].getValueType().isFloatingPoint() && "Invalid FP cast!");
8596     assert(VTList.VTs[0].isVector() == Ops[1].getValueType().isVector() &&
8597            "STRICT_FP_EXTEND result type should be vector iff the operand "
8598            "type is vector!");
8599     assert((!VTList.VTs[0].isVector() ||
8600             VTList.VTs[0].getVectorNumElements() ==
8601             Ops[1].getValueType().getVectorNumElements()) &&
8602            "Vector element count mismatch!");
8603     assert(Ops[1].getValueType().bitsLT(VTList.VTs[0]) &&
8604            "Invalid fpext node, dst <= src!");
8605     break;
8606   case ISD::STRICT_FP_ROUND:
8607     assert(VTList.NumVTs == 2 && Ops.size() == 3 && "Invalid STRICT_FP_ROUND!");
8608     assert(VTList.VTs[0].isVector() == Ops[1].getValueType().isVector() &&
8609            "STRICT_FP_ROUND result type should be vector iff the operand "
8610            "type is vector!");
8611     assert((!VTList.VTs[0].isVector() ||
8612             VTList.VTs[0].getVectorNumElements() ==
8613             Ops[1].getValueType().getVectorNumElements()) &&
8614            "Vector element count mismatch!");
8615     assert(VTList.VTs[0].isFloatingPoint() &&
8616            Ops[1].getValueType().isFloatingPoint() &&
8617            VTList.VTs[0].bitsLT(Ops[1].getValueType()) &&
8618            isa<ConstantSDNode>(Ops[2]) &&
8619            (cast<ConstantSDNode>(Ops[2])->getZExtValue() == 0 ||
8620             cast<ConstantSDNode>(Ops[2])->getZExtValue() == 1) &&
8621            "Invalid STRICT_FP_ROUND!");
8622     break;
8623 #if 0
8624   // FIXME: figure out how to safely handle things like
8625   // int foo(int x) { return 1 << (x & 255); }
8626   // int bar() { return foo(256); }
8627   case ISD::SRA_PARTS:
8628   case ISD::SRL_PARTS:
8629   case ISD::SHL_PARTS:
8630     if (N3.getOpcode() == ISD::SIGN_EXTEND_INREG &&
8631         cast<VTSDNode>(N3.getOperand(1))->getVT() != MVT::i1)
8632       return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0));
8633     else if (N3.getOpcode() == ISD::AND)
8634       if (ConstantSDNode *AndRHS = dyn_cast<ConstantSDNode>(N3.getOperand(1))) {
8635         // If the and is only masking out bits that cannot effect the shift,
8636         // eliminate the and.
8637         unsigned NumBits = VT.getScalarSizeInBits()*2;
8638         if ((AndRHS->getValue() & (NumBits-1)) == NumBits-1)
8639           return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0));
8640       }
8641     break;
8642 #endif
8643   }
8644 
8645   // Memoize the node unless it returns a flag.
8646   SDNode *N;
8647   if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) {
8648     FoldingSetNodeID ID;
8649     AddNodeIDNode(ID, Opcode, VTList, Ops);
8650     void *IP = nullptr;
8651     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
8652       return SDValue(E, 0);
8653 
8654     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList);
8655     createOperands(N, Ops);
8656     CSEMap.InsertNode(N, IP);
8657   } else {
8658     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList);
8659     createOperands(N, Ops);
8660   }
8661 
8662   N->setFlags(Flags);
8663   InsertNode(N);
8664   SDValue V(N, 0);
8665   NewSDValueDbgMsg(V, "Creating new node: ", this);
8666   return V;
8667 }
8668 
8669 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL,
8670                               SDVTList VTList) {
8671   return getNode(Opcode, DL, VTList, None);
8672 }
8673 
8674 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
8675                               SDValue N1) {
8676   SDValue Ops[] = { N1 };
8677   return getNode(Opcode, DL, VTList, Ops);
8678 }
8679 
8680 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
8681                               SDValue N1, SDValue N2) {
8682   SDValue Ops[] = { N1, N2 };
8683   return getNode(Opcode, DL, VTList, Ops);
8684 }
8685 
8686 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
8687                               SDValue N1, SDValue N2, SDValue N3) {
8688   SDValue Ops[] = { N1, N2, N3 };
8689   return getNode(Opcode, DL, VTList, Ops);
8690 }
8691 
8692 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
8693                               SDValue N1, SDValue N2, SDValue N3, SDValue N4) {
8694   SDValue Ops[] = { N1, N2, N3, N4 };
8695   return getNode(Opcode, DL, VTList, Ops);
8696 }
8697 
8698 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
8699                               SDValue N1, SDValue N2, SDValue N3, SDValue N4,
8700                               SDValue N5) {
8701   SDValue Ops[] = { N1, N2, N3, N4, N5 };
8702   return getNode(Opcode, DL, VTList, Ops);
8703 }
8704 
8705 SDVTList SelectionDAG::getVTList(EVT VT) {
8706   return makeVTList(SDNode::getValueTypeList(VT), 1);
8707 }
8708 
8709 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2) {
8710   FoldingSetNodeID ID;
8711   ID.AddInteger(2U);
8712   ID.AddInteger(VT1.getRawBits());
8713   ID.AddInteger(VT2.getRawBits());
8714 
8715   void *IP = nullptr;
8716   SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
8717   if (!Result) {
8718     EVT *Array = Allocator.Allocate<EVT>(2);
8719     Array[0] = VT1;
8720     Array[1] = VT2;
8721     Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 2);
8722     VTListMap.InsertNode(Result, IP);
8723   }
8724   return Result->getSDVTList();
8725 }
8726 
8727 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3) {
8728   FoldingSetNodeID ID;
8729   ID.AddInteger(3U);
8730   ID.AddInteger(VT1.getRawBits());
8731   ID.AddInteger(VT2.getRawBits());
8732   ID.AddInteger(VT3.getRawBits());
8733 
8734   void *IP = nullptr;
8735   SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
8736   if (!Result) {
8737     EVT *Array = Allocator.Allocate<EVT>(3);
8738     Array[0] = VT1;
8739     Array[1] = VT2;
8740     Array[2] = VT3;
8741     Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 3);
8742     VTListMap.InsertNode(Result, IP);
8743   }
8744   return Result->getSDVTList();
8745 }
8746 
8747 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3, EVT VT4) {
8748   FoldingSetNodeID ID;
8749   ID.AddInteger(4U);
8750   ID.AddInteger(VT1.getRawBits());
8751   ID.AddInteger(VT2.getRawBits());
8752   ID.AddInteger(VT3.getRawBits());
8753   ID.AddInteger(VT4.getRawBits());
8754 
8755   void *IP = nullptr;
8756   SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
8757   if (!Result) {
8758     EVT *Array = Allocator.Allocate<EVT>(4);
8759     Array[0] = VT1;
8760     Array[1] = VT2;
8761     Array[2] = VT3;
8762     Array[3] = VT4;
8763     Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 4);
8764     VTListMap.InsertNode(Result, IP);
8765   }
8766   return Result->getSDVTList();
8767 }
8768 
8769 SDVTList SelectionDAG::getVTList(ArrayRef<EVT> VTs) {
8770   unsigned NumVTs = VTs.size();
8771   FoldingSetNodeID ID;
8772   ID.AddInteger(NumVTs);
8773   for (unsigned index = 0; index < NumVTs; index++) {
8774     ID.AddInteger(VTs[index].getRawBits());
8775   }
8776 
8777   void *IP = nullptr;
8778   SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
8779   if (!Result) {
8780     EVT *Array = Allocator.Allocate<EVT>(NumVTs);
8781     llvm::copy(VTs, Array);
8782     Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, NumVTs);
8783     VTListMap.InsertNode(Result, IP);
8784   }
8785   return Result->getSDVTList();
8786 }
8787 
8788 
8789 /// UpdateNodeOperands - *Mutate* the specified node in-place to have the
8790 /// specified operands.  If the resultant node already exists in the DAG,
8791 /// this does not modify the specified node, instead it returns the node that
8792 /// already exists.  If the resultant node does not exist in the DAG, the
8793 /// input node is returned.  As a degenerate case, if you specify the same
8794 /// input operands as the node already has, the input node is returned.
8795 SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op) {
8796   assert(N->getNumOperands() == 1 && "Update with wrong number of operands");
8797 
8798   // Check to see if there is no change.
8799   if (Op == N->getOperand(0)) return N;
8800 
8801   // See if the modified node already exists.
8802   void *InsertPos = nullptr;
8803   if (SDNode *Existing = FindModifiedNodeSlot(N, Op, InsertPos))
8804     return Existing;
8805 
8806   // Nope it doesn't.  Remove the node from its current place in the maps.
8807   if (InsertPos)
8808     if (!RemoveNodeFromCSEMaps(N))
8809       InsertPos = nullptr;
8810 
8811   // Now we update the operands.
8812   N->OperandList[0].set(Op);
8813 
8814   updateDivergence(N);
8815   // If this gets put into a CSE map, add it.
8816   if (InsertPos) CSEMap.InsertNode(N, InsertPos);
8817   return N;
8818 }
8819 
8820 SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2) {
8821   assert(N->getNumOperands() == 2 && "Update with wrong number of operands");
8822 
8823   // Check to see if there is no change.
8824   if (Op1 == N->getOperand(0) && Op2 == N->getOperand(1))
8825     return N;   // No operands changed, just return the input node.
8826 
8827   // See if the modified node already exists.
8828   void *InsertPos = nullptr;
8829   if (SDNode *Existing = FindModifiedNodeSlot(N, Op1, Op2, InsertPos))
8830     return Existing;
8831 
8832   // Nope it doesn't.  Remove the node from its current place in the maps.
8833   if (InsertPos)
8834     if (!RemoveNodeFromCSEMaps(N))
8835       InsertPos = nullptr;
8836 
8837   // Now we update the operands.
8838   if (N->OperandList[0] != Op1)
8839     N->OperandList[0].set(Op1);
8840   if (N->OperandList[1] != Op2)
8841     N->OperandList[1].set(Op2);
8842 
8843   updateDivergence(N);
8844   // If this gets put into a CSE map, add it.
8845   if (InsertPos) CSEMap.InsertNode(N, InsertPos);
8846   return N;
8847 }
8848 
8849 SDNode *SelectionDAG::
8850 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2, SDValue Op3) {
8851   SDValue Ops[] = { Op1, Op2, Op3 };
8852   return UpdateNodeOperands(N, Ops);
8853 }
8854 
8855 SDNode *SelectionDAG::
8856 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2,
8857                    SDValue Op3, SDValue Op4) {
8858   SDValue Ops[] = { Op1, Op2, Op3, Op4 };
8859   return UpdateNodeOperands(N, Ops);
8860 }
8861 
8862 SDNode *SelectionDAG::
8863 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2,
8864                    SDValue Op3, SDValue Op4, SDValue Op5) {
8865   SDValue Ops[] = { Op1, Op2, Op3, Op4, Op5 };
8866   return UpdateNodeOperands(N, Ops);
8867 }
8868 
8869 SDNode *SelectionDAG::
8870 UpdateNodeOperands(SDNode *N, ArrayRef<SDValue> Ops) {
8871   unsigned NumOps = Ops.size();
8872   assert(N->getNumOperands() == NumOps &&
8873          "Update with wrong number of operands");
8874 
8875   // If no operands changed just return the input node.
8876   if (std::equal(Ops.begin(), Ops.end(), N->op_begin()))
8877     return N;
8878 
8879   // See if the modified node already exists.
8880   void *InsertPos = nullptr;
8881   if (SDNode *Existing = FindModifiedNodeSlot(N, Ops, InsertPos))
8882     return Existing;
8883 
8884   // Nope it doesn't.  Remove the node from its current place in the maps.
8885   if (InsertPos)
8886     if (!RemoveNodeFromCSEMaps(N))
8887       InsertPos = nullptr;
8888 
8889   // Now we update the operands.
8890   for (unsigned i = 0; i != NumOps; ++i)
8891     if (N->OperandList[i] != Ops[i])
8892       N->OperandList[i].set(Ops[i]);
8893 
8894   updateDivergence(N);
8895   // If this gets put into a CSE map, add it.
8896   if (InsertPos) CSEMap.InsertNode(N, InsertPos);
8897   return N;
8898 }
8899 
8900 /// DropOperands - Release the operands and set this node to have
8901 /// zero operands.
8902 void SDNode::DropOperands() {
8903   // Unlike the code in MorphNodeTo that does this, we don't need to
8904   // watch for dead nodes here.
8905   for (op_iterator I = op_begin(), E = op_end(); I != E; ) {
8906     SDUse &Use = *I++;
8907     Use.set(SDValue());
8908   }
8909 }
8910 
8911 void SelectionDAG::setNodeMemRefs(MachineSDNode *N,
8912                                   ArrayRef<MachineMemOperand *> NewMemRefs) {
8913   if (NewMemRefs.empty()) {
8914     N->clearMemRefs();
8915     return;
8916   }
8917 
8918   // Check if we can avoid allocating by storing a single reference directly.
8919   if (NewMemRefs.size() == 1) {
8920     N->MemRefs = NewMemRefs[0];
8921     N->NumMemRefs = 1;
8922     return;
8923   }
8924 
8925   MachineMemOperand **MemRefsBuffer =
8926       Allocator.template Allocate<MachineMemOperand *>(NewMemRefs.size());
8927   llvm::copy(NewMemRefs, MemRefsBuffer);
8928   N->MemRefs = MemRefsBuffer;
8929   N->NumMemRefs = static_cast<int>(NewMemRefs.size());
8930 }
8931 
8932 /// SelectNodeTo - These are wrappers around MorphNodeTo that accept a
8933 /// machine opcode.
8934 ///
8935 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8936                                    EVT VT) {
8937   SDVTList VTs = getVTList(VT);
8938   return SelectNodeTo(N, MachineOpc, VTs, None);
8939 }
8940 
8941 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8942                                    EVT VT, SDValue Op1) {
8943   SDVTList VTs = getVTList(VT);
8944   SDValue Ops[] = { Op1 };
8945   return SelectNodeTo(N, MachineOpc, VTs, Ops);
8946 }
8947 
8948 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8949                                    EVT VT, SDValue Op1,
8950                                    SDValue Op2) {
8951   SDVTList VTs = getVTList(VT);
8952   SDValue Ops[] = { Op1, Op2 };
8953   return SelectNodeTo(N, MachineOpc, VTs, Ops);
8954 }
8955 
8956 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8957                                    EVT VT, SDValue Op1,
8958                                    SDValue Op2, SDValue Op3) {
8959   SDVTList VTs = getVTList(VT);
8960   SDValue Ops[] = { Op1, Op2, Op3 };
8961   return SelectNodeTo(N, MachineOpc, VTs, Ops);
8962 }
8963 
8964 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8965                                    EVT VT, ArrayRef<SDValue> Ops) {
8966   SDVTList VTs = getVTList(VT);
8967   return SelectNodeTo(N, MachineOpc, VTs, Ops);
8968 }
8969 
8970 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8971                                    EVT VT1, EVT VT2, ArrayRef<SDValue> Ops) {
8972   SDVTList VTs = getVTList(VT1, VT2);
8973   return SelectNodeTo(N, MachineOpc, VTs, Ops);
8974 }
8975 
8976 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8977                                    EVT VT1, EVT VT2) {
8978   SDVTList VTs = getVTList(VT1, VT2);
8979   return SelectNodeTo(N, MachineOpc, VTs, None);
8980 }
8981 
8982 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8983                                    EVT VT1, EVT VT2, EVT VT3,
8984                                    ArrayRef<SDValue> Ops) {
8985   SDVTList VTs = getVTList(VT1, VT2, VT3);
8986   return SelectNodeTo(N, MachineOpc, VTs, Ops);
8987 }
8988 
8989 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8990                                    EVT VT1, EVT VT2,
8991                                    SDValue Op1, SDValue Op2) {
8992   SDVTList VTs = getVTList(VT1, VT2);
8993   SDValue Ops[] = { Op1, Op2 };
8994   return SelectNodeTo(N, MachineOpc, VTs, Ops);
8995 }
8996 
8997 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8998                                    SDVTList VTs,ArrayRef<SDValue> Ops) {
8999   SDNode *New = MorphNodeTo(N, ~MachineOpc, VTs, Ops);
9000   // Reset the NodeID to -1.
9001   New->setNodeId(-1);
9002   if (New != N) {
9003     ReplaceAllUsesWith(N, New);
9004     RemoveDeadNode(N);
9005   }
9006   return New;
9007 }
9008 
9009 /// UpdateSDLocOnMergeSDNode - If the opt level is -O0 then it throws away
9010 /// the line number information on the merged node since it is not possible to
9011 /// preserve the information that operation is associated with multiple lines.
9012 /// This will make the debugger working better at -O0, were there is a higher
9013 /// probability having other instructions associated with that line.
9014 ///
9015 /// For IROrder, we keep the smaller of the two
9016 SDNode *SelectionDAG::UpdateSDLocOnMergeSDNode(SDNode *N, const SDLoc &OLoc) {
9017   DebugLoc NLoc = N->getDebugLoc();
9018   if (NLoc && OptLevel == CodeGenOpt::None && OLoc.getDebugLoc() != NLoc) {
9019     N->setDebugLoc(DebugLoc());
9020   }
9021   unsigned Order = std::min(N->getIROrder(), OLoc.getIROrder());
9022   N->setIROrder(Order);
9023   return N;
9024 }
9025 
9026 /// MorphNodeTo - This *mutates* the specified node to have the specified
9027 /// return type, opcode, and operands.
9028 ///
9029 /// Note that MorphNodeTo returns the resultant node.  If there is already a
9030 /// node of the specified opcode and operands, it returns that node instead of
9031 /// the current one.  Note that the SDLoc need not be the same.
9032 ///
9033 /// Using MorphNodeTo is faster than creating a new node and swapping it in
9034 /// with ReplaceAllUsesWith both because it often avoids allocating a new
9035 /// node, and because it doesn't require CSE recalculation for any of
9036 /// the node's users.
9037 ///
9038 /// However, note that MorphNodeTo recursively deletes dead nodes from the DAG.
9039 /// As a consequence it isn't appropriate to use from within the DAG combiner or
9040 /// the legalizer which maintain worklists that would need to be updated when
9041 /// deleting things.
9042 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
9043                                   SDVTList VTs, ArrayRef<SDValue> Ops) {
9044   // If an identical node already exists, use it.
9045   void *IP = nullptr;
9046   if (VTs.VTs[VTs.NumVTs-1] != MVT::Glue) {
9047     FoldingSetNodeID ID;
9048     AddNodeIDNode(ID, Opc, VTs, Ops);
9049     if (SDNode *ON = FindNodeOrInsertPos(ID, SDLoc(N), IP))
9050       return UpdateSDLocOnMergeSDNode(ON, SDLoc(N));
9051   }
9052 
9053   if (!RemoveNodeFromCSEMaps(N))
9054     IP = nullptr;
9055 
9056   // Start the morphing.
9057   N->NodeType = Opc;
9058   N->ValueList = VTs.VTs;
9059   N->NumValues = VTs.NumVTs;
9060 
9061   // Clear the operands list, updating used nodes to remove this from their
9062   // use list.  Keep track of any operands that become dead as a result.
9063   SmallPtrSet<SDNode*, 16> DeadNodeSet;
9064   for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) {
9065     SDUse &Use = *I++;
9066     SDNode *Used = Use.getNode();
9067     Use.set(SDValue());
9068     if (Used->use_empty())
9069       DeadNodeSet.insert(Used);
9070   }
9071 
9072   // For MachineNode, initialize the memory references information.
9073   if (MachineSDNode *MN = dyn_cast<MachineSDNode>(N))
9074     MN->clearMemRefs();
9075 
9076   // Swap for an appropriately sized array from the recycler.
9077   removeOperands(N);
9078   createOperands(N, Ops);
9079 
9080   // Delete any nodes that are still dead after adding the uses for the
9081   // new operands.
9082   if (!DeadNodeSet.empty()) {
9083     SmallVector<SDNode *, 16> DeadNodes;
9084     for (SDNode *N : DeadNodeSet)
9085       if (N->use_empty())
9086         DeadNodes.push_back(N);
9087     RemoveDeadNodes(DeadNodes);
9088   }
9089 
9090   if (IP)
9091     CSEMap.InsertNode(N, IP);   // Memoize the new node.
9092   return N;
9093 }
9094 
9095 SDNode* SelectionDAG::mutateStrictFPToFP(SDNode *Node) {
9096   unsigned OrigOpc = Node->getOpcode();
9097   unsigned NewOpc;
9098   switch (OrigOpc) {
9099   default:
9100     llvm_unreachable("mutateStrictFPToFP called with unexpected opcode!");
9101 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN)               \
9102   case ISD::STRICT_##DAGN: NewOpc = ISD::DAGN; break;
9103 #define CMP_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN)               \
9104   case ISD::STRICT_##DAGN: NewOpc = ISD::SETCC; break;
9105 #include "llvm/IR/ConstrainedOps.def"
9106   }
9107 
9108   assert(Node->getNumValues() == 2 && "Unexpected number of results!");
9109 
9110   // We're taking this node out of the chain, so we need to re-link things.
9111   SDValue InputChain = Node->getOperand(0);
9112   SDValue OutputChain = SDValue(Node, 1);
9113   ReplaceAllUsesOfValueWith(OutputChain, InputChain);
9114 
9115   SmallVector<SDValue, 3> Ops;
9116   for (unsigned i = 1, e = Node->getNumOperands(); i != e; ++i)
9117     Ops.push_back(Node->getOperand(i));
9118 
9119   SDVTList VTs = getVTList(Node->getValueType(0));
9120   SDNode *Res = MorphNodeTo(Node, NewOpc, VTs, Ops);
9121 
9122   // MorphNodeTo can operate in two ways: if an existing node with the
9123   // specified operands exists, it can just return it.  Otherwise, it
9124   // updates the node in place to have the requested operands.
9125   if (Res == Node) {
9126     // If we updated the node in place, reset the node ID.  To the isel,
9127     // this should be just like a newly allocated machine node.
9128     Res->setNodeId(-1);
9129   } else {
9130     ReplaceAllUsesWith(Node, Res);
9131     RemoveDeadNode(Node);
9132   }
9133 
9134   return Res;
9135 }
9136 
9137 /// getMachineNode - These are used for target selectors to create a new node
9138 /// with specified return type(s), MachineInstr opcode, and operands.
9139 ///
9140 /// Note that getMachineNode returns the resultant node.  If there is already a
9141 /// node of the specified opcode and operands, it returns that node instead of
9142 /// the current one.
9143 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9144                                             EVT VT) {
9145   SDVTList VTs = getVTList(VT);
9146   return getMachineNode(Opcode, dl, VTs, None);
9147 }
9148 
9149 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9150                                             EVT VT, SDValue Op1) {
9151   SDVTList VTs = getVTList(VT);
9152   SDValue Ops[] = { Op1 };
9153   return getMachineNode(Opcode, dl, VTs, Ops);
9154 }
9155 
9156 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9157                                             EVT VT, SDValue Op1, SDValue Op2) {
9158   SDVTList VTs = getVTList(VT);
9159   SDValue Ops[] = { Op1, Op2 };
9160   return getMachineNode(Opcode, dl, VTs, Ops);
9161 }
9162 
9163 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9164                                             EVT VT, SDValue Op1, SDValue Op2,
9165                                             SDValue Op3) {
9166   SDVTList VTs = getVTList(VT);
9167   SDValue Ops[] = { Op1, Op2, Op3 };
9168   return getMachineNode(Opcode, dl, VTs, Ops);
9169 }
9170 
9171 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9172                                             EVT VT, ArrayRef<SDValue> Ops) {
9173   SDVTList VTs = getVTList(VT);
9174   return getMachineNode(Opcode, dl, VTs, Ops);
9175 }
9176 
9177 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9178                                             EVT VT1, EVT VT2, SDValue Op1,
9179                                             SDValue Op2) {
9180   SDVTList VTs = getVTList(VT1, VT2);
9181   SDValue Ops[] = { Op1, Op2 };
9182   return getMachineNode(Opcode, dl, VTs, Ops);
9183 }
9184 
9185 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9186                                             EVT VT1, EVT VT2, SDValue Op1,
9187                                             SDValue Op2, SDValue Op3) {
9188   SDVTList VTs = getVTList(VT1, VT2);
9189   SDValue Ops[] = { Op1, Op2, Op3 };
9190   return getMachineNode(Opcode, dl, VTs, Ops);
9191 }
9192 
9193 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9194                                             EVT VT1, EVT VT2,
9195                                             ArrayRef<SDValue> Ops) {
9196   SDVTList VTs = getVTList(VT1, VT2);
9197   return getMachineNode(Opcode, dl, VTs, Ops);
9198 }
9199 
9200 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9201                                             EVT VT1, EVT VT2, EVT VT3,
9202                                             SDValue Op1, SDValue Op2) {
9203   SDVTList VTs = getVTList(VT1, VT2, VT3);
9204   SDValue Ops[] = { Op1, Op2 };
9205   return getMachineNode(Opcode, dl, VTs, Ops);
9206 }
9207 
9208 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9209                                             EVT VT1, EVT VT2, EVT VT3,
9210                                             SDValue Op1, SDValue Op2,
9211                                             SDValue Op3) {
9212   SDVTList VTs = getVTList(VT1, VT2, VT3);
9213   SDValue Ops[] = { Op1, Op2, Op3 };
9214   return getMachineNode(Opcode, dl, VTs, Ops);
9215 }
9216 
9217 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9218                                             EVT VT1, EVT VT2, EVT VT3,
9219                                             ArrayRef<SDValue> Ops) {
9220   SDVTList VTs = getVTList(VT1, VT2, VT3);
9221   return getMachineNode(Opcode, dl, VTs, Ops);
9222 }
9223 
9224 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9225                                             ArrayRef<EVT> ResultTys,
9226                                             ArrayRef<SDValue> Ops) {
9227   SDVTList VTs = getVTList(ResultTys);
9228   return getMachineNode(Opcode, dl, VTs, Ops);
9229 }
9230 
9231 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &DL,
9232                                             SDVTList VTs,
9233                                             ArrayRef<SDValue> Ops) {
9234   bool DoCSE = VTs.VTs[VTs.NumVTs-1] != MVT::Glue;
9235   MachineSDNode *N;
9236   void *IP = nullptr;
9237 
9238   if (DoCSE) {
9239     FoldingSetNodeID ID;
9240     AddNodeIDNode(ID, ~Opcode, VTs, Ops);
9241     IP = nullptr;
9242     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
9243       return cast<MachineSDNode>(UpdateSDLocOnMergeSDNode(E, DL));
9244     }
9245   }
9246 
9247   // Allocate a new MachineSDNode.
9248   N = newSDNode<MachineSDNode>(~Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
9249   createOperands(N, Ops);
9250 
9251   if (DoCSE)
9252     CSEMap.InsertNode(N, IP);
9253 
9254   InsertNode(N);
9255   NewSDValueDbgMsg(SDValue(N, 0), "Creating new machine node: ", this);
9256   return N;
9257 }
9258 
9259 /// getTargetExtractSubreg - A convenience function for creating
9260 /// TargetOpcode::EXTRACT_SUBREG nodes.
9261 SDValue SelectionDAG::getTargetExtractSubreg(int SRIdx, const SDLoc &DL, EVT VT,
9262                                              SDValue Operand) {
9263   SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32);
9264   SDNode *Subreg = getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL,
9265                                   VT, Operand, SRIdxVal);
9266   return SDValue(Subreg, 0);
9267 }
9268 
9269 /// getTargetInsertSubreg - A convenience function for creating
9270 /// TargetOpcode::INSERT_SUBREG nodes.
9271 SDValue SelectionDAG::getTargetInsertSubreg(int SRIdx, const SDLoc &DL, EVT VT,
9272                                             SDValue Operand, SDValue Subreg) {
9273   SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32);
9274   SDNode *Result = getMachineNode(TargetOpcode::INSERT_SUBREG, DL,
9275                                   VT, Operand, Subreg, SRIdxVal);
9276   return SDValue(Result, 0);
9277 }
9278 
9279 /// getNodeIfExists - Get the specified node if it's already available, or
9280 /// else return NULL.
9281 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList,
9282                                       ArrayRef<SDValue> Ops) {
9283   SDNodeFlags Flags;
9284   if (Inserter)
9285     Flags = Inserter->getFlags();
9286   return getNodeIfExists(Opcode, VTList, Ops, Flags);
9287 }
9288 
9289 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList,
9290                                       ArrayRef<SDValue> Ops,
9291                                       const SDNodeFlags Flags) {
9292   if (VTList.VTs[VTList.NumVTs - 1] != MVT::Glue) {
9293     FoldingSetNodeID ID;
9294     AddNodeIDNode(ID, Opcode, VTList, Ops);
9295     void *IP = nullptr;
9296     if (SDNode *E = FindNodeOrInsertPos(ID, SDLoc(), IP)) {
9297       E->intersectFlagsWith(Flags);
9298       return E;
9299     }
9300   }
9301   return nullptr;
9302 }
9303 
9304 /// doesNodeExist - Check if a node exists without modifying its flags.
9305 bool SelectionDAG::doesNodeExist(unsigned Opcode, SDVTList VTList,
9306                                  ArrayRef<SDValue> Ops) {
9307   if (VTList.VTs[VTList.NumVTs - 1] != MVT::Glue) {
9308     FoldingSetNodeID ID;
9309     AddNodeIDNode(ID, Opcode, VTList, Ops);
9310     void *IP = nullptr;
9311     if (FindNodeOrInsertPos(ID, SDLoc(), IP))
9312       return true;
9313   }
9314   return false;
9315 }
9316 
9317 /// getDbgValue - Creates a SDDbgValue node.
9318 ///
9319 /// SDNode
9320 SDDbgValue *SelectionDAG::getDbgValue(DIVariable *Var, DIExpression *Expr,
9321                                       SDNode *N, unsigned R, bool IsIndirect,
9322                                       const DebugLoc &DL, unsigned O) {
9323   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
9324          "Expected inlined-at fields to agree");
9325   return new (DbgInfo->getAlloc())
9326       SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromNode(N, R),
9327                  {}, IsIndirect, DL, O,
9328                  /*IsVariadic=*/false);
9329 }
9330 
9331 /// Constant
9332 SDDbgValue *SelectionDAG::getConstantDbgValue(DIVariable *Var,
9333                                               DIExpression *Expr,
9334                                               const Value *C,
9335                                               const DebugLoc &DL, unsigned O) {
9336   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
9337          "Expected inlined-at fields to agree");
9338   return new (DbgInfo->getAlloc())
9339       SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromConst(C), {},
9340                  /*IsIndirect=*/false, DL, O,
9341                  /*IsVariadic=*/false);
9342 }
9343 
9344 /// FrameIndex
9345 SDDbgValue *SelectionDAG::getFrameIndexDbgValue(DIVariable *Var,
9346                                                 DIExpression *Expr, unsigned FI,
9347                                                 bool IsIndirect,
9348                                                 const DebugLoc &DL,
9349                                                 unsigned O) {
9350   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
9351          "Expected inlined-at fields to agree");
9352   return getFrameIndexDbgValue(Var, Expr, FI, {}, IsIndirect, DL, O);
9353 }
9354 
9355 /// FrameIndex with dependencies
9356 SDDbgValue *SelectionDAG::getFrameIndexDbgValue(DIVariable *Var,
9357                                                 DIExpression *Expr, unsigned FI,
9358                                                 ArrayRef<SDNode *> Dependencies,
9359                                                 bool IsIndirect,
9360                                                 const DebugLoc &DL,
9361                                                 unsigned O) {
9362   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
9363          "Expected inlined-at fields to agree");
9364   return new (DbgInfo->getAlloc())
9365       SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromFrameIdx(FI),
9366                  Dependencies, IsIndirect, DL, O,
9367                  /*IsVariadic=*/false);
9368 }
9369 
9370 /// VReg
9371 SDDbgValue *SelectionDAG::getVRegDbgValue(DIVariable *Var, DIExpression *Expr,
9372                                           unsigned VReg, bool IsIndirect,
9373                                           const DebugLoc &DL, unsigned O) {
9374   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
9375          "Expected inlined-at fields to agree");
9376   return new (DbgInfo->getAlloc())
9377       SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromVReg(VReg),
9378                  {}, IsIndirect, DL, O,
9379                  /*IsVariadic=*/false);
9380 }
9381 
9382 SDDbgValue *SelectionDAG::getDbgValueList(DIVariable *Var, DIExpression *Expr,
9383                                           ArrayRef<SDDbgOperand> Locs,
9384                                           ArrayRef<SDNode *> Dependencies,
9385                                           bool IsIndirect, const DebugLoc &DL,
9386                                           unsigned O, bool IsVariadic) {
9387   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
9388          "Expected inlined-at fields to agree");
9389   return new (DbgInfo->getAlloc())
9390       SDDbgValue(DbgInfo->getAlloc(), Var, Expr, Locs, Dependencies, IsIndirect,
9391                  DL, O, IsVariadic);
9392 }
9393 
9394 void SelectionDAG::transferDbgValues(SDValue From, SDValue To,
9395                                      unsigned OffsetInBits, unsigned SizeInBits,
9396                                      bool InvalidateDbg) {
9397   SDNode *FromNode = From.getNode();
9398   SDNode *ToNode = To.getNode();
9399   assert(FromNode && ToNode && "Can't modify dbg values");
9400 
9401   // PR35338
9402   // TODO: assert(From != To && "Redundant dbg value transfer");
9403   // TODO: assert(FromNode != ToNode && "Intranode dbg value transfer");
9404   if (From == To || FromNode == ToNode)
9405     return;
9406 
9407   if (!FromNode->getHasDebugValue())
9408     return;
9409 
9410   SDDbgOperand FromLocOp =
9411       SDDbgOperand::fromNode(From.getNode(), From.getResNo());
9412   SDDbgOperand ToLocOp = SDDbgOperand::fromNode(To.getNode(), To.getResNo());
9413 
9414   SmallVector<SDDbgValue *, 2> ClonedDVs;
9415   for (SDDbgValue *Dbg : GetDbgValues(FromNode)) {
9416     if (Dbg->isInvalidated())
9417       continue;
9418 
9419     // TODO: assert(!Dbg->isInvalidated() && "Transfer of invalid dbg value");
9420 
9421     // Create a new location ops vector that is equal to the old vector, but
9422     // with each instance of FromLocOp replaced with ToLocOp.
9423     bool Changed = false;
9424     auto NewLocOps = Dbg->copyLocationOps();
9425     std::replace_if(
9426         NewLocOps.begin(), NewLocOps.end(),
9427         [&Changed, FromLocOp](const SDDbgOperand &Op) {
9428           bool Match = Op == FromLocOp;
9429           Changed |= Match;
9430           return Match;
9431         },
9432         ToLocOp);
9433     // Ignore this SDDbgValue if we didn't find a matching location.
9434     if (!Changed)
9435       continue;
9436 
9437     DIVariable *Var = Dbg->getVariable();
9438     auto *Expr = Dbg->getExpression();
9439     // If a fragment is requested, update the expression.
9440     if (SizeInBits) {
9441       // When splitting a larger (e.g., sign-extended) value whose
9442       // lower bits are described with an SDDbgValue, do not attempt
9443       // to transfer the SDDbgValue to the upper bits.
9444       if (auto FI = Expr->getFragmentInfo())
9445         if (OffsetInBits + SizeInBits > FI->SizeInBits)
9446           continue;
9447       auto Fragment = DIExpression::createFragmentExpression(Expr, OffsetInBits,
9448                                                              SizeInBits);
9449       if (!Fragment)
9450         continue;
9451       Expr = *Fragment;
9452     }
9453 
9454     auto AdditionalDependencies = Dbg->getAdditionalDependencies();
9455     // Clone the SDDbgValue and move it to To.
9456     SDDbgValue *Clone = getDbgValueList(
9457         Var, Expr, NewLocOps, AdditionalDependencies, Dbg->isIndirect(),
9458         Dbg->getDebugLoc(), std::max(ToNode->getIROrder(), Dbg->getOrder()),
9459         Dbg->isVariadic());
9460     ClonedDVs.push_back(Clone);
9461 
9462     if (InvalidateDbg) {
9463       // Invalidate value and indicate the SDDbgValue should not be emitted.
9464       Dbg->setIsInvalidated();
9465       Dbg->setIsEmitted();
9466     }
9467   }
9468 
9469   for (SDDbgValue *Dbg : ClonedDVs) {
9470     assert(is_contained(Dbg->getSDNodes(), ToNode) &&
9471            "Transferred DbgValues should depend on the new SDNode");
9472     AddDbgValue(Dbg, false);
9473   }
9474 }
9475 
9476 void SelectionDAG::salvageDebugInfo(SDNode &N) {
9477   if (!N.getHasDebugValue())
9478     return;
9479 
9480   SmallVector<SDDbgValue *, 2> ClonedDVs;
9481   for (auto DV : GetDbgValues(&N)) {
9482     if (DV->isInvalidated())
9483       continue;
9484     switch (N.getOpcode()) {
9485     default:
9486       break;
9487     case ISD::ADD:
9488       SDValue N0 = N.getOperand(0);
9489       SDValue N1 = N.getOperand(1);
9490       if (!isConstantIntBuildVectorOrConstantInt(N0) &&
9491           isConstantIntBuildVectorOrConstantInt(N1)) {
9492         uint64_t Offset = N.getConstantOperandVal(1);
9493 
9494         // Rewrite an ADD constant node into a DIExpression. Since we are
9495         // performing arithmetic to compute the variable's *value* in the
9496         // DIExpression, we need to mark the expression with a
9497         // DW_OP_stack_value.
9498         auto *DIExpr = DV->getExpression();
9499         auto NewLocOps = DV->copyLocationOps();
9500         bool Changed = false;
9501         for (size_t i = 0; i < NewLocOps.size(); ++i) {
9502           // We're not given a ResNo to compare against because the whole
9503           // node is going away. We know that any ISD::ADD only has one
9504           // result, so we can assume any node match is using the result.
9505           if (NewLocOps[i].getKind() != SDDbgOperand::SDNODE ||
9506               NewLocOps[i].getSDNode() != &N)
9507             continue;
9508           NewLocOps[i] = SDDbgOperand::fromNode(N0.getNode(), N0.getResNo());
9509           SmallVector<uint64_t, 3> ExprOps;
9510           DIExpression::appendOffset(ExprOps, Offset);
9511           DIExpr = DIExpression::appendOpsToArg(DIExpr, ExprOps, i, true);
9512           Changed = true;
9513         }
9514         (void)Changed;
9515         assert(Changed && "Salvage target doesn't use N");
9516 
9517         auto AdditionalDependencies = DV->getAdditionalDependencies();
9518         SDDbgValue *Clone = getDbgValueList(DV->getVariable(), DIExpr,
9519                                             NewLocOps, AdditionalDependencies,
9520                                             DV->isIndirect(), DV->getDebugLoc(),
9521                                             DV->getOrder(), DV->isVariadic());
9522         ClonedDVs.push_back(Clone);
9523         DV->setIsInvalidated();
9524         DV->setIsEmitted();
9525         LLVM_DEBUG(dbgs() << "SALVAGE: Rewriting";
9526                    N0.getNode()->dumprFull(this);
9527                    dbgs() << " into " << *DIExpr << '\n');
9528       }
9529     }
9530   }
9531 
9532   for (SDDbgValue *Dbg : ClonedDVs) {
9533     assert(!Dbg->getSDNodes().empty() &&
9534            "Salvaged DbgValue should depend on a new SDNode");
9535     AddDbgValue(Dbg, false);
9536   }
9537 }
9538 
9539 /// Creates a SDDbgLabel node.
9540 SDDbgLabel *SelectionDAG::getDbgLabel(DILabel *Label,
9541                                       const DebugLoc &DL, unsigned O) {
9542   assert(cast<DILabel>(Label)->isValidLocationForIntrinsic(DL) &&
9543          "Expected inlined-at fields to agree");
9544   return new (DbgInfo->getAlloc()) SDDbgLabel(Label, DL, O);
9545 }
9546 
9547 namespace {
9548 
9549 /// RAUWUpdateListener - Helper for ReplaceAllUsesWith - When the node
9550 /// pointed to by a use iterator is deleted, increment the use iterator
9551 /// so that it doesn't dangle.
9552 ///
9553 class RAUWUpdateListener : public SelectionDAG::DAGUpdateListener {
9554   SDNode::use_iterator &UI;
9555   SDNode::use_iterator &UE;
9556 
9557   void NodeDeleted(SDNode *N, SDNode *E) override {
9558     // Increment the iterator as needed.
9559     while (UI != UE && N == *UI)
9560       ++UI;
9561   }
9562 
9563 public:
9564   RAUWUpdateListener(SelectionDAG &d,
9565                      SDNode::use_iterator &ui,
9566                      SDNode::use_iterator &ue)
9567     : SelectionDAG::DAGUpdateListener(d), UI(ui), UE(ue) {}
9568 };
9569 
9570 } // end anonymous namespace
9571 
9572 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
9573 /// This can cause recursive merging of nodes in the DAG.
9574 ///
9575 /// This version assumes From has a single result value.
9576 ///
9577 void SelectionDAG::ReplaceAllUsesWith(SDValue FromN, SDValue To) {
9578   SDNode *From = FromN.getNode();
9579   assert(From->getNumValues() == 1 && FromN.getResNo() == 0 &&
9580          "Cannot replace with this method!");
9581   assert(From != To.getNode() && "Cannot replace uses of with self");
9582 
9583   // Preserve Debug Values
9584   transferDbgValues(FromN, To);
9585 
9586   // Iterate over all the existing uses of From. New uses will be added
9587   // to the beginning of the use list, which we avoid visiting.
9588   // This specifically avoids visiting uses of From that arise while the
9589   // replacement is happening, because any such uses would be the result
9590   // of CSE: If an existing node looks like From after one of its operands
9591   // is replaced by To, we don't want to replace of all its users with To
9592   // too. See PR3018 for more info.
9593   SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
9594   RAUWUpdateListener Listener(*this, UI, UE);
9595   while (UI != UE) {
9596     SDNode *User = *UI;
9597 
9598     // This node is about to morph, remove its old self from the CSE maps.
9599     RemoveNodeFromCSEMaps(User);
9600 
9601     // A user can appear in a use list multiple times, and when this
9602     // happens the uses are usually next to each other in the list.
9603     // To help reduce the number of CSE recomputations, process all
9604     // the uses of this user that we can find this way.
9605     do {
9606       SDUse &Use = UI.getUse();
9607       ++UI;
9608       Use.set(To);
9609       if (To->isDivergent() != From->isDivergent())
9610         updateDivergence(User);
9611     } while (UI != UE && *UI == User);
9612     // Now that we have modified User, add it back to the CSE maps.  If it
9613     // already exists there, recursively merge the results together.
9614     AddModifiedNodeToCSEMaps(User);
9615   }
9616 
9617   // If we just RAUW'd the root, take note.
9618   if (FromN == getRoot())
9619     setRoot(To);
9620 }
9621 
9622 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
9623 /// This can cause recursive merging of nodes in the DAG.
9624 ///
9625 /// This version assumes that for each value of From, there is a
9626 /// corresponding value in To in the same position with the same type.
9627 ///
9628 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, SDNode *To) {
9629 #ifndef NDEBUG
9630   for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
9631     assert((!From->hasAnyUseOfValue(i) ||
9632             From->getValueType(i) == To->getValueType(i)) &&
9633            "Cannot use this version of ReplaceAllUsesWith!");
9634 #endif
9635 
9636   // Handle the trivial case.
9637   if (From == To)
9638     return;
9639 
9640   // Preserve Debug Info. Only do this if there's a use.
9641   for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
9642     if (From->hasAnyUseOfValue(i)) {
9643       assert((i < To->getNumValues()) && "Invalid To location");
9644       transferDbgValues(SDValue(From, i), SDValue(To, i));
9645     }
9646 
9647   // Iterate over just the existing users of From. See the comments in
9648   // the ReplaceAllUsesWith above.
9649   SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
9650   RAUWUpdateListener Listener(*this, UI, UE);
9651   while (UI != UE) {
9652     SDNode *User = *UI;
9653 
9654     // This node is about to morph, remove its old self from the CSE maps.
9655     RemoveNodeFromCSEMaps(User);
9656 
9657     // A user can appear in a use list multiple times, and when this
9658     // happens the uses are usually next to each other in the list.
9659     // To help reduce the number of CSE recomputations, process all
9660     // the uses of this user that we can find this way.
9661     do {
9662       SDUse &Use = UI.getUse();
9663       ++UI;
9664       Use.setNode(To);
9665       if (To->isDivergent() != From->isDivergent())
9666         updateDivergence(User);
9667     } while (UI != UE && *UI == User);
9668 
9669     // Now that we have modified User, add it back to the CSE maps.  If it
9670     // already exists there, recursively merge the results together.
9671     AddModifiedNodeToCSEMaps(User);
9672   }
9673 
9674   // If we just RAUW'd the root, take note.
9675   if (From == getRoot().getNode())
9676     setRoot(SDValue(To, getRoot().getResNo()));
9677 }
9678 
9679 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
9680 /// This can cause recursive merging of nodes in the DAG.
9681 ///
9682 /// This version can replace From with any result values.  To must match the
9683 /// number and types of values returned by From.
9684 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, const SDValue *To) {
9685   if (From->getNumValues() == 1)  // Handle the simple case efficiently.
9686     return ReplaceAllUsesWith(SDValue(From, 0), To[0]);
9687 
9688   // Preserve Debug Info.
9689   for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
9690     transferDbgValues(SDValue(From, i), To[i]);
9691 
9692   // Iterate over just the existing users of From. See the comments in
9693   // the ReplaceAllUsesWith above.
9694   SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
9695   RAUWUpdateListener Listener(*this, UI, UE);
9696   while (UI != UE) {
9697     SDNode *User = *UI;
9698 
9699     // This node is about to morph, remove its old self from the CSE maps.
9700     RemoveNodeFromCSEMaps(User);
9701 
9702     // A user can appear in a use list multiple times, and when this happens the
9703     // uses are usually next to each other in the list.  To help reduce the
9704     // number of CSE and divergence recomputations, process all the uses of this
9705     // user that we can find this way.
9706     bool To_IsDivergent = false;
9707     do {
9708       SDUse &Use = UI.getUse();
9709       const SDValue &ToOp = To[Use.getResNo()];
9710       ++UI;
9711       Use.set(ToOp);
9712       To_IsDivergent |= ToOp->isDivergent();
9713     } while (UI != UE && *UI == User);
9714 
9715     if (To_IsDivergent != From->isDivergent())
9716       updateDivergence(User);
9717 
9718     // Now that we have modified User, add it back to the CSE maps.  If it
9719     // already exists there, recursively merge the results together.
9720     AddModifiedNodeToCSEMaps(User);
9721   }
9722 
9723   // If we just RAUW'd the root, take note.
9724   if (From == getRoot().getNode())
9725     setRoot(SDValue(To[getRoot().getResNo()]));
9726 }
9727 
9728 /// ReplaceAllUsesOfValueWith - Replace any uses of From with To, leaving
9729 /// uses of other values produced by From.getNode() alone.  The Deleted
9730 /// vector is handled the same way as for ReplaceAllUsesWith.
9731 void SelectionDAG::ReplaceAllUsesOfValueWith(SDValue From, SDValue To){
9732   // Handle the really simple, really trivial case efficiently.
9733   if (From == To) return;
9734 
9735   // Handle the simple, trivial, case efficiently.
9736   if (From.getNode()->getNumValues() == 1) {
9737     ReplaceAllUsesWith(From, To);
9738     return;
9739   }
9740 
9741   // Preserve Debug Info.
9742   transferDbgValues(From, To);
9743 
9744   // Iterate over just the existing users of From. See the comments in
9745   // the ReplaceAllUsesWith above.
9746   SDNode::use_iterator UI = From.getNode()->use_begin(),
9747                        UE = From.getNode()->use_end();
9748   RAUWUpdateListener Listener(*this, UI, UE);
9749   while (UI != UE) {
9750     SDNode *User = *UI;
9751     bool UserRemovedFromCSEMaps = false;
9752 
9753     // A user can appear in a use list multiple times, and when this
9754     // happens the uses are usually next to each other in the list.
9755     // To help reduce the number of CSE recomputations, process all
9756     // the uses of this user that we can find this way.
9757     do {
9758       SDUse &Use = UI.getUse();
9759 
9760       // Skip uses of different values from the same node.
9761       if (Use.getResNo() != From.getResNo()) {
9762         ++UI;
9763         continue;
9764       }
9765 
9766       // If this node hasn't been modified yet, it's still in the CSE maps,
9767       // so remove its old self from the CSE maps.
9768       if (!UserRemovedFromCSEMaps) {
9769         RemoveNodeFromCSEMaps(User);
9770         UserRemovedFromCSEMaps = true;
9771       }
9772 
9773       ++UI;
9774       Use.set(To);
9775       if (To->isDivergent() != From->isDivergent())
9776         updateDivergence(User);
9777     } while (UI != UE && *UI == User);
9778     // We are iterating over all uses of the From node, so if a use
9779     // doesn't use the specific value, no changes are made.
9780     if (!UserRemovedFromCSEMaps)
9781       continue;
9782 
9783     // Now that we have modified User, add it back to the CSE maps.  If it
9784     // already exists there, recursively merge the results together.
9785     AddModifiedNodeToCSEMaps(User);
9786   }
9787 
9788   // If we just RAUW'd the root, take note.
9789   if (From == getRoot())
9790     setRoot(To);
9791 }
9792 
9793 namespace {
9794 
9795 /// UseMemo - This class is used by SelectionDAG::ReplaceAllUsesOfValuesWith
9796 /// to record information about a use.
9797 struct UseMemo {
9798   SDNode *User;
9799   unsigned Index;
9800   SDUse *Use;
9801 };
9802 
9803 /// operator< - Sort Memos by User.
9804 bool operator<(const UseMemo &L, const UseMemo &R) {
9805   return (intptr_t)L.User < (intptr_t)R.User;
9806 }
9807 
9808 /// RAUOVWUpdateListener - Helper for ReplaceAllUsesOfValuesWith - When the node
9809 /// pointed to by a UseMemo is deleted, set the User to nullptr to indicate that
9810 /// the node already has been taken care of recursively.
9811 class RAUOVWUpdateListener : public SelectionDAG::DAGUpdateListener {
9812   SmallVector<UseMemo, 4> &Uses;
9813 
9814   void NodeDeleted(SDNode *N, SDNode *E) override {
9815     for (UseMemo &Memo : Uses)
9816       if (Memo.User == N)
9817         Memo.User = nullptr;
9818   }
9819 
9820 public:
9821   RAUOVWUpdateListener(SelectionDAG &d, SmallVector<UseMemo, 4> &uses)
9822       : SelectionDAG::DAGUpdateListener(d), Uses(uses) {}
9823 };
9824 
9825 } // end anonymous namespace
9826 
9827 bool SelectionDAG::calculateDivergence(SDNode *N) {
9828   if (TLI->isSDNodeAlwaysUniform(N)) {
9829     assert(!TLI->isSDNodeSourceOfDivergence(N, FLI, DA) &&
9830            "Conflicting divergence information!");
9831     return false;
9832   }
9833   if (TLI->isSDNodeSourceOfDivergence(N, FLI, DA))
9834     return true;
9835   for (auto &Op : N->ops()) {
9836     if (Op.Val.getValueType() != MVT::Other && Op.getNode()->isDivergent())
9837       return true;
9838   }
9839   return false;
9840 }
9841 
9842 void SelectionDAG::updateDivergence(SDNode *N) {
9843   SmallVector<SDNode *, 16> Worklist(1, N);
9844   do {
9845     N = Worklist.pop_back_val();
9846     bool IsDivergent = calculateDivergence(N);
9847     if (N->SDNodeBits.IsDivergent != IsDivergent) {
9848       N->SDNodeBits.IsDivergent = IsDivergent;
9849       llvm::append_range(Worklist, N->uses());
9850     }
9851   } while (!Worklist.empty());
9852 }
9853 
9854 void SelectionDAG::CreateTopologicalOrder(std::vector<SDNode *> &Order) {
9855   DenseMap<SDNode *, unsigned> Degree;
9856   Order.reserve(AllNodes.size());
9857   for (auto &N : allnodes()) {
9858     unsigned NOps = N.getNumOperands();
9859     Degree[&N] = NOps;
9860     if (0 == NOps)
9861       Order.push_back(&N);
9862   }
9863   for (size_t I = 0; I != Order.size(); ++I) {
9864     SDNode *N = Order[I];
9865     for (auto U : N->uses()) {
9866       unsigned &UnsortedOps = Degree[U];
9867       if (0 == --UnsortedOps)
9868         Order.push_back(U);
9869     }
9870   }
9871 }
9872 
9873 #ifndef NDEBUG
9874 void SelectionDAG::VerifyDAGDivergence() {
9875   std::vector<SDNode *> TopoOrder;
9876   CreateTopologicalOrder(TopoOrder);
9877   for (auto *N : TopoOrder) {
9878     assert(calculateDivergence(N) == N->isDivergent() &&
9879            "Divergence bit inconsistency detected");
9880   }
9881 }
9882 #endif
9883 
9884 /// ReplaceAllUsesOfValuesWith - Replace any uses of From with To, leaving
9885 /// uses of other values produced by From.getNode() alone.  The same value
9886 /// may appear in both the From and To list.  The Deleted vector is
9887 /// handled the same way as for ReplaceAllUsesWith.
9888 void SelectionDAG::ReplaceAllUsesOfValuesWith(const SDValue *From,
9889                                               const SDValue *To,
9890                                               unsigned Num){
9891   // Handle the simple, trivial case efficiently.
9892   if (Num == 1)
9893     return ReplaceAllUsesOfValueWith(*From, *To);
9894 
9895   transferDbgValues(*From, *To);
9896 
9897   // Read up all the uses and make records of them. This helps
9898   // processing new uses that are introduced during the
9899   // replacement process.
9900   SmallVector<UseMemo, 4> Uses;
9901   for (unsigned i = 0; i != Num; ++i) {
9902     unsigned FromResNo = From[i].getResNo();
9903     SDNode *FromNode = From[i].getNode();
9904     for (SDNode::use_iterator UI = FromNode->use_begin(),
9905          E = FromNode->use_end(); UI != E; ++UI) {
9906       SDUse &Use = UI.getUse();
9907       if (Use.getResNo() == FromResNo) {
9908         UseMemo Memo = { *UI, i, &Use };
9909         Uses.push_back(Memo);
9910       }
9911     }
9912   }
9913 
9914   // Sort the uses, so that all the uses from a given User are together.
9915   llvm::sort(Uses);
9916   RAUOVWUpdateListener Listener(*this, Uses);
9917 
9918   for (unsigned UseIndex = 0, UseIndexEnd = Uses.size();
9919        UseIndex != UseIndexEnd; ) {
9920     // We know that this user uses some value of From.  If it is the right
9921     // value, update it.
9922     SDNode *User = Uses[UseIndex].User;
9923     // If the node has been deleted by recursive CSE updates when updating
9924     // another node, then just skip this entry.
9925     if (User == nullptr) {
9926       ++UseIndex;
9927       continue;
9928     }
9929 
9930     // This node is about to morph, remove its old self from the CSE maps.
9931     RemoveNodeFromCSEMaps(User);
9932 
9933     // The Uses array is sorted, so all the uses for a given User
9934     // are next to each other in the list.
9935     // To help reduce the number of CSE recomputations, process all
9936     // the uses of this user that we can find this way.
9937     do {
9938       unsigned i = Uses[UseIndex].Index;
9939       SDUse &Use = *Uses[UseIndex].Use;
9940       ++UseIndex;
9941 
9942       Use.set(To[i]);
9943     } while (UseIndex != UseIndexEnd && Uses[UseIndex].User == User);
9944 
9945     // Now that we have modified User, add it back to the CSE maps.  If it
9946     // already exists there, recursively merge the results together.
9947     AddModifiedNodeToCSEMaps(User);
9948   }
9949 }
9950 
9951 /// AssignTopologicalOrder - Assign a unique node id for each node in the DAG
9952 /// based on their topological order. It returns the maximum id and a vector
9953 /// of the SDNodes* in assigned order by reference.
9954 unsigned SelectionDAG::AssignTopologicalOrder() {
9955   unsigned DAGSize = 0;
9956 
9957   // SortedPos tracks the progress of the algorithm. Nodes before it are
9958   // sorted, nodes after it are unsorted. When the algorithm completes
9959   // it is at the end of the list.
9960   allnodes_iterator SortedPos = allnodes_begin();
9961 
9962   // Visit all the nodes. Move nodes with no operands to the front of
9963   // the list immediately. Annotate nodes that do have operands with their
9964   // operand count. Before we do this, the Node Id fields of the nodes
9965   // may contain arbitrary values. After, the Node Id fields for nodes
9966   // before SortedPos will contain the topological sort index, and the
9967   // Node Id fields for nodes At SortedPos and after will contain the
9968   // count of outstanding operands.
9969   for (SDNode &N : llvm::make_early_inc_range(allnodes())) {
9970     checkForCycles(&N, this);
9971     unsigned Degree = N.getNumOperands();
9972     if (Degree == 0) {
9973       // A node with no uses, add it to the result array immediately.
9974       N.setNodeId(DAGSize++);
9975       allnodes_iterator Q(&N);
9976       if (Q != SortedPos)
9977         SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(Q));
9978       assert(SortedPos != AllNodes.end() && "Overran node list");
9979       ++SortedPos;
9980     } else {
9981       // Temporarily use the Node Id as scratch space for the degree count.
9982       N.setNodeId(Degree);
9983     }
9984   }
9985 
9986   // Visit all the nodes. As we iterate, move nodes into sorted order,
9987   // such that by the time the end is reached all nodes will be sorted.
9988   for (SDNode &Node : allnodes()) {
9989     SDNode *N = &Node;
9990     checkForCycles(N, this);
9991     // N is in sorted position, so all its uses have one less operand
9992     // that needs to be sorted.
9993     for (SDNode *P : N->uses()) {
9994       unsigned Degree = P->getNodeId();
9995       assert(Degree != 0 && "Invalid node degree");
9996       --Degree;
9997       if (Degree == 0) {
9998         // All of P's operands are sorted, so P may sorted now.
9999         P->setNodeId(DAGSize++);
10000         if (P->getIterator() != SortedPos)
10001           SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(P));
10002         assert(SortedPos != AllNodes.end() && "Overran node list");
10003         ++SortedPos;
10004       } else {
10005         // Update P's outstanding operand count.
10006         P->setNodeId(Degree);
10007       }
10008     }
10009     if (Node.getIterator() == SortedPos) {
10010 #ifndef NDEBUG
10011       allnodes_iterator I(N);
10012       SDNode *S = &*++I;
10013       dbgs() << "Overran sorted position:\n";
10014       S->dumprFull(this); dbgs() << "\n";
10015       dbgs() << "Checking if this is due to cycles\n";
10016       checkForCycles(this, true);
10017 #endif
10018       llvm_unreachable(nullptr);
10019     }
10020   }
10021 
10022   assert(SortedPos == AllNodes.end() &&
10023          "Topological sort incomplete!");
10024   assert(AllNodes.front().getOpcode() == ISD::EntryToken &&
10025          "First node in topological sort is not the entry token!");
10026   assert(AllNodes.front().getNodeId() == 0 &&
10027          "First node in topological sort has non-zero id!");
10028   assert(AllNodes.front().getNumOperands() == 0 &&
10029          "First node in topological sort has operands!");
10030   assert(AllNodes.back().getNodeId() == (int)DAGSize-1 &&
10031          "Last node in topologic sort has unexpected id!");
10032   assert(AllNodes.back().use_empty() &&
10033          "Last node in topologic sort has users!");
10034   assert(DAGSize == allnodes_size() && "Node count mismatch!");
10035   return DAGSize;
10036 }
10037 
10038 /// AddDbgValue - Add a dbg_value SDNode. If SD is non-null that means the
10039 /// value is produced by SD.
10040 void SelectionDAG::AddDbgValue(SDDbgValue *DB, bool isParameter) {
10041   for (SDNode *SD : DB->getSDNodes()) {
10042     if (!SD)
10043       continue;
10044     assert(DbgInfo->getSDDbgValues(SD).empty() || SD->getHasDebugValue());
10045     SD->setHasDebugValue(true);
10046   }
10047   DbgInfo->add(DB, isParameter);
10048 }
10049 
10050 void SelectionDAG::AddDbgLabel(SDDbgLabel *DB) { DbgInfo->add(DB); }
10051 
10052 SDValue SelectionDAG::makeEquivalentMemoryOrdering(SDValue OldChain,
10053                                                    SDValue NewMemOpChain) {
10054   assert(isa<MemSDNode>(NewMemOpChain) && "Expected a memop node");
10055   assert(NewMemOpChain.getValueType() == MVT::Other && "Expected a token VT");
10056   // The new memory operation must have the same position as the old load in
10057   // terms of memory dependency. Create a TokenFactor for the old load and new
10058   // memory operation and update uses of the old load's output chain to use that
10059   // TokenFactor.
10060   if (OldChain == NewMemOpChain || OldChain.use_empty())
10061     return NewMemOpChain;
10062 
10063   SDValue TokenFactor = getNode(ISD::TokenFactor, SDLoc(OldChain), MVT::Other,
10064                                 OldChain, NewMemOpChain);
10065   ReplaceAllUsesOfValueWith(OldChain, TokenFactor);
10066   UpdateNodeOperands(TokenFactor.getNode(), OldChain, NewMemOpChain);
10067   return TokenFactor;
10068 }
10069 
10070 SDValue SelectionDAG::makeEquivalentMemoryOrdering(LoadSDNode *OldLoad,
10071                                                    SDValue NewMemOp) {
10072   assert(isa<MemSDNode>(NewMemOp.getNode()) && "Expected a memop node");
10073   SDValue OldChain = SDValue(OldLoad, 1);
10074   SDValue NewMemOpChain = NewMemOp.getValue(1);
10075   return makeEquivalentMemoryOrdering(OldChain, NewMemOpChain);
10076 }
10077 
10078 SDValue SelectionDAG::getSymbolFunctionGlobalAddress(SDValue Op,
10079                                                      Function **OutFunction) {
10080   assert(isa<ExternalSymbolSDNode>(Op) && "Node should be an ExternalSymbol");
10081 
10082   auto *Symbol = cast<ExternalSymbolSDNode>(Op)->getSymbol();
10083   auto *Module = MF->getFunction().getParent();
10084   auto *Function = Module->getFunction(Symbol);
10085 
10086   if (OutFunction != nullptr)
10087       *OutFunction = Function;
10088 
10089   if (Function != nullptr) {
10090     auto PtrTy = TLI->getPointerTy(getDataLayout(), Function->getAddressSpace());
10091     return getGlobalAddress(Function, SDLoc(Op), PtrTy);
10092   }
10093 
10094   std::string ErrorStr;
10095   raw_string_ostream ErrorFormatter(ErrorStr);
10096   ErrorFormatter << "Undefined external symbol ";
10097   ErrorFormatter << '"' << Symbol << '"';
10098   report_fatal_error(Twine(ErrorFormatter.str()));
10099 }
10100 
10101 //===----------------------------------------------------------------------===//
10102 //                              SDNode Class
10103 //===----------------------------------------------------------------------===//
10104 
10105 bool llvm::isNullConstant(SDValue V) {
10106   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
10107   return Const != nullptr && Const->isZero();
10108 }
10109 
10110 bool llvm::isNullFPConstant(SDValue V) {
10111   ConstantFPSDNode *Const = dyn_cast<ConstantFPSDNode>(V);
10112   return Const != nullptr && Const->isZero() && !Const->isNegative();
10113 }
10114 
10115 bool llvm::isAllOnesConstant(SDValue V) {
10116   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
10117   return Const != nullptr && Const->isAllOnes();
10118 }
10119 
10120 bool llvm::isOneConstant(SDValue V) {
10121   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
10122   return Const != nullptr && Const->isOne();
10123 }
10124 
10125 SDValue llvm::peekThroughBitcasts(SDValue V) {
10126   while (V.getOpcode() == ISD::BITCAST)
10127     V = V.getOperand(0);
10128   return V;
10129 }
10130 
10131 SDValue llvm::peekThroughOneUseBitcasts(SDValue V) {
10132   while (V.getOpcode() == ISD::BITCAST && V.getOperand(0).hasOneUse())
10133     V = V.getOperand(0);
10134   return V;
10135 }
10136 
10137 SDValue llvm::peekThroughExtractSubvectors(SDValue V) {
10138   while (V.getOpcode() == ISD::EXTRACT_SUBVECTOR)
10139     V = V.getOperand(0);
10140   return V;
10141 }
10142 
10143 bool llvm::isBitwiseNot(SDValue V, bool AllowUndefs) {
10144   if (V.getOpcode() != ISD::XOR)
10145     return false;
10146   V = peekThroughBitcasts(V.getOperand(1));
10147   unsigned NumBits = V.getScalarValueSizeInBits();
10148   ConstantSDNode *C =
10149       isConstOrConstSplat(V, AllowUndefs, /*AllowTruncation*/ true);
10150   return C && (C->getAPIntValue().countTrailingOnes() >= NumBits);
10151 }
10152 
10153 ConstantSDNode *llvm::isConstOrConstSplat(SDValue N, bool AllowUndefs,
10154                                           bool AllowTruncation) {
10155   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
10156     return CN;
10157 
10158   // SplatVectors can truncate their operands. Ignore that case here unless
10159   // AllowTruncation is set.
10160   if (N->getOpcode() == ISD::SPLAT_VECTOR) {
10161     EVT VecEltVT = N->getValueType(0).getVectorElementType();
10162     if (auto *CN = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
10163       EVT CVT = CN->getValueType(0);
10164       assert(CVT.bitsGE(VecEltVT) && "Illegal splat_vector element extension");
10165       if (AllowTruncation || CVT == VecEltVT)
10166         return CN;
10167     }
10168   }
10169 
10170   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
10171     BitVector UndefElements;
10172     ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
10173 
10174     // BuildVectors can truncate their operands. Ignore that case here unless
10175     // AllowTruncation is set.
10176     if (CN && (UndefElements.none() || AllowUndefs)) {
10177       EVT CVT = CN->getValueType(0);
10178       EVT NSVT = N.getValueType().getScalarType();
10179       assert(CVT.bitsGE(NSVT) && "Illegal build vector element extension");
10180       if (AllowTruncation || (CVT == NSVT))
10181         return CN;
10182     }
10183   }
10184 
10185   return nullptr;
10186 }
10187 
10188 ConstantSDNode *llvm::isConstOrConstSplat(SDValue N, const APInt &DemandedElts,
10189                                           bool AllowUndefs,
10190                                           bool AllowTruncation) {
10191   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
10192     return CN;
10193 
10194   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
10195     BitVector UndefElements;
10196     ConstantSDNode *CN = BV->getConstantSplatNode(DemandedElts, &UndefElements);
10197 
10198     // BuildVectors can truncate their operands. Ignore that case here unless
10199     // AllowTruncation is set.
10200     if (CN && (UndefElements.none() || AllowUndefs)) {
10201       EVT CVT = CN->getValueType(0);
10202       EVT NSVT = N.getValueType().getScalarType();
10203       assert(CVT.bitsGE(NSVT) && "Illegal build vector element extension");
10204       if (AllowTruncation || (CVT == NSVT))
10205         return CN;
10206     }
10207   }
10208 
10209   return nullptr;
10210 }
10211 
10212 ConstantFPSDNode *llvm::isConstOrConstSplatFP(SDValue N, bool AllowUndefs) {
10213   if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
10214     return CN;
10215 
10216   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
10217     BitVector UndefElements;
10218     ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements);
10219     if (CN && (UndefElements.none() || AllowUndefs))
10220       return CN;
10221   }
10222 
10223   if (N.getOpcode() == ISD::SPLAT_VECTOR)
10224     if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N.getOperand(0)))
10225       return CN;
10226 
10227   return nullptr;
10228 }
10229 
10230 ConstantFPSDNode *llvm::isConstOrConstSplatFP(SDValue N,
10231                                               const APInt &DemandedElts,
10232                                               bool AllowUndefs) {
10233   if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
10234     return CN;
10235 
10236   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
10237     BitVector UndefElements;
10238     ConstantFPSDNode *CN =
10239         BV->getConstantFPSplatNode(DemandedElts, &UndefElements);
10240     if (CN && (UndefElements.none() || AllowUndefs))
10241       return CN;
10242   }
10243 
10244   return nullptr;
10245 }
10246 
10247 bool llvm::isNullOrNullSplat(SDValue N, bool AllowUndefs) {
10248   // TODO: may want to use peekThroughBitcast() here.
10249   ConstantSDNode *C =
10250       isConstOrConstSplat(N, AllowUndefs, /*AllowTruncation=*/true);
10251   return C && C->isZero();
10252 }
10253 
10254 bool llvm::isOneOrOneSplat(SDValue N, bool AllowUndefs) {
10255   // TODO: may want to use peekThroughBitcast() here.
10256   unsigned BitWidth = N.getScalarValueSizeInBits();
10257   ConstantSDNode *C = isConstOrConstSplat(N, AllowUndefs);
10258   return C && C->isOne() && C->getValueSizeInBits(0) == BitWidth;
10259 }
10260 
10261 bool llvm::isAllOnesOrAllOnesSplat(SDValue N, bool AllowUndefs) {
10262   N = peekThroughBitcasts(N);
10263   unsigned BitWidth = N.getScalarValueSizeInBits();
10264   ConstantSDNode *C = isConstOrConstSplat(N, AllowUndefs);
10265   return C && C->isAllOnes() && C->getValueSizeInBits(0) == BitWidth;
10266 }
10267 
10268 HandleSDNode::~HandleSDNode() {
10269   DropOperands();
10270 }
10271 
10272 GlobalAddressSDNode::GlobalAddressSDNode(unsigned Opc, unsigned Order,
10273                                          const DebugLoc &DL,
10274                                          const GlobalValue *GA, EVT VT,
10275                                          int64_t o, unsigned TF)
10276     : SDNode(Opc, Order, DL, getSDVTList(VT)), Offset(o), TargetFlags(TF) {
10277   TheGlobal = GA;
10278 }
10279 
10280 AddrSpaceCastSDNode::AddrSpaceCastSDNode(unsigned Order, const DebugLoc &dl,
10281                                          EVT VT, unsigned SrcAS,
10282                                          unsigned DestAS)
10283     : SDNode(ISD::ADDRSPACECAST, Order, dl, getSDVTList(VT)),
10284       SrcAddrSpace(SrcAS), DestAddrSpace(DestAS) {}
10285 
10286 MemSDNode::MemSDNode(unsigned Opc, unsigned Order, const DebugLoc &dl,
10287                      SDVTList VTs, EVT memvt, MachineMemOperand *mmo)
10288     : SDNode(Opc, Order, dl, VTs), MemoryVT(memvt), MMO(mmo) {
10289   MemSDNodeBits.IsVolatile = MMO->isVolatile();
10290   MemSDNodeBits.IsNonTemporal = MMO->isNonTemporal();
10291   MemSDNodeBits.IsDereferenceable = MMO->isDereferenceable();
10292   MemSDNodeBits.IsInvariant = MMO->isInvariant();
10293 
10294   // We check here that the size of the memory operand fits within the size of
10295   // the MMO. This is because the MMO might indicate only a possible address
10296   // range instead of specifying the affected memory addresses precisely.
10297   // TODO: Make MachineMemOperands aware of scalable vectors.
10298   assert(memvt.getStoreSize().getKnownMinSize() <= MMO->getSize() &&
10299          "Size mismatch!");
10300 }
10301 
10302 /// Profile - Gather unique data for the node.
10303 ///
10304 void SDNode::Profile(FoldingSetNodeID &ID) const {
10305   AddNodeIDNode(ID, this);
10306 }
10307 
10308 namespace {
10309 
10310   struct EVTArray {
10311     std::vector<EVT> VTs;
10312 
10313     EVTArray() {
10314       VTs.reserve(MVT::VALUETYPE_SIZE);
10315       for (unsigned i = 0; i < MVT::VALUETYPE_SIZE; ++i)
10316         VTs.push_back(MVT((MVT::SimpleValueType)i));
10317     }
10318   };
10319 
10320 } // end anonymous namespace
10321 
10322 static ManagedStatic<std::set<EVT, EVT::compareRawBits>> EVTs;
10323 static ManagedStatic<EVTArray> SimpleVTArray;
10324 static ManagedStatic<sys::SmartMutex<true>> VTMutex;
10325 
10326 /// getValueTypeList - Return a pointer to the specified value type.
10327 ///
10328 const EVT *SDNode::getValueTypeList(EVT VT) {
10329   if (VT.isExtended()) {
10330     sys::SmartScopedLock<true> Lock(*VTMutex);
10331     return &(*EVTs->insert(VT).first);
10332   }
10333   assert(VT.getSimpleVT() < MVT::VALUETYPE_SIZE && "Value type out of range!");
10334   return &SimpleVTArray->VTs[VT.getSimpleVT().SimpleTy];
10335 }
10336 
10337 /// hasNUsesOfValue - Return true if there are exactly NUSES uses of the
10338 /// indicated value.  This method ignores uses of other values defined by this
10339 /// operation.
10340 bool SDNode::hasNUsesOfValue(unsigned NUses, unsigned Value) const {
10341   assert(Value < getNumValues() && "Bad value!");
10342 
10343   // TODO: Only iterate over uses of a given value of the node
10344   for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) {
10345     if (UI.getUse().getResNo() == Value) {
10346       if (NUses == 0)
10347         return false;
10348       --NUses;
10349     }
10350   }
10351 
10352   // Found exactly the right number of uses?
10353   return NUses == 0;
10354 }
10355 
10356 /// hasAnyUseOfValue - Return true if there are any use of the indicated
10357 /// value. This method ignores uses of other values defined by this operation.
10358 bool SDNode::hasAnyUseOfValue(unsigned Value) const {
10359   assert(Value < getNumValues() && "Bad value!");
10360 
10361   for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI)
10362     if (UI.getUse().getResNo() == Value)
10363       return true;
10364 
10365   return false;
10366 }
10367 
10368 /// isOnlyUserOf - Return true if this node is the only use of N.
10369 bool SDNode::isOnlyUserOf(const SDNode *N) const {
10370   bool Seen = false;
10371   for (const SDNode *User : N->uses()) {
10372     if (User == this)
10373       Seen = true;
10374     else
10375       return false;
10376   }
10377 
10378   return Seen;
10379 }
10380 
10381 /// Return true if the only users of N are contained in Nodes.
10382 bool SDNode::areOnlyUsersOf(ArrayRef<const SDNode *> Nodes, const SDNode *N) {
10383   bool Seen = false;
10384   for (const SDNode *User : N->uses()) {
10385     if (llvm::is_contained(Nodes, User))
10386       Seen = true;
10387     else
10388       return false;
10389   }
10390 
10391   return Seen;
10392 }
10393 
10394 /// isOperand - Return true if this node is an operand of N.
10395 bool SDValue::isOperandOf(const SDNode *N) const {
10396   return is_contained(N->op_values(), *this);
10397 }
10398 
10399 bool SDNode::isOperandOf(const SDNode *N) const {
10400   return any_of(N->op_values(),
10401                 [this](SDValue Op) { return this == Op.getNode(); });
10402 }
10403 
10404 /// reachesChainWithoutSideEffects - Return true if this operand (which must
10405 /// be a chain) reaches the specified operand without crossing any
10406 /// side-effecting instructions on any chain path.  In practice, this looks
10407 /// through token factors and non-volatile loads.  In order to remain efficient,
10408 /// this only looks a couple of nodes in, it does not do an exhaustive search.
10409 ///
10410 /// Note that we only need to examine chains when we're searching for
10411 /// side-effects; SelectionDAG requires that all side-effects are represented
10412 /// by chains, even if another operand would force a specific ordering. This
10413 /// constraint is necessary to allow transformations like splitting loads.
10414 bool SDValue::reachesChainWithoutSideEffects(SDValue Dest,
10415                                              unsigned Depth) const {
10416   if (*this == Dest) return true;
10417 
10418   // Don't search too deeply, we just want to be able to see through
10419   // TokenFactor's etc.
10420   if (Depth == 0) return false;
10421 
10422   // If this is a token factor, all inputs to the TF happen in parallel.
10423   if (getOpcode() == ISD::TokenFactor) {
10424     // First, try a shallow search.
10425     if (is_contained((*this)->ops(), Dest)) {
10426       // We found the chain we want as an operand of this TokenFactor.
10427       // Essentially, we reach the chain without side-effects if we could
10428       // serialize the TokenFactor into a simple chain of operations with
10429       // Dest as the last operation. This is automatically true if the
10430       // chain has one use: there are no other ordering constraints.
10431       // If the chain has more than one use, we give up: some other
10432       // use of Dest might force a side-effect between Dest and the current
10433       // node.
10434       if (Dest.hasOneUse())
10435         return true;
10436     }
10437     // Next, try a deep search: check whether every operand of the TokenFactor
10438     // reaches Dest.
10439     return llvm::all_of((*this)->ops(), [=](SDValue Op) {
10440       return Op.reachesChainWithoutSideEffects(Dest, Depth - 1);
10441     });
10442   }
10443 
10444   // Loads don't have side effects, look through them.
10445   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(*this)) {
10446     if (Ld->isUnordered())
10447       return Ld->getChain().reachesChainWithoutSideEffects(Dest, Depth-1);
10448   }
10449   return false;
10450 }
10451 
10452 bool SDNode::hasPredecessor(const SDNode *N) const {
10453   SmallPtrSet<const SDNode *, 32> Visited;
10454   SmallVector<const SDNode *, 16> Worklist;
10455   Worklist.push_back(this);
10456   return hasPredecessorHelper(N, Visited, Worklist);
10457 }
10458 
10459 void SDNode::intersectFlagsWith(const SDNodeFlags Flags) {
10460   this->Flags.intersectWith(Flags);
10461 }
10462 
10463 SDValue
10464 SelectionDAG::matchBinOpReduction(SDNode *Extract, ISD::NodeType &BinOp,
10465                                   ArrayRef<ISD::NodeType> CandidateBinOps,
10466                                   bool AllowPartials) {
10467   // The pattern must end in an extract from index 0.
10468   if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10469       !isNullConstant(Extract->getOperand(1)))
10470     return SDValue();
10471 
10472   // Match against one of the candidate binary ops.
10473   SDValue Op = Extract->getOperand(0);
10474   if (llvm::none_of(CandidateBinOps, [Op](ISD::NodeType BinOp) {
10475         return Op.getOpcode() == unsigned(BinOp);
10476       }))
10477     return SDValue();
10478 
10479   // Floating-point reductions may require relaxed constraints on the final step
10480   // of the reduction because they may reorder intermediate operations.
10481   unsigned CandidateBinOp = Op.getOpcode();
10482   if (Op.getValueType().isFloatingPoint()) {
10483     SDNodeFlags Flags = Op->getFlags();
10484     switch (CandidateBinOp) {
10485     case ISD::FADD:
10486       if (!Flags.hasNoSignedZeros() || !Flags.hasAllowReassociation())
10487         return SDValue();
10488       break;
10489     default:
10490       llvm_unreachable("Unhandled FP opcode for binop reduction");
10491     }
10492   }
10493 
10494   // Matching failed - attempt to see if we did enough stages that a partial
10495   // reduction from a subvector is possible.
10496   auto PartialReduction = [&](SDValue Op, unsigned NumSubElts) {
10497     if (!AllowPartials || !Op)
10498       return SDValue();
10499     EVT OpVT = Op.getValueType();
10500     EVT OpSVT = OpVT.getScalarType();
10501     EVT SubVT = EVT::getVectorVT(*getContext(), OpSVT, NumSubElts);
10502     if (!TLI->isExtractSubvectorCheap(SubVT, OpVT, 0))
10503       return SDValue();
10504     BinOp = (ISD::NodeType)CandidateBinOp;
10505     return getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(Op), SubVT, Op,
10506                    getVectorIdxConstant(0, SDLoc(Op)));
10507   };
10508 
10509   // At each stage, we're looking for something that looks like:
10510   // %s = shufflevector <8 x i32> %op, <8 x i32> undef,
10511   //                    <8 x i32> <i32 2, i32 3, i32 undef, i32 undef,
10512   //                               i32 undef, i32 undef, i32 undef, i32 undef>
10513   // %a = binop <8 x i32> %op, %s
10514   // Where the mask changes according to the stage. E.g. for a 3-stage pyramid,
10515   // we expect something like:
10516   // <4,5,6,7,u,u,u,u>
10517   // <2,3,u,u,u,u,u,u>
10518   // <1,u,u,u,u,u,u,u>
10519   // While a partial reduction match would be:
10520   // <2,3,u,u,u,u,u,u>
10521   // <1,u,u,u,u,u,u,u>
10522   unsigned Stages = Log2_32(Op.getValueType().getVectorNumElements());
10523   SDValue PrevOp;
10524   for (unsigned i = 0; i < Stages; ++i) {
10525     unsigned MaskEnd = (1 << i);
10526 
10527     if (Op.getOpcode() != CandidateBinOp)
10528       return PartialReduction(PrevOp, MaskEnd);
10529 
10530     SDValue Op0 = Op.getOperand(0);
10531     SDValue Op1 = Op.getOperand(1);
10532 
10533     ShuffleVectorSDNode *Shuffle = dyn_cast<ShuffleVectorSDNode>(Op0);
10534     if (Shuffle) {
10535       Op = Op1;
10536     } else {
10537       Shuffle = dyn_cast<ShuffleVectorSDNode>(Op1);
10538       Op = Op0;
10539     }
10540 
10541     // The first operand of the shuffle should be the same as the other operand
10542     // of the binop.
10543     if (!Shuffle || Shuffle->getOperand(0) != Op)
10544       return PartialReduction(PrevOp, MaskEnd);
10545 
10546     // Verify the shuffle has the expected (at this stage of the pyramid) mask.
10547     for (int Index = 0; Index < (int)MaskEnd; ++Index)
10548       if (Shuffle->getMaskElt(Index) != (int)(MaskEnd + Index))
10549         return PartialReduction(PrevOp, MaskEnd);
10550 
10551     PrevOp = Op;
10552   }
10553 
10554   // Handle subvector reductions, which tend to appear after the shuffle
10555   // reduction stages.
10556   while (Op.getOpcode() == CandidateBinOp) {
10557     unsigned NumElts = Op.getValueType().getVectorNumElements();
10558     SDValue Op0 = Op.getOperand(0);
10559     SDValue Op1 = Op.getOperand(1);
10560     if (Op0.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
10561         Op1.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
10562         Op0.getOperand(0) != Op1.getOperand(0))
10563       break;
10564     SDValue Src = Op0.getOperand(0);
10565     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
10566     if (NumSrcElts != (2 * NumElts))
10567       break;
10568     if (!(Op0.getConstantOperandAPInt(1) == 0 &&
10569           Op1.getConstantOperandAPInt(1) == NumElts) &&
10570         !(Op1.getConstantOperandAPInt(1) == 0 &&
10571           Op0.getConstantOperandAPInt(1) == NumElts))
10572       break;
10573     Op = Src;
10574   }
10575 
10576   BinOp = (ISD::NodeType)CandidateBinOp;
10577   return Op;
10578 }
10579 
10580 SDValue SelectionDAG::UnrollVectorOp(SDNode *N, unsigned ResNE) {
10581   assert(N->getNumValues() == 1 &&
10582          "Can't unroll a vector with multiple results!");
10583 
10584   EVT VT = N->getValueType(0);
10585   unsigned NE = VT.getVectorNumElements();
10586   EVT EltVT = VT.getVectorElementType();
10587   SDLoc dl(N);
10588 
10589   SmallVector<SDValue, 8> Scalars;
10590   SmallVector<SDValue, 4> Operands(N->getNumOperands());
10591 
10592   // If ResNE is 0, fully unroll the vector op.
10593   if (ResNE == 0)
10594     ResNE = NE;
10595   else if (NE > ResNE)
10596     NE = ResNE;
10597 
10598   unsigned i;
10599   for (i= 0; i != NE; ++i) {
10600     for (unsigned j = 0, e = N->getNumOperands(); j != e; ++j) {
10601       SDValue Operand = N->getOperand(j);
10602       EVT OperandVT = Operand.getValueType();
10603       if (OperandVT.isVector()) {
10604         // A vector operand; extract a single element.
10605         EVT OperandEltVT = OperandVT.getVectorElementType();
10606         Operands[j] = getNode(ISD::EXTRACT_VECTOR_ELT, dl, OperandEltVT,
10607                               Operand, getVectorIdxConstant(i, dl));
10608       } else {
10609         // A scalar operand; just use it as is.
10610         Operands[j] = Operand;
10611       }
10612     }
10613 
10614     switch (N->getOpcode()) {
10615     default: {
10616       Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands,
10617                                 N->getFlags()));
10618       break;
10619     }
10620     case ISD::VSELECT:
10621       Scalars.push_back(getNode(ISD::SELECT, dl, EltVT, Operands));
10622       break;
10623     case ISD::SHL:
10624     case ISD::SRA:
10625     case ISD::SRL:
10626     case ISD::ROTL:
10627     case ISD::ROTR:
10628       Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands[0],
10629                                getShiftAmountOperand(Operands[0].getValueType(),
10630                                                      Operands[1])));
10631       break;
10632     case ISD::SIGN_EXTEND_INREG: {
10633       EVT ExtVT = cast<VTSDNode>(Operands[1])->getVT().getVectorElementType();
10634       Scalars.push_back(getNode(N->getOpcode(), dl, EltVT,
10635                                 Operands[0],
10636                                 getValueType(ExtVT)));
10637     }
10638     }
10639   }
10640 
10641   for (; i < ResNE; ++i)
10642     Scalars.push_back(getUNDEF(EltVT));
10643 
10644   EVT VecVT = EVT::getVectorVT(*getContext(), EltVT, ResNE);
10645   return getBuildVector(VecVT, dl, Scalars);
10646 }
10647 
10648 std::pair<SDValue, SDValue> SelectionDAG::UnrollVectorOverflowOp(
10649     SDNode *N, unsigned ResNE) {
10650   unsigned Opcode = N->getOpcode();
10651   assert((Opcode == ISD::UADDO || Opcode == ISD::SADDO ||
10652           Opcode == ISD::USUBO || Opcode == ISD::SSUBO ||
10653           Opcode == ISD::UMULO || Opcode == ISD::SMULO) &&
10654          "Expected an overflow opcode");
10655 
10656   EVT ResVT = N->getValueType(0);
10657   EVT OvVT = N->getValueType(1);
10658   EVT ResEltVT = ResVT.getVectorElementType();
10659   EVT OvEltVT = OvVT.getVectorElementType();
10660   SDLoc dl(N);
10661 
10662   // If ResNE is 0, fully unroll the vector op.
10663   unsigned NE = ResVT.getVectorNumElements();
10664   if (ResNE == 0)
10665     ResNE = NE;
10666   else if (NE > ResNE)
10667     NE = ResNE;
10668 
10669   SmallVector<SDValue, 8> LHSScalars;
10670   SmallVector<SDValue, 8> RHSScalars;
10671   ExtractVectorElements(N->getOperand(0), LHSScalars, 0, NE);
10672   ExtractVectorElements(N->getOperand(1), RHSScalars, 0, NE);
10673 
10674   EVT SVT = TLI->getSetCCResultType(getDataLayout(), *getContext(), ResEltVT);
10675   SDVTList VTs = getVTList(ResEltVT, SVT);
10676   SmallVector<SDValue, 8> ResScalars;
10677   SmallVector<SDValue, 8> OvScalars;
10678   for (unsigned i = 0; i < NE; ++i) {
10679     SDValue Res = getNode(Opcode, dl, VTs, LHSScalars[i], RHSScalars[i]);
10680     SDValue Ov =
10681         getSelect(dl, OvEltVT, Res.getValue(1),
10682                   getBoolConstant(true, dl, OvEltVT, ResVT),
10683                   getConstant(0, dl, OvEltVT));
10684 
10685     ResScalars.push_back(Res);
10686     OvScalars.push_back(Ov);
10687   }
10688 
10689   ResScalars.append(ResNE - NE, getUNDEF(ResEltVT));
10690   OvScalars.append(ResNE - NE, getUNDEF(OvEltVT));
10691 
10692   EVT NewResVT = EVT::getVectorVT(*getContext(), ResEltVT, ResNE);
10693   EVT NewOvVT = EVT::getVectorVT(*getContext(), OvEltVT, ResNE);
10694   return std::make_pair(getBuildVector(NewResVT, dl, ResScalars),
10695                         getBuildVector(NewOvVT, dl, OvScalars));
10696 }
10697 
10698 bool SelectionDAG::areNonVolatileConsecutiveLoads(LoadSDNode *LD,
10699                                                   LoadSDNode *Base,
10700                                                   unsigned Bytes,
10701                                                   int Dist) const {
10702   if (LD->isVolatile() || Base->isVolatile())
10703     return false;
10704   // TODO: probably too restrictive for atomics, revisit
10705   if (!LD->isSimple())
10706     return false;
10707   if (LD->isIndexed() || Base->isIndexed())
10708     return false;
10709   if (LD->getChain() != Base->getChain())
10710     return false;
10711   EVT VT = LD->getValueType(0);
10712   if (VT.getSizeInBits() / 8 != Bytes)
10713     return false;
10714 
10715   auto BaseLocDecomp = BaseIndexOffset::match(Base, *this);
10716   auto LocDecomp = BaseIndexOffset::match(LD, *this);
10717 
10718   int64_t Offset = 0;
10719   if (BaseLocDecomp.equalBaseIndex(LocDecomp, *this, Offset))
10720     return (Dist * Bytes == Offset);
10721   return false;
10722 }
10723 
10724 /// InferPtrAlignment - Infer alignment of a load / store address. Return None
10725 /// if it cannot be inferred.
10726 MaybeAlign SelectionDAG::InferPtrAlign(SDValue Ptr) const {
10727   // If this is a GlobalAddress + cst, return the alignment.
10728   const GlobalValue *GV = nullptr;
10729   int64_t GVOffset = 0;
10730   if (TLI->isGAPlusOffset(Ptr.getNode(), GV, GVOffset)) {
10731     unsigned PtrWidth = getDataLayout().getPointerTypeSizeInBits(GV->getType());
10732     KnownBits Known(PtrWidth);
10733     llvm::computeKnownBits(GV, Known, getDataLayout());
10734     unsigned AlignBits = Known.countMinTrailingZeros();
10735     if (AlignBits)
10736       return commonAlignment(Align(1ull << std::min(31U, AlignBits)), GVOffset);
10737   }
10738 
10739   // If this is a direct reference to a stack slot, use information about the
10740   // stack slot's alignment.
10741   int FrameIdx = INT_MIN;
10742   int64_t FrameOffset = 0;
10743   if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr)) {
10744     FrameIdx = FI->getIndex();
10745   } else if (isBaseWithConstantOffset(Ptr) &&
10746              isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
10747     // Handle FI+Cst
10748     FrameIdx = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
10749     FrameOffset = Ptr.getConstantOperandVal(1);
10750   }
10751 
10752   if (FrameIdx != INT_MIN) {
10753     const MachineFrameInfo &MFI = getMachineFunction().getFrameInfo();
10754     return commonAlignment(MFI.getObjectAlign(FrameIdx), FrameOffset);
10755   }
10756 
10757   return None;
10758 }
10759 
10760 /// GetSplitDestVTs - Compute the VTs needed for the low/hi parts of a type
10761 /// which is split (or expanded) into two not necessarily identical pieces.
10762 std::pair<EVT, EVT> SelectionDAG::GetSplitDestVTs(const EVT &VT) const {
10763   // Currently all types are split in half.
10764   EVT LoVT, HiVT;
10765   if (!VT.isVector())
10766     LoVT = HiVT = TLI->getTypeToTransformTo(*getContext(), VT);
10767   else
10768     LoVT = HiVT = VT.getHalfNumVectorElementsVT(*getContext());
10769 
10770   return std::make_pair(LoVT, HiVT);
10771 }
10772 
10773 /// GetDependentSplitDestVTs - Compute the VTs needed for the low/hi parts of a
10774 /// type, dependent on an enveloping VT that has been split into two identical
10775 /// pieces. Sets the HiIsEmpty flag when hi type has zero storage size.
10776 std::pair<EVT, EVT>
10777 SelectionDAG::GetDependentSplitDestVTs(const EVT &VT, const EVT &EnvVT,
10778                                        bool *HiIsEmpty) const {
10779   EVT EltTp = VT.getVectorElementType();
10780   // Examples:
10781   //   custom VL=8  with enveloping VL=8/8 yields 8/0 (hi empty)
10782   //   custom VL=9  with enveloping VL=8/8 yields 8/1
10783   //   custom VL=10 with enveloping VL=8/8 yields 8/2
10784   //   etc.
10785   ElementCount VTNumElts = VT.getVectorElementCount();
10786   ElementCount EnvNumElts = EnvVT.getVectorElementCount();
10787   assert(VTNumElts.isScalable() == EnvNumElts.isScalable() &&
10788          "Mixing fixed width and scalable vectors when enveloping a type");
10789   EVT LoVT, HiVT;
10790   if (VTNumElts.getKnownMinValue() > EnvNumElts.getKnownMinValue()) {
10791     LoVT = EVT::getVectorVT(*getContext(), EltTp, EnvNumElts);
10792     HiVT = EVT::getVectorVT(*getContext(), EltTp, VTNumElts - EnvNumElts);
10793     *HiIsEmpty = false;
10794   } else {
10795     // Flag that hi type has zero storage size, but return split envelop type
10796     // (this would be easier if vector types with zero elements were allowed).
10797     LoVT = EVT::getVectorVT(*getContext(), EltTp, VTNumElts);
10798     HiVT = EVT::getVectorVT(*getContext(), EltTp, EnvNumElts);
10799     *HiIsEmpty = true;
10800   }
10801   return std::make_pair(LoVT, HiVT);
10802 }
10803 
10804 /// SplitVector - Split the vector with EXTRACT_SUBVECTOR and return the
10805 /// low/high part.
10806 std::pair<SDValue, SDValue>
10807 SelectionDAG::SplitVector(const SDValue &N, const SDLoc &DL, const EVT &LoVT,
10808                           const EVT &HiVT) {
10809   assert(LoVT.isScalableVector() == HiVT.isScalableVector() &&
10810          LoVT.isScalableVector() == N.getValueType().isScalableVector() &&
10811          "Splitting vector with an invalid mixture of fixed and scalable "
10812          "vector types");
10813   assert(LoVT.getVectorMinNumElements() + HiVT.getVectorMinNumElements() <=
10814              N.getValueType().getVectorMinNumElements() &&
10815          "More vector elements requested than available!");
10816   SDValue Lo, Hi;
10817   Lo =
10818       getNode(ISD::EXTRACT_SUBVECTOR, DL, LoVT, N, getVectorIdxConstant(0, DL));
10819   // For scalable vectors it is safe to use LoVT.getVectorMinNumElements()
10820   // (rather than having to use ElementCount), because EXTRACT_SUBVECTOR scales
10821   // IDX with the runtime scaling factor of the result vector type. For
10822   // fixed-width result vectors, that runtime scaling factor is 1.
10823   Hi = getNode(ISD::EXTRACT_SUBVECTOR, DL, HiVT, N,
10824                getVectorIdxConstant(LoVT.getVectorMinNumElements(), DL));
10825   return std::make_pair(Lo, Hi);
10826 }
10827 
10828 std::pair<SDValue, SDValue> SelectionDAG::SplitEVL(SDValue N, EVT VecVT,
10829                                                    const SDLoc &DL) {
10830   // Split the vector length parameter.
10831   // %evl -> umin(%evl, %halfnumelts) and usubsat(%evl - %halfnumelts).
10832   EVT VT = N.getValueType();
10833   assert(VecVT.getVectorElementCount().isKnownEven() &&
10834          "Expecting the mask to be an evenly-sized vector");
10835   unsigned HalfMinNumElts = VecVT.getVectorMinNumElements() / 2;
10836   SDValue HalfNumElts =
10837       VecVT.isFixedLengthVector()
10838           ? getConstant(HalfMinNumElts, DL, VT)
10839           : getVScale(DL, VT, APInt(VT.getScalarSizeInBits(), HalfMinNumElts));
10840   SDValue Lo = getNode(ISD::UMIN, DL, VT, N, HalfNumElts);
10841   SDValue Hi = getNode(ISD::USUBSAT, DL, VT, N, HalfNumElts);
10842   return std::make_pair(Lo, Hi);
10843 }
10844 
10845 /// Widen the vector up to the next power of two using INSERT_SUBVECTOR.
10846 SDValue SelectionDAG::WidenVector(const SDValue &N, const SDLoc &DL) {
10847   EVT VT = N.getValueType();
10848   EVT WideVT = EVT::getVectorVT(*getContext(), VT.getVectorElementType(),
10849                                 NextPowerOf2(VT.getVectorNumElements()));
10850   return getNode(ISD::INSERT_SUBVECTOR, DL, WideVT, getUNDEF(WideVT), N,
10851                  getVectorIdxConstant(0, DL));
10852 }
10853 
10854 void SelectionDAG::ExtractVectorElements(SDValue Op,
10855                                          SmallVectorImpl<SDValue> &Args,
10856                                          unsigned Start, unsigned Count,
10857                                          EVT EltVT) {
10858   EVT VT = Op.getValueType();
10859   if (Count == 0)
10860     Count = VT.getVectorNumElements();
10861   if (EltVT == EVT())
10862     EltVT = VT.getVectorElementType();
10863   SDLoc SL(Op);
10864   for (unsigned i = Start, e = Start + Count; i != e; ++i) {
10865     Args.push_back(getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Op,
10866                            getVectorIdxConstant(i, SL)));
10867   }
10868 }
10869 
10870 // getAddressSpace - Return the address space this GlobalAddress belongs to.
10871 unsigned GlobalAddressSDNode::getAddressSpace() const {
10872   return getGlobal()->getType()->getAddressSpace();
10873 }
10874 
10875 Type *ConstantPoolSDNode::getType() const {
10876   if (isMachineConstantPoolEntry())
10877     return Val.MachineCPVal->getType();
10878   return Val.ConstVal->getType();
10879 }
10880 
10881 bool BuildVectorSDNode::isConstantSplat(APInt &SplatValue, APInt &SplatUndef,
10882                                         unsigned &SplatBitSize,
10883                                         bool &HasAnyUndefs,
10884                                         unsigned MinSplatBits,
10885                                         bool IsBigEndian) const {
10886   EVT VT = getValueType(0);
10887   assert(VT.isVector() && "Expected a vector type");
10888   unsigned VecWidth = VT.getSizeInBits();
10889   if (MinSplatBits > VecWidth)
10890     return false;
10891 
10892   // FIXME: The widths are based on this node's type, but build vectors can
10893   // truncate their operands.
10894   SplatValue = APInt(VecWidth, 0);
10895   SplatUndef = APInt(VecWidth, 0);
10896 
10897   // Get the bits. Bits with undefined values (when the corresponding element
10898   // of the vector is an ISD::UNDEF value) are set in SplatUndef and cleared
10899   // in SplatValue. If any of the values are not constant, give up and return
10900   // false.
10901   unsigned int NumOps = getNumOperands();
10902   assert(NumOps > 0 && "isConstantSplat has 0-size build vector");
10903   unsigned EltWidth = VT.getScalarSizeInBits();
10904 
10905   for (unsigned j = 0; j < NumOps; ++j) {
10906     unsigned i = IsBigEndian ? NumOps - 1 - j : j;
10907     SDValue OpVal = getOperand(i);
10908     unsigned BitPos = j * EltWidth;
10909 
10910     if (OpVal.isUndef())
10911       SplatUndef.setBits(BitPos, BitPos + EltWidth);
10912     else if (auto *CN = dyn_cast<ConstantSDNode>(OpVal))
10913       SplatValue.insertBits(CN->getAPIntValue().zextOrTrunc(EltWidth), BitPos);
10914     else if (auto *CN = dyn_cast<ConstantFPSDNode>(OpVal))
10915       SplatValue.insertBits(CN->getValueAPF().bitcastToAPInt(), BitPos);
10916     else
10917       return false;
10918   }
10919 
10920   // The build_vector is all constants or undefs. Find the smallest element
10921   // size that splats the vector.
10922   HasAnyUndefs = (SplatUndef != 0);
10923 
10924   // FIXME: This does not work for vectors with elements less than 8 bits.
10925   while (VecWidth > 8) {
10926     unsigned HalfSize = VecWidth / 2;
10927     APInt HighValue = SplatValue.extractBits(HalfSize, HalfSize);
10928     APInt LowValue = SplatValue.extractBits(HalfSize, 0);
10929     APInt HighUndef = SplatUndef.extractBits(HalfSize, HalfSize);
10930     APInt LowUndef = SplatUndef.extractBits(HalfSize, 0);
10931 
10932     // If the two halves do not match (ignoring undef bits), stop here.
10933     if ((HighValue & ~LowUndef) != (LowValue & ~HighUndef) ||
10934         MinSplatBits > HalfSize)
10935       break;
10936 
10937     SplatValue = HighValue | LowValue;
10938     SplatUndef = HighUndef & LowUndef;
10939 
10940     VecWidth = HalfSize;
10941   }
10942 
10943   SplatBitSize = VecWidth;
10944   return true;
10945 }
10946 
10947 SDValue BuildVectorSDNode::getSplatValue(const APInt &DemandedElts,
10948                                          BitVector *UndefElements) const {
10949   unsigned NumOps = getNumOperands();
10950   if (UndefElements) {
10951     UndefElements->clear();
10952     UndefElements->resize(NumOps);
10953   }
10954   assert(NumOps == DemandedElts.getBitWidth() && "Unexpected vector size");
10955   if (!DemandedElts)
10956     return SDValue();
10957   SDValue Splatted;
10958   for (unsigned i = 0; i != NumOps; ++i) {
10959     if (!DemandedElts[i])
10960       continue;
10961     SDValue Op = getOperand(i);
10962     if (Op.isUndef()) {
10963       if (UndefElements)
10964         (*UndefElements)[i] = true;
10965     } else if (!Splatted) {
10966       Splatted = Op;
10967     } else if (Splatted != Op) {
10968       return SDValue();
10969     }
10970   }
10971 
10972   if (!Splatted) {
10973     unsigned FirstDemandedIdx = DemandedElts.countTrailingZeros();
10974     assert(getOperand(FirstDemandedIdx).isUndef() &&
10975            "Can only have a splat without a constant for all undefs.");
10976     return getOperand(FirstDemandedIdx);
10977   }
10978 
10979   return Splatted;
10980 }
10981 
10982 SDValue BuildVectorSDNode::getSplatValue(BitVector *UndefElements) const {
10983   APInt DemandedElts = APInt::getAllOnes(getNumOperands());
10984   return getSplatValue(DemandedElts, UndefElements);
10985 }
10986 
10987 bool BuildVectorSDNode::getRepeatedSequence(const APInt &DemandedElts,
10988                                             SmallVectorImpl<SDValue> &Sequence,
10989                                             BitVector *UndefElements) const {
10990   unsigned NumOps = getNumOperands();
10991   Sequence.clear();
10992   if (UndefElements) {
10993     UndefElements->clear();
10994     UndefElements->resize(NumOps);
10995   }
10996   assert(NumOps == DemandedElts.getBitWidth() && "Unexpected vector size");
10997   if (!DemandedElts || NumOps < 2 || !isPowerOf2_32(NumOps))
10998     return false;
10999 
11000   // Set the undefs even if we don't find a sequence (like getSplatValue).
11001   if (UndefElements)
11002     for (unsigned I = 0; I != NumOps; ++I)
11003       if (DemandedElts[I] && getOperand(I).isUndef())
11004         (*UndefElements)[I] = true;
11005 
11006   // Iteratively widen the sequence length looking for repetitions.
11007   for (unsigned SeqLen = 1; SeqLen < NumOps; SeqLen *= 2) {
11008     Sequence.append(SeqLen, SDValue());
11009     for (unsigned I = 0; I != NumOps; ++I) {
11010       if (!DemandedElts[I])
11011         continue;
11012       SDValue &SeqOp = Sequence[I % SeqLen];
11013       SDValue Op = getOperand(I);
11014       if (Op.isUndef()) {
11015         if (!SeqOp)
11016           SeqOp = Op;
11017         continue;
11018       }
11019       if (SeqOp && !SeqOp.isUndef() && SeqOp != Op) {
11020         Sequence.clear();
11021         break;
11022       }
11023       SeqOp = Op;
11024     }
11025     if (!Sequence.empty())
11026       return true;
11027   }
11028 
11029   assert(Sequence.empty() && "Failed to empty non-repeating sequence pattern");
11030   return false;
11031 }
11032 
11033 bool BuildVectorSDNode::getRepeatedSequence(SmallVectorImpl<SDValue> &Sequence,
11034                                             BitVector *UndefElements) const {
11035   APInt DemandedElts = APInt::getAllOnes(getNumOperands());
11036   return getRepeatedSequence(DemandedElts, Sequence, UndefElements);
11037 }
11038 
11039 ConstantSDNode *
11040 BuildVectorSDNode::getConstantSplatNode(const APInt &DemandedElts,
11041                                         BitVector *UndefElements) const {
11042   return dyn_cast_or_null<ConstantSDNode>(
11043       getSplatValue(DemandedElts, UndefElements));
11044 }
11045 
11046 ConstantSDNode *
11047 BuildVectorSDNode::getConstantSplatNode(BitVector *UndefElements) const {
11048   return dyn_cast_or_null<ConstantSDNode>(getSplatValue(UndefElements));
11049 }
11050 
11051 ConstantFPSDNode *
11052 BuildVectorSDNode::getConstantFPSplatNode(const APInt &DemandedElts,
11053                                           BitVector *UndefElements) const {
11054   return dyn_cast_or_null<ConstantFPSDNode>(
11055       getSplatValue(DemandedElts, UndefElements));
11056 }
11057 
11058 ConstantFPSDNode *
11059 BuildVectorSDNode::getConstantFPSplatNode(BitVector *UndefElements) const {
11060   return dyn_cast_or_null<ConstantFPSDNode>(getSplatValue(UndefElements));
11061 }
11062 
11063 int32_t
11064 BuildVectorSDNode::getConstantFPSplatPow2ToLog2Int(BitVector *UndefElements,
11065                                                    uint32_t BitWidth) const {
11066   if (ConstantFPSDNode *CN =
11067           dyn_cast_or_null<ConstantFPSDNode>(getSplatValue(UndefElements))) {
11068     bool IsExact;
11069     APSInt IntVal(BitWidth);
11070     const APFloat &APF = CN->getValueAPF();
11071     if (APF.convertToInteger(IntVal, APFloat::rmTowardZero, &IsExact) !=
11072             APFloat::opOK ||
11073         !IsExact)
11074       return -1;
11075 
11076     return IntVal.exactLogBase2();
11077   }
11078   return -1;
11079 }
11080 
11081 bool BuildVectorSDNode::getConstantRawBits(
11082     bool IsLittleEndian, unsigned DstEltSizeInBits,
11083     SmallVectorImpl<APInt> &RawBitElements, BitVector &UndefElements) const {
11084   // Early-out if this contains anything but Undef/Constant/ConstantFP.
11085   if (!isConstant())
11086     return false;
11087 
11088   unsigned NumSrcOps = getNumOperands();
11089   unsigned SrcEltSizeInBits = getValueType(0).getScalarSizeInBits();
11090   assert(((NumSrcOps * SrcEltSizeInBits) % DstEltSizeInBits) == 0 &&
11091          "Invalid bitcast scale");
11092 
11093   // Extract raw src bits.
11094   SmallVector<APInt> SrcBitElements(NumSrcOps,
11095                                     APInt::getNullValue(SrcEltSizeInBits));
11096   BitVector SrcUndeElements(NumSrcOps, false);
11097 
11098   for (unsigned I = 0; I != NumSrcOps; ++I) {
11099     SDValue Op = getOperand(I);
11100     if (Op.isUndef()) {
11101       SrcUndeElements.set(I);
11102       continue;
11103     }
11104     auto *CInt = dyn_cast<ConstantSDNode>(Op);
11105     auto *CFP = dyn_cast<ConstantFPSDNode>(Op);
11106     assert((CInt || CFP) && "Unknown constant");
11107     SrcBitElements[I] =
11108         CInt ? CInt->getAPIntValue().truncOrSelf(SrcEltSizeInBits)
11109              : CFP->getValueAPF().bitcastToAPInt();
11110   }
11111 
11112   // Recast to dst width.
11113   recastRawBits(IsLittleEndian, DstEltSizeInBits, RawBitElements,
11114                 SrcBitElements, UndefElements, SrcUndeElements);
11115   return true;
11116 }
11117 
11118 void BuildVectorSDNode::recastRawBits(bool IsLittleEndian,
11119                                       unsigned DstEltSizeInBits,
11120                                       SmallVectorImpl<APInt> &DstBitElements,
11121                                       ArrayRef<APInt> SrcBitElements,
11122                                       BitVector &DstUndefElements,
11123                                       const BitVector &SrcUndefElements) {
11124   unsigned NumSrcOps = SrcBitElements.size();
11125   unsigned SrcEltSizeInBits = SrcBitElements[0].getBitWidth();
11126   assert(((NumSrcOps * SrcEltSizeInBits) % DstEltSizeInBits) == 0 &&
11127          "Invalid bitcast scale");
11128   assert(NumSrcOps == SrcUndefElements.size() &&
11129          "Vector size mismatch");
11130 
11131   unsigned NumDstOps = (NumSrcOps * SrcEltSizeInBits) / DstEltSizeInBits;
11132   DstUndefElements.clear();
11133   DstUndefElements.resize(NumDstOps, false);
11134   DstBitElements.assign(NumDstOps, APInt::getNullValue(DstEltSizeInBits));
11135 
11136   // Concatenate src elements constant bits together into dst element.
11137   if (SrcEltSizeInBits <= DstEltSizeInBits) {
11138     unsigned Scale = DstEltSizeInBits / SrcEltSizeInBits;
11139     for (unsigned I = 0; I != NumDstOps; ++I) {
11140       DstUndefElements.set(I);
11141       APInt &DstBits = DstBitElements[I];
11142       for (unsigned J = 0; J != Scale; ++J) {
11143         unsigned Idx = (I * Scale) + (IsLittleEndian ? J : (Scale - J - 1));
11144         if (SrcUndefElements[Idx])
11145           continue;
11146         DstUndefElements.reset(I);
11147         const APInt &SrcBits = SrcBitElements[Idx];
11148         assert(SrcBits.getBitWidth() == SrcEltSizeInBits &&
11149                "Illegal constant bitwidths");
11150         DstBits.insertBits(SrcBits, J * SrcEltSizeInBits);
11151       }
11152     }
11153     return;
11154   }
11155 
11156   // Split src element constant bits into dst elements.
11157   unsigned Scale = SrcEltSizeInBits / DstEltSizeInBits;
11158   for (unsigned I = 0; I != NumSrcOps; ++I) {
11159     if (SrcUndefElements[I]) {
11160       DstUndefElements.set(I * Scale, (I + 1) * Scale);
11161       continue;
11162     }
11163     const APInt &SrcBits = SrcBitElements[I];
11164     for (unsigned J = 0; J != Scale; ++J) {
11165       unsigned Idx = (I * Scale) + (IsLittleEndian ? J : (Scale - J - 1));
11166       APInt &DstBits = DstBitElements[Idx];
11167       DstBits = SrcBits.extractBits(DstEltSizeInBits, J * DstEltSizeInBits);
11168     }
11169   }
11170 }
11171 
11172 bool BuildVectorSDNode::isConstant() const {
11173   for (const SDValue &Op : op_values()) {
11174     unsigned Opc = Op.getOpcode();
11175     if (Opc != ISD::UNDEF && Opc != ISD::Constant && Opc != ISD::ConstantFP)
11176       return false;
11177   }
11178   return true;
11179 }
11180 
11181 bool ShuffleVectorSDNode::isSplatMask(const int *Mask, EVT VT) {
11182   // Find the first non-undef value in the shuffle mask.
11183   unsigned i, e;
11184   for (i = 0, e = VT.getVectorNumElements(); i != e && Mask[i] < 0; ++i)
11185     /* search */;
11186 
11187   // If all elements are undefined, this shuffle can be considered a splat
11188   // (although it should eventually get simplified away completely).
11189   if (i == e)
11190     return true;
11191 
11192   // Make sure all remaining elements are either undef or the same as the first
11193   // non-undef value.
11194   for (int Idx = Mask[i]; i != e; ++i)
11195     if (Mask[i] >= 0 && Mask[i] != Idx)
11196       return false;
11197   return true;
11198 }
11199 
11200 // Returns the SDNode if it is a constant integer BuildVector
11201 // or constant integer.
11202 SDNode *SelectionDAG::isConstantIntBuildVectorOrConstantInt(SDValue N) const {
11203   if (isa<ConstantSDNode>(N))
11204     return N.getNode();
11205   if (ISD::isBuildVectorOfConstantSDNodes(N.getNode()))
11206     return N.getNode();
11207   // Treat a GlobalAddress supporting constant offset folding as a
11208   // constant integer.
11209   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N))
11210     if (GA->getOpcode() == ISD::GlobalAddress &&
11211         TLI->isOffsetFoldingLegal(GA))
11212       return GA;
11213   if ((N.getOpcode() == ISD::SPLAT_VECTOR) &&
11214       isa<ConstantSDNode>(N.getOperand(0)))
11215     return N.getNode();
11216   return nullptr;
11217 }
11218 
11219 // Returns the SDNode if it is a constant float BuildVector
11220 // or constant float.
11221 SDNode *SelectionDAG::isConstantFPBuildVectorOrConstantFP(SDValue N) const {
11222   if (isa<ConstantFPSDNode>(N))
11223     return N.getNode();
11224 
11225   if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode()))
11226     return N.getNode();
11227 
11228   if ((N.getOpcode() == ISD::SPLAT_VECTOR) &&
11229       isa<ConstantFPSDNode>(N.getOperand(0)))
11230     return N.getNode();
11231 
11232   return nullptr;
11233 }
11234 
11235 void SelectionDAG::createOperands(SDNode *Node, ArrayRef<SDValue> Vals) {
11236   assert(!Node->OperandList && "Node already has operands");
11237   assert(SDNode::getMaxNumOperands() >= Vals.size() &&
11238          "too many operands to fit into SDNode");
11239   SDUse *Ops = OperandRecycler.allocate(
11240       ArrayRecycler<SDUse>::Capacity::get(Vals.size()), OperandAllocator);
11241 
11242   bool IsDivergent = false;
11243   for (unsigned I = 0; I != Vals.size(); ++I) {
11244     Ops[I].setUser(Node);
11245     Ops[I].setInitial(Vals[I]);
11246     if (Ops[I].Val.getValueType() != MVT::Other) // Skip Chain. It does not carry divergence.
11247       IsDivergent |= Ops[I].getNode()->isDivergent();
11248   }
11249   Node->NumOperands = Vals.size();
11250   Node->OperandList = Ops;
11251   if (!TLI->isSDNodeAlwaysUniform(Node)) {
11252     IsDivergent |= TLI->isSDNodeSourceOfDivergence(Node, FLI, DA);
11253     Node->SDNodeBits.IsDivergent = IsDivergent;
11254   }
11255   checkForCycles(Node);
11256 }
11257 
11258 SDValue SelectionDAG::getTokenFactor(const SDLoc &DL,
11259                                      SmallVectorImpl<SDValue> &Vals) {
11260   size_t Limit = SDNode::getMaxNumOperands();
11261   while (Vals.size() > Limit) {
11262     unsigned SliceIdx = Vals.size() - Limit;
11263     auto ExtractedTFs = ArrayRef<SDValue>(Vals).slice(SliceIdx, Limit);
11264     SDValue NewTF = getNode(ISD::TokenFactor, DL, MVT::Other, ExtractedTFs);
11265     Vals.erase(Vals.begin() + SliceIdx, Vals.end());
11266     Vals.emplace_back(NewTF);
11267   }
11268   return getNode(ISD::TokenFactor, DL, MVT::Other, Vals);
11269 }
11270 
11271 SDValue SelectionDAG::getNeutralElement(unsigned Opcode, const SDLoc &DL,
11272                                         EVT VT, SDNodeFlags Flags) {
11273   switch (Opcode) {
11274   default:
11275     return SDValue();
11276   case ISD::ADD:
11277   case ISD::OR:
11278   case ISD::XOR:
11279   case ISD::UMAX:
11280     return getConstant(0, DL, VT);
11281   case ISD::MUL:
11282     return getConstant(1, DL, VT);
11283   case ISD::AND:
11284   case ISD::UMIN:
11285     return getAllOnesConstant(DL, VT);
11286   case ISD::SMAX:
11287     return getConstant(APInt::getSignedMinValue(VT.getSizeInBits()), DL, VT);
11288   case ISD::SMIN:
11289     return getConstant(APInt::getSignedMaxValue(VT.getSizeInBits()), DL, VT);
11290   case ISD::FADD:
11291     return getConstantFP(-0.0, DL, VT);
11292   case ISD::FMUL:
11293     return getConstantFP(1.0, DL, VT);
11294   case ISD::FMINNUM:
11295   case ISD::FMAXNUM: {
11296     // Neutral element for fminnum is NaN, Inf or FLT_MAX, depending on FMF.
11297     const fltSemantics &Semantics = EVTToAPFloatSemantics(VT);
11298     APFloat NeutralAF = !Flags.hasNoNaNs() ? APFloat::getQNaN(Semantics) :
11299                         !Flags.hasNoInfs() ? APFloat::getInf(Semantics) :
11300                         APFloat::getLargest(Semantics);
11301     if (Opcode == ISD::FMAXNUM)
11302       NeutralAF.changeSign();
11303 
11304     return getConstantFP(NeutralAF, DL, VT);
11305   }
11306   }
11307 }
11308 
11309 #ifndef NDEBUG
11310 static void checkForCyclesHelper(const SDNode *N,
11311                                  SmallPtrSetImpl<const SDNode*> &Visited,
11312                                  SmallPtrSetImpl<const SDNode*> &Checked,
11313                                  const llvm::SelectionDAG *DAG) {
11314   // If this node has already been checked, don't check it again.
11315   if (Checked.count(N))
11316     return;
11317 
11318   // If a node has already been visited on this depth-first walk, reject it as
11319   // a cycle.
11320   if (!Visited.insert(N).second) {
11321     errs() << "Detected cycle in SelectionDAG\n";
11322     dbgs() << "Offending node:\n";
11323     N->dumprFull(DAG); dbgs() << "\n";
11324     abort();
11325   }
11326 
11327   for (const SDValue &Op : N->op_values())
11328     checkForCyclesHelper(Op.getNode(), Visited, Checked, DAG);
11329 
11330   Checked.insert(N);
11331   Visited.erase(N);
11332 }
11333 #endif
11334 
11335 void llvm::checkForCycles(const llvm::SDNode *N,
11336                           const llvm::SelectionDAG *DAG,
11337                           bool force) {
11338 #ifndef NDEBUG
11339   bool check = force;
11340 #ifdef EXPENSIVE_CHECKS
11341   check = true;
11342 #endif  // EXPENSIVE_CHECKS
11343   if (check) {
11344     assert(N && "Checking nonexistent SDNode");
11345     SmallPtrSet<const SDNode*, 32> visited;
11346     SmallPtrSet<const SDNode*, 32> checked;
11347     checkForCyclesHelper(N, visited, checked, DAG);
11348   }
11349 #endif  // !NDEBUG
11350 }
11351 
11352 void llvm::checkForCycles(const llvm::SelectionDAG *DAG, bool force) {
11353   checkForCycles(DAG->getRoot().getNode(), DAG, force);
11354 }
11355