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