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     break;
718   }
719   case ISD::STORE: {
720     const StoreSDNode *ST = cast<StoreSDNode>(N);
721     ID.AddInteger(ST->getMemoryVT().getRawBits());
722     ID.AddInteger(ST->getRawSubclassData());
723     ID.AddInteger(ST->getPointerInfo().getAddrSpace());
724     break;
725   }
726   case ISD::VP_LOAD: {
727     const VPLoadSDNode *ELD = cast<VPLoadSDNode>(N);
728     ID.AddInteger(ELD->getMemoryVT().getRawBits());
729     ID.AddInteger(ELD->getRawSubclassData());
730     ID.AddInteger(ELD->getPointerInfo().getAddrSpace());
731     break;
732   }
733   case ISD::VP_STORE: {
734     const VPStoreSDNode *EST = cast<VPStoreSDNode>(N);
735     ID.AddInteger(EST->getMemoryVT().getRawBits());
736     ID.AddInteger(EST->getRawSubclassData());
737     ID.AddInteger(EST->getPointerInfo().getAddrSpace());
738     break;
739   }
740   case ISD::VP_GATHER: {
741     const VPGatherSDNode *EG = cast<VPGatherSDNode>(N);
742     ID.AddInteger(EG->getMemoryVT().getRawBits());
743     ID.AddInteger(EG->getRawSubclassData());
744     ID.AddInteger(EG->getPointerInfo().getAddrSpace());
745     break;
746   }
747   case ISD::VP_SCATTER: {
748     const VPScatterSDNode *ES = cast<VPScatterSDNode>(N);
749     ID.AddInteger(ES->getMemoryVT().getRawBits());
750     ID.AddInteger(ES->getRawSubclassData());
751     ID.AddInteger(ES->getPointerInfo().getAddrSpace());
752     break;
753   }
754   case ISD::MLOAD: {
755     const MaskedLoadSDNode *MLD = cast<MaskedLoadSDNode>(N);
756     ID.AddInteger(MLD->getMemoryVT().getRawBits());
757     ID.AddInteger(MLD->getRawSubclassData());
758     ID.AddInteger(MLD->getPointerInfo().getAddrSpace());
759     break;
760   }
761   case ISD::MSTORE: {
762     const MaskedStoreSDNode *MST = cast<MaskedStoreSDNode>(N);
763     ID.AddInteger(MST->getMemoryVT().getRawBits());
764     ID.AddInteger(MST->getRawSubclassData());
765     ID.AddInteger(MST->getPointerInfo().getAddrSpace());
766     break;
767   }
768   case ISD::MGATHER: {
769     const MaskedGatherSDNode *MG = cast<MaskedGatherSDNode>(N);
770     ID.AddInteger(MG->getMemoryVT().getRawBits());
771     ID.AddInteger(MG->getRawSubclassData());
772     ID.AddInteger(MG->getPointerInfo().getAddrSpace());
773     break;
774   }
775   case ISD::MSCATTER: {
776     const MaskedScatterSDNode *MS = cast<MaskedScatterSDNode>(N);
777     ID.AddInteger(MS->getMemoryVT().getRawBits());
778     ID.AddInteger(MS->getRawSubclassData());
779     ID.AddInteger(MS->getPointerInfo().getAddrSpace());
780     break;
781   }
782   case ISD::ATOMIC_CMP_SWAP:
783   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
784   case ISD::ATOMIC_SWAP:
785   case ISD::ATOMIC_LOAD_ADD:
786   case ISD::ATOMIC_LOAD_SUB:
787   case ISD::ATOMIC_LOAD_AND:
788   case ISD::ATOMIC_LOAD_CLR:
789   case ISD::ATOMIC_LOAD_OR:
790   case ISD::ATOMIC_LOAD_XOR:
791   case ISD::ATOMIC_LOAD_NAND:
792   case ISD::ATOMIC_LOAD_MIN:
793   case ISD::ATOMIC_LOAD_MAX:
794   case ISD::ATOMIC_LOAD_UMIN:
795   case ISD::ATOMIC_LOAD_UMAX:
796   case ISD::ATOMIC_LOAD:
797   case ISD::ATOMIC_STORE: {
798     const AtomicSDNode *AT = cast<AtomicSDNode>(N);
799     ID.AddInteger(AT->getMemoryVT().getRawBits());
800     ID.AddInteger(AT->getRawSubclassData());
801     ID.AddInteger(AT->getPointerInfo().getAddrSpace());
802     break;
803   }
804   case ISD::PREFETCH: {
805     const MemSDNode *PF = cast<MemSDNode>(N);
806     ID.AddInteger(PF->getPointerInfo().getAddrSpace());
807     break;
808   }
809   case ISD::VECTOR_SHUFFLE: {
810     const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
811     for (unsigned i = 0, e = N->getValueType(0).getVectorNumElements();
812          i != e; ++i)
813       ID.AddInteger(SVN->getMaskElt(i));
814     break;
815   }
816   case ISD::TargetBlockAddress:
817   case ISD::BlockAddress: {
818     const BlockAddressSDNode *BA = cast<BlockAddressSDNode>(N);
819     ID.AddPointer(BA->getBlockAddress());
820     ID.AddInteger(BA->getOffset());
821     ID.AddInteger(BA->getTargetFlags());
822     break;
823   }
824   } // end switch (N->getOpcode())
825 
826   // Target specific memory nodes could also have address spaces to check.
827   if (N->isTargetMemoryOpcode())
828     ID.AddInteger(cast<MemSDNode>(N)->getPointerInfo().getAddrSpace());
829 }
830 
831 /// AddNodeIDNode - Generic routine for adding a nodes info to the NodeID
832 /// data.
833 static void AddNodeIDNode(FoldingSetNodeID &ID, const SDNode *N) {
834   AddNodeIDOpcode(ID, N->getOpcode());
835   // Add the return value info.
836   AddNodeIDValueTypes(ID, N->getVTList());
837   // Add the operand info.
838   AddNodeIDOperands(ID, N->ops());
839 
840   // Handle SDNode leafs with special info.
841   AddNodeIDCustom(ID, N);
842 }
843 
844 //===----------------------------------------------------------------------===//
845 //                              SelectionDAG Class
846 //===----------------------------------------------------------------------===//
847 
848 /// doNotCSE - Return true if CSE should not be performed for this node.
849 static bool doNotCSE(SDNode *N) {
850   if (N->getValueType(0) == MVT::Glue)
851     return true; // Never CSE anything that produces a flag.
852 
853   switch (N->getOpcode()) {
854   default: break;
855   case ISD::HANDLENODE:
856   case ISD::EH_LABEL:
857     return true;   // Never CSE these nodes.
858   }
859 
860   // Check that remaining values produced are not flags.
861   for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
862     if (N->getValueType(i) == MVT::Glue)
863       return true; // Never CSE anything that produces a flag.
864 
865   return false;
866 }
867 
868 /// RemoveDeadNodes - This method deletes all unreachable nodes in the
869 /// SelectionDAG.
870 void SelectionDAG::RemoveDeadNodes() {
871   // Create a dummy node (which is not added to allnodes), that adds a reference
872   // to the root node, preventing it from being deleted.
873   HandleSDNode Dummy(getRoot());
874 
875   SmallVector<SDNode*, 128> DeadNodes;
876 
877   // Add all obviously-dead nodes to the DeadNodes worklist.
878   for (SDNode &Node : allnodes())
879     if (Node.use_empty())
880       DeadNodes.push_back(&Node);
881 
882   RemoveDeadNodes(DeadNodes);
883 
884   // If the root changed (e.g. it was a dead load, update the root).
885   setRoot(Dummy.getValue());
886 }
887 
888 /// RemoveDeadNodes - This method deletes the unreachable nodes in the
889 /// given list, and any nodes that become unreachable as a result.
890 void SelectionDAG::RemoveDeadNodes(SmallVectorImpl<SDNode *> &DeadNodes) {
891 
892   // Process the worklist, deleting the nodes and adding their uses to the
893   // worklist.
894   while (!DeadNodes.empty()) {
895     SDNode *N = DeadNodes.pop_back_val();
896     // Skip to next node if we've already managed to delete the node. This could
897     // happen if replacing a node causes a node previously added to the node to
898     // be deleted.
899     if (N->getOpcode() == ISD::DELETED_NODE)
900       continue;
901 
902     for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
903       DUL->NodeDeleted(N, nullptr);
904 
905     // Take the node out of the appropriate CSE map.
906     RemoveNodeFromCSEMaps(N);
907 
908     // Next, brutally remove the operand list.  This is safe to do, as there are
909     // no cycles in the graph.
910     for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) {
911       SDUse &Use = *I++;
912       SDNode *Operand = Use.getNode();
913       Use.set(SDValue());
914 
915       // Now that we removed this operand, see if there are no uses of it left.
916       if (Operand->use_empty())
917         DeadNodes.push_back(Operand);
918     }
919 
920     DeallocateNode(N);
921   }
922 }
923 
924 void SelectionDAG::RemoveDeadNode(SDNode *N){
925   SmallVector<SDNode*, 16> DeadNodes(1, N);
926 
927   // Create a dummy node that adds a reference to the root node, preventing
928   // it from being deleted.  (This matters if the root is an operand of the
929   // dead node.)
930   HandleSDNode Dummy(getRoot());
931 
932   RemoveDeadNodes(DeadNodes);
933 }
934 
935 void SelectionDAG::DeleteNode(SDNode *N) {
936   // First take this out of the appropriate CSE map.
937   RemoveNodeFromCSEMaps(N);
938 
939   // Finally, remove uses due to operands of this node, remove from the
940   // AllNodes list, and delete the node.
941   DeleteNodeNotInCSEMaps(N);
942 }
943 
944 void SelectionDAG::DeleteNodeNotInCSEMaps(SDNode *N) {
945   assert(N->getIterator() != AllNodes.begin() &&
946          "Cannot delete the entry node!");
947   assert(N->use_empty() && "Cannot delete a node that is not dead!");
948 
949   // Drop all of the operands and decrement used node's use counts.
950   N->DropOperands();
951 
952   DeallocateNode(N);
953 }
954 
955 void SDDbgInfo::add(SDDbgValue *V, bool isParameter) {
956   assert(!(V->isVariadic() && isParameter));
957   if (isParameter)
958     ByvalParmDbgValues.push_back(V);
959   else
960     DbgValues.push_back(V);
961   for (const SDNode *Node : V->getSDNodes())
962     if (Node)
963       DbgValMap[Node].push_back(V);
964 }
965 
966 void SDDbgInfo::erase(const SDNode *Node) {
967   DbgValMapType::iterator I = DbgValMap.find(Node);
968   if (I == DbgValMap.end())
969     return;
970   for (auto &Val: I->second)
971     Val->setIsInvalidated();
972   DbgValMap.erase(I);
973 }
974 
975 void SelectionDAG::DeallocateNode(SDNode *N) {
976   // If we have operands, deallocate them.
977   removeOperands(N);
978 
979   NodeAllocator.Deallocate(AllNodes.remove(N));
980 
981   // Set the opcode to DELETED_NODE to help catch bugs when node
982   // memory is reallocated.
983   // FIXME: There are places in SDag that have grown a dependency on the opcode
984   // value in the released node.
985   __asan_unpoison_memory_region(&N->NodeType, sizeof(N->NodeType));
986   N->NodeType = ISD::DELETED_NODE;
987 
988   // If any of the SDDbgValue nodes refer to this SDNode, invalidate
989   // them and forget about that node.
990   DbgInfo->erase(N);
991 }
992 
993 #ifndef NDEBUG
994 /// VerifySDNode - Check the given SDNode.  Aborts if it is invalid.
995 static void VerifySDNode(SDNode *N) {
996   switch (N->getOpcode()) {
997   default:
998     break;
999   case ISD::BUILD_PAIR: {
1000     EVT VT = N->getValueType(0);
1001     assert(N->getNumValues() == 1 && "Too many results!");
1002     assert(!VT.isVector() && (VT.isInteger() || VT.isFloatingPoint()) &&
1003            "Wrong return type!");
1004     assert(N->getNumOperands() == 2 && "Wrong number of operands!");
1005     assert(N->getOperand(0).getValueType() == N->getOperand(1).getValueType() &&
1006            "Mismatched operand types!");
1007     assert(N->getOperand(0).getValueType().isInteger() == VT.isInteger() &&
1008            "Wrong operand type!");
1009     assert(VT.getSizeInBits() == 2 * N->getOperand(0).getValueSizeInBits() &&
1010            "Wrong return type size");
1011     break;
1012   }
1013   case ISD::BUILD_VECTOR: {
1014     assert(N->getNumValues() == 1 && "Too many results!");
1015     assert(N->getValueType(0).isVector() && "Wrong return type!");
1016     assert(N->getNumOperands() == N->getValueType(0).getVectorNumElements() &&
1017            "Wrong number of operands!");
1018     EVT EltVT = N->getValueType(0).getVectorElementType();
1019     for (const SDUse &Op : N->ops()) {
1020       assert((Op.getValueType() == EltVT ||
1021               (EltVT.isInteger() && Op.getValueType().isInteger() &&
1022                EltVT.bitsLE(Op.getValueType()))) &&
1023              "Wrong operand type!");
1024       assert(Op.getValueType() == N->getOperand(0).getValueType() &&
1025              "Operands must all have the same type");
1026     }
1027     break;
1028   }
1029   }
1030 }
1031 #endif // NDEBUG
1032 
1033 /// Insert a newly allocated node into the DAG.
1034 ///
1035 /// Handles insertion into the all nodes list and CSE map, as well as
1036 /// verification and other common operations when a new node is allocated.
1037 void SelectionDAG::InsertNode(SDNode *N) {
1038   AllNodes.push_back(N);
1039 #ifndef NDEBUG
1040   N->PersistentId = NextPersistentId++;
1041   VerifySDNode(N);
1042 #endif
1043   for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
1044     DUL->NodeInserted(N);
1045 }
1046 
1047 /// RemoveNodeFromCSEMaps - Take the specified node out of the CSE map that
1048 /// correspond to it.  This is useful when we're about to delete or repurpose
1049 /// the node.  We don't want future request for structurally identical nodes
1050 /// to return N anymore.
1051 bool SelectionDAG::RemoveNodeFromCSEMaps(SDNode *N) {
1052   bool Erased = false;
1053   switch (N->getOpcode()) {
1054   case ISD::HANDLENODE: return false;  // noop.
1055   case ISD::CONDCODE:
1056     assert(CondCodeNodes[cast<CondCodeSDNode>(N)->get()] &&
1057            "Cond code doesn't exist!");
1058     Erased = CondCodeNodes[cast<CondCodeSDNode>(N)->get()] != nullptr;
1059     CondCodeNodes[cast<CondCodeSDNode>(N)->get()] = nullptr;
1060     break;
1061   case ISD::ExternalSymbol:
1062     Erased = ExternalSymbols.erase(cast<ExternalSymbolSDNode>(N)->getSymbol());
1063     break;
1064   case ISD::TargetExternalSymbol: {
1065     ExternalSymbolSDNode *ESN = cast<ExternalSymbolSDNode>(N);
1066     Erased = TargetExternalSymbols.erase(std::pair<std::string, unsigned>(
1067         ESN->getSymbol(), ESN->getTargetFlags()));
1068     break;
1069   }
1070   case ISD::MCSymbol: {
1071     auto *MCSN = cast<MCSymbolSDNode>(N);
1072     Erased = MCSymbols.erase(MCSN->getMCSymbol());
1073     break;
1074   }
1075   case ISD::VALUETYPE: {
1076     EVT VT = cast<VTSDNode>(N)->getVT();
1077     if (VT.isExtended()) {
1078       Erased = ExtendedValueTypeNodes.erase(VT);
1079     } else {
1080       Erased = ValueTypeNodes[VT.getSimpleVT().SimpleTy] != nullptr;
1081       ValueTypeNodes[VT.getSimpleVT().SimpleTy] = nullptr;
1082     }
1083     break;
1084   }
1085   default:
1086     // Remove it from the CSE Map.
1087     assert(N->getOpcode() != ISD::DELETED_NODE && "DELETED_NODE in CSEMap!");
1088     assert(N->getOpcode() != ISD::EntryToken && "EntryToken in CSEMap!");
1089     Erased = CSEMap.RemoveNode(N);
1090     break;
1091   }
1092 #ifndef NDEBUG
1093   // Verify that the node was actually in one of the CSE maps, unless it has a
1094   // flag result (which cannot be CSE'd) or is one of the special cases that are
1095   // not subject to CSE.
1096   if (!Erased && N->getValueType(N->getNumValues()-1) != MVT::Glue &&
1097       !N->isMachineOpcode() && !doNotCSE(N)) {
1098     N->dump(this);
1099     dbgs() << "\n";
1100     llvm_unreachable("Node is not in map!");
1101   }
1102 #endif
1103   return Erased;
1104 }
1105 
1106 /// AddModifiedNodeToCSEMaps - The specified node has been removed from the CSE
1107 /// maps and modified in place. Add it back to the CSE maps, unless an identical
1108 /// node already exists, in which case transfer all its users to the existing
1109 /// node. This transfer can potentially trigger recursive merging.
1110 void
1111 SelectionDAG::AddModifiedNodeToCSEMaps(SDNode *N) {
1112   // For node types that aren't CSE'd, just act as if no identical node
1113   // already exists.
1114   if (!doNotCSE(N)) {
1115     SDNode *Existing = CSEMap.GetOrInsertNode(N);
1116     if (Existing != N) {
1117       // If there was already an existing matching node, use ReplaceAllUsesWith
1118       // to replace the dead one with the existing one.  This can cause
1119       // recursive merging of other unrelated nodes down the line.
1120       ReplaceAllUsesWith(N, Existing);
1121 
1122       // N is now dead. Inform the listeners and delete it.
1123       for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
1124         DUL->NodeDeleted(N, Existing);
1125       DeleteNodeNotInCSEMaps(N);
1126       return;
1127     }
1128   }
1129 
1130   // If the node doesn't already exist, we updated it.  Inform listeners.
1131   for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
1132     DUL->NodeUpdated(N);
1133 }
1134 
1135 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
1136 /// were replaced with those specified.  If this node is never memoized,
1137 /// return null, otherwise return a pointer to the slot it would take.  If a
1138 /// node already exists with these operands, the slot will be non-null.
1139 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, SDValue Op,
1140                                            void *&InsertPos) {
1141   if (doNotCSE(N))
1142     return nullptr;
1143 
1144   SDValue Ops[] = { Op };
1145   FoldingSetNodeID ID;
1146   AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops);
1147   AddNodeIDCustom(ID, N);
1148   SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos);
1149   if (Node)
1150     Node->intersectFlagsWith(N->getFlags());
1151   return Node;
1152 }
1153 
1154 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
1155 /// were replaced with those specified.  If this node is never memoized,
1156 /// return null, otherwise return a pointer to the slot it would take.  If a
1157 /// node already exists with these operands, the slot will be non-null.
1158 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N,
1159                                            SDValue Op1, SDValue Op2,
1160                                            void *&InsertPos) {
1161   if (doNotCSE(N))
1162     return nullptr;
1163 
1164   SDValue Ops[] = { Op1, Op2 };
1165   FoldingSetNodeID ID;
1166   AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops);
1167   AddNodeIDCustom(ID, N);
1168   SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos);
1169   if (Node)
1170     Node->intersectFlagsWith(N->getFlags());
1171   return Node;
1172 }
1173 
1174 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
1175 /// were replaced with those specified.  If this node is never memoized,
1176 /// return null, otherwise return a pointer to the slot it would take.  If a
1177 /// node already exists with these operands, the slot will be non-null.
1178 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, ArrayRef<SDValue> Ops,
1179                                            void *&InsertPos) {
1180   if (doNotCSE(N))
1181     return nullptr;
1182 
1183   FoldingSetNodeID ID;
1184   AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops);
1185   AddNodeIDCustom(ID, N);
1186   SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos);
1187   if (Node)
1188     Node->intersectFlagsWith(N->getFlags());
1189   return Node;
1190 }
1191 
1192 Align SelectionDAG::getEVTAlign(EVT VT) const {
1193   Type *Ty = VT == MVT::iPTR ?
1194                    PointerType::get(Type::getInt8Ty(*getContext()), 0) :
1195                    VT.getTypeForEVT(*getContext());
1196 
1197   return getDataLayout().getABITypeAlign(Ty);
1198 }
1199 
1200 // EntryNode could meaningfully have debug info if we can find it...
1201 SelectionDAG::SelectionDAG(const TargetMachine &tm, CodeGenOpt::Level OL)
1202     : TM(tm), OptLevel(OL),
1203       EntryNode(ISD::EntryToken, 0, DebugLoc(), getVTList(MVT::Other)),
1204       Root(getEntryNode()) {
1205   InsertNode(&EntryNode);
1206   DbgInfo = new SDDbgInfo();
1207 }
1208 
1209 void SelectionDAG::init(MachineFunction &NewMF,
1210                         OptimizationRemarkEmitter &NewORE,
1211                         Pass *PassPtr, const TargetLibraryInfo *LibraryInfo,
1212                         LegacyDivergenceAnalysis * Divergence,
1213                         ProfileSummaryInfo *PSIin,
1214                         BlockFrequencyInfo *BFIin) {
1215   MF = &NewMF;
1216   SDAGISelPass = PassPtr;
1217   ORE = &NewORE;
1218   TLI = getSubtarget().getTargetLowering();
1219   TSI = getSubtarget().getSelectionDAGInfo();
1220   LibInfo = LibraryInfo;
1221   Context = &MF->getFunction().getContext();
1222   DA = Divergence;
1223   PSI = PSIin;
1224   BFI = BFIin;
1225 }
1226 
1227 SelectionDAG::~SelectionDAG() {
1228   assert(!UpdateListeners && "Dangling registered DAGUpdateListeners");
1229   allnodes_clear();
1230   OperandRecycler.clear(OperandAllocator);
1231   delete DbgInfo;
1232 }
1233 
1234 bool SelectionDAG::shouldOptForSize() const {
1235   return MF->getFunction().hasOptSize() ||
1236       llvm::shouldOptimizeForSize(FLI->MBB->getBasicBlock(), PSI, BFI);
1237 }
1238 
1239 void SelectionDAG::allnodes_clear() {
1240   assert(&*AllNodes.begin() == &EntryNode);
1241   AllNodes.remove(AllNodes.begin());
1242   while (!AllNodes.empty())
1243     DeallocateNode(&AllNodes.front());
1244 #ifndef NDEBUG
1245   NextPersistentId = 0;
1246 #endif
1247 }
1248 
1249 SDNode *SelectionDAG::FindNodeOrInsertPos(const FoldingSetNodeID &ID,
1250                                           void *&InsertPos) {
1251   SDNode *N = CSEMap.FindNodeOrInsertPos(ID, InsertPos);
1252   if (N) {
1253     switch (N->getOpcode()) {
1254     default: break;
1255     case ISD::Constant:
1256     case ISD::ConstantFP:
1257       llvm_unreachable("Querying for Constant and ConstantFP nodes requires "
1258                        "debug location.  Use another overload.");
1259     }
1260   }
1261   return N;
1262 }
1263 
1264 SDNode *SelectionDAG::FindNodeOrInsertPos(const FoldingSetNodeID &ID,
1265                                           const SDLoc &DL, void *&InsertPos) {
1266   SDNode *N = CSEMap.FindNodeOrInsertPos(ID, InsertPos);
1267   if (N) {
1268     switch (N->getOpcode()) {
1269     case ISD::Constant:
1270     case ISD::ConstantFP:
1271       // Erase debug location from the node if the node is used at several
1272       // different places. Do not propagate one location to all uses as it
1273       // will cause a worse single stepping debugging experience.
1274       if (N->getDebugLoc() != DL.getDebugLoc())
1275         N->setDebugLoc(DebugLoc());
1276       break;
1277     default:
1278       // When the node's point of use is located earlier in the instruction
1279       // sequence than its prior point of use, update its debug info to the
1280       // earlier location.
1281       if (DL.getIROrder() && DL.getIROrder() < N->getIROrder())
1282         N->setDebugLoc(DL.getDebugLoc());
1283       break;
1284     }
1285   }
1286   return N;
1287 }
1288 
1289 void SelectionDAG::clear() {
1290   allnodes_clear();
1291   OperandRecycler.clear(OperandAllocator);
1292   OperandAllocator.Reset();
1293   CSEMap.clear();
1294 
1295   ExtendedValueTypeNodes.clear();
1296   ExternalSymbols.clear();
1297   TargetExternalSymbols.clear();
1298   MCSymbols.clear();
1299   SDCallSiteDbgInfo.clear();
1300   std::fill(CondCodeNodes.begin(), CondCodeNodes.end(),
1301             static_cast<CondCodeSDNode*>(nullptr));
1302   std::fill(ValueTypeNodes.begin(), ValueTypeNodes.end(),
1303             static_cast<SDNode*>(nullptr));
1304 
1305   EntryNode.UseList = nullptr;
1306   InsertNode(&EntryNode);
1307   Root = getEntryNode();
1308   DbgInfo->clear();
1309 }
1310 
1311 SDValue SelectionDAG::getFPExtendOrRound(SDValue Op, const SDLoc &DL, EVT VT) {
1312   return VT.bitsGT(Op.getValueType())
1313              ? getNode(ISD::FP_EXTEND, DL, VT, Op)
1314              : getNode(ISD::FP_ROUND, DL, VT, Op, getIntPtrConstant(0, DL));
1315 }
1316 
1317 std::pair<SDValue, SDValue>
1318 SelectionDAG::getStrictFPExtendOrRound(SDValue Op, SDValue Chain,
1319                                        const SDLoc &DL, EVT VT) {
1320   assert(!VT.bitsEq(Op.getValueType()) &&
1321          "Strict no-op FP extend/round not allowed.");
1322   SDValue Res =
1323       VT.bitsGT(Op.getValueType())
1324           ? getNode(ISD::STRICT_FP_EXTEND, DL, {VT, MVT::Other}, {Chain, Op})
1325           : getNode(ISD::STRICT_FP_ROUND, DL, {VT, MVT::Other},
1326                     {Chain, Op, getIntPtrConstant(0, DL)});
1327 
1328   return std::pair<SDValue, SDValue>(Res, SDValue(Res.getNode(), 1));
1329 }
1330 
1331 SDValue SelectionDAG::getAnyExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
1332   return VT.bitsGT(Op.getValueType()) ?
1333     getNode(ISD::ANY_EXTEND, DL, VT, Op) :
1334     getNode(ISD::TRUNCATE, DL, VT, Op);
1335 }
1336 
1337 SDValue SelectionDAG::getSExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
1338   return VT.bitsGT(Op.getValueType()) ?
1339     getNode(ISD::SIGN_EXTEND, DL, VT, Op) :
1340     getNode(ISD::TRUNCATE, DL, VT, Op);
1341 }
1342 
1343 SDValue SelectionDAG::getZExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
1344   return VT.bitsGT(Op.getValueType()) ?
1345     getNode(ISD::ZERO_EXTEND, DL, VT, Op) :
1346     getNode(ISD::TRUNCATE, DL, VT, Op);
1347 }
1348 
1349 SDValue SelectionDAG::getBoolExtOrTrunc(SDValue Op, const SDLoc &SL, EVT VT,
1350                                         EVT OpVT) {
1351   if (VT.bitsLE(Op.getValueType()))
1352     return getNode(ISD::TRUNCATE, SL, VT, Op);
1353 
1354   TargetLowering::BooleanContent BType = TLI->getBooleanContents(OpVT);
1355   return getNode(TLI->getExtendForContent(BType), SL, VT, Op);
1356 }
1357 
1358 SDValue SelectionDAG::getZeroExtendInReg(SDValue Op, const SDLoc &DL, EVT VT) {
1359   EVT OpVT = Op.getValueType();
1360   assert(VT.isInteger() && OpVT.isInteger() &&
1361          "Cannot getZeroExtendInReg FP types");
1362   assert(VT.isVector() == OpVT.isVector() &&
1363          "getZeroExtendInReg type should be vector iff the operand "
1364          "type is vector!");
1365   assert((!VT.isVector() ||
1366           VT.getVectorElementCount() == OpVT.getVectorElementCount()) &&
1367          "Vector element counts must match in getZeroExtendInReg");
1368   assert(VT.bitsLE(OpVT) && "Not extending!");
1369   if (OpVT == VT)
1370     return Op;
1371   APInt Imm = APInt::getLowBitsSet(OpVT.getScalarSizeInBits(),
1372                                    VT.getScalarSizeInBits());
1373   return getNode(ISD::AND, DL, OpVT, Op, getConstant(Imm, DL, OpVT));
1374 }
1375 
1376 SDValue SelectionDAG::getPtrExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
1377   // Only unsigned pointer semantics are supported right now. In the future this
1378   // might delegate to TLI to check pointer signedness.
1379   return getZExtOrTrunc(Op, DL, VT);
1380 }
1381 
1382 SDValue SelectionDAG::getPtrExtendInReg(SDValue Op, const SDLoc &DL, EVT VT) {
1383   // Only unsigned pointer semantics are supported right now. In the future this
1384   // might delegate to TLI to check pointer signedness.
1385   return getZeroExtendInReg(Op, DL, VT);
1386 }
1387 
1388 /// getNOT - Create a bitwise NOT operation as (XOR Val, -1).
1389 SDValue SelectionDAG::getNOT(const SDLoc &DL, SDValue Val, EVT VT) {
1390   return getNode(ISD::XOR, DL, VT, Val, getAllOnesConstant(DL, VT));
1391 }
1392 
1393 SDValue SelectionDAG::getLogicalNOT(const SDLoc &DL, SDValue Val, EVT VT) {
1394   SDValue TrueValue = getBoolConstant(true, DL, VT, VT);
1395   return getNode(ISD::XOR, DL, VT, Val, TrueValue);
1396 }
1397 
1398 SDValue SelectionDAG::getBoolConstant(bool V, const SDLoc &DL, EVT VT,
1399                                       EVT OpVT) {
1400   if (!V)
1401     return getConstant(0, DL, VT);
1402 
1403   switch (TLI->getBooleanContents(OpVT)) {
1404   case TargetLowering::ZeroOrOneBooleanContent:
1405   case TargetLowering::UndefinedBooleanContent:
1406     return getConstant(1, DL, VT);
1407   case TargetLowering::ZeroOrNegativeOneBooleanContent:
1408     return getAllOnesConstant(DL, VT);
1409   }
1410   llvm_unreachable("Unexpected boolean content enum!");
1411 }
1412 
1413 SDValue SelectionDAG::getConstant(uint64_t Val, const SDLoc &DL, EVT VT,
1414                                   bool isT, bool isO) {
1415   EVT EltVT = VT.getScalarType();
1416   assert((EltVT.getSizeInBits() >= 64 ||
1417           (uint64_t)((int64_t)Val >> EltVT.getSizeInBits()) + 1 < 2) &&
1418          "getConstant with a uint64_t value that doesn't fit in the type!");
1419   return getConstant(APInt(EltVT.getSizeInBits(), Val), DL, VT, isT, isO);
1420 }
1421 
1422 SDValue SelectionDAG::getConstant(const APInt &Val, const SDLoc &DL, EVT VT,
1423                                   bool isT, bool isO) {
1424   return getConstant(*ConstantInt::get(*Context, Val), DL, VT, isT, isO);
1425 }
1426 
1427 SDValue SelectionDAG::getConstant(const ConstantInt &Val, const SDLoc &DL,
1428                                   EVT VT, bool isT, bool isO) {
1429   assert(VT.isInteger() && "Cannot create FP integer constant!");
1430 
1431   EVT EltVT = VT.getScalarType();
1432   const ConstantInt *Elt = &Val;
1433 
1434   // In some cases the vector type is legal but the element type is illegal and
1435   // needs to be promoted, for example v8i8 on ARM.  In this case, promote the
1436   // inserted value (the type does not need to match the vector element type).
1437   // Any extra bits introduced will be truncated away.
1438   if (VT.isVector() && TLI->getTypeAction(*getContext(), EltVT) ==
1439                            TargetLowering::TypePromoteInteger) {
1440     EltVT = TLI->getTypeToTransformTo(*getContext(), EltVT);
1441     APInt NewVal = Elt->getValue().zextOrTrunc(EltVT.getSizeInBits());
1442     Elt = ConstantInt::get(*getContext(), NewVal);
1443   }
1444   // In other cases the element type is illegal and needs to be expanded, for
1445   // example v2i64 on MIPS32. In this case, find the nearest legal type, split
1446   // the value into n parts and use a vector type with n-times the elements.
1447   // Then bitcast to the type requested.
1448   // Legalizing constants too early makes the DAGCombiner's job harder so we
1449   // only legalize if the DAG tells us we must produce legal types.
1450   else if (NewNodesMustHaveLegalTypes && VT.isVector() &&
1451            TLI->getTypeAction(*getContext(), EltVT) ==
1452                TargetLowering::TypeExpandInteger) {
1453     const APInt &NewVal = Elt->getValue();
1454     EVT ViaEltVT = TLI->getTypeToTransformTo(*getContext(), EltVT);
1455     unsigned ViaEltSizeInBits = ViaEltVT.getSizeInBits();
1456 
1457     // For scalable vectors, try to use a SPLAT_VECTOR_PARTS node.
1458     if (VT.isScalableVector()) {
1459       assert(EltVT.getSizeInBits() % ViaEltSizeInBits == 0 &&
1460              "Can only handle an even split!");
1461       unsigned Parts = EltVT.getSizeInBits() / ViaEltSizeInBits;
1462 
1463       SmallVector<SDValue, 2> ScalarParts;
1464       for (unsigned i = 0; i != Parts; ++i)
1465         ScalarParts.push_back(getConstant(
1466             NewVal.extractBits(ViaEltSizeInBits, i * ViaEltSizeInBits), DL,
1467             ViaEltVT, isT, isO));
1468 
1469       return getNode(ISD::SPLAT_VECTOR_PARTS, DL, VT, ScalarParts);
1470     }
1471 
1472     unsigned ViaVecNumElts = VT.getSizeInBits() / ViaEltSizeInBits;
1473     EVT ViaVecVT = EVT::getVectorVT(*getContext(), ViaEltVT, ViaVecNumElts);
1474 
1475     // Check the temporary vector is the correct size. If this fails then
1476     // getTypeToTransformTo() probably returned a type whose size (in bits)
1477     // isn't a power-of-2 factor of the requested type size.
1478     assert(ViaVecVT.getSizeInBits() == VT.getSizeInBits());
1479 
1480     SmallVector<SDValue, 2> EltParts;
1481     for (unsigned i = 0; i < ViaVecNumElts / VT.getVectorNumElements(); ++i)
1482       EltParts.push_back(getConstant(
1483           NewVal.extractBits(ViaEltSizeInBits, i * ViaEltSizeInBits), DL,
1484           ViaEltVT, isT, isO));
1485 
1486     // EltParts is currently in little endian order. If we actually want
1487     // big-endian order then reverse it now.
1488     if (getDataLayout().isBigEndian())
1489       std::reverse(EltParts.begin(), EltParts.end());
1490 
1491     // The elements must be reversed when the element order is different
1492     // to the endianness of the elements (because the BITCAST is itself a
1493     // vector shuffle in this situation). However, we do not need any code to
1494     // perform this reversal because getConstant() is producing a vector
1495     // splat.
1496     // This situation occurs in MIPS MSA.
1497 
1498     SmallVector<SDValue, 8> Ops;
1499     for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
1500       llvm::append_range(Ops, EltParts);
1501 
1502     SDValue V =
1503         getNode(ISD::BITCAST, DL, VT, getBuildVector(ViaVecVT, DL, Ops));
1504     return V;
1505   }
1506 
1507   assert(Elt->getBitWidth() == EltVT.getSizeInBits() &&
1508          "APInt size does not match type size!");
1509   unsigned Opc = isT ? ISD::TargetConstant : ISD::Constant;
1510   FoldingSetNodeID ID;
1511   AddNodeIDNode(ID, Opc, getVTList(EltVT), None);
1512   ID.AddPointer(Elt);
1513   ID.AddBoolean(isO);
1514   void *IP = nullptr;
1515   SDNode *N = nullptr;
1516   if ((N = FindNodeOrInsertPos(ID, DL, IP)))
1517     if (!VT.isVector())
1518       return SDValue(N, 0);
1519 
1520   if (!N) {
1521     N = newSDNode<ConstantSDNode>(isT, isO, Elt, EltVT);
1522     CSEMap.InsertNode(N, IP);
1523     InsertNode(N);
1524     NewSDValueDbgMsg(SDValue(N, 0), "Creating constant: ", this);
1525   }
1526 
1527   SDValue Result(N, 0);
1528   if (VT.isScalableVector())
1529     Result = getSplatVector(VT, DL, Result);
1530   else if (VT.isVector())
1531     Result = getSplatBuildVector(VT, DL, Result);
1532 
1533   return Result;
1534 }
1535 
1536 SDValue SelectionDAG::getIntPtrConstant(uint64_t Val, const SDLoc &DL,
1537                                         bool isTarget) {
1538   return getConstant(Val, DL, TLI->getPointerTy(getDataLayout()), isTarget);
1539 }
1540 
1541 SDValue SelectionDAG::getShiftAmountConstant(uint64_t Val, EVT VT,
1542                                              const SDLoc &DL, bool LegalTypes) {
1543   assert(VT.isInteger() && "Shift amount is not an integer type!");
1544   EVT ShiftVT = TLI->getShiftAmountTy(VT, getDataLayout(), LegalTypes);
1545   return getConstant(Val, DL, ShiftVT);
1546 }
1547 
1548 SDValue SelectionDAG::getVectorIdxConstant(uint64_t Val, const SDLoc &DL,
1549                                            bool isTarget) {
1550   return getConstant(Val, DL, TLI->getVectorIdxTy(getDataLayout()), isTarget);
1551 }
1552 
1553 SDValue SelectionDAG::getConstantFP(const APFloat &V, const SDLoc &DL, EVT VT,
1554                                     bool isTarget) {
1555   return getConstantFP(*ConstantFP::get(*getContext(), V), DL, VT, isTarget);
1556 }
1557 
1558 SDValue SelectionDAG::getConstantFP(const ConstantFP &V, const SDLoc &DL,
1559                                     EVT VT, bool isTarget) {
1560   assert(VT.isFloatingPoint() && "Cannot create integer FP constant!");
1561 
1562   EVT EltVT = VT.getScalarType();
1563 
1564   // Do the map lookup using the actual bit pattern for the floating point
1565   // value, so that we don't have problems with 0.0 comparing equal to -0.0, and
1566   // we don't have issues with SNANs.
1567   unsigned Opc = isTarget ? ISD::TargetConstantFP : ISD::ConstantFP;
1568   FoldingSetNodeID ID;
1569   AddNodeIDNode(ID, Opc, getVTList(EltVT), None);
1570   ID.AddPointer(&V);
1571   void *IP = nullptr;
1572   SDNode *N = nullptr;
1573   if ((N = FindNodeOrInsertPos(ID, DL, IP)))
1574     if (!VT.isVector())
1575       return SDValue(N, 0);
1576 
1577   if (!N) {
1578     N = newSDNode<ConstantFPSDNode>(isTarget, &V, EltVT);
1579     CSEMap.InsertNode(N, IP);
1580     InsertNode(N);
1581   }
1582 
1583   SDValue Result(N, 0);
1584   if (VT.isScalableVector())
1585     Result = getSplatVector(VT, DL, Result);
1586   else if (VT.isVector())
1587     Result = getSplatBuildVector(VT, DL, Result);
1588   NewSDValueDbgMsg(Result, "Creating fp constant: ", this);
1589   return Result;
1590 }
1591 
1592 SDValue SelectionDAG::getConstantFP(double Val, const SDLoc &DL, EVT VT,
1593                                     bool isTarget) {
1594   EVT EltVT = VT.getScalarType();
1595   if (EltVT == MVT::f32)
1596     return getConstantFP(APFloat((float)Val), DL, VT, isTarget);
1597   if (EltVT == MVT::f64)
1598     return getConstantFP(APFloat(Val), DL, VT, isTarget);
1599   if (EltVT == MVT::f80 || EltVT == MVT::f128 || EltVT == MVT::ppcf128 ||
1600       EltVT == MVT::f16 || EltVT == MVT::bf16) {
1601     bool Ignored;
1602     APFloat APF = APFloat(Val);
1603     APF.convert(EVTToAPFloatSemantics(EltVT), APFloat::rmNearestTiesToEven,
1604                 &Ignored);
1605     return getConstantFP(APF, DL, VT, isTarget);
1606   }
1607   llvm_unreachable("Unsupported type in getConstantFP");
1608 }
1609 
1610 SDValue SelectionDAG::getGlobalAddress(const GlobalValue *GV, const SDLoc &DL,
1611                                        EVT VT, int64_t Offset, bool isTargetGA,
1612                                        unsigned TargetFlags) {
1613   assert((TargetFlags == 0 || isTargetGA) &&
1614          "Cannot set target flags on target-independent globals");
1615 
1616   // Truncate (with sign-extension) the offset value to the pointer size.
1617   unsigned BitWidth = getDataLayout().getPointerTypeSizeInBits(GV->getType());
1618   if (BitWidth < 64)
1619     Offset = SignExtend64(Offset, BitWidth);
1620 
1621   unsigned Opc;
1622   if (GV->isThreadLocal())
1623     Opc = isTargetGA ? ISD::TargetGlobalTLSAddress : ISD::GlobalTLSAddress;
1624   else
1625     Opc = isTargetGA ? ISD::TargetGlobalAddress : ISD::GlobalAddress;
1626 
1627   FoldingSetNodeID ID;
1628   AddNodeIDNode(ID, Opc, getVTList(VT), None);
1629   ID.AddPointer(GV);
1630   ID.AddInteger(Offset);
1631   ID.AddInteger(TargetFlags);
1632   void *IP = nullptr;
1633   if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
1634     return SDValue(E, 0);
1635 
1636   auto *N = newSDNode<GlobalAddressSDNode>(
1637       Opc, DL.getIROrder(), DL.getDebugLoc(), GV, VT, Offset, TargetFlags);
1638   CSEMap.InsertNode(N, IP);
1639     InsertNode(N);
1640   return SDValue(N, 0);
1641 }
1642 
1643 SDValue SelectionDAG::getFrameIndex(int FI, EVT VT, bool isTarget) {
1644   unsigned Opc = isTarget ? ISD::TargetFrameIndex : ISD::FrameIndex;
1645   FoldingSetNodeID ID;
1646   AddNodeIDNode(ID, Opc, getVTList(VT), None);
1647   ID.AddInteger(FI);
1648   void *IP = nullptr;
1649   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1650     return SDValue(E, 0);
1651 
1652   auto *N = newSDNode<FrameIndexSDNode>(FI, VT, isTarget);
1653   CSEMap.InsertNode(N, IP);
1654   InsertNode(N);
1655   return SDValue(N, 0);
1656 }
1657 
1658 SDValue SelectionDAG::getJumpTable(int JTI, EVT VT, bool isTarget,
1659                                    unsigned TargetFlags) {
1660   assert((TargetFlags == 0 || isTarget) &&
1661          "Cannot set target flags on target-independent jump tables");
1662   unsigned Opc = isTarget ? ISD::TargetJumpTable : ISD::JumpTable;
1663   FoldingSetNodeID ID;
1664   AddNodeIDNode(ID, Opc, getVTList(VT), None);
1665   ID.AddInteger(JTI);
1666   ID.AddInteger(TargetFlags);
1667   void *IP = nullptr;
1668   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1669     return SDValue(E, 0);
1670 
1671   auto *N = newSDNode<JumpTableSDNode>(JTI, VT, isTarget, TargetFlags);
1672   CSEMap.InsertNode(N, IP);
1673   InsertNode(N);
1674   return SDValue(N, 0);
1675 }
1676 
1677 SDValue SelectionDAG::getConstantPool(const Constant *C, EVT VT,
1678                                       MaybeAlign Alignment, int Offset,
1679                                       bool isTarget, unsigned TargetFlags) {
1680   assert((TargetFlags == 0 || isTarget) &&
1681          "Cannot set target flags on target-independent globals");
1682   if (!Alignment)
1683     Alignment = shouldOptForSize()
1684                     ? getDataLayout().getABITypeAlign(C->getType())
1685                     : getDataLayout().getPrefTypeAlign(C->getType());
1686   unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
1687   FoldingSetNodeID ID;
1688   AddNodeIDNode(ID, Opc, getVTList(VT), None);
1689   ID.AddInteger(Alignment->value());
1690   ID.AddInteger(Offset);
1691   ID.AddPointer(C);
1692   ID.AddInteger(TargetFlags);
1693   void *IP = nullptr;
1694   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1695     return SDValue(E, 0);
1696 
1697   auto *N = newSDNode<ConstantPoolSDNode>(isTarget, C, VT, Offset, *Alignment,
1698                                           TargetFlags);
1699   CSEMap.InsertNode(N, IP);
1700   InsertNode(N);
1701   SDValue V = SDValue(N, 0);
1702   NewSDValueDbgMsg(V, "Creating new constant pool: ", this);
1703   return V;
1704 }
1705 
1706 SDValue SelectionDAG::getConstantPool(MachineConstantPoolValue *C, EVT VT,
1707                                       MaybeAlign Alignment, int Offset,
1708                                       bool isTarget, unsigned TargetFlags) {
1709   assert((TargetFlags == 0 || isTarget) &&
1710          "Cannot set target flags on target-independent globals");
1711   if (!Alignment)
1712     Alignment = getDataLayout().getPrefTypeAlign(C->getType());
1713   unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
1714   FoldingSetNodeID ID;
1715   AddNodeIDNode(ID, Opc, getVTList(VT), None);
1716   ID.AddInteger(Alignment->value());
1717   ID.AddInteger(Offset);
1718   C->addSelectionDAGCSEId(ID);
1719   ID.AddInteger(TargetFlags);
1720   void *IP = nullptr;
1721   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1722     return SDValue(E, 0);
1723 
1724   auto *N = newSDNode<ConstantPoolSDNode>(isTarget, C, VT, Offset, *Alignment,
1725                                           TargetFlags);
1726   CSEMap.InsertNode(N, IP);
1727   InsertNode(N);
1728   return SDValue(N, 0);
1729 }
1730 
1731 SDValue SelectionDAG::getTargetIndex(int Index, EVT VT, int64_t Offset,
1732                                      unsigned TargetFlags) {
1733   FoldingSetNodeID ID;
1734   AddNodeIDNode(ID, ISD::TargetIndex, getVTList(VT), None);
1735   ID.AddInteger(Index);
1736   ID.AddInteger(Offset);
1737   ID.AddInteger(TargetFlags);
1738   void *IP = nullptr;
1739   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1740     return SDValue(E, 0);
1741 
1742   auto *N = newSDNode<TargetIndexSDNode>(Index, VT, Offset, TargetFlags);
1743   CSEMap.InsertNode(N, IP);
1744   InsertNode(N);
1745   return SDValue(N, 0);
1746 }
1747 
1748 SDValue SelectionDAG::getBasicBlock(MachineBasicBlock *MBB) {
1749   FoldingSetNodeID ID;
1750   AddNodeIDNode(ID, ISD::BasicBlock, getVTList(MVT::Other), None);
1751   ID.AddPointer(MBB);
1752   void *IP = nullptr;
1753   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1754     return SDValue(E, 0);
1755 
1756   auto *N = newSDNode<BasicBlockSDNode>(MBB);
1757   CSEMap.InsertNode(N, IP);
1758   InsertNode(N);
1759   return SDValue(N, 0);
1760 }
1761 
1762 SDValue SelectionDAG::getValueType(EVT VT) {
1763   if (VT.isSimple() && (unsigned)VT.getSimpleVT().SimpleTy >=
1764       ValueTypeNodes.size())
1765     ValueTypeNodes.resize(VT.getSimpleVT().SimpleTy+1);
1766 
1767   SDNode *&N = VT.isExtended() ?
1768     ExtendedValueTypeNodes[VT] : ValueTypeNodes[VT.getSimpleVT().SimpleTy];
1769 
1770   if (N) return SDValue(N, 0);
1771   N = newSDNode<VTSDNode>(VT);
1772   InsertNode(N);
1773   return SDValue(N, 0);
1774 }
1775 
1776 SDValue SelectionDAG::getExternalSymbol(const char *Sym, EVT VT) {
1777   SDNode *&N = ExternalSymbols[Sym];
1778   if (N) return SDValue(N, 0);
1779   N = newSDNode<ExternalSymbolSDNode>(false, Sym, 0, VT);
1780   InsertNode(N);
1781   return SDValue(N, 0);
1782 }
1783 
1784 SDValue SelectionDAG::getMCSymbol(MCSymbol *Sym, EVT VT) {
1785   SDNode *&N = MCSymbols[Sym];
1786   if (N)
1787     return SDValue(N, 0);
1788   N = newSDNode<MCSymbolSDNode>(Sym, VT);
1789   InsertNode(N);
1790   return SDValue(N, 0);
1791 }
1792 
1793 SDValue SelectionDAG::getTargetExternalSymbol(const char *Sym, EVT VT,
1794                                               unsigned TargetFlags) {
1795   SDNode *&N =
1796       TargetExternalSymbols[std::pair<std::string, unsigned>(Sym, TargetFlags)];
1797   if (N) return SDValue(N, 0);
1798   N = newSDNode<ExternalSymbolSDNode>(true, Sym, TargetFlags, VT);
1799   InsertNode(N);
1800   return SDValue(N, 0);
1801 }
1802 
1803 SDValue SelectionDAG::getCondCode(ISD::CondCode Cond) {
1804   if ((unsigned)Cond >= CondCodeNodes.size())
1805     CondCodeNodes.resize(Cond+1);
1806 
1807   if (!CondCodeNodes[Cond]) {
1808     auto *N = newSDNode<CondCodeSDNode>(Cond);
1809     CondCodeNodes[Cond] = N;
1810     InsertNode(N);
1811   }
1812 
1813   return SDValue(CondCodeNodes[Cond], 0);
1814 }
1815 
1816 SDValue SelectionDAG::getStepVector(const SDLoc &DL, EVT ResVT) {
1817   APInt One(ResVT.getScalarSizeInBits(), 1);
1818   return getStepVector(DL, ResVT, One);
1819 }
1820 
1821 SDValue SelectionDAG::getStepVector(const SDLoc &DL, EVT ResVT, APInt StepVal) {
1822   assert(ResVT.getScalarSizeInBits() == StepVal.getBitWidth());
1823   if (ResVT.isScalableVector())
1824     return getNode(
1825         ISD::STEP_VECTOR, DL, ResVT,
1826         getTargetConstant(StepVal, DL, ResVT.getVectorElementType()));
1827 
1828   SmallVector<SDValue, 16> OpsStepConstants;
1829   for (uint64_t i = 0; i < ResVT.getVectorNumElements(); i++)
1830     OpsStepConstants.push_back(
1831         getConstant(StepVal * i, DL, ResVT.getVectorElementType()));
1832   return getBuildVector(ResVT, DL, OpsStepConstants);
1833 }
1834 
1835 /// Swaps the values of N1 and N2. Swaps all indices in the shuffle mask M that
1836 /// point at N1 to point at N2 and indices that point at N2 to point at N1.
1837 static void commuteShuffle(SDValue &N1, SDValue &N2, MutableArrayRef<int> M) {
1838   std::swap(N1, N2);
1839   ShuffleVectorSDNode::commuteMask(M);
1840 }
1841 
1842 SDValue SelectionDAG::getVectorShuffle(EVT VT, const SDLoc &dl, SDValue N1,
1843                                        SDValue N2, ArrayRef<int> Mask) {
1844   assert(VT.getVectorNumElements() == Mask.size() &&
1845          "Must have the same number of vector elements as mask elements!");
1846   assert(VT == N1.getValueType() && VT == N2.getValueType() &&
1847          "Invalid VECTOR_SHUFFLE");
1848 
1849   // Canonicalize shuffle undef, undef -> undef
1850   if (N1.isUndef() && N2.isUndef())
1851     return getUNDEF(VT);
1852 
1853   // Validate that all indices in Mask are within the range of the elements
1854   // input to the shuffle.
1855   int NElts = Mask.size();
1856   assert(llvm::all_of(Mask,
1857                       [&](int M) { return M < (NElts * 2) && M >= -1; }) &&
1858          "Index out of range");
1859 
1860   // Copy the mask so we can do any needed cleanup.
1861   SmallVector<int, 8> MaskVec(Mask.begin(), Mask.end());
1862 
1863   // Canonicalize shuffle v, v -> v, undef
1864   if (N1 == N2) {
1865     N2 = getUNDEF(VT);
1866     for (int i = 0; i != NElts; ++i)
1867       if (MaskVec[i] >= NElts) MaskVec[i] -= NElts;
1868   }
1869 
1870   // Canonicalize shuffle undef, v -> v, undef.  Commute the shuffle mask.
1871   if (N1.isUndef())
1872     commuteShuffle(N1, N2, MaskVec);
1873 
1874   if (TLI->hasVectorBlend()) {
1875     // If shuffling a splat, try to blend the splat instead. We do this here so
1876     // that even when this arises during lowering we don't have to re-handle it.
1877     auto BlendSplat = [&](BuildVectorSDNode *BV, int Offset) {
1878       BitVector UndefElements;
1879       SDValue Splat = BV->getSplatValue(&UndefElements);
1880       if (!Splat)
1881         return;
1882 
1883       for (int i = 0; i < NElts; ++i) {
1884         if (MaskVec[i] < Offset || MaskVec[i] >= (Offset + NElts))
1885           continue;
1886 
1887         // If this input comes from undef, mark it as such.
1888         if (UndefElements[MaskVec[i] - Offset]) {
1889           MaskVec[i] = -1;
1890           continue;
1891         }
1892 
1893         // If we can blend a non-undef lane, use that instead.
1894         if (!UndefElements[i])
1895           MaskVec[i] = i + Offset;
1896       }
1897     };
1898     if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
1899       BlendSplat(N1BV, 0);
1900     if (auto *N2BV = dyn_cast<BuildVectorSDNode>(N2))
1901       BlendSplat(N2BV, NElts);
1902   }
1903 
1904   // Canonicalize all index into lhs, -> shuffle lhs, undef
1905   // Canonicalize all index into rhs, -> shuffle rhs, undef
1906   bool AllLHS = true, AllRHS = true;
1907   bool N2Undef = N2.isUndef();
1908   for (int i = 0; i != NElts; ++i) {
1909     if (MaskVec[i] >= NElts) {
1910       if (N2Undef)
1911         MaskVec[i] = -1;
1912       else
1913         AllLHS = false;
1914     } else if (MaskVec[i] >= 0) {
1915       AllRHS = false;
1916     }
1917   }
1918   if (AllLHS && AllRHS)
1919     return getUNDEF(VT);
1920   if (AllLHS && !N2Undef)
1921     N2 = getUNDEF(VT);
1922   if (AllRHS) {
1923     N1 = getUNDEF(VT);
1924     commuteShuffle(N1, N2, MaskVec);
1925   }
1926   // Reset our undef status after accounting for the mask.
1927   N2Undef = N2.isUndef();
1928   // Re-check whether both sides ended up undef.
1929   if (N1.isUndef() && N2Undef)
1930     return getUNDEF(VT);
1931 
1932   // If Identity shuffle return that node.
1933   bool Identity = true, AllSame = true;
1934   for (int i = 0; i != NElts; ++i) {
1935     if (MaskVec[i] >= 0 && MaskVec[i] != i) Identity = false;
1936     if (MaskVec[i] != MaskVec[0]) AllSame = false;
1937   }
1938   if (Identity && NElts)
1939     return N1;
1940 
1941   // Shuffling a constant splat doesn't change the result.
1942   if (N2Undef) {
1943     SDValue V = N1;
1944 
1945     // Look through any bitcasts. We check that these don't change the number
1946     // (and size) of elements and just changes their types.
1947     while (V.getOpcode() == ISD::BITCAST)
1948       V = V->getOperand(0);
1949 
1950     // A splat should always show up as a build vector node.
1951     if (auto *BV = dyn_cast<BuildVectorSDNode>(V)) {
1952       BitVector UndefElements;
1953       SDValue Splat = BV->getSplatValue(&UndefElements);
1954       // If this is a splat of an undef, shuffling it is also undef.
1955       if (Splat && Splat.isUndef())
1956         return getUNDEF(VT);
1957 
1958       bool SameNumElts =
1959           V.getValueType().getVectorNumElements() == VT.getVectorNumElements();
1960 
1961       // We only have a splat which can skip shuffles if there is a splatted
1962       // value and no undef lanes rearranged by the shuffle.
1963       if (Splat && UndefElements.none()) {
1964         // Splat of <x, x, ..., x>, return <x, x, ..., x>, provided that the
1965         // number of elements match or the value splatted is a zero constant.
1966         if (SameNumElts)
1967           return N1;
1968         if (auto *C = dyn_cast<ConstantSDNode>(Splat))
1969           if (C->isZero())
1970             return N1;
1971       }
1972 
1973       // If the shuffle itself creates a splat, build the vector directly.
1974       if (AllSame && SameNumElts) {
1975         EVT BuildVT = BV->getValueType(0);
1976         const SDValue &Splatted = BV->getOperand(MaskVec[0]);
1977         SDValue NewBV = getSplatBuildVector(BuildVT, dl, Splatted);
1978 
1979         // We may have jumped through bitcasts, so the type of the
1980         // BUILD_VECTOR may not match the type of the shuffle.
1981         if (BuildVT != VT)
1982           NewBV = getNode(ISD::BITCAST, dl, VT, NewBV);
1983         return NewBV;
1984       }
1985     }
1986   }
1987 
1988   FoldingSetNodeID ID;
1989   SDValue Ops[2] = { N1, N2 };
1990   AddNodeIDNode(ID, ISD::VECTOR_SHUFFLE, getVTList(VT), Ops);
1991   for (int i = 0; i != NElts; ++i)
1992     ID.AddInteger(MaskVec[i]);
1993 
1994   void* IP = nullptr;
1995   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
1996     return SDValue(E, 0);
1997 
1998   // Allocate the mask array for the node out of the BumpPtrAllocator, since
1999   // SDNode doesn't have access to it.  This memory will be "leaked" when
2000   // the node is deallocated, but recovered when the NodeAllocator is released.
2001   int *MaskAlloc = OperandAllocator.Allocate<int>(NElts);
2002   llvm::copy(MaskVec, MaskAlloc);
2003 
2004   auto *N = newSDNode<ShuffleVectorSDNode>(VT, dl.getIROrder(),
2005                                            dl.getDebugLoc(), MaskAlloc);
2006   createOperands(N, Ops);
2007 
2008   CSEMap.InsertNode(N, IP);
2009   InsertNode(N);
2010   SDValue V = SDValue(N, 0);
2011   NewSDValueDbgMsg(V, "Creating new node: ", this);
2012   return V;
2013 }
2014 
2015 SDValue SelectionDAG::getCommutedVectorShuffle(const ShuffleVectorSDNode &SV) {
2016   EVT VT = SV.getValueType(0);
2017   SmallVector<int, 8> MaskVec(SV.getMask().begin(), SV.getMask().end());
2018   ShuffleVectorSDNode::commuteMask(MaskVec);
2019 
2020   SDValue Op0 = SV.getOperand(0);
2021   SDValue Op1 = SV.getOperand(1);
2022   return getVectorShuffle(VT, SDLoc(&SV), Op1, Op0, MaskVec);
2023 }
2024 
2025 SDValue SelectionDAG::getRegister(unsigned RegNo, EVT VT) {
2026   FoldingSetNodeID ID;
2027   AddNodeIDNode(ID, ISD::Register, getVTList(VT), None);
2028   ID.AddInteger(RegNo);
2029   void *IP = nullptr;
2030   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2031     return SDValue(E, 0);
2032 
2033   auto *N = newSDNode<RegisterSDNode>(RegNo, VT);
2034   N->SDNodeBits.IsDivergent = TLI->isSDNodeSourceOfDivergence(N, FLI, DA);
2035   CSEMap.InsertNode(N, IP);
2036   InsertNode(N);
2037   return SDValue(N, 0);
2038 }
2039 
2040 SDValue SelectionDAG::getRegisterMask(const uint32_t *RegMask) {
2041   FoldingSetNodeID ID;
2042   AddNodeIDNode(ID, ISD::RegisterMask, getVTList(MVT::Untyped), None);
2043   ID.AddPointer(RegMask);
2044   void *IP = nullptr;
2045   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2046     return SDValue(E, 0);
2047 
2048   auto *N = newSDNode<RegisterMaskSDNode>(RegMask);
2049   CSEMap.InsertNode(N, IP);
2050   InsertNode(N);
2051   return SDValue(N, 0);
2052 }
2053 
2054 SDValue SelectionDAG::getEHLabel(const SDLoc &dl, SDValue Root,
2055                                  MCSymbol *Label) {
2056   return getLabelNode(ISD::EH_LABEL, dl, Root, Label);
2057 }
2058 
2059 SDValue SelectionDAG::getLabelNode(unsigned Opcode, const SDLoc &dl,
2060                                    SDValue Root, MCSymbol *Label) {
2061   FoldingSetNodeID ID;
2062   SDValue Ops[] = { Root };
2063   AddNodeIDNode(ID, Opcode, getVTList(MVT::Other), Ops);
2064   ID.AddPointer(Label);
2065   void *IP = nullptr;
2066   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2067     return SDValue(E, 0);
2068 
2069   auto *N =
2070       newSDNode<LabelSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(), Label);
2071   createOperands(N, Ops);
2072 
2073   CSEMap.InsertNode(N, IP);
2074   InsertNode(N);
2075   return SDValue(N, 0);
2076 }
2077 
2078 SDValue SelectionDAG::getBlockAddress(const BlockAddress *BA, EVT VT,
2079                                       int64_t Offset, bool isTarget,
2080                                       unsigned TargetFlags) {
2081   unsigned Opc = isTarget ? ISD::TargetBlockAddress : ISD::BlockAddress;
2082 
2083   FoldingSetNodeID ID;
2084   AddNodeIDNode(ID, Opc, getVTList(VT), None);
2085   ID.AddPointer(BA);
2086   ID.AddInteger(Offset);
2087   ID.AddInteger(TargetFlags);
2088   void *IP = nullptr;
2089   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2090     return SDValue(E, 0);
2091 
2092   auto *N = newSDNode<BlockAddressSDNode>(Opc, VT, BA, Offset, TargetFlags);
2093   CSEMap.InsertNode(N, IP);
2094   InsertNode(N);
2095   return SDValue(N, 0);
2096 }
2097 
2098 SDValue SelectionDAG::getSrcValue(const Value *V) {
2099   FoldingSetNodeID ID;
2100   AddNodeIDNode(ID, ISD::SRCVALUE, getVTList(MVT::Other), None);
2101   ID.AddPointer(V);
2102 
2103   void *IP = nullptr;
2104   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2105     return SDValue(E, 0);
2106 
2107   auto *N = newSDNode<SrcValueSDNode>(V);
2108   CSEMap.InsertNode(N, IP);
2109   InsertNode(N);
2110   return SDValue(N, 0);
2111 }
2112 
2113 SDValue SelectionDAG::getMDNode(const MDNode *MD) {
2114   FoldingSetNodeID ID;
2115   AddNodeIDNode(ID, ISD::MDNODE_SDNODE, getVTList(MVT::Other), None);
2116   ID.AddPointer(MD);
2117 
2118   void *IP = nullptr;
2119   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2120     return SDValue(E, 0);
2121 
2122   auto *N = newSDNode<MDNodeSDNode>(MD);
2123   CSEMap.InsertNode(N, IP);
2124   InsertNode(N);
2125   return SDValue(N, 0);
2126 }
2127 
2128 SDValue SelectionDAG::getBitcast(EVT VT, SDValue V) {
2129   if (VT == V.getValueType())
2130     return V;
2131 
2132   return getNode(ISD::BITCAST, SDLoc(V), VT, V);
2133 }
2134 
2135 SDValue SelectionDAG::getAddrSpaceCast(const SDLoc &dl, EVT VT, SDValue Ptr,
2136                                        unsigned SrcAS, unsigned DestAS) {
2137   SDValue Ops[] = {Ptr};
2138   FoldingSetNodeID ID;
2139   AddNodeIDNode(ID, ISD::ADDRSPACECAST, getVTList(VT), Ops);
2140   ID.AddInteger(SrcAS);
2141   ID.AddInteger(DestAS);
2142 
2143   void *IP = nullptr;
2144   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
2145     return SDValue(E, 0);
2146 
2147   auto *N = newSDNode<AddrSpaceCastSDNode>(dl.getIROrder(), dl.getDebugLoc(),
2148                                            VT, SrcAS, DestAS);
2149   createOperands(N, Ops);
2150 
2151   CSEMap.InsertNode(N, IP);
2152   InsertNode(N);
2153   return SDValue(N, 0);
2154 }
2155 
2156 SDValue SelectionDAG::getFreeze(SDValue V) {
2157   return getNode(ISD::FREEZE, SDLoc(V), V.getValueType(), V);
2158 }
2159 
2160 /// getShiftAmountOperand - Return the specified value casted to
2161 /// the target's desired shift amount type.
2162 SDValue SelectionDAG::getShiftAmountOperand(EVT LHSTy, SDValue Op) {
2163   EVT OpTy = Op.getValueType();
2164   EVT ShTy = TLI->getShiftAmountTy(LHSTy, getDataLayout());
2165   if (OpTy == ShTy || OpTy.isVector()) return Op;
2166 
2167   return getZExtOrTrunc(Op, SDLoc(Op), ShTy);
2168 }
2169 
2170 SDValue SelectionDAG::expandVAArg(SDNode *Node) {
2171   SDLoc dl(Node);
2172   const TargetLowering &TLI = getTargetLoweringInfo();
2173   const Value *V = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
2174   EVT VT = Node->getValueType(0);
2175   SDValue Tmp1 = Node->getOperand(0);
2176   SDValue Tmp2 = Node->getOperand(1);
2177   const MaybeAlign MA(Node->getConstantOperandVal(3));
2178 
2179   SDValue VAListLoad = getLoad(TLI.getPointerTy(getDataLayout()), dl, Tmp1,
2180                                Tmp2, MachinePointerInfo(V));
2181   SDValue VAList = VAListLoad;
2182 
2183   if (MA && *MA > TLI.getMinStackArgumentAlignment()) {
2184     VAList = getNode(ISD::ADD, dl, VAList.getValueType(), VAList,
2185                      getConstant(MA->value() - 1, dl, VAList.getValueType()));
2186 
2187     VAList =
2188         getNode(ISD::AND, dl, VAList.getValueType(), VAList,
2189                 getConstant(-(int64_t)MA->value(), dl, VAList.getValueType()));
2190   }
2191 
2192   // Increment the pointer, VAList, to the next vaarg
2193   Tmp1 = getNode(ISD::ADD, dl, VAList.getValueType(), VAList,
2194                  getConstant(getDataLayout().getTypeAllocSize(
2195                                                VT.getTypeForEVT(*getContext())),
2196                              dl, VAList.getValueType()));
2197   // Store the incremented VAList to the legalized pointer
2198   Tmp1 =
2199       getStore(VAListLoad.getValue(1), dl, Tmp1, Tmp2, MachinePointerInfo(V));
2200   // Load the actual argument out of the pointer VAList
2201   return getLoad(VT, dl, Tmp1, VAList, MachinePointerInfo());
2202 }
2203 
2204 SDValue SelectionDAG::expandVACopy(SDNode *Node) {
2205   SDLoc dl(Node);
2206   const TargetLowering &TLI = getTargetLoweringInfo();
2207   // This defaults to loading a pointer from the input and storing it to the
2208   // output, returning the chain.
2209   const Value *VD = cast<SrcValueSDNode>(Node->getOperand(3))->getValue();
2210   const Value *VS = cast<SrcValueSDNode>(Node->getOperand(4))->getValue();
2211   SDValue Tmp1 =
2212       getLoad(TLI.getPointerTy(getDataLayout()), dl, Node->getOperand(0),
2213               Node->getOperand(2), MachinePointerInfo(VS));
2214   return getStore(Tmp1.getValue(1), dl, Tmp1, Node->getOperand(1),
2215                   MachinePointerInfo(VD));
2216 }
2217 
2218 Align SelectionDAG::getReducedAlign(EVT VT, bool UseABI) {
2219   const DataLayout &DL = getDataLayout();
2220   Type *Ty = VT.getTypeForEVT(*getContext());
2221   Align RedAlign = UseABI ? DL.getABITypeAlign(Ty) : DL.getPrefTypeAlign(Ty);
2222 
2223   if (TLI->isTypeLegal(VT) || !VT.isVector())
2224     return RedAlign;
2225 
2226   const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering();
2227   const Align StackAlign = TFI->getStackAlign();
2228 
2229   // See if we can choose a smaller ABI alignment in cases where it's an
2230   // illegal vector type that will get broken down.
2231   if (RedAlign > StackAlign) {
2232     EVT IntermediateVT;
2233     MVT RegisterVT;
2234     unsigned NumIntermediates;
2235     TLI->getVectorTypeBreakdown(*getContext(), VT, IntermediateVT,
2236                                 NumIntermediates, RegisterVT);
2237     Ty = IntermediateVT.getTypeForEVT(*getContext());
2238     Align RedAlign2 = UseABI ? DL.getABITypeAlign(Ty) : DL.getPrefTypeAlign(Ty);
2239     if (RedAlign2 < RedAlign)
2240       RedAlign = RedAlign2;
2241   }
2242 
2243   return RedAlign;
2244 }
2245 
2246 SDValue SelectionDAG::CreateStackTemporary(TypeSize Bytes, Align Alignment) {
2247   MachineFrameInfo &MFI = MF->getFrameInfo();
2248   const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering();
2249   int StackID = 0;
2250   if (Bytes.isScalable())
2251     StackID = TFI->getStackIDForScalableVectors();
2252   // The stack id gives an indication of whether the object is scalable or
2253   // not, so it's safe to pass in the minimum size here.
2254   int FrameIdx = MFI.CreateStackObject(Bytes.getKnownMinSize(), Alignment,
2255                                        false, nullptr, StackID);
2256   return getFrameIndex(FrameIdx, TLI->getFrameIndexTy(getDataLayout()));
2257 }
2258 
2259 SDValue SelectionDAG::CreateStackTemporary(EVT VT, unsigned minAlign) {
2260   Type *Ty = VT.getTypeForEVT(*getContext());
2261   Align StackAlign =
2262       std::max(getDataLayout().getPrefTypeAlign(Ty), Align(minAlign));
2263   return CreateStackTemporary(VT.getStoreSize(), StackAlign);
2264 }
2265 
2266 SDValue SelectionDAG::CreateStackTemporary(EVT VT1, EVT VT2) {
2267   TypeSize VT1Size = VT1.getStoreSize();
2268   TypeSize VT2Size = VT2.getStoreSize();
2269   assert(VT1Size.isScalable() == VT2Size.isScalable() &&
2270          "Don't know how to choose the maximum size when creating a stack "
2271          "temporary");
2272   TypeSize Bytes =
2273       VT1Size.getKnownMinSize() > VT2Size.getKnownMinSize() ? VT1Size : VT2Size;
2274 
2275   Type *Ty1 = VT1.getTypeForEVT(*getContext());
2276   Type *Ty2 = VT2.getTypeForEVT(*getContext());
2277   const DataLayout &DL = getDataLayout();
2278   Align Align = std::max(DL.getPrefTypeAlign(Ty1), DL.getPrefTypeAlign(Ty2));
2279   return CreateStackTemporary(Bytes, Align);
2280 }
2281 
2282 SDValue SelectionDAG::FoldSetCC(EVT VT, SDValue N1, SDValue N2,
2283                                 ISD::CondCode Cond, const SDLoc &dl) {
2284   EVT OpVT = N1.getValueType();
2285 
2286   // These setcc operations always fold.
2287   switch (Cond) {
2288   default: break;
2289   case ISD::SETFALSE:
2290   case ISD::SETFALSE2: return getBoolConstant(false, dl, VT, OpVT);
2291   case ISD::SETTRUE:
2292   case ISD::SETTRUE2: return getBoolConstant(true, dl, VT, OpVT);
2293 
2294   case ISD::SETOEQ:
2295   case ISD::SETOGT:
2296   case ISD::SETOGE:
2297   case ISD::SETOLT:
2298   case ISD::SETOLE:
2299   case ISD::SETONE:
2300   case ISD::SETO:
2301   case ISD::SETUO:
2302   case ISD::SETUEQ:
2303   case ISD::SETUNE:
2304     assert(!OpVT.isInteger() && "Illegal setcc for integer!");
2305     break;
2306   }
2307 
2308   if (OpVT.isInteger()) {
2309     // For EQ and NE, we can always pick a value for the undef to make the
2310     // predicate pass or fail, so we can return undef.
2311     // Matches behavior in llvm::ConstantFoldCompareInstruction.
2312     // icmp eq/ne X, undef -> undef.
2313     if ((N1.isUndef() || N2.isUndef()) &&
2314         (Cond == ISD::SETEQ || Cond == ISD::SETNE))
2315       return getUNDEF(VT);
2316 
2317     // If both operands are undef, we can return undef for int comparison.
2318     // icmp undef, undef -> undef.
2319     if (N1.isUndef() && N2.isUndef())
2320       return getUNDEF(VT);
2321 
2322     // icmp X, X -> true/false
2323     // icmp X, undef -> true/false because undef could be X.
2324     if (N1 == N2)
2325       return getBoolConstant(ISD::isTrueWhenEqual(Cond), dl, VT, OpVT);
2326   }
2327 
2328   if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2)) {
2329     const APInt &C2 = N2C->getAPIntValue();
2330     if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1)) {
2331       const APInt &C1 = N1C->getAPIntValue();
2332 
2333       return getBoolConstant(ICmpInst::compare(C1, C2, getICmpCondCode(Cond)),
2334                              dl, VT, OpVT);
2335     }
2336   }
2337 
2338   auto *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
2339   auto *N2CFP = dyn_cast<ConstantFPSDNode>(N2);
2340 
2341   if (N1CFP && N2CFP) {
2342     APFloat::cmpResult R = N1CFP->getValueAPF().compare(N2CFP->getValueAPF());
2343     switch (Cond) {
2344     default: break;
2345     case ISD::SETEQ:  if (R==APFloat::cmpUnordered)
2346                         return getUNDEF(VT);
2347                       LLVM_FALLTHROUGH;
2348     case ISD::SETOEQ: return getBoolConstant(R==APFloat::cmpEqual, dl, VT,
2349                                              OpVT);
2350     case ISD::SETNE:  if (R==APFloat::cmpUnordered)
2351                         return getUNDEF(VT);
2352                       LLVM_FALLTHROUGH;
2353     case ISD::SETONE: return getBoolConstant(R==APFloat::cmpGreaterThan ||
2354                                              R==APFloat::cmpLessThan, dl, VT,
2355                                              OpVT);
2356     case ISD::SETLT:  if (R==APFloat::cmpUnordered)
2357                         return getUNDEF(VT);
2358                       LLVM_FALLTHROUGH;
2359     case ISD::SETOLT: return getBoolConstant(R==APFloat::cmpLessThan, dl, VT,
2360                                              OpVT);
2361     case ISD::SETGT:  if (R==APFloat::cmpUnordered)
2362                         return getUNDEF(VT);
2363                       LLVM_FALLTHROUGH;
2364     case ISD::SETOGT: return getBoolConstant(R==APFloat::cmpGreaterThan, dl,
2365                                              VT, OpVT);
2366     case ISD::SETLE:  if (R==APFloat::cmpUnordered)
2367                         return getUNDEF(VT);
2368                       LLVM_FALLTHROUGH;
2369     case ISD::SETOLE: return getBoolConstant(R==APFloat::cmpLessThan ||
2370                                              R==APFloat::cmpEqual, dl, VT,
2371                                              OpVT);
2372     case ISD::SETGE:  if (R==APFloat::cmpUnordered)
2373                         return getUNDEF(VT);
2374                       LLVM_FALLTHROUGH;
2375     case ISD::SETOGE: return getBoolConstant(R==APFloat::cmpGreaterThan ||
2376                                          R==APFloat::cmpEqual, dl, VT, OpVT);
2377     case ISD::SETO:   return getBoolConstant(R!=APFloat::cmpUnordered, dl, VT,
2378                                              OpVT);
2379     case ISD::SETUO:  return getBoolConstant(R==APFloat::cmpUnordered, dl, VT,
2380                                              OpVT);
2381     case ISD::SETUEQ: return getBoolConstant(R==APFloat::cmpUnordered ||
2382                                              R==APFloat::cmpEqual, dl, VT,
2383                                              OpVT);
2384     case ISD::SETUNE: return getBoolConstant(R!=APFloat::cmpEqual, dl, VT,
2385                                              OpVT);
2386     case ISD::SETULT: return getBoolConstant(R==APFloat::cmpUnordered ||
2387                                              R==APFloat::cmpLessThan, dl, VT,
2388                                              OpVT);
2389     case ISD::SETUGT: return getBoolConstant(R==APFloat::cmpGreaterThan ||
2390                                              R==APFloat::cmpUnordered, dl, VT,
2391                                              OpVT);
2392     case ISD::SETULE: return getBoolConstant(R!=APFloat::cmpGreaterThan, dl,
2393                                              VT, OpVT);
2394     case ISD::SETUGE: return getBoolConstant(R!=APFloat::cmpLessThan, dl, VT,
2395                                              OpVT);
2396     }
2397   } else if (N1CFP && OpVT.isSimple() && !N2.isUndef()) {
2398     // Ensure that the constant occurs on the RHS.
2399     ISD::CondCode SwappedCond = ISD::getSetCCSwappedOperands(Cond);
2400     if (!TLI->isCondCodeLegal(SwappedCond, OpVT.getSimpleVT()))
2401       return SDValue();
2402     return getSetCC(dl, VT, N2, N1, SwappedCond);
2403   } else if ((N2CFP && N2CFP->getValueAPF().isNaN()) ||
2404              (OpVT.isFloatingPoint() && (N1.isUndef() || N2.isUndef()))) {
2405     // If an operand is known to be a nan (or undef that could be a nan), we can
2406     // fold it.
2407     // Choosing NaN for the undef will always make unordered comparison succeed
2408     // and ordered comparison fails.
2409     // Matches behavior in llvm::ConstantFoldCompareInstruction.
2410     switch (ISD::getUnorderedFlavor(Cond)) {
2411     default:
2412       llvm_unreachable("Unknown flavor!");
2413     case 0: // Known false.
2414       return getBoolConstant(false, dl, VT, OpVT);
2415     case 1: // Known true.
2416       return getBoolConstant(true, dl, VT, OpVT);
2417     case 2: // Undefined.
2418       return getUNDEF(VT);
2419     }
2420   }
2421 
2422   // Could not fold it.
2423   return SDValue();
2424 }
2425 
2426 /// See if the specified operand can be simplified with the knowledge that only
2427 /// the bits specified by DemandedBits are used.
2428 /// TODO: really we should be making this into the DAG equivalent of
2429 /// SimplifyMultipleUseDemandedBits and not generate any new nodes.
2430 SDValue SelectionDAG::GetDemandedBits(SDValue V, const APInt &DemandedBits) {
2431   EVT VT = V.getValueType();
2432 
2433   if (VT.isScalableVector())
2434     return SDValue();
2435 
2436   APInt DemandedElts = VT.isVector()
2437                            ? APInt::getAllOnes(VT.getVectorNumElements())
2438                            : APInt(1, 1);
2439   return GetDemandedBits(V, DemandedBits, DemandedElts);
2440 }
2441 
2442 /// See if the specified operand can be simplified with the knowledge that only
2443 /// the bits specified by DemandedBits are used in the elements specified by
2444 /// DemandedElts.
2445 /// TODO: really we should be making this into the DAG equivalent of
2446 /// SimplifyMultipleUseDemandedBits and not generate any new nodes.
2447 SDValue SelectionDAG::GetDemandedBits(SDValue V, const APInt &DemandedBits,
2448                                       const APInt &DemandedElts) {
2449   switch (V.getOpcode()) {
2450   default:
2451     return TLI->SimplifyMultipleUseDemandedBits(V, DemandedBits, DemandedElts,
2452                                                 *this);
2453   case ISD::Constant: {
2454     const APInt &CVal = cast<ConstantSDNode>(V)->getAPIntValue();
2455     APInt NewVal = CVal & DemandedBits;
2456     if (NewVal != CVal)
2457       return getConstant(NewVal, SDLoc(V), V.getValueType());
2458     break;
2459   }
2460   case ISD::SRL:
2461     // Only look at single-use SRLs.
2462     if (!V.getNode()->hasOneUse())
2463       break;
2464     if (auto *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
2465       // See if we can recursively simplify the LHS.
2466       unsigned Amt = RHSC->getZExtValue();
2467 
2468       // Watch out for shift count overflow though.
2469       if (Amt >= DemandedBits.getBitWidth())
2470         break;
2471       APInt SrcDemandedBits = DemandedBits << Amt;
2472       if (SDValue SimplifyLHS =
2473               GetDemandedBits(V.getOperand(0), SrcDemandedBits))
2474         return getNode(ISD::SRL, SDLoc(V), V.getValueType(), SimplifyLHS,
2475                        V.getOperand(1));
2476     }
2477     break;
2478   }
2479   return SDValue();
2480 }
2481 
2482 /// SignBitIsZero - Return true if the sign bit of Op is known to be zero.  We
2483 /// use this predicate to simplify operations downstream.
2484 bool SelectionDAG::SignBitIsZero(SDValue Op, unsigned Depth) const {
2485   unsigned BitWidth = Op.getScalarValueSizeInBits();
2486   return MaskedValueIsZero(Op, APInt::getSignMask(BitWidth), Depth);
2487 }
2488 
2489 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero.  We use
2490 /// this predicate to simplify operations downstream.  Mask is known to be zero
2491 /// for bits that V cannot have.
2492 bool SelectionDAG::MaskedValueIsZero(SDValue V, const APInt &Mask,
2493                                      unsigned Depth) const {
2494   return Mask.isSubsetOf(computeKnownBits(V, Depth).Zero);
2495 }
2496 
2497 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero in
2498 /// DemandedElts.  We use this predicate to simplify operations downstream.
2499 /// Mask is known to be zero for bits that V cannot have.
2500 bool SelectionDAG::MaskedValueIsZero(SDValue V, const APInt &Mask,
2501                                      const APInt &DemandedElts,
2502                                      unsigned Depth) const {
2503   return Mask.isSubsetOf(computeKnownBits(V, DemandedElts, Depth).Zero);
2504 }
2505 
2506 /// MaskedValueIsAllOnes - Return true if '(Op & Mask) == Mask'.
2507 bool SelectionDAG::MaskedValueIsAllOnes(SDValue V, const APInt &Mask,
2508                                         unsigned Depth) const {
2509   return Mask.isSubsetOf(computeKnownBits(V, Depth).One);
2510 }
2511 
2512 /// isSplatValue - Return true if the vector V has the same value
2513 /// across all DemandedElts. For scalable vectors it does not make
2514 /// sense to specify which elements are demanded or undefined, therefore
2515 /// they are simply ignored.
2516 bool SelectionDAG::isSplatValue(SDValue V, const APInt &DemandedElts,
2517                                 APInt &UndefElts, unsigned Depth) const {
2518   unsigned Opcode = V.getOpcode();
2519   EVT VT = V.getValueType();
2520   assert(VT.isVector() && "Vector type expected");
2521 
2522   if (!VT.isScalableVector() && !DemandedElts)
2523     return false; // No demanded elts, better to assume we don't know anything.
2524 
2525   if (Depth >= MaxRecursionDepth)
2526     return false; // Limit search depth.
2527 
2528   // Deal with some common cases here that work for both fixed and scalable
2529   // vector types.
2530   switch (Opcode) {
2531   case ISD::SPLAT_VECTOR:
2532     UndefElts = V.getOperand(0).isUndef()
2533                     ? APInt::getAllOnes(DemandedElts.getBitWidth())
2534                     : APInt(DemandedElts.getBitWidth(), 0);
2535     return true;
2536   case ISD::ADD:
2537   case ISD::SUB:
2538   case ISD::AND:
2539   case ISD::XOR:
2540   case ISD::OR: {
2541     APInt UndefLHS, UndefRHS;
2542     SDValue LHS = V.getOperand(0);
2543     SDValue RHS = V.getOperand(1);
2544     if (isSplatValue(LHS, DemandedElts, UndefLHS, Depth + 1) &&
2545         isSplatValue(RHS, DemandedElts, UndefRHS, Depth + 1)) {
2546       UndefElts = UndefLHS | UndefRHS;
2547       return true;
2548     }
2549     return false;
2550   }
2551   case ISD::ABS:
2552   case ISD::TRUNCATE:
2553   case ISD::SIGN_EXTEND:
2554   case ISD::ZERO_EXTEND:
2555     return isSplatValue(V.getOperand(0), DemandedElts, UndefElts, Depth + 1);
2556   default:
2557     if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::INTRINSIC_WO_CHAIN ||
2558         Opcode == ISD::INTRINSIC_W_CHAIN || Opcode == ISD::INTRINSIC_VOID)
2559       return TLI->isSplatValueForTargetNode(V, DemandedElts, UndefElts, Depth);
2560     break;
2561 }
2562 
2563   // We don't support other cases than those above for scalable vectors at
2564   // the moment.
2565   if (VT.isScalableVector())
2566     return false;
2567 
2568   unsigned NumElts = VT.getVectorNumElements();
2569   assert(NumElts == DemandedElts.getBitWidth() && "Vector size mismatch");
2570   UndefElts = APInt::getZero(NumElts);
2571 
2572   switch (Opcode) {
2573   case ISD::BUILD_VECTOR: {
2574     SDValue Scl;
2575     for (unsigned i = 0; i != NumElts; ++i) {
2576       SDValue Op = V.getOperand(i);
2577       if (Op.isUndef()) {
2578         UndefElts.setBit(i);
2579         continue;
2580       }
2581       if (!DemandedElts[i])
2582         continue;
2583       if (Scl && Scl != Op)
2584         return false;
2585       Scl = Op;
2586     }
2587     return true;
2588   }
2589   case ISD::VECTOR_SHUFFLE: {
2590     // Check if this is a shuffle node doing a splat or a shuffle of a splat.
2591     APInt DemandedLHS = APInt::getNullValue(NumElts);
2592     APInt DemandedRHS = APInt::getNullValue(NumElts);
2593     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(V)->getMask();
2594     for (int i = 0; i != (int)NumElts; ++i) {
2595       int M = Mask[i];
2596       if (M < 0) {
2597         UndefElts.setBit(i);
2598         continue;
2599       }
2600       if (!DemandedElts[i])
2601         continue;
2602       if (M < (int)NumElts)
2603         DemandedLHS.setBit(M);
2604       else
2605         DemandedRHS.setBit(M - NumElts);
2606     }
2607 
2608     // If we aren't demanding either op, assume there's no splat.
2609     // If we are demanding both ops, assume there's no splat.
2610     if ((DemandedLHS.isZero() && DemandedRHS.isZero()) ||
2611         (!DemandedLHS.isZero() && !DemandedRHS.isZero()))
2612       return false;
2613 
2614     // See if the demanded elts of the source op is a splat or we only demand
2615     // one element, which should always be a splat.
2616     // TODO: Handle source ops splats with undefs.
2617     auto CheckSplatSrc = [&](SDValue Src, const APInt &SrcElts) {
2618       APInt SrcUndefs;
2619       return (SrcElts.countPopulation() == 1) ||
2620              (isSplatValue(Src, SrcElts, SrcUndefs, Depth + 1) &&
2621               (SrcElts & SrcUndefs).isZero());
2622     };
2623     if (!DemandedLHS.isZero())
2624       return CheckSplatSrc(V.getOperand(0), DemandedLHS);
2625     return CheckSplatSrc(V.getOperand(1), DemandedRHS);
2626   }
2627   case ISD::EXTRACT_SUBVECTOR: {
2628     // Offset the demanded elts by the subvector index.
2629     SDValue Src = V.getOperand(0);
2630     // We don't support scalable vectors at the moment.
2631     if (Src.getValueType().isScalableVector())
2632       return false;
2633     uint64_t Idx = V.getConstantOperandVal(1);
2634     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
2635     APInt UndefSrcElts;
2636     APInt DemandedSrcElts = DemandedElts.zextOrSelf(NumSrcElts).shl(Idx);
2637     if (isSplatValue(Src, DemandedSrcElts, UndefSrcElts, Depth + 1)) {
2638       UndefElts = UndefSrcElts.extractBits(NumElts, Idx);
2639       return true;
2640     }
2641     break;
2642   }
2643   case ISD::ANY_EXTEND_VECTOR_INREG:
2644   case ISD::SIGN_EXTEND_VECTOR_INREG:
2645   case ISD::ZERO_EXTEND_VECTOR_INREG: {
2646     // Widen the demanded elts by the src element count.
2647     SDValue Src = V.getOperand(0);
2648     // We don't support scalable vectors at the moment.
2649     if (Src.getValueType().isScalableVector())
2650       return false;
2651     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
2652     APInt UndefSrcElts;
2653     APInt DemandedSrcElts = DemandedElts.zextOrSelf(NumSrcElts);
2654     if (isSplatValue(Src, DemandedSrcElts, UndefSrcElts, Depth + 1)) {
2655       UndefElts = UndefSrcElts.truncOrSelf(NumElts);
2656       return true;
2657     }
2658     break;
2659   }
2660   case ISD::BITCAST: {
2661     SDValue Src = V.getOperand(0);
2662     EVT SrcVT = Src.getValueType();
2663     unsigned SrcBitWidth = SrcVT.getScalarSizeInBits();
2664     unsigned BitWidth = VT.getScalarSizeInBits();
2665 
2666     // Ignore bitcasts from unsupported types.
2667     // TODO: Add fp support?
2668     if (!SrcVT.isVector() || !SrcVT.isInteger() || !VT.isInteger())
2669       break;
2670 
2671     // Bitcast 'small element' vector to 'large element' vector.
2672     if ((BitWidth % SrcBitWidth) == 0) {
2673       // See if each sub element is a splat.
2674       unsigned Scale = BitWidth / SrcBitWidth;
2675       unsigned NumSrcElts = SrcVT.getVectorNumElements();
2676       APInt ScaledDemandedElts =
2677           APIntOps::ScaleBitMask(DemandedElts, NumSrcElts);
2678       for (unsigned I = 0; I != Scale; ++I) {
2679         APInt SubUndefElts;
2680         APInt SubDemandedElt = APInt::getOneBitSet(Scale, I);
2681         APInt SubDemandedElts = APInt::getSplat(NumSrcElts, SubDemandedElt);
2682         SubDemandedElts &= ScaledDemandedElts;
2683         if (!isSplatValue(Src, SubDemandedElts, SubUndefElts, Depth + 1))
2684           return false;
2685         // TODO: Add support for merging sub undef elements.
2686         if (SubDemandedElts.isSubsetOf(SubUndefElts))
2687           return false;
2688       }
2689       return true;
2690     }
2691     break;
2692   }
2693   }
2694 
2695   return false;
2696 }
2697 
2698 /// Helper wrapper to main isSplatValue function.
2699 bool SelectionDAG::isSplatValue(SDValue V, bool AllowUndefs) const {
2700   EVT VT = V.getValueType();
2701   assert(VT.isVector() && "Vector type expected");
2702 
2703   APInt UndefElts;
2704   APInt DemandedElts;
2705 
2706   // For now we don't support this with scalable vectors.
2707   if (!VT.isScalableVector())
2708     DemandedElts = APInt::getAllOnes(VT.getVectorNumElements());
2709   return isSplatValue(V, DemandedElts, UndefElts) &&
2710          (AllowUndefs || !UndefElts);
2711 }
2712 
2713 SDValue SelectionDAG::getSplatSourceVector(SDValue V, int &SplatIdx) {
2714   V = peekThroughExtractSubvectors(V);
2715 
2716   EVT VT = V.getValueType();
2717   unsigned Opcode = V.getOpcode();
2718   switch (Opcode) {
2719   default: {
2720     APInt UndefElts;
2721     APInt DemandedElts;
2722 
2723     if (!VT.isScalableVector())
2724       DemandedElts = APInt::getAllOnes(VT.getVectorNumElements());
2725 
2726     if (isSplatValue(V, DemandedElts, UndefElts)) {
2727       if (VT.isScalableVector()) {
2728         // DemandedElts and UndefElts are ignored for scalable vectors, since
2729         // the only supported cases are SPLAT_VECTOR nodes.
2730         SplatIdx = 0;
2731       } else {
2732         // Handle case where all demanded elements are UNDEF.
2733         if (DemandedElts.isSubsetOf(UndefElts)) {
2734           SplatIdx = 0;
2735           return getUNDEF(VT);
2736         }
2737         SplatIdx = (UndefElts & DemandedElts).countTrailingOnes();
2738       }
2739       return V;
2740     }
2741     break;
2742   }
2743   case ISD::SPLAT_VECTOR:
2744     SplatIdx = 0;
2745     return V;
2746   case ISD::VECTOR_SHUFFLE: {
2747     if (VT.isScalableVector())
2748       return SDValue();
2749 
2750     // Check if this is a shuffle node doing a splat.
2751     // TODO - remove this and rely purely on SelectionDAG::isSplatValue,
2752     // getTargetVShiftNode currently struggles without the splat source.
2753     auto *SVN = cast<ShuffleVectorSDNode>(V);
2754     if (!SVN->isSplat())
2755       break;
2756     int Idx = SVN->getSplatIndex();
2757     int NumElts = V.getValueType().getVectorNumElements();
2758     SplatIdx = Idx % NumElts;
2759     return V.getOperand(Idx / NumElts);
2760   }
2761   }
2762 
2763   return SDValue();
2764 }
2765 
2766 SDValue SelectionDAG::getSplatValue(SDValue V, bool LegalTypes) {
2767   int SplatIdx;
2768   if (SDValue SrcVector = getSplatSourceVector(V, SplatIdx)) {
2769     EVT SVT = SrcVector.getValueType().getScalarType();
2770     EVT LegalSVT = SVT;
2771     if (LegalTypes && !TLI->isTypeLegal(SVT)) {
2772       if (!SVT.isInteger())
2773         return SDValue();
2774       LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT);
2775       if (LegalSVT.bitsLT(SVT))
2776         return SDValue();
2777     }
2778     return getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(V), LegalSVT, SrcVector,
2779                    getVectorIdxConstant(SplatIdx, SDLoc(V)));
2780   }
2781   return SDValue();
2782 }
2783 
2784 const APInt *
2785 SelectionDAG::getValidShiftAmountConstant(SDValue V,
2786                                           const APInt &DemandedElts) const {
2787   assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL ||
2788           V.getOpcode() == ISD::SRA) &&
2789          "Unknown shift node");
2790   unsigned BitWidth = V.getScalarValueSizeInBits();
2791   if (ConstantSDNode *SA = isConstOrConstSplat(V.getOperand(1), DemandedElts)) {
2792     // Shifting more than the bitwidth is not valid.
2793     const APInt &ShAmt = SA->getAPIntValue();
2794     if (ShAmt.ult(BitWidth))
2795       return &ShAmt;
2796   }
2797   return nullptr;
2798 }
2799 
2800 const APInt *SelectionDAG::getValidMinimumShiftAmountConstant(
2801     SDValue V, const APInt &DemandedElts) const {
2802   assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL ||
2803           V.getOpcode() == ISD::SRA) &&
2804          "Unknown shift node");
2805   if (const APInt *ValidAmt = getValidShiftAmountConstant(V, DemandedElts))
2806     return ValidAmt;
2807   unsigned BitWidth = V.getScalarValueSizeInBits();
2808   auto *BV = dyn_cast<BuildVectorSDNode>(V.getOperand(1));
2809   if (!BV)
2810     return nullptr;
2811   const APInt *MinShAmt = nullptr;
2812   for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
2813     if (!DemandedElts[i])
2814       continue;
2815     auto *SA = dyn_cast<ConstantSDNode>(BV->getOperand(i));
2816     if (!SA)
2817       return nullptr;
2818     // Shifting more than the bitwidth is not valid.
2819     const APInt &ShAmt = SA->getAPIntValue();
2820     if (ShAmt.uge(BitWidth))
2821       return nullptr;
2822     if (MinShAmt && MinShAmt->ule(ShAmt))
2823       continue;
2824     MinShAmt = &ShAmt;
2825   }
2826   return MinShAmt;
2827 }
2828 
2829 const APInt *SelectionDAG::getValidMaximumShiftAmountConstant(
2830     SDValue V, const APInt &DemandedElts) const {
2831   assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL ||
2832           V.getOpcode() == ISD::SRA) &&
2833          "Unknown shift node");
2834   if (const APInt *ValidAmt = getValidShiftAmountConstant(V, DemandedElts))
2835     return ValidAmt;
2836   unsigned BitWidth = V.getScalarValueSizeInBits();
2837   auto *BV = dyn_cast<BuildVectorSDNode>(V.getOperand(1));
2838   if (!BV)
2839     return nullptr;
2840   const APInt *MaxShAmt = nullptr;
2841   for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
2842     if (!DemandedElts[i])
2843       continue;
2844     auto *SA = dyn_cast<ConstantSDNode>(BV->getOperand(i));
2845     if (!SA)
2846       return nullptr;
2847     // Shifting more than the bitwidth is not valid.
2848     const APInt &ShAmt = SA->getAPIntValue();
2849     if (ShAmt.uge(BitWidth))
2850       return nullptr;
2851     if (MaxShAmt && MaxShAmt->uge(ShAmt))
2852       continue;
2853     MaxShAmt = &ShAmt;
2854   }
2855   return MaxShAmt;
2856 }
2857 
2858 /// Determine which bits of Op are known to be either zero or one and return
2859 /// them in Known. For vectors, the known bits are those that are shared by
2860 /// every vector element.
2861 KnownBits SelectionDAG::computeKnownBits(SDValue Op, unsigned Depth) const {
2862   EVT VT = Op.getValueType();
2863 
2864   // TOOD: Until we have a plan for how to represent demanded elements for
2865   // scalable vectors, we can just bail out for now.
2866   if (Op.getValueType().isScalableVector()) {
2867     unsigned BitWidth = Op.getScalarValueSizeInBits();
2868     return KnownBits(BitWidth);
2869   }
2870 
2871   APInt DemandedElts = VT.isVector()
2872                            ? APInt::getAllOnes(VT.getVectorNumElements())
2873                            : APInt(1, 1);
2874   return computeKnownBits(Op, DemandedElts, Depth);
2875 }
2876 
2877 /// Determine which bits of Op are known to be either zero or one and return
2878 /// them in Known. The DemandedElts argument allows us to only collect the known
2879 /// bits that are shared by the requested vector elements.
2880 KnownBits SelectionDAG::computeKnownBits(SDValue Op, const APInt &DemandedElts,
2881                                          unsigned Depth) const {
2882   unsigned BitWidth = Op.getScalarValueSizeInBits();
2883 
2884   KnownBits Known(BitWidth);   // Don't know anything.
2885 
2886   // TOOD: Until we have a plan for how to represent demanded elements for
2887   // scalable vectors, we can just bail out for now.
2888   if (Op.getValueType().isScalableVector())
2889     return Known;
2890 
2891   if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
2892     // We know all of the bits for a constant!
2893     return KnownBits::makeConstant(C->getAPIntValue());
2894   }
2895   if (auto *C = dyn_cast<ConstantFPSDNode>(Op)) {
2896     // We know all of the bits for a constant fp!
2897     return KnownBits::makeConstant(C->getValueAPF().bitcastToAPInt());
2898   }
2899 
2900   if (Depth >= MaxRecursionDepth)
2901     return Known;  // Limit search depth.
2902 
2903   KnownBits Known2;
2904   unsigned NumElts = DemandedElts.getBitWidth();
2905   assert((!Op.getValueType().isVector() ||
2906           NumElts == Op.getValueType().getVectorNumElements()) &&
2907          "Unexpected vector size");
2908 
2909   if (!DemandedElts)
2910     return Known;  // No demanded elts, better to assume we don't know anything.
2911 
2912   unsigned Opcode = Op.getOpcode();
2913   switch (Opcode) {
2914   case ISD::BUILD_VECTOR:
2915     // Collect the known bits that are shared by every demanded vector element.
2916     Known.Zero.setAllBits(); Known.One.setAllBits();
2917     for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
2918       if (!DemandedElts[i])
2919         continue;
2920 
2921       SDValue SrcOp = Op.getOperand(i);
2922       Known2 = computeKnownBits(SrcOp, Depth + 1);
2923 
2924       // BUILD_VECTOR can implicitly truncate sources, we must handle this.
2925       if (SrcOp.getValueSizeInBits() != BitWidth) {
2926         assert(SrcOp.getValueSizeInBits() > BitWidth &&
2927                "Expected BUILD_VECTOR implicit truncation");
2928         Known2 = Known2.trunc(BitWidth);
2929       }
2930 
2931       // Known bits are the values that are shared by every demanded element.
2932       Known = KnownBits::commonBits(Known, Known2);
2933 
2934       // If we don't know any bits, early out.
2935       if (Known.isUnknown())
2936         break;
2937     }
2938     break;
2939   case ISD::VECTOR_SHUFFLE: {
2940     // Collect the known bits that are shared by every vector element referenced
2941     // by the shuffle.
2942     APInt DemandedLHS(NumElts, 0), DemandedRHS(NumElts, 0);
2943     Known.Zero.setAllBits(); Known.One.setAllBits();
2944     const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op);
2945     assert(NumElts == SVN->getMask().size() && "Unexpected vector size");
2946     for (unsigned i = 0; i != NumElts; ++i) {
2947       if (!DemandedElts[i])
2948         continue;
2949 
2950       int M = SVN->getMaskElt(i);
2951       if (M < 0) {
2952         // For UNDEF elements, we don't know anything about the common state of
2953         // the shuffle result.
2954         Known.resetAll();
2955         DemandedLHS.clearAllBits();
2956         DemandedRHS.clearAllBits();
2957         break;
2958       }
2959 
2960       if ((unsigned)M < NumElts)
2961         DemandedLHS.setBit((unsigned)M % NumElts);
2962       else
2963         DemandedRHS.setBit((unsigned)M % NumElts);
2964     }
2965     // Known bits are the values that are shared by every demanded element.
2966     if (!!DemandedLHS) {
2967       SDValue LHS = Op.getOperand(0);
2968       Known2 = computeKnownBits(LHS, DemandedLHS, Depth + 1);
2969       Known = KnownBits::commonBits(Known, Known2);
2970     }
2971     // If we don't know any bits, early out.
2972     if (Known.isUnknown())
2973       break;
2974     if (!!DemandedRHS) {
2975       SDValue RHS = Op.getOperand(1);
2976       Known2 = computeKnownBits(RHS, DemandedRHS, Depth + 1);
2977       Known = KnownBits::commonBits(Known, Known2);
2978     }
2979     break;
2980   }
2981   case ISD::CONCAT_VECTORS: {
2982     // Split DemandedElts and test each of the demanded subvectors.
2983     Known.Zero.setAllBits(); Known.One.setAllBits();
2984     EVT SubVectorVT = Op.getOperand(0).getValueType();
2985     unsigned NumSubVectorElts = SubVectorVT.getVectorNumElements();
2986     unsigned NumSubVectors = Op.getNumOperands();
2987     for (unsigned i = 0; i != NumSubVectors; ++i) {
2988       APInt DemandedSub =
2989           DemandedElts.extractBits(NumSubVectorElts, i * NumSubVectorElts);
2990       if (!!DemandedSub) {
2991         SDValue Sub = Op.getOperand(i);
2992         Known2 = computeKnownBits(Sub, DemandedSub, Depth + 1);
2993         Known = KnownBits::commonBits(Known, Known2);
2994       }
2995       // If we don't know any bits, early out.
2996       if (Known.isUnknown())
2997         break;
2998     }
2999     break;
3000   }
3001   case ISD::INSERT_SUBVECTOR: {
3002     // Demand any elements from the subvector and the remainder from the src its
3003     // inserted into.
3004     SDValue Src = Op.getOperand(0);
3005     SDValue Sub = Op.getOperand(1);
3006     uint64_t Idx = Op.getConstantOperandVal(2);
3007     unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
3008     APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
3009     APInt DemandedSrcElts = DemandedElts;
3010     DemandedSrcElts.insertBits(APInt::getZero(NumSubElts), Idx);
3011 
3012     Known.One.setAllBits();
3013     Known.Zero.setAllBits();
3014     if (!!DemandedSubElts) {
3015       Known = computeKnownBits(Sub, DemandedSubElts, Depth + 1);
3016       if (Known.isUnknown())
3017         break; // early-out.
3018     }
3019     if (!!DemandedSrcElts) {
3020       Known2 = computeKnownBits(Src, DemandedSrcElts, Depth + 1);
3021       Known = KnownBits::commonBits(Known, Known2);
3022     }
3023     break;
3024   }
3025   case ISD::EXTRACT_SUBVECTOR: {
3026     // Offset the demanded elts by the subvector index.
3027     SDValue Src = Op.getOperand(0);
3028     // Bail until we can represent demanded elements for scalable vectors.
3029     if (Src.getValueType().isScalableVector())
3030       break;
3031     uint64_t Idx = Op.getConstantOperandVal(1);
3032     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
3033     APInt DemandedSrcElts = DemandedElts.zextOrSelf(NumSrcElts).shl(Idx);
3034     Known = computeKnownBits(Src, DemandedSrcElts, Depth + 1);
3035     break;
3036   }
3037   case ISD::SCALAR_TO_VECTOR: {
3038     // We know about scalar_to_vector as much as we know about it source,
3039     // which becomes the first element of otherwise unknown vector.
3040     if (DemandedElts != 1)
3041       break;
3042 
3043     SDValue N0 = Op.getOperand(0);
3044     Known = computeKnownBits(N0, Depth + 1);
3045     if (N0.getValueSizeInBits() != BitWidth)
3046       Known = Known.trunc(BitWidth);
3047 
3048     break;
3049   }
3050   case ISD::BITCAST: {
3051     SDValue N0 = Op.getOperand(0);
3052     EVT SubVT = N0.getValueType();
3053     unsigned SubBitWidth = SubVT.getScalarSizeInBits();
3054 
3055     // Ignore bitcasts from unsupported types.
3056     if (!(SubVT.isInteger() || SubVT.isFloatingPoint()))
3057       break;
3058 
3059     // Fast handling of 'identity' bitcasts.
3060     if (BitWidth == SubBitWidth) {
3061       Known = computeKnownBits(N0, DemandedElts, Depth + 1);
3062       break;
3063     }
3064 
3065     bool IsLE = getDataLayout().isLittleEndian();
3066 
3067     // Bitcast 'small element' vector to 'large element' scalar/vector.
3068     if ((BitWidth % SubBitWidth) == 0) {
3069       assert(N0.getValueType().isVector() && "Expected bitcast from vector");
3070 
3071       // Collect known bits for the (larger) output by collecting the known
3072       // bits from each set of sub elements and shift these into place.
3073       // We need to separately call computeKnownBits for each set of
3074       // sub elements as the knownbits for each is likely to be different.
3075       unsigned SubScale = BitWidth / SubBitWidth;
3076       APInt SubDemandedElts(NumElts * SubScale, 0);
3077       for (unsigned i = 0; i != NumElts; ++i)
3078         if (DemandedElts[i])
3079           SubDemandedElts.setBit(i * SubScale);
3080 
3081       for (unsigned i = 0; i != SubScale; ++i) {
3082         Known2 = computeKnownBits(N0, SubDemandedElts.shl(i),
3083                          Depth + 1);
3084         unsigned Shifts = IsLE ? i : SubScale - 1 - i;
3085         Known.insertBits(Known2, SubBitWidth * Shifts);
3086       }
3087     }
3088 
3089     // Bitcast 'large element' scalar/vector to 'small element' vector.
3090     if ((SubBitWidth % BitWidth) == 0) {
3091       assert(Op.getValueType().isVector() && "Expected bitcast to vector");
3092 
3093       // Collect known bits for the (smaller) output by collecting the known
3094       // bits from the overlapping larger input elements and extracting the
3095       // sub sections we actually care about.
3096       unsigned SubScale = SubBitWidth / BitWidth;
3097       APInt SubDemandedElts =
3098           APIntOps::ScaleBitMask(DemandedElts, NumElts / SubScale);
3099       Known2 = computeKnownBits(N0, SubDemandedElts, Depth + 1);
3100 
3101       Known.Zero.setAllBits(); Known.One.setAllBits();
3102       for (unsigned i = 0; i != NumElts; ++i)
3103         if (DemandedElts[i]) {
3104           unsigned Shifts = IsLE ? i : NumElts - 1 - i;
3105           unsigned Offset = (Shifts % SubScale) * BitWidth;
3106           Known = KnownBits::commonBits(Known,
3107                                         Known2.extractBits(BitWidth, Offset));
3108           // If we don't know any bits, early out.
3109           if (Known.isUnknown())
3110             break;
3111         }
3112     }
3113     break;
3114   }
3115   case ISD::AND:
3116     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3117     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3118 
3119     Known &= Known2;
3120     break;
3121   case ISD::OR:
3122     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3123     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3124 
3125     Known |= Known2;
3126     break;
3127   case ISD::XOR:
3128     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3129     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3130 
3131     Known ^= Known2;
3132     break;
3133   case ISD::MUL: {
3134     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3135     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3136     bool SelfMultiply = Op.getOperand(0) == Op.getOperand(1);
3137     // TODO: SelfMultiply can be poison, but not undef.
3138     if (SelfMultiply)
3139       SelfMultiply &= isGuaranteedNotToBeUndefOrPoison(
3140           Op.getOperand(0), DemandedElts, false, Depth + 1);
3141     Known = KnownBits::mul(Known, Known2, SelfMultiply);
3142     break;
3143   }
3144   case ISD::MULHU: {
3145     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3146     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3147     Known = KnownBits::mulhu(Known, Known2);
3148     break;
3149   }
3150   case ISD::MULHS: {
3151     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3152     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3153     Known = KnownBits::mulhs(Known, Known2);
3154     break;
3155   }
3156   case ISD::UMUL_LOHI: {
3157     assert((Op.getResNo() == 0 || Op.getResNo() == 1) && "Unknown result");
3158     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3159     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3160     bool SelfMultiply = Op.getOperand(0) == Op.getOperand(1);
3161     if (Op.getResNo() == 0)
3162       Known = KnownBits::mul(Known, Known2, SelfMultiply);
3163     else
3164       Known = KnownBits::mulhu(Known, Known2);
3165     break;
3166   }
3167   case ISD::SMUL_LOHI: {
3168     assert((Op.getResNo() == 0 || Op.getResNo() == 1) && "Unknown result");
3169     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3170     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3171     bool SelfMultiply = Op.getOperand(0) == Op.getOperand(1);
3172     if (Op.getResNo() == 0)
3173       Known = KnownBits::mul(Known, Known2, SelfMultiply);
3174     else
3175       Known = KnownBits::mulhs(Known, Known2);
3176     break;
3177   }
3178   case ISD::UDIV: {
3179     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3180     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3181     Known = KnownBits::udiv(Known, Known2);
3182     break;
3183   }
3184   case ISD::AVGCEILU: {
3185     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3186     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3187     Known = Known.zext(BitWidth + 1);
3188     Known2 = Known2.zext(BitWidth + 1);
3189     KnownBits One = KnownBits::makeConstant(APInt(1, 1));
3190     Known = KnownBits::computeForAddCarry(Known, Known2, One);
3191     Known = Known.extractBits(BitWidth, 1);
3192     break;
3193   }
3194   case ISD::SELECT:
3195   case ISD::VSELECT:
3196     Known = computeKnownBits(Op.getOperand(2), DemandedElts, Depth+1);
3197     // If we don't know any bits, early out.
3198     if (Known.isUnknown())
3199       break;
3200     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth+1);
3201 
3202     // Only known if known in both the LHS and RHS.
3203     Known = KnownBits::commonBits(Known, Known2);
3204     break;
3205   case ISD::SELECT_CC:
3206     Known = computeKnownBits(Op.getOperand(3), DemandedElts, Depth+1);
3207     // If we don't know any bits, early out.
3208     if (Known.isUnknown())
3209       break;
3210     Known2 = computeKnownBits(Op.getOperand(2), DemandedElts, Depth+1);
3211 
3212     // Only known if known in both the LHS and RHS.
3213     Known = KnownBits::commonBits(Known, Known2);
3214     break;
3215   case ISD::SMULO:
3216   case ISD::UMULO:
3217     if (Op.getResNo() != 1)
3218       break;
3219     // The boolean result conforms to getBooleanContents.
3220     // If we know the result of a setcc has the top bits zero, use this info.
3221     // We know that we have an integer-based boolean since these operations
3222     // are only available for integer.
3223     if (TLI->getBooleanContents(Op.getValueType().isVector(), false) ==
3224             TargetLowering::ZeroOrOneBooleanContent &&
3225         BitWidth > 1)
3226       Known.Zero.setBitsFrom(1);
3227     break;
3228   case ISD::SETCC:
3229   case ISD::STRICT_FSETCC:
3230   case ISD::STRICT_FSETCCS: {
3231     unsigned OpNo = Op->isStrictFPOpcode() ? 1 : 0;
3232     // If we know the result of a setcc has the top bits zero, use this info.
3233     if (TLI->getBooleanContents(Op.getOperand(OpNo).getValueType()) ==
3234             TargetLowering::ZeroOrOneBooleanContent &&
3235         BitWidth > 1)
3236       Known.Zero.setBitsFrom(1);
3237     break;
3238   }
3239   case ISD::SHL:
3240     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3241     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3242     Known = KnownBits::shl(Known, Known2);
3243 
3244     // Minimum shift low bits are known zero.
3245     if (const APInt *ShMinAmt =
3246             getValidMinimumShiftAmountConstant(Op, DemandedElts))
3247       Known.Zero.setLowBits(ShMinAmt->getZExtValue());
3248     break;
3249   case ISD::SRL:
3250     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3251     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3252     Known = KnownBits::lshr(Known, Known2);
3253 
3254     // Minimum shift high bits are known zero.
3255     if (const APInt *ShMinAmt =
3256             getValidMinimumShiftAmountConstant(Op, DemandedElts))
3257       Known.Zero.setHighBits(ShMinAmt->getZExtValue());
3258     break;
3259   case ISD::SRA:
3260     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3261     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3262     Known = KnownBits::ashr(Known, Known2);
3263     // TODO: Add minimum shift high known sign bits.
3264     break;
3265   case ISD::FSHL:
3266   case ISD::FSHR:
3267     if (ConstantSDNode *C = isConstOrConstSplat(Op.getOperand(2), DemandedElts)) {
3268       unsigned Amt = C->getAPIntValue().urem(BitWidth);
3269 
3270       // For fshl, 0-shift returns the 1st arg.
3271       // For fshr, 0-shift returns the 2nd arg.
3272       if (Amt == 0) {
3273         Known = computeKnownBits(Op.getOperand(Opcode == ISD::FSHL ? 0 : 1),
3274                                  DemandedElts, Depth + 1);
3275         break;
3276       }
3277 
3278       // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW)))
3279       // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW))
3280       Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3281       Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3282       if (Opcode == ISD::FSHL) {
3283         Known.One <<= Amt;
3284         Known.Zero <<= Amt;
3285         Known2.One.lshrInPlace(BitWidth - Amt);
3286         Known2.Zero.lshrInPlace(BitWidth - Amt);
3287       } else {
3288         Known.One <<= BitWidth - Amt;
3289         Known.Zero <<= BitWidth - Amt;
3290         Known2.One.lshrInPlace(Amt);
3291         Known2.Zero.lshrInPlace(Amt);
3292       }
3293       Known.One |= Known2.One;
3294       Known.Zero |= Known2.Zero;
3295     }
3296     break;
3297   case ISD::SIGN_EXTEND_INREG: {
3298     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3299     EVT EVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
3300     Known = Known.sextInReg(EVT.getScalarSizeInBits());
3301     break;
3302   }
3303   case ISD::CTTZ:
3304   case ISD::CTTZ_ZERO_UNDEF: {
3305     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3306     // If we have a known 1, its position is our upper bound.
3307     unsigned PossibleTZ = Known2.countMaxTrailingZeros();
3308     unsigned LowBits = Log2_32(PossibleTZ) + 1;
3309     Known.Zero.setBitsFrom(LowBits);
3310     break;
3311   }
3312   case ISD::CTLZ:
3313   case ISD::CTLZ_ZERO_UNDEF: {
3314     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3315     // If we have a known 1, its position is our upper bound.
3316     unsigned PossibleLZ = Known2.countMaxLeadingZeros();
3317     unsigned LowBits = Log2_32(PossibleLZ) + 1;
3318     Known.Zero.setBitsFrom(LowBits);
3319     break;
3320   }
3321   case ISD::CTPOP: {
3322     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3323     // If we know some of the bits are zero, they can't be one.
3324     unsigned PossibleOnes = Known2.countMaxPopulation();
3325     Known.Zero.setBitsFrom(Log2_32(PossibleOnes) + 1);
3326     break;
3327   }
3328   case ISD::PARITY: {
3329     // Parity returns 0 everywhere but the LSB.
3330     Known.Zero.setBitsFrom(1);
3331     break;
3332   }
3333   case ISD::LOAD: {
3334     LoadSDNode *LD = cast<LoadSDNode>(Op);
3335     const Constant *Cst = TLI->getTargetConstantFromLoad(LD);
3336     if (ISD::isNON_EXTLoad(LD) && Cst) {
3337       // Determine any common known bits from the loaded constant pool value.
3338       Type *CstTy = Cst->getType();
3339       if ((NumElts * BitWidth) == CstTy->getPrimitiveSizeInBits()) {
3340         // If its a vector splat, then we can (quickly) reuse the scalar path.
3341         // NOTE: We assume all elements match and none are UNDEF.
3342         if (CstTy->isVectorTy()) {
3343           if (const Constant *Splat = Cst->getSplatValue()) {
3344             Cst = Splat;
3345             CstTy = Cst->getType();
3346           }
3347         }
3348         // TODO - do we need to handle different bitwidths?
3349         if (CstTy->isVectorTy() && BitWidth == CstTy->getScalarSizeInBits()) {
3350           // Iterate across all vector elements finding common known bits.
3351           Known.One.setAllBits();
3352           Known.Zero.setAllBits();
3353           for (unsigned i = 0; i != NumElts; ++i) {
3354             if (!DemandedElts[i])
3355               continue;
3356             if (Constant *Elt = Cst->getAggregateElement(i)) {
3357               if (auto *CInt = dyn_cast<ConstantInt>(Elt)) {
3358                 const APInt &Value = CInt->getValue();
3359                 Known.One &= Value;
3360                 Known.Zero &= ~Value;
3361                 continue;
3362               }
3363               if (auto *CFP = dyn_cast<ConstantFP>(Elt)) {
3364                 APInt Value = CFP->getValueAPF().bitcastToAPInt();
3365                 Known.One &= Value;
3366                 Known.Zero &= ~Value;
3367                 continue;
3368               }
3369             }
3370             Known.One.clearAllBits();
3371             Known.Zero.clearAllBits();
3372             break;
3373           }
3374         } else if (BitWidth == CstTy->getPrimitiveSizeInBits()) {
3375           if (auto *CInt = dyn_cast<ConstantInt>(Cst)) {
3376             Known = KnownBits::makeConstant(CInt->getValue());
3377           } else if (auto *CFP = dyn_cast<ConstantFP>(Cst)) {
3378             Known =
3379                 KnownBits::makeConstant(CFP->getValueAPF().bitcastToAPInt());
3380           }
3381         }
3382       }
3383     } else if (ISD::isZEXTLoad(Op.getNode()) && Op.getResNo() == 0) {
3384       // If this is a ZEXTLoad and we are looking at the loaded value.
3385       EVT VT = LD->getMemoryVT();
3386       unsigned MemBits = VT.getScalarSizeInBits();
3387       Known.Zero.setBitsFrom(MemBits);
3388     } else if (const MDNode *Ranges = LD->getRanges()) {
3389       if (LD->getExtensionType() == ISD::NON_EXTLOAD)
3390         computeKnownBitsFromRangeMetadata(*Ranges, Known);
3391     }
3392     break;
3393   }
3394   case ISD::ZERO_EXTEND_VECTOR_INREG: {
3395     EVT InVT = Op.getOperand(0).getValueType();
3396     APInt InDemandedElts = DemandedElts.zextOrSelf(InVT.getVectorNumElements());
3397     Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1);
3398     Known = Known.zext(BitWidth);
3399     break;
3400   }
3401   case ISD::ZERO_EXTEND: {
3402     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3403     Known = Known.zext(BitWidth);
3404     break;
3405   }
3406   case ISD::SIGN_EXTEND_VECTOR_INREG: {
3407     EVT InVT = Op.getOperand(0).getValueType();
3408     APInt InDemandedElts = DemandedElts.zextOrSelf(InVT.getVectorNumElements());
3409     Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1);
3410     // If the sign bit is known to be zero or one, then sext will extend
3411     // it to the top bits, else it will just zext.
3412     Known = Known.sext(BitWidth);
3413     break;
3414   }
3415   case ISD::SIGN_EXTEND: {
3416     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3417     // If the sign bit is known to be zero or one, then sext will extend
3418     // it to the top bits, else it will just zext.
3419     Known = Known.sext(BitWidth);
3420     break;
3421   }
3422   case ISD::ANY_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     Known = Known.anyext(BitWidth);
3427     break;
3428   }
3429   case ISD::ANY_EXTEND: {
3430     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3431     Known = Known.anyext(BitWidth);
3432     break;
3433   }
3434   case ISD::TRUNCATE: {
3435     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3436     Known = Known.trunc(BitWidth);
3437     break;
3438   }
3439   case ISD::AssertZext: {
3440     EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
3441     APInt InMask = APInt::getLowBitsSet(BitWidth, VT.getSizeInBits());
3442     Known = computeKnownBits(Op.getOperand(0), Depth+1);
3443     Known.Zero |= (~InMask);
3444     Known.One  &= (~Known.Zero);
3445     break;
3446   }
3447   case ISD::AssertAlign: {
3448     unsigned LogOfAlign = Log2(cast<AssertAlignSDNode>(Op)->getAlign());
3449     assert(LogOfAlign != 0);
3450 
3451     // TODO: Should use maximum with source
3452     // If a node is guaranteed to be aligned, set low zero bits accordingly as
3453     // well as clearing one bits.
3454     Known.Zero.setLowBits(LogOfAlign);
3455     Known.One.clearLowBits(LogOfAlign);
3456     break;
3457   }
3458   case ISD::FGETSIGN:
3459     // All bits are zero except the low bit.
3460     Known.Zero.setBitsFrom(1);
3461     break;
3462   case ISD::USUBO:
3463   case ISD::SSUBO:
3464     if (Op.getResNo() == 1) {
3465       // If we know the result of a setcc has the top bits zero, use this info.
3466       if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) ==
3467               TargetLowering::ZeroOrOneBooleanContent &&
3468           BitWidth > 1)
3469         Known.Zero.setBitsFrom(1);
3470       break;
3471     }
3472     LLVM_FALLTHROUGH;
3473   case ISD::SUB:
3474   case ISD::SUBC: {
3475     assert(Op.getResNo() == 0 &&
3476            "We only compute knownbits for the difference here.");
3477 
3478     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3479     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3480     Known = KnownBits::computeForAddSub(/* Add */ false, /* NSW */ false,
3481                                         Known, Known2);
3482     break;
3483   }
3484   case ISD::UADDO:
3485   case ISD::SADDO:
3486   case ISD::ADDCARRY:
3487     if (Op.getResNo() == 1) {
3488       // If we know the result of a setcc has the top bits zero, use this info.
3489       if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) ==
3490               TargetLowering::ZeroOrOneBooleanContent &&
3491           BitWidth > 1)
3492         Known.Zero.setBitsFrom(1);
3493       break;
3494     }
3495     LLVM_FALLTHROUGH;
3496   case ISD::ADD:
3497   case ISD::ADDC:
3498   case ISD::ADDE: {
3499     assert(Op.getResNo() == 0 && "We only compute knownbits for the sum here.");
3500 
3501     // With ADDE and ADDCARRY, a carry bit may be added in.
3502     KnownBits Carry(1);
3503     if (Opcode == ISD::ADDE)
3504       // Can't track carry from glue, set carry to unknown.
3505       Carry.resetAll();
3506     else if (Opcode == ISD::ADDCARRY)
3507       // TODO: Compute known bits for the carry operand. Not sure if it is worth
3508       // the trouble (how often will we find a known carry bit). And I haven't
3509       // tested this very much yet, but something like this might work:
3510       //   Carry = computeKnownBits(Op.getOperand(2), DemandedElts, Depth + 1);
3511       //   Carry = Carry.zextOrTrunc(1, false);
3512       Carry.resetAll();
3513     else
3514       Carry.setAllZero();
3515 
3516     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3517     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3518     Known = KnownBits::computeForAddCarry(Known, Known2, Carry);
3519     break;
3520   }
3521   case ISD::SREM: {
3522     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3523     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3524     Known = KnownBits::srem(Known, Known2);
3525     break;
3526   }
3527   case ISD::UREM: {
3528     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3529     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3530     Known = KnownBits::urem(Known, Known2);
3531     break;
3532   }
3533   case ISD::EXTRACT_ELEMENT: {
3534     Known = computeKnownBits(Op.getOperand(0), Depth+1);
3535     const unsigned Index = Op.getConstantOperandVal(1);
3536     const unsigned EltBitWidth = Op.getValueSizeInBits();
3537 
3538     // Remove low part of known bits mask
3539     Known.Zero = Known.Zero.getHiBits(Known.getBitWidth() - Index * EltBitWidth);
3540     Known.One = Known.One.getHiBits(Known.getBitWidth() - Index * EltBitWidth);
3541 
3542     // Remove high part of known bit mask
3543     Known = Known.trunc(EltBitWidth);
3544     break;
3545   }
3546   case ISD::EXTRACT_VECTOR_ELT: {
3547     SDValue InVec = Op.getOperand(0);
3548     SDValue EltNo = Op.getOperand(1);
3549     EVT VecVT = InVec.getValueType();
3550     // computeKnownBits not yet implemented for scalable vectors.
3551     if (VecVT.isScalableVector())
3552       break;
3553     const unsigned EltBitWidth = VecVT.getScalarSizeInBits();
3554     const unsigned NumSrcElts = VecVT.getVectorNumElements();
3555 
3556     // If BitWidth > EltBitWidth the value is anyext:ed. So we do not know
3557     // anything about the extended bits.
3558     if (BitWidth > EltBitWidth)
3559       Known = Known.trunc(EltBitWidth);
3560 
3561     // If we know the element index, just demand that vector element, else for
3562     // an unknown element index, ignore DemandedElts and demand them all.
3563     APInt DemandedSrcElts = APInt::getAllOnes(NumSrcElts);
3564     auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
3565     if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts))
3566       DemandedSrcElts =
3567           APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue());
3568 
3569     Known = computeKnownBits(InVec, DemandedSrcElts, Depth + 1);
3570     if (BitWidth > EltBitWidth)
3571       Known = Known.anyext(BitWidth);
3572     break;
3573   }
3574   case ISD::INSERT_VECTOR_ELT: {
3575     // If we know the element index, split the demand between the
3576     // source vector and the inserted element, otherwise assume we need
3577     // the original demanded vector elements and the value.
3578     SDValue InVec = Op.getOperand(0);
3579     SDValue InVal = Op.getOperand(1);
3580     SDValue EltNo = Op.getOperand(2);
3581     bool DemandedVal = true;
3582     APInt DemandedVecElts = DemandedElts;
3583     auto *CEltNo = dyn_cast<ConstantSDNode>(EltNo);
3584     if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) {
3585       unsigned EltIdx = CEltNo->getZExtValue();
3586       DemandedVal = !!DemandedElts[EltIdx];
3587       DemandedVecElts.clearBit(EltIdx);
3588     }
3589     Known.One.setAllBits();
3590     Known.Zero.setAllBits();
3591     if (DemandedVal) {
3592       Known2 = computeKnownBits(InVal, Depth + 1);
3593       Known = KnownBits::commonBits(Known, Known2.zextOrTrunc(BitWidth));
3594     }
3595     if (!!DemandedVecElts) {
3596       Known2 = computeKnownBits(InVec, DemandedVecElts, Depth + 1);
3597       Known = KnownBits::commonBits(Known, Known2);
3598     }
3599     break;
3600   }
3601   case ISD::BITREVERSE: {
3602     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3603     Known = Known2.reverseBits();
3604     break;
3605   }
3606   case ISD::BSWAP: {
3607     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3608     Known = Known2.byteSwap();
3609     break;
3610   }
3611   case ISD::ABS: {
3612     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3613     Known = Known2.abs();
3614     break;
3615   }
3616   case ISD::USUBSAT: {
3617     // The result of usubsat will never be larger than the LHS.
3618     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3619     Known.Zero.setHighBits(Known2.countMinLeadingZeros());
3620     break;
3621   }
3622   case ISD::UMIN: {
3623     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3624     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3625     Known = KnownBits::umin(Known, Known2);
3626     break;
3627   }
3628   case ISD::UMAX: {
3629     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3630     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3631     Known = KnownBits::umax(Known, Known2);
3632     break;
3633   }
3634   case ISD::SMIN:
3635   case ISD::SMAX: {
3636     // If we have a clamp pattern, we know that the number of sign bits will be
3637     // the minimum of the clamp min/max range.
3638     bool IsMax = (Opcode == ISD::SMAX);
3639     ConstantSDNode *CstLow = nullptr, *CstHigh = nullptr;
3640     if ((CstLow = isConstOrConstSplat(Op.getOperand(1), DemandedElts)))
3641       if (Op.getOperand(0).getOpcode() == (IsMax ? ISD::SMIN : ISD::SMAX))
3642         CstHigh =
3643             isConstOrConstSplat(Op.getOperand(0).getOperand(1), DemandedElts);
3644     if (CstLow && CstHigh) {
3645       if (!IsMax)
3646         std::swap(CstLow, CstHigh);
3647 
3648       const APInt &ValueLow = CstLow->getAPIntValue();
3649       const APInt &ValueHigh = CstHigh->getAPIntValue();
3650       if (ValueLow.sle(ValueHigh)) {
3651         unsigned LowSignBits = ValueLow.getNumSignBits();
3652         unsigned HighSignBits = ValueHigh.getNumSignBits();
3653         unsigned MinSignBits = std::min(LowSignBits, HighSignBits);
3654         if (ValueLow.isNegative() && ValueHigh.isNegative()) {
3655           Known.One.setHighBits(MinSignBits);
3656           break;
3657         }
3658         if (ValueLow.isNonNegative() && ValueHigh.isNonNegative()) {
3659           Known.Zero.setHighBits(MinSignBits);
3660           break;
3661         }
3662       }
3663     }
3664 
3665     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3666     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3667     if (IsMax)
3668       Known = KnownBits::smax(Known, Known2);
3669     else
3670       Known = KnownBits::smin(Known, Known2);
3671     break;
3672   }
3673   case ISD::FP_TO_UINT_SAT: {
3674     // FP_TO_UINT_SAT produces an unsigned value that fits in the saturating VT.
3675     EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
3676     Known.Zero |= APInt::getBitsSetFrom(BitWidth, VT.getScalarSizeInBits());
3677     break;
3678   }
3679   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
3680     if (Op.getResNo() == 1) {
3681       // The boolean result conforms to getBooleanContents.
3682       // If we know the result of a setcc has the top bits zero, use this info.
3683       // We know that we have an integer-based boolean since these operations
3684       // are only available for integer.
3685       if (TLI->getBooleanContents(Op.getValueType().isVector(), false) ==
3686               TargetLowering::ZeroOrOneBooleanContent &&
3687           BitWidth > 1)
3688         Known.Zero.setBitsFrom(1);
3689       break;
3690     }
3691     LLVM_FALLTHROUGH;
3692   case ISD::ATOMIC_CMP_SWAP:
3693   case ISD::ATOMIC_SWAP:
3694   case ISD::ATOMIC_LOAD_ADD:
3695   case ISD::ATOMIC_LOAD_SUB:
3696   case ISD::ATOMIC_LOAD_AND:
3697   case ISD::ATOMIC_LOAD_CLR:
3698   case ISD::ATOMIC_LOAD_OR:
3699   case ISD::ATOMIC_LOAD_XOR:
3700   case ISD::ATOMIC_LOAD_NAND:
3701   case ISD::ATOMIC_LOAD_MIN:
3702   case ISD::ATOMIC_LOAD_MAX:
3703   case ISD::ATOMIC_LOAD_UMIN:
3704   case ISD::ATOMIC_LOAD_UMAX:
3705   case ISD::ATOMIC_LOAD: {
3706     unsigned MemBits =
3707         cast<AtomicSDNode>(Op)->getMemoryVT().getScalarSizeInBits();
3708     // If we are looking at the loaded value.
3709     if (Op.getResNo() == 0) {
3710       if (TLI->getExtendForAtomicOps() == ISD::ZERO_EXTEND)
3711         Known.Zero.setBitsFrom(MemBits);
3712     }
3713     break;
3714   }
3715   case ISD::FrameIndex:
3716   case ISD::TargetFrameIndex:
3717     TLI->computeKnownBitsForFrameIndex(cast<FrameIndexSDNode>(Op)->getIndex(),
3718                                        Known, getMachineFunction());
3719     break;
3720 
3721   default:
3722     if (Opcode < ISD::BUILTIN_OP_END)
3723       break;
3724     LLVM_FALLTHROUGH;
3725   case ISD::INTRINSIC_WO_CHAIN:
3726   case ISD::INTRINSIC_W_CHAIN:
3727   case ISD::INTRINSIC_VOID:
3728     // Allow the target to implement this method for its nodes.
3729     TLI->computeKnownBitsForTargetNode(Op, Known, DemandedElts, *this, Depth);
3730     break;
3731   }
3732 
3733   assert(!Known.hasConflict() && "Bits known to be one AND zero?");
3734   return Known;
3735 }
3736 
3737 SelectionDAG::OverflowKind SelectionDAG::computeOverflowKind(SDValue N0,
3738                                                              SDValue N1) const {
3739   // X + 0 never overflow
3740   if (isNullConstant(N1))
3741     return OFK_Never;
3742 
3743   KnownBits N1Known = computeKnownBits(N1);
3744   if (N1Known.Zero.getBoolValue()) {
3745     KnownBits N0Known = computeKnownBits(N0);
3746 
3747     bool overflow;
3748     (void)N0Known.getMaxValue().uadd_ov(N1Known.getMaxValue(), overflow);
3749     if (!overflow)
3750       return OFK_Never;
3751   }
3752 
3753   // mulhi + 1 never overflow
3754   if (N0.getOpcode() == ISD::UMUL_LOHI && N0.getResNo() == 1 &&
3755       (N1Known.getMaxValue() & 0x01) == N1Known.getMaxValue())
3756     return OFK_Never;
3757 
3758   if (N1.getOpcode() == ISD::UMUL_LOHI && N1.getResNo() == 1) {
3759     KnownBits N0Known = computeKnownBits(N0);
3760 
3761     if ((N0Known.getMaxValue() & 0x01) == N0Known.getMaxValue())
3762       return OFK_Never;
3763   }
3764 
3765   return OFK_Sometime;
3766 }
3767 
3768 bool SelectionDAG::isKnownToBeAPowerOfTwo(SDValue Val) const {
3769   EVT OpVT = Val.getValueType();
3770   unsigned BitWidth = OpVT.getScalarSizeInBits();
3771 
3772   // Is the constant a known power of 2?
3773   if (ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Val))
3774     return Const->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2();
3775 
3776   // A left-shift of a constant one will have exactly one bit set because
3777   // shifting the bit off the end is undefined.
3778   if (Val.getOpcode() == ISD::SHL) {
3779     auto *C = isConstOrConstSplat(Val.getOperand(0));
3780     if (C && C->getAPIntValue() == 1)
3781       return true;
3782   }
3783 
3784   // Similarly, a logical right-shift of a constant sign-bit will have exactly
3785   // one bit set.
3786   if (Val.getOpcode() == ISD::SRL) {
3787     auto *C = isConstOrConstSplat(Val.getOperand(0));
3788     if (C && C->getAPIntValue().isSignMask())
3789       return true;
3790   }
3791 
3792   // Are all operands of a build vector constant powers of two?
3793   if (Val.getOpcode() == ISD::BUILD_VECTOR)
3794     if (llvm::all_of(Val->ops(), [BitWidth](SDValue E) {
3795           if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(E))
3796             return C->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2();
3797           return false;
3798         }))
3799       return true;
3800 
3801   // Is the operand of a splat vector a constant power of two?
3802   if (Val.getOpcode() == ISD::SPLAT_VECTOR)
3803     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val->getOperand(0)))
3804       if (C->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2())
3805         return true;
3806 
3807   // More could be done here, though the above checks are enough
3808   // to handle some common cases.
3809 
3810   // Fall back to computeKnownBits to catch other known cases.
3811   KnownBits Known = computeKnownBits(Val);
3812   return (Known.countMaxPopulation() == 1) && (Known.countMinPopulation() == 1);
3813 }
3814 
3815 unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, unsigned Depth) const {
3816   EVT VT = Op.getValueType();
3817 
3818   // TODO: Assume we don't know anything for now.
3819   if (VT.isScalableVector())
3820     return 1;
3821 
3822   APInt DemandedElts = VT.isVector()
3823                            ? APInt::getAllOnes(VT.getVectorNumElements())
3824                            : APInt(1, 1);
3825   return ComputeNumSignBits(Op, DemandedElts, Depth);
3826 }
3827 
3828 unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, const APInt &DemandedElts,
3829                                           unsigned Depth) const {
3830   EVT VT = Op.getValueType();
3831   assert((VT.isInteger() || VT.isFloatingPoint()) && "Invalid VT!");
3832   unsigned VTBits = VT.getScalarSizeInBits();
3833   unsigned NumElts = DemandedElts.getBitWidth();
3834   unsigned Tmp, Tmp2;
3835   unsigned FirstAnswer = 1;
3836 
3837   if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
3838     const APInt &Val = C->getAPIntValue();
3839     return Val.getNumSignBits();
3840   }
3841 
3842   if (Depth >= MaxRecursionDepth)
3843     return 1;  // Limit search depth.
3844 
3845   if (!DemandedElts || VT.isScalableVector())
3846     return 1;  // No demanded elts, better to assume we don't know anything.
3847 
3848   unsigned Opcode = Op.getOpcode();
3849   switch (Opcode) {
3850   default: break;
3851   case ISD::AssertSext:
3852     Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
3853     return VTBits-Tmp+1;
3854   case ISD::AssertZext:
3855     Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
3856     return VTBits-Tmp;
3857 
3858   case ISD::BUILD_VECTOR:
3859     Tmp = VTBits;
3860     for (unsigned i = 0, e = Op.getNumOperands(); (i < e) && (Tmp > 1); ++i) {
3861       if (!DemandedElts[i])
3862         continue;
3863 
3864       SDValue SrcOp = Op.getOperand(i);
3865       Tmp2 = ComputeNumSignBits(SrcOp, Depth + 1);
3866 
3867       // BUILD_VECTOR can implicitly truncate sources, we must handle this.
3868       if (SrcOp.getValueSizeInBits() != VTBits) {
3869         assert(SrcOp.getValueSizeInBits() > VTBits &&
3870                "Expected BUILD_VECTOR implicit truncation");
3871         unsigned ExtraBits = SrcOp.getValueSizeInBits() - VTBits;
3872         Tmp2 = (Tmp2 > ExtraBits ? Tmp2 - ExtraBits : 1);
3873       }
3874       Tmp = std::min(Tmp, Tmp2);
3875     }
3876     return Tmp;
3877 
3878   case ISD::VECTOR_SHUFFLE: {
3879     // Collect the minimum number of sign bits that are shared by every vector
3880     // element referenced by the shuffle.
3881     APInt DemandedLHS(NumElts, 0), DemandedRHS(NumElts, 0);
3882     const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op);
3883     assert(NumElts == SVN->getMask().size() && "Unexpected vector size");
3884     for (unsigned i = 0; i != NumElts; ++i) {
3885       int M = SVN->getMaskElt(i);
3886       if (!DemandedElts[i])
3887         continue;
3888       // For UNDEF elements, we don't know anything about the common state of
3889       // the shuffle result.
3890       if (M < 0)
3891         return 1;
3892       if ((unsigned)M < NumElts)
3893         DemandedLHS.setBit((unsigned)M % NumElts);
3894       else
3895         DemandedRHS.setBit((unsigned)M % NumElts);
3896     }
3897     Tmp = std::numeric_limits<unsigned>::max();
3898     if (!!DemandedLHS)
3899       Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedLHS, Depth + 1);
3900     if (!!DemandedRHS) {
3901       Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedRHS, Depth + 1);
3902       Tmp = std::min(Tmp, Tmp2);
3903     }
3904     // If we don't know anything, early out and try computeKnownBits fall-back.
3905     if (Tmp == 1)
3906       break;
3907     assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
3908     return Tmp;
3909   }
3910 
3911   case ISD::BITCAST: {
3912     SDValue N0 = Op.getOperand(0);
3913     EVT SrcVT = N0.getValueType();
3914     unsigned SrcBits = SrcVT.getScalarSizeInBits();
3915 
3916     // Ignore bitcasts from unsupported types..
3917     if (!(SrcVT.isInteger() || SrcVT.isFloatingPoint()))
3918       break;
3919 
3920     // Fast handling of 'identity' bitcasts.
3921     if (VTBits == SrcBits)
3922       return ComputeNumSignBits(N0, DemandedElts, Depth + 1);
3923 
3924     bool IsLE = getDataLayout().isLittleEndian();
3925 
3926     // Bitcast 'large element' scalar/vector to 'small element' vector.
3927     if ((SrcBits % VTBits) == 0) {
3928       assert(VT.isVector() && "Expected bitcast to vector");
3929 
3930       unsigned Scale = SrcBits / VTBits;
3931       APInt SrcDemandedElts =
3932           APIntOps::ScaleBitMask(DemandedElts, NumElts / Scale);
3933 
3934       // Fast case - sign splat can be simply split across the small elements.
3935       Tmp = ComputeNumSignBits(N0, SrcDemandedElts, Depth + 1);
3936       if (Tmp == SrcBits)
3937         return VTBits;
3938 
3939       // Slow case - determine how far the sign extends into each sub-element.
3940       Tmp2 = VTBits;
3941       for (unsigned i = 0; i != NumElts; ++i)
3942         if (DemandedElts[i]) {
3943           unsigned SubOffset = i % Scale;
3944           SubOffset = (IsLE ? ((Scale - 1) - SubOffset) : SubOffset);
3945           SubOffset = SubOffset * VTBits;
3946           if (Tmp <= SubOffset)
3947             return 1;
3948           Tmp2 = std::min(Tmp2, Tmp - SubOffset);
3949         }
3950       return Tmp2;
3951     }
3952     break;
3953   }
3954 
3955   case ISD::FP_TO_SINT_SAT:
3956     // FP_TO_SINT_SAT produces a signed value that fits in the saturating VT.
3957     Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getScalarSizeInBits();
3958     return VTBits - Tmp + 1;
3959   case ISD::SIGN_EXTEND:
3960     Tmp = VTBits - Op.getOperand(0).getScalarValueSizeInBits();
3961     return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1) + Tmp;
3962   case ISD::SIGN_EXTEND_INREG:
3963     // Max of the input and what this extends.
3964     Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getScalarSizeInBits();
3965     Tmp = VTBits-Tmp+1;
3966     Tmp2 = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1);
3967     return std::max(Tmp, Tmp2);
3968   case ISD::SIGN_EXTEND_VECTOR_INREG: {
3969     SDValue Src = Op.getOperand(0);
3970     EVT SrcVT = Src.getValueType();
3971     APInt DemandedSrcElts = DemandedElts.zextOrSelf(SrcVT.getVectorNumElements());
3972     Tmp = VTBits - SrcVT.getScalarSizeInBits();
3973     return ComputeNumSignBits(Src, DemandedSrcElts, Depth+1) + Tmp;
3974   }
3975   case ISD::SRA:
3976     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
3977     // SRA X, C -> adds C sign bits.
3978     if (const APInt *ShAmt =
3979             getValidMinimumShiftAmountConstant(Op, DemandedElts))
3980       Tmp = std::min<uint64_t>(Tmp + ShAmt->getZExtValue(), VTBits);
3981     return Tmp;
3982   case ISD::SHL:
3983     if (const APInt *ShAmt =
3984             getValidMaximumShiftAmountConstant(Op, DemandedElts)) {
3985       // shl destroys sign bits, ensure it doesn't shift out all sign bits.
3986       Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
3987       if (ShAmt->ult(Tmp))
3988         return Tmp - ShAmt->getZExtValue();
3989     }
3990     break;
3991   case ISD::AND:
3992   case ISD::OR:
3993   case ISD::XOR:    // NOT is handled here.
3994     // Logical binary ops preserve the number of sign bits at the worst.
3995     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1);
3996     if (Tmp != 1) {
3997       Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth+1);
3998       FirstAnswer = std::min(Tmp, Tmp2);
3999       // We computed what we know about the sign bits as our first
4000       // answer. Now proceed to the generic code that uses
4001       // computeKnownBits, and pick whichever answer is better.
4002     }
4003     break;
4004 
4005   case ISD::SELECT:
4006   case ISD::VSELECT:
4007     Tmp = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth+1);
4008     if (Tmp == 1) return 1;  // Early out.
4009     Tmp2 = ComputeNumSignBits(Op.getOperand(2), DemandedElts, Depth+1);
4010     return std::min(Tmp, Tmp2);
4011   case ISD::SELECT_CC:
4012     Tmp = ComputeNumSignBits(Op.getOperand(2), DemandedElts, Depth+1);
4013     if (Tmp == 1) return 1;  // Early out.
4014     Tmp2 = ComputeNumSignBits(Op.getOperand(3), DemandedElts, Depth+1);
4015     return std::min(Tmp, Tmp2);
4016 
4017   case ISD::SMIN:
4018   case ISD::SMAX: {
4019     // If we have a clamp pattern, we know that the number of sign bits will be
4020     // the minimum of the clamp min/max range.
4021     bool IsMax = (Opcode == ISD::SMAX);
4022     ConstantSDNode *CstLow = nullptr, *CstHigh = nullptr;
4023     if ((CstLow = isConstOrConstSplat(Op.getOperand(1), DemandedElts)))
4024       if (Op.getOperand(0).getOpcode() == (IsMax ? ISD::SMIN : ISD::SMAX))
4025         CstHigh =
4026             isConstOrConstSplat(Op.getOperand(0).getOperand(1), DemandedElts);
4027     if (CstLow && CstHigh) {
4028       if (!IsMax)
4029         std::swap(CstLow, CstHigh);
4030       if (CstLow->getAPIntValue().sle(CstHigh->getAPIntValue())) {
4031         Tmp = CstLow->getAPIntValue().getNumSignBits();
4032         Tmp2 = CstHigh->getAPIntValue().getNumSignBits();
4033         return std::min(Tmp, Tmp2);
4034       }
4035     }
4036 
4037     // Fallback - just get the minimum number of sign bits of the operands.
4038     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
4039     if (Tmp == 1)
4040       return 1;  // Early out.
4041     Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
4042     return std::min(Tmp, Tmp2);
4043   }
4044   case ISD::UMIN:
4045   case ISD::UMAX:
4046     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
4047     if (Tmp == 1)
4048       return 1;  // Early out.
4049     Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
4050     return std::min(Tmp, Tmp2);
4051   case ISD::SADDO:
4052   case ISD::UADDO:
4053   case ISD::SSUBO:
4054   case ISD::USUBO:
4055   case ISD::SMULO:
4056   case ISD::UMULO:
4057     if (Op.getResNo() != 1)
4058       break;
4059     // The boolean result conforms to getBooleanContents.  Fall through.
4060     // If setcc returns 0/-1, all bits are sign bits.
4061     // We know that we have an integer-based boolean since these operations
4062     // are only available for integer.
4063     if (TLI->getBooleanContents(VT.isVector(), false) ==
4064         TargetLowering::ZeroOrNegativeOneBooleanContent)
4065       return VTBits;
4066     break;
4067   case ISD::SETCC:
4068   case ISD::STRICT_FSETCC:
4069   case ISD::STRICT_FSETCCS: {
4070     unsigned OpNo = Op->isStrictFPOpcode() ? 1 : 0;
4071     // If setcc returns 0/-1, all bits are sign bits.
4072     if (TLI->getBooleanContents(Op.getOperand(OpNo).getValueType()) ==
4073         TargetLowering::ZeroOrNegativeOneBooleanContent)
4074       return VTBits;
4075     break;
4076   }
4077   case ISD::ROTL:
4078   case ISD::ROTR:
4079     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
4080 
4081     // If we're rotating an 0/-1 value, then it stays an 0/-1 value.
4082     if (Tmp == VTBits)
4083       return VTBits;
4084 
4085     if (ConstantSDNode *C =
4086             isConstOrConstSplat(Op.getOperand(1), DemandedElts)) {
4087       unsigned RotAmt = C->getAPIntValue().urem(VTBits);
4088 
4089       // Handle rotate right by N like a rotate left by 32-N.
4090       if (Opcode == ISD::ROTR)
4091         RotAmt = (VTBits - RotAmt) % VTBits;
4092 
4093       // If we aren't rotating out all of the known-in sign bits, return the
4094       // number that are left.  This handles rotl(sext(x), 1) for example.
4095       if (Tmp > (RotAmt + 1)) return (Tmp - RotAmt);
4096     }
4097     break;
4098   case ISD::ADD:
4099   case ISD::ADDC:
4100     // Add can have at most one carry bit.  Thus we know that the output
4101     // is, at worst, one more bit than the inputs.
4102     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
4103     if (Tmp == 1) return 1; // Early out.
4104 
4105     // Special case decrementing a value (ADD X, -1):
4106     if (ConstantSDNode *CRHS =
4107             isConstOrConstSplat(Op.getOperand(1), DemandedElts))
4108       if (CRHS->isAllOnes()) {
4109         KnownBits Known =
4110             computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4111 
4112         // If the input is known to be 0 or 1, the output is 0/-1, which is all
4113         // sign bits set.
4114         if ((Known.Zero | 1).isAllOnes())
4115           return VTBits;
4116 
4117         // If we are subtracting one from a positive number, there is no carry
4118         // out of the result.
4119         if (Known.isNonNegative())
4120           return Tmp;
4121       }
4122 
4123     Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
4124     if (Tmp2 == 1) return 1; // Early out.
4125     return std::min(Tmp, Tmp2) - 1;
4126   case ISD::SUB:
4127     Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
4128     if (Tmp2 == 1) return 1; // Early out.
4129 
4130     // Handle NEG.
4131     if (ConstantSDNode *CLHS =
4132             isConstOrConstSplat(Op.getOperand(0), DemandedElts))
4133       if (CLHS->isZero()) {
4134         KnownBits Known =
4135             computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4136         // If the input is known to be 0 or 1, the output is 0/-1, which is all
4137         // sign bits set.
4138         if ((Known.Zero | 1).isAllOnes())
4139           return VTBits;
4140 
4141         // If the input is known to be positive (the sign bit is known clear),
4142         // the output of the NEG has the same number of sign bits as the input.
4143         if (Known.isNonNegative())
4144           return Tmp2;
4145 
4146         // Otherwise, we treat this like a SUB.
4147       }
4148 
4149     // Sub can have at most one carry bit.  Thus we know that the output
4150     // is, at worst, one more bit than the inputs.
4151     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
4152     if (Tmp == 1) return 1; // Early out.
4153     return std::min(Tmp, Tmp2) - 1;
4154   case ISD::MUL: {
4155     // The output of the Mul can be at most twice the valid bits in the inputs.
4156     unsigned SignBitsOp0 = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
4157     if (SignBitsOp0 == 1)
4158       break;
4159     unsigned SignBitsOp1 = ComputeNumSignBits(Op.getOperand(1), Depth + 1);
4160     if (SignBitsOp1 == 1)
4161       break;
4162     unsigned OutValidBits =
4163         (VTBits - SignBitsOp0 + 1) + (VTBits - SignBitsOp1 + 1);
4164     return OutValidBits > VTBits ? 1 : VTBits - OutValidBits + 1;
4165   }
4166   case ISD::SREM:
4167     // The sign bit is the LHS's sign bit, except when the result of the
4168     // remainder is zero. The magnitude of the result should be less than or
4169     // equal to the magnitude of the LHS. Therefore, the result should have
4170     // at least as many sign bits as the left hand side.
4171     return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
4172   case ISD::TRUNCATE: {
4173     // Check if the sign bits of source go down as far as the truncated value.
4174     unsigned NumSrcBits = Op.getOperand(0).getScalarValueSizeInBits();
4175     unsigned NumSrcSignBits = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
4176     if (NumSrcSignBits > (NumSrcBits - VTBits))
4177       return NumSrcSignBits - (NumSrcBits - VTBits);
4178     break;
4179   }
4180   case ISD::EXTRACT_ELEMENT: {
4181     const int KnownSign = ComputeNumSignBits(Op.getOperand(0), Depth+1);
4182     const int BitWidth = Op.getValueSizeInBits();
4183     const int Items = Op.getOperand(0).getValueSizeInBits() / BitWidth;
4184 
4185     // Get reverse index (starting from 1), Op1 value indexes elements from
4186     // little end. Sign starts at big end.
4187     const int rIndex = Items - 1 - Op.getConstantOperandVal(1);
4188 
4189     // If the sign portion ends in our element the subtraction gives correct
4190     // result. Otherwise it gives either negative or > bitwidth result
4191     return std::max(std::min(KnownSign - rIndex * BitWidth, BitWidth), 0);
4192   }
4193   case ISD::INSERT_VECTOR_ELT: {
4194     // If we know the element index, split the demand between the
4195     // source vector and the inserted element, otherwise assume we need
4196     // the original demanded vector elements and the value.
4197     SDValue InVec = Op.getOperand(0);
4198     SDValue InVal = Op.getOperand(1);
4199     SDValue EltNo = Op.getOperand(2);
4200     bool DemandedVal = true;
4201     APInt DemandedVecElts = DemandedElts;
4202     auto *CEltNo = dyn_cast<ConstantSDNode>(EltNo);
4203     if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) {
4204       unsigned EltIdx = CEltNo->getZExtValue();
4205       DemandedVal = !!DemandedElts[EltIdx];
4206       DemandedVecElts.clearBit(EltIdx);
4207     }
4208     Tmp = std::numeric_limits<unsigned>::max();
4209     if (DemandedVal) {
4210       // TODO - handle implicit truncation of inserted elements.
4211       if (InVal.getScalarValueSizeInBits() != VTBits)
4212         break;
4213       Tmp2 = ComputeNumSignBits(InVal, Depth + 1);
4214       Tmp = std::min(Tmp, Tmp2);
4215     }
4216     if (!!DemandedVecElts) {
4217       Tmp2 = ComputeNumSignBits(InVec, DemandedVecElts, Depth + 1);
4218       Tmp = std::min(Tmp, Tmp2);
4219     }
4220     assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
4221     return Tmp;
4222   }
4223   case ISD::EXTRACT_VECTOR_ELT: {
4224     SDValue InVec = Op.getOperand(0);
4225     SDValue EltNo = Op.getOperand(1);
4226     EVT VecVT = InVec.getValueType();
4227     // ComputeNumSignBits not yet implemented for scalable vectors.
4228     if (VecVT.isScalableVector())
4229       break;
4230     const unsigned BitWidth = Op.getValueSizeInBits();
4231     const unsigned EltBitWidth = Op.getOperand(0).getScalarValueSizeInBits();
4232     const unsigned NumSrcElts = VecVT.getVectorNumElements();
4233 
4234     // If BitWidth > EltBitWidth the value is anyext:ed, and we do not know
4235     // anything about sign bits. But if the sizes match we can derive knowledge
4236     // about sign bits from the vector operand.
4237     if (BitWidth != EltBitWidth)
4238       break;
4239 
4240     // If we know the element index, just demand that vector element, else for
4241     // an unknown element index, ignore DemandedElts and demand them all.
4242     APInt DemandedSrcElts = APInt::getAllOnes(NumSrcElts);
4243     auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
4244     if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts))
4245       DemandedSrcElts =
4246           APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue());
4247 
4248     return ComputeNumSignBits(InVec, DemandedSrcElts, Depth + 1);
4249   }
4250   case ISD::EXTRACT_SUBVECTOR: {
4251     // Offset the demanded elts by the subvector index.
4252     SDValue Src = Op.getOperand(0);
4253     // Bail until we can represent demanded elements for scalable vectors.
4254     if (Src.getValueType().isScalableVector())
4255       break;
4256     uint64_t Idx = Op.getConstantOperandVal(1);
4257     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
4258     APInt DemandedSrcElts = DemandedElts.zextOrSelf(NumSrcElts).shl(Idx);
4259     return ComputeNumSignBits(Src, DemandedSrcElts, Depth + 1);
4260   }
4261   case ISD::CONCAT_VECTORS: {
4262     // Determine the minimum number of sign bits across all demanded
4263     // elts of the input vectors. Early out if the result is already 1.
4264     Tmp = std::numeric_limits<unsigned>::max();
4265     EVT SubVectorVT = Op.getOperand(0).getValueType();
4266     unsigned NumSubVectorElts = SubVectorVT.getVectorNumElements();
4267     unsigned NumSubVectors = Op.getNumOperands();
4268     for (unsigned i = 0; (i < NumSubVectors) && (Tmp > 1); ++i) {
4269       APInt DemandedSub =
4270           DemandedElts.extractBits(NumSubVectorElts, i * NumSubVectorElts);
4271       if (!DemandedSub)
4272         continue;
4273       Tmp2 = ComputeNumSignBits(Op.getOperand(i), DemandedSub, Depth + 1);
4274       Tmp = std::min(Tmp, Tmp2);
4275     }
4276     assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
4277     return Tmp;
4278   }
4279   case ISD::INSERT_SUBVECTOR: {
4280     // Demand any elements from the subvector and the remainder from the src its
4281     // inserted into.
4282     SDValue Src = Op.getOperand(0);
4283     SDValue Sub = Op.getOperand(1);
4284     uint64_t Idx = Op.getConstantOperandVal(2);
4285     unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
4286     APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
4287     APInt DemandedSrcElts = DemandedElts;
4288     DemandedSrcElts.insertBits(APInt::getZero(NumSubElts), Idx);
4289 
4290     Tmp = std::numeric_limits<unsigned>::max();
4291     if (!!DemandedSubElts) {
4292       Tmp = ComputeNumSignBits(Sub, DemandedSubElts, Depth + 1);
4293       if (Tmp == 1)
4294         return 1; // early-out
4295     }
4296     if (!!DemandedSrcElts) {
4297       Tmp2 = ComputeNumSignBits(Src, DemandedSrcElts, Depth + 1);
4298       Tmp = std::min(Tmp, Tmp2);
4299     }
4300     assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
4301     return Tmp;
4302   }
4303   case ISD::ATOMIC_CMP_SWAP:
4304   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
4305   case ISD::ATOMIC_SWAP:
4306   case ISD::ATOMIC_LOAD_ADD:
4307   case ISD::ATOMIC_LOAD_SUB:
4308   case ISD::ATOMIC_LOAD_AND:
4309   case ISD::ATOMIC_LOAD_CLR:
4310   case ISD::ATOMIC_LOAD_OR:
4311   case ISD::ATOMIC_LOAD_XOR:
4312   case ISD::ATOMIC_LOAD_NAND:
4313   case ISD::ATOMIC_LOAD_MIN:
4314   case ISD::ATOMIC_LOAD_MAX:
4315   case ISD::ATOMIC_LOAD_UMIN:
4316   case ISD::ATOMIC_LOAD_UMAX:
4317   case ISD::ATOMIC_LOAD: {
4318     Tmp = cast<AtomicSDNode>(Op)->getMemoryVT().getScalarSizeInBits();
4319     // If we are looking at the loaded value.
4320     if (Op.getResNo() == 0) {
4321       if (Tmp == VTBits)
4322         return 1; // early-out
4323       if (TLI->getExtendForAtomicOps() == ISD::SIGN_EXTEND)
4324         return VTBits - Tmp + 1;
4325       if (TLI->getExtendForAtomicOps() == ISD::ZERO_EXTEND)
4326         return VTBits - Tmp;
4327     }
4328     break;
4329   }
4330   }
4331 
4332   // If we are looking at the loaded value of the SDNode.
4333   if (Op.getResNo() == 0) {
4334     // Handle LOADX separately here. EXTLOAD case will fallthrough.
4335     if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
4336       unsigned ExtType = LD->getExtensionType();
4337       switch (ExtType) {
4338       default: break;
4339       case ISD::SEXTLOAD: // e.g. i16->i32 = '17' bits known.
4340         Tmp = LD->getMemoryVT().getScalarSizeInBits();
4341         return VTBits - Tmp + 1;
4342       case ISD::ZEXTLOAD: // e.g. i16->i32 = '16' bits known.
4343         Tmp = LD->getMemoryVT().getScalarSizeInBits();
4344         return VTBits - Tmp;
4345       case ISD::NON_EXTLOAD:
4346         if (const Constant *Cst = TLI->getTargetConstantFromLoad(LD)) {
4347           // We only need to handle vectors - computeKnownBits should handle
4348           // scalar cases.
4349           Type *CstTy = Cst->getType();
4350           if (CstTy->isVectorTy() &&
4351               (NumElts * VTBits) == CstTy->getPrimitiveSizeInBits() &&
4352               VTBits == CstTy->getScalarSizeInBits()) {
4353             Tmp = VTBits;
4354             for (unsigned i = 0; i != NumElts; ++i) {
4355               if (!DemandedElts[i])
4356                 continue;
4357               if (Constant *Elt = Cst->getAggregateElement(i)) {
4358                 if (auto *CInt = dyn_cast<ConstantInt>(Elt)) {
4359                   const APInt &Value = CInt->getValue();
4360                   Tmp = std::min(Tmp, Value.getNumSignBits());
4361                   continue;
4362                 }
4363                 if (auto *CFP = dyn_cast<ConstantFP>(Elt)) {
4364                   APInt Value = CFP->getValueAPF().bitcastToAPInt();
4365                   Tmp = std::min(Tmp, Value.getNumSignBits());
4366                   continue;
4367                 }
4368               }
4369               // Unknown type. Conservatively assume no bits match sign bit.
4370               return 1;
4371             }
4372             return Tmp;
4373           }
4374         }
4375         break;
4376       }
4377     }
4378   }
4379 
4380   // Allow the target to implement this method for its nodes.
4381   if (Opcode >= ISD::BUILTIN_OP_END ||
4382       Opcode == ISD::INTRINSIC_WO_CHAIN ||
4383       Opcode == ISD::INTRINSIC_W_CHAIN ||
4384       Opcode == ISD::INTRINSIC_VOID) {
4385     unsigned NumBits =
4386         TLI->ComputeNumSignBitsForTargetNode(Op, DemandedElts, *this, Depth);
4387     if (NumBits > 1)
4388       FirstAnswer = std::max(FirstAnswer, NumBits);
4389   }
4390 
4391   // Finally, if we can prove that the top bits of the result are 0's or 1's,
4392   // use this information.
4393   KnownBits Known = computeKnownBits(Op, DemandedElts, Depth);
4394   return std::max(FirstAnswer, Known.countMinSignBits());
4395 }
4396 
4397 unsigned SelectionDAG::ComputeMaxSignificantBits(SDValue Op,
4398                                                  unsigned Depth) const {
4399   unsigned SignBits = ComputeNumSignBits(Op, Depth);
4400   return Op.getScalarValueSizeInBits() - SignBits + 1;
4401 }
4402 
4403 unsigned SelectionDAG::ComputeMaxSignificantBits(SDValue Op,
4404                                                  const APInt &DemandedElts,
4405                                                  unsigned Depth) const {
4406   unsigned SignBits = ComputeNumSignBits(Op, DemandedElts, Depth);
4407   return Op.getScalarValueSizeInBits() - SignBits + 1;
4408 }
4409 
4410 bool SelectionDAG::isGuaranteedNotToBeUndefOrPoison(SDValue Op, bool PoisonOnly,
4411                                                     unsigned Depth) const {
4412   // Early out for FREEZE.
4413   if (Op.getOpcode() == ISD::FREEZE)
4414     return true;
4415 
4416   // TODO: Assume we don't know anything for now.
4417   EVT VT = Op.getValueType();
4418   if (VT.isScalableVector())
4419     return false;
4420 
4421   APInt DemandedElts = VT.isVector()
4422                            ? APInt::getAllOnes(VT.getVectorNumElements())
4423                            : APInt(1, 1);
4424   return isGuaranteedNotToBeUndefOrPoison(Op, DemandedElts, PoisonOnly, Depth);
4425 }
4426 
4427 bool SelectionDAG::isGuaranteedNotToBeUndefOrPoison(SDValue Op,
4428                                                     const APInt &DemandedElts,
4429                                                     bool PoisonOnly,
4430                                                     unsigned Depth) const {
4431   unsigned Opcode = Op.getOpcode();
4432 
4433   // Early out for FREEZE.
4434   if (Opcode == ISD::FREEZE)
4435     return true;
4436 
4437   if (Depth >= MaxRecursionDepth)
4438     return false; // Limit search depth.
4439 
4440   if (isIntOrFPConstant(Op))
4441     return true;
4442 
4443   switch (Opcode) {
4444   case ISD::UNDEF:
4445     return PoisonOnly;
4446 
4447   case ISD::BUILD_VECTOR:
4448     // NOTE: BUILD_VECTOR has implicit truncation of wider scalar elements -
4449     // this shouldn't affect the result.
4450     for (unsigned i = 0, e = Op.getNumOperands(); i < e; ++i) {
4451       if (!DemandedElts[i])
4452         continue;
4453       if (!isGuaranteedNotToBeUndefOrPoison(Op.getOperand(i), PoisonOnly,
4454                                             Depth + 1))
4455         return false;
4456     }
4457     return true;
4458 
4459   // TODO: Search for noundef attributes from library functions.
4460 
4461   // TODO: Pointers dereferenced by ISD::LOAD/STORE ops are noundef.
4462 
4463   default:
4464     // Allow the target to implement this method for its nodes.
4465     if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::INTRINSIC_WO_CHAIN ||
4466         Opcode == ISD::INTRINSIC_W_CHAIN || Opcode == ISD::INTRINSIC_VOID)
4467       return TLI->isGuaranteedNotToBeUndefOrPoisonForTargetNode(
4468           Op, DemandedElts, *this, PoisonOnly, Depth);
4469     break;
4470   }
4471 
4472   return false;
4473 }
4474 
4475 bool SelectionDAG::isBaseWithConstantOffset(SDValue Op) const {
4476   if ((Op.getOpcode() != ISD::ADD && Op.getOpcode() != ISD::OR) ||
4477       !isa<ConstantSDNode>(Op.getOperand(1)))
4478     return false;
4479 
4480   if (Op.getOpcode() == ISD::OR &&
4481       !MaskedValueIsZero(Op.getOperand(0), Op.getConstantOperandAPInt(1)))
4482     return false;
4483 
4484   return true;
4485 }
4486 
4487 bool SelectionDAG::isKnownNeverNaN(SDValue Op, bool SNaN, unsigned Depth) const {
4488   // If we're told that NaNs won't happen, assume they won't.
4489   if (getTarget().Options.NoNaNsFPMath || Op->getFlags().hasNoNaNs())
4490     return true;
4491 
4492   if (Depth >= MaxRecursionDepth)
4493     return false; // Limit search depth.
4494 
4495   // TODO: Handle vectors.
4496   // If the value is a constant, we can obviously see if it is a NaN or not.
4497   if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) {
4498     return !C->getValueAPF().isNaN() ||
4499            (SNaN && !C->getValueAPF().isSignaling());
4500   }
4501 
4502   unsigned Opcode = Op.getOpcode();
4503   switch (Opcode) {
4504   case ISD::FADD:
4505   case ISD::FSUB:
4506   case ISD::FMUL:
4507   case ISD::FDIV:
4508   case ISD::FREM:
4509   case ISD::FSIN:
4510   case ISD::FCOS: {
4511     if (SNaN)
4512       return true;
4513     // TODO: Need isKnownNeverInfinity
4514     return false;
4515   }
4516   case ISD::FCANONICALIZE:
4517   case ISD::FEXP:
4518   case ISD::FEXP2:
4519   case ISD::FTRUNC:
4520   case ISD::FFLOOR:
4521   case ISD::FCEIL:
4522   case ISD::FROUND:
4523   case ISD::FROUNDEVEN:
4524   case ISD::FRINT:
4525   case ISD::FNEARBYINT: {
4526     if (SNaN)
4527       return true;
4528     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
4529   }
4530   case ISD::FABS:
4531   case ISD::FNEG:
4532   case ISD::FCOPYSIGN: {
4533     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
4534   }
4535   case ISD::SELECT:
4536     return isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1) &&
4537            isKnownNeverNaN(Op.getOperand(2), SNaN, Depth + 1);
4538   case ISD::FP_EXTEND:
4539   case ISD::FP_ROUND: {
4540     if (SNaN)
4541       return true;
4542     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
4543   }
4544   case ISD::SINT_TO_FP:
4545   case ISD::UINT_TO_FP:
4546     return true;
4547   case ISD::FMA:
4548   case ISD::FMAD: {
4549     if (SNaN)
4550       return true;
4551     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) &&
4552            isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1) &&
4553            isKnownNeverNaN(Op.getOperand(2), SNaN, Depth + 1);
4554   }
4555   case ISD::FSQRT: // Need is known positive
4556   case ISD::FLOG:
4557   case ISD::FLOG2:
4558   case ISD::FLOG10:
4559   case ISD::FPOWI:
4560   case ISD::FPOW: {
4561     if (SNaN)
4562       return true;
4563     // TODO: Refine on operand
4564     return false;
4565   }
4566   case ISD::FMINNUM:
4567   case ISD::FMAXNUM: {
4568     // Only one needs to be known not-nan, since it will be returned if the
4569     // other ends up being one.
4570     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) ||
4571            isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1);
4572   }
4573   case ISD::FMINNUM_IEEE:
4574   case ISD::FMAXNUM_IEEE: {
4575     if (SNaN)
4576       return true;
4577     // This can return a NaN if either operand is an sNaN, or if both operands
4578     // are NaN.
4579     return (isKnownNeverNaN(Op.getOperand(0), false, Depth + 1) &&
4580             isKnownNeverSNaN(Op.getOperand(1), Depth + 1)) ||
4581            (isKnownNeverNaN(Op.getOperand(1), false, Depth + 1) &&
4582             isKnownNeverSNaN(Op.getOperand(0), Depth + 1));
4583   }
4584   case ISD::FMINIMUM:
4585   case ISD::FMAXIMUM: {
4586     // TODO: Does this quiet or return the origina NaN as-is?
4587     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) &&
4588            isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1);
4589   }
4590   case ISD::EXTRACT_VECTOR_ELT: {
4591     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
4592   }
4593   default:
4594     if (Opcode >= ISD::BUILTIN_OP_END ||
4595         Opcode == ISD::INTRINSIC_WO_CHAIN ||
4596         Opcode == ISD::INTRINSIC_W_CHAIN ||
4597         Opcode == ISD::INTRINSIC_VOID) {
4598       return TLI->isKnownNeverNaNForTargetNode(Op, *this, SNaN, Depth);
4599     }
4600 
4601     return false;
4602   }
4603 }
4604 
4605 bool SelectionDAG::isKnownNeverZeroFloat(SDValue Op) const {
4606   assert(Op.getValueType().isFloatingPoint() &&
4607          "Floating point type expected");
4608 
4609   // If the value is a constant, we can obviously see if it is a zero or not.
4610   // TODO: Add BuildVector support.
4611   if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op))
4612     return !C->isZero();
4613   return false;
4614 }
4615 
4616 bool SelectionDAG::isKnownNeverZero(SDValue Op) const {
4617   assert(!Op.getValueType().isFloatingPoint() &&
4618          "Floating point types unsupported - use isKnownNeverZeroFloat");
4619 
4620   // If the value is a constant, we can obviously see if it is a zero or not.
4621   if (ISD::matchUnaryPredicate(Op,
4622                                [](ConstantSDNode *C) { return !C->isZero(); }))
4623     return true;
4624 
4625   // TODO: Recognize more cases here.
4626   switch (Op.getOpcode()) {
4627   default: break;
4628   case ISD::OR:
4629     if (isKnownNeverZero(Op.getOperand(1)) ||
4630         isKnownNeverZero(Op.getOperand(0)))
4631       return true;
4632     break;
4633   }
4634 
4635   return false;
4636 }
4637 
4638 bool SelectionDAG::isEqualTo(SDValue A, SDValue B) const {
4639   // Check the obvious case.
4640   if (A == B) return true;
4641 
4642   // For for negative and positive zero.
4643   if (const ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A))
4644     if (const ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B))
4645       if (CA->isZero() && CB->isZero()) return true;
4646 
4647   // Otherwise they may not be equal.
4648   return false;
4649 }
4650 
4651 // FIXME: unify with llvm::haveNoCommonBitsSet.
4652 bool SelectionDAG::haveNoCommonBitsSet(SDValue A, SDValue B) const {
4653   assert(A.getValueType() == B.getValueType() &&
4654          "Values must have the same type");
4655   // Match masked merge pattern (X & ~M) op (Y & M)
4656   if (A->getOpcode() == ISD::AND && B->getOpcode() == ISD::AND) {
4657     auto MatchNoCommonBitsPattern = [&](SDValue NotM, SDValue And) {
4658       if (isBitwiseNot(NotM, true)) {
4659         SDValue NotOperand = NotM->getOperand(0);
4660         return NotOperand == And->getOperand(0) ||
4661                NotOperand == And->getOperand(1);
4662       }
4663       return false;
4664     };
4665     if (MatchNoCommonBitsPattern(A->getOperand(0), B) ||
4666         MatchNoCommonBitsPattern(A->getOperand(1), B) ||
4667         MatchNoCommonBitsPattern(B->getOperand(0), A) ||
4668         MatchNoCommonBitsPattern(B->getOperand(1), A))
4669       return true;
4670   }
4671   return KnownBits::haveNoCommonBitsSet(computeKnownBits(A),
4672                                         computeKnownBits(B));
4673 }
4674 
4675 static SDValue FoldSTEP_VECTOR(const SDLoc &DL, EVT VT, SDValue Step,
4676                                SelectionDAG &DAG) {
4677   if (cast<ConstantSDNode>(Step)->isZero())
4678     return DAG.getConstant(0, DL, VT);
4679 
4680   return SDValue();
4681 }
4682 
4683 static SDValue FoldBUILD_VECTOR(const SDLoc &DL, EVT VT,
4684                                 ArrayRef<SDValue> Ops,
4685                                 SelectionDAG &DAG) {
4686   int NumOps = Ops.size();
4687   assert(NumOps != 0 && "Can't build an empty vector!");
4688   assert(!VT.isScalableVector() &&
4689          "BUILD_VECTOR cannot be used with scalable types");
4690   assert(VT.getVectorNumElements() == (unsigned)NumOps &&
4691          "Incorrect element count in BUILD_VECTOR!");
4692 
4693   // BUILD_VECTOR of UNDEFs is UNDEF.
4694   if (llvm::all_of(Ops, [](SDValue Op) { return Op.isUndef(); }))
4695     return DAG.getUNDEF(VT);
4696 
4697   // BUILD_VECTOR of seq extract/insert from the same vector + type is Identity.
4698   SDValue IdentitySrc;
4699   bool IsIdentity = true;
4700   for (int i = 0; i != NumOps; ++i) {
4701     if (Ops[i].getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
4702         Ops[i].getOperand(0).getValueType() != VT ||
4703         (IdentitySrc && Ops[i].getOperand(0) != IdentitySrc) ||
4704         !isa<ConstantSDNode>(Ops[i].getOperand(1)) ||
4705         cast<ConstantSDNode>(Ops[i].getOperand(1))->getAPIntValue() != i) {
4706       IsIdentity = false;
4707       break;
4708     }
4709     IdentitySrc = Ops[i].getOperand(0);
4710   }
4711   if (IsIdentity)
4712     return IdentitySrc;
4713 
4714   return SDValue();
4715 }
4716 
4717 /// Try to simplify vector concatenation to an input value, undef, or build
4718 /// vector.
4719 static SDValue foldCONCAT_VECTORS(const SDLoc &DL, EVT VT,
4720                                   ArrayRef<SDValue> Ops,
4721                                   SelectionDAG &DAG) {
4722   assert(!Ops.empty() && "Can't concatenate an empty list of vectors!");
4723   assert(llvm::all_of(Ops,
4724                       [Ops](SDValue Op) {
4725                         return Ops[0].getValueType() == Op.getValueType();
4726                       }) &&
4727          "Concatenation of vectors with inconsistent value types!");
4728   assert((Ops[0].getValueType().getVectorElementCount() * Ops.size()) ==
4729              VT.getVectorElementCount() &&
4730          "Incorrect element count in vector concatenation!");
4731 
4732   if (Ops.size() == 1)
4733     return Ops[0];
4734 
4735   // Concat of UNDEFs is UNDEF.
4736   if (llvm::all_of(Ops, [](SDValue Op) { return Op.isUndef(); }))
4737     return DAG.getUNDEF(VT);
4738 
4739   // Scan the operands and look for extract operations from a single source
4740   // that correspond to insertion at the same location via this concatenation:
4741   // concat (extract X, 0*subvec_elts), (extract X, 1*subvec_elts), ...
4742   SDValue IdentitySrc;
4743   bool IsIdentity = true;
4744   for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
4745     SDValue Op = Ops[i];
4746     unsigned IdentityIndex = i * Op.getValueType().getVectorMinNumElements();
4747     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
4748         Op.getOperand(0).getValueType() != VT ||
4749         (IdentitySrc && Op.getOperand(0) != IdentitySrc) ||
4750         Op.getConstantOperandVal(1) != IdentityIndex) {
4751       IsIdentity = false;
4752       break;
4753     }
4754     assert((!IdentitySrc || IdentitySrc == Op.getOperand(0)) &&
4755            "Unexpected identity source vector for concat of extracts");
4756     IdentitySrc = Op.getOperand(0);
4757   }
4758   if (IsIdentity) {
4759     assert(IdentitySrc && "Failed to set source vector of extracts");
4760     return IdentitySrc;
4761   }
4762 
4763   // The code below this point is only designed to work for fixed width
4764   // vectors, so we bail out for now.
4765   if (VT.isScalableVector())
4766     return SDValue();
4767 
4768   // A CONCAT_VECTOR with all UNDEF/BUILD_VECTOR operands can be
4769   // simplified to one big BUILD_VECTOR.
4770   // FIXME: Add support for SCALAR_TO_VECTOR as well.
4771   EVT SVT = VT.getScalarType();
4772   SmallVector<SDValue, 16> Elts;
4773   for (SDValue Op : Ops) {
4774     EVT OpVT = Op.getValueType();
4775     if (Op.isUndef())
4776       Elts.append(OpVT.getVectorNumElements(), DAG.getUNDEF(SVT));
4777     else if (Op.getOpcode() == ISD::BUILD_VECTOR)
4778       Elts.append(Op->op_begin(), Op->op_end());
4779     else
4780       return SDValue();
4781   }
4782 
4783   // BUILD_VECTOR requires all inputs to be of the same type, find the
4784   // maximum type and extend them all.
4785   for (SDValue Op : Elts)
4786     SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
4787 
4788   if (SVT.bitsGT(VT.getScalarType())) {
4789     for (SDValue &Op : Elts) {
4790       if (Op.isUndef())
4791         Op = DAG.getUNDEF(SVT);
4792       else
4793         Op = DAG.getTargetLoweringInfo().isZExtFree(Op.getValueType(), SVT)
4794                  ? DAG.getZExtOrTrunc(Op, DL, SVT)
4795                  : DAG.getSExtOrTrunc(Op, DL, SVT);
4796     }
4797   }
4798 
4799   SDValue V = DAG.getBuildVector(VT, DL, Elts);
4800   NewSDValueDbgMsg(V, "New node fold concat vectors: ", &DAG);
4801   return V;
4802 }
4803 
4804 /// Gets or creates the specified node.
4805 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT) {
4806   FoldingSetNodeID ID;
4807   AddNodeIDNode(ID, Opcode, getVTList(VT), None);
4808   void *IP = nullptr;
4809   if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
4810     return SDValue(E, 0);
4811 
4812   auto *N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(),
4813                               getVTList(VT));
4814   CSEMap.InsertNode(N, IP);
4815 
4816   InsertNode(N);
4817   SDValue V = SDValue(N, 0);
4818   NewSDValueDbgMsg(V, "Creating new node: ", this);
4819   return V;
4820 }
4821 
4822 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
4823                               SDValue Operand) {
4824   SDNodeFlags Flags;
4825   if (Inserter)
4826     Flags = Inserter->getFlags();
4827   return getNode(Opcode, DL, VT, Operand, Flags);
4828 }
4829 
4830 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
4831                               SDValue Operand, const SDNodeFlags Flags) {
4832   assert(Operand.getOpcode() != ISD::DELETED_NODE &&
4833          "Operand is DELETED_NODE!");
4834   // Constant fold unary operations with an integer constant operand. Even
4835   // opaque constant will be folded, because the folding of unary operations
4836   // doesn't create new constants with different values. Nevertheless, the
4837   // opaque flag is preserved during folding to prevent future folding with
4838   // other constants.
4839   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Operand)) {
4840     const APInt &Val = C->getAPIntValue();
4841     switch (Opcode) {
4842     default: break;
4843     case ISD::SIGN_EXTEND:
4844       return getConstant(Val.sextOrTrunc(VT.getSizeInBits()), DL, VT,
4845                          C->isTargetOpcode(), C->isOpaque());
4846     case ISD::TRUNCATE:
4847       if (C->isOpaque())
4848         break;
4849       LLVM_FALLTHROUGH;
4850     case ISD::ZERO_EXTEND:
4851       return getConstant(Val.zextOrTrunc(VT.getSizeInBits()), DL, VT,
4852                          C->isTargetOpcode(), C->isOpaque());
4853     case ISD::ANY_EXTEND:
4854       // Some targets like RISCV prefer to sign extend some types.
4855       if (TLI->isSExtCheaperThanZExt(Operand.getValueType(), VT))
4856         return getConstant(Val.sextOrTrunc(VT.getSizeInBits()), DL, VT,
4857                            C->isTargetOpcode(), C->isOpaque());
4858       return getConstant(Val.zextOrTrunc(VT.getSizeInBits()), DL, VT,
4859                          C->isTargetOpcode(), C->isOpaque());
4860     case ISD::UINT_TO_FP:
4861     case ISD::SINT_TO_FP: {
4862       APFloat apf(EVTToAPFloatSemantics(VT),
4863                   APInt::getZero(VT.getSizeInBits()));
4864       (void)apf.convertFromAPInt(Val,
4865                                  Opcode==ISD::SINT_TO_FP,
4866                                  APFloat::rmNearestTiesToEven);
4867       return getConstantFP(apf, DL, VT);
4868     }
4869     case ISD::BITCAST:
4870       if (VT == MVT::f16 && C->getValueType(0) == MVT::i16)
4871         return getConstantFP(APFloat(APFloat::IEEEhalf(), Val), DL, VT);
4872       if (VT == MVT::f32 && C->getValueType(0) == MVT::i32)
4873         return getConstantFP(APFloat(APFloat::IEEEsingle(), Val), DL, VT);
4874       if (VT == MVT::f64 && C->getValueType(0) == MVT::i64)
4875         return getConstantFP(APFloat(APFloat::IEEEdouble(), Val), DL, VT);
4876       if (VT == MVT::f128 && C->getValueType(0) == MVT::i128)
4877         return getConstantFP(APFloat(APFloat::IEEEquad(), Val), DL, VT);
4878       break;
4879     case ISD::ABS:
4880       return getConstant(Val.abs(), DL, VT, C->isTargetOpcode(),
4881                          C->isOpaque());
4882     case ISD::BITREVERSE:
4883       return getConstant(Val.reverseBits(), DL, VT, C->isTargetOpcode(),
4884                          C->isOpaque());
4885     case ISD::BSWAP:
4886       return getConstant(Val.byteSwap(), DL, VT, C->isTargetOpcode(),
4887                          C->isOpaque());
4888     case ISD::CTPOP:
4889       return getConstant(Val.countPopulation(), DL, VT, C->isTargetOpcode(),
4890                          C->isOpaque());
4891     case ISD::CTLZ:
4892     case ISD::CTLZ_ZERO_UNDEF:
4893       return getConstant(Val.countLeadingZeros(), DL, VT, C->isTargetOpcode(),
4894                          C->isOpaque());
4895     case ISD::CTTZ:
4896     case ISD::CTTZ_ZERO_UNDEF:
4897       return getConstant(Val.countTrailingZeros(), DL, VT, C->isTargetOpcode(),
4898                          C->isOpaque());
4899     case ISD::FP16_TO_FP: {
4900       bool Ignored;
4901       APFloat FPV(APFloat::IEEEhalf(),
4902                   (Val.getBitWidth() == 16) ? Val : Val.trunc(16));
4903 
4904       // This can return overflow, underflow, or inexact; we don't care.
4905       // FIXME need to be more flexible about rounding mode.
4906       (void)FPV.convert(EVTToAPFloatSemantics(VT),
4907                         APFloat::rmNearestTiesToEven, &Ignored);
4908       return getConstantFP(FPV, DL, VT);
4909     }
4910     case ISD::STEP_VECTOR: {
4911       if (SDValue V = FoldSTEP_VECTOR(DL, VT, Operand, *this))
4912         return V;
4913       break;
4914     }
4915     }
4916   }
4917 
4918   // Constant fold unary operations with a floating point constant operand.
4919   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Operand)) {
4920     APFloat V = C->getValueAPF();    // make copy
4921     switch (Opcode) {
4922     case ISD::FNEG:
4923       V.changeSign();
4924       return getConstantFP(V, DL, VT);
4925     case ISD::FABS:
4926       V.clearSign();
4927       return getConstantFP(V, DL, VT);
4928     case ISD::FCEIL: {
4929       APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardPositive);
4930       if (fs == APFloat::opOK || fs == APFloat::opInexact)
4931         return getConstantFP(V, DL, VT);
4932       break;
4933     }
4934     case ISD::FTRUNC: {
4935       APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardZero);
4936       if (fs == APFloat::opOK || fs == APFloat::opInexact)
4937         return getConstantFP(V, DL, VT);
4938       break;
4939     }
4940     case ISD::FFLOOR: {
4941       APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardNegative);
4942       if (fs == APFloat::opOK || fs == APFloat::opInexact)
4943         return getConstantFP(V, DL, VT);
4944       break;
4945     }
4946     case ISD::FP_EXTEND: {
4947       bool ignored;
4948       // This can return overflow, underflow, or inexact; we don't care.
4949       // FIXME need to be more flexible about rounding mode.
4950       (void)V.convert(EVTToAPFloatSemantics(VT),
4951                       APFloat::rmNearestTiesToEven, &ignored);
4952       return getConstantFP(V, DL, VT);
4953     }
4954     case ISD::FP_TO_SINT:
4955     case ISD::FP_TO_UINT: {
4956       bool ignored;
4957       APSInt IntVal(VT.getSizeInBits(), Opcode == ISD::FP_TO_UINT);
4958       // FIXME need to be more flexible about rounding mode.
4959       APFloat::opStatus s =
4960           V.convertToInteger(IntVal, APFloat::rmTowardZero, &ignored);
4961       if (s == APFloat::opInvalidOp) // inexact is OK, in fact usual
4962         break;
4963       return getConstant(IntVal, DL, VT);
4964     }
4965     case ISD::BITCAST:
4966       if (VT == MVT::i16 && C->getValueType(0) == MVT::f16)
4967         return getConstant((uint16_t)V.bitcastToAPInt().getZExtValue(), DL, VT);
4968       if (VT == MVT::i16 && C->getValueType(0) == MVT::bf16)
4969         return getConstant((uint16_t)V.bitcastToAPInt().getZExtValue(), DL, VT);
4970       if (VT == MVT::i32 && C->getValueType(0) == MVT::f32)
4971         return getConstant((uint32_t)V.bitcastToAPInt().getZExtValue(), DL, VT);
4972       if (VT == MVT::i64 && C->getValueType(0) == MVT::f64)
4973         return getConstant(V.bitcastToAPInt().getZExtValue(), DL, VT);
4974       break;
4975     case ISD::FP_TO_FP16: {
4976       bool Ignored;
4977       // This can return overflow, underflow, or inexact; we don't care.
4978       // FIXME need to be more flexible about rounding mode.
4979       (void)V.convert(APFloat::IEEEhalf(),
4980                       APFloat::rmNearestTiesToEven, &Ignored);
4981       return getConstant(V.bitcastToAPInt().getZExtValue(), DL, VT);
4982     }
4983     }
4984   }
4985 
4986   // Constant fold unary operations with a vector integer or float operand.
4987   switch (Opcode) {
4988   default:
4989     // FIXME: Entirely reasonable to perform folding of other unary
4990     // operations here as the need arises.
4991     break;
4992   case ISD::FNEG:
4993   case ISD::FABS:
4994   case ISD::FCEIL:
4995   case ISD::FTRUNC:
4996   case ISD::FFLOOR:
4997   case ISD::FP_EXTEND:
4998   case ISD::FP_TO_SINT:
4999   case ISD::FP_TO_UINT:
5000   case ISD::TRUNCATE:
5001   case ISD::ANY_EXTEND:
5002   case ISD::ZERO_EXTEND:
5003   case ISD::SIGN_EXTEND:
5004   case ISD::UINT_TO_FP:
5005   case ISD::SINT_TO_FP:
5006   case ISD::ABS:
5007   case ISD::BITREVERSE:
5008   case ISD::BSWAP:
5009   case ISD::CTLZ:
5010   case ISD::CTLZ_ZERO_UNDEF:
5011   case ISD::CTTZ:
5012   case ISD::CTTZ_ZERO_UNDEF:
5013   case ISD::CTPOP: {
5014     SDValue Ops = {Operand};
5015     if (SDValue Fold = FoldConstantArithmetic(Opcode, DL, VT, Ops))
5016       return Fold;
5017   }
5018   }
5019 
5020   unsigned OpOpcode = Operand.getNode()->getOpcode();
5021   switch (Opcode) {
5022   case ISD::STEP_VECTOR:
5023     assert(VT.isScalableVector() &&
5024            "STEP_VECTOR can only be used with scalable types");
5025     assert(OpOpcode == ISD::TargetConstant &&
5026            VT.getVectorElementType() == Operand.getValueType() &&
5027            "Unexpected step operand");
5028     break;
5029   case ISD::FREEZE:
5030     assert(VT == Operand.getValueType() && "Unexpected VT!");
5031     break;
5032   case ISD::TokenFactor:
5033   case ISD::MERGE_VALUES:
5034   case ISD::CONCAT_VECTORS:
5035     return Operand;         // Factor, merge or concat of one node?  No need.
5036   case ISD::BUILD_VECTOR: {
5037     // Attempt to simplify BUILD_VECTOR.
5038     SDValue Ops[] = {Operand};
5039     if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
5040       return V;
5041     break;
5042   }
5043   case ISD::FP_ROUND: llvm_unreachable("Invalid method to make FP_ROUND node");
5044   case ISD::FP_EXTEND:
5045     assert(VT.isFloatingPoint() &&
5046            Operand.getValueType().isFloatingPoint() && "Invalid FP cast!");
5047     if (Operand.getValueType() == VT) return Operand;  // noop conversion.
5048     assert((!VT.isVector() ||
5049             VT.getVectorElementCount() ==
5050             Operand.getValueType().getVectorElementCount()) &&
5051            "Vector element count mismatch!");
5052     assert(Operand.getValueType().bitsLT(VT) &&
5053            "Invalid fpext node, dst < src!");
5054     if (Operand.isUndef())
5055       return getUNDEF(VT);
5056     break;
5057   case ISD::FP_TO_SINT:
5058   case ISD::FP_TO_UINT:
5059     if (Operand.isUndef())
5060       return getUNDEF(VT);
5061     break;
5062   case ISD::SINT_TO_FP:
5063   case ISD::UINT_TO_FP:
5064     // [us]itofp(undef) = 0, because the result value is bounded.
5065     if (Operand.isUndef())
5066       return getConstantFP(0.0, DL, VT);
5067     break;
5068   case ISD::SIGN_EXTEND:
5069     assert(VT.isInteger() && Operand.getValueType().isInteger() &&
5070            "Invalid SIGN_EXTEND!");
5071     assert(VT.isVector() == Operand.getValueType().isVector() &&
5072            "SIGN_EXTEND result type type should be vector iff the operand "
5073            "type is vector!");
5074     if (Operand.getValueType() == VT) return Operand;   // noop extension
5075     assert((!VT.isVector() ||
5076             VT.getVectorElementCount() ==
5077                 Operand.getValueType().getVectorElementCount()) &&
5078            "Vector element count mismatch!");
5079     assert(Operand.getValueType().bitsLT(VT) &&
5080            "Invalid sext node, dst < src!");
5081     if (OpOpcode == ISD::SIGN_EXTEND || OpOpcode == ISD::ZERO_EXTEND)
5082       return getNode(OpOpcode, DL, VT, Operand.getOperand(0));
5083     if (OpOpcode == ISD::UNDEF)
5084       // sext(undef) = 0, because the top bits will all be the same.
5085       return getConstant(0, DL, VT);
5086     break;
5087   case ISD::ZERO_EXTEND:
5088     assert(VT.isInteger() && Operand.getValueType().isInteger() &&
5089            "Invalid ZERO_EXTEND!");
5090     assert(VT.isVector() == Operand.getValueType().isVector() &&
5091            "ZERO_EXTEND result type type should be vector iff the operand "
5092            "type is vector!");
5093     if (Operand.getValueType() == VT) return Operand;   // noop extension
5094     assert((!VT.isVector() ||
5095             VT.getVectorElementCount() ==
5096                 Operand.getValueType().getVectorElementCount()) &&
5097            "Vector element count mismatch!");
5098     assert(Operand.getValueType().bitsLT(VT) &&
5099            "Invalid zext node, dst < src!");
5100     if (OpOpcode == ISD::ZERO_EXTEND)   // (zext (zext x)) -> (zext x)
5101       return getNode(ISD::ZERO_EXTEND, DL, VT, Operand.getOperand(0));
5102     if (OpOpcode == ISD::UNDEF)
5103       // zext(undef) = 0, because the top bits will be zero.
5104       return getConstant(0, DL, VT);
5105     break;
5106   case ISD::ANY_EXTEND:
5107     assert(VT.isInteger() && Operand.getValueType().isInteger() &&
5108            "Invalid ANY_EXTEND!");
5109     assert(VT.isVector() == Operand.getValueType().isVector() &&
5110            "ANY_EXTEND result type type should be vector iff the operand "
5111            "type is vector!");
5112     if (Operand.getValueType() == VT) return Operand;   // noop extension
5113     assert((!VT.isVector() ||
5114             VT.getVectorElementCount() ==
5115                 Operand.getValueType().getVectorElementCount()) &&
5116            "Vector element count mismatch!");
5117     assert(Operand.getValueType().bitsLT(VT) &&
5118            "Invalid anyext node, dst < src!");
5119 
5120     if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
5121         OpOpcode == ISD::ANY_EXTEND)
5122       // (ext (zext x)) -> (zext x)  and  (ext (sext x)) -> (sext x)
5123       return getNode(OpOpcode, DL, VT, Operand.getOperand(0));
5124     if (OpOpcode == ISD::UNDEF)
5125       return getUNDEF(VT);
5126 
5127     // (ext (trunc x)) -> x
5128     if (OpOpcode == ISD::TRUNCATE) {
5129       SDValue OpOp = Operand.getOperand(0);
5130       if (OpOp.getValueType() == VT) {
5131         transferDbgValues(Operand, OpOp);
5132         return OpOp;
5133       }
5134     }
5135     break;
5136   case ISD::TRUNCATE:
5137     assert(VT.isInteger() && Operand.getValueType().isInteger() &&
5138            "Invalid TRUNCATE!");
5139     assert(VT.isVector() == Operand.getValueType().isVector() &&
5140            "TRUNCATE result type type should be vector iff the operand "
5141            "type is vector!");
5142     if (Operand.getValueType() == VT) return Operand;   // noop truncate
5143     assert((!VT.isVector() ||
5144             VT.getVectorElementCount() ==
5145                 Operand.getValueType().getVectorElementCount()) &&
5146            "Vector element count mismatch!");
5147     assert(Operand.getValueType().bitsGT(VT) &&
5148            "Invalid truncate node, src < dst!");
5149     if (OpOpcode == ISD::TRUNCATE)
5150       return getNode(ISD::TRUNCATE, DL, VT, Operand.getOperand(0));
5151     if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
5152         OpOpcode == ISD::ANY_EXTEND) {
5153       // If the source is smaller than the dest, we still need an extend.
5154       if (Operand.getOperand(0).getValueType().getScalarType()
5155             .bitsLT(VT.getScalarType()))
5156         return getNode(OpOpcode, DL, VT, Operand.getOperand(0));
5157       if (Operand.getOperand(0).getValueType().bitsGT(VT))
5158         return getNode(ISD::TRUNCATE, DL, VT, Operand.getOperand(0));
5159       return Operand.getOperand(0);
5160     }
5161     if (OpOpcode == ISD::UNDEF)
5162       return getUNDEF(VT);
5163     if (OpOpcode == ISD::VSCALE && !NewNodesMustHaveLegalTypes)
5164       return getVScale(DL, VT, Operand.getConstantOperandAPInt(0));
5165     break;
5166   case ISD::ANY_EXTEND_VECTOR_INREG:
5167   case ISD::ZERO_EXTEND_VECTOR_INREG:
5168   case ISD::SIGN_EXTEND_VECTOR_INREG:
5169     assert(VT.isVector() && "This DAG node is restricted to vector types.");
5170     assert(Operand.getValueType().bitsLE(VT) &&
5171            "The input must be the same size or smaller than the result.");
5172     assert(VT.getVectorMinNumElements() <
5173                Operand.getValueType().getVectorMinNumElements() &&
5174            "The destination vector type must have fewer lanes than the input.");
5175     break;
5176   case ISD::ABS:
5177     assert(VT.isInteger() && VT == Operand.getValueType() &&
5178            "Invalid ABS!");
5179     if (OpOpcode == ISD::UNDEF)
5180       return getUNDEF(VT);
5181     break;
5182   case ISD::BSWAP:
5183     assert(VT.isInteger() && VT == Operand.getValueType() &&
5184            "Invalid BSWAP!");
5185     assert((VT.getScalarSizeInBits() % 16 == 0) &&
5186            "BSWAP types must be a multiple of 16 bits!");
5187     if (OpOpcode == ISD::UNDEF)
5188       return getUNDEF(VT);
5189     // bswap(bswap(X)) -> X.
5190     if (OpOpcode == ISD::BSWAP)
5191       return Operand.getOperand(0);
5192     break;
5193   case ISD::BITREVERSE:
5194     assert(VT.isInteger() && VT == Operand.getValueType() &&
5195            "Invalid BITREVERSE!");
5196     if (OpOpcode == ISD::UNDEF)
5197       return getUNDEF(VT);
5198     break;
5199   case ISD::BITCAST:
5200     assert(VT.getSizeInBits() == Operand.getValueSizeInBits() &&
5201            "Cannot BITCAST between types of different sizes!");
5202     if (VT == Operand.getValueType()) return Operand;  // noop conversion.
5203     if (OpOpcode == ISD::BITCAST)  // bitconv(bitconv(x)) -> bitconv(x)
5204       return getNode(ISD::BITCAST, DL, VT, Operand.getOperand(0));
5205     if (OpOpcode == ISD::UNDEF)
5206       return getUNDEF(VT);
5207     break;
5208   case ISD::SCALAR_TO_VECTOR:
5209     assert(VT.isVector() && !Operand.getValueType().isVector() &&
5210            (VT.getVectorElementType() == Operand.getValueType() ||
5211             (VT.getVectorElementType().isInteger() &&
5212              Operand.getValueType().isInteger() &&
5213              VT.getVectorElementType().bitsLE(Operand.getValueType()))) &&
5214            "Illegal SCALAR_TO_VECTOR node!");
5215     if (OpOpcode == ISD::UNDEF)
5216       return getUNDEF(VT);
5217     // scalar_to_vector(extract_vector_elt V, 0) -> V, top bits are undefined.
5218     if (OpOpcode == ISD::EXTRACT_VECTOR_ELT &&
5219         isa<ConstantSDNode>(Operand.getOperand(1)) &&
5220         Operand.getConstantOperandVal(1) == 0 &&
5221         Operand.getOperand(0).getValueType() == VT)
5222       return Operand.getOperand(0);
5223     break;
5224   case ISD::FNEG:
5225     // Negation of an unknown bag of bits is still completely undefined.
5226     if (OpOpcode == ISD::UNDEF)
5227       return getUNDEF(VT);
5228 
5229     if (OpOpcode == ISD::FNEG)  // --X -> X
5230       return Operand.getOperand(0);
5231     break;
5232   case ISD::FABS:
5233     if (OpOpcode == ISD::FNEG)  // abs(-X) -> abs(X)
5234       return getNode(ISD::FABS, DL, VT, Operand.getOperand(0));
5235     break;
5236   case ISD::VSCALE:
5237     assert(VT == Operand.getValueType() && "Unexpected VT!");
5238     break;
5239   case ISD::CTPOP:
5240     if (Operand.getValueType().getScalarType() == MVT::i1)
5241       return Operand;
5242     break;
5243   case ISD::CTLZ:
5244   case ISD::CTTZ:
5245     if (Operand.getValueType().getScalarType() == MVT::i1)
5246       return getNOT(DL, Operand, Operand.getValueType());
5247     break;
5248   case ISD::VECREDUCE_SMIN:
5249   case ISD::VECREDUCE_UMAX:
5250     if (Operand.getValueType().getScalarType() == MVT::i1)
5251       return getNode(ISD::VECREDUCE_OR, DL, VT, Operand);
5252     break;
5253   case ISD::VECREDUCE_SMAX:
5254   case ISD::VECREDUCE_UMIN:
5255     if (Operand.getValueType().getScalarType() == MVT::i1)
5256       return getNode(ISD::VECREDUCE_AND, DL, VT, Operand);
5257     break;
5258   }
5259 
5260   SDNode *N;
5261   SDVTList VTs = getVTList(VT);
5262   SDValue Ops[] = {Operand};
5263   if (VT != MVT::Glue) { // Don't CSE flag producing nodes
5264     FoldingSetNodeID ID;
5265     AddNodeIDNode(ID, Opcode, VTs, Ops);
5266     void *IP = nullptr;
5267     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
5268       E->intersectFlagsWith(Flags);
5269       return SDValue(E, 0);
5270     }
5271 
5272     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
5273     N->setFlags(Flags);
5274     createOperands(N, Ops);
5275     CSEMap.InsertNode(N, IP);
5276   } else {
5277     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
5278     createOperands(N, Ops);
5279   }
5280 
5281   InsertNode(N);
5282   SDValue V = SDValue(N, 0);
5283   NewSDValueDbgMsg(V, "Creating new node: ", this);
5284   return V;
5285 }
5286 
5287 static llvm::Optional<APInt> FoldValue(unsigned Opcode, const APInt &C1,
5288                                        const APInt &C2) {
5289   switch (Opcode) {
5290   case ISD::ADD:  return C1 + C2;
5291   case ISD::SUB:  return C1 - C2;
5292   case ISD::MUL:  return C1 * C2;
5293   case ISD::AND:  return C1 & C2;
5294   case ISD::OR:   return C1 | C2;
5295   case ISD::XOR:  return C1 ^ C2;
5296   case ISD::SHL:  return C1 << C2;
5297   case ISD::SRL:  return C1.lshr(C2);
5298   case ISD::SRA:  return C1.ashr(C2);
5299   case ISD::ROTL: return C1.rotl(C2);
5300   case ISD::ROTR: return C1.rotr(C2);
5301   case ISD::SMIN: return C1.sle(C2) ? C1 : C2;
5302   case ISD::SMAX: return C1.sge(C2) ? C1 : C2;
5303   case ISD::UMIN: return C1.ule(C2) ? C1 : C2;
5304   case ISD::UMAX: return C1.uge(C2) ? C1 : C2;
5305   case ISD::SADDSAT: return C1.sadd_sat(C2);
5306   case ISD::UADDSAT: return C1.uadd_sat(C2);
5307   case ISD::SSUBSAT: return C1.ssub_sat(C2);
5308   case ISD::USUBSAT: return C1.usub_sat(C2);
5309   case ISD::SSHLSAT: return C1.sshl_sat(C2);
5310   case ISD::USHLSAT: return C1.ushl_sat(C2);
5311   case ISD::UDIV:
5312     if (!C2.getBoolValue())
5313       break;
5314     return C1.udiv(C2);
5315   case ISD::UREM:
5316     if (!C2.getBoolValue())
5317       break;
5318     return C1.urem(C2);
5319   case ISD::SDIV:
5320     if (!C2.getBoolValue())
5321       break;
5322     return C1.sdiv(C2);
5323   case ISD::SREM:
5324     if (!C2.getBoolValue())
5325       break;
5326     return C1.srem(C2);
5327   case ISD::MULHS: {
5328     unsigned FullWidth = C1.getBitWidth() * 2;
5329     APInt C1Ext = C1.sext(FullWidth);
5330     APInt C2Ext = C2.sext(FullWidth);
5331     return (C1Ext * C2Ext).extractBits(C1.getBitWidth(), C1.getBitWidth());
5332   }
5333   case ISD::MULHU: {
5334     unsigned FullWidth = C1.getBitWidth() * 2;
5335     APInt C1Ext = C1.zext(FullWidth);
5336     APInt C2Ext = C2.zext(FullWidth);
5337     return (C1Ext * C2Ext).extractBits(C1.getBitWidth(), C1.getBitWidth());
5338   }
5339   case ISD::AVGFLOORS: {
5340     unsigned FullWidth = C1.getBitWidth() + 1;
5341     APInt C1Ext = C1.sext(FullWidth);
5342     APInt C2Ext = C2.sext(FullWidth);
5343     return (C1Ext + C2Ext).extractBits(C1.getBitWidth(), 1);
5344   }
5345   case ISD::AVGFLOORU: {
5346     unsigned FullWidth = C1.getBitWidth() + 1;
5347     APInt C1Ext = C1.zext(FullWidth);
5348     APInt C2Ext = C2.zext(FullWidth);
5349     return (C1Ext + C2Ext).extractBits(C1.getBitWidth(), 1);
5350   }
5351   case ISD::AVGCEILS: {
5352     unsigned FullWidth = C1.getBitWidth() + 1;
5353     APInt C1Ext = C1.sext(FullWidth);
5354     APInt C2Ext = C2.sext(FullWidth);
5355     return (C1Ext + C2Ext + 1).extractBits(C1.getBitWidth(), 1);
5356   }
5357   case ISD::AVGCEILU: {
5358     unsigned FullWidth = C1.getBitWidth() + 1;
5359     APInt C1Ext = C1.zext(FullWidth);
5360     APInt C2Ext = C2.zext(FullWidth);
5361     return (C1Ext + C2Ext + 1).extractBits(C1.getBitWidth(), 1);
5362   }
5363   }
5364   return llvm::None;
5365 }
5366 
5367 SDValue SelectionDAG::FoldSymbolOffset(unsigned Opcode, EVT VT,
5368                                        const GlobalAddressSDNode *GA,
5369                                        const SDNode *N2) {
5370   if (GA->getOpcode() != ISD::GlobalAddress)
5371     return SDValue();
5372   if (!TLI->isOffsetFoldingLegal(GA))
5373     return SDValue();
5374   auto *C2 = dyn_cast<ConstantSDNode>(N2);
5375   if (!C2)
5376     return SDValue();
5377   int64_t Offset = C2->getSExtValue();
5378   switch (Opcode) {
5379   case ISD::ADD: break;
5380   case ISD::SUB: Offset = -uint64_t(Offset); break;
5381   default: return SDValue();
5382   }
5383   return getGlobalAddress(GA->getGlobal(), SDLoc(C2), VT,
5384                           GA->getOffset() + uint64_t(Offset));
5385 }
5386 
5387 bool SelectionDAG::isUndef(unsigned Opcode, ArrayRef<SDValue> Ops) {
5388   switch (Opcode) {
5389   case ISD::SDIV:
5390   case ISD::UDIV:
5391   case ISD::SREM:
5392   case ISD::UREM: {
5393     // If a divisor is zero/undef or any element of a divisor vector is
5394     // zero/undef, the whole op is undef.
5395     assert(Ops.size() == 2 && "Div/rem should have 2 operands");
5396     SDValue Divisor = Ops[1];
5397     if (Divisor.isUndef() || isNullConstant(Divisor))
5398       return true;
5399 
5400     return ISD::isBuildVectorOfConstantSDNodes(Divisor.getNode()) &&
5401            llvm::any_of(Divisor->op_values(),
5402                         [](SDValue V) { return V.isUndef() ||
5403                                         isNullConstant(V); });
5404     // TODO: Handle signed overflow.
5405   }
5406   // TODO: Handle oversized shifts.
5407   default:
5408     return false;
5409   }
5410 }
5411 
5412 SDValue SelectionDAG::FoldConstantArithmetic(unsigned Opcode, const SDLoc &DL,
5413                                              EVT VT, ArrayRef<SDValue> Ops) {
5414   // If the opcode is a target-specific ISD node, there's nothing we can
5415   // do here and the operand rules may not line up with the below, so
5416   // bail early.
5417   // We can't create a scalar CONCAT_VECTORS so skip it. It will break
5418   // for concats involving SPLAT_VECTOR. Concats of BUILD_VECTORS are handled by
5419   // foldCONCAT_VECTORS in getNode before this is called.
5420   if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::CONCAT_VECTORS)
5421     return SDValue();
5422 
5423   unsigned NumOps = Ops.size();
5424   if (NumOps == 0)
5425     return SDValue();
5426 
5427   if (isUndef(Opcode, Ops))
5428     return getUNDEF(VT);
5429 
5430   // Handle binops special cases.
5431   if (NumOps == 2) {
5432     if (SDValue CFP = foldConstantFPMath(Opcode, DL, VT, Ops[0], Ops[1]))
5433       return CFP;
5434 
5435     if (auto *C1 = dyn_cast<ConstantSDNode>(Ops[0])) {
5436       if (auto *C2 = dyn_cast<ConstantSDNode>(Ops[1])) {
5437         if (C1->isOpaque() || C2->isOpaque())
5438           return SDValue();
5439 
5440         Optional<APInt> FoldAttempt =
5441             FoldValue(Opcode, C1->getAPIntValue(), C2->getAPIntValue());
5442         if (!FoldAttempt)
5443           return SDValue();
5444 
5445         SDValue Folded = getConstant(FoldAttempt.getValue(), DL, VT);
5446         assert((!Folded || !VT.isVector()) &&
5447                "Can't fold vectors ops with scalar operands");
5448         return Folded;
5449       }
5450     }
5451 
5452     // fold (add Sym, c) -> Sym+c
5453     if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Ops[0]))
5454       return FoldSymbolOffset(Opcode, VT, GA, Ops[1].getNode());
5455     if (TLI->isCommutativeBinOp(Opcode))
5456       if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Ops[1]))
5457         return FoldSymbolOffset(Opcode, VT, GA, Ops[0].getNode());
5458   }
5459 
5460   // This is for vector folding only from here on.
5461   if (!VT.isVector())
5462     return SDValue();
5463 
5464   ElementCount NumElts = VT.getVectorElementCount();
5465 
5466   // See if we can fold through bitcasted integer ops.
5467   // TODO: Can we handle undef elements?
5468   if (NumOps == 2 && VT.isFixedLengthVector() && VT.isInteger() &&
5469       Ops[0].getValueType() == VT && Ops[1].getValueType() == VT &&
5470       Ops[0].getOpcode() == ISD::BITCAST &&
5471       Ops[1].getOpcode() == ISD::BITCAST) {
5472     SDValue N1 = peekThroughBitcasts(Ops[0]);
5473     SDValue N2 = peekThroughBitcasts(Ops[1]);
5474     auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
5475     auto *BV2 = dyn_cast<BuildVectorSDNode>(N2);
5476     EVT BVVT = N1.getValueType();
5477     if (BV1 && BV2 && BVVT.isInteger() && BVVT == N2.getValueType()) {
5478       bool IsLE = getDataLayout().isLittleEndian();
5479       unsigned EltBits = VT.getScalarSizeInBits();
5480       SmallVector<APInt> RawBits1, RawBits2;
5481       BitVector UndefElts1, UndefElts2;
5482       if (BV1->getConstantRawBits(IsLE, EltBits, RawBits1, UndefElts1) &&
5483           BV2->getConstantRawBits(IsLE, EltBits, RawBits2, UndefElts2) &&
5484           UndefElts1.none() && UndefElts2.none()) {
5485         SmallVector<APInt> RawBits;
5486         for (unsigned I = 0, E = NumElts.getFixedValue(); I != E; ++I) {
5487           Optional<APInt> Fold = FoldValue(Opcode, RawBits1[I], RawBits2[I]);
5488           if (!Fold)
5489             break;
5490           RawBits.push_back(Fold.getValue());
5491         }
5492         if (RawBits.size() == NumElts.getFixedValue()) {
5493           // We have constant folded, but we need to cast this again back to
5494           // the original (possibly legalized) type.
5495           SmallVector<APInt> DstBits;
5496           BitVector DstUndefs;
5497           BuildVectorSDNode::recastRawBits(IsLE, BVVT.getScalarSizeInBits(),
5498                                            DstBits, RawBits, DstUndefs,
5499                                            BitVector(RawBits.size(), false));
5500           EVT BVEltVT = BV1->getOperand(0).getValueType();
5501           unsigned BVEltBits = BVEltVT.getSizeInBits();
5502           SmallVector<SDValue> Ops(DstBits.size(), getUNDEF(BVEltVT));
5503           for (unsigned I = 0, E = DstBits.size(); I != E; ++I) {
5504             if (DstUndefs[I])
5505               continue;
5506             Ops[I] = getConstant(DstBits[I].sextOrSelf(BVEltBits), DL, BVEltVT);
5507           }
5508           return getBitcast(VT, getBuildVector(BVVT, DL, Ops));
5509         }
5510       }
5511     }
5512   }
5513 
5514   // Fold (mul step_vector(C0), C1) to (step_vector(C0 * C1)).
5515   //      (shl step_vector(C0), C1) -> (step_vector(C0 << C1))
5516   if ((Opcode == ISD::MUL || Opcode == ISD::SHL) &&
5517       Ops[0].getOpcode() == ISD::STEP_VECTOR) {
5518     APInt RHSVal;
5519     if (ISD::isConstantSplatVector(Ops[1].getNode(), RHSVal)) {
5520       APInt NewStep = Opcode == ISD::MUL
5521                           ? Ops[0].getConstantOperandAPInt(0) * RHSVal
5522                           : Ops[0].getConstantOperandAPInt(0) << RHSVal;
5523       return getStepVector(DL, VT, NewStep);
5524     }
5525   }
5526 
5527   auto IsScalarOrSameVectorSize = [NumElts](const SDValue &Op) {
5528     return !Op.getValueType().isVector() ||
5529            Op.getValueType().getVectorElementCount() == NumElts;
5530   };
5531 
5532   auto IsBuildVectorSplatVectorOrUndef = [](const SDValue &Op) {
5533     return Op.isUndef() || Op.getOpcode() == ISD::CONDCODE ||
5534            Op.getOpcode() == ISD::BUILD_VECTOR ||
5535            Op.getOpcode() == ISD::SPLAT_VECTOR;
5536   };
5537 
5538   // All operands must be vector types with the same number of elements as
5539   // the result type and must be either UNDEF or a build/splat vector
5540   // or UNDEF scalars.
5541   if (!llvm::all_of(Ops, IsBuildVectorSplatVectorOrUndef) ||
5542       !llvm::all_of(Ops, IsScalarOrSameVectorSize))
5543     return SDValue();
5544 
5545   // If we are comparing vectors, then the result needs to be a i1 boolean
5546   // that is then sign-extended back to the legal result type.
5547   EVT SVT = (Opcode == ISD::SETCC ? MVT::i1 : VT.getScalarType());
5548 
5549   // Find legal integer scalar type for constant promotion and
5550   // ensure that its scalar size is at least as large as source.
5551   EVT LegalSVT = VT.getScalarType();
5552   if (NewNodesMustHaveLegalTypes && LegalSVT.isInteger()) {
5553     LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT);
5554     if (LegalSVT.bitsLT(VT.getScalarType()))
5555       return SDValue();
5556   }
5557 
5558   // For scalable vector types we know we're dealing with SPLAT_VECTORs. We
5559   // only have one operand to check. For fixed-length vector types we may have
5560   // a combination of BUILD_VECTOR and SPLAT_VECTOR.
5561   unsigned NumVectorElts = NumElts.isScalable() ? 1 : NumElts.getFixedValue();
5562 
5563   // Constant fold each scalar lane separately.
5564   SmallVector<SDValue, 4> ScalarResults;
5565   for (unsigned I = 0; I != NumVectorElts; I++) {
5566     SmallVector<SDValue, 4> ScalarOps;
5567     for (SDValue Op : Ops) {
5568       EVT InSVT = Op.getValueType().getScalarType();
5569       if (Op.getOpcode() != ISD::BUILD_VECTOR &&
5570           Op.getOpcode() != ISD::SPLAT_VECTOR) {
5571         if (Op.isUndef())
5572           ScalarOps.push_back(getUNDEF(InSVT));
5573         else
5574           ScalarOps.push_back(Op);
5575         continue;
5576       }
5577 
5578       SDValue ScalarOp =
5579           Op.getOperand(Op.getOpcode() == ISD::SPLAT_VECTOR ? 0 : I);
5580       EVT ScalarVT = ScalarOp.getValueType();
5581 
5582       // Build vector (integer) scalar operands may need implicit
5583       // truncation - do this before constant folding.
5584       if (ScalarVT.isInteger() && ScalarVT.bitsGT(InSVT))
5585         ScalarOp = getNode(ISD::TRUNCATE, DL, InSVT, ScalarOp);
5586 
5587       ScalarOps.push_back(ScalarOp);
5588     }
5589 
5590     // Constant fold the scalar operands.
5591     SDValue ScalarResult = getNode(Opcode, DL, SVT, ScalarOps);
5592 
5593     // Legalize the (integer) scalar constant if necessary.
5594     if (LegalSVT != SVT)
5595       ScalarResult = getNode(ISD::SIGN_EXTEND, DL, LegalSVT, ScalarResult);
5596 
5597     // Scalar folding only succeeded if the result is a constant or UNDEF.
5598     if (!ScalarResult.isUndef() && ScalarResult.getOpcode() != ISD::Constant &&
5599         ScalarResult.getOpcode() != ISD::ConstantFP)
5600       return SDValue();
5601     ScalarResults.push_back(ScalarResult);
5602   }
5603 
5604   SDValue V = NumElts.isScalable() ? getSplatVector(VT, DL, ScalarResults[0])
5605                                    : getBuildVector(VT, DL, ScalarResults);
5606   NewSDValueDbgMsg(V, "New node fold constant vector: ", this);
5607   return V;
5608 }
5609 
5610 SDValue SelectionDAG::foldConstantFPMath(unsigned Opcode, const SDLoc &DL,
5611                                          EVT VT, SDValue N1, SDValue N2) {
5612   // TODO: We don't do any constant folding for strict FP opcodes here, but we
5613   //       should. That will require dealing with a potentially non-default
5614   //       rounding mode, checking the "opStatus" return value from the APFloat
5615   //       math calculations, and possibly other variations.
5616   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1, /*AllowUndefs*/ false);
5617   ConstantFPSDNode *N2CFP = isConstOrConstSplatFP(N2, /*AllowUndefs*/ false);
5618   if (N1CFP && N2CFP) {
5619     APFloat C1 = N1CFP->getValueAPF(); // make copy
5620     const APFloat &C2 = N2CFP->getValueAPF();
5621     switch (Opcode) {
5622     case ISD::FADD:
5623       C1.add(C2, APFloat::rmNearestTiesToEven);
5624       return getConstantFP(C1, DL, VT);
5625     case ISD::FSUB:
5626       C1.subtract(C2, APFloat::rmNearestTiesToEven);
5627       return getConstantFP(C1, DL, VT);
5628     case ISD::FMUL:
5629       C1.multiply(C2, APFloat::rmNearestTiesToEven);
5630       return getConstantFP(C1, DL, VT);
5631     case ISD::FDIV:
5632       C1.divide(C2, APFloat::rmNearestTiesToEven);
5633       return getConstantFP(C1, DL, VT);
5634     case ISD::FREM:
5635       C1.mod(C2);
5636       return getConstantFP(C1, DL, VT);
5637     case ISD::FCOPYSIGN:
5638       C1.copySign(C2);
5639       return getConstantFP(C1, DL, VT);
5640     case ISD::FMINNUM:
5641       return getConstantFP(minnum(C1, C2), DL, VT);
5642     case ISD::FMAXNUM:
5643       return getConstantFP(maxnum(C1, C2), DL, VT);
5644     case ISD::FMINIMUM:
5645       return getConstantFP(minimum(C1, C2), DL, VT);
5646     case ISD::FMAXIMUM:
5647       return getConstantFP(maximum(C1, C2), DL, VT);
5648     default: break;
5649     }
5650   }
5651   if (N1CFP && Opcode == ISD::FP_ROUND) {
5652     APFloat C1 = N1CFP->getValueAPF();    // make copy
5653     bool Unused;
5654     // This can return overflow, underflow, or inexact; we don't care.
5655     // FIXME need to be more flexible about rounding mode.
5656     (void) C1.convert(EVTToAPFloatSemantics(VT), APFloat::rmNearestTiesToEven,
5657                       &Unused);
5658     return getConstantFP(C1, DL, VT);
5659   }
5660 
5661   switch (Opcode) {
5662   case ISD::FSUB:
5663     // -0.0 - undef --> undef (consistent with "fneg undef")
5664     if (ConstantFPSDNode *N1C = isConstOrConstSplatFP(N1, /*AllowUndefs*/ true))
5665       if (N1C && N1C->getValueAPF().isNegZero() && N2.isUndef())
5666         return getUNDEF(VT);
5667     LLVM_FALLTHROUGH;
5668 
5669   case ISD::FADD:
5670   case ISD::FMUL:
5671   case ISD::FDIV:
5672   case ISD::FREM:
5673     // If both operands are undef, the result is undef. If 1 operand is undef,
5674     // the result is NaN. This should match the behavior of the IR optimizer.
5675     if (N1.isUndef() && N2.isUndef())
5676       return getUNDEF(VT);
5677     if (N1.isUndef() || N2.isUndef())
5678       return getConstantFP(APFloat::getNaN(EVTToAPFloatSemantics(VT)), DL, VT);
5679   }
5680   return SDValue();
5681 }
5682 
5683 SDValue SelectionDAG::getAssertAlign(const SDLoc &DL, SDValue Val, Align A) {
5684   assert(Val.getValueType().isInteger() && "Invalid AssertAlign!");
5685 
5686   // There's no need to assert on a byte-aligned pointer. All pointers are at
5687   // least byte aligned.
5688   if (A == Align(1))
5689     return Val;
5690 
5691   FoldingSetNodeID ID;
5692   AddNodeIDNode(ID, ISD::AssertAlign, getVTList(Val.getValueType()), {Val});
5693   ID.AddInteger(A.value());
5694 
5695   void *IP = nullptr;
5696   if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
5697     return SDValue(E, 0);
5698 
5699   auto *N = newSDNode<AssertAlignSDNode>(DL.getIROrder(), DL.getDebugLoc(),
5700                                          Val.getValueType(), A);
5701   createOperands(N, {Val});
5702 
5703   CSEMap.InsertNode(N, IP);
5704   InsertNode(N);
5705 
5706   SDValue V(N, 0);
5707   NewSDValueDbgMsg(V, "Creating new node: ", this);
5708   return V;
5709 }
5710 
5711 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
5712                               SDValue N1, SDValue N2) {
5713   SDNodeFlags Flags;
5714   if (Inserter)
5715     Flags = Inserter->getFlags();
5716   return getNode(Opcode, DL, VT, N1, N2, Flags);
5717 }
5718 
5719 void SelectionDAG::canonicalizeCommutativeBinop(unsigned Opcode, SDValue &N1,
5720                                                 SDValue &N2) const {
5721   if (!TLI->isCommutativeBinOp(Opcode))
5722     return;
5723 
5724   // Canonicalize:
5725   //   binop(const, nonconst) -> binop(nonconst, const)
5726   bool IsN1C = isConstantIntBuildVectorOrConstantInt(N1);
5727   bool IsN2C = isConstantIntBuildVectorOrConstantInt(N2);
5728   bool IsN1CFP = isConstantFPBuildVectorOrConstantFP(N1);
5729   bool IsN2CFP = isConstantFPBuildVectorOrConstantFP(N2);
5730   if ((IsN1C && !IsN2C) || (IsN1CFP && !IsN2CFP))
5731     std::swap(N1, N2);
5732 
5733   // Canonicalize:
5734   //  binop(splat(x), step_vector) -> binop(step_vector, splat(x))
5735   else if (N1.getOpcode() == ISD::SPLAT_VECTOR &&
5736            N2.getOpcode() == ISD::STEP_VECTOR)
5737     std::swap(N1, N2);
5738 }
5739 
5740 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
5741                               SDValue N1, SDValue N2, const SDNodeFlags Flags) {
5742   assert(N1.getOpcode() != ISD::DELETED_NODE &&
5743          N2.getOpcode() != ISD::DELETED_NODE &&
5744          "Operand is DELETED_NODE!");
5745 
5746   canonicalizeCommutativeBinop(Opcode, N1, N2);
5747 
5748   auto *N1C = dyn_cast<ConstantSDNode>(N1);
5749   auto *N2C = dyn_cast<ConstantSDNode>(N2);
5750 
5751   // Don't allow undefs in vector splats - we might be returning N2 when folding
5752   // to zero etc.
5753   ConstantSDNode *N2CV =
5754       isConstOrConstSplat(N2, /*AllowUndefs*/ false, /*AllowTruncation*/ true);
5755 
5756   switch (Opcode) {
5757   default: break;
5758   case ISD::TokenFactor:
5759     assert(VT == MVT::Other && N1.getValueType() == MVT::Other &&
5760            N2.getValueType() == MVT::Other && "Invalid token factor!");
5761     // Fold trivial token factors.
5762     if (N1.getOpcode() == ISD::EntryToken) return N2;
5763     if (N2.getOpcode() == ISD::EntryToken) return N1;
5764     if (N1 == N2) return N1;
5765     break;
5766   case ISD::BUILD_VECTOR: {
5767     // Attempt to simplify BUILD_VECTOR.
5768     SDValue Ops[] = {N1, N2};
5769     if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
5770       return V;
5771     break;
5772   }
5773   case ISD::CONCAT_VECTORS: {
5774     SDValue Ops[] = {N1, N2};
5775     if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this))
5776       return V;
5777     break;
5778   }
5779   case ISD::AND:
5780     assert(VT.isInteger() && "This operator does not apply to FP types!");
5781     assert(N1.getValueType() == N2.getValueType() &&
5782            N1.getValueType() == VT && "Binary operator types must match!");
5783     // (X & 0) -> 0.  This commonly occurs when legalizing i64 values, so it's
5784     // worth handling here.
5785     if (N2CV && N2CV->isZero())
5786       return N2;
5787     if (N2CV && N2CV->isAllOnes()) // X & -1 -> X
5788       return N1;
5789     break;
5790   case ISD::OR:
5791   case ISD::XOR:
5792   case ISD::ADD:
5793   case ISD::SUB:
5794     assert(VT.isInteger() && "This operator does not apply to FP types!");
5795     assert(N1.getValueType() == N2.getValueType() &&
5796            N1.getValueType() == VT && "Binary operator types must match!");
5797     // (X ^|+- 0) -> X.  This commonly occurs when legalizing i64 values, so
5798     // it's worth handling here.
5799     if (N2CV && N2CV->isZero())
5800       return N1;
5801     if ((Opcode == ISD::ADD || Opcode == ISD::SUB) && VT.isVector() &&
5802         VT.getVectorElementType() == MVT::i1)
5803       return getNode(ISD::XOR, DL, VT, N1, N2);
5804     break;
5805   case ISD::MUL:
5806     assert(VT.isInteger() && "This operator does not apply to FP types!");
5807     assert(N1.getValueType() == N2.getValueType() &&
5808            N1.getValueType() == VT && "Binary operator types must match!");
5809     if (VT.isVector() && VT.getVectorElementType() == MVT::i1)
5810       return getNode(ISD::AND, DL, VT, N1, N2);
5811     if (N2C && (N1.getOpcode() == ISD::VSCALE) && Flags.hasNoSignedWrap()) {
5812       const APInt &MulImm = N1->getConstantOperandAPInt(0);
5813       const APInt &N2CImm = N2C->getAPIntValue();
5814       return getVScale(DL, VT, MulImm * N2CImm);
5815     }
5816     break;
5817   case ISD::UDIV:
5818   case ISD::UREM:
5819   case ISD::MULHU:
5820   case ISD::MULHS:
5821   case ISD::SDIV:
5822   case ISD::SREM:
5823   case ISD::SADDSAT:
5824   case ISD::SSUBSAT:
5825   case ISD::UADDSAT:
5826   case ISD::USUBSAT:
5827     assert(VT.isInteger() && "This operator does not apply to FP types!");
5828     assert(N1.getValueType() == N2.getValueType() &&
5829            N1.getValueType() == VT && "Binary operator types must match!");
5830     if (VT.isVector() && VT.getVectorElementType() == MVT::i1) {
5831       // fold (add_sat x, y) -> (or x, y) for bool types.
5832       if (Opcode == ISD::SADDSAT || Opcode == ISD::UADDSAT)
5833         return getNode(ISD::OR, DL, VT, N1, N2);
5834       // fold (sub_sat x, y) -> (and x, ~y) for bool types.
5835       if (Opcode == ISD::SSUBSAT || Opcode == ISD::USUBSAT)
5836         return getNode(ISD::AND, DL, VT, N1, getNOT(DL, N2, VT));
5837     }
5838     break;
5839   case ISD::SMIN:
5840   case ISD::UMAX:
5841     assert(VT.isInteger() && "This operator does not apply to FP types!");
5842     assert(N1.getValueType() == N2.getValueType() &&
5843            N1.getValueType() == VT && "Binary operator types must match!");
5844     if (VT.isVector() && VT.getVectorElementType() == MVT::i1)
5845       return getNode(ISD::OR, DL, VT, N1, N2);
5846     break;
5847   case ISD::SMAX:
5848   case ISD::UMIN:
5849     assert(VT.isInteger() && "This operator does not apply to FP types!");
5850     assert(N1.getValueType() == N2.getValueType() &&
5851            N1.getValueType() == VT && "Binary operator types must match!");
5852     if (VT.isVector() && VT.getVectorElementType() == MVT::i1)
5853       return getNode(ISD::AND, DL, VT, N1, N2);
5854     break;
5855   case ISD::FADD:
5856   case ISD::FSUB:
5857   case ISD::FMUL:
5858   case ISD::FDIV:
5859   case ISD::FREM:
5860     assert(VT.isFloatingPoint() && "This operator only applies to FP types!");
5861     assert(N1.getValueType() == N2.getValueType() &&
5862            N1.getValueType() == VT && "Binary operator types must match!");
5863     if (SDValue V = simplifyFPBinop(Opcode, N1, N2, Flags))
5864       return V;
5865     break;
5866   case ISD::FCOPYSIGN:   // N1 and result must match.  N1/N2 need not match.
5867     assert(N1.getValueType() == VT &&
5868            N1.getValueType().isFloatingPoint() &&
5869            N2.getValueType().isFloatingPoint() &&
5870            "Invalid FCOPYSIGN!");
5871     break;
5872   case ISD::SHL:
5873     if (N2C && (N1.getOpcode() == ISD::VSCALE) && Flags.hasNoSignedWrap()) {
5874       const APInt &MulImm = N1->getConstantOperandAPInt(0);
5875       const APInt &ShiftImm = N2C->getAPIntValue();
5876       return getVScale(DL, VT, MulImm << ShiftImm);
5877     }
5878     LLVM_FALLTHROUGH;
5879   case ISD::SRA:
5880   case ISD::SRL:
5881     if (SDValue V = simplifyShift(N1, N2))
5882       return V;
5883     LLVM_FALLTHROUGH;
5884   case ISD::ROTL:
5885   case ISD::ROTR:
5886     assert(VT == N1.getValueType() &&
5887            "Shift operators return type must be the same as their first arg");
5888     assert(VT.isInteger() && N2.getValueType().isInteger() &&
5889            "Shifts only work on integers");
5890     assert((!VT.isVector() || VT == N2.getValueType()) &&
5891            "Vector shift amounts must be in the same as their first arg");
5892     // Verify that the shift amount VT is big enough to hold valid shift
5893     // amounts.  This catches things like trying to shift an i1024 value by an
5894     // i8, which is easy to fall into in generic code that uses
5895     // TLI.getShiftAmount().
5896     assert(N2.getValueType().getScalarSizeInBits() >=
5897                Log2_32_Ceil(VT.getScalarSizeInBits()) &&
5898            "Invalid use of small shift amount with oversized value!");
5899 
5900     // Always fold shifts of i1 values so the code generator doesn't need to
5901     // handle them.  Since we know the size of the shift has to be less than the
5902     // size of the value, the shift/rotate count is guaranteed to be zero.
5903     if (VT == MVT::i1)
5904       return N1;
5905     if (N2CV && N2CV->isZero())
5906       return N1;
5907     break;
5908   case ISD::FP_ROUND:
5909     assert(VT.isFloatingPoint() &&
5910            N1.getValueType().isFloatingPoint() &&
5911            VT.bitsLE(N1.getValueType()) &&
5912            N2C && (N2C->getZExtValue() == 0 || N2C->getZExtValue() == 1) &&
5913            "Invalid FP_ROUND!");
5914     if (N1.getValueType() == VT) return N1;  // noop conversion.
5915     break;
5916   case ISD::AssertSext:
5917   case ISD::AssertZext: {
5918     EVT EVT = cast<VTSDNode>(N2)->getVT();
5919     assert(VT == N1.getValueType() && "Not an inreg extend!");
5920     assert(VT.isInteger() && EVT.isInteger() &&
5921            "Cannot *_EXTEND_INREG FP types");
5922     assert(!EVT.isVector() &&
5923            "AssertSExt/AssertZExt type should be the vector element type "
5924            "rather than the vector type!");
5925     assert(EVT.bitsLE(VT.getScalarType()) && "Not extending!");
5926     if (VT.getScalarType() == EVT) return N1; // noop assertion.
5927     break;
5928   }
5929   case ISD::SIGN_EXTEND_INREG: {
5930     EVT EVT = cast<VTSDNode>(N2)->getVT();
5931     assert(VT == N1.getValueType() && "Not an inreg extend!");
5932     assert(VT.isInteger() && EVT.isInteger() &&
5933            "Cannot *_EXTEND_INREG FP types");
5934     assert(EVT.isVector() == VT.isVector() &&
5935            "SIGN_EXTEND_INREG type should be vector iff the operand "
5936            "type is vector!");
5937     assert((!EVT.isVector() ||
5938             EVT.getVectorElementCount() == VT.getVectorElementCount()) &&
5939            "Vector element counts must match in SIGN_EXTEND_INREG");
5940     assert(EVT.bitsLE(VT) && "Not extending!");
5941     if (EVT == VT) return N1;  // Not actually extending
5942 
5943     auto SignExtendInReg = [&](APInt Val, llvm::EVT ConstantVT) {
5944       unsigned FromBits = EVT.getScalarSizeInBits();
5945       Val <<= Val.getBitWidth() - FromBits;
5946       Val.ashrInPlace(Val.getBitWidth() - FromBits);
5947       return getConstant(Val, DL, ConstantVT);
5948     };
5949 
5950     if (N1C) {
5951       const APInt &Val = N1C->getAPIntValue();
5952       return SignExtendInReg(Val, VT);
5953     }
5954 
5955     if (ISD::isBuildVectorOfConstantSDNodes(N1.getNode())) {
5956       SmallVector<SDValue, 8> Ops;
5957       llvm::EVT OpVT = N1.getOperand(0).getValueType();
5958       for (int i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
5959         SDValue Op = N1.getOperand(i);
5960         if (Op.isUndef()) {
5961           Ops.push_back(getUNDEF(OpVT));
5962           continue;
5963         }
5964         ConstantSDNode *C = cast<ConstantSDNode>(Op);
5965         APInt Val = C->getAPIntValue();
5966         Ops.push_back(SignExtendInReg(Val, OpVT));
5967       }
5968       return getBuildVector(VT, DL, Ops);
5969     }
5970     break;
5971   }
5972   case ISD::FP_TO_SINT_SAT:
5973   case ISD::FP_TO_UINT_SAT: {
5974     assert(VT.isInteger() && cast<VTSDNode>(N2)->getVT().isInteger() &&
5975            N1.getValueType().isFloatingPoint() && "Invalid FP_TO_*INT_SAT");
5976     assert(N1.getValueType().isVector() == VT.isVector() &&
5977            "FP_TO_*INT_SAT type should be vector iff the operand type is "
5978            "vector!");
5979     assert((!VT.isVector() || VT.getVectorNumElements() ==
5980                                   N1.getValueType().getVectorNumElements()) &&
5981            "Vector element counts must match in FP_TO_*INT_SAT");
5982     assert(!cast<VTSDNode>(N2)->getVT().isVector() &&
5983            "Type to saturate to must be a scalar.");
5984     assert(cast<VTSDNode>(N2)->getVT().bitsLE(VT.getScalarType()) &&
5985            "Not extending!");
5986     break;
5987   }
5988   case ISD::EXTRACT_VECTOR_ELT:
5989     assert(VT.getSizeInBits() >= N1.getValueType().getScalarSizeInBits() &&
5990            "The result of EXTRACT_VECTOR_ELT must be at least as wide as the \
5991              element type of the vector.");
5992 
5993     // Extract from an undefined value or using an undefined index is undefined.
5994     if (N1.isUndef() || N2.isUndef())
5995       return getUNDEF(VT);
5996 
5997     // EXTRACT_VECTOR_ELT of out-of-bounds element is an UNDEF for fixed length
5998     // vectors. For scalable vectors we will provide appropriate support for
5999     // dealing with arbitrary indices.
6000     if (N2C && N1.getValueType().isFixedLengthVector() &&
6001         N2C->getAPIntValue().uge(N1.getValueType().getVectorNumElements()))
6002       return getUNDEF(VT);
6003 
6004     // EXTRACT_VECTOR_ELT of CONCAT_VECTORS is often formed while lowering is
6005     // expanding copies of large vectors from registers. This only works for
6006     // fixed length vectors, since we need to know the exact number of
6007     // elements.
6008     if (N2C && N1.getOperand(0).getValueType().isFixedLengthVector() &&
6009         N1.getOpcode() == ISD::CONCAT_VECTORS && N1.getNumOperands() > 0) {
6010       unsigned Factor =
6011         N1.getOperand(0).getValueType().getVectorNumElements();
6012       return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
6013                      N1.getOperand(N2C->getZExtValue() / Factor),
6014                      getVectorIdxConstant(N2C->getZExtValue() % Factor, DL));
6015     }
6016 
6017     // EXTRACT_VECTOR_ELT of BUILD_VECTOR or SPLAT_VECTOR is often formed while
6018     // lowering is expanding large vector constants.
6019     if (N2C && (N1.getOpcode() == ISD::BUILD_VECTOR ||
6020                 N1.getOpcode() == ISD::SPLAT_VECTOR)) {
6021       assert((N1.getOpcode() != ISD::BUILD_VECTOR ||
6022               N1.getValueType().isFixedLengthVector()) &&
6023              "BUILD_VECTOR used for scalable vectors");
6024       unsigned Index =
6025           N1.getOpcode() == ISD::BUILD_VECTOR ? N2C->getZExtValue() : 0;
6026       SDValue Elt = N1.getOperand(Index);
6027 
6028       if (VT != Elt.getValueType())
6029         // If the vector element type is not legal, the BUILD_VECTOR operands
6030         // are promoted and implicitly truncated, and the result implicitly
6031         // extended. Make that explicit here.
6032         Elt = getAnyExtOrTrunc(Elt, DL, VT);
6033 
6034       return Elt;
6035     }
6036 
6037     // EXTRACT_VECTOR_ELT of INSERT_VECTOR_ELT is often formed when vector
6038     // operations are lowered to scalars.
6039     if (N1.getOpcode() == ISD::INSERT_VECTOR_ELT) {
6040       // If the indices are the same, return the inserted element else
6041       // if the indices are known different, extract the element from
6042       // the original vector.
6043       SDValue N1Op2 = N1.getOperand(2);
6044       ConstantSDNode *N1Op2C = dyn_cast<ConstantSDNode>(N1Op2);
6045 
6046       if (N1Op2C && N2C) {
6047         if (N1Op2C->getZExtValue() == N2C->getZExtValue()) {
6048           if (VT == N1.getOperand(1).getValueType())
6049             return N1.getOperand(1);
6050           return getSExtOrTrunc(N1.getOperand(1), DL, VT);
6051         }
6052         return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0), N2);
6053       }
6054     }
6055 
6056     // EXTRACT_VECTOR_ELT of v1iX EXTRACT_SUBVECTOR could be formed
6057     // when vector types are scalarized and v1iX is legal.
6058     // vextract (v1iX extract_subvector(vNiX, Idx)) -> vextract(vNiX,Idx).
6059     // Here we are completely ignoring the extract element index (N2),
6060     // which is fine for fixed width vectors, since any index other than 0
6061     // is undefined anyway. However, this cannot be ignored for scalable
6062     // vectors - in theory we could support this, but we don't want to do this
6063     // without a profitability check.
6064     if (N1.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
6065         N1.getValueType().isFixedLengthVector() &&
6066         N1.getValueType().getVectorNumElements() == 1) {
6067       return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0),
6068                      N1.getOperand(1));
6069     }
6070     break;
6071   case ISD::EXTRACT_ELEMENT:
6072     assert(N2C && (unsigned)N2C->getZExtValue() < 2 && "Bad EXTRACT_ELEMENT!");
6073     assert(!N1.getValueType().isVector() && !VT.isVector() &&
6074            (N1.getValueType().isInteger() == VT.isInteger()) &&
6075            N1.getValueType() != VT &&
6076            "Wrong types for EXTRACT_ELEMENT!");
6077 
6078     // EXTRACT_ELEMENT of BUILD_PAIR is often formed while legalize is expanding
6079     // 64-bit integers into 32-bit parts.  Instead of building the extract of
6080     // the BUILD_PAIR, only to have legalize rip it apart, just do it now.
6081     if (N1.getOpcode() == ISD::BUILD_PAIR)
6082       return N1.getOperand(N2C->getZExtValue());
6083 
6084     // EXTRACT_ELEMENT of a constant int is also very common.
6085     if (N1C) {
6086       unsigned ElementSize = VT.getSizeInBits();
6087       unsigned Shift = ElementSize * N2C->getZExtValue();
6088       const APInt &Val = N1C->getAPIntValue();
6089       return getConstant(Val.extractBits(ElementSize, Shift), DL, VT);
6090     }
6091     break;
6092   case ISD::EXTRACT_SUBVECTOR: {
6093     EVT N1VT = N1.getValueType();
6094     assert(VT.isVector() && N1VT.isVector() &&
6095            "Extract subvector VTs must be vectors!");
6096     assert(VT.getVectorElementType() == N1VT.getVectorElementType() &&
6097            "Extract subvector VTs must have the same element type!");
6098     assert((VT.isFixedLengthVector() || N1VT.isScalableVector()) &&
6099            "Cannot extract a scalable vector from a fixed length vector!");
6100     assert((VT.isScalableVector() != N1VT.isScalableVector() ||
6101             VT.getVectorMinNumElements() <= N1VT.getVectorMinNumElements()) &&
6102            "Extract subvector must be from larger vector to smaller vector!");
6103     assert(N2C && "Extract subvector index must be a constant");
6104     assert((VT.isScalableVector() != N1VT.isScalableVector() ||
6105             (VT.getVectorMinNumElements() + N2C->getZExtValue()) <=
6106                 N1VT.getVectorMinNumElements()) &&
6107            "Extract subvector overflow!");
6108     assert(N2C->getAPIntValue().getBitWidth() ==
6109                TLI->getVectorIdxTy(getDataLayout()).getFixedSizeInBits() &&
6110            "Constant index for EXTRACT_SUBVECTOR has an invalid size");
6111 
6112     // Trivial extraction.
6113     if (VT == N1VT)
6114       return N1;
6115 
6116     // EXTRACT_SUBVECTOR of an UNDEF is an UNDEF.
6117     if (N1.isUndef())
6118       return getUNDEF(VT);
6119 
6120     // EXTRACT_SUBVECTOR of CONCAT_VECTOR can be simplified if the pieces of
6121     // the concat have the same type as the extract.
6122     if (N1.getOpcode() == ISD::CONCAT_VECTORS && N1.getNumOperands() > 0 &&
6123         VT == N1.getOperand(0).getValueType()) {
6124       unsigned Factor = VT.getVectorMinNumElements();
6125       return N1.getOperand(N2C->getZExtValue() / Factor);
6126     }
6127 
6128     // EXTRACT_SUBVECTOR of INSERT_SUBVECTOR is often created
6129     // during shuffle legalization.
6130     if (N1.getOpcode() == ISD::INSERT_SUBVECTOR && N2 == N1.getOperand(2) &&
6131         VT == N1.getOperand(1).getValueType())
6132       return N1.getOperand(1);
6133     break;
6134   }
6135   }
6136 
6137   // Perform trivial constant folding.
6138   if (SDValue SV = FoldConstantArithmetic(Opcode, DL, VT, {N1, N2}))
6139     return SV;
6140 
6141   // Canonicalize an UNDEF to the RHS, even over a constant.
6142   if (N1.isUndef()) {
6143     if (TLI->isCommutativeBinOp(Opcode)) {
6144       std::swap(N1, N2);
6145     } else {
6146       switch (Opcode) {
6147       case ISD::SIGN_EXTEND_INREG:
6148       case ISD::SUB:
6149         return getUNDEF(VT);     // fold op(undef, arg2) -> undef
6150       case ISD::UDIV:
6151       case ISD::SDIV:
6152       case ISD::UREM:
6153       case ISD::SREM:
6154       case ISD::SSUBSAT:
6155       case ISD::USUBSAT:
6156         return getConstant(0, DL, VT);    // fold op(undef, arg2) -> 0
6157       }
6158     }
6159   }
6160 
6161   // Fold a bunch of operators when the RHS is undef.
6162   if (N2.isUndef()) {
6163     switch (Opcode) {
6164     case ISD::XOR:
6165       if (N1.isUndef())
6166         // Handle undef ^ undef -> 0 special case. This is a common
6167         // idiom (misuse).
6168         return getConstant(0, DL, VT);
6169       LLVM_FALLTHROUGH;
6170     case ISD::ADD:
6171     case ISD::SUB:
6172     case ISD::UDIV:
6173     case ISD::SDIV:
6174     case ISD::UREM:
6175     case ISD::SREM:
6176       return getUNDEF(VT);       // fold op(arg1, undef) -> undef
6177     case ISD::MUL:
6178     case ISD::AND:
6179     case ISD::SSUBSAT:
6180     case ISD::USUBSAT:
6181       return getConstant(0, DL, VT);  // fold op(arg1, undef) -> 0
6182     case ISD::OR:
6183     case ISD::SADDSAT:
6184     case ISD::UADDSAT:
6185       return getAllOnesConstant(DL, VT);
6186     }
6187   }
6188 
6189   // Memoize this node if possible.
6190   SDNode *N;
6191   SDVTList VTs = getVTList(VT);
6192   SDValue Ops[] = {N1, N2};
6193   if (VT != MVT::Glue) {
6194     FoldingSetNodeID ID;
6195     AddNodeIDNode(ID, Opcode, VTs, Ops);
6196     void *IP = nullptr;
6197     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
6198       E->intersectFlagsWith(Flags);
6199       return SDValue(E, 0);
6200     }
6201 
6202     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
6203     N->setFlags(Flags);
6204     createOperands(N, Ops);
6205     CSEMap.InsertNode(N, IP);
6206   } else {
6207     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
6208     createOperands(N, Ops);
6209   }
6210 
6211   InsertNode(N);
6212   SDValue V = SDValue(N, 0);
6213   NewSDValueDbgMsg(V, "Creating new node: ", this);
6214   return V;
6215 }
6216 
6217 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
6218                               SDValue N1, SDValue N2, SDValue N3) {
6219   SDNodeFlags Flags;
6220   if (Inserter)
6221     Flags = Inserter->getFlags();
6222   return getNode(Opcode, DL, VT, N1, N2, N3, Flags);
6223 }
6224 
6225 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
6226                               SDValue N1, SDValue N2, SDValue N3,
6227                               const SDNodeFlags Flags) {
6228   assert(N1.getOpcode() != ISD::DELETED_NODE &&
6229          N2.getOpcode() != ISD::DELETED_NODE &&
6230          N3.getOpcode() != ISD::DELETED_NODE &&
6231          "Operand is DELETED_NODE!");
6232   // Perform various simplifications.
6233   switch (Opcode) {
6234   case ISD::FMA: {
6235     assert(VT.isFloatingPoint() && "This operator only applies to FP types!");
6236     assert(N1.getValueType() == VT && N2.getValueType() == VT &&
6237            N3.getValueType() == VT && "FMA types must match!");
6238     ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6239     ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2);
6240     ConstantFPSDNode *N3CFP = dyn_cast<ConstantFPSDNode>(N3);
6241     if (N1CFP && N2CFP && N3CFP) {
6242       APFloat  V1 = N1CFP->getValueAPF();
6243       const APFloat &V2 = N2CFP->getValueAPF();
6244       const APFloat &V3 = N3CFP->getValueAPF();
6245       V1.fusedMultiplyAdd(V2, V3, APFloat::rmNearestTiesToEven);
6246       return getConstantFP(V1, DL, VT);
6247     }
6248     break;
6249   }
6250   case ISD::BUILD_VECTOR: {
6251     // Attempt to simplify BUILD_VECTOR.
6252     SDValue Ops[] = {N1, N2, N3};
6253     if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
6254       return V;
6255     break;
6256   }
6257   case ISD::CONCAT_VECTORS: {
6258     SDValue Ops[] = {N1, N2, N3};
6259     if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this))
6260       return V;
6261     break;
6262   }
6263   case ISD::SETCC: {
6264     assert(VT.isInteger() && "SETCC result type must be an integer!");
6265     assert(N1.getValueType() == N2.getValueType() &&
6266            "SETCC operands must have the same type!");
6267     assert(VT.isVector() == N1.getValueType().isVector() &&
6268            "SETCC type should be vector iff the operand type is vector!");
6269     assert((!VT.isVector() || VT.getVectorElementCount() ==
6270                                   N1.getValueType().getVectorElementCount()) &&
6271            "SETCC vector element counts must match!");
6272     // Use FoldSetCC to simplify SETCC's.
6273     if (SDValue V = FoldSetCC(VT, N1, N2, cast<CondCodeSDNode>(N3)->get(), DL))
6274       return V;
6275     // Vector constant folding.
6276     SDValue Ops[] = {N1, N2, N3};
6277     if (SDValue V = FoldConstantArithmetic(Opcode, DL, VT, Ops)) {
6278       NewSDValueDbgMsg(V, "New node vector constant folding: ", this);
6279       return V;
6280     }
6281     break;
6282   }
6283   case ISD::SELECT:
6284   case ISD::VSELECT:
6285     if (SDValue V = simplifySelect(N1, N2, N3))
6286       return V;
6287     break;
6288   case ISD::VECTOR_SHUFFLE:
6289     llvm_unreachable("should use getVectorShuffle constructor!");
6290   case ISD::VECTOR_SPLICE: {
6291     if (cast<ConstantSDNode>(N3)->isNullValue())
6292       return N1;
6293     break;
6294   }
6295   case ISD::INSERT_VECTOR_ELT: {
6296     ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3);
6297     // INSERT_VECTOR_ELT into out-of-bounds element is an UNDEF, except
6298     // for scalable vectors where we will generate appropriate code to
6299     // deal with out-of-bounds cases correctly.
6300     if (N3C && N1.getValueType().isFixedLengthVector() &&
6301         N3C->getZExtValue() >= N1.getValueType().getVectorNumElements())
6302       return getUNDEF(VT);
6303 
6304     // Undefined index can be assumed out-of-bounds, so that's UNDEF too.
6305     if (N3.isUndef())
6306       return getUNDEF(VT);
6307 
6308     // If the inserted element is an UNDEF, just use the input vector.
6309     if (N2.isUndef())
6310       return N1;
6311 
6312     break;
6313   }
6314   case ISD::INSERT_SUBVECTOR: {
6315     // Inserting undef into undef is still undef.
6316     if (N1.isUndef() && N2.isUndef())
6317       return getUNDEF(VT);
6318 
6319     EVT N2VT = N2.getValueType();
6320     assert(VT == N1.getValueType() &&
6321            "Dest and insert subvector source types must match!");
6322     assert(VT.isVector() && N2VT.isVector() &&
6323            "Insert subvector VTs must be vectors!");
6324     assert((VT.isScalableVector() || N2VT.isFixedLengthVector()) &&
6325            "Cannot insert a scalable vector into a fixed length vector!");
6326     assert((VT.isScalableVector() != N2VT.isScalableVector() ||
6327             VT.getVectorMinNumElements() >= N2VT.getVectorMinNumElements()) &&
6328            "Insert subvector must be from smaller vector to larger vector!");
6329     assert(isa<ConstantSDNode>(N3) &&
6330            "Insert subvector index must be constant");
6331     assert((VT.isScalableVector() != N2VT.isScalableVector() ||
6332             (N2VT.getVectorMinNumElements() +
6333              cast<ConstantSDNode>(N3)->getZExtValue()) <=
6334                 VT.getVectorMinNumElements()) &&
6335            "Insert subvector overflow!");
6336     assert(cast<ConstantSDNode>(N3)->getAPIntValue().getBitWidth() ==
6337                TLI->getVectorIdxTy(getDataLayout()).getFixedSizeInBits() &&
6338            "Constant index for INSERT_SUBVECTOR has an invalid size");
6339 
6340     // Trivial insertion.
6341     if (VT == N2VT)
6342       return N2;
6343 
6344     // If this is an insert of an extracted vector into an undef vector, we
6345     // can just use the input to the extract.
6346     if (N1.isUndef() && N2.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
6347         N2.getOperand(1) == N3 && N2.getOperand(0).getValueType() == VT)
6348       return N2.getOperand(0);
6349     break;
6350   }
6351   case ISD::BITCAST:
6352     // Fold bit_convert nodes from a type to themselves.
6353     if (N1.getValueType() == VT)
6354       return N1;
6355     break;
6356   }
6357 
6358   // Memoize node if it doesn't produce a flag.
6359   SDNode *N;
6360   SDVTList VTs = getVTList(VT);
6361   SDValue Ops[] = {N1, N2, N3};
6362   if (VT != MVT::Glue) {
6363     FoldingSetNodeID ID;
6364     AddNodeIDNode(ID, Opcode, VTs, Ops);
6365     void *IP = nullptr;
6366     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
6367       E->intersectFlagsWith(Flags);
6368       return SDValue(E, 0);
6369     }
6370 
6371     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
6372     N->setFlags(Flags);
6373     createOperands(N, Ops);
6374     CSEMap.InsertNode(N, IP);
6375   } else {
6376     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
6377     createOperands(N, Ops);
6378   }
6379 
6380   InsertNode(N);
6381   SDValue V = SDValue(N, 0);
6382   NewSDValueDbgMsg(V, "Creating new node: ", this);
6383   return V;
6384 }
6385 
6386 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
6387                               SDValue N1, SDValue N2, SDValue N3, SDValue N4) {
6388   SDValue Ops[] = { N1, N2, N3, N4 };
6389   return getNode(Opcode, DL, VT, Ops);
6390 }
6391 
6392 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
6393                               SDValue N1, SDValue N2, SDValue N3, SDValue N4,
6394                               SDValue N5) {
6395   SDValue Ops[] = { N1, N2, N3, N4, N5 };
6396   return getNode(Opcode, DL, VT, Ops);
6397 }
6398 
6399 /// getStackArgumentTokenFactor - Compute a TokenFactor to force all
6400 /// the incoming stack arguments to be loaded from the stack.
6401 SDValue SelectionDAG::getStackArgumentTokenFactor(SDValue Chain) {
6402   SmallVector<SDValue, 8> ArgChains;
6403 
6404   // Include the original chain at the beginning of the list. When this is
6405   // used by target LowerCall hooks, this helps legalize find the
6406   // CALLSEQ_BEGIN node.
6407   ArgChains.push_back(Chain);
6408 
6409   // Add a chain value for each stack argument.
6410   for (SDNode *U : getEntryNode().getNode()->uses())
6411     if (LoadSDNode *L = dyn_cast<LoadSDNode>(U))
6412       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
6413         if (FI->getIndex() < 0)
6414           ArgChains.push_back(SDValue(L, 1));
6415 
6416   // Build a tokenfactor for all the chains.
6417   return getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains);
6418 }
6419 
6420 /// getMemsetValue - Vectorized representation of the memset value
6421 /// operand.
6422 static SDValue getMemsetValue(SDValue Value, EVT VT, SelectionDAG &DAG,
6423                               const SDLoc &dl) {
6424   assert(!Value.isUndef());
6425 
6426   unsigned NumBits = VT.getScalarSizeInBits();
6427   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
6428     assert(C->getAPIntValue().getBitWidth() == 8);
6429     APInt Val = APInt::getSplat(NumBits, C->getAPIntValue());
6430     if (VT.isInteger()) {
6431       bool IsOpaque = VT.getSizeInBits() > 64 ||
6432           !DAG.getTargetLoweringInfo().isLegalStoreImmediate(C->getSExtValue());
6433       return DAG.getConstant(Val, dl, VT, false, IsOpaque);
6434     }
6435     return DAG.getConstantFP(APFloat(DAG.EVTToAPFloatSemantics(VT), Val), dl,
6436                              VT);
6437   }
6438 
6439   assert(Value.getValueType() == MVT::i8 && "memset with non-byte fill value?");
6440   EVT IntVT = VT.getScalarType();
6441   if (!IntVT.isInteger())
6442     IntVT = EVT::getIntegerVT(*DAG.getContext(), IntVT.getSizeInBits());
6443 
6444   Value = DAG.getNode(ISD::ZERO_EXTEND, dl, IntVT, Value);
6445   if (NumBits > 8) {
6446     // Use a multiplication with 0x010101... to extend the input to the
6447     // required length.
6448     APInt Magic = APInt::getSplat(NumBits, APInt(8, 0x01));
6449     Value = DAG.getNode(ISD::MUL, dl, IntVT, Value,
6450                         DAG.getConstant(Magic, dl, IntVT));
6451   }
6452 
6453   if (VT != Value.getValueType() && !VT.isInteger())
6454     Value = DAG.getBitcast(VT.getScalarType(), Value);
6455   if (VT != Value.getValueType())
6456     Value = DAG.getSplatBuildVector(VT, dl, Value);
6457 
6458   return Value;
6459 }
6460 
6461 /// getMemsetStringVal - Similar to getMemsetValue. Except this is only
6462 /// used when a memcpy is turned into a memset when the source is a constant
6463 /// string ptr.
6464 static SDValue getMemsetStringVal(EVT VT, const SDLoc &dl, SelectionDAG &DAG,
6465                                   const TargetLowering &TLI,
6466                                   const ConstantDataArraySlice &Slice) {
6467   // Handle vector with all elements zero.
6468   if (Slice.Array == nullptr) {
6469     if (VT.isInteger())
6470       return DAG.getConstant(0, dl, VT);
6471     if (VT == MVT::f32 || VT == MVT::f64 || VT == MVT::f128)
6472       return DAG.getConstantFP(0.0, dl, VT);
6473     if (VT.isVector()) {
6474       unsigned NumElts = VT.getVectorNumElements();
6475       MVT EltVT = (VT.getVectorElementType() == MVT::f32) ? MVT::i32 : MVT::i64;
6476       return DAG.getNode(ISD::BITCAST, dl, VT,
6477                          DAG.getConstant(0, dl,
6478                                          EVT::getVectorVT(*DAG.getContext(),
6479                                                           EltVT, NumElts)));
6480     }
6481     llvm_unreachable("Expected type!");
6482   }
6483 
6484   assert(!VT.isVector() && "Can't handle vector type here!");
6485   unsigned NumVTBits = VT.getSizeInBits();
6486   unsigned NumVTBytes = NumVTBits / 8;
6487   unsigned NumBytes = std::min(NumVTBytes, unsigned(Slice.Length));
6488 
6489   APInt Val(NumVTBits, 0);
6490   if (DAG.getDataLayout().isLittleEndian()) {
6491     for (unsigned i = 0; i != NumBytes; ++i)
6492       Val |= (uint64_t)(unsigned char)Slice[i] << i*8;
6493   } else {
6494     for (unsigned i = 0; i != NumBytes; ++i)
6495       Val |= (uint64_t)(unsigned char)Slice[i] << (NumVTBytes-i-1)*8;
6496   }
6497 
6498   // If the "cost" of materializing the integer immediate is less than the cost
6499   // of a load, then it is cost effective to turn the load into the immediate.
6500   Type *Ty = VT.getTypeForEVT(*DAG.getContext());
6501   if (TLI.shouldConvertConstantLoadToIntImm(Val, Ty))
6502     return DAG.getConstant(Val, dl, VT);
6503   return SDValue();
6504 }
6505 
6506 SDValue SelectionDAG::getMemBasePlusOffset(SDValue Base, TypeSize Offset,
6507                                            const SDLoc &DL,
6508                                            const SDNodeFlags Flags) {
6509   EVT VT = Base.getValueType();
6510   SDValue Index;
6511 
6512   if (Offset.isScalable())
6513     Index = getVScale(DL, Base.getValueType(),
6514                       APInt(Base.getValueSizeInBits().getFixedSize(),
6515                             Offset.getKnownMinSize()));
6516   else
6517     Index = getConstant(Offset.getFixedSize(), DL, VT);
6518 
6519   return getMemBasePlusOffset(Base, Index, DL, Flags);
6520 }
6521 
6522 SDValue SelectionDAG::getMemBasePlusOffset(SDValue Ptr, SDValue Offset,
6523                                            const SDLoc &DL,
6524                                            const SDNodeFlags Flags) {
6525   assert(Offset.getValueType().isInteger());
6526   EVT BasePtrVT = Ptr.getValueType();
6527   return getNode(ISD::ADD, DL, BasePtrVT, Ptr, Offset, Flags);
6528 }
6529 
6530 /// Returns true if memcpy source is constant data.
6531 static bool isMemSrcFromConstant(SDValue Src, ConstantDataArraySlice &Slice) {
6532   uint64_t SrcDelta = 0;
6533   GlobalAddressSDNode *G = nullptr;
6534   if (Src.getOpcode() == ISD::GlobalAddress)
6535     G = cast<GlobalAddressSDNode>(Src);
6536   else if (Src.getOpcode() == ISD::ADD &&
6537            Src.getOperand(0).getOpcode() == ISD::GlobalAddress &&
6538            Src.getOperand(1).getOpcode() == ISD::Constant) {
6539     G = cast<GlobalAddressSDNode>(Src.getOperand(0));
6540     SrcDelta = cast<ConstantSDNode>(Src.getOperand(1))->getZExtValue();
6541   }
6542   if (!G)
6543     return false;
6544 
6545   return getConstantDataArrayInfo(G->getGlobal(), Slice, 8,
6546                                   SrcDelta + G->getOffset());
6547 }
6548 
6549 static bool shouldLowerMemFuncForSize(const MachineFunction &MF,
6550                                       SelectionDAG &DAG) {
6551   // On Darwin, -Os means optimize for size without hurting performance, so
6552   // only really optimize for size when -Oz (MinSize) is used.
6553   if (MF.getTarget().getTargetTriple().isOSDarwin())
6554     return MF.getFunction().hasMinSize();
6555   return DAG.shouldOptForSize();
6556 }
6557 
6558 static void chainLoadsAndStoresForMemcpy(SelectionDAG &DAG, const SDLoc &dl,
6559                           SmallVector<SDValue, 32> &OutChains, unsigned From,
6560                           unsigned To, SmallVector<SDValue, 16> &OutLoadChains,
6561                           SmallVector<SDValue, 16> &OutStoreChains) {
6562   assert(OutLoadChains.size() && "Missing loads in memcpy inlining");
6563   assert(OutStoreChains.size() && "Missing stores in memcpy inlining");
6564   SmallVector<SDValue, 16> GluedLoadChains;
6565   for (unsigned i = From; i < To; ++i) {
6566     OutChains.push_back(OutLoadChains[i]);
6567     GluedLoadChains.push_back(OutLoadChains[i]);
6568   }
6569 
6570   // Chain for all loads.
6571   SDValue LoadToken = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
6572                                   GluedLoadChains);
6573 
6574   for (unsigned i = From; i < To; ++i) {
6575     StoreSDNode *ST = dyn_cast<StoreSDNode>(OutStoreChains[i]);
6576     SDValue NewStore = DAG.getTruncStore(LoadToken, dl, ST->getValue(),
6577                                   ST->getBasePtr(), ST->getMemoryVT(),
6578                                   ST->getMemOperand());
6579     OutChains.push_back(NewStore);
6580   }
6581 }
6582 
6583 static SDValue getMemcpyLoadsAndStores(SelectionDAG &DAG, const SDLoc &dl,
6584                                        SDValue Chain, SDValue Dst, SDValue Src,
6585                                        uint64_t Size, Align Alignment,
6586                                        bool isVol, bool AlwaysInline,
6587                                        MachinePointerInfo DstPtrInfo,
6588                                        MachinePointerInfo SrcPtrInfo,
6589                                        const AAMDNodes &AAInfo) {
6590   // Turn a memcpy of undef to nop.
6591   // FIXME: We need to honor volatile even is Src is undef.
6592   if (Src.isUndef())
6593     return Chain;
6594 
6595   // Expand memcpy to a series of load and store ops if the size operand falls
6596   // below a certain threshold.
6597   // TODO: In the AlwaysInline case, if the size is big then generate a loop
6598   // rather than maybe a humongous number of loads and stores.
6599   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6600   const DataLayout &DL = DAG.getDataLayout();
6601   LLVMContext &C = *DAG.getContext();
6602   std::vector<EVT> MemOps;
6603   bool DstAlignCanChange = false;
6604   MachineFunction &MF = DAG.getMachineFunction();
6605   MachineFrameInfo &MFI = MF.getFrameInfo();
6606   bool OptSize = shouldLowerMemFuncForSize(MF, DAG);
6607   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
6608   if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
6609     DstAlignCanChange = true;
6610   MaybeAlign SrcAlign = DAG.InferPtrAlign(Src);
6611   if (!SrcAlign || Alignment > *SrcAlign)
6612     SrcAlign = Alignment;
6613   assert(SrcAlign && "SrcAlign must be set");
6614   ConstantDataArraySlice Slice;
6615   // If marked as volatile, perform a copy even when marked as constant.
6616   bool CopyFromConstant = !isVol && isMemSrcFromConstant(Src, Slice);
6617   bool isZeroConstant = CopyFromConstant && Slice.Array == nullptr;
6618   unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemcpy(OptSize);
6619   const MemOp Op = isZeroConstant
6620                        ? MemOp::Set(Size, DstAlignCanChange, Alignment,
6621                                     /*IsZeroMemset*/ true, isVol)
6622                        : MemOp::Copy(Size, DstAlignCanChange, Alignment,
6623                                      *SrcAlign, isVol, CopyFromConstant);
6624   if (!TLI.findOptimalMemOpLowering(
6625           MemOps, Limit, Op, DstPtrInfo.getAddrSpace(),
6626           SrcPtrInfo.getAddrSpace(), MF.getFunction().getAttributes()))
6627     return SDValue();
6628 
6629   if (DstAlignCanChange) {
6630     Type *Ty = MemOps[0].getTypeForEVT(C);
6631     Align NewAlign = DL.getABITypeAlign(Ty);
6632 
6633     // Don't promote to an alignment that would require dynamic stack
6634     // realignment.
6635     const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
6636     if (!TRI->hasStackRealignment(MF))
6637       while (NewAlign > Alignment && DL.exceedsNaturalStackAlignment(NewAlign))
6638         NewAlign = NewAlign / 2;
6639 
6640     if (NewAlign > Alignment) {
6641       // Give the stack frame object a larger alignment if needed.
6642       if (MFI.getObjectAlign(FI->getIndex()) < NewAlign)
6643         MFI.setObjectAlignment(FI->getIndex(), NewAlign);
6644       Alignment = NewAlign;
6645     }
6646   }
6647 
6648   // Prepare AAInfo for loads/stores after lowering this memcpy.
6649   AAMDNodes NewAAInfo = AAInfo;
6650   NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr;
6651 
6652   MachineMemOperand::Flags MMOFlags =
6653       isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone;
6654   SmallVector<SDValue, 16> OutLoadChains;
6655   SmallVector<SDValue, 16> OutStoreChains;
6656   SmallVector<SDValue, 32> OutChains;
6657   unsigned NumMemOps = MemOps.size();
6658   uint64_t SrcOff = 0, DstOff = 0;
6659   for (unsigned i = 0; i != NumMemOps; ++i) {
6660     EVT VT = MemOps[i];
6661     unsigned VTSize = VT.getSizeInBits() / 8;
6662     SDValue Value, Store;
6663 
6664     if (VTSize > Size) {
6665       // Issuing an unaligned load / store pair  that overlaps with the previous
6666       // pair. Adjust the offset accordingly.
6667       assert(i == NumMemOps-1 && i != 0);
6668       SrcOff -= VTSize - Size;
6669       DstOff -= VTSize - Size;
6670     }
6671 
6672     if (CopyFromConstant &&
6673         (isZeroConstant || (VT.isInteger() && !VT.isVector()))) {
6674       // It's unlikely a store of a vector immediate can be done in a single
6675       // instruction. It would require a load from a constantpool first.
6676       // We only handle zero vectors here.
6677       // FIXME: Handle other cases where store of vector immediate is done in
6678       // a single instruction.
6679       ConstantDataArraySlice SubSlice;
6680       if (SrcOff < Slice.Length) {
6681         SubSlice = Slice;
6682         SubSlice.move(SrcOff);
6683       } else {
6684         // This is an out-of-bounds access and hence UB. Pretend we read zero.
6685         SubSlice.Array = nullptr;
6686         SubSlice.Offset = 0;
6687         SubSlice.Length = VTSize;
6688       }
6689       Value = getMemsetStringVal(VT, dl, DAG, TLI, SubSlice);
6690       if (Value.getNode()) {
6691         Store = DAG.getStore(
6692             Chain, dl, Value,
6693             DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl),
6694             DstPtrInfo.getWithOffset(DstOff), Alignment, MMOFlags, NewAAInfo);
6695         OutChains.push_back(Store);
6696       }
6697     }
6698 
6699     if (!Store.getNode()) {
6700       // The type might not be legal for the target.  This should only happen
6701       // if the type is smaller than a legal type, as on PPC, so the right
6702       // thing to do is generate a LoadExt/StoreTrunc pair.  These simplify
6703       // to Load/Store if NVT==VT.
6704       // FIXME does the case above also need this?
6705       EVT NVT = TLI.getTypeToTransformTo(C, VT);
6706       assert(NVT.bitsGE(VT));
6707 
6708       bool isDereferenceable =
6709         SrcPtrInfo.getWithOffset(SrcOff).isDereferenceable(VTSize, C, DL);
6710       MachineMemOperand::Flags SrcMMOFlags = MMOFlags;
6711       if (isDereferenceable)
6712         SrcMMOFlags |= MachineMemOperand::MODereferenceable;
6713 
6714       Value = DAG.getExtLoad(
6715           ISD::EXTLOAD, dl, NVT, Chain,
6716           DAG.getMemBasePlusOffset(Src, TypeSize::Fixed(SrcOff), dl),
6717           SrcPtrInfo.getWithOffset(SrcOff), VT,
6718           commonAlignment(*SrcAlign, SrcOff), SrcMMOFlags, NewAAInfo);
6719       OutLoadChains.push_back(Value.getValue(1));
6720 
6721       Store = DAG.getTruncStore(
6722           Chain, dl, Value,
6723           DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl),
6724           DstPtrInfo.getWithOffset(DstOff), VT, Alignment, MMOFlags, NewAAInfo);
6725       OutStoreChains.push_back(Store);
6726     }
6727     SrcOff += VTSize;
6728     DstOff += VTSize;
6729     Size -= VTSize;
6730   }
6731 
6732   unsigned GluedLdStLimit = MaxLdStGlue == 0 ?
6733                                 TLI.getMaxGluedStoresPerMemcpy() : MaxLdStGlue;
6734   unsigned NumLdStInMemcpy = OutStoreChains.size();
6735 
6736   if (NumLdStInMemcpy) {
6737     // It may be that memcpy might be converted to memset if it's memcpy
6738     // of constants. In such a case, we won't have loads and stores, but
6739     // just stores. In the absence of loads, there is nothing to gang up.
6740     if ((GluedLdStLimit <= 1) || !EnableMemCpyDAGOpt) {
6741       // If target does not care, just leave as it.
6742       for (unsigned i = 0; i < NumLdStInMemcpy; ++i) {
6743         OutChains.push_back(OutLoadChains[i]);
6744         OutChains.push_back(OutStoreChains[i]);
6745       }
6746     } else {
6747       // Ld/St less than/equal limit set by target.
6748       if (NumLdStInMemcpy <= GluedLdStLimit) {
6749           chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, 0,
6750                                         NumLdStInMemcpy, OutLoadChains,
6751                                         OutStoreChains);
6752       } else {
6753         unsigned NumberLdChain =  NumLdStInMemcpy / GluedLdStLimit;
6754         unsigned RemainingLdStInMemcpy = NumLdStInMemcpy % GluedLdStLimit;
6755         unsigned GlueIter = 0;
6756 
6757         for (unsigned cnt = 0; cnt < NumberLdChain; ++cnt) {
6758           unsigned IndexFrom = NumLdStInMemcpy - GlueIter - GluedLdStLimit;
6759           unsigned IndexTo   = NumLdStInMemcpy - GlueIter;
6760 
6761           chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, IndexFrom, IndexTo,
6762                                        OutLoadChains, OutStoreChains);
6763           GlueIter += GluedLdStLimit;
6764         }
6765 
6766         // Residual ld/st.
6767         if (RemainingLdStInMemcpy) {
6768           chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, 0,
6769                                         RemainingLdStInMemcpy, OutLoadChains,
6770                                         OutStoreChains);
6771         }
6772       }
6773     }
6774   }
6775   return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
6776 }
6777 
6778 static SDValue getMemmoveLoadsAndStores(SelectionDAG &DAG, const SDLoc &dl,
6779                                         SDValue Chain, SDValue Dst, SDValue Src,
6780                                         uint64_t Size, Align Alignment,
6781                                         bool isVol, bool AlwaysInline,
6782                                         MachinePointerInfo DstPtrInfo,
6783                                         MachinePointerInfo SrcPtrInfo,
6784                                         const AAMDNodes &AAInfo) {
6785   // Turn a memmove of undef to nop.
6786   // FIXME: We need to honor volatile even is Src is undef.
6787   if (Src.isUndef())
6788     return Chain;
6789 
6790   // Expand memmove to a series of load and store ops if the size operand falls
6791   // below a certain threshold.
6792   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6793   const DataLayout &DL = DAG.getDataLayout();
6794   LLVMContext &C = *DAG.getContext();
6795   std::vector<EVT> MemOps;
6796   bool DstAlignCanChange = false;
6797   MachineFunction &MF = DAG.getMachineFunction();
6798   MachineFrameInfo &MFI = MF.getFrameInfo();
6799   bool OptSize = shouldLowerMemFuncForSize(MF, DAG);
6800   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
6801   if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
6802     DstAlignCanChange = true;
6803   MaybeAlign SrcAlign = DAG.InferPtrAlign(Src);
6804   if (!SrcAlign || Alignment > *SrcAlign)
6805     SrcAlign = Alignment;
6806   assert(SrcAlign && "SrcAlign must be set");
6807   unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemmove(OptSize);
6808   if (!TLI.findOptimalMemOpLowering(
6809           MemOps, Limit,
6810           MemOp::Copy(Size, DstAlignCanChange, Alignment, *SrcAlign,
6811                       /*IsVolatile*/ true),
6812           DstPtrInfo.getAddrSpace(), SrcPtrInfo.getAddrSpace(),
6813           MF.getFunction().getAttributes()))
6814     return SDValue();
6815 
6816   if (DstAlignCanChange) {
6817     Type *Ty = MemOps[0].getTypeForEVT(C);
6818     Align NewAlign = DL.getABITypeAlign(Ty);
6819     if (NewAlign > Alignment) {
6820       // Give the stack frame object a larger alignment if needed.
6821       if (MFI.getObjectAlign(FI->getIndex()) < NewAlign)
6822         MFI.setObjectAlignment(FI->getIndex(), NewAlign);
6823       Alignment = NewAlign;
6824     }
6825   }
6826 
6827   // Prepare AAInfo for loads/stores after lowering this memmove.
6828   AAMDNodes NewAAInfo = AAInfo;
6829   NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr;
6830 
6831   MachineMemOperand::Flags MMOFlags =
6832       isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone;
6833   uint64_t SrcOff = 0, DstOff = 0;
6834   SmallVector<SDValue, 8> LoadValues;
6835   SmallVector<SDValue, 8> LoadChains;
6836   SmallVector<SDValue, 8> OutChains;
6837   unsigned NumMemOps = MemOps.size();
6838   for (unsigned i = 0; i < NumMemOps; i++) {
6839     EVT VT = MemOps[i];
6840     unsigned VTSize = VT.getSizeInBits() / 8;
6841     SDValue Value;
6842 
6843     bool isDereferenceable =
6844       SrcPtrInfo.getWithOffset(SrcOff).isDereferenceable(VTSize, C, DL);
6845     MachineMemOperand::Flags SrcMMOFlags = MMOFlags;
6846     if (isDereferenceable)
6847       SrcMMOFlags |= MachineMemOperand::MODereferenceable;
6848 
6849     Value = DAG.getLoad(
6850         VT, dl, Chain,
6851         DAG.getMemBasePlusOffset(Src, TypeSize::Fixed(SrcOff), dl),
6852         SrcPtrInfo.getWithOffset(SrcOff), *SrcAlign, SrcMMOFlags, NewAAInfo);
6853     LoadValues.push_back(Value);
6854     LoadChains.push_back(Value.getValue(1));
6855     SrcOff += VTSize;
6856   }
6857   Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
6858   OutChains.clear();
6859   for (unsigned i = 0; i < NumMemOps; i++) {
6860     EVT VT = MemOps[i];
6861     unsigned VTSize = VT.getSizeInBits() / 8;
6862     SDValue Store;
6863 
6864     Store = DAG.getStore(
6865         Chain, dl, LoadValues[i],
6866         DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl),
6867         DstPtrInfo.getWithOffset(DstOff), Alignment, MMOFlags, NewAAInfo);
6868     OutChains.push_back(Store);
6869     DstOff += VTSize;
6870   }
6871 
6872   return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
6873 }
6874 
6875 /// Lower the call to 'memset' intrinsic function into a series of store
6876 /// operations.
6877 ///
6878 /// \param DAG Selection DAG where lowered code is placed.
6879 /// \param dl Link to corresponding IR location.
6880 /// \param Chain Control flow dependency.
6881 /// \param Dst Pointer to destination memory location.
6882 /// \param Src Value of byte to write into the memory.
6883 /// \param Size Number of bytes to write.
6884 /// \param Alignment Alignment of the destination in bytes.
6885 /// \param isVol True if destination is volatile.
6886 /// \param DstPtrInfo IR information on the memory pointer.
6887 /// \returns New head in the control flow, if lowering was successful, empty
6888 /// SDValue otherwise.
6889 ///
6890 /// The function tries to replace 'llvm.memset' intrinsic with several store
6891 /// operations and value calculation code. This is usually profitable for small
6892 /// memory size.
6893 static SDValue getMemsetStores(SelectionDAG &DAG, const SDLoc &dl,
6894                                SDValue Chain, SDValue Dst, SDValue Src,
6895                                uint64_t Size, Align Alignment, bool isVol,
6896                                MachinePointerInfo DstPtrInfo,
6897                                const AAMDNodes &AAInfo) {
6898   // Turn a memset of undef to nop.
6899   // FIXME: We need to honor volatile even is Src is undef.
6900   if (Src.isUndef())
6901     return Chain;
6902 
6903   // Expand memset to a series of load/store ops if the size operand
6904   // falls below a certain threshold.
6905   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6906   std::vector<EVT> MemOps;
6907   bool DstAlignCanChange = false;
6908   MachineFunction &MF = DAG.getMachineFunction();
6909   MachineFrameInfo &MFI = MF.getFrameInfo();
6910   bool OptSize = shouldLowerMemFuncForSize(MF, DAG);
6911   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
6912   if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
6913     DstAlignCanChange = true;
6914   bool IsZeroVal =
6915       isa<ConstantSDNode>(Src) && cast<ConstantSDNode>(Src)->isZero();
6916   if (!TLI.findOptimalMemOpLowering(
6917           MemOps, TLI.getMaxStoresPerMemset(OptSize),
6918           MemOp::Set(Size, DstAlignCanChange, Alignment, IsZeroVal, isVol),
6919           DstPtrInfo.getAddrSpace(), ~0u, MF.getFunction().getAttributes()))
6920     return SDValue();
6921 
6922   if (DstAlignCanChange) {
6923     Type *Ty = MemOps[0].getTypeForEVT(*DAG.getContext());
6924     Align NewAlign = DAG.getDataLayout().getABITypeAlign(Ty);
6925     if (NewAlign > Alignment) {
6926       // Give the stack frame object a larger alignment if needed.
6927       if (MFI.getObjectAlign(FI->getIndex()) < NewAlign)
6928         MFI.setObjectAlignment(FI->getIndex(), NewAlign);
6929       Alignment = NewAlign;
6930     }
6931   }
6932 
6933   SmallVector<SDValue, 8> OutChains;
6934   uint64_t DstOff = 0;
6935   unsigned NumMemOps = MemOps.size();
6936 
6937   // Find the largest store and generate the bit pattern for it.
6938   EVT LargestVT = MemOps[0];
6939   for (unsigned i = 1; i < NumMemOps; i++)
6940     if (MemOps[i].bitsGT(LargestVT))
6941       LargestVT = MemOps[i];
6942   SDValue MemSetValue = getMemsetValue(Src, LargestVT, DAG, dl);
6943 
6944   // Prepare AAInfo for loads/stores after lowering this memset.
6945   AAMDNodes NewAAInfo = AAInfo;
6946   NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr;
6947 
6948   for (unsigned i = 0; i < NumMemOps; i++) {
6949     EVT VT = MemOps[i];
6950     unsigned VTSize = VT.getSizeInBits() / 8;
6951     if (VTSize > Size) {
6952       // Issuing an unaligned load / store pair  that overlaps with the previous
6953       // pair. Adjust the offset accordingly.
6954       assert(i == NumMemOps-1 && i != 0);
6955       DstOff -= VTSize - Size;
6956     }
6957 
6958     // If this store is smaller than the largest store see whether we can get
6959     // the smaller value for free with a truncate.
6960     SDValue Value = MemSetValue;
6961     if (VT.bitsLT(LargestVT)) {
6962       if (!LargestVT.isVector() && !VT.isVector() &&
6963           TLI.isTruncateFree(LargestVT, VT))
6964         Value = DAG.getNode(ISD::TRUNCATE, dl, VT, MemSetValue);
6965       else
6966         Value = getMemsetValue(Src, VT, DAG, dl);
6967     }
6968     assert(Value.getValueType() == VT && "Value with wrong type.");
6969     SDValue Store = DAG.getStore(
6970         Chain, dl, Value,
6971         DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl),
6972         DstPtrInfo.getWithOffset(DstOff), Alignment,
6973         isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone,
6974         NewAAInfo);
6975     OutChains.push_back(Store);
6976     DstOff += VT.getSizeInBits() / 8;
6977     Size -= VTSize;
6978   }
6979 
6980   return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
6981 }
6982 
6983 static void checkAddrSpaceIsValidForLibcall(const TargetLowering *TLI,
6984                                             unsigned AS) {
6985   // Lowering memcpy / memset / memmove intrinsics to calls is only valid if all
6986   // pointer operands can be losslessly bitcasted to pointers of address space 0
6987   if (AS != 0 && !TLI->getTargetMachine().isNoopAddrSpaceCast(AS, 0)) {
6988     report_fatal_error("cannot lower memory intrinsic in address space " +
6989                        Twine(AS));
6990   }
6991 }
6992 
6993 SDValue SelectionDAG::getMemcpy(SDValue Chain, const SDLoc &dl, SDValue Dst,
6994                                 SDValue Src, SDValue Size, Align Alignment,
6995                                 bool isVol, bool AlwaysInline, bool isTailCall,
6996                                 MachinePointerInfo DstPtrInfo,
6997                                 MachinePointerInfo SrcPtrInfo,
6998                                 const AAMDNodes &AAInfo) {
6999   // Check to see if we should lower the memcpy to loads and stores first.
7000   // For cases within the target-specified limits, this is the best choice.
7001   ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
7002   if (ConstantSize) {
7003     // Memcpy with size zero? Just return the original chain.
7004     if (ConstantSize->isZero())
7005       return Chain;
7006 
7007     SDValue Result = getMemcpyLoadsAndStores(
7008         *this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), Alignment,
7009         isVol, false, DstPtrInfo, SrcPtrInfo, AAInfo);
7010     if (Result.getNode())
7011       return Result;
7012   }
7013 
7014   // Then check to see if we should lower the memcpy with target-specific
7015   // code. If the target chooses to do this, this is the next best.
7016   if (TSI) {
7017     SDValue Result = TSI->EmitTargetCodeForMemcpy(
7018         *this, dl, Chain, Dst, Src, Size, Alignment, isVol, AlwaysInline,
7019         DstPtrInfo, SrcPtrInfo);
7020     if (Result.getNode())
7021       return Result;
7022   }
7023 
7024   // If we really need inline code and the target declined to provide it,
7025   // use a (potentially long) sequence of loads and stores.
7026   if (AlwaysInline) {
7027     assert(ConstantSize && "AlwaysInline requires a constant size!");
7028     return getMemcpyLoadsAndStores(*this, dl, Chain, Dst, Src,
7029                                    ConstantSize->getZExtValue(), Alignment,
7030                                    isVol, true, DstPtrInfo, SrcPtrInfo, AAInfo);
7031   }
7032 
7033   checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace());
7034   checkAddrSpaceIsValidForLibcall(TLI, SrcPtrInfo.getAddrSpace());
7035 
7036   // FIXME: If the memcpy is volatile (isVol), lowering it to a plain libc
7037   // memcpy is not guaranteed to be safe. libc memcpys aren't required to
7038   // respect volatile, so they may do things like read or write memory
7039   // beyond the given memory regions. But fixing this isn't easy, and most
7040   // people don't care.
7041 
7042   // Emit a library call.
7043   TargetLowering::ArgListTy Args;
7044   TargetLowering::ArgListEntry Entry;
7045   Entry.Ty = Type::getInt8PtrTy(*getContext());
7046   Entry.Node = Dst; Args.push_back(Entry);
7047   Entry.Node = Src; Args.push_back(Entry);
7048 
7049   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
7050   Entry.Node = Size; Args.push_back(Entry);
7051   // FIXME: pass in SDLoc
7052   TargetLowering::CallLoweringInfo CLI(*this);
7053   CLI.setDebugLoc(dl)
7054       .setChain(Chain)
7055       .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMCPY),
7056                     Dst.getValueType().getTypeForEVT(*getContext()),
7057                     getExternalSymbol(TLI->getLibcallName(RTLIB::MEMCPY),
7058                                       TLI->getPointerTy(getDataLayout())),
7059                     std::move(Args))
7060       .setDiscardResult()
7061       .setTailCall(isTailCall);
7062 
7063   std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
7064   return CallResult.second;
7065 }
7066 
7067 SDValue SelectionDAG::getAtomicMemcpy(SDValue Chain, const SDLoc &dl,
7068                                       SDValue Dst, unsigned DstAlign,
7069                                       SDValue Src, unsigned SrcAlign,
7070                                       SDValue Size, Type *SizeTy,
7071                                       unsigned ElemSz, bool isTailCall,
7072                                       MachinePointerInfo DstPtrInfo,
7073                                       MachinePointerInfo SrcPtrInfo) {
7074   // Emit a library call.
7075   TargetLowering::ArgListTy Args;
7076   TargetLowering::ArgListEntry Entry;
7077   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
7078   Entry.Node = Dst;
7079   Args.push_back(Entry);
7080 
7081   Entry.Node = Src;
7082   Args.push_back(Entry);
7083 
7084   Entry.Ty = SizeTy;
7085   Entry.Node = Size;
7086   Args.push_back(Entry);
7087 
7088   RTLIB::Libcall LibraryCall =
7089       RTLIB::getMEMCPY_ELEMENT_UNORDERED_ATOMIC(ElemSz);
7090   if (LibraryCall == RTLIB::UNKNOWN_LIBCALL)
7091     report_fatal_error("Unsupported element size");
7092 
7093   TargetLowering::CallLoweringInfo CLI(*this);
7094   CLI.setDebugLoc(dl)
7095       .setChain(Chain)
7096       .setLibCallee(TLI->getLibcallCallingConv(LibraryCall),
7097                     Type::getVoidTy(*getContext()),
7098                     getExternalSymbol(TLI->getLibcallName(LibraryCall),
7099                                       TLI->getPointerTy(getDataLayout())),
7100                     std::move(Args))
7101       .setDiscardResult()
7102       .setTailCall(isTailCall);
7103 
7104   std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
7105   return CallResult.second;
7106 }
7107 
7108 SDValue SelectionDAG::getMemmove(SDValue Chain, const SDLoc &dl, SDValue Dst,
7109                                  SDValue Src, SDValue Size, Align Alignment,
7110                                  bool isVol, bool isTailCall,
7111                                  MachinePointerInfo DstPtrInfo,
7112                                  MachinePointerInfo SrcPtrInfo,
7113                                  const AAMDNodes &AAInfo) {
7114   // Check to see if we should lower the memmove to loads and stores first.
7115   // For cases within the target-specified limits, this is the best choice.
7116   ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
7117   if (ConstantSize) {
7118     // Memmove with size zero? Just return the original chain.
7119     if (ConstantSize->isZero())
7120       return Chain;
7121 
7122     SDValue Result = getMemmoveLoadsAndStores(
7123         *this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), Alignment,
7124         isVol, false, DstPtrInfo, SrcPtrInfo, AAInfo);
7125     if (Result.getNode())
7126       return Result;
7127   }
7128 
7129   // Then check to see if we should lower the memmove with target-specific
7130   // code. If the target chooses to do this, this is the next best.
7131   if (TSI) {
7132     SDValue Result =
7133         TSI->EmitTargetCodeForMemmove(*this, dl, Chain, Dst, Src, Size,
7134                                       Alignment, isVol, DstPtrInfo, SrcPtrInfo);
7135     if (Result.getNode())
7136       return Result;
7137   }
7138 
7139   checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace());
7140   checkAddrSpaceIsValidForLibcall(TLI, SrcPtrInfo.getAddrSpace());
7141 
7142   // FIXME: If the memmove is volatile, lowering it to plain libc memmove may
7143   // not be safe.  See memcpy above for more details.
7144 
7145   // Emit a library call.
7146   TargetLowering::ArgListTy Args;
7147   TargetLowering::ArgListEntry Entry;
7148   Entry.Ty = Type::getInt8PtrTy(*getContext());
7149   Entry.Node = Dst; Args.push_back(Entry);
7150   Entry.Node = Src; Args.push_back(Entry);
7151 
7152   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
7153   Entry.Node = Size; Args.push_back(Entry);
7154   // FIXME:  pass in SDLoc
7155   TargetLowering::CallLoweringInfo CLI(*this);
7156   CLI.setDebugLoc(dl)
7157       .setChain(Chain)
7158       .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMMOVE),
7159                     Dst.getValueType().getTypeForEVT(*getContext()),
7160                     getExternalSymbol(TLI->getLibcallName(RTLIB::MEMMOVE),
7161                                       TLI->getPointerTy(getDataLayout())),
7162                     std::move(Args))
7163       .setDiscardResult()
7164       .setTailCall(isTailCall);
7165 
7166   std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
7167   return CallResult.second;
7168 }
7169 
7170 SDValue SelectionDAG::getAtomicMemmove(SDValue Chain, const SDLoc &dl,
7171                                        SDValue Dst, unsigned DstAlign,
7172                                        SDValue Src, unsigned SrcAlign,
7173                                        SDValue Size, Type *SizeTy,
7174                                        unsigned ElemSz, bool isTailCall,
7175                                        MachinePointerInfo DstPtrInfo,
7176                                        MachinePointerInfo SrcPtrInfo) {
7177   // Emit a library call.
7178   TargetLowering::ArgListTy Args;
7179   TargetLowering::ArgListEntry Entry;
7180   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
7181   Entry.Node = Dst;
7182   Args.push_back(Entry);
7183 
7184   Entry.Node = Src;
7185   Args.push_back(Entry);
7186 
7187   Entry.Ty = SizeTy;
7188   Entry.Node = Size;
7189   Args.push_back(Entry);
7190 
7191   RTLIB::Libcall LibraryCall =
7192       RTLIB::getMEMMOVE_ELEMENT_UNORDERED_ATOMIC(ElemSz);
7193   if (LibraryCall == RTLIB::UNKNOWN_LIBCALL)
7194     report_fatal_error("Unsupported element size");
7195 
7196   TargetLowering::CallLoweringInfo CLI(*this);
7197   CLI.setDebugLoc(dl)
7198       .setChain(Chain)
7199       .setLibCallee(TLI->getLibcallCallingConv(LibraryCall),
7200                     Type::getVoidTy(*getContext()),
7201                     getExternalSymbol(TLI->getLibcallName(LibraryCall),
7202                                       TLI->getPointerTy(getDataLayout())),
7203                     std::move(Args))
7204       .setDiscardResult()
7205       .setTailCall(isTailCall);
7206 
7207   std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
7208   return CallResult.second;
7209 }
7210 
7211 SDValue SelectionDAG::getMemset(SDValue Chain, const SDLoc &dl, SDValue Dst,
7212                                 SDValue Src, SDValue Size, Align Alignment,
7213                                 bool isVol, bool isTailCall,
7214                                 MachinePointerInfo DstPtrInfo,
7215                                 const AAMDNodes &AAInfo) {
7216   // Check to see if we should lower the memset to stores first.
7217   // For cases within the target-specified limits, this is the best choice.
7218   ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
7219   if (ConstantSize) {
7220     // Memset with size zero? Just return the original chain.
7221     if (ConstantSize->isZero())
7222       return Chain;
7223 
7224     SDValue Result = getMemsetStores(*this, dl, Chain, Dst, Src,
7225                                      ConstantSize->getZExtValue(), Alignment,
7226                                      isVol, DstPtrInfo, AAInfo);
7227 
7228     if (Result.getNode())
7229       return Result;
7230   }
7231 
7232   // Then check to see if we should lower the memset with target-specific
7233   // code. If the target chooses to do this, this is the next best.
7234   if (TSI) {
7235     SDValue Result = TSI->EmitTargetCodeForMemset(
7236         *this, dl, Chain, Dst, Src, Size, Alignment, isVol, DstPtrInfo);
7237     if (Result.getNode())
7238       return Result;
7239   }
7240 
7241   checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace());
7242 
7243   // Emit a library call.
7244   TargetLowering::ArgListTy Args;
7245   TargetLowering::ArgListEntry Entry;
7246   Entry.Node = Dst; Entry.Ty = Type::getInt8PtrTy(*getContext());
7247   Args.push_back(Entry);
7248   Entry.Node = Src;
7249   Entry.Ty = Src.getValueType().getTypeForEVT(*getContext());
7250   Args.push_back(Entry);
7251   Entry.Node = Size;
7252   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
7253   Args.push_back(Entry);
7254 
7255   // FIXME: pass in SDLoc
7256   TargetLowering::CallLoweringInfo CLI(*this);
7257   CLI.setDebugLoc(dl)
7258       .setChain(Chain)
7259       .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMSET),
7260                     Dst.getValueType().getTypeForEVT(*getContext()),
7261                     getExternalSymbol(TLI->getLibcallName(RTLIB::MEMSET),
7262                                       TLI->getPointerTy(getDataLayout())),
7263                     std::move(Args))
7264       .setDiscardResult()
7265       .setTailCall(isTailCall);
7266 
7267   std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
7268   return CallResult.second;
7269 }
7270 
7271 SDValue SelectionDAG::getAtomicMemset(SDValue Chain, const SDLoc &dl,
7272                                       SDValue Dst, unsigned DstAlign,
7273                                       SDValue Value, SDValue Size, Type *SizeTy,
7274                                       unsigned ElemSz, bool isTailCall,
7275                                       MachinePointerInfo DstPtrInfo) {
7276   // Emit a library call.
7277   TargetLowering::ArgListTy Args;
7278   TargetLowering::ArgListEntry Entry;
7279   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
7280   Entry.Node = Dst;
7281   Args.push_back(Entry);
7282 
7283   Entry.Ty = Type::getInt8Ty(*getContext());
7284   Entry.Node = Value;
7285   Args.push_back(Entry);
7286 
7287   Entry.Ty = SizeTy;
7288   Entry.Node = Size;
7289   Args.push_back(Entry);
7290 
7291   RTLIB::Libcall LibraryCall =
7292       RTLIB::getMEMSET_ELEMENT_UNORDERED_ATOMIC(ElemSz);
7293   if (LibraryCall == RTLIB::UNKNOWN_LIBCALL)
7294     report_fatal_error("Unsupported element size");
7295 
7296   TargetLowering::CallLoweringInfo CLI(*this);
7297   CLI.setDebugLoc(dl)
7298       .setChain(Chain)
7299       .setLibCallee(TLI->getLibcallCallingConv(LibraryCall),
7300                     Type::getVoidTy(*getContext()),
7301                     getExternalSymbol(TLI->getLibcallName(LibraryCall),
7302                                       TLI->getPointerTy(getDataLayout())),
7303                     std::move(Args))
7304       .setDiscardResult()
7305       .setTailCall(isTailCall);
7306 
7307   std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
7308   return CallResult.second;
7309 }
7310 
7311 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
7312                                 SDVTList VTList, ArrayRef<SDValue> Ops,
7313                                 MachineMemOperand *MMO) {
7314   FoldingSetNodeID ID;
7315   ID.AddInteger(MemVT.getRawBits());
7316   AddNodeIDNode(ID, Opcode, VTList, Ops);
7317   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7318   void* IP = nullptr;
7319   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7320     cast<AtomicSDNode>(E)->refineAlignment(MMO);
7321     return SDValue(E, 0);
7322   }
7323 
7324   auto *N = newSDNode<AtomicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
7325                                     VTList, MemVT, MMO);
7326   createOperands(N, Ops);
7327 
7328   CSEMap.InsertNode(N, IP);
7329   InsertNode(N);
7330   return SDValue(N, 0);
7331 }
7332 
7333 SDValue SelectionDAG::getAtomicCmpSwap(unsigned Opcode, const SDLoc &dl,
7334                                        EVT MemVT, SDVTList VTs, SDValue Chain,
7335                                        SDValue Ptr, SDValue Cmp, SDValue Swp,
7336                                        MachineMemOperand *MMO) {
7337   assert(Opcode == ISD::ATOMIC_CMP_SWAP ||
7338          Opcode == ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS);
7339   assert(Cmp.getValueType() == Swp.getValueType() && "Invalid Atomic Op Types");
7340 
7341   SDValue Ops[] = {Chain, Ptr, Cmp, Swp};
7342   return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
7343 }
7344 
7345 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
7346                                 SDValue Chain, SDValue Ptr, SDValue Val,
7347                                 MachineMemOperand *MMO) {
7348   assert((Opcode == ISD::ATOMIC_LOAD_ADD ||
7349           Opcode == ISD::ATOMIC_LOAD_SUB ||
7350           Opcode == ISD::ATOMIC_LOAD_AND ||
7351           Opcode == ISD::ATOMIC_LOAD_CLR ||
7352           Opcode == ISD::ATOMIC_LOAD_OR ||
7353           Opcode == ISD::ATOMIC_LOAD_XOR ||
7354           Opcode == ISD::ATOMIC_LOAD_NAND ||
7355           Opcode == ISD::ATOMIC_LOAD_MIN ||
7356           Opcode == ISD::ATOMIC_LOAD_MAX ||
7357           Opcode == ISD::ATOMIC_LOAD_UMIN ||
7358           Opcode == ISD::ATOMIC_LOAD_UMAX ||
7359           Opcode == ISD::ATOMIC_LOAD_FADD ||
7360           Opcode == ISD::ATOMIC_LOAD_FSUB ||
7361           Opcode == ISD::ATOMIC_SWAP ||
7362           Opcode == ISD::ATOMIC_STORE) &&
7363          "Invalid Atomic Op");
7364 
7365   EVT VT = Val.getValueType();
7366 
7367   SDVTList VTs = Opcode == ISD::ATOMIC_STORE ? getVTList(MVT::Other) :
7368                                                getVTList(VT, MVT::Other);
7369   SDValue Ops[] = {Chain, Ptr, Val};
7370   return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
7371 }
7372 
7373 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
7374                                 EVT VT, SDValue Chain, SDValue Ptr,
7375                                 MachineMemOperand *MMO) {
7376   assert(Opcode == ISD::ATOMIC_LOAD && "Invalid Atomic Op");
7377 
7378   SDVTList VTs = getVTList(VT, MVT::Other);
7379   SDValue Ops[] = {Chain, Ptr};
7380   return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
7381 }
7382 
7383 /// getMergeValues - Create a MERGE_VALUES node from the given operands.
7384 SDValue SelectionDAG::getMergeValues(ArrayRef<SDValue> Ops, const SDLoc &dl) {
7385   if (Ops.size() == 1)
7386     return Ops[0];
7387 
7388   SmallVector<EVT, 4> VTs;
7389   VTs.reserve(Ops.size());
7390   for (const SDValue &Op : Ops)
7391     VTs.push_back(Op.getValueType());
7392   return getNode(ISD::MERGE_VALUES, dl, getVTList(VTs), Ops);
7393 }
7394 
7395 SDValue SelectionDAG::getMemIntrinsicNode(
7396     unsigned Opcode, const SDLoc &dl, SDVTList VTList, ArrayRef<SDValue> Ops,
7397     EVT MemVT, MachinePointerInfo PtrInfo, Align Alignment,
7398     MachineMemOperand::Flags Flags, uint64_t Size, const AAMDNodes &AAInfo) {
7399   if (!Size && MemVT.isScalableVector())
7400     Size = MemoryLocation::UnknownSize;
7401   else if (!Size)
7402     Size = MemVT.getStoreSize();
7403 
7404   MachineFunction &MF = getMachineFunction();
7405   MachineMemOperand *MMO =
7406       MF.getMachineMemOperand(PtrInfo, Flags, Size, Alignment, AAInfo);
7407 
7408   return getMemIntrinsicNode(Opcode, dl, VTList, Ops, MemVT, MMO);
7409 }
7410 
7411 SDValue SelectionDAG::getMemIntrinsicNode(unsigned Opcode, const SDLoc &dl,
7412                                           SDVTList VTList,
7413                                           ArrayRef<SDValue> Ops, EVT MemVT,
7414                                           MachineMemOperand *MMO) {
7415   assert((Opcode == ISD::INTRINSIC_VOID ||
7416           Opcode == ISD::INTRINSIC_W_CHAIN ||
7417           Opcode == ISD::PREFETCH ||
7418           ((int)Opcode <= std::numeric_limits<int>::max() &&
7419            (int)Opcode >= ISD::FIRST_TARGET_MEMORY_OPCODE)) &&
7420          "Opcode is not a memory-accessing opcode!");
7421 
7422   // Memoize the node unless it returns a flag.
7423   MemIntrinsicSDNode *N;
7424   if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) {
7425     FoldingSetNodeID ID;
7426     AddNodeIDNode(ID, Opcode, VTList, Ops);
7427     ID.AddInteger(getSyntheticNodeSubclassData<MemIntrinsicSDNode>(
7428         Opcode, dl.getIROrder(), VTList, MemVT, MMO));
7429     ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7430     void *IP = nullptr;
7431     if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7432       cast<MemIntrinsicSDNode>(E)->refineAlignment(MMO);
7433       return SDValue(E, 0);
7434     }
7435 
7436     N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
7437                                       VTList, MemVT, MMO);
7438     createOperands(N, Ops);
7439 
7440   CSEMap.InsertNode(N, IP);
7441   } else {
7442     N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
7443                                       VTList, MemVT, MMO);
7444     createOperands(N, Ops);
7445   }
7446   InsertNode(N);
7447   SDValue V(N, 0);
7448   NewSDValueDbgMsg(V, "Creating new node: ", this);
7449   return V;
7450 }
7451 
7452 SDValue SelectionDAG::getLifetimeNode(bool IsStart, const SDLoc &dl,
7453                                       SDValue Chain, int FrameIndex,
7454                                       int64_t Size, int64_t Offset) {
7455   const unsigned Opcode = IsStart ? ISD::LIFETIME_START : ISD::LIFETIME_END;
7456   const auto VTs = getVTList(MVT::Other);
7457   SDValue Ops[2] = {
7458       Chain,
7459       getFrameIndex(FrameIndex,
7460                     getTargetLoweringInfo().getFrameIndexTy(getDataLayout()),
7461                     true)};
7462 
7463   FoldingSetNodeID ID;
7464   AddNodeIDNode(ID, Opcode, VTs, Ops);
7465   ID.AddInteger(FrameIndex);
7466   ID.AddInteger(Size);
7467   ID.AddInteger(Offset);
7468   void *IP = nullptr;
7469   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
7470     return SDValue(E, 0);
7471 
7472   LifetimeSDNode *N = newSDNode<LifetimeSDNode>(
7473       Opcode, dl.getIROrder(), dl.getDebugLoc(), VTs, Size, Offset);
7474   createOperands(N, Ops);
7475   CSEMap.InsertNode(N, IP);
7476   InsertNode(N);
7477   SDValue V(N, 0);
7478   NewSDValueDbgMsg(V, "Creating new node: ", this);
7479   return V;
7480 }
7481 
7482 SDValue SelectionDAG::getPseudoProbeNode(const SDLoc &Dl, SDValue Chain,
7483                                          uint64_t Guid, uint64_t Index,
7484                                          uint32_t Attr) {
7485   const unsigned Opcode = ISD::PSEUDO_PROBE;
7486   const auto VTs = getVTList(MVT::Other);
7487   SDValue Ops[] = {Chain};
7488   FoldingSetNodeID ID;
7489   AddNodeIDNode(ID, Opcode, VTs, Ops);
7490   ID.AddInteger(Guid);
7491   ID.AddInteger(Index);
7492   void *IP = nullptr;
7493   if (SDNode *E = FindNodeOrInsertPos(ID, Dl, IP))
7494     return SDValue(E, 0);
7495 
7496   auto *N = newSDNode<PseudoProbeSDNode>(
7497       Opcode, Dl.getIROrder(), Dl.getDebugLoc(), VTs, Guid, Index, Attr);
7498   createOperands(N, Ops);
7499   CSEMap.InsertNode(N, IP);
7500   InsertNode(N);
7501   SDValue V(N, 0);
7502   NewSDValueDbgMsg(V, "Creating new node: ", this);
7503   return V;
7504 }
7505 
7506 /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a
7507 /// MachinePointerInfo record from it.  This is particularly useful because the
7508 /// code generator has many cases where it doesn't bother passing in a
7509 /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst".
7510 static MachinePointerInfo InferPointerInfo(const MachinePointerInfo &Info,
7511                                            SelectionDAG &DAG, SDValue Ptr,
7512                                            int64_t Offset = 0) {
7513   // If this is FI+Offset, we can model it.
7514   if (const FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr))
7515     return MachinePointerInfo::getFixedStack(DAG.getMachineFunction(),
7516                                              FI->getIndex(), Offset);
7517 
7518   // If this is (FI+Offset1)+Offset2, we can model it.
7519   if (Ptr.getOpcode() != ISD::ADD ||
7520       !isa<ConstantSDNode>(Ptr.getOperand(1)) ||
7521       !isa<FrameIndexSDNode>(Ptr.getOperand(0)))
7522     return Info;
7523 
7524   int FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
7525   return MachinePointerInfo::getFixedStack(
7526       DAG.getMachineFunction(), FI,
7527       Offset + cast<ConstantSDNode>(Ptr.getOperand(1))->getSExtValue());
7528 }
7529 
7530 /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a
7531 /// MachinePointerInfo record from it.  This is particularly useful because the
7532 /// code generator has many cases where it doesn't bother passing in a
7533 /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst".
7534 static MachinePointerInfo InferPointerInfo(const MachinePointerInfo &Info,
7535                                            SelectionDAG &DAG, SDValue Ptr,
7536                                            SDValue OffsetOp) {
7537   // If the 'Offset' value isn't a constant, we can't handle this.
7538   if (ConstantSDNode *OffsetNode = dyn_cast<ConstantSDNode>(OffsetOp))
7539     return InferPointerInfo(Info, DAG, Ptr, OffsetNode->getSExtValue());
7540   if (OffsetOp.isUndef())
7541     return InferPointerInfo(Info, DAG, Ptr);
7542   return Info;
7543 }
7544 
7545 SDValue SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType,
7546                               EVT VT, const SDLoc &dl, SDValue Chain,
7547                               SDValue Ptr, SDValue Offset,
7548                               MachinePointerInfo PtrInfo, EVT MemVT,
7549                               Align Alignment,
7550                               MachineMemOperand::Flags MMOFlags,
7551                               const AAMDNodes &AAInfo, const MDNode *Ranges) {
7552   assert(Chain.getValueType() == MVT::Other &&
7553         "Invalid chain type");
7554 
7555   MMOFlags |= MachineMemOperand::MOLoad;
7556   assert((MMOFlags & MachineMemOperand::MOStore) == 0);
7557   // If we don't have a PtrInfo, infer the trivial frame index case to simplify
7558   // clients.
7559   if (PtrInfo.V.isNull())
7560     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr, Offset);
7561 
7562   uint64_t Size = MemoryLocation::getSizeOrUnknown(MemVT.getStoreSize());
7563   MachineFunction &MF = getMachineFunction();
7564   MachineMemOperand *MMO = MF.getMachineMemOperand(PtrInfo, MMOFlags, Size,
7565                                                    Alignment, AAInfo, Ranges);
7566   return getLoad(AM, ExtType, VT, dl, Chain, Ptr, Offset, MemVT, MMO);
7567 }
7568 
7569 SDValue SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType,
7570                               EVT VT, const SDLoc &dl, SDValue Chain,
7571                               SDValue Ptr, SDValue Offset, EVT MemVT,
7572                               MachineMemOperand *MMO) {
7573   if (VT == MemVT) {
7574     ExtType = ISD::NON_EXTLOAD;
7575   } else if (ExtType == ISD::NON_EXTLOAD) {
7576     assert(VT == MemVT && "Non-extending load from different memory type!");
7577   } else {
7578     // Extending load.
7579     assert(MemVT.getScalarType().bitsLT(VT.getScalarType()) &&
7580            "Should only be an extending load, not truncating!");
7581     assert(VT.isInteger() == MemVT.isInteger() &&
7582            "Cannot convert from FP to Int or Int -> FP!");
7583     assert(VT.isVector() == MemVT.isVector() &&
7584            "Cannot use an ext load to convert to or from a vector!");
7585     assert((!VT.isVector() ||
7586             VT.getVectorElementCount() == MemVT.getVectorElementCount()) &&
7587            "Cannot use an ext load to change the number of vector elements!");
7588   }
7589 
7590   bool Indexed = AM != ISD::UNINDEXED;
7591   assert((Indexed || Offset.isUndef()) && "Unindexed load with an offset!");
7592 
7593   SDVTList VTs = Indexed ?
7594     getVTList(VT, Ptr.getValueType(), MVT::Other) : getVTList(VT, MVT::Other);
7595   SDValue Ops[] = { Chain, Ptr, Offset };
7596   FoldingSetNodeID ID;
7597   AddNodeIDNode(ID, ISD::LOAD, VTs, Ops);
7598   ID.AddInteger(MemVT.getRawBits());
7599   ID.AddInteger(getSyntheticNodeSubclassData<LoadSDNode>(
7600       dl.getIROrder(), VTs, AM, ExtType, MemVT, MMO));
7601   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7602   void *IP = nullptr;
7603   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7604     cast<LoadSDNode>(E)->refineAlignment(MMO);
7605     return SDValue(E, 0);
7606   }
7607   auto *N = newSDNode<LoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
7608                                   ExtType, MemVT, MMO);
7609   createOperands(N, Ops);
7610 
7611   CSEMap.InsertNode(N, IP);
7612   InsertNode(N);
7613   SDValue V(N, 0);
7614   NewSDValueDbgMsg(V, "Creating new node: ", this);
7615   return V;
7616 }
7617 
7618 SDValue SelectionDAG::getLoad(EVT VT, const SDLoc &dl, SDValue Chain,
7619                               SDValue Ptr, MachinePointerInfo PtrInfo,
7620                               MaybeAlign Alignment,
7621                               MachineMemOperand::Flags MMOFlags,
7622                               const AAMDNodes &AAInfo, const MDNode *Ranges) {
7623   SDValue Undef = getUNDEF(Ptr.getValueType());
7624   return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
7625                  PtrInfo, VT, Alignment, MMOFlags, AAInfo, Ranges);
7626 }
7627 
7628 SDValue SelectionDAG::getLoad(EVT VT, const SDLoc &dl, SDValue Chain,
7629                               SDValue Ptr, MachineMemOperand *MMO) {
7630   SDValue Undef = getUNDEF(Ptr.getValueType());
7631   return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
7632                  VT, MMO);
7633 }
7634 
7635 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl,
7636                                  EVT VT, SDValue Chain, SDValue Ptr,
7637                                  MachinePointerInfo PtrInfo, EVT MemVT,
7638                                  MaybeAlign Alignment,
7639                                  MachineMemOperand::Flags MMOFlags,
7640                                  const AAMDNodes &AAInfo) {
7641   SDValue Undef = getUNDEF(Ptr.getValueType());
7642   return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, PtrInfo,
7643                  MemVT, Alignment, MMOFlags, AAInfo);
7644 }
7645 
7646 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl,
7647                                  EVT VT, SDValue Chain, SDValue Ptr, EVT MemVT,
7648                                  MachineMemOperand *MMO) {
7649   SDValue Undef = getUNDEF(Ptr.getValueType());
7650   return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef,
7651                  MemVT, MMO);
7652 }
7653 
7654 SDValue SelectionDAG::getIndexedLoad(SDValue OrigLoad, const SDLoc &dl,
7655                                      SDValue Base, SDValue Offset,
7656                                      ISD::MemIndexedMode AM) {
7657   LoadSDNode *LD = cast<LoadSDNode>(OrigLoad);
7658   assert(LD->getOffset().isUndef() && "Load is already a indexed load!");
7659   // Don't propagate the invariant or dereferenceable flags.
7660   auto MMOFlags =
7661       LD->getMemOperand()->getFlags() &
7662       ~(MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable);
7663   return getLoad(AM, LD->getExtensionType(), OrigLoad.getValueType(), dl,
7664                  LD->getChain(), Base, Offset, LD->getPointerInfo(),
7665                  LD->getMemoryVT(), LD->getAlign(), MMOFlags, LD->getAAInfo());
7666 }
7667 
7668 SDValue SelectionDAG::getStore(SDValue Chain, const SDLoc &dl, SDValue Val,
7669                                SDValue Ptr, MachinePointerInfo PtrInfo,
7670                                Align Alignment,
7671                                MachineMemOperand::Flags MMOFlags,
7672                                const AAMDNodes &AAInfo) {
7673   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
7674 
7675   MMOFlags |= MachineMemOperand::MOStore;
7676   assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
7677 
7678   if (PtrInfo.V.isNull())
7679     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
7680 
7681   MachineFunction &MF = getMachineFunction();
7682   uint64_t Size =
7683       MemoryLocation::getSizeOrUnknown(Val.getValueType().getStoreSize());
7684   MachineMemOperand *MMO =
7685       MF.getMachineMemOperand(PtrInfo, MMOFlags, Size, Alignment, AAInfo);
7686   return getStore(Chain, dl, Val, Ptr, MMO);
7687 }
7688 
7689 SDValue SelectionDAG::getStore(SDValue Chain, const SDLoc &dl, SDValue Val,
7690                                SDValue Ptr, MachineMemOperand *MMO) {
7691   assert(Chain.getValueType() == MVT::Other &&
7692         "Invalid chain type");
7693   EVT VT = Val.getValueType();
7694   SDVTList VTs = getVTList(MVT::Other);
7695   SDValue Undef = getUNDEF(Ptr.getValueType());
7696   SDValue Ops[] = { Chain, Val, Ptr, Undef };
7697   FoldingSetNodeID ID;
7698   AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
7699   ID.AddInteger(VT.getRawBits());
7700   ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>(
7701       dl.getIROrder(), VTs, ISD::UNINDEXED, false, VT, MMO));
7702   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7703   void *IP = nullptr;
7704   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7705     cast<StoreSDNode>(E)->refineAlignment(MMO);
7706     return SDValue(E, 0);
7707   }
7708   auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
7709                                    ISD::UNINDEXED, false, VT, MMO);
7710   createOperands(N, Ops);
7711 
7712   CSEMap.InsertNode(N, IP);
7713   InsertNode(N);
7714   SDValue V(N, 0);
7715   NewSDValueDbgMsg(V, "Creating new node: ", this);
7716   return V;
7717 }
7718 
7719 SDValue SelectionDAG::getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val,
7720                                     SDValue Ptr, MachinePointerInfo PtrInfo,
7721                                     EVT SVT, Align Alignment,
7722                                     MachineMemOperand::Flags MMOFlags,
7723                                     const AAMDNodes &AAInfo) {
7724   assert(Chain.getValueType() == MVT::Other &&
7725         "Invalid chain type");
7726 
7727   MMOFlags |= MachineMemOperand::MOStore;
7728   assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
7729 
7730   if (PtrInfo.V.isNull())
7731     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
7732 
7733   MachineFunction &MF = getMachineFunction();
7734   MachineMemOperand *MMO = MF.getMachineMemOperand(
7735       PtrInfo, MMOFlags, MemoryLocation::getSizeOrUnknown(SVT.getStoreSize()),
7736       Alignment, AAInfo);
7737   return getTruncStore(Chain, dl, Val, Ptr, SVT, MMO);
7738 }
7739 
7740 SDValue SelectionDAG::getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val,
7741                                     SDValue Ptr, EVT SVT,
7742                                     MachineMemOperand *MMO) {
7743   EVT VT = Val.getValueType();
7744 
7745   assert(Chain.getValueType() == MVT::Other &&
7746         "Invalid chain type");
7747   if (VT == SVT)
7748     return getStore(Chain, dl, Val, Ptr, MMO);
7749 
7750   assert(SVT.getScalarType().bitsLT(VT.getScalarType()) &&
7751          "Should only be a truncating store, not extending!");
7752   assert(VT.isInteger() == SVT.isInteger() &&
7753          "Can't do FP-INT conversion!");
7754   assert(VT.isVector() == SVT.isVector() &&
7755          "Cannot use trunc store to convert to or from a vector!");
7756   assert((!VT.isVector() ||
7757           VT.getVectorElementCount() == SVT.getVectorElementCount()) &&
7758          "Cannot use trunc store to change the number of vector elements!");
7759 
7760   SDVTList VTs = getVTList(MVT::Other);
7761   SDValue Undef = getUNDEF(Ptr.getValueType());
7762   SDValue Ops[] = { Chain, Val, Ptr, Undef };
7763   FoldingSetNodeID ID;
7764   AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
7765   ID.AddInteger(SVT.getRawBits());
7766   ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>(
7767       dl.getIROrder(), VTs, ISD::UNINDEXED, true, SVT, MMO));
7768   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7769   void *IP = nullptr;
7770   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7771     cast<StoreSDNode>(E)->refineAlignment(MMO);
7772     return SDValue(E, 0);
7773   }
7774   auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
7775                                    ISD::UNINDEXED, true, SVT, MMO);
7776   createOperands(N, Ops);
7777 
7778   CSEMap.InsertNode(N, IP);
7779   InsertNode(N);
7780   SDValue V(N, 0);
7781   NewSDValueDbgMsg(V, "Creating new node: ", this);
7782   return V;
7783 }
7784 
7785 SDValue SelectionDAG::getIndexedStore(SDValue OrigStore, const SDLoc &dl,
7786                                       SDValue Base, SDValue Offset,
7787                                       ISD::MemIndexedMode AM) {
7788   StoreSDNode *ST = cast<StoreSDNode>(OrigStore);
7789   assert(ST->getOffset().isUndef() && "Store is already a indexed store!");
7790   SDVTList VTs = getVTList(Base.getValueType(), MVT::Other);
7791   SDValue Ops[] = { ST->getChain(), ST->getValue(), Base, Offset };
7792   FoldingSetNodeID ID;
7793   AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
7794   ID.AddInteger(ST->getMemoryVT().getRawBits());
7795   ID.AddInteger(ST->getRawSubclassData());
7796   ID.AddInteger(ST->getPointerInfo().getAddrSpace());
7797   void *IP = nullptr;
7798   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
7799     return SDValue(E, 0);
7800 
7801   auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
7802                                    ST->isTruncatingStore(), ST->getMemoryVT(),
7803                                    ST->getMemOperand());
7804   createOperands(N, Ops);
7805 
7806   CSEMap.InsertNode(N, IP);
7807   InsertNode(N);
7808   SDValue V(N, 0);
7809   NewSDValueDbgMsg(V, "Creating new node: ", this);
7810   return V;
7811 }
7812 
7813 SDValue SelectionDAG::getLoadVP(
7814     ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, EVT VT, const SDLoc &dl,
7815     SDValue Chain, SDValue Ptr, SDValue Offset, SDValue Mask, SDValue EVL,
7816     MachinePointerInfo PtrInfo, EVT MemVT, Align Alignment,
7817     MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo,
7818     const MDNode *Ranges, bool IsExpanding) {
7819   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
7820 
7821   MMOFlags |= MachineMemOperand::MOLoad;
7822   assert((MMOFlags & MachineMemOperand::MOStore) == 0);
7823   // If we don't have a PtrInfo, infer the trivial frame index case to simplify
7824   // clients.
7825   if (PtrInfo.V.isNull())
7826     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr, Offset);
7827 
7828   uint64_t Size = MemoryLocation::getSizeOrUnknown(MemVT.getStoreSize());
7829   MachineFunction &MF = getMachineFunction();
7830   MachineMemOperand *MMO = MF.getMachineMemOperand(PtrInfo, MMOFlags, Size,
7831                                                    Alignment, AAInfo, Ranges);
7832   return getLoadVP(AM, ExtType, VT, dl, Chain, Ptr, Offset, Mask, EVL, MemVT,
7833                    MMO, IsExpanding);
7834 }
7835 
7836 SDValue SelectionDAG::getLoadVP(ISD::MemIndexedMode AM,
7837                                 ISD::LoadExtType ExtType, EVT VT,
7838                                 const SDLoc &dl, SDValue Chain, SDValue Ptr,
7839                                 SDValue Offset, SDValue Mask, SDValue EVL,
7840                                 EVT MemVT, MachineMemOperand *MMO,
7841                                 bool IsExpanding) {
7842   bool Indexed = AM != ISD::UNINDEXED;
7843   assert((Indexed || Offset.isUndef()) && "Unindexed load with an offset!");
7844 
7845   SDVTList VTs = Indexed ? getVTList(VT, Ptr.getValueType(), MVT::Other)
7846                          : getVTList(VT, MVT::Other);
7847   SDValue Ops[] = {Chain, Ptr, Offset, Mask, EVL};
7848   FoldingSetNodeID ID;
7849   AddNodeIDNode(ID, ISD::VP_LOAD, VTs, Ops);
7850   ID.AddInteger(VT.getRawBits());
7851   ID.AddInteger(getSyntheticNodeSubclassData<VPLoadSDNode>(
7852       dl.getIROrder(), VTs, AM, ExtType, IsExpanding, MemVT, MMO));
7853   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7854   void *IP = nullptr;
7855   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7856     cast<VPLoadSDNode>(E)->refineAlignment(MMO);
7857     return SDValue(E, 0);
7858   }
7859   auto *N = newSDNode<VPLoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
7860                                     ExtType, IsExpanding, MemVT, MMO);
7861   createOperands(N, Ops);
7862 
7863   CSEMap.InsertNode(N, IP);
7864   InsertNode(N);
7865   SDValue V(N, 0);
7866   NewSDValueDbgMsg(V, "Creating new node: ", this);
7867   return V;
7868 }
7869 
7870 SDValue SelectionDAG::getLoadVP(EVT VT, const SDLoc &dl, SDValue Chain,
7871                                 SDValue Ptr, SDValue Mask, SDValue EVL,
7872                                 MachinePointerInfo PtrInfo,
7873                                 MaybeAlign Alignment,
7874                                 MachineMemOperand::Flags MMOFlags,
7875                                 const AAMDNodes &AAInfo, const MDNode *Ranges,
7876                                 bool IsExpanding) {
7877   SDValue Undef = getUNDEF(Ptr.getValueType());
7878   return getLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
7879                    Mask, EVL, PtrInfo, VT, Alignment, MMOFlags, AAInfo, Ranges,
7880                    IsExpanding);
7881 }
7882 
7883 SDValue SelectionDAG::getLoadVP(EVT VT, const SDLoc &dl, SDValue Chain,
7884                                 SDValue Ptr, SDValue Mask, SDValue EVL,
7885                                 MachineMemOperand *MMO, bool IsExpanding) {
7886   SDValue Undef = getUNDEF(Ptr.getValueType());
7887   return getLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
7888                    Mask, EVL, VT, MMO, IsExpanding);
7889 }
7890 
7891 SDValue SelectionDAG::getExtLoadVP(ISD::LoadExtType ExtType, const SDLoc &dl,
7892                                    EVT VT, SDValue Chain, SDValue Ptr,
7893                                    SDValue Mask, SDValue EVL,
7894                                    MachinePointerInfo PtrInfo, EVT MemVT,
7895                                    MaybeAlign Alignment,
7896                                    MachineMemOperand::Flags MMOFlags,
7897                                    const AAMDNodes &AAInfo, bool IsExpanding) {
7898   SDValue Undef = getUNDEF(Ptr.getValueType());
7899   return getLoadVP(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, Mask,
7900                    EVL, PtrInfo, MemVT, Alignment, MMOFlags, AAInfo, nullptr,
7901                    IsExpanding);
7902 }
7903 
7904 SDValue SelectionDAG::getExtLoadVP(ISD::LoadExtType ExtType, const SDLoc &dl,
7905                                    EVT VT, SDValue Chain, SDValue Ptr,
7906                                    SDValue Mask, SDValue EVL, EVT MemVT,
7907                                    MachineMemOperand *MMO, bool IsExpanding) {
7908   SDValue Undef = getUNDEF(Ptr.getValueType());
7909   return getLoadVP(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, Mask,
7910                    EVL, MemVT, MMO, IsExpanding);
7911 }
7912 
7913 SDValue SelectionDAG::getIndexedLoadVP(SDValue OrigLoad, const SDLoc &dl,
7914                                        SDValue Base, SDValue Offset,
7915                                        ISD::MemIndexedMode AM) {
7916   auto *LD = cast<VPLoadSDNode>(OrigLoad);
7917   assert(LD->getOffset().isUndef() && "Load is already a indexed load!");
7918   // Don't propagate the invariant or dereferenceable flags.
7919   auto MMOFlags =
7920       LD->getMemOperand()->getFlags() &
7921       ~(MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable);
7922   return getLoadVP(AM, LD->getExtensionType(), OrigLoad.getValueType(), dl,
7923                    LD->getChain(), Base, Offset, LD->getMask(),
7924                    LD->getVectorLength(), LD->getPointerInfo(),
7925                    LD->getMemoryVT(), LD->getAlign(), MMOFlags, LD->getAAInfo(),
7926                    nullptr, LD->isExpandingLoad());
7927 }
7928 
7929 SDValue SelectionDAG::getStoreVP(SDValue Chain, const SDLoc &dl, SDValue Val,
7930                                  SDValue Ptr, SDValue Offset, SDValue Mask,
7931                                  SDValue EVL, EVT MemVT, MachineMemOperand *MMO,
7932                                  ISD::MemIndexedMode AM, bool IsTruncating,
7933                                  bool IsCompressing) {
7934   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
7935   bool Indexed = AM != ISD::UNINDEXED;
7936   assert((Indexed || Offset.isUndef()) && "Unindexed vp_store with an offset!");
7937   SDVTList VTs = Indexed ? getVTList(Ptr.getValueType(), MVT::Other)
7938                          : getVTList(MVT::Other);
7939   SDValue Ops[] = {Chain, Val, Ptr, Offset, Mask, EVL};
7940   FoldingSetNodeID ID;
7941   AddNodeIDNode(ID, ISD::VP_STORE, VTs, Ops);
7942   ID.AddInteger(MemVT.getRawBits());
7943   ID.AddInteger(getSyntheticNodeSubclassData<VPStoreSDNode>(
7944       dl.getIROrder(), VTs, AM, IsTruncating, IsCompressing, MemVT, MMO));
7945   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7946   void *IP = nullptr;
7947   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7948     cast<VPStoreSDNode>(E)->refineAlignment(MMO);
7949     return SDValue(E, 0);
7950   }
7951   auto *N = newSDNode<VPStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
7952                                      IsTruncating, IsCompressing, MemVT, MMO);
7953   createOperands(N, Ops);
7954 
7955   CSEMap.InsertNode(N, IP);
7956   InsertNode(N);
7957   SDValue V(N, 0);
7958   NewSDValueDbgMsg(V, "Creating new node: ", this);
7959   return V;
7960 }
7961 
7962 SDValue SelectionDAG::getTruncStoreVP(SDValue Chain, const SDLoc &dl,
7963                                       SDValue Val, SDValue Ptr, SDValue Mask,
7964                                       SDValue EVL, MachinePointerInfo PtrInfo,
7965                                       EVT SVT, Align Alignment,
7966                                       MachineMemOperand::Flags MMOFlags,
7967                                       const AAMDNodes &AAInfo,
7968                                       bool IsCompressing) {
7969   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
7970 
7971   MMOFlags |= MachineMemOperand::MOStore;
7972   assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
7973 
7974   if (PtrInfo.V.isNull())
7975     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
7976 
7977   MachineFunction &MF = getMachineFunction();
7978   MachineMemOperand *MMO = MF.getMachineMemOperand(
7979       PtrInfo, MMOFlags, MemoryLocation::getSizeOrUnknown(SVT.getStoreSize()),
7980       Alignment, AAInfo);
7981   return getTruncStoreVP(Chain, dl, Val, Ptr, Mask, EVL, SVT, MMO,
7982                          IsCompressing);
7983 }
7984 
7985 SDValue SelectionDAG::getTruncStoreVP(SDValue Chain, const SDLoc &dl,
7986                                       SDValue Val, SDValue Ptr, SDValue Mask,
7987                                       SDValue EVL, EVT SVT,
7988                                       MachineMemOperand *MMO,
7989                                       bool IsCompressing) {
7990   EVT VT = Val.getValueType();
7991 
7992   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
7993   if (VT == SVT)
7994     return getStoreVP(Chain, dl, Val, Ptr, getUNDEF(Ptr.getValueType()), Mask,
7995                       EVL, VT, MMO, ISD::UNINDEXED,
7996                       /*IsTruncating*/ false, IsCompressing);
7997 
7998   assert(SVT.getScalarType().bitsLT(VT.getScalarType()) &&
7999          "Should only be a truncating store, not extending!");
8000   assert(VT.isInteger() == SVT.isInteger() && "Can't do FP-INT conversion!");
8001   assert(VT.isVector() == SVT.isVector() &&
8002          "Cannot use trunc store to convert to or from a vector!");
8003   assert((!VT.isVector() ||
8004           VT.getVectorElementCount() == SVT.getVectorElementCount()) &&
8005          "Cannot use trunc store to change the number of vector elements!");
8006 
8007   SDVTList VTs = getVTList(MVT::Other);
8008   SDValue Undef = getUNDEF(Ptr.getValueType());
8009   SDValue Ops[] = {Chain, Val, Ptr, Undef, Mask, EVL};
8010   FoldingSetNodeID ID;
8011   AddNodeIDNode(ID, ISD::VP_STORE, VTs, Ops);
8012   ID.AddInteger(SVT.getRawBits());
8013   ID.AddInteger(getSyntheticNodeSubclassData<VPStoreSDNode>(
8014       dl.getIROrder(), VTs, ISD::UNINDEXED, true, IsCompressing, SVT, MMO));
8015   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8016   void *IP = nullptr;
8017   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
8018     cast<VPStoreSDNode>(E)->refineAlignment(MMO);
8019     return SDValue(E, 0);
8020   }
8021   auto *N =
8022       newSDNode<VPStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
8023                                ISD::UNINDEXED, true, IsCompressing, SVT, MMO);
8024   createOperands(N, Ops);
8025 
8026   CSEMap.InsertNode(N, IP);
8027   InsertNode(N);
8028   SDValue V(N, 0);
8029   NewSDValueDbgMsg(V, "Creating new node: ", this);
8030   return V;
8031 }
8032 
8033 SDValue SelectionDAG::getIndexedStoreVP(SDValue OrigStore, const SDLoc &dl,
8034                                         SDValue Base, SDValue Offset,
8035                                         ISD::MemIndexedMode AM) {
8036   auto *ST = cast<VPStoreSDNode>(OrigStore);
8037   assert(ST->getOffset().isUndef() && "Store is already an indexed store!");
8038   SDVTList VTs = getVTList(Base.getValueType(), MVT::Other);
8039   SDValue Ops[] = {ST->getChain(), ST->getValue(), Base,
8040                    Offset,         ST->getMask(),  ST->getVectorLength()};
8041   FoldingSetNodeID ID;
8042   AddNodeIDNode(ID, ISD::VP_STORE, VTs, Ops);
8043   ID.AddInteger(ST->getMemoryVT().getRawBits());
8044   ID.AddInteger(ST->getRawSubclassData());
8045   ID.AddInteger(ST->getPointerInfo().getAddrSpace());
8046   void *IP = nullptr;
8047   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
8048     return SDValue(E, 0);
8049 
8050   auto *N = newSDNode<VPStoreSDNode>(
8051       dl.getIROrder(), dl.getDebugLoc(), VTs, AM, ST->isTruncatingStore(),
8052       ST->isCompressingStore(), ST->getMemoryVT(), ST->getMemOperand());
8053   createOperands(N, Ops);
8054 
8055   CSEMap.InsertNode(N, IP);
8056   InsertNode(N);
8057   SDValue V(N, 0);
8058   NewSDValueDbgMsg(V, "Creating new node: ", this);
8059   return V;
8060 }
8061 
8062 SDValue SelectionDAG::getGatherVP(SDVTList VTs, EVT VT, const SDLoc &dl,
8063                                   ArrayRef<SDValue> Ops, MachineMemOperand *MMO,
8064                                   ISD::MemIndexType IndexType) {
8065   assert(Ops.size() == 6 && "Incompatible number of operands");
8066 
8067   FoldingSetNodeID ID;
8068   AddNodeIDNode(ID, ISD::VP_GATHER, VTs, Ops);
8069   ID.AddInteger(VT.getRawBits());
8070   ID.AddInteger(getSyntheticNodeSubclassData<VPGatherSDNode>(
8071       dl.getIROrder(), VTs, VT, MMO, IndexType));
8072   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8073   void *IP = nullptr;
8074   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
8075     cast<VPGatherSDNode>(E)->refineAlignment(MMO);
8076     return SDValue(E, 0);
8077   }
8078 
8079   auto *N = newSDNode<VPGatherSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
8080                                       VT, MMO, IndexType);
8081   createOperands(N, Ops);
8082 
8083   assert(N->getMask().getValueType().getVectorElementCount() ==
8084              N->getValueType(0).getVectorElementCount() &&
8085          "Vector width mismatch between mask and data");
8086   assert(N->getIndex().getValueType().getVectorElementCount().isScalable() ==
8087              N->getValueType(0).getVectorElementCount().isScalable() &&
8088          "Scalable flags of index and data do not match");
8089   assert(ElementCount::isKnownGE(
8090              N->getIndex().getValueType().getVectorElementCount(),
8091              N->getValueType(0).getVectorElementCount()) &&
8092          "Vector width mismatch between index and data");
8093   assert(isa<ConstantSDNode>(N->getScale()) &&
8094          cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() &&
8095          "Scale should be a constant power of 2");
8096 
8097   CSEMap.InsertNode(N, IP);
8098   InsertNode(N);
8099   SDValue V(N, 0);
8100   NewSDValueDbgMsg(V, "Creating new node: ", this);
8101   return V;
8102 }
8103 
8104 SDValue SelectionDAG::getScatterVP(SDVTList VTs, EVT VT, const SDLoc &dl,
8105                                    ArrayRef<SDValue> Ops,
8106                                    MachineMemOperand *MMO,
8107                                    ISD::MemIndexType IndexType) {
8108   assert(Ops.size() == 7 && "Incompatible number of operands");
8109 
8110   FoldingSetNodeID ID;
8111   AddNodeIDNode(ID, ISD::VP_SCATTER, VTs, Ops);
8112   ID.AddInteger(VT.getRawBits());
8113   ID.AddInteger(getSyntheticNodeSubclassData<VPScatterSDNode>(
8114       dl.getIROrder(), VTs, VT, MMO, IndexType));
8115   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8116   void *IP = nullptr;
8117   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
8118     cast<VPScatterSDNode>(E)->refineAlignment(MMO);
8119     return SDValue(E, 0);
8120   }
8121   auto *N = newSDNode<VPScatterSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
8122                                        VT, MMO, IndexType);
8123   createOperands(N, Ops);
8124 
8125   assert(N->getMask().getValueType().getVectorElementCount() ==
8126              N->getValue().getValueType().getVectorElementCount() &&
8127          "Vector width mismatch between mask and data");
8128   assert(
8129       N->getIndex().getValueType().getVectorElementCount().isScalable() ==
8130           N->getValue().getValueType().getVectorElementCount().isScalable() &&
8131       "Scalable flags of index and data do not match");
8132   assert(ElementCount::isKnownGE(
8133              N->getIndex().getValueType().getVectorElementCount(),
8134              N->getValue().getValueType().getVectorElementCount()) &&
8135          "Vector width mismatch between index and data");
8136   assert(isa<ConstantSDNode>(N->getScale()) &&
8137          cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() &&
8138          "Scale should be a constant power of 2");
8139 
8140   CSEMap.InsertNode(N, IP);
8141   InsertNode(N);
8142   SDValue V(N, 0);
8143   NewSDValueDbgMsg(V, "Creating new node: ", this);
8144   return V;
8145 }
8146 
8147 SDValue SelectionDAG::getMaskedLoad(EVT VT, const SDLoc &dl, SDValue Chain,
8148                                     SDValue Base, SDValue Offset, SDValue Mask,
8149                                     SDValue PassThru, EVT MemVT,
8150                                     MachineMemOperand *MMO,
8151                                     ISD::MemIndexedMode AM,
8152                                     ISD::LoadExtType ExtTy, bool isExpanding) {
8153   bool Indexed = AM != ISD::UNINDEXED;
8154   assert((Indexed || Offset.isUndef()) &&
8155          "Unindexed masked load with an offset!");
8156   SDVTList VTs = Indexed ? getVTList(VT, Base.getValueType(), MVT::Other)
8157                          : getVTList(VT, MVT::Other);
8158   SDValue Ops[] = {Chain, Base, Offset, Mask, PassThru};
8159   FoldingSetNodeID ID;
8160   AddNodeIDNode(ID, ISD::MLOAD, VTs, Ops);
8161   ID.AddInteger(MemVT.getRawBits());
8162   ID.AddInteger(getSyntheticNodeSubclassData<MaskedLoadSDNode>(
8163       dl.getIROrder(), VTs, AM, ExtTy, isExpanding, MemVT, MMO));
8164   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8165   void *IP = nullptr;
8166   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
8167     cast<MaskedLoadSDNode>(E)->refineAlignment(MMO);
8168     return SDValue(E, 0);
8169   }
8170   auto *N = newSDNode<MaskedLoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
8171                                         AM, ExtTy, isExpanding, MemVT, MMO);
8172   createOperands(N, Ops);
8173 
8174   CSEMap.InsertNode(N, IP);
8175   InsertNode(N);
8176   SDValue V(N, 0);
8177   NewSDValueDbgMsg(V, "Creating new node: ", this);
8178   return V;
8179 }
8180 
8181 SDValue SelectionDAG::getIndexedMaskedLoad(SDValue OrigLoad, const SDLoc &dl,
8182                                            SDValue Base, SDValue Offset,
8183                                            ISD::MemIndexedMode AM) {
8184   MaskedLoadSDNode *LD = cast<MaskedLoadSDNode>(OrigLoad);
8185   assert(LD->getOffset().isUndef() && "Masked load is already a indexed load!");
8186   return getMaskedLoad(OrigLoad.getValueType(), dl, LD->getChain(), Base,
8187                        Offset, LD->getMask(), LD->getPassThru(),
8188                        LD->getMemoryVT(), LD->getMemOperand(), AM,
8189                        LD->getExtensionType(), LD->isExpandingLoad());
8190 }
8191 
8192 SDValue SelectionDAG::getMaskedStore(SDValue Chain, const SDLoc &dl,
8193                                      SDValue Val, SDValue Base, SDValue Offset,
8194                                      SDValue Mask, EVT MemVT,
8195                                      MachineMemOperand *MMO,
8196                                      ISD::MemIndexedMode AM, bool IsTruncating,
8197                                      bool IsCompressing) {
8198   assert(Chain.getValueType() == MVT::Other &&
8199         "Invalid chain type");
8200   bool Indexed = AM != ISD::UNINDEXED;
8201   assert((Indexed || Offset.isUndef()) &&
8202          "Unindexed masked store with an offset!");
8203   SDVTList VTs = Indexed ? getVTList(Base.getValueType(), MVT::Other)
8204                          : getVTList(MVT::Other);
8205   SDValue Ops[] = {Chain, Val, Base, Offset, Mask};
8206   FoldingSetNodeID ID;
8207   AddNodeIDNode(ID, ISD::MSTORE, VTs, Ops);
8208   ID.AddInteger(MemVT.getRawBits());
8209   ID.AddInteger(getSyntheticNodeSubclassData<MaskedStoreSDNode>(
8210       dl.getIROrder(), VTs, AM, IsTruncating, IsCompressing, MemVT, MMO));
8211   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8212   void *IP = nullptr;
8213   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
8214     cast<MaskedStoreSDNode>(E)->refineAlignment(MMO);
8215     return SDValue(E, 0);
8216   }
8217   auto *N =
8218       newSDNode<MaskedStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
8219                                    IsTruncating, IsCompressing, MemVT, MMO);
8220   createOperands(N, Ops);
8221 
8222   CSEMap.InsertNode(N, IP);
8223   InsertNode(N);
8224   SDValue V(N, 0);
8225   NewSDValueDbgMsg(V, "Creating new node: ", this);
8226   return V;
8227 }
8228 
8229 SDValue SelectionDAG::getIndexedMaskedStore(SDValue OrigStore, const SDLoc &dl,
8230                                             SDValue Base, SDValue Offset,
8231                                             ISD::MemIndexedMode AM) {
8232   MaskedStoreSDNode *ST = cast<MaskedStoreSDNode>(OrigStore);
8233   assert(ST->getOffset().isUndef() &&
8234          "Masked store is already a indexed store!");
8235   return getMaskedStore(ST->getChain(), dl, ST->getValue(), Base, Offset,
8236                         ST->getMask(), ST->getMemoryVT(), ST->getMemOperand(),
8237                         AM, ST->isTruncatingStore(), ST->isCompressingStore());
8238 }
8239 
8240 SDValue SelectionDAG::getMaskedGather(SDVTList VTs, EVT MemVT, const SDLoc &dl,
8241                                       ArrayRef<SDValue> Ops,
8242                                       MachineMemOperand *MMO,
8243                                       ISD::MemIndexType IndexType,
8244                                       ISD::LoadExtType ExtTy) {
8245   assert(Ops.size() == 6 && "Incompatible number of operands");
8246 
8247   FoldingSetNodeID ID;
8248   AddNodeIDNode(ID, ISD::MGATHER, VTs, Ops);
8249   ID.AddInteger(MemVT.getRawBits());
8250   ID.AddInteger(getSyntheticNodeSubclassData<MaskedGatherSDNode>(
8251       dl.getIROrder(), VTs, MemVT, MMO, IndexType, ExtTy));
8252   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8253   void *IP = nullptr;
8254   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
8255     cast<MaskedGatherSDNode>(E)->refineAlignment(MMO);
8256     return SDValue(E, 0);
8257   }
8258 
8259   IndexType = TLI->getCanonicalIndexType(IndexType, MemVT, Ops[4]);
8260   auto *N = newSDNode<MaskedGatherSDNode>(dl.getIROrder(), dl.getDebugLoc(),
8261                                           VTs, MemVT, MMO, IndexType, ExtTy);
8262   createOperands(N, Ops);
8263 
8264   assert(N->getPassThru().getValueType() == N->getValueType(0) &&
8265          "Incompatible type of the PassThru value in MaskedGatherSDNode");
8266   assert(N->getMask().getValueType().getVectorElementCount() ==
8267              N->getValueType(0).getVectorElementCount() &&
8268          "Vector width mismatch between mask and data");
8269   assert(N->getIndex().getValueType().getVectorElementCount().isScalable() ==
8270              N->getValueType(0).getVectorElementCount().isScalable() &&
8271          "Scalable flags of index and data do not match");
8272   assert(ElementCount::isKnownGE(
8273              N->getIndex().getValueType().getVectorElementCount(),
8274              N->getValueType(0).getVectorElementCount()) &&
8275          "Vector width mismatch between index and data");
8276   assert(isa<ConstantSDNode>(N->getScale()) &&
8277          cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() &&
8278          "Scale should be a constant power of 2");
8279 
8280   CSEMap.InsertNode(N, IP);
8281   InsertNode(N);
8282   SDValue V(N, 0);
8283   NewSDValueDbgMsg(V, "Creating new node: ", this);
8284   return V;
8285 }
8286 
8287 SDValue SelectionDAG::getMaskedScatter(SDVTList VTs, EVT MemVT, const SDLoc &dl,
8288                                        ArrayRef<SDValue> Ops,
8289                                        MachineMemOperand *MMO,
8290                                        ISD::MemIndexType IndexType,
8291                                        bool IsTrunc) {
8292   assert(Ops.size() == 6 && "Incompatible number of operands");
8293 
8294   FoldingSetNodeID ID;
8295   AddNodeIDNode(ID, ISD::MSCATTER, VTs, Ops);
8296   ID.AddInteger(MemVT.getRawBits());
8297   ID.AddInteger(getSyntheticNodeSubclassData<MaskedScatterSDNode>(
8298       dl.getIROrder(), VTs, MemVT, MMO, IndexType, IsTrunc));
8299   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8300   void *IP = nullptr;
8301   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
8302     cast<MaskedScatterSDNode>(E)->refineAlignment(MMO);
8303     return SDValue(E, 0);
8304   }
8305 
8306   IndexType = TLI->getCanonicalIndexType(IndexType, MemVT, Ops[4]);
8307   auto *N = newSDNode<MaskedScatterSDNode>(dl.getIROrder(), dl.getDebugLoc(),
8308                                            VTs, MemVT, MMO, IndexType, IsTrunc);
8309   createOperands(N, Ops);
8310 
8311   assert(N->getMask().getValueType().getVectorElementCount() ==
8312              N->getValue().getValueType().getVectorElementCount() &&
8313          "Vector width mismatch between mask and data");
8314   assert(
8315       N->getIndex().getValueType().getVectorElementCount().isScalable() ==
8316           N->getValue().getValueType().getVectorElementCount().isScalable() &&
8317       "Scalable flags of index and data do not match");
8318   assert(ElementCount::isKnownGE(
8319              N->getIndex().getValueType().getVectorElementCount(),
8320              N->getValue().getValueType().getVectorElementCount()) &&
8321          "Vector width mismatch between index and data");
8322   assert(isa<ConstantSDNode>(N->getScale()) &&
8323          cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() &&
8324          "Scale should be a constant power of 2");
8325 
8326   CSEMap.InsertNode(N, IP);
8327   InsertNode(N);
8328   SDValue V(N, 0);
8329   NewSDValueDbgMsg(V, "Creating new node: ", this);
8330   return V;
8331 }
8332 
8333 SDValue SelectionDAG::simplifySelect(SDValue Cond, SDValue T, SDValue F) {
8334   // select undef, T, F --> T (if T is a constant), otherwise F
8335   // select, ?, undef, F --> F
8336   // select, ?, T, undef --> T
8337   if (Cond.isUndef())
8338     return isConstantValueOfAnyType(T) ? T : F;
8339   if (T.isUndef())
8340     return F;
8341   if (F.isUndef())
8342     return T;
8343 
8344   // select true, T, F --> T
8345   // select false, T, F --> F
8346   if (auto *CondC = dyn_cast<ConstantSDNode>(Cond))
8347     return CondC->isZero() ? F : T;
8348 
8349   // TODO: This should simplify VSELECT with constant condition using something
8350   // like this (but check boolean contents to be complete?):
8351   //  if (ISD::isBuildVectorAllOnes(Cond.getNode()))
8352   //    return T;
8353   //  if (ISD::isBuildVectorAllZeros(Cond.getNode()))
8354   //    return F;
8355 
8356   // select ?, T, T --> T
8357   if (T == F)
8358     return T;
8359 
8360   return SDValue();
8361 }
8362 
8363 SDValue SelectionDAG::simplifyShift(SDValue X, SDValue Y) {
8364   // shift undef, Y --> 0 (can always assume that the undef value is 0)
8365   if (X.isUndef())
8366     return getConstant(0, SDLoc(X.getNode()), X.getValueType());
8367   // shift X, undef --> undef (because it may shift by the bitwidth)
8368   if (Y.isUndef())
8369     return getUNDEF(X.getValueType());
8370 
8371   // shift 0, Y --> 0
8372   // shift X, 0 --> X
8373   if (isNullOrNullSplat(X) || isNullOrNullSplat(Y))
8374     return X;
8375 
8376   // shift X, C >= bitwidth(X) --> undef
8377   // All vector elements must be too big (or undef) to avoid partial undefs.
8378   auto isShiftTooBig = [X](ConstantSDNode *Val) {
8379     return !Val || Val->getAPIntValue().uge(X.getScalarValueSizeInBits());
8380   };
8381   if (ISD::matchUnaryPredicate(Y, isShiftTooBig, true))
8382     return getUNDEF(X.getValueType());
8383 
8384   return SDValue();
8385 }
8386 
8387 SDValue SelectionDAG::simplifyFPBinop(unsigned Opcode, SDValue X, SDValue Y,
8388                                       SDNodeFlags Flags) {
8389   // If this operation has 'nnan' or 'ninf' and at least 1 disallowed operand
8390   // (an undef operand can be chosen to be Nan/Inf), then the result of this
8391   // operation is poison. That result can be relaxed to undef.
8392   ConstantFPSDNode *XC = isConstOrConstSplatFP(X, /* AllowUndefs */ true);
8393   ConstantFPSDNode *YC = isConstOrConstSplatFP(Y, /* AllowUndefs */ true);
8394   bool HasNan = (XC && XC->getValueAPF().isNaN()) ||
8395                 (YC && YC->getValueAPF().isNaN());
8396   bool HasInf = (XC && XC->getValueAPF().isInfinity()) ||
8397                 (YC && YC->getValueAPF().isInfinity());
8398 
8399   if (Flags.hasNoNaNs() && (HasNan || X.isUndef() || Y.isUndef()))
8400     return getUNDEF(X.getValueType());
8401 
8402   if (Flags.hasNoInfs() && (HasInf || X.isUndef() || Y.isUndef()))
8403     return getUNDEF(X.getValueType());
8404 
8405   if (!YC)
8406     return SDValue();
8407 
8408   // X + -0.0 --> X
8409   if (Opcode == ISD::FADD)
8410     if (YC->getValueAPF().isNegZero())
8411       return X;
8412 
8413   // X - +0.0 --> X
8414   if (Opcode == ISD::FSUB)
8415     if (YC->getValueAPF().isPosZero())
8416       return X;
8417 
8418   // X * 1.0 --> X
8419   // X / 1.0 --> X
8420   if (Opcode == ISD::FMUL || Opcode == ISD::FDIV)
8421     if (YC->getValueAPF().isExactlyValue(1.0))
8422       return X;
8423 
8424   // X * 0.0 --> 0.0
8425   if (Opcode == ISD::FMUL && Flags.hasNoNaNs() && Flags.hasNoSignedZeros())
8426     if (YC->getValueAPF().isZero())
8427       return getConstantFP(0.0, SDLoc(Y), Y.getValueType());
8428 
8429   return SDValue();
8430 }
8431 
8432 SDValue SelectionDAG::getVAArg(EVT VT, const SDLoc &dl, SDValue Chain,
8433                                SDValue Ptr, SDValue SV, unsigned Align) {
8434   SDValue Ops[] = { Chain, Ptr, SV, getTargetConstant(Align, dl, MVT::i32) };
8435   return getNode(ISD::VAARG, dl, getVTList(VT, MVT::Other), Ops);
8436 }
8437 
8438 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
8439                               ArrayRef<SDUse> Ops) {
8440   switch (Ops.size()) {
8441   case 0: return getNode(Opcode, DL, VT);
8442   case 1: return getNode(Opcode, DL, VT, static_cast<const SDValue>(Ops[0]));
8443   case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1]);
8444   case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2]);
8445   default: break;
8446   }
8447 
8448   // Copy from an SDUse array into an SDValue array for use with
8449   // the regular getNode logic.
8450   SmallVector<SDValue, 8> NewOps(Ops.begin(), Ops.end());
8451   return getNode(Opcode, DL, VT, NewOps);
8452 }
8453 
8454 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
8455                               ArrayRef<SDValue> Ops) {
8456   SDNodeFlags Flags;
8457   if (Inserter)
8458     Flags = Inserter->getFlags();
8459   return getNode(Opcode, DL, VT, Ops, Flags);
8460 }
8461 
8462 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
8463                               ArrayRef<SDValue> Ops, const SDNodeFlags Flags) {
8464   unsigned NumOps = Ops.size();
8465   switch (NumOps) {
8466   case 0: return getNode(Opcode, DL, VT);
8467   case 1: return getNode(Opcode, DL, VT, Ops[0], Flags);
8468   case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Flags);
8469   case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2], Flags);
8470   default: break;
8471   }
8472 
8473 #ifndef NDEBUG
8474   for (auto &Op : Ops)
8475     assert(Op.getOpcode() != ISD::DELETED_NODE &&
8476            "Operand is DELETED_NODE!");
8477 #endif
8478 
8479   switch (Opcode) {
8480   default: break;
8481   case ISD::BUILD_VECTOR:
8482     // Attempt to simplify BUILD_VECTOR.
8483     if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
8484       return V;
8485     break;
8486   case ISD::CONCAT_VECTORS:
8487     if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this))
8488       return V;
8489     break;
8490   case ISD::SELECT_CC:
8491     assert(NumOps == 5 && "SELECT_CC takes 5 operands!");
8492     assert(Ops[0].getValueType() == Ops[1].getValueType() &&
8493            "LHS and RHS of condition must have same type!");
8494     assert(Ops[2].getValueType() == Ops[3].getValueType() &&
8495            "True and False arms of SelectCC must have same type!");
8496     assert(Ops[2].getValueType() == VT &&
8497            "select_cc node must be of same type as true and false value!");
8498     break;
8499   case ISD::BR_CC:
8500     assert(NumOps == 5 && "BR_CC takes 5 operands!");
8501     assert(Ops[2].getValueType() == Ops[3].getValueType() &&
8502            "LHS/RHS of comparison should match types!");
8503     break;
8504   }
8505 
8506   // Memoize nodes.
8507   SDNode *N;
8508   SDVTList VTs = getVTList(VT);
8509 
8510   if (VT != MVT::Glue) {
8511     FoldingSetNodeID ID;
8512     AddNodeIDNode(ID, Opcode, VTs, Ops);
8513     void *IP = nullptr;
8514 
8515     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
8516       return SDValue(E, 0);
8517 
8518     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
8519     createOperands(N, Ops);
8520 
8521     CSEMap.InsertNode(N, IP);
8522   } else {
8523     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
8524     createOperands(N, Ops);
8525   }
8526 
8527   N->setFlags(Flags);
8528   InsertNode(N);
8529   SDValue V(N, 0);
8530   NewSDValueDbgMsg(V, "Creating new node: ", this);
8531   return V;
8532 }
8533 
8534 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL,
8535                               ArrayRef<EVT> ResultTys, ArrayRef<SDValue> Ops) {
8536   return getNode(Opcode, DL, getVTList(ResultTys), Ops);
8537 }
8538 
8539 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
8540                               ArrayRef<SDValue> Ops) {
8541   SDNodeFlags Flags;
8542   if (Inserter)
8543     Flags = Inserter->getFlags();
8544   return getNode(Opcode, DL, VTList, Ops, Flags);
8545 }
8546 
8547 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
8548                               ArrayRef<SDValue> Ops, const SDNodeFlags Flags) {
8549   if (VTList.NumVTs == 1)
8550     return getNode(Opcode, DL, VTList.VTs[0], Ops);
8551 
8552 #ifndef NDEBUG
8553   for (auto &Op : Ops)
8554     assert(Op.getOpcode() != ISD::DELETED_NODE &&
8555            "Operand is DELETED_NODE!");
8556 #endif
8557 
8558   switch (Opcode) {
8559   case ISD::STRICT_FP_EXTEND:
8560     assert(VTList.NumVTs == 2 && Ops.size() == 2 &&
8561            "Invalid STRICT_FP_EXTEND!");
8562     assert(VTList.VTs[0].isFloatingPoint() &&
8563            Ops[1].getValueType().isFloatingPoint() && "Invalid FP cast!");
8564     assert(VTList.VTs[0].isVector() == Ops[1].getValueType().isVector() &&
8565            "STRICT_FP_EXTEND result type should be vector iff the operand "
8566            "type is vector!");
8567     assert((!VTList.VTs[0].isVector() ||
8568             VTList.VTs[0].getVectorNumElements() ==
8569             Ops[1].getValueType().getVectorNumElements()) &&
8570            "Vector element count mismatch!");
8571     assert(Ops[1].getValueType().bitsLT(VTList.VTs[0]) &&
8572            "Invalid fpext node, dst <= src!");
8573     break;
8574   case ISD::STRICT_FP_ROUND:
8575     assert(VTList.NumVTs == 2 && Ops.size() == 3 && "Invalid STRICT_FP_ROUND!");
8576     assert(VTList.VTs[0].isVector() == Ops[1].getValueType().isVector() &&
8577            "STRICT_FP_ROUND result type should be vector iff the operand "
8578            "type is vector!");
8579     assert((!VTList.VTs[0].isVector() ||
8580             VTList.VTs[0].getVectorNumElements() ==
8581             Ops[1].getValueType().getVectorNumElements()) &&
8582            "Vector element count mismatch!");
8583     assert(VTList.VTs[0].isFloatingPoint() &&
8584            Ops[1].getValueType().isFloatingPoint() &&
8585            VTList.VTs[0].bitsLT(Ops[1].getValueType()) &&
8586            isa<ConstantSDNode>(Ops[2]) &&
8587            (cast<ConstantSDNode>(Ops[2])->getZExtValue() == 0 ||
8588             cast<ConstantSDNode>(Ops[2])->getZExtValue() == 1) &&
8589            "Invalid STRICT_FP_ROUND!");
8590     break;
8591 #if 0
8592   // FIXME: figure out how to safely handle things like
8593   // int foo(int x) { return 1 << (x & 255); }
8594   // int bar() { return foo(256); }
8595   case ISD::SRA_PARTS:
8596   case ISD::SRL_PARTS:
8597   case ISD::SHL_PARTS:
8598     if (N3.getOpcode() == ISD::SIGN_EXTEND_INREG &&
8599         cast<VTSDNode>(N3.getOperand(1))->getVT() != MVT::i1)
8600       return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0));
8601     else if (N3.getOpcode() == ISD::AND)
8602       if (ConstantSDNode *AndRHS = dyn_cast<ConstantSDNode>(N3.getOperand(1))) {
8603         // If the and is only masking out bits that cannot effect the shift,
8604         // eliminate the and.
8605         unsigned NumBits = VT.getScalarSizeInBits()*2;
8606         if ((AndRHS->getValue() & (NumBits-1)) == NumBits-1)
8607           return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0));
8608       }
8609     break;
8610 #endif
8611   }
8612 
8613   // Memoize the node unless it returns a flag.
8614   SDNode *N;
8615   if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) {
8616     FoldingSetNodeID ID;
8617     AddNodeIDNode(ID, Opcode, VTList, Ops);
8618     void *IP = nullptr;
8619     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
8620       return SDValue(E, 0);
8621 
8622     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList);
8623     createOperands(N, Ops);
8624     CSEMap.InsertNode(N, IP);
8625   } else {
8626     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList);
8627     createOperands(N, Ops);
8628   }
8629 
8630   N->setFlags(Flags);
8631   InsertNode(N);
8632   SDValue V(N, 0);
8633   NewSDValueDbgMsg(V, "Creating new node: ", this);
8634   return V;
8635 }
8636 
8637 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL,
8638                               SDVTList VTList) {
8639   return getNode(Opcode, DL, VTList, None);
8640 }
8641 
8642 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
8643                               SDValue N1) {
8644   SDValue Ops[] = { N1 };
8645   return getNode(Opcode, DL, VTList, Ops);
8646 }
8647 
8648 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
8649                               SDValue N1, SDValue N2) {
8650   SDValue Ops[] = { N1, N2 };
8651   return getNode(Opcode, DL, VTList, Ops);
8652 }
8653 
8654 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
8655                               SDValue N1, SDValue N2, SDValue N3) {
8656   SDValue Ops[] = { N1, N2, N3 };
8657   return getNode(Opcode, DL, VTList, Ops);
8658 }
8659 
8660 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
8661                               SDValue N1, SDValue N2, SDValue N3, SDValue N4) {
8662   SDValue Ops[] = { N1, N2, N3, N4 };
8663   return getNode(Opcode, DL, VTList, Ops);
8664 }
8665 
8666 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
8667                               SDValue N1, SDValue N2, SDValue N3, SDValue N4,
8668                               SDValue N5) {
8669   SDValue Ops[] = { N1, N2, N3, N4, N5 };
8670   return getNode(Opcode, DL, VTList, Ops);
8671 }
8672 
8673 SDVTList SelectionDAG::getVTList(EVT VT) {
8674   return makeVTList(SDNode::getValueTypeList(VT), 1);
8675 }
8676 
8677 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2) {
8678   FoldingSetNodeID ID;
8679   ID.AddInteger(2U);
8680   ID.AddInteger(VT1.getRawBits());
8681   ID.AddInteger(VT2.getRawBits());
8682 
8683   void *IP = nullptr;
8684   SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
8685   if (!Result) {
8686     EVT *Array = Allocator.Allocate<EVT>(2);
8687     Array[0] = VT1;
8688     Array[1] = VT2;
8689     Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 2);
8690     VTListMap.InsertNode(Result, IP);
8691   }
8692   return Result->getSDVTList();
8693 }
8694 
8695 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3) {
8696   FoldingSetNodeID ID;
8697   ID.AddInteger(3U);
8698   ID.AddInteger(VT1.getRawBits());
8699   ID.AddInteger(VT2.getRawBits());
8700   ID.AddInteger(VT3.getRawBits());
8701 
8702   void *IP = nullptr;
8703   SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
8704   if (!Result) {
8705     EVT *Array = Allocator.Allocate<EVT>(3);
8706     Array[0] = VT1;
8707     Array[1] = VT2;
8708     Array[2] = VT3;
8709     Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 3);
8710     VTListMap.InsertNode(Result, IP);
8711   }
8712   return Result->getSDVTList();
8713 }
8714 
8715 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3, EVT VT4) {
8716   FoldingSetNodeID ID;
8717   ID.AddInteger(4U);
8718   ID.AddInteger(VT1.getRawBits());
8719   ID.AddInteger(VT2.getRawBits());
8720   ID.AddInteger(VT3.getRawBits());
8721   ID.AddInteger(VT4.getRawBits());
8722 
8723   void *IP = nullptr;
8724   SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
8725   if (!Result) {
8726     EVT *Array = Allocator.Allocate<EVT>(4);
8727     Array[0] = VT1;
8728     Array[1] = VT2;
8729     Array[2] = VT3;
8730     Array[3] = VT4;
8731     Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 4);
8732     VTListMap.InsertNode(Result, IP);
8733   }
8734   return Result->getSDVTList();
8735 }
8736 
8737 SDVTList SelectionDAG::getVTList(ArrayRef<EVT> VTs) {
8738   unsigned NumVTs = VTs.size();
8739   FoldingSetNodeID ID;
8740   ID.AddInteger(NumVTs);
8741   for (unsigned index = 0; index < NumVTs; index++) {
8742     ID.AddInteger(VTs[index].getRawBits());
8743   }
8744 
8745   void *IP = nullptr;
8746   SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
8747   if (!Result) {
8748     EVT *Array = Allocator.Allocate<EVT>(NumVTs);
8749     llvm::copy(VTs, Array);
8750     Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, NumVTs);
8751     VTListMap.InsertNode(Result, IP);
8752   }
8753   return Result->getSDVTList();
8754 }
8755 
8756 
8757 /// UpdateNodeOperands - *Mutate* the specified node in-place to have the
8758 /// specified operands.  If the resultant node already exists in the DAG,
8759 /// this does not modify the specified node, instead it returns the node that
8760 /// already exists.  If the resultant node does not exist in the DAG, the
8761 /// input node is returned.  As a degenerate case, if you specify the same
8762 /// input operands as the node already has, the input node is returned.
8763 SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op) {
8764   assert(N->getNumOperands() == 1 && "Update with wrong number of operands");
8765 
8766   // Check to see if there is no change.
8767   if (Op == N->getOperand(0)) return N;
8768 
8769   // See if the modified node already exists.
8770   void *InsertPos = nullptr;
8771   if (SDNode *Existing = FindModifiedNodeSlot(N, Op, InsertPos))
8772     return Existing;
8773 
8774   // Nope it doesn't.  Remove the node from its current place in the maps.
8775   if (InsertPos)
8776     if (!RemoveNodeFromCSEMaps(N))
8777       InsertPos = nullptr;
8778 
8779   // Now we update the operands.
8780   N->OperandList[0].set(Op);
8781 
8782   updateDivergence(N);
8783   // If this gets put into a CSE map, add it.
8784   if (InsertPos) CSEMap.InsertNode(N, InsertPos);
8785   return N;
8786 }
8787 
8788 SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2) {
8789   assert(N->getNumOperands() == 2 && "Update with wrong number of operands");
8790 
8791   // Check to see if there is no change.
8792   if (Op1 == N->getOperand(0) && Op2 == N->getOperand(1))
8793     return N;   // No operands changed, just return the input node.
8794 
8795   // See if the modified node already exists.
8796   void *InsertPos = nullptr;
8797   if (SDNode *Existing = FindModifiedNodeSlot(N, Op1, Op2, InsertPos))
8798     return Existing;
8799 
8800   // Nope it doesn't.  Remove the node from its current place in the maps.
8801   if (InsertPos)
8802     if (!RemoveNodeFromCSEMaps(N))
8803       InsertPos = nullptr;
8804 
8805   // Now we update the operands.
8806   if (N->OperandList[0] != Op1)
8807     N->OperandList[0].set(Op1);
8808   if (N->OperandList[1] != Op2)
8809     N->OperandList[1].set(Op2);
8810 
8811   updateDivergence(N);
8812   // If this gets put into a CSE map, add it.
8813   if (InsertPos) CSEMap.InsertNode(N, InsertPos);
8814   return N;
8815 }
8816 
8817 SDNode *SelectionDAG::
8818 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2, SDValue Op3) {
8819   SDValue Ops[] = { Op1, Op2, Op3 };
8820   return UpdateNodeOperands(N, Ops);
8821 }
8822 
8823 SDNode *SelectionDAG::
8824 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2,
8825                    SDValue Op3, SDValue Op4) {
8826   SDValue Ops[] = { Op1, Op2, Op3, Op4 };
8827   return UpdateNodeOperands(N, Ops);
8828 }
8829 
8830 SDNode *SelectionDAG::
8831 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2,
8832                    SDValue Op3, SDValue Op4, SDValue Op5) {
8833   SDValue Ops[] = { Op1, Op2, Op3, Op4, Op5 };
8834   return UpdateNodeOperands(N, Ops);
8835 }
8836 
8837 SDNode *SelectionDAG::
8838 UpdateNodeOperands(SDNode *N, ArrayRef<SDValue> Ops) {
8839   unsigned NumOps = Ops.size();
8840   assert(N->getNumOperands() == NumOps &&
8841          "Update with wrong number of operands");
8842 
8843   // If no operands changed just return the input node.
8844   if (std::equal(Ops.begin(), Ops.end(), N->op_begin()))
8845     return N;
8846 
8847   // See if the modified node already exists.
8848   void *InsertPos = nullptr;
8849   if (SDNode *Existing = FindModifiedNodeSlot(N, Ops, InsertPos))
8850     return Existing;
8851 
8852   // Nope it doesn't.  Remove the node from its current place in the maps.
8853   if (InsertPos)
8854     if (!RemoveNodeFromCSEMaps(N))
8855       InsertPos = nullptr;
8856 
8857   // Now we update the operands.
8858   for (unsigned i = 0; i != NumOps; ++i)
8859     if (N->OperandList[i] != Ops[i])
8860       N->OperandList[i].set(Ops[i]);
8861 
8862   updateDivergence(N);
8863   // If this gets put into a CSE map, add it.
8864   if (InsertPos) CSEMap.InsertNode(N, InsertPos);
8865   return N;
8866 }
8867 
8868 /// DropOperands - Release the operands and set this node to have
8869 /// zero operands.
8870 void SDNode::DropOperands() {
8871   // Unlike the code in MorphNodeTo that does this, we don't need to
8872   // watch for dead nodes here.
8873   for (op_iterator I = op_begin(), E = op_end(); I != E; ) {
8874     SDUse &Use = *I++;
8875     Use.set(SDValue());
8876   }
8877 }
8878 
8879 void SelectionDAG::setNodeMemRefs(MachineSDNode *N,
8880                                   ArrayRef<MachineMemOperand *> NewMemRefs) {
8881   if (NewMemRefs.empty()) {
8882     N->clearMemRefs();
8883     return;
8884   }
8885 
8886   // Check if we can avoid allocating by storing a single reference directly.
8887   if (NewMemRefs.size() == 1) {
8888     N->MemRefs = NewMemRefs[0];
8889     N->NumMemRefs = 1;
8890     return;
8891   }
8892 
8893   MachineMemOperand **MemRefsBuffer =
8894       Allocator.template Allocate<MachineMemOperand *>(NewMemRefs.size());
8895   llvm::copy(NewMemRefs, MemRefsBuffer);
8896   N->MemRefs = MemRefsBuffer;
8897   N->NumMemRefs = static_cast<int>(NewMemRefs.size());
8898 }
8899 
8900 /// SelectNodeTo - These are wrappers around MorphNodeTo that accept a
8901 /// machine opcode.
8902 ///
8903 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8904                                    EVT VT) {
8905   SDVTList VTs = getVTList(VT);
8906   return SelectNodeTo(N, MachineOpc, VTs, None);
8907 }
8908 
8909 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8910                                    EVT VT, SDValue Op1) {
8911   SDVTList VTs = getVTList(VT);
8912   SDValue Ops[] = { Op1 };
8913   return SelectNodeTo(N, MachineOpc, VTs, Ops);
8914 }
8915 
8916 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8917                                    EVT VT, SDValue Op1,
8918                                    SDValue Op2) {
8919   SDVTList VTs = getVTList(VT);
8920   SDValue Ops[] = { Op1, Op2 };
8921   return SelectNodeTo(N, MachineOpc, VTs, Ops);
8922 }
8923 
8924 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8925                                    EVT VT, SDValue Op1,
8926                                    SDValue Op2, SDValue Op3) {
8927   SDVTList VTs = getVTList(VT);
8928   SDValue Ops[] = { Op1, Op2, Op3 };
8929   return SelectNodeTo(N, MachineOpc, VTs, Ops);
8930 }
8931 
8932 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8933                                    EVT VT, ArrayRef<SDValue> Ops) {
8934   SDVTList VTs = getVTList(VT);
8935   return SelectNodeTo(N, MachineOpc, VTs, Ops);
8936 }
8937 
8938 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8939                                    EVT VT1, EVT VT2, ArrayRef<SDValue> Ops) {
8940   SDVTList VTs = getVTList(VT1, VT2);
8941   return SelectNodeTo(N, MachineOpc, VTs, Ops);
8942 }
8943 
8944 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8945                                    EVT VT1, EVT VT2) {
8946   SDVTList VTs = getVTList(VT1, VT2);
8947   return SelectNodeTo(N, MachineOpc, VTs, None);
8948 }
8949 
8950 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8951                                    EVT VT1, EVT VT2, EVT VT3,
8952                                    ArrayRef<SDValue> Ops) {
8953   SDVTList VTs = getVTList(VT1, VT2, VT3);
8954   return SelectNodeTo(N, MachineOpc, VTs, Ops);
8955 }
8956 
8957 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8958                                    EVT VT1, EVT VT2,
8959                                    SDValue Op1, SDValue Op2) {
8960   SDVTList VTs = getVTList(VT1, VT2);
8961   SDValue Ops[] = { Op1, Op2 };
8962   return SelectNodeTo(N, MachineOpc, VTs, Ops);
8963 }
8964 
8965 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8966                                    SDVTList VTs,ArrayRef<SDValue> Ops) {
8967   SDNode *New = MorphNodeTo(N, ~MachineOpc, VTs, Ops);
8968   // Reset the NodeID to -1.
8969   New->setNodeId(-1);
8970   if (New != N) {
8971     ReplaceAllUsesWith(N, New);
8972     RemoveDeadNode(N);
8973   }
8974   return New;
8975 }
8976 
8977 /// UpdateSDLocOnMergeSDNode - If the opt level is -O0 then it throws away
8978 /// the line number information on the merged node since it is not possible to
8979 /// preserve the information that operation is associated with multiple lines.
8980 /// This will make the debugger working better at -O0, were there is a higher
8981 /// probability having other instructions associated with that line.
8982 ///
8983 /// For IROrder, we keep the smaller of the two
8984 SDNode *SelectionDAG::UpdateSDLocOnMergeSDNode(SDNode *N, const SDLoc &OLoc) {
8985   DebugLoc NLoc = N->getDebugLoc();
8986   if (NLoc && OptLevel == CodeGenOpt::None && OLoc.getDebugLoc() != NLoc) {
8987     N->setDebugLoc(DebugLoc());
8988   }
8989   unsigned Order = std::min(N->getIROrder(), OLoc.getIROrder());
8990   N->setIROrder(Order);
8991   return N;
8992 }
8993 
8994 /// MorphNodeTo - This *mutates* the specified node to have the specified
8995 /// return type, opcode, and operands.
8996 ///
8997 /// Note that MorphNodeTo returns the resultant node.  If there is already a
8998 /// node of the specified opcode and operands, it returns that node instead of
8999 /// the current one.  Note that the SDLoc need not be the same.
9000 ///
9001 /// Using MorphNodeTo is faster than creating a new node and swapping it in
9002 /// with ReplaceAllUsesWith both because it often avoids allocating a new
9003 /// node, and because it doesn't require CSE recalculation for any of
9004 /// the node's users.
9005 ///
9006 /// However, note that MorphNodeTo recursively deletes dead nodes from the DAG.
9007 /// As a consequence it isn't appropriate to use from within the DAG combiner or
9008 /// the legalizer which maintain worklists that would need to be updated when
9009 /// deleting things.
9010 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
9011                                   SDVTList VTs, ArrayRef<SDValue> Ops) {
9012   // If an identical node already exists, use it.
9013   void *IP = nullptr;
9014   if (VTs.VTs[VTs.NumVTs-1] != MVT::Glue) {
9015     FoldingSetNodeID ID;
9016     AddNodeIDNode(ID, Opc, VTs, Ops);
9017     if (SDNode *ON = FindNodeOrInsertPos(ID, SDLoc(N), IP))
9018       return UpdateSDLocOnMergeSDNode(ON, SDLoc(N));
9019   }
9020 
9021   if (!RemoveNodeFromCSEMaps(N))
9022     IP = nullptr;
9023 
9024   // Start the morphing.
9025   N->NodeType = Opc;
9026   N->ValueList = VTs.VTs;
9027   N->NumValues = VTs.NumVTs;
9028 
9029   // Clear the operands list, updating used nodes to remove this from their
9030   // use list.  Keep track of any operands that become dead as a result.
9031   SmallPtrSet<SDNode*, 16> DeadNodeSet;
9032   for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) {
9033     SDUse &Use = *I++;
9034     SDNode *Used = Use.getNode();
9035     Use.set(SDValue());
9036     if (Used->use_empty())
9037       DeadNodeSet.insert(Used);
9038   }
9039 
9040   // For MachineNode, initialize the memory references information.
9041   if (MachineSDNode *MN = dyn_cast<MachineSDNode>(N))
9042     MN->clearMemRefs();
9043 
9044   // Swap for an appropriately sized array from the recycler.
9045   removeOperands(N);
9046   createOperands(N, Ops);
9047 
9048   // Delete any nodes that are still dead after adding the uses for the
9049   // new operands.
9050   if (!DeadNodeSet.empty()) {
9051     SmallVector<SDNode *, 16> DeadNodes;
9052     for (SDNode *N : DeadNodeSet)
9053       if (N->use_empty())
9054         DeadNodes.push_back(N);
9055     RemoveDeadNodes(DeadNodes);
9056   }
9057 
9058   if (IP)
9059     CSEMap.InsertNode(N, IP);   // Memoize the new node.
9060   return N;
9061 }
9062 
9063 SDNode* SelectionDAG::mutateStrictFPToFP(SDNode *Node) {
9064   unsigned OrigOpc = Node->getOpcode();
9065   unsigned NewOpc;
9066   switch (OrigOpc) {
9067   default:
9068     llvm_unreachable("mutateStrictFPToFP called with unexpected opcode!");
9069 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN)               \
9070   case ISD::STRICT_##DAGN: NewOpc = ISD::DAGN; break;
9071 #define CMP_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN)               \
9072   case ISD::STRICT_##DAGN: NewOpc = ISD::SETCC; break;
9073 #include "llvm/IR/ConstrainedOps.def"
9074   }
9075 
9076   assert(Node->getNumValues() == 2 && "Unexpected number of results!");
9077 
9078   // We're taking this node out of the chain, so we need to re-link things.
9079   SDValue InputChain = Node->getOperand(0);
9080   SDValue OutputChain = SDValue(Node, 1);
9081   ReplaceAllUsesOfValueWith(OutputChain, InputChain);
9082 
9083   SmallVector<SDValue, 3> Ops;
9084   for (unsigned i = 1, e = Node->getNumOperands(); i != e; ++i)
9085     Ops.push_back(Node->getOperand(i));
9086 
9087   SDVTList VTs = getVTList(Node->getValueType(0));
9088   SDNode *Res = MorphNodeTo(Node, NewOpc, VTs, Ops);
9089 
9090   // MorphNodeTo can operate in two ways: if an existing node with the
9091   // specified operands exists, it can just return it.  Otherwise, it
9092   // updates the node in place to have the requested operands.
9093   if (Res == Node) {
9094     // If we updated the node in place, reset the node ID.  To the isel,
9095     // this should be just like a newly allocated machine node.
9096     Res->setNodeId(-1);
9097   } else {
9098     ReplaceAllUsesWith(Node, Res);
9099     RemoveDeadNode(Node);
9100   }
9101 
9102   return Res;
9103 }
9104 
9105 /// getMachineNode - These are used for target selectors to create a new node
9106 /// with specified return type(s), MachineInstr opcode, and operands.
9107 ///
9108 /// Note that getMachineNode returns the resultant node.  If there is already a
9109 /// node of the specified opcode and operands, it returns that node instead of
9110 /// the current one.
9111 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9112                                             EVT VT) {
9113   SDVTList VTs = getVTList(VT);
9114   return getMachineNode(Opcode, dl, VTs, None);
9115 }
9116 
9117 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9118                                             EVT VT, SDValue Op1) {
9119   SDVTList VTs = getVTList(VT);
9120   SDValue Ops[] = { Op1 };
9121   return getMachineNode(Opcode, dl, VTs, Ops);
9122 }
9123 
9124 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9125                                             EVT VT, SDValue Op1, SDValue Op2) {
9126   SDVTList VTs = getVTList(VT);
9127   SDValue Ops[] = { Op1, Op2 };
9128   return getMachineNode(Opcode, dl, VTs, Ops);
9129 }
9130 
9131 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9132                                             EVT VT, SDValue Op1, SDValue Op2,
9133                                             SDValue Op3) {
9134   SDVTList VTs = getVTList(VT);
9135   SDValue Ops[] = { Op1, Op2, Op3 };
9136   return getMachineNode(Opcode, dl, VTs, Ops);
9137 }
9138 
9139 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9140                                             EVT VT, ArrayRef<SDValue> Ops) {
9141   SDVTList VTs = getVTList(VT);
9142   return getMachineNode(Opcode, dl, VTs, Ops);
9143 }
9144 
9145 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9146                                             EVT VT1, EVT VT2, SDValue Op1,
9147                                             SDValue Op2) {
9148   SDVTList VTs = getVTList(VT1, VT2);
9149   SDValue Ops[] = { Op1, Op2 };
9150   return getMachineNode(Opcode, dl, VTs, Ops);
9151 }
9152 
9153 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9154                                             EVT VT1, EVT VT2, SDValue Op1,
9155                                             SDValue Op2, SDValue Op3) {
9156   SDVTList VTs = getVTList(VT1, VT2);
9157   SDValue Ops[] = { Op1, Op2, Op3 };
9158   return getMachineNode(Opcode, dl, VTs, Ops);
9159 }
9160 
9161 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9162                                             EVT VT1, EVT VT2,
9163                                             ArrayRef<SDValue> Ops) {
9164   SDVTList VTs = getVTList(VT1, VT2);
9165   return getMachineNode(Opcode, dl, VTs, Ops);
9166 }
9167 
9168 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9169                                             EVT VT1, EVT VT2, EVT VT3,
9170                                             SDValue Op1, SDValue Op2) {
9171   SDVTList VTs = getVTList(VT1, VT2, VT3);
9172   SDValue Ops[] = { Op1, Op2 };
9173   return getMachineNode(Opcode, dl, VTs, Ops);
9174 }
9175 
9176 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9177                                             EVT VT1, EVT VT2, EVT VT3,
9178                                             SDValue Op1, SDValue Op2,
9179                                             SDValue Op3) {
9180   SDVTList VTs = getVTList(VT1, VT2, VT3);
9181   SDValue Ops[] = { Op1, Op2, Op3 };
9182   return getMachineNode(Opcode, dl, VTs, Ops);
9183 }
9184 
9185 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9186                                             EVT VT1, EVT VT2, EVT VT3,
9187                                             ArrayRef<SDValue> Ops) {
9188   SDVTList VTs = getVTList(VT1, VT2, VT3);
9189   return getMachineNode(Opcode, dl, VTs, Ops);
9190 }
9191 
9192 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9193                                             ArrayRef<EVT> ResultTys,
9194                                             ArrayRef<SDValue> Ops) {
9195   SDVTList VTs = getVTList(ResultTys);
9196   return getMachineNode(Opcode, dl, VTs, Ops);
9197 }
9198 
9199 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &DL,
9200                                             SDVTList VTs,
9201                                             ArrayRef<SDValue> Ops) {
9202   bool DoCSE = VTs.VTs[VTs.NumVTs-1] != MVT::Glue;
9203   MachineSDNode *N;
9204   void *IP = nullptr;
9205 
9206   if (DoCSE) {
9207     FoldingSetNodeID ID;
9208     AddNodeIDNode(ID, ~Opcode, VTs, Ops);
9209     IP = nullptr;
9210     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
9211       return cast<MachineSDNode>(UpdateSDLocOnMergeSDNode(E, DL));
9212     }
9213   }
9214 
9215   // Allocate a new MachineSDNode.
9216   N = newSDNode<MachineSDNode>(~Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
9217   createOperands(N, Ops);
9218 
9219   if (DoCSE)
9220     CSEMap.InsertNode(N, IP);
9221 
9222   InsertNode(N);
9223   NewSDValueDbgMsg(SDValue(N, 0), "Creating new machine node: ", this);
9224   return N;
9225 }
9226 
9227 /// getTargetExtractSubreg - A convenience function for creating
9228 /// TargetOpcode::EXTRACT_SUBREG nodes.
9229 SDValue SelectionDAG::getTargetExtractSubreg(int SRIdx, const SDLoc &DL, EVT VT,
9230                                              SDValue Operand) {
9231   SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32);
9232   SDNode *Subreg = getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL,
9233                                   VT, Operand, SRIdxVal);
9234   return SDValue(Subreg, 0);
9235 }
9236 
9237 /// getTargetInsertSubreg - A convenience function for creating
9238 /// TargetOpcode::INSERT_SUBREG nodes.
9239 SDValue SelectionDAG::getTargetInsertSubreg(int SRIdx, const SDLoc &DL, EVT VT,
9240                                             SDValue Operand, SDValue Subreg) {
9241   SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32);
9242   SDNode *Result = getMachineNode(TargetOpcode::INSERT_SUBREG, DL,
9243                                   VT, Operand, Subreg, SRIdxVal);
9244   return SDValue(Result, 0);
9245 }
9246 
9247 /// getNodeIfExists - Get the specified node if it's already available, or
9248 /// else return NULL.
9249 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList,
9250                                       ArrayRef<SDValue> Ops) {
9251   SDNodeFlags Flags;
9252   if (Inserter)
9253     Flags = Inserter->getFlags();
9254   return getNodeIfExists(Opcode, VTList, Ops, Flags);
9255 }
9256 
9257 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList,
9258                                       ArrayRef<SDValue> Ops,
9259                                       const SDNodeFlags Flags) {
9260   if (VTList.VTs[VTList.NumVTs - 1] != MVT::Glue) {
9261     FoldingSetNodeID ID;
9262     AddNodeIDNode(ID, Opcode, VTList, Ops);
9263     void *IP = nullptr;
9264     if (SDNode *E = FindNodeOrInsertPos(ID, SDLoc(), IP)) {
9265       E->intersectFlagsWith(Flags);
9266       return E;
9267     }
9268   }
9269   return nullptr;
9270 }
9271 
9272 /// doesNodeExist - Check if a node exists without modifying its flags.
9273 bool SelectionDAG::doesNodeExist(unsigned Opcode, SDVTList VTList,
9274                                  ArrayRef<SDValue> Ops) {
9275   if (VTList.VTs[VTList.NumVTs - 1] != MVT::Glue) {
9276     FoldingSetNodeID ID;
9277     AddNodeIDNode(ID, Opcode, VTList, Ops);
9278     void *IP = nullptr;
9279     if (FindNodeOrInsertPos(ID, SDLoc(), IP))
9280       return true;
9281   }
9282   return false;
9283 }
9284 
9285 /// getDbgValue - Creates a SDDbgValue node.
9286 ///
9287 /// SDNode
9288 SDDbgValue *SelectionDAG::getDbgValue(DIVariable *Var, DIExpression *Expr,
9289                                       SDNode *N, unsigned R, bool IsIndirect,
9290                                       const DebugLoc &DL, unsigned O) {
9291   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
9292          "Expected inlined-at fields to agree");
9293   return new (DbgInfo->getAlloc())
9294       SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromNode(N, R),
9295                  {}, IsIndirect, DL, O,
9296                  /*IsVariadic=*/false);
9297 }
9298 
9299 /// Constant
9300 SDDbgValue *SelectionDAG::getConstantDbgValue(DIVariable *Var,
9301                                               DIExpression *Expr,
9302                                               const Value *C,
9303                                               const DebugLoc &DL, unsigned O) {
9304   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
9305          "Expected inlined-at fields to agree");
9306   return new (DbgInfo->getAlloc())
9307       SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromConst(C), {},
9308                  /*IsIndirect=*/false, DL, O,
9309                  /*IsVariadic=*/false);
9310 }
9311 
9312 /// FrameIndex
9313 SDDbgValue *SelectionDAG::getFrameIndexDbgValue(DIVariable *Var,
9314                                                 DIExpression *Expr, unsigned FI,
9315                                                 bool IsIndirect,
9316                                                 const DebugLoc &DL,
9317                                                 unsigned O) {
9318   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
9319          "Expected inlined-at fields to agree");
9320   return getFrameIndexDbgValue(Var, Expr, FI, {}, IsIndirect, DL, O);
9321 }
9322 
9323 /// FrameIndex with dependencies
9324 SDDbgValue *SelectionDAG::getFrameIndexDbgValue(DIVariable *Var,
9325                                                 DIExpression *Expr, unsigned FI,
9326                                                 ArrayRef<SDNode *> Dependencies,
9327                                                 bool IsIndirect,
9328                                                 const DebugLoc &DL,
9329                                                 unsigned O) {
9330   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
9331          "Expected inlined-at fields to agree");
9332   return new (DbgInfo->getAlloc())
9333       SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromFrameIdx(FI),
9334                  Dependencies, IsIndirect, DL, O,
9335                  /*IsVariadic=*/false);
9336 }
9337 
9338 /// VReg
9339 SDDbgValue *SelectionDAG::getVRegDbgValue(DIVariable *Var, DIExpression *Expr,
9340                                           unsigned VReg, bool IsIndirect,
9341                                           const DebugLoc &DL, unsigned O) {
9342   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
9343          "Expected inlined-at fields to agree");
9344   return new (DbgInfo->getAlloc())
9345       SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromVReg(VReg),
9346                  {}, IsIndirect, DL, O,
9347                  /*IsVariadic=*/false);
9348 }
9349 
9350 SDDbgValue *SelectionDAG::getDbgValueList(DIVariable *Var, DIExpression *Expr,
9351                                           ArrayRef<SDDbgOperand> Locs,
9352                                           ArrayRef<SDNode *> Dependencies,
9353                                           bool IsIndirect, const DebugLoc &DL,
9354                                           unsigned O, bool IsVariadic) {
9355   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
9356          "Expected inlined-at fields to agree");
9357   return new (DbgInfo->getAlloc())
9358       SDDbgValue(DbgInfo->getAlloc(), Var, Expr, Locs, Dependencies, IsIndirect,
9359                  DL, O, IsVariadic);
9360 }
9361 
9362 void SelectionDAG::transferDbgValues(SDValue From, SDValue To,
9363                                      unsigned OffsetInBits, unsigned SizeInBits,
9364                                      bool InvalidateDbg) {
9365   SDNode *FromNode = From.getNode();
9366   SDNode *ToNode = To.getNode();
9367   assert(FromNode && ToNode && "Can't modify dbg values");
9368 
9369   // PR35338
9370   // TODO: assert(From != To && "Redundant dbg value transfer");
9371   // TODO: assert(FromNode != ToNode && "Intranode dbg value transfer");
9372   if (From == To || FromNode == ToNode)
9373     return;
9374 
9375   if (!FromNode->getHasDebugValue())
9376     return;
9377 
9378   SDDbgOperand FromLocOp =
9379       SDDbgOperand::fromNode(From.getNode(), From.getResNo());
9380   SDDbgOperand ToLocOp = SDDbgOperand::fromNode(To.getNode(), To.getResNo());
9381 
9382   SmallVector<SDDbgValue *, 2> ClonedDVs;
9383   for (SDDbgValue *Dbg : GetDbgValues(FromNode)) {
9384     if (Dbg->isInvalidated())
9385       continue;
9386 
9387     // TODO: assert(!Dbg->isInvalidated() && "Transfer of invalid dbg value");
9388 
9389     // Create a new location ops vector that is equal to the old vector, but
9390     // with each instance of FromLocOp replaced with ToLocOp.
9391     bool Changed = false;
9392     auto NewLocOps = Dbg->copyLocationOps();
9393     std::replace_if(
9394         NewLocOps.begin(), NewLocOps.end(),
9395         [&Changed, FromLocOp](const SDDbgOperand &Op) {
9396           bool Match = Op == FromLocOp;
9397           Changed |= Match;
9398           return Match;
9399         },
9400         ToLocOp);
9401     // Ignore this SDDbgValue if we didn't find a matching location.
9402     if (!Changed)
9403       continue;
9404 
9405     DIVariable *Var = Dbg->getVariable();
9406     auto *Expr = Dbg->getExpression();
9407     // If a fragment is requested, update the expression.
9408     if (SizeInBits) {
9409       // When splitting a larger (e.g., sign-extended) value whose
9410       // lower bits are described with an SDDbgValue, do not attempt
9411       // to transfer the SDDbgValue to the upper bits.
9412       if (auto FI = Expr->getFragmentInfo())
9413         if (OffsetInBits + SizeInBits > FI->SizeInBits)
9414           continue;
9415       auto Fragment = DIExpression::createFragmentExpression(Expr, OffsetInBits,
9416                                                              SizeInBits);
9417       if (!Fragment)
9418         continue;
9419       Expr = *Fragment;
9420     }
9421 
9422     auto AdditionalDependencies = Dbg->getAdditionalDependencies();
9423     // Clone the SDDbgValue and move it to To.
9424     SDDbgValue *Clone = getDbgValueList(
9425         Var, Expr, NewLocOps, AdditionalDependencies, Dbg->isIndirect(),
9426         Dbg->getDebugLoc(), std::max(ToNode->getIROrder(), Dbg->getOrder()),
9427         Dbg->isVariadic());
9428     ClonedDVs.push_back(Clone);
9429 
9430     if (InvalidateDbg) {
9431       // Invalidate value and indicate the SDDbgValue should not be emitted.
9432       Dbg->setIsInvalidated();
9433       Dbg->setIsEmitted();
9434     }
9435   }
9436 
9437   for (SDDbgValue *Dbg : ClonedDVs) {
9438     assert(is_contained(Dbg->getSDNodes(), ToNode) &&
9439            "Transferred DbgValues should depend on the new SDNode");
9440     AddDbgValue(Dbg, false);
9441   }
9442 }
9443 
9444 void SelectionDAG::salvageDebugInfo(SDNode &N) {
9445   if (!N.getHasDebugValue())
9446     return;
9447 
9448   SmallVector<SDDbgValue *, 2> ClonedDVs;
9449   for (auto DV : GetDbgValues(&N)) {
9450     if (DV->isInvalidated())
9451       continue;
9452     switch (N.getOpcode()) {
9453     default:
9454       break;
9455     case ISD::ADD:
9456       SDValue N0 = N.getOperand(0);
9457       SDValue N1 = N.getOperand(1);
9458       if (!isConstantIntBuildVectorOrConstantInt(N0) &&
9459           isConstantIntBuildVectorOrConstantInt(N1)) {
9460         uint64_t Offset = N.getConstantOperandVal(1);
9461 
9462         // Rewrite an ADD constant node into a DIExpression. Since we are
9463         // performing arithmetic to compute the variable's *value* in the
9464         // DIExpression, we need to mark the expression with a
9465         // DW_OP_stack_value.
9466         auto *DIExpr = DV->getExpression();
9467         auto NewLocOps = DV->copyLocationOps();
9468         bool Changed = false;
9469         for (size_t i = 0; i < NewLocOps.size(); ++i) {
9470           // We're not given a ResNo to compare against because the whole
9471           // node is going away. We know that any ISD::ADD only has one
9472           // result, so we can assume any node match is using the result.
9473           if (NewLocOps[i].getKind() != SDDbgOperand::SDNODE ||
9474               NewLocOps[i].getSDNode() != &N)
9475             continue;
9476           NewLocOps[i] = SDDbgOperand::fromNode(N0.getNode(), N0.getResNo());
9477           SmallVector<uint64_t, 3> ExprOps;
9478           DIExpression::appendOffset(ExprOps, Offset);
9479           DIExpr = DIExpression::appendOpsToArg(DIExpr, ExprOps, i, true);
9480           Changed = true;
9481         }
9482         (void)Changed;
9483         assert(Changed && "Salvage target doesn't use N");
9484 
9485         auto AdditionalDependencies = DV->getAdditionalDependencies();
9486         SDDbgValue *Clone = getDbgValueList(DV->getVariable(), DIExpr,
9487                                             NewLocOps, AdditionalDependencies,
9488                                             DV->isIndirect(), DV->getDebugLoc(),
9489                                             DV->getOrder(), DV->isVariadic());
9490         ClonedDVs.push_back(Clone);
9491         DV->setIsInvalidated();
9492         DV->setIsEmitted();
9493         LLVM_DEBUG(dbgs() << "SALVAGE: Rewriting";
9494                    N0.getNode()->dumprFull(this);
9495                    dbgs() << " into " << *DIExpr << '\n');
9496       }
9497     }
9498   }
9499 
9500   for (SDDbgValue *Dbg : ClonedDVs) {
9501     assert(!Dbg->getSDNodes().empty() &&
9502            "Salvaged DbgValue should depend on a new SDNode");
9503     AddDbgValue(Dbg, false);
9504   }
9505 }
9506 
9507 /// Creates a SDDbgLabel node.
9508 SDDbgLabel *SelectionDAG::getDbgLabel(DILabel *Label,
9509                                       const DebugLoc &DL, unsigned O) {
9510   assert(cast<DILabel>(Label)->isValidLocationForIntrinsic(DL) &&
9511          "Expected inlined-at fields to agree");
9512   return new (DbgInfo->getAlloc()) SDDbgLabel(Label, DL, O);
9513 }
9514 
9515 namespace {
9516 
9517 /// RAUWUpdateListener - Helper for ReplaceAllUsesWith - When the node
9518 /// pointed to by a use iterator is deleted, increment the use iterator
9519 /// so that it doesn't dangle.
9520 ///
9521 class RAUWUpdateListener : public SelectionDAG::DAGUpdateListener {
9522   SDNode::use_iterator &UI;
9523   SDNode::use_iterator &UE;
9524 
9525   void NodeDeleted(SDNode *N, SDNode *E) override {
9526     // Increment the iterator as needed.
9527     while (UI != UE && N == *UI)
9528       ++UI;
9529   }
9530 
9531 public:
9532   RAUWUpdateListener(SelectionDAG &d,
9533                      SDNode::use_iterator &ui,
9534                      SDNode::use_iterator &ue)
9535     : SelectionDAG::DAGUpdateListener(d), UI(ui), UE(ue) {}
9536 };
9537 
9538 } // end anonymous namespace
9539 
9540 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
9541 /// This can cause recursive merging of nodes in the DAG.
9542 ///
9543 /// This version assumes From has a single result value.
9544 ///
9545 void SelectionDAG::ReplaceAllUsesWith(SDValue FromN, SDValue To) {
9546   SDNode *From = FromN.getNode();
9547   assert(From->getNumValues() == 1 && FromN.getResNo() == 0 &&
9548          "Cannot replace with this method!");
9549   assert(From != To.getNode() && "Cannot replace uses of with self");
9550 
9551   // Preserve Debug Values
9552   transferDbgValues(FromN, To);
9553 
9554   // Iterate over all the existing uses of From. New uses will be added
9555   // to the beginning of the use list, which we avoid visiting.
9556   // This specifically avoids visiting uses of From that arise while the
9557   // replacement is happening, because any such uses would be the result
9558   // of CSE: If an existing node looks like From after one of its operands
9559   // is replaced by To, we don't want to replace of all its users with To
9560   // too. See PR3018 for more info.
9561   SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
9562   RAUWUpdateListener Listener(*this, UI, UE);
9563   while (UI != UE) {
9564     SDNode *User = *UI;
9565 
9566     // This node is about to morph, remove its old self from the CSE maps.
9567     RemoveNodeFromCSEMaps(User);
9568 
9569     // A user can appear in a use list multiple times, and when this
9570     // happens the uses are usually next to each other in the list.
9571     // To help reduce the number of CSE recomputations, process all
9572     // the uses of this user that we can find this way.
9573     do {
9574       SDUse &Use = UI.getUse();
9575       ++UI;
9576       Use.set(To);
9577       if (To->isDivergent() != From->isDivergent())
9578         updateDivergence(User);
9579     } while (UI != UE && *UI == User);
9580     // Now that we have modified User, add it back to the CSE maps.  If it
9581     // already exists there, recursively merge the results together.
9582     AddModifiedNodeToCSEMaps(User);
9583   }
9584 
9585   // If we just RAUW'd the root, take note.
9586   if (FromN == getRoot())
9587     setRoot(To);
9588 }
9589 
9590 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
9591 /// This can cause recursive merging of nodes in the DAG.
9592 ///
9593 /// This version assumes that for each value of From, there is a
9594 /// corresponding value in To in the same position with the same type.
9595 ///
9596 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, SDNode *To) {
9597 #ifndef NDEBUG
9598   for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
9599     assert((!From->hasAnyUseOfValue(i) ||
9600             From->getValueType(i) == To->getValueType(i)) &&
9601            "Cannot use this version of ReplaceAllUsesWith!");
9602 #endif
9603 
9604   // Handle the trivial case.
9605   if (From == To)
9606     return;
9607 
9608   // Preserve Debug Info. Only do this if there's a use.
9609   for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
9610     if (From->hasAnyUseOfValue(i)) {
9611       assert((i < To->getNumValues()) && "Invalid To location");
9612       transferDbgValues(SDValue(From, i), SDValue(To, i));
9613     }
9614 
9615   // Iterate over just the existing users of From. See the comments in
9616   // the ReplaceAllUsesWith above.
9617   SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
9618   RAUWUpdateListener Listener(*this, UI, UE);
9619   while (UI != UE) {
9620     SDNode *User = *UI;
9621 
9622     // This node is about to morph, remove its old self from the CSE maps.
9623     RemoveNodeFromCSEMaps(User);
9624 
9625     // A user can appear in a use list multiple times, and when this
9626     // happens the uses are usually next to each other in the list.
9627     // To help reduce the number of CSE recomputations, process all
9628     // the uses of this user that we can find this way.
9629     do {
9630       SDUse &Use = UI.getUse();
9631       ++UI;
9632       Use.setNode(To);
9633       if (To->isDivergent() != From->isDivergent())
9634         updateDivergence(User);
9635     } while (UI != UE && *UI == User);
9636 
9637     // Now that we have modified User, add it back to the CSE maps.  If it
9638     // already exists there, recursively merge the results together.
9639     AddModifiedNodeToCSEMaps(User);
9640   }
9641 
9642   // If we just RAUW'd the root, take note.
9643   if (From == getRoot().getNode())
9644     setRoot(SDValue(To, getRoot().getResNo()));
9645 }
9646 
9647 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
9648 /// This can cause recursive merging of nodes in the DAG.
9649 ///
9650 /// This version can replace From with any result values.  To must match the
9651 /// number and types of values returned by From.
9652 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, const SDValue *To) {
9653   if (From->getNumValues() == 1)  // Handle the simple case efficiently.
9654     return ReplaceAllUsesWith(SDValue(From, 0), To[0]);
9655 
9656   // Preserve Debug Info.
9657   for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
9658     transferDbgValues(SDValue(From, i), To[i]);
9659 
9660   // Iterate over just the existing users of From. See the comments in
9661   // the ReplaceAllUsesWith above.
9662   SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
9663   RAUWUpdateListener Listener(*this, UI, UE);
9664   while (UI != UE) {
9665     SDNode *User = *UI;
9666 
9667     // This node is about to morph, remove its old self from the CSE maps.
9668     RemoveNodeFromCSEMaps(User);
9669 
9670     // A user can appear in a use list multiple times, and when this happens the
9671     // uses are usually next to each other in the list.  To help reduce the
9672     // number of CSE and divergence recomputations, process all the uses of this
9673     // user that we can find this way.
9674     bool To_IsDivergent = false;
9675     do {
9676       SDUse &Use = UI.getUse();
9677       const SDValue &ToOp = To[Use.getResNo()];
9678       ++UI;
9679       Use.set(ToOp);
9680       To_IsDivergent |= ToOp->isDivergent();
9681     } while (UI != UE && *UI == User);
9682 
9683     if (To_IsDivergent != From->isDivergent())
9684       updateDivergence(User);
9685 
9686     // Now that we have modified User, add it back to the CSE maps.  If it
9687     // already exists there, recursively merge the results together.
9688     AddModifiedNodeToCSEMaps(User);
9689   }
9690 
9691   // If we just RAUW'd the root, take note.
9692   if (From == getRoot().getNode())
9693     setRoot(SDValue(To[getRoot().getResNo()]));
9694 }
9695 
9696 /// ReplaceAllUsesOfValueWith - Replace any uses of From with To, leaving
9697 /// uses of other values produced by From.getNode() alone.  The Deleted
9698 /// vector is handled the same way as for ReplaceAllUsesWith.
9699 void SelectionDAG::ReplaceAllUsesOfValueWith(SDValue From, SDValue To){
9700   // Handle the really simple, really trivial case efficiently.
9701   if (From == To) return;
9702 
9703   // Handle the simple, trivial, case efficiently.
9704   if (From.getNode()->getNumValues() == 1) {
9705     ReplaceAllUsesWith(From, To);
9706     return;
9707   }
9708 
9709   // Preserve Debug Info.
9710   transferDbgValues(From, To);
9711 
9712   // Iterate over just the existing users of From. See the comments in
9713   // the ReplaceAllUsesWith above.
9714   SDNode::use_iterator UI = From.getNode()->use_begin(),
9715                        UE = From.getNode()->use_end();
9716   RAUWUpdateListener Listener(*this, UI, UE);
9717   while (UI != UE) {
9718     SDNode *User = *UI;
9719     bool UserRemovedFromCSEMaps = false;
9720 
9721     // A user can appear in a use list multiple times, and when this
9722     // happens the uses are usually next to each other in the list.
9723     // To help reduce the number of CSE recomputations, process all
9724     // the uses of this user that we can find this way.
9725     do {
9726       SDUse &Use = UI.getUse();
9727 
9728       // Skip uses of different values from the same node.
9729       if (Use.getResNo() != From.getResNo()) {
9730         ++UI;
9731         continue;
9732       }
9733 
9734       // If this node hasn't been modified yet, it's still in the CSE maps,
9735       // so remove its old self from the CSE maps.
9736       if (!UserRemovedFromCSEMaps) {
9737         RemoveNodeFromCSEMaps(User);
9738         UserRemovedFromCSEMaps = true;
9739       }
9740 
9741       ++UI;
9742       Use.set(To);
9743       if (To->isDivergent() != From->isDivergent())
9744         updateDivergence(User);
9745     } while (UI != UE && *UI == User);
9746     // We are iterating over all uses of the From node, so if a use
9747     // doesn't use the specific value, no changes are made.
9748     if (!UserRemovedFromCSEMaps)
9749       continue;
9750 
9751     // Now that we have modified User, add it back to the CSE maps.  If it
9752     // already exists there, recursively merge the results together.
9753     AddModifiedNodeToCSEMaps(User);
9754   }
9755 
9756   // If we just RAUW'd the root, take note.
9757   if (From == getRoot())
9758     setRoot(To);
9759 }
9760 
9761 namespace {
9762 
9763 /// UseMemo - This class is used by SelectionDAG::ReplaceAllUsesOfValuesWith
9764 /// to record information about a use.
9765 struct UseMemo {
9766   SDNode *User;
9767   unsigned Index;
9768   SDUse *Use;
9769 };
9770 
9771 /// operator< - Sort Memos by User.
9772 bool operator<(const UseMemo &L, const UseMemo &R) {
9773   return (intptr_t)L.User < (intptr_t)R.User;
9774 }
9775 
9776 /// RAUOVWUpdateListener - Helper for ReplaceAllUsesOfValuesWith - When the node
9777 /// pointed to by a UseMemo is deleted, set the User to nullptr to indicate that
9778 /// the node already has been taken care of recursively.
9779 class RAUOVWUpdateListener : public SelectionDAG::DAGUpdateListener {
9780   SmallVector<UseMemo, 4> &Uses;
9781 
9782   void NodeDeleted(SDNode *N, SDNode *E) override {
9783     for (UseMemo &Memo : Uses)
9784       if (Memo.User == N)
9785         Memo.User = nullptr;
9786   }
9787 
9788 public:
9789   RAUOVWUpdateListener(SelectionDAG &d, SmallVector<UseMemo, 4> &uses)
9790       : SelectionDAG::DAGUpdateListener(d), Uses(uses) {}
9791 };
9792 
9793 } // end anonymous namespace
9794 
9795 bool SelectionDAG::calculateDivergence(SDNode *N) {
9796   if (TLI->isSDNodeAlwaysUniform(N)) {
9797     assert(!TLI->isSDNodeSourceOfDivergence(N, FLI, DA) &&
9798            "Conflicting divergence information!");
9799     return false;
9800   }
9801   if (TLI->isSDNodeSourceOfDivergence(N, FLI, DA))
9802     return true;
9803   for (auto &Op : N->ops()) {
9804     if (Op.Val.getValueType() != MVT::Other && Op.getNode()->isDivergent())
9805       return true;
9806   }
9807   return false;
9808 }
9809 
9810 void SelectionDAG::updateDivergence(SDNode *N) {
9811   SmallVector<SDNode *, 16> Worklist(1, N);
9812   do {
9813     N = Worklist.pop_back_val();
9814     bool IsDivergent = calculateDivergence(N);
9815     if (N->SDNodeBits.IsDivergent != IsDivergent) {
9816       N->SDNodeBits.IsDivergent = IsDivergent;
9817       llvm::append_range(Worklist, N->uses());
9818     }
9819   } while (!Worklist.empty());
9820 }
9821 
9822 void SelectionDAG::CreateTopologicalOrder(std::vector<SDNode *> &Order) {
9823   DenseMap<SDNode *, unsigned> Degree;
9824   Order.reserve(AllNodes.size());
9825   for (auto &N : allnodes()) {
9826     unsigned NOps = N.getNumOperands();
9827     Degree[&N] = NOps;
9828     if (0 == NOps)
9829       Order.push_back(&N);
9830   }
9831   for (size_t I = 0; I != Order.size(); ++I) {
9832     SDNode *N = Order[I];
9833     for (auto U : N->uses()) {
9834       unsigned &UnsortedOps = Degree[U];
9835       if (0 == --UnsortedOps)
9836         Order.push_back(U);
9837     }
9838   }
9839 }
9840 
9841 #ifndef NDEBUG
9842 void SelectionDAG::VerifyDAGDivergence() {
9843   std::vector<SDNode *> TopoOrder;
9844   CreateTopologicalOrder(TopoOrder);
9845   for (auto *N : TopoOrder) {
9846     assert(calculateDivergence(N) == N->isDivergent() &&
9847            "Divergence bit inconsistency detected");
9848   }
9849 }
9850 #endif
9851 
9852 /// ReplaceAllUsesOfValuesWith - Replace any uses of From with To, leaving
9853 /// uses of other values produced by From.getNode() alone.  The same value
9854 /// may appear in both the From and To list.  The Deleted vector is
9855 /// handled the same way as for ReplaceAllUsesWith.
9856 void SelectionDAG::ReplaceAllUsesOfValuesWith(const SDValue *From,
9857                                               const SDValue *To,
9858                                               unsigned Num){
9859   // Handle the simple, trivial case efficiently.
9860   if (Num == 1)
9861     return ReplaceAllUsesOfValueWith(*From, *To);
9862 
9863   transferDbgValues(*From, *To);
9864 
9865   // Read up all the uses and make records of them. This helps
9866   // processing new uses that are introduced during the
9867   // replacement process.
9868   SmallVector<UseMemo, 4> Uses;
9869   for (unsigned i = 0; i != Num; ++i) {
9870     unsigned FromResNo = From[i].getResNo();
9871     SDNode *FromNode = From[i].getNode();
9872     for (SDNode::use_iterator UI = FromNode->use_begin(),
9873          E = FromNode->use_end(); UI != E; ++UI) {
9874       SDUse &Use = UI.getUse();
9875       if (Use.getResNo() == FromResNo) {
9876         UseMemo Memo = { *UI, i, &Use };
9877         Uses.push_back(Memo);
9878       }
9879     }
9880   }
9881 
9882   // Sort the uses, so that all the uses from a given User are together.
9883   llvm::sort(Uses);
9884   RAUOVWUpdateListener Listener(*this, Uses);
9885 
9886   for (unsigned UseIndex = 0, UseIndexEnd = Uses.size();
9887        UseIndex != UseIndexEnd; ) {
9888     // We know that this user uses some value of From.  If it is the right
9889     // value, update it.
9890     SDNode *User = Uses[UseIndex].User;
9891     // If the node has been deleted by recursive CSE updates when updating
9892     // another node, then just skip this entry.
9893     if (User == nullptr) {
9894       ++UseIndex;
9895       continue;
9896     }
9897 
9898     // This node is about to morph, remove its old self from the CSE maps.
9899     RemoveNodeFromCSEMaps(User);
9900 
9901     // The Uses array is sorted, so all the uses for a given User
9902     // are next to each other in the list.
9903     // To help reduce the number of CSE recomputations, process all
9904     // the uses of this user that we can find this way.
9905     do {
9906       unsigned i = Uses[UseIndex].Index;
9907       SDUse &Use = *Uses[UseIndex].Use;
9908       ++UseIndex;
9909 
9910       Use.set(To[i]);
9911     } while (UseIndex != UseIndexEnd && Uses[UseIndex].User == User);
9912 
9913     // Now that we have modified User, add it back to the CSE maps.  If it
9914     // already exists there, recursively merge the results together.
9915     AddModifiedNodeToCSEMaps(User);
9916   }
9917 }
9918 
9919 /// AssignTopologicalOrder - Assign a unique node id for each node in the DAG
9920 /// based on their topological order. It returns the maximum id and a vector
9921 /// of the SDNodes* in assigned order by reference.
9922 unsigned SelectionDAG::AssignTopologicalOrder() {
9923   unsigned DAGSize = 0;
9924 
9925   // SortedPos tracks the progress of the algorithm. Nodes before it are
9926   // sorted, nodes after it are unsorted. When the algorithm completes
9927   // it is at the end of the list.
9928   allnodes_iterator SortedPos = allnodes_begin();
9929 
9930   // Visit all the nodes. Move nodes with no operands to the front of
9931   // the list immediately. Annotate nodes that do have operands with their
9932   // operand count. Before we do this, the Node Id fields of the nodes
9933   // may contain arbitrary values. After, the Node Id fields for nodes
9934   // before SortedPos will contain the topological sort index, and the
9935   // Node Id fields for nodes At SortedPos and after will contain the
9936   // count of outstanding operands.
9937   for (SDNode &N : llvm::make_early_inc_range(allnodes())) {
9938     checkForCycles(&N, this);
9939     unsigned Degree = N.getNumOperands();
9940     if (Degree == 0) {
9941       // A node with no uses, add it to the result array immediately.
9942       N.setNodeId(DAGSize++);
9943       allnodes_iterator Q(&N);
9944       if (Q != SortedPos)
9945         SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(Q));
9946       assert(SortedPos != AllNodes.end() && "Overran node list");
9947       ++SortedPos;
9948     } else {
9949       // Temporarily use the Node Id as scratch space for the degree count.
9950       N.setNodeId(Degree);
9951     }
9952   }
9953 
9954   // Visit all the nodes. As we iterate, move nodes into sorted order,
9955   // such that by the time the end is reached all nodes will be sorted.
9956   for (SDNode &Node : allnodes()) {
9957     SDNode *N = &Node;
9958     checkForCycles(N, this);
9959     // N is in sorted position, so all its uses have one less operand
9960     // that needs to be sorted.
9961     for (SDNode *P : N->uses()) {
9962       unsigned Degree = P->getNodeId();
9963       assert(Degree != 0 && "Invalid node degree");
9964       --Degree;
9965       if (Degree == 0) {
9966         // All of P's operands are sorted, so P may sorted now.
9967         P->setNodeId(DAGSize++);
9968         if (P->getIterator() != SortedPos)
9969           SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(P));
9970         assert(SortedPos != AllNodes.end() && "Overran node list");
9971         ++SortedPos;
9972       } else {
9973         // Update P's outstanding operand count.
9974         P->setNodeId(Degree);
9975       }
9976     }
9977     if (Node.getIterator() == SortedPos) {
9978 #ifndef NDEBUG
9979       allnodes_iterator I(N);
9980       SDNode *S = &*++I;
9981       dbgs() << "Overran sorted position:\n";
9982       S->dumprFull(this); dbgs() << "\n";
9983       dbgs() << "Checking if this is due to cycles\n";
9984       checkForCycles(this, true);
9985 #endif
9986       llvm_unreachable(nullptr);
9987     }
9988   }
9989 
9990   assert(SortedPos == AllNodes.end() &&
9991          "Topological sort incomplete!");
9992   assert(AllNodes.front().getOpcode() == ISD::EntryToken &&
9993          "First node in topological sort is not the entry token!");
9994   assert(AllNodes.front().getNodeId() == 0 &&
9995          "First node in topological sort has non-zero id!");
9996   assert(AllNodes.front().getNumOperands() == 0 &&
9997          "First node in topological sort has operands!");
9998   assert(AllNodes.back().getNodeId() == (int)DAGSize-1 &&
9999          "Last node in topologic sort has unexpected id!");
10000   assert(AllNodes.back().use_empty() &&
10001          "Last node in topologic sort has users!");
10002   assert(DAGSize == allnodes_size() && "Node count mismatch!");
10003   return DAGSize;
10004 }
10005 
10006 /// AddDbgValue - Add a dbg_value SDNode. If SD is non-null that means the
10007 /// value is produced by SD.
10008 void SelectionDAG::AddDbgValue(SDDbgValue *DB, bool isParameter) {
10009   for (SDNode *SD : DB->getSDNodes()) {
10010     if (!SD)
10011       continue;
10012     assert(DbgInfo->getSDDbgValues(SD).empty() || SD->getHasDebugValue());
10013     SD->setHasDebugValue(true);
10014   }
10015   DbgInfo->add(DB, isParameter);
10016 }
10017 
10018 void SelectionDAG::AddDbgLabel(SDDbgLabel *DB) { DbgInfo->add(DB); }
10019 
10020 SDValue SelectionDAG::makeEquivalentMemoryOrdering(SDValue OldChain,
10021                                                    SDValue NewMemOpChain) {
10022   assert(isa<MemSDNode>(NewMemOpChain) && "Expected a memop node");
10023   assert(NewMemOpChain.getValueType() == MVT::Other && "Expected a token VT");
10024   // The new memory operation must have the same position as the old load in
10025   // terms of memory dependency. Create a TokenFactor for the old load and new
10026   // memory operation and update uses of the old load's output chain to use that
10027   // TokenFactor.
10028   if (OldChain == NewMemOpChain || OldChain.use_empty())
10029     return NewMemOpChain;
10030 
10031   SDValue TokenFactor = getNode(ISD::TokenFactor, SDLoc(OldChain), MVT::Other,
10032                                 OldChain, NewMemOpChain);
10033   ReplaceAllUsesOfValueWith(OldChain, TokenFactor);
10034   UpdateNodeOperands(TokenFactor.getNode(), OldChain, NewMemOpChain);
10035   return TokenFactor;
10036 }
10037 
10038 SDValue SelectionDAG::makeEquivalentMemoryOrdering(LoadSDNode *OldLoad,
10039                                                    SDValue NewMemOp) {
10040   assert(isa<MemSDNode>(NewMemOp.getNode()) && "Expected a memop node");
10041   SDValue OldChain = SDValue(OldLoad, 1);
10042   SDValue NewMemOpChain = NewMemOp.getValue(1);
10043   return makeEquivalentMemoryOrdering(OldChain, NewMemOpChain);
10044 }
10045 
10046 SDValue SelectionDAG::getSymbolFunctionGlobalAddress(SDValue Op,
10047                                                      Function **OutFunction) {
10048   assert(isa<ExternalSymbolSDNode>(Op) && "Node should be an ExternalSymbol");
10049 
10050   auto *Symbol = cast<ExternalSymbolSDNode>(Op)->getSymbol();
10051   auto *Module = MF->getFunction().getParent();
10052   auto *Function = Module->getFunction(Symbol);
10053 
10054   if (OutFunction != nullptr)
10055       *OutFunction = Function;
10056 
10057   if (Function != nullptr) {
10058     auto PtrTy = TLI->getPointerTy(getDataLayout(), Function->getAddressSpace());
10059     return getGlobalAddress(Function, SDLoc(Op), PtrTy);
10060   }
10061 
10062   std::string ErrorStr;
10063   raw_string_ostream ErrorFormatter(ErrorStr);
10064   ErrorFormatter << "Undefined external symbol ";
10065   ErrorFormatter << '"' << Symbol << '"';
10066   report_fatal_error(Twine(ErrorFormatter.str()));
10067 }
10068 
10069 //===----------------------------------------------------------------------===//
10070 //                              SDNode Class
10071 //===----------------------------------------------------------------------===//
10072 
10073 bool llvm::isNullConstant(SDValue V) {
10074   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
10075   return Const != nullptr && Const->isZero();
10076 }
10077 
10078 bool llvm::isNullFPConstant(SDValue V) {
10079   ConstantFPSDNode *Const = dyn_cast<ConstantFPSDNode>(V);
10080   return Const != nullptr && Const->isZero() && !Const->isNegative();
10081 }
10082 
10083 bool llvm::isAllOnesConstant(SDValue V) {
10084   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
10085   return Const != nullptr && Const->isAllOnes();
10086 }
10087 
10088 bool llvm::isOneConstant(SDValue V) {
10089   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
10090   return Const != nullptr && Const->isOne();
10091 }
10092 
10093 SDValue llvm::peekThroughBitcasts(SDValue V) {
10094   while (V.getOpcode() == ISD::BITCAST)
10095     V = V.getOperand(0);
10096   return V;
10097 }
10098 
10099 SDValue llvm::peekThroughOneUseBitcasts(SDValue V) {
10100   while (V.getOpcode() == ISD::BITCAST && V.getOperand(0).hasOneUse())
10101     V = V.getOperand(0);
10102   return V;
10103 }
10104 
10105 SDValue llvm::peekThroughExtractSubvectors(SDValue V) {
10106   while (V.getOpcode() == ISD::EXTRACT_SUBVECTOR)
10107     V = V.getOperand(0);
10108   return V;
10109 }
10110 
10111 bool llvm::isBitwiseNot(SDValue V, bool AllowUndefs) {
10112   if (V.getOpcode() != ISD::XOR)
10113     return false;
10114   V = peekThroughBitcasts(V.getOperand(1));
10115   unsigned NumBits = V.getScalarValueSizeInBits();
10116   ConstantSDNode *C =
10117       isConstOrConstSplat(V, AllowUndefs, /*AllowTruncation*/ true);
10118   return C && (C->getAPIntValue().countTrailingOnes() >= NumBits);
10119 }
10120 
10121 ConstantSDNode *llvm::isConstOrConstSplat(SDValue N, bool AllowUndefs,
10122                                           bool AllowTruncation) {
10123   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
10124     return CN;
10125 
10126   // SplatVectors can truncate their operands. Ignore that case here unless
10127   // AllowTruncation is set.
10128   if (N->getOpcode() == ISD::SPLAT_VECTOR) {
10129     EVT VecEltVT = N->getValueType(0).getVectorElementType();
10130     if (auto *CN = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
10131       EVT CVT = CN->getValueType(0);
10132       assert(CVT.bitsGE(VecEltVT) && "Illegal splat_vector element extension");
10133       if (AllowTruncation || CVT == VecEltVT)
10134         return CN;
10135     }
10136   }
10137 
10138   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
10139     BitVector UndefElements;
10140     ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
10141 
10142     // BuildVectors can truncate their operands. Ignore that case here unless
10143     // AllowTruncation is set.
10144     if (CN && (UndefElements.none() || AllowUndefs)) {
10145       EVT CVT = CN->getValueType(0);
10146       EVT NSVT = N.getValueType().getScalarType();
10147       assert(CVT.bitsGE(NSVT) && "Illegal build vector element extension");
10148       if (AllowTruncation || (CVT == NSVT))
10149         return CN;
10150     }
10151   }
10152 
10153   return nullptr;
10154 }
10155 
10156 ConstantSDNode *llvm::isConstOrConstSplat(SDValue N, const APInt &DemandedElts,
10157                                           bool AllowUndefs,
10158                                           bool AllowTruncation) {
10159   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
10160     return CN;
10161 
10162   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
10163     BitVector UndefElements;
10164     ConstantSDNode *CN = BV->getConstantSplatNode(DemandedElts, &UndefElements);
10165 
10166     // BuildVectors can truncate their operands. Ignore that case here unless
10167     // AllowTruncation is set.
10168     if (CN && (UndefElements.none() || AllowUndefs)) {
10169       EVT CVT = CN->getValueType(0);
10170       EVT NSVT = N.getValueType().getScalarType();
10171       assert(CVT.bitsGE(NSVT) && "Illegal build vector element extension");
10172       if (AllowTruncation || (CVT == NSVT))
10173         return CN;
10174     }
10175   }
10176 
10177   return nullptr;
10178 }
10179 
10180 ConstantFPSDNode *llvm::isConstOrConstSplatFP(SDValue N, bool AllowUndefs) {
10181   if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
10182     return CN;
10183 
10184   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
10185     BitVector UndefElements;
10186     ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements);
10187     if (CN && (UndefElements.none() || AllowUndefs))
10188       return CN;
10189   }
10190 
10191   if (N.getOpcode() == ISD::SPLAT_VECTOR)
10192     if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N.getOperand(0)))
10193       return CN;
10194 
10195   return nullptr;
10196 }
10197 
10198 ConstantFPSDNode *llvm::isConstOrConstSplatFP(SDValue N,
10199                                               const APInt &DemandedElts,
10200                                               bool AllowUndefs) {
10201   if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
10202     return CN;
10203 
10204   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
10205     BitVector UndefElements;
10206     ConstantFPSDNode *CN =
10207         BV->getConstantFPSplatNode(DemandedElts, &UndefElements);
10208     if (CN && (UndefElements.none() || AllowUndefs))
10209       return CN;
10210   }
10211 
10212   return nullptr;
10213 }
10214 
10215 bool llvm::isNullOrNullSplat(SDValue N, bool AllowUndefs) {
10216   // TODO: may want to use peekThroughBitcast() here.
10217   ConstantSDNode *C =
10218       isConstOrConstSplat(N, AllowUndefs, /*AllowTruncation=*/true);
10219   return C && C->isZero();
10220 }
10221 
10222 bool llvm::isOneOrOneSplat(SDValue N, bool AllowUndefs) {
10223   // TODO: may want to use peekThroughBitcast() here.
10224   unsigned BitWidth = N.getScalarValueSizeInBits();
10225   ConstantSDNode *C = isConstOrConstSplat(N, AllowUndefs);
10226   return C && C->isOne() && C->getValueSizeInBits(0) == BitWidth;
10227 }
10228 
10229 bool llvm::isAllOnesOrAllOnesSplat(SDValue N, bool AllowUndefs) {
10230   N = peekThroughBitcasts(N);
10231   unsigned BitWidth = N.getScalarValueSizeInBits();
10232   ConstantSDNode *C = isConstOrConstSplat(N, AllowUndefs);
10233   return C && C->isAllOnes() && C->getValueSizeInBits(0) == BitWidth;
10234 }
10235 
10236 HandleSDNode::~HandleSDNode() {
10237   DropOperands();
10238 }
10239 
10240 GlobalAddressSDNode::GlobalAddressSDNode(unsigned Opc, unsigned Order,
10241                                          const DebugLoc &DL,
10242                                          const GlobalValue *GA, EVT VT,
10243                                          int64_t o, unsigned TF)
10244     : SDNode(Opc, Order, DL, getSDVTList(VT)), Offset(o), TargetFlags(TF) {
10245   TheGlobal = GA;
10246 }
10247 
10248 AddrSpaceCastSDNode::AddrSpaceCastSDNode(unsigned Order, const DebugLoc &dl,
10249                                          EVT VT, unsigned SrcAS,
10250                                          unsigned DestAS)
10251     : SDNode(ISD::ADDRSPACECAST, Order, dl, getSDVTList(VT)),
10252       SrcAddrSpace(SrcAS), DestAddrSpace(DestAS) {}
10253 
10254 MemSDNode::MemSDNode(unsigned Opc, unsigned Order, const DebugLoc &dl,
10255                      SDVTList VTs, EVT memvt, MachineMemOperand *mmo)
10256     : SDNode(Opc, Order, dl, VTs), MemoryVT(memvt), MMO(mmo) {
10257   MemSDNodeBits.IsVolatile = MMO->isVolatile();
10258   MemSDNodeBits.IsNonTemporal = MMO->isNonTemporal();
10259   MemSDNodeBits.IsDereferenceable = MMO->isDereferenceable();
10260   MemSDNodeBits.IsInvariant = MMO->isInvariant();
10261 
10262   // We check here that the size of the memory operand fits within the size of
10263   // the MMO. This is because the MMO might indicate only a possible address
10264   // range instead of specifying the affected memory addresses precisely.
10265   // TODO: Make MachineMemOperands aware of scalable vectors.
10266   assert(memvt.getStoreSize().getKnownMinSize() <= MMO->getSize() &&
10267          "Size mismatch!");
10268 }
10269 
10270 /// Profile - Gather unique data for the node.
10271 ///
10272 void SDNode::Profile(FoldingSetNodeID &ID) const {
10273   AddNodeIDNode(ID, this);
10274 }
10275 
10276 namespace {
10277 
10278   struct EVTArray {
10279     std::vector<EVT> VTs;
10280 
10281     EVTArray() {
10282       VTs.reserve(MVT::VALUETYPE_SIZE);
10283       for (unsigned i = 0; i < MVT::VALUETYPE_SIZE; ++i)
10284         VTs.push_back(MVT((MVT::SimpleValueType)i));
10285     }
10286   };
10287 
10288 } // end anonymous namespace
10289 
10290 static ManagedStatic<std::set<EVT, EVT::compareRawBits>> EVTs;
10291 static ManagedStatic<EVTArray> SimpleVTArray;
10292 static ManagedStatic<sys::SmartMutex<true>> VTMutex;
10293 
10294 /// getValueTypeList - Return a pointer to the specified value type.
10295 ///
10296 const EVT *SDNode::getValueTypeList(EVT VT) {
10297   if (VT.isExtended()) {
10298     sys::SmartScopedLock<true> Lock(*VTMutex);
10299     return &(*EVTs->insert(VT).first);
10300   }
10301   assert(VT.getSimpleVT() < MVT::VALUETYPE_SIZE && "Value type out of range!");
10302   return &SimpleVTArray->VTs[VT.getSimpleVT().SimpleTy];
10303 }
10304 
10305 /// hasNUsesOfValue - Return true if there are exactly NUSES uses of the
10306 /// indicated value.  This method ignores uses of other values defined by this
10307 /// operation.
10308 bool SDNode::hasNUsesOfValue(unsigned NUses, unsigned Value) const {
10309   assert(Value < getNumValues() && "Bad value!");
10310 
10311   // TODO: Only iterate over uses of a given value of the node
10312   for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) {
10313     if (UI.getUse().getResNo() == Value) {
10314       if (NUses == 0)
10315         return false;
10316       --NUses;
10317     }
10318   }
10319 
10320   // Found exactly the right number of uses?
10321   return NUses == 0;
10322 }
10323 
10324 /// hasAnyUseOfValue - Return true if there are any use of the indicated
10325 /// value. This method ignores uses of other values defined by this operation.
10326 bool SDNode::hasAnyUseOfValue(unsigned Value) const {
10327   assert(Value < getNumValues() && "Bad value!");
10328 
10329   for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI)
10330     if (UI.getUse().getResNo() == Value)
10331       return true;
10332 
10333   return false;
10334 }
10335 
10336 /// isOnlyUserOf - Return true if this node is the only use of N.
10337 bool SDNode::isOnlyUserOf(const SDNode *N) const {
10338   bool Seen = false;
10339   for (const SDNode *User : N->uses()) {
10340     if (User == this)
10341       Seen = true;
10342     else
10343       return false;
10344   }
10345 
10346   return Seen;
10347 }
10348 
10349 /// Return true if the only users of N are contained in Nodes.
10350 bool SDNode::areOnlyUsersOf(ArrayRef<const SDNode *> Nodes, const SDNode *N) {
10351   bool Seen = false;
10352   for (const SDNode *User : N->uses()) {
10353     if (llvm::is_contained(Nodes, User))
10354       Seen = true;
10355     else
10356       return false;
10357   }
10358 
10359   return Seen;
10360 }
10361 
10362 /// isOperand - Return true if this node is an operand of N.
10363 bool SDValue::isOperandOf(const SDNode *N) const {
10364   return is_contained(N->op_values(), *this);
10365 }
10366 
10367 bool SDNode::isOperandOf(const SDNode *N) const {
10368   return any_of(N->op_values(),
10369                 [this](SDValue Op) { return this == Op.getNode(); });
10370 }
10371 
10372 /// reachesChainWithoutSideEffects - Return true if this operand (which must
10373 /// be a chain) reaches the specified operand without crossing any
10374 /// side-effecting instructions on any chain path.  In practice, this looks
10375 /// through token factors and non-volatile loads.  In order to remain efficient,
10376 /// this only looks a couple of nodes in, it does not do an exhaustive search.
10377 ///
10378 /// Note that we only need to examine chains when we're searching for
10379 /// side-effects; SelectionDAG requires that all side-effects are represented
10380 /// by chains, even if another operand would force a specific ordering. This
10381 /// constraint is necessary to allow transformations like splitting loads.
10382 bool SDValue::reachesChainWithoutSideEffects(SDValue Dest,
10383                                              unsigned Depth) const {
10384   if (*this == Dest) return true;
10385 
10386   // Don't search too deeply, we just want to be able to see through
10387   // TokenFactor's etc.
10388   if (Depth == 0) return false;
10389 
10390   // If this is a token factor, all inputs to the TF happen in parallel.
10391   if (getOpcode() == ISD::TokenFactor) {
10392     // First, try a shallow search.
10393     if (is_contained((*this)->ops(), Dest)) {
10394       // We found the chain we want as an operand of this TokenFactor.
10395       // Essentially, we reach the chain without side-effects if we could
10396       // serialize the TokenFactor into a simple chain of operations with
10397       // Dest as the last operation. This is automatically true if the
10398       // chain has one use: there are no other ordering constraints.
10399       // If the chain has more than one use, we give up: some other
10400       // use of Dest might force a side-effect between Dest and the current
10401       // node.
10402       if (Dest.hasOneUse())
10403         return true;
10404     }
10405     // Next, try a deep search: check whether every operand of the TokenFactor
10406     // reaches Dest.
10407     return llvm::all_of((*this)->ops(), [=](SDValue Op) {
10408       return Op.reachesChainWithoutSideEffects(Dest, Depth - 1);
10409     });
10410   }
10411 
10412   // Loads don't have side effects, look through them.
10413   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(*this)) {
10414     if (Ld->isUnordered())
10415       return Ld->getChain().reachesChainWithoutSideEffects(Dest, Depth-1);
10416   }
10417   return false;
10418 }
10419 
10420 bool SDNode::hasPredecessor(const SDNode *N) const {
10421   SmallPtrSet<const SDNode *, 32> Visited;
10422   SmallVector<const SDNode *, 16> Worklist;
10423   Worklist.push_back(this);
10424   return hasPredecessorHelper(N, Visited, Worklist);
10425 }
10426 
10427 void SDNode::intersectFlagsWith(const SDNodeFlags Flags) {
10428   this->Flags.intersectWith(Flags);
10429 }
10430 
10431 SDValue
10432 SelectionDAG::matchBinOpReduction(SDNode *Extract, ISD::NodeType &BinOp,
10433                                   ArrayRef<ISD::NodeType> CandidateBinOps,
10434                                   bool AllowPartials) {
10435   // The pattern must end in an extract from index 0.
10436   if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10437       !isNullConstant(Extract->getOperand(1)))
10438     return SDValue();
10439 
10440   // Match against one of the candidate binary ops.
10441   SDValue Op = Extract->getOperand(0);
10442   if (llvm::none_of(CandidateBinOps, [Op](ISD::NodeType BinOp) {
10443         return Op.getOpcode() == unsigned(BinOp);
10444       }))
10445     return SDValue();
10446 
10447   // Floating-point reductions may require relaxed constraints on the final step
10448   // of the reduction because they may reorder intermediate operations.
10449   unsigned CandidateBinOp = Op.getOpcode();
10450   if (Op.getValueType().isFloatingPoint()) {
10451     SDNodeFlags Flags = Op->getFlags();
10452     switch (CandidateBinOp) {
10453     case ISD::FADD:
10454       if (!Flags.hasNoSignedZeros() || !Flags.hasAllowReassociation())
10455         return SDValue();
10456       break;
10457     default:
10458       llvm_unreachable("Unhandled FP opcode for binop reduction");
10459     }
10460   }
10461 
10462   // Matching failed - attempt to see if we did enough stages that a partial
10463   // reduction from a subvector is possible.
10464   auto PartialReduction = [&](SDValue Op, unsigned NumSubElts) {
10465     if (!AllowPartials || !Op)
10466       return SDValue();
10467     EVT OpVT = Op.getValueType();
10468     EVT OpSVT = OpVT.getScalarType();
10469     EVT SubVT = EVT::getVectorVT(*getContext(), OpSVT, NumSubElts);
10470     if (!TLI->isExtractSubvectorCheap(SubVT, OpVT, 0))
10471       return SDValue();
10472     BinOp = (ISD::NodeType)CandidateBinOp;
10473     return getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(Op), SubVT, Op,
10474                    getVectorIdxConstant(0, SDLoc(Op)));
10475   };
10476 
10477   // At each stage, we're looking for something that looks like:
10478   // %s = shufflevector <8 x i32> %op, <8 x i32> undef,
10479   //                    <8 x i32> <i32 2, i32 3, i32 undef, i32 undef,
10480   //                               i32 undef, i32 undef, i32 undef, i32 undef>
10481   // %a = binop <8 x i32> %op, %s
10482   // Where the mask changes according to the stage. E.g. for a 3-stage pyramid,
10483   // we expect something like:
10484   // <4,5,6,7,u,u,u,u>
10485   // <2,3,u,u,u,u,u,u>
10486   // <1,u,u,u,u,u,u,u>
10487   // While a partial reduction match would be:
10488   // <2,3,u,u,u,u,u,u>
10489   // <1,u,u,u,u,u,u,u>
10490   unsigned Stages = Log2_32(Op.getValueType().getVectorNumElements());
10491   SDValue PrevOp;
10492   for (unsigned i = 0; i < Stages; ++i) {
10493     unsigned MaskEnd = (1 << i);
10494 
10495     if (Op.getOpcode() != CandidateBinOp)
10496       return PartialReduction(PrevOp, MaskEnd);
10497 
10498     SDValue Op0 = Op.getOperand(0);
10499     SDValue Op1 = Op.getOperand(1);
10500 
10501     ShuffleVectorSDNode *Shuffle = dyn_cast<ShuffleVectorSDNode>(Op0);
10502     if (Shuffle) {
10503       Op = Op1;
10504     } else {
10505       Shuffle = dyn_cast<ShuffleVectorSDNode>(Op1);
10506       Op = Op0;
10507     }
10508 
10509     // The first operand of the shuffle should be the same as the other operand
10510     // of the binop.
10511     if (!Shuffle || Shuffle->getOperand(0) != Op)
10512       return PartialReduction(PrevOp, MaskEnd);
10513 
10514     // Verify the shuffle has the expected (at this stage of the pyramid) mask.
10515     for (int Index = 0; Index < (int)MaskEnd; ++Index)
10516       if (Shuffle->getMaskElt(Index) != (int)(MaskEnd + Index))
10517         return PartialReduction(PrevOp, MaskEnd);
10518 
10519     PrevOp = Op;
10520   }
10521 
10522   // Handle subvector reductions, which tend to appear after the shuffle
10523   // reduction stages.
10524   while (Op.getOpcode() == CandidateBinOp) {
10525     unsigned NumElts = Op.getValueType().getVectorNumElements();
10526     SDValue Op0 = Op.getOperand(0);
10527     SDValue Op1 = Op.getOperand(1);
10528     if (Op0.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
10529         Op1.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
10530         Op0.getOperand(0) != Op1.getOperand(0))
10531       break;
10532     SDValue Src = Op0.getOperand(0);
10533     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
10534     if (NumSrcElts != (2 * NumElts))
10535       break;
10536     if (!(Op0.getConstantOperandAPInt(1) == 0 &&
10537           Op1.getConstantOperandAPInt(1) == NumElts) &&
10538         !(Op1.getConstantOperandAPInt(1) == 0 &&
10539           Op0.getConstantOperandAPInt(1) == NumElts))
10540       break;
10541     Op = Src;
10542   }
10543 
10544   BinOp = (ISD::NodeType)CandidateBinOp;
10545   return Op;
10546 }
10547 
10548 SDValue SelectionDAG::UnrollVectorOp(SDNode *N, unsigned ResNE) {
10549   assert(N->getNumValues() == 1 &&
10550          "Can't unroll a vector with multiple results!");
10551 
10552   EVT VT = N->getValueType(0);
10553   unsigned NE = VT.getVectorNumElements();
10554   EVT EltVT = VT.getVectorElementType();
10555   SDLoc dl(N);
10556 
10557   SmallVector<SDValue, 8> Scalars;
10558   SmallVector<SDValue, 4> Operands(N->getNumOperands());
10559 
10560   // If ResNE is 0, fully unroll the vector op.
10561   if (ResNE == 0)
10562     ResNE = NE;
10563   else if (NE > ResNE)
10564     NE = ResNE;
10565 
10566   unsigned i;
10567   for (i= 0; i != NE; ++i) {
10568     for (unsigned j = 0, e = N->getNumOperands(); j != e; ++j) {
10569       SDValue Operand = N->getOperand(j);
10570       EVT OperandVT = Operand.getValueType();
10571       if (OperandVT.isVector()) {
10572         // A vector operand; extract a single element.
10573         EVT OperandEltVT = OperandVT.getVectorElementType();
10574         Operands[j] = getNode(ISD::EXTRACT_VECTOR_ELT, dl, OperandEltVT,
10575                               Operand, getVectorIdxConstant(i, dl));
10576       } else {
10577         // A scalar operand; just use it as is.
10578         Operands[j] = Operand;
10579       }
10580     }
10581 
10582     switch (N->getOpcode()) {
10583     default: {
10584       Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands,
10585                                 N->getFlags()));
10586       break;
10587     }
10588     case ISD::VSELECT:
10589       Scalars.push_back(getNode(ISD::SELECT, dl, EltVT, Operands));
10590       break;
10591     case ISD::SHL:
10592     case ISD::SRA:
10593     case ISD::SRL:
10594     case ISD::ROTL:
10595     case ISD::ROTR:
10596       Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands[0],
10597                                getShiftAmountOperand(Operands[0].getValueType(),
10598                                                      Operands[1])));
10599       break;
10600     case ISD::SIGN_EXTEND_INREG: {
10601       EVT ExtVT = cast<VTSDNode>(Operands[1])->getVT().getVectorElementType();
10602       Scalars.push_back(getNode(N->getOpcode(), dl, EltVT,
10603                                 Operands[0],
10604                                 getValueType(ExtVT)));
10605     }
10606     }
10607   }
10608 
10609   for (; i < ResNE; ++i)
10610     Scalars.push_back(getUNDEF(EltVT));
10611 
10612   EVT VecVT = EVT::getVectorVT(*getContext(), EltVT, ResNE);
10613   return getBuildVector(VecVT, dl, Scalars);
10614 }
10615 
10616 std::pair<SDValue, SDValue> SelectionDAG::UnrollVectorOverflowOp(
10617     SDNode *N, unsigned ResNE) {
10618   unsigned Opcode = N->getOpcode();
10619   assert((Opcode == ISD::UADDO || Opcode == ISD::SADDO ||
10620           Opcode == ISD::USUBO || Opcode == ISD::SSUBO ||
10621           Opcode == ISD::UMULO || Opcode == ISD::SMULO) &&
10622          "Expected an overflow opcode");
10623 
10624   EVT ResVT = N->getValueType(0);
10625   EVT OvVT = N->getValueType(1);
10626   EVT ResEltVT = ResVT.getVectorElementType();
10627   EVT OvEltVT = OvVT.getVectorElementType();
10628   SDLoc dl(N);
10629 
10630   // If ResNE is 0, fully unroll the vector op.
10631   unsigned NE = ResVT.getVectorNumElements();
10632   if (ResNE == 0)
10633     ResNE = NE;
10634   else if (NE > ResNE)
10635     NE = ResNE;
10636 
10637   SmallVector<SDValue, 8> LHSScalars;
10638   SmallVector<SDValue, 8> RHSScalars;
10639   ExtractVectorElements(N->getOperand(0), LHSScalars, 0, NE);
10640   ExtractVectorElements(N->getOperand(1), RHSScalars, 0, NE);
10641 
10642   EVT SVT = TLI->getSetCCResultType(getDataLayout(), *getContext(), ResEltVT);
10643   SDVTList VTs = getVTList(ResEltVT, SVT);
10644   SmallVector<SDValue, 8> ResScalars;
10645   SmallVector<SDValue, 8> OvScalars;
10646   for (unsigned i = 0; i < NE; ++i) {
10647     SDValue Res = getNode(Opcode, dl, VTs, LHSScalars[i], RHSScalars[i]);
10648     SDValue Ov =
10649         getSelect(dl, OvEltVT, Res.getValue(1),
10650                   getBoolConstant(true, dl, OvEltVT, ResVT),
10651                   getConstant(0, dl, OvEltVT));
10652 
10653     ResScalars.push_back(Res);
10654     OvScalars.push_back(Ov);
10655   }
10656 
10657   ResScalars.append(ResNE - NE, getUNDEF(ResEltVT));
10658   OvScalars.append(ResNE - NE, getUNDEF(OvEltVT));
10659 
10660   EVT NewResVT = EVT::getVectorVT(*getContext(), ResEltVT, ResNE);
10661   EVT NewOvVT = EVT::getVectorVT(*getContext(), OvEltVT, ResNE);
10662   return std::make_pair(getBuildVector(NewResVT, dl, ResScalars),
10663                         getBuildVector(NewOvVT, dl, OvScalars));
10664 }
10665 
10666 bool SelectionDAG::areNonVolatileConsecutiveLoads(LoadSDNode *LD,
10667                                                   LoadSDNode *Base,
10668                                                   unsigned Bytes,
10669                                                   int Dist) const {
10670   if (LD->isVolatile() || Base->isVolatile())
10671     return false;
10672   // TODO: probably too restrictive for atomics, revisit
10673   if (!LD->isSimple())
10674     return false;
10675   if (LD->isIndexed() || Base->isIndexed())
10676     return false;
10677   if (LD->getChain() != Base->getChain())
10678     return false;
10679   EVT VT = LD->getValueType(0);
10680   if (VT.getSizeInBits() / 8 != Bytes)
10681     return false;
10682 
10683   auto BaseLocDecomp = BaseIndexOffset::match(Base, *this);
10684   auto LocDecomp = BaseIndexOffset::match(LD, *this);
10685 
10686   int64_t Offset = 0;
10687   if (BaseLocDecomp.equalBaseIndex(LocDecomp, *this, Offset))
10688     return (Dist * Bytes == Offset);
10689   return false;
10690 }
10691 
10692 /// InferPtrAlignment - Infer alignment of a load / store address. Return None
10693 /// if it cannot be inferred.
10694 MaybeAlign SelectionDAG::InferPtrAlign(SDValue Ptr) const {
10695   // If this is a GlobalAddress + cst, return the alignment.
10696   const GlobalValue *GV = nullptr;
10697   int64_t GVOffset = 0;
10698   if (TLI->isGAPlusOffset(Ptr.getNode(), GV, GVOffset)) {
10699     unsigned PtrWidth = getDataLayout().getPointerTypeSizeInBits(GV->getType());
10700     KnownBits Known(PtrWidth);
10701     llvm::computeKnownBits(GV, Known, getDataLayout());
10702     unsigned AlignBits = Known.countMinTrailingZeros();
10703     if (AlignBits)
10704       return commonAlignment(Align(1ull << std::min(31U, AlignBits)), GVOffset);
10705   }
10706 
10707   // If this is a direct reference to a stack slot, use information about the
10708   // stack slot's alignment.
10709   int FrameIdx = INT_MIN;
10710   int64_t FrameOffset = 0;
10711   if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr)) {
10712     FrameIdx = FI->getIndex();
10713   } else if (isBaseWithConstantOffset(Ptr) &&
10714              isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
10715     // Handle FI+Cst
10716     FrameIdx = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
10717     FrameOffset = Ptr.getConstantOperandVal(1);
10718   }
10719 
10720   if (FrameIdx != INT_MIN) {
10721     const MachineFrameInfo &MFI = getMachineFunction().getFrameInfo();
10722     return commonAlignment(MFI.getObjectAlign(FrameIdx), FrameOffset);
10723   }
10724 
10725   return None;
10726 }
10727 
10728 /// GetSplitDestVTs - Compute the VTs needed for the low/hi parts of a type
10729 /// which is split (or expanded) into two not necessarily identical pieces.
10730 std::pair<EVT, EVT> SelectionDAG::GetSplitDestVTs(const EVT &VT) const {
10731   // Currently all types are split in half.
10732   EVT LoVT, HiVT;
10733   if (!VT.isVector())
10734     LoVT = HiVT = TLI->getTypeToTransformTo(*getContext(), VT);
10735   else
10736     LoVT = HiVT = VT.getHalfNumVectorElementsVT(*getContext());
10737 
10738   return std::make_pair(LoVT, HiVT);
10739 }
10740 
10741 /// GetDependentSplitDestVTs - Compute the VTs needed for the low/hi parts of a
10742 /// type, dependent on an enveloping VT that has been split into two identical
10743 /// pieces. Sets the HiIsEmpty flag when hi type has zero storage size.
10744 std::pair<EVT, EVT>
10745 SelectionDAG::GetDependentSplitDestVTs(const EVT &VT, const EVT &EnvVT,
10746                                        bool *HiIsEmpty) const {
10747   EVT EltTp = VT.getVectorElementType();
10748   // Examples:
10749   //   custom VL=8  with enveloping VL=8/8 yields 8/0 (hi empty)
10750   //   custom VL=9  with enveloping VL=8/8 yields 8/1
10751   //   custom VL=10 with enveloping VL=8/8 yields 8/2
10752   //   etc.
10753   ElementCount VTNumElts = VT.getVectorElementCount();
10754   ElementCount EnvNumElts = EnvVT.getVectorElementCount();
10755   assert(VTNumElts.isScalable() == EnvNumElts.isScalable() &&
10756          "Mixing fixed width and scalable vectors when enveloping a type");
10757   EVT LoVT, HiVT;
10758   if (VTNumElts.getKnownMinValue() > EnvNumElts.getKnownMinValue()) {
10759     LoVT = EVT::getVectorVT(*getContext(), EltTp, EnvNumElts);
10760     HiVT = EVT::getVectorVT(*getContext(), EltTp, VTNumElts - EnvNumElts);
10761     *HiIsEmpty = false;
10762   } else {
10763     // Flag that hi type has zero storage size, but return split envelop type
10764     // (this would be easier if vector types with zero elements were allowed).
10765     LoVT = EVT::getVectorVT(*getContext(), EltTp, VTNumElts);
10766     HiVT = EVT::getVectorVT(*getContext(), EltTp, EnvNumElts);
10767     *HiIsEmpty = true;
10768   }
10769   return std::make_pair(LoVT, HiVT);
10770 }
10771 
10772 /// SplitVector - Split the vector with EXTRACT_SUBVECTOR and return the
10773 /// low/high part.
10774 std::pair<SDValue, SDValue>
10775 SelectionDAG::SplitVector(const SDValue &N, const SDLoc &DL, const EVT &LoVT,
10776                           const EVT &HiVT) {
10777   assert(LoVT.isScalableVector() == HiVT.isScalableVector() &&
10778          LoVT.isScalableVector() == N.getValueType().isScalableVector() &&
10779          "Splitting vector with an invalid mixture of fixed and scalable "
10780          "vector types");
10781   assert(LoVT.getVectorMinNumElements() + HiVT.getVectorMinNumElements() <=
10782              N.getValueType().getVectorMinNumElements() &&
10783          "More vector elements requested than available!");
10784   SDValue Lo, Hi;
10785   Lo =
10786       getNode(ISD::EXTRACT_SUBVECTOR, DL, LoVT, N, getVectorIdxConstant(0, DL));
10787   // For scalable vectors it is safe to use LoVT.getVectorMinNumElements()
10788   // (rather than having to use ElementCount), because EXTRACT_SUBVECTOR scales
10789   // IDX with the runtime scaling factor of the result vector type. For
10790   // fixed-width result vectors, that runtime scaling factor is 1.
10791   Hi = getNode(ISD::EXTRACT_SUBVECTOR, DL, HiVT, N,
10792                getVectorIdxConstant(LoVT.getVectorMinNumElements(), DL));
10793   return std::make_pair(Lo, Hi);
10794 }
10795 
10796 std::pair<SDValue, SDValue> SelectionDAG::SplitEVL(SDValue N, EVT VecVT,
10797                                                    const SDLoc &DL) {
10798   // Split the vector length parameter.
10799   // %evl -> umin(%evl, %halfnumelts) and usubsat(%evl - %halfnumelts).
10800   EVT VT = N.getValueType();
10801   assert(VecVT.getVectorElementCount().isKnownEven() &&
10802          "Expecting the mask to be an evenly-sized vector");
10803   unsigned HalfMinNumElts = VecVT.getVectorMinNumElements() / 2;
10804   SDValue HalfNumElts =
10805       VecVT.isFixedLengthVector()
10806           ? getConstant(HalfMinNumElts, DL, VT)
10807           : getVScale(DL, VT, APInt(VT.getScalarSizeInBits(), HalfMinNumElts));
10808   SDValue Lo = getNode(ISD::UMIN, DL, VT, N, HalfNumElts);
10809   SDValue Hi = getNode(ISD::USUBSAT, DL, VT, N, HalfNumElts);
10810   return std::make_pair(Lo, Hi);
10811 }
10812 
10813 /// Widen the vector up to the next power of two using INSERT_SUBVECTOR.
10814 SDValue SelectionDAG::WidenVector(const SDValue &N, const SDLoc &DL) {
10815   EVT VT = N.getValueType();
10816   EVT WideVT = EVT::getVectorVT(*getContext(), VT.getVectorElementType(),
10817                                 NextPowerOf2(VT.getVectorNumElements()));
10818   return getNode(ISD::INSERT_SUBVECTOR, DL, WideVT, getUNDEF(WideVT), N,
10819                  getVectorIdxConstant(0, DL));
10820 }
10821 
10822 void SelectionDAG::ExtractVectorElements(SDValue Op,
10823                                          SmallVectorImpl<SDValue> &Args,
10824                                          unsigned Start, unsigned Count,
10825                                          EVT EltVT) {
10826   EVT VT = Op.getValueType();
10827   if (Count == 0)
10828     Count = VT.getVectorNumElements();
10829   if (EltVT == EVT())
10830     EltVT = VT.getVectorElementType();
10831   SDLoc SL(Op);
10832   for (unsigned i = Start, e = Start + Count; i != e; ++i) {
10833     Args.push_back(getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Op,
10834                            getVectorIdxConstant(i, SL)));
10835   }
10836 }
10837 
10838 // getAddressSpace - Return the address space this GlobalAddress belongs to.
10839 unsigned GlobalAddressSDNode::getAddressSpace() const {
10840   return getGlobal()->getType()->getAddressSpace();
10841 }
10842 
10843 Type *ConstantPoolSDNode::getType() const {
10844   if (isMachineConstantPoolEntry())
10845     return Val.MachineCPVal->getType();
10846   return Val.ConstVal->getType();
10847 }
10848 
10849 bool BuildVectorSDNode::isConstantSplat(APInt &SplatValue, APInt &SplatUndef,
10850                                         unsigned &SplatBitSize,
10851                                         bool &HasAnyUndefs,
10852                                         unsigned MinSplatBits,
10853                                         bool IsBigEndian) const {
10854   EVT VT = getValueType(0);
10855   assert(VT.isVector() && "Expected a vector type");
10856   unsigned VecWidth = VT.getSizeInBits();
10857   if (MinSplatBits > VecWidth)
10858     return false;
10859 
10860   // FIXME: The widths are based on this node's type, but build vectors can
10861   // truncate their operands.
10862   SplatValue = APInt(VecWidth, 0);
10863   SplatUndef = APInt(VecWidth, 0);
10864 
10865   // Get the bits. Bits with undefined values (when the corresponding element
10866   // of the vector is an ISD::UNDEF value) are set in SplatUndef and cleared
10867   // in SplatValue. If any of the values are not constant, give up and return
10868   // false.
10869   unsigned int NumOps = getNumOperands();
10870   assert(NumOps > 0 && "isConstantSplat has 0-size build vector");
10871   unsigned EltWidth = VT.getScalarSizeInBits();
10872 
10873   for (unsigned j = 0; j < NumOps; ++j) {
10874     unsigned i = IsBigEndian ? NumOps - 1 - j : j;
10875     SDValue OpVal = getOperand(i);
10876     unsigned BitPos = j * EltWidth;
10877 
10878     if (OpVal.isUndef())
10879       SplatUndef.setBits(BitPos, BitPos + EltWidth);
10880     else if (auto *CN = dyn_cast<ConstantSDNode>(OpVal))
10881       SplatValue.insertBits(CN->getAPIntValue().zextOrTrunc(EltWidth), BitPos);
10882     else if (auto *CN = dyn_cast<ConstantFPSDNode>(OpVal))
10883       SplatValue.insertBits(CN->getValueAPF().bitcastToAPInt(), BitPos);
10884     else
10885       return false;
10886   }
10887 
10888   // The build_vector is all constants or undefs. Find the smallest element
10889   // size that splats the vector.
10890   HasAnyUndefs = (SplatUndef != 0);
10891 
10892   // FIXME: This does not work for vectors with elements less than 8 bits.
10893   while (VecWidth > 8) {
10894     unsigned HalfSize = VecWidth / 2;
10895     APInt HighValue = SplatValue.extractBits(HalfSize, HalfSize);
10896     APInt LowValue = SplatValue.extractBits(HalfSize, 0);
10897     APInt HighUndef = SplatUndef.extractBits(HalfSize, HalfSize);
10898     APInt LowUndef = SplatUndef.extractBits(HalfSize, 0);
10899 
10900     // If the two halves do not match (ignoring undef bits), stop here.
10901     if ((HighValue & ~LowUndef) != (LowValue & ~HighUndef) ||
10902         MinSplatBits > HalfSize)
10903       break;
10904 
10905     SplatValue = HighValue | LowValue;
10906     SplatUndef = HighUndef & LowUndef;
10907 
10908     VecWidth = HalfSize;
10909   }
10910 
10911   SplatBitSize = VecWidth;
10912   return true;
10913 }
10914 
10915 SDValue BuildVectorSDNode::getSplatValue(const APInt &DemandedElts,
10916                                          BitVector *UndefElements) const {
10917   unsigned NumOps = getNumOperands();
10918   if (UndefElements) {
10919     UndefElements->clear();
10920     UndefElements->resize(NumOps);
10921   }
10922   assert(NumOps == DemandedElts.getBitWidth() && "Unexpected vector size");
10923   if (!DemandedElts)
10924     return SDValue();
10925   SDValue Splatted;
10926   for (unsigned i = 0; i != NumOps; ++i) {
10927     if (!DemandedElts[i])
10928       continue;
10929     SDValue Op = getOperand(i);
10930     if (Op.isUndef()) {
10931       if (UndefElements)
10932         (*UndefElements)[i] = true;
10933     } else if (!Splatted) {
10934       Splatted = Op;
10935     } else if (Splatted != Op) {
10936       return SDValue();
10937     }
10938   }
10939 
10940   if (!Splatted) {
10941     unsigned FirstDemandedIdx = DemandedElts.countTrailingZeros();
10942     assert(getOperand(FirstDemandedIdx).isUndef() &&
10943            "Can only have a splat without a constant for all undefs.");
10944     return getOperand(FirstDemandedIdx);
10945   }
10946 
10947   return Splatted;
10948 }
10949 
10950 SDValue BuildVectorSDNode::getSplatValue(BitVector *UndefElements) const {
10951   APInt DemandedElts = APInt::getAllOnes(getNumOperands());
10952   return getSplatValue(DemandedElts, UndefElements);
10953 }
10954 
10955 bool BuildVectorSDNode::getRepeatedSequence(const APInt &DemandedElts,
10956                                             SmallVectorImpl<SDValue> &Sequence,
10957                                             BitVector *UndefElements) const {
10958   unsigned NumOps = getNumOperands();
10959   Sequence.clear();
10960   if (UndefElements) {
10961     UndefElements->clear();
10962     UndefElements->resize(NumOps);
10963   }
10964   assert(NumOps == DemandedElts.getBitWidth() && "Unexpected vector size");
10965   if (!DemandedElts || NumOps < 2 || !isPowerOf2_32(NumOps))
10966     return false;
10967 
10968   // Set the undefs even if we don't find a sequence (like getSplatValue).
10969   if (UndefElements)
10970     for (unsigned I = 0; I != NumOps; ++I)
10971       if (DemandedElts[I] && getOperand(I).isUndef())
10972         (*UndefElements)[I] = true;
10973 
10974   // Iteratively widen the sequence length looking for repetitions.
10975   for (unsigned SeqLen = 1; SeqLen < NumOps; SeqLen *= 2) {
10976     Sequence.append(SeqLen, SDValue());
10977     for (unsigned I = 0; I != NumOps; ++I) {
10978       if (!DemandedElts[I])
10979         continue;
10980       SDValue &SeqOp = Sequence[I % SeqLen];
10981       SDValue Op = getOperand(I);
10982       if (Op.isUndef()) {
10983         if (!SeqOp)
10984           SeqOp = Op;
10985         continue;
10986       }
10987       if (SeqOp && !SeqOp.isUndef() && SeqOp != Op) {
10988         Sequence.clear();
10989         break;
10990       }
10991       SeqOp = Op;
10992     }
10993     if (!Sequence.empty())
10994       return true;
10995   }
10996 
10997   assert(Sequence.empty() && "Failed to empty non-repeating sequence pattern");
10998   return false;
10999 }
11000 
11001 bool BuildVectorSDNode::getRepeatedSequence(SmallVectorImpl<SDValue> &Sequence,
11002                                             BitVector *UndefElements) const {
11003   APInt DemandedElts = APInt::getAllOnes(getNumOperands());
11004   return getRepeatedSequence(DemandedElts, Sequence, UndefElements);
11005 }
11006 
11007 ConstantSDNode *
11008 BuildVectorSDNode::getConstantSplatNode(const APInt &DemandedElts,
11009                                         BitVector *UndefElements) const {
11010   return dyn_cast_or_null<ConstantSDNode>(
11011       getSplatValue(DemandedElts, UndefElements));
11012 }
11013 
11014 ConstantSDNode *
11015 BuildVectorSDNode::getConstantSplatNode(BitVector *UndefElements) const {
11016   return dyn_cast_or_null<ConstantSDNode>(getSplatValue(UndefElements));
11017 }
11018 
11019 ConstantFPSDNode *
11020 BuildVectorSDNode::getConstantFPSplatNode(const APInt &DemandedElts,
11021                                           BitVector *UndefElements) const {
11022   return dyn_cast_or_null<ConstantFPSDNode>(
11023       getSplatValue(DemandedElts, UndefElements));
11024 }
11025 
11026 ConstantFPSDNode *
11027 BuildVectorSDNode::getConstantFPSplatNode(BitVector *UndefElements) const {
11028   return dyn_cast_or_null<ConstantFPSDNode>(getSplatValue(UndefElements));
11029 }
11030 
11031 int32_t
11032 BuildVectorSDNode::getConstantFPSplatPow2ToLog2Int(BitVector *UndefElements,
11033                                                    uint32_t BitWidth) const {
11034   if (ConstantFPSDNode *CN =
11035           dyn_cast_or_null<ConstantFPSDNode>(getSplatValue(UndefElements))) {
11036     bool IsExact;
11037     APSInt IntVal(BitWidth);
11038     const APFloat &APF = CN->getValueAPF();
11039     if (APF.convertToInteger(IntVal, APFloat::rmTowardZero, &IsExact) !=
11040             APFloat::opOK ||
11041         !IsExact)
11042       return -1;
11043 
11044     return IntVal.exactLogBase2();
11045   }
11046   return -1;
11047 }
11048 
11049 bool BuildVectorSDNode::getConstantRawBits(
11050     bool IsLittleEndian, unsigned DstEltSizeInBits,
11051     SmallVectorImpl<APInt> &RawBitElements, BitVector &UndefElements) const {
11052   // Early-out if this contains anything but Undef/Constant/ConstantFP.
11053   if (!isConstant())
11054     return false;
11055 
11056   unsigned NumSrcOps = getNumOperands();
11057   unsigned SrcEltSizeInBits = getValueType(0).getScalarSizeInBits();
11058   assert(((NumSrcOps * SrcEltSizeInBits) % DstEltSizeInBits) == 0 &&
11059          "Invalid bitcast scale");
11060 
11061   // Extract raw src bits.
11062   SmallVector<APInt> SrcBitElements(NumSrcOps,
11063                                     APInt::getNullValue(SrcEltSizeInBits));
11064   BitVector SrcUndeElements(NumSrcOps, false);
11065 
11066   for (unsigned I = 0; I != NumSrcOps; ++I) {
11067     SDValue Op = getOperand(I);
11068     if (Op.isUndef()) {
11069       SrcUndeElements.set(I);
11070       continue;
11071     }
11072     auto *CInt = dyn_cast<ConstantSDNode>(Op);
11073     auto *CFP = dyn_cast<ConstantFPSDNode>(Op);
11074     assert((CInt || CFP) && "Unknown constant");
11075     SrcBitElements[I] =
11076         CInt ? CInt->getAPIntValue().truncOrSelf(SrcEltSizeInBits)
11077              : CFP->getValueAPF().bitcastToAPInt();
11078   }
11079 
11080   // Recast to dst width.
11081   recastRawBits(IsLittleEndian, DstEltSizeInBits, RawBitElements,
11082                 SrcBitElements, UndefElements, SrcUndeElements);
11083   return true;
11084 }
11085 
11086 void BuildVectorSDNode::recastRawBits(bool IsLittleEndian,
11087                                       unsigned DstEltSizeInBits,
11088                                       SmallVectorImpl<APInt> &DstBitElements,
11089                                       ArrayRef<APInt> SrcBitElements,
11090                                       BitVector &DstUndefElements,
11091                                       const BitVector &SrcUndefElements) {
11092   unsigned NumSrcOps = SrcBitElements.size();
11093   unsigned SrcEltSizeInBits = SrcBitElements[0].getBitWidth();
11094   assert(((NumSrcOps * SrcEltSizeInBits) % DstEltSizeInBits) == 0 &&
11095          "Invalid bitcast scale");
11096   assert(NumSrcOps == SrcUndefElements.size() &&
11097          "Vector size mismatch");
11098 
11099   unsigned NumDstOps = (NumSrcOps * SrcEltSizeInBits) / DstEltSizeInBits;
11100   DstUndefElements.clear();
11101   DstUndefElements.resize(NumDstOps, false);
11102   DstBitElements.assign(NumDstOps, APInt::getNullValue(DstEltSizeInBits));
11103 
11104   // Concatenate src elements constant bits together into dst element.
11105   if (SrcEltSizeInBits <= DstEltSizeInBits) {
11106     unsigned Scale = DstEltSizeInBits / SrcEltSizeInBits;
11107     for (unsigned I = 0; I != NumDstOps; ++I) {
11108       DstUndefElements.set(I);
11109       APInt &DstBits = DstBitElements[I];
11110       for (unsigned J = 0; J != Scale; ++J) {
11111         unsigned Idx = (I * Scale) + (IsLittleEndian ? J : (Scale - J - 1));
11112         if (SrcUndefElements[Idx])
11113           continue;
11114         DstUndefElements.reset(I);
11115         const APInt &SrcBits = SrcBitElements[Idx];
11116         assert(SrcBits.getBitWidth() == SrcEltSizeInBits &&
11117                "Illegal constant bitwidths");
11118         DstBits.insertBits(SrcBits, J * SrcEltSizeInBits);
11119       }
11120     }
11121     return;
11122   }
11123 
11124   // Split src element constant bits into dst elements.
11125   unsigned Scale = SrcEltSizeInBits / DstEltSizeInBits;
11126   for (unsigned I = 0; I != NumSrcOps; ++I) {
11127     if (SrcUndefElements[I]) {
11128       DstUndefElements.set(I * Scale, (I + 1) * Scale);
11129       continue;
11130     }
11131     const APInt &SrcBits = SrcBitElements[I];
11132     for (unsigned J = 0; J != Scale; ++J) {
11133       unsigned Idx = (I * Scale) + (IsLittleEndian ? J : (Scale - J - 1));
11134       APInt &DstBits = DstBitElements[Idx];
11135       DstBits = SrcBits.extractBits(DstEltSizeInBits, J * DstEltSizeInBits);
11136     }
11137   }
11138 }
11139 
11140 bool BuildVectorSDNode::isConstant() const {
11141   for (const SDValue &Op : op_values()) {
11142     unsigned Opc = Op.getOpcode();
11143     if (Opc != ISD::UNDEF && Opc != ISD::Constant && Opc != ISD::ConstantFP)
11144       return false;
11145   }
11146   return true;
11147 }
11148 
11149 bool ShuffleVectorSDNode::isSplatMask(const int *Mask, EVT VT) {
11150   // Find the first non-undef value in the shuffle mask.
11151   unsigned i, e;
11152   for (i = 0, e = VT.getVectorNumElements(); i != e && Mask[i] < 0; ++i)
11153     /* search */;
11154 
11155   // If all elements are undefined, this shuffle can be considered a splat
11156   // (although it should eventually get simplified away completely).
11157   if (i == e)
11158     return true;
11159 
11160   // Make sure all remaining elements are either undef or the same as the first
11161   // non-undef value.
11162   for (int Idx = Mask[i]; i != e; ++i)
11163     if (Mask[i] >= 0 && Mask[i] != Idx)
11164       return false;
11165   return true;
11166 }
11167 
11168 // Returns the SDNode if it is a constant integer BuildVector
11169 // or constant integer.
11170 SDNode *SelectionDAG::isConstantIntBuildVectorOrConstantInt(SDValue N) const {
11171   if (isa<ConstantSDNode>(N))
11172     return N.getNode();
11173   if (ISD::isBuildVectorOfConstantSDNodes(N.getNode()))
11174     return N.getNode();
11175   // Treat a GlobalAddress supporting constant offset folding as a
11176   // constant integer.
11177   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N))
11178     if (GA->getOpcode() == ISD::GlobalAddress &&
11179         TLI->isOffsetFoldingLegal(GA))
11180       return GA;
11181   if ((N.getOpcode() == ISD::SPLAT_VECTOR) &&
11182       isa<ConstantSDNode>(N.getOperand(0)))
11183     return N.getNode();
11184   return nullptr;
11185 }
11186 
11187 // Returns the SDNode if it is a constant float BuildVector
11188 // or constant float.
11189 SDNode *SelectionDAG::isConstantFPBuildVectorOrConstantFP(SDValue N) const {
11190   if (isa<ConstantFPSDNode>(N))
11191     return N.getNode();
11192 
11193   if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode()))
11194     return N.getNode();
11195 
11196   if ((N.getOpcode() == ISD::SPLAT_VECTOR) &&
11197       isa<ConstantFPSDNode>(N.getOperand(0)))
11198     return N.getNode();
11199 
11200   return nullptr;
11201 }
11202 
11203 void SelectionDAG::createOperands(SDNode *Node, ArrayRef<SDValue> Vals) {
11204   assert(!Node->OperandList && "Node already has operands");
11205   assert(SDNode::getMaxNumOperands() >= Vals.size() &&
11206          "too many operands to fit into SDNode");
11207   SDUse *Ops = OperandRecycler.allocate(
11208       ArrayRecycler<SDUse>::Capacity::get(Vals.size()), OperandAllocator);
11209 
11210   bool IsDivergent = false;
11211   for (unsigned I = 0; I != Vals.size(); ++I) {
11212     Ops[I].setUser(Node);
11213     Ops[I].setInitial(Vals[I]);
11214     if (Ops[I].Val.getValueType() != MVT::Other) // Skip Chain. It does not carry divergence.
11215       IsDivergent |= Ops[I].getNode()->isDivergent();
11216   }
11217   Node->NumOperands = Vals.size();
11218   Node->OperandList = Ops;
11219   if (!TLI->isSDNodeAlwaysUniform(Node)) {
11220     IsDivergent |= TLI->isSDNodeSourceOfDivergence(Node, FLI, DA);
11221     Node->SDNodeBits.IsDivergent = IsDivergent;
11222   }
11223   checkForCycles(Node);
11224 }
11225 
11226 SDValue SelectionDAG::getTokenFactor(const SDLoc &DL,
11227                                      SmallVectorImpl<SDValue> &Vals) {
11228   size_t Limit = SDNode::getMaxNumOperands();
11229   while (Vals.size() > Limit) {
11230     unsigned SliceIdx = Vals.size() - Limit;
11231     auto ExtractedTFs = ArrayRef<SDValue>(Vals).slice(SliceIdx, Limit);
11232     SDValue NewTF = getNode(ISD::TokenFactor, DL, MVT::Other, ExtractedTFs);
11233     Vals.erase(Vals.begin() + SliceIdx, Vals.end());
11234     Vals.emplace_back(NewTF);
11235   }
11236   return getNode(ISD::TokenFactor, DL, MVT::Other, Vals);
11237 }
11238 
11239 SDValue SelectionDAG::getNeutralElement(unsigned Opcode, const SDLoc &DL,
11240                                         EVT VT, SDNodeFlags Flags) {
11241   switch (Opcode) {
11242   default:
11243     return SDValue();
11244   case ISD::ADD:
11245   case ISD::OR:
11246   case ISD::XOR:
11247   case ISD::UMAX:
11248     return getConstant(0, DL, VT);
11249   case ISD::MUL:
11250     return getConstant(1, DL, VT);
11251   case ISD::AND:
11252   case ISD::UMIN:
11253     return getAllOnesConstant(DL, VT);
11254   case ISD::SMAX:
11255     return getConstant(APInt::getSignedMinValue(VT.getSizeInBits()), DL, VT);
11256   case ISD::SMIN:
11257     return getConstant(APInt::getSignedMaxValue(VT.getSizeInBits()), DL, VT);
11258   case ISD::FADD:
11259     return getConstantFP(-0.0, DL, VT);
11260   case ISD::FMUL:
11261     return getConstantFP(1.0, DL, VT);
11262   case ISD::FMINNUM:
11263   case ISD::FMAXNUM: {
11264     // Neutral element for fminnum is NaN, Inf or FLT_MAX, depending on FMF.
11265     const fltSemantics &Semantics = EVTToAPFloatSemantics(VT);
11266     APFloat NeutralAF = !Flags.hasNoNaNs() ? APFloat::getQNaN(Semantics) :
11267                         !Flags.hasNoInfs() ? APFloat::getInf(Semantics) :
11268                         APFloat::getLargest(Semantics);
11269     if (Opcode == ISD::FMAXNUM)
11270       NeutralAF.changeSign();
11271 
11272     return getConstantFP(NeutralAF, DL, VT);
11273   }
11274   }
11275 }
11276 
11277 #ifndef NDEBUG
11278 static void checkForCyclesHelper(const SDNode *N,
11279                                  SmallPtrSetImpl<const SDNode*> &Visited,
11280                                  SmallPtrSetImpl<const SDNode*> &Checked,
11281                                  const llvm::SelectionDAG *DAG) {
11282   // If this node has already been checked, don't check it again.
11283   if (Checked.count(N))
11284     return;
11285 
11286   // If a node has already been visited on this depth-first walk, reject it as
11287   // a cycle.
11288   if (!Visited.insert(N).second) {
11289     errs() << "Detected cycle in SelectionDAG\n";
11290     dbgs() << "Offending node:\n";
11291     N->dumprFull(DAG); dbgs() << "\n";
11292     abort();
11293   }
11294 
11295   for (const SDValue &Op : N->op_values())
11296     checkForCyclesHelper(Op.getNode(), Visited, Checked, DAG);
11297 
11298   Checked.insert(N);
11299   Visited.erase(N);
11300 }
11301 #endif
11302 
11303 void llvm::checkForCycles(const llvm::SDNode *N,
11304                           const llvm::SelectionDAG *DAG,
11305                           bool force) {
11306 #ifndef NDEBUG
11307   bool check = force;
11308 #ifdef EXPENSIVE_CHECKS
11309   check = true;
11310 #endif  // EXPENSIVE_CHECKS
11311   if (check) {
11312     assert(N && "Checking nonexistent SDNode");
11313     SmallPtrSet<const SDNode*, 32> visited;
11314     SmallPtrSet<const SDNode*, 32> checked;
11315     checkForCyclesHelper(N, visited, checked, DAG);
11316   }
11317 #endif  // !NDEBUG
11318 }
11319 
11320 void llvm::checkForCycles(const llvm::SelectionDAG *DAG, bool force) {
11321   checkForCycles(DAG->getRoot().getNode(), DAG, force);
11322 }
11323