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     return ISD::FADD;
377   case ISD::VECREDUCE_FMUL:
378   case ISD::VECREDUCE_SEQ_FMUL:
379     return ISD::FMUL;
380   case ISD::VECREDUCE_ADD:
381     return ISD::ADD;
382   case ISD::VECREDUCE_MUL:
383     return ISD::MUL;
384   case ISD::VECREDUCE_AND:
385     return ISD::AND;
386   case ISD::VECREDUCE_OR:
387     return ISD::OR;
388   case ISD::VECREDUCE_XOR:
389     return ISD::XOR;
390   case ISD::VECREDUCE_SMAX:
391     return ISD::SMAX;
392   case ISD::VECREDUCE_SMIN:
393     return ISD::SMIN;
394   case ISD::VECREDUCE_UMAX:
395     return ISD::UMAX;
396   case ISD::VECREDUCE_UMIN:
397     return ISD::UMIN;
398   case ISD::VECREDUCE_FMAX:
399     return ISD::FMAXNUM;
400   case ISD::VECREDUCE_FMIN:
401     return ISD::FMINNUM;
402   }
403 }
404 
405 bool ISD::isVPOpcode(unsigned Opcode) {
406   switch (Opcode) {
407   default:
408     return false;
409 #define BEGIN_REGISTER_VP_SDNODE(VPSD, ...)                                    \
410   case ISD::VPSD:                                                              \
411     return true;
412 #include "llvm/IR/VPIntrinsics.def"
413   }
414 }
415 
416 bool ISD::isVPBinaryOp(unsigned Opcode) {
417   switch (Opcode) {
418   default:
419     break;
420 #define BEGIN_REGISTER_VP_SDNODE(VPSD, ...) case ISD::VPSD:
421 #define VP_PROPERTY_BINARYOP return true;
422 #define END_REGISTER_VP_SDNODE(VPSD) break;
423 #include "llvm/IR/VPIntrinsics.def"
424   }
425   return false;
426 }
427 
428 bool ISD::isVPReduction(unsigned Opcode) {
429   switch (Opcode) {
430   default:
431     break;
432 #define BEGIN_REGISTER_VP_SDNODE(VPSD, ...) case ISD::VPSD:
433 #define VP_PROPERTY_REDUCTION(STARTPOS, ...) return true;
434 #define END_REGISTER_VP_SDNODE(VPSD) break;
435 #include "llvm/IR/VPIntrinsics.def"
436   }
437   return false;
438 }
439 
440 /// The operand position of the vector mask.
441 Optional<unsigned> ISD::getVPMaskIdx(unsigned Opcode) {
442   switch (Opcode) {
443   default:
444     return None;
445 #define BEGIN_REGISTER_VP_SDNODE(VPSD, LEGALPOS, TDNAME, MASKPOS, ...)         \
446   case ISD::VPSD:                                                              \
447     return MASKPOS;
448 #include "llvm/IR/VPIntrinsics.def"
449   }
450 }
451 
452 /// The operand position of the explicit vector length parameter.
453 Optional<unsigned> ISD::getVPExplicitVectorLengthIdx(unsigned Opcode) {
454   switch (Opcode) {
455   default:
456     return None;
457 #define BEGIN_REGISTER_VP_SDNODE(VPSD, LEGALPOS, TDNAME, MASKPOS, EVLPOS)      \
458   case ISD::VPSD:                                                              \
459     return EVLPOS;
460 #include "llvm/IR/VPIntrinsics.def"
461   }
462 }
463 
464 ISD::NodeType ISD::getExtForLoadExtType(bool IsFP, ISD::LoadExtType ExtType) {
465   switch (ExtType) {
466   case ISD::EXTLOAD:
467     return IsFP ? ISD::FP_EXTEND : ISD::ANY_EXTEND;
468   case ISD::SEXTLOAD:
469     return ISD::SIGN_EXTEND;
470   case ISD::ZEXTLOAD:
471     return ISD::ZERO_EXTEND;
472   default:
473     break;
474   }
475 
476   llvm_unreachable("Invalid LoadExtType");
477 }
478 
479 ISD::CondCode ISD::getSetCCSwappedOperands(ISD::CondCode Operation) {
480   // To perform this operation, we just need to swap the L and G bits of the
481   // operation.
482   unsigned OldL = (Operation >> 2) & 1;
483   unsigned OldG = (Operation >> 1) & 1;
484   return ISD::CondCode((Operation & ~6) |  // Keep the N, U, E bits
485                        (OldL << 1) |       // New G bit
486                        (OldG << 2));       // New L bit.
487 }
488 
489 static ISD::CondCode getSetCCInverseImpl(ISD::CondCode Op, bool isIntegerLike) {
490   unsigned Operation = Op;
491   if (isIntegerLike)
492     Operation ^= 7;   // Flip L, G, E bits, but not U.
493   else
494     Operation ^= 15;  // Flip all of the condition bits.
495 
496   if (Operation > ISD::SETTRUE2)
497     Operation &= ~8;  // Don't let N and U bits get set.
498 
499   return ISD::CondCode(Operation);
500 }
501 
502 ISD::CondCode ISD::getSetCCInverse(ISD::CondCode Op, EVT Type) {
503   return getSetCCInverseImpl(Op, Type.isInteger());
504 }
505 
506 ISD::CondCode ISD::GlobalISel::getSetCCInverse(ISD::CondCode Op,
507                                                bool isIntegerLike) {
508   return getSetCCInverseImpl(Op, isIntegerLike);
509 }
510 
511 /// For an integer comparison, return 1 if the comparison is a signed operation
512 /// and 2 if the result is an unsigned comparison. Return zero if the operation
513 /// does not depend on the sign of the input (setne and seteq).
514 static int isSignedOp(ISD::CondCode Opcode) {
515   switch (Opcode) {
516   default: llvm_unreachable("Illegal integer setcc operation!");
517   case ISD::SETEQ:
518   case ISD::SETNE: return 0;
519   case ISD::SETLT:
520   case ISD::SETLE:
521   case ISD::SETGT:
522   case ISD::SETGE: return 1;
523   case ISD::SETULT:
524   case ISD::SETULE:
525   case ISD::SETUGT:
526   case ISD::SETUGE: return 2;
527   }
528 }
529 
530 ISD::CondCode ISD::getSetCCOrOperation(ISD::CondCode Op1, ISD::CondCode Op2,
531                                        EVT Type) {
532   bool IsInteger = Type.isInteger();
533   if (IsInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
534     // Cannot fold a signed integer setcc with an unsigned integer setcc.
535     return ISD::SETCC_INVALID;
536 
537   unsigned Op = Op1 | Op2;  // Combine all of the condition bits.
538 
539   // If the N and U bits get set, then the resultant comparison DOES suddenly
540   // care about orderedness, and it is true when ordered.
541   if (Op > ISD::SETTRUE2)
542     Op &= ~16;     // Clear the U bit if the N bit is set.
543 
544   // Canonicalize illegal integer setcc's.
545   if (IsInteger && Op == ISD::SETUNE)  // e.g. SETUGT | SETULT
546     Op = ISD::SETNE;
547 
548   return ISD::CondCode(Op);
549 }
550 
551 ISD::CondCode ISD::getSetCCAndOperation(ISD::CondCode Op1, ISD::CondCode Op2,
552                                         EVT Type) {
553   bool IsInteger = Type.isInteger();
554   if (IsInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
555     // Cannot fold a signed setcc with an unsigned setcc.
556     return ISD::SETCC_INVALID;
557 
558   // Combine all of the condition bits.
559   ISD::CondCode Result = ISD::CondCode(Op1 & Op2);
560 
561   // Canonicalize illegal integer setcc's.
562   if (IsInteger) {
563     switch (Result) {
564     default: break;
565     case ISD::SETUO : Result = ISD::SETFALSE; break;  // SETUGT & SETULT
566     case ISD::SETOEQ:                                 // SETEQ  & SETU[LG]E
567     case ISD::SETUEQ: Result = ISD::SETEQ   ; break;  // SETUGE & SETULE
568     case ISD::SETOLT: Result = ISD::SETULT  ; break;  // SETULT & SETNE
569     case ISD::SETOGT: Result = ISD::SETUGT  ; break;  // SETUGT & SETNE
570     }
571   }
572 
573   return Result;
574 }
575 
576 //===----------------------------------------------------------------------===//
577 //                           SDNode Profile Support
578 //===----------------------------------------------------------------------===//
579 
580 /// AddNodeIDOpcode - Add the node opcode to the NodeID data.
581 static void AddNodeIDOpcode(FoldingSetNodeID &ID, unsigned OpC)  {
582   ID.AddInteger(OpC);
583 }
584 
585 /// AddNodeIDValueTypes - Value type lists are intern'd so we can represent them
586 /// solely with their pointer.
587 static void AddNodeIDValueTypes(FoldingSetNodeID &ID, SDVTList VTList) {
588   ID.AddPointer(VTList.VTs);
589 }
590 
591 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data.
592 static void AddNodeIDOperands(FoldingSetNodeID &ID,
593                               ArrayRef<SDValue> Ops) {
594   for (auto& Op : Ops) {
595     ID.AddPointer(Op.getNode());
596     ID.AddInteger(Op.getResNo());
597   }
598 }
599 
600 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data.
601 static void AddNodeIDOperands(FoldingSetNodeID &ID,
602                               ArrayRef<SDUse> Ops) {
603   for (auto& Op : Ops) {
604     ID.AddPointer(Op.getNode());
605     ID.AddInteger(Op.getResNo());
606   }
607 }
608 
609 static void AddNodeIDNode(FoldingSetNodeID &ID, unsigned short OpC,
610                           SDVTList VTList, ArrayRef<SDValue> OpList) {
611   AddNodeIDOpcode(ID, OpC);
612   AddNodeIDValueTypes(ID, VTList);
613   AddNodeIDOperands(ID, OpList);
614 }
615 
616 /// If this is an SDNode with special info, add this info to the NodeID data.
617 static void AddNodeIDCustom(FoldingSetNodeID &ID, const SDNode *N) {
618   switch (N->getOpcode()) {
619   case ISD::TargetExternalSymbol:
620   case ISD::ExternalSymbol:
621   case ISD::MCSymbol:
622     llvm_unreachable("Should only be used on nodes with operands");
623   default: break;  // Normal nodes don't need extra info.
624   case ISD::TargetConstant:
625   case ISD::Constant: {
626     const ConstantSDNode *C = cast<ConstantSDNode>(N);
627     ID.AddPointer(C->getConstantIntValue());
628     ID.AddBoolean(C->isOpaque());
629     break;
630   }
631   case ISD::TargetConstantFP:
632   case ISD::ConstantFP:
633     ID.AddPointer(cast<ConstantFPSDNode>(N)->getConstantFPValue());
634     break;
635   case ISD::TargetGlobalAddress:
636   case ISD::GlobalAddress:
637   case ISD::TargetGlobalTLSAddress:
638   case ISD::GlobalTLSAddress: {
639     const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(N);
640     ID.AddPointer(GA->getGlobal());
641     ID.AddInteger(GA->getOffset());
642     ID.AddInteger(GA->getTargetFlags());
643     break;
644   }
645   case ISD::BasicBlock:
646     ID.AddPointer(cast<BasicBlockSDNode>(N)->getBasicBlock());
647     break;
648   case ISD::Register:
649     ID.AddInteger(cast<RegisterSDNode>(N)->getReg());
650     break;
651   case ISD::RegisterMask:
652     ID.AddPointer(cast<RegisterMaskSDNode>(N)->getRegMask());
653     break;
654   case ISD::SRCVALUE:
655     ID.AddPointer(cast<SrcValueSDNode>(N)->getValue());
656     break;
657   case ISD::FrameIndex:
658   case ISD::TargetFrameIndex:
659     ID.AddInteger(cast<FrameIndexSDNode>(N)->getIndex());
660     break;
661   case ISD::LIFETIME_START:
662   case ISD::LIFETIME_END:
663     if (cast<LifetimeSDNode>(N)->hasOffset()) {
664       ID.AddInteger(cast<LifetimeSDNode>(N)->getSize());
665       ID.AddInteger(cast<LifetimeSDNode>(N)->getOffset());
666     }
667     break;
668   case ISD::PSEUDO_PROBE:
669     ID.AddInteger(cast<PseudoProbeSDNode>(N)->getGuid());
670     ID.AddInteger(cast<PseudoProbeSDNode>(N)->getIndex());
671     ID.AddInteger(cast<PseudoProbeSDNode>(N)->getAttributes());
672     break;
673   case ISD::JumpTable:
674   case ISD::TargetJumpTable:
675     ID.AddInteger(cast<JumpTableSDNode>(N)->getIndex());
676     ID.AddInteger(cast<JumpTableSDNode>(N)->getTargetFlags());
677     break;
678   case ISD::ConstantPool:
679   case ISD::TargetConstantPool: {
680     const ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(N);
681     ID.AddInteger(CP->getAlign().value());
682     ID.AddInteger(CP->getOffset());
683     if (CP->isMachineConstantPoolEntry())
684       CP->getMachineCPVal()->addSelectionDAGCSEId(ID);
685     else
686       ID.AddPointer(CP->getConstVal());
687     ID.AddInteger(CP->getTargetFlags());
688     break;
689   }
690   case ISD::TargetIndex: {
691     const TargetIndexSDNode *TI = cast<TargetIndexSDNode>(N);
692     ID.AddInteger(TI->getIndex());
693     ID.AddInteger(TI->getOffset());
694     ID.AddInteger(TI->getTargetFlags());
695     break;
696   }
697   case ISD::LOAD: {
698     const LoadSDNode *LD = cast<LoadSDNode>(N);
699     ID.AddInteger(LD->getMemoryVT().getRawBits());
700     ID.AddInteger(LD->getRawSubclassData());
701     ID.AddInteger(LD->getPointerInfo().getAddrSpace());
702     break;
703   }
704   case ISD::STORE: {
705     const StoreSDNode *ST = cast<StoreSDNode>(N);
706     ID.AddInteger(ST->getMemoryVT().getRawBits());
707     ID.AddInteger(ST->getRawSubclassData());
708     ID.AddInteger(ST->getPointerInfo().getAddrSpace());
709     break;
710   }
711   case ISD::VP_LOAD: {
712     const VPLoadSDNode *ELD = cast<VPLoadSDNode>(N);
713     ID.AddInteger(ELD->getMemoryVT().getRawBits());
714     ID.AddInteger(ELD->getRawSubclassData());
715     ID.AddInteger(ELD->getPointerInfo().getAddrSpace());
716     break;
717   }
718   case ISD::VP_STORE: {
719     const VPStoreSDNode *EST = cast<VPStoreSDNode>(N);
720     ID.AddInteger(EST->getMemoryVT().getRawBits());
721     ID.AddInteger(EST->getRawSubclassData());
722     ID.AddInteger(EST->getPointerInfo().getAddrSpace());
723     break;
724   }
725   case ISD::VP_GATHER: {
726     const VPGatherSDNode *EG = cast<VPGatherSDNode>(N);
727     ID.AddInteger(EG->getMemoryVT().getRawBits());
728     ID.AddInteger(EG->getRawSubclassData());
729     ID.AddInteger(EG->getPointerInfo().getAddrSpace());
730     break;
731   }
732   case ISD::VP_SCATTER: {
733     const VPScatterSDNode *ES = cast<VPScatterSDNode>(N);
734     ID.AddInteger(ES->getMemoryVT().getRawBits());
735     ID.AddInteger(ES->getRawSubclassData());
736     ID.AddInteger(ES->getPointerInfo().getAddrSpace());
737     break;
738   }
739   case ISD::MLOAD: {
740     const MaskedLoadSDNode *MLD = cast<MaskedLoadSDNode>(N);
741     ID.AddInteger(MLD->getMemoryVT().getRawBits());
742     ID.AddInteger(MLD->getRawSubclassData());
743     ID.AddInteger(MLD->getPointerInfo().getAddrSpace());
744     break;
745   }
746   case ISD::MSTORE: {
747     const MaskedStoreSDNode *MST = cast<MaskedStoreSDNode>(N);
748     ID.AddInteger(MST->getMemoryVT().getRawBits());
749     ID.AddInteger(MST->getRawSubclassData());
750     ID.AddInteger(MST->getPointerInfo().getAddrSpace());
751     break;
752   }
753   case ISD::MGATHER: {
754     const MaskedGatherSDNode *MG = cast<MaskedGatherSDNode>(N);
755     ID.AddInteger(MG->getMemoryVT().getRawBits());
756     ID.AddInteger(MG->getRawSubclassData());
757     ID.AddInteger(MG->getPointerInfo().getAddrSpace());
758     break;
759   }
760   case ISD::MSCATTER: {
761     const MaskedScatterSDNode *MS = cast<MaskedScatterSDNode>(N);
762     ID.AddInteger(MS->getMemoryVT().getRawBits());
763     ID.AddInteger(MS->getRawSubclassData());
764     ID.AddInteger(MS->getPointerInfo().getAddrSpace());
765     break;
766   }
767   case ISD::ATOMIC_CMP_SWAP:
768   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
769   case ISD::ATOMIC_SWAP:
770   case ISD::ATOMIC_LOAD_ADD:
771   case ISD::ATOMIC_LOAD_SUB:
772   case ISD::ATOMIC_LOAD_AND:
773   case ISD::ATOMIC_LOAD_CLR:
774   case ISD::ATOMIC_LOAD_OR:
775   case ISD::ATOMIC_LOAD_XOR:
776   case ISD::ATOMIC_LOAD_NAND:
777   case ISD::ATOMIC_LOAD_MIN:
778   case ISD::ATOMIC_LOAD_MAX:
779   case ISD::ATOMIC_LOAD_UMIN:
780   case ISD::ATOMIC_LOAD_UMAX:
781   case ISD::ATOMIC_LOAD:
782   case ISD::ATOMIC_STORE: {
783     const AtomicSDNode *AT = cast<AtomicSDNode>(N);
784     ID.AddInteger(AT->getMemoryVT().getRawBits());
785     ID.AddInteger(AT->getRawSubclassData());
786     ID.AddInteger(AT->getPointerInfo().getAddrSpace());
787     break;
788   }
789   case ISD::PREFETCH: {
790     const MemSDNode *PF = cast<MemSDNode>(N);
791     ID.AddInteger(PF->getPointerInfo().getAddrSpace());
792     break;
793   }
794   case ISD::VECTOR_SHUFFLE: {
795     const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
796     for (unsigned i = 0, e = N->getValueType(0).getVectorNumElements();
797          i != e; ++i)
798       ID.AddInteger(SVN->getMaskElt(i));
799     break;
800   }
801   case ISD::TargetBlockAddress:
802   case ISD::BlockAddress: {
803     const BlockAddressSDNode *BA = cast<BlockAddressSDNode>(N);
804     ID.AddPointer(BA->getBlockAddress());
805     ID.AddInteger(BA->getOffset());
806     ID.AddInteger(BA->getTargetFlags());
807     break;
808   }
809   } // end switch (N->getOpcode())
810 
811   // Target specific memory nodes could also have address spaces to check.
812   if (N->isTargetMemoryOpcode())
813     ID.AddInteger(cast<MemSDNode>(N)->getPointerInfo().getAddrSpace());
814 }
815 
816 /// AddNodeIDNode - Generic routine for adding a nodes info to the NodeID
817 /// data.
818 static void AddNodeIDNode(FoldingSetNodeID &ID, const SDNode *N) {
819   AddNodeIDOpcode(ID, N->getOpcode());
820   // Add the return value info.
821   AddNodeIDValueTypes(ID, N->getVTList());
822   // Add the operand info.
823   AddNodeIDOperands(ID, N->ops());
824 
825   // Handle SDNode leafs with special info.
826   AddNodeIDCustom(ID, N);
827 }
828 
829 //===----------------------------------------------------------------------===//
830 //                              SelectionDAG Class
831 //===----------------------------------------------------------------------===//
832 
833 /// doNotCSE - Return true if CSE should not be performed for this node.
834 static bool doNotCSE(SDNode *N) {
835   if (N->getValueType(0) == MVT::Glue)
836     return true; // Never CSE anything that produces a flag.
837 
838   switch (N->getOpcode()) {
839   default: break;
840   case ISD::HANDLENODE:
841   case ISD::EH_LABEL:
842     return true;   // Never CSE these nodes.
843   }
844 
845   // Check that remaining values produced are not flags.
846   for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
847     if (N->getValueType(i) == MVT::Glue)
848       return true; // Never CSE anything that produces a flag.
849 
850   return false;
851 }
852 
853 /// RemoveDeadNodes - This method deletes all unreachable nodes in the
854 /// SelectionDAG.
855 void SelectionDAG::RemoveDeadNodes() {
856   // Create a dummy node (which is not added to allnodes), that adds a reference
857   // to the root node, preventing it from being deleted.
858   HandleSDNode Dummy(getRoot());
859 
860   SmallVector<SDNode*, 128> DeadNodes;
861 
862   // Add all obviously-dead nodes to the DeadNodes worklist.
863   for (SDNode &Node : allnodes())
864     if (Node.use_empty())
865       DeadNodes.push_back(&Node);
866 
867   RemoveDeadNodes(DeadNodes);
868 
869   // If the root changed (e.g. it was a dead load, update the root).
870   setRoot(Dummy.getValue());
871 }
872 
873 /// RemoveDeadNodes - This method deletes the unreachable nodes in the
874 /// given list, and any nodes that become unreachable as a result.
875 void SelectionDAG::RemoveDeadNodes(SmallVectorImpl<SDNode *> &DeadNodes) {
876 
877   // Process the worklist, deleting the nodes and adding their uses to the
878   // worklist.
879   while (!DeadNodes.empty()) {
880     SDNode *N = DeadNodes.pop_back_val();
881     // Skip to next node if we've already managed to delete the node. This could
882     // happen if replacing a node causes a node previously added to the node to
883     // be deleted.
884     if (N->getOpcode() == ISD::DELETED_NODE)
885       continue;
886 
887     for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
888       DUL->NodeDeleted(N, nullptr);
889 
890     // Take the node out of the appropriate CSE map.
891     RemoveNodeFromCSEMaps(N);
892 
893     // Next, brutally remove the operand list.  This is safe to do, as there are
894     // no cycles in the graph.
895     for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) {
896       SDUse &Use = *I++;
897       SDNode *Operand = Use.getNode();
898       Use.set(SDValue());
899 
900       // Now that we removed this operand, see if there are no uses of it left.
901       if (Operand->use_empty())
902         DeadNodes.push_back(Operand);
903     }
904 
905     DeallocateNode(N);
906   }
907 }
908 
909 void SelectionDAG::RemoveDeadNode(SDNode *N){
910   SmallVector<SDNode*, 16> DeadNodes(1, N);
911 
912   // Create a dummy node that adds a reference to the root node, preventing
913   // it from being deleted.  (This matters if the root is an operand of the
914   // dead node.)
915   HandleSDNode Dummy(getRoot());
916 
917   RemoveDeadNodes(DeadNodes);
918 }
919 
920 void SelectionDAG::DeleteNode(SDNode *N) {
921   // First take this out of the appropriate CSE map.
922   RemoveNodeFromCSEMaps(N);
923 
924   // Finally, remove uses due to operands of this node, remove from the
925   // AllNodes list, and delete the node.
926   DeleteNodeNotInCSEMaps(N);
927 }
928 
929 void SelectionDAG::DeleteNodeNotInCSEMaps(SDNode *N) {
930   assert(N->getIterator() != AllNodes.begin() &&
931          "Cannot delete the entry node!");
932   assert(N->use_empty() && "Cannot delete a node that is not dead!");
933 
934   // Drop all of the operands and decrement used node's use counts.
935   N->DropOperands();
936 
937   DeallocateNode(N);
938 }
939 
940 void SDDbgInfo::add(SDDbgValue *V, bool isParameter) {
941   assert(!(V->isVariadic() && isParameter));
942   if (isParameter)
943     ByvalParmDbgValues.push_back(V);
944   else
945     DbgValues.push_back(V);
946   for (const SDNode *Node : V->getSDNodes())
947     if (Node)
948       DbgValMap[Node].push_back(V);
949 }
950 
951 void SDDbgInfo::erase(const SDNode *Node) {
952   DbgValMapType::iterator I = DbgValMap.find(Node);
953   if (I == DbgValMap.end())
954     return;
955   for (auto &Val: I->second)
956     Val->setIsInvalidated();
957   DbgValMap.erase(I);
958 }
959 
960 void SelectionDAG::DeallocateNode(SDNode *N) {
961   // If we have operands, deallocate them.
962   removeOperands(N);
963 
964   NodeAllocator.Deallocate(AllNodes.remove(N));
965 
966   // Set the opcode to DELETED_NODE to help catch bugs when node
967   // memory is reallocated.
968   // FIXME: There are places in SDag that have grown a dependency on the opcode
969   // value in the released node.
970   __asan_unpoison_memory_region(&N->NodeType, sizeof(N->NodeType));
971   N->NodeType = ISD::DELETED_NODE;
972 
973   // If any of the SDDbgValue nodes refer to this SDNode, invalidate
974   // them and forget about that node.
975   DbgInfo->erase(N);
976 }
977 
978 #ifndef NDEBUG
979 /// VerifySDNode - Check the given SDNode.  Aborts if it is invalid.
980 static void VerifySDNode(SDNode *N) {
981   switch (N->getOpcode()) {
982   default:
983     break;
984   case ISD::BUILD_PAIR: {
985     EVT VT = N->getValueType(0);
986     assert(N->getNumValues() == 1 && "Too many results!");
987     assert(!VT.isVector() && (VT.isInteger() || VT.isFloatingPoint()) &&
988            "Wrong return type!");
989     assert(N->getNumOperands() == 2 && "Wrong number of operands!");
990     assert(N->getOperand(0).getValueType() == N->getOperand(1).getValueType() &&
991            "Mismatched operand types!");
992     assert(N->getOperand(0).getValueType().isInteger() == VT.isInteger() &&
993            "Wrong operand type!");
994     assert(VT.getSizeInBits() == 2 * N->getOperand(0).getValueSizeInBits() &&
995            "Wrong return type size");
996     break;
997   }
998   case ISD::BUILD_VECTOR: {
999     assert(N->getNumValues() == 1 && "Too many results!");
1000     assert(N->getValueType(0).isVector() && "Wrong return type!");
1001     assert(N->getNumOperands() == N->getValueType(0).getVectorNumElements() &&
1002            "Wrong number of operands!");
1003     EVT EltVT = N->getValueType(0).getVectorElementType();
1004     for (const SDUse &Op : N->ops()) {
1005       assert((Op.getValueType() == EltVT ||
1006               (EltVT.isInteger() && Op.getValueType().isInteger() &&
1007                EltVT.bitsLE(Op.getValueType()))) &&
1008              "Wrong operand type!");
1009       assert(Op.getValueType() == N->getOperand(0).getValueType() &&
1010              "Operands must all have the same type");
1011     }
1012     break;
1013   }
1014   }
1015 }
1016 #endif // NDEBUG
1017 
1018 /// Insert a newly allocated node into the DAG.
1019 ///
1020 /// Handles insertion into the all nodes list and CSE map, as well as
1021 /// verification and other common operations when a new node is allocated.
1022 void SelectionDAG::InsertNode(SDNode *N) {
1023   AllNodes.push_back(N);
1024 #ifndef NDEBUG
1025   N->PersistentId = NextPersistentId++;
1026   VerifySDNode(N);
1027 #endif
1028   for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
1029     DUL->NodeInserted(N);
1030 }
1031 
1032 /// RemoveNodeFromCSEMaps - Take the specified node out of the CSE map that
1033 /// correspond to it.  This is useful when we're about to delete or repurpose
1034 /// the node.  We don't want future request for structurally identical nodes
1035 /// to return N anymore.
1036 bool SelectionDAG::RemoveNodeFromCSEMaps(SDNode *N) {
1037   bool Erased = false;
1038   switch (N->getOpcode()) {
1039   case ISD::HANDLENODE: return false;  // noop.
1040   case ISD::CONDCODE:
1041     assert(CondCodeNodes[cast<CondCodeSDNode>(N)->get()] &&
1042            "Cond code doesn't exist!");
1043     Erased = CondCodeNodes[cast<CondCodeSDNode>(N)->get()] != nullptr;
1044     CondCodeNodes[cast<CondCodeSDNode>(N)->get()] = nullptr;
1045     break;
1046   case ISD::ExternalSymbol:
1047     Erased = ExternalSymbols.erase(cast<ExternalSymbolSDNode>(N)->getSymbol());
1048     break;
1049   case ISD::TargetExternalSymbol: {
1050     ExternalSymbolSDNode *ESN = cast<ExternalSymbolSDNode>(N);
1051     Erased = TargetExternalSymbols.erase(std::pair<std::string, unsigned>(
1052         ESN->getSymbol(), ESN->getTargetFlags()));
1053     break;
1054   }
1055   case ISD::MCSymbol: {
1056     auto *MCSN = cast<MCSymbolSDNode>(N);
1057     Erased = MCSymbols.erase(MCSN->getMCSymbol());
1058     break;
1059   }
1060   case ISD::VALUETYPE: {
1061     EVT VT = cast<VTSDNode>(N)->getVT();
1062     if (VT.isExtended()) {
1063       Erased = ExtendedValueTypeNodes.erase(VT);
1064     } else {
1065       Erased = ValueTypeNodes[VT.getSimpleVT().SimpleTy] != nullptr;
1066       ValueTypeNodes[VT.getSimpleVT().SimpleTy] = nullptr;
1067     }
1068     break;
1069   }
1070   default:
1071     // Remove it from the CSE Map.
1072     assert(N->getOpcode() != ISD::DELETED_NODE && "DELETED_NODE in CSEMap!");
1073     assert(N->getOpcode() != ISD::EntryToken && "EntryToken in CSEMap!");
1074     Erased = CSEMap.RemoveNode(N);
1075     break;
1076   }
1077 #ifndef NDEBUG
1078   // Verify that the node was actually in one of the CSE maps, unless it has a
1079   // flag result (which cannot be CSE'd) or is one of the special cases that are
1080   // not subject to CSE.
1081   if (!Erased && N->getValueType(N->getNumValues()-1) != MVT::Glue &&
1082       !N->isMachineOpcode() && !doNotCSE(N)) {
1083     N->dump(this);
1084     dbgs() << "\n";
1085     llvm_unreachable("Node is not in map!");
1086   }
1087 #endif
1088   return Erased;
1089 }
1090 
1091 /// AddModifiedNodeToCSEMaps - The specified node has been removed from the CSE
1092 /// maps and modified in place. Add it back to the CSE maps, unless an identical
1093 /// node already exists, in which case transfer all its users to the existing
1094 /// node. This transfer can potentially trigger recursive merging.
1095 void
1096 SelectionDAG::AddModifiedNodeToCSEMaps(SDNode *N) {
1097   // For node types that aren't CSE'd, just act as if no identical node
1098   // already exists.
1099   if (!doNotCSE(N)) {
1100     SDNode *Existing = CSEMap.GetOrInsertNode(N);
1101     if (Existing != N) {
1102       // If there was already an existing matching node, use ReplaceAllUsesWith
1103       // to replace the dead one with the existing one.  This can cause
1104       // recursive merging of other unrelated nodes down the line.
1105       ReplaceAllUsesWith(N, Existing);
1106 
1107       // N is now dead. Inform the listeners and delete it.
1108       for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
1109         DUL->NodeDeleted(N, Existing);
1110       DeleteNodeNotInCSEMaps(N);
1111       return;
1112     }
1113   }
1114 
1115   // If the node doesn't already exist, we updated it.  Inform listeners.
1116   for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
1117     DUL->NodeUpdated(N);
1118 }
1119 
1120 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
1121 /// were replaced with those specified.  If this node is never memoized,
1122 /// return null, otherwise return a pointer to the slot it would take.  If a
1123 /// node already exists with these operands, the slot will be non-null.
1124 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, SDValue Op,
1125                                            void *&InsertPos) {
1126   if (doNotCSE(N))
1127     return nullptr;
1128 
1129   SDValue Ops[] = { Op };
1130   FoldingSetNodeID ID;
1131   AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops);
1132   AddNodeIDCustom(ID, N);
1133   SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos);
1134   if (Node)
1135     Node->intersectFlagsWith(N->getFlags());
1136   return Node;
1137 }
1138 
1139 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
1140 /// were replaced with those specified.  If this node is never memoized,
1141 /// return null, otherwise return a pointer to the slot it would take.  If a
1142 /// node already exists with these operands, the slot will be non-null.
1143 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N,
1144                                            SDValue Op1, SDValue Op2,
1145                                            void *&InsertPos) {
1146   if (doNotCSE(N))
1147     return nullptr;
1148 
1149   SDValue Ops[] = { Op1, Op2 };
1150   FoldingSetNodeID ID;
1151   AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops);
1152   AddNodeIDCustom(ID, N);
1153   SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos);
1154   if (Node)
1155     Node->intersectFlagsWith(N->getFlags());
1156   return Node;
1157 }
1158 
1159 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
1160 /// were replaced with those specified.  If this node is never memoized,
1161 /// return null, otherwise return a pointer to the slot it would take.  If a
1162 /// node already exists with these operands, the slot will be non-null.
1163 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, ArrayRef<SDValue> Ops,
1164                                            void *&InsertPos) {
1165   if (doNotCSE(N))
1166     return nullptr;
1167 
1168   FoldingSetNodeID ID;
1169   AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops);
1170   AddNodeIDCustom(ID, N);
1171   SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos);
1172   if (Node)
1173     Node->intersectFlagsWith(N->getFlags());
1174   return Node;
1175 }
1176 
1177 Align SelectionDAG::getEVTAlign(EVT VT) const {
1178   Type *Ty = VT == MVT::iPTR ?
1179                    PointerType::get(Type::getInt8Ty(*getContext()), 0) :
1180                    VT.getTypeForEVT(*getContext());
1181 
1182   return getDataLayout().getABITypeAlign(Ty);
1183 }
1184 
1185 // EntryNode could meaningfully have debug info if we can find it...
1186 SelectionDAG::SelectionDAG(const TargetMachine &tm, CodeGenOpt::Level OL)
1187     : TM(tm), OptLevel(OL),
1188       EntryNode(ISD::EntryToken, 0, DebugLoc(), getVTList(MVT::Other)),
1189       Root(getEntryNode()) {
1190   InsertNode(&EntryNode);
1191   DbgInfo = new SDDbgInfo();
1192 }
1193 
1194 void SelectionDAG::init(MachineFunction &NewMF,
1195                         OptimizationRemarkEmitter &NewORE,
1196                         Pass *PassPtr, const TargetLibraryInfo *LibraryInfo,
1197                         LegacyDivergenceAnalysis * Divergence,
1198                         ProfileSummaryInfo *PSIin,
1199                         BlockFrequencyInfo *BFIin) {
1200   MF = &NewMF;
1201   SDAGISelPass = PassPtr;
1202   ORE = &NewORE;
1203   TLI = getSubtarget().getTargetLowering();
1204   TSI = getSubtarget().getSelectionDAGInfo();
1205   LibInfo = LibraryInfo;
1206   Context = &MF->getFunction().getContext();
1207   DA = Divergence;
1208   PSI = PSIin;
1209   BFI = BFIin;
1210 }
1211 
1212 SelectionDAG::~SelectionDAG() {
1213   assert(!UpdateListeners && "Dangling registered DAGUpdateListeners");
1214   allnodes_clear();
1215   OperandRecycler.clear(OperandAllocator);
1216   delete DbgInfo;
1217 }
1218 
1219 bool SelectionDAG::shouldOptForSize() const {
1220   return MF->getFunction().hasOptSize() ||
1221       llvm::shouldOptimizeForSize(FLI->MBB->getBasicBlock(), PSI, BFI);
1222 }
1223 
1224 void SelectionDAG::allnodes_clear() {
1225   assert(&*AllNodes.begin() == &EntryNode);
1226   AllNodes.remove(AllNodes.begin());
1227   while (!AllNodes.empty())
1228     DeallocateNode(&AllNodes.front());
1229 #ifndef NDEBUG
1230   NextPersistentId = 0;
1231 #endif
1232 }
1233 
1234 SDNode *SelectionDAG::FindNodeOrInsertPos(const FoldingSetNodeID &ID,
1235                                           void *&InsertPos) {
1236   SDNode *N = CSEMap.FindNodeOrInsertPos(ID, InsertPos);
1237   if (N) {
1238     switch (N->getOpcode()) {
1239     default: break;
1240     case ISD::Constant:
1241     case ISD::ConstantFP:
1242       llvm_unreachable("Querying for Constant and ConstantFP nodes requires "
1243                        "debug location.  Use another overload.");
1244     }
1245   }
1246   return N;
1247 }
1248 
1249 SDNode *SelectionDAG::FindNodeOrInsertPos(const FoldingSetNodeID &ID,
1250                                           const SDLoc &DL, void *&InsertPos) {
1251   SDNode *N = CSEMap.FindNodeOrInsertPos(ID, InsertPos);
1252   if (N) {
1253     switch (N->getOpcode()) {
1254     case ISD::Constant:
1255     case ISD::ConstantFP:
1256       // Erase debug location from the node if the node is used at several
1257       // different places. Do not propagate one location to all uses as it
1258       // will cause a worse single stepping debugging experience.
1259       if (N->getDebugLoc() != DL.getDebugLoc())
1260         N->setDebugLoc(DebugLoc());
1261       break;
1262     default:
1263       // When the node's point of use is located earlier in the instruction
1264       // sequence than its prior point of use, update its debug info to the
1265       // earlier location.
1266       if (DL.getIROrder() && DL.getIROrder() < N->getIROrder())
1267         N->setDebugLoc(DL.getDebugLoc());
1268       break;
1269     }
1270   }
1271   return N;
1272 }
1273 
1274 void SelectionDAG::clear() {
1275   allnodes_clear();
1276   OperandRecycler.clear(OperandAllocator);
1277   OperandAllocator.Reset();
1278   CSEMap.clear();
1279 
1280   ExtendedValueTypeNodes.clear();
1281   ExternalSymbols.clear();
1282   TargetExternalSymbols.clear();
1283   MCSymbols.clear();
1284   SDCallSiteDbgInfo.clear();
1285   std::fill(CondCodeNodes.begin(), CondCodeNodes.end(),
1286             static_cast<CondCodeSDNode*>(nullptr));
1287   std::fill(ValueTypeNodes.begin(), ValueTypeNodes.end(),
1288             static_cast<SDNode*>(nullptr));
1289 
1290   EntryNode.UseList = nullptr;
1291   InsertNode(&EntryNode);
1292   Root = getEntryNode();
1293   DbgInfo->clear();
1294 }
1295 
1296 SDValue SelectionDAG::getFPExtendOrRound(SDValue Op, const SDLoc &DL, EVT VT) {
1297   return VT.bitsGT(Op.getValueType())
1298              ? getNode(ISD::FP_EXTEND, DL, VT, Op)
1299              : getNode(ISD::FP_ROUND, DL, VT, Op, getIntPtrConstant(0, DL));
1300 }
1301 
1302 std::pair<SDValue, SDValue>
1303 SelectionDAG::getStrictFPExtendOrRound(SDValue Op, SDValue Chain,
1304                                        const SDLoc &DL, EVT VT) {
1305   assert(!VT.bitsEq(Op.getValueType()) &&
1306          "Strict no-op FP extend/round not allowed.");
1307   SDValue Res =
1308       VT.bitsGT(Op.getValueType())
1309           ? getNode(ISD::STRICT_FP_EXTEND, DL, {VT, MVT::Other}, {Chain, Op})
1310           : getNode(ISD::STRICT_FP_ROUND, DL, {VT, MVT::Other},
1311                     {Chain, Op, getIntPtrConstant(0, DL)});
1312 
1313   return std::pair<SDValue, SDValue>(Res, SDValue(Res.getNode(), 1));
1314 }
1315 
1316 SDValue SelectionDAG::getAnyExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
1317   return VT.bitsGT(Op.getValueType()) ?
1318     getNode(ISD::ANY_EXTEND, DL, VT, Op) :
1319     getNode(ISD::TRUNCATE, DL, VT, Op);
1320 }
1321 
1322 SDValue SelectionDAG::getSExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
1323   return VT.bitsGT(Op.getValueType()) ?
1324     getNode(ISD::SIGN_EXTEND, DL, VT, Op) :
1325     getNode(ISD::TRUNCATE, DL, VT, Op);
1326 }
1327 
1328 SDValue SelectionDAG::getZExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
1329   return VT.bitsGT(Op.getValueType()) ?
1330     getNode(ISD::ZERO_EXTEND, DL, VT, Op) :
1331     getNode(ISD::TRUNCATE, DL, VT, Op);
1332 }
1333 
1334 SDValue SelectionDAG::getBoolExtOrTrunc(SDValue Op, const SDLoc &SL, EVT VT,
1335                                         EVT OpVT) {
1336   if (VT.bitsLE(Op.getValueType()))
1337     return getNode(ISD::TRUNCATE, SL, VT, Op);
1338 
1339   TargetLowering::BooleanContent BType = TLI->getBooleanContents(OpVT);
1340   return getNode(TLI->getExtendForContent(BType), SL, VT, Op);
1341 }
1342 
1343 SDValue SelectionDAG::getZeroExtendInReg(SDValue Op, const SDLoc &DL, EVT VT) {
1344   EVT OpVT = Op.getValueType();
1345   assert(VT.isInteger() && OpVT.isInteger() &&
1346          "Cannot getZeroExtendInReg FP types");
1347   assert(VT.isVector() == OpVT.isVector() &&
1348          "getZeroExtendInReg type should be vector iff the operand "
1349          "type is vector!");
1350   assert((!VT.isVector() ||
1351           VT.getVectorElementCount() == OpVT.getVectorElementCount()) &&
1352          "Vector element counts must match in getZeroExtendInReg");
1353   assert(VT.bitsLE(OpVT) && "Not extending!");
1354   if (OpVT == VT)
1355     return Op;
1356   APInt Imm = APInt::getLowBitsSet(OpVT.getScalarSizeInBits(),
1357                                    VT.getScalarSizeInBits());
1358   return getNode(ISD::AND, DL, OpVT, Op, getConstant(Imm, DL, OpVT));
1359 }
1360 
1361 SDValue SelectionDAG::getPtrExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
1362   // Only unsigned pointer semantics are supported right now. In the future this
1363   // might delegate to TLI to check pointer signedness.
1364   return getZExtOrTrunc(Op, DL, VT);
1365 }
1366 
1367 SDValue SelectionDAG::getPtrExtendInReg(SDValue Op, const SDLoc &DL, EVT VT) {
1368   // Only unsigned pointer semantics are supported right now. In the future this
1369   // might delegate to TLI to check pointer signedness.
1370   return getZeroExtendInReg(Op, DL, VT);
1371 }
1372 
1373 /// getNOT - Create a bitwise NOT operation as (XOR Val, -1).
1374 SDValue SelectionDAG::getNOT(const SDLoc &DL, SDValue Val, EVT VT) {
1375   return getNode(ISD::XOR, DL, VT, Val, getAllOnesConstant(DL, VT));
1376 }
1377 
1378 SDValue SelectionDAG::getLogicalNOT(const SDLoc &DL, SDValue Val, EVT VT) {
1379   SDValue TrueValue = getBoolConstant(true, DL, VT, VT);
1380   return getNode(ISD::XOR, DL, VT, Val, TrueValue);
1381 }
1382 
1383 SDValue SelectionDAG::getBoolConstant(bool V, const SDLoc &DL, EVT VT,
1384                                       EVT OpVT) {
1385   if (!V)
1386     return getConstant(0, DL, VT);
1387 
1388   switch (TLI->getBooleanContents(OpVT)) {
1389   case TargetLowering::ZeroOrOneBooleanContent:
1390   case TargetLowering::UndefinedBooleanContent:
1391     return getConstant(1, DL, VT);
1392   case TargetLowering::ZeroOrNegativeOneBooleanContent:
1393     return getAllOnesConstant(DL, VT);
1394   }
1395   llvm_unreachable("Unexpected boolean content enum!");
1396 }
1397 
1398 SDValue SelectionDAG::getConstant(uint64_t Val, const SDLoc &DL, EVT VT,
1399                                   bool isT, bool isO) {
1400   EVT EltVT = VT.getScalarType();
1401   assert((EltVT.getSizeInBits() >= 64 ||
1402           (uint64_t)((int64_t)Val >> EltVT.getSizeInBits()) + 1 < 2) &&
1403          "getConstant with a uint64_t value that doesn't fit in the type!");
1404   return getConstant(APInt(EltVT.getSizeInBits(), Val), DL, VT, isT, isO);
1405 }
1406 
1407 SDValue SelectionDAG::getConstant(const APInt &Val, const SDLoc &DL, EVT VT,
1408                                   bool isT, bool isO) {
1409   return getConstant(*ConstantInt::get(*Context, Val), DL, VT, isT, isO);
1410 }
1411 
1412 SDValue SelectionDAG::getConstant(const ConstantInt &Val, const SDLoc &DL,
1413                                   EVT VT, bool isT, bool isO) {
1414   assert(VT.isInteger() && "Cannot create FP integer constant!");
1415 
1416   EVT EltVT = VT.getScalarType();
1417   const ConstantInt *Elt = &Val;
1418 
1419   // In some cases the vector type is legal but the element type is illegal and
1420   // needs to be promoted, for example v8i8 on ARM.  In this case, promote the
1421   // inserted value (the type does not need to match the vector element type).
1422   // Any extra bits introduced will be truncated away.
1423   if (VT.isVector() && TLI->getTypeAction(*getContext(), EltVT) ==
1424                            TargetLowering::TypePromoteInteger) {
1425     EltVT = TLI->getTypeToTransformTo(*getContext(), EltVT);
1426     APInt NewVal = Elt->getValue().zextOrTrunc(EltVT.getSizeInBits());
1427     Elt = ConstantInt::get(*getContext(), NewVal);
1428   }
1429   // In other cases the element type is illegal and needs to be expanded, for
1430   // example v2i64 on MIPS32. In this case, find the nearest legal type, split
1431   // the value into n parts and use a vector type with n-times the elements.
1432   // Then bitcast to the type requested.
1433   // Legalizing constants too early makes the DAGCombiner's job harder so we
1434   // only legalize if the DAG tells us we must produce legal types.
1435   else if (NewNodesMustHaveLegalTypes && VT.isVector() &&
1436            TLI->getTypeAction(*getContext(), EltVT) ==
1437                TargetLowering::TypeExpandInteger) {
1438     const APInt &NewVal = Elt->getValue();
1439     EVT ViaEltVT = TLI->getTypeToTransformTo(*getContext(), EltVT);
1440     unsigned ViaEltSizeInBits = ViaEltVT.getSizeInBits();
1441 
1442     // For scalable vectors, try to use a SPLAT_VECTOR_PARTS node.
1443     if (VT.isScalableVector()) {
1444       assert(EltVT.getSizeInBits() % ViaEltSizeInBits == 0 &&
1445              "Can only handle an even split!");
1446       unsigned Parts = EltVT.getSizeInBits() / ViaEltSizeInBits;
1447 
1448       SmallVector<SDValue, 2> ScalarParts;
1449       for (unsigned i = 0; i != Parts; ++i)
1450         ScalarParts.push_back(getConstant(
1451             NewVal.extractBits(ViaEltSizeInBits, i * ViaEltSizeInBits), DL,
1452             ViaEltVT, isT, isO));
1453 
1454       return getNode(ISD::SPLAT_VECTOR_PARTS, DL, VT, ScalarParts);
1455     }
1456 
1457     unsigned ViaVecNumElts = VT.getSizeInBits() / ViaEltSizeInBits;
1458     EVT ViaVecVT = EVT::getVectorVT(*getContext(), ViaEltVT, ViaVecNumElts);
1459 
1460     // Check the temporary vector is the correct size. If this fails then
1461     // getTypeToTransformTo() probably returned a type whose size (in bits)
1462     // isn't a power-of-2 factor of the requested type size.
1463     assert(ViaVecVT.getSizeInBits() == VT.getSizeInBits());
1464 
1465     SmallVector<SDValue, 2> EltParts;
1466     for (unsigned i = 0; i < ViaVecNumElts / VT.getVectorNumElements(); ++i)
1467       EltParts.push_back(getConstant(
1468           NewVal.extractBits(ViaEltSizeInBits, i * ViaEltSizeInBits), DL,
1469           ViaEltVT, isT, isO));
1470 
1471     // EltParts is currently in little endian order. If we actually want
1472     // big-endian order then reverse it now.
1473     if (getDataLayout().isBigEndian())
1474       std::reverse(EltParts.begin(), EltParts.end());
1475 
1476     // The elements must be reversed when the element order is different
1477     // to the endianness of the elements (because the BITCAST is itself a
1478     // vector shuffle in this situation). However, we do not need any code to
1479     // perform this reversal because getConstant() is producing a vector
1480     // splat.
1481     // This situation occurs in MIPS MSA.
1482 
1483     SmallVector<SDValue, 8> Ops;
1484     for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
1485       llvm::append_range(Ops, EltParts);
1486 
1487     SDValue V =
1488         getNode(ISD::BITCAST, DL, VT, getBuildVector(ViaVecVT, DL, Ops));
1489     return V;
1490   }
1491 
1492   assert(Elt->getBitWidth() == EltVT.getSizeInBits() &&
1493          "APInt size does not match type size!");
1494   unsigned Opc = isT ? ISD::TargetConstant : ISD::Constant;
1495   FoldingSetNodeID ID;
1496   AddNodeIDNode(ID, Opc, getVTList(EltVT), None);
1497   ID.AddPointer(Elt);
1498   ID.AddBoolean(isO);
1499   void *IP = nullptr;
1500   SDNode *N = nullptr;
1501   if ((N = FindNodeOrInsertPos(ID, DL, IP)))
1502     if (!VT.isVector())
1503       return SDValue(N, 0);
1504 
1505   if (!N) {
1506     N = newSDNode<ConstantSDNode>(isT, isO, Elt, EltVT);
1507     CSEMap.InsertNode(N, IP);
1508     InsertNode(N);
1509     NewSDValueDbgMsg(SDValue(N, 0), "Creating constant: ", this);
1510   }
1511 
1512   SDValue Result(N, 0);
1513   if (VT.isScalableVector())
1514     Result = getSplatVector(VT, DL, Result);
1515   else if (VT.isVector())
1516     Result = getSplatBuildVector(VT, DL, Result);
1517 
1518   return Result;
1519 }
1520 
1521 SDValue SelectionDAG::getIntPtrConstant(uint64_t Val, const SDLoc &DL,
1522                                         bool isTarget) {
1523   return getConstant(Val, DL, TLI->getPointerTy(getDataLayout()), isTarget);
1524 }
1525 
1526 SDValue SelectionDAG::getShiftAmountConstant(uint64_t Val, EVT VT,
1527                                              const SDLoc &DL, bool LegalTypes) {
1528   assert(VT.isInteger() && "Shift amount is not an integer type!");
1529   EVT ShiftVT = TLI->getShiftAmountTy(VT, getDataLayout(), LegalTypes);
1530   return getConstant(Val, DL, ShiftVT);
1531 }
1532 
1533 SDValue SelectionDAG::getVectorIdxConstant(uint64_t Val, const SDLoc &DL,
1534                                            bool isTarget) {
1535   return getConstant(Val, DL, TLI->getVectorIdxTy(getDataLayout()), isTarget);
1536 }
1537 
1538 SDValue SelectionDAG::getConstantFP(const APFloat &V, const SDLoc &DL, EVT VT,
1539                                     bool isTarget) {
1540   return getConstantFP(*ConstantFP::get(*getContext(), V), DL, VT, isTarget);
1541 }
1542 
1543 SDValue SelectionDAG::getConstantFP(const ConstantFP &V, const SDLoc &DL,
1544                                     EVT VT, bool isTarget) {
1545   assert(VT.isFloatingPoint() && "Cannot create integer FP constant!");
1546 
1547   EVT EltVT = VT.getScalarType();
1548 
1549   // Do the map lookup using the actual bit pattern for the floating point
1550   // value, so that we don't have problems with 0.0 comparing equal to -0.0, and
1551   // we don't have issues with SNANs.
1552   unsigned Opc = isTarget ? ISD::TargetConstantFP : ISD::ConstantFP;
1553   FoldingSetNodeID ID;
1554   AddNodeIDNode(ID, Opc, getVTList(EltVT), None);
1555   ID.AddPointer(&V);
1556   void *IP = nullptr;
1557   SDNode *N = nullptr;
1558   if ((N = FindNodeOrInsertPos(ID, DL, IP)))
1559     if (!VT.isVector())
1560       return SDValue(N, 0);
1561 
1562   if (!N) {
1563     N = newSDNode<ConstantFPSDNode>(isTarget, &V, EltVT);
1564     CSEMap.InsertNode(N, IP);
1565     InsertNode(N);
1566   }
1567 
1568   SDValue Result(N, 0);
1569   if (VT.isScalableVector())
1570     Result = getSplatVector(VT, DL, Result);
1571   else if (VT.isVector())
1572     Result = getSplatBuildVector(VT, DL, Result);
1573   NewSDValueDbgMsg(Result, "Creating fp constant: ", this);
1574   return Result;
1575 }
1576 
1577 SDValue SelectionDAG::getConstantFP(double Val, const SDLoc &DL, EVT VT,
1578                                     bool isTarget) {
1579   EVT EltVT = VT.getScalarType();
1580   if (EltVT == MVT::f32)
1581     return getConstantFP(APFloat((float)Val), DL, VT, isTarget);
1582   if (EltVT == MVT::f64)
1583     return getConstantFP(APFloat(Val), DL, VT, isTarget);
1584   if (EltVT == MVT::f80 || EltVT == MVT::f128 || EltVT == MVT::ppcf128 ||
1585       EltVT == MVT::f16 || EltVT == MVT::bf16) {
1586     bool Ignored;
1587     APFloat APF = APFloat(Val);
1588     APF.convert(EVTToAPFloatSemantics(EltVT), APFloat::rmNearestTiesToEven,
1589                 &Ignored);
1590     return getConstantFP(APF, DL, VT, isTarget);
1591   }
1592   llvm_unreachable("Unsupported type in getConstantFP");
1593 }
1594 
1595 SDValue SelectionDAG::getGlobalAddress(const GlobalValue *GV, const SDLoc &DL,
1596                                        EVT VT, int64_t Offset, bool isTargetGA,
1597                                        unsigned TargetFlags) {
1598   assert((TargetFlags == 0 || isTargetGA) &&
1599          "Cannot set target flags on target-independent globals");
1600 
1601   // Truncate (with sign-extension) the offset value to the pointer size.
1602   unsigned BitWidth = getDataLayout().getPointerTypeSizeInBits(GV->getType());
1603   if (BitWidth < 64)
1604     Offset = SignExtend64(Offset, BitWidth);
1605 
1606   unsigned Opc;
1607   if (GV->isThreadLocal())
1608     Opc = isTargetGA ? ISD::TargetGlobalTLSAddress : ISD::GlobalTLSAddress;
1609   else
1610     Opc = isTargetGA ? ISD::TargetGlobalAddress : ISD::GlobalAddress;
1611 
1612   FoldingSetNodeID ID;
1613   AddNodeIDNode(ID, Opc, getVTList(VT), None);
1614   ID.AddPointer(GV);
1615   ID.AddInteger(Offset);
1616   ID.AddInteger(TargetFlags);
1617   void *IP = nullptr;
1618   if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
1619     return SDValue(E, 0);
1620 
1621   auto *N = newSDNode<GlobalAddressSDNode>(
1622       Opc, DL.getIROrder(), DL.getDebugLoc(), GV, VT, Offset, TargetFlags);
1623   CSEMap.InsertNode(N, IP);
1624     InsertNode(N);
1625   return SDValue(N, 0);
1626 }
1627 
1628 SDValue SelectionDAG::getFrameIndex(int FI, EVT VT, bool isTarget) {
1629   unsigned Opc = isTarget ? ISD::TargetFrameIndex : ISD::FrameIndex;
1630   FoldingSetNodeID ID;
1631   AddNodeIDNode(ID, Opc, getVTList(VT), None);
1632   ID.AddInteger(FI);
1633   void *IP = nullptr;
1634   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1635     return SDValue(E, 0);
1636 
1637   auto *N = newSDNode<FrameIndexSDNode>(FI, VT, isTarget);
1638   CSEMap.InsertNode(N, IP);
1639   InsertNode(N);
1640   return SDValue(N, 0);
1641 }
1642 
1643 SDValue SelectionDAG::getJumpTable(int JTI, EVT VT, bool isTarget,
1644                                    unsigned TargetFlags) {
1645   assert((TargetFlags == 0 || isTarget) &&
1646          "Cannot set target flags on target-independent jump tables");
1647   unsigned Opc = isTarget ? ISD::TargetJumpTable : ISD::JumpTable;
1648   FoldingSetNodeID ID;
1649   AddNodeIDNode(ID, Opc, getVTList(VT), None);
1650   ID.AddInteger(JTI);
1651   ID.AddInteger(TargetFlags);
1652   void *IP = nullptr;
1653   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1654     return SDValue(E, 0);
1655 
1656   auto *N = newSDNode<JumpTableSDNode>(JTI, VT, isTarget, TargetFlags);
1657   CSEMap.InsertNode(N, IP);
1658   InsertNode(N);
1659   return SDValue(N, 0);
1660 }
1661 
1662 SDValue SelectionDAG::getConstantPool(const Constant *C, EVT VT,
1663                                       MaybeAlign Alignment, int Offset,
1664                                       bool isTarget, unsigned TargetFlags) {
1665   assert((TargetFlags == 0 || isTarget) &&
1666          "Cannot set target flags on target-independent globals");
1667   if (!Alignment)
1668     Alignment = shouldOptForSize()
1669                     ? getDataLayout().getABITypeAlign(C->getType())
1670                     : getDataLayout().getPrefTypeAlign(C->getType());
1671   unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
1672   FoldingSetNodeID ID;
1673   AddNodeIDNode(ID, Opc, getVTList(VT), None);
1674   ID.AddInteger(Alignment->value());
1675   ID.AddInteger(Offset);
1676   ID.AddPointer(C);
1677   ID.AddInteger(TargetFlags);
1678   void *IP = nullptr;
1679   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1680     return SDValue(E, 0);
1681 
1682   auto *N = newSDNode<ConstantPoolSDNode>(isTarget, C, VT, Offset, *Alignment,
1683                                           TargetFlags);
1684   CSEMap.InsertNode(N, IP);
1685   InsertNode(N);
1686   SDValue V = SDValue(N, 0);
1687   NewSDValueDbgMsg(V, "Creating new constant pool: ", this);
1688   return V;
1689 }
1690 
1691 SDValue SelectionDAG::getConstantPool(MachineConstantPoolValue *C, EVT VT,
1692                                       MaybeAlign Alignment, int Offset,
1693                                       bool isTarget, unsigned TargetFlags) {
1694   assert((TargetFlags == 0 || isTarget) &&
1695          "Cannot set target flags on target-independent globals");
1696   if (!Alignment)
1697     Alignment = getDataLayout().getPrefTypeAlign(C->getType());
1698   unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
1699   FoldingSetNodeID ID;
1700   AddNodeIDNode(ID, Opc, getVTList(VT), None);
1701   ID.AddInteger(Alignment->value());
1702   ID.AddInteger(Offset);
1703   C->addSelectionDAGCSEId(ID);
1704   ID.AddInteger(TargetFlags);
1705   void *IP = nullptr;
1706   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1707     return SDValue(E, 0);
1708 
1709   auto *N = newSDNode<ConstantPoolSDNode>(isTarget, C, VT, Offset, *Alignment,
1710                                           TargetFlags);
1711   CSEMap.InsertNode(N, IP);
1712   InsertNode(N);
1713   return SDValue(N, 0);
1714 }
1715 
1716 SDValue SelectionDAG::getTargetIndex(int Index, EVT VT, int64_t Offset,
1717                                      unsigned TargetFlags) {
1718   FoldingSetNodeID ID;
1719   AddNodeIDNode(ID, ISD::TargetIndex, getVTList(VT), None);
1720   ID.AddInteger(Index);
1721   ID.AddInteger(Offset);
1722   ID.AddInteger(TargetFlags);
1723   void *IP = nullptr;
1724   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1725     return SDValue(E, 0);
1726 
1727   auto *N = newSDNode<TargetIndexSDNode>(Index, VT, Offset, TargetFlags);
1728   CSEMap.InsertNode(N, IP);
1729   InsertNode(N);
1730   return SDValue(N, 0);
1731 }
1732 
1733 SDValue SelectionDAG::getBasicBlock(MachineBasicBlock *MBB) {
1734   FoldingSetNodeID ID;
1735   AddNodeIDNode(ID, ISD::BasicBlock, getVTList(MVT::Other), None);
1736   ID.AddPointer(MBB);
1737   void *IP = nullptr;
1738   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1739     return SDValue(E, 0);
1740 
1741   auto *N = newSDNode<BasicBlockSDNode>(MBB);
1742   CSEMap.InsertNode(N, IP);
1743   InsertNode(N);
1744   return SDValue(N, 0);
1745 }
1746 
1747 SDValue SelectionDAG::getValueType(EVT VT) {
1748   if (VT.isSimple() && (unsigned)VT.getSimpleVT().SimpleTy >=
1749       ValueTypeNodes.size())
1750     ValueTypeNodes.resize(VT.getSimpleVT().SimpleTy+1);
1751 
1752   SDNode *&N = VT.isExtended() ?
1753     ExtendedValueTypeNodes[VT] : ValueTypeNodes[VT.getSimpleVT().SimpleTy];
1754 
1755   if (N) return SDValue(N, 0);
1756   N = newSDNode<VTSDNode>(VT);
1757   InsertNode(N);
1758   return SDValue(N, 0);
1759 }
1760 
1761 SDValue SelectionDAG::getExternalSymbol(const char *Sym, EVT VT) {
1762   SDNode *&N = ExternalSymbols[Sym];
1763   if (N) return SDValue(N, 0);
1764   N = newSDNode<ExternalSymbolSDNode>(false, Sym, 0, VT);
1765   InsertNode(N);
1766   return SDValue(N, 0);
1767 }
1768 
1769 SDValue SelectionDAG::getMCSymbol(MCSymbol *Sym, EVT VT) {
1770   SDNode *&N = MCSymbols[Sym];
1771   if (N)
1772     return SDValue(N, 0);
1773   N = newSDNode<MCSymbolSDNode>(Sym, VT);
1774   InsertNode(N);
1775   return SDValue(N, 0);
1776 }
1777 
1778 SDValue SelectionDAG::getTargetExternalSymbol(const char *Sym, EVT VT,
1779                                               unsigned TargetFlags) {
1780   SDNode *&N =
1781       TargetExternalSymbols[std::pair<std::string, unsigned>(Sym, TargetFlags)];
1782   if (N) return SDValue(N, 0);
1783   N = newSDNode<ExternalSymbolSDNode>(true, Sym, TargetFlags, VT);
1784   InsertNode(N);
1785   return SDValue(N, 0);
1786 }
1787 
1788 SDValue SelectionDAG::getCondCode(ISD::CondCode Cond) {
1789   if ((unsigned)Cond >= CondCodeNodes.size())
1790     CondCodeNodes.resize(Cond+1);
1791 
1792   if (!CondCodeNodes[Cond]) {
1793     auto *N = newSDNode<CondCodeSDNode>(Cond);
1794     CondCodeNodes[Cond] = N;
1795     InsertNode(N);
1796   }
1797 
1798   return SDValue(CondCodeNodes[Cond], 0);
1799 }
1800 
1801 SDValue SelectionDAG::getStepVector(const SDLoc &DL, EVT ResVT) {
1802   APInt One(ResVT.getScalarSizeInBits(), 1);
1803   return getStepVector(DL, ResVT, One);
1804 }
1805 
1806 SDValue SelectionDAG::getStepVector(const SDLoc &DL, EVT ResVT, APInt StepVal) {
1807   assert(ResVT.getScalarSizeInBits() == StepVal.getBitWidth());
1808   if (ResVT.isScalableVector())
1809     return getNode(
1810         ISD::STEP_VECTOR, DL, ResVT,
1811         getTargetConstant(StepVal, DL, ResVT.getVectorElementType()));
1812 
1813   SmallVector<SDValue, 16> OpsStepConstants;
1814   for (uint64_t i = 0; i < ResVT.getVectorNumElements(); i++)
1815     OpsStepConstants.push_back(
1816         getConstant(StepVal * i, DL, ResVT.getVectorElementType()));
1817   return getBuildVector(ResVT, DL, OpsStepConstants);
1818 }
1819 
1820 /// Swaps the values of N1 and N2. Swaps all indices in the shuffle mask M that
1821 /// point at N1 to point at N2 and indices that point at N2 to point at N1.
1822 static void commuteShuffle(SDValue &N1, SDValue &N2, MutableArrayRef<int> M) {
1823   std::swap(N1, N2);
1824   ShuffleVectorSDNode::commuteMask(M);
1825 }
1826 
1827 SDValue SelectionDAG::getVectorShuffle(EVT VT, const SDLoc &dl, SDValue N1,
1828                                        SDValue N2, ArrayRef<int> Mask) {
1829   assert(VT.getVectorNumElements() == Mask.size() &&
1830          "Must have the same number of vector elements as mask elements!");
1831   assert(VT == N1.getValueType() && VT == N2.getValueType() &&
1832          "Invalid VECTOR_SHUFFLE");
1833 
1834   // Canonicalize shuffle undef, undef -> undef
1835   if (N1.isUndef() && N2.isUndef())
1836     return getUNDEF(VT);
1837 
1838   // Validate that all indices in Mask are within the range of the elements
1839   // input to the shuffle.
1840   int NElts = Mask.size();
1841   assert(llvm::all_of(Mask,
1842                       [&](int M) { return M < (NElts * 2) && M >= -1; }) &&
1843          "Index out of range");
1844 
1845   // Copy the mask so we can do any needed cleanup.
1846   SmallVector<int, 8> MaskVec(Mask.begin(), Mask.end());
1847 
1848   // Canonicalize shuffle v, v -> v, undef
1849   if (N1 == N2) {
1850     N2 = getUNDEF(VT);
1851     for (int i = 0; i != NElts; ++i)
1852       if (MaskVec[i] >= NElts) MaskVec[i] -= NElts;
1853   }
1854 
1855   // Canonicalize shuffle undef, v -> v, undef.  Commute the shuffle mask.
1856   if (N1.isUndef())
1857     commuteShuffle(N1, N2, MaskVec);
1858 
1859   if (TLI->hasVectorBlend()) {
1860     // If shuffling a splat, try to blend the splat instead. We do this here so
1861     // that even when this arises during lowering we don't have to re-handle it.
1862     auto BlendSplat = [&](BuildVectorSDNode *BV, int Offset) {
1863       BitVector UndefElements;
1864       SDValue Splat = BV->getSplatValue(&UndefElements);
1865       if (!Splat)
1866         return;
1867 
1868       for (int i = 0; i < NElts; ++i) {
1869         if (MaskVec[i] < Offset || MaskVec[i] >= (Offset + NElts))
1870           continue;
1871 
1872         // If this input comes from undef, mark it as such.
1873         if (UndefElements[MaskVec[i] - Offset]) {
1874           MaskVec[i] = -1;
1875           continue;
1876         }
1877 
1878         // If we can blend a non-undef lane, use that instead.
1879         if (!UndefElements[i])
1880           MaskVec[i] = i + Offset;
1881       }
1882     };
1883     if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
1884       BlendSplat(N1BV, 0);
1885     if (auto *N2BV = dyn_cast<BuildVectorSDNode>(N2))
1886       BlendSplat(N2BV, NElts);
1887   }
1888 
1889   // Canonicalize all index into lhs, -> shuffle lhs, undef
1890   // Canonicalize all index into rhs, -> shuffle rhs, undef
1891   bool AllLHS = true, AllRHS = true;
1892   bool N2Undef = N2.isUndef();
1893   for (int i = 0; i != NElts; ++i) {
1894     if (MaskVec[i] >= NElts) {
1895       if (N2Undef)
1896         MaskVec[i] = -1;
1897       else
1898         AllLHS = false;
1899     } else if (MaskVec[i] >= 0) {
1900       AllRHS = false;
1901     }
1902   }
1903   if (AllLHS && AllRHS)
1904     return getUNDEF(VT);
1905   if (AllLHS && !N2Undef)
1906     N2 = getUNDEF(VT);
1907   if (AllRHS) {
1908     N1 = getUNDEF(VT);
1909     commuteShuffle(N1, N2, MaskVec);
1910   }
1911   // Reset our undef status after accounting for the mask.
1912   N2Undef = N2.isUndef();
1913   // Re-check whether both sides ended up undef.
1914   if (N1.isUndef() && N2Undef)
1915     return getUNDEF(VT);
1916 
1917   // If Identity shuffle return that node.
1918   bool Identity = true, AllSame = true;
1919   for (int i = 0; i != NElts; ++i) {
1920     if (MaskVec[i] >= 0 && MaskVec[i] != i) Identity = false;
1921     if (MaskVec[i] != MaskVec[0]) AllSame = false;
1922   }
1923   if (Identity && NElts)
1924     return N1;
1925 
1926   // Shuffling a constant splat doesn't change the result.
1927   if (N2Undef) {
1928     SDValue V = N1;
1929 
1930     // Look through any bitcasts. We check that these don't change the number
1931     // (and size) of elements and just changes their types.
1932     while (V.getOpcode() == ISD::BITCAST)
1933       V = V->getOperand(0);
1934 
1935     // A splat should always show up as a build vector node.
1936     if (auto *BV = dyn_cast<BuildVectorSDNode>(V)) {
1937       BitVector UndefElements;
1938       SDValue Splat = BV->getSplatValue(&UndefElements);
1939       // If this is a splat of an undef, shuffling it is also undef.
1940       if (Splat && Splat.isUndef())
1941         return getUNDEF(VT);
1942 
1943       bool SameNumElts =
1944           V.getValueType().getVectorNumElements() == VT.getVectorNumElements();
1945 
1946       // We only have a splat which can skip shuffles if there is a splatted
1947       // value and no undef lanes rearranged by the shuffle.
1948       if (Splat && UndefElements.none()) {
1949         // Splat of <x, x, ..., x>, return <x, x, ..., x>, provided that the
1950         // number of elements match or the value splatted is a zero constant.
1951         if (SameNumElts)
1952           return N1;
1953         if (auto *C = dyn_cast<ConstantSDNode>(Splat))
1954           if (C->isZero())
1955             return N1;
1956       }
1957 
1958       // If the shuffle itself creates a splat, build the vector directly.
1959       if (AllSame && SameNumElts) {
1960         EVT BuildVT = BV->getValueType(0);
1961         const SDValue &Splatted = BV->getOperand(MaskVec[0]);
1962         SDValue NewBV = getSplatBuildVector(BuildVT, dl, Splatted);
1963 
1964         // We may have jumped through bitcasts, so the type of the
1965         // BUILD_VECTOR may not match the type of the shuffle.
1966         if (BuildVT != VT)
1967           NewBV = getNode(ISD::BITCAST, dl, VT, NewBV);
1968         return NewBV;
1969       }
1970     }
1971   }
1972 
1973   FoldingSetNodeID ID;
1974   SDValue Ops[2] = { N1, N2 };
1975   AddNodeIDNode(ID, ISD::VECTOR_SHUFFLE, getVTList(VT), Ops);
1976   for (int i = 0; i != NElts; ++i)
1977     ID.AddInteger(MaskVec[i]);
1978 
1979   void* IP = nullptr;
1980   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
1981     return SDValue(E, 0);
1982 
1983   // Allocate the mask array for the node out of the BumpPtrAllocator, since
1984   // SDNode doesn't have access to it.  This memory will be "leaked" when
1985   // the node is deallocated, but recovered when the NodeAllocator is released.
1986   int *MaskAlloc = OperandAllocator.Allocate<int>(NElts);
1987   llvm::copy(MaskVec, MaskAlloc);
1988 
1989   auto *N = newSDNode<ShuffleVectorSDNode>(VT, dl.getIROrder(),
1990                                            dl.getDebugLoc(), MaskAlloc);
1991   createOperands(N, Ops);
1992 
1993   CSEMap.InsertNode(N, IP);
1994   InsertNode(N);
1995   SDValue V = SDValue(N, 0);
1996   NewSDValueDbgMsg(V, "Creating new node: ", this);
1997   return V;
1998 }
1999 
2000 SDValue SelectionDAG::getCommutedVectorShuffle(const ShuffleVectorSDNode &SV) {
2001   EVT VT = SV.getValueType(0);
2002   SmallVector<int, 8> MaskVec(SV.getMask().begin(), SV.getMask().end());
2003   ShuffleVectorSDNode::commuteMask(MaskVec);
2004 
2005   SDValue Op0 = SV.getOperand(0);
2006   SDValue Op1 = SV.getOperand(1);
2007   return getVectorShuffle(VT, SDLoc(&SV), Op1, Op0, MaskVec);
2008 }
2009 
2010 SDValue SelectionDAG::getRegister(unsigned RegNo, EVT VT) {
2011   FoldingSetNodeID ID;
2012   AddNodeIDNode(ID, ISD::Register, getVTList(VT), None);
2013   ID.AddInteger(RegNo);
2014   void *IP = nullptr;
2015   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2016     return SDValue(E, 0);
2017 
2018   auto *N = newSDNode<RegisterSDNode>(RegNo, VT);
2019   N->SDNodeBits.IsDivergent = TLI->isSDNodeSourceOfDivergence(N, FLI, DA);
2020   CSEMap.InsertNode(N, IP);
2021   InsertNode(N);
2022   return SDValue(N, 0);
2023 }
2024 
2025 SDValue SelectionDAG::getRegisterMask(const uint32_t *RegMask) {
2026   FoldingSetNodeID ID;
2027   AddNodeIDNode(ID, ISD::RegisterMask, getVTList(MVT::Untyped), None);
2028   ID.AddPointer(RegMask);
2029   void *IP = nullptr;
2030   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2031     return SDValue(E, 0);
2032 
2033   auto *N = newSDNode<RegisterMaskSDNode>(RegMask);
2034   CSEMap.InsertNode(N, IP);
2035   InsertNode(N);
2036   return SDValue(N, 0);
2037 }
2038 
2039 SDValue SelectionDAG::getEHLabel(const SDLoc &dl, SDValue Root,
2040                                  MCSymbol *Label) {
2041   return getLabelNode(ISD::EH_LABEL, dl, Root, Label);
2042 }
2043 
2044 SDValue SelectionDAG::getLabelNode(unsigned Opcode, const SDLoc &dl,
2045                                    SDValue Root, MCSymbol *Label) {
2046   FoldingSetNodeID ID;
2047   SDValue Ops[] = { Root };
2048   AddNodeIDNode(ID, Opcode, getVTList(MVT::Other), Ops);
2049   ID.AddPointer(Label);
2050   void *IP = nullptr;
2051   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2052     return SDValue(E, 0);
2053 
2054   auto *N =
2055       newSDNode<LabelSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(), Label);
2056   createOperands(N, Ops);
2057 
2058   CSEMap.InsertNode(N, IP);
2059   InsertNode(N);
2060   return SDValue(N, 0);
2061 }
2062 
2063 SDValue SelectionDAG::getBlockAddress(const BlockAddress *BA, EVT VT,
2064                                       int64_t Offset, bool isTarget,
2065                                       unsigned TargetFlags) {
2066   unsigned Opc = isTarget ? ISD::TargetBlockAddress : ISD::BlockAddress;
2067 
2068   FoldingSetNodeID ID;
2069   AddNodeIDNode(ID, Opc, getVTList(VT), None);
2070   ID.AddPointer(BA);
2071   ID.AddInteger(Offset);
2072   ID.AddInteger(TargetFlags);
2073   void *IP = nullptr;
2074   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2075     return SDValue(E, 0);
2076 
2077   auto *N = newSDNode<BlockAddressSDNode>(Opc, VT, BA, Offset, TargetFlags);
2078   CSEMap.InsertNode(N, IP);
2079   InsertNode(N);
2080   return SDValue(N, 0);
2081 }
2082 
2083 SDValue SelectionDAG::getSrcValue(const Value *V) {
2084   FoldingSetNodeID ID;
2085   AddNodeIDNode(ID, ISD::SRCVALUE, getVTList(MVT::Other), None);
2086   ID.AddPointer(V);
2087 
2088   void *IP = nullptr;
2089   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2090     return SDValue(E, 0);
2091 
2092   auto *N = newSDNode<SrcValueSDNode>(V);
2093   CSEMap.InsertNode(N, IP);
2094   InsertNode(N);
2095   return SDValue(N, 0);
2096 }
2097 
2098 SDValue SelectionDAG::getMDNode(const MDNode *MD) {
2099   FoldingSetNodeID ID;
2100   AddNodeIDNode(ID, ISD::MDNODE_SDNODE, getVTList(MVT::Other), None);
2101   ID.AddPointer(MD);
2102 
2103   void *IP = nullptr;
2104   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2105     return SDValue(E, 0);
2106 
2107   auto *N = newSDNode<MDNodeSDNode>(MD);
2108   CSEMap.InsertNode(N, IP);
2109   InsertNode(N);
2110   return SDValue(N, 0);
2111 }
2112 
2113 SDValue SelectionDAG::getBitcast(EVT VT, SDValue V) {
2114   if (VT == V.getValueType())
2115     return V;
2116 
2117   return getNode(ISD::BITCAST, SDLoc(V), VT, V);
2118 }
2119 
2120 SDValue SelectionDAG::getAddrSpaceCast(const SDLoc &dl, EVT VT, SDValue Ptr,
2121                                        unsigned SrcAS, unsigned DestAS) {
2122   SDValue Ops[] = {Ptr};
2123   FoldingSetNodeID ID;
2124   AddNodeIDNode(ID, ISD::ADDRSPACECAST, getVTList(VT), Ops);
2125   ID.AddInteger(SrcAS);
2126   ID.AddInteger(DestAS);
2127 
2128   void *IP = nullptr;
2129   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
2130     return SDValue(E, 0);
2131 
2132   auto *N = newSDNode<AddrSpaceCastSDNode>(dl.getIROrder(), dl.getDebugLoc(),
2133                                            VT, SrcAS, DestAS);
2134   createOperands(N, Ops);
2135 
2136   CSEMap.InsertNode(N, IP);
2137   InsertNode(N);
2138   return SDValue(N, 0);
2139 }
2140 
2141 SDValue SelectionDAG::getFreeze(SDValue V) {
2142   return getNode(ISD::FREEZE, SDLoc(V), V.getValueType(), V);
2143 }
2144 
2145 /// getShiftAmountOperand - Return the specified value casted to
2146 /// the target's desired shift amount type.
2147 SDValue SelectionDAG::getShiftAmountOperand(EVT LHSTy, SDValue Op) {
2148   EVT OpTy = Op.getValueType();
2149   EVT ShTy = TLI->getShiftAmountTy(LHSTy, getDataLayout());
2150   if (OpTy == ShTy || OpTy.isVector()) return Op;
2151 
2152   return getZExtOrTrunc(Op, SDLoc(Op), ShTy);
2153 }
2154 
2155 SDValue SelectionDAG::expandVAArg(SDNode *Node) {
2156   SDLoc dl(Node);
2157   const TargetLowering &TLI = getTargetLoweringInfo();
2158   const Value *V = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
2159   EVT VT = Node->getValueType(0);
2160   SDValue Tmp1 = Node->getOperand(0);
2161   SDValue Tmp2 = Node->getOperand(1);
2162   const MaybeAlign MA(Node->getConstantOperandVal(3));
2163 
2164   SDValue VAListLoad = getLoad(TLI.getPointerTy(getDataLayout()), dl, Tmp1,
2165                                Tmp2, MachinePointerInfo(V));
2166   SDValue VAList = VAListLoad;
2167 
2168   if (MA && *MA > TLI.getMinStackArgumentAlignment()) {
2169     VAList = getNode(ISD::ADD, dl, VAList.getValueType(), VAList,
2170                      getConstant(MA->value() - 1, dl, VAList.getValueType()));
2171 
2172     VAList =
2173         getNode(ISD::AND, dl, VAList.getValueType(), VAList,
2174                 getConstant(-(int64_t)MA->value(), dl, VAList.getValueType()));
2175   }
2176 
2177   // Increment the pointer, VAList, to the next vaarg
2178   Tmp1 = getNode(ISD::ADD, dl, VAList.getValueType(), VAList,
2179                  getConstant(getDataLayout().getTypeAllocSize(
2180                                                VT.getTypeForEVT(*getContext())),
2181                              dl, VAList.getValueType()));
2182   // Store the incremented VAList to the legalized pointer
2183   Tmp1 =
2184       getStore(VAListLoad.getValue(1), dl, Tmp1, Tmp2, MachinePointerInfo(V));
2185   // Load the actual argument out of the pointer VAList
2186   return getLoad(VT, dl, Tmp1, VAList, MachinePointerInfo());
2187 }
2188 
2189 SDValue SelectionDAG::expandVACopy(SDNode *Node) {
2190   SDLoc dl(Node);
2191   const TargetLowering &TLI = getTargetLoweringInfo();
2192   // This defaults to loading a pointer from the input and storing it to the
2193   // output, returning the chain.
2194   const Value *VD = cast<SrcValueSDNode>(Node->getOperand(3))->getValue();
2195   const Value *VS = cast<SrcValueSDNode>(Node->getOperand(4))->getValue();
2196   SDValue Tmp1 =
2197       getLoad(TLI.getPointerTy(getDataLayout()), dl, Node->getOperand(0),
2198               Node->getOperand(2), MachinePointerInfo(VS));
2199   return getStore(Tmp1.getValue(1), dl, Tmp1, Node->getOperand(1),
2200                   MachinePointerInfo(VD));
2201 }
2202 
2203 Align SelectionDAG::getReducedAlign(EVT VT, bool UseABI) {
2204   const DataLayout &DL = getDataLayout();
2205   Type *Ty = VT.getTypeForEVT(*getContext());
2206   Align RedAlign = UseABI ? DL.getABITypeAlign(Ty) : DL.getPrefTypeAlign(Ty);
2207 
2208   if (TLI->isTypeLegal(VT) || !VT.isVector())
2209     return RedAlign;
2210 
2211   const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering();
2212   const Align StackAlign = TFI->getStackAlign();
2213 
2214   // See if we can choose a smaller ABI alignment in cases where it's an
2215   // illegal vector type that will get broken down.
2216   if (RedAlign > StackAlign) {
2217     EVT IntermediateVT;
2218     MVT RegisterVT;
2219     unsigned NumIntermediates;
2220     TLI->getVectorTypeBreakdown(*getContext(), VT, IntermediateVT,
2221                                 NumIntermediates, RegisterVT);
2222     Ty = IntermediateVT.getTypeForEVT(*getContext());
2223     Align RedAlign2 = UseABI ? DL.getABITypeAlign(Ty) : DL.getPrefTypeAlign(Ty);
2224     if (RedAlign2 < RedAlign)
2225       RedAlign = RedAlign2;
2226   }
2227 
2228   return RedAlign;
2229 }
2230 
2231 SDValue SelectionDAG::CreateStackTemporary(TypeSize Bytes, Align Alignment) {
2232   MachineFrameInfo &MFI = MF->getFrameInfo();
2233   const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering();
2234   int StackID = 0;
2235   if (Bytes.isScalable())
2236     StackID = TFI->getStackIDForScalableVectors();
2237   // The stack id gives an indication of whether the object is scalable or
2238   // not, so it's safe to pass in the minimum size here.
2239   int FrameIdx = MFI.CreateStackObject(Bytes.getKnownMinSize(), Alignment,
2240                                        false, nullptr, StackID);
2241   return getFrameIndex(FrameIdx, TLI->getFrameIndexTy(getDataLayout()));
2242 }
2243 
2244 SDValue SelectionDAG::CreateStackTemporary(EVT VT, unsigned minAlign) {
2245   Type *Ty = VT.getTypeForEVT(*getContext());
2246   Align StackAlign =
2247       std::max(getDataLayout().getPrefTypeAlign(Ty), Align(minAlign));
2248   return CreateStackTemporary(VT.getStoreSize(), StackAlign);
2249 }
2250 
2251 SDValue SelectionDAG::CreateStackTemporary(EVT VT1, EVT VT2) {
2252   TypeSize VT1Size = VT1.getStoreSize();
2253   TypeSize VT2Size = VT2.getStoreSize();
2254   assert(VT1Size.isScalable() == VT2Size.isScalable() &&
2255          "Don't know how to choose the maximum size when creating a stack "
2256          "temporary");
2257   TypeSize Bytes =
2258       VT1Size.getKnownMinSize() > VT2Size.getKnownMinSize() ? VT1Size : VT2Size;
2259 
2260   Type *Ty1 = VT1.getTypeForEVT(*getContext());
2261   Type *Ty2 = VT2.getTypeForEVT(*getContext());
2262   const DataLayout &DL = getDataLayout();
2263   Align Align = std::max(DL.getPrefTypeAlign(Ty1), DL.getPrefTypeAlign(Ty2));
2264   return CreateStackTemporary(Bytes, Align);
2265 }
2266 
2267 SDValue SelectionDAG::FoldSetCC(EVT VT, SDValue N1, SDValue N2,
2268                                 ISD::CondCode Cond, const SDLoc &dl) {
2269   EVT OpVT = N1.getValueType();
2270 
2271   // These setcc operations always fold.
2272   switch (Cond) {
2273   default: break;
2274   case ISD::SETFALSE:
2275   case ISD::SETFALSE2: return getBoolConstant(false, dl, VT, OpVT);
2276   case ISD::SETTRUE:
2277   case ISD::SETTRUE2: return getBoolConstant(true, dl, VT, OpVT);
2278 
2279   case ISD::SETOEQ:
2280   case ISD::SETOGT:
2281   case ISD::SETOGE:
2282   case ISD::SETOLT:
2283   case ISD::SETOLE:
2284   case ISD::SETONE:
2285   case ISD::SETO:
2286   case ISD::SETUO:
2287   case ISD::SETUEQ:
2288   case ISD::SETUNE:
2289     assert(!OpVT.isInteger() && "Illegal setcc for integer!");
2290     break;
2291   }
2292 
2293   if (OpVT.isInteger()) {
2294     // For EQ and NE, we can always pick a value for the undef to make the
2295     // predicate pass or fail, so we can return undef.
2296     // Matches behavior in llvm::ConstantFoldCompareInstruction.
2297     // icmp eq/ne X, undef -> undef.
2298     if ((N1.isUndef() || N2.isUndef()) &&
2299         (Cond == ISD::SETEQ || Cond == ISD::SETNE))
2300       return getUNDEF(VT);
2301 
2302     // If both operands are undef, we can return undef for int comparison.
2303     // icmp undef, undef -> undef.
2304     if (N1.isUndef() && N2.isUndef())
2305       return getUNDEF(VT);
2306 
2307     // icmp X, X -> true/false
2308     // icmp X, undef -> true/false because undef could be X.
2309     if (N1 == N2)
2310       return getBoolConstant(ISD::isTrueWhenEqual(Cond), dl, VT, OpVT);
2311   }
2312 
2313   if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2)) {
2314     const APInt &C2 = N2C->getAPIntValue();
2315     if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1)) {
2316       const APInt &C1 = N1C->getAPIntValue();
2317 
2318       return getBoolConstant(ICmpInst::compare(C1, C2, getICmpCondCode(Cond)),
2319                              dl, VT, OpVT);
2320     }
2321   }
2322 
2323   auto *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
2324   auto *N2CFP = dyn_cast<ConstantFPSDNode>(N2);
2325 
2326   if (N1CFP && N2CFP) {
2327     APFloat::cmpResult R = N1CFP->getValueAPF().compare(N2CFP->getValueAPF());
2328     switch (Cond) {
2329     default: break;
2330     case ISD::SETEQ:  if (R==APFloat::cmpUnordered)
2331                         return getUNDEF(VT);
2332                       LLVM_FALLTHROUGH;
2333     case ISD::SETOEQ: return getBoolConstant(R==APFloat::cmpEqual, dl, VT,
2334                                              OpVT);
2335     case ISD::SETNE:  if (R==APFloat::cmpUnordered)
2336                         return getUNDEF(VT);
2337                       LLVM_FALLTHROUGH;
2338     case ISD::SETONE: return getBoolConstant(R==APFloat::cmpGreaterThan ||
2339                                              R==APFloat::cmpLessThan, dl, VT,
2340                                              OpVT);
2341     case ISD::SETLT:  if (R==APFloat::cmpUnordered)
2342                         return getUNDEF(VT);
2343                       LLVM_FALLTHROUGH;
2344     case ISD::SETOLT: return getBoolConstant(R==APFloat::cmpLessThan, dl, VT,
2345                                              OpVT);
2346     case ISD::SETGT:  if (R==APFloat::cmpUnordered)
2347                         return getUNDEF(VT);
2348                       LLVM_FALLTHROUGH;
2349     case ISD::SETOGT: return getBoolConstant(R==APFloat::cmpGreaterThan, dl,
2350                                              VT, OpVT);
2351     case ISD::SETLE:  if (R==APFloat::cmpUnordered)
2352                         return getUNDEF(VT);
2353                       LLVM_FALLTHROUGH;
2354     case ISD::SETOLE: return getBoolConstant(R==APFloat::cmpLessThan ||
2355                                              R==APFloat::cmpEqual, dl, VT,
2356                                              OpVT);
2357     case ISD::SETGE:  if (R==APFloat::cmpUnordered)
2358                         return getUNDEF(VT);
2359                       LLVM_FALLTHROUGH;
2360     case ISD::SETOGE: return getBoolConstant(R==APFloat::cmpGreaterThan ||
2361                                          R==APFloat::cmpEqual, dl, VT, OpVT);
2362     case ISD::SETO:   return getBoolConstant(R!=APFloat::cmpUnordered, dl, VT,
2363                                              OpVT);
2364     case ISD::SETUO:  return getBoolConstant(R==APFloat::cmpUnordered, dl, VT,
2365                                              OpVT);
2366     case ISD::SETUEQ: return getBoolConstant(R==APFloat::cmpUnordered ||
2367                                              R==APFloat::cmpEqual, dl, VT,
2368                                              OpVT);
2369     case ISD::SETUNE: return getBoolConstant(R!=APFloat::cmpEqual, dl, VT,
2370                                              OpVT);
2371     case ISD::SETULT: return getBoolConstant(R==APFloat::cmpUnordered ||
2372                                              R==APFloat::cmpLessThan, dl, VT,
2373                                              OpVT);
2374     case ISD::SETUGT: return getBoolConstant(R==APFloat::cmpGreaterThan ||
2375                                              R==APFloat::cmpUnordered, dl, VT,
2376                                              OpVT);
2377     case ISD::SETULE: return getBoolConstant(R!=APFloat::cmpGreaterThan, dl,
2378                                              VT, OpVT);
2379     case ISD::SETUGE: return getBoolConstant(R!=APFloat::cmpLessThan, dl, VT,
2380                                              OpVT);
2381     }
2382   } else if (N1CFP && OpVT.isSimple() && !N2.isUndef()) {
2383     // Ensure that the constant occurs on the RHS.
2384     ISD::CondCode SwappedCond = ISD::getSetCCSwappedOperands(Cond);
2385     if (!TLI->isCondCodeLegal(SwappedCond, OpVT.getSimpleVT()))
2386       return SDValue();
2387     return getSetCC(dl, VT, N2, N1, SwappedCond);
2388   } else if ((N2CFP && N2CFP->getValueAPF().isNaN()) ||
2389              (OpVT.isFloatingPoint() && (N1.isUndef() || N2.isUndef()))) {
2390     // If an operand is known to be a nan (or undef that could be a nan), we can
2391     // fold it.
2392     // Choosing NaN for the undef will always make unordered comparison succeed
2393     // and ordered comparison fails.
2394     // Matches behavior in llvm::ConstantFoldCompareInstruction.
2395     switch (ISD::getUnorderedFlavor(Cond)) {
2396     default:
2397       llvm_unreachable("Unknown flavor!");
2398     case 0: // Known false.
2399       return getBoolConstant(false, dl, VT, OpVT);
2400     case 1: // Known true.
2401       return getBoolConstant(true, dl, VT, OpVT);
2402     case 2: // Undefined.
2403       return getUNDEF(VT);
2404     }
2405   }
2406 
2407   // Could not fold it.
2408   return SDValue();
2409 }
2410 
2411 /// See if the specified operand can be simplified with the knowledge that only
2412 /// the bits specified by DemandedBits are used.
2413 /// TODO: really we should be making this into the DAG equivalent of
2414 /// SimplifyMultipleUseDemandedBits and not generate any new nodes.
2415 SDValue SelectionDAG::GetDemandedBits(SDValue V, const APInt &DemandedBits) {
2416   EVT VT = V.getValueType();
2417 
2418   if (VT.isScalableVector())
2419     return SDValue();
2420 
2421   APInt DemandedElts = VT.isVector()
2422                            ? APInt::getAllOnes(VT.getVectorNumElements())
2423                            : APInt(1, 1);
2424   return GetDemandedBits(V, DemandedBits, DemandedElts);
2425 }
2426 
2427 /// See if the specified operand can be simplified with the knowledge that only
2428 /// the bits specified by DemandedBits are used in the elements specified by
2429 /// DemandedElts.
2430 /// TODO: really we should be making this into the DAG equivalent of
2431 /// SimplifyMultipleUseDemandedBits and not generate any new nodes.
2432 SDValue SelectionDAG::GetDemandedBits(SDValue V, const APInt &DemandedBits,
2433                                       const APInt &DemandedElts) {
2434   switch (V.getOpcode()) {
2435   default:
2436     return TLI->SimplifyMultipleUseDemandedBits(V, DemandedBits, DemandedElts,
2437                                                 *this, 0);
2438   case ISD::Constant: {
2439     const APInt &CVal = cast<ConstantSDNode>(V)->getAPIntValue();
2440     APInt NewVal = CVal & DemandedBits;
2441     if (NewVal != CVal)
2442       return getConstant(NewVal, SDLoc(V), V.getValueType());
2443     break;
2444   }
2445   case ISD::SRL:
2446     // Only look at single-use SRLs.
2447     if (!V.getNode()->hasOneUse())
2448       break;
2449     if (auto *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
2450       // See if we can recursively simplify the LHS.
2451       unsigned Amt = RHSC->getZExtValue();
2452 
2453       // Watch out for shift count overflow though.
2454       if (Amt >= DemandedBits.getBitWidth())
2455         break;
2456       APInt SrcDemandedBits = DemandedBits << Amt;
2457       if (SDValue SimplifyLHS =
2458               GetDemandedBits(V.getOperand(0), SrcDemandedBits))
2459         return getNode(ISD::SRL, SDLoc(V), V.getValueType(), SimplifyLHS,
2460                        V.getOperand(1));
2461     }
2462     break;
2463   }
2464   return SDValue();
2465 }
2466 
2467 /// SignBitIsZero - Return true if the sign bit of Op is known to be zero.  We
2468 /// use this predicate to simplify operations downstream.
2469 bool SelectionDAG::SignBitIsZero(SDValue Op, unsigned Depth) const {
2470   unsigned BitWidth = Op.getScalarValueSizeInBits();
2471   return MaskedValueIsZero(Op, APInt::getSignMask(BitWidth), Depth);
2472 }
2473 
2474 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero.  We use
2475 /// this predicate to simplify operations downstream.  Mask is known to be zero
2476 /// for bits that V cannot have.
2477 bool SelectionDAG::MaskedValueIsZero(SDValue V, const APInt &Mask,
2478                                      unsigned Depth) const {
2479   return Mask.isSubsetOf(computeKnownBits(V, Depth).Zero);
2480 }
2481 
2482 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero in
2483 /// DemandedElts.  We use this predicate to simplify operations downstream.
2484 /// Mask is known to be zero for bits that V cannot have.
2485 bool SelectionDAG::MaskedValueIsZero(SDValue V, const APInt &Mask,
2486                                      const APInt &DemandedElts,
2487                                      unsigned Depth) const {
2488   return Mask.isSubsetOf(computeKnownBits(V, DemandedElts, Depth).Zero);
2489 }
2490 
2491 /// MaskedValueIsAllOnes - Return true if '(Op & Mask) == Mask'.
2492 bool SelectionDAG::MaskedValueIsAllOnes(SDValue V, const APInt &Mask,
2493                                         unsigned Depth) const {
2494   return Mask.isSubsetOf(computeKnownBits(V, Depth).One);
2495 }
2496 
2497 /// isSplatValue - Return true if the vector V has the same value
2498 /// across all DemandedElts. For scalable vectors it does not make
2499 /// sense to specify which elements are demanded or undefined, therefore
2500 /// they are simply ignored.
2501 bool SelectionDAG::isSplatValue(SDValue V, const APInt &DemandedElts,
2502                                 APInt &UndefElts, unsigned Depth) const {
2503   unsigned Opcode = V.getOpcode();
2504   EVT VT = V.getValueType();
2505   assert(VT.isVector() && "Vector type expected");
2506 
2507   if (!VT.isScalableVector() && !DemandedElts)
2508     return false; // No demanded elts, better to assume we don't know anything.
2509 
2510   if (Depth >= MaxRecursionDepth)
2511     return false; // Limit search depth.
2512 
2513   // Deal with some common cases here that work for both fixed and scalable
2514   // vector types.
2515   switch (Opcode) {
2516   case ISD::SPLAT_VECTOR:
2517     UndefElts = V.getOperand(0).isUndef()
2518                     ? APInt::getAllOnes(DemandedElts.getBitWidth())
2519                     : APInt(DemandedElts.getBitWidth(), 0);
2520     return true;
2521   case ISD::ADD:
2522   case ISD::SUB:
2523   case ISD::AND:
2524   case ISD::XOR:
2525   case ISD::OR: {
2526     APInt UndefLHS, UndefRHS;
2527     SDValue LHS = V.getOperand(0);
2528     SDValue RHS = V.getOperand(1);
2529     if (isSplatValue(LHS, DemandedElts, UndefLHS, Depth + 1) &&
2530         isSplatValue(RHS, DemandedElts, UndefRHS, Depth + 1)) {
2531       UndefElts = UndefLHS | UndefRHS;
2532       return true;
2533     }
2534     return false;
2535   }
2536   case ISD::ABS:
2537   case ISD::TRUNCATE:
2538   case ISD::SIGN_EXTEND:
2539   case ISD::ZERO_EXTEND:
2540     return isSplatValue(V.getOperand(0), DemandedElts, UndefElts, Depth + 1);
2541   default:
2542     if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::INTRINSIC_WO_CHAIN ||
2543         Opcode == ISD::INTRINSIC_W_CHAIN || Opcode == ISD::INTRINSIC_VOID)
2544       return TLI->isSplatValueForTargetNode(V, DemandedElts, UndefElts, Depth);
2545     break;
2546 }
2547 
2548   // We don't support other cases than those above for scalable vectors at
2549   // the moment.
2550   if (VT.isScalableVector())
2551     return false;
2552 
2553   unsigned NumElts = VT.getVectorNumElements();
2554   assert(NumElts == DemandedElts.getBitWidth() && "Vector size mismatch");
2555   UndefElts = APInt::getZero(NumElts);
2556 
2557   switch (Opcode) {
2558   case ISD::BUILD_VECTOR: {
2559     SDValue Scl;
2560     for (unsigned i = 0; i != NumElts; ++i) {
2561       SDValue Op = V.getOperand(i);
2562       if (Op.isUndef()) {
2563         UndefElts.setBit(i);
2564         continue;
2565       }
2566       if (!DemandedElts[i])
2567         continue;
2568       if (Scl && Scl != Op)
2569         return false;
2570       Scl = Op;
2571     }
2572     return true;
2573   }
2574   case ISD::VECTOR_SHUFFLE: {
2575     // Check if this is a shuffle node doing a splat.
2576     // TODO: Do we need to handle shuffle(splat, undef, mask)?
2577     int SplatIndex = -1;
2578     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(V)->getMask();
2579     for (int i = 0; i != (int)NumElts; ++i) {
2580       int M = Mask[i];
2581       if (M < 0) {
2582         UndefElts.setBit(i);
2583         continue;
2584       }
2585       if (!DemandedElts[i])
2586         continue;
2587       if (0 <= SplatIndex && SplatIndex != M)
2588         return false;
2589       SplatIndex = M;
2590     }
2591     return true;
2592   }
2593   case ISD::EXTRACT_SUBVECTOR: {
2594     // Offset the demanded elts by the subvector index.
2595     SDValue Src = V.getOperand(0);
2596     // We don't support scalable vectors at the moment.
2597     if (Src.getValueType().isScalableVector())
2598       return false;
2599     uint64_t Idx = V.getConstantOperandVal(1);
2600     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
2601     APInt UndefSrcElts;
2602     APInt DemandedSrcElts = DemandedElts.zextOrSelf(NumSrcElts).shl(Idx);
2603     if (isSplatValue(Src, DemandedSrcElts, UndefSrcElts, Depth + 1)) {
2604       UndefElts = UndefSrcElts.extractBits(NumElts, Idx);
2605       return true;
2606     }
2607     break;
2608   }
2609   case ISD::ANY_EXTEND_VECTOR_INREG:
2610   case ISD::SIGN_EXTEND_VECTOR_INREG:
2611   case ISD::ZERO_EXTEND_VECTOR_INREG: {
2612     // Widen the demanded elts by the src element count.
2613     SDValue Src = V.getOperand(0);
2614     // We don't support scalable vectors at the moment.
2615     if (Src.getValueType().isScalableVector())
2616       return false;
2617     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
2618     APInt UndefSrcElts;
2619     APInt DemandedSrcElts = DemandedElts.zextOrSelf(NumSrcElts);
2620     if (isSplatValue(Src, DemandedSrcElts, UndefSrcElts, Depth + 1)) {
2621       UndefElts = UndefSrcElts.truncOrSelf(NumElts);
2622       return true;
2623     }
2624     break;
2625   }
2626   }
2627 
2628   return false;
2629 }
2630 
2631 /// Helper wrapper to main isSplatValue function.
2632 bool SelectionDAG::isSplatValue(SDValue V, bool AllowUndefs) const {
2633   EVT VT = V.getValueType();
2634   assert(VT.isVector() && "Vector type expected");
2635 
2636   APInt UndefElts;
2637   APInt DemandedElts;
2638 
2639   // For now we don't support this with scalable vectors.
2640   if (!VT.isScalableVector())
2641     DemandedElts = APInt::getAllOnes(VT.getVectorNumElements());
2642   return isSplatValue(V, DemandedElts, UndefElts) &&
2643          (AllowUndefs || !UndefElts);
2644 }
2645 
2646 SDValue SelectionDAG::getSplatSourceVector(SDValue V, int &SplatIdx) {
2647   V = peekThroughExtractSubvectors(V);
2648 
2649   EVT VT = V.getValueType();
2650   unsigned Opcode = V.getOpcode();
2651   switch (Opcode) {
2652   default: {
2653     APInt UndefElts;
2654     APInt DemandedElts;
2655 
2656     if (!VT.isScalableVector())
2657       DemandedElts = APInt::getAllOnes(VT.getVectorNumElements());
2658 
2659     if (isSplatValue(V, DemandedElts, UndefElts)) {
2660       if (VT.isScalableVector()) {
2661         // DemandedElts and UndefElts are ignored for scalable vectors, since
2662         // the only supported cases are SPLAT_VECTOR nodes.
2663         SplatIdx = 0;
2664       } else {
2665         // Handle case where all demanded elements are UNDEF.
2666         if (DemandedElts.isSubsetOf(UndefElts)) {
2667           SplatIdx = 0;
2668           return getUNDEF(VT);
2669         }
2670         SplatIdx = (UndefElts & DemandedElts).countTrailingOnes();
2671       }
2672       return V;
2673     }
2674     break;
2675   }
2676   case ISD::SPLAT_VECTOR:
2677     SplatIdx = 0;
2678     return V;
2679   case ISD::VECTOR_SHUFFLE: {
2680     if (VT.isScalableVector())
2681       return SDValue();
2682 
2683     // Check if this is a shuffle node doing a splat.
2684     // TODO - remove this and rely purely on SelectionDAG::isSplatValue,
2685     // getTargetVShiftNode currently struggles without the splat source.
2686     auto *SVN = cast<ShuffleVectorSDNode>(V);
2687     if (!SVN->isSplat())
2688       break;
2689     int Idx = SVN->getSplatIndex();
2690     int NumElts = V.getValueType().getVectorNumElements();
2691     SplatIdx = Idx % NumElts;
2692     return V.getOperand(Idx / NumElts);
2693   }
2694   }
2695 
2696   return SDValue();
2697 }
2698 
2699 SDValue SelectionDAG::getSplatValue(SDValue V, bool LegalTypes) {
2700   int SplatIdx;
2701   if (SDValue SrcVector = getSplatSourceVector(V, SplatIdx)) {
2702     EVT SVT = SrcVector.getValueType().getScalarType();
2703     EVT LegalSVT = SVT;
2704     if (LegalTypes && !TLI->isTypeLegal(SVT)) {
2705       if (!SVT.isInteger())
2706         return SDValue();
2707       LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT);
2708       if (LegalSVT.bitsLT(SVT))
2709         return SDValue();
2710     }
2711     return getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(V), LegalSVT, SrcVector,
2712                    getVectorIdxConstant(SplatIdx, SDLoc(V)));
2713   }
2714   return SDValue();
2715 }
2716 
2717 const APInt *
2718 SelectionDAG::getValidShiftAmountConstant(SDValue V,
2719                                           const APInt &DemandedElts) const {
2720   assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL ||
2721           V.getOpcode() == ISD::SRA) &&
2722          "Unknown shift node");
2723   unsigned BitWidth = V.getScalarValueSizeInBits();
2724   if (ConstantSDNode *SA = isConstOrConstSplat(V.getOperand(1), DemandedElts)) {
2725     // Shifting more than the bitwidth is not valid.
2726     const APInt &ShAmt = SA->getAPIntValue();
2727     if (ShAmt.ult(BitWidth))
2728       return &ShAmt;
2729   }
2730   return nullptr;
2731 }
2732 
2733 const APInt *SelectionDAG::getValidMinimumShiftAmountConstant(
2734     SDValue V, const APInt &DemandedElts) const {
2735   assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL ||
2736           V.getOpcode() == ISD::SRA) &&
2737          "Unknown shift node");
2738   if (const APInt *ValidAmt = getValidShiftAmountConstant(V, DemandedElts))
2739     return ValidAmt;
2740   unsigned BitWidth = V.getScalarValueSizeInBits();
2741   auto *BV = dyn_cast<BuildVectorSDNode>(V.getOperand(1));
2742   if (!BV)
2743     return nullptr;
2744   const APInt *MinShAmt = nullptr;
2745   for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
2746     if (!DemandedElts[i])
2747       continue;
2748     auto *SA = dyn_cast<ConstantSDNode>(BV->getOperand(i));
2749     if (!SA)
2750       return nullptr;
2751     // Shifting more than the bitwidth is not valid.
2752     const APInt &ShAmt = SA->getAPIntValue();
2753     if (ShAmt.uge(BitWidth))
2754       return nullptr;
2755     if (MinShAmt && MinShAmt->ule(ShAmt))
2756       continue;
2757     MinShAmt = &ShAmt;
2758   }
2759   return MinShAmt;
2760 }
2761 
2762 const APInt *SelectionDAG::getValidMaximumShiftAmountConstant(
2763     SDValue V, const APInt &DemandedElts) const {
2764   assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL ||
2765           V.getOpcode() == ISD::SRA) &&
2766          "Unknown shift node");
2767   if (const APInt *ValidAmt = getValidShiftAmountConstant(V, DemandedElts))
2768     return ValidAmt;
2769   unsigned BitWidth = V.getScalarValueSizeInBits();
2770   auto *BV = dyn_cast<BuildVectorSDNode>(V.getOperand(1));
2771   if (!BV)
2772     return nullptr;
2773   const APInt *MaxShAmt = nullptr;
2774   for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
2775     if (!DemandedElts[i])
2776       continue;
2777     auto *SA = dyn_cast<ConstantSDNode>(BV->getOperand(i));
2778     if (!SA)
2779       return nullptr;
2780     // Shifting more than the bitwidth is not valid.
2781     const APInt &ShAmt = SA->getAPIntValue();
2782     if (ShAmt.uge(BitWidth))
2783       return nullptr;
2784     if (MaxShAmt && MaxShAmt->uge(ShAmt))
2785       continue;
2786     MaxShAmt = &ShAmt;
2787   }
2788   return MaxShAmt;
2789 }
2790 
2791 /// Determine which bits of Op are known to be either zero or one and return
2792 /// them in Known. For vectors, the known bits are those that are shared by
2793 /// every vector element.
2794 KnownBits SelectionDAG::computeKnownBits(SDValue Op, unsigned Depth) const {
2795   EVT VT = Op.getValueType();
2796 
2797   // TOOD: Until we have a plan for how to represent demanded elements for
2798   // scalable vectors, we can just bail out for now.
2799   if (Op.getValueType().isScalableVector()) {
2800     unsigned BitWidth = Op.getScalarValueSizeInBits();
2801     return KnownBits(BitWidth);
2802   }
2803 
2804   APInt DemandedElts = VT.isVector()
2805                            ? APInt::getAllOnes(VT.getVectorNumElements())
2806                            : APInt(1, 1);
2807   return computeKnownBits(Op, DemandedElts, Depth);
2808 }
2809 
2810 /// Determine which bits of Op are known to be either zero or one and return
2811 /// them in Known. The DemandedElts argument allows us to only collect the known
2812 /// bits that are shared by the requested vector elements.
2813 KnownBits SelectionDAG::computeKnownBits(SDValue Op, const APInt &DemandedElts,
2814                                          unsigned Depth) const {
2815   unsigned BitWidth = Op.getScalarValueSizeInBits();
2816 
2817   KnownBits Known(BitWidth);   // Don't know anything.
2818 
2819   // TOOD: Until we have a plan for how to represent demanded elements for
2820   // scalable vectors, we can just bail out for now.
2821   if (Op.getValueType().isScalableVector())
2822     return Known;
2823 
2824   if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
2825     // We know all of the bits for a constant!
2826     return KnownBits::makeConstant(C->getAPIntValue());
2827   }
2828   if (auto *C = dyn_cast<ConstantFPSDNode>(Op)) {
2829     // We know all of the bits for a constant fp!
2830     return KnownBits::makeConstant(C->getValueAPF().bitcastToAPInt());
2831   }
2832 
2833   if (Depth >= MaxRecursionDepth)
2834     return Known;  // Limit search depth.
2835 
2836   KnownBits Known2;
2837   unsigned NumElts = DemandedElts.getBitWidth();
2838   assert((!Op.getValueType().isVector() ||
2839           NumElts == Op.getValueType().getVectorNumElements()) &&
2840          "Unexpected vector size");
2841 
2842   if (!DemandedElts)
2843     return Known;  // No demanded elts, better to assume we don't know anything.
2844 
2845   unsigned Opcode = Op.getOpcode();
2846   switch (Opcode) {
2847   case ISD::BUILD_VECTOR:
2848     // Collect the known bits that are shared by every demanded vector element.
2849     Known.Zero.setAllBits(); Known.One.setAllBits();
2850     for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
2851       if (!DemandedElts[i])
2852         continue;
2853 
2854       SDValue SrcOp = Op.getOperand(i);
2855       Known2 = computeKnownBits(SrcOp, Depth + 1);
2856 
2857       // BUILD_VECTOR can implicitly truncate sources, we must handle this.
2858       if (SrcOp.getValueSizeInBits() != BitWidth) {
2859         assert(SrcOp.getValueSizeInBits() > BitWidth &&
2860                "Expected BUILD_VECTOR implicit truncation");
2861         Known2 = Known2.trunc(BitWidth);
2862       }
2863 
2864       // Known bits are the values that are shared by every demanded element.
2865       Known = KnownBits::commonBits(Known, Known2);
2866 
2867       // If we don't know any bits, early out.
2868       if (Known.isUnknown())
2869         break;
2870     }
2871     break;
2872   case ISD::VECTOR_SHUFFLE: {
2873     // Collect the known bits that are shared by every vector element referenced
2874     // by the shuffle.
2875     APInt DemandedLHS(NumElts, 0), DemandedRHS(NumElts, 0);
2876     Known.Zero.setAllBits(); Known.One.setAllBits();
2877     const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op);
2878     assert(NumElts == SVN->getMask().size() && "Unexpected vector size");
2879     for (unsigned i = 0; i != NumElts; ++i) {
2880       if (!DemandedElts[i])
2881         continue;
2882 
2883       int M = SVN->getMaskElt(i);
2884       if (M < 0) {
2885         // For UNDEF elements, we don't know anything about the common state of
2886         // the shuffle result.
2887         Known.resetAll();
2888         DemandedLHS.clearAllBits();
2889         DemandedRHS.clearAllBits();
2890         break;
2891       }
2892 
2893       if ((unsigned)M < NumElts)
2894         DemandedLHS.setBit((unsigned)M % NumElts);
2895       else
2896         DemandedRHS.setBit((unsigned)M % NumElts);
2897     }
2898     // Known bits are the values that are shared by every demanded element.
2899     if (!!DemandedLHS) {
2900       SDValue LHS = Op.getOperand(0);
2901       Known2 = computeKnownBits(LHS, DemandedLHS, Depth + 1);
2902       Known = KnownBits::commonBits(Known, Known2);
2903     }
2904     // If we don't know any bits, early out.
2905     if (Known.isUnknown())
2906       break;
2907     if (!!DemandedRHS) {
2908       SDValue RHS = Op.getOperand(1);
2909       Known2 = computeKnownBits(RHS, DemandedRHS, Depth + 1);
2910       Known = KnownBits::commonBits(Known, Known2);
2911     }
2912     break;
2913   }
2914   case ISD::CONCAT_VECTORS: {
2915     // Split DemandedElts and test each of the demanded subvectors.
2916     Known.Zero.setAllBits(); Known.One.setAllBits();
2917     EVT SubVectorVT = Op.getOperand(0).getValueType();
2918     unsigned NumSubVectorElts = SubVectorVT.getVectorNumElements();
2919     unsigned NumSubVectors = Op.getNumOperands();
2920     for (unsigned i = 0; i != NumSubVectors; ++i) {
2921       APInt DemandedSub =
2922           DemandedElts.extractBits(NumSubVectorElts, i * NumSubVectorElts);
2923       if (!!DemandedSub) {
2924         SDValue Sub = Op.getOperand(i);
2925         Known2 = computeKnownBits(Sub, DemandedSub, Depth + 1);
2926         Known = KnownBits::commonBits(Known, Known2);
2927       }
2928       // If we don't know any bits, early out.
2929       if (Known.isUnknown())
2930         break;
2931     }
2932     break;
2933   }
2934   case ISD::INSERT_SUBVECTOR: {
2935     // Demand any elements from the subvector and the remainder from the src its
2936     // inserted into.
2937     SDValue Src = Op.getOperand(0);
2938     SDValue Sub = Op.getOperand(1);
2939     uint64_t Idx = Op.getConstantOperandVal(2);
2940     unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
2941     APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
2942     APInt DemandedSrcElts = DemandedElts;
2943     DemandedSrcElts.insertBits(APInt::getZero(NumSubElts), Idx);
2944 
2945     Known.One.setAllBits();
2946     Known.Zero.setAllBits();
2947     if (!!DemandedSubElts) {
2948       Known = computeKnownBits(Sub, DemandedSubElts, Depth + 1);
2949       if (Known.isUnknown())
2950         break; // early-out.
2951     }
2952     if (!!DemandedSrcElts) {
2953       Known2 = computeKnownBits(Src, DemandedSrcElts, Depth + 1);
2954       Known = KnownBits::commonBits(Known, Known2);
2955     }
2956     break;
2957   }
2958   case ISD::EXTRACT_SUBVECTOR: {
2959     // Offset the demanded elts by the subvector index.
2960     SDValue Src = Op.getOperand(0);
2961     // Bail until we can represent demanded elements for scalable vectors.
2962     if (Src.getValueType().isScalableVector())
2963       break;
2964     uint64_t Idx = Op.getConstantOperandVal(1);
2965     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
2966     APInt DemandedSrcElts = DemandedElts.zextOrSelf(NumSrcElts).shl(Idx);
2967     Known = computeKnownBits(Src, DemandedSrcElts, Depth + 1);
2968     break;
2969   }
2970   case ISD::SCALAR_TO_VECTOR: {
2971     // We know about scalar_to_vector as much as we know about it source,
2972     // which becomes the first element of otherwise unknown vector.
2973     if (DemandedElts != 1)
2974       break;
2975 
2976     SDValue N0 = Op.getOperand(0);
2977     Known = computeKnownBits(N0, Depth + 1);
2978     if (N0.getValueSizeInBits() != BitWidth)
2979       Known = Known.trunc(BitWidth);
2980 
2981     break;
2982   }
2983   case ISD::BITCAST: {
2984     SDValue N0 = Op.getOperand(0);
2985     EVT SubVT = N0.getValueType();
2986     unsigned SubBitWidth = SubVT.getScalarSizeInBits();
2987 
2988     // Ignore bitcasts from unsupported types.
2989     if (!(SubVT.isInteger() || SubVT.isFloatingPoint()))
2990       break;
2991 
2992     // Fast handling of 'identity' bitcasts.
2993     if (BitWidth == SubBitWidth) {
2994       Known = computeKnownBits(N0, DemandedElts, Depth + 1);
2995       break;
2996     }
2997 
2998     bool IsLE = getDataLayout().isLittleEndian();
2999 
3000     // Bitcast 'small element' vector to 'large element' scalar/vector.
3001     if ((BitWidth % SubBitWidth) == 0) {
3002       assert(N0.getValueType().isVector() && "Expected bitcast from vector");
3003 
3004       // Collect known bits for the (larger) output by collecting the known
3005       // bits from each set of sub elements and shift these into place.
3006       // We need to separately call computeKnownBits for each set of
3007       // sub elements as the knownbits for each is likely to be different.
3008       unsigned SubScale = BitWidth / SubBitWidth;
3009       APInt SubDemandedElts(NumElts * SubScale, 0);
3010       for (unsigned i = 0; i != NumElts; ++i)
3011         if (DemandedElts[i])
3012           SubDemandedElts.setBit(i * SubScale);
3013 
3014       for (unsigned i = 0; i != SubScale; ++i) {
3015         Known2 = computeKnownBits(N0, SubDemandedElts.shl(i),
3016                          Depth + 1);
3017         unsigned Shifts = IsLE ? i : SubScale - 1 - i;
3018         Known.insertBits(Known2, SubBitWidth * Shifts);
3019       }
3020     }
3021 
3022     // Bitcast 'large element' scalar/vector to 'small element' vector.
3023     if ((SubBitWidth % BitWidth) == 0) {
3024       assert(Op.getValueType().isVector() && "Expected bitcast to vector");
3025 
3026       // Collect known bits for the (smaller) output by collecting the known
3027       // bits from the overlapping larger input elements and extracting the
3028       // sub sections we actually care about.
3029       unsigned SubScale = SubBitWidth / BitWidth;
3030       APInt SubDemandedElts =
3031           APIntOps::ScaleBitMask(DemandedElts, NumElts / SubScale);
3032       Known2 = computeKnownBits(N0, SubDemandedElts, Depth + 1);
3033 
3034       Known.Zero.setAllBits(); Known.One.setAllBits();
3035       for (unsigned i = 0; i != NumElts; ++i)
3036         if (DemandedElts[i]) {
3037           unsigned Shifts = IsLE ? i : NumElts - 1 - i;
3038           unsigned Offset = (Shifts % SubScale) * BitWidth;
3039           Known = KnownBits::commonBits(Known,
3040                                         Known2.extractBits(BitWidth, Offset));
3041           // If we don't know any bits, early out.
3042           if (Known.isUnknown())
3043             break;
3044         }
3045     }
3046     break;
3047   }
3048   case ISD::AND:
3049     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3050     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3051 
3052     Known &= Known2;
3053     break;
3054   case ISD::OR:
3055     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3056     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3057 
3058     Known |= Known2;
3059     break;
3060   case ISD::XOR:
3061     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3062     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3063 
3064     Known ^= Known2;
3065     break;
3066   case ISD::MUL: {
3067     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3068     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3069     Known = KnownBits::mul(Known, Known2);
3070     break;
3071   }
3072   case ISD::MULHU: {
3073     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3074     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3075     Known = KnownBits::mulhu(Known, Known2);
3076     break;
3077   }
3078   case ISD::MULHS: {
3079     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3080     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3081     Known = KnownBits::mulhs(Known, Known2);
3082     break;
3083   }
3084   case ISD::UMUL_LOHI: {
3085     assert((Op.getResNo() == 0 || Op.getResNo() == 1) && "Unknown result");
3086     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3087     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3088     if (Op.getResNo() == 0)
3089       Known = KnownBits::mul(Known, Known2);
3090     else
3091       Known = KnownBits::mulhu(Known, Known2);
3092     break;
3093   }
3094   case ISD::SMUL_LOHI: {
3095     assert((Op.getResNo() == 0 || Op.getResNo() == 1) && "Unknown result");
3096     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3097     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3098     if (Op.getResNo() == 0)
3099       Known = KnownBits::mul(Known, Known2);
3100     else
3101       Known = KnownBits::mulhs(Known, Known2);
3102     break;
3103   }
3104   case ISD::UDIV: {
3105     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3106     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3107     Known = KnownBits::udiv(Known, Known2);
3108     break;
3109   }
3110   case ISD::SELECT:
3111   case ISD::VSELECT:
3112     Known = computeKnownBits(Op.getOperand(2), DemandedElts, Depth+1);
3113     // If we don't know any bits, early out.
3114     if (Known.isUnknown())
3115       break;
3116     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth+1);
3117 
3118     // Only known if known in both the LHS and RHS.
3119     Known = KnownBits::commonBits(Known, Known2);
3120     break;
3121   case ISD::SELECT_CC:
3122     Known = computeKnownBits(Op.getOperand(3), DemandedElts, Depth+1);
3123     // If we don't know any bits, early out.
3124     if (Known.isUnknown())
3125       break;
3126     Known2 = computeKnownBits(Op.getOperand(2), DemandedElts, Depth+1);
3127 
3128     // Only known if known in both the LHS and RHS.
3129     Known = KnownBits::commonBits(Known, Known2);
3130     break;
3131   case ISD::SMULO:
3132   case ISD::UMULO:
3133     if (Op.getResNo() != 1)
3134       break;
3135     // The boolean result conforms to getBooleanContents.
3136     // If we know the result of a setcc has the top bits zero, use this info.
3137     // We know that we have an integer-based boolean since these operations
3138     // are only available for integer.
3139     if (TLI->getBooleanContents(Op.getValueType().isVector(), false) ==
3140             TargetLowering::ZeroOrOneBooleanContent &&
3141         BitWidth > 1)
3142       Known.Zero.setBitsFrom(1);
3143     break;
3144   case ISD::SETCC:
3145   case ISD::STRICT_FSETCC:
3146   case ISD::STRICT_FSETCCS: {
3147     unsigned OpNo = Op->isStrictFPOpcode() ? 1 : 0;
3148     // If we know the result of a setcc has the top bits zero, use this info.
3149     if (TLI->getBooleanContents(Op.getOperand(OpNo).getValueType()) ==
3150             TargetLowering::ZeroOrOneBooleanContent &&
3151         BitWidth > 1)
3152       Known.Zero.setBitsFrom(1);
3153     break;
3154   }
3155   case ISD::SHL:
3156     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3157     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3158     Known = KnownBits::shl(Known, Known2);
3159 
3160     // Minimum shift low bits are known zero.
3161     if (const APInt *ShMinAmt =
3162             getValidMinimumShiftAmountConstant(Op, DemandedElts))
3163       Known.Zero.setLowBits(ShMinAmt->getZExtValue());
3164     break;
3165   case ISD::SRL:
3166     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3167     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3168     Known = KnownBits::lshr(Known, Known2);
3169 
3170     // Minimum shift high bits are known zero.
3171     if (const APInt *ShMinAmt =
3172             getValidMinimumShiftAmountConstant(Op, DemandedElts))
3173       Known.Zero.setHighBits(ShMinAmt->getZExtValue());
3174     break;
3175   case ISD::SRA:
3176     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3177     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3178     Known = KnownBits::ashr(Known, Known2);
3179     // TODO: Add minimum shift high known sign bits.
3180     break;
3181   case ISD::FSHL:
3182   case ISD::FSHR:
3183     if (ConstantSDNode *C = isConstOrConstSplat(Op.getOperand(2), DemandedElts)) {
3184       unsigned Amt = C->getAPIntValue().urem(BitWidth);
3185 
3186       // For fshl, 0-shift returns the 1st arg.
3187       // For fshr, 0-shift returns the 2nd arg.
3188       if (Amt == 0) {
3189         Known = computeKnownBits(Op.getOperand(Opcode == ISD::FSHL ? 0 : 1),
3190                                  DemandedElts, Depth + 1);
3191         break;
3192       }
3193 
3194       // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW)))
3195       // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW))
3196       Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3197       Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3198       if (Opcode == ISD::FSHL) {
3199         Known.One <<= Amt;
3200         Known.Zero <<= Amt;
3201         Known2.One.lshrInPlace(BitWidth - Amt);
3202         Known2.Zero.lshrInPlace(BitWidth - Amt);
3203       } else {
3204         Known.One <<= BitWidth - Amt;
3205         Known.Zero <<= BitWidth - Amt;
3206         Known2.One.lshrInPlace(Amt);
3207         Known2.Zero.lshrInPlace(Amt);
3208       }
3209       Known.One |= Known2.One;
3210       Known.Zero |= Known2.Zero;
3211     }
3212     break;
3213   case ISD::SIGN_EXTEND_INREG: {
3214     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3215     EVT EVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
3216     Known = Known.sextInReg(EVT.getScalarSizeInBits());
3217     break;
3218   }
3219   case ISD::CTTZ:
3220   case ISD::CTTZ_ZERO_UNDEF: {
3221     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3222     // If we have a known 1, its position is our upper bound.
3223     unsigned PossibleTZ = Known2.countMaxTrailingZeros();
3224     unsigned LowBits = Log2_32(PossibleTZ) + 1;
3225     Known.Zero.setBitsFrom(LowBits);
3226     break;
3227   }
3228   case ISD::CTLZ:
3229   case ISD::CTLZ_ZERO_UNDEF: {
3230     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3231     // If we have a known 1, its position is our upper bound.
3232     unsigned PossibleLZ = Known2.countMaxLeadingZeros();
3233     unsigned LowBits = Log2_32(PossibleLZ) + 1;
3234     Known.Zero.setBitsFrom(LowBits);
3235     break;
3236   }
3237   case ISD::CTPOP: {
3238     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3239     // If we know some of the bits are zero, they can't be one.
3240     unsigned PossibleOnes = Known2.countMaxPopulation();
3241     Known.Zero.setBitsFrom(Log2_32(PossibleOnes) + 1);
3242     break;
3243   }
3244   case ISD::PARITY: {
3245     // Parity returns 0 everywhere but the LSB.
3246     Known.Zero.setBitsFrom(1);
3247     break;
3248   }
3249   case ISD::LOAD: {
3250     LoadSDNode *LD = cast<LoadSDNode>(Op);
3251     const Constant *Cst = TLI->getTargetConstantFromLoad(LD);
3252     if (ISD::isNON_EXTLoad(LD) && Cst) {
3253       // Determine any common known bits from the loaded constant pool value.
3254       Type *CstTy = Cst->getType();
3255       if ((NumElts * BitWidth) == CstTy->getPrimitiveSizeInBits()) {
3256         // If its a vector splat, then we can (quickly) reuse the scalar path.
3257         // NOTE: We assume all elements match and none are UNDEF.
3258         if (CstTy->isVectorTy()) {
3259           if (const Constant *Splat = Cst->getSplatValue()) {
3260             Cst = Splat;
3261             CstTy = Cst->getType();
3262           }
3263         }
3264         // TODO - do we need to handle different bitwidths?
3265         if (CstTy->isVectorTy() && BitWidth == CstTy->getScalarSizeInBits()) {
3266           // Iterate across all vector elements finding common known bits.
3267           Known.One.setAllBits();
3268           Known.Zero.setAllBits();
3269           for (unsigned i = 0; i != NumElts; ++i) {
3270             if (!DemandedElts[i])
3271               continue;
3272             if (Constant *Elt = Cst->getAggregateElement(i)) {
3273               if (auto *CInt = dyn_cast<ConstantInt>(Elt)) {
3274                 const APInt &Value = CInt->getValue();
3275                 Known.One &= Value;
3276                 Known.Zero &= ~Value;
3277                 continue;
3278               }
3279               if (auto *CFP = dyn_cast<ConstantFP>(Elt)) {
3280                 APInt Value = CFP->getValueAPF().bitcastToAPInt();
3281                 Known.One &= Value;
3282                 Known.Zero &= ~Value;
3283                 continue;
3284               }
3285             }
3286             Known.One.clearAllBits();
3287             Known.Zero.clearAllBits();
3288             break;
3289           }
3290         } else if (BitWidth == CstTy->getPrimitiveSizeInBits()) {
3291           if (auto *CInt = dyn_cast<ConstantInt>(Cst)) {
3292             Known = KnownBits::makeConstant(CInt->getValue());
3293           } else if (auto *CFP = dyn_cast<ConstantFP>(Cst)) {
3294             Known =
3295                 KnownBits::makeConstant(CFP->getValueAPF().bitcastToAPInt());
3296           }
3297         }
3298       }
3299     } else if (ISD::isZEXTLoad(Op.getNode()) && Op.getResNo() == 0) {
3300       // If this is a ZEXTLoad and we are looking at the loaded value.
3301       EVT VT = LD->getMemoryVT();
3302       unsigned MemBits = VT.getScalarSizeInBits();
3303       Known.Zero.setBitsFrom(MemBits);
3304     } else if (const MDNode *Ranges = LD->getRanges()) {
3305       if (LD->getExtensionType() == ISD::NON_EXTLOAD)
3306         computeKnownBitsFromRangeMetadata(*Ranges, Known);
3307     }
3308     break;
3309   }
3310   case ISD::ZERO_EXTEND_VECTOR_INREG: {
3311     EVT InVT = Op.getOperand(0).getValueType();
3312     APInt InDemandedElts = DemandedElts.zextOrSelf(InVT.getVectorNumElements());
3313     Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1);
3314     Known = Known.zext(BitWidth);
3315     break;
3316   }
3317   case ISD::ZERO_EXTEND: {
3318     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3319     Known = Known.zext(BitWidth);
3320     break;
3321   }
3322   case ISD::SIGN_EXTEND_VECTOR_INREG: {
3323     EVT InVT = Op.getOperand(0).getValueType();
3324     APInt InDemandedElts = DemandedElts.zextOrSelf(InVT.getVectorNumElements());
3325     Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1);
3326     // If the sign bit is known to be zero or one, then sext will extend
3327     // it to the top bits, else it will just zext.
3328     Known = Known.sext(BitWidth);
3329     break;
3330   }
3331   case ISD::SIGN_EXTEND: {
3332     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3333     // If the sign bit is known to be zero or one, then sext will extend
3334     // it to the top bits, else it will just zext.
3335     Known = Known.sext(BitWidth);
3336     break;
3337   }
3338   case ISD::ANY_EXTEND_VECTOR_INREG: {
3339     EVT InVT = Op.getOperand(0).getValueType();
3340     APInt InDemandedElts = DemandedElts.zextOrSelf(InVT.getVectorNumElements());
3341     Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1);
3342     Known = Known.anyext(BitWidth);
3343     break;
3344   }
3345   case ISD::ANY_EXTEND: {
3346     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3347     Known = Known.anyext(BitWidth);
3348     break;
3349   }
3350   case ISD::TRUNCATE: {
3351     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3352     Known = Known.trunc(BitWidth);
3353     break;
3354   }
3355   case ISD::AssertZext: {
3356     EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
3357     APInt InMask = APInt::getLowBitsSet(BitWidth, VT.getSizeInBits());
3358     Known = computeKnownBits(Op.getOperand(0), Depth+1);
3359     Known.Zero |= (~InMask);
3360     Known.One  &= (~Known.Zero);
3361     break;
3362   }
3363   case ISD::AssertAlign: {
3364     unsigned LogOfAlign = Log2(cast<AssertAlignSDNode>(Op)->getAlign());
3365     assert(LogOfAlign != 0);
3366     // If a node is guaranteed to be aligned, set low zero bits accordingly as
3367     // well as clearing one bits.
3368     Known.Zero.setLowBits(LogOfAlign);
3369     Known.One.clearLowBits(LogOfAlign);
3370     break;
3371   }
3372   case ISD::FGETSIGN:
3373     // All bits are zero except the low bit.
3374     Known.Zero.setBitsFrom(1);
3375     break;
3376   case ISD::USUBO:
3377   case ISD::SSUBO:
3378     if (Op.getResNo() == 1) {
3379       // If we know the result of a setcc has the top bits zero, use this info.
3380       if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) ==
3381               TargetLowering::ZeroOrOneBooleanContent &&
3382           BitWidth > 1)
3383         Known.Zero.setBitsFrom(1);
3384       break;
3385     }
3386     LLVM_FALLTHROUGH;
3387   case ISD::SUB:
3388   case ISD::SUBC: {
3389     assert(Op.getResNo() == 0 &&
3390            "We only compute knownbits for the difference here.");
3391 
3392     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3393     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3394     Known = KnownBits::computeForAddSub(/* Add */ false, /* NSW */ false,
3395                                         Known, Known2);
3396     break;
3397   }
3398   case ISD::UADDO:
3399   case ISD::SADDO:
3400   case ISD::ADDCARRY:
3401     if (Op.getResNo() == 1) {
3402       // If we know the result of a setcc has the top bits zero, use this info.
3403       if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) ==
3404               TargetLowering::ZeroOrOneBooleanContent &&
3405           BitWidth > 1)
3406         Known.Zero.setBitsFrom(1);
3407       break;
3408     }
3409     LLVM_FALLTHROUGH;
3410   case ISD::ADD:
3411   case ISD::ADDC:
3412   case ISD::ADDE: {
3413     assert(Op.getResNo() == 0 && "We only compute knownbits for the sum here.");
3414 
3415     // With ADDE and ADDCARRY, a carry bit may be added in.
3416     KnownBits Carry(1);
3417     if (Opcode == ISD::ADDE)
3418       // Can't track carry from glue, set carry to unknown.
3419       Carry.resetAll();
3420     else if (Opcode == ISD::ADDCARRY)
3421       // TODO: Compute known bits for the carry operand. Not sure if it is worth
3422       // the trouble (how often will we find a known carry bit). And I haven't
3423       // tested this very much yet, but something like this might work:
3424       //   Carry = computeKnownBits(Op.getOperand(2), DemandedElts, Depth + 1);
3425       //   Carry = Carry.zextOrTrunc(1, false);
3426       Carry.resetAll();
3427     else
3428       Carry.setAllZero();
3429 
3430     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3431     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3432     Known = KnownBits::computeForAddCarry(Known, Known2, Carry);
3433     break;
3434   }
3435   case ISD::SREM: {
3436     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3437     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3438     Known = KnownBits::srem(Known, Known2);
3439     break;
3440   }
3441   case ISD::UREM: {
3442     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3443     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3444     Known = KnownBits::urem(Known, Known2);
3445     break;
3446   }
3447   case ISD::EXTRACT_ELEMENT: {
3448     Known = computeKnownBits(Op.getOperand(0), Depth+1);
3449     const unsigned Index = Op.getConstantOperandVal(1);
3450     const unsigned EltBitWidth = Op.getValueSizeInBits();
3451 
3452     // Remove low part of known bits mask
3453     Known.Zero = Known.Zero.getHiBits(Known.getBitWidth() - Index * EltBitWidth);
3454     Known.One = Known.One.getHiBits(Known.getBitWidth() - Index * EltBitWidth);
3455 
3456     // Remove high part of known bit mask
3457     Known = Known.trunc(EltBitWidth);
3458     break;
3459   }
3460   case ISD::EXTRACT_VECTOR_ELT: {
3461     SDValue InVec = Op.getOperand(0);
3462     SDValue EltNo = Op.getOperand(1);
3463     EVT VecVT = InVec.getValueType();
3464     // computeKnownBits not yet implemented for scalable vectors.
3465     if (VecVT.isScalableVector())
3466       break;
3467     const unsigned EltBitWidth = VecVT.getScalarSizeInBits();
3468     const unsigned NumSrcElts = VecVT.getVectorNumElements();
3469 
3470     // If BitWidth > EltBitWidth the value is anyext:ed. So we do not know
3471     // anything about the extended bits.
3472     if (BitWidth > EltBitWidth)
3473       Known = Known.trunc(EltBitWidth);
3474 
3475     // If we know the element index, just demand that vector element, else for
3476     // an unknown element index, ignore DemandedElts and demand them all.
3477     APInt DemandedSrcElts = APInt::getAllOnes(NumSrcElts);
3478     auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
3479     if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts))
3480       DemandedSrcElts =
3481           APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue());
3482 
3483     Known = computeKnownBits(InVec, DemandedSrcElts, Depth + 1);
3484     if (BitWidth > EltBitWidth)
3485       Known = Known.anyext(BitWidth);
3486     break;
3487   }
3488   case ISD::INSERT_VECTOR_ELT: {
3489     // If we know the element index, split the demand between the
3490     // source vector and the inserted element, otherwise assume we need
3491     // the original demanded vector elements and the value.
3492     SDValue InVec = Op.getOperand(0);
3493     SDValue InVal = Op.getOperand(1);
3494     SDValue EltNo = Op.getOperand(2);
3495     bool DemandedVal = true;
3496     APInt DemandedVecElts = DemandedElts;
3497     auto *CEltNo = dyn_cast<ConstantSDNode>(EltNo);
3498     if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) {
3499       unsigned EltIdx = CEltNo->getZExtValue();
3500       DemandedVal = !!DemandedElts[EltIdx];
3501       DemandedVecElts.clearBit(EltIdx);
3502     }
3503     Known.One.setAllBits();
3504     Known.Zero.setAllBits();
3505     if (DemandedVal) {
3506       Known2 = computeKnownBits(InVal, Depth + 1);
3507       Known = KnownBits::commonBits(Known, Known2.zextOrTrunc(BitWidth));
3508     }
3509     if (!!DemandedVecElts) {
3510       Known2 = computeKnownBits(InVec, DemandedVecElts, Depth + 1);
3511       Known = KnownBits::commonBits(Known, Known2);
3512     }
3513     break;
3514   }
3515   case ISD::BITREVERSE: {
3516     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3517     Known = Known2.reverseBits();
3518     break;
3519   }
3520   case ISD::BSWAP: {
3521     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3522     Known = Known2.byteSwap();
3523     break;
3524   }
3525   case ISD::ABS: {
3526     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3527     Known = Known2.abs();
3528     break;
3529   }
3530   case ISD::USUBSAT: {
3531     // The result of usubsat will never be larger than the LHS.
3532     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3533     Known.Zero.setHighBits(Known2.countMinLeadingZeros());
3534     break;
3535   }
3536   case ISD::UMIN: {
3537     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3538     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3539     Known = KnownBits::umin(Known, Known2);
3540     break;
3541   }
3542   case ISD::UMAX: {
3543     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3544     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3545     Known = KnownBits::umax(Known, Known2);
3546     break;
3547   }
3548   case ISD::SMIN:
3549   case ISD::SMAX: {
3550     // If we have a clamp pattern, we know that the number of sign bits will be
3551     // the minimum of the clamp min/max range.
3552     bool IsMax = (Opcode == ISD::SMAX);
3553     ConstantSDNode *CstLow = nullptr, *CstHigh = nullptr;
3554     if ((CstLow = isConstOrConstSplat(Op.getOperand(1), DemandedElts)))
3555       if (Op.getOperand(0).getOpcode() == (IsMax ? ISD::SMIN : ISD::SMAX))
3556         CstHigh =
3557             isConstOrConstSplat(Op.getOperand(0).getOperand(1), DemandedElts);
3558     if (CstLow && CstHigh) {
3559       if (!IsMax)
3560         std::swap(CstLow, CstHigh);
3561 
3562       const APInt &ValueLow = CstLow->getAPIntValue();
3563       const APInt &ValueHigh = CstHigh->getAPIntValue();
3564       if (ValueLow.sle(ValueHigh)) {
3565         unsigned LowSignBits = ValueLow.getNumSignBits();
3566         unsigned HighSignBits = ValueHigh.getNumSignBits();
3567         unsigned MinSignBits = std::min(LowSignBits, HighSignBits);
3568         if (ValueLow.isNegative() && ValueHigh.isNegative()) {
3569           Known.One.setHighBits(MinSignBits);
3570           break;
3571         }
3572         if (ValueLow.isNonNegative() && ValueHigh.isNonNegative()) {
3573           Known.Zero.setHighBits(MinSignBits);
3574           break;
3575         }
3576       }
3577     }
3578 
3579     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3580     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3581     if (IsMax)
3582       Known = KnownBits::smax(Known, Known2);
3583     else
3584       Known = KnownBits::smin(Known, Known2);
3585     break;
3586   }
3587   case ISD::FP_TO_UINT_SAT: {
3588     // FP_TO_UINT_SAT produces an unsigned value that fits in the saturating VT.
3589     EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
3590     Known.Zero |= APInt::getBitsSetFrom(BitWidth, VT.getScalarSizeInBits());
3591     break;
3592   }
3593   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
3594     if (Op.getResNo() == 1) {
3595       // The boolean result conforms to getBooleanContents.
3596       // If we know the result of a setcc has the top bits zero, use this info.
3597       // We know that we have an integer-based boolean since these operations
3598       // are only available for integer.
3599       if (TLI->getBooleanContents(Op.getValueType().isVector(), false) ==
3600               TargetLowering::ZeroOrOneBooleanContent &&
3601           BitWidth > 1)
3602         Known.Zero.setBitsFrom(1);
3603       break;
3604     }
3605     LLVM_FALLTHROUGH;
3606   case ISD::ATOMIC_CMP_SWAP:
3607   case ISD::ATOMIC_SWAP:
3608   case ISD::ATOMIC_LOAD_ADD:
3609   case ISD::ATOMIC_LOAD_SUB:
3610   case ISD::ATOMIC_LOAD_AND:
3611   case ISD::ATOMIC_LOAD_CLR:
3612   case ISD::ATOMIC_LOAD_OR:
3613   case ISD::ATOMIC_LOAD_XOR:
3614   case ISD::ATOMIC_LOAD_NAND:
3615   case ISD::ATOMIC_LOAD_MIN:
3616   case ISD::ATOMIC_LOAD_MAX:
3617   case ISD::ATOMIC_LOAD_UMIN:
3618   case ISD::ATOMIC_LOAD_UMAX:
3619   case ISD::ATOMIC_LOAD: {
3620     unsigned MemBits =
3621         cast<AtomicSDNode>(Op)->getMemoryVT().getScalarSizeInBits();
3622     // If we are looking at the loaded value.
3623     if (Op.getResNo() == 0) {
3624       if (TLI->getExtendForAtomicOps() == ISD::ZERO_EXTEND)
3625         Known.Zero.setBitsFrom(MemBits);
3626     }
3627     break;
3628   }
3629   case ISD::FrameIndex:
3630   case ISD::TargetFrameIndex:
3631     TLI->computeKnownBitsForFrameIndex(cast<FrameIndexSDNode>(Op)->getIndex(),
3632                                        Known, getMachineFunction());
3633     break;
3634 
3635   default:
3636     if (Opcode < ISD::BUILTIN_OP_END)
3637       break;
3638     LLVM_FALLTHROUGH;
3639   case ISD::INTRINSIC_WO_CHAIN:
3640   case ISD::INTRINSIC_W_CHAIN:
3641   case ISD::INTRINSIC_VOID:
3642     // Allow the target to implement this method for its nodes.
3643     TLI->computeKnownBitsForTargetNode(Op, Known, DemandedElts, *this, Depth);
3644     break;
3645   }
3646 
3647   assert(!Known.hasConflict() && "Bits known to be one AND zero?");
3648   return Known;
3649 }
3650 
3651 SelectionDAG::OverflowKind SelectionDAG::computeOverflowKind(SDValue N0,
3652                                                              SDValue N1) const {
3653   // X + 0 never overflow
3654   if (isNullConstant(N1))
3655     return OFK_Never;
3656 
3657   KnownBits N1Known = computeKnownBits(N1);
3658   if (N1Known.Zero.getBoolValue()) {
3659     KnownBits N0Known = computeKnownBits(N0);
3660 
3661     bool overflow;
3662     (void)N0Known.getMaxValue().uadd_ov(N1Known.getMaxValue(), overflow);
3663     if (!overflow)
3664       return OFK_Never;
3665   }
3666 
3667   // mulhi + 1 never overflow
3668   if (N0.getOpcode() == ISD::UMUL_LOHI && N0.getResNo() == 1 &&
3669       (N1Known.getMaxValue() & 0x01) == N1Known.getMaxValue())
3670     return OFK_Never;
3671 
3672   if (N1.getOpcode() == ISD::UMUL_LOHI && N1.getResNo() == 1) {
3673     KnownBits N0Known = computeKnownBits(N0);
3674 
3675     if ((N0Known.getMaxValue() & 0x01) == N0Known.getMaxValue())
3676       return OFK_Never;
3677   }
3678 
3679   return OFK_Sometime;
3680 }
3681 
3682 bool SelectionDAG::isKnownToBeAPowerOfTwo(SDValue Val) const {
3683   EVT OpVT = Val.getValueType();
3684   unsigned BitWidth = OpVT.getScalarSizeInBits();
3685 
3686   // Is the constant a known power of 2?
3687   if (ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Val))
3688     return Const->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2();
3689 
3690   // A left-shift of a constant one will have exactly one bit set because
3691   // shifting the bit off the end is undefined.
3692   if (Val.getOpcode() == ISD::SHL) {
3693     auto *C = isConstOrConstSplat(Val.getOperand(0));
3694     if (C && C->getAPIntValue() == 1)
3695       return true;
3696   }
3697 
3698   // Similarly, a logical right-shift of a constant sign-bit will have exactly
3699   // one bit set.
3700   if (Val.getOpcode() == ISD::SRL) {
3701     auto *C = isConstOrConstSplat(Val.getOperand(0));
3702     if (C && C->getAPIntValue().isSignMask())
3703       return true;
3704   }
3705 
3706   // Are all operands of a build vector constant powers of two?
3707   if (Val.getOpcode() == ISD::BUILD_VECTOR)
3708     if (llvm::all_of(Val->ops(), [BitWidth](SDValue E) {
3709           if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(E))
3710             return C->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2();
3711           return false;
3712         }))
3713       return true;
3714 
3715   // Is the operand of a splat vector a constant power of two?
3716   if (Val.getOpcode() == ISD::SPLAT_VECTOR)
3717     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val->getOperand(0)))
3718       if (C->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2())
3719         return true;
3720 
3721   // More could be done here, though the above checks are enough
3722   // to handle some common cases.
3723 
3724   // Fall back to computeKnownBits to catch other known cases.
3725   KnownBits Known = computeKnownBits(Val);
3726   return (Known.countMaxPopulation() == 1) && (Known.countMinPopulation() == 1);
3727 }
3728 
3729 unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, unsigned Depth) const {
3730   EVT VT = Op.getValueType();
3731 
3732   // TODO: Assume we don't know anything for now.
3733   if (VT.isScalableVector())
3734     return 1;
3735 
3736   APInt DemandedElts = VT.isVector()
3737                            ? APInt::getAllOnes(VT.getVectorNumElements())
3738                            : APInt(1, 1);
3739   return ComputeNumSignBits(Op, DemandedElts, Depth);
3740 }
3741 
3742 unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, const APInt &DemandedElts,
3743                                           unsigned Depth) const {
3744   EVT VT = Op.getValueType();
3745   assert((VT.isInteger() || VT.isFloatingPoint()) && "Invalid VT!");
3746   unsigned VTBits = VT.getScalarSizeInBits();
3747   unsigned NumElts = DemandedElts.getBitWidth();
3748   unsigned Tmp, Tmp2;
3749   unsigned FirstAnswer = 1;
3750 
3751   if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
3752     const APInt &Val = C->getAPIntValue();
3753     return Val.getNumSignBits();
3754   }
3755 
3756   if (Depth >= MaxRecursionDepth)
3757     return 1;  // Limit search depth.
3758 
3759   if (!DemandedElts || VT.isScalableVector())
3760     return 1;  // No demanded elts, better to assume we don't know anything.
3761 
3762   unsigned Opcode = Op.getOpcode();
3763   switch (Opcode) {
3764   default: break;
3765   case ISD::AssertSext:
3766     Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
3767     return VTBits-Tmp+1;
3768   case ISD::AssertZext:
3769     Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
3770     return VTBits-Tmp;
3771 
3772   case ISD::BUILD_VECTOR:
3773     Tmp = VTBits;
3774     for (unsigned i = 0, e = Op.getNumOperands(); (i < e) && (Tmp > 1); ++i) {
3775       if (!DemandedElts[i])
3776         continue;
3777 
3778       SDValue SrcOp = Op.getOperand(i);
3779       Tmp2 = ComputeNumSignBits(SrcOp, Depth + 1);
3780 
3781       // BUILD_VECTOR can implicitly truncate sources, we must handle this.
3782       if (SrcOp.getValueSizeInBits() != VTBits) {
3783         assert(SrcOp.getValueSizeInBits() > VTBits &&
3784                "Expected BUILD_VECTOR implicit truncation");
3785         unsigned ExtraBits = SrcOp.getValueSizeInBits() - VTBits;
3786         Tmp2 = (Tmp2 > ExtraBits ? Tmp2 - ExtraBits : 1);
3787       }
3788       Tmp = std::min(Tmp, Tmp2);
3789     }
3790     return Tmp;
3791 
3792   case ISD::VECTOR_SHUFFLE: {
3793     // Collect the minimum number of sign bits that are shared by every vector
3794     // element referenced by the shuffle.
3795     APInt DemandedLHS(NumElts, 0), DemandedRHS(NumElts, 0);
3796     const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op);
3797     assert(NumElts == SVN->getMask().size() && "Unexpected vector size");
3798     for (unsigned i = 0; i != NumElts; ++i) {
3799       int M = SVN->getMaskElt(i);
3800       if (!DemandedElts[i])
3801         continue;
3802       // For UNDEF elements, we don't know anything about the common state of
3803       // the shuffle result.
3804       if (M < 0)
3805         return 1;
3806       if ((unsigned)M < NumElts)
3807         DemandedLHS.setBit((unsigned)M % NumElts);
3808       else
3809         DemandedRHS.setBit((unsigned)M % NumElts);
3810     }
3811     Tmp = std::numeric_limits<unsigned>::max();
3812     if (!!DemandedLHS)
3813       Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedLHS, Depth + 1);
3814     if (!!DemandedRHS) {
3815       Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedRHS, Depth + 1);
3816       Tmp = std::min(Tmp, Tmp2);
3817     }
3818     // If we don't know anything, early out and try computeKnownBits fall-back.
3819     if (Tmp == 1)
3820       break;
3821     assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
3822     return Tmp;
3823   }
3824 
3825   case ISD::BITCAST: {
3826     SDValue N0 = Op.getOperand(0);
3827     EVT SrcVT = N0.getValueType();
3828     unsigned SrcBits = SrcVT.getScalarSizeInBits();
3829 
3830     // Ignore bitcasts from unsupported types..
3831     if (!(SrcVT.isInteger() || SrcVT.isFloatingPoint()))
3832       break;
3833 
3834     // Fast handling of 'identity' bitcasts.
3835     if (VTBits == SrcBits)
3836       return ComputeNumSignBits(N0, DemandedElts, Depth + 1);
3837 
3838     bool IsLE = getDataLayout().isLittleEndian();
3839 
3840     // Bitcast 'large element' scalar/vector to 'small element' vector.
3841     if ((SrcBits % VTBits) == 0) {
3842       assert(VT.isVector() && "Expected bitcast to vector");
3843 
3844       unsigned Scale = SrcBits / VTBits;
3845       APInt SrcDemandedElts =
3846           APIntOps::ScaleBitMask(DemandedElts, NumElts / Scale);
3847 
3848       // Fast case - sign splat can be simply split across the small elements.
3849       Tmp = ComputeNumSignBits(N0, SrcDemandedElts, Depth + 1);
3850       if (Tmp == SrcBits)
3851         return VTBits;
3852 
3853       // Slow case - determine how far the sign extends into each sub-element.
3854       Tmp2 = VTBits;
3855       for (unsigned i = 0; i != NumElts; ++i)
3856         if (DemandedElts[i]) {
3857           unsigned SubOffset = i % Scale;
3858           SubOffset = (IsLE ? ((Scale - 1) - SubOffset) : SubOffset);
3859           SubOffset = SubOffset * VTBits;
3860           if (Tmp <= SubOffset)
3861             return 1;
3862           Tmp2 = std::min(Tmp2, Tmp - SubOffset);
3863         }
3864       return Tmp2;
3865     }
3866     break;
3867   }
3868 
3869   case ISD::FP_TO_SINT_SAT:
3870     // FP_TO_SINT_SAT produces a signed value that fits in the saturating VT.
3871     Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getScalarSizeInBits();
3872     return VTBits - Tmp + 1;
3873   case ISD::SIGN_EXTEND:
3874     Tmp = VTBits - Op.getOperand(0).getScalarValueSizeInBits();
3875     return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1) + Tmp;
3876   case ISD::SIGN_EXTEND_INREG:
3877     // Max of the input and what this extends.
3878     Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getScalarSizeInBits();
3879     Tmp = VTBits-Tmp+1;
3880     Tmp2 = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1);
3881     return std::max(Tmp, Tmp2);
3882   case ISD::SIGN_EXTEND_VECTOR_INREG: {
3883     SDValue Src = Op.getOperand(0);
3884     EVT SrcVT = Src.getValueType();
3885     APInt DemandedSrcElts = DemandedElts.zextOrSelf(SrcVT.getVectorNumElements());
3886     Tmp = VTBits - SrcVT.getScalarSizeInBits();
3887     return ComputeNumSignBits(Src, DemandedSrcElts, Depth+1) + Tmp;
3888   }
3889   case ISD::SRA:
3890     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
3891     // SRA X, C -> adds C sign bits.
3892     if (const APInt *ShAmt =
3893             getValidMinimumShiftAmountConstant(Op, DemandedElts))
3894       Tmp = std::min<uint64_t>(Tmp + ShAmt->getZExtValue(), VTBits);
3895     return Tmp;
3896   case ISD::SHL:
3897     if (const APInt *ShAmt =
3898             getValidMaximumShiftAmountConstant(Op, DemandedElts)) {
3899       // shl destroys sign bits, ensure it doesn't shift out all sign bits.
3900       Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
3901       if (ShAmt->ult(Tmp))
3902         return Tmp - ShAmt->getZExtValue();
3903     }
3904     break;
3905   case ISD::AND:
3906   case ISD::OR:
3907   case ISD::XOR:    // NOT is handled here.
3908     // Logical binary ops preserve the number of sign bits at the worst.
3909     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1);
3910     if (Tmp != 1) {
3911       Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth+1);
3912       FirstAnswer = std::min(Tmp, Tmp2);
3913       // We computed what we know about the sign bits as our first
3914       // answer. Now proceed to the generic code that uses
3915       // computeKnownBits, and pick whichever answer is better.
3916     }
3917     break;
3918 
3919   case ISD::SELECT:
3920   case ISD::VSELECT:
3921     Tmp = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth+1);
3922     if (Tmp == 1) return 1;  // Early out.
3923     Tmp2 = ComputeNumSignBits(Op.getOperand(2), DemandedElts, Depth+1);
3924     return std::min(Tmp, Tmp2);
3925   case ISD::SELECT_CC:
3926     Tmp = ComputeNumSignBits(Op.getOperand(2), DemandedElts, Depth+1);
3927     if (Tmp == 1) return 1;  // Early out.
3928     Tmp2 = ComputeNumSignBits(Op.getOperand(3), DemandedElts, Depth+1);
3929     return std::min(Tmp, Tmp2);
3930 
3931   case ISD::SMIN:
3932   case ISD::SMAX: {
3933     // If we have a clamp pattern, we know that the number of sign bits will be
3934     // the minimum of the clamp min/max range.
3935     bool IsMax = (Opcode == ISD::SMAX);
3936     ConstantSDNode *CstLow = nullptr, *CstHigh = nullptr;
3937     if ((CstLow = isConstOrConstSplat(Op.getOperand(1), DemandedElts)))
3938       if (Op.getOperand(0).getOpcode() == (IsMax ? ISD::SMIN : ISD::SMAX))
3939         CstHigh =
3940             isConstOrConstSplat(Op.getOperand(0).getOperand(1), DemandedElts);
3941     if (CstLow && CstHigh) {
3942       if (!IsMax)
3943         std::swap(CstLow, CstHigh);
3944       if (CstLow->getAPIntValue().sle(CstHigh->getAPIntValue())) {
3945         Tmp = CstLow->getAPIntValue().getNumSignBits();
3946         Tmp2 = CstHigh->getAPIntValue().getNumSignBits();
3947         return std::min(Tmp, Tmp2);
3948       }
3949     }
3950 
3951     // Fallback - just get the minimum number of sign bits of the operands.
3952     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
3953     if (Tmp == 1)
3954       return 1;  // Early out.
3955     Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
3956     return std::min(Tmp, Tmp2);
3957   }
3958   case ISD::UMIN:
3959   case ISD::UMAX:
3960     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
3961     if (Tmp == 1)
3962       return 1;  // Early out.
3963     Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
3964     return std::min(Tmp, Tmp2);
3965   case ISD::SADDO:
3966   case ISD::UADDO:
3967   case ISD::SSUBO:
3968   case ISD::USUBO:
3969   case ISD::SMULO:
3970   case ISD::UMULO:
3971     if (Op.getResNo() != 1)
3972       break;
3973     // The boolean result conforms to getBooleanContents.  Fall through.
3974     // If setcc returns 0/-1, all bits are sign bits.
3975     // We know that we have an integer-based boolean since these operations
3976     // are only available for integer.
3977     if (TLI->getBooleanContents(VT.isVector(), false) ==
3978         TargetLowering::ZeroOrNegativeOneBooleanContent)
3979       return VTBits;
3980     break;
3981   case ISD::SETCC:
3982   case ISD::STRICT_FSETCC:
3983   case ISD::STRICT_FSETCCS: {
3984     unsigned OpNo = Op->isStrictFPOpcode() ? 1 : 0;
3985     // If setcc returns 0/-1, all bits are sign bits.
3986     if (TLI->getBooleanContents(Op.getOperand(OpNo).getValueType()) ==
3987         TargetLowering::ZeroOrNegativeOneBooleanContent)
3988       return VTBits;
3989     break;
3990   }
3991   case ISD::ROTL:
3992   case ISD::ROTR:
3993     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
3994 
3995     // If we're rotating an 0/-1 value, then it stays an 0/-1 value.
3996     if (Tmp == VTBits)
3997       return VTBits;
3998 
3999     if (ConstantSDNode *C =
4000             isConstOrConstSplat(Op.getOperand(1), DemandedElts)) {
4001       unsigned RotAmt = C->getAPIntValue().urem(VTBits);
4002 
4003       // Handle rotate right by N like a rotate left by 32-N.
4004       if (Opcode == ISD::ROTR)
4005         RotAmt = (VTBits - RotAmt) % VTBits;
4006 
4007       // If we aren't rotating out all of the known-in sign bits, return the
4008       // number that are left.  This handles rotl(sext(x), 1) for example.
4009       if (Tmp > (RotAmt + 1)) return (Tmp - RotAmt);
4010     }
4011     break;
4012   case ISD::ADD:
4013   case ISD::ADDC:
4014     // Add can have at most one carry bit.  Thus we know that the output
4015     // is, at worst, one more bit than the inputs.
4016     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
4017     if (Tmp == 1) return 1; // Early out.
4018 
4019     // Special case decrementing a value (ADD X, -1):
4020     if (ConstantSDNode *CRHS =
4021             isConstOrConstSplat(Op.getOperand(1), DemandedElts))
4022       if (CRHS->isAllOnes()) {
4023         KnownBits Known =
4024             computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4025 
4026         // If the input is known to be 0 or 1, the output is 0/-1, which is all
4027         // sign bits set.
4028         if ((Known.Zero | 1).isAllOnes())
4029           return VTBits;
4030 
4031         // If we are subtracting one from a positive number, there is no carry
4032         // out of the result.
4033         if (Known.isNonNegative())
4034           return Tmp;
4035       }
4036 
4037     Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
4038     if (Tmp2 == 1) return 1; // Early out.
4039     return std::min(Tmp, Tmp2) - 1;
4040   case ISD::SUB:
4041     Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
4042     if (Tmp2 == 1) return 1; // Early out.
4043 
4044     // Handle NEG.
4045     if (ConstantSDNode *CLHS =
4046             isConstOrConstSplat(Op.getOperand(0), DemandedElts))
4047       if (CLHS->isZero()) {
4048         KnownBits Known =
4049             computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4050         // If the input is known to be 0 or 1, the output is 0/-1, which is all
4051         // sign bits set.
4052         if ((Known.Zero | 1).isAllOnes())
4053           return VTBits;
4054 
4055         // If the input is known to be positive (the sign bit is known clear),
4056         // the output of the NEG has the same number of sign bits as the input.
4057         if (Known.isNonNegative())
4058           return Tmp2;
4059 
4060         // Otherwise, we treat this like a SUB.
4061       }
4062 
4063     // Sub can have at most one carry bit.  Thus we know that the output
4064     // is, at worst, one more bit than the inputs.
4065     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
4066     if (Tmp == 1) return 1; // Early out.
4067     return std::min(Tmp, Tmp2) - 1;
4068   case ISD::MUL: {
4069     // The output of the Mul can be at most twice the valid bits in the inputs.
4070     unsigned SignBitsOp0 = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
4071     if (SignBitsOp0 == 1)
4072       break;
4073     unsigned SignBitsOp1 = ComputeNumSignBits(Op.getOperand(1), Depth + 1);
4074     if (SignBitsOp1 == 1)
4075       break;
4076     unsigned OutValidBits =
4077         (VTBits - SignBitsOp0 + 1) + (VTBits - SignBitsOp1 + 1);
4078     return OutValidBits > VTBits ? 1 : VTBits - OutValidBits + 1;
4079   }
4080   case ISD::SREM:
4081     // The sign bit is the LHS's sign bit, except when the result of the
4082     // remainder is zero. The magnitude of the result should be less than or
4083     // equal to the magnitude of the LHS. Therefore, the result should have
4084     // at least as many sign bits as the left hand side.
4085     return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
4086   case ISD::TRUNCATE: {
4087     // Check if the sign bits of source go down as far as the truncated value.
4088     unsigned NumSrcBits = Op.getOperand(0).getScalarValueSizeInBits();
4089     unsigned NumSrcSignBits = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
4090     if (NumSrcSignBits > (NumSrcBits - VTBits))
4091       return NumSrcSignBits - (NumSrcBits - VTBits);
4092     break;
4093   }
4094   case ISD::EXTRACT_ELEMENT: {
4095     const int KnownSign = ComputeNumSignBits(Op.getOperand(0), Depth+1);
4096     const int BitWidth = Op.getValueSizeInBits();
4097     const int Items = Op.getOperand(0).getValueSizeInBits() / BitWidth;
4098 
4099     // Get reverse index (starting from 1), Op1 value indexes elements from
4100     // little end. Sign starts at big end.
4101     const int rIndex = Items - 1 - Op.getConstantOperandVal(1);
4102 
4103     // If the sign portion ends in our element the subtraction gives correct
4104     // result. Otherwise it gives either negative or > bitwidth result
4105     return std::max(std::min(KnownSign - rIndex * BitWidth, BitWidth), 0);
4106   }
4107   case ISD::INSERT_VECTOR_ELT: {
4108     // If we know the element index, split the demand between the
4109     // source vector and the inserted element, otherwise assume we need
4110     // the original demanded vector elements and the value.
4111     SDValue InVec = Op.getOperand(0);
4112     SDValue InVal = Op.getOperand(1);
4113     SDValue EltNo = Op.getOperand(2);
4114     bool DemandedVal = true;
4115     APInt DemandedVecElts = DemandedElts;
4116     auto *CEltNo = dyn_cast<ConstantSDNode>(EltNo);
4117     if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) {
4118       unsigned EltIdx = CEltNo->getZExtValue();
4119       DemandedVal = !!DemandedElts[EltIdx];
4120       DemandedVecElts.clearBit(EltIdx);
4121     }
4122     Tmp = std::numeric_limits<unsigned>::max();
4123     if (DemandedVal) {
4124       // TODO - handle implicit truncation of inserted elements.
4125       if (InVal.getScalarValueSizeInBits() != VTBits)
4126         break;
4127       Tmp2 = ComputeNumSignBits(InVal, Depth + 1);
4128       Tmp = std::min(Tmp, Tmp2);
4129     }
4130     if (!!DemandedVecElts) {
4131       Tmp2 = ComputeNumSignBits(InVec, DemandedVecElts, Depth + 1);
4132       Tmp = std::min(Tmp, Tmp2);
4133     }
4134     assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
4135     return Tmp;
4136   }
4137   case ISD::EXTRACT_VECTOR_ELT: {
4138     SDValue InVec = Op.getOperand(0);
4139     SDValue EltNo = Op.getOperand(1);
4140     EVT VecVT = InVec.getValueType();
4141     // ComputeNumSignBits not yet implemented for scalable vectors.
4142     if (VecVT.isScalableVector())
4143       break;
4144     const unsigned BitWidth = Op.getValueSizeInBits();
4145     const unsigned EltBitWidth = Op.getOperand(0).getScalarValueSizeInBits();
4146     const unsigned NumSrcElts = VecVT.getVectorNumElements();
4147 
4148     // If BitWidth > EltBitWidth the value is anyext:ed, and we do not know
4149     // anything about sign bits. But if the sizes match we can derive knowledge
4150     // about sign bits from the vector operand.
4151     if (BitWidth != EltBitWidth)
4152       break;
4153 
4154     // If we know the element index, just demand that vector element, else for
4155     // an unknown element index, ignore DemandedElts and demand them all.
4156     APInt DemandedSrcElts = APInt::getAllOnes(NumSrcElts);
4157     auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
4158     if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts))
4159       DemandedSrcElts =
4160           APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue());
4161 
4162     return ComputeNumSignBits(InVec, DemandedSrcElts, Depth + 1);
4163   }
4164   case ISD::EXTRACT_SUBVECTOR: {
4165     // Offset the demanded elts by the subvector index.
4166     SDValue Src = Op.getOperand(0);
4167     // Bail until we can represent demanded elements for scalable vectors.
4168     if (Src.getValueType().isScalableVector())
4169       break;
4170     uint64_t Idx = Op.getConstantOperandVal(1);
4171     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
4172     APInt DemandedSrcElts = DemandedElts.zextOrSelf(NumSrcElts).shl(Idx);
4173     return ComputeNumSignBits(Src, DemandedSrcElts, Depth + 1);
4174   }
4175   case ISD::CONCAT_VECTORS: {
4176     // Determine the minimum number of sign bits across all demanded
4177     // elts of the input vectors. Early out if the result is already 1.
4178     Tmp = std::numeric_limits<unsigned>::max();
4179     EVT SubVectorVT = Op.getOperand(0).getValueType();
4180     unsigned NumSubVectorElts = SubVectorVT.getVectorNumElements();
4181     unsigned NumSubVectors = Op.getNumOperands();
4182     for (unsigned i = 0; (i < NumSubVectors) && (Tmp > 1); ++i) {
4183       APInt DemandedSub =
4184           DemandedElts.extractBits(NumSubVectorElts, i * NumSubVectorElts);
4185       if (!DemandedSub)
4186         continue;
4187       Tmp2 = ComputeNumSignBits(Op.getOperand(i), DemandedSub, Depth + 1);
4188       Tmp = std::min(Tmp, Tmp2);
4189     }
4190     assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
4191     return Tmp;
4192   }
4193   case ISD::INSERT_SUBVECTOR: {
4194     // Demand any elements from the subvector and the remainder from the src its
4195     // inserted into.
4196     SDValue Src = Op.getOperand(0);
4197     SDValue Sub = Op.getOperand(1);
4198     uint64_t Idx = Op.getConstantOperandVal(2);
4199     unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
4200     APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
4201     APInt DemandedSrcElts = DemandedElts;
4202     DemandedSrcElts.insertBits(APInt::getZero(NumSubElts), Idx);
4203 
4204     Tmp = std::numeric_limits<unsigned>::max();
4205     if (!!DemandedSubElts) {
4206       Tmp = ComputeNumSignBits(Sub, DemandedSubElts, Depth + 1);
4207       if (Tmp == 1)
4208         return 1; // early-out
4209     }
4210     if (!!DemandedSrcElts) {
4211       Tmp2 = ComputeNumSignBits(Src, DemandedSrcElts, Depth + 1);
4212       Tmp = std::min(Tmp, Tmp2);
4213     }
4214     assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
4215     return Tmp;
4216   }
4217   case ISD::ATOMIC_CMP_SWAP:
4218   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
4219   case ISD::ATOMIC_SWAP:
4220   case ISD::ATOMIC_LOAD_ADD:
4221   case ISD::ATOMIC_LOAD_SUB:
4222   case ISD::ATOMIC_LOAD_AND:
4223   case ISD::ATOMIC_LOAD_CLR:
4224   case ISD::ATOMIC_LOAD_OR:
4225   case ISD::ATOMIC_LOAD_XOR:
4226   case ISD::ATOMIC_LOAD_NAND:
4227   case ISD::ATOMIC_LOAD_MIN:
4228   case ISD::ATOMIC_LOAD_MAX:
4229   case ISD::ATOMIC_LOAD_UMIN:
4230   case ISD::ATOMIC_LOAD_UMAX:
4231   case ISD::ATOMIC_LOAD: {
4232     Tmp = cast<AtomicSDNode>(Op)->getMemoryVT().getScalarSizeInBits();
4233     // If we are looking at the loaded value.
4234     if (Op.getResNo() == 0) {
4235       if (Tmp == VTBits)
4236         return 1; // early-out
4237       if (TLI->getExtendForAtomicOps() == ISD::SIGN_EXTEND)
4238         return VTBits - Tmp + 1;
4239       if (TLI->getExtendForAtomicOps() == ISD::ZERO_EXTEND)
4240         return VTBits - Tmp;
4241     }
4242     break;
4243   }
4244   }
4245 
4246   // If we are looking at the loaded value of the SDNode.
4247   if (Op.getResNo() == 0) {
4248     // Handle LOADX separately here. EXTLOAD case will fallthrough.
4249     if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
4250       unsigned ExtType = LD->getExtensionType();
4251       switch (ExtType) {
4252       default: break;
4253       case ISD::SEXTLOAD: // e.g. i16->i32 = '17' bits known.
4254         Tmp = LD->getMemoryVT().getScalarSizeInBits();
4255         return VTBits - Tmp + 1;
4256       case ISD::ZEXTLOAD: // e.g. i16->i32 = '16' bits known.
4257         Tmp = LD->getMemoryVT().getScalarSizeInBits();
4258         return VTBits - Tmp;
4259       case ISD::NON_EXTLOAD:
4260         if (const Constant *Cst = TLI->getTargetConstantFromLoad(LD)) {
4261           // We only need to handle vectors - computeKnownBits should handle
4262           // scalar cases.
4263           Type *CstTy = Cst->getType();
4264           if (CstTy->isVectorTy() &&
4265               (NumElts * VTBits) == CstTy->getPrimitiveSizeInBits()) {
4266             Tmp = VTBits;
4267             for (unsigned i = 0; i != NumElts; ++i) {
4268               if (!DemandedElts[i])
4269                 continue;
4270               if (Constant *Elt = Cst->getAggregateElement(i)) {
4271                 if (auto *CInt = dyn_cast<ConstantInt>(Elt)) {
4272                   const APInt &Value = CInt->getValue();
4273                   Tmp = std::min(Tmp, Value.getNumSignBits());
4274                   continue;
4275                 }
4276                 if (auto *CFP = dyn_cast<ConstantFP>(Elt)) {
4277                   APInt Value = CFP->getValueAPF().bitcastToAPInt();
4278                   Tmp = std::min(Tmp, Value.getNumSignBits());
4279                   continue;
4280                 }
4281               }
4282               // Unknown type. Conservatively assume no bits match sign bit.
4283               return 1;
4284             }
4285             return Tmp;
4286           }
4287         }
4288         break;
4289       }
4290     }
4291   }
4292 
4293   // Allow the target to implement this method for its nodes.
4294   if (Opcode >= ISD::BUILTIN_OP_END ||
4295       Opcode == ISD::INTRINSIC_WO_CHAIN ||
4296       Opcode == ISD::INTRINSIC_W_CHAIN ||
4297       Opcode == ISD::INTRINSIC_VOID) {
4298     unsigned NumBits =
4299         TLI->ComputeNumSignBitsForTargetNode(Op, DemandedElts, *this, Depth);
4300     if (NumBits > 1)
4301       FirstAnswer = std::max(FirstAnswer, NumBits);
4302   }
4303 
4304   // Finally, if we can prove that the top bits of the result are 0's or 1's,
4305   // use this information.
4306   KnownBits Known = computeKnownBits(Op, DemandedElts, Depth);
4307   return std::max(FirstAnswer, Known.countMinSignBits());
4308 }
4309 
4310 unsigned SelectionDAG::ComputeMaxSignificantBits(SDValue Op,
4311                                                  unsigned Depth) const {
4312   unsigned SignBits = ComputeNumSignBits(Op, Depth);
4313   return Op.getScalarValueSizeInBits() - SignBits + 1;
4314 }
4315 
4316 unsigned SelectionDAG::ComputeMaxSignificantBits(SDValue Op,
4317                                                  const APInt &DemandedElts,
4318                                                  unsigned Depth) const {
4319   unsigned SignBits = ComputeNumSignBits(Op, DemandedElts, Depth);
4320   return Op.getScalarValueSizeInBits() - SignBits + 1;
4321 }
4322 
4323 bool SelectionDAG::isGuaranteedNotToBeUndefOrPoison(SDValue Op, bool PoisonOnly,
4324                                                     unsigned Depth) const {
4325   // Early out for FREEZE.
4326   if (Op.getOpcode() == ISD::FREEZE)
4327     return true;
4328 
4329   // TODO: Assume we don't know anything for now.
4330   EVT VT = Op.getValueType();
4331   if (VT.isScalableVector())
4332     return false;
4333 
4334   APInt DemandedElts = VT.isVector()
4335                            ? APInt::getAllOnes(VT.getVectorNumElements())
4336                            : APInt(1, 1);
4337   return isGuaranteedNotToBeUndefOrPoison(Op, DemandedElts, PoisonOnly, Depth);
4338 }
4339 
4340 bool SelectionDAG::isGuaranteedNotToBeUndefOrPoison(SDValue Op,
4341                                                     const APInt &DemandedElts,
4342                                                     bool PoisonOnly,
4343                                                     unsigned Depth) const {
4344   unsigned Opcode = Op.getOpcode();
4345 
4346   // Early out for FREEZE.
4347   if (Opcode == ISD::FREEZE)
4348     return true;
4349 
4350   if (Depth >= MaxRecursionDepth)
4351     return false; // Limit search depth.
4352 
4353   if (isIntOrFPConstant(Op))
4354     return true;
4355 
4356   switch (Opcode) {
4357   case ISD::UNDEF:
4358     return PoisonOnly;
4359 
4360   case ISD::BUILD_VECTOR:
4361     // NOTE: BUILD_VECTOR has implicit truncation of wider scalar elements -
4362     // this shouldn't affect the result.
4363     for (unsigned i = 0, e = Op.getNumOperands(); i < e; ++i) {
4364       if (!DemandedElts[i])
4365         continue;
4366       if (!isGuaranteedNotToBeUndefOrPoison(Op.getOperand(i), PoisonOnly,
4367                                             Depth + 1))
4368         return false;
4369     }
4370     return true;
4371 
4372   // TODO: Search for noundef attributes from library functions.
4373 
4374   // TODO: Pointers dereferenced by ISD::LOAD/STORE ops are noundef.
4375 
4376   default:
4377     // Allow the target to implement this method for its nodes.
4378     if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::INTRINSIC_WO_CHAIN ||
4379         Opcode == ISD::INTRINSIC_W_CHAIN || Opcode == ISD::INTRINSIC_VOID)
4380       return TLI->isGuaranteedNotToBeUndefOrPoisonForTargetNode(
4381           Op, DemandedElts, *this, PoisonOnly, Depth);
4382     break;
4383   }
4384 
4385   return false;
4386 }
4387 
4388 bool SelectionDAG::isBaseWithConstantOffset(SDValue Op) const {
4389   if ((Op.getOpcode() != ISD::ADD && Op.getOpcode() != ISD::OR) ||
4390       !isa<ConstantSDNode>(Op.getOperand(1)))
4391     return false;
4392 
4393   if (Op.getOpcode() == ISD::OR &&
4394       !MaskedValueIsZero(Op.getOperand(0), Op.getConstantOperandAPInt(1)))
4395     return false;
4396 
4397   return true;
4398 }
4399 
4400 bool SelectionDAG::isKnownNeverNaN(SDValue Op, bool SNaN, unsigned Depth) const {
4401   // If we're told that NaNs won't happen, assume they won't.
4402   if (getTarget().Options.NoNaNsFPMath || Op->getFlags().hasNoNaNs())
4403     return true;
4404 
4405   if (Depth >= MaxRecursionDepth)
4406     return false; // Limit search depth.
4407 
4408   // TODO: Handle vectors.
4409   // If the value is a constant, we can obviously see if it is a NaN or not.
4410   if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) {
4411     return !C->getValueAPF().isNaN() ||
4412            (SNaN && !C->getValueAPF().isSignaling());
4413   }
4414 
4415   unsigned Opcode = Op.getOpcode();
4416   switch (Opcode) {
4417   case ISD::FADD:
4418   case ISD::FSUB:
4419   case ISD::FMUL:
4420   case ISD::FDIV:
4421   case ISD::FREM:
4422   case ISD::FSIN:
4423   case ISD::FCOS: {
4424     if (SNaN)
4425       return true;
4426     // TODO: Need isKnownNeverInfinity
4427     return false;
4428   }
4429   case ISD::FCANONICALIZE:
4430   case ISD::FEXP:
4431   case ISD::FEXP2:
4432   case ISD::FTRUNC:
4433   case ISD::FFLOOR:
4434   case ISD::FCEIL:
4435   case ISD::FROUND:
4436   case ISD::FROUNDEVEN:
4437   case ISD::FRINT:
4438   case ISD::FNEARBYINT: {
4439     if (SNaN)
4440       return true;
4441     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
4442   }
4443   case ISD::FABS:
4444   case ISD::FNEG:
4445   case ISD::FCOPYSIGN: {
4446     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
4447   }
4448   case ISD::SELECT:
4449     return isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1) &&
4450            isKnownNeverNaN(Op.getOperand(2), SNaN, Depth + 1);
4451   case ISD::FP_EXTEND:
4452   case ISD::FP_ROUND: {
4453     if (SNaN)
4454       return true;
4455     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
4456   }
4457   case ISD::SINT_TO_FP:
4458   case ISD::UINT_TO_FP:
4459     return true;
4460   case ISD::FMA:
4461   case ISD::FMAD: {
4462     if (SNaN)
4463       return true;
4464     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) &&
4465            isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1) &&
4466            isKnownNeverNaN(Op.getOperand(2), SNaN, Depth + 1);
4467   }
4468   case ISD::FSQRT: // Need is known positive
4469   case ISD::FLOG:
4470   case ISD::FLOG2:
4471   case ISD::FLOG10:
4472   case ISD::FPOWI:
4473   case ISD::FPOW: {
4474     if (SNaN)
4475       return true;
4476     // TODO: Refine on operand
4477     return false;
4478   }
4479   case ISD::FMINNUM:
4480   case ISD::FMAXNUM: {
4481     // Only one needs to be known not-nan, since it will be returned if the
4482     // other ends up being one.
4483     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) ||
4484            isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1);
4485   }
4486   case ISD::FMINNUM_IEEE:
4487   case ISD::FMAXNUM_IEEE: {
4488     if (SNaN)
4489       return true;
4490     // This can return a NaN if either operand is an sNaN, or if both operands
4491     // are NaN.
4492     return (isKnownNeverNaN(Op.getOperand(0), false, Depth + 1) &&
4493             isKnownNeverSNaN(Op.getOperand(1), Depth + 1)) ||
4494            (isKnownNeverNaN(Op.getOperand(1), false, Depth + 1) &&
4495             isKnownNeverSNaN(Op.getOperand(0), Depth + 1));
4496   }
4497   case ISD::FMINIMUM:
4498   case ISD::FMAXIMUM: {
4499     // TODO: Does this quiet or return the origina NaN as-is?
4500     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) &&
4501            isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1);
4502   }
4503   case ISD::EXTRACT_VECTOR_ELT: {
4504     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
4505   }
4506   default:
4507     if (Opcode >= ISD::BUILTIN_OP_END ||
4508         Opcode == ISD::INTRINSIC_WO_CHAIN ||
4509         Opcode == ISD::INTRINSIC_W_CHAIN ||
4510         Opcode == ISD::INTRINSIC_VOID) {
4511       return TLI->isKnownNeverNaNForTargetNode(Op, *this, SNaN, Depth);
4512     }
4513 
4514     return false;
4515   }
4516 }
4517 
4518 bool SelectionDAG::isKnownNeverZeroFloat(SDValue Op) const {
4519   assert(Op.getValueType().isFloatingPoint() &&
4520          "Floating point type expected");
4521 
4522   // If the value is a constant, we can obviously see if it is a zero or not.
4523   // TODO: Add BuildVector support.
4524   if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op))
4525     return !C->isZero();
4526   return false;
4527 }
4528 
4529 bool SelectionDAG::isKnownNeverZero(SDValue Op) const {
4530   assert(!Op.getValueType().isFloatingPoint() &&
4531          "Floating point types unsupported - use isKnownNeverZeroFloat");
4532 
4533   // If the value is a constant, we can obviously see if it is a zero or not.
4534   if (ISD::matchUnaryPredicate(Op,
4535                                [](ConstantSDNode *C) { return !C->isZero(); }))
4536     return true;
4537 
4538   // TODO: Recognize more cases here.
4539   switch (Op.getOpcode()) {
4540   default: break;
4541   case ISD::OR:
4542     if (isKnownNeverZero(Op.getOperand(1)) ||
4543         isKnownNeverZero(Op.getOperand(0)))
4544       return true;
4545     break;
4546   }
4547 
4548   return false;
4549 }
4550 
4551 bool SelectionDAG::isEqualTo(SDValue A, SDValue B) const {
4552   // Check the obvious case.
4553   if (A == B) return true;
4554 
4555   // For for negative and positive zero.
4556   if (const ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A))
4557     if (const ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B))
4558       if (CA->isZero() && CB->isZero()) return true;
4559 
4560   // Otherwise they may not be equal.
4561   return false;
4562 }
4563 
4564 // FIXME: unify with llvm::haveNoCommonBitsSet.
4565 bool SelectionDAG::haveNoCommonBitsSet(SDValue A, SDValue B) const {
4566   assert(A.getValueType() == B.getValueType() &&
4567          "Values must have the same type");
4568   // Match masked merge pattern (X & ~M) op (Y & M)
4569   if (A->getOpcode() == ISD::AND && B->getOpcode() == ISD::AND) {
4570     auto MatchNoCommonBitsPattern = [&](SDValue NotM, SDValue And) {
4571       if (isBitwiseNot(NotM, true)) {
4572         SDValue NotOperand = NotM->getOperand(0);
4573         return NotOperand == And->getOperand(0) ||
4574                NotOperand == And->getOperand(1);
4575       }
4576       return false;
4577     };
4578     if (MatchNoCommonBitsPattern(A->getOperand(0), B) ||
4579         MatchNoCommonBitsPattern(A->getOperand(1), B) ||
4580         MatchNoCommonBitsPattern(B->getOperand(0), A) ||
4581         MatchNoCommonBitsPattern(B->getOperand(1), A))
4582       return true;
4583   }
4584   return KnownBits::haveNoCommonBitsSet(computeKnownBits(A),
4585                                         computeKnownBits(B));
4586 }
4587 
4588 static SDValue FoldSTEP_VECTOR(const SDLoc &DL, EVT VT, SDValue Step,
4589                                SelectionDAG &DAG) {
4590   if (cast<ConstantSDNode>(Step)->isZero())
4591     return DAG.getConstant(0, DL, VT);
4592 
4593   return SDValue();
4594 }
4595 
4596 static SDValue FoldBUILD_VECTOR(const SDLoc &DL, EVT VT,
4597                                 ArrayRef<SDValue> Ops,
4598                                 SelectionDAG &DAG) {
4599   int NumOps = Ops.size();
4600   assert(NumOps != 0 && "Can't build an empty vector!");
4601   assert(!VT.isScalableVector() &&
4602          "BUILD_VECTOR cannot be used with scalable types");
4603   assert(VT.getVectorNumElements() == (unsigned)NumOps &&
4604          "Incorrect element count in BUILD_VECTOR!");
4605 
4606   // BUILD_VECTOR of UNDEFs is UNDEF.
4607   if (llvm::all_of(Ops, [](SDValue Op) { return Op.isUndef(); }))
4608     return DAG.getUNDEF(VT);
4609 
4610   // BUILD_VECTOR of seq extract/insert from the same vector + type is Identity.
4611   SDValue IdentitySrc;
4612   bool IsIdentity = true;
4613   for (int i = 0; i != NumOps; ++i) {
4614     if (Ops[i].getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
4615         Ops[i].getOperand(0).getValueType() != VT ||
4616         (IdentitySrc && Ops[i].getOperand(0) != IdentitySrc) ||
4617         !isa<ConstantSDNode>(Ops[i].getOperand(1)) ||
4618         cast<ConstantSDNode>(Ops[i].getOperand(1))->getAPIntValue() != i) {
4619       IsIdentity = false;
4620       break;
4621     }
4622     IdentitySrc = Ops[i].getOperand(0);
4623   }
4624   if (IsIdentity)
4625     return IdentitySrc;
4626 
4627   return SDValue();
4628 }
4629 
4630 /// Try to simplify vector concatenation to an input value, undef, or build
4631 /// vector.
4632 static SDValue foldCONCAT_VECTORS(const SDLoc &DL, EVT VT,
4633                                   ArrayRef<SDValue> Ops,
4634                                   SelectionDAG &DAG) {
4635   assert(!Ops.empty() && "Can't concatenate an empty list of vectors!");
4636   assert(llvm::all_of(Ops,
4637                       [Ops](SDValue Op) {
4638                         return Ops[0].getValueType() == Op.getValueType();
4639                       }) &&
4640          "Concatenation of vectors with inconsistent value types!");
4641   assert((Ops[0].getValueType().getVectorElementCount() * Ops.size()) ==
4642              VT.getVectorElementCount() &&
4643          "Incorrect element count in vector concatenation!");
4644 
4645   if (Ops.size() == 1)
4646     return Ops[0];
4647 
4648   // Concat of UNDEFs is UNDEF.
4649   if (llvm::all_of(Ops, [](SDValue Op) { return Op.isUndef(); }))
4650     return DAG.getUNDEF(VT);
4651 
4652   // Scan the operands and look for extract operations from a single source
4653   // that correspond to insertion at the same location via this concatenation:
4654   // concat (extract X, 0*subvec_elts), (extract X, 1*subvec_elts), ...
4655   SDValue IdentitySrc;
4656   bool IsIdentity = true;
4657   for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
4658     SDValue Op = Ops[i];
4659     unsigned IdentityIndex = i * Op.getValueType().getVectorMinNumElements();
4660     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
4661         Op.getOperand(0).getValueType() != VT ||
4662         (IdentitySrc && Op.getOperand(0) != IdentitySrc) ||
4663         Op.getConstantOperandVal(1) != IdentityIndex) {
4664       IsIdentity = false;
4665       break;
4666     }
4667     assert((!IdentitySrc || IdentitySrc == Op.getOperand(0)) &&
4668            "Unexpected identity source vector for concat of extracts");
4669     IdentitySrc = Op.getOperand(0);
4670   }
4671   if (IsIdentity) {
4672     assert(IdentitySrc && "Failed to set source vector of extracts");
4673     return IdentitySrc;
4674   }
4675 
4676   // The code below this point is only designed to work for fixed width
4677   // vectors, so we bail out for now.
4678   if (VT.isScalableVector())
4679     return SDValue();
4680 
4681   // A CONCAT_VECTOR with all UNDEF/BUILD_VECTOR operands can be
4682   // simplified to one big BUILD_VECTOR.
4683   // FIXME: Add support for SCALAR_TO_VECTOR as well.
4684   EVT SVT = VT.getScalarType();
4685   SmallVector<SDValue, 16> Elts;
4686   for (SDValue Op : Ops) {
4687     EVT OpVT = Op.getValueType();
4688     if (Op.isUndef())
4689       Elts.append(OpVT.getVectorNumElements(), DAG.getUNDEF(SVT));
4690     else if (Op.getOpcode() == ISD::BUILD_VECTOR)
4691       Elts.append(Op->op_begin(), Op->op_end());
4692     else
4693       return SDValue();
4694   }
4695 
4696   // BUILD_VECTOR requires all inputs to be of the same type, find the
4697   // maximum type and extend them all.
4698   for (SDValue Op : Elts)
4699     SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
4700 
4701   if (SVT.bitsGT(VT.getScalarType())) {
4702     for (SDValue &Op : Elts) {
4703       if (Op.isUndef())
4704         Op = DAG.getUNDEF(SVT);
4705       else
4706         Op = DAG.getTargetLoweringInfo().isZExtFree(Op.getValueType(), SVT)
4707                  ? DAG.getZExtOrTrunc(Op, DL, SVT)
4708                  : DAG.getSExtOrTrunc(Op, DL, SVT);
4709     }
4710   }
4711 
4712   SDValue V = DAG.getBuildVector(VT, DL, Elts);
4713   NewSDValueDbgMsg(V, "New node fold concat vectors: ", &DAG);
4714   return V;
4715 }
4716 
4717 /// Gets or creates the specified node.
4718 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT) {
4719   FoldingSetNodeID ID;
4720   AddNodeIDNode(ID, Opcode, getVTList(VT), None);
4721   void *IP = nullptr;
4722   if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
4723     return SDValue(E, 0);
4724 
4725   auto *N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(),
4726                               getVTList(VT));
4727   CSEMap.InsertNode(N, IP);
4728 
4729   InsertNode(N);
4730   SDValue V = SDValue(N, 0);
4731   NewSDValueDbgMsg(V, "Creating new node: ", this);
4732   return V;
4733 }
4734 
4735 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
4736                               SDValue Operand) {
4737   SDNodeFlags Flags;
4738   if (Inserter)
4739     Flags = Inserter->getFlags();
4740   return getNode(Opcode, DL, VT, Operand, Flags);
4741 }
4742 
4743 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
4744                               SDValue Operand, const SDNodeFlags Flags) {
4745   assert(Operand.getOpcode() != ISD::DELETED_NODE &&
4746          "Operand is DELETED_NODE!");
4747   // Constant fold unary operations with an integer constant operand. Even
4748   // opaque constant will be folded, because the folding of unary operations
4749   // doesn't create new constants with different values. Nevertheless, the
4750   // opaque flag is preserved during folding to prevent future folding with
4751   // other constants.
4752   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Operand)) {
4753     const APInt &Val = C->getAPIntValue();
4754     switch (Opcode) {
4755     default: break;
4756     case ISD::SIGN_EXTEND:
4757       return getConstant(Val.sextOrTrunc(VT.getSizeInBits()), DL, VT,
4758                          C->isTargetOpcode(), C->isOpaque());
4759     case ISD::TRUNCATE:
4760       if (C->isOpaque())
4761         break;
4762       LLVM_FALLTHROUGH;
4763     case ISD::ZERO_EXTEND:
4764       return getConstant(Val.zextOrTrunc(VT.getSizeInBits()), DL, VT,
4765                          C->isTargetOpcode(), C->isOpaque());
4766     case ISD::ANY_EXTEND:
4767       // Some targets like RISCV prefer to sign extend some types.
4768       if (TLI->isSExtCheaperThanZExt(Operand.getValueType(), VT))
4769         return getConstant(Val.sextOrTrunc(VT.getSizeInBits()), DL, VT,
4770                            C->isTargetOpcode(), C->isOpaque());
4771       return getConstant(Val.zextOrTrunc(VT.getSizeInBits()), DL, VT,
4772                          C->isTargetOpcode(), C->isOpaque());
4773     case ISD::UINT_TO_FP:
4774     case ISD::SINT_TO_FP: {
4775       APFloat apf(EVTToAPFloatSemantics(VT),
4776                   APInt::getZero(VT.getSizeInBits()));
4777       (void)apf.convertFromAPInt(Val,
4778                                  Opcode==ISD::SINT_TO_FP,
4779                                  APFloat::rmNearestTiesToEven);
4780       return getConstantFP(apf, DL, VT);
4781     }
4782     case ISD::BITCAST:
4783       if (VT == MVT::f16 && C->getValueType(0) == MVT::i16)
4784         return getConstantFP(APFloat(APFloat::IEEEhalf(), Val), DL, VT);
4785       if (VT == MVT::f32 && C->getValueType(0) == MVT::i32)
4786         return getConstantFP(APFloat(APFloat::IEEEsingle(), Val), DL, VT);
4787       if (VT == MVT::f64 && C->getValueType(0) == MVT::i64)
4788         return getConstantFP(APFloat(APFloat::IEEEdouble(), Val), DL, VT);
4789       if (VT == MVT::f128 && C->getValueType(0) == MVT::i128)
4790         return getConstantFP(APFloat(APFloat::IEEEquad(), Val), DL, VT);
4791       break;
4792     case ISD::ABS:
4793       return getConstant(Val.abs(), DL, VT, C->isTargetOpcode(),
4794                          C->isOpaque());
4795     case ISD::BITREVERSE:
4796       return getConstant(Val.reverseBits(), DL, VT, C->isTargetOpcode(),
4797                          C->isOpaque());
4798     case ISD::BSWAP:
4799       return getConstant(Val.byteSwap(), DL, VT, C->isTargetOpcode(),
4800                          C->isOpaque());
4801     case ISD::CTPOP:
4802       return getConstant(Val.countPopulation(), DL, VT, C->isTargetOpcode(),
4803                          C->isOpaque());
4804     case ISD::CTLZ:
4805     case ISD::CTLZ_ZERO_UNDEF:
4806       return getConstant(Val.countLeadingZeros(), DL, VT, C->isTargetOpcode(),
4807                          C->isOpaque());
4808     case ISD::CTTZ:
4809     case ISD::CTTZ_ZERO_UNDEF:
4810       return getConstant(Val.countTrailingZeros(), DL, VT, C->isTargetOpcode(),
4811                          C->isOpaque());
4812     case ISD::FP16_TO_FP: {
4813       bool Ignored;
4814       APFloat FPV(APFloat::IEEEhalf(),
4815                   (Val.getBitWidth() == 16) ? Val : Val.trunc(16));
4816 
4817       // This can return overflow, underflow, or inexact; we don't care.
4818       // FIXME need to be more flexible about rounding mode.
4819       (void)FPV.convert(EVTToAPFloatSemantics(VT),
4820                         APFloat::rmNearestTiesToEven, &Ignored);
4821       return getConstantFP(FPV, DL, VT);
4822     }
4823     case ISD::STEP_VECTOR: {
4824       if (SDValue V = FoldSTEP_VECTOR(DL, VT, Operand, *this))
4825         return V;
4826       break;
4827     }
4828     }
4829   }
4830 
4831   // Constant fold unary operations with a floating point constant operand.
4832   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Operand)) {
4833     APFloat V = C->getValueAPF();    // make copy
4834     switch (Opcode) {
4835     case ISD::FNEG:
4836       V.changeSign();
4837       return getConstantFP(V, DL, VT);
4838     case ISD::FABS:
4839       V.clearSign();
4840       return getConstantFP(V, DL, VT);
4841     case ISD::FCEIL: {
4842       APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardPositive);
4843       if (fs == APFloat::opOK || fs == APFloat::opInexact)
4844         return getConstantFP(V, DL, VT);
4845       break;
4846     }
4847     case ISD::FTRUNC: {
4848       APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardZero);
4849       if (fs == APFloat::opOK || fs == APFloat::opInexact)
4850         return getConstantFP(V, DL, VT);
4851       break;
4852     }
4853     case ISD::FFLOOR: {
4854       APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardNegative);
4855       if (fs == APFloat::opOK || fs == APFloat::opInexact)
4856         return getConstantFP(V, DL, VT);
4857       break;
4858     }
4859     case ISD::FP_EXTEND: {
4860       bool ignored;
4861       // This can return overflow, underflow, or inexact; we don't care.
4862       // FIXME need to be more flexible about rounding mode.
4863       (void)V.convert(EVTToAPFloatSemantics(VT),
4864                       APFloat::rmNearestTiesToEven, &ignored);
4865       return getConstantFP(V, DL, VT);
4866     }
4867     case ISD::FP_TO_SINT:
4868     case ISD::FP_TO_UINT: {
4869       bool ignored;
4870       APSInt IntVal(VT.getSizeInBits(), Opcode == ISD::FP_TO_UINT);
4871       // FIXME need to be more flexible about rounding mode.
4872       APFloat::opStatus s =
4873           V.convertToInteger(IntVal, APFloat::rmTowardZero, &ignored);
4874       if (s == APFloat::opInvalidOp) // inexact is OK, in fact usual
4875         break;
4876       return getConstant(IntVal, DL, VT);
4877     }
4878     case ISD::BITCAST:
4879       if (VT == MVT::i16 && C->getValueType(0) == MVT::f16)
4880         return getConstant((uint16_t)V.bitcastToAPInt().getZExtValue(), DL, VT);
4881       if (VT == MVT::i16 && C->getValueType(0) == MVT::bf16)
4882         return getConstant((uint16_t)V.bitcastToAPInt().getZExtValue(), DL, VT);
4883       if (VT == MVT::i32 && C->getValueType(0) == MVT::f32)
4884         return getConstant((uint32_t)V.bitcastToAPInt().getZExtValue(), DL, VT);
4885       if (VT == MVT::i64 && C->getValueType(0) == MVT::f64)
4886         return getConstant(V.bitcastToAPInt().getZExtValue(), DL, VT);
4887       break;
4888     case ISD::FP_TO_FP16: {
4889       bool Ignored;
4890       // This can return overflow, underflow, or inexact; we don't care.
4891       // FIXME need to be more flexible about rounding mode.
4892       (void)V.convert(APFloat::IEEEhalf(),
4893                       APFloat::rmNearestTiesToEven, &Ignored);
4894       return getConstant(V.bitcastToAPInt().getZExtValue(), DL, VT);
4895     }
4896     }
4897   }
4898 
4899   // Constant fold unary operations with a vector integer or float operand.
4900   switch (Opcode) {
4901   default:
4902     // FIXME: Entirely reasonable to perform folding of other unary
4903     // operations here as the need arises.
4904     break;
4905   case ISD::FNEG:
4906   case ISD::FABS:
4907   case ISD::FCEIL:
4908   case ISD::FTRUNC:
4909   case ISD::FFLOOR:
4910   case ISD::FP_EXTEND:
4911   case ISD::FP_TO_SINT:
4912   case ISD::FP_TO_UINT:
4913   case ISD::TRUNCATE:
4914   case ISD::ANY_EXTEND:
4915   case ISD::ZERO_EXTEND:
4916   case ISD::SIGN_EXTEND:
4917   case ISD::UINT_TO_FP:
4918   case ISD::SINT_TO_FP:
4919   case ISD::ABS:
4920   case ISD::BITREVERSE:
4921   case ISD::BSWAP:
4922   case ISD::CTLZ:
4923   case ISD::CTLZ_ZERO_UNDEF:
4924   case ISD::CTTZ:
4925   case ISD::CTTZ_ZERO_UNDEF:
4926   case ISD::CTPOP: {
4927     SDValue Ops = {Operand};
4928     if (SDValue Fold = FoldConstantArithmetic(Opcode, DL, VT, Ops))
4929       return Fold;
4930   }
4931   }
4932 
4933   unsigned OpOpcode = Operand.getNode()->getOpcode();
4934   switch (Opcode) {
4935   case ISD::STEP_VECTOR:
4936     assert(VT.isScalableVector() &&
4937            "STEP_VECTOR can only be used with scalable types");
4938     assert(OpOpcode == ISD::TargetConstant &&
4939            VT.getVectorElementType() == Operand.getValueType() &&
4940            "Unexpected step operand");
4941     break;
4942   case ISD::FREEZE:
4943     assert(VT == Operand.getValueType() && "Unexpected VT!");
4944     break;
4945   case ISD::TokenFactor:
4946   case ISD::MERGE_VALUES:
4947   case ISD::CONCAT_VECTORS:
4948     return Operand;         // Factor, merge or concat of one node?  No need.
4949   case ISD::BUILD_VECTOR: {
4950     // Attempt to simplify BUILD_VECTOR.
4951     SDValue Ops[] = {Operand};
4952     if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
4953       return V;
4954     break;
4955   }
4956   case ISD::FP_ROUND: llvm_unreachable("Invalid method to make FP_ROUND node");
4957   case ISD::FP_EXTEND:
4958     assert(VT.isFloatingPoint() &&
4959            Operand.getValueType().isFloatingPoint() && "Invalid FP cast!");
4960     if (Operand.getValueType() == VT) return Operand;  // noop conversion.
4961     assert((!VT.isVector() ||
4962             VT.getVectorElementCount() ==
4963             Operand.getValueType().getVectorElementCount()) &&
4964            "Vector element count mismatch!");
4965     assert(Operand.getValueType().bitsLT(VT) &&
4966            "Invalid fpext node, dst < src!");
4967     if (Operand.isUndef())
4968       return getUNDEF(VT);
4969     break;
4970   case ISD::FP_TO_SINT:
4971   case ISD::FP_TO_UINT:
4972     if (Operand.isUndef())
4973       return getUNDEF(VT);
4974     break;
4975   case ISD::SINT_TO_FP:
4976   case ISD::UINT_TO_FP:
4977     // [us]itofp(undef) = 0, because the result value is bounded.
4978     if (Operand.isUndef())
4979       return getConstantFP(0.0, DL, VT);
4980     break;
4981   case ISD::SIGN_EXTEND:
4982     assert(VT.isInteger() && Operand.getValueType().isInteger() &&
4983            "Invalid SIGN_EXTEND!");
4984     assert(VT.isVector() == Operand.getValueType().isVector() &&
4985            "SIGN_EXTEND result type type should be vector iff the operand "
4986            "type is vector!");
4987     if (Operand.getValueType() == VT) return Operand;   // noop extension
4988     assert((!VT.isVector() ||
4989             VT.getVectorElementCount() ==
4990                 Operand.getValueType().getVectorElementCount()) &&
4991            "Vector element count mismatch!");
4992     assert(Operand.getValueType().bitsLT(VT) &&
4993            "Invalid sext node, dst < src!");
4994     if (OpOpcode == ISD::SIGN_EXTEND || OpOpcode == ISD::ZERO_EXTEND)
4995       return getNode(OpOpcode, DL, VT, Operand.getOperand(0));
4996     if (OpOpcode == ISD::UNDEF)
4997       // sext(undef) = 0, because the top bits will all be the same.
4998       return getConstant(0, DL, VT);
4999     break;
5000   case ISD::ZERO_EXTEND:
5001     assert(VT.isInteger() && Operand.getValueType().isInteger() &&
5002            "Invalid ZERO_EXTEND!");
5003     assert(VT.isVector() == Operand.getValueType().isVector() &&
5004            "ZERO_EXTEND result type type should be vector iff the operand "
5005            "type is vector!");
5006     if (Operand.getValueType() == VT) return Operand;   // noop extension
5007     assert((!VT.isVector() ||
5008             VT.getVectorElementCount() ==
5009                 Operand.getValueType().getVectorElementCount()) &&
5010            "Vector element count mismatch!");
5011     assert(Operand.getValueType().bitsLT(VT) &&
5012            "Invalid zext node, dst < src!");
5013     if (OpOpcode == ISD::ZERO_EXTEND)   // (zext (zext x)) -> (zext x)
5014       return getNode(ISD::ZERO_EXTEND, DL, VT, Operand.getOperand(0));
5015     if (OpOpcode == ISD::UNDEF)
5016       // zext(undef) = 0, because the top bits will be zero.
5017       return getConstant(0, DL, VT);
5018     break;
5019   case ISD::ANY_EXTEND:
5020     assert(VT.isInteger() && Operand.getValueType().isInteger() &&
5021            "Invalid ANY_EXTEND!");
5022     assert(VT.isVector() == Operand.getValueType().isVector() &&
5023            "ANY_EXTEND result type type should be vector iff the operand "
5024            "type is vector!");
5025     if (Operand.getValueType() == VT) return Operand;   // noop extension
5026     assert((!VT.isVector() ||
5027             VT.getVectorElementCount() ==
5028                 Operand.getValueType().getVectorElementCount()) &&
5029            "Vector element count mismatch!");
5030     assert(Operand.getValueType().bitsLT(VT) &&
5031            "Invalid anyext node, dst < src!");
5032 
5033     if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
5034         OpOpcode == ISD::ANY_EXTEND)
5035       // (ext (zext x)) -> (zext x)  and  (ext (sext x)) -> (sext x)
5036       return getNode(OpOpcode, DL, VT, Operand.getOperand(0));
5037     if (OpOpcode == ISD::UNDEF)
5038       return getUNDEF(VT);
5039 
5040     // (ext (trunc x)) -> x
5041     if (OpOpcode == ISD::TRUNCATE) {
5042       SDValue OpOp = Operand.getOperand(0);
5043       if (OpOp.getValueType() == VT) {
5044         transferDbgValues(Operand, OpOp);
5045         return OpOp;
5046       }
5047     }
5048     break;
5049   case ISD::TRUNCATE:
5050     assert(VT.isInteger() && Operand.getValueType().isInteger() &&
5051            "Invalid TRUNCATE!");
5052     assert(VT.isVector() == Operand.getValueType().isVector() &&
5053            "TRUNCATE result type type should be vector iff the operand "
5054            "type is vector!");
5055     if (Operand.getValueType() == VT) return Operand;   // noop truncate
5056     assert((!VT.isVector() ||
5057             VT.getVectorElementCount() ==
5058                 Operand.getValueType().getVectorElementCount()) &&
5059            "Vector element count mismatch!");
5060     assert(Operand.getValueType().bitsGT(VT) &&
5061            "Invalid truncate node, src < dst!");
5062     if (OpOpcode == ISD::TRUNCATE)
5063       return getNode(ISD::TRUNCATE, DL, VT, Operand.getOperand(0));
5064     if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
5065         OpOpcode == ISD::ANY_EXTEND) {
5066       // If the source is smaller than the dest, we still need an extend.
5067       if (Operand.getOperand(0).getValueType().getScalarType()
5068             .bitsLT(VT.getScalarType()))
5069         return getNode(OpOpcode, DL, VT, Operand.getOperand(0));
5070       if (Operand.getOperand(0).getValueType().bitsGT(VT))
5071         return getNode(ISD::TRUNCATE, DL, VT, Operand.getOperand(0));
5072       return Operand.getOperand(0);
5073     }
5074     if (OpOpcode == ISD::UNDEF)
5075       return getUNDEF(VT);
5076     if (OpOpcode == ISD::VSCALE && !NewNodesMustHaveLegalTypes)
5077       return getVScale(DL, VT, Operand.getConstantOperandAPInt(0));
5078     break;
5079   case ISD::ANY_EXTEND_VECTOR_INREG:
5080   case ISD::ZERO_EXTEND_VECTOR_INREG:
5081   case ISD::SIGN_EXTEND_VECTOR_INREG:
5082     assert(VT.isVector() && "This DAG node is restricted to vector types.");
5083     assert(Operand.getValueType().bitsLE(VT) &&
5084            "The input must be the same size or smaller than the result.");
5085     assert(VT.getVectorMinNumElements() <
5086                Operand.getValueType().getVectorMinNumElements() &&
5087            "The destination vector type must have fewer lanes than the input.");
5088     break;
5089   case ISD::ABS:
5090     assert(VT.isInteger() && VT == Operand.getValueType() &&
5091            "Invalid ABS!");
5092     if (OpOpcode == ISD::UNDEF)
5093       return getUNDEF(VT);
5094     break;
5095   case ISD::BSWAP:
5096     assert(VT.isInteger() && VT == Operand.getValueType() &&
5097            "Invalid BSWAP!");
5098     assert((VT.getScalarSizeInBits() % 16 == 0) &&
5099            "BSWAP types must be a multiple of 16 bits!");
5100     if (OpOpcode == ISD::UNDEF)
5101       return getUNDEF(VT);
5102     break;
5103   case ISD::BITREVERSE:
5104     assert(VT.isInteger() && VT == Operand.getValueType() &&
5105            "Invalid BITREVERSE!");
5106     if (OpOpcode == ISD::UNDEF)
5107       return getUNDEF(VT);
5108     break;
5109   case ISD::BITCAST:
5110     assert(VT.getSizeInBits() == Operand.getValueSizeInBits() &&
5111            "Cannot BITCAST between types of different sizes!");
5112     if (VT == Operand.getValueType()) return Operand;  // noop conversion.
5113     if (OpOpcode == ISD::BITCAST)  // bitconv(bitconv(x)) -> bitconv(x)
5114       return getNode(ISD::BITCAST, DL, VT, Operand.getOperand(0));
5115     if (OpOpcode == ISD::UNDEF)
5116       return getUNDEF(VT);
5117     break;
5118   case ISD::SCALAR_TO_VECTOR:
5119     assert(VT.isVector() && !Operand.getValueType().isVector() &&
5120            (VT.getVectorElementType() == Operand.getValueType() ||
5121             (VT.getVectorElementType().isInteger() &&
5122              Operand.getValueType().isInteger() &&
5123              VT.getVectorElementType().bitsLE(Operand.getValueType()))) &&
5124            "Illegal SCALAR_TO_VECTOR node!");
5125     if (OpOpcode == ISD::UNDEF)
5126       return getUNDEF(VT);
5127     // scalar_to_vector(extract_vector_elt V, 0) -> V, top bits are undefined.
5128     if (OpOpcode == ISD::EXTRACT_VECTOR_ELT &&
5129         isa<ConstantSDNode>(Operand.getOperand(1)) &&
5130         Operand.getConstantOperandVal(1) == 0 &&
5131         Operand.getOperand(0).getValueType() == VT)
5132       return Operand.getOperand(0);
5133     break;
5134   case ISD::FNEG:
5135     // Negation of an unknown bag of bits is still completely undefined.
5136     if (OpOpcode == ISD::UNDEF)
5137       return getUNDEF(VT);
5138 
5139     if (OpOpcode == ISD::FNEG)  // --X -> X
5140       return Operand.getOperand(0);
5141     break;
5142   case ISD::FABS:
5143     if (OpOpcode == ISD::FNEG)  // abs(-X) -> abs(X)
5144       return getNode(ISD::FABS, DL, VT, Operand.getOperand(0));
5145     break;
5146   case ISD::VSCALE:
5147     assert(VT == Operand.getValueType() && "Unexpected VT!");
5148     break;
5149   case ISD::CTPOP:
5150     if (Operand.getValueType().getScalarType() == MVT::i1)
5151       return Operand;
5152     break;
5153   case ISD::CTLZ:
5154   case ISD::CTTZ:
5155     if (Operand.getValueType().getScalarType() == MVT::i1)
5156       return getNOT(DL, Operand, Operand.getValueType());
5157     break;
5158   case ISD::VECREDUCE_SMIN:
5159   case ISD::VECREDUCE_UMAX:
5160     if (Operand.getValueType().getScalarType() == MVT::i1)
5161       return getNode(ISD::VECREDUCE_OR, DL, VT, Operand);
5162     break;
5163   case ISD::VECREDUCE_SMAX:
5164   case ISD::VECREDUCE_UMIN:
5165     if (Operand.getValueType().getScalarType() == MVT::i1)
5166       return getNode(ISD::VECREDUCE_AND, DL, VT, Operand);
5167     break;
5168   }
5169 
5170   SDNode *N;
5171   SDVTList VTs = getVTList(VT);
5172   SDValue Ops[] = {Operand};
5173   if (VT != MVT::Glue) { // Don't CSE flag producing nodes
5174     FoldingSetNodeID ID;
5175     AddNodeIDNode(ID, Opcode, VTs, Ops);
5176     void *IP = nullptr;
5177     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
5178       E->intersectFlagsWith(Flags);
5179       return SDValue(E, 0);
5180     }
5181 
5182     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
5183     N->setFlags(Flags);
5184     createOperands(N, Ops);
5185     CSEMap.InsertNode(N, IP);
5186   } else {
5187     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
5188     createOperands(N, Ops);
5189   }
5190 
5191   InsertNode(N);
5192   SDValue V = SDValue(N, 0);
5193   NewSDValueDbgMsg(V, "Creating new node: ", this);
5194   return V;
5195 }
5196 
5197 static llvm::Optional<APInt> FoldValue(unsigned Opcode, const APInt &C1,
5198                                        const APInt &C2) {
5199   switch (Opcode) {
5200   case ISD::ADD:  return C1 + C2;
5201   case ISD::SUB:  return C1 - C2;
5202   case ISD::MUL:  return C1 * C2;
5203   case ISD::AND:  return C1 & C2;
5204   case ISD::OR:   return C1 | C2;
5205   case ISD::XOR:  return C1 ^ C2;
5206   case ISD::SHL:  return C1 << C2;
5207   case ISD::SRL:  return C1.lshr(C2);
5208   case ISD::SRA:  return C1.ashr(C2);
5209   case ISD::ROTL: return C1.rotl(C2);
5210   case ISD::ROTR: return C1.rotr(C2);
5211   case ISD::SMIN: return C1.sle(C2) ? C1 : C2;
5212   case ISD::SMAX: return C1.sge(C2) ? C1 : C2;
5213   case ISD::UMIN: return C1.ule(C2) ? C1 : C2;
5214   case ISD::UMAX: return C1.uge(C2) ? C1 : C2;
5215   case ISD::SADDSAT: return C1.sadd_sat(C2);
5216   case ISD::UADDSAT: return C1.uadd_sat(C2);
5217   case ISD::SSUBSAT: return C1.ssub_sat(C2);
5218   case ISD::USUBSAT: return C1.usub_sat(C2);
5219   case ISD::UDIV:
5220     if (!C2.getBoolValue())
5221       break;
5222     return C1.udiv(C2);
5223   case ISD::UREM:
5224     if (!C2.getBoolValue())
5225       break;
5226     return C1.urem(C2);
5227   case ISD::SDIV:
5228     if (!C2.getBoolValue())
5229       break;
5230     return C1.sdiv(C2);
5231   case ISD::SREM:
5232     if (!C2.getBoolValue())
5233       break;
5234     return C1.srem(C2);
5235   case ISD::MULHS: {
5236     unsigned FullWidth = C1.getBitWidth() * 2;
5237     APInt C1Ext = C1.sext(FullWidth);
5238     APInt C2Ext = C2.sext(FullWidth);
5239     return (C1Ext * C2Ext).extractBits(C1.getBitWidth(), C1.getBitWidth());
5240   }
5241   case ISD::MULHU: {
5242     unsigned FullWidth = C1.getBitWidth() * 2;
5243     APInt C1Ext = C1.zext(FullWidth);
5244     APInt C2Ext = C2.zext(FullWidth);
5245     return (C1Ext * C2Ext).extractBits(C1.getBitWidth(), C1.getBitWidth());
5246   }
5247   }
5248   return llvm::None;
5249 }
5250 
5251 SDValue SelectionDAG::FoldSymbolOffset(unsigned Opcode, EVT VT,
5252                                        const GlobalAddressSDNode *GA,
5253                                        const SDNode *N2) {
5254   if (GA->getOpcode() != ISD::GlobalAddress)
5255     return SDValue();
5256   if (!TLI->isOffsetFoldingLegal(GA))
5257     return SDValue();
5258   auto *C2 = dyn_cast<ConstantSDNode>(N2);
5259   if (!C2)
5260     return SDValue();
5261   int64_t Offset = C2->getSExtValue();
5262   switch (Opcode) {
5263   case ISD::ADD: break;
5264   case ISD::SUB: Offset = -uint64_t(Offset); break;
5265   default: return SDValue();
5266   }
5267   return getGlobalAddress(GA->getGlobal(), SDLoc(C2), VT,
5268                           GA->getOffset() + uint64_t(Offset));
5269 }
5270 
5271 bool SelectionDAG::isUndef(unsigned Opcode, ArrayRef<SDValue> Ops) {
5272   switch (Opcode) {
5273   case ISD::SDIV:
5274   case ISD::UDIV:
5275   case ISD::SREM:
5276   case ISD::UREM: {
5277     // If a divisor is zero/undef or any element of a divisor vector is
5278     // zero/undef, the whole op is undef.
5279     assert(Ops.size() == 2 && "Div/rem should have 2 operands");
5280     SDValue Divisor = Ops[1];
5281     if (Divisor.isUndef() || isNullConstant(Divisor))
5282       return true;
5283 
5284     return ISD::isBuildVectorOfConstantSDNodes(Divisor.getNode()) &&
5285            llvm::any_of(Divisor->op_values(),
5286                         [](SDValue V) { return V.isUndef() ||
5287                                         isNullConstant(V); });
5288     // TODO: Handle signed overflow.
5289   }
5290   // TODO: Handle oversized shifts.
5291   default:
5292     return false;
5293   }
5294 }
5295 
5296 SDValue SelectionDAG::FoldConstantArithmetic(unsigned Opcode, const SDLoc &DL,
5297                                              EVT VT, ArrayRef<SDValue> Ops) {
5298   // If the opcode is a target-specific ISD node, there's nothing we can
5299   // do here and the operand rules may not line up with the below, so
5300   // bail early.
5301   // We can't create a scalar CONCAT_VECTORS so skip it. It will break
5302   // for concats involving SPLAT_VECTOR. Concats of BUILD_VECTORS are handled by
5303   // foldCONCAT_VECTORS in getNode before this is called.
5304   if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::CONCAT_VECTORS)
5305     return SDValue();
5306 
5307   unsigned NumOps = Ops.size();
5308   if (NumOps == 0)
5309     return SDValue();
5310 
5311   if (isUndef(Opcode, Ops))
5312     return getUNDEF(VT);
5313 
5314   // Handle binops special cases.
5315   if (NumOps == 2) {
5316     if (SDValue CFP = foldConstantFPMath(Opcode, DL, VT, Ops[0], Ops[1]))
5317       return CFP;
5318 
5319     if (auto *C1 = dyn_cast<ConstantSDNode>(Ops[0])) {
5320       if (auto *C2 = dyn_cast<ConstantSDNode>(Ops[1])) {
5321         if (C1->isOpaque() || C2->isOpaque())
5322           return SDValue();
5323 
5324         Optional<APInt> FoldAttempt =
5325             FoldValue(Opcode, C1->getAPIntValue(), C2->getAPIntValue());
5326         if (!FoldAttempt)
5327           return SDValue();
5328 
5329         SDValue Folded = getConstant(FoldAttempt.getValue(), DL, VT);
5330         assert((!Folded || !VT.isVector()) &&
5331                "Can't fold vectors ops with scalar operands");
5332         return Folded;
5333       }
5334     }
5335 
5336     // fold (add Sym, c) -> Sym+c
5337     if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Ops[0]))
5338       return FoldSymbolOffset(Opcode, VT, GA, Ops[1].getNode());
5339     if (TLI->isCommutativeBinOp(Opcode))
5340       if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Ops[1]))
5341         return FoldSymbolOffset(Opcode, VT, GA, Ops[0].getNode());
5342   }
5343 
5344   // This is for vector folding only from here on.
5345   if (!VT.isVector())
5346     return SDValue();
5347 
5348   ElementCount NumElts = VT.getVectorElementCount();
5349 
5350   // See if we can fold through bitcasted integer ops.
5351   // TODO: Can we handle undef elements?
5352   if (NumOps == 2 && VT.isFixedLengthVector() && VT.isInteger() &&
5353       Ops[0].getValueType() == VT && Ops[1].getValueType() == VT &&
5354       Ops[0].getOpcode() == ISD::BITCAST &&
5355       Ops[1].getOpcode() == ISD::BITCAST) {
5356     SDValue N1 = peekThroughBitcasts(Ops[0]);
5357     SDValue N2 = peekThroughBitcasts(Ops[1]);
5358     auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
5359     auto *BV2 = dyn_cast<BuildVectorSDNode>(N2);
5360     EVT BVVT = N1.getValueType();
5361     if (BV1 && BV2 && BVVT.isInteger() && BVVT == N2.getValueType()) {
5362       bool IsLE = getDataLayout().isLittleEndian();
5363       unsigned EltBits = VT.getScalarSizeInBits();
5364       SmallVector<APInt> RawBits1, RawBits2;
5365       BitVector UndefElts1, UndefElts2;
5366       if (BV1->getConstantRawBits(IsLE, EltBits, RawBits1, UndefElts1) &&
5367           BV2->getConstantRawBits(IsLE, EltBits, RawBits2, UndefElts2) &&
5368           UndefElts1.none() && UndefElts2.none()) {
5369         SmallVector<APInt> RawBits;
5370         for (unsigned I = 0, E = NumElts.getFixedValue(); I != E; ++I) {
5371           Optional<APInt> Fold = FoldValue(Opcode, RawBits1[I], RawBits2[I]);
5372           if (!Fold)
5373             break;
5374           RawBits.push_back(Fold.getValue());
5375         }
5376         if (RawBits.size() == NumElts.getFixedValue()) {
5377           // We have constant folded, but we need to cast this again back to
5378           // the original (possibly legalized) type.
5379           SmallVector<APInt> DstBits;
5380           BitVector DstUndefs;
5381           BuildVectorSDNode::recastRawBits(IsLE, BVVT.getScalarSizeInBits(),
5382                                            DstBits, RawBits, DstUndefs,
5383                                            BitVector(RawBits.size(), false));
5384           EVT BVEltVT = BV1->getOperand(0).getValueType();
5385           unsigned BVEltBits = BVEltVT.getSizeInBits();
5386           SmallVector<SDValue> Ops(DstBits.size(), getUNDEF(BVEltVT));
5387           for (unsigned I = 0, E = DstBits.size(); I != E; ++I) {
5388             if (DstUndefs[I])
5389               continue;
5390             Ops[I] = getConstant(DstBits[I].sextOrSelf(BVEltBits), DL, BVEltVT);
5391           }
5392           return getBitcast(VT, getBuildVector(BVVT, DL, Ops));
5393         }
5394       }
5395     }
5396   }
5397 
5398   auto IsScalarOrSameVectorSize = [NumElts](const SDValue &Op) {
5399     return !Op.getValueType().isVector() ||
5400            Op.getValueType().getVectorElementCount() == NumElts;
5401   };
5402 
5403   auto IsBuildVectorSplatVectorOrUndef = [](const SDValue &Op) {
5404     return Op.isUndef() || Op.getOpcode() == ISD::CONDCODE ||
5405            Op.getOpcode() == ISD::BUILD_VECTOR ||
5406            Op.getOpcode() == ISD::SPLAT_VECTOR;
5407   };
5408 
5409   // All operands must be vector types with the same number of elements as
5410   // the result type and must be either UNDEF or a build/splat vector
5411   // or UNDEF scalars.
5412   if (!llvm::all_of(Ops, IsBuildVectorSplatVectorOrUndef) ||
5413       !llvm::all_of(Ops, IsScalarOrSameVectorSize))
5414     return SDValue();
5415 
5416   // If we are comparing vectors, then the result needs to be a i1 boolean
5417   // that is then sign-extended back to the legal result type.
5418   EVT SVT = (Opcode == ISD::SETCC ? MVT::i1 : VT.getScalarType());
5419 
5420   // Find legal integer scalar type for constant promotion and
5421   // ensure that its scalar size is at least as large as source.
5422   EVT LegalSVT = VT.getScalarType();
5423   if (NewNodesMustHaveLegalTypes && LegalSVT.isInteger()) {
5424     LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT);
5425     if (LegalSVT.bitsLT(VT.getScalarType()))
5426       return SDValue();
5427   }
5428 
5429   // For scalable vector types we know we're dealing with SPLAT_VECTORs. We
5430   // only have one operand to check. For fixed-length vector types we may have
5431   // a combination of BUILD_VECTOR and SPLAT_VECTOR.
5432   unsigned NumVectorElts = NumElts.isScalable() ? 1 : NumElts.getFixedValue();
5433 
5434   // Constant fold each scalar lane separately.
5435   SmallVector<SDValue, 4> ScalarResults;
5436   for (unsigned I = 0; I != NumVectorElts; I++) {
5437     SmallVector<SDValue, 4> ScalarOps;
5438     for (SDValue Op : Ops) {
5439       EVT InSVT = Op.getValueType().getScalarType();
5440       if (Op.getOpcode() != ISD::BUILD_VECTOR &&
5441           Op.getOpcode() != ISD::SPLAT_VECTOR) {
5442         if (Op.isUndef())
5443           ScalarOps.push_back(getUNDEF(InSVT));
5444         else
5445           ScalarOps.push_back(Op);
5446         continue;
5447       }
5448 
5449       SDValue ScalarOp =
5450           Op.getOperand(Op.getOpcode() == ISD::SPLAT_VECTOR ? 0 : I);
5451       EVT ScalarVT = ScalarOp.getValueType();
5452 
5453       // Build vector (integer) scalar operands may need implicit
5454       // truncation - do this before constant folding.
5455       if (ScalarVT.isInteger() && ScalarVT.bitsGT(InSVT))
5456         ScalarOp = getNode(ISD::TRUNCATE, DL, InSVT, ScalarOp);
5457 
5458       ScalarOps.push_back(ScalarOp);
5459     }
5460 
5461     // Constant fold the scalar operands.
5462     SDValue ScalarResult = getNode(Opcode, DL, SVT, ScalarOps);
5463 
5464     // Legalize the (integer) scalar constant if necessary.
5465     if (LegalSVT != SVT)
5466       ScalarResult = getNode(ISD::SIGN_EXTEND, DL, LegalSVT, ScalarResult);
5467 
5468     // Scalar folding only succeeded if the result is a constant or UNDEF.
5469     if (!ScalarResult.isUndef() && ScalarResult.getOpcode() != ISD::Constant &&
5470         ScalarResult.getOpcode() != ISD::ConstantFP)
5471       return SDValue();
5472     ScalarResults.push_back(ScalarResult);
5473   }
5474 
5475   SDValue V = NumElts.isScalable() ? getSplatVector(VT, DL, ScalarResults[0])
5476                                    : getBuildVector(VT, DL, ScalarResults);
5477   NewSDValueDbgMsg(V, "New node fold constant vector: ", this);
5478   return V;
5479 }
5480 
5481 SDValue SelectionDAG::foldConstantFPMath(unsigned Opcode, const SDLoc &DL,
5482                                          EVT VT, SDValue N1, SDValue N2) {
5483   // TODO: We don't do any constant folding for strict FP opcodes here, but we
5484   //       should. That will require dealing with a potentially non-default
5485   //       rounding mode, checking the "opStatus" return value from the APFloat
5486   //       math calculations, and possibly other variations.
5487   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1, /*AllowUndefs*/ false);
5488   ConstantFPSDNode *N2CFP = isConstOrConstSplatFP(N2, /*AllowUndefs*/ false);
5489   if (N1CFP && N2CFP) {
5490     APFloat C1 = N1CFP->getValueAPF(); // make copy
5491     const APFloat &C2 = N2CFP->getValueAPF();
5492     switch (Opcode) {
5493     case ISD::FADD:
5494       C1.add(C2, APFloat::rmNearestTiesToEven);
5495       return getConstantFP(C1, DL, VT);
5496     case ISD::FSUB:
5497       C1.subtract(C2, APFloat::rmNearestTiesToEven);
5498       return getConstantFP(C1, DL, VT);
5499     case ISD::FMUL:
5500       C1.multiply(C2, APFloat::rmNearestTiesToEven);
5501       return getConstantFP(C1, DL, VT);
5502     case ISD::FDIV:
5503       C1.divide(C2, APFloat::rmNearestTiesToEven);
5504       return getConstantFP(C1, DL, VT);
5505     case ISD::FREM:
5506       C1.mod(C2);
5507       return getConstantFP(C1, DL, VT);
5508     case ISD::FCOPYSIGN:
5509       C1.copySign(C2);
5510       return getConstantFP(C1, DL, VT);
5511     case ISD::FMINNUM:
5512       return getConstantFP(minnum(C1, C2), DL, VT);
5513     case ISD::FMAXNUM:
5514       return getConstantFP(maxnum(C1, C2), DL, VT);
5515     case ISD::FMINIMUM:
5516       return getConstantFP(minimum(C1, C2), DL, VT);
5517     case ISD::FMAXIMUM:
5518       return getConstantFP(maximum(C1, C2), DL, VT);
5519     default: break;
5520     }
5521   }
5522   if (N1CFP && Opcode == ISD::FP_ROUND) {
5523     APFloat C1 = N1CFP->getValueAPF();    // make copy
5524     bool Unused;
5525     // This can return overflow, underflow, or inexact; we don't care.
5526     // FIXME need to be more flexible about rounding mode.
5527     (void) C1.convert(EVTToAPFloatSemantics(VT), APFloat::rmNearestTiesToEven,
5528                       &Unused);
5529     return getConstantFP(C1, DL, VT);
5530   }
5531 
5532   switch (Opcode) {
5533   case ISD::FSUB:
5534     // -0.0 - undef --> undef (consistent with "fneg undef")
5535     if (ConstantFPSDNode *N1C = isConstOrConstSplatFP(N1, /*AllowUndefs*/ true))
5536       if (N1C && N1C->getValueAPF().isNegZero() && N2.isUndef())
5537         return getUNDEF(VT);
5538     LLVM_FALLTHROUGH;
5539 
5540   case ISD::FADD:
5541   case ISD::FMUL:
5542   case ISD::FDIV:
5543   case ISD::FREM:
5544     // If both operands are undef, the result is undef. If 1 operand is undef,
5545     // the result is NaN. This should match the behavior of the IR optimizer.
5546     if (N1.isUndef() && N2.isUndef())
5547       return getUNDEF(VT);
5548     if (N1.isUndef() || N2.isUndef())
5549       return getConstantFP(APFloat::getNaN(EVTToAPFloatSemantics(VT)), DL, VT);
5550   }
5551   return SDValue();
5552 }
5553 
5554 SDValue SelectionDAG::getAssertAlign(const SDLoc &DL, SDValue Val, Align A) {
5555   assert(Val.getValueType().isInteger() && "Invalid AssertAlign!");
5556 
5557   // There's no need to assert on a byte-aligned pointer. All pointers are at
5558   // least byte aligned.
5559   if (A == Align(1))
5560     return Val;
5561 
5562   FoldingSetNodeID ID;
5563   AddNodeIDNode(ID, ISD::AssertAlign, getVTList(Val.getValueType()), {Val});
5564   ID.AddInteger(A.value());
5565 
5566   void *IP = nullptr;
5567   if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
5568     return SDValue(E, 0);
5569 
5570   auto *N = newSDNode<AssertAlignSDNode>(DL.getIROrder(), DL.getDebugLoc(),
5571                                          Val.getValueType(), A);
5572   createOperands(N, {Val});
5573 
5574   CSEMap.InsertNode(N, IP);
5575   InsertNode(N);
5576 
5577   SDValue V(N, 0);
5578   NewSDValueDbgMsg(V, "Creating new node: ", this);
5579   return V;
5580 }
5581 
5582 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
5583                               SDValue N1, SDValue N2) {
5584   SDNodeFlags Flags;
5585   if (Inserter)
5586     Flags = Inserter->getFlags();
5587   return getNode(Opcode, DL, VT, N1, N2, Flags);
5588 }
5589 
5590 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
5591                               SDValue N1, SDValue N2, const SDNodeFlags Flags) {
5592   assert(N1.getOpcode() != ISD::DELETED_NODE &&
5593          N2.getOpcode() != ISD::DELETED_NODE &&
5594          "Operand is DELETED_NODE!");
5595   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
5596   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
5597   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
5598   ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2);
5599 
5600   // Canonicalize constant to RHS if commutative.
5601   if (TLI->isCommutativeBinOp(Opcode)) {
5602     if (N1C && !N2C) {
5603       std::swap(N1C, N2C);
5604       std::swap(N1, N2);
5605     } else if (N1CFP && !N2CFP) {
5606       std::swap(N1CFP, N2CFP);
5607       std::swap(N1, N2);
5608     }
5609   }
5610 
5611   switch (Opcode) {
5612   default: break;
5613   case ISD::TokenFactor:
5614     assert(VT == MVT::Other && N1.getValueType() == MVT::Other &&
5615            N2.getValueType() == MVT::Other && "Invalid token factor!");
5616     // Fold trivial token factors.
5617     if (N1.getOpcode() == ISD::EntryToken) return N2;
5618     if (N2.getOpcode() == ISD::EntryToken) return N1;
5619     if (N1 == N2) return N1;
5620     break;
5621   case ISD::BUILD_VECTOR: {
5622     // Attempt to simplify BUILD_VECTOR.
5623     SDValue Ops[] = {N1, N2};
5624     if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
5625       return V;
5626     break;
5627   }
5628   case ISD::CONCAT_VECTORS: {
5629     SDValue Ops[] = {N1, N2};
5630     if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this))
5631       return V;
5632     break;
5633   }
5634   case ISD::AND:
5635     assert(VT.isInteger() && "This operator does not apply to FP types!");
5636     assert(N1.getValueType() == N2.getValueType() &&
5637            N1.getValueType() == VT && "Binary operator types must match!");
5638     // (X & 0) -> 0.  This commonly occurs when legalizing i64 values, so it's
5639     // worth handling here.
5640     if (N2C && N2C->isZero())
5641       return N2;
5642     if (N2C && N2C->isAllOnes()) // X & -1 -> X
5643       return N1;
5644     break;
5645   case ISD::OR:
5646   case ISD::XOR:
5647   case ISD::ADD:
5648   case ISD::SUB:
5649     assert(VT.isInteger() && "This operator does not apply to FP types!");
5650     assert(N1.getValueType() == N2.getValueType() &&
5651            N1.getValueType() == VT && "Binary operator types must match!");
5652     // (X ^|+- 0) -> X.  This commonly occurs when legalizing i64 values, so
5653     // it's worth handling here.
5654     if (N2C && N2C->isZero())
5655       return N1;
5656     if ((Opcode == ISD::ADD || Opcode == ISD::SUB) && VT.isVector() &&
5657         VT.getVectorElementType() == MVT::i1)
5658       return getNode(ISD::XOR, DL, VT, N1, N2);
5659     break;
5660   case ISD::MUL:
5661     assert(VT.isInteger() && "This operator does not apply to FP types!");
5662     assert(N1.getValueType() == N2.getValueType() &&
5663            N1.getValueType() == VT && "Binary operator types must match!");
5664     if (VT.isVector() && VT.getVectorElementType() == MVT::i1)
5665       return getNode(ISD::AND, DL, VT, N1, N2);
5666     if (N2C && (N1.getOpcode() == ISD::VSCALE) && Flags.hasNoSignedWrap()) {
5667       const APInt &MulImm = N1->getConstantOperandAPInt(0);
5668       const APInt &N2CImm = N2C->getAPIntValue();
5669       return getVScale(DL, VT, MulImm * N2CImm);
5670     }
5671     break;
5672   case ISD::UDIV:
5673   case ISD::UREM:
5674   case ISD::MULHU:
5675   case ISD::MULHS:
5676   case ISD::SDIV:
5677   case ISD::SREM:
5678   case ISD::SADDSAT:
5679   case ISD::SSUBSAT:
5680   case ISD::UADDSAT:
5681   case ISD::USUBSAT:
5682     assert(VT.isInteger() && "This operator does not apply to FP types!");
5683     assert(N1.getValueType() == N2.getValueType() &&
5684            N1.getValueType() == VT && "Binary operator types must match!");
5685     if (VT.isVector() && VT.getVectorElementType() == MVT::i1) {
5686       // fold (add_sat x, y) -> (or x, y) for bool types.
5687       if (Opcode == ISD::SADDSAT || Opcode == ISD::UADDSAT)
5688         return getNode(ISD::OR, DL, VT, N1, N2);
5689       // fold (sub_sat x, y) -> (and x, ~y) for bool types.
5690       if (Opcode == ISD::SSUBSAT || Opcode == ISD::USUBSAT)
5691         return getNode(ISD::AND, DL, VT, N1, getNOT(DL, N2, VT));
5692     }
5693     break;
5694   case ISD::SMIN:
5695   case ISD::UMAX:
5696     assert(VT.isInteger() && "This operator does not apply to FP types!");
5697     assert(N1.getValueType() == N2.getValueType() &&
5698            N1.getValueType() == VT && "Binary operator types must match!");
5699     if (VT.isVector() && VT.getVectorElementType() == MVT::i1)
5700       return getNode(ISD::OR, DL, VT, N1, N2);
5701     break;
5702   case ISD::SMAX:
5703   case ISD::UMIN:
5704     assert(VT.isInteger() && "This operator does not apply to FP types!");
5705     assert(N1.getValueType() == N2.getValueType() &&
5706            N1.getValueType() == VT && "Binary operator types must match!");
5707     if (VT.isVector() && VT.getVectorElementType() == MVT::i1)
5708       return getNode(ISD::AND, DL, VT, N1, N2);
5709     break;
5710   case ISD::FADD:
5711   case ISD::FSUB:
5712   case ISD::FMUL:
5713   case ISD::FDIV:
5714   case ISD::FREM:
5715     assert(VT.isFloatingPoint() && "This operator only applies to FP types!");
5716     assert(N1.getValueType() == N2.getValueType() &&
5717            N1.getValueType() == VT && "Binary operator types must match!");
5718     if (SDValue V = simplifyFPBinop(Opcode, N1, N2, Flags))
5719       return V;
5720     break;
5721   case ISD::FCOPYSIGN:   // N1 and result must match.  N1/N2 need not match.
5722     assert(N1.getValueType() == VT &&
5723            N1.getValueType().isFloatingPoint() &&
5724            N2.getValueType().isFloatingPoint() &&
5725            "Invalid FCOPYSIGN!");
5726     break;
5727   case ISD::SHL:
5728     if (N2C && (N1.getOpcode() == ISD::VSCALE) && Flags.hasNoSignedWrap()) {
5729       const APInt &MulImm = N1->getConstantOperandAPInt(0);
5730       const APInt &ShiftImm = N2C->getAPIntValue();
5731       return getVScale(DL, VT, MulImm << ShiftImm);
5732     }
5733     LLVM_FALLTHROUGH;
5734   case ISD::SRA:
5735   case ISD::SRL:
5736     if (SDValue V = simplifyShift(N1, N2))
5737       return V;
5738     LLVM_FALLTHROUGH;
5739   case ISD::ROTL:
5740   case ISD::ROTR:
5741     assert(VT == N1.getValueType() &&
5742            "Shift operators return type must be the same as their first arg");
5743     assert(VT.isInteger() && N2.getValueType().isInteger() &&
5744            "Shifts only work on integers");
5745     assert((!VT.isVector() || VT == N2.getValueType()) &&
5746            "Vector shift amounts must be in the same as their first arg");
5747     // Verify that the shift amount VT is big enough to hold valid shift
5748     // amounts.  This catches things like trying to shift an i1024 value by an
5749     // i8, which is easy to fall into in generic code that uses
5750     // TLI.getShiftAmount().
5751     assert(N2.getValueType().getScalarSizeInBits() >=
5752                Log2_32_Ceil(VT.getScalarSizeInBits()) &&
5753            "Invalid use of small shift amount with oversized value!");
5754 
5755     // Always fold shifts of i1 values so the code generator doesn't need to
5756     // handle them.  Since we know the size of the shift has to be less than the
5757     // size of the value, the shift/rotate count is guaranteed to be zero.
5758     if (VT == MVT::i1)
5759       return N1;
5760     if (N2C && N2C->isZero())
5761       return N1;
5762     break;
5763   case ISD::FP_ROUND:
5764     assert(VT.isFloatingPoint() &&
5765            N1.getValueType().isFloatingPoint() &&
5766            VT.bitsLE(N1.getValueType()) &&
5767            N2C && (N2C->getZExtValue() == 0 || N2C->getZExtValue() == 1) &&
5768            "Invalid FP_ROUND!");
5769     if (N1.getValueType() == VT) return N1;  // noop conversion.
5770     break;
5771   case ISD::AssertSext:
5772   case ISD::AssertZext: {
5773     EVT EVT = cast<VTSDNode>(N2)->getVT();
5774     assert(VT == N1.getValueType() && "Not an inreg extend!");
5775     assert(VT.isInteger() && EVT.isInteger() &&
5776            "Cannot *_EXTEND_INREG FP types");
5777     assert(!EVT.isVector() &&
5778            "AssertSExt/AssertZExt type should be the vector element type "
5779            "rather than the vector type!");
5780     assert(EVT.bitsLE(VT.getScalarType()) && "Not extending!");
5781     if (VT.getScalarType() == EVT) return N1; // noop assertion.
5782     break;
5783   }
5784   case ISD::SIGN_EXTEND_INREG: {
5785     EVT EVT = cast<VTSDNode>(N2)->getVT();
5786     assert(VT == N1.getValueType() && "Not an inreg extend!");
5787     assert(VT.isInteger() && EVT.isInteger() &&
5788            "Cannot *_EXTEND_INREG FP types");
5789     assert(EVT.isVector() == VT.isVector() &&
5790            "SIGN_EXTEND_INREG type should be vector iff the operand "
5791            "type is vector!");
5792     assert((!EVT.isVector() ||
5793             EVT.getVectorElementCount() == VT.getVectorElementCount()) &&
5794            "Vector element counts must match in SIGN_EXTEND_INREG");
5795     assert(EVT.bitsLE(VT) && "Not extending!");
5796     if (EVT == VT) return N1;  // Not actually extending
5797 
5798     auto SignExtendInReg = [&](APInt Val, llvm::EVT ConstantVT) {
5799       unsigned FromBits = EVT.getScalarSizeInBits();
5800       Val <<= Val.getBitWidth() - FromBits;
5801       Val.ashrInPlace(Val.getBitWidth() - FromBits);
5802       return getConstant(Val, DL, ConstantVT);
5803     };
5804 
5805     if (N1C) {
5806       const APInt &Val = N1C->getAPIntValue();
5807       return SignExtendInReg(Val, VT);
5808     }
5809 
5810     if (ISD::isBuildVectorOfConstantSDNodes(N1.getNode())) {
5811       SmallVector<SDValue, 8> Ops;
5812       llvm::EVT OpVT = N1.getOperand(0).getValueType();
5813       for (int i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
5814         SDValue Op = N1.getOperand(i);
5815         if (Op.isUndef()) {
5816           Ops.push_back(getUNDEF(OpVT));
5817           continue;
5818         }
5819         ConstantSDNode *C = cast<ConstantSDNode>(Op);
5820         APInt Val = C->getAPIntValue();
5821         Ops.push_back(SignExtendInReg(Val, OpVT));
5822       }
5823       return getBuildVector(VT, DL, Ops);
5824     }
5825     break;
5826   }
5827   case ISD::FP_TO_SINT_SAT:
5828   case ISD::FP_TO_UINT_SAT: {
5829     assert(VT.isInteger() && cast<VTSDNode>(N2)->getVT().isInteger() &&
5830            N1.getValueType().isFloatingPoint() && "Invalid FP_TO_*INT_SAT");
5831     assert(N1.getValueType().isVector() == VT.isVector() &&
5832            "FP_TO_*INT_SAT type should be vector iff the operand type is "
5833            "vector!");
5834     assert((!VT.isVector() || VT.getVectorNumElements() ==
5835                                   N1.getValueType().getVectorNumElements()) &&
5836            "Vector element counts must match in FP_TO_*INT_SAT");
5837     assert(!cast<VTSDNode>(N2)->getVT().isVector() &&
5838            "Type to saturate to must be a scalar.");
5839     assert(cast<VTSDNode>(N2)->getVT().bitsLE(VT.getScalarType()) &&
5840            "Not extending!");
5841     break;
5842   }
5843   case ISD::EXTRACT_VECTOR_ELT:
5844     assert(VT.getSizeInBits() >= N1.getValueType().getScalarSizeInBits() &&
5845            "The result of EXTRACT_VECTOR_ELT must be at least as wide as the \
5846              element type of the vector.");
5847 
5848     // Extract from an undefined value or using an undefined index is undefined.
5849     if (N1.isUndef() || N2.isUndef())
5850       return getUNDEF(VT);
5851 
5852     // EXTRACT_VECTOR_ELT of out-of-bounds element is an UNDEF for fixed length
5853     // vectors. For scalable vectors we will provide appropriate support for
5854     // dealing with arbitrary indices.
5855     if (N2C && N1.getValueType().isFixedLengthVector() &&
5856         N2C->getAPIntValue().uge(N1.getValueType().getVectorNumElements()))
5857       return getUNDEF(VT);
5858 
5859     // EXTRACT_VECTOR_ELT of CONCAT_VECTORS is often formed while lowering is
5860     // expanding copies of large vectors from registers. This only works for
5861     // fixed length vectors, since we need to know the exact number of
5862     // elements.
5863     if (N2C && N1.getOperand(0).getValueType().isFixedLengthVector() &&
5864         N1.getOpcode() == ISD::CONCAT_VECTORS && N1.getNumOperands() > 0) {
5865       unsigned Factor =
5866         N1.getOperand(0).getValueType().getVectorNumElements();
5867       return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
5868                      N1.getOperand(N2C->getZExtValue() / Factor),
5869                      getVectorIdxConstant(N2C->getZExtValue() % Factor, DL));
5870     }
5871 
5872     // EXTRACT_VECTOR_ELT of BUILD_VECTOR or SPLAT_VECTOR is often formed while
5873     // lowering is expanding large vector constants.
5874     if (N2C && (N1.getOpcode() == ISD::BUILD_VECTOR ||
5875                 N1.getOpcode() == ISD::SPLAT_VECTOR)) {
5876       assert((N1.getOpcode() != ISD::BUILD_VECTOR ||
5877               N1.getValueType().isFixedLengthVector()) &&
5878              "BUILD_VECTOR used for scalable vectors");
5879       unsigned Index =
5880           N1.getOpcode() == ISD::BUILD_VECTOR ? N2C->getZExtValue() : 0;
5881       SDValue Elt = N1.getOperand(Index);
5882 
5883       if (VT != Elt.getValueType())
5884         // If the vector element type is not legal, the BUILD_VECTOR operands
5885         // are promoted and implicitly truncated, and the result implicitly
5886         // extended. Make that explicit here.
5887         Elt = getAnyExtOrTrunc(Elt, DL, VT);
5888 
5889       return Elt;
5890     }
5891 
5892     // EXTRACT_VECTOR_ELT of INSERT_VECTOR_ELT is often formed when vector
5893     // operations are lowered to scalars.
5894     if (N1.getOpcode() == ISD::INSERT_VECTOR_ELT) {
5895       // If the indices are the same, return the inserted element else
5896       // if the indices are known different, extract the element from
5897       // the original vector.
5898       SDValue N1Op2 = N1.getOperand(2);
5899       ConstantSDNode *N1Op2C = dyn_cast<ConstantSDNode>(N1Op2);
5900 
5901       if (N1Op2C && N2C) {
5902         if (N1Op2C->getZExtValue() == N2C->getZExtValue()) {
5903           if (VT == N1.getOperand(1).getValueType())
5904             return N1.getOperand(1);
5905           return getSExtOrTrunc(N1.getOperand(1), DL, VT);
5906         }
5907         return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0), N2);
5908       }
5909     }
5910 
5911     // EXTRACT_VECTOR_ELT of v1iX EXTRACT_SUBVECTOR could be formed
5912     // when vector types are scalarized and v1iX is legal.
5913     // vextract (v1iX extract_subvector(vNiX, Idx)) -> vextract(vNiX,Idx).
5914     // Here we are completely ignoring the extract element index (N2),
5915     // which is fine for fixed width vectors, since any index other than 0
5916     // is undefined anyway. However, this cannot be ignored for scalable
5917     // vectors - in theory we could support this, but we don't want to do this
5918     // without a profitability check.
5919     if (N1.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
5920         N1.getValueType().isFixedLengthVector() &&
5921         N1.getValueType().getVectorNumElements() == 1) {
5922       return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0),
5923                      N1.getOperand(1));
5924     }
5925     break;
5926   case ISD::EXTRACT_ELEMENT:
5927     assert(N2C && (unsigned)N2C->getZExtValue() < 2 && "Bad EXTRACT_ELEMENT!");
5928     assert(!N1.getValueType().isVector() && !VT.isVector() &&
5929            (N1.getValueType().isInteger() == VT.isInteger()) &&
5930            N1.getValueType() != VT &&
5931            "Wrong types for EXTRACT_ELEMENT!");
5932 
5933     // EXTRACT_ELEMENT of BUILD_PAIR is often formed while legalize is expanding
5934     // 64-bit integers into 32-bit parts.  Instead of building the extract of
5935     // the BUILD_PAIR, only to have legalize rip it apart, just do it now.
5936     if (N1.getOpcode() == ISD::BUILD_PAIR)
5937       return N1.getOperand(N2C->getZExtValue());
5938 
5939     // EXTRACT_ELEMENT of a constant int is also very common.
5940     if (N1C) {
5941       unsigned ElementSize = VT.getSizeInBits();
5942       unsigned Shift = ElementSize * N2C->getZExtValue();
5943       const APInt &Val = N1C->getAPIntValue();
5944       return getConstant(Val.extractBits(ElementSize, Shift), DL, VT);
5945     }
5946     break;
5947   case ISD::EXTRACT_SUBVECTOR: {
5948     EVT N1VT = N1.getValueType();
5949     assert(VT.isVector() && N1VT.isVector() &&
5950            "Extract subvector VTs must be vectors!");
5951     assert(VT.getVectorElementType() == N1VT.getVectorElementType() &&
5952            "Extract subvector VTs must have the same element type!");
5953     assert((VT.isFixedLengthVector() || N1VT.isScalableVector()) &&
5954            "Cannot extract a scalable vector from a fixed length vector!");
5955     assert((VT.isScalableVector() != N1VT.isScalableVector() ||
5956             VT.getVectorMinNumElements() <= N1VT.getVectorMinNumElements()) &&
5957            "Extract subvector must be from larger vector to smaller vector!");
5958     assert(N2C && "Extract subvector index must be a constant");
5959     assert((VT.isScalableVector() != N1VT.isScalableVector() ||
5960             (VT.getVectorMinNumElements() + N2C->getZExtValue()) <=
5961                 N1VT.getVectorMinNumElements()) &&
5962            "Extract subvector overflow!");
5963     assert(N2C->getAPIntValue().getBitWidth() ==
5964                TLI->getVectorIdxTy(getDataLayout()).getFixedSizeInBits() &&
5965            "Constant index for EXTRACT_SUBVECTOR has an invalid size");
5966 
5967     // Trivial extraction.
5968     if (VT == N1VT)
5969       return N1;
5970 
5971     // EXTRACT_SUBVECTOR of an UNDEF is an UNDEF.
5972     if (N1.isUndef())
5973       return getUNDEF(VT);
5974 
5975     // EXTRACT_SUBVECTOR of CONCAT_VECTOR can be simplified if the pieces of
5976     // the concat have the same type as the extract.
5977     if (N1.getOpcode() == ISD::CONCAT_VECTORS && N1.getNumOperands() > 0 &&
5978         VT == N1.getOperand(0).getValueType()) {
5979       unsigned Factor = VT.getVectorMinNumElements();
5980       return N1.getOperand(N2C->getZExtValue() / Factor);
5981     }
5982 
5983     // EXTRACT_SUBVECTOR of INSERT_SUBVECTOR is often created
5984     // during shuffle legalization.
5985     if (N1.getOpcode() == ISD::INSERT_SUBVECTOR && N2 == N1.getOperand(2) &&
5986         VT == N1.getOperand(1).getValueType())
5987       return N1.getOperand(1);
5988     break;
5989   }
5990   }
5991 
5992   // Perform trivial constant folding.
5993   if (SDValue SV = FoldConstantArithmetic(Opcode, DL, VT, {N1, N2}))
5994     return SV;
5995 
5996   // Canonicalize an UNDEF to the RHS, even over a constant.
5997   if (N1.isUndef()) {
5998     if (TLI->isCommutativeBinOp(Opcode)) {
5999       std::swap(N1, N2);
6000     } else {
6001       switch (Opcode) {
6002       case ISD::SIGN_EXTEND_INREG:
6003       case ISD::SUB:
6004         return getUNDEF(VT);     // fold op(undef, arg2) -> undef
6005       case ISD::UDIV:
6006       case ISD::SDIV:
6007       case ISD::UREM:
6008       case ISD::SREM:
6009       case ISD::SSUBSAT:
6010       case ISD::USUBSAT:
6011         return getConstant(0, DL, VT);    // fold op(undef, arg2) -> 0
6012       }
6013     }
6014   }
6015 
6016   // Fold a bunch of operators when the RHS is undef.
6017   if (N2.isUndef()) {
6018     switch (Opcode) {
6019     case ISD::XOR:
6020       if (N1.isUndef())
6021         // Handle undef ^ undef -> 0 special case. This is a common
6022         // idiom (misuse).
6023         return getConstant(0, DL, VT);
6024       LLVM_FALLTHROUGH;
6025     case ISD::ADD:
6026     case ISD::SUB:
6027     case ISD::UDIV:
6028     case ISD::SDIV:
6029     case ISD::UREM:
6030     case ISD::SREM:
6031       return getUNDEF(VT);       // fold op(arg1, undef) -> undef
6032     case ISD::MUL:
6033     case ISD::AND:
6034     case ISD::SSUBSAT:
6035     case ISD::USUBSAT:
6036       return getConstant(0, DL, VT);  // fold op(arg1, undef) -> 0
6037     case ISD::OR:
6038     case ISD::SADDSAT:
6039     case ISD::UADDSAT:
6040       return getAllOnesConstant(DL, VT);
6041     }
6042   }
6043 
6044   // Memoize this node if possible.
6045   SDNode *N;
6046   SDVTList VTs = getVTList(VT);
6047   SDValue Ops[] = {N1, N2};
6048   if (VT != MVT::Glue) {
6049     FoldingSetNodeID ID;
6050     AddNodeIDNode(ID, Opcode, VTs, Ops);
6051     void *IP = nullptr;
6052     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
6053       E->intersectFlagsWith(Flags);
6054       return SDValue(E, 0);
6055     }
6056 
6057     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
6058     N->setFlags(Flags);
6059     createOperands(N, Ops);
6060     CSEMap.InsertNode(N, IP);
6061   } else {
6062     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
6063     createOperands(N, Ops);
6064   }
6065 
6066   InsertNode(N);
6067   SDValue V = SDValue(N, 0);
6068   NewSDValueDbgMsg(V, "Creating new node: ", this);
6069   return V;
6070 }
6071 
6072 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
6073                               SDValue N1, SDValue N2, SDValue N3) {
6074   SDNodeFlags Flags;
6075   if (Inserter)
6076     Flags = Inserter->getFlags();
6077   return getNode(Opcode, DL, VT, N1, N2, N3, Flags);
6078 }
6079 
6080 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
6081                               SDValue N1, SDValue N2, SDValue N3,
6082                               const SDNodeFlags Flags) {
6083   assert(N1.getOpcode() != ISD::DELETED_NODE &&
6084          N2.getOpcode() != ISD::DELETED_NODE &&
6085          N3.getOpcode() != ISD::DELETED_NODE &&
6086          "Operand is DELETED_NODE!");
6087   // Perform various simplifications.
6088   switch (Opcode) {
6089   case ISD::FMA: {
6090     assert(VT.isFloatingPoint() && "This operator only applies to FP types!");
6091     assert(N1.getValueType() == VT && N2.getValueType() == VT &&
6092            N3.getValueType() == VT && "FMA types must match!");
6093     ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6094     ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2);
6095     ConstantFPSDNode *N3CFP = dyn_cast<ConstantFPSDNode>(N3);
6096     if (N1CFP && N2CFP && N3CFP) {
6097       APFloat  V1 = N1CFP->getValueAPF();
6098       const APFloat &V2 = N2CFP->getValueAPF();
6099       const APFloat &V3 = N3CFP->getValueAPF();
6100       V1.fusedMultiplyAdd(V2, V3, APFloat::rmNearestTiesToEven);
6101       return getConstantFP(V1, DL, VT);
6102     }
6103     break;
6104   }
6105   case ISD::BUILD_VECTOR: {
6106     // Attempt to simplify BUILD_VECTOR.
6107     SDValue Ops[] = {N1, N2, N3};
6108     if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
6109       return V;
6110     break;
6111   }
6112   case ISD::CONCAT_VECTORS: {
6113     SDValue Ops[] = {N1, N2, N3};
6114     if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this))
6115       return V;
6116     break;
6117   }
6118   case ISD::SETCC: {
6119     assert(VT.isInteger() && "SETCC result type must be an integer!");
6120     assert(N1.getValueType() == N2.getValueType() &&
6121            "SETCC operands must have the same type!");
6122     assert(VT.isVector() == N1.getValueType().isVector() &&
6123            "SETCC type should be vector iff the operand type is vector!");
6124     assert((!VT.isVector() || VT.getVectorElementCount() ==
6125                                   N1.getValueType().getVectorElementCount()) &&
6126            "SETCC vector element counts must match!");
6127     // Use FoldSetCC to simplify SETCC's.
6128     if (SDValue V = FoldSetCC(VT, N1, N2, cast<CondCodeSDNode>(N3)->get(), DL))
6129       return V;
6130     // Vector constant folding.
6131     SDValue Ops[] = {N1, N2, N3};
6132     if (SDValue V = FoldConstantArithmetic(Opcode, DL, VT, Ops)) {
6133       NewSDValueDbgMsg(V, "New node vector constant folding: ", this);
6134       return V;
6135     }
6136     break;
6137   }
6138   case ISD::SELECT:
6139   case ISD::VSELECT:
6140     if (SDValue V = simplifySelect(N1, N2, N3))
6141       return V;
6142     break;
6143   case ISD::VECTOR_SHUFFLE:
6144     llvm_unreachable("should use getVectorShuffle constructor!");
6145   case ISD::VECTOR_SPLICE: {
6146     if (cast<ConstantSDNode>(N3)->isNullValue())
6147       return N1;
6148     break;
6149   }
6150   case ISD::INSERT_VECTOR_ELT: {
6151     ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3);
6152     // INSERT_VECTOR_ELT into out-of-bounds element is an UNDEF, except
6153     // for scalable vectors where we will generate appropriate code to
6154     // deal with out-of-bounds cases correctly.
6155     if (N3C && N1.getValueType().isFixedLengthVector() &&
6156         N3C->getZExtValue() >= N1.getValueType().getVectorNumElements())
6157       return getUNDEF(VT);
6158 
6159     // Undefined index can be assumed out-of-bounds, so that's UNDEF too.
6160     if (N3.isUndef())
6161       return getUNDEF(VT);
6162 
6163     // If the inserted element is an UNDEF, just use the input vector.
6164     if (N2.isUndef())
6165       return N1;
6166 
6167     break;
6168   }
6169   case ISD::INSERT_SUBVECTOR: {
6170     // Inserting undef into undef is still undef.
6171     if (N1.isUndef() && N2.isUndef())
6172       return getUNDEF(VT);
6173 
6174     EVT N2VT = N2.getValueType();
6175     assert(VT == N1.getValueType() &&
6176            "Dest and insert subvector source types must match!");
6177     assert(VT.isVector() && N2VT.isVector() &&
6178            "Insert subvector VTs must be vectors!");
6179     assert((VT.isScalableVector() || N2VT.isFixedLengthVector()) &&
6180            "Cannot insert a scalable vector into a fixed length vector!");
6181     assert((VT.isScalableVector() != N2VT.isScalableVector() ||
6182             VT.getVectorMinNumElements() >= N2VT.getVectorMinNumElements()) &&
6183            "Insert subvector must be from smaller vector to larger vector!");
6184     assert(isa<ConstantSDNode>(N3) &&
6185            "Insert subvector index must be constant");
6186     assert((VT.isScalableVector() != N2VT.isScalableVector() ||
6187             (N2VT.getVectorMinNumElements() +
6188              cast<ConstantSDNode>(N3)->getZExtValue()) <=
6189                 VT.getVectorMinNumElements()) &&
6190            "Insert subvector overflow!");
6191     assert(cast<ConstantSDNode>(N3)->getAPIntValue().getBitWidth() ==
6192                TLI->getVectorIdxTy(getDataLayout()).getFixedSizeInBits() &&
6193            "Constant index for INSERT_SUBVECTOR has an invalid size");
6194 
6195     // Trivial insertion.
6196     if (VT == N2VT)
6197       return N2;
6198 
6199     // If this is an insert of an extracted vector into an undef vector, we
6200     // can just use the input to the extract.
6201     if (N1.isUndef() && N2.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
6202         N2.getOperand(1) == N3 && N2.getOperand(0).getValueType() == VT)
6203       return N2.getOperand(0);
6204     break;
6205   }
6206   case ISD::BITCAST:
6207     // Fold bit_convert nodes from a type to themselves.
6208     if (N1.getValueType() == VT)
6209       return N1;
6210     break;
6211   }
6212 
6213   // Memoize node if it doesn't produce a flag.
6214   SDNode *N;
6215   SDVTList VTs = getVTList(VT);
6216   SDValue Ops[] = {N1, N2, N3};
6217   if (VT != MVT::Glue) {
6218     FoldingSetNodeID ID;
6219     AddNodeIDNode(ID, Opcode, VTs, Ops);
6220     void *IP = nullptr;
6221     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
6222       E->intersectFlagsWith(Flags);
6223       return SDValue(E, 0);
6224     }
6225 
6226     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
6227     N->setFlags(Flags);
6228     createOperands(N, Ops);
6229     CSEMap.InsertNode(N, IP);
6230   } else {
6231     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
6232     createOperands(N, Ops);
6233   }
6234 
6235   InsertNode(N);
6236   SDValue V = SDValue(N, 0);
6237   NewSDValueDbgMsg(V, "Creating new node: ", this);
6238   return V;
6239 }
6240 
6241 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
6242                               SDValue N1, SDValue N2, SDValue N3, SDValue N4) {
6243   SDValue Ops[] = { N1, N2, N3, N4 };
6244   return getNode(Opcode, DL, VT, Ops);
6245 }
6246 
6247 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
6248                               SDValue N1, SDValue N2, SDValue N3, SDValue N4,
6249                               SDValue N5) {
6250   SDValue Ops[] = { N1, N2, N3, N4, N5 };
6251   return getNode(Opcode, DL, VT, Ops);
6252 }
6253 
6254 /// getStackArgumentTokenFactor - Compute a TokenFactor to force all
6255 /// the incoming stack arguments to be loaded from the stack.
6256 SDValue SelectionDAG::getStackArgumentTokenFactor(SDValue Chain) {
6257   SmallVector<SDValue, 8> ArgChains;
6258 
6259   // Include the original chain at the beginning of the list. When this is
6260   // used by target LowerCall hooks, this helps legalize find the
6261   // CALLSEQ_BEGIN node.
6262   ArgChains.push_back(Chain);
6263 
6264   // Add a chain value for each stack argument.
6265   for (SDNode *U : getEntryNode().getNode()->uses())
6266     if (LoadSDNode *L = dyn_cast<LoadSDNode>(U))
6267       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
6268         if (FI->getIndex() < 0)
6269           ArgChains.push_back(SDValue(L, 1));
6270 
6271   // Build a tokenfactor for all the chains.
6272   return getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains);
6273 }
6274 
6275 /// getMemsetValue - Vectorized representation of the memset value
6276 /// operand.
6277 static SDValue getMemsetValue(SDValue Value, EVT VT, SelectionDAG &DAG,
6278                               const SDLoc &dl) {
6279   assert(!Value.isUndef());
6280 
6281   unsigned NumBits = VT.getScalarSizeInBits();
6282   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
6283     assert(C->getAPIntValue().getBitWidth() == 8);
6284     APInt Val = APInt::getSplat(NumBits, C->getAPIntValue());
6285     if (VT.isInteger()) {
6286       bool IsOpaque = VT.getSizeInBits() > 64 ||
6287           !DAG.getTargetLoweringInfo().isLegalStoreImmediate(C->getSExtValue());
6288       return DAG.getConstant(Val, dl, VT, false, IsOpaque);
6289     }
6290     return DAG.getConstantFP(APFloat(DAG.EVTToAPFloatSemantics(VT), Val), dl,
6291                              VT);
6292   }
6293 
6294   assert(Value.getValueType() == MVT::i8 && "memset with non-byte fill value?");
6295   EVT IntVT = VT.getScalarType();
6296   if (!IntVT.isInteger())
6297     IntVT = EVT::getIntegerVT(*DAG.getContext(), IntVT.getSizeInBits());
6298 
6299   Value = DAG.getNode(ISD::ZERO_EXTEND, dl, IntVT, Value);
6300   if (NumBits > 8) {
6301     // Use a multiplication with 0x010101... to extend the input to the
6302     // required length.
6303     APInt Magic = APInt::getSplat(NumBits, APInt(8, 0x01));
6304     Value = DAG.getNode(ISD::MUL, dl, IntVT, Value,
6305                         DAG.getConstant(Magic, dl, IntVT));
6306   }
6307 
6308   if (VT != Value.getValueType() && !VT.isInteger())
6309     Value = DAG.getBitcast(VT.getScalarType(), Value);
6310   if (VT != Value.getValueType())
6311     Value = DAG.getSplatBuildVector(VT, dl, Value);
6312 
6313   return Value;
6314 }
6315 
6316 /// getMemsetStringVal - Similar to getMemsetValue. Except this is only
6317 /// used when a memcpy is turned into a memset when the source is a constant
6318 /// string ptr.
6319 static SDValue getMemsetStringVal(EVT VT, const SDLoc &dl, SelectionDAG &DAG,
6320                                   const TargetLowering &TLI,
6321                                   const ConstantDataArraySlice &Slice) {
6322   // Handle vector with all elements zero.
6323   if (Slice.Array == nullptr) {
6324     if (VT.isInteger())
6325       return DAG.getConstant(0, dl, VT);
6326     if (VT == MVT::f32 || VT == MVT::f64 || VT == MVT::f128)
6327       return DAG.getConstantFP(0.0, dl, VT);
6328     if (VT.isVector()) {
6329       unsigned NumElts = VT.getVectorNumElements();
6330       MVT EltVT = (VT.getVectorElementType() == MVT::f32) ? MVT::i32 : MVT::i64;
6331       return DAG.getNode(ISD::BITCAST, dl, VT,
6332                          DAG.getConstant(0, dl,
6333                                          EVT::getVectorVT(*DAG.getContext(),
6334                                                           EltVT, NumElts)));
6335     }
6336     llvm_unreachable("Expected type!");
6337   }
6338 
6339   assert(!VT.isVector() && "Can't handle vector type here!");
6340   unsigned NumVTBits = VT.getSizeInBits();
6341   unsigned NumVTBytes = NumVTBits / 8;
6342   unsigned NumBytes = std::min(NumVTBytes, unsigned(Slice.Length));
6343 
6344   APInt Val(NumVTBits, 0);
6345   if (DAG.getDataLayout().isLittleEndian()) {
6346     for (unsigned i = 0; i != NumBytes; ++i)
6347       Val |= (uint64_t)(unsigned char)Slice[i] << i*8;
6348   } else {
6349     for (unsigned i = 0; i != NumBytes; ++i)
6350       Val |= (uint64_t)(unsigned char)Slice[i] << (NumVTBytes-i-1)*8;
6351   }
6352 
6353   // If the "cost" of materializing the integer immediate is less than the cost
6354   // of a load, then it is cost effective to turn the load into the immediate.
6355   Type *Ty = VT.getTypeForEVT(*DAG.getContext());
6356   if (TLI.shouldConvertConstantLoadToIntImm(Val, Ty))
6357     return DAG.getConstant(Val, dl, VT);
6358   return SDValue();
6359 }
6360 
6361 SDValue SelectionDAG::getMemBasePlusOffset(SDValue Base, TypeSize Offset,
6362                                            const SDLoc &DL,
6363                                            const SDNodeFlags Flags) {
6364   EVT VT = Base.getValueType();
6365   SDValue Index;
6366 
6367   if (Offset.isScalable())
6368     Index = getVScale(DL, Base.getValueType(),
6369                       APInt(Base.getValueSizeInBits().getFixedSize(),
6370                             Offset.getKnownMinSize()));
6371   else
6372     Index = getConstant(Offset.getFixedSize(), DL, VT);
6373 
6374   return getMemBasePlusOffset(Base, Index, DL, Flags);
6375 }
6376 
6377 SDValue SelectionDAG::getMemBasePlusOffset(SDValue Ptr, SDValue Offset,
6378                                            const SDLoc &DL,
6379                                            const SDNodeFlags Flags) {
6380   assert(Offset.getValueType().isInteger());
6381   EVT BasePtrVT = Ptr.getValueType();
6382   return getNode(ISD::ADD, DL, BasePtrVT, Ptr, Offset, Flags);
6383 }
6384 
6385 /// Returns true if memcpy source is constant data.
6386 static bool isMemSrcFromConstant(SDValue Src, ConstantDataArraySlice &Slice) {
6387   uint64_t SrcDelta = 0;
6388   GlobalAddressSDNode *G = nullptr;
6389   if (Src.getOpcode() == ISD::GlobalAddress)
6390     G = cast<GlobalAddressSDNode>(Src);
6391   else if (Src.getOpcode() == ISD::ADD &&
6392            Src.getOperand(0).getOpcode() == ISD::GlobalAddress &&
6393            Src.getOperand(1).getOpcode() == ISD::Constant) {
6394     G = cast<GlobalAddressSDNode>(Src.getOperand(0));
6395     SrcDelta = cast<ConstantSDNode>(Src.getOperand(1))->getZExtValue();
6396   }
6397   if (!G)
6398     return false;
6399 
6400   return getConstantDataArrayInfo(G->getGlobal(), Slice, 8,
6401                                   SrcDelta + G->getOffset());
6402 }
6403 
6404 static bool shouldLowerMemFuncForSize(const MachineFunction &MF,
6405                                       SelectionDAG &DAG) {
6406   // On Darwin, -Os means optimize for size without hurting performance, so
6407   // only really optimize for size when -Oz (MinSize) is used.
6408   if (MF.getTarget().getTargetTriple().isOSDarwin())
6409     return MF.getFunction().hasMinSize();
6410   return DAG.shouldOptForSize();
6411 }
6412 
6413 static void chainLoadsAndStoresForMemcpy(SelectionDAG &DAG, const SDLoc &dl,
6414                           SmallVector<SDValue, 32> &OutChains, unsigned From,
6415                           unsigned To, SmallVector<SDValue, 16> &OutLoadChains,
6416                           SmallVector<SDValue, 16> &OutStoreChains) {
6417   assert(OutLoadChains.size() && "Missing loads in memcpy inlining");
6418   assert(OutStoreChains.size() && "Missing stores in memcpy inlining");
6419   SmallVector<SDValue, 16> GluedLoadChains;
6420   for (unsigned i = From; i < To; ++i) {
6421     OutChains.push_back(OutLoadChains[i]);
6422     GluedLoadChains.push_back(OutLoadChains[i]);
6423   }
6424 
6425   // Chain for all loads.
6426   SDValue LoadToken = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
6427                                   GluedLoadChains);
6428 
6429   for (unsigned i = From; i < To; ++i) {
6430     StoreSDNode *ST = dyn_cast<StoreSDNode>(OutStoreChains[i]);
6431     SDValue NewStore = DAG.getTruncStore(LoadToken, dl, ST->getValue(),
6432                                   ST->getBasePtr(), ST->getMemoryVT(),
6433                                   ST->getMemOperand());
6434     OutChains.push_back(NewStore);
6435   }
6436 }
6437 
6438 static SDValue getMemcpyLoadsAndStores(SelectionDAG &DAG, const SDLoc &dl,
6439                                        SDValue Chain, SDValue Dst, SDValue Src,
6440                                        uint64_t Size, Align Alignment,
6441                                        bool isVol, bool AlwaysInline,
6442                                        MachinePointerInfo DstPtrInfo,
6443                                        MachinePointerInfo SrcPtrInfo,
6444                                        const AAMDNodes &AAInfo) {
6445   // Turn a memcpy of undef to nop.
6446   // FIXME: We need to honor volatile even is Src is undef.
6447   if (Src.isUndef())
6448     return Chain;
6449 
6450   // Expand memcpy to a series of load and store ops if the size operand falls
6451   // below a certain threshold.
6452   // TODO: In the AlwaysInline case, if the size is big then generate a loop
6453   // rather than maybe a humongous number of loads and stores.
6454   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6455   const DataLayout &DL = DAG.getDataLayout();
6456   LLVMContext &C = *DAG.getContext();
6457   std::vector<EVT> MemOps;
6458   bool DstAlignCanChange = false;
6459   MachineFunction &MF = DAG.getMachineFunction();
6460   MachineFrameInfo &MFI = MF.getFrameInfo();
6461   bool OptSize = shouldLowerMemFuncForSize(MF, DAG);
6462   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
6463   if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
6464     DstAlignCanChange = true;
6465   MaybeAlign SrcAlign = DAG.InferPtrAlign(Src);
6466   if (!SrcAlign || Alignment > *SrcAlign)
6467     SrcAlign = Alignment;
6468   assert(SrcAlign && "SrcAlign must be set");
6469   ConstantDataArraySlice Slice;
6470   // If marked as volatile, perform a copy even when marked as constant.
6471   bool CopyFromConstant = !isVol && isMemSrcFromConstant(Src, Slice);
6472   bool isZeroConstant = CopyFromConstant && Slice.Array == nullptr;
6473   unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemcpy(OptSize);
6474   const MemOp Op = isZeroConstant
6475                        ? MemOp::Set(Size, DstAlignCanChange, Alignment,
6476                                     /*IsZeroMemset*/ true, isVol)
6477                        : MemOp::Copy(Size, DstAlignCanChange, Alignment,
6478                                      *SrcAlign, isVol, CopyFromConstant);
6479   if (!TLI.findOptimalMemOpLowering(
6480           MemOps, Limit, Op, DstPtrInfo.getAddrSpace(),
6481           SrcPtrInfo.getAddrSpace(), MF.getFunction().getAttributes()))
6482     return SDValue();
6483 
6484   if (DstAlignCanChange) {
6485     Type *Ty = MemOps[0].getTypeForEVT(C);
6486     Align NewAlign = DL.getABITypeAlign(Ty);
6487 
6488     // Don't promote to an alignment that would require dynamic stack
6489     // realignment.
6490     const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
6491     if (!TRI->hasStackRealignment(MF))
6492       while (NewAlign > Alignment && DL.exceedsNaturalStackAlignment(NewAlign))
6493         NewAlign = NewAlign / 2;
6494 
6495     if (NewAlign > Alignment) {
6496       // Give the stack frame object a larger alignment if needed.
6497       if (MFI.getObjectAlign(FI->getIndex()) < NewAlign)
6498         MFI.setObjectAlignment(FI->getIndex(), NewAlign);
6499       Alignment = NewAlign;
6500     }
6501   }
6502 
6503   // Prepare AAInfo for loads/stores after lowering this memcpy.
6504   AAMDNodes NewAAInfo = AAInfo;
6505   NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr;
6506 
6507   MachineMemOperand::Flags MMOFlags =
6508       isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone;
6509   SmallVector<SDValue, 16> OutLoadChains;
6510   SmallVector<SDValue, 16> OutStoreChains;
6511   SmallVector<SDValue, 32> OutChains;
6512   unsigned NumMemOps = MemOps.size();
6513   uint64_t SrcOff = 0, DstOff = 0;
6514   for (unsigned i = 0; i != NumMemOps; ++i) {
6515     EVT VT = MemOps[i];
6516     unsigned VTSize = VT.getSizeInBits() / 8;
6517     SDValue Value, Store;
6518 
6519     if (VTSize > Size) {
6520       // Issuing an unaligned load / store pair  that overlaps with the previous
6521       // pair. Adjust the offset accordingly.
6522       assert(i == NumMemOps-1 && i != 0);
6523       SrcOff -= VTSize - Size;
6524       DstOff -= VTSize - Size;
6525     }
6526 
6527     if (CopyFromConstant &&
6528         (isZeroConstant || (VT.isInteger() && !VT.isVector()))) {
6529       // It's unlikely a store of a vector immediate can be done in a single
6530       // instruction. It would require a load from a constantpool first.
6531       // We only handle zero vectors here.
6532       // FIXME: Handle other cases where store of vector immediate is done in
6533       // a single instruction.
6534       ConstantDataArraySlice SubSlice;
6535       if (SrcOff < Slice.Length) {
6536         SubSlice = Slice;
6537         SubSlice.move(SrcOff);
6538       } else {
6539         // This is an out-of-bounds access and hence UB. Pretend we read zero.
6540         SubSlice.Array = nullptr;
6541         SubSlice.Offset = 0;
6542         SubSlice.Length = VTSize;
6543       }
6544       Value = getMemsetStringVal(VT, dl, DAG, TLI, SubSlice);
6545       if (Value.getNode()) {
6546         Store = DAG.getStore(
6547             Chain, dl, Value,
6548             DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl),
6549             DstPtrInfo.getWithOffset(DstOff), Alignment, MMOFlags, NewAAInfo);
6550         OutChains.push_back(Store);
6551       }
6552     }
6553 
6554     if (!Store.getNode()) {
6555       // The type might not be legal for the target.  This should only happen
6556       // if the type is smaller than a legal type, as on PPC, so the right
6557       // thing to do is generate a LoadExt/StoreTrunc pair.  These simplify
6558       // to Load/Store if NVT==VT.
6559       // FIXME does the case above also need this?
6560       EVT NVT = TLI.getTypeToTransformTo(C, VT);
6561       assert(NVT.bitsGE(VT));
6562 
6563       bool isDereferenceable =
6564         SrcPtrInfo.getWithOffset(SrcOff).isDereferenceable(VTSize, C, DL);
6565       MachineMemOperand::Flags SrcMMOFlags = MMOFlags;
6566       if (isDereferenceable)
6567         SrcMMOFlags |= MachineMemOperand::MODereferenceable;
6568 
6569       Value = DAG.getExtLoad(
6570           ISD::EXTLOAD, dl, NVT, Chain,
6571           DAG.getMemBasePlusOffset(Src, TypeSize::Fixed(SrcOff), dl),
6572           SrcPtrInfo.getWithOffset(SrcOff), VT,
6573           commonAlignment(*SrcAlign, SrcOff), SrcMMOFlags, NewAAInfo);
6574       OutLoadChains.push_back(Value.getValue(1));
6575 
6576       Store = DAG.getTruncStore(
6577           Chain, dl, Value,
6578           DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl),
6579           DstPtrInfo.getWithOffset(DstOff), VT, Alignment, MMOFlags, NewAAInfo);
6580       OutStoreChains.push_back(Store);
6581     }
6582     SrcOff += VTSize;
6583     DstOff += VTSize;
6584     Size -= VTSize;
6585   }
6586 
6587   unsigned GluedLdStLimit = MaxLdStGlue == 0 ?
6588                                 TLI.getMaxGluedStoresPerMemcpy() : MaxLdStGlue;
6589   unsigned NumLdStInMemcpy = OutStoreChains.size();
6590 
6591   if (NumLdStInMemcpy) {
6592     // It may be that memcpy might be converted to memset if it's memcpy
6593     // of constants. In such a case, we won't have loads and stores, but
6594     // just stores. In the absence of loads, there is nothing to gang up.
6595     if ((GluedLdStLimit <= 1) || !EnableMemCpyDAGOpt) {
6596       // If target does not care, just leave as it.
6597       for (unsigned i = 0; i < NumLdStInMemcpy; ++i) {
6598         OutChains.push_back(OutLoadChains[i]);
6599         OutChains.push_back(OutStoreChains[i]);
6600       }
6601     } else {
6602       // Ld/St less than/equal limit set by target.
6603       if (NumLdStInMemcpy <= GluedLdStLimit) {
6604           chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, 0,
6605                                         NumLdStInMemcpy, OutLoadChains,
6606                                         OutStoreChains);
6607       } else {
6608         unsigned NumberLdChain =  NumLdStInMemcpy / GluedLdStLimit;
6609         unsigned RemainingLdStInMemcpy = NumLdStInMemcpy % GluedLdStLimit;
6610         unsigned GlueIter = 0;
6611 
6612         for (unsigned cnt = 0; cnt < NumberLdChain; ++cnt) {
6613           unsigned IndexFrom = NumLdStInMemcpy - GlueIter - GluedLdStLimit;
6614           unsigned IndexTo   = NumLdStInMemcpy - GlueIter;
6615 
6616           chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, IndexFrom, IndexTo,
6617                                        OutLoadChains, OutStoreChains);
6618           GlueIter += GluedLdStLimit;
6619         }
6620 
6621         // Residual ld/st.
6622         if (RemainingLdStInMemcpy) {
6623           chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, 0,
6624                                         RemainingLdStInMemcpy, OutLoadChains,
6625                                         OutStoreChains);
6626         }
6627       }
6628     }
6629   }
6630   return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
6631 }
6632 
6633 static SDValue getMemmoveLoadsAndStores(SelectionDAG &DAG, const SDLoc &dl,
6634                                         SDValue Chain, SDValue Dst, SDValue Src,
6635                                         uint64_t Size, Align Alignment,
6636                                         bool isVol, bool AlwaysInline,
6637                                         MachinePointerInfo DstPtrInfo,
6638                                         MachinePointerInfo SrcPtrInfo,
6639                                         const AAMDNodes &AAInfo) {
6640   // Turn a memmove of undef to nop.
6641   // FIXME: We need to honor volatile even is Src is undef.
6642   if (Src.isUndef())
6643     return Chain;
6644 
6645   // Expand memmove to a series of load and store ops if the size operand falls
6646   // below a certain threshold.
6647   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6648   const DataLayout &DL = DAG.getDataLayout();
6649   LLVMContext &C = *DAG.getContext();
6650   std::vector<EVT> MemOps;
6651   bool DstAlignCanChange = false;
6652   MachineFunction &MF = DAG.getMachineFunction();
6653   MachineFrameInfo &MFI = MF.getFrameInfo();
6654   bool OptSize = shouldLowerMemFuncForSize(MF, DAG);
6655   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
6656   if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
6657     DstAlignCanChange = true;
6658   MaybeAlign SrcAlign = DAG.InferPtrAlign(Src);
6659   if (!SrcAlign || Alignment > *SrcAlign)
6660     SrcAlign = Alignment;
6661   assert(SrcAlign && "SrcAlign must be set");
6662   unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemmove(OptSize);
6663   if (!TLI.findOptimalMemOpLowering(
6664           MemOps, Limit,
6665           MemOp::Copy(Size, DstAlignCanChange, Alignment, *SrcAlign,
6666                       /*IsVolatile*/ true),
6667           DstPtrInfo.getAddrSpace(), SrcPtrInfo.getAddrSpace(),
6668           MF.getFunction().getAttributes()))
6669     return SDValue();
6670 
6671   if (DstAlignCanChange) {
6672     Type *Ty = MemOps[0].getTypeForEVT(C);
6673     Align NewAlign = DL.getABITypeAlign(Ty);
6674     if (NewAlign > Alignment) {
6675       // Give the stack frame object a larger alignment if needed.
6676       if (MFI.getObjectAlign(FI->getIndex()) < NewAlign)
6677         MFI.setObjectAlignment(FI->getIndex(), NewAlign);
6678       Alignment = NewAlign;
6679     }
6680   }
6681 
6682   // Prepare AAInfo for loads/stores after lowering this memmove.
6683   AAMDNodes NewAAInfo = AAInfo;
6684   NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr;
6685 
6686   MachineMemOperand::Flags MMOFlags =
6687       isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone;
6688   uint64_t SrcOff = 0, DstOff = 0;
6689   SmallVector<SDValue, 8> LoadValues;
6690   SmallVector<SDValue, 8> LoadChains;
6691   SmallVector<SDValue, 8> OutChains;
6692   unsigned NumMemOps = MemOps.size();
6693   for (unsigned i = 0; i < NumMemOps; i++) {
6694     EVT VT = MemOps[i];
6695     unsigned VTSize = VT.getSizeInBits() / 8;
6696     SDValue Value;
6697 
6698     bool isDereferenceable =
6699       SrcPtrInfo.getWithOffset(SrcOff).isDereferenceable(VTSize, C, DL);
6700     MachineMemOperand::Flags SrcMMOFlags = MMOFlags;
6701     if (isDereferenceable)
6702       SrcMMOFlags |= MachineMemOperand::MODereferenceable;
6703 
6704     Value = DAG.getLoad(
6705         VT, dl, Chain,
6706         DAG.getMemBasePlusOffset(Src, TypeSize::Fixed(SrcOff), dl),
6707         SrcPtrInfo.getWithOffset(SrcOff), *SrcAlign, SrcMMOFlags, NewAAInfo);
6708     LoadValues.push_back(Value);
6709     LoadChains.push_back(Value.getValue(1));
6710     SrcOff += VTSize;
6711   }
6712   Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
6713   OutChains.clear();
6714   for (unsigned i = 0; i < NumMemOps; i++) {
6715     EVT VT = MemOps[i];
6716     unsigned VTSize = VT.getSizeInBits() / 8;
6717     SDValue Store;
6718 
6719     Store = DAG.getStore(
6720         Chain, dl, LoadValues[i],
6721         DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl),
6722         DstPtrInfo.getWithOffset(DstOff), Alignment, MMOFlags, NewAAInfo);
6723     OutChains.push_back(Store);
6724     DstOff += VTSize;
6725   }
6726 
6727   return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
6728 }
6729 
6730 /// Lower the call to 'memset' intrinsic function into a series of store
6731 /// operations.
6732 ///
6733 /// \param DAG Selection DAG where lowered code is placed.
6734 /// \param dl Link to corresponding IR location.
6735 /// \param Chain Control flow dependency.
6736 /// \param Dst Pointer to destination memory location.
6737 /// \param Src Value of byte to write into the memory.
6738 /// \param Size Number of bytes to write.
6739 /// \param Alignment Alignment of the destination in bytes.
6740 /// \param isVol True if destination is volatile.
6741 /// \param DstPtrInfo IR information on the memory pointer.
6742 /// \returns New head in the control flow, if lowering was successful, empty
6743 /// SDValue otherwise.
6744 ///
6745 /// The function tries to replace 'llvm.memset' intrinsic with several store
6746 /// operations and value calculation code. This is usually profitable for small
6747 /// memory size.
6748 static SDValue getMemsetStores(SelectionDAG &DAG, const SDLoc &dl,
6749                                SDValue Chain, SDValue Dst, SDValue Src,
6750                                uint64_t Size, Align Alignment, bool isVol,
6751                                MachinePointerInfo DstPtrInfo,
6752                                const AAMDNodes &AAInfo) {
6753   // Turn a memset of undef to nop.
6754   // FIXME: We need to honor volatile even is Src is undef.
6755   if (Src.isUndef())
6756     return Chain;
6757 
6758   // Expand memset to a series of load/store ops if the size operand
6759   // falls below a certain threshold.
6760   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6761   std::vector<EVT> MemOps;
6762   bool DstAlignCanChange = false;
6763   MachineFunction &MF = DAG.getMachineFunction();
6764   MachineFrameInfo &MFI = MF.getFrameInfo();
6765   bool OptSize = shouldLowerMemFuncForSize(MF, DAG);
6766   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
6767   if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
6768     DstAlignCanChange = true;
6769   bool IsZeroVal =
6770       isa<ConstantSDNode>(Src) && cast<ConstantSDNode>(Src)->isZero();
6771   if (!TLI.findOptimalMemOpLowering(
6772           MemOps, TLI.getMaxStoresPerMemset(OptSize),
6773           MemOp::Set(Size, DstAlignCanChange, Alignment, IsZeroVal, isVol),
6774           DstPtrInfo.getAddrSpace(), ~0u, MF.getFunction().getAttributes()))
6775     return SDValue();
6776 
6777   if (DstAlignCanChange) {
6778     Type *Ty = MemOps[0].getTypeForEVT(*DAG.getContext());
6779     Align NewAlign = DAG.getDataLayout().getABITypeAlign(Ty);
6780     if (NewAlign > Alignment) {
6781       // Give the stack frame object a larger alignment if needed.
6782       if (MFI.getObjectAlign(FI->getIndex()) < NewAlign)
6783         MFI.setObjectAlignment(FI->getIndex(), NewAlign);
6784       Alignment = NewAlign;
6785     }
6786   }
6787 
6788   SmallVector<SDValue, 8> OutChains;
6789   uint64_t DstOff = 0;
6790   unsigned NumMemOps = MemOps.size();
6791 
6792   // Find the largest store and generate the bit pattern for it.
6793   EVT LargestVT = MemOps[0];
6794   for (unsigned i = 1; i < NumMemOps; i++)
6795     if (MemOps[i].bitsGT(LargestVT))
6796       LargestVT = MemOps[i];
6797   SDValue MemSetValue = getMemsetValue(Src, LargestVT, DAG, dl);
6798 
6799   // Prepare AAInfo for loads/stores after lowering this memset.
6800   AAMDNodes NewAAInfo = AAInfo;
6801   NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr;
6802 
6803   for (unsigned i = 0; i < NumMemOps; i++) {
6804     EVT VT = MemOps[i];
6805     unsigned VTSize = VT.getSizeInBits() / 8;
6806     if (VTSize > Size) {
6807       // Issuing an unaligned load / store pair  that overlaps with the previous
6808       // pair. Adjust the offset accordingly.
6809       assert(i == NumMemOps-1 && i != 0);
6810       DstOff -= VTSize - Size;
6811     }
6812 
6813     // If this store is smaller than the largest store see whether we can get
6814     // the smaller value for free with a truncate.
6815     SDValue Value = MemSetValue;
6816     if (VT.bitsLT(LargestVT)) {
6817       if (!LargestVT.isVector() && !VT.isVector() &&
6818           TLI.isTruncateFree(LargestVT, VT))
6819         Value = DAG.getNode(ISD::TRUNCATE, dl, VT, MemSetValue);
6820       else
6821         Value = getMemsetValue(Src, VT, DAG, dl);
6822     }
6823     assert(Value.getValueType() == VT && "Value with wrong type.");
6824     SDValue Store = DAG.getStore(
6825         Chain, dl, Value,
6826         DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl),
6827         DstPtrInfo.getWithOffset(DstOff), Alignment,
6828         isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone,
6829         NewAAInfo);
6830     OutChains.push_back(Store);
6831     DstOff += VT.getSizeInBits() / 8;
6832     Size -= VTSize;
6833   }
6834 
6835   return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
6836 }
6837 
6838 static void checkAddrSpaceIsValidForLibcall(const TargetLowering *TLI,
6839                                             unsigned AS) {
6840   // Lowering memcpy / memset / memmove intrinsics to calls is only valid if all
6841   // pointer operands can be losslessly bitcasted to pointers of address space 0
6842   if (AS != 0 && !TLI->getTargetMachine().isNoopAddrSpaceCast(AS, 0)) {
6843     report_fatal_error("cannot lower memory intrinsic in address space " +
6844                        Twine(AS));
6845   }
6846 }
6847 
6848 SDValue SelectionDAG::getMemcpy(SDValue Chain, const SDLoc &dl, SDValue Dst,
6849                                 SDValue Src, SDValue Size, Align Alignment,
6850                                 bool isVol, bool AlwaysInline, bool isTailCall,
6851                                 MachinePointerInfo DstPtrInfo,
6852                                 MachinePointerInfo SrcPtrInfo,
6853                                 const AAMDNodes &AAInfo) {
6854   // Check to see if we should lower the memcpy to loads and stores first.
6855   // For cases within the target-specified limits, this is the best choice.
6856   ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
6857   if (ConstantSize) {
6858     // Memcpy with size zero? Just return the original chain.
6859     if (ConstantSize->isZero())
6860       return Chain;
6861 
6862     SDValue Result = getMemcpyLoadsAndStores(
6863         *this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), Alignment,
6864         isVol, false, DstPtrInfo, SrcPtrInfo, AAInfo);
6865     if (Result.getNode())
6866       return Result;
6867   }
6868 
6869   // Then check to see if we should lower the memcpy with target-specific
6870   // code. If the target chooses to do this, this is the next best.
6871   if (TSI) {
6872     SDValue Result = TSI->EmitTargetCodeForMemcpy(
6873         *this, dl, Chain, Dst, Src, Size, Alignment, isVol, AlwaysInline,
6874         DstPtrInfo, SrcPtrInfo);
6875     if (Result.getNode())
6876       return Result;
6877   }
6878 
6879   // If we really need inline code and the target declined to provide it,
6880   // use a (potentially long) sequence of loads and stores.
6881   if (AlwaysInline) {
6882     assert(ConstantSize && "AlwaysInline requires a constant size!");
6883     return getMemcpyLoadsAndStores(*this, dl, Chain, Dst, Src,
6884                                    ConstantSize->getZExtValue(), Alignment,
6885                                    isVol, true, DstPtrInfo, SrcPtrInfo, AAInfo);
6886   }
6887 
6888   checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace());
6889   checkAddrSpaceIsValidForLibcall(TLI, SrcPtrInfo.getAddrSpace());
6890 
6891   // FIXME: If the memcpy is volatile (isVol), lowering it to a plain libc
6892   // memcpy is not guaranteed to be safe. libc memcpys aren't required to
6893   // respect volatile, so they may do things like read or write memory
6894   // beyond the given memory regions. But fixing this isn't easy, and most
6895   // people don't care.
6896 
6897   // Emit a library call.
6898   TargetLowering::ArgListTy Args;
6899   TargetLowering::ArgListEntry Entry;
6900   Entry.Ty = Type::getInt8PtrTy(*getContext());
6901   Entry.Node = Dst; Args.push_back(Entry);
6902   Entry.Node = Src; Args.push_back(Entry);
6903 
6904   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
6905   Entry.Node = Size; Args.push_back(Entry);
6906   // FIXME: pass in SDLoc
6907   TargetLowering::CallLoweringInfo CLI(*this);
6908   CLI.setDebugLoc(dl)
6909       .setChain(Chain)
6910       .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMCPY),
6911                     Dst.getValueType().getTypeForEVT(*getContext()),
6912                     getExternalSymbol(TLI->getLibcallName(RTLIB::MEMCPY),
6913                                       TLI->getPointerTy(getDataLayout())),
6914                     std::move(Args))
6915       .setDiscardResult()
6916       .setTailCall(isTailCall);
6917 
6918   std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
6919   return CallResult.second;
6920 }
6921 
6922 SDValue SelectionDAG::getAtomicMemcpy(SDValue Chain, const SDLoc &dl,
6923                                       SDValue Dst, unsigned DstAlign,
6924                                       SDValue Src, unsigned SrcAlign,
6925                                       SDValue Size, Type *SizeTy,
6926                                       unsigned ElemSz, bool isTailCall,
6927                                       MachinePointerInfo DstPtrInfo,
6928                                       MachinePointerInfo SrcPtrInfo) {
6929   // Emit a library call.
6930   TargetLowering::ArgListTy Args;
6931   TargetLowering::ArgListEntry Entry;
6932   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
6933   Entry.Node = Dst;
6934   Args.push_back(Entry);
6935 
6936   Entry.Node = Src;
6937   Args.push_back(Entry);
6938 
6939   Entry.Ty = SizeTy;
6940   Entry.Node = Size;
6941   Args.push_back(Entry);
6942 
6943   RTLIB::Libcall LibraryCall =
6944       RTLIB::getMEMCPY_ELEMENT_UNORDERED_ATOMIC(ElemSz);
6945   if (LibraryCall == RTLIB::UNKNOWN_LIBCALL)
6946     report_fatal_error("Unsupported element size");
6947 
6948   TargetLowering::CallLoweringInfo CLI(*this);
6949   CLI.setDebugLoc(dl)
6950       .setChain(Chain)
6951       .setLibCallee(TLI->getLibcallCallingConv(LibraryCall),
6952                     Type::getVoidTy(*getContext()),
6953                     getExternalSymbol(TLI->getLibcallName(LibraryCall),
6954                                       TLI->getPointerTy(getDataLayout())),
6955                     std::move(Args))
6956       .setDiscardResult()
6957       .setTailCall(isTailCall);
6958 
6959   std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
6960   return CallResult.second;
6961 }
6962 
6963 SDValue SelectionDAG::getMemmove(SDValue Chain, const SDLoc &dl, SDValue Dst,
6964                                  SDValue Src, SDValue Size, Align Alignment,
6965                                  bool isVol, bool isTailCall,
6966                                  MachinePointerInfo DstPtrInfo,
6967                                  MachinePointerInfo SrcPtrInfo,
6968                                  const AAMDNodes &AAInfo) {
6969   // Check to see if we should lower the memmove to loads and stores first.
6970   // For cases within the target-specified limits, this is the best choice.
6971   ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
6972   if (ConstantSize) {
6973     // Memmove with size zero? Just return the original chain.
6974     if (ConstantSize->isZero())
6975       return Chain;
6976 
6977     SDValue Result = getMemmoveLoadsAndStores(
6978         *this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), Alignment,
6979         isVol, false, DstPtrInfo, SrcPtrInfo, AAInfo);
6980     if (Result.getNode())
6981       return Result;
6982   }
6983 
6984   // Then check to see if we should lower the memmove with target-specific
6985   // code. If the target chooses to do this, this is the next best.
6986   if (TSI) {
6987     SDValue Result =
6988         TSI->EmitTargetCodeForMemmove(*this, dl, Chain, Dst, Src, Size,
6989                                       Alignment, isVol, DstPtrInfo, SrcPtrInfo);
6990     if (Result.getNode())
6991       return Result;
6992   }
6993 
6994   checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace());
6995   checkAddrSpaceIsValidForLibcall(TLI, SrcPtrInfo.getAddrSpace());
6996 
6997   // FIXME: If the memmove is volatile, lowering it to plain libc memmove may
6998   // not be safe.  See memcpy above for more details.
6999 
7000   // Emit a library call.
7001   TargetLowering::ArgListTy Args;
7002   TargetLowering::ArgListEntry Entry;
7003   Entry.Ty = Type::getInt8PtrTy(*getContext());
7004   Entry.Node = Dst; Args.push_back(Entry);
7005   Entry.Node = Src; Args.push_back(Entry);
7006 
7007   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
7008   Entry.Node = Size; Args.push_back(Entry);
7009   // FIXME:  pass in SDLoc
7010   TargetLowering::CallLoweringInfo CLI(*this);
7011   CLI.setDebugLoc(dl)
7012       .setChain(Chain)
7013       .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMMOVE),
7014                     Dst.getValueType().getTypeForEVT(*getContext()),
7015                     getExternalSymbol(TLI->getLibcallName(RTLIB::MEMMOVE),
7016                                       TLI->getPointerTy(getDataLayout())),
7017                     std::move(Args))
7018       .setDiscardResult()
7019       .setTailCall(isTailCall);
7020 
7021   std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
7022   return CallResult.second;
7023 }
7024 
7025 SDValue SelectionDAG::getAtomicMemmove(SDValue Chain, const SDLoc &dl,
7026                                        SDValue Dst, unsigned DstAlign,
7027                                        SDValue Src, unsigned SrcAlign,
7028                                        SDValue Size, Type *SizeTy,
7029                                        unsigned ElemSz, bool isTailCall,
7030                                        MachinePointerInfo DstPtrInfo,
7031                                        MachinePointerInfo SrcPtrInfo) {
7032   // Emit a library call.
7033   TargetLowering::ArgListTy Args;
7034   TargetLowering::ArgListEntry Entry;
7035   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
7036   Entry.Node = Dst;
7037   Args.push_back(Entry);
7038 
7039   Entry.Node = Src;
7040   Args.push_back(Entry);
7041 
7042   Entry.Ty = SizeTy;
7043   Entry.Node = Size;
7044   Args.push_back(Entry);
7045 
7046   RTLIB::Libcall LibraryCall =
7047       RTLIB::getMEMMOVE_ELEMENT_UNORDERED_ATOMIC(ElemSz);
7048   if (LibraryCall == RTLIB::UNKNOWN_LIBCALL)
7049     report_fatal_error("Unsupported element size");
7050 
7051   TargetLowering::CallLoweringInfo CLI(*this);
7052   CLI.setDebugLoc(dl)
7053       .setChain(Chain)
7054       .setLibCallee(TLI->getLibcallCallingConv(LibraryCall),
7055                     Type::getVoidTy(*getContext()),
7056                     getExternalSymbol(TLI->getLibcallName(LibraryCall),
7057                                       TLI->getPointerTy(getDataLayout())),
7058                     std::move(Args))
7059       .setDiscardResult()
7060       .setTailCall(isTailCall);
7061 
7062   std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
7063   return CallResult.second;
7064 }
7065 
7066 SDValue SelectionDAG::getMemset(SDValue Chain, const SDLoc &dl, SDValue Dst,
7067                                 SDValue Src, SDValue Size, Align Alignment,
7068                                 bool isVol, bool isTailCall,
7069                                 MachinePointerInfo DstPtrInfo,
7070                                 const AAMDNodes &AAInfo) {
7071   // Check to see if we should lower the memset to stores first.
7072   // For cases within the target-specified limits, this is the best choice.
7073   ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
7074   if (ConstantSize) {
7075     // Memset with size zero? Just return the original chain.
7076     if (ConstantSize->isZero())
7077       return Chain;
7078 
7079     SDValue Result = getMemsetStores(*this, dl, Chain, Dst, Src,
7080                                      ConstantSize->getZExtValue(), Alignment,
7081                                      isVol, DstPtrInfo, AAInfo);
7082 
7083     if (Result.getNode())
7084       return Result;
7085   }
7086 
7087   // Then check to see if we should lower the memset with target-specific
7088   // code. If the target chooses to do this, this is the next best.
7089   if (TSI) {
7090     SDValue Result = TSI->EmitTargetCodeForMemset(
7091         *this, dl, Chain, Dst, Src, Size, Alignment, isVol, DstPtrInfo);
7092     if (Result.getNode())
7093       return Result;
7094   }
7095 
7096   checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace());
7097 
7098   // Emit a library call.
7099   TargetLowering::ArgListTy Args;
7100   TargetLowering::ArgListEntry Entry;
7101   Entry.Node = Dst; Entry.Ty = Type::getInt8PtrTy(*getContext());
7102   Args.push_back(Entry);
7103   Entry.Node = Src;
7104   Entry.Ty = Src.getValueType().getTypeForEVT(*getContext());
7105   Args.push_back(Entry);
7106   Entry.Node = Size;
7107   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
7108   Args.push_back(Entry);
7109 
7110   // FIXME: pass in SDLoc
7111   TargetLowering::CallLoweringInfo CLI(*this);
7112   CLI.setDebugLoc(dl)
7113       .setChain(Chain)
7114       .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMSET),
7115                     Dst.getValueType().getTypeForEVT(*getContext()),
7116                     getExternalSymbol(TLI->getLibcallName(RTLIB::MEMSET),
7117                                       TLI->getPointerTy(getDataLayout())),
7118                     std::move(Args))
7119       .setDiscardResult()
7120       .setTailCall(isTailCall);
7121 
7122   std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
7123   return CallResult.second;
7124 }
7125 
7126 SDValue SelectionDAG::getAtomicMemset(SDValue Chain, const SDLoc &dl,
7127                                       SDValue Dst, unsigned DstAlign,
7128                                       SDValue Value, SDValue Size, Type *SizeTy,
7129                                       unsigned ElemSz, bool isTailCall,
7130                                       MachinePointerInfo DstPtrInfo) {
7131   // Emit a library call.
7132   TargetLowering::ArgListTy Args;
7133   TargetLowering::ArgListEntry Entry;
7134   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
7135   Entry.Node = Dst;
7136   Args.push_back(Entry);
7137 
7138   Entry.Ty = Type::getInt8Ty(*getContext());
7139   Entry.Node = Value;
7140   Args.push_back(Entry);
7141 
7142   Entry.Ty = SizeTy;
7143   Entry.Node = Size;
7144   Args.push_back(Entry);
7145 
7146   RTLIB::Libcall LibraryCall =
7147       RTLIB::getMEMSET_ELEMENT_UNORDERED_ATOMIC(ElemSz);
7148   if (LibraryCall == RTLIB::UNKNOWN_LIBCALL)
7149     report_fatal_error("Unsupported element size");
7150 
7151   TargetLowering::CallLoweringInfo CLI(*this);
7152   CLI.setDebugLoc(dl)
7153       .setChain(Chain)
7154       .setLibCallee(TLI->getLibcallCallingConv(LibraryCall),
7155                     Type::getVoidTy(*getContext()),
7156                     getExternalSymbol(TLI->getLibcallName(LibraryCall),
7157                                       TLI->getPointerTy(getDataLayout())),
7158                     std::move(Args))
7159       .setDiscardResult()
7160       .setTailCall(isTailCall);
7161 
7162   std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
7163   return CallResult.second;
7164 }
7165 
7166 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
7167                                 SDVTList VTList, ArrayRef<SDValue> Ops,
7168                                 MachineMemOperand *MMO) {
7169   FoldingSetNodeID ID;
7170   ID.AddInteger(MemVT.getRawBits());
7171   AddNodeIDNode(ID, Opcode, VTList, Ops);
7172   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7173   void* IP = nullptr;
7174   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7175     cast<AtomicSDNode>(E)->refineAlignment(MMO);
7176     return SDValue(E, 0);
7177   }
7178 
7179   auto *N = newSDNode<AtomicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
7180                                     VTList, MemVT, MMO);
7181   createOperands(N, Ops);
7182 
7183   CSEMap.InsertNode(N, IP);
7184   InsertNode(N);
7185   return SDValue(N, 0);
7186 }
7187 
7188 SDValue SelectionDAG::getAtomicCmpSwap(unsigned Opcode, const SDLoc &dl,
7189                                        EVT MemVT, SDVTList VTs, SDValue Chain,
7190                                        SDValue Ptr, SDValue Cmp, SDValue Swp,
7191                                        MachineMemOperand *MMO) {
7192   assert(Opcode == ISD::ATOMIC_CMP_SWAP ||
7193          Opcode == ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS);
7194   assert(Cmp.getValueType() == Swp.getValueType() && "Invalid Atomic Op Types");
7195 
7196   SDValue Ops[] = {Chain, Ptr, Cmp, Swp};
7197   return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
7198 }
7199 
7200 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
7201                                 SDValue Chain, SDValue Ptr, SDValue Val,
7202                                 MachineMemOperand *MMO) {
7203   assert((Opcode == ISD::ATOMIC_LOAD_ADD ||
7204           Opcode == ISD::ATOMIC_LOAD_SUB ||
7205           Opcode == ISD::ATOMIC_LOAD_AND ||
7206           Opcode == ISD::ATOMIC_LOAD_CLR ||
7207           Opcode == ISD::ATOMIC_LOAD_OR ||
7208           Opcode == ISD::ATOMIC_LOAD_XOR ||
7209           Opcode == ISD::ATOMIC_LOAD_NAND ||
7210           Opcode == ISD::ATOMIC_LOAD_MIN ||
7211           Opcode == ISD::ATOMIC_LOAD_MAX ||
7212           Opcode == ISD::ATOMIC_LOAD_UMIN ||
7213           Opcode == ISD::ATOMIC_LOAD_UMAX ||
7214           Opcode == ISD::ATOMIC_LOAD_FADD ||
7215           Opcode == ISD::ATOMIC_LOAD_FSUB ||
7216           Opcode == ISD::ATOMIC_SWAP ||
7217           Opcode == ISD::ATOMIC_STORE) &&
7218          "Invalid Atomic Op");
7219 
7220   EVT VT = Val.getValueType();
7221 
7222   SDVTList VTs = Opcode == ISD::ATOMIC_STORE ? getVTList(MVT::Other) :
7223                                                getVTList(VT, MVT::Other);
7224   SDValue Ops[] = {Chain, Ptr, Val};
7225   return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
7226 }
7227 
7228 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
7229                                 EVT VT, SDValue Chain, SDValue Ptr,
7230                                 MachineMemOperand *MMO) {
7231   assert(Opcode == ISD::ATOMIC_LOAD && "Invalid Atomic Op");
7232 
7233   SDVTList VTs = getVTList(VT, MVT::Other);
7234   SDValue Ops[] = {Chain, Ptr};
7235   return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
7236 }
7237 
7238 /// getMergeValues - Create a MERGE_VALUES node from the given operands.
7239 SDValue SelectionDAG::getMergeValues(ArrayRef<SDValue> Ops, const SDLoc &dl) {
7240   if (Ops.size() == 1)
7241     return Ops[0];
7242 
7243   SmallVector<EVT, 4> VTs;
7244   VTs.reserve(Ops.size());
7245   for (const SDValue &Op : Ops)
7246     VTs.push_back(Op.getValueType());
7247   return getNode(ISD::MERGE_VALUES, dl, getVTList(VTs), Ops);
7248 }
7249 
7250 SDValue SelectionDAG::getMemIntrinsicNode(
7251     unsigned Opcode, const SDLoc &dl, SDVTList VTList, ArrayRef<SDValue> Ops,
7252     EVT MemVT, MachinePointerInfo PtrInfo, Align Alignment,
7253     MachineMemOperand::Flags Flags, uint64_t Size, const AAMDNodes &AAInfo) {
7254   if (!Size && MemVT.isScalableVector())
7255     Size = MemoryLocation::UnknownSize;
7256   else if (!Size)
7257     Size = MemVT.getStoreSize();
7258 
7259   MachineFunction &MF = getMachineFunction();
7260   MachineMemOperand *MMO =
7261       MF.getMachineMemOperand(PtrInfo, Flags, Size, Alignment, AAInfo);
7262 
7263   return getMemIntrinsicNode(Opcode, dl, VTList, Ops, MemVT, MMO);
7264 }
7265 
7266 SDValue SelectionDAG::getMemIntrinsicNode(unsigned Opcode, const SDLoc &dl,
7267                                           SDVTList VTList,
7268                                           ArrayRef<SDValue> Ops, EVT MemVT,
7269                                           MachineMemOperand *MMO) {
7270   assert((Opcode == ISD::INTRINSIC_VOID ||
7271           Opcode == ISD::INTRINSIC_W_CHAIN ||
7272           Opcode == ISD::PREFETCH ||
7273           ((int)Opcode <= std::numeric_limits<int>::max() &&
7274            (int)Opcode >= ISD::FIRST_TARGET_MEMORY_OPCODE)) &&
7275          "Opcode is not a memory-accessing opcode!");
7276 
7277   // Memoize the node unless it returns a flag.
7278   MemIntrinsicSDNode *N;
7279   if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) {
7280     FoldingSetNodeID ID;
7281     AddNodeIDNode(ID, Opcode, VTList, Ops);
7282     ID.AddInteger(getSyntheticNodeSubclassData<MemIntrinsicSDNode>(
7283         Opcode, dl.getIROrder(), VTList, MemVT, MMO));
7284     ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7285     void *IP = nullptr;
7286     if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7287       cast<MemIntrinsicSDNode>(E)->refineAlignment(MMO);
7288       return SDValue(E, 0);
7289     }
7290 
7291     N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
7292                                       VTList, MemVT, MMO);
7293     createOperands(N, Ops);
7294 
7295   CSEMap.InsertNode(N, IP);
7296   } else {
7297     N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
7298                                       VTList, MemVT, MMO);
7299     createOperands(N, Ops);
7300   }
7301   InsertNode(N);
7302   SDValue V(N, 0);
7303   NewSDValueDbgMsg(V, "Creating new node: ", this);
7304   return V;
7305 }
7306 
7307 SDValue SelectionDAG::getLifetimeNode(bool IsStart, const SDLoc &dl,
7308                                       SDValue Chain, int FrameIndex,
7309                                       int64_t Size, int64_t Offset) {
7310   const unsigned Opcode = IsStart ? ISD::LIFETIME_START : ISD::LIFETIME_END;
7311   const auto VTs = getVTList(MVT::Other);
7312   SDValue Ops[2] = {
7313       Chain,
7314       getFrameIndex(FrameIndex,
7315                     getTargetLoweringInfo().getFrameIndexTy(getDataLayout()),
7316                     true)};
7317 
7318   FoldingSetNodeID ID;
7319   AddNodeIDNode(ID, Opcode, VTs, Ops);
7320   ID.AddInteger(FrameIndex);
7321   ID.AddInteger(Size);
7322   ID.AddInteger(Offset);
7323   void *IP = nullptr;
7324   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
7325     return SDValue(E, 0);
7326 
7327   LifetimeSDNode *N = newSDNode<LifetimeSDNode>(
7328       Opcode, dl.getIROrder(), dl.getDebugLoc(), VTs, Size, Offset);
7329   createOperands(N, Ops);
7330   CSEMap.InsertNode(N, IP);
7331   InsertNode(N);
7332   SDValue V(N, 0);
7333   NewSDValueDbgMsg(V, "Creating new node: ", this);
7334   return V;
7335 }
7336 
7337 SDValue SelectionDAG::getPseudoProbeNode(const SDLoc &Dl, SDValue Chain,
7338                                          uint64_t Guid, uint64_t Index,
7339                                          uint32_t Attr) {
7340   const unsigned Opcode = ISD::PSEUDO_PROBE;
7341   const auto VTs = getVTList(MVT::Other);
7342   SDValue Ops[] = {Chain};
7343   FoldingSetNodeID ID;
7344   AddNodeIDNode(ID, Opcode, VTs, Ops);
7345   ID.AddInteger(Guid);
7346   ID.AddInteger(Index);
7347   void *IP = nullptr;
7348   if (SDNode *E = FindNodeOrInsertPos(ID, Dl, IP))
7349     return SDValue(E, 0);
7350 
7351   auto *N = newSDNode<PseudoProbeSDNode>(
7352       Opcode, Dl.getIROrder(), Dl.getDebugLoc(), VTs, Guid, Index, Attr);
7353   createOperands(N, Ops);
7354   CSEMap.InsertNode(N, IP);
7355   InsertNode(N);
7356   SDValue V(N, 0);
7357   NewSDValueDbgMsg(V, "Creating new node: ", this);
7358   return V;
7359 }
7360 
7361 /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a
7362 /// MachinePointerInfo record from it.  This is particularly useful because the
7363 /// code generator has many cases where it doesn't bother passing in a
7364 /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst".
7365 static MachinePointerInfo InferPointerInfo(const MachinePointerInfo &Info,
7366                                            SelectionDAG &DAG, SDValue Ptr,
7367                                            int64_t Offset = 0) {
7368   // If this is FI+Offset, we can model it.
7369   if (const FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr))
7370     return MachinePointerInfo::getFixedStack(DAG.getMachineFunction(),
7371                                              FI->getIndex(), Offset);
7372 
7373   // If this is (FI+Offset1)+Offset2, we can model it.
7374   if (Ptr.getOpcode() != ISD::ADD ||
7375       !isa<ConstantSDNode>(Ptr.getOperand(1)) ||
7376       !isa<FrameIndexSDNode>(Ptr.getOperand(0)))
7377     return Info;
7378 
7379   int FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
7380   return MachinePointerInfo::getFixedStack(
7381       DAG.getMachineFunction(), FI,
7382       Offset + cast<ConstantSDNode>(Ptr.getOperand(1))->getSExtValue());
7383 }
7384 
7385 /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a
7386 /// MachinePointerInfo record from it.  This is particularly useful because the
7387 /// code generator has many cases where it doesn't bother passing in a
7388 /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst".
7389 static MachinePointerInfo InferPointerInfo(const MachinePointerInfo &Info,
7390                                            SelectionDAG &DAG, SDValue Ptr,
7391                                            SDValue OffsetOp) {
7392   // If the 'Offset' value isn't a constant, we can't handle this.
7393   if (ConstantSDNode *OffsetNode = dyn_cast<ConstantSDNode>(OffsetOp))
7394     return InferPointerInfo(Info, DAG, Ptr, OffsetNode->getSExtValue());
7395   if (OffsetOp.isUndef())
7396     return InferPointerInfo(Info, DAG, Ptr);
7397   return Info;
7398 }
7399 
7400 SDValue SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType,
7401                               EVT VT, const SDLoc &dl, SDValue Chain,
7402                               SDValue Ptr, SDValue Offset,
7403                               MachinePointerInfo PtrInfo, EVT MemVT,
7404                               Align Alignment,
7405                               MachineMemOperand::Flags MMOFlags,
7406                               const AAMDNodes &AAInfo, const MDNode *Ranges) {
7407   assert(Chain.getValueType() == MVT::Other &&
7408         "Invalid chain type");
7409 
7410   MMOFlags |= MachineMemOperand::MOLoad;
7411   assert((MMOFlags & MachineMemOperand::MOStore) == 0);
7412   // If we don't have a PtrInfo, infer the trivial frame index case to simplify
7413   // clients.
7414   if (PtrInfo.V.isNull())
7415     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr, Offset);
7416 
7417   uint64_t Size = MemoryLocation::getSizeOrUnknown(MemVT.getStoreSize());
7418   MachineFunction &MF = getMachineFunction();
7419   MachineMemOperand *MMO = MF.getMachineMemOperand(PtrInfo, MMOFlags, Size,
7420                                                    Alignment, AAInfo, Ranges);
7421   return getLoad(AM, ExtType, VT, dl, Chain, Ptr, Offset, MemVT, MMO);
7422 }
7423 
7424 SDValue SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType,
7425                               EVT VT, const SDLoc &dl, SDValue Chain,
7426                               SDValue Ptr, SDValue Offset, EVT MemVT,
7427                               MachineMemOperand *MMO) {
7428   if (VT == MemVT) {
7429     ExtType = ISD::NON_EXTLOAD;
7430   } else if (ExtType == ISD::NON_EXTLOAD) {
7431     assert(VT == MemVT && "Non-extending load from different memory type!");
7432   } else {
7433     // Extending load.
7434     assert(MemVT.getScalarType().bitsLT(VT.getScalarType()) &&
7435            "Should only be an extending load, not truncating!");
7436     assert(VT.isInteger() == MemVT.isInteger() &&
7437            "Cannot convert from FP to Int or Int -> FP!");
7438     assert(VT.isVector() == MemVT.isVector() &&
7439            "Cannot use an ext load to convert to or from a vector!");
7440     assert((!VT.isVector() ||
7441             VT.getVectorElementCount() == MemVT.getVectorElementCount()) &&
7442            "Cannot use an ext load to change the number of vector elements!");
7443   }
7444 
7445   bool Indexed = AM != ISD::UNINDEXED;
7446   assert((Indexed || Offset.isUndef()) && "Unindexed load with an offset!");
7447 
7448   SDVTList VTs = Indexed ?
7449     getVTList(VT, Ptr.getValueType(), MVT::Other) : getVTList(VT, MVT::Other);
7450   SDValue Ops[] = { Chain, Ptr, Offset };
7451   FoldingSetNodeID ID;
7452   AddNodeIDNode(ID, ISD::LOAD, VTs, Ops);
7453   ID.AddInteger(MemVT.getRawBits());
7454   ID.AddInteger(getSyntheticNodeSubclassData<LoadSDNode>(
7455       dl.getIROrder(), VTs, AM, ExtType, MemVT, MMO));
7456   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7457   void *IP = nullptr;
7458   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7459     cast<LoadSDNode>(E)->refineAlignment(MMO);
7460     return SDValue(E, 0);
7461   }
7462   auto *N = newSDNode<LoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
7463                                   ExtType, MemVT, MMO);
7464   createOperands(N, Ops);
7465 
7466   CSEMap.InsertNode(N, IP);
7467   InsertNode(N);
7468   SDValue V(N, 0);
7469   NewSDValueDbgMsg(V, "Creating new node: ", this);
7470   return V;
7471 }
7472 
7473 SDValue SelectionDAG::getLoad(EVT VT, const SDLoc &dl, SDValue Chain,
7474                               SDValue Ptr, MachinePointerInfo PtrInfo,
7475                               MaybeAlign Alignment,
7476                               MachineMemOperand::Flags MMOFlags,
7477                               const AAMDNodes &AAInfo, const MDNode *Ranges) {
7478   SDValue Undef = getUNDEF(Ptr.getValueType());
7479   return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
7480                  PtrInfo, VT, Alignment, MMOFlags, AAInfo, Ranges);
7481 }
7482 
7483 SDValue SelectionDAG::getLoad(EVT VT, const SDLoc &dl, SDValue Chain,
7484                               SDValue Ptr, MachineMemOperand *MMO) {
7485   SDValue Undef = getUNDEF(Ptr.getValueType());
7486   return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
7487                  VT, MMO);
7488 }
7489 
7490 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl,
7491                                  EVT VT, SDValue Chain, SDValue Ptr,
7492                                  MachinePointerInfo PtrInfo, EVT MemVT,
7493                                  MaybeAlign Alignment,
7494                                  MachineMemOperand::Flags MMOFlags,
7495                                  const AAMDNodes &AAInfo) {
7496   SDValue Undef = getUNDEF(Ptr.getValueType());
7497   return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, PtrInfo,
7498                  MemVT, Alignment, MMOFlags, AAInfo);
7499 }
7500 
7501 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl,
7502                                  EVT VT, SDValue Chain, SDValue Ptr, EVT MemVT,
7503                                  MachineMemOperand *MMO) {
7504   SDValue Undef = getUNDEF(Ptr.getValueType());
7505   return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef,
7506                  MemVT, MMO);
7507 }
7508 
7509 SDValue SelectionDAG::getIndexedLoad(SDValue OrigLoad, const SDLoc &dl,
7510                                      SDValue Base, SDValue Offset,
7511                                      ISD::MemIndexedMode AM) {
7512   LoadSDNode *LD = cast<LoadSDNode>(OrigLoad);
7513   assert(LD->getOffset().isUndef() && "Load is already a indexed load!");
7514   // Don't propagate the invariant or dereferenceable flags.
7515   auto MMOFlags =
7516       LD->getMemOperand()->getFlags() &
7517       ~(MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable);
7518   return getLoad(AM, LD->getExtensionType(), OrigLoad.getValueType(), dl,
7519                  LD->getChain(), Base, Offset, LD->getPointerInfo(),
7520                  LD->getMemoryVT(), LD->getAlign(), MMOFlags, LD->getAAInfo());
7521 }
7522 
7523 SDValue SelectionDAG::getStore(SDValue Chain, const SDLoc &dl, SDValue Val,
7524                                SDValue Ptr, MachinePointerInfo PtrInfo,
7525                                Align Alignment,
7526                                MachineMemOperand::Flags MMOFlags,
7527                                const AAMDNodes &AAInfo) {
7528   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
7529 
7530   MMOFlags |= MachineMemOperand::MOStore;
7531   assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
7532 
7533   if (PtrInfo.V.isNull())
7534     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
7535 
7536   MachineFunction &MF = getMachineFunction();
7537   uint64_t Size =
7538       MemoryLocation::getSizeOrUnknown(Val.getValueType().getStoreSize());
7539   MachineMemOperand *MMO =
7540       MF.getMachineMemOperand(PtrInfo, MMOFlags, Size, Alignment, AAInfo);
7541   return getStore(Chain, dl, Val, Ptr, MMO);
7542 }
7543 
7544 SDValue SelectionDAG::getStore(SDValue Chain, const SDLoc &dl, SDValue Val,
7545                                SDValue Ptr, MachineMemOperand *MMO) {
7546   assert(Chain.getValueType() == MVT::Other &&
7547         "Invalid chain type");
7548   EVT VT = Val.getValueType();
7549   SDVTList VTs = getVTList(MVT::Other);
7550   SDValue Undef = getUNDEF(Ptr.getValueType());
7551   SDValue Ops[] = { Chain, Val, Ptr, Undef };
7552   FoldingSetNodeID ID;
7553   AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
7554   ID.AddInteger(VT.getRawBits());
7555   ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>(
7556       dl.getIROrder(), VTs, ISD::UNINDEXED, false, VT, MMO));
7557   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7558   void *IP = nullptr;
7559   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7560     cast<StoreSDNode>(E)->refineAlignment(MMO);
7561     return SDValue(E, 0);
7562   }
7563   auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
7564                                    ISD::UNINDEXED, false, VT, MMO);
7565   createOperands(N, Ops);
7566 
7567   CSEMap.InsertNode(N, IP);
7568   InsertNode(N);
7569   SDValue V(N, 0);
7570   NewSDValueDbgMsg(V, "Creating new node: ", this);
7571   return V;
7572 }
7573 
7574 SDValue SelectionDAG::getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val,
7575                                     SDValue Ptr, MachinePointerInfo PtrInfo,
7576                                     EVT SVT, Align Alignment,
7577                                     MachineMemOperand::Flags MMOFlags,
7578                                     const AAMDNodes &AAInfo) {
7579   assert(Chain.getValueType() == MVT::Other &&
7580         "Invalid chain type");
7581 
7582   MMOFlags |= MachineMemOperand::MOStore;
7583   assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
7584 
7585   if (PtrInfo.V.isNull())
7586     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
7587 
7588   MachineFunction &MF = getMachineFunction();
7589   MachineMemOperand *MMO = MF.getMachineMemOperand(
7590       PtrInfo, MMOFlags, MemoryLocation::getSizeOrUnknown(SVT.getStoreSize()),
7591       Alignment, AAInfo);
7592   return getTruncStore(Chain, dl, Val, Ptr, SVT, MMO);
7593 }
7594 
7595 SDValue SelectionDAG::getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val,
7596                                     SDValue Ptr, EVT SVT,
7597                                     MachineMemOperand *MMO) {
7598   EVT VT = Val.getValueType();
7599 
7600   assert(Chain.getValueType() == MVT::Other &&
7601         "Invalid chain type");
7602   if (VT == SVT)
7603     return getStore(Chain, dl, Val, Ptr, MMO);
7604 
7605   assert(SVT.getScalarType().bitsLT(VT.getScalarType()) &&
7606          "Should only be a truncating store, not extending!");
7607   assert(VT.isInteger() == SVT.isInteger() &&
7608          "Can't do FP-INT conversion!");
7609   assert(VT.isVector() == SVT.isVector() &&
7610          "Cannot use trunc store to convert to or from a vector!");
7611   assert((!VT.isVector() ||
7612           VT.getVectorElementCount() == SVT.getVectorElementCount()) &&
7613          "Cannot use trunc store to change the number of vector elements!");
7614 
7615   SDVTList VTs = getVTList(MVT::Other);
7616   SDValue Undef = getUNDEF(Ptr.getValueType());
7617   SDValue Ops[] = { Chain, Val, Ptr, Undef };
7618   FoldingSetNodeID ID;
7619   AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
7620   ID.AddInteger(SVT.getRawBits());
7621   ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>(
7622       dl.getIROrder(), VTs, ISD::UNINDEXED, true, SVT, MMO));
7623   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7624   void *IP = nullptr;
7625   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7626     cast<StoreSDNode>(E)->refineAlignment(MMO);
7627     return SDValue(E, 0);
7628   }
7629   auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
7630                                    ISD::UNINDEXED, true, SVT, MMO);
7631   createOperands(N, Ops);
7632 
7633   CSEMap.InsertNode(N, IP);
7634   InsertNode(N);
7635   SDValue V(N, 0);
7636   NewSDValueDbgMsg(V, "Creating new node: ", this);
7637   return V;
7638 }
7639 
7640 SDValue SelectionDAG::getIndexedStore(SDValue OrigStore, const SDLoc &dl,
7641                                       SDValue Base, SDValue Offset,
7642                                       ISD::MemIndexedMode AM) {
7643   StoreSDNode *ST = cast<StoreSDNode>(OrigStore);
7644   assert(ST->getOffset().isUndef() && "Store is already a indexed store!");
7645   SDVTList VTs = getVTList(Base.getValueType(), MVT::Other);
7646   SDValue Ops[] = { ST->getChain(), ST->getValue(), Base, Offset };
7647   FoldingSetNodeID ID;
7648   AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
7649   ID.AddInteger(ST->getMemoryVT().getRawBits());
7650   ID.AddInteger(ST->getRawSubclassData());
7651   ID.AddInteger(ST->getPointerInfo().getAddrSpace());
7652   void *IP = nullptr;
7653   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
7654     return SDValue(E, 0);
7655 
7656   auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
7657                                    ST->isTruncatingStore(), ST->getMemoryVT(),
7658                                    ST->getMemOperand());
7659   createOperands(N, Ops);
7660 
7661   CSEMap.InsertNode(N, IP);
7662   InsertNode(N);
7663   SDValue V(N, 0);
7664   NewSDValueDbgMsg(V, "Creating new node: ", this);
7665   return V;
7666 }
7667 
7668 SDValue SelectionDAG::getLoadVP(
7669     ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, EVT VT, const SDLoc &dl,
7670     SDValue Chain, SDValue Ptr, SDValue Offset, SDValue Mask, SDValue EVL,
7671     MachinePointerInfo PtrInfo, EVT MemVT, Align Alignment,
7672     MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo,
7673     const MDNode *Ranges, bool IsExpanding) {
7674   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
7675 
7676   MMOFlags |= MachineMemOperand::MOLoad;
7677   assert((MMOFlags & MachineMemOperand::MOStore) == 0);
7678   // If we don't have a PtrInfo, infer the trivial frame index case to simplify
7679   // clients.
7680   if (PtrInfo.V.isNull())
7681     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr, Offset);
7682 
7683   uint64_t Size = MemoryLocation::getSizeOrUnknown(MemVT.getStoreSize());
7684   MachineFunction &MF = getMachineFunction();
7685   MachineMemOperand *MMO = MF.getMachineMemOperand(PtrInfo, MMOFlags, Size,
7686                                                    Alignment, AAInfo, Ranges);
7687   return getLoadVP(AM, ExtType, VT, dl, Chain, Ptr, Offset, Mask, EVL, MemVT,
7688                    MMO, IsExpanding);
7689 }
7690 
7691 SDValue SelectionDAG::getLoadVP(ISD::MemIndexedMode AM,
7692                                 ISD::LoadExtType ExtType, EVT VT,
7693                                 const SDLoc &dl, SDValue Chain, SDValue Ptr,
7694                                 SDValue Offset, SDValue Mask, SDValue EVL,
7695                                 EVT MemVT, MachineMemOperand *MMO,
7696                                 bool IsExpanding) {
7697   bool Indexed = AM != ISD::UNINDEXED;
7698   assert((Indexed || Offset.isUndef()) && "Unindexed load with an offset!");
7699 
7700   SDVTList VTs = Indexed ? getVTList(VT, Ptr.getValueType(), MVT::Other)
7701                          : getVTList(VT, MVT::Other);
7702   SDValue Ops[] = {Chain, Ptr, Offset, Mask, EVL};
7703   FoldingSetNodeID ID;
7704   AddNodeIDNode(ID, ISD::VP_LOAD, VTs, Ops);
7705   ID.AddInteger(VT.getRawBits());
7706   ID.AddInteger(getSyntheticNodeSubclassData<VPLoadSDNode>(
7707       dl.getIROrder(), VTs, AM, ExtType, IsExpanding, MemVT, MMO));
7708   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7709   void *IP = nullptr;
7710   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7711     cast<VPLoadSDNode>(E)->refineAlignment(MMO);
7712     return SDValue(E, 0);
7713   }
7714   auto *N = newSDNode<VPLoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
7715                                     ExtType, IsExpanding, MemVT, MMO);
7716   createOperands(N, Ops);
7717 
7718   CSEMap.InsertNode(N, IP);
7719   InsertNode(N);
7720   SDValue V(N, 0);
7721   NewSDValueDbgMsg(V, "Creating new node: ", this);
7722   return V;
7723 }
7724 
7725 SDValue SelectionDAG::getLoadVP(EVT VT, const SDLoc &dl, SDValue Chain,
7726                                 SDValue Ptr, SDValue Mask, SDValue EVL,
7727                                 MachinePointerInfo PtrInfo,
7728                                 MaybeAlign Alignment,
7729                                 MachineMemOperand::Flags MMOFlags,
7730                                 const AAMDNodes &AAInfo, const MDNode *Ranges,
7731                                 bool IsExpanding) {
7732   SDValue Undef = getUNDEF(Ptr.getValueType());
7733   return getLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
7734                    Mask, EVL, PtrInfo, VT, Alignment, MMOFlags, AAInfo, Ranges,
7735                    IsExpanding);
7736 }
7737 
7738 SDValue SelectionDAG::getLoadVP(EVT VT, const SDLoc &dl, SDValue Chain,
7739                                 SDValue Ptr, SDValue Mask, SDValue EVL,
7740                                 MachineMemOperand *MMO, bool IsExpanding) {
7741   SDValue Undef = getUNDEF(Ptr.getValueType());
7742   return getLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
7743                    Mask, EVL, VT, MMO, IsExpanding);
7744 }
7745 
7746 SDValue SelectionDAG::getExtLoadVP(ISD::LoadExtType ExtType, const SDLoc &dl,
7747                                    EVT VT, SDValue Chain, SDValue Ptr,
7748                                    SDValue Mask, SDValue EVL,
7749                                    MachinePointerInfo PtrInfo, EVT MemVT,
7750                                    MaybeAlign Alignment,
7751                                    MachineMemOperand::Flags MMOFlags,
7752                                    const AAMDNodes &AAInfo, bool IsExpanding) {
7753   SDValue Undef = getUNDEF(Ptr.getValueType());
7754   return getLoadVP(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, Mask,
7755                    EVL, PtrInfo, MemVT, Alignment, MMOFlags, AAInfo, nullptr,
7756                    IsExpanding);
7757 }
7758 
7759 SDValue SelectionDAG::getExtLoadVP(ISD::LoadExtType ExtType, const SDLoc &dl,
7760                                    EVT VT, SDValue Chain, SDValue Ptr,
7761                                    SDValue Mask, SDValue EVL, EVT MemVT,
7762                                    MachineMemOperand *MMO, bool IsExpanding) {
7763   SDValue Undef = getUNDEF(Ptr.getValueType());
7764   return getLoadVP(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, Mask,
7765                    EVL, MemVT, MMO, IsExpanding);
7766 }
7767 
7768 SDValue SelectionDAG::getIndexedLoadVP(SDValue OrigLoad, const SDLoc &dl,
7769                                        SDValue Base, SDValue Offset,
7770                                        ISD::MemIndexedMode AM) {
7771   auto *LD = cast<VPLoadSDNode>(OrigLoad);
7772   assert(LD->getOffset().isUndef() && "Load is already a indexed load!");
7773   // Don't propagate the invariant or dereferenceable flags.
7774   auto MMOFlags =
7775       LD->getMemOperand()->getFlags() &
7776       ~(MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable);
7777   return getLoadVP(AM, LD->getExtensionType(), OrigLoad.getValueType(), dl,
7778                    LD->getChain(), Base, Offset, LD->getMask(),
7779                    LD->getVectorLength(), LD->getPointerInfo(),
7780                    LD->getMemoryVT(), LD->getAlign(), MMOFlags, LD->getAAInfo(),
7781                    nullptr, LD->isExpandingLoad());
7782 }
7783 
7784 SDValue SelectionDAG::getStoreVP(SDValue Chain, const SDLoc &dl, SDValue Val,
7785                                  SDValue Ptr, SDValue Offset, SDValue Mask,
7786                                  SDValue EVL, EVT MemVT, MachineMemOperand *MMO,
7787                                  ISD::MemIndexedMode AM, bool IsTruncating,
7788                                  bool IsCompressing) {
7789   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
7790   bool Indexed = AM != ISD::UNINDEXED;
7791   assert((Indexed || Offset.isUndef()) && "Unindexed vp_store with an offset!");
7792   SDVTList VTs = Indexed ? getVTList(Ptr.getValueType(), MVT::Other)
7793                          : getVTList(MVT::Other);
7794   SDValue Ops[] = {Chain, Val, Ptr, Offset, Mask, EVL};
7795   FoldingSetNodeID ID;
7796   AddNodeIDNode(ID, ISD::VP_STORE, VTs, Ops);
7797   ID.AddInteger(MemVT.getRawBits());
7798   ID.AddInteger(getSyntheticNodeSubclassData<VPStoreSDNode>(
7799       dl.getIROrder(), VTs, AM, IsTruncating, IsCompressing, MemVT, MMO));
7800   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7801   void *IP = nullptr;
7802   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7803     cast<VPStoreSDNode>(E)->refineAlignment(MMO);
7804     return SDValue(E, 0);
7805   }
7806   auto *N = newSDNode<VPStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
7807                                      IsTruncating, IsCompressing, MemVT, MMO);
7808   createOperands(N, Ops);
7809 
7810   CSEMap.InsertNode(N, IP);
7811   InsertNode(N);
7812   SDValue V(N, 0);
7813   NewSDValueDbgMsg(V, "Creating new node: ", this);
7814   return V;
7815 }
7816 
7817 SDValue SelectionDAG::getTruncStoreVP(SDValue Chain, const SDLoc &dl,
7818                                       SDValue Val, SDValue Ptr, SDValue Mask,
7819                                       SDValue EVL, MachinePointerInfo PtrInfo,
7820                                       EVT SVT, Align Alignment,
7821                                       MachineMemOperand::Flags MMOFlags,
7822                                       const AAMDNodes &AAInfo,
7823                                       bool IsCompressing) {
7824   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
7825 
7826   MMOFlags |= MachineMemOperand::MOStore;
7827   assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
7828 
7829   if (PtrInfo.V.isNull())
7830     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
7831 
7832   MachineFunction &MF = getMachineFunction();
7833   MachineMemOperand *MMO = MF.getMachineMemOperand(
7834       PtrInfo, MMOFlags, MemoryLocation::getSizeOrUnknown(SVT.getStoreSize()),
7835       Alignment, AAInfo);
7836   return getTruncStoreVP(Chain, dl, Val, Ptr, Mask, EVL, SVT, MMO,
7837                          IsCompressing);
7838 }
7839 
7840 SDValue SelectionDAG::getTruncStoreVP(SDValue Chain, const SDLoc &dl,
7841                                       SDValue Val, SDValue Ptr, SDValue Mask,
7842                                       SDValue EVL, EVT SVT,
7843                                       MachineMemOperand *MMO,
7844                                       bool IsCompressing) {
7845   EVT VT = Val.getValueType();
7846 
7847   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
7848   if (VT == SVT)
7849     return getStoreVP(Chain, dl, Val, Ptr, getUNDEF(Ptr.getValueType()), Mask,
7850                       EVL, VT, MMO, ISD::UNINDEXED,
7851                       /*IsTruncating*/ false, IsCompressing);
7852 
7853   assert(SVT.getScalarType().bitsLT(VT.getScalarType()) &&
7854          "Should only be a truncating store, not extending!");
7855   assert(VT.isInteger() == SVT.isInteger() && "Can't do FP-INT conversion!");
7856   assert(VT.isVector() == SVT.isVector() &&
7857          "Cannot use trunc store to convert to or from a vector!");
7858   assert((!VT.isVector() ||
7859           VT.getVectorElementCount() == SVT.getVectorElementCount()) &&
7860          "Cannot use trunc store to change the number of vector elements!");
7861 
7862   SDVTList VTs = getVTList(MVT::Other);
7863   SDValue Undef = getUNDEF(Ptr.getValueType());
7864   SDValue Ops[] = {Chain, Val, Ptr, Undef, Mask, EVL};
7865   FoldingSetNodeID ID;
7866   AddNodeIDNode(ID, ISD::VP_STORE, VTs, Ops);
7867   ID.AddInteger(SVT.getRawBits());
7868   ID.AddInteger(getSyntheticNodeSubclassData<VPStoreSDNode>(
7869       dl.getIROrder(), VTs, ISD::UNINDEXED, true, IsCompressing, SVT, MMO));
7870   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7871   void *IP = nullptr;
7872   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7873     cast<VPStoreSDNode>(E)->refineAlignment(MMO);
7874     return SDValue(E, 0);
7875   }
7876   auto *N =
7877       newSDNode<VPStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
7878                                ISD::UNINDEXED, true, IsCompressing, SVT, MMO);
7879   createOperands(N, Ops);
7880 
7881   CSEMap.InsertNode(N, IP);
7882   InsertNode(N);
7883   SDValue V(N, 0);
7884   NewSDValueDbgMsg(V, "Creating new node: ", this);
7885   return V;
7886 }
7887 
7888 SDValue SelectionDAG::getIndexedStoreVP(SDValue OrigStore, const SDLoc &dl,
7889                                         SDValue Base, SDValue Offset,
7890                                         ISD::MemIndexedMode AM) {
7891   auto *ST = cast<VPStoreSDNode>(OrigStore);
7892   assert(ST->getOffset().isUndef() && "Store is already an indexed store!");
7893   SDVTList VTs = getVTList(Base.getValueType(), MVT::Other);
7894   SDValue Ops[] = {ST->getChain(), ST->getValue(), Base,
7895                    Offset,         ST->getMask(),  ST->getVectorLength()};
7896   FoldingSetNodeID ID;
7897   AddNodeIDNode(ID, ISD::VP_STORE, VTs, Ops);
7898   ID.AddInteger(ST->getMemoryVT().getRawBits());
7899   ID.AddInteger(ST->getRawSubclassData());
7900   ID.AddInteger(ST->getPointerInfo().getAddrSpace());
7901   void *IP = nullptr;
7902   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
7903     return SDValue(E, 0);
7904 
7905   auto *N = newSDNode<VPStoreSDNode>(
7906       dl.getIROrder(), dl.getDebugLoc(), VTs, AM, ST->isTruncatingStore(),
7907       ST->isCompressingStore(), ST->getMemoryVT(), ST->getMemOperand());
7908   createOperands(N, Ops);
7909 
7910   CSEMap.InsertNode(N, IP);
7911   InsertNode(N);
7912   SDValue V(N, 0);
7913   NewSDValueDbgMsg(V, "Creating new node: ", this);
7914   return V;
7915 }
7916 
7917 SDValue SelectionDAG::getGatherVP(SDVTList VTs, EVT VT, const SDLoc &dl,
7918                                   ArrayRef<SDValue> Ops, MachineMemOperand *MMO,
7919                                   ISD::MemIndexType IndexType) {
7920   assert(Ops.size() == 6 && "Incompatible number of operands");
7921 
7922   FoldingSetNodeID ID;
7923   AddNodeIDNode(ID, ISD::VP_GATHER, VTs, Ops);
7924   ID.AddInteger(VT.getRawBits());
7925   ID.AddInteger(getSyntheticNodeSubclassData<VPGatherSDNode>(
7926       dl.getIROrder(), VTs, VT, MMO, IndexType));
7927   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7928   void *IP = nullptr;
7929   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7930     cast<VPGatherSDNode>(E)->refineAlignment(MMO);
7931     return SDValue(E, 0);
7932   }
7933 
7934   auto *N = newSDNode<VPGatherSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
7935                                       VT, MMO, IndexType);
7936   createOperands(N, Ops);
7937 
7938   assert(N->getMask().getValueType().getVectorElementCount() ==
7939              N->getValueType(0).getVectorElementCount() &&
7940          "Vector width mismatch between mask and data");
7941   assert(N->getIndex().getValueType().getVectorElementCount().isScalable() ==
7942              N->getValueType(0).getVectorElementCount().isScalable() &&
7943          "Scalable flags of index and data do not match");
7944   assert(ElementCount::isKnownGE(
7945              N->getIndex().getValueType().getVectorElementCount(),
7946              N->getValueType(0).getVectorElementCount()) &&
7947          "Vector width mismatch between index and data");
7948   assert(isa<ConstantSDNode>(N->getScale()) &&
7949          cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() &&
7950          "Scale should be a constant power of 2");
7951 
7952   CSEMap.InsertNode(N, IP);
7953   InsertNode(N);
7954   SDValue V(N, 0);
7955   NewSDValueDbgMsg(V, "Creating new node: ", this);
7956   return V;
7957 }
7958 
7959 SDValue SelectionDAG::getScatterVP(SDVTList VTs, EVT VT, const SDLoc &dl,
7960                                    ArrayRef<SDValue> Ops,
7961                                    MachineMemOperand *MMO,
7962                                    ISD::MemIndexType IndexType) {
7963   assert(Ops.size() == 7 && "Incompatible number of operands");
7964 
7965   FoldingSetNodeID ID;
7966   AddNodeIDNode(ID, ISD::VP_SCATTER, VTs, Ops);
7967   ID.AddInteger(VT.getRawBits());
7968   ID.AddInteger(getSyntheticNodeSubclassData<VPScatterSDNode>(
7969       dl.getIROrder(), VTs, VT, MMO, IndexType));
7970   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7971   void *IP = nullptr;
7972   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7973     cast<VPScatterSDNode>(E)->refineAlignment(MMO);
7974     return SDValue(E, 0);
7975   }
7976   auto *N = newSDNode<VPScatterSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
7977                                        VT, MMO, IndexType);
7978   createOperands(N, Ops);
7979 
7980   assert(N->getMask().getValueType().getVectorElementCount() ==
7981              N->getValue().getValueType().getVectorElementCount() &&
7982          "Vector width mismatch between mask and data");
7983   assert(
7984       N->getIndex().getValueType().getVectorElementCount().isScalable() ==
7985           N->getValue().getValueType().getVectorElementCount().isScalable() &&
7986       "Scalable flags of index and data do not match");
7987   assert(ElementCount::isKnownGE(
7988              N->getIndex().getValueType().getVectorElementCount(),
7989              N->getValue().getValueType().getVectorElementCount()) &&
7990          "Vector width mismatch between index and data");
7991   assert(isa<ConstantSDNode>(N->getScale()) &&
7992          cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() &&
7993          "Scale should be a constant power of 2");
7994 
7995   CSEMap.InsertNode(N, IP);
7996   InsertNode(N);
7997   SDValue V(N, 0);
7998   NewSDValueDbgMsg(V, "Creating new node: ", this);
7999   return V;
8000 }
8001 
8002 SDValue SelectionDAG::getMaskedLoad(EVT VT, const SDLoc &dl, SDValue Chain,
8003                                     SDValue Base, SDValue Offset, SDValue Mask,
8004                                     SDValue PassThru, EVT MemVT,
8005                                     MachineMemOperand *MMO,
8006                                     ISD::MemIndexedMode AM,
8007                                     ISD::LoadExtType ExtTy, bool isExpanding) {
8008   bool Indexed = AM != ISD::UNINDEXED;
8009   assert((Indexed || Offset.isUndef()) &&
8010          "Unindexed masked load with an offset!");
8011   SDVTList VTs = Indexed ? getVTList(VT, Base.getValueType(), MVT::Other)
8012                          : getVTList(VT, MVT::Other);
8013   SDValue Ops[] = {Chain, Base, Offset, Mask, PassThru};
8014   FoldingSetNodeID ID;
8015   AddNodeIDNode(ID, ISD::MLOAD, VTs, Ops);
8016   ID.AddInteger(MemVT.getRawBits());
8017   ID.AddInteger(getSyntheticNodeSubclassData<MaskedLoadSDNode>(
8018       dl.getIROrder(), VTs, AM, ExtTy, isExpanding, MemVT, MMO));
8019   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8020   void *IP = nullptr;
8021   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
8022     cast<MaskedLoadSDNode>(E)->refineAlignment(MMO);
8023     return SDValue(E, 0);
8024   }
8025   auto *N = newSDNode<MaskedLoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
8026                                         AM, ExtTy, isExpanding, MemVT, MMO);
8027   createOperands(N, Ops);
8028 
8029   CSEMap.InsertNode(N, IP);
8030   InsertNode(N);
8031   SDValue V(N, 0);
8032   NewSDValueDbgMsg(V, "Creating new node: ", this);
8033   return V;
8034 }
8035 
8036 SDValue SelectionDAG::getIndexedMaskedLoad(SDValue OrigLoad, const SDLoc &dl,
8037                                            SDValue Base, SDValue Offset,
8038                                            ISD::MemIndexedMode AM) {
8039   MaskedLoadSDNode *LD = cast<MaskedLoadSDNode>(OrigLoad);
8040   assert(LD->getOffset().isUndef() && "Masked load is already a indexed load!");
8041   return getMaskedLoad(OrigLoad.getValueType(), dl, LD->getChain(), Base,
8042                        Offset, LD->getMask(), LD->getPassThru(),
8043                        LD->getMemoryVT(), LD->getMemOperand(), AM,
8044                        LD->getExtensionType(), LD->isExpandingLoad());
8045 }
8046 
8047 SDValue SelectionDAG::getMaskedStore(SDValue Chain, const SDLoc &dl,
8048                                      SDValue Val, SDValue Base, SDValue Offset,
8049                                      SDValue Mask, EVT MemVT,
8050                                      MachineMemOperand *MMO,
8051                                      ISD::MemIndexedMode AM, bool IsTruncating,
8052                                      bool IsCompressing) {
8053   assert(Chain.getValueType() == MVT::Other &&
8054         "Invalid chain type");
8055   bool Indexed = AM != ISD::UNINDEXED;
8056   assert((Indexed || Offset.isUndef()) &&
8057          "Unindexed masked store with an offset!");
8058   SDVTList VTs = Indexed ? getVTList(Base.getValueType(), MVT::Other)
8059                          : getVTList(MVT::Other);
8060   SDValue Ops[] = {Chain, Val, Base, Offset, Mask};
8061   FoldingSetNodeID ID;
8062   AddNodeIDNode(ID, ISD::MSTORE, VTs, Ops);
8063   ID.AddInteger(MemVT.getRawBits());
8064   ID.AddInteger(getSyntheticNodeSubclassData<MaskedStoreSDNode>(
8065       dl.getIROrder(), VTs, AM, IsTruncating, IsCompressing, MemVT, MMO));
8066   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8067   void *IP = nullptr;
8068   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
8069     cast<MaskedStoreSDNode>(E)->refineAlignment(MMO);
8070     return SDValue(E, 0);
8071   }
8072   auto *N =
8073       newSDNode<MaskedStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
8074                                    IsTruncating, IsCompressing, MemVT, MMO);
8075   createOperands(N, Ops);
8076 
8077   CSEMap.InsertNode(N, IP);
8078   InsertNode(N);
8079   SDValue V(N, 0);
8080   NewSDValueDbgMsg(V, "Creating new node: ", this);
8081   return V;
8082 }
8083 
8084 SDValue SelectionDAG::getIndexedMaskedStore(SDValue OrigStore, const SDLoc &dl,
8085                                             SDValue Base, SDValue Offset,
8086                                             ISD::MemIndexedMode AM) {
8087   MaskedStoreSDNode *ST = cast<MaskedStoreSDNode>(OrigStore);
8088   assert(ST->getOffset().isUndef() &&
8089          "Masked store is already a indexed store!");
8090   return getMaskedStore(ST->getChain(), dl, ST->getValue(), Base, Offset,
8091                         ST->getMask(), ST->getMemoryVT(), ST->getMemOperand(),
8092                         AM, ST->isTruncatingStore(), ST->isCompressingStore());
8093 }
8094 
8095 SDValue SelectionDAG::getMaskedGather(SDVTList VTs, EVT MemVT, const SDLoc &dl,
8096                                       ArrayRef<SDValue> Ops,
8097                                       MachineMemOperand *MMO,
8098                                       ISD::MemIndexType IndexType,
8099                                       ISD::LoadExtType ExtTy) {
8100   assert(Ops.size() == 6 && "Incompatible number of operands");
8101 
8102   FoldingSetNodeID ID;
8103   AddNodeIDNode(ID, ISD::MGATHER, VTs, Ops);
8104   ID.AddInteger(MemVT.getRawBits());
8105   ID.AddInteger(getSyntheticNodeSubclassData<MaskedGatherSDNode>(
8106       dl.getIROrder(), VTs, MemVT, MMO, IndexType, ExtTy));
8107   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8108   void *IP = nullptr;
8109   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
8110     cast<MaskedGatherSDNode>(E)->refineAlignment(MMO);
8111     return SDValue(E, 0);
8112   }
8113 
8114   IndexType = TLI->getCanonicalIndexType(IndexType, MemVT, Ops[4]);
8115   auto *N = newSDNode<MaskedGatherSDNode>(dl.getIROrder(), dl.getDebugLoc(),
8116                                           VTs, MemVT, MMO, IndexType, ExtTy);
8117   createOperands(N, Ops);
8118 
8119   assert(N->getPassThru().getValueType() == N->getValueType(0) &&
8120          "Incompatible type of the PassThru value in MaskedGatherSDNode");
8121   assert(N->getMask().getValueType().getVectorElementCount() ==
8122              N->getValueType(0).getVectorElementCount() &&
8123          "Vector width mismatch between mask and data");
8124   assert(N->getIndex().getValueType().getVectorElementCount().isScalable() ==
8125              N->getValueType(0).getVectorElementCount().isScalable() &&
8126          "Scalable flags of index and data do not match");
8127   assert(ElementCount::isKnownGE(
8128              N->getIndex().getValueType().getVectorElementCount(),
8129              N->getValueType(0).getVectorElementCount()) &&
8130          "Vector width mismatch between index and data");
8131   assert(isa<ConstantSDNode>(N->getScale()) &&
8132          cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() &&
8133          "Scale should be a constant power of 2");
8134 
8135   CSEMap.InsertNode(N, IP);
8136   InsertNode(N);
8137   SDValue V(N, 0);
8138   NewSDValueDbgMsg(V, "Creating new node: ", this);
8139   return V;
8140 }
8141 
8142 SDValue SelectionDAG::getMaskedScatter(SDVTList VTs, EVT MemVT, const SDLoc &dl,
8143                                        ArrayRef<SDValue> Ops,
8144                                        MachineMemOperand *MMO,
8145                                        ISD::MemIndexType IndexType,
8146                                        bool IsTrunc) {
8147   assert(Ops.size() == 6 && "Incompatible number of operands");
8148 
8149   FoldingSetNodeID ID;
8150   AddNodeIDNode(ID, ISD::MSCATTER, VTs, Ops);
8151   ID.AddInteger(MemVT.getRawBits());
8152   ID.AddInteger(getSyntheticNodeSubclassData<MaskedScatterSDNode>(
8153       dl.getIROrder(), VTs, MemVT, MMO, IndexType, IsTrunc));
8154   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8155   void *IP = nullptr;
8156   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
8157     cast<MaskedScatterSDNode>(E)->refineAlignment(MMO);
8158     return SDValue(E, 0);
8159   }
8160 
8161   IndexType = TLI->getCanonicalIndexType(IndexType, MemVT, Ops[4]);
8162   auto *N = newSDNode<MaskedScatterSDNode>(dl.getIROrder(), dl.getDebugLoc(),
8163                                            VTs, MemVT, MMO, IndexType, IsTrunc);
8164   createOperands(N, Ops);
8165 
8166   assert(N->getMask().getValueType().getVectorElementCount() ==
8167              N->getValue().getValueType().getVectorElementCount() &&
8168          "Vector width mismatch between mask and data");
8169   assert(
8170       N->getIndex().getValueType().getVectorElementCount().isScalable() ==
8171           N->getValue().getValueType().getVectorElementCount().isScalable() &&
8172       "Scalable flags of index and data do not match");
8173   assert(ElementCount::isKnownGE(
8174              N->getIndex().getValueType().getVectorElementCount(),
8175              N->getValue().getValueType().getVectorElementCount()) &&
8176          "Vector width mismatch between index and data");
8177   assert(isa<ConstantSDNode>(N->getScale()) &&
8178          cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() &&
8179          "Scale should be a constant power of 2");
8180 
8181   CSEMap.InsertNode(N, IP);
8182   InsertNode(N);
8183   SDValue V(N, 0);
8184   NewSDValueDbgMsg(V, "Creating new node: ", this);
8185   return V;
8186 }
8187 
8188 SDValue SelectionDAG::simplifySelect(SDValue Cond, SDValue T, SDValue F) {
8189   // select undef, T, F --> T (if T is a constant), otherwise F
8190   // select, ?, undef, F --> F
8191   // select, ?, T, undef --> T
8192   if (Cond.isUndef())
8193     return isConstantValueOfAnyType(T) ? T : F;
8194   if (T.isUndef())
8195     return F;
8196   if (F.isUndef())
8197     return T;
8198 
8199   // select true, T, F --> T
8200   // select false, T, F --> F
8201   if (auto *CondC = dyn_cast<ConstantSDNode>(Cond))
8202     return CondC->isZero() ? F : T;
8203 
8204   // TODO: This should simplify VSELECT with constant condition using something
8205   // like this (but check boolean contents to be complete?):
8206   //  if (ISD::isBuildVectorAllOnes(Cond.getNode()))
8207   //    return T;
8208   //  if (ISD::isBuildVectorAllZeros(Cond.getNode()))
8209   //    return F;
8210 
8211   // select ?, T, T --> T
8212   if (T == F)
8213     return T;
8214 
8215   return SDValue();
8216 }
8217 
8218 SDValue SelectionDAG::simplifyShift(SDValue X, SDValue Y) {
8219   // shift undef, Y --> 0 (can always assume that the undef value is 0)
8220   if (X.isUndef())
8221     return getConstant(0, SDLoc(X.getNode()), X.getValueType());
8222   // shift X, undef --> undef (because it may shift by the bitwidth)
8223   if (Y.isUndef())
8224     return getUNDEF(X.getValueType());
8225 
8226   // shift 0, Y --> 0
8227   // shift X, 0 --> X
8228   if (isNullOrNullSplat(X) || isNullOrNullSplat(Y))
8229     return X;
8230 
8231   // shift X, C >= bitwidth(X) --> undef
8232   // All vector elements must be too big (or undef) to avoid partial undefs.
8233   auto isShiftTooBig = [X](ConstantSDNode *Val) {
8234     return !Val || Val->getAPIntValue().uge(X.getScalarValueSizeInBits());
8235   };
8236   if (ISD::matchUnaryPredicate(Y, isShiftTooBig, true))
8237     return getUNDEF(X.getValueType());
8238 
8239   return SDValue();
8240 }
8241 
8242 SDValue SelectionDAG::simplifyFPBinop(unsigned Opcode, SDValue X, SDValue Y,
8243                                       SDNodeFlags Flags) {
8244   // If this operation has 'nnan' or 'ninf' and at least 1 disallowed operand
8245   // (an undef operand can be chosen to be Nan/Inf), then the result of this
8246   // operation is poison. That result can be relaxed to undef.
8247   ConstantFPSDNode *XC = isConstOrConstSplatFP(X, /* AllowUndefs */ true);
8248   ConstantFPSDNode *YC = isConstOrConstSplatFP(Y, /* AllowUndefs */ true);
8249   bool HasNan = (XC && XC->getValueAPF().isNaN()) ||
8250                 (YC && YC->getValueAPF().isNaN());
8251   bool HasInf = (XC && XC->getValueAPF().isInfinity()) ||
8252                 (YC && YC->getValueAPF().isInfinity());
8253 
8254   if (Flags.hasNoNaNs() && (HasNan || X.isUndef() || Y.isUndef()))
8255     return getUNDEF(X.getValueType());
8256 
8257   if (Flags.hasNoInfs() && (HasInf || X.isUndef() || Y.isUndef()))
8258     return getUNDEF(X.getValueType());
8259 
8260   if (!YC)
8261     return SDValue();
8262 
8263   // X + -0.0 --> X
8264   if (Opcode == ISD::FADD)
8265     if (YC->getValueAPF().isNegZero())
8266       return X;
8267 
8268   // X - +0.0 --> X
8269   if (Opcode == ISD::FSUB)
8270     if (YC->getValueAPF().isPosZero())
8271       return X;
8272 
8273   // X * 1.0 --> X
8274   // X / 1.0 --> X
8275   if (Opcode == ISD::FMUL || Opcode == ISD::FDIV)
8276     if (YC->getValueAPF().isExactlyValue(1.0))
8277       return X;
8278 
8279   // X * 0.0 --> 0.0
8280   if (Opcode == ISD::FMUL && Flags.hasNoNaNs() && Flags.hasNoSignedZeros())
8281     if (YC->getValueAPF().isZero())
8282       return getConstantFP(0.0, SDLoc(Y), Y.getValueType());
8283 
8284   return SDValue();
8285 }
8286 
8287 SDValue SelectionDAG::getVAArg(EVT VT, const SDLoc &dl, SDValue Chain,
8288                                SDValue Ptr, SDValue SV, unsigned Align) {
8289   SDValue Ops[] = { Chain, Ptr, SV, getTargetConstant(Align, dl, MVT::i32) };
8290   return getNode(ISD::VAARG, dl, getVTList(VT, MVT::Other), Ops);
8291 }
8292 
8293 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
8294                               ArrayRef<SDUse> Ops) {
8295   switch (Ops.size()) {
8296   case 0: return getNode(Opcode, DL, VT);
8297   case 1: return getNode(Opcode, DL, VT, static_cast<const SDValue>(Ops[0]));
8298   case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1]);
8299   case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2]);
8300   default: break;
8301   }
8302 
8303   // Copy from an SDUse array into an SDValue array for use with
8304   // the regular getNode logic.
8305   SmallVector<SDValue, 8> NewOps(Ops.begin(), Ops.end());
8306   return getNode(Opcode, DL, VT, NewOps);
8307 }
8308 
8309 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
8310                               ArrayRef<SDValue> Ops) {
8311   SDNodeFlags Flags;
8312   if (Inserter)
8313     Flags = Inserter->getFlags();
8314   return getNode(Opcode, DL, VT, Ops, Flags);
8315 }
8316 
8317 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
8318                               ArrayRef<SDValue> Ops, const SDNodeFlags Flags) {
8319   unsigned NumOps = Ops.size();
8320   switch (NumOps) {
8321   case 0: return getNode(Opcode, DL, VT);
8322   case 1: return getNode(Opcode, DL, VT, Ops[0], Flags);
8323   case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Flags);
8324   case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2], Flags);
8325   default: break;
8326   }
8327 
8328 #ifndef NDEBUG
8329   for (auto &Op : Ops)
8330     assert(Op.getOpcode() != ISD::DELETED_NODE &&
8331            "Operand is DELETED_NODE!");
8332 #endif
8333 
8334   switch (Opcode) {
8335   default: break;
8336   case ISD::BUILD_VECTOR:
8337     // Attempt to simplify BUILD_VECTOR.
8338     if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
8339       return V;
8340     break;
8341   case ISD::CONCAT_VECTORS:
8342     if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this))
8343       return V;
8344     break;
8345   case ISD::SELECT_CC:
8346     assert(NumOps == 5 && "SELECT_CC takes 5 operands!");
8347     assert(Ops[0].getValueType() == Ops[1].getValueType() &&
8348            "LHS and RHS of condition must have same type!");
8349     assert(Ops[2].getValueType() == Ops[3].getValueType() &&
8350            "True and False arms of SelectCC must have same type!");
8351     assert(Ops[2].getValueType() == VT &&
8352            "select_cc node must be of same type as true and false value!");
8353     break;
8354   case ISD::BR_CC:
8355     assert(NumOps == 5 && "BR_CC takes 5 operands!");
8356     assert(Ops[2].getValueType() == Ops[3].getValueType() &&
8357            "LHS/RHS of comparison should match types!");
8358     break;
8359   }
8360 
8361   // Memoize nodes.
8362   SDNode *N;
8363   SDVTList VTs = getVTList(VT);
8364 
8365   if (VT != MVT::Glue) {
8366     FoldingSetNodeID ID;
8367     AddNodeIDNode(ID, Opcode, VTs, Ops);
8368     void *IP = nullptr;
8369 
8370     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
8371       return SDValue(E, 0);
8372 
8373     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
8374     createOperands(N, Ops);
8375 
8376     CSEMap.InsertNode(N, IP);
8377   } else {
8378     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
8379     createOperands(N, Ops);
8380   }
8381 
8382   N->setFlags(Flags);
8383   InsertNode(N);
8384   SDValue V(N, 0);
8385   NewSDValueDbgMsg(V, "Creating new node: ", this);
8386   return V;
8387 }
8388 
8389 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL,
8390                               ArrayRef<EVT> ResultTys, ArrayRef<SDValue> Ops) {
8391   return getNode(Opcode, DL, getVTList(ResultTys), Ops);
8392 }
8393 
8394 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
8395                               ArrayRef<SDValue> Ops) {
8396   SDNodeFlags Flags;
8397   if (Inserter)
8398     Flags = Inserter->getFlags();
8399   return getNode(Opcode, DL, VTList, Ops, Flags);
8400 }
8401 
8402 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
8403                               ArrayRef<SDValue> Ops, const SDNodeFlags Flags) {
8404   if (VTList.NumVTs == 1)
8405     return getNode(Opcode, DL, VTList.VTs[0], Ops);
8406 
8407 #ifndef NDEBUG
8408   for (auto &Op : Ops)
8409     assert(Op.getOpcode() != ISD::DELETED_NODE &&
8410            "Operand is DELETED_NODE!");
8411 #endif
8412 
8413   switch (Opcode) {
8414   case ISD::STRICT_FP_EXTEND:
8415     assert(VTList.NumVTs == 2 && Ops.size() == 2 &&
8416            "Invalid STRICT_FP_EXTEND!");
8417     assert(VTList.VTs[0].isFloatingPoint() &&
8418            Ops[1].getValueType().isFloatingPoint() && "Invalid FP cast!");
8419     assert(VTList.VTs[0].isVector() == Ops[1].getValueType().isVector() &&
8420            "STRICT_FP_EXTEND result type should be vector iff the operand "
8421            "type is vector!");
8422     assert((!VTList.VTs[0].isVector() ||
8423             VTList.VTs[0].getVectorNumElements() ==
8424             Ops[1].getValueType().getVectorNumElements()) &&
8425            "Vector element count mismatch!");
8426     assert(Ops[1].getValueType().bitsLT(VTList.VTs[0]) &&
8427            "Invalid fpext node, dst <= src!");
8428     break;
8429   case ISD::STRICT_FP_ROUND:
8430     assert(VTList.NumVTs == 2 && Ops.size() == 3 && "Invalid STRICT_FP_ROUND!");
8431     assert(VTList.VTs[0].isVector() == Ops[1].getValueType().isVector() &&
8432            "STRICT_FP_ROUND result type should be vector iff the operand "
8433            "type is vector!");
8434     assert((!VTList.VTs[0].isVector() ||
8435             VTList.VTs[0].getVectorNumElements() ==
8436             Ops[1].getValueType().getVectorNumElements()) &&
8437            "Vector element count mismatch!");
8438     assert(VTList.VTs[0].isFloatingPoint() &&
8439            Ops[1].getValueType().isFloatingPoint() &&
8440            VTList.VTs[0].bitsLT(Ops[1].getValueType()) &&
8441            isa<ConstantSDNode>(Ops[2]) &&
8442            (cast<ConstantSDNode>(Ops[2])->getZExtValue() == 0 ||
8443             cast<ConstantSDNode>(Ops[2])->getZExtValue() == 1) &&
8444            "Invalid STRICT_FP_ROUND!");
8445     break;
8446 #if 0
8447   // FIXME: figure out how to safely handle things like
8448   // int foo(int x) { return 1 << (x & 255); }
8449   // int bar() { return foo(256); }
8450   case ISD::SRA_PARTS:
8451   case ISD::SRL_PARTS:
8452   case ISD::SHL_PARTS:
8453     if (N3.getOpcode() == ISD::SIGN_EXTEND_INREG &&
8454         cast<VTSDNode>(N3.getOperand(1))->getVT() != MVT::i1)
8455       return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0));
8456     else if (N3.getOpcode() == ISD::AND)
8457       if (ConstantSDNode *AndRHS = dyn_cast<ConstantSDNode>(N3.getOperand(1))) {
8458         // If the and is only masking out bits that cannot effect the shift,
8459         // eliminate the and.
8460         unsigned NumBits = VT.getScalarSizeInBits()*2;
8461         if ((AndRHS->getValue() & (NumBits-1)) == NumBits-1)
8462           return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0));
8463       }
8464     break;
8465 #endif
8466   }
8467 
8468   // Memoize the node unless it returns a flag.
8469   SDNode *N;
8470   if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) {
8471     FoldingSetNodeID ID;
8472     AddNodeIDNode(ID, Opcode, VTList, Ops);
8473     void *IP = nullptr;
8474     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
8475       return SDValue(E, 0);
8476 
8477     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList);
8478     createOperands(N, Ops);
8479     CSEMap.InsertNode(N, IP);
8480   } else {
8481     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList);
8482     createOperands(N, Ops);
8483   }
8484 
8485   N->setFlags(Flags);
8486   InsertNode(N);
8487   SDValue V(N, 0);
8488   NewSDValueDbgMsg(V, "Creating new node: ", this);
8489   return V;
8490 }
8491 
8492 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL,
8493                               SDVTList VTList) {
8494   return getNode(Opcode, DL, VTList, None);
8495 }
8496 
8497 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
8498                               SDValue N1) {
8499   SDValue Ops[] = { N1 };
8500   return getNode(Opcode, DL, VTList, Ops);
8501 }
8502 
8503 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
8504                               SDValue N1, SDValue N2) {
8505   SDValue Ops[] = { N1, N2 };
8506   return getNode(Opcode, DL, VTList, Ops);
8507 }
8508 
8509 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
8510                               SDValue N1, SDValue N2, SDValue N3) {
8511   SDValue Ops[] = { N1, N2, N3 };
8512   return getNode(Opcode, DL, VTList, Ops);
8513 }
8514 
8515 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
8516                               SDValue N1, SDValue N2, SDValue N3, SDValue N4) {
8517   SDValue Ops[] = { N1, N2, N3, N4 };
8518   return getNode(Opcode, DL, VTList, Ops);
8519 }
8520 
8521 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
8522                               SDValue N1, SDValue N2, SDValue N3, SDValue N4,
8523                               SDValue N5) {
8524   SDValue Ops[] = { N1, N2, N3, N4, N5 };
8525   return getNode(Opcode, DL, VTList, Ops);
8526 }
8527 
8528 SDVTList SelectionDAG::getVTList(EVT VT) {
8529   return makeVTList(SDNode::getValueTypeList(VT), 1);
8530 }
8531 
8532 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2) {
8533   FoldingSetNodeID ID;
8534   ID.AddInteger(2U);
8535   ID.AddInteger(VT1.getRawBits());
8536   ID.AddInteger(VT2.getRawBits());
8537 
8538   void *IP = nullptr;
8539   SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
8540   if (!Result) {
8541     EVT *Array = Allocator.Allocate<EVT>(2);
8542     Array[0] = VT1;
8543     Array[1] = VT2;
8544     Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 2);
8545     VTListMap.InsertNode(Result, IP);
8546   }
8547   return Result->getSDVTList();
8548 }
8549 
8550 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3) {
8551   FoldingSetNodeID ID;
8552   ID.AddInteger(3U);
8553   ID.AddInteger(VT1.getRawBits());
8554   ID.AddInteger(VT2.getRawBits());
8555   ID.AddInteger(VT3.getRawBits());
8556 
8557   void *IP = nullptr;
8558   SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
8559   if (!Result) {
8560     EVT *Array = Allocator.Allocate<EVT>(3);
8561     Array[0] = VT1;
8562     Array[1] = VT2;
8563     Array[2] = VT3;
8564     Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 3);
8565     VTListMap.InsertNode(Result, IP);
8566   }
8567   return Result->getSDVTList();
8568 }
8569 
8570 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3, EVT VT4) {
8571   FoldingSetNodeID ID;
8572   ID.AddInteger(4U);
8573   ID.AddInteger(VT1.getRawBits());
8574   ID.AddInteger(VT2.getRawBits());
8575   ID.AddInteger(VT3.getRawBits());
8576   ID.AddInteger(VT4.getRawBits());
8577 
8578   void *IP = nullptr;
8579   SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
8580   if (!Result) {
8581     EVT *Array = Allocator.Allocate<EVT>(4);
8582     Array[0] = VT1;
8583     Array[1] = VT2;
8584     Array[2] = VT3;
8585     Array[3] = VT4;
8586     Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 4);
8587     VTListMap.InsertNode(Result, IP);
8588   }
8589   return Result->getSDVTList();
8590 }
8591 
8592 SDVTList SelectionDAG::getVTList(ArrayRef<EVT> VTs) {
8593   unsigned NumVTs = VTs.size();
8594   FoldingSetNodeID ID;
8595   ID.AddInteger(NumVTs);
8596   for (unsigned index = 0; index < NumVTs; index++) {
8597     ID.AddInteger(VTs[index].getRawBits());
8598   }
8599 
8600   void *IP = nullptr;
8601   SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
8602   if (!Result) {
8603     EVT *Array = Allocator.Allocate<EVT>(NumVTs);
8604     llvm::copy(VTs, Array);
8605     Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, NumVTs);
8606     VTListMap.InsertNode(Result, IP);
8607   }
8608   return Result->getSDVTList();
8609 }
8610 
8611 
8612 /// UpdateNodeOperands - *Mutate* the specified node in-place to have the
8613 /// specified operands.  If the resultant node already exists in the DAG,
8614 /// this does not modify the specified node, instead it returns the node that
8615 /// already exists.  If the resultant node does not exist in the DAG, the
8616 /// input node is returned.  As a degenerate case, if you specify the same
8617 /// input operands as the node already has, the input node is returned.
8618 SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op) {
8619   assert(N->getNumOperands() == 1 && "Update with wrong number of operands");
8620 
8621   // Check to see if there is no change.
8622   if (Op == N->getOperand(0)) return N;
8623 
8624   // See if the modified node already exists.
8625   void *InsertPos = nullptr;
8626   if (SDNode *Existing = FindModifiedNodeSlot(N, Op, InsertPos))
8627     return Existing;
8628 
8629   // Nope it doesn't.  Remove the node from its current place in the maps.
8630   if (InsertPos)
8631     if (!RemoveNodeFromCSEMaps(N))
8632       InsertPos = nullptr;
8633 
8634   // Now we update the operands.
8635   N->OperandList[0].set(Op);
8636 
8637   updateDivergence(N);
8638   // If this gets put into a CSE map, add it.
8639   if (InsertPos) CSEMap.InsertNode(N, InsertPos);
8640   return N;
8641 }
8642 
8643 SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2) {
8644   assert(N->getNumOperands() == 2 && "Update with wrong number of operands");
8645 
8646   // Check to see if there is no change.
8647   if (Op1 == N->getOperand(0) && Op2 == N->getOperand(1))
8648     return N;   // No operands changed, just return the input node.
8649 
8650   // See if the modified node already exists.
8651   void *InsertPos = nullptr;
8652   if (SDNode *Existing = FindModifiedNodeSlot(N, Op1, Op2, InsertPos))
8653     return Existing;
8654 
8655   // Nope it doesn't.  Remove the node from its current place in the maps.
8656   if (InsertPos)
8657     if (!RemoveNodeFromCSEMaps(N))
8658       InsertPos = nullptr;
8659 
8660   // Now we update the operands.
8661   if (N->OperandList[0] != Op1)
8662     N->OperandList[0].set(Op1);
8663   if (N->OperandList[1] != Op2)
8664     N->OperandList[1].set(Op2);
8665 
8666   updateDivergence(N);
8667   // If this gets put into a CSE map, add it.
8668   if (InsertPos) CSEMap.InsertNode(N, InsertPos);
8669   return N;
8670 }
8671 
8672 SDNode *SelectionDAG::
8673 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2, SDValue Op3) {
8674   SDValue Ops[] = { Op1, Op2, Op3 };
8675   return UpdateNodeOperands(N, Ops);
8676 }
8677 
8678 SDNode *SelectionDAG::
8679 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2,
8680                    SDValue Op3, SDValue Op4) {
8681   SDValue Ops[] = { Op1, Op2, Op3, Op4 };
8682   return UpdateNodeOperands(N, Ops);
8683 }
8684 
8685 SDNode *SelectionDAG::
8686 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2,
8687                    SDValue Op3, SDValue Op4, SDValue Op5) {
8688   SDValue Ops[] = { Op1, Op2, Op3, Op4, Op5 };
8689   return UpdateNodeOperands(N, Ops);
8690 }
8691 
8692 SDNode *SelectionDAG::
8693 UpdateNodeOperands(SDNode *N, ArrayRef<SDValue> Ops) {
8694   unsigned NumOps = Ops.size();
8695   assert(N->getNumOperands() == NumOps &&
8696          "Update with wrong number of operands");
8697 
8698   // If no operands changed just return the input node.
8699   if (std::equal(Ops.begin(), Ops.end(), N->op_begin()))
8700     return N;
8701 
8702   // See if the modified node already exists.
8703   void *InsertPos = nullptr;
8704   if (SDNode *Existing = FindModifiedNodeSlot(N, Ops, InsertPos))
8705     return Existing;
8706 
8707   // Nope it doesn't.  Remove the node from its current place in the maps.
8708   if (InsertPos)
8709     if (!RemoveNodeFromCSEMaps(N))
8710       InsertPos = nullptr;
8711 
8712   // Now we update the operands.
8713   for (unsigned i = 0; i != NumOps; ++i)
8714     if (N->OperandList[i] != Ops[i])
8715       N->OperandList[i].set(Ops[i]);
8716 
8717   updateDivergence(N);
8718   // If this gets put into a CSE map, add it.
8719   if (InsertPos) CSEMap.InsertNode(N, InsertPos);
8720   return N;
8721 }
8722 
8723 /// DropOperands - Release the operands and set this node to have
8724 /// zero operands.
8725 void SDNode::DropOperands() {
8726   // Unlike the code in MorphNodeTo that does this, we don't need to
8727   // watch for dead nodes here.
8728   for (op_iterator I = op_begin(), E = op_end(); I != E; ) {
8729     SDUse &Use = *I++;
8730     Use.set(SDValue());
8731   }
8732 }
8733 
8734 void SelectionDAG::setNodeMemRefs(MachineSDNode *N,
8735                                   ArrayRef<MachineMemOperand *> NewMemRefs) {
8736   if (NewMemRefs.empty()) {
8737     N->clearMemRefs();
8738     return;
8739   }
8740 
8741   // Check if we can avoid allocating by storing a single reference directly.
8742   if (NewMemRefs.size() == 1) {
8743     N->MemRefs = NewMemRefs[0];
8744     N->NumMemRefs = 1;
8745     return;
8746   }
8747 
8748   MachineMemOperand **MemRefsBuffer =
8749       Allocator.template Allocate<MachineMemOperand *>(NewMemRefs.size());
8750   llvm::copy(NewMemRefs, MemRefsBuffer);
8751   N->MemRefs = MemRefsBuffer;
8752   N->NumMemRefs = static_cast<int>(NewMemRefs.size());
8753 }
8754 
8755 /// SelectNodeTo - These are wrappers around MorphNodeTo that accept a
8756 /// machine opcode.
8757 ///
8758 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8759                                    EVT VT) {
8760   SDVTList VTs = getVTList(VT);
8761   return SelectNodeTo(N, MachineOpc, VTs, None);
8762 }
8763 
8764 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8765                                    EVT VT, SDValue Op1) {
8766   SDVTList VTs = getVTList(VT);
8767   SDValue Ops[] = { Op1 };
8768   return SelectNodeTo(N, MachineOpc, VTs, Ops);
8769 }
8770 
8771 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8772                                    EVT VT, SDValue Op1,
8773                                    SDValue Op2) {
8774   SDVTList VTs = getVTList(VT);
8775   SDValue Ops[] = { Op1, Op2 };
8776   return SelectNodeTo(N, MachineOpc, VTs, Ops);
8777 }
8778 
8779 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8780                                    EVT VT, SDValue Op1,
8781                                    SDValue Op2, SDValue Op3) {
8782   SDVTList VTs = getVTList(VT);
8783   SDValue Ops[] = { Op1, Op2, Op3 };
8784   return SelectNodeTo(N, MachineOpc, VTs, Ops);
8785 }
8786 
8787 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8788                                    EVT VT, ArrayRef<SDValue> Ops) {
8789   SDVTList VTs = getVTList(VT);
8790   return SelectNodeTo(N, MachineOpc, VTs, Ops);
8791 }
8792 
8793 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8794                                    EVT VT1, EVT VT2, ArrayRef<SDValue> Ops) {
8795   SDVTList VTs = getVTList(VT1, VT2);
8796   return SelectNodeTo(N, MachineOpc, VTs, Ops);
8797 }
8798 
8799 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8800                                    EVT VT1, EVT VT2) {
8801   SDVTList VTs = getVTList(VT1, VT2);
8802   return SelectNodeTo(N, MachineOpc, VTs, None);
8803 }
8804 
8805 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8806                                    EVT VT1, EVT VT2, EVT VT3,
8807                                    ArrayRef<SDValue> Ops) {
8808   SDVTList VTs = getVTList(VT1, VT2, VT3);
8809   return SelectNodeTo(N, MachineOpc, VTs, Ops);
8810 }
8811 
8812 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8813                                    EVT VT1, EVT VT2,
8814                                    SDValue Op1, SDValue Op2) {
8815   SDVTList VTs = getVTList(VT1, VT2);
8816   SDValue Ops[] = { Op1, Op2 };
8817   return SelectNodeTo(N, MachineOpc, VTs, Ops);
8818 }
8819 
8820 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8821                                    SDVTList VTs,ArrayRef<SDValue> Ops) {
8822   SDNode *New = MorphNodeTo(N, ~MachineOpc, VTs, Ops);
8823   // Reset the NodeID to -1.
8824   New->setNodeId(-1);
8825   if (New != N) {
8826     ReplaceAllUsesWith(N, New);
8827     RemoveDeadNode(N);
8828   }
8829   return New;
8830 }
8831 
8832 /// UpdateSDLocOnMergeSDNode - If the opt level is -O0 then it throws away
8833 /// the line number information on the merged node since it is not possible to
8834 /// preserve the information that operation is associated with multiple lines.
8835 /// This will make the debugger working better at -O0, were there is a higher
8836 /// probability having other instructions associated with that line.
8837 ///
8838 /// For IROrder, we keep the smaller of the two
8839 SDNode *SelectionDAG::UpdateSDLocOnMergeSDNode(SDNode *N, const SDLoc &OLoc) {
8840   DebugLoc NLoc = N->getDebugLoc();
8841   if (NLoc && OptLevel == CodeGenOpt::None && OLoc.getDebugLoc() != NLoc) {
8842     N->setDebugLoc(DebugLoc());
8843   }
8844   unsigned Order = std::min(N->getIROrder(), OLoc.getIROrder());
8845   N->setIROrder(Order);
8846   return N;
8847 }
8848 
8849 /// MorphNodeTo - This *mutates* the specified node to have the specified
8850 /// return type, opcode, and operands.
8851 ///
8852 /// Note that MorphNodeTo returns the resultant node.  If there is already a
8853 /// node of the specified opcode and operands, it returns that node instead of
8854 /// the current one.  Note that the SDLoc need not be the same.
8855 ///
8856 /// Using MorphNodeTo is faster than creating a new node and swapping it in
8857 /// with ReplaceAllUsesWith both because it often avoids allocating a new
8858 /// node, and because it doesn't require CSE recalculation for any of
8859 /// the node's users.
8860 ///
8861 /// However, note that MorphNodeTo recursively deletes dead nodes from the DAG.
8862 /// As a consequence it isn't appropriate to use from within the DAG combiner or
8863 /// the legalizer which maintain worklists that would need to be updated when
8864 /// deleting things.
8865 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
8866                                   SDVTList VTs, ArrayRef<SDValue> Ops) {
8867   // If an identical node already exists, use it.
8868   void *IP = nullptr;
8869   if (VTs.VTs[VTs.NumVTs-1] != MVT::Glue) {
8870     FoldingSetNodeID ID;
8871     AddNodeIDNode(ID, Opc, VTs, Ops);
8872     if (SDNode *ON = FindNodeOrInsertPos(ID, SDLoc(N), IP))
8873       return UpdateSDLocOnMergeSDNode(ON, SDLoc(N));
8874   }
8875 
8876   if (!RemoveNodeFromCSEMaps(N))
8877     IP = nullptr;
8878 
8879   // Start the morphing.
8880   N->NodeType = Opc;
8881   N->ValueList = VTs.VTs;
8882   N->NumValues = VTs.NumVTs;
8883 
8884   // Clear the operands list, updating used nodes to remove this from their
8885   // use list.  Keep track of any operands that become dead as a result.
8886   SmallPtrSet<SDNode*, 16> DeadNodeSet;
8887   for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) {
8888     SDUse &Use = *I++;
8889     SDNode *Used = Use.getNode();
8890     Use.set(SDValue());
8891     if (Used->use_empty())
8892       DeadNodeSet.insert(Used);
8893   }
8894 
8895   // For MachineNode, initialize the memory references information.
8896   if (MachineSDNode *MN = dyn_cast<MachineSDNode>(N))
8897     MN->clearMemRefs();
8898 
8899   // Swap for an appropriately sized array from the recycler.
8900   removeOperands(N);
8901   createOperands(N, Ops);
8902 
8903   // Delete any nodes that are still dead after adding the uses for the
8904   // new operands.
8905   if (!DeadNodeSet.empty()) {
8906     SmallVector<SDNode *, 16> DeadNodes;
8907     for (SDNode *N : DeadNodeSet)
8908       if (N->use_empty())
8909         DeadNodes.push_back(N);
8910     RemoveDeadNodes(DeadNodes);
8911   }
8912 
8913   if (IP)
8914     CSEMap.InsertNode(N, IP);   // Memoize the new node.
8915   return N;
8916 }
8917 
8918 SDNode* SelectionDAG::mutateStrictFPToFP(SDNode *Node) {
8919   unsigned OrigOpc = Node->getOpcode();
8920   unsigned NewOpc;
8921   switch (OrigOpc) {
8922   default:
8923     llvm_unreachable("mutateStrictFPToFP called with unexpected opcode!");
8924 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN)               \
8925   case ISD::STRICT_##DAGN: NewOpc = ISD::DAGN; break;
8926 #define CMP_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN)               \
8927   case ISD::STRICT_##DAGN: NewOpc = ISD::SETCC; break;
8928 #include "llvm/IR/ConstrainedOps.def"
8929   }
8930 
8931   assert(Node->getNumValues() == 2 && "Unexpected number of results!");
8932 
8933   // We're taking this node out of the chain, so we need to re-link things.
8934   SDValue InputChain = Node->getOperand(0);
8935   SDValue OutputChain = SDValue(Node, 1);
8936   ReplaceAllUsesOfValueWith(OutputChain, InputChain);
8937 
8938   SmallVector<SDValue, 3> Ops;
8939   for (unsigned i = 1, e = Node->getNumOperands(); i != e; ++i)
8940     Ops.push_back(Node->getOperand(i));
8941 
8942   SDVTList VTs = getVTList(Node->getValueType(0));
8943   SDNode *Res = MorphNodeTo(Node, NewOpc, VTs, Ops);
8944 
8945   // MorphNodeTo can operate in two ways: if an existing node with the
8946   // specified operands exists, it can just return it.  Otherwise, it
8947   // updates the node in place to have the requested operands.
8948   if (Res == Node) {
8949     // If we updated the node in place, reset the node ID.  To the isel,
8950     // this should be just like a newly allocated machine node.
8951     Res->setNodeId(-1);
8952   } else {
8953     ReplaceAllUsesWith(Node, Res);
8954     RemoveDeadNode(Node);
8955   }
8956 
8957   return Res;
8958 }
8959 
8960 /// getMachineNode - These are used for target selectors to create a new node
8961 /// with specified return type(s), MachineInstr opcode, and operands.
8962 ///
8963 /// Note that getMachineNode returns the resultant node.  If there is already a
8964 /// node of the specified opcode and operands, it returns that node instead of
8965 /// the current one.
8966 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
8967                                             EVT VT) {
8968   SDVTList VTs = getVTList(VT);
8969   return getMachineNode(Opcode, dl, VTs, None);
8970 }
8971 
8972 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
8973                                             EVT VT, SDValue Op1) {
8974   SDVTList VTs = getVTList(VT);
8975   SDValue Ops[] = { Op1 };
8976   return getMachineNode(Opcode, dl, VTs, Ops);
8977 }
8978 
8979 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
8980                                             EVT VT, SDValue Op1, SDValue Op2) {
8981   SDVTList VTs = getVTList(VT);
8982   SDValue Ops[] = { Op1, Op2 };
8983   return getMachineNode(Opcode, dl, VTs, Ops);
8984 }
8985 
8986 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
8987                                             EVT VT, SDValue Op1, SDValue Op2,
8988                                             SDValue Op3) {
8989   SDVTList VTs = getVTList(VT);
8990   SDValue Ops[] = { Op1, Op2, Op3 };
8991   return getMachineNode(Opcode, dl, VTs, Ops);
8992 }
8993 
8994 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
8995                                             EVT VT, ArrayRef<SDValue> Ops) {
8996   SDVTList VTs = getVTList(VT);
8997   return getMachineNode(Opcode, dl, VTs, Ops);
8998 }
8999 
9000 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9001                                             EVT VT1, EVT VT2, SDValue Op1,
9002                                             SDValue Op2) {
9003   SDVTList VTs = getVTList(VT1, VT2);
9004   SDValue Ops[] = { Op1, Op2 };
9005   return getMachineNode(Opcode, dl, VTs, Ops);
9006 }
9007 
9008 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9009                                             EVT VT1, EVT VT2, SDValue Op1,
9010                                             SDValue Op2, SDValue Op3) {
9011   SDVTList VTs = getVTList(VT1, VT2);
9012   SDValue Ops[] = { Op1, Op2, Op3 };
9013   return getMachineNode(Opcode, dl, VTs, Ops);
9014 }
9015 
9016 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9017                                             EVT VT1, EVT VT2,
9018                                             ArrayRef<SDValue> Ops) {
9019   SDVTList VTs = getVTList(VT1, VT2);
9020   return getMachineNode(Opcode, dl, VTs, Ops);
9021 }
9022 
9023 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9024                                             EVT VT1, EVT VT2, EVT VT3,
9025                                             SDValue Op1, SDValue Op2) {
9026   SDVTList VTs = getVTList(VT1, VT2, VT3);
9027   SDValue Ops[] = { Op1, Op2 };
9028   return getMachineNode(Opcode, dl, VTs, Ops);
9029 }
9030 
9031 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9032                                             EVT VT1, EVT VT2, EVT VT3,
9033                                             SDValue Op1, SDValue Op2,
9034                                             SDValue Op3) {
9035   SDVTList VTs = getVTList(VT1, VT2, VT3);
9036   SDValue Ops[] = { Op1, Op2, Op3 };
9037   return getMachineNode(Opcode, dl, VTs, Ops);
9038 }
9039 
9040 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9041                                             EVT VT1, EVT VT2, EVT VT3,
9042                                             ArrayRef<SDValue> Ops) {
9043   SDVTList VTs = getVTList(VT1, VT2, VT3);
9044   return getMachineNode(Opcode, dl, VTs, Ops);
9045 }
9046 
9047 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9048                                             ArrayRef<EVT> ResultTys,
9049                                             ArrayRef<SDValue> Ops) {
9050   SDVTList VTs = getVTList(ResultTys);
9051   return getMachineNode(Opcode, dl, VTs, Ops);
9052 }
9053 
9054 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &DL,
9055                                             SDVTList VTs,
9056                                             ArrayRef<SDValue> Ops) {
9057   bool DoCSE = VTs.VTs[VTs.NumVTs-1] != MVT::Glue;
9058   MachineSDNode *N;
9059   void *IP = nullptr;
9060 
9061   if (DoCSE) {
9062     FoldingSetNodeID ID;
9063     AddNodeIDNode(ID, ~Opcode, VTs, Ops);
9064     IP = nullptr;
9065     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
9066       return cast<MachineSDNode>(UpdateSDLocOnMergeSDNode(E, DL));
9067     }
9068   }
9069 
9070   // Allocate a new MachineSDNode.
9071   N = newSDNode<MachineSDNode>(~Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
9072   createOperands(N, Ops);
9073 
9074   if (DoCSE)
9075     CSEMap.InsertNode(N, IP);
9076 
9077   InsertNode(N);
9078   NewSDValueDbgMsg(SDValue(N, 0), "Creating new machine node: ", this);
9079   return N;
9080 }
9081 
9082 /// getTargetExtractSubreg - A convenience function for creating
9083 /// TargetOpcode::EXTRACT_SUBREG nodes.
9084 SDValue SelectionDAG::getTargetExtractSubreg(int SRIdx, const SDLoc &DL, EVT VT,
9085                                              SDValue Operand) {
9086   SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32);
9087   SDNode *Subreg = getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL,
9088                                   VT, Operand, SRIdxVal);
9089   return SDValue(Subreg, 0);
9090 }
9091 
9092 /// getTargetInsertSubreg - A convenience function for creating
9093 /// TargetOpcode::INSERT_SUBREG nodes.
9094 SDValue SelectionDAG::getTargetInsertSubreg(int SRIdx, const SDLoc &DL, EVT VT,
9095                                             SDValue Operand, SDValue Subreg) {
9096   SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32);
9097   SDNode *Result = getMachineNode(TargetOpcode::INSERT_SUBREG, DL,
9098                                   VT, Operand, Subreg, SRIdxVal);
9099   return SDValue(Result, 0);
9100 }
9101 
9102 /// getNodeIfExists - Get the specified node if it's already available, or
9103 /// else return NULL.
9104 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList,
9105                                       ArrayRef<SDValue> Ops) {
9106   SDNodeFlags Flags;
9107   if (Inserter)
9108     Flags = Inserter->getFlags();
9109   return getNodeIfExists(Opcode, VTList, Ops, Flags);
9110 }
9111 
9112 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList,
9113                                       ArrayRef<SDValue> Ops,
9114                                       const SDNodeFlags Flags) {
9115   if (VTList.VTs[VTList.NumVTs - 1] != MVT::Glue) {
9116     FoldingSetNodeID ID;
9117     AddNodeIDNode(ID, Opcode, VTList, Ops);
9118     void *IP = nullptr;
9119     if (SDNode *E = FindNodeOrInsertPos(ID, SDLoc(), IP)) {
9120       E->intersectFlagsWith(Flags);
9121       return E;
9122     }
9123   }
9124   return nullptr;
9125 }
9126 
9127 /// doesNodeExist - Check if a node exists without modifying its flags.
9128 bool SelectionDAG::doesNodeExist(unsigned Opcode, SDVTList VTList,
9129                                  ArrayRef<SDValue> Ops) {
9130   if (VTList.VTs[VTList.NumVTs - 1] != MVT::Glue) {
9131     FoldingSetNodeID ID;
9132     AddNodeIDNode(ID, Opcode, VTList, Ops);
9133     void *IP = nullptr;
9134     if (FindNodeOrInsertPos(ID, SDLoc(), IP))
9135       return true;
9136   }
9137   return false;
9138 }
9139 
9140 /// getDbgValue - Creates a SDDbgValue node.
9141 ///
9142 /// SDNode
9143 SDDbgValue *SelectionDAG::getDbgValue(DIVariable *Var, DIExpression *Expr,
9144                                       SDNode *N, unsigned R, bool IsIndirect,
9145                                       const DebugLoc &DL, unsigned O) {
9146   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
9147          "Expected inlined-at fields to agree");
9148   return new (DbgInfo->getAlloc())
9149       SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromNode(N, R),
9150                  {}, IsIndirect, DL, O,
9151                  /*IsVariadic=*/false);
9152 }
9153 
9154 /// Constant
9155 SDDbgValue *SelectionDAG::getConstantDbgValue(DIVariable *Var,
9156                                               DIExpression *Expr,
9157                                               const Value *C,
9158                                               const DebugLoc &DL, unsigned O) {
9159   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
9160          "Expected inlined-at fields to agree");
9161   return new (DbgInfo->getAlloc())
9162       SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromConst(C), {},
9163                  /*IsIndirect=*/false, DL, O,
9164                  /*IsVariadic=*/false);
9165 }
9166 
9167 /// FrameIndex
9168 SDDbgValue *SelectionDAG::getFrameIndexDbgValue(DIVariable *Var,
9169                                                 DIExpression *Expr, unsigned FI,
9170                                                 bool IsIndirect,
9171                                                 const DebugLoc &DL,
9172                                                 unsigned O) {
9173   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
9174          "Expected inlined-at fields to agree");
9175   return getFrameIndexDbgValue(Var, Expr, FI, {}, IsIndirect, DL, O);
9176 }
9177 
9178 /// FrameIndex with dependencies
9179 SDDbgValue *SelectionDAG::getFrameIndexDbgValue(DIVariable *Var,
9180                                                 DIExpression *Expr, unsigned FI,
9181                                                 ArrayRef<SDNode *> Dependencies,
9182                                                 bool IsIndirect,
9183                                                 const DebugLoc &DL,
9184                                                 unsigned O) {
9185   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
9186          "Expected inlined-at fields to agree");
9187   return new (DbgInfo->getAlloc())
9188       SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromFrameIdx(FI),
9189                  Dependencies, IsIndirect, DL, O,
9190                  /*IsVariadic=*/false);
9191 }
9192 
9193 /// VReg
9194 SDDbgValue *SelectionDAG::getVRegDbgValue(DIVariable *Var, DIExpression *Expr,
9195                                           unsigned VReg, bool IsIndirect,
9196                                           const DebugLoc &DL, unsigned O) {
9197   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
9198          "Expected inlined-at fields to agree");
9199   return new (DbgInfo->getAlloc())
9200       SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromVReg(VReg),
9201                  {}, IsIndirect, DL, O,
9202                  /*IsVariadic=*/false);
9203 }
9204 
9205 SDDbgValue *SelectionDAG::getDbgValueList(DIVariable *Var, DIExpression *Expr,
9206                                           ArrayRef<SDDbgOperand> Locs,
9207                                           ArrayRef<SDNode *> Dependencies,
9208                                           bool IsIndirect, const DebugLoc &DL,
9209                                           unsigned O, bool IsVariadic) {
9210   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
9211          "Expected inlined-at fields to agree");
9212   return new (DbgInfo->getAlloc())
9213       SDDbgValue(DbgInfo->getAlloc(), Var, Expr, Locs, Dependencies, IsIndirect,
9214                  DL, O, IsVariadic);
9215 }
9216 
9217 void SelectionDAG::transferDbgValues(SDValue From, SDValue To,
9218                                      unsigned OffsetInBits, unsigned SizeInBits,
9219                                      bool InvalidateDbg) {
9220   SDNode *FromNode = From.getNode();
9221   SDNode *ToNode = To.getNode();
9222   assert(FromNode && ToNode && "Can't modify dbg values");
9223 
9224   // PR35338
9225   // TODO: assert(From != To && "Redundant dbg value transfer");
9226   // TODO: assert(FromNode != ToNode && "Intranode dbg value transfer");
9227   if (From == To || FromNode == ToNode)
9228     return;
9229 
9230   if (!FromNode->getHasDebugValue())
9231     return;
9232 
9233   SDDbgOperand FromLocOp =
9234       SDDbgOperand::fromNode(From.getNode(), From.getResNo());
9235   SDDbgOperand ToLocOp = SDDbgOperand::fromNode(To.getNode(), To.getResNo());
9236 
9237   SmallVector<SDDbgValue *, 2> ClonedDVs;
9238   for (SDDbgValue *Dbg : GetDbgValues(FromNode)) {
9239     if (Dbg->isInvalidated())
9240       continue;
9241 
9242     // TODO: assert(!Dbg->isInvalidated() && "Transfer of invalid dbg value");
9243 
9244     // Create a new location ops vector that is equal to the old vector, but
9245     // with each instance of FromLocOp replaced with ToLocOp.
9246     bool Changed = false;
9247     auto NewLocOps = Dbg->copyLocationOps();
9248     std::replace_if(
9249         NewLocOps.begin(), NewLocOps.end(),
9250         [&Changed, FromLocOp](const SDDbgOperand &Op) {
9251           bool Match = Op == FromLocOp;
9252           Changed |= Match;
9253           return Match;
9254         },
9255         ToLocOp);
9256     // Ignore this SDDbgValue if we didn't find a matching location.
9257     if (!Changed)
9258       continue;
9259 
9260     DIVariable *Var = Dbg->getVariable();
9261     auto *Expr = Dbg->getExpression();
9262     // If a fragment is requested, update the expression.
9263     if (SizeInBits) {
9264       // When splitting a larger (e.g., sign-extended) value whose
9265       // lower bits are described with an SDDbgValue, do not attempt
9266       // to transfer the SDDbgValue to the upper bits.
9267       if (auto FI = Expr->getFragmentInfo())
9268         if (OffsetInBits + SizeInBits > FI->SizeInBits)
9269           continue;
9270       auto Fragment = DIExpression::createFragmentExpression(Expr, OffsetInBits,
9271                                                              SizeInBits);
9272       if (!Fragment)
9273         continue;
9274       Expr = *Fragment;
9275     }
9276 
9277     auto AdditionalDependencies = Dbg->getAdditionalDependencies();
9278     // Clone the SDDbgValue and move it to To.
9279     SDDbgValue *Clone = getDbgValueList(
9280         Var, Expr, NewLocOps, AdditionalDependencies, Dbg->isIndirect(),
9281         Dbg->getDebugLoc(), std::max(ToNode->getIROrder(), Dbg->getOrder()),
9282         Dbg->isVariadic());
9283     ClonedDVs.push_back(Clone);
9284 
9285     if (InvalidateDbg) {
9286       // Invalidate value and indicate the SDDbgValue should not be emitted.
9287       Dbg->setIsInvalidated();
9288       Dbg->setIsEmitted();
9289     }
9290   }
9291 
9292   for (SDDbgValue *Dbg : ClonedDVs) {
9293     assert(is_contained(Dbg->getSDNodes(), ToNode) &&
9294            "Transferred DbgValues should depend on the new SDNode");
9295     AddDbgValue(Dbg, false);
9296   }
9297 }
9298 
9299 void SelectionDAG::salvageDebugInfo(SDNode &N) {
9300   if (!N.getHasDebugValue())
9301     return;
9302 
9303   SmallVector<SDDbgValue *, 2> ClonedDVs;
9304   for (auto DV : GetDbgValues(&N)) {
9305     if (DV->isInvalidated())
9306       continue;
9307     switch (N.getOpcode()) {
9308     default:
9309       break;
9310     case ISD::ADD:
9311       SDValue N0 = N.getOperand(0);
9312       SDValue N1 = N.getOperand(1);
9313       if (!isConstantIntBuildVectorOrConstantInt(N0) &&
9314           isConstantIntBuildVectorOrConstantInt(N1)) {
9315         uint64_t Offset = N.getConstantOperandVal(1);
9316 
9317         // Rewrite an ADD constant node into a DIExpression. Since we are
9318         // performing arithmetic to compute the variable's *value* in the
9319         // DIExpression, we need to mark the expression with a
9320         // DW_OP_stack_value.
9321         auto *DIExpr = DV->getExpression();
9322         auto NewLocOps = DV->copyLocationOps();
9323         bool Changed = false;
9324         for (size_t i = 0; i < NewLocOps.size(); ++i) {
9325           // We're not given a ResNo to compare against because the whole
9326           // node is going away. We know that any ISD::ADD only has one
9327           // result, so we can assume any node match is using the result.
9328           if (NewLocOps[i].getKind() != SDDbgOperand::SDNODE ||
9329               NewLocOps[i].getSDNode() != &N)
9330             continue;
9331           NewLocOps[i] = SDDbgOperand::fromNode(N0.getNode(), N0.getResNo());
9332           SmallVector<uint64_t, 3> ExprOps;
9333           DIExpression::appendOffset(ExprOps, Offset);
9334           DIExpr = DIExpression::appendOpsToArg(DIExpr, ExprOps, i, true);
9335           Changed = true;
9336         }
9337         (void)Changed;
9338         assert(Changed && "Salvage target doesn't use N");
9339 
9340         auto AdditionalDependencies = DV->getAdditionalDependencies();
9341         SDDbgValue *Clone = getDbgValueList(DV->getVariable(), DIExpr,
9342                                             NewLocOps, AdditionalDependencies,
9343                                             DV->isIndirect(), DV->getDebugLoc(),
9344                                             DV->getOrder(), DV->isVariadic());
9345         ClonedDVs.push_back(Clone);
9346         DV->setIsInvalidated();
9347         DV->setIsEmitted();
9348         LLVM_DEBUG(dbgs() << "SALVAGE: Rewriting";
9349                    N0.getNode()->dumprFull(this);
9350                    dbgs() << " into " << *DIExpr << '\n');
9351       }
9352     }
9353   }
9354 
9355   for (SDDbgValue *Dbg : ClonedDVs) {
9356     assert(!Dbg->getSDNodes().empty() &&
9357            "Salvaged DbgValue should depend on a new SDNode");
9358     AddDbgValue(Dbg, false);
9359   }
9360 }
9361 
9362 /// Creates a SDDbgLabel node.
9363 SDDbgLabel *SelectionDAG::getDbgLabel(DILabel *Label,
9364                                       const DebugLoc &DL, unsigned O) {
9365   assert(cast<DILabel>(Label)->isValidLocationForIntrinsic(DL) &&
9366          "Expected inlined-at fields to agree");
9367   return new (DbgInfo->getAlloc()) SDDbgLabel(Label, DL, O);
9368 }
9369 
9370 namespace {
9371 
9372 /// RAUWUpdateListener - Helper for ReplaceAllUsesWith - When the node
9373 /// pointed to by a use iterator is deleted, increment the use iterator
9374 /// so that it doesn't dangle.
9375 ///
9376 class RAUWUpdateListener : public SelectionDAG::DAGUpdateListener {
9377   SDNode::use_iterator &UI;
9378   SDNode::use_iterator &UE;
9379 
9380   void NodeDeleted(SDNode *N, SDNode *E) override {
9381     // Increment the iterator as needed.
9382     while (UI != UE && N == *UI)
9383       ++UI;
9384   }
9385 
9386 public:
9387   RAUWUpdateListener(SelectionDAG &d,
9388                      SDNode::use_iterator &ui,
9389                      SDNode::use_iterator &ue)
9390     : SelectionDAG::DAGUpdateListener(d), UI(ui), UE(ue) {}
9391 };
9392 
9393 } // end anonymous namespace
9394 
9395 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
9396 /// This can cause recursive merging of nodes in the DAG.
9397 ///
9398 /// This version assumes From has a single result value.
9399 ///
9400 void SelectionDAG::ReplaceAllUsesWith(SDValue FromN, SDValue To) {
9401   SDNode *From = FromN.getNode();
9402   assert(From->getNumValues() == 1 && FromN.getResNo() == 0 &&
9403          "Cannot replace with this method!");
9404   assert(From != To.getNode() && "Cannot replace uses of with self");
9405 
9406   // Preserve Debug Values
9407   transferDbgValues(FromN, To);
9408 
9409   // Iterate over all the existing uses of From. New uses will be added
9410   // to the beginning of the use list, which we avoid visiting.
9411   // This specifically avoids visiting uses of From that arise while the
9412   // replacement is happening, because any such uses would be the result
9413   // of CSE: If an existing node looks like From after one of its operands
9414   // is replaced by To, we don't want to replace of all its users with To
9415   // too. See PR3018 for more info.
9416   SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
9417   RAUWUpdateListener Listener(*this, UI, UE);
9418   while (UI != UE) {
9419     SDNode *User = *UI;
9420 
9421     // This node is about to morph, remove its old self from the CSE maps.
9422     RemoveNodeFromCSEMaps(User);
9423 
9424     // A user can appear in a use list multiple times, and when this
9425     // happens the uses are usually next to each other in the list.
9426     // To help reduce the number of CSE recomputations, process all
9427     // the uses of this user that we can find this way.
9428     do {
9429       SDUse &Use = UI.getUse();
9430       ++UI;
9431       Use.set(To);
9432       if (To->isDivergent() != From->isDivergent())
9433         updateDivergence(User);
9434     } while (UI != UE && *UI == User);
9435     // Now that we have modified User, add it back to the CSE maps.  If it
9436     // already exists there, recursively merge the results together.
9437     AddModifiedNodeToCSEMaps(User);
9438   }
9439 
9440   // If we just RAUW'd the root, take note.
9441   if (FromN == getRoot())
9442     setRoot(To);
9443 }
9444 
9445 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
9446 /// This can cause recursive merging of nodes in the DAG.
9447 ///
9448 /// This version assumes that for each value of From, there is a
9449 /// corresponding value in To in the same position with the same type.
9450 ///
9451 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, SDNode *To) {
9452 #ifndef NDEBUG
9453   for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
9454     assert((!From->hasAnyUseOfValue(i) ||
9455             From->getValueType(i) == To->getValueType(i)) &&
9456            "Cannot use this version of ReplaceAllUsesWith!");
9457 #endif
9458 
9459   // Handle the trivial case.
9460   if (From == To)
9461     return;
9462 
9463   // Preserve Debug Info. Only do this if there's a use.
9464   for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
9465     if (From->hasAnyUseOfValue(i)) {
9466       assert((i < To->getNumValues()) && "Invalid To location");
9467       transferDbgValues(SDValue(From, i), SDValue(To, i));
9468     }
9469 
9470   // Iterate over just the existing users of From. See the comments in
9471   // the ReplaceAllUsesWith above.
9472   SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
9473   RAUWUpdateListener Listener(*this, UI, UE);
9474   while (UI != UE) {
9475     SDNode *User = *UI;
9476 
9477     // This node is about to morph, remove its old self from the CSE maps.
9478     RemoveNodeFromCSEMaps(User);
9479 
9480     // A user can appear in a use list multiple times, and when this
9481     // happens the uses are usually next to each other in the list.
9482     // To help reduce the number of CSE recomputations, process all
9483     // the uses of this user that we can find this way.
9484     do {
9485       SDUse &Use = UI.getUse();
9486       ++UI;
9487       Use.setNode(To);
9488       if (To->isDivergent() != From->isDivergent())
9489         updateDivergence(User);
9490     } while (UI != UE && *UI == User);
9491 
9492     // Now that we have modified User, add it back to the CSE maps.  If it
9493     // already exists there, recursively merge the results together.
9494     AddModifiedNodeToCSEMaps(User);
9495   }
9496 
9497   // If we just RAUW'd the root, take note.
9498   if (From == getRoot().getNode())
9499     setRoot(SDValue(To, getRoot().getResNo()));
9500 }
9501 
9502 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
9503 /// This can cause recursive merging of nodes in the DAG.
9504 ///
9505 /// This version can replace From with any result values.  To must match the
9506 /// number and types of values returned by From.
9507 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, const SDValue *To) {
9508   if (From->getNumValues() == 1)  // Handle the simple case efficiently.
9509     return ReplaceAllUsesWith(SDValue(From, 0), To[0]);
9510 
9511   // Preserve Debug Info.
9512   for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
9513     transferDbgValues(SDValue(From, i), To[i]);
9514 
9515   // Iterate over just the existing users of From. See the comments in
9516   // the ReplaceAllUsesWith above.
9517   SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
9518   RAUWUpdateListener Listener(*this, UI, UE);
9519   while (UI != UE) {
9520     SDNode *User = *UI;
9521 
9522     // This node is about to morph, remove its old self from the CSE maps.
9523     RemoveNodeFromCSEMaps(User);
9524 
9525     // A user can appear in a use list multiple times, and when this happens the
9526     // uses are usually next to each other in the list.  To help reduce the
9527     // number of CSE and divergence recomputations, process all the uses of this
9528     // user that we can find this way.
9529     bool To_IsDivergent = false;
9530     do {
9531       SDUse &Use = UI.getUse();
9532       const SDValue &ToOp = To[Use.getResNo()];
9533       ++UI;
9534       Use.set(ToOp);
9535       To_IsDivergent |= ToOp->isDivergent();
9536     } while (UI != UE && *UI == User);
9537 
9538     if (To_IsDivergent != From->isDivergent())
9539       updateDivergence(User);
9540 
9541     // Now that we have modified User, add it back to the CSE maps.  If it
9542     // already exists there, recursively merge the results together.
9543     AddModifiedNodeToCSEMaps(User);
9544   }
9545 
9546   // If we just RAUW'd the root, take note.
9547   if (From == getRoot().getNode())
9548     setRoot(SDValue(To[getRoot().getResNo()]));
9549 }
9550 
9551 /// ReplaceAllUsesOfValueWith - Replace any uses of From with To, leaving
9552 /// uses of other values produced by From.getNode() alone.  The Deleted
9553 /// vector is handled the same way as for ReplaceAllUsesWith.
9554 void SelectionDAG::ReplaceAllUsesOfValueWith(SDValue From, SDValue To){
9555   // Handle the really simple, really trivial case efficiently.
9556   if (From == To) return;
9557 
9558   // Handle the simple, trivial, case efficiently.
9559   if (From.getNode()->getNumValues() == 1) {
9560     ReplaceAllUsesWith(From, To);
9561     return;
9562   }
9563 
9564   // Preserve Debug Info.
9565   transferDbgValues(From, To);
9566 
9567   // Iterate over just the existing users of From. See the comments in
9568   // the ReplaceAllUsesWith above.
9569   SDNode::use_iterator UI = From.getNode()->use_begin(),
9570                        UE = From.getNode()->use_end();
9571   RAUWUpdateListener Listener(*this, UI, UE);
9572   while (UI != UE) {
9573     SDNode *User = *UI;
9574     bool UserRemovedFromCSEMaps = false;
9575 
9576     // A user can appear in a use list multiple times, and when this
9577     // happens the uses are usually next to each other in the list.
9578     // To help reduce the number of CSE recomputations, process all
9579     // the uses of this user that we can find this way.
9580     do {
9581       SDUse &Use = UI.getUse();
9582 
9583       // Skip uses of different values from the same node.
9584       if (Use.getResNo() != From.getResNo()) {
9585         ++UI;
9586         continue;
9587       }
9588 
9589       // If this node hasn't been modified yet, it's still in the CSE maps,
9590       // so remove its old self from the CSE maps.
9591       if (!UserRemovedFromCSEMaps) {
9592         RemoveNodeFromCSEMaps(User);
9593         UserRemovedFromCSEMaps = true;
9594       }
9595 
9596       ++UI;
9597       Use.set(To);
9598       if (To->isDivergent() != From->isDivergent())
9599         updateDivergence(User);
9600     } while (UI != UE && *UI == User);
9601     // We are iterating over all uses of the From node, so if a use
9602     // doesn't use the specific value, no changes are made.
9603     if (!UserRemovedFromCSEMaps)
9604       continue;
9605 
9606     // Now that we have modified User, add it back to the CSE maps.  If it
9607     // already exists there, recursively merge the results together.
9608     AddModifiedNodeToCSEMaps(User);
9609   }
9610 
9611   // If we just RAUW'd the root, take note.
9612   if (From == getRoot())
9613     setRoot(To);
9614 }
9615 
9616 namespace {
9617 
9618   /// UseMemo - This class is used by SelectionDAG::ReplaceAllUsesOfValuesWith
9619   /// to record information about a use.
9620   struct UseMemo {
9621     SDNode *User;
9622     unsigned Index;
9623     SDUse *Use;
9624   };
9625 
9626   /// operator< - Sort Memos by User.
9627   bool operator<(const UseMemo &L, const UseMemo &R) {
9628     return (intptr_t)L.User < (intptr_t)R.User;
9629   }
9630 
9631 } // end anonymous namespace
9632 
9633 bool SelectionDAG::calculateDivergence(SDNode *N) {
9634   if (TLI->isSDNodeAlwaysUniform(N)) {
9635     assert(!TLI->isSDNodeSourceOfDivergence(N, FLI, DA) &&
9636            "Conflicting divergence information!");
9637     return false;
9638   }
9639   if (TLI->isSDNodeSourceOfDivergence(N, FLI, DA))
9640     return true;
9641   for (auto &Op : N->ops()) {
9642     if (Op.Val.getValueType() != MVT::Other && Op.getNode()->isDivergent())
9643       return true;
9644   }
9645   return false;
9646 }
9647 
9648 void SelectionDAG::updateDivergence(SDNode *N) {
9649   SmallVector<SDNode *, 16> Worklist(1, N);
9650   do {
9651     N = Worklist.pop_back_val();
9652     bool IsDivergent = calculateDivergence(N);
9653     if (N->SDNodeBits.IsDivergent != IsDivergent) {
9654       N->SDNodeBits.IsDivergent = IsDivergent;
9655       llvm::append_range(Worklist, N->uses());
9656     }
9657   } while (!Worklist.empty());
9658 }
9659 
9660 void SelectionDAG::CreateTopologicalOrder(std::vector<SDNode *> &Order) {
9661   DenseMap<SDNode *, unsigned> Degree;
9662   Order.reserve(AllNodes.size());
9663   for (auto &N : allnodes()) {
9664     unsigned NOps = N.getNumOperands();
9665     Degree[&N] = NOps;
9666     if (0 == NOps)
9667       Order.push_back(&N);
9668   }
9669   for (size_t I = 0; I != Order.size(); ++I) {
9670     SDNode *N = Order[I];
9671     for (auto U : N->uses()) {
9672       unsigned &UnsortedOps = Degree[U];
9673       if (0 == --UnsortedOps)
9674         Order.push_back(U);
9675     }
9676   }
9677 }
9678 
9679 #ifndef NDEBUG
9680 void SelectionDAG::VerifyDAGDivergence() {
9681   std::vector<SDNode *> TopoOrder;
9682   CreateTopologicalOrder(TopoOrder);
9683   for (auto *N : TopoOrder) {
9684     assert(calculateDivergence(N) == N->isDivergent() &&
9685            "Divergence bit inconsistency detected");
9686   }
9687 }
9688 #endif
9689 
9690 /// ReplaceAllUsesOfValuesWith - Replace any uses of From with To, leaving
9691 /// uses of other values produced by From.getNode() alone.  The same value
9692 /// may appear in both the From and To list.  The Deleted vector is
9693 /// handled the same way as for ReplaceAllUsesWith.
9694 void SelectionDAG::ReplaceAllUsesOfValuesWith(const SDValue *From,
9695                                               const SDValue *To,
9696                                               unsigned Num){
9697   // Handle the simple, trivial case efficiently.
9698   if (Num == 1)
9699     return ReplaceAllUsesOfValueWith(*From, *To);
9700 
9701   transferDbgValues(*From, *To);
9702 
9703   // Read up all the uses and make records of them. This helps
9704   // processing new uses that are introduced during the
9705   // replacement process.
9706   SmallVector<UseMemo, 4> Uses;
9707   for (unsigned i = 0; i != Num; ++i) {
9708     unsigned FromResNo = From[i].getResNo();
9709     SDNode *FromNode = From[i].getNode();
9710     for (SDNode::use_iterator UI = FromNode->use_begin(),
9711          E = FromNode->use_end(); UI != E; ++UI) {
9712       SDUse &Use = UI.getUse();
9713       if (Use.getResNo() == FromResNo) {
9714         UseMemo Memo = { *UI, i, &Use };
9715         Uses.push_back(Memo);
9716       }
9717     }
9718   }
9719 
9720   // Sort the uses, so that all the uses from a given User are together.
9721   llvm::sort(Uses);
9722 
9723   for (unsigned UseIndex = 0, UseIndexEnd = Uses.size();
9724        UseIndex != UseIndexEnd; ) {
9725     // We know that this user uses some value of From.  If it is the right
9726     // value, update it.
9727     SDNode *User = Uses[UseIndex].User;
9728 
9729     // This node is about to morph, remove its old self from the CSE maps.
9730     RemoveNodeFromCSEMaps(User);
9731 
9732     // The Uses array is sorted, so all the uses for a given User
9733     // are next to each other in the list.
9734     // To help reduce the number of CSE recomputations, process all
9735     // the uses of this user that we can find this way.
9736     do {
9737       unsigned i = Uses[UseIndex].Index;
9738       SDUse &Use = *Uses[UseIndex].Use;
9739       ++UseIndex;
9740 
9741       Use.set(To[i]);
9742     } while (UseIndex != UseIndexEnd && Uses[UseIndex].User == User);
9743 
9744     // Now that we have modified User, add it back to the CSE maps.  If it
9745     // already exists there, recursively merge the results together.
9746     AddModifiedNodeToCSEMaps(User);
9747   }
9748 }
9749 
9750 /// AssignTopologicalOrder - Assign a unique node id for each node in the DAG
9751 /// based on their topological order. It returns the maximum id and a vector
9752 /// of the SDNodes* in assigned order by reference.
9753 unsigned SelectionDAG::AssignTopologicalOrder() {
9754   unsigned DAGSize = 0;
9755 
9756   // SortedPos tracks the progress of the algorithm. Nodes before it are
9757   // sorted, nodes after it are unsorted. When the algorithm completes
9758   // it is at the end of the list.
9759   allnodes_iterator SortedPos = allnodes_begin();
9760 
9761   // Visit all the nodes. Move nodes with no operands to the front of
9762   // the list immediately. Annotate nodes that do have operands with their
9763   // operand count. Before we do this, the Node Id fields of the nodes
9764   // may contain arbitrary values. After, the Node Id fields for nodes
9765   // before SortedPos will contain the topological sort index, and the
9766   // Node Id fields for nodes At SortedPos and after will contain the
9767   // count of outstanding operands.
9768   for (SDNode &N : llvm::make_early_inc_range(allnodes())) {
9769     checkForCycles(&N, this);
9770     unsigned Degree = N.getNumOperands();
9771     if (Degree == 0) {
9772       // A node with no uses, add it to the result array immediately.
9773       N.setNodeId(DAGSize++);
9774       allnodes_iterator Q(&N);
9775       if (Q != SortedPos)
9776         SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(Q));
9777       assert(SortedPos != AllNodes.end() && "Overran node list");
9778       ++SortedPos;
9779     } else {
9780       // Temporarily use the Node Id as scratch space for the degree count.
9781       N.setNodeId(Degree);
9782     }
9783   }
9784 
9785   // Visit all the nodes. As we iterate, move nodes into sorted order,
9786   // such that by the time the end is reached all nodes will be sorted.
9787   for (SDNode &Node : allnodes()) {
9788     SDNode *N = &Node;
9789     checkForCycles(N, this);
9790     // N is in sorted position, so all its uses have one less operand
9791     // that needs to be sorted.
9792     for (SDNode *P : N->uses()) {
9793       unsigned Degree = P->getNodeId();
9794       assert(Degree != 0 && "Invalid node degree");
9795       --Degree;
9796       if (Degree == 0) {
9797         // All of P's operands are sorted, so P may sorted now.
9798         P->setNodeId(DAGSize++);
9799         if (P->getIterator() != SortedPos)
9800           SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(P));
9801         assert(SortedPos != AllNodes.end() && "Overran node list");
9802         ++SortedPos;
9803       } else {
9804         // Update P's outstanding operand count.
9805         P->setNodeId(Degree);
9806       }
9807     }
9808     if (Node.getIterator() == SortedPos) {
9809 #ifndef NDEBUG
9810       allnodes_iterator I(N);
9811       SDNode *S = &*++I;
9812       dbgs() << "Overran sorted position:\n";
9813       S->dumprFull(this); dbgs() << "\n";
9814       dbgs() << "Checking if this is due to cycles\n";
9815       checkForCycles(this, true);
9816 #endif
9817       llvm_unreachable(nullptr);
9818     }
9819   }
9820 
9821   assert(SortedPos == AllNodes.end() &&
9822          "Topological sort incomplete!");
9823   assert(AllNodes.front().getOpcode() == ISD::EntryToken &&
9824          "First node in topological sort is not the entry token!");
9825   assert(AllNodes.front().getNodeId() == 0 &&
9826          "First node in topological sort has non-zero id!");
9827   assert(AllNodes.front().getNumOperands() == 0 &&
9828          "First node in topological sort has operands!");
9829   assert(AllNodes.back().getNodeId() == (int)DAGSize-1 &&
9830          "Last node in topologic sort has unexpected id!");
9831   assert(AllNodes.back().use_empty() &&
9832          "Last node in topologic sort has users!");
9833   assert(DAGSize == allnodes_size() && "Node count mismatch!");
9834   return DAGSize;
9835 }
9836 
9837 /// AddDbgValue - Add a dbg_value SDNode. If SD is non-null that means the
9838 /// value is produced by SD.
9839 void SelectionDAG::AddDbgValue(SDDbgValue *DB, bool isParameter) {
9840   for (SDNode *SD : DB->getSDNodes()) {
9841     if (!SD)
9842       continue;
9843     assert(DbgInfo->getSDDbgValues(SD).empty() || SD->getHasDebugValue());
9844     SD->setHasDebugValue(true);
9845   }
9846   DbgInfo->add(DB, isParameter);
9847 }
9848 
9849 void SelectionDAG::AddDbgLabel(SDDbgLabel *DB) { DbgInfo->add(DB); }
9850 
9851 SDValue SelectionDAG::makeEquivalentMemoryOrdering(SDValue OldChain,
9852                                                    SDValue NewMemOpChain) {
9853   assert(isa<MemSDNode>(NewMemOpChain) && "Expected a memop node");
9854   assert(NewMemOpChain.getValueType() == MVT::Other && "Expected a token VT");
9855   // The new memory operation must have the same position as the old load in
9856   // terms of memory dependency. Create a TokenFactor for the old load and new
9857   // memory operation and update uses of the old load's output chain to use that
9858   // TokenFactor.
9859   if (OldChain == NewMemOpChain || OldChain.use_empty())
9860     return NewMemOpChain;
9861 
9862   SDValue TokenFactor = getNode(ISD::TokenFactor, SDLoc(OldChain), MVT::Other,
9863                                 OldChain, NewMemOpChain);
9864   ReplaceAllUsesOfValueWith(OldChain, TokenFactor);
9865   UpdateNodeOperands(TokenFactor.getNode(), OldChain, NewMemOpChain);
9866   return TokenFactor;
9867 }
9868 
9869 SDValue SelectionDAG::makeEquivalentMemoryOrdering(LoadSDNode *OldLoad,
9870                                                    SDValue NewMemOp) {
9871   assert(isa<MemSDNode>(NewMemOp.getNode()) && "Expected a memop node");
9872   SDValue OldChain = SDValue(OldLoad, 1);
9873   SDValue NewMemOpChain = NewMemOp.getValue(1);
9874   return makeEquivalentMemoryOrdering(OldChain, NewMemOpChain);
9875 }
9876 
9877 SDValue SelectionDAG::getSymbolFunctionGlobalAddress(SDValue Op,
9878                                                      Function **OutFunction) {
9879   assert(isa<ExternalSymbolSDNode>(Op) && "Node should be an ExternalSymbol");
9880 
9881   auto *Symbol = cast<ExternalSymbolSDNode>(Op)->getSymbol();
9882   auto *Module = MF->getFunction().getParent();
9883   auto *Function = Module->getFunction(Symbol);
9884 
9885   if (OutFunction != nullptr)
9886       *OutFunction = Function;
9887 
9888   if (Function != nullptr) {
9889     auto PtrTy = TLI->getPointerTy(getDataLayout(), Function->getAddressSpace());
9890     return getGlobalAddress(Function, SDLoc(Op), PtrTy);
9891   }
9892 
9893   std::string ErrorStr;
9894   raw_string_ostream ErrorFormatter(ErrorStr);
9895   ErrorFormatter << "Undefined external symbol ";
9896   ErrorFormatter << '"' << Symbol << '"';
9897   report_fatal_error(Twine(ErrorFormatter.str()));
9898 }
9899 
9900 //===----------------------------------------------------------------------===//
9901 //                              SDNode Class
9902 //===----------------------------------------------------------------------===//
9903 
9904 bool llvm::isNullConstant(SDValue V) {
9905   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
9906   return Const != nullptr && Const->isZero();
9907 }
9908 
9909 bool llvm::isNullFPConstant(SDValue V) {
9910   ConstantFPSDNode *Const = dyn_cast<ConstantFPSDNode>(V);
9911   return Const != nullptr && Const->isZero() && !Const->isNegative();
9912 }
9913 
9914 bool llvm::isAllOnesConstant(SDValue V) {
9915   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
9916   return Const != nullptr && Const->isAllOnes();
9917 }
9918 
9919 bool llvm::isOneConstant(SDValue V) {
9920   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
9921   return Const != nullptr && Const->isOne();
9922 }
9923 
9924 SDValue llvm::peekThroughBitcasts(SDValue V) {
9925   while (V.getOpcode() == ISD::BITCAST)
9926     V = V.getOperand(0);
9927   return V;
9928 }
9929 
9930 SDValue llvm::peekThroughOneUseBitcasts(SDValue V) {
9931   while (V.getOpcode() == ISD::BITCAST && V.getOperand(0).hasOneUse())
9932     V = V.getOperand(0);
9933   return V;
9934 }
9935 
9936 SDValue llvm::peekThroughExtractSubvectors(SDValue V) {
9937   while (V.getOpcode() == ISD::EXTRACT_SUBVECTOR)
9938     V = V.getOperand(0);
9939   return V;
9940 }
9941 
9942 bool llvm::isBitwiseNot(SDValue V, bool AllowUndefs) {
9943   if (V.getOpcode() != ISD::XOR)
9944     return false;
9945   V = peekThroughBitcasts(V.getOperand(1));
9946   unsigned NumBits = V.getScalarValueSizeInBits();
9947   ConstantSDNode *C =
9948       isConstOrConstSplat(V, AllowUndefs, /*AllowTruncation*/ true);
9949   return C && (C->getAPIntValue().countTrailingOnes() >= NumBits);
9950 }
9951 
9952 ConstantSDNode *llvm::isConstOrConstSplat(SDValue N, bool AllowUndefs,
9953                                           bool AllowTruncation) {
9954   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
9955     return CN;
9956 
9957   // SplatVectors can truncate their operands. Ignore that case here unless
9958   // AllowTruncation is set.
9959   if (N->getOpcode() == ISD::SPLAT_VECTOR) {
9960     EVT VecEltVT = N->getValueType(0).getVectorElementType();
9961     if (auto *CN = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
9962       EVT CVT = CN->getValueType(0);
9963       assert(CVT.bitsGE(VecEltVT) && "Illegal splat_vector element extension");
9964       if (AllowTruncation || CVT == VecEltVT)
9965         return CN;
9966     }
9967   }
9968 
9969   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
9970     BitVector UndefElements;
9971     ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
9972 
9973     // BuildVectors can truncate their operands. Ignore that case here unless
9974     // AllowTruncation is set.
9975     if (CN && (UndefElements.none() || AllowUndefs)) {
9976       EVT CVT = CN->getValueType(0);
9977       EVT NSVT = N.getValueType().getScalarType();
9978       assert(CVT.bitsGE(NSVT) && "Illegal build vector element extension");
9979       if (AllowTruncation || (CVT == NSVT))
9980         return CN;
9981     }
9982   }
9983 
9984   return nullptr;
9985 }
9986 
9987 ConstantSDNode *llvm::isConstOrConstSplat(SDValue N, const APInt &DemandedElts,
9988                                           bool AllowUndefs,
9989                                           bool AllowTruncation) {
9990   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
9991     return CN;
9992 
9993   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
9994     BitVector UndefElements;
9995     ConstantSDNode *CN = BV->getConstantSplatNode(DemandedElts, &UndefElements);
9996 
9997     // BuildVectors can truncate their operands. Ignore that case here unless
9998     // AllowTruncation is set.
9999     if (CN && (UndefElements.none() || AllowUndefs)) {
10000       EVT CVT = CN->getValueType(0);
10001       EVT NSVT = N.getValueType().getScalarType();
10002       assert(CVT.bitsGE(NSVT) && "Illegal build vector element extension");
10003       if (AllowTruncation || (CVT == NSVT))
10004         return CN;
10005     }
10006   }
10007 
10008   return nullptr;
10009 }
10010 
10011 ConstantFPSDNode *llvm::isConstOrConstSplatFP(SDValue N, bool AllowUndefs) {
10012   if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
10013     return CN;
10014 
10015   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
10016     BitVector UndefElements;
10017     ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements);
10018     if (CN && (UndefElements.none() || AllowUndefs))
10019       return CN;
10020   }
10021 
10022   if (N.getOpcode() == ISD::SPLAT_VECTOR)
10023     if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N.getOperand(0)))
10024       return CN;
10025 
10026   return nullptr;
10027 }
10028 
10029 ConstantFPSDNode *llvm::isConstOrConstSplatFP(SDValue N,
10030                                               const APInt &DemandedElts,
10031                                               bool AllowUndefs) {
10032   if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
10033     return CN;
10034 
10035   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
10036     BitVector UndefElements;
10037     ConstantFPSDNode *CN =
10038         BV->getConstantFPSplatNode(DemandedElts, &UndefElements);
10039     if (CN && (UndefElements.none() || AllowUndefs))
10040       return CN;
10041   }
10042 
10043   return nullptr;
10044 }
10045 
10046 bool llvm::isNullOrNullSplat(SDValue N, bool AllowUndefs) {
10047   // TODO: may want to use peekThroughBitcast() here.
10048   ConstantSDNode *C =
10049       isConstOrConstSplat(N, AllowUndefs, /*AllowTruncation=*/true);
10050   return C && C->isZero();
10051 }
10052 
10053 bool llvm::isOneOrOneSplat(SDValue N, bool AllowUndefs) {
10054   // TODO: may want to use peekThroughBitcast() here.
10055   unsigned BitWidth = N.getScalarValueSizeInBits();
10056   ConstantSDNode *C = isConstOrConstSplat(N, AllowUndefs);
10057   return C && C->isOne() && C->getValueSizeInBits(0) == BitWidth;
10058 }
10059 
10060 bool llvm::isAllOnesOrAllOnesSplat(SDValue N, bool AllowUndefs) {
10061   N = peekThroughBitcasts(N);
10062   unsigned BitWidth = N.getScalarValueSizeInBits();
10063   ConstantSDNode *C = isConstOrConstSplat(N, AllowUndefs);
10064   return C && C->isAllOnes() && C->getValueSizeInBits(0) == BitWidth;
10065 }
10066 
10067 HandleSDNode::~HandleSDNode() {
10068   DropOperands();
10069 }
10070 
10071 GlobalAddressSDNode::GlobalAddressSDNode(unsigned Opc, unsigned Order,
10072                                          const DebugLoc &DL,
10073                                          const GlobalValue *GA, EVT VT,
10074                                          int64_t o, unsigned TF)
10075     : SDNode(Opc, Order, DL, getSDVTList(VT)), Offset(o), TargetFlags(TF) {
10076   TheGlobal = GA;
10077 }
10078 
10079 AddrSpaceCastSDNode::AddrSpaceCastSDNode(unsigned Order, const DebugLoc &dl,
10080                                          EVT VT, unsigned SrcAS,
10081                                          unsigned DestAS)
10082     : SDNode(ISD::ADDRSPACECAST, Order, dl, getSDVTList(VT)),
10083       SrcAddrSpace(SrcAS), DestAddrSpace(DestAS) {}
10084 
10085 MemSDNode::MemSDNode(unsigned Opc, unsigned Order, const DebugLoc &dl,
10086                      SDVTList VTs, EVT memvt, MachineMemOperand *mmo)
10087     : SDNode(Opc, Order, dl, VTs), MemoryVT(memvt), MMO(mmo) {
10088   MemSDNodeBits.IsVolatile = MMO->isVolatile();
10089   MemSDNodeBits.IsNonTemporal = MMO->isNonTemporal();
10090   MemSDNodeBits.IsDereferenceable = MMO->isDereferenceable();
10091   MemSDNodeBits.IsInvariant = MMO->isInvariant();
10092 
10093   // We check here that the size of the memory operand fits within the size of
10094   // the MMO. This is because the MMO might indicate only a possible address
10095   // range instead of specifying the affected memory addresses precisely.
10096   // TODO: Make MachineMemOperands aware of scalable vectors.
10097   assert(memvt.getStoreSize().getKnownMinSize() <= MMO->getSize() &&
10098          "Size mismatch!");
10099 }
10100 
10101 /// Profile - Gather unique data for the node.
10102 ///
10103 void SDNode::Profile(FoldingSetNodeID &ID) const {
10104   AddNodeIDNode(ID, this);
10105 }
10106 
10107 namespace {
10108 
10109   struct EVTArray {
10110     std::vector<EVT> VTs;
10111 
10112     EVTArray() {
10113       VTs.reserve(MVT::VALUETYPE_SIZE);
10114       for (unsigned i = 0; i < MVT::VALUETYPE_SIZE; ++i)
10115         VTs.push_back(MVT((MVT::SimpleValueType)i));
10116     }
10117   };
10118 
10119 } // end anonymous namespace
10120 
10121 static ManagedStatic<std::set<EVT, EVT::compareRawBits>> EVTs;
10122 static ManagedStatic<EVTArray> SimpleVTArray;
10123 static ManagedStatic<sys::SmartMutex<true>> VTMutex;
10124 
10125 /// getValueTypeList - Return a pointer to the specified value type.
10126 ///
10127 const EVT *SDNode::getValueTypeList(EVT VT) {
10128   if (VT.isExtended()) {
10129     sys::SmartScopedLock<true> Lock(*VTMutex);
10130     return &(*EVTs->insert(VT).first);
10131   }
10132   assert(VT.getSimpleVT() < MVT::VALUETYPE_SIZE && "Value type out of range!");
10133   return &SimpleVTArray->VTs[VT.getSimpleVT().SimpleTy];
10134 }
10135 
10136 /// hasNUsesOfValue - Return true if there are exactly NUSES uses of the
10137 /// indicated value.  This method ignores uses of other values defined by this
10138 /// operation.
10139 bool SDNode::hasNUsesOfValue(unsigned NUses, unsigned Value) const {
10140   assert(Value < getNumValues() && "Bad value!");
10141 
10142   // TODO: Only iterate over uses of a given value of the node
10143   for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) {
10144     if (UI.getUse().getResNo() == Value) {
10145       if (NUses == 0)
10146         return false;
10147       --NUses;
10148     }
10149   }
10150 
10151   // Found exactly the right number of uses?
10152   return NUses == 0;
10153 }
10154 
10155 /// hasAnyUseOfValue - Return true if there are any use of the indicated
10156 /// value. This method ignores uses of other values defined by this operation.
10157 bool SDNode::hasAnyUseOfValue(unsigned Value) const {
10158   assert(Value < getNumValues() && "Bad value!");
10159 
10160   for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI)
10161     if (UI.getUse().getResNo() == Value)
10162       return true;
10163 
10164   return false;
10165 }
10166 
10167 /// isOnlyUserOf - Return true if this node is the only use of N.
10168 bool SDNode::isOnlyUserOf(const SDNode *N) const {
10169   bool Seen = false;
10170   for (const SDNode *User : N->uses()) {
10171     if (User == this)
10172       Seen = true;
10173     else
10174       return false;
10175   }
10176 
10177   return Seen;
10178 }
10179 
10180 /// Return true if the only users of N are contained in Nodes.
10181 bool SDNode::areOnlyUsersOf(ArrayRef<const SDNode *> Nodes, const SDNode *N) {
10182   bool Seen = false;
10183   for (const SDNode *User : N->uses()) {
10184     if (llvm::is_contained(Nodes, User))
10185       Seen = true;
10186     else
10187       return false;
10188   }
10189 
10190   return Seen;
10191 }
10192 
10193 /// isOperand - Return true if this node is an operand of N.
10194 bool SDValue::isOperandOf(const SDNode *N) const {
10195   return is_contained(N->op_values(), *this);
10196 }
10197 
10198 bool SDNode::isOperandOf(const SDNode *N) const {
10199   return any_of(N->op_values(),
10200                 [this](SDValue Op) { return this == Op.getNode(); });
10201 }
10202 
10203 /// reachesChainWithoutSideEffects - Return true if this operand (which must
10204 /// be a chain) reaches the specified operand without crossing any
10205 /// side-effecting instructions on any chain path.  In practice, this looks
10206 /// through token factors and non-volatile loads.  In order to remain efficient,
10207 /// this only looks a couple of nodes in, it does not do an exhaustive search.
10208 ///
10209 /// Note that we only need to examine chains when we're searching for
10210 /// side-effects; SelectionDAG requires that all side-effects are represented
10211 /// by chains, even if another operand would force a specific ordering. This
10212 /// constraint is necessary to allow transformations like splitting loads.
10213 bool SDValue::reachesChainWithoutSideEffects(SDValue Dest,
10214                                              unsigned Depth) const {
10215   if (*this == Dest) return true;
10216 
10217   // Don't search too deeply, we just want to be able to see through
10218   // TokenFactor's etc.
10219   if (Depth == 0) return false;
10220 
10221   // If this is a token factor, all inputs to the TF happen in parallel.
10222   if (getOpcode() == ISD::TokenFactor) {
10223     // First, try a shallow search.
10224     if (is_contained((*this)->ops(), Dest)) {
10225       // We found the chain we want as an operand of this TokenFactor.
10226       // Essentially, we reach the chain without side-effects if we could
10227       // serialize the TokenFactor into a simple chain of operations with
10228       // Dest as the last operation. This is automatically true if the
10229       // chain has one use: there are no other ordering constraints.
10230       // If the chain has more than one use, we give up: some other
10231       // use of Dest might force a side-effect between Dest and the current
10232       // node.
10233       if (Dest.hasOneUse())
10234         return true;
10235     }
10236     // Next, try a deep search: check whether every operand of the TokenFactor
10237     // reaches Dest.
10238     return llvm::all_of((*this)->ops(), [=](SDValue Op) {
10239       return Op.reachesChainWithoutSideEffects(Dest, Depth - 1);
10240     });
10241   }
10242 
10243   // Loads don't have side effects, look through them.
10244   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(*this)) {
10245     if (Ld->isUnordered())
10246       return Ld->getChain().reachesChainWithoutSideEffects(Dest, Depth-1);
10247   }
10248   return false;
10249 }
10250 
10251 bool SDNode::hasPredecessor(const SDNode *N) const {
10252   SmallPtrSet<const SDNode *, 32> Visited;
10253   SmallVector<const SDNode *, 16> Worklist;
10254   Worklist.push_back(this);
10255   return hasPredecessorHelper(N, Visited, Worklist);
10256 }
10257 
10258 void SDNode::intersectFlagsWith(const SDNodeFlags Flags) {
10259   this->Flags.intersectWith(Flags);
10260 }
10261 
10262 SDValue
10263 SelectionDAG::matchBinOpReduction(SDNode *Extract, ISD::NodeType &BinOp,
10264                                   ArrayRef<ISD::NodeType> CandidateBinOps,
10265                                   bool AllowPartials) {
10266   // The pattern must end in an extract from index 0.
10267   if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10268       !isNullConstant(Extract->getOperand(1)))
10269     return SDValue();
10270 
10271   // Match against one of the candidate binary ops.
10272   SDValue Op = Extract->getOperand(0);
10273   if (llvm::none_of(CandidateBinOps, [Op](ISD::NodeType BinOp) {
10274         return Op.getOpcode() == unsigned(BinOp);
10275       }))
10276     return SDValue();
10277 
10278   // Floating-point reductions may require relaxed constraints on the final step
10279   // of the reduction because they may reorder intermediate operations.
10280   unsigned CandidateBinOp = Op.getOpcode();
10281   if (Op.getValueType().isFloatingPoint()) {
10282     SDNodeFlags Flags = Op->getFlags();
10283     switch (CandidateBinOp) {
10284     case ISD::FADD:
10285       if (!Flags.hasNoSignedZeros() || !Flags.hasAllowReassociation())
10286         return SDValue();
10287       break;
10288     default:
10289       llvm_unreachable("Unhandled FP opcode for binop reduction");
10290     }
10291   }
10292 
10293   // Matching failed - attempt to see if we did enough stages that a partial
10294   // reduction from a subvector is possible.
10295   auto PartialReduction = [&](SDValue Op, unsigned NumSubElts) {
10296     if (!AllowPartials || !Op)
10297       return SDValue();
10298     EVT OpVT = Op.getValueType();
10299     EVT OpSVT = OpVT.getScalarType();
10300     EVT SubVT = EVT::getVectorVT(*getContext(), OpSVT, NumSubElts);
10301     if (!TLI->isExtractSubvectorCheap(SubVT, OpVT, 0))
10302       return SDValue();
10303     BinOp = (ISD::NodeType)CandidateBinOp;
10304     return getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(Op), SubVT, Op,
10305                    getVectorIdxConstant(0, SDLoc(Op)));
10306   };
10307 
10308   // At each stage, we're looking for something that looks like:
10309   // %s = shufflevector <8 x i32> %op, <8 x i32> undef,
10310   //                    <8 x i32> <i32 2, i32 3, i32 undef, i32 undef,
10311   //                               i32 undef, i32 undef, i32 undef, i32 undef>
10312   // %a = binop <8 x i32> %op, %s
10313   // Where the mask changes according to the stage. E.g. for a 3-stage pyramid,
10314   // we expect something like:
10315   // <4,5,6,7,u,u,u,u>
10316   // <2,3,u,u,u,u,u,u>
10317   // <1,u,u,u,u,u,u,u>
10318   // While a partial reduction match would be:
10319   // <2,3,u,u,u,u,u,u>
10320   // <1,u,u,u,u,u,u,u>
10321   unsigned Stages = Log2_32(Op.getValueType().getVectorNumElements());
10322   SDValue PrevOp;
10323   for (unsigned i = 0; i < Stages; ++i) {
10324     unsigned MaskEnd = (1 << i);
10325 
10326     if (Op.getOpcode() != CandidateBinOp)
10327       return PartialReduction(PrevOp, MaskEnd);
10328 
10329     SDValue Op0 = Op.getOperand(0);
10330     SDValue Op1 = Op.getOperand(1);
10331 
10332     ShuffleVectorSDNode *Shuffle = dyn_cast<ShuffleVectorSDNode>(Op0);
10333     if (Shuffle) {
10334       Op = Op1;
10335     } else {
10336       Shuffle = dyn_cast<ShuffleVectorSDNode>(Op1);
10337       Op = Op0;
10338     }
10339 
10340     // The first operand of the shuffle should be the same as the other operand
10341     // of the binop.
10342     if (!Shuffle || Shuffle->getOperand(0) != Op)
10343       return PartialReduction(PrevOp, MaskEnd);
10344 
10345     // Verify the shuffle has the expected (at this stage of the pyramid) mask.
10346     for (int Index = 0; Index < (int)MaskEnd; ++Index)
10347       if (Shuffle->getMaskElt(Index) != (int)(MaskEnd + Index))
10348         return PartialReduction(PrevOp, MaskEnd);
10349 
10350     PrevOp = Op;
10351   }
10352 
10353   // Handle subvector reductions, which tend to appear after the shuffle
10354   // reduction stages.
10355   while (Op.getOpcode() == CandidateBinOp) {
10356     unsigned NumElts = Op.getValueType().getVectorNumElements();
10357     SDValue Op0 = Op.getOperand(0);
10358     SDValue Op1 = Op.getOperand(1);
10359     if (Op0.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
10360         Op1.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
10361         Op0.getOperand(0) != Op1.getOperand(0))
10362       break;
10363     SDValue Src = Op0.getOperand(0);
10364     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
10365     if (NumSrcElts != (2 * NumElts))
10366       break;
10367     if (!(Op0.getConstantOperandAPInt(1) == 0 &&
10368           Op1.getConstantOperandAPInt(1) == NumElts) &&
10369         !(Op1.getConstantOperandAPInt(1) == 0 &&
10370           Op0.getConstantOperandAPInt(1) == NumElts))
10371       break;
10372     Op = Src;
10373   }
10374 
10375   BinOp = (ISD::NodeType)CandidateBinOp;
10376   return Op;
10377 }
10378 
10379 SDValue SelectionDAG::UnrollVectorOp(SDNode *N, unsigned ResNE) {
10380   assert(N->getNumValues() == 1 &&
10381          "Can't unroll a vector with multiple results!");
10382 
10383   EVT VT = N->getValueType(0);
10384   unsigned NE = VT.getVectorNumElements();
10385   EVT EltVT = VT.getVectorElementType();
10386   SDLoc dl(N);
10387 
10388   SmallVector<SDValue, 8> Scalars;
10389   SmallVector<SDValue, 4> Operands(N->getNumOperands());
10390 
10391   // If ResNE is 0, fully unroll the vector op.
10392   if (ResNE == 0)
10393     ResNE = NE;
10394   else if (NE > ResNE)
10395     NE = ResNE;
10396 
10397   unsigned i;
10398   for (i= 0; i != NE; ++i) {
10399     for (unsigned j = 0, e = N->getNumOperands(); j != e; ++j) {
10400       SDValue Operand = N->getOperand(j);
10401       EVT OperandVT = Operand.getValueType();
10402       if (OperandVT.isVector()) {
10403         // A vector operand; extract a single element.
10404         EVT OperandEltVT = OperandVT.getVectorElementType();
10405         Operands[j] = getNode(ISD::EXTRACT_VECTOR_ELT, dl, OperandEltVT,
10406                               Operand, getVectorIdxConstant(i, dl));
10407       } else {
10408         // A scalar operand; just use it as is.
10409         Operands[j] = Operand;
10410       }
10411     }
10412 
10413     switch (N->getOpcode()) {
10414     default: {
10415       Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands,
10416                                 N->getFlags()));
10417       break;
10418     }
10419     case ISD::VSELECT:
10420       Scalars.push_back(getNode(ISD::SELECT, dl, EltVT, Operands));
10421       break;
10422     case ISD::SHL:
10423     case ISD::SRA:
10424     case ISD::SRL:
10425     case ISD::ROTL:
10426     case ISD::ROTR:
10427       Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands[0],
10428                                getShiftAmountOperand(Operands[0].getValueType(),
10429                                                      Operands[1])));
10430       break;
10431     case ISD::SIGN_EXTEND_INREG: {
10432       EVT ExtVT = cast<VTSDNode>(Operands[1])->getVT().getVectorElementType();
10433       Scalars.push_back(getNode(N->getOpcode(), dl, EltVT,
10434                                 Operands[0],
10435                                 getValueType(ExtVT)));
10436     }
10437     }
10438   }
10439 
10440   for (; i < ResNE; ++i)
10441     Scalars.push_back(getUNDEF(EltVT));
10442 
10443   EVT VecVT = EVT::getVectorVT(*getContext(), EltVT, ResNE);
10444   return getBuildVector(VecVT, dl, Scalars);
10445 }
10446 
10447 std::pair<SDValue, SDValue> SelectionDAG::UnrollVectorOverflowOp(
10448     SDNode *N, unsigned ResNE) {
10449   unsigned Opcode = N->getOpcode();
10450   assert((Opcode == ISD::UADDO || Opcode == ISD::SADDO ||
10451           Opcode == ISD::USUBO || Opcode == ISD::SSUBO ||
10452           Opcode == ISD::UMULO || Opcode == ISD::SMULO) &&
10453          "Expected an overflow opcode");
10454 
10455   EVT ResVT = N->getValueType(0);
10456   EVT OvVT = N->getValueType(1);
10457   EVT ResEltVT = ResVT.getVectorElementType();
10458   EVT OvEltVT = OvVT.getVectorElementType();
10459   SDLoc dl(N);
10460 
10461   // If ResNE is 0, fully unroll the vector op.
10462   unsigned NE = ResVT.getVectorNumElements();
10463   if (ResNE == 0)
10464     ResNE = NE;
10465   else if (NE > ResNE)
10466     NE = ResNE;
10467 
10468   SmallVector<SDValue, 8> LHSScalars;
10469   SmallVector<SDValue, 8> RHSScalars;
10470   ExtractVectorElements(N->getOperand(0), LHSScalars, 0, NE);
10471   ExtractVectorElements(N->getOperand(1), RHSScalars, 0, NE);
10472 
10473   EVT SVT = TLI->getSetCCResultType(getDataLayout(), *getContext(), ResEltVT);
10474   SDVTList VTs = getVTList(ResEltVT, SVT);
10475   SmallVector<SDValue, 8> ResScalars;
10476   SmallVector<SDValue, 8> OvScalars;
10477   for (unsigned i = 0; i < NE; ++i) {
10478     SDValue Res = getNode(Opcode, dl, VTs, LHSScalars[i], RHSScalars[i]);
10479     SDValue Ov =
10480         getSelect(dl, OvEltVT, Res.getValue(1),
10481                   getBoolConstant(true, dl, OvEltVT, ResVT),
10482                   getConstant(0, dl, OvEltVT));
10483 
10484     ResScalars.push_back(Res);
10485     OvScalars.push_back(Ov);
10486   }
10487 
10488   ResScalars.append(ResNE - NE, getUNDEF(ResEltVT));
10489   OvScalars.append(ResNE - NE, getUNDEF(OvEltVT));
10490 
10491   EVT NewResVT = EVT::getVectorVT(*getContext(), ResEltVT, ResNE);
10492   EVT NewOvVT = EVT::getVectorVT(*getContext(), OvEltVT, ResNE);
10493   return std::make_pair(getBuildVector(NewResVT, dl, ResScalars),
10494                         getBuildVector(NewOvVT, dl, OvScalars));
10495 }
10496 
10497 bool SelectionDAG::areNonVolatileConsecutiveLoads(LoadSDNode *LD,
10498                                                   LoadSDNode *Base,
10499                                                   unsigned Bytes,
10500                                                   int Dist) const {
10501   if (LD->isVolatile() || Base->isVolatile())
10502     return false;
10503   // TODO: probably too restrictive for atomics, revisit
10504   if (!LD->isSimple())
10505     return false;
10506   if (LD->isIndexed() || Base->isIndexed())
10507     return false;
10508   if (LD->getChain() != Base->getChain())
10509     return false;
10510   EVT VT = LD->getValueType(0);
10511   if (VT.getSizeInBits() / 8 != Bytes)
10512     return false;
10513 
10514   auto BaseLocDecomp = BaseIndexOffset::match(Base, *this);
10515   auto LocDecomp = BaseIndexOffset::match(LD, *this);
10516 
10517   int64_t Offset = 0;
10518   if (BaseLocDecomp.equalBaseIndex(LocDecomp, *this, Offset))
10519     return (Dist * Bytes == Offset);
10520   return false;
10521 }
10522 
10523 /// InferPtrAlignment - Infer alignment of a load / store address. Return None
10524 /// if it cannot be inferred.
10525 MaybeAlign SelectionDAG::InferPtrAlign(SDValue Ptr) const {
10526   // If this is a GlobalAddress + cst, return the alignment.
10527   const GlobalValue *GV = nullptr;
10528   int64_t GVOffset = 0;
10529   if (TLI->isGAPlusOffset(Ptr.getNode(), GV, GVOffset)) {
10530     unsigned PtrWidth = getDataLayout().getPointerTypeSizeInBits(GV->getType());
10531     KnownBits Known(PtrWidth);
10532     llvm::computeKnownBits(GV, Known, getDataLayout());
10533     unsigned AlignBits = Known.countMinTrailingZeros();
10534     if (AlignBits)
10535       return commonAlignment(Align(1ull << std::min(31U, AlignBits)), GVOffset);
10536   }
10537 
10538   // If this is a direct reference to a stack slot, use information about the
10539   // stack slot's alignment.
10540   int FrameIdx = INT_MIN;
10541   int64_t FrameOffset = 0;
10542   if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr)) {
10543     FrameIdx = FI->getIndex();
10544   } else if (isBaseWithConstantOffset(Ptr) &&
10545              isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
10546     // Handle FI+Cst
10547     FrameIdx = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
10548     FrameOffset = Ptr.getConstantOperandVal(1);
10549   }
10550 
10551   if (FrameIdx != INT_MIN) {
10552     const MachineFrameInfo &MFI = getMachineFunction().getFrameInfo();
10553     return commonAlignment(MFI.getObjectAlign(FrameIdx), FrameOffset);
10554   }
10555 
10556   return None;
10557 }
10558 
10559 /// GetSplitDestVTs - Compute the VTs needed for the low/hi parts of a type
10560 /// which is split (or expanded) into two not necessarily identical pieces.
10561 std::pair<EVT, EVT> SelectionDAG::GetSplitDestVTs(const EVT &VT) const {
10562   // Currently all types are split in half.
10563   EVT LoVT, HiVT;
10564   if (!VT.isVector())
10565     LoVT = HiVT = TLI->getTypeToTransformTo(*getContext(), VT);
10566   else
10567     LoVT = HiVT = VT.getHalfNumVectorElementsVT(*getContext());
10568 
10569   return std::make_pair(LoVT, HiVT);
10570 }
10571 
10572 /// GetDependentSplitDestVTs - Compute the VTs needed for the low/hi parts of a
10573 /// type, dependent on an enveloping VT that has been split into two identical
10574 /// pieces. Sets the HiIsEmpty flag when hi type has zero storage size.
10575 std::pair<EVT, EVT>
10576 SelectionDAG::GetDependentSplitDestVTs(const EVT &VT, const EVT &EnvVT,
10577                                        bool *HiIsEmpty) const {
10578   EVT EltTp = VT.getVectorElementType();
10579   // Examples:
10580   //   custom VL=8  with enveloping VL=8/8 yields 8/0 (hi empty)
10581   //   custom VL=9  with enveloping VL=8/8 yields 8/1
10582   //   custom VL=10 with enveloping VL=8/8 yields 8/2
10583   //   etc.
10584   ElementCount VTNumElts = VT.getVectorElementCount();
10585   ElementCount EnvNumElts = EnvVT.getVectorElementCount();
10586   assert(VTNumElts.isScalable() == EnvNumElts.isScalable() &&
10587          "Mixing fixed width and scalable vectors when enveloping a type");
10588   EVT LoVT, HiVT;
10589   if (VTNumElts.getKnownMinValue() > EnvNumElts.getKnownMinValue()) {
10590     LoVT = EVT::getVectorVT(*getContext(), EltTp, EnvNumElts);
10591     HiVT = EVT::getVectorVT(*getContext(), EltTp, VTNumElts - EnvNumElts);
10592     *HiIsEmpty = false;
10593   } else {
10594     // Flag that hi type has zero storage size, but return split envelop type
10595     // (this would be easier if vector types with zero elements were allowed).
10596     LoVT = EVT::getVectorVT(*getContext(), EltTp, VTNumElts);
10597     HiVT = EVT::getVectorVT(*getContext(), EltTp, EnvNumElts);
10598     *HiIsEmpty = true;
10599   }
10600   return std::make_pair(LoVT, HiVT);
10601 }
10602 
10603 /// SplitVector - Split the vector with EXTRACT_SUBVECTOR and return the
10604 /// low/high part.
10605 std::pair<SDValue, SDValue>
10606 SelectionDAG::SplitVector(const SDValue &N, const SDLoc &DL, const EVT &LoVT,
10607                           const EVT &HiVT) {
10608   assert(LoVT.isScalableVector() == HiVT.isScalableVector() &&
10609          LoVT.isScalableVector() == N.getValueType().isScalableVector() &&
10610          "Splitting vector with an invalid mixture of fixed and scalable "
10611          "vector types");
10612   assert(LoVT.getVectorMinNumElements() + HiVT.getVectorMinNumElements() <=
10613              N.getValueType().getVectorMinNumElements() &&
10614          "More vector elements requested than available!");
10615   SDValue Lo, Hi;
10616   Lo =
10617       getNode(ISD::EXTRACT_SUBVECTOR, DL, LoVT, N, getVectorIdxConstant(0, DL));
10618   // For scalable vectors it is safe to use LoVT.getVectorMinNumElements()
10619   // (rather than having to use ElementCount), because EXTRACT_SUBVECTOR scales
10620   // IDX with the runtime scaling factor of the result vector type. For
10621   // fixed-width result vectors, that runtime scaling factor is 1.
10622   Hi = getNode(ISD::EXTRACT_SUBVECTOR, DL, HiVT, N,
10623                getVectorIdxConstant(LoVT.getVectorMinNumElements(), DL));
10624   return std::make_pair(Lo, Hi);
10625 }
10626 
10627 std::pair<SDValue, SDValue> SelectionDAG::SplitEVL(SDValue N, EVT VecVT,
10628                                                    const SDLoc &DL) {
10629   // Split the vector length parameter.
10630   // %evl -> umin(%evl, %halfnumelts) and usubsat(%evl - %halfnumelts).
10631   EVT VT = N.getValueType();
10632   assert(VecVT.getVectorElementCount().isKnownEven() &&
10633          "Expecting the mask to be an evenly-sized vector");
10634   unsigned HalfMinNumElts = VecVT.getVectorMinNumElements() / 2;
10635   SDValue HalfNumElts =
10636       VecVT.isFixedLengthVector()
10637           ? getConstant(HalfMinNumElts, DL, VT)
10638           : getVScale(DL, VT, APInt(VT.getScalarSizeInBits(), HalfMinNumElts));
10639   SDValue Lo = getNode(ISD::UMIN, DL, VT, N, HalfNumElts);
10640   SDValue Hi = getNode(ISD::USUBSAT, DL, VT, N, HalfNumElts);
10641   return std::make_pair(Lo, Hi);
10642 }
10643 
10644 /// Widen the vector up to the next power of two using INSERT_SUBVECTOR.
10645 SDValue SelectionDAG::WidenVector(const SDValue &N, const SDLoc &DL) {
10646   EVT VT = N.getValueType();
10647   EVT WideVT = EVT::getVectorVT(*getContext(), VT.getVectorElementType(),
10648                                 NextPowerOf2(VT.getVectorNumElements()));
10649   return getNode(ISD::INSERT_SUBVECTOR, DL, WideVT, getUNDEF(WideVT), N,
10650                  getVectorIdxConstant(0, DL));
10651 }
10652 
10653 void SelectionDAG::ExtractVectorElements(SDValue Op,
10654                                          SmallVectorImpl<SDValue> &Args,
10655                                          unsigned Start, unsigned Count,
10656                                          EVT EltVT) {
10657   EVT VT = Op.getValueType();
10658   if (Count == 0)
10659     Count = VT.getVectorNumElements();
10660   if (EltVT == EVT())
10661     EltVT = VT.getVectorElementType();
10662   SDLoc SL(Op);
10663   for (unsigned i = Start, e = Start + Count; i != e; ++i) {
10664     Args.push_back(getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Op,
10665                            getVectorIdxConstant(i, SL)));
10666   }
10667 }
10668 
10669 // getAddressSpace - Return the address space this GlobalAddress belongs to.
10670 unsigned GlobalAddressSDNode::getAddressSpace() const {
10671   return getGlobal()->getType()->getAddressSpace();
10672 }
10673 
10674 Type *ConstantPoolSDNode::getType() const {
10675   if (isMachineConstantPoolEntry())
10676     return Val.MachineCPVal->getType();
10677   return Val.ConstVal->getType();
10678 }
10679 
10680 bool BuildVectorSDNode::isConstantSplat(APInt &SplatValue, APInt &SplatUndef,
10681                                         unsigned &SplatBitSize,
10682                                         bool &HasAnyUndefs,
10683                                         unsigned MinSplatBits,
10684                                         bool IsBigEndian) const {
10685   EVT VT = getValueType(0);
10686   assert(VT.isVector() && "Expected a vector type");
10687   unsigned VecWidth = VT.getSizeInBits();
10688   if (MinSplatBits > VecWidth)
10689     return false;
10690 
10691   // FIXME: The widths are based on this node's type, but build vectors can
10692   // truncate their operands.
10693   SplatValue = APInt(VecWidth, 0);
10694   SplatUndef = APInt(VecWidth, 0);
10695 
10696   // Get the bits. Bits with undefined values (when the corresponding element
10697   // of the vector is an ISD::UNDEF value) are set in SplatUndef and cleared
10698   // in SplatValue. If any of the values are not constant, give up and return
10699   // false.
10700   unsigned int NumOps = getNumOperands();
10701   assert(NumOps > 0 && "isConstantSplat has 0-size build vector");
10702   unsigned EltWidth = VT.getScalarSizeInBits();
10703 
10704   for (unsigned j = 0; j < NumOps; ++j) {
10705     unsigned i = IsBigEndian ? NumOps - 1 - j : j;
10706     SDValue OpVal = getOperand(i);
10707     unsigned BitPos = j * EltWidth;
10708 
10709     if (OpVal.isUndef())
10710       SplatUndef.setBits(BitPos, BitPos + EltWidth);
10711     else if (auto *CN = dyn_cast<ConstantSDNode>(OpVal))
10712       SplatValue.insertBits(CN->getAPIntValue().zextOrTrunc(EltWidth), BitPos);
10713     else if (auto *CN = dyn_cast<ConstantFPSDNode>(OpVal))
10714       SplatValue.insertBits(CN->getValueAPF().bitcastToAPInt(), BitPos);
10715     else
10716       return false;
10717   }
10718 
10719   // The build_vector is all constants or undefs. Find the smallest element
10720   // size that splats the vector.
10721   HasAnyUndefs = (SplatUndef != 0);
10722 
10723   // FIXME: This does not work for vectors with elements less than 8 bits.
10724   while (VecWidth > 8) {
10725     unsigned HalfSize = VecWidth / 2;
10726     APInt HighValue = SplatValue.extractBits(HalfSize, HalfSize);
10727     APInt LowValue = SplatValue.extractBits(HalfSize, 0);
10728     APInt HighUndef = SplatUndef.extractBits(HalfSize, HalfSize);
10729     APInt LowUndef = SplatUndef.extractBits(HalfSize, 0);
10730 
10731     // If the two halves do not match (ignoring undef bits), stop here.
10732     if ((HighValue & ~LowUndef) != (LowValue & ~HighUndef) ||
10733         MinSplatBits > HalfSize)
10734       break;
10735 
10736     SplatValue = HighValue | LowValue;
10737     SplatUndef = HighUndef & LowUndef;
10738 
10739     VecWidth = HalfSize;
10740   }
10741 
10742   SplatBitSize = VecWidth;
10743   return true;
10744 }
10745 
10746 SDValue BuildVectorSDNode::getSplatValue(const APInt &DemandedElts,
10747                                          BitVector *UndefElements) const {
10748   unsigned NumOps = getNumOperands();
10749   if (UndefElements) {
10750     UndefElements->clear();
10751     UndefElements->resize(NumOps);
10752   }
10753   assert(NumOps == DemandedElts.getBitWidth() && "Unexpected vector size");
10754   if (!DemandedElts)
10755     return SDValue();
10756   SDValue Splatted;
10757   for (unsigned i = 0; i != NumOps; ++i) {
10758     if (!DemandedElts[i])
10759       continue;
10760     SDValue Op = getOperand(i);
10761     if (Op.isUndef()) {
10762       if (UndefElements)
10763         (*UndefElements)[i] = true;
10764     } else if (!Splatted) {
10765       Splatted = Op;
10766     } else if (Splatted != Op) {
10767       return SDValue();
10768     }
10769   }
10770 
10771   if (!Splatted) {
10772     unsigned FirstDemandedIdx = DemandedElts.countTrailingZeros();
10773     assert(getOperand(FirstDemandedIdx).isUndef() &&
10774            "Can only have a splat without a constant for all undefs.");
10775     return getOperand(FirstDemandedIdx);
10776   }
10777 
10778   return Splatted;
10779 }
10780 
10781 SDValue BuildVectorSDNode::getSplatValue(BitVector *UndefElements) const {
10782   APInt DemandedElts = APInt::getAllOnes(getNumOperands());
10783   return getSplatValue(DemandedElts, UndefElements);
10784 }
10785 
10786 bool BuildVectorSDNode::getRepeatedSequence(const APInt &DemandedElts,
10787                                             SmallVectorImpl<SDValue> &Sequence,
10788                                             BitVector *UndefElements) const {
10789   unsigned NumOps = getNumOperands();
10790   Sequence.clear();
10791   if (UndefElements) {
10792     UndefElements->clear();
10793     UndefElements->resize(NumOps);
10794   }
10795   assert(NumOps == DemandedElts.getBitWidth() && "Unexpected vector size");
10796   if (!DemandedElts || NumOps < 2 || !isPowerOf2_32(NumOps))
10797     return false;
10798 
10799   // Set the undefs even if we don't find a sequence (like getSplatValue).
10800   if (UndefElements)
10801     for (unsigned I = 0; I != NumOps; ++I)
10802       if (DemandedElts[I] && getOperand(I).isUndef())
10803         (*UndefElements)[I] = true;
10804 
10805   // Iteratively widen the sequence length looking for repetitions.
10806   for (unsigned SeqLen = 1; SeqLen < NumOps; SeqLen *= 2) {
10807     Sequence.append(SeqLen, SDValue());
10808     for (unsigned I = 0; I != NumOps; ++I) {
10809       if (!DemandedElts[I])
10810         continue;
10811       SDValue &SeqOp = Sequence[I % SeqLen];
10812       SDValue Op = getOperand(I);
10813       if (Op.isUndef()) {
10814         if (!SeqOp)
10815           SeqOp = Op;
10816         continue;
10817       }
10818       if (SeqOp && !SeqOp.isUndef() && SeqOp != Op) {
10819         Sequence.clear();
10820         break;
10821       }
10822       SeqOp = Op;
10823     }
10824     if (!Sequence.empty())
10825       return true;
10826   }
10827 
10828   assert(Sequence.empty() && "Failed to empty non-repeating sequence pattern");
10829   return false;
10830 }
10831 
10832 bool BuildVectorSDNode::getRepeatedSequence(SmallVectorImpl<SDValue> &Sequence,
10833                                             BitVector *UndefElements) const {
10834   APInt DemandedElts = APInt::getAllOnes(getNumOperands());
10835   return getRepeatedSequence(DemandedElts, Sequence, UndefElements);
10836 }
10837 
10838 ConstantSDNode *
10839 BuildVectorSDNode::getConstantSplatNode(const APInt &DemandedElts,
10840                                         BitVector *UndefElements) const {
10841   return dyn_cast_or_null<ConstantSDNode>(
10842       getSplatValue(DemandedElts, UndefElements));
10843 }
10844 
10845 ConstantSDNode *
10846 BuildVectorSDNode::getConstantSplatNode(BitVector *UndefElements) const {
10847   return dyn_cast_or_null<ConstantSDNode>(getSplatValue(UndefElements));
10848 }
10849 
10850 ConstantFPSDNode *
10851 BuildVectorSDNode::getConstantFPSplatNode(const APInt &DemandedElts,
10852                                           BitVector *UndefElements) const {
10853   return dyn_cast_or_null<ConstantFPSDNode>(
10854       getSplatValue(DemandedElts, UndefElements));
10855 }
10856 
10857 ConstantFPSDNode *
10858 BuildVectorSDNode::getConstantFPSplatNode(BitVector *UndefElements) const {
10859   return dyn_cast_or_null<ConstantFPSDNode>(getSplatValue(UndefElements));
10860 }
10861 
10862 int32_t
10863 BuildVectorSDNode::getConstantFPSplatPow2ToLog2Int(BitVector *UndefElements,
10864                                                    uint32_t BitWidth) const {
10865   if (ConstantFPSDNode *CN =
10866           dyn_cast_or_null<ConstantFPSDNode>(getSplatValue(UndefElements))) {
10867     bool IsExact;
10868     APSInt IntVal(BitWidth);
10869     const APFloat &APF = CN->getValueAPF();
10870     if (APF.convertToInteger(IntVal, APFloat::rmTowardZero, &IsExact) !=
10871             APFloat::opOK ||
10872         !IsExact)
10873       return -1;
10874 
10875     return IntVal.exactLogBase2();
10876   }
10877   return -1;
10878 }
10879 
10880 bool BuildVectorSDNode::getConstantRawBits(
10881     bool IsLittleEndian, unsigned DstEltSizeInBits,
10882     SmallVectorImpl<APInt> &RawBitElements, BitVector &UndefElements) const {
10883   // Early-out if this contains anything but Undef/Constant/ConstantFP.
10884   if (!isConstant())
10885     return false;
10886 
10887   unsigned NumSrcOps = getNumOperands();
10888   unsigned SrcEltSizeInBits = getValueType(0).getScalarSizeInBits();
10889   assert(((NumSrcOps * SrcEltSizeInBits) % DstEltSizeInBits) == 0 &&
10890          "Invalid bitcast scale");
10891 
10892   // Extract raw src bits.
10893   SmallVector<APInt> SrcBitElements(NumSrcOps,
10894                                     APInt::getNullValue(SrcEltSizeInBits));
10895   BitVector SrcUndeElements(NumSrcOps, false);
10896 
10897   for (unsigned I = 0; I != NumSrcOps; ++I) {
10898     SDValue Op = getOperand(I);
10899     if (Op.isUndef()) {
10900       SrcUndeElements.set(I);
10901       continue;
10902     }
10903     auto *CInt = dyn_cast<ConstantSDNode>(Op);
10904     auto *CFP = dyn_cast<ConstantFPSDNode>(Op);
10905     assert((CInt || CFP) && "Unknown constant");
10906     SrcBitElements[I] =
10907         CInt ? CInt->getAPIntValue().truncOrSelf(SrcEltSizeInBits)
10908              : CFP->getValueAPF().bitcastToAPInt();
10909   }
10910 
10911   // Recast to dst width.
10912   recastRawBits(IsLittleEndian, DstEltSizeInBits, RawBitElements,
10913                 SrcBitElements, UndefElements, SrcUndeElements);
10914   return true;
10915 }
10916 
10917 void BuildVectorSDNode::recastRawBits(bool IsLittleEndian,
10918                                       unsigned DstEltSizeInBits,
10919                                       SmallVectorImpl<APInt> &DstBitElements,
10920                                       ArrayRef<APInt> SrcBitElements,
10921                                       BitVector &DstUndefElements,
10922                                       const BitVector &SrcUndefElements) {
10923   unsigned NumSrcOps = SrcBitElements.size();
10924   unsigned SrcEltSizeInBits = SrcBitElements[0].getBitWidth();
10925   assert(((NumSrcOps * SrcEltSizeInBits) % DstEltSizeInBits) == 0 &&
10926          "Invalid bitcast scale");
10927   assert(NumSrcOps == SrcUndefElements.size() &&
10928          "Vector size mismatch");
10929 
10930   unsigned NumDstOps = (NumSrcOps * SrcEltSizeInBits) / DstEltSizeInBits;
10931   DstUndefElements.clear();
10932   DstUndefElements.resize(NumDstOps, false);
10933   DstBitElements.assign(NumDstOps, APInt::getNullValue(DstEltSizeInBits));
10934 
10935   // Concatenate src elements constant bits together into dst element.
10936   if (SrcEltSizeInBits <= DstEltSizeInBits) {
10937     unsigned Scale = DstEltSizeInBits / SrcEltSizeInBits;
10938     for (unsigned I = 0; I != NumDstOps; ++I) {
10939       DstUndefElements.set(I);
10940       APInt &DstBits = DstBitElements[I];
10941       for (unsigned J = 0; J != Scale; ++J) {
10942         unsigned Idx = (I * Scale) + (IsLittleEndian ? J : (Scale - J - 1));
10943         if (SrcUndefElements[Idx])
10944           continue;
10945         DstUndefElements.reset(I);
10946         const APInt &SrcBits = SrcBitElements[Idx];
10947         assert(SrcBits.getBitWidth() == SrcEltSizeInBits &&
10948                "Illegal constant bitwidths");
10949         DstBits.insertBits(SrcBits, J * SrcEltSizeInBits);
10950       }
10951     }
10952     return;
10953   }
10954 
10955   // Split src element constant bits into dst elements.
10956   unsigned Scale = SrcEltSizeInBits / DstEltSizeInBits;
10957   for (unsigned I = 0; I != NumSrcOps; ++I) {
10958     if (SrcUndefElements[I]) {
10959       DstUndefElements.set(I * Scale, (I + 1) * Scale);
10960       continue;
10961     }
10962     const APInt &SrcBits = SrcBitElements[I];
10963     for (unsigned J = 0; J != Scale; ++J) {
10964       unsigned Idx = (I * Scale) + (IsLittleEndian ? J : (Scale - J - 1));
10965       APInt &DstBits = DstBitElements[Idx];
10966       DstBits = SrcBits.extractBits(DstEltSizeInBits, J * DstEltSizeInBits);
10967     }
10968   }
10969 }
10970 
10971 bool BuildVectorSDNode::isConstant() const {
10972   for (const SDValue &Op : op_values()) {
10973     unsigned Opc = Op.getOpcode();
10974     if (Opc != ISD::UNDEF && Opc != ISD::Constant && Opc != ISD::ConstantFP)
10975       return false;
10976   }
10977   return true;
10978 }
10979 
10980 bool ShuffleVectorSDNode::isSplatMask(const int *Mask, EVT VT) {
10981   // Find the first non-undef value in the shuffle mask.
10982   unsigned i, e;
10983   for (i = 0, e = VT.getVectorNumElements(); i != e && Mask[i] < 0; ++i)
10984     /* search */;
10985 
10986   // If all elements are undefined, this shuffle can be considered a splat
10987   // (although it should eventually get simplified away completely).
10988   if (i == e)
10989     return true;
10990 
10991   // Make sure all remaining elements are either undef or the same as the first
10992   // non-undef value.
10993   for (int Idx = Mask[i]; i != e; ++i)
10994     if (Mask[i] >= 0 && Mask[i] != Idx)
10995       return false;
10996   return true;
10997 }
10998 
10999 // Returns the SDNode if it is a constant integer BuildVector
11000 // or constant integer.
11001 SDNode *SelectionDAG::isConstantIntBuildVectorOrConstantInt(SDValue N) const {
11002   if (isa<ConstantSDNode>(N))
11003     return N.getNode();
11004   if (ISD::isBuildVectorOfConstantSDNodes(N.getNode()))
11005     return N.getNode();
11006   // Treat a GlobalAddress supporting constant offset folding as a
11007   // constant integer.
11008   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N))
11009     if (GA->getOpcode() == ISD::GlobalAddress &&
11010         TLI->isOffsetFoldingLegal(GA))
11011       return GA;
11012   if ((N.getOpcode() == ISD::SPLAT_VECTOR) &&
11013       isa<ConstantSDNode>(N.getOperand(0)))
11014     return N.getNode();
11015   return nullptr;
11016 }
11017 
11018 // Returns the SDNode if it is a constant float BuildVector
11019 // or constant float.
11020 SDNode *SelectionDAG::isConstantFPBuildVectorOrConstantFP(SDValue N) const {
11021   if (isa<ConstantFPSDNode>(N))
11022     return N.getNode();
11023 
11024   if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode()))
11025     return N.getNode();
11026 
11027   return nullptr;
11028 }
11029 
11030 void SelectionDAG::createOperands(SDNode *Node, ArrayRef<SDValue> Vals) {
11031   assert(!Node->OperandList && "Node already has operands");
11032   assert(SDNode::getMaxNumOperands() >= Vals.size() &&
11033          "too many operands to fit into SDNode");
11034   SDUse *Ops = OperandRecycler.allocate(
11035       ArrayRecycler<SDUse>::Capacity::get(Vals.size()), OperandAllocator);
11036 
11037   bool IsDivergent = false;
11038   for (unsigned I = 0; I != Vals.size(); ++I) {
11039     Ops[I].setUser(Node);
11040     Ops[I].setInitial(Vals[I]);
11041     if (Ops[I].Val.getValueType() != MVT::Other) // Skip Chain. It does not carry divergence.
11042       IsDivergent |= Ops[I].getNode()->isDivergent();
11043   }
11044   Node->NumOperands = Vals.size();
11045   Node->OperandList = Ops;
11046   if (!TLI->isSDNodeAlwaysUniform(Node)) {
11047     IsDivergent |= TLI->isSDNodeSourceOfDivergence(Node, FLI, DA);
11048     Node->SDNodeBits.IsDivergent = IsDivergent;
11049   }
11050   checkForCycles(Node);
11051 }
11052 
11053 SDValue SelectionDAG::getTokenFactor(const SDLoc &DL,
11054                                      SmallVectorImpl<SDValue> &Vals) {
11055   size_t Limit = SDNode::getMaxNumOperands();
11056   while (Vals.size() > Limit) {
11057     unsigned SliceIdx = Vals.size() - Limit;
11058     auto ExtractedTFs = ArrayRef<SDValue>(Vals).slice(SliceIdx, Limit);
11059     SDValue NewTF = getNode(ISD::TokenFactor, DL, MVT::Other, ExtractedTFs);
11060     Vals.erase(Vals.begin() + SliceIdx, Vals.end());
11061     Vals.emplace_back(NewTF);
11062   }
11063   return getNode(ISD::TokenFactor, DL, MVT::Other, Vals);
11064 }
11065 
11066 SDValue SelectionDAG::getNeutralElement(unsigned Opcode, const SDLoc &DL,
11067                                         EVT VT, SDNodeFlags Flags) {
11068   switch (Opcode) {
11069   default:
11070     return SDValue();
11071   case ISD::ADD:
11072   case ISD::OR:
11073   case ISD::XOR:
11074   case ISD::UMAX:
11075     return getConstant(0, DL, VT);
11076   case ISD::MUL:
11077     return getConstant(1, DL, VT);
11078   case ISD::AND:
11079   case ISD::UMIN:
11080     return getAllOnesConstant(DL, VT);
11081   case ISD::SMAX:
11082     return getConstant(APInt::getSignedMinValue(VT.getSizeInBits()), DL, VT);
11083   case ISD::SMIN:
11084     return getConstant(APInt::getSignedMaxValue(VT.getSizeInBits()), DL, VT);
11085   case ISD::FADD:
11086     return getConstantFP(-0.0, DL, VT);
11087   case ISD::FMUL:
11088     return getConstantFP(1.0, DL, VT);
11089   case ISD::FMINNUM:
11090   case ISD::FMAXNUM: {
11091     // Neutral element for fminnum is NaN, Inf or FLT_MAX, depending on FMF.
11092     const fltSemantics &Semantics = EVTToAPFloatSemantics(VT);
11093     APFloat NeutralAF = !Flags.hasNoNaNs() ? APFloat::getQNaN(Semantics) :
11094                         !Flags.hasNoInfs() ? APFloat::getInf(Semantics) :
11095                         APFloat::getLargest(Semantics);
11096     if (Opcode == ISD::FMAXNUM)
11097       NeutralAF.changeSign();
11098 
11099     return getConstantFP(NeutralAF, DL, VT);
11100   }
11101   }
11102 }
11103 
11104 #ifndef NDEBUG
11105 static void checkForCyclesHelper(const SDNode *N,
11106                                  SmallPtrSetImpl<const SDNode*> &Visited,
11107                                  SmallPtrSetImpl<const SDNode*> &Checked,
11108                                  const llvm::SelectionDAG *DAG) {
11109   // If this node has already been checked, don't check it again.
11110   if (Checked.count(N))
11111     return;
11112 
11113   // If a node has already been visited on this depth-first walk, reject it as
11114   // a cycle.
11115   if (!Visited.insert(N).second) {
11116     errs() << "Detected cycle in SelectionDAG\n";
11117     dbgs() << "Offending node:\n";
11118     N->dumprFull(DAG); dbgs() << "\n";
11119     abort();
11120   }
11121 
11122   for (const SDValue &Op : N->op_values())
11123     checkForCyclesHelper(Op.getNode(), Visited, Checked, DAG);
11124 
11125   Checked.insert(N);
11126   Visited.erase(N);
11127 }
11128 #endif
11129 
11130 void llvm::checkForCycles(const llvm::SDNode *N,
11131                           const llvm::SelectionDAG *DAG,
11132                           bool force) {
11133 #ifndef NDEBUG
11134   bool check = force;
11135 #ifdef EXPENSIVE_CHECKS
11136   check = true;
11137 #endif  // EXPENSIVE_CHECKS
11138   if (check) {
11139     assert(N && "Checking nonexistent SDNode");
11140     SmallPtrSet<const SDNode*, 32> visited;
11141     SmallPtrSet<const SDNode*, 32> checked;
11142     checkForCyclesHelper(N, visited, checked, DAG);
11143   }
11144 #endif  // !NDEBUG
11145 }
11146 
11147 void llvm::checkForCycles(const llvm::SelectionDAG *DAG, bool force) {
11148   checkForCycles(DAG->getRoot().getNode(), DAG, force);
11149 }
11150