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(SDOPC, ...)                                   \
410   case ISD::SDOPC:                                                             \
411     return true;
412 #include "llvm/IR/VPIntrinsics.def"
413   }
414 }
415 
416 bool ISD::isVPBinaryOp(unsigned Opcode) {
417   switch (Opcode) {
418   default:
419     return false;
420 #define PROPERTY_VP_BINARYOP_SDNODE(SDOPC)                                     \
421   case ISD::SDOPC:                                                             \
422     return true;
423 #include "llvm/IR/VPIntrinsics.def"
424   }
425 }
426 
427 bool ISD::isVPReduction(unsigned Opcode) {
428   switch (Opcode) {
429   default:
430     return false;
431 #define PROPERTY_VP_REDUCTION_SDNODE(SDOPC)                                    \
432   case ISD::SDOPC:                                                             \
433     return true;
434 #include "llvm/IR/VPIntrinsics.def"
435   }
436 }
437 
438 /// The operand position of the vector mask.
439 Optional<unsigned> ISD::getVPMaskIdx(unsigned Opcode) {
440   switch (Opcode) {
441   default:
442     return None;
443 #define BEGIN_REGISTER_VP_SDNODE(SDOPC, LEGALPOS, TDNAME, MASKPOS, ...)        \
444   case ISD::SDOPC:                                                             \
445     return MASKPOS;
446 #include "llvm/IR/VPIntrinsics.def"
447   }
448 }
449 
450 /// The operand position of the explicit vector length parameter.
451 Optional<unsigned> ISD::getVPExplicitVectorLengthIdx(unsigned Opcode) {
452   switch (Opcode) {
453   default:
454     return None;
455 #define BEGIN_REGISTER_VP_SDNODE(SDOPC, LEGALPOS, TDNAME, MASKPOS, EVLPOS)     \
456   case ISD::SDOPC:                                                             \
457     return EVLPOS;
458 #include "llvm/IR/VPIntrinsics.def"
459   }
460 }
461 
462 ISD::NodeType ISD::getExtForLoadExtType(bool IsFP, ISD::LoadExtType ExtType) {
463   switch (ExtType) {
464   case ISD::EXTLOAD:
465     return IsFP ? ISD::FP_EXTEND : ISD::ANY_EXTEND;
466   case ISD::SEXTLOAD:
467     return ISD::SIGN_EXTEND;
468   case ISD::ZEXTLOAD:
469     return ISD::ZERO_EXTEND;
470   default:
471     break;
472   }
473 
474   llvm_unreachable("Invalid LoadExtType");
475 }
476 
477 ISD::CondCode ISD::getSetCCSwappedOperands(ISD::CondCode Operation) {
478   // To perform this operation, we just need to swap the L and G bits of the
479   // operation.
480   unsigned OldL = (Operation >> 2) & 1;
481   unsigned OldG = (Operation >> 1) & 1;
482   return ISD::CondCode((Operation & ~6) |  // Keep the N, U, E bits
483                        (OldL << 1) |       // New G bit
484                        (OldG << 2));       // New L bit.
485 }
486 
487 static ISD::CondCode getSetCCInverseImpl(ISD::CondCode Op, bool isIntegerLike) {
488   unsigned Operation = Op;
489   if (isIntegerLike)
490     Operation ^= 7;   // Flip L, G, E bits, but not U.
491   else
492     Operation ^= 15;  // Flip all of the condition bits.
493 
494   if (Operation > ISD::SETTRUE2)
495     Operation &= ~8;  // Don't let N and U bits get set.
496 
497   return ISD::CondCode(Operation);
498 }
499 
500 ISD::CondCode ISD::getSetCCInverse(ISD::CondCode Op, EVT Type) {
501   return getSetCCInverseImpl(Op, Type.isInteger());
502 }
503 
504 ISD::CondCode ISD::GlobalISel::getSetCCInverse(ISD::CondCode Op,
505                                                bool isIntegerLike) {
506   return getSetCCInverseImpl(Op, isIntegerLike);
507 }
508 
509 /// For an integer comparison, return 1 if the comparison is a signed operation
510 /// and 2 if the result is an unsigned comparison. Return zero if the operation
511 /// does not depend on the sign of the input (setne and seteq).
512 static int isSignedOp(ISD::CondCode Opcode) {
513   switch (Opcode) {
514   default: llvm_unreachable("Illegal integer setcc operation!");
515   case ISD::SETEQ:
516   case ISD::SETNE: return 0;
517   case ISD::SETLT:
518   case ISD::SETLE:
519   case ISD::SETGT:
520   case ISD::SETGE: return 1;
521   case ISD::SETULT:
522   case ISD::SETULE:
523   case ISD::SETUGT:
524   case ISD::SETUGE: return 2;
525   }
526 }
527 
528 ISD::CondCode ISD::getSetCCOrOperation(ISD::CondCode Op1, ISD::CondCode Op2,
529                                        EVT Type) {
530   bool IsInteger = Type.isInteger();
531   if (IsInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
532     // Cannot fold a signed integer setcc with an unsigned integer setcc.
533     return ISD::SETCC_INVALID;
534 
535   unsigned Op = Op1 | Op2;  // Combine all of the condition bits.
536 
537   // If the N and U bits get set, then the resultant comparison DOES suddenly
538   // care about orderedness, and it is true when ordered.
539   if (Op > ISD::SETTRUE2)
540     Op &= ~16;     // Clear the U bit if the N bit is set.
541 
542   // Canonicalize illegal integer setcc's.
543   if (IsInteger && Op == ISD::SETUNE)  // e.g. SETUGT | SETULT
544     Op = ISD::SETNE;
545 
546   return ISD::CondCode(Op);
547 }
548 
549 ISD::CondCode ISD::getSetCCAndOperation(ISD::CondCode Op1, ISD::CondCode Op2,
550                                         EVT Type) {
551   bool IsInteger = Type.isInteger();
552   if (IsInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
553     // Cannot fold a signed setcc with an unsigned setcc.
554     return ISD::SETCC_INVALID;
555 
556   // Combine all of the condition bits.
557   ISD::CondCode Result = ISD::CondCode(Op1 & Op2);
558 
559   // Canonicalize illegal integer setcc's.
560   if (IsInteger) {
561     switch (Result) {
562     default: break;
563     case ISD::SETUO : Result = ISD::SETFALSE; break;  // SETUGT & SETULT
564     case ISD::SETOEQ:                                 // SETEQ  & SETU[LG]E
565     case ISD::SETUEQ: Result = ISD::SETEQ   ; break;  // SETUGE & SETULE
566     case ISD::SETOLT: Result = ISD::SETULT  ; break;  // SETULT & SETNE
567     case ISD::SETOGT: Result = ISD::SETUGT  ; break;  // SETUGT & SETNE
568     }
569   }
570 
571   return Result;
572 }
573 
574 //===----------------------------------------------------------------------===//
575 //                           SDNode Profile Support
576 //===----------------------------------------------------------------------===//
577 
578 /// AddNodeIDOpcode - Add the node opcode to the NodeID data.
579 static void AddNodeIDOpcode(FoldingSetNodeID &ID, unsigned OpC)  {
580   ID.AddInteger(OpC);
581 }
582 
583 /// AddNodeIDValueTypes - Value type lists are intern'd so we can represent them
584 /// solely with their pointer.
585 static void AddNodeIDValueTypes(FoldingSetNodeID &ID, SDVTList VTList) {
586   ID.AddPointer(VTList.VTs);
587 }
588 
589 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data.
590 static void AddNodeIDOperands(FoldingSetNodeID &ID,
591                               ArrayRef<SDValue> Ops) {
592   for (auto& Op : Ops) {
593     ID.AddPointer(Op.getNode());
594     ID.AddInteger(Op.getResNo());
595   }
596 }
597 
598 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data.
599 static void AddNodeIDOperands(FoldingSetNodeID &ID,
600                               ArrayRef<SDUse> Ops) {
601   for (auto& Op : Ops) {
602     ID.AddPointer(Op.getNode());
603     ID.AddInteger(Op.getResNo());
604   }
605 }
606 
607 static void AddNodeIDNode(FoldingSetNodeID &ID, unsigned short OpC,
608                           SDVTList VTList, ArrayRef<SDValue> OpList) {
609   AddNodeIDOpcode(ID, OpC);
610   AddNodeIDValueTypes(ID, VTList);
611   AddNodeIDOperands(ID, OpList);
612 }
613 
614 /// If this is an SDNode with special info, add this info to the NodeID data.
615 static void AddNodeIDCustom(FoldingSetNodeID &ID, const SDNode *N) {
616   switch (N->getOpcode()) {
617   case ISD::TargetExternalSymbol:
618   case ISD::ExternalSymbol:
619   case ISD::MCSymbol:
620     llvm_unreachable("Should only be used on nodes with operands");
621   default: break;  // Normal nodes don't need extra info.
622   case ISD::TargetConstant:
623   case ISD::Constant: {
624     const ConstantSDNode *C = cast<ConstantSDNode>(N);
625     ID.AddPointer(C->getConstantIntValue());
626     ID.AddBoolean(C->isOpaque());
627     break;
628   }
629   case ISD::TargetConstantFP:
630   case ISD::ConstantFP:
631     ID.AddPointer(cast<ConstantFPSDNode>(N)->getConstantFPValue());
632     break;
633   case ISD::TargetGlobalAddress:
634   case ISD::GlobalAddress:
635   case ISD::TargetGlobalTLSAddress:
636   case ISD::GlobalTLSAddress: {
637     const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(N);
638     ID.AddPointer(GA->getGlobal());
639     ID.AddInteger(GA->getOffset());
640     ID.AddInteger(GA->getTargetFlags());
641     break;
642   }
643   case ISD::BasicBlock:
644     ID.AddPointer(cast<BasicBlockSDNode>(N)->getBasicBlock());
645     break;
646   case ISD::Register:
647     ID.AddInteger(cast<RegisterSDNode>(N)->getReg());
648     break;
649   case ISD::RegisterMask:
650     ID.AddPointer(cast<RegisterMaskSDNode>(N)->getRegMask());
651     break;
652   case ISD::SRCVALUE:
653     ID.AddPointer(cast<SrcValueSDNode>(N)->getValue());
654     break;
655   case ISD::FrameIndex:
656   case ISD::TargetFrameIndex:
657     ID.AddInteger(cast<FrameIndexSDNode>(N)->getIndex());
658     break;
659   case ISD::LIFETIME_START:
660   case ISD::LIFETIME_END:
661     if (cast<LifetimeSDNode>(N)->hasOffset()) {
662       ID.AddInteger(cast<LifetimeSDNode>(N)->getSize());
663       ID.AddInteger(cast<LifetimeSDNode>(N)->getOffset());
664     }
665     break;
666   case ISD::PSEUDO_PROBE:
667     ID.AddInteger(cast<PseudoProbeSDNode>(N)->getGuid());
668     ID.AddInteger(cast<PseudoProbeSDNode>(N)->getIndex());
669     ID.AddInteger(cast<PseudoProbeSDNode>(N)->getAttributes());
670     break;
671   case ISD::JumpTable:
672   case ISD::TargetJumpTable:
673     ID.AddInteger(cast<JumpTableSDNode>(N)->getIndex());
674     ID.AddInteger(cast<JumpTableSDNode>(N)->getTargetFlags());
675     break;
676   case ISD::ConstantPool:
677   case ISD::TargetConstantPool: {
678     const ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(N);
679     ID.AddInteger(CP->getAlign().value());
680     ID.AddInteger(CP->getOffset());
681     if (CP->isMachineConstantPoolEntry())
682       CP->getMachineCPVal()->addSelectionDAGCSEId(ID);
683     else
684       ID.AddPointer(CP->getConstVal());
685     ID.AddInteger(CP->getTargetFlags());
686     break;
687   }
688   case ISD::TargetIndex: {
689     const TargetIndexSDNode *TI = cast<TargetIndexSDNode>(N);
690     ID.AddInteger(TI->getIndex());
691     ID.AddInteger(TI->getOffset());
692     ID.AddInteger(TI->getTargetFlags());
693     break;
694   }
695   case ISD::LOAD: {
696     const LoadSDNode *LD = cast<LoadSDNode>(N);
697     ID.AddInteger(LD->getMemoryVT().getRawBits());
698     ID.AddInteger(LD->getRawSubclassData());
699     ID.AddInteger(LD->getPointerInfo().getAddrSpace());
700     break;
701   }
702   case ISD::STORE: {
703     const StoreSDNode *ST = cast<StoreSDNode>(N);
704     ID.AddInteger(ST->getMemoryVT().getRawBits());
705     ID.AddInteger(ST->getRawSubclassData());
706     ID.AddInteger(ST->getPointerInfo().getAddrSpace());
707     break;
708   }
709   case ISD::VP_LOAD: {
710     const VPLoadSDNode *ELD = cast<VPLoadSDNode>(N);
711     ID.AddInteger(ELD->getMemoryVT().getRawBits());
712     ID.AddInteger(ELD->getRawSubclassData());
713     ID.AddInteger(ELD->getPointerInfo().getAddrSpace());
714     break;
715   }
716   case ISD::VP_STORE: {
717     const VPStoreSDNode *EST = cast<VPStoreSDNode>(N);
718     ID.AddInteger(EST->getMemoryVT().getRawBits());
719     ID.AddInteger(EST->getRawSubclassData());
720     ID.AddInteger(EST->getPointerInfo().getAddrSpace());
721     break;
722   }
723   case ISD::VP_GATHER: {
724     const VPGatherSDNode *EG = cast<VPGatherSDNode>(N);
725     ID.AddInteger(EG->getMemoryVT().getRawBits());
726     ID.AddInteger(EG->getRawSubclassData());
727     ID.AddInteger(EG->getPointerInfo().getAddrSpace());
728     break;
729   }
730   case ISD::VP_SCATTER: {
731     const VPScatterSDNode *ES = cast<VPScatterSDNode>(N);
732     ID.AddInteger(ES->getMemoryVT().getRawBits());
733     ID.AddInteger(ES->getRawSubclassData());
734     ID.AddInteger(ES->getPointerInfo().getAddrSpace());
735     break;
736   }
737   case ISD::MLOAD: {
738     const MaskedLoadSDNode *MLD = cast<MaskedLoadSDNode>(N);
739     ID.AddInteger(MLD->getMemoryVT().getRawBits());
740     ID.AddInteger(MLD->getRawSubclassData());
741     ID.AddInteger(MLD->getPointerInfo().getAddrSpace());
742     break;
743   }
744   case ISD::MSTORE: {
745     const MaskedStoreSDNode *MST = cast<MaskedStoreSDNode>(N);
746     ID.AddInteger(MST->getMemoryVT().getRawBits());
747     ID.AddInteger(MST->getRawSubclassData());
748     ID.AddInteger(MST->getPointerInfo().getAddrSpace());
749     break;
750   }
751   case ISD::MGATHER: {
752     const MaskedGatherSDNode *MG = cast<MaskedGatherSDNode>(N);
753     ID.AddInteger(MG->getMemoryVT().getRawBits());
754     ID.AddInteger(MG->getRawSubclassData());
755     ID.AddInteger(MG->getPointerInfo().getAddrSpace());
756     break;
757   }
758   case ISD::MSCATTER: {
759     const MaskedScatterSDNode *MS = cast<MaskedScatterSDNode>(N);
760     ID.AddInteger(MS->getMemoryVT().getRawBits());
761     ID.AddInteger(MS->getRawSubclassData());
762     ID.AddInteger(MS->getPointerInfo().getAddrSpace());
763     break;
764   }
765   case ISD::ATOMIC_CMP_SWAP:
766   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
767   case ISD::ATOMIC_SWAP:
768   case ISD::ATOMIC_LOAD_ADD:
769   case ISD::ATOMIC_LOAD_SUB:
770   case ISD::ATOMIC_LOAD_AND:
771   case ISD::ATOMIC_LOAD_CLR:
772   case ISD::ATOMIC_LOAD_OR:
773   case ISD::ATOMIC_LOAD_XOR:
774   case ISD::ATOMIC_LOAD_NAND:
775   case ISD::ATOMIC_LOAD_MIN:
776   case ISD::ATOMIC_LOAD_MAX:
777   case ISD::ATOMIC_LOAD_UMIN:
778   case ISD::ATOMIC_LOAD_UMAX:
779   case ISD::ATOMIC_LOAD:
780   case ISD::ATOMIC_STORE: {
781     const AtomicSDNode *AT = cast<AtomicSDNode>(N);
782     ID.AddInteger(AT->getMemoryVT().getRawBits());
783     ID.AddInteger(AT->getRawSubclassData());
784     ID.AddInteger(AT->getPointerInfo().getAddrSpace());
785     break;
786   }
787   case ISD::PREFETCH: {
788     const MemSDNode *PF = cast<MemSDNode>(N);
789     ID.AddInteger(PF->getPointerInfo().getAddrSpace());
790     break;
791   }
792   case ISD::VECTOR_SHUFFLE: {
793     const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
794     for (unsigned i = 0, e = N->getValueType(0).getVectorNumElements();
795          i != e; ++i)
796       ID.AddInteger(SVN->getMaskElt(i));
797     break;
798   }
799   case ISD::TargetBlockAddress:
800   case ISD::BlockAddress: {
801     const BlockAddressSDNode *BA = cast<BlockAddressSDNode>(N);
802     ID.AddPointer(BA->getBlockAddress());
803     ID.AddInteger(BA->getOffset());
804     ID.AddInteger(BA->getTargetFlags());
805     break;
806   }
807   } // end switch (N->getOpcode())
808 
809   // Target specific memory nodes could also have address spaces to check.
810   if (N->isTargetMemoryOpcode())
811     ID.AddInteger(cast<MemSDNode>(N)->getPointerInfo().getAddrSpace());
812 }
813 
814 /// AddNodeIDNode - Generic routine for adding a nodes info to the NodeID
815 /// data.
816 static void AddNodeIDNode(FoldingSetNodeID &ID, const SDNode *N) {
817   AddNodeIDOpcode(ID, N->getOpcode());
818   // Add the return value info.
819   AddNodeIDValueTypes(ID, N->getVTList());
820   // Add the operand info.
821   AddNodeIDOperands(ID, N->ops());
822 
823   // Handle SDNode leafs with special info.
824   AddNodeIDCustom(ID, N);
825 }
826 
827 //===----------------------------------------------------------------------===//
828 //                              SelectionDAG Class
829 //===----------------------------------------------------------------------===//
830 
831 /// doNotCSE - Return true if CSE should not be performed for this node.
832 static bool doNotCSE(SDNode *N) {
833   if (N->getValueType(0) == MVT::Glue)
834     return true; // Never CSE anything that produces a flag.
835 
836   switch (N->getOpcode()) {
837   default: break;
838   case ISD::HANDLENODE:
839   case ISD::EH_LABEL:
840     return true;   // Never CSE these nodes.
841   }
842 
843   // Check that remaining values produced are not flags.
844   for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
845     if (N->getValueType(i) == MVT::Glue)
846       return true; // Never CSE anything that produces a flag.
847 
848   return false;
849 }
850 
851 /// RemoveDeadNodes - This method deletes all unreachable nodes in the
852 /// SelectionDAG.
853 void SelectionDAG::RemoveDeadNodes() {
854   // Create a dummy node (which is not added to allnodes), that adds a reference
855   // to the root node, preventing it from being deleted.
856   HandleSDNode Dummy(getRoot());
857 
858   SmallVector<SDNode*, 128> DeadNodes;
859 
860   // Add all obviously-dead nodes to the DeadNodes worklist.
861   for (SDNode &Node : allnodes())
862     if (Node.use_empty())
863       DeadNodes.push_back(&Node);
864 
865   RemoveDeadNodes(DeadNodes);
866 
867   // If the root changed (e.g. it was a dead load, update the root).
868   setRoot(Dummy.getValue());
869 }
870 
871 /// RemoveDeadNodes - This method deletes the unreachable nodes in the
872 /// given list, and any nodes that become unreachable as a result.
873 void SelectionDAG::RemoveDeadNodes(SmallVectorImpl<SDNode *> &DeadNodes) {
874 
875   // Process the worklist, deleting the nodes and adding their uses to the
876   // worklist.
877   while (!DeadNodes.empty()) {
878     SDNode *N = DeadNodes.pop_back_val();
879     // Skip to next node if we've already managed to delete the node. This could
880     // happen if replacing a node causes a node previously added to the node to
881     // be deleted.
882     if (N->getOpcode() == ISD::DELETED_NODE)
883       continue;
884 
885     for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
886       DUL->NodeDeleted(N, nullptr);
887 
888     // Take the node out of the appropriate CSE map.
889     RemoveNodeFromCSEMaps(N);
890 
891     // Next, brutally remove the operand list.  This is safe to do, as there are
892     // no cycles in the graph.
893     for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) {
894       SDUse &Use = *I++;
895       SDNode *Operand = Use.getNode();
896       Use.set(SDValue());
897 
898       // Now that we removed this operand, see if there are no uses of it left.
899       if (Operand->use_empty())
900         DeadNodes.push_back(Operand);
901     }
902 
903     DeallocateNode(N);
904   }
905 }
906 
907 void SelectionDAG::RemoveDeadNode(SDNode *N){
908   SmallVector<SDNode*, 16> DeadNodes(1, N);
909 
910   // Create a dummy node that adds a reference to the root node, preventing
911   // it from being deleted.  (This matters if the root is an operand of the
912   // dead node.)
913   HandleSDNode Dummy(getRoot());
914 
915   RemoveDeadNodes(DeadNodes);
916 }
917 
918 void SelectionDAG::DeleteNode(SDNode *N) {
919   // First take this out of the appropriate CSE map.
920   RemoveNodeFromCSEMaps(N);
921 
922   // Finally, remove uses due to operands of this node, remove from the
923   // AllNodes list, and delete the node.
924   DeleteNodeNotInCSEMaps(N);
925 }
926 
927 void SelectionDAG::DeleteNodeNotInCSEMaps(SDNode *N) {
928   assert(N->getIterator() != AllNodes.begin() &&
929          "Cannot delete the entry node!");
930   assert(N->use_empty() && "Cannot delete a node that is not dead!");
931 
932   // Drop all of the operands and decrement used node's use counts.
933   N->DropOperands();
934 
935   DeallocateNode(N);
936 }
937 
938 void SDDbgInfo::add(SDDbgValue *V, bool isParameter) {
939   assert(!(V->isVariadic() && isParameter));
940   if (isParameter)
941     ByvalParmDbgValues.push_back(V);
942   else
943     DbgValues.push_back(V);
944   for (const SDNode *Node : V->getSDNodes())
945     if (Node)
946       DbgValMap[Node].push_back(V);
947 }
948 
949 void SDDbgInfo::erase(const SDNode *Node) {
950   DbgValMapType::iterator I = DbgValMap.find(Node);
951   if (I == DbgValMap.end())
952     return;
953   for (auto &Val: I->second)
954     Val->setIsInvalidated();
955   DbgValMap.erase(I);
956 }
957 
958 void SelectionDAG::DeallocateNode(SDNode *N) {
959   // If we have operands, deallocate them.
960   removeOperands(N);
961 
962   NodeAllocator.Deallocate(AllNodes.remove(N));
963 
964   // Set the opcode to DELETED_NODE to help catch bugs when node
965   // memory is reallocated.
966   // FIXME: There are places in SDag that have grown a dependency on the opcode
967   // value in the released node.
968   __asan_unpoison_memory_region(&N->NodeType, sizeof(N->NodeType));
969   N->NodeType = ISD::DELETED_NODE;
970 
971   // If any of the SDDbgValue nodes refer to this SDNode, invalidate
972   // them and forget about that node.
973   DbgInfo->erase(N);
974 }
975 
976 #ifndef NDEBUG
977 /// VerifySDNode - Sanity check the given SDNode.  Aborts if it is invalid.
978 static void VerifySDNode(SDNode *N) {
979   switch (N->getOpcode()) {
980   default:
981     break;
982   case ISD::BUILD_PAIR: {
983     EVT VT = N->getValueType(0);
984     assert(N->getNumValues() == 1 && "Too many results!");
985     assert(!VT.isVector() && (VT.isInteger() || VT.isFloatingPoint()) &&
986            "Wrong return type!");
987     assert(N->getNumOperands() == 2 && "Wrong number of operands!");
988     assert(N->getOperand(0).getValueType() == N->getOperand(1).getValueType() &&
989            "Mismatched operand types!");
990     assert(N->getOperand(0).getValueType().isInteger() == VT.isInteger() &&
991            "Wrong operand type!");
992     assert(VT.getSizeInBits() == 2 * N->getOperand(0).getValueSizeInBits() &&
993            "Wrong return type size");
994     break;
995   }
996   case ISD::BUILD_VECTOR: {
997     assert(N->getNumValues() == 1 && "Too many results!");
998     assert(N->getValueType(0).isVector() && "Wrong return type!");
999     assert(N->getNumOperands() == N->getValueType(0).getVectorNumElements() &&
1000            "Wrong number of operands!");
1001     EVT EltVT = N->getValueType(0).getVectorElementType();
1002     for (const SDUse &Op : N->ops()) {
1003       assert((Op.getValueType() == EltVT ||
1004               (EltVT.isInteger() && Op.getValueType().isInteger() &&
1005                EltVT.bitsLE(Op.getValueType()))) &&
1006              "Wrong operand type!");
1007       assert(Op.getValueType() == N->getOperand(0).getValueType() &&
1008              "Operands must all have the same type");
1009     }
1010     break;
1011   }
1012   }
1013 }
1014 #endif // NDEBUG
1015 
1016 /// Insert a newly allocated node into the DAG.
1017 ///
1018 /// Handles insertion into the all nodes list and CSE map, as well as
1019 /// verification and other common operations when a new node is allocated.
1020 void SelectionDAG::InsertNode(SDNode *N) {
1021   AllNodes.push_back(N);
1022 #ifndef NDEBUG
1023   N->PersistentId = NextPersistentId++;
1024   VerifySDNode(N);
1025 #endif
1026   for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
1027     DUL->NodeInserted(N);
1028 }
1029 
1030 /// RemoveNodeFromCSEMaps - Take the specified node out of the CSE map that
1031 /// correspond to it.  This is useful when we're about to delete or repurpose
1032 /// the node.  We don't want future request for structurally identical nodes
1033 /// to return N anymore.
1034 bool SelectionDAG::RemoveNodeFromCSEMaps(SDNode *N) {
1035   bool Erased = false;
1036   switch (N->getOpcode()) {
1037   case ISD::HANDLENODE: return false;  // noop.
1038   case ISD::CONDCODE:
1039     assert(CondCodeNodes[cast<CondCodeSDNode>(N)->get()] &&
1040            "Cond code doesn't exist!");
1041     Erased = CondCodeNodes[cast<CondCodeSDNode>(N)->get()] != nullptr;
1042     CondCodeNodes[cast<CondCodeSDNode>(N)->get()] = nullptr;
1043     break;
1044   case ISD::ExternalSymbol:
1045     Erased = ExternalSymbols.erase(cast<ExternalSymbolSDNode>(N)->getSymbol());
1046     break;
1047   case ISD::TargetExternalSymbol: {
1048     ExternalSymbolSDNode *ESN = cast<ExternalSymbolSDNode>(N);
1049     Erased = TargetExternalSymbols.erase(std::pair<std::string, unsigned>(
1050         ESN->getSymbol(), ESN->getTargetFlags()));
1051     break;
1052   }
1053   case ISD::MCSymbol: {
1054     auto *MCSN = cast<MCSymbolSDNode>(N);
1055     Erased = MCSymbols.erase(MCSN->getMCSymbol());
1056     break;
1057   }
1058   case ISD::VALUETYPE: {
1059     EVT VT = cast<VTSDNode>(N)->getVT();
1060     if (VT.isExtended()) {
1061       Erased = ExtendedValueTypeNodes.erase(VT);
1062     } else {
1063       Erased = ValueTypeNodes[VT.getSimpleVT().SimpleTy] != nullptr;
1064       ValueTypeNodes[VT.getSimpleVT().SimpleTy] = nullptr;
1065     }
1066     break;
1067   }
1068   default:
1069     // Remove it from the CSE Map.
1070     assert(N->getOpcode() != ISD::DELETED_NODE && "DELETED_NODE in CSEMap!");
1071     assert(N->getOpcode() != ISD::EntryToken && "EntryToken in CSEMap!");
1072     Erased = CSEMap.RemoveNode(N);
1073     break;
1074   }
1075 #ifndef NDEBUG
1076   // Verify that the node was actually in one of the CSE maps, unless it has a
1077   // flag result (which cannot be CSE'd) or is one of the special cases that are
1078   // not subject to CSE.
1079   if (!Erased && N->getValueType(N->getNumValues()-1) != MVT::Glue &&
1080       !N->isMachineOpcode() && !doNotCSE(N)) {
1081     N->dump(this);
1082     dbgs() << "\n";
1083     llvm_unreachable("Node is not in map!");
1084   }
1085 #endif
1086   return Erased;
1087 }
1088 
1089 /// AddModifiedNodeToCSEMaps - The specified node has been removed from the CSE
1090 /// maps and modified in place. Add it back to the CSE maps, unless an identical
1091 /// node already exists, in which case transfer all its users to the existing
1092 /// node. This transfer can potentially trigger recursive merging.
1093 void
1094 SelectionDAG::AddModifiedNodeToCSEMaps(SDNode *N) {
1095   // For node types that aren't CSE'd, just act as if no identical node
1096   // already exists.
1097   if (!doNotCSE(N)) {
1098     SDNode *Existing = CSEMap.GetOrInsertNode(N);
1099     if (Existing != N) {
1100       // If there was already an existing matching node, use ReplaceAllUsesWith
1101       // to replace the dead one with the existing one.  This can cause
1102       // recursive merging of other unrelated nodes down the line.
1103       ReplaceAllUsesWith(N, Existing);
1104 
1105       // N is now dead. Inform the listeners and delete it.
1106       for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
1107         DUL->NodeDeleted(N, Existing);
1108       DeleteNodeNotInCSEMaps(N);
1109       return;
1110     }
1111   }
1112 
1113   // If the node doesn't already exist, we updated it.  Inform listeners.
1114   for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
1115     DUL->NodeUpdated(N);
1116 }
1117 
1118 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
1119 /// were replaced with those specified.  If this node is never memoized,
1120 /// return null, otherwise return a pointer to the slot it would take.  If a
1121 /// node already exists with these operands, the slot will be non-null.
1122 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, SDValue Op,
1123                                            void *&InsertPos) {
1124   if (doNotCSE(N))
1125     return nullptr;
1126 
1127   SDValue Ops[] = { Op };
1128   FoldingSetNodeID ID;
1129   AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops);
1130   AddNodeIDCustom(ID, N);
1131   SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos);
1132   if (Node)
1133     Node->intersectFlagsWith(N->getFlags());
1134   return Node;
1135 }
1136 
1137 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
1138 /// were replaced with those specified.  If this node is never memoized,
1139 /// return null, otherwise return a pointer to the slot it would take.  If a
1140 /// node already exists with these operands, the slot will be non-null.
1141 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N,
1142                                            SDValue Op1, SDValue Op2,
1143                                            void *&InsertPos) {
1144   if (doNotCSE(N))
1145     return nullptr;
1146 
1147   SDValue Ops[] = { Op1, Op2 };
1148   FoldingSetNodeID ID;
1149   AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops);
1150   AddNodeIDCustom(ID, N);
1151   SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos);
1152   if (Node)
1153     Node->intersectFlagsWith(N->getFlags());
1154   return Node;
1155 }
1156 
1157 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
1158 /// were replaced with those specified.  If this node is never memoized,
1159 /// return null, otherwise return a pointer to the slot it would take.  If a
1160 /// node already exists with these operands, the slot will be non-null.
1161 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, ArrayRef<SDValue> Ops,
1162                                            void *&InsertPos) {
1163   if (doNotCSE(N))
1164     return nullptr;
1165 
1166   FoldingSetNodeID ID;
1167   AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops);
1168   AddNodeIDCustom(ID, N);
1169   SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos);
1170   if (Node)
1171     Node->intersectFlagsWith(N->getFlags());
1172   return Node;
1173 }
1174 
1175 Align SelectionDAG::getEVTAlign(EVT VT) const {
1176   Type *Ty = VT == MVT::iPTR ?
1177                    PointerType::get(Type::getInt8Ty(*getContext()), 0) :
1178                    VT.getTypeForEVT(*getContext());
1179 
1180   return getDataLayout().getABITypeAlign(Ty);
1181 }
1182 
1183 // EntryNode could meaningfully have debug info if we can find it...
1184 SelectionDAG::SelectionDAG(const TargetMachine &tm, CodeGenOpt::Level OL)
1185     : TM(tm), OptLevel(OL),
1186       EntryNode(ISD::EntryToken, 0, DebugLoc(), getVTList(MVT::Other)),
1187       Root(getEntryNode()) {
1188   InsertNode(&EntryNode);
1189   DbgInfo = new SDDbgInfo();
1190 }
1191 
1192 void SelectionDAG::init(MachineFunction &NewMF,
1193                         OptimizationRemarkEmitter &NewORE,
1194                         Pass *PassPtr, const TargetLibraryInfo *LibraryInfo,
1195                         LegacyDivergenceAnalysis * Divergence,
1196                         ProfileSummaryInfo *PSIin,
1197                         BlockFrequencyInfo *BFIin) {
1198   MF = &NewMF;
1199   SDAGISelPass = PassPtr;
1200   ORE = &NewORE;
1201   TLI = getSubtarget().getTargetLowering();
1202   TSI = getSubtarget().getSelectionDAGInfo();
1203   LibInfo = LibraryInfo;
1204   Context = &MF->getFunction().getContext();
1205   DA = Divergence;
1206   PSI = PSIin;
1207   BFI = BFIin;
1208 }
1209 
1210 SelectionDAG::~SelectionDAG() {
1211   assert(!UpdateListeners && "Dangling registered DAGUpdateListeners");
1212   allnodes_clear();
1213   OperandRecycler.clear(OperandAllocator);
1214   delete DbgInfo;
1215 }
1216 
1217 bool SelectionDAG::shouldOptForSize() const {
1218   return MF->getFunction().hasOptSize() ||
1219       llvm::shouldOptimizeForSize(FLI->MBB->getBasicBlock(), PSI, BFI);
1220 }
1221 
1222 void SelectionDAG::allnodes_clear() {
1223   assert(&*AllNodes.begin() == &EntryNode);
1224   AllNodes.remove(AllNodes.begin());
1225   while (!AllNodes.empty())
1226     DeallocateNode(&AllNodes.front());
1227 #ifndef NDEBUG
1228   NextPersistentId = 0;
1229 #endif
1230 }
1231 
1232 SDNode *SelectionDAG::FindNodeOrInsertPos(const FoldingSetNodeID &ID,
1233                                           void *&InsertPos) {
1234   SDNode *N = CSEMap.FindNodeOrInsertPos(ID, InsertPos);
1235   if (N) {
1236     switch (N->getOpcode()) {
1237     default: break;
1238     case ISD::Constant:
1239     case ISD::ConstantFP:
1240       llvm_unreachable("Querying for Constant and ConstantFP nodes requires "
1241                        "debug location.  Use another overload.");
1242     }
1243   }
1244   return N;
1245 }
1246 
1247 SDNode *SelectionDAG::FindNodeOrInsertPos(const FoldingSetNodeID &ID,
1248                                           const SDLoc &DL, void *&InsertPos) {
1249   SDNode *N = CSEMap.FindNodeOrInsertPos(ID, InsertPos);
1250   if (N) {
1251     switch (N->getOpcode()) {
1252     case ISD::Constant:
1253     case ISD::ConstantFP:
1254       // Erase debug location from the node if the node is used at several
1255       // different places. Do not propagate one location to all uses as it
1256       // will cause a worse single stepping debugging experience.
1257       if (N->getDebugLoc() != DL.getDebugLoc())
1258         N->setDebugLoc(DebugLoc());
1259       break;
1260     default:
1261       // When the node's point of use is located earlier in the instruction
1262       // sequence than its prior point of use, update its debug info to the
1263       // earlier location.
1264       if (DL.getIROrder() && DL.getIROrder() < N->getIROrder())
1265         N->setDebugLoc(DL.getDebugLoc());
1266       break;
1267     }
1268   }
1269   return N;
1270 }
1271 
1272 void SelectionDAG::clear() {
1273   allnodes_clear();
1274   OperandRecycler.clear(OperandAllocator);
1275   OperandAllocator.Reset();
1276   CSEMap.clear();
1277 
1278   ExtendedValueTypeNodes.clear();
1279   ExternalSymbols.clear();
1280   TargetExternalSymbols.clear();
1281   MCSymbols.clear();
1282   SDCallSiteDbgInfo.clear();
1283   std::fill(CondCodeNodes.begin(), CondCodeNodes.end(),
1284             static_cast<CondCodeSDNode*>(nullptr));
1285   std::fill(ValueTypeNodes.begin(), ValueTypeNodes.end(),
1286             static_cast<SDNode*>(nullptr));
1287 
1288   EntryNode.UseList = nullptr;
1289   InsertNode(&EntryNode);
1290   Root = getEntryNode();
1291   DbgInfo->clear();
1292 }
1293 
1294 SDValue SelectionDAG::getFPExtendOrRound(SDValue Op, const SDLoc &DL, EVT VT) {
1295   return VT.bitsGT(Op.getValueType())
1296              ? getNode(ISD::FP_EXTEND, DL, VT, Op)
1297              : getNode(ISD::FP_ROUND, DL, VT, Op, getIntPtrConstant(0, DL));
1298 }
1299 
1300 std::pair<SDValue, SDValue>
1301 SelectionDAG::getStrictFPExtendOrRound(SDValue Op, SDValue Chain,
1302                                        const SDLoc &DL, EVT VT) {
1303   assert(!VT.bitsEq(Op.getValueType()) &&
1304          "Strict no-op FP extend/round not allowed.");
1305   SDValue Res =
1306       VT.bitsGT(Op.getValueType())
1307           ? getNode(ISD::STRICT_FP_EXTEND, DL, {VT, MVT::Other}, {Chain, Op})
1308           : getNode(ISD::STRICT_FP_ROUND, DL, {VT, MVT::Other},
1309                     {Chain, Op, getIntPtrConstant(0, DL)});
1310 
1311   return std::pair<SDValue, SDValue>(Res, SDValue(Res.getNode(), 1));
1312 }
1313 
1314 SDValue SelectionDAG::getAnyExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
1315   return VT.bitsGT(Op.getValueType()) ?
1316     getNode(ISD::ANY_EXTEND, DL, VT, Op) :
1317     getNode(ISD::TRUNCATE, DL, VT, Op);
1318 }
1319 
1320 SDValue SelectionDAG::getSExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
1321   return VT.bitsGT(Op.getValueType()) ?
1322     getNode(ISD::SIGN_EXTEND, DL, VT, Op) :
1323     getNode(ISD::TRUNCATE, DL, VT, Op);
1324 }
1325 
1326 SDValue SelectionDAG::getZExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
1327   return VT.bitsGT(Op.getValueType()) ?
1328     getNode(ISD::ZERO_EXTEND, DL, VT, Op) :
1329     getNode(ISD::TRUNCATE, DL, VT, Op);
1330 }
1331 
1332 SDValue SelectionDAG::getBoolExtOrTrunc(SDValue Op, const SDLoc &SL, EVT VT,
1333                                         EVT OpVT) {
1334   if (VT.bitsLE(Op.getValueType()))
1335     return getNode(ISD::TRUNCATE, SL, VT, Op);
1336 
1337   TargetLowering::BooleanContent BType = TLI->getBooleanContents(OpVT);
1338   return getNode(TLI->getExtendForContent(BType), SL, VT, Op);
1339 }
1340 
1341 SDValue SelectionDAG::getZeroExtendInReg(SDValue Op, const SDLoc &DL, EVT VT) {
1342   EVT OpVT = Op.getValueType();
1343   assert(VT.isInteger() && OpVT.isInteger() &&
1344          "Cannot getZeroExtendInReg FP types");
1345   assert(VT.isVector() == OpVT.isVector() &&
1346          "getZeroExtendInReg type should be vector iff the operand "
1347          "type is vector!");
1348   assert((!VT.isVector() ||
1349           VT.getVectorElementCount() == OpVT.getVectorElementCount()) &&
1350          "Vector element counts must match in getZeroExtendInReg");
1351   assert(VT.bitsLE(OpVT) && "Not extending!");
1352   if (OpVT == VT)
1353     return Op;
1354   APInt Imm = APInt::getLowBitsSet(OpVT.getScalarSizeInBits(),
1355                                    VT.getScalarSizeInBits());
1356   return getNode(ISD::AND, DL, OpVT, Op, getConstant(Imm, DL, OpVT));
1357 }
1358 
1359 SDValue SelectionDAG::getPtrExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
1360   // Only unsigned pointer semantics are supported right now. In the future this
1361   // might delegate to TLI to check pointer signedness.
1362   return getZExtOrTrunc(Op, DL, VT);
1363 }
1364 
1365 SDValue SelectionDAG::getPtrExtendInReg(SDValue Op, const SDLoc &DL, EVT VT) {
1366   // Only unsigned pointer semantics are supported right now. In the future this
1367   // might delegate to TLI to check pointer signedness.
1368   return getZeroExtendInReg(Op, DL, VT);
1369 }
1370 
1371 /// getNOT - Create a bitwise NOT operation as (XOR Val, -1).
1372 SDValue SelectionDAG::getNOT(const SDLoc &DL, SDValue Val, EVT VT) {
1373   return getNode(ISD::XOR, DL, VT, Val, getAllOnesConstant(DL, VT));
1374 }
1375 
1376 SDValue SelectionDAG::getLogicalNOT(const SDLoc &DL, SDValue Val, EVT VT) {
1377   SDValue TrueValue = getBoolConstant(true, DL, VT, VT);
1378   return getNode(ISD::XOR, DL, VT, Val, TrueValue);
1379 }
1380 
1381 SDValue SelectionDAG::getBoolConstant(bool V, const SDLoc &DL, EVT VT,
1382                                       EVT OpVT) {
1383   if (!V)
1384     return getConstant(0, DL, VT);
1385 
1386   switch (TLI->getBooleanContents(OpVT)) {
1387   case TargetLowering::ZeroOrOneBooleanContent:
1388   case TargetLowering::UndefinedBooleanContent:
1389     return getConstant(1, DL, VT);
1390   case TargetLowering::ZeroOrNegativeOneBooleanContent:
1391     return getAllOnesConstant(DL, VT);
1392   }
1393   llvm_unreachable("Unexpected boolean content enum!");
1394 }
1395 
1396 SDValue SelectionDAG::getConstant(uint64_t Val, const SDLoc &DL, EVT VT,
1397                                   bool isT, bool isO) {
1398   EVT EltVT = VT.getScalarType();
1399   assert((EltVT.getSizeInBits() >= 64 ||
1400           (uint64_t)((int64_t)Val >> EltVT.getSizeInBits()) + 1 < 2) &&
1401          "getConstant with a uint64_t value that doesn't fit in the type!");
1402   return getConstant(APInt(EltVT.getSizeInBits(), Val), DL, VT, isT, isO);
1403 }
1404 
1405 SDValue SelectionDAG::getConstant(const APInt &Val, const SDLoc &DL, EVT VT,
1406                                   bool isT, bool isO) {
1407   return getConstant(*ConstantInt::get(*Context, Val), DL, VT, isT, isO);
1408 }
1409 
1410 SDValue SelectionDAG::getConstant(const ConstantInt &Val, const SDLoc &DL,
1411                                   EVT VT, bool isT, bool isO) {
1412   assert(VT.isInteger() && "Cannot create FP integer constant!");
1413 
1414   EVT EltVT = VT.getScalarType();
1415   const ConstantInt *Elt = &Val;
1416 
1417   // In some cases the vector type is legal but the element type is illegal and
1418   // needs to be promoted, for example v8i8 on ARM.  In this case, promote the
1419   // inserted value (the type does not need to match the vector element type).
1420   // Any extra bits introduced will be truncated away.
1421   if (VT.isVector() && TLI->getTypeAction(*getContext(), EltVT) ==
1422                            TargetLowering::TypePromoteInteger) {
1423     EltVT = TLI->getTypeToTransformTo(*getContext(), EltVT);
1424     APInt NewVal = Elt->getValue().zextOrTrunc(EltVT.getSizeInBits());
1425     Elt = ConstantInt::get(*getContext(), NewVal);
1426   }
1427   // In other cases the element type is illegal and needs to be expanded, for
1428   // example v2i64 on MIPS32. In this case, find the nearest legal type, split
1429   // the value into n parts and use a vector type with n-times the elements.
1430   // Then bitcast to the type requested.
1431   // Legalizing constants too early makes the DAGCombiner's job harder so we
1432   // only legalize if the DAG tells us we must produce legal types.
1433   else if (NewNodesMustHaveLegalTypes && VT.isVector() &&
1434            TLI->getTypeAction(*getContext(), EltVT) ==
1435                TargetLowering::TypeExpandInteger) {
1436     const APInt &NewVal = Elt->getValue();
1437     EVT ViaEltVT = TLI->getTypeToTransformTo(*getContext(), EltVT);
1438     unsigned ViaEltSizeInBits = ViaEltVT.getSizeInBits();
1439 
1440     // For scalable vectors, try to use a SPLAT_VECTOR_PARTS node.
1441     if (VT.isScalableVector()) {
1442       assert(EltVT.getSizeInBits() % ViaEltSizeInBits == 0 &&
1443              "Can only handle an even split!");
1444       unsigned Parts = EltVT.getSizeInBits() / ViaEltSizeInBits;
1445 
1446       SmallVector<SDValue, 2> ScalarParts;
1447       for (unsigned i = 0; i != Parts; ++i)
1448         ScalarParts.push_back(getConstant(
1449             NewVal.extractBits(ViaEltSizeInBits, i * ViaEltSizeInBits), DL,
1450             ViaEltVT, isT, isO));
1451 
1452       return getNode(ISD::SPLAT_VECTOR_PARTS, DL, VT, ScalarParts);
1453     }
1454 
1455     unsigned ViaVecNumElts = VT.getSizeInBits() / ViaEltSizeInBits;
1456     EVT ViaVecVT = EVT::getVectorVT(*getContext(), ViaEltVT, ViaVecNumElts);
1457 
1458     // Check the temporary vector is the correct size. If this fails then
1459     // getTypeToTransformTo() probably returned a type whose size (in bits)
1460     // isn't a power-of-2 factor of the requested type size.
1461     assert(ViaVecVT.getSizeInBits() == VT.getSizeInBits());
1462 
1463     SmallVector<SDValue, 2> EltParts;
1464     for (unsigned i = 0; i < ViaVecNumElts / VT.getVectorNumElements(); ++i)
1465       EltParts.push_back(getConstant(
1466           NewVal.extractBits(ViaEltSizeInBits, i * ViaEltSizeInBits), DL,
1467           ViaEltVT, isT, isO));
1468 
1469     // EltParts is currently in little endian order. If we actually want
1470     // big-endian order then reverse it now.
1471     if (getDataLayout().isBigEndian())
1472       std::reverse(EltParts.begin(), EltParts.end());
1473 
1474     // The elements must be reversed when the element order is different
1475     // to the endianness of the elements (because the BITCAST is itself a
1476     // vector shuffle in this situation). However, we do not need any code to
1477     // perform this reversal because getConstant() is producing a vector
1478     // splat.
1479     // This situation occurs in MIPS MSA.
1480 
1481     SmallVector<SDValue, 8> Ops;
1482     for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
1483       llvm::append_range(Ops, EltParts);
1484 
1485     SDValue V =
1486         getNode(ISD::BITCAST, DL, VT, getBuildVector(ViaVecVT, DL, Ops));
1487     return V;
1488   }
1489 
1490   assert(Elt->getBitWidth() == EltVT.getSizeInBits() &&
1491          "APInt size does not match type size!");
1492   unsigned Opc = isT ? ISD::TargetConstant : ISD::Constant;
1493   FoldingSetNodeID ID;
1494   AddNodeIDNode(ID, Opc, getVTList(EltVT), None);
1495   ID.AddPointer(Elt);
1496   ID.AddBoolean(isO);
1497   void *IP = nullptr;
1498   SDNode *N = nullptr;
1499   if ((N = FindNodeOrInsertPos(ID, DL, IP)))
1500     if (!VT.isVector())
1501       return SDValue(N, 0);
1502 
1503   if (!N) {
1504     N = newSDNode<ConstantSDNode>(isT, isO, Elt, EltVT);
1505     CSEMap.InsertNode(N, IP);
1506     InsertNode(N);
1507     NewSDValueDbgMsg(SDValue(N, 0), "Creating constant: ", this);
1508   }
1509 
1510   SDValue Result(N, 0);
1511   if (VT.isScalableVector())
1512     Result = getSplatVector(VT, DL, Result);
1513   else if (VT.isVector())
1514     Result = getSplatBuildVector(VT, DL, Result);
1515 
1516   return Result;
1517 }
1518 
1519 SDValue SelectionDAG::getIntPtrConstant(uint64_t Val, const SDLoc &DL,
1520                                         bool isTarget) {
1521   return getConstant(Val, DL, TLI->getPointerTy(getDataLayout()), isTarget);
1522 }
1523 
1524 SDValue SelectionDAG::getShiftAmountConstant(uint64_t Val, EVT VT,
1525                                              const SDLoc &DL, bool LegalTypes) {
1526   assert(VT.isInteger() && "Shift amount is not an integer type!");
1527   EVT ShiftVT = TLI->getShiftAmountTy(VT, getDataLayout(), LegalTypes);
1528   return getConstant(Val, DL, ShiftVT);
1529 }
1530 
1531 SDValue SelectionDAG::getVectorIdxConstant(uint64_t Val, const SDLoc &DL,
1532                                            bool isTarget) {
1533   return getConstant(Val, DL, TLI->getVectorIdxTy(getDataLayout()), isTarget);
1534 }
1535 
1536 SDValue SelectionDAG::getConstantFP(const APFloat &V, const SDLoc &DL, EVT VT,
1537                                     bool isTarget) {
1538   return getConstantFP(*ConstantFP::get(*getContext(), V), DL, VT, isTarget);
1539 }
1540 
1541 SDValue SelectionDAG::getConstantFP(const ConstantFP &V, const SDLoc &DL,
1542                                     EVT VT, bool isTarget) {
1543   assert(VT.isFloatingPoint() && "Cannot create integer FP constant!");
1544 
1545   EVT EltVT = VT.getScalarType();
1546 
1547   // Do the map lookup using the actual bit pattern for the floating point
1548   // value, so that we don't have problems with 0.0 comparing equal to -0.0, and
1549   // we don't have issues with SNANs.
1550   unsigned Opc = isTarget ? ISD::TargetConstantFP : ISD::ConstantFP;
1551   FoldingSetNodeID ID;
1552   AddNodeIDNode(ID, Opc, getVTList(EltVT), None);
1553   ID.AddPointer(&V);
1554   void *IP = nullptr;
1555   SDNode *N = nullptr;
1556   if ((N = FindNodeOrInsertPos(ID, DL, IP)))
1557     if (!VT.isVector())
1558       return SDValue(N, 0);
1559 
1560   if (!N) {
1561     N = newSDNode<ConstantFPSDNode>(isTarget, &V, EltVT);
1562     CSEMap.InsertNode(N, IP);
1563     InsertNode(N);
1564   }
1565 
1566   SDValue Result(N, 0);
1567   if (VT.isScalableVector())
1568     Result = getSplatVector(VT, DL, Result);
1569   else if (VT.isVector())
1570     Result = getSplatBuildVector(VT, DL, Result);
1571   NewSDValueDbgMsg(Result, "Creating fp constant: ", this);
1572   return Result;
1573 }
1574 
1575 SDValue SelectionDAG::getConstantFP(double Val, const SDLoc &DL, EVT VT,
1576                                     bool isTarget) {
1577   EVT EltVT = VT.getScalarType();
1578   if (EltVT == MVT::f32)
1579     return getConstantFP(APFloat((float)Val), DL, VT, isTarget);
1580   if (EltVT == MVT::f64)
1581     return getConstantFP(APFloat(Val), DL, VT, isTarget);
1582   if (EltVT == MVT::f80 || EltVT == MVT::f128 || EltVT == MVT::ppcf128 ||
1583       EltVT == MVT::f16 || EltVT == MVT::bf16) {
1584     bool Ignored;
1585     APFloat APF = APFloat(Val);
1586     APF.convert(EVTToAPFloatSemantics(EltVT), APFloat::rmNearestTiesToEven,
1587                 &Ignored);
1588     return getConstantFP(APF, DL, VT, isTarget);
1589   }
1590   llvm_unreachable("Unsupported type in getConstantFP");
1591 }
1592 
1593 SDValue SelectionDAG::getGlobalAddress(const GlobalValue *GV, const SDLoc &DL,
1594                                        EVT VT, int64_t Offset, bool isTargetGA,
1595                                        unsigned TargetFlags) {
1596   assert((TargetFlags == 0 || isTargetGA) &&
1597          "Cannot set target flags on target-independent globals");
1598 
1599   // Truncate (with sign-extension) the offset value to the pointer size.
1600   unsigned BitWidth = getDataLayout().getPointerTypeSizeInBits(GV->getType());
1601   if (BitWidth < 64)
1602     Offset = SignExtend64(Offset, BitWidth);
1603 
1604   unsigned Opc;
1605   if (GV->isThreadLocal())
1606     Opc = isTargetGA ? ISD::TargetGlobalTLSAddress : ISD::GlobalTLSAddress;
1607   else
1608     Opc = isTargetGA ? ISD::TargetGlobalAddress : ISD::GlobalAddress;
1609 
1610   FoldingSetNodeID ID;
1611   AddNodeIDNode(ID, Opc, getVTList(VT), None);
1612   ID.AddPointer(GV);
1613   ID.AddInteger(Offset);
1614   ID.AddInteger(TargetFlags);
1615   void *IP = nullptr;
1616   if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
1617     return SDValue(E, 0);
1618 
1619   auto *N = newSDNode<GlobalAddressSDNode>(
1620       Opc, DL.getIROrder(), DL.getDebugLoc(), GV, VT, Offset, TargetFlags);
1621   CSEMap.InsertNode(N, IP);
1622     InsertNode(N);
1623   return SDValue(N, 0);
1624 }
1625 
1626 SDValue SelectionDAG::getFrameIndex(int FI, EVT VT, bool isTarget) {
1627   unsigned Opc = isTarget ? ISD::TargetFrameIndex : ISD::FrameIndex;
1628   FoldingSetNodeID ID;
1629   AddNodeIDNode(ID, Opc, getVTList(VT), None);
1630   ID.AddInteger(FI);
1631   void *IP = nullptr;
1632   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1633     return SDValue(E, 0);
1634 
1635   auto *N = newSDNode<FrameIndexSDNode>(FI, VT, isTarget);
1636   CSEMap.InsertNode(N, IP);
1637   InsertNode(N);
1638   return SDValue(N, 0);
1639 }
1640 
1641 SDValue SelectionDAG::getJumpTable(int JTI, EVT VT, bool isTarget,
1642                                    unsigned TargetFlags) {
1643   assert((TargetFlags == 0 || isTarget) &&
1644          "Cannot set target flags on target-independent jump tables");
1645   unsigned Opc = isTarget ? ISD::TargetJumpTable : ISD::JumpTable;
1646   FoldingSetNodeID ID;
1647   AddNodeIDNode(ID, Opc, getVTList(VT), None);
1648   ID.AddInteger(JTI);
1649   ID.AddInteger(TargetFlags);
1650   void *IP = nullptr;
1651   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1652     return SDValue(E, 0);
1653 
1654   auto *N = newSDNode<JumpTableSDNode>(JTI, VT, isTarget, TargetFlags);
1655   CSEMap.InsertNode(N, IP);
1656   InsertNode(N);
1657   return SDValue(N, 0);
1658 }
1659 
1660 SDValue SelectionDAG::getConstantPool(const Constant *C, EVT VT,
1661                                       MaybeAlign Alignment, int Offset,
1662                                       bool isTarget, unsigned TargetFlags) {
1663   assert((TargetFlags == 0 || isTarget) &&
1664          "Cannot set target flags on target-independent globals");
1665   if (!Alignment)
1666     Alignment = shouldOptForSize()
1667                     ? getDataLayout().getABITypeAlign(C->getType())
1668                     : getDataLayout().getPrefTypeAlign(C->getType());
1669   unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
1670   FoldingSetNodeID ID;
1671   AddNodeIDNode(ID, Opc, getVTList(VT), None);
1672   ID.AddInteger(Alignment->value());
1673   ID.AddInteger(Offset);
1674   ID.AddPointer(C);
1675   ID.AddInteger(TargetFlags);
1676   void *IP = nullptr;
1677   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1678     return SDValue(E, 0);
1679 
1680   auto *N = newSDNode<ConstantPoolSDNode>(isTarget, C, VT, Offset, *Alignment,
1681                                           TargetFlags);
1682   CSEMap.InsertNode(N, IP);
1683   InsertNode(N);
1684   SDValue V = SDValue(N, 0);
1685   NewSDValueDbgMsg(V, "Creating new constant pool: ", this);
1686   return V;
1687 }
1688 
1689 SDValue SelectionDAG::getConstantPool(MachineConstantPoolValue *C, EVT VT,
1690                                       MaybeAlign Alignment, int Offset,
1691                                       bool isTarget, unsigned TargetFlags) {
1692   assert((TargetFlags == 0 || isTarget) &&
1693          "Cannot set target flags on target-independent globals");
1694   if (!Alignment)
1695     Alignment = getDataLayout().getPrefTypeAlign(C->getType());
1696   unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
1697   FoldingSetNodeID ID;
1698   AddNodeIDNode(ID, Opc, getVTList(VT), None);
1699   ID.AddInteger(Alignment->value());
1700   ID.AddInteger(Offset);
1701   C->addSelectionDAGCSEId(ID);
1702   ID.AddInteger(TargetFlags);
1703   void *IP = nullptr;
1704   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1705     return SDValue(E, 0);
1706 
1707   auto *N = newSDNode<ConstantPoolSDNode>(isTarget, C, VT, Offset, *Alignment,
1708                                           TargetFlags);
1709   CSEMap.InsertNode(N, IP);
1710   InsertNode(N);
1711   return SDValue(N, 0);
1712 }
1713 
1714 SDValue SelectionDAG::getTargetIndex(int Index, EVT VT, int64_t Offset,
1715                                      unsigned TargetFlags) {
1716   FoldingSetNodeID ID;
1717   AddNodeIDNode(ID, ISD::TargetIndex, getVTList(VT), None);
1718   ID.AddInteger(Index);
1719   ID.AddInteger(Offset);
1720   ID.AddInteger(TargetFlags);
1721   void *IP = nullptr;
1722   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1723     return SDValue(E, 0);
1724 
1725   auto *N = newSDNode<TargetIndexSDNode>(Index, VT, Offset, TargetFlags);
1726   CSEMap.InsertNode(N, IP);
1727   InsertNode(N);
1728   return SDValue(N, 0);
1729 }
1730 
1731 SDValue SelectionDAG::getBasicBlock(MachineBasicBlock *MBB) {
1732   FoldingSetNodeID ID;
1733   AddNodeIDNode(ID, ISD::BasicBlock, getVTList(MVT::Other), None);
1734   ID.AddPointer(MBB);
1735   void *IP = nullptr;
1736   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1737     return SDValue(E, 0);
1738 
1739   auto *N = newSDNode<BasicBlockSDNode>(MBB);
1740   CSEMap.InsertNode(N, IP);
1741   InsertNode(N);
1742   return SDValue(N, 0);
1743 }
1744 
1745 SDValue SelectionDAG::getValueType(EVT VT) {
1746   if (VT.isSimple() && (unsigned)VT.getSimpleVT().SimpleTy >=
1747       ValueTypeNodes.size())
1748     ValueTypeNodes.resize(VT.getSimpleVT().SimpleTy+1);
1749 
1750   SDNode *&N = VT.isExtended() ?
1751     ExtendedValueTypeNodes[VT] : ValueTypeNodes[VT.getSimpleVT().SimpleTy];
1752 
1753   if (N) return SDValue(N, 0);
1754   N = newSDNode<VTSDNode>(VT);
1755   InsertNode(N);
1756   return SDValue(N, 0);
1757 }
1758 
1759 SDValue SelectionDAG::getExternalSymbol(const char *Sym, EVT VT) {
1760   SDNode *&N = ExternalSymbols[Sym];
1761   if (N) return SDValue(N, 0);
1762   N = newSDNode<ExternalSymbolSDNode>(false, Sym, 0, VT);
1763   InsertNode(N);
1764   return SDValue(N, 0);
1765 }
1766 
1767 SDValue SelectionDAG::getMCSymbol(MCSymbol *Sym, EVT VT) {
1768   SDNode *&N = MCSymbols[Sym];
1769   if (N)
1770     return SDValue(N, 0);
1771   N = newSDNode<MCSymbolSDNode>(Sym, VT);
1772   InsertNode(N);
1773   return SDValue(N, 0);
1774 }
1775 
1776 SDValue SelectionDAG::getTargetExternalSymbol(const char *Sym, EVT VT,
1777                                               unsigned TargetFlags) {
1778   SDNode *&N =
1779       TargetExternalSymbols[std::pair<std::string, unsigned>(Sym, TargetFlags)];
1780   if (N) return SDValue(N, 0);
1781   N = newSDNode<ExternalSymbolSDNode>(true, Sym, TargetFlags, VT);
1782   InsertNode(N);
1783   return SDValue(N, 0);
1784 }
1785 
1786 SDValue SelectionDAG::getCondCode(ISD::CondCode Cond) {
1787   if ((unsigned)Cond >= CondCodeNodes.size())
1788     CondCodeNodes.resize(Cond+1);
1789 
1790   if (!CondCodeNodes[Cond]) {
1791     auto *N = newSDNode<CondCodeSDNode>(Cond);
1792     CondCodeNodes[Cond] = N;
1793     InsertNode(N);
1794   }
1795 
1796   return SDValue(CondCodeNodes[Cond], 0);
1797 }
1798 
1799 SDValue SelectionDAG::getStepVector(const SDLoc &DL, EVT ResVT) {
1800   APInt One(ResVT.getScalarSizeInBits(), 1);
1801   return getStepVector(DL, ResVT, One);
1802 }
1803 
1804 SDValue SelectionDAG::getStepVector(const SDLoc &DL, EVT ResVT, APInt StepVal) {
1805   assert(ResVT.getScalarSizeInBits() == StepVal.getBitWidth());
1806   if (ResVT.isScalableVector())
1807     return getNode(
1808         ISD::STEP_VECTOR, DL, ResVT,
1809         getTargetConstant(StepVal, DL, ResVT.getVectorElementType()));
1810 
1811   SmallVector<SDValue, 16> OpsStepConstants;
1812   for (uint64_t i = 0; i < ResVT.getVectorNumElements(); i++)
1813     OpsStepConstants.push_back(
1814         getConstant(StepVal * i, DL, ResVT.getVectorElementType()));
1815   return getBuildVector(ResVT, DL, OpsStepConstants);
1816 }
1817 
1818 /// Swaps the values of N1 and N2. Swaps all indices in the shuffle mask M that
1819 /// point at N1 to point at N2 and indices that point at N2 to point at N1.
1820 static void commuteShuffle(SDValue &N1, SDValue &N2, MutableArrayRef<int> M) {
1821   std::swap(N1, N2);
1822   ShuffleVectorSDNode::commuteMask(M);
1823 }
1824 
1825 SDValue SelectionDAG::getVectorShuffle(EVT VT, const SDLoc &dl, SDValue N1,
1826                                        SDValue N2, ArrayRef<int> Mask) {
1827   assert(VT.getVectorNumElements() == Mask.size() &&
1828          "Must have the same number of vector elements as mask elements!");
1829   assert(VT == N1.getValueType() && VT == N2.getValueType() &&
1830          "Invalid VECTOR_SHUFFLE");
1831 
1832   // Canonicalize shuffle undef, undef -> undef
1833   if (N1.isUndef() && N2.isUndef())
1834     return getUNDEF(VT);
1835 
1836   // Validate that all indices in Mask are within the range of the elements
1837   // input to the shuffle.
1838   int NElts = Mask.size();
1839   assert(llvm::all_of(Mask,
1840                       [&](int M) { return M < (NElts * 2) && M >= -1; }) &&
1841          "Index out of range");
1842 
1843   // Copy the mask so we can do any needed cleanup.
1844   SmallVector<int, 8> MaskVec(Mask.begin(), Mask.end());
1845 
1846   // Canonicalize shuffle v, v -> v, undef
1847   if (N1 == N2) {
1848     N2 = getUNDEF(VT);
1849     for (int i = 0; i != NElts; ++i)
1850       if (MaskVec[i] >= NElts) MaskVec[i] -= NElts;
1851   }
1852 
1853   // Canonicalize shuffle undef, v -> v, undef.  Commute the shuffle mask.
1854   if (N1.isUndef())
1855     commuteShuffle(N1, N2, MaskVec);
1856 
1857   if (TLI->hasVectorBlend()) {
1858     // If shuffling a splat, try to blend the splat instead. We do this here so
1859     // that even when this arises during lowering we don't have to re-handle it.
1860     auto BlendSplat = [&](BuildVectorSDNode *BV, int Offset) {
1861       BitVector UndefElements;
1862       SDValue Splat = BV->getSplatValue(&UndefElements);
1863       if (!Splat)
1864         return;
1865 
1866       for (int i = 0; i < NElts; ++i) {
1867         if (MaskVec[i] < Offset || MaskVec[i] >= (Offset + NElts))
1868           continue;
1869 
1870         // If this input comes from undef, mark it as such.
1871         if (UndefElements[MaskVec[i] - Offset]) {
1872           MaskVec[i] = -1;
1873           continue;
1874         }
1875 
1876         // If we can blend a non-undef lane, use that instead.
1877         if (!UndefElements[i])
1878           MaskVec[i] = i + Offset;
1879       }
1880     };
1881     if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
1882       BlendSplat(N1BV, 0);
1883     if (auto *N2BV = dyn_cast<BuildVectorSDNode>(N2))
1884       BlendSplat(N2BV, NElts);
1885   }
1886 
1887   // Canonicalize all index into lhs, -> shuffle lhs, undef
1888   // Canonicalize all index into rhs, -> shuffle rhs, undef
1889   bool AllLHS = true, AllRHS = true;
1890   bool N2Undef = N2.isUndef();
1891   for (int i = 0; i != NElts; ++i) {
1892     if (MaskVec[i] >= NElts) {
1893       if (N2Undef)
1894         MaskVec[i] = -1;
1895       else
1896         AllLHS = false;
1897     } else if (MaskVec[i] >= 0) {
1898       AllRHS = false;
1899     }
1900   }
1901   if (AllLHS && AllRHS)
1902     return getUNDEF(VT);
1903   if (AllLHS && !N2Undef)
1904     N2 = getUNDEF(VT);
1905   if (AllRHS) {
1906     N1 = getUNDEF(VT);
1907     commuteShuffle(N1, N2, MaskVec);
1908   }
1909   // Reset our undef status after accounting for the mask.
1910   N2Undef = N2.isUndef();
1911   // Re-check whether both sides ended up undef.
1912   if (N1.isUndef() && N2Undef)
1913     return getUNDEF(VT);
1914 
1915   // If Identity shuffle return that node.
1916   bool Identity = true, AllSame = true;
1917   for (int i = 0; i != NElts; ++i) {
1918     if (MaskVec[i] >= 0 && MaskVec[i] != i) Identity = false;
1919     if (MaskVec[i] != MaskVec[0]) AllSame = false;
1920   }
1921   if (Identity && NElts)
1922     return N1;
1923 
1924   // Shuffling a constant splat doesn't change the result.
1925   if (N2Undef) {
1926     SDValue V = N1;
1927 
1928     // Look through any bitcasts. We check that these don't change the number
1929     // (and size) of elements and just changes their types.
1930     while (V.getOpcode() == ISD::BITCAST)
1931       V = V->getOperand(0);
1932 
1933     // A splat should always show up as a build vector node.
1934     if (auto *BV = dyn_cast<BuildVectorSDNode>(V)) {
1935       BitVector UndefElements;
1936       SDValue Splat = BV->getSplatValue(&UndefElements);
1937       // If this is a splat of an undef, shuffling it is also undef.
1938       if (Splat && Splat.isUndef())
1939         return getUNDEF(VT);
1940 
1941       bool SameNumElts =
1942           V.getValueType().getVectorNumElements() == VT.getVectorNumElements();
1943 
1944       // We only have a splat which can skip shuffles if there is a splatted
1945       // value and no undef lanes rearranged by the shuffle.
1946       if (Splat && UndefElements.none()) {
1947         // Splat of <x, x, ..., x>, return <x, x, ..., x>, provided that the
1948         // number of elements match or the value splatted is a zero constant.
1949         if (SameNumElts)
1950           return N1;
1951         if (auto *C = dyn_cast<ConstantSDNode>(Splat))
1952           if (C->isZero())
1953             return N1;
1954       }
1955 
1956       // If the shuffle itself creates a splat, build the vector directly.
1957       if (AllSame && SameNumElts) {
1958         EVT BuildVT = BV->getValueType(0);
1959         const SDValue &Splatted = BV->getOperand(MaskVec[0]);
1960         SDValue NewBV = getSplatBuildVector(BuildVT, dl, Splatted);
1961 
1962         // We may have jumped through bitcasts, so the type of the
1963         // BUILD_VECTOR may not match the type of the shuffle.
1964         if (BuildVT != VT)
1965           NewBV = getNode(ISD::BITCAST, dl, VT, NewBV);
1966         return NewBV;
1967       }
1968     }
1969   }
1970 
1971   FoldingSetNodeID ID;
1972   SDValue Ops[2] = { N1, N2 };
1973   AddNodeIDNode(ID, ISD::VECTOR_SHUFFLE, getVTList(VT), Ops);
1974   for (int i = 0; i != NElts; ++i)
1975     ID.AddInteger(MaskVec[i]);
1976 
1977   void* IP = nullptr;
1978   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
1979     return SDValue(E, 0);
1980 
1981   // Allocate the mask array for the node out of the BumpPtrAllocator, since
1982   // SDNode doesn't have access to it.  This memory will be "leaked" when
1983   // the node is deallocated, but recovered when the NodeAllocator is released.
1984   int *MaskAlloc = OperandAllocator.Allocate<int>(NElts);
1985   llvm::copy(MaskVec, MaskAlloc);
1986 
1987   auto *N = newSDNode<ShuffleVectorSDNode>(VT, dl.getIROrder(),
1988                                            dl.getDebugLoc(), MaskAlloc);
1989   createOperands(N, Ops);
1990 
1991   CSEMap.InsertNode(N, IP);
1992   InsertNode(N);
1993   SDValue V = SDValue(N, 0);
1994   NewSDValueDbgMsg(V, "Creating new node: ", this);
1995   return V;
1996 }
1997 
1998 SDValue SelectionDAG::getCommutedVectorShuffle(const ShuffleVectorSDNode &SV) {
1999   EVT VT = SV.getValueType(0);
2000   SmallVector<int, 8> MaskVec(SV.getMask().begin(), SV.getMask().end());
2001   ShuffleVectorSDNode::commuteMask(MaskVec);
2002 
2003   SDValue Op0 = SV.getOperand(0);
2004   SDValue Op1 = SV.getOperand(1);
2005   return getVectorShuffle(VT, SDLoc(&SV), Op1, Op0, MaskVec);
2006 }
2007 
2008 SDValue SelectionDAG::getRegister(unsigned RegNo, EVT VT) {
2009   FoldingSetNodeID ID;
2010   AddNodeIDNode(ID, ISD::Register, getVTList(VT), None);
2011   ID.AddInteger(RegNo);
2012   void *IP = nullptr;
2013   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2014     return SDValue(E, 0);
2015 
2016   auto *N = newSDNode<RegisterSDNode>(RegNo, VT);
2017   N->SDNodeBits.IsDivergent = TLI->isSDNodeSourceOfDivergence(N, FLI, DA);
2018   CSEMap.InsertNode(N, IP);
2019   InsertNode(N);
2020   return SDValue(N, 0);
2021 }
2022 
2023 SDValue SelectionDAG::getRegisterMask(const uint32_t *RegMask) {
2024   FoldingSetNodeID ID;
2025   AddNodeIDNode(ID, ISD::RegisterMask, getVTList(MVT::Untyped), None);
2026   ID.AddPointer(RegMask);
2027   void *IP = nullptr;
2028   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2029     return SDValue(E, 0);
2030 
2031   auto *N = newSDNode<RegisterMaskSDNode>(RegMask);
2032   CSEMap.InsertNode(N, IP);
2033   InsertNode(N);
2034   return SDValue(N, 0);
2035 }
2036 
2037 SDValue SelectionDAG::getEHLabel(const SDLoc &dl, SDValue Root,
2038                                  MCSymbol *Label) {
2039   return getLabelNode(ISD::EH_LABEL, dl, Root, Label);
2040 }
2041 
2042 SDValue SelectionDAG::getLabelNode(unsigned Opcode, const SDLoc &dl,
2043                                    SDValue Root, MCSymbol *Label) {
2044   FoldingSetNodeID ID;
2045   SDValue Ops[] = { Root };
2046   AddNodeIDNode(ID, Opcode, getVTList(MVT::Other), Ops);
2047   ID.AddPointer(Label);
2048   void *IP = nullptr;
2049   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2050     return SDValue(E, 0);
2051 
2052   auto *N =
2053       newSDNode<LabelSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(), Label);
2054   createOperands(N, Ops);
2055 
2056   CSEMap.InsertNode(N, IP);
2057   InsertNode(N);
2058   return SDValue(N, 0);
2059 }
2060 
2061 SDValue SelectionDAG::getBlockAddress(const BlockAddress *BA, EVT VT,
2062                                       int64_t Offset, bool isTarget,
2063                                       unsigned TargetFlags) {
2064   unsigned Opc = isTarget ? ISD::TargetBlockAddress : ISD::BlockAddress;
2065 
2066   FoldingSetNodeID ID;
2067   AddNodeIDNode(ID, Opc, getVTList(VT), None);
2068   ID.AddPointer(BA);
2069   ID.AddInteger(Offset);
2070   ID.AddInteger(TargetFlags);
2071   void *IP = nullptr;
2072   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2073     return SDValue(E, 0);
2074 
2075   auto *N = newSDNode<BlockAddressSDNode>(Opc, VT, BA, Offset, TargetFlags);
2076   CSEMap.InsertNode(N, IP);
2077   InsertNode(N);
2078   return SDValue(N, 0);
2079 }
2080 
2081 SDValue SelectionDAG::getSrcValue(const Value *V) {
2082   FoldingSetNodeID ID;
2083   AddNodeIDNode(ID, ISD::SRCVALUE, getVTList(MVT::Other), None);
2084   ID.AddPointer(V);
2085 
2086   void *IP = nullptr;
2087   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2088     return SDValue(E, 0);
2089 
2090   auto *N = newSDNode<SrcValueSDNode>(V);
2091   CSEMap.InsertNode(N, IP);
2092   InsertNode(N);
2093   return SDValue(N, 0);
2094 }
2095 
2096 SDValue SelectionDAG::getMDNode(const MDNode *MD) {
2097   FoldingSetNodeID ID;
2098   AddNodeIDNode(ID, ISD::MDNODE_SDNODE, getVTList(MVT::Other), None);
2099   ID.AddPointer(MD);
2100 
2101   void *IP = nullptr;
2102   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2103     return SDValue(E, 0);
2104 
2105   auto *N = newSDNode<MDNodeSDNode>(MD);
2106   CSEMap.InsertNode(N, IP);
2107   InsertNode(N);
2108   return SDValue(N, 0);
2109 }
2110 
2111 SDValue SelectionDAG::getBitcast(EVT VT, SDValue V) {
2112   if (VT == V.getValueType())
2113     return V;
2114 
2115   return getNode(ISD::BITCAST, SDLoc(V), VT, V);
2116 }
2117 
2118 SDValue SelectionDAG::getAddrSpaceCast(const SDLoc &dl, EVT VT, SDValue Ptr,
2119                                        unsigned SrcAS, unsigned DestAS) {
2120   SDValue Ops[] = {Ptr};
2121   FoldingSetNodeID ID;
2122   AddNodeIDNode(ID, ISD::ADDRSPACECAST, getVTList(VT), Ops);
2123   ID.AddInteger(SrcAS);
2124   ID.AddInteger(DestAS);
2125 
2126   void *IP = nullptr;
2127   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
2128     return SDValue(E, 0);
2129 
2130   auto *N = newSDNode<AddrSpaceCastSDNode>(dl.getIROrder(), dl.getDebugLoc(),
2131                                            VT, SrcAS, DestAS);
2132   createOperands(N, Ops);
2133 
2134   CSEMap.InsertNode(N, IP);
2135   InsertNode(N);
2136   return SDValue(N, 0);
2137 }
2138 
2139 SDValue SelectionDAG::getFreeze(SDValue V) {
2140   return getNode(ISD::FREEZE, SDLoc(V), V.getValueType(), V);
2141 }
2142 
2143 /// getShiftAmountOperand - Return the specified value casted to
2144 /// the target's desired shift amount type.
2145 SDValue SelectionDAG::getShiftAmountOperand(EVT LHSTy, SDValue Op) {
2146   EVT OpTy = Op.getValueType();
2147   EVT ShTy = TLI->getShiftAmountTy(LHSTy, getDataLayout());
2148   if (OpTy == ShTy || OpTy.isVector()) return Op;
2149 
2150   return getZExtOrTrunc(Op, SDLoc(Op), ShTy);
2151 }
2152 
2153 SDValue SelectionDAG::expandVAArg(SDNode *Node) {
2154   SDLoc dl(Node);
2155   const TargetLowering &TLI = getTargetLoweringInfo();
2156   const Value *V = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
2157   EVT VT = Node->getValueType(0);
2158   SDValue Tmp1 = Node->getOperand(0);
2159   SDValue Tmp2 = Node->getOperand(1);
2160   const MaybeAlign MA(Node->getConstantOperandVal(3));
2161 
2162   SDValue VAListLoad = getLoad(TLI.getPointerTy(getDataLayout()), dl, Tmp1,
2163                                Tmp2, MachinePointerInfo(V));
2164   SDValue VAList = VAListLoad;
2165 
2166   if (MA && *MA > TLI.getMinStackArgumentAlignment()) {
2167     VAList = getNode(ISD::ADD, dl, VAList.getValueType(), VAList,
2168                      getConstant(MA->value() - 1, dl, VAList.getValueType()));
2169 
2170     VAList =
2171         getNode(ISD::AND, dl, VAList.getValueType(), VAList,
2172                 getConstant(-(int64_t)MA->value(), dl, VAList.getValueType()));
2173   }
2174 
2175   // Increment the pointer, VAList, to the next vaarg
2176   Tmp1 = getNode(ISD::ADD, dl, VAList.getValueType(), VAList,
2177                  getConstant(getDataLayout().getTypeAllocSize(
2178                                                VT.getTypeForEVT(*getContext())),
2179                              dl, VAList.getValueType()));
2180   // Store the incremented VAList to the legalized pointer
2181   Tmp1 =
2182       getStore(VAListLoad.getValue(1), dl, Tmp1, Tmp2, MachinePointerInfo(V));
2183   // Load the actual argument out of the pointer VAList
2184   return getLoad(VT, dl, Tmp1, VAList, MachinePointerInfo());
2185 }
2186 
2187 SDValue SelectionDAG::expandVACopy(SDNode *Node) {
2188   SDLoc dl(Node);
2189   const TargetLowering &TLI = getTargetLoweringInfo();
2190   // This defaults to loading a pointer from the input and storing it to the
2191   // output, returning the chain.
2192   const Value *VD = cast<SrcValueSDNode>(Node->getOperand(3))->getValue();
2193   const Value *VS = cast<SrcValueSDNode>(Node->getOperand(4))->getValue();
2194   SDValue Tmp1 =
2195       getLoad(TLI.getPointerTy(getDataLayout()), dl, Node->getOperand(0),
2196               Node->getOperand(2), MachinePointerInfo(VS));
2197   return getStore(Tmp1.getValue(1), dl, Tmp1, Node->getOperand(1),
2198                   MachinePointerInfo(VD));
2199 }
2200 
2201 Align SelectionDAG::getReducedAlign(EVT VT, bool UseABI) {
2202   const DataLayout &DL = getDataLayout();
2203   Type *Ty = VT.getTypeForEVT(*getContext());
2204   Align RedAlign = UseABI ? DL.getABITypeAlign(Ty) : DL.getPrefTypeAlign(Ty);
2205 
2206   if (TLI->isTypeLegal(VT) || !VT.isVector())
2207     return RedAlign;
2208 
2209   const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering();
2210   const Align StackAlign = TFI->getStackAlign();
2211 
2212   // See if we can choose a smaller ABI alignment in cases where it's an
2213   // illegal vector type that will get broken down.
2214   if (RedAlign > StackAlign) {
2215     EVT IntermediateVT;
2216     MVT RegisterVT;
2217     unsigned NumIntermediates;
2218     TLI->getVectorTypeBreakdown(*getContext(), VT, IntermediateVT,
2219                                 NumIntermediates, RegisterVT);
2220     Ty = IntermediateVT.getTypeForEVT(*getContext());
2221     Align RedAlign2 = UseABI ? DL.getABITypeAlign(Ty) : DL.getPrefTypeAlign(Ty);
2222     if (RedAlign2 < RedAlign)
2223       RedAlign = RedAlign2;
2224   }
2225 
2226   return RedAlign;
2227 }
2228 
2229 SDValue SelectionDAG::CreateStackTemporary(TypeSize Bytes, Align Alignment) {
2230   MachineFrameInfo &MFI = MF->getFrameInfo();
2231   const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering();
2232   int StackID = 0;
2233   if (Bytes.isScalable())
2234     StackID = TFI->getStackIDForScalableVectors();
2235   // The stack id gives an indication of whether the object is scalable or
2236   // not, so it's safe to pass in the minimum size here.
2237   int FrameIdx = MFI.CreateStackObject(Bytes.getKnownMinSize(), Alignment,
2238                                        false, nullptr, StackID);
2239   return getFrameIndex(FrameIdx, TLI->getFrameIndexTy(getDataLayout()));
2240 }
2241 
2242 SDValue SelectionDAG::CreateStackTemporary(EVT VT, unsigned minAlign) {
2243   Type *Ty = VT.getTypeForEVT(*getContext());
2244   Align StackAlign =
2245       std::max(getDataLayout().getPrefTypeAlign(Ty), Align(minAlign));
2246   return CreateStackTemporary(VT.getStoreSize(), StackAlign);
2247 }
2248 
2249 SDValue SelectionDAG::CreateStackTemporary(EVT VT1, EVT VT2) {
2250   TypeSize VT1Size = VT1.getStoreSize();
2251   TypeSize VT2Size = VT2.getStoreSize();
2252   assert(VT1Size.isScalable() == VT2Size.isScalable() &&
2253          "Don't know how to choose the maximum size when creating a stack "
2254          "temporary");
2255   TypeSize Bytes =
2256       VT1Size.getKnownMinSize() > VT2Size.getKnownMinSize() ? VT1Size : VT2Size;
2257 
2258   Type *Ty1 = VT1.getTypeForEVT(*getContext());
2259   Type *Ty2 = VT2.getTypeForEVT(*getContext());
2260   const DataLayout &DL = getDataLayout();
2261   Align Align = std::max(DL.getPrefTypeAlign(Ty1), DL.getPrefTypeAlign(Ty2));
2262   return CreateStackTemporary(Bytes, Align);
2263 }
2264 
2265 SDValue SelectionDAG::FoldSetCC(EVT VT, SDValue N1, SDValue N2,
2266                                 ISD::CondCode Cond, const SDLoc &dl) {
2267   EVT OpVT = N1.getValueType();
2268 
2269   // These setcc operations always fold.
2270   switch (Cond) {
2271   default: break;
2272   case ISD::SETFALSE:
2273   case ISD::SETFALSE2: return getBoolConstant(false, dl, VT, OpVT);
2274   case ISD::SETTRUE:
2275   case ISD::SETTRUE2: return getBoolConstant(true, dl, VT, OpVT);
2276 
2277   case ISD::SETOEQ:
2278   case ISD::SETOGT:
2279   case ISD::SETOGE:
2280   case ISD::SETOLT:
2281   case ISD::SETOLE:
2282   case ISD::SETONE:
2283   case ISD::SETO:
2284   case ISD::SETUO:
2285   case ISD::SETUEQ:
2286   case ISD::SETUNE:
2287     assert(!OpVT.isInteger() && "Illegal setcc for integer!");
2288     break;
2289   }
2290 
2291   if (OpVT.isInteger()) {
2292     // For EQ and NE, we can always pick a value for the undef to make the
2293     // predicate pass or fail, so we can return undef.
2294     // Matches behavior in llvm::ConstantFoldCompareInstruction.
2295     // icmp eq/ne X, undef -> undef.
2296     if ((N1.isUndef() || N2.isUndef()) &&
2297         (Cond == ISD::SETEQ || Cond == ISD::SETNE))
2298       return getUNDEF(VT);
2299 
2300     // If both operands are undef, we can return undef for int comparison.
2301     // icmp undef, undef -> undef.
2302     if (N1.isUndef() && N2.isUndef())
2303       return getUNDEF(VT);
2304 
2305     // icmp X, X -> true/false
2306     // icmp X, undef -> true/false because undef could be X.
2307     if (N1 == N2)
2308       return getBoolConstant(ISD::isTrueWhenEqual(Cond), dl, VT, OpVT);
2309   }
2310 
2311   if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2)) {
2312     const APInt &C2 = N2C->getAPIntValue();
2313     if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1)) {
2314       const APInt &C1 = N1C->getAPIntValue();
2315 
2316       return getBoolConstant(ICmpInst::compare(C1, C2, getICmpCondCode(Cond)),
2317                              dl, VT, OpVT);
2318     }
2319   }
2320 
2321   auto *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
2322   auto *N2CFP = dyn_cast<ConstantFPSDNode>(N2);
2323 
2324   if (N1CFP && N2CFP) {
2325     APFloat::cmpResult R = N1CFP->getValueAPF().compare(N2CFP->getValueAPF());
2326     switch (Cond) {
2327     default: break;
2328     case ISD::SETEQ:  if (R==APFloat::cmpUnordered)
2329                         return getUNDEF(VT);
2330                       LLVM_FALLTHROUGH;
2331     case ISD::SETOEQ: return getBoolConstant(R==APFloat::cmpEqual, dl, VT,
2332                                              OpVT);
2333     case ISD::SETNE:  if (R==APFloat::cmpUnordered)
2334                         return getUNDEF(VT);
2335                       LLVM_FALLTHROUGH;
2336     case ISD::SETONE: return getBoolConstant(R==APFloat::cmpGreaterThan ||
2337                                              R==APFloat::cmpLessThan, dl, VT,
2338                                              OpVT);
2339     case ISD::SETLT:  if (R==APFloat::cmpUnordered)
2340                         return getUNDEF(VT);
2341                       LLVM_FALLTHROUGH;
2342     case ISD::SETOLT: return getBoolConstant(R==APFloat::cmpLessThan, dl, VT,
2343                                              OpVT);
2344     case ISD::SETGT:  if (R==APFloat::cmpUnordered)
2345                         return getUNDEF(VT);
2346                       LLVM_FALLTHROUGH;
2347     case ISD::SETOGT: return getBoolConstant(R==APFloat::cmpGreaterThan, dl,
2348                                              VT, OpVT);
2349     case ISD::SETLE:  if (R==APFloat::cmpUnordered)
2350                         return getUNDEF(VT);
2351                       LLVM_FALLTHROUGH;
2352     case ISD::SETOLE: return getBoolConstant(R==APFloat::cmpLessThan ||
2353                                              R==APFloat::cmpEqual, dl, VT,
2354                                              OpVT);
2355     case ISD::SETGE:  if (R==APFloat::cmpUnordered)
2356                         return getUNDEF(VT);
2357                       LLVM_FALLTHROUGH;
2358     case ISD::SETOGE: return getBoolConstant(R==APFloat::cmpGreaterThan ||
2359                                          R==APFloat::cmpEqual, dl, VT, OpVT);
2360     case ISD::SETO:   return getBoolConstant(R!=APFloat::cmpUnordered, dl, VT,
2361                                              OpVT);
2362     case ISD::SETUO:  return getBoolConstant(R==APFloat::cmpUnordered, dl, VT,
2363                                              OpVT);
2364     case ISD::SETUEQ: return getBoolConstant(R==APFloat::cmpUnordered ||
2365                                              R==APFloat::cmpEqual, dl, VT,
2366                                              OpVT);
2367     case ISD::SETUNE: return getBoolConstant(R!=APFloat::cmpEqual, dl, VT,
2368                                              OpVT);
2369     case ISD::SETULT: return getBoolConstant(R==APFloat::cmpUnordered ||
2370                                              R==APFloat::cmpLessThan, dl, VT,
2371                                              OpVT);
2372     case ISD::SETUGT: return getBoolConstant(R==APFloat::cmpGreaterThan ||
2373                                              R==APFloat::cmpUnordered, dl, VT,
2374                                              OpVT);
2375     case ISD::SETULE: return getBoolConstant(R!=APFloat::cmpGreaterThan, dl,
2376                                              VT, OpVT);
2377     case ISD::SETUGE: return getBoolConstant(R!=APFloat::cmpLessThan, dl, VT,
2378                                              OpVT);
2379     }
2380   } else if (N1CFP && OpVT.isSimple() && !N2.isUndef()) {
2381     // Ensure that the constant occurs on the RHS.
2382     ISD::CondCode SwappedCond = ISD::getSetCCSwappedOperands(Cond);
2383     if (!TLI->isCondCodeLegal(SwappedCond, OpVT.getSimpleVT()))
2384       return SDValue();
2385     return getSetCC(dl, VT, N2, N1, SwappedCond);
2386   } else if ((N2CFP && N2CFP->getValueAPF().isNaN()) ||
2387              (OpVT.isFloatingPoint() && (N1.isUndef() || N2.isUndef()))) {
2388     // If an operand is known to be a nan (or undef that could be a nan), we can
2389     // fold it.
2390     // Choosing NaN for the undef will always make unordered comparison succeed
2391     // and ordered comparison fails.
2392     // Matches behavior in llvm::ConstantFoldCompareInstruction.
2393     switch (ISD::getUnorderedFlavor(Cond)) {
2394     default:
2395       llvm_unreachable("Unknown flavor!");
2396     case 0: // Known false.
2397       return getBoolConstant(false, dl, VT, OpVT);
2398     case 1: // Known true.
2399       return getBoolConstant(true, dl, VT, OpVT);
2400     case 2: // Undefined.
2401       return getUNDEF(VT);
2402     }
2403   }
2404 
2405   // Could not fold it.
2406   return SDValue();
2407 }
2408 
2409 /// See if the specified operand can be simplified with the knowledge that only
2410 /// the bits specified by DemandedBits are used.
2411 /// TODO: really we should be making this into the DAG equivalent of
2412 /// SimplifyMultipleUseDemandedBits and not generate any new nodes.
2413 SDValue SelectionDAG::GetDemandedBits(SDValue V, const APInt &DemandedBits) {
2414   EVT VT = V.getValueType();
2415 
2416   if (VT.isScalableVector())
2417     return SDValue();
2418 
2419   APInt DemandedElts = VT.isVector()
2420                            ? APInt::getAllOnes(VT.getVectorNumElements())
2421                            : APInt(1, 1);
2422   return GetDemandedBits(V, DemandedBits, DemandedElts);
2423 }
2424 
2425 /// See if the specified operand can be simplified with the knowledge that only
2426 /// the bits specified by DemandedBits are used in the elements specified by
2427 /// DemandedElts.
2428 /// TODO: really we should be making this into the DAG equivalent of
2429 /// SimplifyMultipleUseDemandedBits and not generate any new nodes.
2430 SDValue SelectionDAG::GetDemandedBits(SDValue V, const APInt &DemandedBits,
2431                                       const APInt &DemandedElts) {
2432   switch (V.getOpcode()) {
2433   default:
2434     return TLI->SimplifyMultipleUseDemandedBits(V, DemandedBits, DemandedElts,
2435                                                 *this, 0);
2436   case ISD::Constant: {
2437     const APInt &CVal = cast<ConstantSDNode>(V)->getAPIntValue();
2438     APInt NewVal = CVal & DemandedBits;
2439     if (NewVal != CVal)
2440       return getConstant(NewVal, SDLoc(V), V.getValueType());
2441     break;
2442   }
2443   case ISD::SRL:
2444     // Only look at single-use SRLs.
2445     if (!V.getNode()->hasOneUse())
2446       break;
2447     if (auto *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
2448       // See if we can recursively simplify the LHS.
2449       unsigned Amt = RHSC->getZExtValue();
2450 
2451       // Watch out for shift count overflow though.
2452       if (Amt >= DemandedBits.getBitWidth())
2453         break;
2454       APInt SrcDemandedBits = DemandedBits << Amt;
2455       if (SDValue SimplifyLHS =
2456               GetDemandedBits(V.getOperand(0), SrcDemandedBits))
2457         return getNode(ISD::SRL, SDLoc(V), V.getValueType(), SimplifyLHS,
2458                        V.getOperand(1));
2459     }
2460     break;
2461   }
2462   return SDValue();
2463 }
2464 
2465 /// SignBitIsZero - Return true if the sign bit of Op is known to be zero.  We
2466 /// use this predicate to simplify operations downstream.
2467 bool SelectionDAG::SignBitIsZero(SDValue Op, unsigned Depth) const {
2468   unsigned BitWidth = Op.getScalarValueSizeInBits();
2469   return MaskedValueIsZero(Op, APInt::getSignMask(BitWidth), Depth);
2470 }
2471 
2472 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero.  We use
2473 /// this predicate to simplify operations downstream.  Mask is known to be zero
2474 /// for bits that V cannot have.
2475 bool SelectionDAG::MaskedValueIsZero(SDValue V, const APInt &Mask,
2476                                      unsigned Depth) const {
2477   return Mask.isSubsetOf(computeKnownBits(V, Depth).Zero);
2478 }
2479 
2480 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero in
2481 /// DemandedElts.  We use this predicate to simplify operations downstream.
2482 /// Mask is known to be zero for bits that V cannot have.
2483 bool SelectionDAG::MaskedValueIsZero(SDValue V, const APInt &Mask,
2484                                      const APInt &DemandedElts,
2485                                      unsigned Depth) const {
2486   return Mask.isSubsetOf(computeKnownBits(V, DemandedElts, Depth).Zero);
2487 }
2488 
2489 /// MaskedValueIsAllOnes - Return true if '(Op & Mask) == Mask'.
2490 bool SelectionDAG::MaskedValueIsAllOnes(SDValue V, const APInt &Mask,
2491                                         unsigned Depth) const {
2492   return Mask.isSubsetOf(computeKnownBits(V, Depth).One);
2493 }
2494 
2495 /// isSplatValue - Return true if the vector V has the same value
2496 /// across all DemandedElts. For scalable vectors it does not make
2497 /// sense to specify which elements are demanded or undefined, therefore
2498 /// they are simply ignored.
2499 bool SelectionDAG::isSplatValue(SDValue V, const APInt &DemandedElts,
2500                                 APInt &UndefElts, unsigned Depth) {
2501   EVT VT = V.getValueType();
2502   assert(VT.isVector() && "Vector type expected");
2503 
2504   if (!VT.isScalableVector() && !DemandedElts)
2505     return false; // No demanded elts, better to assume we don't know anything.
2506 
2507   if (Depth >= MaxRecursionDepth)
2508     return false; // Limit search depth.
2509 
2510   // Deal with some common cases here that work for both fixed and scalable
2511   // vector types.
2512   switch (V.getOpcode()) {
2513   case ISD::SPLAT_VECTOR:
2514     UndefElts = V.getOperand(0).isUndef()
2515                     ? APInt::getAllOnes(DemandedElts.getBitWidth())
2516                     : APInt(DemandedElts.getBitWidth(), 0);
2517     return true;
2518   case ISD::ADD:
2519   case ISD::SUB:
2520   case ISD::AND:
2521   case ISD::XOR:
2522   case ISD::OR: {
2523     APInt UndefLHS, UndefRHS;
2524     SDValue LHS = V.getOperand(0);
2525     SDValue RHS = V.getOperand(1);
2526     if (isSplatValue(LHS, DemandedElts, UndefLHS, Depth + 1) &&
2527         isSplatValue(RHS, DemandedElts, UndefRHS, Depth + 1)) {
2528       UndefElts = UndefLHS | UndefRHS;
2529       return true;
2530     }
2531     return false;
2532   }
2533   case ISD::ABS:
2534   case ISD::TRUNCATE:
2535   case ISD::SIGN_EXTEND:
2536   case ISD::ZERO_EXTEND:
2537     return isSplatValue(V.getOperand(0), DemandedElts, UndefElts, Depth + 1);
2538   }
2539 
2540   // We don't support other cases than those above for scalable vectors at
2541   // the moment.
2542   if (VT.isScalableVector())
2543     return false;
2544 
2545   unsigned NumElts = VT.getVectorNumElements();
2546   assert(NumElts == DemandedElts.getBitWidth() && "Vector size mismatch");
2547   UndefElts = APInt::getZero(NumElts);
2548 
2549   switch (V.getOpcode()) {
2550   case ISD::BUILD_VECTOR: {
2551     SDValue Scl;
2552     for (unsigned i = 0; i != NumElts; ++i) {
2553       SDValue Op = V.getOperand(i);
2554       if (Op.isUndef()) {
2555         UndefElts.setBit(i);
2556         continue;
2557       }
2558       if (!DemandedElts[i])
2559         continue;
2560       if (Scl && Scl != Op)
2561         return false;
2562       Scl = Op;
2563     }
2564     return true;
2565   }
2566   case ISD::VECTOR_SHUFFLE: {
2567     // Check if this is a shuffle node doing a splat.
2568     // TODO: Do we need to handle shuffle(splat, undef, mask)?
2569     int SplatIndex = -1;
2570     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(V)->getMask();
2571     for (int i = 0; i != (int)NumElts; ++i) {
2572       int M = Mask[i];
2573       if (M < 0) {
2574         UndefElts.setBit(i);
2575         continue;
2576       }
2577       if (!DemandedElts[i])
2578         continue;
2579       if (0 <= SplatIndex && SplatIndex != M)
2580         return false;
2581       SplatIndex = M;
2582     }
2583     return true;
2584   }
2585   case ISD::EXTRACT_SUBVECTOR: {
2586     // Offset the demanded elts by the subvector index.
2587     SDValue Src = V.getOperand(0);
2588     // We don't support scalable vectors at the moment.
2589     if (Src.getValueType().isScalableVector())
2590       return false;
2591     uint64_t Idx = V.getConstantOperandVal(1);
2592     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
2593     APInt UndefSrcElts;
2594     APInt DemandedSrcElts = DemandedElts.zextOrSelf(NumSrcElts).shl(Idx);
2595     if (isSplatValue(Src, DemandedSrcElts, UndefSrcElts, Depth + 1)) {
2596       UndefElts = UndefSrcElts.extractBits(NumElts, Idx);
2597       return true;
2598     }
2599     break;
2600   }
2601   }
2602 
2603   return false;
2604 }
2605 
2606 /// Helper wrapper to main isSplatValue function.
2607 bool SelectionDAG::isSplatValue(SDValue V, bool AllowUndefs) {
2608   EVT VT = V.getValueType();
2609   assert(VT.isVector() && "Vector type expected");
2610 
2611   APInt UndefElts;
2612   APInt DemandedElts;
2613 
2614   // For now we don't support this with scalable vectors.
2615   if (!VT.isScalableVector())
2616     DemandedElts = APInt::getAllOnes(VT.getVectorNumElements());
2617   return isSplatValue(V, DemandedElts, UndefElts) &&
2618          (AllowUndefs || !UndefElts);
2619 }
2620 
2621 SDValue SelectionDAG::getSplatSourceVector(SDValue V, int &SplatIdx) {
2622   V = peekThroughExtractSubvectors(V);
2623 
2624   EVT VT = V.getValueType();
2625   unsigned Opcode = V.getOpcode();
2626   switch (Opcode) {
2627   default: {
2628     APInt UndefElts;
2629     APInt DemandedElts;
2630 
2631     if (!VT.isScalableVector())
2632       DemandedElts = APInt::getAllOnes(VT.getVectorNumElements());
2633 
2634     if (isSplatValue(V, DemandedElts, UndefElts)) {
2635       if (VT.isScalableVector()) {
2636         // DemandedElts and UndefElts are ignored for scalable vectors, since
2637         // the only supported cases are SPLAT_VECTOR nodes.
2638         SplatIdx = 0;
2639       } else {
2640         // Handle case where all demanded elements are UNDEF.
2641         if (DemandedElts.isSubsetOf(UndefElts)) {
2642           SplatIdx = 0;
2643           return getUNDEF(VT);
2644         }
2645         SplatIdx = (UndefElts & DemandedElts).countTrailingOnes();
2646       }
2647       return V;
2648     }
2649     break;
2650   }
2651   case ISD::SPLAT_VECTOR:
2652     SplatIdx = 0;
2653     return V;
2654   case ISD::VECTOR_SHUFFLE: {
2655     if (VT.isScalableVector())
2656       return SDValue();
2657 
2658     // Check if this is a shuffle node doing a splat.
2659     // TODO - remove this and rely purely on SelectionDAG::isSplatValue,
2660     // getTargetVShiftNode currently struggles without the splat source.
2661     auto *SVN = cast<ShuffleVectorSDNode>(V);
2662     if (!SVN->isSplat())
2663       break;
2664     int Idx = SVN->getSplatIndex();
2665     int NumElts = V.getValueType().getVectorNumElements();
2666     SplatIdx = Idx % NumElts;
2667     return V.getOperand(Idx / NumElts);
2668   }
2669   }
2670 
2671   return SDValue();
2672 }
2673 
2674 SDValue SelectionDAG::getSplatValue(SDValue V, bool LegalTypes) {
2675   int SplatIdx;
2676   if (SDValue SrcVector = getSplatSourceVector(V, SplatIdx)) {
2677     EVT SVT = SrcVector.getValueType().getScalarType();
2678     EVT LegalSVT = SVT;
2679     if (LegalTypes && !TLI->isTypeLegal(SVT)) {
2680       if (!SVT.isInteger())
2681         return SDValue();
2682       LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT);
2683       if (LegalSVT.bitsLT(SVT))
2684         return SDValue();
2685     }
2686     return getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(V), LegalSVT, SrcVector,
2687                    getVectorIdxConstant(SplatIdx, SDLoc(V)));
2688   }
2689   return SDValue();
2690 }
2691 
2692 const APInt *
2693 SelectionDAG::getValidShiftAmountConstant(SDValue V,
2694                                           const APInt &DemandedElts) const {
2695   assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL ||
2696           V.getOpcode() == ISD::SRA) &&
2697          "Unknown shift node");
2698   unsigned BitWidth = V.getScalarValueSizeInBits();
2699   if (ConstantSDNode *SA = isConstOrConstSplat(V.getOperand(1), DemandedElts)) {
2700     // Shifting more than the bitwidth is not valid.
2701     const APInt &ShAmt = SA->getAPIntValue();
2702     if (ShAmt.ult(BitWidth))
2703       return &ShAmt;
2704   }
2705   return nullptr;
2706 }
2707 
2708 const APInt *SelectionDAG::getValidMinimumShiftAmountConstant(
2709     SDValue V, const APInt &DemandedElts) const {
2710   assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL ||
2711           V.getOpcode() == ISD::SRA) &&
2712          "Unknown shift node");
2713   if (const APInt *ValidAmt = getValidShiftAmountConstant(V, DemandedElts))
2714     return ValidAmt;
2715   unsigned BitWidth = V.getScalarValueSizeInBits();
2716   auto *BV = dyn_cast<BuildVectorSDNode>(V.getOperand(1));
2717   if (!BV)
2718     return nullptr;
2719   const APInt *MinShAmt = nullptr;
2720   for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
2721     if (!DemandedElts[i])
2722       continue;
2723     auto *SA = dyn_cast<ConstantSDNode>(BV->getOperand(i));
2724     if (!SA)
2725       return nullptr;
2726     // Shifting more than the bitwidth is not valid.
2727     const APInt &ShAmt = SA->getAPIntValue();
2728     if (ShAmt.uge(BitWidth))
2729       return nullptr;
2730     if (MinShAmt && MinShAmt->ule(ShAmt))
2731       continue;
2732     MinShAmt = &ShAmt;
2733   }
2734   return MinShAmt;
2735 }
2736 
2737 const APInt *SelectionDAG::getValidMaximumShiftAmountConstant(
2738     SDValue V, const APInt &DemandedElts) const {
2739   assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL ||
2740           V.getOpcode() == ISD::SRA) &&
2741          "Unknown shift node");
2742   if (const APInt *ValidAmt = getValidShiftAmountConstant(V, DemandedElts))
2743     return ValidAmt;
2744   unsigned BitWidth = V.getScalarValueSizeInBits();
2745   auto *BV = dyn_cast<BuildVectorSDNode>(V.getOperand(1));
2746   if (!BV)
2747     return nullptr;
2748   const APInt *MaxShAmt = nullptr;
2749   for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
2750     if (!DemandedElts[i])
2751       continue;
2752     auto *SA = dyn_cast<ConstantSDNode>(BV->getOperand(i));
2753     if (!SA)
2754       return nullptr;
2755     // Shifting more than the bitwidth is not valid.
2756     const APInt &ShAmt = SA->getAPIntValue();
2757     if (ShAmt.uge(BitWidth))
2758       return nullptr;
2759     if (MaxShAmt && MaxShAmt->uge(ShAmt))
2760       continue;
2761     MaxShAmt = &ShAmt;
2762   }
2763   return MaxShAmt;
2764 }
2765 
2766 /// Determine which bits of Op are known to be either zero or one and return
2767 /// them in Known. For vectors, the known bits are those that are shared by
2768 /// every vector element.
2769 KnownBits SelectionDAG::computeKnownBits(SDValue Op, unsigned Depth) const {
2770   EVT VT = Op.getValueType();
2771 
2772   // TOOD: Until we have a plan for how to represent demanded elements for
2773   // scalable vectors, we can just bail out for now.
2774   if (Op.getValueType().isScalableVector()) {
2775     unsigned BitWidth = Op.getScalarValueSizeInBits();
2776     return KnownBits(BitWidth);
2777   }
2778 
2779   APInt DemandedElts = VT.isVector()
2780                            ? APInt::getAllOnes(VT.getVectorNumElements())
2781                            : APInt(1, 1);
2782   return computeKnownBits(Op, DemandedElts, Depth);
2783 }
2784 
2785 /// Determine which bits of Op are known to be either zero or one and return
2786 /// them in Known. The DemandedElts argument allows us to only collect the known
2787 /// bits that are shared by the requested vector elements.
2788 KnownBits SelectionDAG::computeKnownBits(SDValue Op, const APInt &DemandedElts,
2789                                          unsigned Depth) const {
2790   unsigned BitWidth = Op.getScalarValueSizeInBits();
2791 
2792   KnownBits Known(BitWidth);   // Don't know anything.
2793 
2794   // TOOD: Until we have a plan for how to represent demanded elements for
2795   // scalable vectors, we can just bail out for now.
2796   if (Op.getValueType().isScalableVector())
2797     return Known;
2798 
2799   if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
2800     // We know all of the bits for a constant!
2801     return KnownBits::makeConstant(C->getAPIntValue());
2802   }
2803   if (auto *C = dyn_cast<ConstantFPSDNode>(Op)) {
2804     // We know all of the bits for a constant fp!
2805     return KnownBits::makeConstant(C->getValueAPF().bitcastToAPInt());
2806   }
2807 
2808   if (Depth >= MaxRecursionDepth)
2809     return Known;  // Limit search depth.
2810 
2811   KnownBits Known2;
2812   unsigned NumElts = DemandedElts.getBitWidth();
2813   assert((!Op.getValueType().isVector() ||
2814           NumElts == Op.getValueType().getVectorNumElements()) &&
2815          "Unexpected vector size");
2816 
2817   if (!DemandedElts)
2818     return Known;  // No demanded elts, better to assume we don't know anything.
2819 
2820   unsigned Opcode = Op.getOpcode();
2821   switch (Opcode) {
2822   case ISD::BUILD_VECTOR:
2823     // Collect the known bits that are shared by every demanded vector element.
2824     Known.Zero.setAllBits(); Known.One.setAllBits();
2825     for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
2826       if (!DemandedElts[i])
2827         continue;
2828 
2829       SDValue SrcOp = Op.getOperand(i);
2830       Known2 = computeKnownBits(SrcOp, Depth + 1);
2831 
2832       // BUILD_VECTOR can implicitly truncate sources, we must handle this.
2833       if (SrcOp.getValueSizeInBits() != BitWidth) {
2834         assert(SrcOp.getValueSizeInBits() > BitWidth &&
2835                "Expected BUILD_VECTOR implicit truncation");
2836         Known2 = Known2.trunc(BitWidth);
2837       }
2838 
2839       // Known bits are the values that are shared by every demanded element.
2840       Known = KnownBits::commonBits(Known, Known2);
2841 
2842       // If we don't know any bits, early out.
2843       if (Known.isUnknown())
2844         break;
2845     }
2846     break;
2847   case ISD::VECTOR_SHUFFLE: {
2848     // Collect the known bits that are shared by every vector element referenced
2849     // by the shuffle.
2850     APInt DemandedLHS(NumElts, 0), DemandedRHS(NumElts, 0);
2851     Known.Zero.setAllBits(); Known.One.setAllBits();
2852     const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op);
2853     assert(NumElts == SVN->getMask().size() && "Unexpected vector size");
2854     for (unsigned i = 0; i != NumElts; ++i) {
2855       if (!DemandedElts[i])
2856         continue;
2857 
2858       int M = SVN->getMaskElt(i);
2859       if (M < 0) {
2860         // For UNDEF elements, we don't know anything about the common state of
2861         // the shuffle result.
2862         Known.resetAll();
2863         DemandedLHS.clearAllBits();
2864         DemandedRHS.clearAllBits();
2865         break;
2866       }
2867 
2868       if ((unsigned)M < NumElts)
2869         DemandedLHS.setBit((unsigned)M % NumElts);
2870       else
2871         DemandedRHS.setBit((unsigned)M % NumElts);
2872     }
2873     // Known bits are the values that are shared by every demanded element.
2874     if (!!DemandedLHS) {
2875       SDValue LHS = Op.getOperand(0);
2876       Known2 = computeKnownBits(LHS, DemandedLHS, Depth + 1);
2877       Known = KnownBits::commonBits(Known, Known2);
2878     }
2879     // If we don't know any bits, early out.
2880     if (Known.isUnknown())
2881       break;
2882     if (!!DemandedRHS) {
2883       SDValue RHS = Op.getOperand(1);
2884       Known2 = computeKnownBits(RHS, DemandedRHS, Depth + 1);
2885       Known = KnownBits::commonBits(Known, Known2);
2886     }
2887     break;
2888   }
2889   case ISD::CONCAT_VECTORS: {
2890     // Split DemandedElts and test each of the demanded subvectors.
2891     Known.Zero.setAllBits(); Known.One.setAllBits();
2892     EVT SubVectorVT = Op.getOperand(0).getValueType();
2893     unsigned NumSubVectorElts = SubVectorVT.getVectorNumElements();
2894     unsigned NumSubVectors = Op.getNumOperands();
2895     for (unsigned i = 0; i != NumSubVectors; ++i) {
2896       APInt DemandedSub =
2897           DemandedElts.extractBits(NumSubVectorElts, i * NumSubVectorElts);
2898       if (!!DemandedSub) {
2899         SDValue Sub = Op.getOperand(i);
2900         Known2 = computeKnownBits(Sub, DemandedSub, Depth + 1);
2901         Known = KnownBits::commonBits(Known, Known2);
2902       }
2903       // If we don't know any bits, early out.
2904       if (Known.isUnknown())
2905         break;
2906     }
2907     break;
2908   }
2909   case ISD::INSERT_SUBVECTOR: {
2910     // Demand any elements from the subvector and the remainder from the src its
2911     // inserted into.
2912     SDValue Src = Op.getOperand(0);
2913     SDValue Sub = Op.getOperand(1);
2914     uint64_t Idx = Op.getConstantOperandVal(2);
2915     unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
2916     APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
2917     APInt DemandedSrcElts = DemandedElts;
2918     DemandedSrcElts.insertBits(APInt::getZero(NumSubElts), Idx);
2919 
2920     Known.One.setAllBits();
2921     Known.Zero.setAllBits();
2922     if (!!DemandedSubElts) {
2923       Known = computeKnownBits(Sub, DemandedSubElts, Depth + 1);
2924       if (Known.isUnknown())
2925         break; // early-out.
2926     }
2927     if (!!DemandedSrcElts) {
2928       Known2 = computeKnownBits(Src, DemandedSrcElts, Depth + 1);
2929       Known = KnownBits::commonBits(Known, Known2);
2930     }
2931     break;
2932   }
2933   case ISD::EXTRACT_SUBVECTOR: {
2934     // Offset the demanded elts by the subvector index.
2935     SDValue Src = Op.getOperand(0);
2936     // Bail until we can represent demanded elements for scalable vectors.
2937     if (Src.getValueType().isScalableVector())
2938       break;
2939     uint64_t Idx = Op.getConstantOperandVal(1);
2940     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
2941     APInt DemandedSrcElts = DemandedElts.zextOrSelf(NumSrcElts).shl(Idx);
2942     Known = computeKnownBits(Src, DemandedSrcElts, Depth + 1);
2943     break;
2944   }
2945   case ISD::SCALAR_TO_VECTOR: {
2946     // We know about scalar_to_vector as much as we know about it source,
2947     // which becomes the first element of otherwise unknown vector.
2948     if (DemandedElts != 1)
2949       break;
2950 
2951     SDValue N0 = Op.getOperand(0);
2952     Known = computeKnownBits(N0, Depth + 1);
2953     if (N0.getValueSizeInBits() != BitWidth)
2954       Known = Known.trunc(BitWidth);
2955 
2956     break;
2957   }
2958   case ISD::BITCAST: {
2959     SDValue N0 = Op.getOperand(0);
2960     EVT SubVT = N0.getValueType();
2961     unsigned SubBitWidth = SubVT.getScalarSizeInBits();
2962 
2963     // Ignore bitcasts from unsupported types.
2964     if (!(SubVT.isInteger() || SubVT.isFloatingPoint()))
2965       break;
2966 
2967     // Fast handling of 'identity' bitcasts.
2968     if (BitWidth == SubBitWidth) {
2969       Known = computeKnownBits(N0, DemandedElts, Depth + 1);
2970       break;
2971     }
2972 
2973     bool IsLE = getDataLayout().isLittleEndian();
2974 
2975     // Bitcast 'small element' vector to 'large element' scalar/vector.
2976     if ((BitWidth % SubBitWidth) == 0) {
2977       assert(N0.getValueType().isVector() && "Expected bitcast from vector");
2978 
2979       // Collect known bits for the (larger) output by collecting the known
2980       // bits from each set of sub elements and shift these into place.
2981       // We need to separately call computeKnownBits for each set of
2982       // sub elements as the knownbits for each is likely to be different.
2983       unsigned SubScale = BitWidth / SubBitWidth;
2984       APInt SubDemandedElts(NumElts * SubScale, 0);
2985       for (unsigned i = 0; i != NumElts; ++i)
2986         if (DemandedElts[i])
2987           SubDemandedElts.setBit(i * SubScale);
2988 
2989       for (unsigned i = 0; i != SubScale; ++i) {
2990         Known2 = computeKnownBits(N0, SubDemandedElts.shl(i),
2991                          Depth + 1);
2992         unsigned Shifts = IsLE ? i : SubScale - 1 - i;
2993         Known.insertBits(Known2, SubBitWidth * Shifts);
2994       }
2995     }
2996 
2997     // Bitcast 'large element' scalar/vector to 'small element' vector.
2998     if ((SubBitWidth % BitWidth) == 0) {
2999       assert(Op.getValueType().isVector() && "Expected bitcast to vector");
3000 
3001       // Collect known bits for the (smaller) output by collecting the known
3002       // bits from the overlapping larger input elements and extracting the
3003       // sub sections we actually care about.
3004       unsigned SubScale = SubBitWidth / BitWidth;
3005       APInt SubDemandedElts =
3006           APIntOps::ScaleBitMask(DemandedElts, NumElts / SubScale);
3007       Known2 = computeKnownBits(N0, SubDemandedElts, Depth + 1);
3008 
3009       Known.Zero.setAllBits(); Known.One.setAllBits();
3010       for (unsigned i = 0; i != NumElts; ++i)
3011         if (DemandedElts[i]) {
3012           unsigned Shifts = IsLE ? i : NumElts - 1 - i;
3013           unsigned Offset = (Shifts % SubScale) * BitWidth;
3014           Known = KnownBits::commonBits(Known,
3015                                         Known2.extractBits(BitWidth, Offset));
3016           // If we don't know any bits, early out.
3017           if (Known.isUnknown())
3018             break;
3019         }
3020     }
3021     break;
3022   }
3023   case ISD::AND:
3024     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3025     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3026 
3027     Known &= Known2;
3028     break;
3029   case ISD::OR:
3030     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3031     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3032 
3033     Known |= Known2;
3034     break;
3035   case ISD::XOR:
3036     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3037     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3038 
3039     Known ^= Known2;
3040     break;
3041   case ISD::MUL: {
3042     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3043     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3044     Known = KnownBits::mul(Known, Known2);
3045     break;
3046   }
3047   case ISD::MULHU: {
3048     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3049     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3050     Known = KnownBits::mulhu(Known, Known2);
3051     break;
3052   }
3053   case ISD::MULHS: {
3054     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3055     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3056     Known = KnownBits::mulhs(Known, Known2);
3057     break;
3058   }
3059   case ISD::UMUL_LOHI: {
3060     assert((Op.getResNo() == 0 || Op.getResNo() == 1) && "Unknown result");
3061     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3062     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3063     if (Op.getResNo() == 0)
3064       Known = KnownBits::mul(Known, Known2);
3065     else
3066       Known = KnownBits::mulhu(Known, Known2);
3067     break;
3068   }
3069   case ISD::SMUL_LOHI: {
3070     assert((Op.getResNo() == 0 || Op.getResNo() == 1) && "Unknown result");
3071     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3072     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3073     if (Op.getResNo() == 0)
3074       Known = KnownBits::mul(Known, Known2);
3075     else
3076       Known = KnownBits::mulhs(Known, Known2);
3077     break;
3078   }
3079   case ISD::UDIV: {
3080     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3081     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3082     Known = KnownBits::udiv(Known, Known2);
3083     break;
3084   }
3085   case ISD::SELECT:
3086   case ISD::VSELECT:
3087     Known = computeKnownBits(Op.getOperand(2), DemandedElts, Depth+1);
3088     // If we don't know any bits, early out.
3089     if (Known.isUnknown())
3090       break;
3091     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth+1);
3092 
3093     // Only known if known in both the LHS and RHS.
3094     Known = KnownBits::commonBits(Known, Known2);
3095     break;
3096   case ISD::SELECT_CC:
3097     Known = computeKnownBits(Op.getOperand(3), DemandedElts, Depth+1);
3098     // If we don't know any bits, early out.
3099     if (Known.isUnknown())
3100       break;
3101     Known2 = computeKnownBits(Op.getOperand(2), DemandedElts, Depth+1);
3102 
3103     // Only known if known in both the LHS and RHS.
3104     Known = KnownBits::commonBits(Known, Known2);
3105     break;
3106   case ISD::SMULO:
3107   case ISD::UMULO:
3108     if (Op.getResNo() != 1)
3109       break;
3110     // The boolean result conforms to getBooleanContents.
3111     // If we know the result of a setcc has the top bits zero, use this info.
3112     // We know that we have an integer-based boolean since these operations
3113     // are only available for integer.
3114     if (TLI->getBooleanContents(Op.getValueType().isVector(), false) ==
3115             TargetLowering::ZeroOrOneBooleanContent &&
3116         BitWidth > 1)
3117       Known.Zero.setBitsFrom(1);
3118     break;
3119   case ISD::SETCC:
3120   case ISD::STRICT_FSETCC:
3121   case ISD::STRICT_FSETCCS: {
3122     unsigned OpNo = Op->isStrictFPOpcode() ? 1 : 0;
3123     // If we know the result of a setcc has the top bits zero, use this info.
3124     if (TLI->getBooleanContents(Op.getOperand(OpNo).getValueType()) ==
3125             TargetLowering::ZeroOrOneBooleanContent &&
3126         BitWidth > 1)
3127       Known.Zero.setBitsFrom(1);
3128     break;
3129   }
3130   case ISD::SHL:
3131     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3132     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3133     Known = KnownBits::shl(Known, Known2);
3134 
3135     // Minimum shift low bits are known zero.
3136     if (const APInt *ShMinAmt =
3137             getValidMinimumShiftAmountConstant(Op, DemandedElts))
3138       Known.Zero.setLowBits(ShMinAmt->getZExtValue());
3139     break;
3140   case ISD::SRL:
3141     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3142     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3143     Known = KnownBits::lshr(Known, Known2);
3144 
3145     // Minimum shift high bits are known zero.
3146     if (const APInt *ShMinAmt =
3147             getValidMinimumShiftAmountConstant(Op, DemandedElts))
3148       Known.Zero.setHighBits(ShMinAmt->getZExtValue());
3149     break;
3150   case ISD::SRA:
3151     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3152     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3153     Known = KnownBits::ashr(Known, Known2);
3154     // TODO: Add minimum shift high known sign bits.
3155     break;
3156   case ISD::FSHL:
3157   case ISD::FSHR:
3158     if (ConstantSDNode *C = isConstOrConstSplat(Op.getOperand(2), DemandedElts)) {
3159       unsigned Amt = C->getAPIntValue().urem(BitWidth);
3160 
3161       // For fshl, 0-shift returns the 1st arg.
3162       // For fshr, 0-shift returns the 2nd arg.
3163       if (Amt == 0) {
3164         Known = computeKnownBits(Op.getOperand(Opcode == ISD::FSHL ? 0 : 1),
3165                                  DemandedElts, Depth + 1);
3166         break;
3167       }
3168 
3169       // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW)))
3170       // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW))
3171       Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3172       Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3173       if (Opcode == ISD::FSHL) {
3174         Known.One <<= Amt;
3175         Known.Zero <<= Amt;
3176         Known2.One.lshrInPlace(BitWidth - Amt);
3177         Known2.Zero.lshrInPlace(BitWidth - Amt);
3178       } else {
3179         Known.One <<= BitWidth - Amt;
3180         Known.Zero <<= BitWidth - Amt;
3181         Known2.One.lshrInPlace(Amt);
3182         Known2.Zero.lshrInPlace(Amt);
3183       }
3184       Known.One |= Known2.One;
3185       Known.Zero |= Known2.Zero;
3186     }
3187     break;
3188   case ISD::SIGN_EXTEND_INREG: {
3189     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3190     EVT EVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
3191     Known = Known.sextInReg(EVT.getScalarSizeInBits());
3192     break;
3193   }
3194   case ISD::CTTZ:
3195   case ISD::CTTZ_ZERO_UNDEF: {
3196     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3197     // If we have a known 1, its position is our upper bound.
3198     unsigned PossibleTZ = Known2.countMaxTrailingZeros();
3199     unsigned LowBits = Log2_32(PossibleTZ) + 1;
3200     Known.Zero.setBitsFrom(LowBits);
3201     break;
3202   }
3203   case ISD::CTLZ:
3204   case ISD::CTLZ_ZERO_UNDEF: {
3205     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3206     // If we have a known 1, its position is our upper bound.
3207     unsigned PossibleLZ = Known2.countMaxLeadingZeros();
3208     unsigned LowBits = Log2_32(PossibleLZ) + 1;
3209     Known.Zero.setBitsFrom(LowBits);
3210     break;
3211   }
3212   case ISD::CTPOP: {
3213     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3214     // If we know some of the bits are zero, they can't be one.
3215     unsigned PossibleOnes = Known2.countMaxPopulation();
3216     Known.Zero.setBitsFrom(Log2_32(PossibleOnes) + 1);
3217     break;
3218   }
3219   case ISD::PARITY: {
3220     // Parity returns 0 everywhere but the LSB.
3221     Known.Zero.setBitsFrom(1);
3222     break;
3223   }
3224   case ISD::LOAD: {
3225     LoadSDNode *LD = cast<LoadSDNode>(Op);
3226     const Constant *Cst = TLI->getTargetConstantFromLoad(LD);
3227     if (ISD::isNON_EXTLoad(LD) && Cst) {
3228       // Determine any common known bits from the loaded constant pool value.
3229       Type *CstTy = Cst->getType();
3230       if ((NumElts * BitWidth) == CstTy->getPrimitiveSizeInBits()) {
3231         // If its a vector splat, then we can (quickly) reuse the scalar path.
3232         // NOTE: We assume all elements match and none are UNDEF.
3233         if (CstTy->isVectorTy()) {
3234           if (const Constant *Splat = Cst->getSplatValue()) {
3235             Cst = Splat;
3236             CstTy = Cst->getType();
3237           }
3238         }
3239         // TODO - do we need to handle different bitwidths?
3240         if (CstTy->isVectorTy() && BitWidth == CstTy->getScalarSizeInBits()) {
3241           // Iterate across all vector elements finding common known bits.
3242           Known.One.setAllBits();
3243           Known.Zero.setAllBits();
3244           for (unsigned i = 0; i != NumElts; ++i) {
3245             if (!DemandedElts[i])
3246               continue;
3247             if (Constant *Elt = Cst->getAggregateElement(i)) {
3248               if (auto *CInt = dyn_cast<ConstantInt>(Elt)) {
3249                 const APInt &Value = CInt->getValue();
3250                 Known.One &= Value;
3251                 Known.Zero &= ~Value;
3252                 continue;
3253               }
3254               if (auto *CFP = dyn_cast<ConstantFP>(Elt)) {
3255                 APInt Value = CFP->getValueAPF().bitcastToAPInt();
3256                 Known.One &= Value;
3257                 Known.Zero &= ~Value;
3258                 continue;
3259               }
3260             }
3261             Known.One.clearAllBits();
3262             Known.Zero.clearAllBits();
3263             break;
3264           }
3265         } else if (BitWidth == CstTy->getPrimitiveSizeInBits()) {
3266           if (auto *CInt = dyn_cast<ConstantInt>(Cst)) {
3267             Known = KnownBits::makeConstant(CInt->getValue());
3268           } else if (auto *CFP = dyn_cast<ConstantFP>(Cst)) {
3269             Known =
3270                 KnownBits::makeConstant(CFP->getValueAPF().bitcastToAPInt());
3271           }
3272         }
3273       }
3274     } else if (ISD::isZEXTLoad(Op.getNode()) && Op.getResNo() == 0) {
3275       // If this is a ZEXTLoad and we are looking at the loaded value.
3276       EVT VT = LD->getMemoryVT();
3277       unsigned MemBits = VT.getScalarSizeInBits();
3278       Known.Zero.setBitsFrom(MemBits);
3279     } else if (const MDNode *Ranges = LD->getRanges()) {
3280       if (LD->getExtensionType() == ISD::NON_EXTLOAD)
3281         computeKnownBitsFromRangeMetadata(*Ranges, Known);
3282     }
3283     break;
3284   }
3285   case ISD::ZERO_EXTEND_VECTOR_INREG: {
3286     EVT InVT = Op.getOperand(0).getValueType();
3287     APInt InDemandedElts = DemandedElts.zextOrSelf(InVT.getVectorNumElements());
3288     Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1);
3289     Known = Known.zext(BitWidth);
3290     break;
3291   }
3292   case ISD::ZERO_EXTEND: {
3293     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3294     Known = Known.zext(BitWidth);
3295     break;
3296   }
3297   case ISD::SIGN_EXTEND_VECTOR_INREG: {
3298     EVT InVT = Op.getOperand(0).getValueType();
3299     APInt InDemandedElts = DemandedElts.zextOrSelf(InVT.getVectorNumElements());
3300     Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1);
3301     // If the sign bit is known to be zero or one, then sext will extend
3302     // it to the top bits, else it will just zext.
3303     Known = Known.sext(BitWidth);
3304     break;
3305   }
3306   case ISD::SIGN_EXTEND: {
3307     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3308     // If the sign bit is known to be zero or one, then sext will extend
3309     // it to the top bits, else it will just zext.
3310     Known = Known.sext(BitWidth);
3311     break;
3312   }
3313   case ISD::ANY_EXTEND_VECTOR_INREG: {
3314     EVT InVT = Op.getOperand(0).getValueType();
3315     APInt InDemandedElts = DemandedElts.zextOrSelf(InVT.getVectorNumElements());
3316     Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1);
3317     Known = Known.anyext(BitWidth);
3318     break;
3319   }
3320   case ISD::ANY_EXTEND: {
3321     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3322     Known = Known.anyext(BitWidth);
3323     break;
3324   }
3325   case ISD::TRUNCATE: {
3326     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3327     Known = Known.trunc(BitWidth);
3328     break;
3329   }
3330   case ISD::AssertZext: {
3331     EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
3332     APInt InMask = APInt::getLowBitsSet(BitWidth, VT.getSizeInBits());
3333     Known = computeKnownBits(Op.getOperand(0), Depth+1);
3334     Known.Zero |= (~InMask);
3335     Known.One  &= (~Known.Zero);
3336     break;
3337   }
3338   case ISD::AssertAlign: {
3339     unsigned LogOfAlign = Log2(cast<AssertAlignSDNode>(Op)->getAlign());
3340     assert(LogOfAlign != 0);
3341     // If a node is guaranteed to be aligned, set low zero bits accordingly as
3342     // well as clearing one bits.
3343     Known.Zero.setLowBits(LogOfAlign);
3344     Known.One.clearLowBits(LogOfAlign);
3345     break;
3346   }
3347   case ISD::FGETSIGN:
3348     // All bits are zero except the low bit.
3349     Known.Zero.setBitsFrom(1);
3350     break;
3351   case ISD::USUBO:
3352   case ISD::SSUBO:
3353     if (Op.getResNo() == 1) {
3354       // If we know the result of a setcc has the top bits zero, use this info.
3355       if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) ==
3356               TargetLowering::ZeroOrOneBooleanContent &&
3357           BitWidth > 1)
3358         Known.Zero.setBitsFrom(1);
3359       break;
3360     }
3361     LLVM_FALLTHROUGH;
3362   case ISD::SUB:
3363   case ISD::SUBC: {
3364     assert(Op.getResNo() == 0 &&
3365            "We only compute knownbits for the difference here.");
3366 
3367     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3368     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3369     Known = KnownBits::computeForAddSub(/* Add */ false, /* NSW */ false,
3370                                         Known, Known2);
3371     break;
3372   }
3373   case ISD::UADDO:
3374   case ISD::SADDO:
3375   case ISD::ADDCARRY:
3376     if (Op.getResNo() == 1) {
3377       // If we know the result of a setcc has the top bits zero, use this info.
3378       if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) ==
3379               TargetLowering::ZeroOrOneBooleanContent &&
3380           BitWidth > 1)
3381         Known.Zero.setBitsFrom(1);
3382       break;
3383     }
3384     LLVM_FALLTHROUGH;
3385   case ISD::ADD:
3386   case ISD::ADDC:
3387   case ISD::ADDE: {
3388     assert(Op.getResNo() == 0 && "We only compute knownbits for the sum here.");
3389 
3390     // With ADDE and ADDCARRY, a carry bit may be added in.
3391     KnownBits Carry(1);
3392     if (Opcode == ISD::ADDE)
3393       // Can't track carry from glue, set carry to unknown.
3394       Carry.resetAll();
3395     else if (Opcode == ISD::ADDCARRY)
3396       // TODO: Compute known bits for the carry operand. Not sure if it is worth
3397       // the trouble (how often will we find a known carry bit). And I haven't
3398       // tested this very much yet, but something like this might work:
3399       //   Carry = computeKnownBits(Op.getOperand(2), DemandedElts, Depth + 1);
3400       //   Carry = Carry.zextOrTrunc(1, false);
3401       Carry.resetAll();
3402     else
3403       Carry.setAllZero();
3404 
3405     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3406     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3407     Known = KnownBits::computeForAddCarry(Known, Known2, Carry);
3408     break;
3409   }
3410   case ISD::SREM: {
3411     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3412     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3413     Known = KnownBits::srem(Known, Known2);
3414     break;
3415   }
3416   case ISD::UREM: {
3417     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3418     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3419     Known = KnownBits::urem(Known, Known2);
3420     break;
3421   }
3422   case ISD::EXTRACT_ELEMENT: {
3423     Known = computeKnownBits(Op.getOperand(0), Depth+1);
3424     const unsigned Index = Op.getConstantOperandVal(1);
3425     const unsigned EltBitWidth = Op.getValueSizeInBits();
3426 
3427     // Remove low part of known bits mask
3428     Known.Zero = Known.Zero.getHiBits(Known.getBitWidth() - Index * EltBitWidth);
3429     Known.One = Known.One.getHiBits(Known.getBitWidth() - Index * EltBitWidth);
3430 
3431     // Remove high part of known bit mask
3432     Known = Known.trunc(EltBitWidth);
3433     break;
3434   }
3435   case ISD::EXTRACT_VECTOR_ELT: {
3436     SDValue InVec = Op.getOperand(0);
3437     SDValue EltNo = Op.getOperand(1);
3438     EVT VecVT = InVec.getValueType();
3439     // computeKnownBits not yet implemented for scalable vectors.
3440     if (VecVT.isScalableVector())
3441       break;
3442     const unsigned EltBitWidth = VecVT.getScalarSizeInBits();
3443     const unsigned NumSrcElts = VecVT.getVectorNumElements();
3444 
3445     // If BitWidth > EltBitWidth the value is anyext:ed. So we do not know
3446     // anything about the extended bits.
3447     if (BitWidth > EltBitWidth)
3448       Known = Known.trunc(EltBitWidth);
3449 
3450     // If we know the element index, just demand that vector element, else for
3451     // an unknown element index, ignore DemandedElts and demand them all.
3452     APInt DemandedSrcElts = APInt::getAllOnes(NumSrcElts);
3453     auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
3454     if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts))
3455       DemandedSrcElts =
3456           APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue());
3457 
3458     Known = computeKnownBits(InVec, DemandedSrcElts, Depth + 1);
3459     if (BitWidth > EltBitWidth)
3460       Known = Known.anyext(BitWidth);
3461     break;
3462   }
3463   case ISD::INSERT_VECTOR_ELT: {
3464     // If we know the element index, split the demand between the
3465     // source vector and the inserted element, otherwise assume we need
3466     // the original demanded vector elements and the value.
3467     SDValue InVec = Op.getOperand(0);
3468     SDValue InVal = Op.getOperand(1);
3469     SDValue EltNo = Op.getOperand(2);
3470     bool DemandedVal = true;
3471     APInt DemandedVecElts = DemandedElts;
3472     auto *CEltNo = dyn_cast<ConstantSDNode>(EltNo);
3473     if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) {
3474       unsigned EltIdx = CEltNo->getZExtValue();
3475       DemandedVal = !!DemandedElts[EltIdx];
3476       DemandedVecElts.clearBit(EltIdx);
3477     }
3478     Known.One.setAllBits();
3479     Known.Zero.setAllBits();
3480     if (DemandedVal) {
3481       Known2 = computeKnownBits(InVal, Depth + 1);
3482       Known = KnownBits::commonBits(Known, Known2.zextOrTrunc(BitWidth));
3483     }
3484     if (!!DemandedVecElts) {
3485       Known2 = computeKnownBits(InVec, DemandedVecElts, Depth + 1);
3486       Known = KnownBits::commonBits(Known, Known2);
3487     }
3488     break;
3489   }
3490   case ISD::BITREVERSE: {
3491     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3492     Known = Known2.reverseBits();
3493     break;
3494   }
3495   case ISD::BSWAP: {
3496     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3497     Known = Known2.byteSwap();
3498     break;
3499   }
3500   case ISD::ABS: {
3501     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3502     Known = Known2.abs();
3503     break;
3504   }
3505   case ISD::USUBSAT: {
3506     // The result of usubsat will never be larger than the LHS.
3507     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3508     Known.Zero.setHighBits(Known2.countMinLeadingZeros());
3509     break;
3510   }
3511   case ISD::UMIN: {
3512     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3513     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3514     Known = KnownBits::umin(Known, Known2);
3515     break;
3516   }
3517   case ISD::UMAX: {
3518     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3519     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3520     Known = KnownBits::umax(Known, Known2);
3521     break;
3522   }
3523   case ISD::SMIN:
3524   case ISD::SMAX: {
3525     // If we have a clamp pattern, we know that the number of sign bits will be
3526     // the minimum of the clamp min/max range.
3527     bool IsMax = (Opcode == ISD::SMAX);
3528     ConstantSDNode *CstLow = nullptr, *CstHigh = nullptr;
3529     if ((CstLow = isConstOrConstSplat(Op.getOperand(1), DemandedElts)))
3530       if (Op.getOperand(0).getOpcode() == (IsMax ? ISD::SMIN : ISD::SMAX))
3531         CstHigh =
3532             isConstOrConstSplat(Op.getOperand(0).getOperand(1), DemandedElts);
3533     if (CstLow && CstHigh) {
3534       if (!IsMax)
3535         std::swap(CstLow, CstHigh);
3536 
3537       const APInt &ValueLow = CstLow->getAPIntValue();
3538       const APInt &ValueHigh = CstHigh->getAPIntValue();
3539       if (ValueLow.sle(ValueHigh)) {
3540         unsigned LowSignBits = ValueLow.getNumSignBits();
3541         unsigned HighSignBits = ValueHigh.getNumSignBits();
3542         unsigned MinSignBits = std::min(LowSignBits, HighSignBits);
3543         if (ValueLow.isNegative() && ValueHigh.isNegative()) {
3544           Known.One.setHighBits(MinSignBits);
3545           break;
3546         }
3547         if (ValueLow.isNonNegative() && ValueHigh.isNonNegative()) {
3548           Known.Zero.setHighBits(MinSignBits);
3549           break;
3550         }
3551       }
3552     }
3553 
3554     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3555     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3556     if (IsMax)
3557       Known = KnownBits::smax(Known, Known2);
3558     else
3559       Known = KnownBits::smin(Known, Known2);
3560     break;
3561   }
3562   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
3563     if (Op.getResNo() == 1) {
3564       // The boolean result conforms to getBooleanContents.
3565       // If we know the result of a setcc has the top bits zero, use this info.
3566       // We know that we have an integer-based boolean since these operations
3567       // are only available for integer.
3568       if (TLI->getBooleanContents(Op.getValueType().isVector(), false) ==
3569               TargetLowering::ZeroOrOneBooleanContent &&
3570           BitWidth > 1)
3571         Known.Zero.setBitsFrom(1);
3572       break;
3573     }
3574     LLVM_FALLTHROUGH;
3575   case ISD::ATOMIC_CMP_SWAP:
3576   case ISD::ATOMIC_SWAP:
3577   case ISD::ATOMIC_LOAD_ADD:
3578   case ISD::ATOMIC_LOAD_SUB:
3579   case ISD::ATOMIC_LOAD_AND:
3580   case ISD::ATOMIC_LOAD_CLR:
3581   case ISD::ATOMIC_LOAD_OR:
3582   case ISD::ATOMIC_LOAD_XOR:
3583   case ISD::ATOMIC_LOAD_NAND:
3584   case ISD::ATOMIC_LOAD_MIN:
3585   case ISD::ATOMIC_LOAD_MAX:
3586   case ISD::ATOMIC_LOAD_UMIN:
3587   case ISD::ATOMIC_LOAD_UMAX:
3588   case ISD::ATOMIC_LOAD: {
3589     unsigned MemBits =
3590         cast<AtomicSDNode>(Op)->getMemoryVT().getScalarSizeInBits();
3591     // If we are looking at the loaded value.
3592     if (Op.getResNo() == 0) {
3593       if (TLI->getExtendForAtomicOps() == ISD::ZERO_EXTEND)
3594         Known.Zero.setBitsFrom(MemBits);
3595     }
3596     break;
3597   }
3598   case ISD::FrameIndex:
3599   case ISD::TargetFrameIndex:
3600     TLI->computeKnownBitsForFrameIndex(cast<FrameIndexSDNode>(Op)->getIndex(),
3601                                        Known, getMachineFunction());
3602     break;
3603 
3604   default:
3605     if (Opcode < ISD::BUILTIN_OP_END)
3606       break;
3607     LLVM_FALLTHROUGH;
3608   case ISD::INTRINSIC_WO_CHAIN:
3609   case ISD::INTRINSIC_W_CHAIN:
3610   case ISD::INTRINSIC_VOID:
3611     // Allow the target to implement this method for its nodes.
3612     TLI->computeKnownBitsForTargetNode(Op, Known, DemandedElts, *this, Depth);
3613     break;
3614   }
3615 
3616   assert(!Known.hasConflict() && "Bits known to be one AND zero?");
3617   return Known;
3618 }
3619 
3620 SelectionDAG::OverflowKind SelectionDAG::computeOverflowKind(SDValue N0,
3621                                                              SDValue N1) const {
3622   // X + 0 never overflow
3623   if (isNullConstant(N1))
3624     return OFK_Never;
3625 
3626   KnownBits N1Known = computeKnownBits(N1);
3627   if (N1Known.Zero.getBoolValue()) {
3628     KnownBits N0Known = computeKnownBits(N0);
3629 
3630     bool overflow;
3631     (void)N0Known.getMaxValue().uadd_ov(N1Known.getMaxValue(), overflow);
3632     if (!overflow)
3633       return OFK_Never;
3634   }
3635 
3636   // mulhi + 1 never overflow
3637   if (N0.getOpcode() == ISD::UMUL_LOHI && N0.getResNo() == 1 &&
3638       (N1Known.getMaxValue() & 0x01) == N1Known.getMaxValue())
3639     return OFK_Never;
3640 
3641   if (N1.getOpcode() == ISD::UMUL_LOHI && N1.getResNo() == 1) {
3642     KnownBits N0Known = computeKnownBits(N0);
3643 
3644     if ((N0Known.getMaxValue() & 0x01) == N0Known.getMaxValue())
3645       return OFK_Never;
3646   }
3647 
3648   return OFK_Sometime;
3649 }
3650 
3651 bool SelectionDAG::isKnownToBeAPowerOfTwo(SDValue Val) const {
3652   EVT OpVT = Val.getValueType();
3653   unsigned BitWidth = OpVT.getScalarSizeInBits();
3654 
3655   // Is the constant a known power of 2?
3656   if (ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Val))
3657     return Const->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2();
3658 
3659   // A left-shift of a constant one will have exactly one bit set because
3660   // shifting the bit off the end is undefined.
3661   if (Val.getOpcode() == ISD::SHL) {
3662     auto *C = isConstOrConstSplat(Val.getOperand(0));
3663     if (C && C->getAPIntValue() == 1)
3664       return true;
3665   }
3666 
3667   // Similarly, a logical right-shift of a constant sign-bit will have exactly
3668   // one bit set.
3669   if (Val.getOpcode() == ISD::SRL) {
3670     auto *C = isConstOrConstSplat(Val.getOperand(0));
3671     if (C && C->getAPIntValue().isSignMask())
3672       return true;
3673   }
3674 
3675   // Are all operands of a build vector constant powers of two?
3676   if (Val.getOpcode() == ISD::BUILD_VECTOR)
3677     if (llvm::all_of(Val->ops(), [BitWidth](SDValue E) {
3678           if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(E))
3679             return C->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2();
3680           return false;
3681         }))
3682       return true;
3683 
3684   // Is the operand of a splat vector a constant power of two?
3685   if (Val.getOpcode() == ISD::SPLAT_VECTOR)
3686     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val->getOperand(0)))
3687       if (C->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2())
3688         return true;
3689 
3690   // More could be done here, though the above checks are enough
3691   // to handle some common cases.
3692 
3693   // Fall back to computeKnownBits to catch other known cases.
3694   KnownBits Known = computeKnownBits(Val);
3695   return (Known.countMaxPopulation() == 1) && (Known.countMinPopulation() == 1);
3696 }
3697 
3698 unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, unsigned Depth) const {
3699   EVT VT = Op.getValueType();
3700 
3701   // TODO: Assume we don't know anything for now.
3702   if (VT.isScalableVector())
3703     return 1;
3704 
3705   APInt DemandedElts = VT.isVector()
3706                            ? APInt::getAllOnes(VT.getVectorNumElements())
3707                            : APInt(1, 1);
3708   return ComputeNumSignBits(Op, DemandedElts, Depth);
3709 }
3710 
3711 unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, const APInt &DemandedElts,
3712                                           unsigned Depth) const {
3713   EVT VT = Op.getValueType();
3714   assert((VT.isInteger() || VT.isFloatingPoint()) && "Invalid VT!");
3715   unsigned VTBits = VT.getScalarSizeInBits();
3716   unsigned NumElts = DemandedElts.getBitWidth();
3717   unsigned Tmp, Tmp2;
3718   unsigned FirstAnswer = 1;
3719 
3720   if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
3721     const APInt &Val = C->getAPIntValue();
3722     return Val.getNumSignBits();
3723   }
3724 
3725   if (Depth >= MaxRecursionDepth)
3726     return 1;  // Limit search depth.
3727 
3728   if (!DemandedElts || VT.isScalableVector())
3729     return 1;  // No demanded elts, better to assume we don't know anything.
3730 
3731   unsigned Opcode = Op.getOpcode();
3732   switch (Opcode) {
3733   default: break;
3734   case ISD::AssertSext:
3735     Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
3736     return VTBits-Tmp+1;
3737   case ISD::AssertZext:
3738     Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
3739     return VTBits-Tmp;
3740 
3741   case ISD::BUILD_VECTOR:
3742     Tmp = VTBits;
3743     for (unsigned i = 0, e = Op.getNumOperands(); (i < e) && (Tmp > 1); ++i) {
3744       if (!DemandedElts[i])
3745         continue;
3746 
3747       SDValue SrcOp = Op.getOperand(i);
3748       Tmp2 = ComputeNumSignBits(SrcOp, Depth + 1);
3749 
3750       // BUILD_VECTOR can implicitly truncate sources, we must handle this.
3751       if (SrcOp.getValueSizeInBits() != VTBits) {
3752         assert(SrcOp.getValueSizeInBits() > VTBits &&
3753                "Expected BUILD_VECTOR implicit truncation");
3754         unsigned ExtraBits = SrcOp.getValueSizeInBits() - VTBits;
3755         Tmp2 = (Tmp2 > ExtraBits ? Tmp2 - ExtraBits : 1);
3756       }
3757       Tmp = std::min(Tmp, Tmp2);
3758     }
3759     return Tmp;
3760 
3761   case ISD::VECTOR_SHUFFLE: {
3762     // Collect the minimum number of sign bits that are shared by every vector
3763     // element referenced by the shuffle.
3764     APInt DemandedLHS(NumElts, 0), DemandedRHS(NumElts, 0);
3765     const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op);
3766     assert(NumElts == SVN->getMask().size() && "Unexpected vector size");
3767     for (unsigned i = 0; i != NumElts; ++i) {
3768       int M = SVN->getMaskElt(i);
3769       if (!DemandedElts[i])
3770         continue;
3771       // For UNDEF elements, we don't know anything about the common state of
3772       // the shuffle result.
3773       if (M < 0)
3774         return 1;
3775       if ((unsigned)M < NumElts)
3776         DemandedLHS.setBit((unsigned)M % NumElts);
3777       else
3778         DemandedRHS.setBit((unsigned)M % NumElts);
3779     }
3780     Tmp = std::numeric_limits<unsigned>::max();
3781     if (!!DemandedLHS)
3782       Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedLHS, Depth + 1);
3783     if (!!DemandedRHS) {
3784       Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedRHS, Depth + 1);
3785       Tmp = std::min(Tmp, Tmp2);
3786     }
3787     // If we don't know anything, early out and try computeKnownBits fall-back.
3788     if (Tmp == 1)
3789       break;
3790     assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
3791     return Tmp;
3792   }
3793 
3794   case ISD::BITCAST: {
3795     SDValue N0 = Op.getOperand(0);
3796     EVT SrcVT = N0.getValueType();
3797     unsigned SrcBits = SrcVT.getScalarSizeInBits();
3798 
3799     // Ignore bitcasts from unsupported types..
3800     if (!(SrcVT.isInteger() || SrcVT.isFloatingPoint()))
3801       break;
3802 
3803     // Fast handling of 'identity' bitcasts.
3804     if (VTBits == SrcBits)
3805       return ComputeNumSignBits(N0, DemandedElts, Depth + 1);
3806 
3807     bool IsLE = getDataLayout().isLittleEndian();
3808 
3809     // Bitcast 'large element' scalar/vector to 'small element' vector.
3810     if ((SrcBits % VTBits) == 0) {
3811       assert(VT.isVector() && "Expected bitcast to vector");
3812 
3813       unsigned Scale = SrcBits / VTBits;
3814       APInt SrcDemandedElts =
3815           APIntOps::ScaleBitMask(DemandedElts, NumElts / Scale);
3816 
3817       // Fast case - sign splat can be simply split across the small elements.
3818       Tmp = ComputeNumSignBits(N0, SrcDemandedElts, Depth + 1);
3819       if (Tmp == SrcBits)
3820         return VTBits;
3821 
3822       // Slow case - determine how far the sign extends into each sub-element.
3823       Tmp2 = VTBits;
3824       for (unsigned i = 0; i != NumElts; ++i)
3825         if (DemandedElts[i]) {
3826           unsigned SubOffset = i % Scale;
3827           SubOffset = (IsLE ? ((Scale - 1) - SubOffset) : SubOffset);
3828           SubOffset = SubOffset * VTBits;
3829           if (Tmp <= SubOffset)
3830             return 1;
3831           Tmp2 = std::min(Tmp2, Tmp - SubOffset);
3832         }
3833       return Tmp2;
3834     }
3835     break;
3836   }
3837 
3838   case ISD::SIGN_EXTEND:
3839     Tmp = VTBits - Op.getOperand(0).getScalarValueSizeInBits();
3840     return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1) + Tmp;
3841   case ISD::SIGN_EXTEND_INREG:
3842     // Max of the input and what this extends.
3843     Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getScalarSizeInBits();
3844     Tmp = VTBits-Tmp+1;
3845     Tmp2 = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1);
3846     return std::max(Tmp, Tmp2);
3847   case ISD::SIGN_EXTEND_VECTOR_INREG: {
3848     SDValue Src = Op.getOperand(0);
3849     EVT SrcVT = Src.getValueType();
3850     APInt DemandedSrcElts = DemandedElts.zextOrSelf(SrcVT.getVectorNumElements());
3851     Tmp = VTBits - SrcVT.getScalarSizeInBits();
3852     return ComputeNumSignBits(Src, DemandedSrcElts, Depth+1) + Tmp;
3853   }
3854   case ISD::SRA:
3855     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
3856     // SRA X, C -> adds C sign bits.
3857     if (const APInt *ShAmt =
3858             getValidMinimumShiftAmountConstant(Op, DemandedElts))
3859       Tmp = std::min<uint64_t>(Tmp + ShAmt->getZExtValue(), VTBits);
3860     return Tmp;
3861   case ISD::SHL:
3862     if (const APInt *ShAmt =
3863             getValidMaximumShiftAmountConstant(Op, DemandedElts)) {
3864       // shl destroys sign bits, ensure it doesn't shift out all sign bits.
3865       Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
3866       if (ShAmt->ult(Tmp))
3867         return Tmp - ShAmt->getZExtValue();
3868     }
3869     break;
3870   case ISD::AND:
3871   case ISD::OR:
3872   case ISD::XOR:    // NOT is handled here.
3873     // Logical binary ops preserve the number of sign bits at the worst.
3874     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1);
3875     if (Tmp != 1) {
3876       Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth+1);
3877       FirstAnswer = std::min(Tmp, Tmp2);
3878       // We computed what we know about the sign bits as our first
3879       // answer. Now proceed to the generic code that uses
3880       // computeKnownBits, and pick whichever answer is better.
3881     }
3882     break;
3883 
3884   case ISD::SELECT:
3885   case ISD::VSELECT:
3886     Tmp = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth+1);
3887     if (Tmp == 1) return 1;  // Early out.
3888     Tmp2 = ComputeNumSignBits(Op.getOperand(2), DemandedElts, Depth+1);
3889     return std::min(Tmp, Tmp2);
3890   case ISD::SELECT_CC:
3891     Tmp = ComputeNumSignBits(Op.getOperand(2), DemandedElts, Depth+1);
3892     if (Tmp == 1) return 1;  // Early out.
3893     Tmp2 = ComputeNumSignBits(Op.getOperand(3), DemandedElts, Depth+1);
3894     return std::min(Tmp, Tmp2);
3895 
3896   case ISD::SMIN:
3897   case ISD::SMAX: {
3898     // If we have a clamp pattern, we know that the number of sign bits will be
3899     // the minimum of the clamp min/max range.
3900     bool IsMax = (Opcode == ISD::SMAX);
3901     ConstantSDNode *CstLow = nullptr, *CstHigh = nullptr;
3902     if ((CstLow = isConstOrConstSplat(Op.getOperand(1), DemandedElts)))
3903       if (Op.getOperand(0).getOpcode() == (IsMax ? ISD::SMIN : ISD::SMAX))
3904         CstHigh =
3905             isConstOrConstSplat(Op.getOperand(0).getOperand(1), DemandedElts);
3906     if (CstLow && CstHigh) {
3907       if (!IsMax)
3908         std::swap(CstLow, CstHigh);
3909       if (CstLow->getAPIntValue().sle(CstHigh->getAPIntValue())) {
3910         Tmp = CstLow->getAPIntValue().getNumSignBits();
3911         Tmp2 = CstHigh->getAPIntValue().getNumSignBits();
3912         return std::min(Tmp, Tmp2);
3913       }
3914     }
3915 
3916     // Fallback - just get the minimum number of sign bits of the operands.
3917     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
3918     if (Tmp == 1)
3919       return 1;  // Early out.
3920     Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
3921     return std::min(Tmp, Tmp2);
3922   }
3923   case ISD::UMIN:
3924   case ISD::UMAX:
3925     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
3926     if (Tmp == 1)
3927       return 1;  // Early out.
3928     Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
3929     return std::min(Tmp, Tmp2);
3930   case ISD::SADDO:
3931   case ISD::UADDO:
3932   case ISD::SSUBO:
3933   case ISD::USUBO:
3934   case ISD::SMULO:
3935   case ISD::UMULO:
3936     if (Op.getResNo() != 1)
3937       break;
3938     // The boolean result conforms to getBooleanContents.  Fall through.
3939     // If setcc returns 0/-1, all bits are sign bits.
3940     // We know that we have an integer-based boolean since these operations
3941     // are only available for integer.
3942     if (TLI->getBooleanContents(VT.isVector(), false) ==
3943         TargetLowering::ZeroOrNegativeOneBooleanContent)
3944       return VTBits;
3945     break;
3946   case ISD::SETCC:
3947   case ISD::STRICT_FSETCC:
3948   case ISD::STRICT_FSETCCS: {
3949     unsigned OpNo = Op->isStrictFPOpcode() ? 1 : 0;
3950     // If setcc returns 0/-1, all bits are sign bits.
3951     if (TLI->getBooleanContents(Op.getOperand(OpNo).getValueType()) ==
3952         TargetLowering::ZeroOrNegativeOneBooleanContent)
3953       return VTBits;
3954     break;
3955   }
3956   case ISD::ROTL:
3957   case ISD::ROTR:
3958     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
3959 
3960     // If we're rotating an 0/-1 value, then it stays an 0/-1 value.
3961     if (Tmp == VTBits)
3962       return VTBits;
3963 
3964     if (ConstantSDNode *C =
3965             isConstOrConstSplat(Op.getOperand(1), DemandedElts)) {
3966       unsigned RotAmt = C->getAPIntValue().urem(VTBits);
3967 
3968       // Handle rotate right by N like a rotate left by 32-N.
3969       if (Opcode == ISD::ROTR)
3970         RotAmt = (VTBits - RotAmt) % VTBits;
3971 
3972       // If we aren't rotating out all of the known-in sign bits, return the
3973       // number that are left.  This handles rotl(sext(x), 1) for example.
3974       if (Tmp > (RotAmt + 1)) return (Tmp - RotAmt);
3975     }
3976     break;
3977   case ISD::ADD:
3978   case ISD::ADDC:
3979     // Add can have at most one carry bit.  Thus we know that the output
3980     // is, at worst, one more bit than the inputs.
3981     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
3982     if (Tmp == 1) return 1; // Early out.
3983 
3984     // Special case decrementing a value (ADD X, -1):
3985     if (ConstantSDNode *CRHS =
3986             isConstOrConstSplat(Op.getOperand(1), DemandedElts))
3987       if (CRHS->isAllOnes()) {
3988         KnownBits Known =
3989             computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3990 
3991         // If the input is known to be 0 or 1, the output is 0/-1, which is all
3992         // sign bits set.
3993         if ((Known.Zero | 1).isAllOnes())
3994           return VTBits;
3995 
3996         // If we are subtracting one from a positive number, there is no carry
3997         // out of the result.
3998         if (Known.isNonNegative())
3999           return Tmp;
4000       }
4001 
4002     Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
4003     if (Tmp2 == 1) return 1; // Early out.
4004     return std::min(Tmp, Tmp2) - 1;
4005   case ISD::SUB:
4006     Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
4007     if (Tmp2 == 1) return 1; // Early out.
4008 
4009     // Handle NEG.
4010     if (ConstantSDNode *CLHS =
4011             isConstOrConstSplat(Op.getOperand(0), DemandedElts))
4012       if (CLHS->isZero()) {
4013         KnownBits Known =
4014             computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4015         // If the input is known to be 0 or 1, the output is 0/-1, which is all
4016         // sign bits set.
4017         if ((Known.Zero | 1).isAllOnes())
4018           return VTBits;
4019 
4020         // If the input is known to be positive (the sign bit is known clear),
4021         // the output of the NEG has the same number of sign bits as the input.
4022         if (Known.isNonNegative())
4023           return Tmp2;
4024 
4025         // Otherwise, we treat this like a SUB.
4026       }
4027 
4028     // Sub can have at most one carry bit.  Thus we know that the output
4029     // is, at worst, one more bit than the inputs.
4030     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
4031     if (Tmp == 1) return 1; // Early out.
4032     return std::min(Tmp, Tmp2) - 1;
4033   case ISD::MUL: {
4034     // The output of the Mul can be at most twice the valid bits in the inputs.
4035     unsigned SignBitsOp0 = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
4036     if (SignBitsOp0 == 1)
4037       break;
4038     unsigned SignBitsOp1 = ComputeNumSignBits(Op.getOperand(1), Depth + 1);
4039     if (SignBitsOp1 == 1)
4040       break;
4041     unsigned OutValidBits =
4042         (VTBits - SignBitsOp0 + 1) + (VTBits - SignBitsOp1 + 1);
4043     return OutValidBits > VTBits ? 1 : VTBits - OutValidBits + 1;
4044   }
4045   case ISD::SREM:
4046     // The sign bit is the LHS's sign bit, except when the result of the
4047     // remainder is zero. The magnitude of the result should be less than or
4048     // equal to the magnitude of the LHS. Therefore, the result should have
4049     // at least as many sign bits as the left hand side.
4050     return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
4051   case ISD::TRUNCATE: {
4052     // Check if the sign bits of source go down as far as the truncated value.
4053     unsigned NumSrcBits = Op.getOperand(0).getScalarValueSizeInBits();
4054     unsigned NumSrcSignBits = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
4055     if (NumSrcSignBits > (NumSrcBits - VTBits))
4056       return NumSrcSignBits - (NumSrcBits - VTBits);
4057     break;
4058   }
4059   case ISD::EXTRACT_ELEMENT: {
4060     const int KnownSign = ComputeNumSignBits(Op.getOperand(0), Depth+1);
4061     const int BitWidth = Op.getValueSizeInBits();
4062     const int Items = Op.getOperand(0).getValueSizeInBits() / BitWidth;
4063 
4064     // Get reverse index (starting from 1), Op1 value indexes elements from
4065     // little end. Sign starts at big end.
4066     const int rIndex = Items - 1 - Op.getConstantOperandVal(1);
4067 
4068     // If the sign portion ends in our element the subtraction gives correct
4069     // result. Otherwise it gives either negative or > bitwidth result
4070     return std::max(std::min(KnownSign - rIndex * BitWidth, BitWidth), 0);
4071   }
4072   case ISD::INSERT_VECTOR_ELT: {
4073     // If we know the element index, split the demand between the
4074     // source vector and the inserted element, otherwise assume we need
4075     // the original demanded vector elements and the value.
4076     SDValue InVec = Op.getOperand(0);
4077     SDValue InVal = Op.getOperand(1);
4078     SDValue EltNo = Op.getOperand(2);
4079     bool DemandedVal = true;
4080     APInt DemandedVecElts = DemandedElts;
4081     auto *CEltNo = dyn_cast<ConstantSDNode>(EltNo);
4082     if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) {
4083       unsigned EltIdx = CEltNo->getZExtValue();
4084       DemandedVal = !!DemandedElts[EltIdx];
4085       DemandedVecElts.clearBit(EltIdx);
4086     }
4087     Tmp = std::numeric_limits<unsigned>::max();
4088     if (DemandedVal) {
4089       // TODO - handle implicit truncation of inserted elements.
4090       if (InVal.getScalarValueSizeInBits() != VTBits)
4091         break;
4092       Tmp2 = ComputeNumSignBits(InVal, Depth + 1);
4093       Tmp = std::min(Tmp, Tmp2);
4094     }
4095     if (!!DemandedVecElts) {
4096       Tmp2 = ComputeNumSignBits(InVec, DemandedVecElts, Depth + 1);
4097       Tmp = std::min(Tmp, Tmp2);
4098     }
4099     assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
4100     return Tmp;
4101   }
4102   case ISD::EXTRACT_VECTOR_ELT: {
4103     SDValue InVec = Op.getOperand(0);
4104     SDValue EltNo = Op.getOperand(1);
4105     EVT VecVT = InVec.getValueType();
4106     // ComputeNumSignBits not yet implemented for scalable vectors.
4107     if (VecVT.isScalableVector())
4108       break;
4109     const unsigned BitWidth = Op.getValueSizeInBits();
4110     const unsigned EltBitWidth = Op.getOperand(0).getScalarValueSizeInBits();
4111     const unsigned NumSrcElts = VecVT.getVectorNumElements();
4112 
4113     // If BitWidth > EltBitWidth the value is anyext:ed, and we do not know
4114     // anything about sign bits. But if the sizes match we can derive knowledge
4115     // about sign bits from the vector operand.
4116     if (BitWidth != EltBitWidth)
4117       break;
4118 
4119     // If we know the element index, just demand that vector element, else for
4120     // an unknown element index, ignore DemandedElts and demand them all.
4121     APInt DemandedSrcElts = APInt::getAllOnes(NumSrcElts);
4122     auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
4123     if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts))
4124       DemandedSrcElts =
4125           APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue());
4126 
4127     return ComputeNumSignBits(InVec, DemandedSrcElts, Depth + 1);
4128   }
4129   case ISD::EXTRACT_SUBVECTOR: {
4130     // Offset the demanded elts by the subvector index.
4131     SDValue Src = Op.getOperand(0);
4132     // Bail until we can represent demanded elements for scalable vectors.
4133     if (Src.getValueType().isScalableVector())
4134       break;
4135     uint64_t Idx = Op.getConstantOperandVal(1);
4136     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
4137     APInt DemandedSrcElts = DemandedElts.zextOrSelf(NumSrcElts).shl(Idx);
4138     return ComputeNumSignBits(Src, DemandedSrcElts, Depth + 1);
4139   }
4140   case ISD::CONCAT_VECTORS: {
4141     // Determine the minimum number of sign bits across all demanded
4142     // elts of the input vectors. Early out if the result is already 1.
4143     Tmp = std::numeric_limits<unsigned>::max();
4144     EVT SubVectorVT = Op.getOperand(0).getValueType();
4145     unsigned NumSubVectorElts = SubVectorVT.getVectorNumElements();
4146     unsigned NumSubVectors = Op.getNumOperands();
4147     for (unsigned i = 0; (i < NumSubVectors) && (Tmp > 1); ++i) {
4148       APInt DemandedSub =
4149           DemandedElts.extractBits(NumSubVectorElts, i * NumSubVectorElts);
4150       if (!DemandedSub)
4151         continue;
4152       Tmp2 = ComputeNumSignBits(Op.getOperand(i), DemandedSub, Depth + 1);
4153       Tmp = std::min(Tmp, Tmp2);
4154     }
4155     assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
4156     return Tmp;
4157   }
4158   case ISD::INSERT_SUBVECTOR: {
4159     // Demand any elements from the subvector and the remainder from the src its
4160     // inserted into.
4161     SDValue Src = Op.getOperand(0);
4162     SDValue Sub = Op.getOperand(1);
4163     uint64_t Idx = Op.getConstantOperandVal(2);
4164     unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
4165     APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
4166     APInt DemandedSrcElts = DemandedElts;
4167     DemandedSrcElts.insertBits(APInt::getZero(NumSubElts), Idx);
4168 
4169     Tmp = std::numeric_limits<unsigned>::max();
4170     if (!!DemandedSubElts) {
4171       Tmp = ComputeNumSignBits(Sub, DemandedSubElts, Depth + 1);
4172       if (Tmp == 1)
4173         return 1; // early-out
4174     }
4175     if (!!DemandedSrcElts) {
4176       Tmp2 = ComputeNumSignBits(Src, DemandedSrcElts, Depth + 1);
4177       Tmp = std::min(Tmp, Tmp2);
4178     }
4179     assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
4180     return Tmp;
4181   }
4182   case ISD::ATOMIC_CMP_SWAP:
4183   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
4184   case ISD::ATOMIC_SWAP:
4185   case ISD::ATOMIC_LOAD_ADD:
4186   case ISD::ATOMIC_LOAD_SUB:
4187   case ISD::ATOMIC_LOAD_AND:
4188   case ISD::ATOMIC_LOAD_CLR:
4189   case ISD::ATOMIC_LOAD_OR:
4190   case ISD::ATOMIC_LOAD_XOR:
4191   case ISD::ATOMIC_LOAD_NAND:
4192   case ISD::ATOMIC_LOAD_MIN:
4193   case ISD::ATOMIC_LOAD_MAX:
4194   case ISD::ATOMIC_LOAD_UMIN:
4195   case ISD::ATOMIC_LOAD_UMAX:
4196   case ISD::ATOMIC_LOAD: {
4197     Tmp = cast<AtomicSDNode>(Op)->getMemoryVT().getScalarSizeInBits();
4198     // If we are looking at the loaded value.
4199     if (Op.getResNo() == 0) {
4200       if (Tmp == VTBits)
4201         return 1; // early-out
4202       if (TLI->getExtendForAtomicOps() == ISD::SIGN_EXTEND)
4203         return VTBits - Tmp + 1;
4204       if (TLI->getExtendForAtomicOps() == ISD::ZERO_EXTEND)
4205         return VTBits - Tmp;
4206     }
4207     break;
4208   }
4209   }
4210 
4211   // If we are looking at the loaded value of the SDNode.
4212   if (Op.getResNo() == 0) {
4213     // Handle LOADX separately here. EXTLOAD case will fallthrough.
4214     if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
4215       unsigned ExtType = LD->getExtensionType();
4216       switch (ExtType) {
4217       default: break;
4218       case ISD::SEXTLOAD: // e.g. i16->i32 = '17' bits known.
4219         Tmp = LD->getMemoryVT().getScalarSizeInBits();
4220         return VTBits - Tmp + 1;
4221       case ISD::ZEXTLOAD: // e.g. i16->i32 = '16' bits known.
4222         Tmp = LD->getMemoryVT().getScalarSizeInBits();
4223         return VTBits - Tmp;
4224       case ISD::NON_EXTLOAD:
4225         if (const Constant *Cst = TLI->getTargetConstantFromLoad(LD)) {
4226           // We only need to handle vectors - computeKnownBits should handle
4227           // scalar cases.
4228           Type *CstTy = Cst->getType();
4229           if (CstTy->isVectorTy() &&
4230               (NumElts * VTBits) == CstTy->getPrimitiveSizeInBits()) {
4231             Tmp = VTBits;
4232             for (unsigned i = 0; i != NumElts; ++i) {
4233               if (!DemandedElts[i])
4234                 continue;
4235               if (Constant *Elt = Cst->getAggregateElement(i)) {
4236                 if (auto *CInt = dyn_cast<ConstantInt>(Elt)) {
4237                   const APInt &Value = CInt->getValue();
4238                   Tmp = std::min(Tmp, Value.getNumSignBits());
4239                   continue;
4240                 }
4241                 if (auto *CFP = dyn_cast<ConstantFP>(Elt)) {
4242                   APInt Value = CFP->getValueAPF().bitcastToAPInt();
4243                   Tmp = std::min(Tmp, Value.getNumSignBits());
4244                   continue;
4245                 }
4246               }
4247               // Unknown type. Conservatively assume no bits match sign bit.
4248               return 1;
4249             }
4250             return Tmp;
4251           }
4252         }
4253         break;
4254       }
4255     }
4256   }
4257 
4258   // Allow the target to implement this method for its nodes.
4259   if (Opcode >= ISD::BUILTIN_OP_END ||
4260       Opcode == ISD::INTRINSIC_WO_CHAIN ||
4261       Opcode == ISD::INTRINSIC_W_CHAIN ||
4262       Opcode == ISD::INTRINSIC_VOID) {
4263     unsigned NumBits =
4264         TLI->ComputeNumSignBitsForTargetNode(Op, DemandedElts, *this, Depth);
4265     if (NumBits > 1)
4266       FirstAnswer = std::max(FirstAnswer, NumBits);
4267   }
4268 
4269   // Finally, if we can prove that the top bits of the result are 0's or 1's,
4270   // use this information.
4271   KnownBits Known = computeKnownBits(Op, DemandedElts, Depth);
4272 
4273   APInt Mask;
4274   if (Known.isNonNegative()) {        // sign bit is 0
4275     Mask = Known.Zero;
4276   } else if (Known.isNegative()) {  // sign bit is 1;
4277     Mask = Known.One;
4278   } else {
4279     // Nothing known.
4280     return FirstAnswer;
4281   }
4282 
4283   // Okay, we know that the sign bit in Mask is set.  Use CLO to determine
4284   // the number of identical bits in the top of the input value.
4285   Mask <<= Mask.getBitWidth()-VTBits;
4286   return std::max(FirstAnswer, Mask.countLeadingOnes());
4287 }
4288 
4289 unsigned SelectionDAG::ComputeMinSignedBits(SDValue Op, unsigned Depth) const {
4290   unsigned SignBits = ComputeNumSignBits(Op, Depth);
4291   return Op.getScalarValueSizeInBits() - SignBits + 1;
4292 }
4293 
4294 unsigned SelectionDAG::ComputeMinSignedBits(SDValue Op,
4295                                             const APInt &DemandedElts,
4296                                             unsigned Depth) const {
4297   unsigned SignBits = ComputeNumSignBits(Op, DemandedElts, Depth);
4298   return Op.getScalarValueSizeInBits() - SignBits + 1;
4299 }
4300 
4301 bool SelectionDAG::isGuaranteedNotToBeUndefOrPoison(SDValue Op, bool PoisonOnly,
4302                                                     unsigned Depth) const {
4303   // Early out for FREEZE.
4304   if (Op.getOpcode() == ISD::FREEZE)
4305     return true;
4306 
4307   // TODO: Assume we don't know anything for now.
4308   EVT VT = Op.getValueType();
4309   if (VT.isScalableVector())
4310     return false;
4311 
4312   APInt DemandedElts = VT.isVector()
4313                            ? APInt::getAllOnes(VT.getVectorNumElements())
4314                            : APInt(1, 1);
4315   return isGuaranteedNotToBeUndefOrPoison(Op, DemandedElts, PoisonOnly, Depth);
4316 }
4317 
4318 bool SelectionDAG::isGuaranteedNotToBeUndefOrPoison(SDValue Op,
4319                                                     const APInt &DemandedElts,
4320                                                     bool PoisonOnly,
4321                                                     unsigned Depth) const {
4322   unsigned Opcode = Op.getOpcode();
4323 
4324   // Early out for FREEZE.
4325   if (Opcode == ISD::FREEZE)
4326     return true;
4327 
4328   if (Depth >= MaxRecursionDepth)
4329     return false; // Limit search depth.
4330 
4331   if (isIntOrFPConstant(Op))
4332     return true;
4333 
4334   switch (Opcode) {
4335   case ISD::UNDEF:
4336     return PoisonOnly;
4337 
4338   case ISD::BUILD_VECTOR:
4339     // NOTE: BUILD_VECTOR has implicit truncation of wider scalar elements -
4340     // this shouldn't affect the result.
4341     for (unsigned i = 0, e = Op.getNumOperands(); i < e; ++i) {
4342       if (!DemandedElts[i])
4343         continue;
4344       if (!isGuaranteedNotToBeUndefOrPoison(Op.getOperand(i), PoisonOnly,
4345                                             Depth + 1))
4346         return false;
4347     }
4348     return true;
4349 
4350   // TODO: Search for noundef attributes from library functions.
4351 
4352   // TODO: Pointers dereferenced by ISD::LOAD/STORE ops are noundef.
4353 
4354   default:
4355     // Allow the target to implement this method for its nodes.
4356     if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::INTRINSIC_WO_CHAIN ||
4357         Opcode == ISD::INTRINSIC_W_CHAIN || Opcode == ISD::INTRINSIC_VOID)
4358       return TLI->isGuaranteedNotToBeUndefOrPoisonForTargetNode(
4359           Op, DemandedElts, *this, PoisonOnly, Depth);
4360     break;
4361   }
4362 
4363   return false;
4364 }
4365 
4366 bool SelectionDAG::isBaseWithConstantOffset(SDValue Op) const {
4367   if ((Op.getOpcode() != ISD::ADD && Op.getOpcode() != ISD::OR) ||
4368       !isa<ConstantSDNode>(Op.getOperand(1)))
4369     return false;
4370 
4371   if (Op.getOpcode() == ISD::OR &&
4372       !MaskedValueIsZero(Op.getOperand(0), Op.getConstantOperandAPInt(1)))
4373     return false;
4374 
4375   return true;
4376 }
4377 
4378 bool SelectionDAG::isKnownNeverNaN(SDValue Op, bool SNaN, unsigned Depth) const {
4379   // If we're told that NaNs won't happen, assume they won't.
4380   if (getTarget().Options.NoNaNsFPMath || Op->getFlags().hasNoNaNs())
4381     return true;
4382 
4383   if (Depth >= MaxRecursionDepth)
4384     return false; // Limit search depth.
4385 
4386   // TODO: Handle vectors.
4387   // If the value is a constant, we can obviously see if it is a NaN or not.
4388   if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) {
4389     return !C->getValueAPF().isNaN() ||
4390            (SNaN && !C->getValueAPF().isSignaling());
4391   }
4392 
4393   unsigned Opcode = Op.getOpcode();
4394   switch (Opcode) {
4395   case ISD::FADD:
4396   case ISD::FSUB:
4397   case ISD::FMUL:
4398   case ISD::FDIV:
4399   case ISD::FREM:
4400   case ISD::FSIN:
4401   case ISD::FCOS: {
4402     if (SNaN)
4403       return true;
4404     // TODO: Need isKnownNeverInfinity
4405     return false;
4406   }
4407   case ISD::FCANONICALIZE:
4408   case ISD::FEXP:
4409   case ISD::FEXP2:
4410   case ISD::FTRUNC:
4411   case ISD::FFLOOR:
4412   case ISD::FCEIL:
4413   case ISD::FROUND:
4414   case ISD::FROUNDEVEN:
4415   case ISD::FRINT:
4416   case ISD::FNEARBYINT: {
4417     if (SNaN)
4418       return true;
4419     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
4420   }
4421   case ISD::FABS:
4422   case ISD::FNEG:
4423   case ISD::FCOPYSIGN: {
4424     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
4425   }
4426   case ISD::SELECT:
4427     return isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1) &&
4428            isKnownNeverNaN(Op.getOperand(2), SNaN, Depth + 1);
4429   case ISD::FP_EXTEND:
4430   case ISD::FP_ROUND: {
4431     if (SNaN)
4432       return true;
4433     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
4434   }
4435   case ISD::SINT_TO_FP:
4436   case ISD::UINT_TO_FP:
4437     return true;
4438   case ISD::FMA:
4439   case ISD::FMAD: {
4440     if (SNaN)
4441       return true;
4442     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) &&
4443            isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1) &&
4444            isKnownNeverNaN(Op.getOperand(2), SNaN, Depth + 1);
4445   }
4446   case ISD::FSQRT: // Need is known positive
4447   case ISD::FLOG:
4448   case ISD::FLOG2:
4449   case ISD::FLOG10:
4450   case ISD::FPOWI:
4451   case ISD::FPOW: {
4452     if (SNaN)
4453       return true;
4454     // TODO: Refine on operand
4455     return false;
4456   }
4457   case ISD::FMINNUM:
4458   case ISD::FMAXNUM: {
4459     // Only one needs to be known not-nan, since it will be returned if the
4460     // other ends up being one.
4461     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) ||
4462            isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1);
4463   }
4464   case ISD::FMINNUM_IEEE:
4465   case ISD::FMAXNUM_IEEE: {
4466     if (SNaN)
4467       return true;
4468     // This can return a NaN if either operand is an sNaN, or if both operands
4469     // are NaN.
4470     return (isKnownNeverNaN(Op.getOperand(0), false, Depth + 1) &&
4471             isKnownNeverSNaN(Op.getOperand(1), Depth + 1)) ||
4472            (isKnownNeverNaN(Op.getOperand(1), false, Depth + 1) &&
4473             isKnownNeverSNaN(Op.getOperand(0), Depth + 1));
4474   }
4475   case ISD::FMINIMUM:
4476   case ISD::FMAXIMUM: {
4477     // TODO: Does this quiet or return the origina NaN as-is?
4478     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) &&
4479            isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1);
4480   }
4481   case ISD::EXTRACT_VECTOR_ELT: {
4482     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
4483   }
4484   default:
4485     if (Opcode >= ISD::BUILTIN_OP_END ||
4486         Opcode == ISD::INTRINSIC_WO_CHAIN ||
4487         Opcode == ISD::INTRINSIC_W_CHAIN ||
4488         Opcode == ISD::INTRINSIC_VOID) {
4489       return TLI->isKnownNeverNaNForTargetNode(Op, *this, SNaN, Depth);
4490     }
4491 
4492     return false;
4493   }
4494 }
4495 
4496 bool SelectionDAG::isKnownNeverZeroFloat(SDValue Op) const {
4497   assert(Op.getValueType().isFloatingPoint() &&
4498          "Floating point type expected");
4499 
4500   // If the value is a constant, we can obviously see if it is a zero or not.
4501   // TODO: Add BuildVector support.
4502   if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op))
4503     return !C->isZero();
4504   return false;
4505 }
4506 
4507 bool SelectionDAG::isKnownNeverZero(SDValue Op) const {
4508   assert(!Op.getValueType().isFloatingPoint() &&
4509          "Floating point types unsupported - use isKnownNeverZeroFloat");
4510 
4511   // If the value is a constant, we can obviously see if it is a zero or not.
4512   if (ISD::matchUnaryPredicate(Op,
4513                                [](ConstantSDNode *C) { return !C->isZero(); }))
4514     return true;
4515 
4516   // TODO: Recognize more cases here.
4517   switch (Op.getOpcode()) {
4518   default: break;
4519   case ISD::OR:
4520     if (isKnownNeverZero(Op.getOperand(1)) ||
4521         isKnownNeverZero(Op.getOperand(0)))
4522       return true;
4523     break;
4524   }
4525 
4526   return false;
4527 }
4528 
4529 bool SelectionDAG::isEqualTo(SDValue A, SDValue B) const {
4530   // Check the obvious case.
4531   if (A == B) return true;
4532 
4533   // For for negative and positive zero.
4534   if (const ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A))
4535     if (const ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B))
4536       if (CA->isZero() && CB->isZero()) return true;
4537 
4538   // Otherwise they may not be equal.
4539   return false;
4540 }
4541 
4542 // FIXME: unify with llvm::haveNoCommonBitsSet.
4543 // FIXME: could also handle masked merge pattern (X & ~M) op (Y & M)
4544 bool SelectionDAG::haveNoCommonBitsSet(SDValue A, SDValue B) const {
4545   assert(A.getValueType() == B.getValueType() &&
4546          "Values must have the same type");
4547   return KnownBits::haveNoCommonBitsSet(computeKnownBits(A),
4548                                         computeKnownBits(B));
4549 }
4550 
4551 static SDValue FoldSTEP_VECTOR(const SDLoc &DL, EVT VT, SDValue Step,
4552                                SelectionDAG &DAG) {
4553   if (cast<ConstantSDNode>(Step)->isZero())
4554     return DAG.getConstant(0, DL, VT);
4555 
4556   return SDValue();
4557 }
4558 
4559 static SDValue FoldBUILD_VECTOR(const SDLoc &DL, EVT VT,
4560                                 ArrayRef<SDValue> Ops,
4561                                 SelectionDAG &DAG) {
4562   int NumOps = Ops.size();
4563   assert(NumOps != 0 && "Can't build an empty vector!");
4564   assert(!VT.isScalableVector() &&
4565          "BUILD_VECTOR cannot be used with scalable types");
4566   assert(VT.getVectorNumElements() == (unsigned)NumOps &&
4567          "Incorrect element count in BUILD_VECTOR!");
4568 
4569   // BUILD_VECTOR of UNDEFs is UNDEF.
4570   if (llvm::all_of(Ops, [](SDValue Op) { return Op.isUndef(); }))
4571     return DAG.getUNDEF(VT);
4572 
4573   // BUILD_VECTOR of seq extract/insert from the same vector + type is Identity.
4574   SDValue IdentitySrc;
4575   bool IsIdentity = true;
4576   for (int i = 0; i != NumOps; ++i) {
4577     if (Ops[i].getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
4578         Ops[i].getOperand(0).getValueType() != VT ||
4579         (IdentitySrc && Ops[i].getOperand(0) != IdentitySrc) ||
4580         !isa<ConstantSDNode>(Ops[i].getOperand(1)) ||
4581         cast<ConstantSDNode>(Ops[i].getOperand(1))->getAPIntValue() != i) {
4582       IsIdentity = false;
4583       break;
4584     }
4585     IdentitySrc = Ops[i].getOperand(0);
4586   }
4587   if (IsIdentity)
4588     return IdentitySrc;
4589 
4590   return SDValue();
4591 }
4592 
4593 /// Try to simplify vector concatenation to an input value, undef, or build
4594 /// vector.
4595 static SDValue foldCONCAT_VECTORS(const SDLoc &DL, EVT VT,
4596                                   ArrayRef<SDValue> Ops,
4597                                   SelectionDAG &DAG) {
4598   assert(!Ops.empty() && "Can't concatenate an empty list of vectors!");
4599   assert(llvm::all_of(Ops,
4600                       [Ops](SDValue Op) {
4601                         return Ops[0].getValueType() == Op.getValueType();
4602                       }) &&
4603          "Concatenation of vectors with inconsistent value types!");
4604   assert((Ops[0].getValueType().getVectorElementCount() * Ops.size()) ==
4605              VT.getVectorElementCount() &&
4606          "Incorrect element count in vector concatenation!");
4607 
4608   if (Ops.size() == 1)
4609     return Ops[0];
4610 
4611   // Concat of UNDEFs is UNDEF.
4612   if (llvm::all_of(Ops, [](SDValue Op) { return Op.isUndef(); }))
4613     return DAG.getUNDEF(VT);
4614 
4615   // Scan the operands and look for extract operations from a single source
4616   // that correspond to insertion at the same location via this concatenation:
4617   // concat (extract X, 0*subvec_elts), (extract X, 1*subvec_elts), ...
4618   SDValue IdentitySrc;
4619   bool IsIdentity = true;
4620   for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
4621     SDValue Op = Ops[i];
4622     unsigned IdentityIndex = i * Op.getValueType().getVectorMinNumElements();
4623     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
4624         Op.getOperand(0).getValueType() != VT ||
4625         (IdentitySrc && Op.getOperand(0) != IdentitySrc) ||
4626         Op.getConstantOperandVal(1) != IdentityIndex) {
4627       IsIdentity = false;
4628       break;
4629     }
4630     assert((!IdentitySrc || IdentitySrc == Op.getOperand(0)) &&
4631            "Unexpected identity source vector for concat of extracts");
4632     IdentitySrc = Op.getOperand(0);
4633   }
4634   if (IsIdentity) {
4635     assert(IdentitySrc && "Failed to set source vector of extracts");
4636     return IdentitySrc;
4637   }
4638 
4639   // The code below this point is only designed to work for fixed width
4640   // vectors, so we bail out for now.
4641   if (VT.isScalableVector())
4642     return SDValue();
4643 
4644   // A CONCAT_VECTOR with all UNDEF/BUILD_VECTOR operands can be
4645   // simplified to one big BUILD_VECTOR.
4646   // FIXME: Add support for SCALAR_TO_VECTOR as well.
4647   EVT SVT = VT.getScalarType();
4648   SmallVector<SDValue, 16> Elts;
4649   for (SDValue Op : Ops) {
4650     EVT OpVT = Op.getValueType();
4651     if (Op.isUndef())
4652       Elts.append(OpVT.getVectorNumElements(), DAG.getUNDEF(SVT));
4653     else if (Op.getOpcode() == ISD::BUILD_VECTOR)
4654       Elts.append(Op->op_begin(), Op->op_end());
4655     else
4656       return SDValue();
4657   }
4658 
4659   // BUILD_VECTOR requires all inputs to be of the same type, find the
4660   // maximum type and extend them all.
4661   for (SDValue Op : Elts)
4662     SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
4663 
4664   if (SVT.bitsGT(VT.getScalarType())) {
4665     for (SDValue &Op : Elts) {
4666       if (Op.isUndef())
4667         Op = DAG.getUNDEF(SVT);
4668       else
4669         Op = DAG.getTargetLoweringInfo().isZExtFree(Op.getValueType(), SVT)
4670                  ? DAG.getZExtOrTrunc(Op, DL, SVT)
4671                  : DAG.getSExtOrTrunc(Op, DL, SVT);
4672     }
4673   }
4674 
4675   SDValue V = DAG.getBuildVector(VT, DL, Elts);
4676   NewSDValueDbgMsg(V, "New node fold concat vectors: ", &DAG);
4677   return V;
4678 }
4679 
4680 /// Gets or creates the specified node.
4681 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT) {
4682   FoldingSetNodeID ID;
4683   AddNodeIDNode(ID, Opcode, getVTList(VT), None);
4684   void *IP = nullptr;
4685   if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
4686     return SDValue(E, 0);
4687 
4688   auto *N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(),
4689                               getVTList(VT));
4690   CSEMap.InsertNode(N, IP);
4691 
4692   InsertNode(N);
4693   SDValue V = SDValue(N, 0);
4694   NewSDValueDbgMsg(V, "Creating new node: ", this);
4695   return V;
4696 }
4697 
4698 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
4699                               SDValue Operand) {
4700   SDNodeFlags Flags;
4701   if (Inserter)
4702     Flags = Inserter->getFlags();
4703   return getNode(Opcode, DL, VT, Operand, Flags);
4704 }
4705 
4706 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
4707                               SDValue Operand, const SDNodeFlags Flags) {
4708   assert(Operand.getOpcode() != ISD::DELETED_NODE &&
4709          "Operand is DELETED_NODE!");
4710   // Constant fold unary operations with an integer constant operand. Even
4711   // opaque constant will be folded, because the folding of unary operations
4712   // doesn't create new constants with different values. Nevertheless, the
4713   // opaque flag is preserved during folding to prevent future folding with
4714   // other constants.
4715   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Operand)) {
4716     const APInt &Val = C->getAPIntValue();
4717     switch (Opcode) {
4718     default: break;
4719     case ISD::SIGN_EXTEND:
4720       return getConstant(Val.sextOrTrunc(VT.getSizeInBits()), DL, VT,
4721                          C->isTargetOpcode(), C->isOpaque());
4722     case ISD::TRUNCATE:
4723       if (C->isOpaque())
4724         break;
4725       LLVM_FALLTHROUGH;
4726     case ISD::ZERO_EXTEND:
4727       return getConstant(Val.zextOrTrunc(VT.getSizeInBits()), DL, VT,
4728                          C->isTargetOpcode(), C->isOpaque());
4729     case ISD::ANY_EXTEND:
4730       // Some targets like RISCV prefer to sign extend some types.
4731       if (TLI->isSExtCheaperThanZExt(Operand.getValueType(), VT))
4732         return getConstant(Val.sextOrTrunc(VT.getSizeInBits()), DL, VT,
4733                            C->isTargetOpcode(), C->isOpaque());
4734       return getConstant(Val.zextOrTrunc(VT.getSizeInBits()), DL, VT,
4735                          C->isTargetOpcode(), C->isOpaque());
4736     case ISD::UINT_TO_FP:
4737     case ISD::SINT_TO_FP: {
4738       APFloat apf(EVTToAPFloatSemantics(VT),
4739                   APInt::getZero(VT.getSizeInBits()));
4740       (void)apf.convertFromAPInt(Val,
4741                                  Opcode==ISD::SINT_TO_FP,
4742                                  APFloat::rmNearestTiesToEven);
4743       return getConstantFP(apf, DL, VT);
4744     }
4745     case ISD::BITCAST:
4746       if (VT == MVT::f16 && C->getValueType(0) == MVT::i16)
4747         return getConstantFP(APFloat(APFloat::IEEEhalf(), Val), DL, VT);
4748       if (VT == MVT::f32 && C->getValueType(0) == MVT::i32)
4749         return getConstantFP(APFloat(APFloat::IEEEsingle(), Val), DL, VT);
4750       if (VT == MVT::f64 && C->getValueType(0) == MVT::i64)
4751         return getConstantFP(APFloat(APFloat::IEEEdouble(), Val), DL, VT);
4752       if (VT == MVT::f128 && C->getValueType(0) == MVT::i128)
4753         return getConstantFP(APFloat(APFloat::IEEEquad(), Val), DL, VT);
4754       break;
4755     case ISD::ABS:
4756       return getConstant(Val.abs(), DL, VT, C->isTargetOpcode(),
4757                          C->isOpaque());
4758     case ISD::BITREVERSE:
4759       return getConstant(Val.reverseBits(), DL, VT, C->isTargetOpcode(),
4760                          C->isOpaque());
4761     case ISD::BSWAP:
4762       return getConstant(Val.byteSwap(), DL, VT, C->isTargetOpcode(),
4763                          C->isOpaque());
4764     case ISD::CTPOP:
4765       return getConstant(Val.countPopulation(), DL, VT, C->isTargetOpcode(),
4766                          C->isOpaque());
4767     case ISD::CTLZ:
4768     case ISD::CTLZ_ZERO_UNDEF:
4769       return getConstant(Val.countLeadingZeros(), DL, VT, C->isTargetOpcode(),
4770                          C->isOpaque());
4771     case ISD::CTTZ:
4772     case ISD::CTTZ_ZERO_UNDEF:
4773       return getConstant(Val.countTrailingZeros(), DL, VT, C->isTargetOpcode(),
4774                          C->isOpaque());
4775     case ISD::FP16_TO_FP: {
4776       bool Ignored;
4777       APFloat FPV(APFloat::IEEEhalf(),
4778                   (Val.getBitWidth() == 16) ? Val : Val.trunc(16));
4779 
4780       // This can return overflow, underflow, or inexact; we don't care.
4781       // FIXME need to be more flexible about rounding mode.
4782       (void)FPV.convert(EVTToAPFloatSemantics(VT),
4783                         APFloat::rmNearestTiesToEven, &Ignored);
4784       return getConstantFP(FPV, DL, VT);
4785     }
4786     case ISD::STEP_VECTOR: {
4787       if (SDValue V = FoldSTEP_VECTOR(DL, VT, Operand, *this))
4788         return V;
4789       break;
4790     }
4791     }
4792   }
4793 
4794   // Constant fold unary operations with a floating point constant operand.
4795   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Operand)) {
4796     APFloat V = C->getValueAPF();    // make copy
4797     switch (Opcode) {
4798     case ISD::FNEG:
4799       V.changeSign();
4800       return getConstantFP(V, DL, VT);
4801     case ISD::FABS:
4802       V.clearSign();
4803       return getConstantFP(V, DL, VT);
4804     case ISD::FCEIL: {
4805       APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardPositive);
4806       if (fs == APFloat::opOK || fs == APFloat::opInexact)
4807         return getConstantFP(V, DL, VT);
4808       break;
4809     }
4810     case ISD::FTRUNC: {
4811       APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardZero);
4812       if (fs == APFloat::opOK || fs == APFloat::opInexact)
4813         return getConstantFP(V, DL, VT);
4814       break;
4815     }
4816     case ISD::FFLOOR: {
4817       APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardNegative);
4818       if (fs == APFloat::opOK || fs == APFloat::opInexact)
4819         return getConstantFP(V, DL, VT);
4820       break;
4821     }
4822     case ISD::FP_EXTEND: {
4823       bool ignored;
4824       // This can return overflow, underflow, or inexact; we don't care.
4825       // FIXME need to be more flexible about rounding mode.
4826       (void)V.convert(EVTToAPFloatSemantics(VT),
4827                       APFloat::rmNearestTiesToEven, &ignored);
4828       return getConstantFP(V, DL, VT);
4829     }
4830     case ISD::FP_TO_SINT:
4831     case ISD::FP_TO_UINT: {
4832       bool ignored;
4833       APSInt IntVal(VT.getSizeInBits(), Opcode == ISD::FP_TO_UINT);
4834       // FIXME need to be more flexible about rounding mode.
4835       APFloat::opStatus s =
4836           V.convertToInteger(IntVal, APFloat::rmTowardZero, &ignored);
4837       if (s == APFloat::opInvalidOp) // inexact is OK, in fact usual
4838         break;
4839       return getConstant(IntVal, DL, VT);
4840     }
4841     case ISD::BITCAST:
4842       if (VT == MVT::i16 && C->getValueType(0) == MVT::f16)
4843         return getConstant((uint16_t)V.bitcastToAPInt().getZExtValue(), DL, VT);
4844       if (VT == MVT::i16 && C->getValueType(0) == MVT::bf16)
4845         return getConstant((uint16_t)V.bitcastToAPInt().getZExtValue(), DL, VT);
4846       if (VT == MVT::i32 && C->getValueType(0) == MVT::f32)
4847         return getConstant((uint32_t)V.bitcastToAPInt().getZExtValue(), DL, VT);
4848       if (VT == MVT::i64 && C->getValueType(0) == MVT::f64)
4849         return getConstant(V.bitcastToAPInt().getZExtValue(), DL, VT);
4850       break;
4851     case ISD::FP_TO_FP16: {
4852       bool Ignored;
4853       // This can return overflow, underflow, or inexact; we don't care.
4854       // FIXME need to be more flexible about rounding mode.
4855       (void)V.convert(APFloat::IEEEhalf(),
4856                       APFloat::rmNearestTiesToEven, &Ignored);
4857       return getConstant(V.bitcastToAPInt().getZExtValue(), DL, VT);
4858     }
4859     }
4860   }
4861 
4862   // Constant fold unary operations with a vector integer or float operand.
4863   switch (Opcode) {
4864   default:
4865     // FIXME: Entirely reasonable to perform folding of other unary
4866     // operations here as the need arises.
4867     break;
4868   case ISD::FNEG:
4869   case ISD::FABS:
4870   case ISD::FCEIL:
4871   case ISD::FTRUNC:
4872   case ISD::FFLOOR:
4873   case ISD::FP_EXTEND:
4874   case ISD::FP_TO_SINT:
4875   case ISD::FP_TO_UINT:
4876   case ISD::TRUNCATE:
4877   case ISD::ANY_EXTEND:
4878   case ISD::ZERO_EXTEND:
4879   case ISD::SIGN_EXTEND:
4880   case ISD::UINT_TO_FP:
4881   case ISD::SINT_TO_FP:
4882   case ISD::ABS:
4883   case ISD::BITREVERSE:
4884   case ISD::BSWAP:
4885   case ISD::CTLZ:
4886   case ISD::CTLZ_ZERO_UNDEF:
4887   case ISD::CTTZ:
4888   case ISD::CTTZ_ZERO_UNDEF:
4889   case ISD::CTPOP: {
4890     SDValue Ops = {Operand};
4891     if (SDValue Fold = FoldConstantArithmetic(Opcode, DL, VT, Ops))
4892       return Fold;
4893   }
4894   }
4895 
4896   unsigned OpOpcode = Operand.getNode()->getOpcode();
4897   switch (Opcode) {
4898   case ISD::STEP_VECTOR:
4899     assert(VT.isScalableVector() &&
4900            "STEP_VECTOR can only be used with scalable types");
4901     assert(OpOpcode == ISD::TargetConstant &&
4902            VT.getVectorElementType() == Operand.getValueType() &&
4903            "Unexpected step operand");
4904     break;
4905   case ISD::FREEZE:
4906     assert(VT == Operand.getValueType() && "Unexpected VT!");
4907     break;
4908   case ISD::TokenFactor:
4909   case ISD::MERGE_VALUES:
4910   case ISD::CONCAT_VECTORS:
4911     return Operand;         // Factor, merge or concat of one node?  No need.
4912   case ISD::BUILD_VECTOR: {
4913     // Attempt to simplify BUILD_VECTOR.
4914     SDValue Ops[] = {Operand};
4915     if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
4916       return V;
4917     break;
4918   }
4919   case ISD::FP_ROUND: llvm_unreachable("Invalid method to make FP_ROUND node");
4920   case ISD::FP_EXTEND:
4921     assert(VT.isFloatingPoint() &&
4922            Operand.getValueType().isFloatingPoint() && "Invalid FP cast!");
4923     if (Operand.getValueType() == VT) return Operand;  // noop conversion.
4924     assert((!VT.isVector() ||
4925             VT.getVectorElementCount() ==
4926             Operand.getValueType().getVectorElementCount()) &&
4927            "Vector element count mismatch!");
4928     assert(Operand.getValueType().bitsLT(VT) &&
4929            "Invalid fpext node, dst < src!");
4930     if (Operand.isUndef())
4931       return getUNDEF(VT);
4932     break;
4933   case ISD::FP_TO_SINT:
4934   case ISD::FP_TO_UINT:
4935     if (Operand.isUndef())
4936       return getUNDEF(VT);
4937     break;
4938   case ISD::SINT_TO_FP:
4939   case ISD::UINT_TO_FP:
4940     // [us]itofp(undef) = 0, because the result value is bounded.
4941     if (Operand.isUndef())
4942       return getConstantFP(0.0, DL, VT);
4943     break;
4944   case ISD::SIGN_EXTEND:
4945     assert(VT.isInteger() && Operand.getValueType().isInteger() &&
4946            "Invalid SIGN_EXTEND!");
4947     assert(VT.isVector() == Operand.getValueType().isVector() &&
4948            "SIGN_EXTEND result type type should be vector iff the operand "
4949            "type is vector!");
4950     if (Operand.getValueType() == VT) return Operand;   // noop extension
4951     assert((!VT.isVector() ||
4952             VT.getVectorElementCount() ==
4953                 Operand.getValueType().getVectorElementCount()) &&
4954            "Vector element count mismatch!");
4955     assert(Operand.getValueType().bitsLT(VT) &&
4956            "Invalid sext node, dst < src!");
4957     if (OpOpcode == ISD::SIGN_EXTEND || OpOpcode == ISD::ZERO_EXTEND)
4958       return getNode(OpOpcode, DL, VT, Operand.getOperand(0));
4959     if (OpOpcode == ISD::UNDEF)
4960       // sext(undef) = 0, because the top bits will all be the same.
4961       return getConstant(0, DL, VT);
4962     break;
4963   case ISD::ZERO_EXTEND:
4964     assert(VT.isInteger() && Operand.getValueType().isInteger() &&
4965            "Invalid ZERO_EXTEND!");
4966     assert(VT.isVector() == Operand.getValueType().isVector() &&
4967            "ZERO_EXTEND result type type should be vector iff the operand "
4968            "type is vector!");
4969     if (Operand.getValueType() == VT) return Operand;   // noop extension
4970     assert((!VT.isVector() ||
4971             VT.getVectorElementCount() ==
4972                 Operand.getValueType().getVectorElementCount()) &&
4973            "Vector element count mismatch!");
4974     assert(Operand.getValueType().bitsLT(VT) &&
4975            "Invalid zext node, dst < src!");
4976     if (OpOpcode == ISD::ZERO_EXTEND)   // (zext (zext x)) -> (zext x)
4977       return getNode(ISD::ZERO_EXTEND, DL, VT, Operand.getOperand(0));
4978     if (OpOpcode == ISD::UNDEF)
4979       // zext(undef) = 0, because the top bits will be zero.
4980       return getConstant(0, DL, VT);
4981     break;
4982   case ISD::ANY_EXTEND:
4983     assert(VT.isInteger() && Operand.getValueType().isInteger() &&
4984            "Invalid ANY_EXTEND!");
4985     assert(VT.isVector() == Operand.getValueType().isVector() &&
4986            "ANY_EXTEND result type type should be vector iff the operand "
4987            "type is vector!");
4988     if (Operand.getValueType() == VT) return Operand;   // noop extension
4989     assert((!VT.isVector() ||
4990             VT.getVectorElementCount() ==
4991                 Operand.getValueType().getVectorElementCount()) &&
4992            "Vector element count mismatch!");
4993     assert(Operand.getValueType().bitsLT(VT) &&
4994            "Invalid anyext node, dst < src!");
4995 
4996     if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
4997         OpOpcode == ISD::ANY_EXTEND)
4998       // (ext (zext x)) -> (zext x)  and  (ext (sext x)) -> (sext x)
4999       return getNode(OpOpcode, DL, VT, Operand.getOperand(0));
5000     if (OpOpcode == ISD::UNDEF)
5001       return getUNDEF(VT);
5002 
5003     // (ext (trunc x)) -> x
5004     if (OpOpcode == ISD::TRUNCATE) {
5005       SDValue OpOp = Operand.getOperand(0);
5006       if (OpOp.getValueType() == VT) {
5007         transferDbgValues(Operand, OpOp);
5008         return OpOp;
5009       }
5010     }
5011     break;
5012   case ISD::TRUNCATE:
5013     assert(VT.isInteger() && Operand.getValueType().isInteger() &&
5014            "Invalid TRUNCATE!");
5015     assert(VT.isVector() == Operand.getValueType().isVector() &&
5016            "TRUNCATE result type type should be vector iff the operand "
5017            "type is vector!");
5018     if (Operand.getValueType() == VT) return Operand;   // noop truncate
5019     assert((!VT.isVector() ||
5020             VT.getVectorElementCount() ==
5021                 Operand.getValueType().getVectorElementCount()) &&
5022            "Vector element count mismatch!");
5023     assert(Operand.getValueType().bitsGT(VT) &&
5024            "Invalid truncate node, src < dst!");
5025     if (OpOpcode == ISD::TRUNCATE)
5026       return getNode(ISD::TRUNCATE, DL, VT, Operand.getOperand(0));
5027     if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
5028         OpOpcode == ISD::ANY_EXTEND) {
5029       // If the source is smaller than the dest, we still need an extend.
5030       if (Operand.getOperand(0).getValueType().getScalarType()
5031             .bitsLT(VT.getScalarType()))
5032         return getNode(OpOpcode, DL, VT, Operand.getOperand(0));
5033       if (Operand.getOperand(0).getValueType().bitsGT(VT))
5034         return getNode(ISD::TRUNCATE, DL, VT, Operand.getOperand(0));
5035       return Operand.getOperand(0);
5036     }
5037     if (OpOpcode == ISD::UNDEF)
5038       return getUNDEF(VT);
5039     if (OpOpcode == ISD::VSCALE && !NewNodesMustHaveLegalTypes)
5040       return getVScale(DL, VT, Operand.getConstantOperandAPInt(0));
5041     break;
5042   case ISD::ANY_EXTEND_VECTOR_INREG:
5043   case ISD::ZERO_EXTEND_VECTOR_INREG:
5044   case ISD::SIGN_EXTEND_VECTOR_INREG:
5045     assert(VT.isVector() && "This DAG node is restricted to vector types.");
5046     assert(Operand.getValueType().bitsLE(VT) &&
5047            "The input must be the same size or smaller than the result.");
5048     assert(VT.getVectorMinNumElements() <
5049                Operand.getValueType().getVectorMinNumElements() &&
5050            "The destination vector type must have fewer lanes than the input.");
5051     break;
5052   case ISD::ABS:
5053     assert(VT.isInteger() && VT == Operand.getValueType() &&
5054            "Invalid ABS!");
5055     if (OpOpcode == ISD::UNDEF)
5056       return getUNDEF(VT);
5057     break;
5058   case ISD::BSWAP:
5059     assert(VT.isInteger() && VT == Operand.getValueType() &&
5060            "Invalid BSWAP!");
5061     assert((VT.getScalarSizeInBits() % 16 == 0) &&
5062            "BSWAP types must be a multiple of 16 bits!");
5063     if (OpOpcode == ISD::UNDEF)
5064       return getUNDEF(VT);
5065     break;
5066   case ISD::BITREVERSE:
5067     assert(VT.isInteger() && VT == Operand.getValueType() &&
5068            "Invalid BITREVERSE!");
5069     if (OpOpcode == ISD::UNDEF)
5070       return getUNDEF(VT);
5071     break;
5072   case ISD::BITCAST:
5073     // Basic sanity checking.
5074     assert(VT.getSizeInBits() == Operand.getValueSizeInBits() &&
5075            "Cannot BITCAST between types of different sizes!");
5076     if (VT == Operand.getValueType()) return Operand;  // noop conversion.
5077     if (OpOpcode == ISD::BITCAST)  // bitconv(bitconv(x)) -> bitconv(x)
5078       return getNode(ISD::BITCAST, DL, VT, Operand.getOperand(0));
5079     if (OpOpcode == ISD::UNDEF)
5080       return getUNDEF(VT);
5081     break;
5082   case ISD::SCALAR_TO_VECTOR:
5083     assert(VT.isVector() && !Operand.getValueType().isVector() &&
5084            (VT.getVectorElementType() == Operand.getValueType() ||
5085             (VT.getVectorElementType().isInteger() &&
5086              Operand.getValueType().isInteger() &&
5087              VT.getVectorElementType().bitsLE(Operand.getValueType()))) &&
5088            "Illegal SCALAR_TO_VECTOR node!");
5089     if (OpOpcode == ISD::UNDEF)
5090       return getUNDEF(VT);
5091     // scalar_to_vector(extract_vector_elt V, 0) -> V, top bits are undefined.
5092     if (OpOpcode == ISD::EXTRACT_VECTOR_ELT &&
5093         isa<ConstantSDNode>(Operand.getOperand(1)) &&
5094         Operand.getConstantOperandVal(1) == 0 &&
5095         Operand.getOperand(0).getValueType() == VT)
5096       return Operand.getOperand(0);
5097     break;
5098   case ISD::FNEG:
5099     // Negation of an unknown bag of bits is still completely undefined.
5100     if (OpOpcode == ISD::UNDEF)
5101       return getUNDEF(VT);
5102 
5103     if (OpOpcode == ISD::FNEG)  // --X -> X
5104       return Operand.getOperand(0);
5105     break;
5106   case ISD::FABS:
5107     if (OpOpcode == ISD::FNEG)  // abs(-X) -> abs(X)
5108       return getNode(ISD::FABS, DL, VT, Operand.getOperand(0));
5109     break;
5110   case ISD::VSCALE:
5111     assert(VT == Operand.getValueType() && "Unexpected VT!");
5112     break;
5113   case ISD::CTPOP:
5114     if (Operand.getValueType().getScalarType() == MVT::i1)
5115       return Operand;
5116     break;
5117   case ISD::CTLZ:
5118   case ISD::CTTZ:
5119     if (Operand.getValueType().getScalarType() == MVT::i1)
5120       return getNOT(DL, Operand, Operand.getValueType());
5121     break;
5122   case ISD::VECREDUCE_SMIN:
5123   case ISD::VECREDUCE_UMAX:
5124     if (Operand.getValueType().getScalarType() == MVT::i1)
5125       return getNode(ISD::VECREDUCE_OR, DL, VT, Operand);
5126     break;
5127   case ISD::VECREDUCE_SMAX:
5128   case ISD::VECREDUCE_UMIN:
5129     if (Operand.getValueType().getScalarType() == MVT::i1)
5130       return getNode(ISD::VECREDUCE_AND, DL, VT, Operand);
5131     break;
5132   }
5133 
5134   SDNode *N;
5135   SDVTList VTs = getVTList(VT);
5136   SDValue Ops[] = {Operand};
5137   if (VT != MVT::Glue) { // Don't CSE flag producing nodes
5138     FoldingSetNodeID ID;
5139     AddNodeIDNode(ID, Opcode, VTs, Ops);
5140     void *IP = nullptr;
5141     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
5142       E->intersectFlagsWith(Flags);
5143       return SDValue(E, 0);
5144     }
5145 
5146     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
5147     N->setFlags(Flags);
5148     createOperands(N, Ops);
5149     CSEMap.InsertNode(N, IP);
5150   } else {
5151     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
5152     createOperands(N, Ops);
5153   }
5154 
5155   InsertNode(N);
5156   SDValue V = SDValue(N, 0);
5157   NewSDValueDbgMsg(V, "Creating new node: ", this);
5158   return V;
5159 }
5160 
5161 static llvm::Optional<APInt> FoldValue(unsigned Opcode, const APInt &C1,
5162                                        const APInt &C2) {
5163   switch (Opcode) {
5164   case ISD::ADD:  return C1 + C2;
5165   case ISD::SUB:  return C1 - C2;
5166   case ISD::MUL:  return C1 * C2;
5167   case ISD::AND:  return C1 & C2;
5168   case ISD::OR:   return C1 | C2;
5169   case ISD::XOR:  return C1 ^ C2;
5170   case ISD::SHL:  return C1 << C2;
5171   case ISD::SRL:  return C1.lshr(C2);
5172   case ISD::SRA:  return C1.ashr(C2);
5173   case ISD::ROTL: return C1.rotl(C2);
5174   case ISD::ROTR: return C1.rotr(C2);
5175   case ISD::SMIN: return C1.sle(C2) ? C1 : C2;
5176   case ISD::SMAX: return C1.sge(C2) ? C1 : C2;
5177   case ISD::UMIN: return C1.ule(C2) ? C1 : C2;
5178   case ISD::UMAX: return C1.uge(C2) ? C1 : C2;
5179   case ISD::SADDSAT: return C1.sadd_sat(C2);
5180   case ISD::UADDSAT: return C1.uadd_sat(C2);
5181   case ISD::SSUBSAT: return C1.ssub_sat(C2);
5182   case ISD::USUBSAT: return C1.usub_sat(C2);
5183   case ISD::UDIV:
5184     if (!C2.getBoolValue())
5185       break;
5186     return C1.udiv(C2);
5187   case ISD::UREM:
5188     if (!C2.getBoolValue())
5189       break;
5190     return C1.urem(C2);
5191   case ISD::SDIV:
5192     if (!C2.getBoolValue())
5193       break;
5194     return C1.sdiv(C2);
5195   case ISD::SREM:
5196     if (!C2.getBoolValue())
5197       break;
5198     return C1.srem(C2);
5199   case ISD::MULHS: {
5200     unsigned FullWidth = C1.getBitWidth() * 2;
5201     APInt C1Ext = C1.sext(FullWidth);
5202     APInt C2Ext = C2.sext(FullWidth);
5203     return (C1Ext * C2Ext).extractBits(C1.getBitWidth(), C1.getBitWidth());
5204   }
5205   case ISD::MULHU: {
5206     unsigned FullWidth = C1.getBitWidth() * 2;
5207     APInt C1Ext = C1.zext(FullWidth);
5208     APInt C2Ext = C2.zext(FullWidth);
5209     return (C1Ext * C2Ext).extractBits(C1.getBitWidth(), C1.getBitWidth());
5210   }
5211   }
5212   return llvm::None;
5213 }
5214 
5215 SDValue SelectionDAG::FoldSymbolOffset(unsigned Opcode, EVT VT,
5216                                        const GlobalAddressSDNode *GA,
5217                                        const SDNode *N2) {
5218   if (GA->getOpcode() != ISD::GlobalAddress)
5219     return SDValue();
5220   if (!TLI->isOffsetFoldingLegal(GA))
5221     return SDValue();
5222   auto *C2 = dyn_cast<ConstantSDNode>(N2);
5223   if (!C2)
5224     return SDValue();
5225   int64_t Offset = C2->getSExtValue();
5226   switch (Opcode) {
5227   case ISD::ADD: break;
5228   case ISD::SUB: Offset = -uint64_t(Offset); break;
5229   default: return SDValue();
5230   }
5231   return getGlobalAddress(GA->getGlobal(), SDLoc(C2), VT,
5232                           GA->getOffset() + uint64_t(Offset));
5233 }
5234 
5235 bool SelectionDAG::isUndef(unsigned Opcode, ArrayRef<SDValue> Ops) {
5236   switch (Opcode) {
5237   case ISD::SDIV:
5238   case ISD::UDIV:
5239   case ISD::SREM:
5240   case ISD::UREM: {
5241     // If a divisor is zero/undef or any element of a divisor vector is
5242     // zero/undef, the whole op is undef.
5243     assert(Ops.size() == 2 && "Div/rem should have 2 operands");
5244     SDValue Divisor = Ops[1];
5245     if (Divisor.isUndef() || isNullConstant(Divisor))
5246       return true;
5247 
5248     return ISD::isBuildVectorOfConstantSDNodes(Divisor.getNode()) &&
5249            llvm::any_of(Divisor->op_values(),
5250                         [](SDValue V) { return V.isUndef() ||
5251                                         isNullConstant(V); });
5252     // TODO: Handle signed overflow.
5253   }
5254   // TODO: Handle oversized shifts.
5255   default:
5256     return false;
5257   }
5258 }
5259 
5260 SDValue SelectionDAG::FoldConstantArithmetic(unsigned Opcode, const SDLoc &DL,
5261                                              EVT VT, ArrayRef<SDValue> Ops) {
5262   // If the opcode is a target-specific ISD node, there's nothing we can
5263   // do here and the operand rules may not line up with the below, so
5264   // bail early.
5265   // We can't create a scalar CONCAT_VECTORS so skip it. It will break
5266   // for concats involving SPLAT_VECTOR. Concats of BUILD_VECTORS are handled by
5267   // foldCONCAT_VECTORS in getNode before this is called.
5268   if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::CONCAT_VECTORS)
5269     return SDValue();
5270 
5271   unsigned NumOps = Ops.size();
5272   if (NumOps == 0)
5273     return SDValue();
5274 
5275   if (isUndef(Opcode, Ops))
5276     return getUNDEF(VT);
5277 
5278   // Handle the case of two scalars.
5279   if (NumOps == 2) {
5280     // TODO: Move foldConstantFPMath here?
5281 
5282     if (auto *C1 = dyn_cast<ConstantSDNode>(Ops[0])) {
5283       if (auto *C2 = dyn_cast<ConstantSDNode>(Ops[1])) {
5284         if (C1->isOpaque() || C2->isOpaque())
5285           return SDValue();
5286 
5287         Optional<APInt> FoldAttempt =
5288             FoldValue(Opcode, C1->getAPIntValue(), C2->getAPIntValue());
5289         if (!FoldAttempt)
5290           return SDValue();
5291 
5292         SDValue Folded = getConstant(FoldAttempt.getValue(), DL, VT);
5293         assert((!Folded || !VT.isVector()) &&
5294                "Can't fold vectors ops with scalar operands");
5295         return Folded;
5296       }
5297     }
5298 
5299     // fold (add Sym, c) -> Sym+c
5300     if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Ops[0]))
5301       return FoldSymbolOffset(Opcode, VT, GA, Ops[1].getNode());
5302     if (TLI->isCommutativeBinOp(Opcode))
5303       if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Ops[1]))
5304         return FoldSymbolOffset(Opcode, VT, GA, Ops[0].getNode());
5305   }
5306 
5307   // This is for vector folding only from here on.
5308   if (!VT.isVector())
5309     return SDValue();
5310 
5311   ElementCount NumElts = VT.getVectorElementCount();
5312 
5313   // See if we can fold through bitcasted integer ops.
5314   // TODO: Can we handle undef elements?
5315   if (NumOps == 2 && VT.isFixedLengthVector() && VT.isInteger() &&
5316       Ops[0].getValueType() == VT && Ops[1].getValueType() == VT &&
5317       Ops[0].getOpcode() == ISD::BITCAST &&
5318       Ops[1].getOpcode() == ISD::BITCAST) {
5319     SDValue N1 = peekThroughBitcasts(Ops[0]);
5320     SDValue N2 = peekThroughBitcasts(Ops[1]);
5321     auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
5322     auto *BV2 = dyn_cast<BuildVectorSDNode>(N2);
5323     EVT BVVT = N1.getValueType();
5324     if (BV1 && BV2 && BVVT.isInteger() && BVVT == N2.getValueType()) {
5325       bool IsLE = getDataLayout().isLittleEndian();
5326       unsigned EltBits = VT.getScalarSizeInBits();
5327       SmallVector<APInt> RawBits1, RawBits2;
5328       BitVector UndefElts1, UndefElts2;
5329       if (BV1->getConstantRawBits(IsLE, EltBits, RawBits1, UndefElts1) &&
5330           BV2->getConstantRawBits(IsLE, EltBits, RawBits2, UndefElts2) &&
5331           UndefElts1.none() && UndefElts2.none()) {
5332         SmallVector<APInt> RawBits;
5333         for (unsigned I = 0, E = NumElts.getFixedValue(); I != E; ++I) {
5334           Optional<APInt> Fold = FoldValue(Opcode, RawBits1[I], RawBits2[I]);
5335           if (!Fold)
5336             break;
5337           RawBits.push_back(Fold.getValue());
5338         }
5339         if (RawBits.size() == NumElts.getFixedValue()) {
5340           // We have constant folded, but we need to cast this again back to
5341           // the original (possibly legalized) type.
5342           SmallVector<APInt> DstBits;
5343           BitVector DstUndefs;
5344           BuildVectorSDNode::recastRawBits(IsLE, BVVT.getScalarSizeInBits(),
5345                                            DstBits, RawBits, DstUndefs,
5346                                            BitVector(RawBits.size(), false));
5347           EVT BVEltVT = BV1->getOperand(0).getValueType();
5348           unsigned BVEltBits = BVEltVT.getSizeInBits();
5349           SmallVector<SDValue> Ops(DstBits.size(), getUNDEF(BVEltVT));
5350           for (unsigned I = 0, E = DstBits.size(); I != E; ++I) {
5351             if (DstUndefs[I])
5352               continue;
5353             Ops[I] = getConstant(DstBits[I].sextOrSelf(BVEltBits), DL, BVEltVT);
5354           }
5355           return getBitcast(VT, getBuildVector(BVVT, DL, Ops));
5356         }
5357       }
5358     }
5359   }
5360 
5361   auto IsScalarOrSameVectorSize = [NumElts](const SDValue &Op) {
5362     return !Op.getValueType().isVector() ||
5363            Op.getValueType().getVectorElementCount() == NumElts;
5364   };
5365 
5366   auto IsBuildVectorSplatVectorOrUndef = [](const SDValue &Op) {
5367     return Op.isUndef() || Op.getOpcode() == ISD::CONDCODE ||
5368            Op.getOpcode() == ISD::BUILD_VECTOR ||
5369            Op.getOpcode() == ISD::SPLAT_VECTOR;
5370   };
5371 
5372   // All operands must be vector types with the same number of elements as
5373   // the result type and must be either UNDEF or a build/splat vector
5374   // or UNDEF scalars.
5375   if (!llvm::all_of(Ops, IsBuildVectorSplatVectorOrUndef) ||
5376       !llvm::all_of(Ops, IsScalarOrSameVectorSize))
5377     return SDValue();
5378 
5379   // If we are comparing vectors, then the result needs to be a i1 boolean
5380   // that is then sign-extended back to the legal result type.
5381   EVT SVT = (Opcode == ISD::SETCC ? MVT::i1 : VT.getScalarType());
5382 
5383   // Find legal integer scalar type for constant promotion and
5384   // ensure that its scalar size is at least as large as source.
5385   EVT LegalSVT = VT.getScalarType();
5386   if (NewNodesMustHaveLegalTypes && LegalSVT.isInteger()) {
5387     LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT);
5388     if (LegalSVT.bitsLT(VT.getScalarType()))
5389       return SDValue();
5390   }
5391 
5392   // For scalable vector types we know we're dealing with SPLAT_VECTORs. We
5393   // only have one operand to check. For fixed-length vector types we may have
5394   // a combination of BUILD_VECTOR and SPLAT_VECTOR.
5395   unsigned NumVectorElts = NumElts.isScalable() ? 1 : NumElts.getFixedValue();
5396 
5397   // Constant fold each scalar lane separately.
5398   SmallVector<SDValue, 4> ScalarResults;
5399   for (unsigned I = 0; I != NumVectorElts; I++) {
5400     SmallVector<SDValue, 4> ScalarOps;
5401     for (SDValue Op : Ops) {
5402       EVT InSVT = Op.getValueType().getScalarType();
5403       if (Op.getOpcode() != ISD::BUILD_VECTOR &&
5404           Op.getOpcode() != ISD::SPLAT_VECTOR) {
5405         if (Op.isUndef())
5406           ScalarOps.push_back(getUNDEF(InSVT));
5407         else
5408           ScalarOps.push_back(Op);
5409         continue;
5410       }
5411 
5412       SDValue ScalarOp =
5413           Op.getOperand(Op.getOpcode() == ISD::SPLAT_VECTOR ? 0 : I);
5414       EVT ScalarVT = ScalarOp.getValueType();
5415 
5416       // Build vector (integer) scalar operands may need implicit
5417       // truncation - do this before constant folding.
5418       if (ScalarVT.isInteger() && ScalarVT.bitsGT(InSVT))
5419         ScalarOp = getNode(ISD::TRUNCATE, DL, InSVT, ScalarOp);
5420 
5421       ScalarOps.push_back(ScalarOp);
5422     }
5423 
5424     // Constant fold the scalar operands.
5425     SDValue ScalarResult = getNode(Opcode, DL, SVT, ScalarOps);
5426 
5427     // Legalize the (integer) scalar constant if necessary.
5428     if (LegalSVT != SVT)
5429       ScalarResult = getNode(ISD::SIGN_EXTEND, DL, LegalSVT, ScalarResult);
5430 
5431     // Scalar folding only succeeded if the result is a constant or UNDEF.
5432     if (!ScalarResult.isUndef() && ScalarResult.getOpcode() != ISD::Constant &&
5433         ScalarResult.getOpcode() != ISD::ConstantFP)
5434       return SDValue();
5435     ScalarResults.push_back(ScalarResult);
5436   }
5437 
5438   SDValue V = NumElts.isScalable() ? getSplatVector(VT, DL, ScalarResults[0])
5439                                    : getBuildVector(VT, DL, ScalarResults);
5440   NewSDValueDbgMsg(V, "New node fold constant vector: ", this);
5441   return V;
5442 }
5443 
5444 SDValue SelectionDAG::foldConstantFPMath(unsigned Opcode, const SDLoc &DL,
5445                                          EVT VT, SDValue N1, SDValue N2) {
5446   // TODO: We don't do any constant folding for strict FP opcodes here, but we
5447   //       should. That will require dealing with a potentially non-default
5448   //       rounding mode, checking the "opStatus" return value from the APFloat
5449   //       math calculations, and possibly other variations.
5450   auto *N1CFP = dyn_cast<ConstantFPSDNode>(N1.getNode());
5451   auto *N2CFP = dyn_cast<ConstantFPSDNode>(N2.getNode());
5452   if (N1CFP && N2CFP) {
5453     APFloat C1 = N1CFP->getValueAPF(), C2 = N2CFP->getValueAPF();
5454     switch (Opcode) {
5455     case ISD::FADD:
5456       C1.add(C2, APFloat::rmNearestTiesToEven);
5457       return getConstantFP(C1, DL, VT);
5458     case ISD::FSUB:
5459       C1.subtract(C2, APFloat::rmNearestTiesToEven);
5460       return getConstantFP(C1, DL, VT);
5461     case ISD::FMUL:
5462       C1.multiply(C2, APFloat::rmNearestTiesToEven);
5463       return getConstantFP(C1, DL, VT);
5464     case ISD::FDIV:
5465       C1.divide(C2, APFloat::rmNearestTiesToEven);
5466       return getConstantFP(C1, DL, VT);
5467     case ISD::FREM:
5468       C1.mod(C2);
5469       return getConstantFP(C1, DL, VT);
5470     case ISD::FCOPYSIGN:
5471       C1.copySign(C2);
5472       return getConstantFP(C1, DL, VT);
5473     default: break;
5474     }
5475   }
5476   if (N1CFP && Opcode == ISD::FP_ROUND) {
5477     APFloat C1 = N1CFP->getValueAPF();    // make copy
5478     bool Unused;
5479     // This can return overflow, underflow, or inexact; we don't care.
5480     // FIXME need to be more flexible about rounding mode.
5481     (void) C1.convert(EVTToAPFloatSemantics(VT), APFloat::rmNearestTiesToEven,
5482                       &Unused);
5483     return getConstantFP(C1, DL, VT);
5484   }
5485 
5486   switch (Opcode) {
5487   case ISD::FSUB:
5488     // -0.0 - undef --> undef (consistent with "fneg undef")
5489     if (N1CFP && N1CFP->getValueAPF().isNegZero() && N2.isUndef())
5490       return getUNDEF(VT);
5491     LLVM_FALLTHROUGH;
5492 
5493   case ISD::FADD:
5494   case ISD::FMUL:
5495   case ISD::FDIV:
5496   case ISD::FREM:
5497     // If both operands are undef, the result is undef. If 1 operand is undef,
5498     // the result is NaN. This should match the behavior of the IR optimizer.
5499     if (N1.isUndef() && N2.isUndef())
5500       return getUNDEF(VT);
5501     if (N1.isUndef() || N2.isUndef())
5502       return getConstantFP(APFloat::getNaN(EVTToAPFloatSemantics(VT)), DL, VT);
5503   }
5504   return SDValue();
5505 }
5506 
5507 SDValue SelectionDAG::getAssertAlign(const SDLoc &DL, SDValue Val, Align A) {
5508   assert(Val.getValueType().isInteger() && "Invalid AssertAlign!");
5509 
5510   // There's no need to assert on a byte-aligned pointer. All pointers are at
5511   // least byte aligned.
5512   if (A == Align(1))
5513     return Val;
5514 
5515   FoldingSetNodeID ID;
5516   AddNodeIDNode(ID, ISD::AssertAlign, getVTList(Val.getValueType()), {Val});
5517   ID.AddInteger(A.value());
5518 
5519   void *IP = nullptr;
5520   if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
5521     return SDValue(E, 0);
5522 
5523   auto *N = newSDNode<AssertAlignSDNode>(DL.getIROrder(), DL.getDebugLoc(),
5524                                          Val.getValueType(), A);
5525   createOperands(N, {Val});
5526 
5527   CSEMap.InsertNode(N, IP);
5528   InsertNode(N);
5529 
5530   SDValue V(N, 0);
5531   NewSDValueDbgMsg(V, "Creating new node: ", this);
5532   return V;
5533 }
5534 
5535 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
5536                               SDValue N1, SDValue N2) {
5537   SDNodeFlags Flags;
5538   if (Inserter)
5539     Flags = Inserter->getFlags();
5540   return getNode(Opcode, DL, VT, N1, N2, Flags);
5541 }
5542 
5543 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
5544                               SDValue N1, SDValue N2, const SDNodeFlags Flags) {
5545   assert(N1.getOpcode() != ISD::DELETED_NODE &&
5546          N2.getOpcode() != ISD::DELETED_NODE &&
5547          "Operand is DELETED_NODE!");
5548   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
5549   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
5550   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
5551   ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2);
5552 
5553   // Canonicalize constant to RHS if commutative.
5554   if (TLI->isCommutativeBinOp(Opcode)) {
5555     if (N1C && !N2C) {
5556       std::swap(N1C, N2C);
5557       std::swap(N1, N2);
5558     } else if (N1CFP && !N2CFP) {
5559       std::swap(N1CFP, N2CFP);
5560       std::swap(N1, N2);
5561     }
5562   }
5563 
5564   switch (Opcode) {
5565   default: break;
5566   case ISD::TokenFactor:
5567     assert(VT == MVT::Other && N1.getValueType() == MVT::Other &&
5568            N2.getValueType() == MVT::Other && "Invalid token factor!");
5569     // Fold trivial token factors.
5570     if (N1.getOpcode() == ISD::EntryToken) return N2;
5571     if (N2.getOpcode() == ISD::EntryToken) return N1;
5572     if (N1 == N2) return N1;
5573     break;
5574   case ISD::BUILD_VECTOR: {
5575     // Attempt to simplify BUILD_VECTOR.
5576     SDValue Ops[] = {N1, N2};
5577     if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
5578       return V;
5579     break;
5580   }
5581   case ISD::CONCAT_VECTORS: {
5582     SDValue Ops[] = {N1, N2};
5583     if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this))
5584       return V;
5585     break;
5586   }
5587   case ISD::AND:
5588     assert(VT.isInteger() && "This operator does not apply to FP types!");
5589     assert(N1.getValueType() == N2.getValueType() &&
5590            N1.getValueType() == VT && "Binary operator types must match!");
5591     // (X & 0) -> 0.  This commonly occurs when legalizing i64 values, so it's
5592     // worth handling here.
5593     if (N2C && N2C->isZero())
5594       return N2;
5595     if (N2C && N2C->isAllOnes()) // X & -1 -> X
5596       return N1;
5597     break;
5598   case ISD::OR:
5599   case ISD::XOR:
5600   case ISD::ADD:
5601   case ISD::SUB:
5602     assert(VT.isInteger() && "This operator does not apply to FP types!");
5603     assert(N1.getValueType() == N2.getValueType() &&
5604            N1.getValueType() == VT && "Binary operator types must match!");
5605     // (X ^|+- 0) -> X.  This commonly occurs when legalizing i64 values, so
5606     // it's worth handling here.
5607     if (N2C && N2C->isZero())
5608       return N1;
5609     if ((Opcode == ISD::ADD || Opcode == ISD::SUB) && VT.isVector() &&
5610         VT.getVectorElementType() == MVT::i1)
5611       return getNode(ISD::XOR, DL, VT, N1, N2);
5612     break;
5613   case ISD::MUL:
5614     assert(VT.isInteger() && "This operator does not apply to FP types!");
5615     assert(N1.getValueType() == N2.getValueType() &&
5616            N1.getValueType() == VT && "Binary operator types must match!");
5617     if (VT.isVector() && VT.getVectorElementType() == MVT::i1)
5618       return getNode(ISD::AND, DL, VT, N1, N2);
5619     if (N2C && (N1.getOpcode() == ISD::VSCALE) && Flags.hasNoSignedWrap()) {
5620       const APInt &MulImm = N1->getConstantOperandAPInt(0);
5621       const APInt &N2CImm = N2C->getAPIntValue();
5622       return getVScale(DL, VT, MulImm * N2CImm);
5623     }
5624     break;
5625   case ISD::UDIV:
5626   case ISD::UREM:
5627   case ISD::MULHU:
5628   case ISD::MULHS:
5629   case ISD::SDIV:
5630   case ISD::SREM:
5631   case ISD::SADDSAT:
5632   case ISD::SSUBSAT:
5633   case ISD::UADDSAT:
5634   case ISD::USUBSAT:
5635     assert(VT.isInteger() && "This operator does not apply to FP types!");
5636     assert(N1.getValueType() == N2.getValueType() &&
5637            N1.getValueType() == VT && "Binary operator types must match!");
5638     if (VT.isVector() && VT.getVectorElementType() == MVT::i1) {
5639       // fold (add_sat x, y) -> (or x, y) for bool types.
5640       if (Opcode == ISD::SADDSAT || Opcode == ISD::UADDSAT)
5641         return getNode(ISD::OR, DL, VT, N1, N2);
5642       // fold (sub_sat x, y) -> (and x, ~y) for bool types.
5643       if (Opcode == ISD::SSUBSAT || Opcode == ISD::USUBSAT)
5644         return getNode(ISD::AND, DL, VT, N1, getNOT(DL, N2, VT));
5645     }
5646     break;
5647   case ISD::SMIN:
5648   case ISD::UMAX:
5649     assert(VT.isInteger() && "This operator does not apply to FP types!");
5650     assert(N1.getValueType() == N2.getValueType() &&
5651            N1.getValueType() == VT && "Binary operator types must match!");
5652     if (VT.isVector() && VT.getVectorElementType() == MVT::i1)
5653       return getNode(ISD::OR, DL, VT, N1, N2);
5654     break;
5655   case ISD::SMAX:
5656   case ISD::UMIN:
5657     assert(VT.isInteger() && "This operator does not apply to FP types!");
5658     assert(N1.getValueType() == N2.getValueType() &&
5659            N1.getValueType() == VT && "Binary operator types must match!");
5660     if (VT.isVector() && VT.getVectorElementType() == MVT::i1)
5661       return getNode(ISD::AND, DL, VT, N1, N2);
5662     break;
5663   case ISD::FADD:
5664   case ISD::FSUB:
5665   case ISD::FMUL:
5666   case ISD::FDIV:
5667   case ISD::FREM:
5668     assert(VT.isFloatingPoint() && "This operator only applies to FP types!");
5669     assert(N1.getValueType() == N2.getValueType() &&
5670            N1.getValueType() == VT && "Binary operator types must match!");
5671     if (SDValue V = simplifyFPBinop(Opcode, N1, N2, Flags))
5672       return V;
5673     break;
5674   case ISD::FCOPYSIGN:   // N1 and result must match.  N1/N2 need not match.
5675     assert(N1.getValueType() == VT &&
5676            N1.getValueType().isFloatingPoint() &&
5677            N2.getValueType().isFloatingPoint() &&
5678            "Invalid FCOPYSIGN!");
5679     break;
5680   case ISD::SHL:
5681     if (N2C && (N1.getOpcode() == ISD::VSCALE) && Flags.hasNoSignedWrap()) {
5682       const APInt &MulImm = N1->getConstantOperandAPInt(0);
5683       const APInt &ShiftImm = N2C->getAPIntValue();
5684       return getVScale(DL, VT, MulImm << ShiftImm);
5685     }
5686     LLVM_FALLTHROUGH;
5687   case ISD::SRA:
5688   case ISD::SRL:
5689     if (SDValue V = simplifyShift(N1, N2))
5690       return V;
5691     LLVM_FALLTHROUGH;
5692   case ISD::ROTL:
5693   case ISD::ROTR:
5694     assert(VT == N1.getValueType() &&
5695            "Shift operators return type must be the same as their first arg");
5696     assert(VT.isInteger() && N2.getValueType().isInteger() &&
5697            "Shifts only work on integers");
5698     assert((!VT.isVector() || VT == N2.getValueType()) &&
5699            "Vector shift amounts must be in the same as their first arg");
5700     // Verify that the shift amount VT is big enough to hold valid shift
5701     // amounts.  This catches things like trying to shift an i1024 value by an
5702     // i8, which is easy to fall into in generic code that uses
5703     // TLI.getShiftAmount().
5704     assert(N2.getValueType().getScalarSizeInBits() >=
5705                Log2_32_Ceil(VT.getScalarSizeInBits()) &&
5706            "Invalid use of small shift amount with oversized value!");
5707 
5708     // Always fold shifts of i1 values so the code generator doesn't need to
5709     // handle them.  Since we know the size of the shift has to be less than the
5710     // size of the value, the shift/rotate count is guaranteed to be zero.
5711     if (VT == MVT::i1)
5712       return N1;
5713     if (N2C && N2C->isZero())
5714       return N1;
5715     break;
5716   case ISD::FP_ROUND:
5717     assert(VT.isFloatingPoint() &&
5718            N1.getValueType().isFloatingPoint() &&
5719            VT.bitsLE(N1.getValueType()) &&
5720            N2C && (N2C->getZExtValue() == 0 || N2C->getZExtValue() == 1) &&
5721            "Invalid FP_ROUND!");
5722     if (N1.getValueType() == VT) return N1;  // noop conversion.
5723     break;
5724   case ISD::AssertSext:
5725   case ISD::AssertZext: {
5726     EVT EVT = cast<VTSDNode>(N2)->getVT();
5727     assert(VT == N1.getValueType() && "Not an inreg extend!");
5728     assert(VT.isInteger() && EVT.isInteger() &&
5729            "Cannot *_EXTEND_INREG FP types");
5730     assert(!EVT.isVector() &&
5731            "AssertSExt/AssertZExt type should be the vector element type "
5732            "rather than the vector type!");
5733     assert(EVT.bitsLE(VT.getScalarType()) && "Not extending!");
5734     if (VT.getScalarType() == EVT) return N1; // noop assertion.
5735     break;
5736   }
5737   case ISD::SIGN_EXTEND_INREG: {
5738     EVT EVT = cast<VTSDNode>(N2)->getVT();
5739     assert(VT == N1.getValueType() && "Not an inreg extend!");
5740     assert(VT.isInteger() && EVT.isInteger() &&
5741            "Cannot *_EXTEND_INREG FP types");
5742     assert(EVT.isVector() == VT.isVector() &&
5743            "SIGN_EXTEND_INREG type should be vector iff the operand "
5744            "type is vector!");
5745     assert((!EVT.isVector() ||
5746             EVT.getVectorElementCount() == VT.getVectorElementCount()) &&
5747            "Vector element counts must match in SIGN_EXTEND_INREG");
5748     assert(EVT.bitsLE(VT) && "Not extending!");
5749     if (EVT == VT) return N1;  // Not actually extending
5750 
5751     auto SignExtendInReg = [&](APInt Val, llvm::EVT ConstantVT) {
5752       unsigned FromBits = EVT.getScalarSizeInBits();
5753       Val <<= Val.getBitWidth() - FromBits;
5754       Val.ashrInPlace(Val.getBitWidth() - FromBits);
5755       return getConstant(Val, DL, ConstantVT);
5756     };
5757 
5758     if (N1C) {
5759       const APInt &Val = N1C->getAPIntValue();
5760       return SignExtendInReg(Val, VT);
5761     }
5762 
5763     if (ISD::isBuildVectorOfConstantSDNodes(N1.getNode())) {
5764       SmallVector<SDValue, 8> Ops;
5765       llvm::EVT OpVT = N1.getOperand(0).getValueType();
5766       for (int i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
5767         SDValue Op = N1.getOperand(i);
5768         if (Op.isUndef()) {
5769           Ops.push_back(getUNDEF(OpVT));
5770           continue;
5771         }
5772         ConstantSDNode *C = cast<ConstantSDNode>(Op);
5773         APInt Val = C->getAPIntValue();
5774         Ops.push_back(SignExtendInReg(Val, OpVT));
5775       }
5776       return getBuildVector(VT, DL, Ops);
5777     }
5778     break;
5779   }
5780   case ISD::FP_TO_SINT_SAT:
5781   case ISD::FP_TO_UINT_SAT: {
5782     assert(VT.isInteger() && cast<VTSDNode>(N2)->getVT().isInteger() &&
5783            N1.getValueType().isFloatingPoint() && "Invalid FP_TO_*INT_SAT");
5784     assert(N1.getValueType().isVector() == VT.isVector() &&
5785            "FP_TO_*INT_SAT type should be vector iff the operand type is "
5786            "vector!");
5787     assert((!VT.isVector() || VT.getVectorNumElements() ==
5788                                   N1.getValueType().getVectorNumElements()) &&
5789            "Vector element counts must match in FP_TO_*INT_SAT");
5790     assert(!cast<VTSDNode>(N2)->getVT().isVector() &&
5791            "Type to saturate to must be a scalar.");
5792     assert(cast<VTSDNode>(N2)->getVT().bitsLE(VT.getScalarType()) &&
5793            "Not extending!");
5794     break;
5795   }
5796   case ISD::EXTRACT_VECTOR_ELT:
5797     assert(VT.getSizeInBits() >= N1.getValueType().getScalarSizeInBits() &&
5798            "The result of EXTRACT_VECTOR_ELT must be at least as wide as the \
5799              element type of the vector.");
5800 
5801     // Extract from an undefined value or using an undefined index is undefined.
5802     if (N1.isUndef() || N2.isUndef())
5803       return getUNDEF(VT);
5804 
5805     // EXTRACT_VECTOR_ELT of out-of-bounds element is an UNDEF for fixed length
5806     // vectors. For scalable vectors we will provide appropriate support for
5807     // dealing with arbitrary indices.
5808     if (N2C && N1.getValueType().isFixedLengthVector() &&
5809         N2C->getAPIntValue().uge(N1.getValueType().getVectorNumElements()))
5810       return getUNDEF(VT);
5811 
5812     // EXTRACT_VECTOR_ELT of CONCAT_VECTORS is often formed while lowering is
5813     // expanding copies of large vectors from registers. This only works for
5814     // fixed length vectors, since we need to know the exact number of
5815     // elements.
5816     if (N2C && N1.getOperand(0).getValueType().isFixedLengthVector() &&
5817         N1.getOpcode() == ISD::CONCAT_VECTORS && N1.getNumOperands() > 0) {
5818       unsigned Factor =
5819         N1.getOperand(0).getValueType().getVectorNumElements();
5820       return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
5821                      N1.getOperand(N2C->getZExtValue() / Factor),
5822                      getVectorIdxConstant(N2C->getZExtValue() % Factor, DL));
5823     }
5824 
5825     // EXTRACT_VECTOR_ELT of BUILD_VECTOR or SPLAT_VECTOR is often formed while
5826     // lowering is expanding large vector constants.
5827     if (N2C && (N1.getOpcode() == ISD::BUILD_VECTOR ||
5828                 N1.getOpcode() == ISD::SPLAT_VECTOR)) {
5829       assert((N1.getOpcode() != ISD::BUILD_VECTOR ||
5830               N1.getValueType().isFixedLengthVector()) &&
5831              "BUILD_VECTOR used for scalable vectors");
5832       unsigned Index =
5833           N1.getOpcode() == ISD::BUILD_VECTOR ? N2C->getZExtValue() : 0;
5834       SDValue Elt = N1.getOperand(Index);
5835 
5836       if (VT != Elt.getValueType())
5837         // If the vector element type is not legal, the BUILD_VECTOR operands
5838         // are promoted and implicitly truncated, and the result implicitly
5839         // extended. Make that explicit here.
5840         Elt = getAnyExtOrTrunc(Elt, DL, VT);
5841 
5842       return Elt;
5843     }
5844 
5845     // EXTRACT_VECTOR_ELT of INSERT_VECTOR_ELT is often formed when vector
5846     // operations are lowered to scalars.
5847     if (N1.getOpcode() == ISD::INSERT_VECTOR_ELT) {
5848       // If the indices are the same, return the inserted element else
5849       // if the indices are known different, extract the element from
5850       // the original vector.
5851       SDValue N1Op2 = N1.getOperand(2);
5852       ConstantSDNode *N1Op2C = dyn_cast<ConstantSDNode>(N1Op2);
5853 
5854       if (N1Op2C && N2C) {
5855         if (N1Op2C->getZExtValue() == N2C->getZExtValue()) {
5856           if (VT == N1.getOperand(1).getValueType())
5857             return N1.getOperand(1);
5858           return getSExtOrTrunc(N1.getOperand(1), DL, VT);
5859         }
5860         return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0), N2);
5861       }
5862     }
5863 
5864     // EXTRACT_VECTOR_ELT of v1iX EXTRACT_SUBVECTOR could be formed
5865     // when vector types are scalarized and v1iX is legal.
5866     // vextract (v1iX extract_subvector(vNiX, Idx)) -> vextract(vNiX,Idx).
5867     // Here we are completely ignoring the extract element index (N2),
5868     // which is fine for fixed width vectors, since any index other than 0
5869     // is undefined anyway. However, this cannot be ignored for scalable
5870     // vectors - in theory we could support this, but we don't want to do this
5871     // without a profitability check.
5872     if (N1.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
5873         N1.getValueType().isFixedLengthVector() &&
5874         N1.getValueType().getVectorNumElements() == 1) {
5875       return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0),
5876                      N1.getOperand(1));
5877     }
5878     break;
5879   case ISD::EXTRACT_ELEMENT:
5880     assert(N2C && (unsigned)N2C->getZExtValue() < 2 && "Bad EXTRACT_ELEMENT!");
5881     assert(!N1.getValueType().isVector() && !VT.isVector() &&
5882            (N1.getValueType().isInteger() == VT.isInteger()) &&
5883            N1.getValueType() != VT &&
5884            "Wrong types for EXTRACT_ELEMENT!");
5885 
5886     // EXTRACT_ELEMENT of BUILD_PAIR is often formed while legalize is expanding
5887     // 64-bit integers into 32-bit parts.  Instead of building the extract of
5888     // the BUILD_PAIR, only to have legalize rip it apart, just do it now.
5889     if (N1.getOpcode() == ISD::BUILD_PAIR)
5890       return N1.getOperand(N2C->getZExtValue());
5891 
5892     // EXTRACT_ELEMENT of a constant int is also very common.
5893     if (N1C) {
5894       unsigned ElementSize = VT.getSizeInBits();
5895       unsigned Shift = ElementSize * N2C->getZExtValue();
5896       const APInt &Val = N1C->getAPIntValue();
5897       return getConstant(Val.extractBits(ElementSize, Shift), DL, VT);
5898     }
5899     break;
5900   case ISD::EXTRACT_SUBVECTOR: {
5901     EVT N1VT = N1.getValueType();
5902     assert(VT.isVector() && N1VT.isVector() &&
5903            "Extract subvector VTs must be vectors!");
5904     assert(VT.getVectorElementType() == N1VT.getVectorElementType() &&
5905            "Extract subvector VTs must have the same element type!");
5906     assert((VT.isFixedLengthVector() || N1VT.isScalableVector()) &&
5907            "Cannot extract a scalable vector from a fixed length vector!");
5908     assert((VT.isScalableVector() != N1VT.isScalableVector() ||
5909             VT.getVectorMinNumElements() <= N1VT.getVectorMinNumElements()) &&
5910            "Extract subvector must be from larger vector to smaller vector!");
5911     assert(N2C && "Extract subvector index must be a constant");
5912     assert((VT.isScalableVector() != N1VT.isScalableVector() ||
5913             (VT.getVectorMinNumElements() + N2C->getZExtValue()) <=
5914                 N1VT.getVectorMinNumElements()) &&
5915            "Extract subvector overflow!");
5916     assert(N2C->getAPIntValue().getBitWidth() ==
5917                TLI->getVectorIdxTy(getDataLayout()).getFixedSizeInBits() &&
5918            "Constant index for EXTRACT_SUBVECTOR has an invalid size");
5919 
5920     // Trivial extraction.
5921     if (VT == N1VT)
5922       return N1;
5923 
5924     // EXTRACT_SUBVECTOR of an UNDEF is an UNDEF.
5925     if (N1.isUndef())
5926       return getUNDEF(VT);
5927 
5928     // EXTRACT_SUBVECTOR of CONCAT_VECTOR can be simplified if the pieces of
5929     // the concat have the same type as the extract.
5930     if (N1.getOpcode() == ISD::CONCAT_VECTORS && N1.getNumOperands() > 0 &&
5931         VT == N1.getOperand(0).getValueType()) {
5932       unsigned Factor = VT.getVectorMinNumElements();
5933       return N1.getOperand(N2C->getZExtValue() / Factor);
5934     }
5935 
5936     // EXTRACT_SUBVECTOR of INSERT_SUBVECTOR is often created
5937     // during shuffle legalization.
5938     if (N1.getOpcode() == ISD::INSERT_SUBVECTOR && N2 == N1.getOperand(2) &&
5939         VT == N1.getOperand(1).getValueType())
5940       return N1.getOperand(1);
5941     break;
5942   }
5943   }
5944 
5945   // Perform trivial constant folding.
5946   if (SDValue SV = FoldConstantArithmetic(Opcode, DL, VT, {N1, N2}))
5947     return SV;
5948 
5949   if (SDValue V = foldConstantFPMath(Opcode, DL, VT, N1, N2))
5950     return V;
5951 
5952   // Canonicalize an UNDEF to the RHS, even over a constant.
5953   if (N1.isUndef()) {
5954     if (TLI->isCommutativeBinOp(Opcode)) {
5955       std::swap(N1, N2);
5956     } else {
5957       switch (Opcode) {
5958       case ISD::SIGN_EXTEND_INREG:
5959       case ISD::SUB:
5960         return getUNDEF(VT);     // fold op(undef, arg2) -> undef
5961       case ISD::UDIV:
5962       case ISD::SDIV:
5963       case ISD::UREM:
5964       case ISD::SREM:
5965       case ISD::SSUBSAT:
5966       case ISD::USUBSAT:
5967         return getConstant(0, DL, VT);    // fold op(undef, arg2) -> 0
5968       }
5969     }
5970   }
5971 
5972   // Fold a bunch of operators when the RHS is undef.
5973   if (N2.isUndef()) {
5974     switch (Opcode) {
5975     case ISD::XOR:
5976       if (N1.isUndef())
5977         // Handle undef ^ undef -> 0 special case. This is a common
5978         // idiom (misuse).
5979         return getConstant(0, DL, VT);
5980       LLVM_FALLTHROUGH;
5981     case ISD::ADD:
5982     case ISD::SUB:
5983     case ISD::UDIV:
5984     case ISD::SDIV:
5985     case ISD::UREM:
5986     case ISD::SREM:
5987       return getUNDEF(VT);       // fold op(arg1, undef) -> undef
5988     case ISD::MUL:
5989     case ISD::AND:
5990     case ISD::SSUBSAT:
5991     case ISD::USUBSAT:
5992       return getConstant(0, DL, VT);  // fold op(arg1, undef) -> 0
5993     case ISD::OR:
5994     case ISD::SADDSAT:
5995     case ISD::UADDSAT:
5996       return getAllOnesConstant(DL, VT);
5997     }
5998   }
5999 
6000   // Memoize this node if possible.
6001   SDNode *N;
6002   SDVTList VTs = getVTList(VT);
6003   SDValue Ops[] = {N1, N2};
6004   if (VT != MVT::Glue) {
6005     FoldingSetNodeID ID;
6006     AddNodeIDNode(ID, Opcode, VTs, Ops);
6007     void *IP = nullptr;
6008     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
6009       E->intersectFlagsWith(Flags);
6010       return SDValue(E, 0);
6011     }
6012 
6013     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
6014     N->setFlags(Flags);
6015     createOperands(N, Ops);
6016     CSEMap.InsertNode(N, IP);
6017   } else {
6018     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
6019     createOperands(N, Ops);
6020   }
6021 
6022   InsertNode(N);
6023   SDValue V = SDValue(N, 0);
6024   NewSDValueDbgMsg(V, "Creating new node: ", this);
6025   return V;
6026 }
6027 
6028 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
6029                               SDValue N1, SDValue N2, SDValue N3) {
6030   SDNodeFlags Flags;
6031   if (Inserter)
6032     Flags = Inserter->getFlags();
6033   return getNode(Opcode, DL, VT, N1, N2, N3, Flags);
6034 }
6035 
6036 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
6037                               SDValue N1, SDValue N2, SDValue N3,
6038                               const SDNodeFlags Flags) {
6039   assert(N1.getOpcode() != ISD::DELETED_NODE &&
6040          N2.getOpcode() != ISD::DELETED_NODE &&
6041          N3.getOpcode() != ISD::DELETED_NODE &&
6042          "Operand is DELETED_NODE!");
6043   // Perform various simplifications.
6044   switch (Opcode) {
6045   case ISD::FMA: {
6046     assert(VT.isFloatingPoint() && "This operator only applies to FP types!");
6047     assert(N1.getValueType() == VT && N2.getValueType() == VT &&
6048            N3.getValueType() == VT && "FMA types must match!");
6049     ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6050     ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2);
6051     ConstantFPSDNode *N3CFP = dyn_cast<ConstantFPSDNode>(N3);
6052     if (N1CFP && N2CFP && N3CFP) {
6053       APFloat  V1 = N1CFP->getValueAPF();
6054       const APFloat &V2 = N2CFP->getValueAPF();
6055       const APFloat &V3 = N3CFP->getValueAPF();
6056       V1.fusedMultiplyAdd(V2, V3, APFloat::rmNearestTiesToEven);
6057       return getConstantFP(V1, DL, VT);
6058     }
6059     break;
6060   }
6061   case ISD::BUILD_VECTOR: {
6062     // Attempt to simplify BUILD_VECTOR.
6063     SDValue Ops[] = {N1, N2, N3};
6064     if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
6065       return V;
6066     break;
6067   }
6068   case ISD::CONCAT_VECTORS: {
6069     SDValue Ops[] = {N1, N2, N3};
6070     if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this))
6071       return V;
6072     break;
6073   }
6074   case ISD::SETCC: {
6075     assert(VT.isInteger() && "SETCC result type must be an integer!");
6076     assert(N1.getValueType() == N2.getValueType() &&
6077            "SETCC operands must have the same type!");
6078     assert(VT.isVector() == N1.getValueType().isVector() &&
6079            "SETCC type should be vector iff the operand type is vector!");
6080     assert((!VT.isVector() || VT.getVectorElementCount() ==
6081                                   N1.getValueType().getVectorElementCount()) &&
6082            "SETCC vector element counts must match!");
6083     // Use FoldSetCC to simplify SETCC's.
6084     if (SDValue V = FoldSetCC(VT, N1, N2, cast<CondCodeSDNode>(N3)->get(), DL))
6085       return V;
6086     // Vector constant folding.
6087     SDValue Ops[] = {N1, N2, N3};
6088     if (SDValue V = FoldConstantArithmetic(Opcode, DL, VT, Ops)) {
6089       NewSDValueDbgMsg(V, "New node vector constant folding: ", this);
6090       return V;
6091     }
6092     break;
6093   }
6094   case ISD::SELECT:
6095   case ISD::VSELECT:
6096     if (SDValue V = simplifySelect(N1, N2, N3))
6097       return V;
6098     break;
6099   case ISD::VECTOR_SHUFFLE:
6100     llvm_unreachable("should use getVectorShuffle constructor!");
6101   case ISD::VECTOR_SPLICE: {
6102     if (cast<ConstantSDNode>(N3)->isNullValue())
6103       return N1;
6104     break;
6105   }
6106   case ISD::INSERT_VECTOR_ELT: {
6107     ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3);
6108     // INSERT_VECTOR_ELT into out-of-bounds element is an UNDEF, except
6109     // for scalable vectors where we will generate appropriate code to
6110     // deal with out-of-bounds cases correctly.
6111     if (N3C && N1.getValueType().isFixedLengthVector() &&
6112         N3C->getZExtValue() >= N1.getValueType().getVectorNumElements())
6113       return getUNDEF(VT);
6114 
6115     // Undefined index can be assumed out-of-bounds, so that's UNDEF too.
6116     if (N3.isUndef())
6117       return getUNDEF(VT);
6118 
6119     // If the inserted element is an UNDEF, just use the input vector.
6120     if (N2.isUndef())
6121       return N1;
6122 
6123     break;
6124   }
6125   case ISD::INSERT_SUBVECTOR: {
6126     // Inserting undef into undef is still undef.
6127     if (N1.isUndef() && N2.isUndef())
6128       return getUNDEF(VT);
6129 
6130     EVT N2VT = N2.getValueType();
6131     assert(VT == N1.getValueType() &&
6132            "Dest and insert subvector source types must match!");
6133     assert(VT.isVector() && N2VT.isVector() &&
6134            "Insert subvector VTs must be vectors!");
6135     assert((VT.isScalableVector() || N2VT.isFixedLengthVector()) &&
6136            "Cannot insert a scalable vector into a fixed length vector!");
6137     assert((VT.isScalableVector() != N2VT.isScalableVector() ||
6138             VT.getVectorMinNumElements() >= N2VT.getVectorMinNumElements()) &&
6139            "Insert subvector must be from smaller vector to larger vector!");
6140     assert(isa<ConstantSDNode>(N3) &&
6141            "Insert subvector index must be constant");
6142     assert((VT.isScalableVector() != N2VT.isScalableVector() ||
6143             (N2VT.getVectorMinNumElements() +
6144              cast<ConstantSDNode>(N3)->getZExtValue()) <=
6145                 VT.getVectorMinNumElements()) &&
6146            "Insert subvector overflow!");
6147     assert(cast<ConstantSDNode>(N3)->getAPIntValue().getBitWidth() ==
6148                TLI->getVectorIdxTy(getDataLayout()).getFixedSizeInBits() &&
6149            "Constant index for INSERT_SUBVECTOR has an invalid size");
6150 
6151     // Trivial insertion.
6152     if (VT == N2VT)
6153       return N2;
6154 
6155     // If this is an insert of an extracted vector into an undef vector, we
6156     // can just use the input to the extract.
6157     if (N1.isUndef() && N2.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
6158         N2.getOperand(1) == N3 && N2.getOperand(0).getValueType() == VT)
6159       return N2.getOperand(0);
6160     break;
6161   }
6162   case ISD::BITCAST:
6163     // Fold bit_convert nodes from a type to themselves.
6164     if (N1.getValueType() == VT)
6165       return N1;
6166     break;
6167   }
6168 
6169   // Memoize node if it doesn't produce a flag.
6170   SDNode *N;
6171   SDVTList VTs = getVTList(VT);
6172   SDValue Ops[] = {N1, N2, N3};
6173   if (VT != MVT::Glue) {
6174     FoldingSetNodeID ID;
6175     AddNodeIDNode(ID, Opcode, VTs, Ops);
6176     void *IP = nullptr;
6177     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
6178       E->intersectFlagsWith(Flags);
6179       return SDValue(E, 0);
6180     }
6181 
6182     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
6183     N->setFlags(Flags);
6184     createOperands(N, Ops);
6185     CSEMap.InsertNode(N, IP);
6186   } else {
6187     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
6188     createOperands(N, Ops);
6189   }
6190 
6191   InsertNode(N);
6192   SDValue V = SDValue(N, 0);
6193   NewSDValueDbgMsg(V, "Creating new node: ", this);
6194   return V;
6195 }
6196 
6197 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
6198                               SDValue N1, SDValue N2, SDValue N3, SDValue N4) {
6199   SDValue Ops[] = { N1, N2, N3, N4 };
6200   return getNode(Opcode, DL, VT, Ops);
6201 }
6202 
6203 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
6204                               SDValue N1, SDValue N2, SDValue N3, SDValue N4,
6205                               SDValue N5) {
6206   SDValue Ops[] = { N1, N2, N3, N4, N5 };
6207   return getNode(Opcode, DL, VT, Ops);
6208 }
6209 
6210 /// getStackArgumentTokenFactor - Compute a TokenFactor to force all
6211 /// the incoming stack arguments to be loaded from the stack.
6212 SDValue SelectionDAG::getStackArgumentTokenFactor(SDValue Chain) {
6213   SmallVector<SDValue, 8> ArgChains;
6214 
6215   // Include the original chain at the beginning of the list. When this is
6216   // used by target LowerCall hooks, this helps legalize find the
6217   // CALLSEQ_BEGIN node.
6218   ArgChains.push_back(Chain);
6219 
6220   // Add a chain value for each stack argument.
6221   for (SDNode::use_iterator U = getEntryNode().getNode()->use_begin(),
6222        UE = getEntryNode().getNode()->use_end(); U != UE; ++U)
6223     if (LoadSDNode *L = dyn_cast<LoadSDNode>(*U))
6224       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
6225         if (FI->getIndex() < 0)
6226           ArgChains.push_back(SDValue(L, 1));
6227 
6228   // Build a tokenfactor for all the chains.
6229   return getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains);
6230 }
6231 
6232 /// getMemsetValue - Vectorized representation of the memset value
6233 /// operand.
6234 static SDValue getMemsetValue(SDValue Value, EVT VT, SelectionDAG &DAG,
6235                               const SDLoc &dl) {
6236   assert(!Value.isUndef());
6237 
6238   unsigned NumBits = VT.getScalarSizeInBits();
6239   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
6240     assert(C->getAPIntValue().getBitWidth() == 8);
6241     APInt Val = APInt::getSplat(NumBits, C->getAPIntValue());
6242     if (VT.isInteger()) {
6243       bool IsOpaque = VT.getSizeInBits() > 64 ||
6244           !DAG.getTargetLoweringInfo().isLegalStoreImmediate(C->getSExtValue());
6245       return DAG.getConstant(Val, dl, VT, false, IsOpaque);
6246     }
6247     return DAG.getConstantFP(APFloat(DAG.EVTToAPFloatSemantics(VT), Val), dl,
6248                              VT);
6249   }
6250 
6251   assert(Value.getValueType() == MVT::i8 && "memset with non-byte fill value?");
6252   EVT IntVT = VT.getScalarType();
6253   if (!IntVT.isInteger())
6254     IntVT = EVT::getIntegerVT(*DAG.getContext(), IntVT.getSizeInBits());
6255 
6256   Value = DAG.getNode(ISD::ZERO_EXTEND, dl, IntVT, Value);
6257   if (NumBits > 8) {
6258     // Use a multiplication with 0x010101... to extend the input to the
6259     // required length.
6260     APInt Magic = APInt::getSplat(NumBits, APInt(8, 0x01));
6261     Value = DAG.getNode(ISD::MUL, dl, IntVT, Value,
6262                         DAG.getConstant(Magic, dl, IntVT));
6263   }
6264 
6265   if (VT != Value.getValueType() && !VT.isInteger())
6266     Value = DAG.getBitcast(VT.getScalarType(), Value);
6267   if (VT != Value.getValueType())
6268     Value = DAG.getSplatBuildVector(VT, dl, Value);
6269 
6270   return Value;
6271 }
6272 
6273 /// getMemsetStringVal - Similar to getMemsetValue. Except this is only
6274 /// used when a memcpy is turned into a memset when the source is a constant
6275 /// string ptr.
6276 static SDValue getMemsetStringVal(EVT VT, const SDLoc &dl, SelectionDAG &DAG,
6277                                   const TargetLowering &TLI,
6278                                   const ConstantDataArraySlice &Slice) {
6279   // Handle vector with all elements zero.
6280   if (Slice.Array == nullptr) {
6281     if (VT.isInteger())
6282       return DAG.getConstant(0, dl, VT);
6283     if (VT == MVT::f32 || VT == MVT::f64 || VT == MVT::f128)
6284       return DAG.getConstantFP(0.0, dl, VT);
6285     if (VT.isVector()) {
6286       unsigned NumElts = VT.getVectorNumElements();
6287       MVT EltVT = (VT.getVectorElementType() == MVT::f32) ? MVT::i32 : MVT::i64;
6288       return DAG.getNode(ISD::BITCAST, dl, VT,
6289                          DAG.getConstant(0, dl,
6290                                          EVT::getVectorVT(*DAG.getContext(),
6291                                                           EltVT, NumElts)));
6292     }
6293     llvm_unreachable("Expected type!");
6294   }
6295 
6296   assert(!VT.isVector() && "Can't handle vector type here!");
6297   unsigned NumVTBits = VT.getSizeInBits();
6298   unsigned NumVTBytes = NumVTBits / 8;
6299   unsigned NumBytes = std::min(NumVTBytes, unsigned(Slice.Length));
6300 
6301   APInt Val(NumVTBits, 0);
6302   if (DAG.getDataLayout().isLittleEndian()) {
6303     for (unsigned i = 0; i != NumBytes; ++i)
6304       Val |= (uint64_t)(unsigned char)Slice[i] << i*8;
6305   } else {
6306     for (unsigned i = 0; i != NumBytes; ++i)
6307       Val |= (uint64_t)(unsigned char)Slice[i] << (NumVTBytes-i-1)*8;
6308   }
6309 
6310   // If the "cost" of materializing the integer immediate is less than the cost
6311   // of a load, then it is cost effective to turn the load into the immediate.
6312   Type *Ty = VT.getTypeForEVT(*DAG.getContext());
6313   if (TLI.shouldConvertConstantLoadToIntImm(Val, Ty))
6314     return DAG.getConstant(Val, dl, VT);
6315   return SDValue(nullptr, 0);
6316 }
6317 
6318 SDValue SelectionDAG::getMemBasePlusOffset(SDValue Base, TypeSize Offset,
6319                                            const SDLoc &DL,
6320                                            const SDNodeFlags Flags) {
6321   EVT VT = Base.getValueType();
6322   SDValue Index;
6323 
6324   if (Offset.isScalable())
6325     Index = getVScale(DL, Base.getValueType(),
6326                       APInt(Base.getValueSizeInBits().getFixedSize(),
6327                             Offset.getKnownMinSize()));
6328   else
6329     Index = getConstant(Offset.getFixedSize(), DL, VT);
6330 
6331   return getMemBasePlusOffset(Base, Index, DL, Flags);
6332 }
6333 
6334 SDValue SelectionDAG::getMemBasePlusOffset(SDValue Ptr, SDValue Offset,
6335                                            const SDLoc &DL,
6336                                            const SDNodeFlags Flags) {
6337   assert(Offset.getValueType().isInteger());
6338   EVT BasePtrVT = Ptr.getValueType();
6339   return getNode(ISD::ADD, DL, BasePtrVT, Ptr, Offset, Flags);
6340 }
6341 
6342 /// Returns true if memcpy source is constant data.
6343 static bool isMemSrcFromConstant(SDValue Src, ConstantDataArraySlice &Slice) {
6344   uint64_t SrcDelta = 0;
6345   GlobalAddressSDNode *G = nullptr;
6346   if (Src.getOpcode() == ISD::GlobalAddress)
6347     G = cast<GlobalAddressSDNode>(Src);
6348   else if (Src.getOpcode() == ISD::ADD &&
6349            Src.getOperand(0).getOpcode() == ISD::GlobalAddress &&
6350            Src.getOperand(1).getOpcode() == ISD::Constant) {
6351     G = cast<GlobalAddressSDNode>(Src.getOperand(0));
6352     SrcDelta = cast<ConstantSDNode>(Src.getOperand(1))->getZExtValue();
6353   }
6354   if (!G)
6355     return false;
6356 
6357   return getConstantDataArrayInfo(G->getGlobal(), Slice, 8,
6358                                   SrcDelta + G->getOffset());
6359 }
6360 
6361 static bool shouldLowerMemFuncForSize(const MachineFunction &MF,
6362                                       SelectionDAG &DAG) {
6363   // On Darwin, -Os means optimize for size without hurting performance, so
6364   // only really optimize for size when -Oz (MinSize) is used.
6365   if (MF.getTarget().getTargetTriple().isOSDarwin())
6366     return MF.getFunction().hasMinSize();
6367   return DAG.shouldOptForSize();
6368 }
6369 
6370 static void chainLoadsAndStoresForMemcpy(SelectionDAG &DAG, const SDLoc &dl,
6371                           SmallVector<SDValue, 32> &OutChains, unsigned From,
6372                           unsigned To, SmallVector<SDValue, 16> &OutLoadChains,
6373                           SmallVector<SDValue, 16> &OutStoreChains) {
6374   assert(OutLoadChains.size() && "Missing loads in memcpy inlining");
6375   assert(OutStoreChains.size() && "Missing stores in memcpy inlining");
6376   SmallVector<SDValue, 16> GluedLoadChains;
6377   for (unsigned i = From; i < To; ++i) {
6378     OutChains.push_back(OutLoadChains[i]);
6379     GluedLoadChains.push_back(OutLoadChains[i]);
6380   }
6381 
6382   // Chain for all loads.
6383   SDValue LoadToken = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
6384                                   GluedLoadChains);
6385 
6386   for (unsigned i = From; i < To; ++i) {
6387     StoreSDNode *ST = dyn_cast<StoreSDNode>(OutStoreChains[i]);
6388     SDValue NewStore = DAG.getTruncStore(LoadToken, dl, ST->getValue(),
6389                                   ST->getBasePtr(), ST->getMemoryVT(),
6390                                   ST->getMemOperand());
6391     OutChains.push_back(NewStore);
6392   }
6393 }
6394 
6395 static SDValue getMemcpyLoadsAndStores(SelectionDAG &DAG, const SDLoc &dl,
6396                                        SDValue Chain, SDValue Dst, SDValue Src,
6397                                        uint64_t Size, Align Alignment,
6398                                        bool isVol, bool AlwaysInline,
6399                                        MachinePointerInfo DstPtrInfo,
6400                                        MachinePointerInfo SrcPtrInfo,
6401                                        const AAMDNodes &AAInfo) {
6402   // Turn a memcpy of undef to nop.
6403   // FIXME: We need to honor volatile even is Src is undef.
6404   if (Src.isUndef())
6405     return Chain;
6406 
6407   // Expand memcpy to a series of load and store ops if the size operand falls
6408   // below a certain threshold.
6409   // TODO: In the AlwaysInline case, if the size is big then generate a loop
6410   // rather than maybe a humongous number of loads and stores.
6411   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6412   const DataLayout &DL = DAG.getDataLayout();
6413   LLVMContext &C = *DAG.getContext();
6414   std::vector<EVT> MemOps;
6415   bool DstAlignCanChange = false;
6416   MachineFunction &MF = DAG.getMachineFunction();
6417   MachineFrameInfo &MFI = MF.getFrameInfo();
6418   bool OptSize = shouldLowerMemFuncForSize(MF, DAG);
6419   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
6420   if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
6421     DstAlignCanChange = true;
6422   MaybeAlign SrcAlign = DAG.InferPtrAlign(Src);
6423   if (!SrcAlign || Alignment > *SrcAlign)
6424     SrcAlign = Alignment;
6425   assert(SrcAlign && "SrcAlign must be set");
6426   ConstantDataArraySlice Slice;
6427   // If marked as volatile, perform a copy even when marked as constant.
6428   bool CopyFromConstant = !isVol && isMemSrcFromConstant(Src, Slice);
6429   bool isZeroConstant = CopyFromConstant && Slice.Array == nullptr;
6430   unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemcpy(OptSize);
6431   const MemOp Op = isZeroConstant
6432                        ? MemOp::Set(Size, DstAlignCanChange, Alignment,
6433                                     /*IsZeroMemset*/ true, isVol)
6434                        : MemOp::Copy(Size, DstAlignCanChange, Alignment,
6435                                      *SrcAlign, isVol, CopyFromConstant);
6436   if (!TLI.findOptimalMemOpLowering(
6437           MemOps, Limit, Op, DstPtrInfo.getAddrSpace(),
6438           SrcPtrInfo.getAddrSpace(), MF.getFunction().getAttributes()))
6439     return SDValue();
6440 
6441   if (DstAlignCanChange) {
6442     Type *Ty = MemOps[0].getTypeForEVT(C);
6443     Align NewAlign = DL.getABITypeAlign(Ty);
6444 
6445     // Don't promote to an alignment that would require dynamic stack
6446     // realignment.
6447     const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
6448     if (!TRI->hasStackRealignment(MF))
6449       while (NewAlign > Alignment && DL.exceedsNaturalStackAlignment(NewAlign))
6450         NewAlign = NewAlign / 2;
6451 
6452     if (NewAlign > Alignment) {
6453       // Give the stack frame object a larger alignment if needed.
6454       if (MFI.getObjectAlign(FI->getIndex()) < NewAlign)
6455         MFI.setObjectAlignment(FI->getIndex(), NewAlign);
6456       Alignment = NewAlign;
6457     }
6458   }
6459 
6460   // Prepare AAInfo for loads/stores after lowering this memcpy.
6461   AAMDNodes NewAAInfo = AAInfo;
6462   NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr;
6463 
6464   MachineMemOperand::Flags MMOFlags =
6465       isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone;
6466   SmallVector<SDValue, 16> OutLoadChains;
6467   SmallVector<SDValue, 16> OutStoreChains;
6468   SmallVector<SDValue, 32> OutChains;
6469   unsigned NumMemOps = MemOps.size();
6470   uint64_t SrcOff = 0, DstOff = 0;
6471   for (unsigned i = 0; i != NumMemOps; ++i) {
6472     EVT VT = MemOps[i];
6473     unsigned VTSize = VT.getSizeInBits() / 8;
6474     SDValue Value, Store;
6475 
6476     if (VTSize > Size) {
6477       // Issuing an unaligned load / store pair  that overlaps with the previous
6478       // pair. Adjust the offset accordingly.
6479       assert(i == NumMemOps-1 && i != 0);
6480       SrcOff -= VTSize - Size;
6481       DstOff -= VTSize - Size;
6482     }
6483 
6484     if (CopyFromConstant &&
6485         (isZeroConstant || (VT.isInteger() && !VT.isVector()))) {
6486       // It's unlikely a store of a vector immediate can be done in a single
6487       // instruction. It would require a load from a constantpool first.
6488       // We only handle zero vectors here.
6489       // FIXME: Handle other cases where store of vector immediate is done in
6490       // a single instruction.
6491       ConstantDataArraySlice SubSlice;
6492       if (SrcOff < Slice.Length) {
6493         SubSlice = Slice;
6494         SubSlice.move(SrcOff);
6495       } else {
6496         // This is an out-of-bounds access and hence UB. Pretend we read zero.
6497         SubSlice.Array = nullptr;
6498         SubSlice.Offset = 0;
6499         SubSlice.Length = VTSize;
6500       }
6501       Value = getMemsetStringVal(VT, dl, DAG, TLI, SubSlice);
6502       if (Value.getNode()) {
6503         Store = DAG.getStore(
6504             Chain, dl, Value,
6505             DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl),
6506             DstPtrInfo.getWithOffset(DstOff), Alignment, MMOFlags, NewAAInfo);
6507         OutChains.push_back(Store);
6508       }
6509     }
6510 
6511     if (!Store.getNode()) {
6512       // The type might not be legal for the target.  This should only happen
6513       // if the type is smaller than a legal type, as on PPC, so the right
6514       // thing to do is generate a LoadExt/StoreTrunc pair.  These simplify
6515       // to Load/Store if NVT==VT.
6516       // FIXME does the case above also need this?
6517       EVT NVT = TLI.getTypeToTransformTo(C, VT);
6518       assert(NVT.bitsGE(VT));
6519 
6520       bool isDereferenceable =
6521         SrcPtrInfo.getWithOffset(SrcOff).isDereferenceable(VTSize, C, DL);
6522       MachineMemOperand::Flags SrcMMOFlags = MMOFlags;
6523       if (isDereferenceable)
6524         SrcMMOFlags |= MachineMemOperand::MODereferenceable;
6525 
6526       Value = DAG.getExtLoad(
6527           ISD::EXTLOAD, dl, NVT, Chain,
6528           DAG.getMemBasePlusOffset(Src, TypeSize::Fixed(SrcOff), dl),
6529           SrcPtrInfo.getWithOffset(SrcOff), VT,
6530           commonAlignment(*SrcAlign, SrcOff), SrcMMOFlags, NewAAInfo);
6531       OutLoadChains.push_back(Value.getValue(1));
6532 
6533       Store = DAG.getTruncStore(
6534           Chain, dl, Value,
6535           DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl),
6536           DstPtrInfo.getWithOffset(DstOff), VT, Alignment, MMOFlags, NewAAInfo);
6537       OutStoreChains.push_back(Store);
6538     }
6539     SrcOff += VTSize;
6540     DstOff += VTSize;
6541     Size -= VTSize;
6542   }
6543 
6544   unsigned GluedLdStLimit = MaxLdStGlue == 0 ?
6545                                 TLI.getMaxGluedStoresPerMemcpy() : MaxLdStGlue;
6546   unsigned NumLdStInMemcpy = OutStoreChains.size();
6547 
6548   if (NumLdStInMemcpy) {
6549     // It may be that memcpy might be converted to memset if it's memcpy
6550     // of constants. In such a case, we won't have loads and stores, but
6551     // just stores. In the absence of loads, there is nothing to gang up.
6552     if ((GluedLdStLimit <= 1) || !EnableMemCpyDAGOpt) {
6553       // If target does not care, just leave as it.
6554       for (unsigned i = 0; i < NumLdStInMemcpy; ++i) {
6555         OutChains.push_back(OutLoadChains[i]);
6556         OutChains.push_back(OutStoreChains[i]);
6557       }
6558     } else {
6559       // Ld/St less than/equal limit set by target.
6560       if (NumLdStInMemcpy <= GluedLdStLimit) {
6561           chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, 0,
6562                                         NumLdStInMemcpy, OutLoadChains,
6563                                         OutStoreChains);
6564       } else {
6565         unsigned NumberLdChain =  NumLdStInMemcpy / GluedLdStLimit;
6566         unsigned RemainingLdStInMemcpy = NumLdStInMemcpy % GluedLdStLimit;
6567         unsigned GlueIter = 0;
6568 
6569         for (unsigned cnt = 0; cnt < NumberLdChain; ++cnt) {
6570           unsigned IndexFrom = NumLdStInMemcpy - GlueIter - GluedLdStLimit;
6571           unsigned IndexTo   = NumLdStInMemcpy - GlueIter;
6572 
6573           chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, IndexFrom, IndexTo,
6574                                        OutLoadChains, OutStoreChains);
6575           GlueIter += GluedLdStLimit;
6576         }
6577 
6578         // Residual ld/st.
6579         if (RemainingLdStInMemcpy) {
6580           chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, 0,
6581                                         RemainingLdStInMemcpy, OutLoadChains,
6582                                         OutStoreChains);
6583         }
6584       }
6585     }
6586   }
6587   return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
6588 }
6589 
6590 static SDValue getMemmoveLoadsAndStores(SelectionDAG &DAG, const SDLoc &dl,
6591                                         SDValue Chain, SDValue Dst, SDValue Src,
6592                                         uint64_t Size, Align Alignment,
6593                                         bool isVol, bool AlwaysInline,
6594                                         MachinePointerInfo DstPtrInfo,
6595                                         MachinePointerInfo SrcPtrInfo,
6596                                         const AAMDNodes &AAInfo) {
6597   // Turn a memmove of undef to nop.
6598   // FIXME: We need to honor volatile even is Src is undef.
6599   if (Src.isUndef())
6600     return Chain;
6601 
6602   // Expand memmove to a series of load and store ops if the size operand falls
6603   // below a certain threshold.
6604   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6605   const DataLayout &DL = DAG.getDataLayout();
6606   LLVMContext &C = *DAG.getContext();
6607   std::vector<EVT> MemOps;
6608   bool DstAlignCanChange = false;
6609   MachineFunction &MF = DAG.getMachineFunction();
6610   MachineFrameInfo &MFI = MF.getFrameInfo();
6611   bool OptSize = shouldLowerMemFuncForSize(MF, DAG);
6612   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
6613   if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
6614     DstAlignCanChange = true;
6615   MaybeAlign SrcAlign = DAG.InferPtrAlign(Src);
6616   if (!SrcAlign || Alignment > *SrcAlign)
6617     SrcAlign = Alignment;
6618   assert(SrcAlign && "SrcAlign must be set");
6619   unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemmove(OptSize);
6620   if (!TLI.findOptimalMemOpLowering(
6621           MemOps, Limit,
6622           MemOp::Copy(Size, DstAlignCanChange, Alignment, *SrcAlign,
6623                       /*IsVolatile*/ true),
6624           DstPtrInfo.getAddrSpace(), SrcPtrInfo.getAddrSpace(),
6625           MF.getFunction().getAttributes()))
6626     return SDValue();
6627 
6628   if (DstAlignCanChange) {
6629     Type *Ty = MemOps[0].getTypeForEVT(C);
6630     Align NewAlign = DL.getABITypeAlign(Ty);
6631     if (NewAlign > Alignment) {
6632       // Give the stack frame object a larger alignment if needed.
6633       if (MFI.getObjectAlign(FI->getIndex()) < NewAlign)
6634         MFI.setObjectAlignment(FI->getIndex(), NewAlign);
6635       Alignment = NewAlign;
6636     }
6637   }
6638 
6639   // Prepare AAInfo for loads/stores after lowering this memmove.
6640   AAMDNodes NewAAInfo = AAInfo;
6641   NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr;
6642 
6643   MachineMemOperand::Flags MMOFlags =
6644       isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone;
6645   uint64_t SrcOff = 0, DstOff = 0;
6646   SmallVector<SDValue, 8> LoadValues;
6647   SmallVector<SDValue, 8> LoadChains;
6648   SmallVector<SDValue, 8> OutChains;
6649   unsigned NumMemOps = MemOps.size();
6650   for (unsigned i = 0; i < NumMemOps; i++) {
6651     EVT VT = MemOps[i];
6652     unsigned VTSize = VT.getSizeInBits() / 8;
6653     SDValue Value;
6654 
6655     bool isDereferenceable =
6656       SrcPtrInfo.getWithOffset(SrcOff).isDereferenceable(VTSize, C, DL);
6657     MachineMemOperand::Flags SrcMMOFlags = MMOFlags;
6658     if (isDereferenceable)
6659       SrcMMOFlags |= MachineMemOperand::MODereferenceable;
6660 
6661     Value = DAG.getLoad(
6662         VT, dl, Chain,
6663         DAG.getMemBasePlusOffset(Src, TypeSize::Fixed(SrcOff), dl),
6664         SrcPtrInfo.getWithOffset(SrcOff), *SrcAlign, SrcMMOFlags, NewAAInfo);
6665     LoadValues.push_back(Value);
6666     LoadChains.push_back(Value.getValue(1));
6667     SrcOff += VTSize;
6668   }
6669   Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
6670   OutChains.clear();
6671   for (unsigned i = 0; i < NumMemOps; i++) {
6672     EVT VT = MemOps[i];
6673     unsigned VTSize = VT.getSizeInBits() / 8;
6674     SDValue Store;
6675 
6676     Store = DAG.getStore(
6677         Chain, dl, LoadValues[i],
6678         DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl),
6679         DstPtrInfo.getWithOffset(DstOff), Alignment, MMOFlags, NewAAInfo);
6680     OutChains.push_back(Store);
6681     DstOff += VTSize;
6682   }
6683 
6684   return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
6685 }
6686 
6687 /// Lower the call to 'memset' intrinsic function into a series of store
6688 /// operations.
6689 ///
6690 /// \param DAG Selection DAG where lowered code is placed.
6691 /// \param dl Link to corresponding IR location.
6692 /// \param Chain Control flow dependency.
6693 /// \param Dst Pointer to destination memory location.
6694 /// \param Src Value of byte to write into the memory.
6695 /// \param Size Number of bytes to write.
6696 /// \param Alignment Alignment of the destination in bytes.
6697 /// \param isVol True if destination is volatile.
6698 /// \param DstPtrInfo IR information on the memory pointer.
6699 /// \returns New head in the control flow, if lowering was successful, empty
6700 /// SDValue otherwise.
6701 ///
6702 /// The function tries to replace 'llvm.memset' intrinsic with several store
6703 /// operations and value calculation code. This is usually profitable for small
6704 /// memory size.
6705 static SDValue getMemsetStores(SelectionDAG &DAG, const SDLoc &dl,
6706                                SDValue Chain, SDValue Dst, SDValue Src,
6707                                uint64_t Size, Align Alignment, bool isVol,
6708                                MachinePointerInfo DstPtrInfo,
6709                                const AAMDNodes &AAInfo) {
6710   // Turn a memset of undef to nop.
6711   // FIXME: We need to honor volatile even is Src is undef.
6712   if (Src.isUndef())
6713     return Chain;
6714 
6715   // Expand memset to a series of load/store ops if the size operand
6716   // falls below a certain threshold.
6717   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6718   std::vector<EVT> MemOps;
6719   bool DstAlignCanChange = false;
6720   MachineFunction &MF = DAG.getMachineFunction();
6721   MachineFrameInfo &MFI = MF.getFrameInfo();
6722   bool OptSize = shouldLowerMemFuncForSize(MF, DAG);
6723   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
6724   if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
6725     DstAlignCanChange = true;
6726   bool IsZeroVal =
6727       isa<ConstantSDNode>(Src) && cast<ConstantSDNode>(Src)->isZero();
6728   if (!TLI.findOptimalMemOpLowering(
6729           MemOps, TLI.getMaxStoresPerMemset(OptSize),
6730           MemOp::Set(Size, DstAlignCanChange, Alignment, IsZeroVal, isVol),
6731           DstPtrInfo.getAddrSpace(), ~0u, MF.getFunction().getAttributes()))
6732     return SDValue();
6733 
6734   if (DstAlignCanChange) {
6735     Type *Ty = MemOps[0].getTypeForEVT(*DAG.getContext());
6736     Align NewAlign = DAG.getDataLayout().getABITypeAlign(Ty);
6737     if (NewAlign > Alignment) {
6738       // Give the stack frame object a larger alignment if needed.
6739       if (MFI.getObjectAlign(FI->getIndex()) < NewAlign)
6740         MFI.setObjectAlignment(FI->getIndex(), NewAlign);
6741       Alignment = NewAlign;
6742     }
6743   }
6744 
6745   SmallVector<SDValue, 8> OutChains;
6746   uint64_t DstOff = 0;
6747   unsigned NumMemOps = MemOps.size();
6748 
6749   // Find the largest store and generate the bit pattern for it.
6750   EVT LargestVT = MemOps[0];
6751   for (unsigned i = 1; i < NumMemOps; i++)
6752     if (MemOps[i].bitsGT(LargestVT))
6753       LargestVT = MemOps[i];
6754   SDValue MemSetValue = getMemsetValue(Src, LargestVT, DAG, dl);
6755 
6756   // Prepare AAInfo for loads/stores after lowering this memset.
6757   AAMDNodes NewAAInfo = AAInfo;
6758   NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr;
6759 
6760   for (unsigned i = 0; i < NumMemOps; i++) {
6761     EVT VT = MemOps[i];
6762     unsigned VTSize = VT.getSizeInBits() / 8;
6763     if (VTSize > Size) {
6764       // Issuing an unaligned load / store pair  that overlaps with the previous
6765       // pair. Adjust the offset accordingly.
6766       assert(i == NumMemOps-1 && i != 0);
6767       DstOff -= VTSize - Size;
6768     }
6769 
6770     // If this store is smaller than the largest store see whether we can get
6771     // the smaller value for free with a truncate.
6772     SDValue Value = MemSetValue;
6773     if (VT.bitsLT(LargestVT)) {
6774       if (!LargestVT.isVector() && !VT.isVector() &&
6775           TLI.isTruncateFree(LargestVT, VT))
6776         Value = DAG.getNode(ISD::TRUNCATE, dl, VT, MemSetValue);
6777       else
6778         Value = getMemsetValue(Src, VT, DAG, dl);
6779     }
6780     assert(Value.getValueType() == VT && "Value with wrong type.");
6781     SDValue Store = DAG.getStore(
6782         Chain, dl, Value,
6783         DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl),
6784         DstPtrInfo.getWithOffset(DstOff), Alignment,
6785         isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone,
6786         NewAAInfo);
6787     OutChains.push_back(Store);
6788     DstOff += VT.getSizeInBits() / 8;
6789     Size -= VTSize;
6790   }
6791 
6792   return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
6793 }
6794 
6795 static void checkAddrSpaceIsValidForLibcall(const TargetLowering *TLI,
6796                                             unsigned AS) {
6797   // Lowering memcpy / memset / memmove intrinsics to calls is only valid if all
6798   // pointer operands can be losslessly bitcasted to pointers of address space 0
6799   if (AS != 0 && !TLI->getTargetMachine().isNoopAddrSpaceCast(AS, 0)) {
6800     report_fatal_error("cannot lower memory intrinsic in address space " +
6801                        Twine(AS));
6802   }
6803 }
6804 
6805 SDValue SelectionDAG::getMemcpy(SDValue Chain, const SDLoc &dl, SDValue Dst,
6806                                 SDValue Src, SDValue Size, Align Alignment,
6807                                 bool isVol, bool AlwaysInline, bool isTailCall,
6808                                 MachinePointerInfo DstPtrInfo,
6809                                 MachinePointerInfo SrcPtrInfo,
6810                                 const AAMDNodes &AAInfo) {
6811   // Check to see if we should lower the memcpy to loads and stores first.
6812   // For cases within the target-specified limits, this is the best choice.
6813   ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
6814   if (ConstantSize) {
6815     // Memcpy with size zero? Just return the original chain.
6816     if (ConstantSize->isZero())
6817       return Chain;
6818 
6819     SDValue Result = getMemcpyLoadsAndStores(
6820         *this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), Alignment,
6821         isVol, false, DstPtrInfo, SrcPtrInfo, AAInfo);
6822     if (Result.getNode())
6823       return Result;
6824   }
6825 
6826   // Then check to see if we should lower the memcpy with target-specific
6827   // code. If the target chooses to do this, this is the next best.
6828   if (TSI) {
6829     SDValue Result = TSI->EmitTargetCodeForMemcpy(
6830         *this, dl, Chain, Dst, Src, Size, Alignment, isVol, AlwaysInline,
6831         DstPtrInfo, SrcPtrInfo);
6832     if (Result.getNode())
6833       return Result;
6834   }
6835 
6836   // If we really need inline code and the target declined to provide it,
6837   // use a (potentially long) sequence of loads and stores.
6838   if (AlwaysInline) {
6839     assert(ConstantSize && "AlwaysInline requires a constant size!");
6840     return getMemcpyLoadsAndStores(*this, dl, Chain, Dst, Src,
6841                                    ConstantSize->getZExtValue(), Alignment,
6842                                    isVol, true, DstPtrInfo, SrcPtrInfo, AAInfo);
6843   }
6844 
6845   checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace());
6846   checkAddrSpaceIsValidForLibcall(TLI, SrcPtrInfo.getAddrSpace());
6847 
6848   // FIXME: If the memcpy is volatile (isVol), lowering it to a plain libc
6849   // memcpy is not guaranteed to be safe. libc memcpys aren't required to
6850   // respect volatile, so they may do things like read or write memory
6851   // beyond the given memory regions. But fixing this isn't easy, and most
6852   // people don't care.
6853 
6854   // Emit a library call.
6855   TargetLowering::ArgListTy Args;
6856   TargetLowering::ArgListEntry Entry;
6857   Entry.Ty = Type::getInt8PtrTy(*getContext());
6858   Entry.Node = Dst; Args.push_back(Entry);
6859   Entry.Node = Src; Args.push_back(Entry);
6860 
6861   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
6862   Entry.Node = Size; Args.push_back(Entry);
6863   // FIXME: pass in SDLoc
6864   TargetLowering::CallLoweringInfo CLI(*this);
6865   CLI.setDebugLoc(dl)
6866       .setChain(Chain)
6867       .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMCPY),
6868                     Dst.getValueType().getTypeForEVT(*getContext()),
6869                     getExternalSymbol(TLI->getLibcallName(RTLIB::MEMCPY),
6870                                       TLI->getPointerTy(getDataLayout())),
6871                     std::move(Args))
6872       .setDiscardResult()
6873       .setTailCall(isTailCall);
6874 
6875   std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
6876   return CallResult.second;
6877 }
6878 
6879 SDValue SelectionDAG::getAtomicMemcpy(SDValue Chain, const SDLoc &dl,
6880                                       SDValue Dst, unsigned DstAlign,
6881                                       SDValue Src, unsigned SrcAlign,
6882                                       SDValue Size, Type *SizeTy,
6883                                       unsigned ElemSz, bool isTailCall,
6884                                       MachinePointerInfo DstPtrInfo,
6885                                       MachinePointerInfo SrcPtrInfo) {
6886   // Emit a library call.
6887   TargetLowering::ArgListTy Args;
6888   TargetLowering::ArgListEntry Entry;
6889   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
6890   Entry.Node = Dst;
6891   Args.push_back(Entry);
6892 
6893   Entry.Node = Src;
6894   Args.push_back(Entry);
6895 
6896   Entry.Ty = SizeTy;
6897   Entry.Node = Size;
6898   Args.push_back(Entry);
6899 
6900   RTLIB::Libcall LibraryCall =
6901       RTLIB::getMEMCPY_ELEMENT_UNORDERED_ATOMIC(ElemSz);
6902   if (LibraryCall == RTLIB::UNKNOWN_LIBCALL)
6903     report_fatal_error("Unsupported element size");
6904 
6905   TargetLowering::CallLoweringInfo CLI(*this);
6906   CLI.setDebugLoc(dl)
6907       .setChain(Chain)
6908       .setLibCallee(TLI->getLibcallCallingConv(LibraryCall),
6909                     Type::getVoidTy(*getContext()),
6910                     getExternalSymbol(TLI->getLibcallName(LibraryCall),
6911                                       TLI->getPointerTy(getDataLayout())),
6912                     std::move(Args))
6913       .setDiscardResult()
6914       .setTailCall(isTailCall);
6915 
6916   std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
6917   return CallResult.second;
6918 }
6919 
6920 SDValue SelectionDAG::getMemmove(SDValue Chain, const SDLoc &dl, SDValue Dst,
6921                                  SDValue Src, SDValue Size, Align Alignment,
6922                                  bool isVol, bool isTailCall,
6923                                  MachinePointerInfo DstPtrInfo,
6924                                  MachinePointerInfo SrcPtrInfo,
6925                                  const AAMDNodes &AAInfo) {
6926   // Check to see if we should lower the memmove to loads and stores first.
6927   // For cases within the target-specified limits, this is the best choice.
6928   ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
6929   if (ConstantSize) {
6930     // Memmove with size zero? Just return the original chain.
6931     if (ConstantSize->isZero())
6932       return Chain;
6933 
6934     SDValue Result = getMemmoveLoadsAndStores(
6935         *this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), Alignment,
6936         isVol, false, DstPtrInfo, SrcPtrInfo, AAInfo);
6937     if (Result.getNode())
6938       return Result;
6939   }
6940 
6941   // Then check to see if we should lower the memmove with target-specific
6942   // code. If the target chooses to do this, this is the next best.
6943   if (TSI) {
6944     SDValue Result =
6945         TSI->EmitTargetCodeForMemmove(*this, dl, Chain, Dst, Src, Size,
6946                                       Alignment, isVol, DstPtrInfo, SrcPtrInfo);
6947     if (Result.getNode())
6948       return Result;
6949   }
6950 
6951   checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace());
6952   checkAddrSpaceIsValidForLibcall(TLI, SrcPtrInfo.getAddrSpace());
6953 
6954   // FIXME: If the memmove is volatile, lowering it to plain libc memmove may
6955   // not be safe.  See memcpy above for more details.
6956 
6957   // Emit a library call.
6958   TargetLowering::ArgListTy Args;
6959   TargetLowering::ArgListEntry Entry;
6960   Entry.Ty = Type::getInt8PtrTy(*getContext());
6961   Entry.Node = Dst; Args.push_back(Entry);
6962   Entry.Node = Src; Args.push_back(Entry);
6963 
6964   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
6965   Entry.Node = Size; Args.push_back(Entry);
6966   // FIXME:  pass in SDLoc
6967   TargetLowering::CallLoweringInfo CLI(*this);
6968   CLI.setDebugLoc(dl)
6969       .setChain(Chain)
6970       .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMMOVE),
6971                     Dst.getValueType().getTypeForEVT(*getContext()),
6972                     getExternalSymbol(TLI->getLibcallName(RTLIB::MEMMOVE),
6973                                       TLI->getPointerTy(getDataLayout())),
6974                     std::move(Args))
6975       .setDiscardResult()
6976       .setTailCall(isTailCall);
6977 
6978   std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
6979   return CallResult.second;
6980 }
6981 
6982 SDValue SelectionDAG::getAtomicMemmove(SDValue Chain, const SDLoc &dl,
6983                                        SDValue Dst, unsigned DstAlign,
6984                                        SDValue Src, unsigned SrcAlign,
6985                                        SDValue Size, Type *SizeTy,
6986                                        unsigned ElemSz, bool isTailCall,
6987                                        MachinePointerInfo DstPtrInfo,
6988                                        MachinePointerInfo SrcPtrInfo) {
6989   // Emit a library call.
6990   TargetLowering::ArgListTy Args;
6991   TargetLowering::ArgListEntry Entry;
6992   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
6993   Entry.Node = Dst;
6994   Args.push_back(Entry);
6995 
6996   Entry.Node = Src;
6997   Args.push_back(Entry);
6998 
6999   Entry.Ty = SizeTy;
7000   Entry.Node = Size;
7001   Args.push_back(Entry);
7002 
7003   RTLIB::Libcall LibraryCall =
7004       RTLIB::getMEMMOVE_ELEMENT_UNORDERED_ATOMIC(ElemSz);
7005   if (LibraryCall == RTLIB::UNKNOWN_LIBCALL)
7006     report_fatal_error("Unsupported element size");
7007 
7008   TargetLowering::CallLoweringInfo CLI(*this);
7009   CLI.setDebugLoc(dl)
7010       .setChain(Chain)
7011       .setLibCallee(TLI->getLibcallCallingConv(LibraryCall),
7012                     Type::getVoidTy(*getContext()),
7013                     getExternalSymbol(TLI->getLibcallName(LibraryCall),
7014                                       TLI->getPointerTy(getDataLayout())),
7015                     std::move(Args))
7016       .setDiscardResult()
7017       .setTailCall(isTailCall);
7018 
7019   std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
7020   return CallResult.second;
7021 }
7022 
7023 SDValue SelectionDAG::getMemset(SDValue Chain, const SDLoc &dl, SDValue Dst,
7024                                 SDValue Src, SDValue Size, Align Alignment,
7025                                 bool isVol, bool isTailCall,
7026                                 MachinePointerInfo DstPtrInfo,
7027                                 const AAMDNodes &AAInfo) {
7028   // Check to see if we should lower the memset to stores first.
7029   // For cases within the target-specified limits, this is the best choice.
7030   ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
7031   if (ConstantSize) {
7032     // Memset with size zero? Just return the original chain.
7033     if (ConstantSize->isZero())
7034       return Chain;
7035 
7036     SDValue Result = getMemsetStores(*this, dl, Chain, Dst, Src,
7037                                      ConstantSize->getZExtValue(), Alignment,
7038                                      isVol, DstPtrInfo, AAInfo);
7039 
7040     if (Result.getNode())
7041       return Result;
7042   }
7043 
7044   // Then check to see if we should lower the memset with target-specific
7045   // code. If the target chooses to do this, this is the next best.
7046   if (TSI) {
7047     SDValue Result = TSI->EmitTargetCodeForMemset(
7048         *this, dl, Chain, Dst, Src, Size, Alignment, isVol, DstPtrInfo);
7049     if (Result.getNode())
7050       return Result;
7051   }
7052 
7053   checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace());
7054 
7055   // Emit a library call.
7056   TargetLowering::ArgListTy Args;
7057   TargetLowering::ArgListEntry Entry;
7058   Entry.Node = Dst; Entry.Ty = Type::getInt8PtrTy(*getContext());
7059   Args.push_back(Entry);
7060   Entry.Node = Src;
7061   Entry.Ty = Src.getValueType().getTypeForEVT(*getContext());
7062   Args.push_back(Entry);
7063   Entry.Node = Size;
7064   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
7065   Args.push_back(Entry);
7066 
7067   // FIXME: pass in SDLoc
7068   TargetLowering::CallLoweringInfo CLI(*this);
7069   CLI.setDebugLoc(dl)
7070       .setChain(Chain)
7071       .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMSET),
7072                     Dst.getValueType().getTypeForEVT(*getContext()),
7073                     getExternalSymbol(TLI->getLibcallName(RTLIB::MEMSET),
7074                                       TLI->getPointerTy(getDataLayout())),
7075                     std::move(Args))
7076       .setDiscardResult()
7077       .setTailCall(isTailCall);
7078 
7079   std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
7080   return CallResult.second;
7081 }
7082 
7083 SDValue SelectionDAG::getAtomicMemset(SDValue Chain, const SDLoc &dl,
7084                                       SDValue Dst, unsigned DstAlign,
7085                                       SDValue Value, SDValue Size, Type *SizeTy,
7086                                       unsigned ElemSz, bool isTailCall,
7087                                       MachinePointerInfo DstPtrInfo) {
7088   // Emit a library call.
7089   TargetLowering::ArgListTy Args;
7090   TargetLowering::ArgListEntry Entry;
7091   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
7092   Entry.Node = Dst;
7093   Args.push_back(Entry);
7094 
7095   Entry.Ty = Type::getInt8Ty(*getContext());
7096   Entry.Node = Value;
7097   Args.push_back(Entry);
7098 
7099   Entry.Ty = SizeTy;
7100   Entry.Node = Size;
7101   Args.push_back(Entry);
7102 
7103   RTLIB::Libcall LibraryCall =
7104       RTLIB::getMEMSET_ELEMENT_UNORDERED_ATOMIC(ElemSz);
7105   if (LibraryCall == RTLIB::UNKNOWN_LIBCALL)
7106     report_fatal_error("Unsupported element size");
7107 
7108   TargetLowering::CallLoweringInfo CLI(*this);
7109   CLI.setDebugLoc(dl)
7110       .setChain(Chain)
7111       .setLibCallee(TLI->getLibcallCallingConv(LibraryCall),
7112                     Type::getVoidTy(*getContext()),
7113                     getExternalSymbol(TLI->getLibcallName(LibraryCall),
7114                                       TLI->getPointerTy(getDataLayout())),
7115                     std::move(Args))
7116       .setDiscardResult()
7117       .setTailCall(isTailCall);
7118 
7119   std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
7120   return CallResult.second;
7121 }
7122 
7123 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
7124                                 SDVTList VTList, ArrayRef<SDValue> Ops,
7125                                 MachineMemOperand *MMO) {
7126   FoldingSetNodeID ID;
7127   ID.AddInteger(MemVT.getRawBits());
7128   AddNodeIDNode(ID, Opcode, VTList, Ops);
7129   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7130   void* IP = nullptr;
7131   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7132     cast<AtomicSDNode>(E)->refineAlignment(MMO);
7133     return SDValue(E, 0);
7134   }
7135 
7136   auto *N = newSDNode<AtomicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
7137                                     VTList, MemVT, MMO);
7138   createOperands(N, Ops);
7139 
7140   CSEMap.InsertNode(N, IP);
7141   InsertNode(N);
7142   return SDValue(N, 0);
7143 }
7144 
7145 SDValue SelectionDAG::getAtomicCmpSwap(unsigned Opcode, const SDLoc &dl,
7146                                        EVT MemVT, SDVTList VTs, SDValue Chain,
7147                                        SDValue Ptr, SDValue Cmp, SDValue Swp,
7148                                        MachineMemOperand *MMO) {
7149   assert(Opcode == ISD::ATOMIC_CMP_SWAP ||
7150          Opcode == ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS);
7151   assert(Cmp.getValueType() == Swp.getValueType() && "Invalid Atomic Op Types");
7152 
7153   SDValue Ops[] = {Chain, Ptr, Cmp, Swp};
7154   return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
7155 }
7156 
7157 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
7158                                 SDValue Chain, SDValue Ptr, SDValue Val,
7159                                 MachineMemOperand *MMO) {
7160   assert((Opcode == ISD::ATOMIC_LOAD_ADD ||
7161           Opcode == ISD::ATOMIC_LOAD_SUB ||
7162           Opcode == ISD::ATOMIC_LOAD_AND ||
7163           Opcode == ISD::ATOMIC_LOAD_CLR ||
7164           Opcode == ISD::ATOMIC_LOAD_OR ||
7165           Opcode == ISD::ATOMIC_LOAD_XOR ||
7166           Opcode == ISD::ATOMIC_LOAD_NAND ||
7167           Opcode == ISD::ATOMIC_LOAD_MIN ||
7168           Opcode == ISD::ATOMIC_LOAD_MAX ||
7169           Opcode == ISD::ATOMIC_LOAD_UMIN ||
7170           Opcode == ISD::ATOMIC_LOAD_UMAX ||
7171           Opcode == ISD::ATOMIC_LOAD_FADD ||
7172           Opcode == ISD::ATOMIC_LOAD_FSUB ||
7173           Opcode == ISD::ATOMIC_SWAP ||
7174           Opcode == ISD::ATOMIC_STORE) &&
7175          "Invalid Atomic Op");
7176 
7177   EVT VT = Val.getValueType();
7178 
7179   SDVTList VTs = Opcode == ISD::ATOMIC_STORE ? getVTList(MVT::Other) :
7180                                                getVTList(VT, MVT::Other);
7181   SDValue Ops[] = {Chain, Ptr, Val};
7182   return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
7183 }
7184 
7185 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
7186                                 EVT VT, SDValue Chain, SDValue Ptr,
7187                                 MachineMemOperand *MMO) {
7188   assert(Opcode == ISD::ATOMIC_LOAD && "Invalid Atomic Op");
7189 
7190   SDVTList VTs = getVTList(VT, MVT::Other);
7191   SDValue Ops[] = {Chain, Ptr};
7192   return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
7193 }
7194 
7195 /// getMergeValues - Create a MERGE_VALUES node from the given operands.
7196 SDValue SelectionDAG::getMergeValues(ArrayRef<SDValue> Ops, const SDLoc &dl) {
7197   if (Ops.size() == 1)
7198     return Ops[0];
7199 
7200   SmallVector<EVT, 4> VTs;
7201   VTs.reserve(Ops.size());
7202   for (const SDValue &Op : Ops)
7203     VTs.push_back(Op.getValueType());
7204   return getNode(ISD::MERGE_VALUES, dl, getVTList(VTs), Ops);
7205 }
7206 
7207 SDValue SelectionDAG::getMemIntrinsicNode(
7208     unsigned Opcode, const SDLoc &dl, SDVTList VTList, ArrayRef<SDValue> Ops,
7209     EVT MemVT, MachinePointerInfo PtrInfo, Align Alignment,
7210     MachineMemOperand::Flags Flags, uint64_t Size, const AAMDNodes &AAInfo) {
7211   if (!Size && MemVT.isScalableVector())
7212     Size = MemoryLocation::UnknownSize;
7213   else if (!Size)
7214     Size = MemVT.getStoreSize();
7215 
7216   MachineFunction &MF = getMachineFunction();
7217   MachineMemOperand *MMO =
7218       MF.getMachineMemOperand(PtrInfo, Flags, Size, Alignment, AAInfo);
7219 
7220   return getMemIntrinsicNode(Opcode, dl, VTList, Ops, MemVT, MMO);
7221 }
7222 
7223 SDValue SelectionDAG::getMemIntrinsicNode(unsigned Opcode, const SDLoc &dl,
7224                                           SDVTList VTList,
7225                                           ArrayRef<SDValue> Ops, EVT MemVT,
7226                                           MachineMemOperand *MMO) {
7227   assert((Opcode == ISD::INTRINSIC_VOID ||
7228           Opcode == ISD::INTRINSIC_W_CHAIN ||
7229           Opcode == ISD::PREFETCH ||
7230           ((int)Opcode <= std::numeric_limits<int>::max() &&
7231            (int)Opcode >= ISD::FIRST_TARGET_MEMORY_OPCODE)) &&
7232          "Opcode is not a memory-accessing opcode!");
7233 
7234   // Memoize the node unless it returns a flag.
7235   MemIntrinsicSDNode *N;
7236   if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) {
7237     FoldingSetNodeID ID;
7238     AddNodeIDNode(ID, Opcode, VTList, Ops);
7239     ID.AddInteger(getSyntheticNodeSubclassData<MemIntrinsicSDNode>(
7240         Opcode, dl.getIROrder(), VTList, MemVT, MMO));
7241     ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7242     void *IP = nullptr;
7243     if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7244       cast<MemIntrinsicSDNode>(E)->refineAlignment(MMO);
7245       return SDValue(E, 0);
7246     }
7247 
7248     N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
7249                                       VTList, MemVT, MMO);
7250     createOperands(N, Ops);
7251 
7252   CSEMap.InsertNode(N, IP);
7253   } else {
7254     N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
7255                                       VTList, MemVT, MMO);
7256     createOperands(N, Ops);
7257   }
7258   InsertNode(N);
7259   SDValue V(N, 0);
7260   NewSDValueDbgMsg(V, "Creating new node: ", this);
7261   return V;
7262 }
7263 
7264 SDValue SelectionDAG::getLifetimeNode(bool IsStart, const SDLoc &dl,
7265                                       SDValue Chain, int FrameIndex,
7266                                       int64_t Size, int64_t Offset) {
7267   const unsigned Opcode = IsStart ? ISD::LIFETIME_START : ISD::LIFETIME_END;
7268   const auto VTs = getVTList(MVT::Other);
7269   SDValue Ops[2] = {
7270       Chain,
7271       getFrameIndex(FrameIndex,
7272                     getTargetLoweringInfo().getFrameIndexTy(getDataLayout()),
7273                     true)};
7274 
7275   FoldingSetNodeID ID;
7276   AddNodeIDNode(ID, Opcode, VTs, Ops);
7277   ID.AddInteger(FrameIndex);
7278   ID.AddInteger(Size);
7279   ID.AddInteger(Offset);
7280   void *IP = nullptr;
7281   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
7282     return SDValue(E, 0);
7283 
7284   LifetimeSDNode *N = newSDNode<LifetimeSDNode>(
7285       Opcode, dl.getIROrder(), dl.getDebugLoc(), VTs, Size, Offset);
7286   createOperands(N, Ops);
7287   CSEMap.InsertNode(N, IP);
7288   InsertNode(N);
7289   SDValue V(N, 0);
7290   NewSDValueDbgMsg(V, "Creating new node: ", this);
7291   return V;
7292 }
7293 
7294 SDValue SelectionDAG::getPseudoProbeNode(const SDLoc &Dl, SDValue Chain,
7295                                          uint64_t Guid, uint64_t Index,
7296                                          uint32_t Attr) {
7297   const unsigned Opcode = ISD::PSEUDO_PROBE;
7298   const auto VTs = getVTList(MVT::Other);
7299   SDValue Ops[] = {Chain};
7300   FoldingSetNodeID ID;
7301   AddNodeIDNode(ID, Opcode, VTs, Ops);
7302   ID.AddInteger(Guid);
7303   ID.AddInteger(Index);
7304   void *IP = nullptr;
7305   if (SDNode *E = FindNodeOrInsertPos(ID, Dl, IP))
7306     return SDValue(E, 0);
7307 
7308   auto *N = newSDNode<PseudoProbeSDNode>(
7309       Opcode, Dl.getIROrder(), Dl.getDebugLoc(), VTs, Guid, Index, Attr);
7310   createOperands(N, Ops);
7311   CSEMap.InsertNode(N, IP);
7312   InsertNode(N);
7313   SDValue V(N, 0);
7314   NewSDValueDbgMsg(V, "Creating new node: ", this);
7315   return V;
7316 }
7317 
7318 /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a
7319 /// MachinePointerInfo record from it.  This is particularly useful because the
7320 /// code generator has many cases where it doesn't bother passing in a
7321 /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst".
7322 static MachinePointerInfo InferPointerInfo(const MachinePointerInfo &Info,
7323                                            SelectionDAG &DAG, SDValue Ptr,
7324                                            int64_t Offset = 0) {
7325   // If this is FI+Offset, we can model it.
7326   if (const FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr))
7327     return MachinePointerInfo::getFixedStack(DAG.getMachineFunction(),
7328                                              FI->getIndex(), Offset);
7329 
7330   // If this is (FI+Offset1)+Offset2, we can model it.
7331   if (Ptr.getOpcode() != ISD::ADD ||
7332       !isa<ConstantSDNode>(Ptr.getOperand(1)) ||
7333       !isa<FrameIndexSDNode>(Ptr.getOperand(0)))
7334     return Info;
7335 
7336   int FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
7337   return MachinePointerInfo::getFixedStack(
7338       DAG.getMachineFunction(), FI,
7339       Offset + cast<ConstantSDNode>(Ptr.getOperand(1))->getSExtValue());
7340 }
7341 
7342 /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a
7343 /// MachinePointerInfo record from it.  This is particularly useful because the
7344 /// code generator has many cases where it doesn't bother passing in a
7345 /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst".
7346 static MachinePointerInfo InferPointerInfo(const MachinePointerInfo &Info,
7347                                            SelectionDAG &DAG, SDValue Ptr,
7348                                            SDValue OffsetOp) {
7349   // If the 'Offset' value isn't a constant, we can't handle this.
7350   if (ConstantSDNode *OffsetNode = dyn_cast<ConstantSDNode>(OffsetOp))
7351     return InferPointerInfo(Info, DAG, Ptr, OffsetNode->getSExtValue());
7352   if (OffsetOp.isUndef())
7353     return InferPointerInfo(Info, DAG, Ptr);
7354   return Info;
7355 }
7356 
7357 SDValue SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType,
7358                               EVT VT, const SDLoc &dl, SDValue Chain,
7359                               SDValue Ptr, SDValue Offset,
7360                               MachinePointerInfo PtrInfo, EVT MemVT,
7361                               Align Alignment,
7362                               MachineMemOperand::Flags MMOFlags,
7363                               const AAMDNodes &AAInfo, const MDNode *Ranges) {
7364   assert(Chain.getValueType() == MVT::Other &&
7365         "Invalid chain type");
7366 
7367   MMOFlags |= MachineMemOperand::MOLoad;
7368   assert((MMOFlags & MachineMemOperand::MOStore) == 0);
7369   // If we don't have a PtrInfo, infer the trivial frame index case to simplify
7370   // clients.
7371   if (PtrInfo.V.isNull())
7372     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr, Offset);
7373 
7374   uint64_t Size = MemoryLocation::getSizeOrUnknown(MemVT.getStoreSize());
7375   MachineFunction &MF = getMachineFunction();
7376   MachineMemOperand *MMO = MF.getMachineMemOperand(PtrInfo, MMOFlags, Size,
7377                                                    Alignment, AAInfo, Ranges);
7378   return getLoad(AM, ExtType, VT, dl, Chain, Ptr, Offset, MemVT, MMO);
7379 }
7380 
7381 SDValue SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType,
7382                               EVT VT, const SDLoc &dl, SDValue Chain,
7383                               SDValue Ptr, SDValue Offset, EVT MemVT,
7384                               MachineMemOperand *MMO) {
7385   if (VT == MemVT) {
7386     ExtType = ISD::NON_EXTLOAD;
7387   } else if (ExtType == ISD::NON_EXTLOAD) {
7388     assert(VT == MemVT && "Non-extending load from different memory type!");
7389   } else {
7390     // Extending load.
7391     assert(MemVT.getScalarType().bitsLT(VT.getScalarType()) &&
7392            "Should only be an extending load, not truncating!");
7393     assert(VT.isInteger() == MemVT.isInteger() &&
7394            "Cannot convert from FP to Int or Int -> FP!");
7395     assert(VT.isVector() == MemVT.isVector() &&
7396            "Cannot use an ext load to convert to or from a vector!");
7397     assert((!VT.isVector() ||
7398             VT.getVectorElementCount() == MemVT.getVectorElementCount()) &&
7399            "Cannot use an ext load to change the number of vector elements!");
7400   }
7401 
7402   bool Indexed = AM != ISD::UNINDEXED;
7403   assert((Indexed || Offset.isUndef()) && "Unindexed load with an offset!");
7404 
7405   SDVTList VTs = Indexed ?
7406     getVTList(VT, Ptr.getValueType(), MVT::Other) : getVTList(VT, MVT::Other);
7407   SDValue Ops[] = { Chain, Ptr, Offset };
7408   FoldingSetNodeID ID;
7409   AddNodeIDNode(ID, ISD::LOAD, VTs, Ops);
7410   ID.AddInteger(MemVT.getRawBits());
7411   ID.AddInteger(getSyntheticNodeSubclassData<LoadSDNode>(
7412       dl.getIROrder(), VTs, AM, ExtType, MemVT, MMO));
7413   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7414   void *IP = nullptr;
7415   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7416     cast<LoadSDNode>(E)->refineAlignment(MMO);
7417     return SDValue(E, 0);
7418   }
7419   auto *N = newSDNode<LoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
7420                                   ExtType, MemVT, MMO);
7421   createOperands(N, Ops);
7422 
7423   CSEMap.InsertNode(N, IP);
7424   InsertNode(N);
7425   SDValue V(N, 0);
7426   NewSDValueDbgMsg(V, "Creating new node: ", this);
7427   return V;
7428 }
7429 
7430 SDValue SelectionDAG::getLoad(EVT VT, const SDLoc &dl, SDValue Chain,
7431                               SDValue Ptr, MachinePointerInfo PtrInfo,
7432                               MaybeAlign Alignment,
7433                               MachineMemOperand::Flags MMOFlags,
7434                               const AAMDNodes &AAInfo, const MDNode *Ranges) {
7435   SDValue Undef = getUNDEF(Ptr.getValueType());
7436   return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
7437                  PtrInfo, VT, Alignment, MMOFlags, AAInfo, Ranges);
7438 }
7439 
7440 SDValue SelectionDAG::getLoad(EVT VT, const SDLoc &dl, SDValue Chain,
7441                               SDValue Ptr, MachineMemOperand *MMO) {
7442   SDValue Undef = getUNDEF(Ptr.getValueType());
7443   return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
7444                  VT, MMO);
7445 }
7446 
7447 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl,
7448                                  EVT VT, SDValue Chain, SDValue Ptr,
7449                                  MachinePointerInfo PtrInfo, EVT MemVT,
7450                                  MaybeAlign Alignment,
7451                                  MachineMemOperand::Flags MMOFlags,
7452                                  const AAMDNodes &AAInfo) {
7453   SDValue Undef = getUNDEF(Ptr.getValueType());
7454   return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, PtrInfo,
7455                  MemVT, Alignment, MMOFlags, AAInfo);
7456 }
7457 
7458 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl,
7459                                  EVT VT, SDValue Chain, SDValue Ptr, EVT MemVT,
7460                                  MachineMemOperand *MMO) {
7461   SDValue Undef = getUNDEF(Ptr.getValueType());
7462   return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef,
7463                  MemVT, MMO);
7464 }
7465 
7466 SDValue SelectionDAG::getIndexedLoad(SDValue OrigLoad, const SDLoc &dl,
7467                                      SDValue Base, SDValue Offset,
7468                                      ISD::MemIndexedMode AM) {
7469   LoadSDNode *LD = cast<LoadSDNode>(OrigLoad);
7470   assert(LD->getOffset().isUndef() && "Load is already a indexed load!");
7471   // Don't propagate the invariant or dereferenceable flags.
7472   auto MMOFlags =
7473       LD->getMemOperand()->getFlags() &
7474       ~(MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable);
7475   return getLoad(AM, LD->getExtensionType(), OrigLoad.getValueType(), dl,
7476                  LD->getChain(), Base, Offset, LD->getPointerInfo(),
7477                  LD->getMemoryVT(), LD->getAlign(), MMOFlags, LD->getAAInfo());
7478 }
7479 
7480 SDValue SelectionDAG::getStore(SDValue Chain, const SDLoc &dl, SDValue Val,
7481                                SDValue Ptr, MachinePointerInfo PtrInfo,
7482                                Align Alignment,
7483                                MachineMemOperand::Flags MMOFlags,
7484                                const AAMDNodes &AAInfo) {
7485   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
7486 
7487   MMOFlags |= MachineMemOperand::MOStore;
7488   assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
7489 
7490   if (PtrInfo.V.isNull())
7491     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
7492 
7493   MachineFunction &MF = getMachineFunction();
7494   uint64_t Size =
7495       MemoryLocation::getSizeOrUnknown(Val.getValueType().getStoreSize());
7496   MachineMemOperand *MMO =
7497       MF.getMachineMemOperand(PtrInfo, MMOFlags, Size, Alignment, AAInfo);
7498   return getStore(Chain, dl, Val, Ptr, MMO);
7499 }
7500 
7501 SDValue SelectionDAG::getStore(SDValue Chain, const SDLoc &dl, SDValue Val,
7502                                SDValue Ptr, MachineMemOperand *MMO) {
7503   assert(Chain.getValueType() == MVT::Other &&
7504         "Invalid chain type");
7505   EVT VT = Val.getValueType();
7506   SDVTList VTs = getVTList(MVT::Other);
7507   SDValue Undef = getUNDEF(Ptr.getValueType());
7508   SDValue Ops[] = { Chain, Val, Ptr, Undef };
7509   FoldingSetNodeID ID;
7510   AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
7511   ID.AddInteger(VT.getRawBits());
7512   ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>(
7513       dl.getIROrder(), VTs, ISD::UNINDEXED, false, VT, MMO));
7514   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7515   void *IP = nullptr;
7516   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7517     cast<StoreSDNode>(E)->refineAlignment(MMO);
7518     return SDValue(E, 0);
7519   }
7520   auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
7521                                    ISD::UNINDEXED, false, VT, MMO);
7522   createOperands(N, Ops);
7523 
7524   CSEMap.InsertNode(N, IP);
7525   InsertNode(N);
7526   SDValue V(N, 0);
7527   NewSDValueDbgMsg(V, "Creating new node: ", this);
7528   return V;
7529 }
7530 
7531 SDValue SelectionDAG::getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val,
7532                                     SDValue Ptr, MachinePointerInfo PtrInfo,
7533                                     EVT SVT, Align Alignment,
7534                                     MachineMemOperand::Flags MMOFlags,
7535                                     const AAMDNodes &AAInfo) {
7536   assert(Chain.getValueType() == MVT::Other &&
7537         "Invalid chain type");
7538 
7539   MMOFlags |= MachineMemOperand::MOStore;
7540   assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
7541 
7542   if (PtrInfo.V.isNull())
7543     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
7544 
7545   MachineFunction &MF = getMachineFunction();
7546   MachineMemOperand *MMO = MF.getMachineMemOperand(
7547       PtrInfo, MMOFlags, MemoryLocation::getSizeOrUnknown(SVT.getStoreSize()),
7548       Alignment, AAInfo);
7549   return getTruncStore(Chain, dl, Val, Ptr, SVT, MMO);
7550 }
7551 
7552 SDValue SelectionDAG::getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val,
7553                                     SDValue Ptr, EVT SVT,
7554                                     MachineMemOperand *MMO) {
7555   EVT VT = Val.getValueType();
7556 
7557   assert(Chain.getValueType() == MVT::Other &&
7558         "Invalid chain type");
7559   if (VT == SVT)
7560     return getStore(Chain, dl, Val, Ptr, MMO);
7561 
7562   assert(SVT.getScalarType().bitsLT(VT.getScalarType()) &&
7563          "Should only be a truncating store, not extending!");
7564   assert(VT.isInteger() == SVT.isInteger() &&
7565          "Can't do FP-INT conversion!");
7566   assert(VT.isVector() == SVT.isVector() &&
7567          "Cannot use trunc store to convert to or from a vector!");
7568   assert((!VT.isVector() ||
7569           VT.getVectorElementCount() == SVT.getVectorElementCount()) &&
7570          "Cannot use trunc store to change the number of vector elements!");
7571 
7572   SDVTList VTs = getVTList(MVT::Other);
7573   SDValue Undef = getUNDEF(Ptr.getValueType());
7574   SDValue Ops[] = { Chain, Val, Ptr, Undef };
7575   FoldingSetNodeID ID;
7576   AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
7577   ID.AddInteger(SVT.getRawBits());
7578   ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>(
7579       dl.getIROrder(), VTs, ISD::UNINDEXED, true, SVT, MMO));
7580   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7581   void *IP = nullptr;
7582   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7583     cast<StoreSDNode>(E)->refineAlignment(MMO);
7584     return SDValue(E, 0);
7585   }
7586   auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
7587                                    ISD::UNINDEXED, true, SVT, MMO);
7588   createOperands(N, Ops);
7589 
7590   CSEMap.InsertNode(N, IP);
7591   InsertNode(N);
7592   SDValue V(N, 0);
7593   NewSDValueDbgMsg(V, "Creating new node: ", this);
7594   return V;
7595 }
7596 
7597 SDValue SelectionDAG::getIndexedStore(SDValue OrigStore, const SDLoc &dl,
7598                                       SDValue Base, SDValue Offset,
7599                                       ISD::MemIndexedMode AM) {
7600   StoreSDNode *ST = cast<StoreSDNode>(OrigStore);
7601   assert(ST->getOffset().isUndef() && "Store is already a indexed store!");
7602   SDVTList VTs = getVTList(Base.getValueType(), MVT::Other);
7603   SDValue Ops[] = { ST->getChain(), ST->getValue(), Base, Offset };
7604   FoldingSetNodeID ID;
7605   AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
7606   ID.AddInteger(ST->getMemoryVT().getRawBits());
7607   ID.AddInteger(ST->getRawSubclassData());
7608   ID.AddInteger(ST->getPointerInfo().getAddrSpace());
7609   void *IP = nullptr;
7610   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
7611     return SDValue(E, 0);
7612 
7613   auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
7614                                    ST->isTruncatingStore(), ST->getMemoryVT(),
7615                                    ST->getMemOperand());
7616   createOperands(N, Ops);
7617 
7618   CSEMap.InsertNode(N, IP);
7619   InsertNode(N);
7620   SDValue V(N, 0);
7621   NewSDValueDbgMsg(V, "Creating new node: ", this);
7622   return V;
7623 }
7624 
7625 SDValue SelectionDAG::getLoadVP(
7626     ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, EVT VT, const SDLoc &dl,
7627     SDValue Chain, SDValue Ptr, SDValue Offset, SDValue Mask, SDValue EVL,
7628     MachinePointerInfo PtrInfo, EVT MemVT, Align Alignment,
7629     MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo,
7630     const MDNode *Ranges, bool IsExpanding) {
7631   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
7632 
7633   MMOFlags |= MachineMemOperand::MOLoad;
7634   assert((MMOFlags & MachineMemOperand::MOStore) == 0);
7635   // If we don't have a PtrInfo, infer the trivial frame index case to simplify
7636   // clients.
7637   if (PtrInfo.V.isNull())
7638     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr, Offset);
7639 
7640   uint64_t Size = MemoryLocation::getSizeOrUnknown(MemVT.getStoreSize());
7641   MachineFunction &MF = getMachineFunction();
7642   MachineMemOperand *MMO = MF.getMachineMemOperand(PtrInfo, MMOFlags, Size,
7643                                                    Alignment, AAInfo, Ranges);
7644   return getLoadVP(AM, ExtType, VT, dl, Chain, Ptr, Offset, Mask, EVL, MemVT,
7645                    MMO, IsExpanding);
7646 }
7647 
7648 SDValue SelectionDAG::getLoadVP(ISD::MemIndexedMode AM,
7649                                 ISD::LoadExtType ExtType, EVT VT,
7650                                 const SDLoc &dl, SDValue Chain, SDValue Ptr,
7651                                 SDValue Offset, SDValue Mask, SDValue EVL,
7652                                 EVT MemVT, MachineMemOperand *MMO,
7653                                 bool IsExpanding) {
7654   if (VT == MemVT) {
7655     ExtType = ISD::NON_EXTLOAD;
7656   } else if (ExtType == ISD::NON_EXTLOAD) {
7657     assert(VT == MemVT && "Non-extending load from different memory type!");
7658   } else {
7659     // Extending load.
7660     assert(MemVT.getScalarType().bitsLT(VT.getScalarType()) &&
7661            "Should only be an extending load, not truncating!");
7662     assert(VT.isInteger() == MemVT.isInteger() &&
7663            "Cannot convert from FP to Int or Int -> FP!");
7664     assert(VT.isVector() == MemVT.isVector() &&
7665            "Cannot use an ext load to convert to or from a vector!");
7666     assert((!VT.isVector() ||
7667             VT.getVectorElementCount() == MemVT.getVectorElementCount()) &&
7668            "Cannot use an ext load to change the number of vector elements!");
7669   }
7670 
7671   bool Indexed = AM != ISD::UNINDEXED;
7672   assert((Indexed || Offset.isUndef()) && "Unindexed load with an offset!");
7673 
7674   SDVTList VTs = Indexed ? getVTList(VT, Ptr.getValueType(), MVT::Other)
7675                          : getVTList(VT, MVT::Other);
7676   SDValue Ops[] = {Chain, Ptr, Offset, Mask, EVL};
7677   FoldingSetNodeID ID;
7678   AddNodeIDNode(ID, ISD::VP_LOAD, VTs, Ops);
7679   ID.AddInteger(VT.getRawBits());
7680   ID.AddInteger(getSyntheticNodeSubclassData<VPLoadSDNode>(
7681       dl.getIROrder(), VTs, AM, ExtType, IsExpanding, MemVT, MMO));
7682   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7683   void *IP = nullptr;
7684   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7685     cast<VPLoadSDNode>(E)->refineAlignment(MMO);
7686     return SDValue(E, 0);
7687   }
7688   auto *N = newSDNode<VPLoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
7689                                     ExtType, IsExpanding, MemVT, MMO);
7690   createOperands(N, Ops);
7691 
7692   CSEMap.InsertNode(N, IP);
7693   InsertNode(N);
7694   SDValue V(N, 0);
7695   NewSDValueDbgMsg(V, "Creating new node: ", this);
7696   return V;
7697 }
7698 
7699 SDValue SelectionDAG::getLoadVP(EVT VT, const SDLoc &dl, SDValue Chain,
7700                                 SDValue Ptr, SDValue Mask, SDValue EVL,
7701                                 MachinePointerInfo PtrInfo,
7702                                 MaybeAlign Alignment,
7703                                 MachineMemOperand::Flags MMOFlags,
7704                                 const AAMDNodes &AAInfo, const MDNode *Ranges,
7705                                 bool IsExpanding) {
7706   SDValue Undef = getUNDEF(Ptr.getValueType());
7707   return getLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
7708                    Mask, EVL, PtrInfo, VT, Alignment, MMOFlags, AAInfo, Ranges,
7709                    IsExpanding);
7710 }
7711 
7712 SDValue SelectionDAG::getLoadVP(EVT VT, const SDLoc &dl, SDValue Chain,
7713                                 SDValue Ptr, SDValue Mask, SDValue EVL,
7714                                 MachineMemOperand *MMO, bool IsExpanding) {
7715   SDValue Undef = getUNDEF(Ptr.getValueType());
7716   return getLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
7717                    Mask, EVL, VT, MMO, IsExpanding);
7718 }
7719 
7720 SDValue SelectionDAG::getExtLoadVP(ISD::LoadExtType ExtType, const SDLoc &dl,
7721                                    EVT VT, SDValue Chain, SDValue Ptr,
7722                                    SDValue Mask, SDValue EVL,
7723                                    MachinePointerInfo PtrInfo, EVT MemVT,
7724                                    MaybeAlign Alignment,
7725                                    MachineMemOperand::Flags MMOFlags,
7726                                    const AAMDNodes &AAInfo, bool IsExpanding) {
7727   SDValue Undef = getUNDEF(Ptr.getValueType());
7728   return getLoadVP(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, Mask,
7729                    EVL, PtrInfo, MemVT, Alignment, MMOFlags, AAInfo, nullptr,
7730                    IsExpanding);
7731 }
7732 
7733 SDValue SelectionDAG::getExtLoadVP(ISD::LoadExtType ExtType, const SDLoc &dl,
7734                                    EVT VT, SDValue Chain, SDValue Ptr,
7735                                    SDValue Mask, SDValue EVL, EVT MemVT,
7736                                    MachineMemOperand *MMO, bool IsExpanding) {
7737   SDValue Undef = getUNDEF(Ptr.getValueType());
7738   return getLoadVP(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, Mask,
7739                    EVL, MemVT, MMO, IsExpanding);
7740 }
7741 
7742 SDValue SelectionDAG::getIndexedLoadVP(SDValue OrigLoad, const SDLoc &dl,
7743                                        SDValue Base, SDValue Offset,
7744                                        ISD::MemIndexedMode AM) {
7745   auto *LD = cast<VPLoadSDNode>(OrigLoad);
7746   assert(LD->getOffset().isUndef() && "Load is already a indexed load!");
7747   // Don't propagate the invariant or dereferenceable flags.
7748   auto MMOFlags =
7749       LD->getMemOperand()->getFlags() &
7750       ~(MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable);
7751   return getLoadVP(AM, LD->getExtensionType(), OrigLoad.getValueType(), dl,
7752                    LD->getChain(), Base, Offset, LD->getMask(),
7753                    LD->getVectorLength(), LD->getPointerInfo(),
7754                    LD->getMemoryVT(), LD->getAlign(), MMOFlags, LD->getAAInfo(),
7755                    nullptr, LD->isExpandingLoad());
7756 }
7757 
7758 SDValue SelectionDAG::getStoreVP(SDValue Chain, const SDLoc &dl, SDValue Val,
7759                                  SDValue Ptr, SDValue Mask, SDValue EVL,
7760                                  MachinePointerInfo PtrInfo, Align Alignment,
7761                                  MachineMemOperand::Flags MMOFlags,
7762                                  const AAMDNodes &AAInfo, bool IsCompressing) {
7763   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
7764 
7765   MMOFlags |= MachineMemOperand::MOStore;
7766   assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
7767 
7768   if (PtrInfo.V.isNull())
7769     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
7770 
7771   MachineFunction &MF = getMachineFunction();
7772   uint64_t Size =
7773       MemoryLocation::getSizeOrUnknown(Val.getValueType().getStoreSize());
7774   MachineMemOperand *MMO =
7775       MF.getMachineMemOperand(PtrInfo, MMOFlags, Size, Alignment, AAInfo);
7776   return getStoreVP(Chain, dl, Val, Ptr, Mask, EVL, MMO, IsCompressing);
7777 }
7778 
7779 SDValue SelectionDAG::getStoreVP(SDValue Chain, const SDLoc &dl, SDValue Val,
7780                                  SDValue Ptr, SDValue Mask, SDValue EVL,
7781                                  MachineMemOperand *MMO, bool IsCompressing) {
7782   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
7783   EVT VT = Val.getValueType();
7784   SDVTList VTs = getVTList(MVT::Other);
7785   SDValue Undef = getUNDEF(Ptr.getValueType());
7786   SDValue Ops[] = {Chain, Val, Ptr, Undef, Mask, EVL};
7787   FoldingSetNodeID ID;
7788   AddNodeIDNode(ID, ISD::VP_STORE, VTs, Ops);
7789   ID.AddInteger(VT.getRawBits());
7790   ID.AddInteger(getSyntheticNodeSubclassData<VPStoreSDNode>(
7791       dl.getIROrder(), VTs, ISD::UNINDEXED, false, IsCompressing, VT, MMO));
7792   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7793   void *IP = nullptr;
7794   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7795     cast<VPStoreSDNode>(E)->refineAlignment(MMO);
7796     return SDValue(E, 0);
7797   }
7798   auto *N =
7799       newSDNode<VPStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
7800                                ISD::UNINDEXED, false, IsCompressing, VT, MMO);
7801   createOperands(N, Ops);
7802 
7803   CSEMap.InsertNode(N, IP);
7804   InsertNode(N);
7805   SDValue V(N, 0);
7806   NewSDValueDbgMsg(V, "Creating new node: ", this);
7807   return V;
7808 }
7809 
7810 SDValue SelectionDAG::getTruncStoreVP(SDValue Chain, const SDLoc &dl,
7811                                       SDValue Val, SDValue Ptr, SDValue Mask,
7812                                       SDValue EVL, MachinePointerInfo PtrInfo,
7813                                       EVT SVT, Align Alignment,
7814                                       MachineMemOperand::Flags MMOFlags,
7815                                       const AAMDNodes &AAInfo,
7816                                       bool IsCompressing) {
7817   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
7818 
7819   MMOFlags |= MachineMemOperand::MOStore;
7820   assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
7821 
7822   if (PtrInfo.V.isNull())
7823     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
7824 
7825   MachineFunction &MF = getMachineFunction();
7826   MachineMemOperand *MMO = MF.getMachineMemOperand(
7827       PtrInfo, MMOFlags, MemoryLocation::getSizeOrUnknown(SVT.getStoreSize()),
7828       Alignment, AAInfo);
7829   return getTruncStoreVP(Chain, dl, Val, Ptr, Mask, EVL, SVT, MMO,
7830                          IsCompressing);
7831 }
7832 
7833 SDValue SelectionDAG::getTruncStoreVP(SDValue Chain, const SDLoc &dl,
7834                                       SDValue Val, SDValue Ptr, SDValue Mask,
7835                                       SDValue EVL, EVT SVT,
7836                                       MachineMemOperand *MMO,
7837                                       bool IsCompressing) {
7838   EVT VT = Val.getValueType();
7839 
7840   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
7841   if (VT == SVT)
7842     return getStoreVP(Chain, dl, Val, Ptr, Mask, EVL, MMO, IsCompressing);
7843 
7844   assert(SVT.getScalarType().bitsLT(VT.getScalarType()) &&
7845          "Should only be a truncating store, not extending!");
7846   assert(VT.isInteger() == SVT.isInteger() && "Can't do FP-INT conversion!");
7847   assert(VT.isVector() == SVT.isVector() &&
7848          "Cannot use trunc store to convert to or from a vector!");
7849   assert((!VT.isVector() ||
7850           VT.getVectorElementCount() == SVT.getVectorElementCount()) &&
7851          "Cannot use trunc store to change the number of vector elements!");
7852 
7853   SDVTList VTs = getVTList(MVT::Other);
7854   SDValue Undef = getUNDEF(Ptr.getValueType());
7855   SDValue Ops[] = {Chain, Val, Ptr, Undef, Mask, EVL};
7856   FoldingSetNodeID ID;
7857   AddNodeIDNode(ID, ISD::VP_STORE, VTs, Ops);
7858   ID.AddInteger(SVT.getRawBits());
7859   ID.AddInteger(getSyntheticNodeSubclassData<VPStoreSDNode>(
7860       dl.getIROrder(), VTs, ISD::UNINDEXED, true, IsCompressing, SVT, MMO));
7861   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7862   void *IP = nullptr;
7863   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7864     cast<VPStoreSDNode>(E)->refineAlignment(MMO);
7865     return SDValue(E, 0);
7866   }
7867   auto *N =
7868       newSDNode<VPStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
7869                                ISD::UNINDEXED, true, IsCompressing, SVT, MMO);
7870   createOperands(N, Ops);
7871 
7872   CSEMap.InsertNode(N, IP);
7873   InsertNode(N);
7874   SDValue V(N, 0);
7875   NewSDValueDbgMsg(V, "Creating new node: ", this);
7876   return V;
7877 }
7878 
7879 SDValue SelectionDAG::getIndexedStoreVP(SDValue OrigStore, const SDLoc &dl,
7880                                         SDValue Base, SDValue Offset,
7881                                         ISD::MemIndexedMode AM) {
7882   auto *ST = cast<VPStoreSDNode>(OrigStore);
7883   assert(ST->getOffset().isUndef() && "Store is already an indexed store!");
7884   SDVTList VTs = getVTList(Base.getValueType(), MVT::Other);
7885   SDValue Ops[] = {ST->getChain(), ST->getValue(), Base,
7886                    Offset,         ST->getMask(),  ST->getVectorLength()};
7887   FoldingSetNodeID ID;
7888   AddNodeIDNode(ID, ISD::VP_STORE, VTs, Ops);
7889   ID.AddInteger(ST->getMemoryVT().getRawBits());
7890   ID.AddInteger(ST->getRawSubclassData());
7891   ID.AddInteger(ST->getPointerInfo().getAddrSpace());
7892   void *IP = nullptr;
7893   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
7894     return SDValue(E, 0);
7895 
7896   auto *N = newSDNode<VPStoreSDNode>(
7897       dl.getIROrder(), dl.getDebugLoc(), VTs, AM, ST->isTruncatingStore(),
7898       ST->isCompressingStore(), ST->getMemoryVT(), ST->getMemOperand());
7899   createOperands(N, Ops);
7900 
7901   CSEMap.InsertNode(N, IP);
7902   InsertNode(N);
7903   SDValue V(N, 0);
7904   NewSDValueDbgMsg(V, "Creating new node: ", this);
7905   return V;
7906 }
7907 
7908 SDValue SelectionDAG::getGatherVP(SDVTList VTs, EVT VT, const SDLoc &dl,
7909                                   ArrayRef<SDValue> Ops, MachineMemOperand *MMO,
7910                                   ISD::MemIndexType IndexType) {
7911   assert(Ops.size() == 6 && "Incompatible number of operands");
7912 
7913   FoldingSetNodeID ID;
7914   AddNodeIDNode(ID, ISD::VP_GATHER, VTs, Ops);
7915   ID.AddInteger(VT.getRawBits());
7916   ID.AddInteger(getSyntheticNodeSubclassData<VPGatherSDNode>(
7917       dl.getIROrder(), VTs, VT, MMO, IndexType));
7918   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7919   void *IP = nullptr;
7920   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7921     cast<VPGatherSDNode>(E)->refineAlignment(MMO);
7922     return SDValue(E, 0);
7923   }
7924 
7925   auto *N = newSDNode<VPGatherSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
7926                                       VT, MMO, IndexType);
7927   createOperands(N, Ops);
7928 
7929   assert(N->getMask().getValueType().getVectorElementCount() ==
7930              N->getValueType(0).getVectorElementCount() &&
7931          "Vector width mismatch between mask and data");
7932   assert(N->getIndex().getValueType().getVectorElementCount().isScalable() ==
7933              N->getValueType(0).getVectorElementCount().isScalable() &&
7934          "Scalable flags of index and data do not match");
7935   assert(ElementCount::isKnownGE(
7936              N->getIndex().getValueType().getVectorElementCount(),
7937              N->getValueType(0).getVectorElementCount()) &&
7938          "Vector width mismatch between index and data");
7939   assert(isa<ConstantSDNode>(N->getScale()) &&
7940          cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() &&
7941          "Scale should be a constant power of 2");
7942 
7943   CSEMap.InsertNode(N, IP);
7944   InsertNode(N);
7945   SDValue V(N, 0);
7946   NewSDValueDbgMsg(V, "Creating new node: ", this);
7947   return V;
7948 }
7949 
7950 SDValue SelectionDAG::getScatterVP(SDVTList VTs, EVT VT, const SDLoc &dl,
7951                                    ArrayRef<SDValue> Ops,
7952                                    MachineMemOperand *MMO,
7953                                    ISD::MemIndexType IndexType) {
7954   assert(Ops.size() == 7 && "Incompatible number of operands");
7955 
7956   FoldingSetNodeID ID;
7957   AddNodeIDNode(ID, ISD::VP_SCATTER, VTs, Ops);
7958   ID.AddInteger(VT.getRawBits());
7959   ID.AddInteger(getSyntheticNodeSubclassData<VPScatterSDNode>(
7960       dl.getIROrder(), VTs, VT, MMO, IndexType));
7961   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7962   void *IP = nullptr;
7963   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7964     cast<VPScatterSDNode>(E)->refineAlignment(MMO);
7965     return SDValue(E, 0);
7966   }
7967   auto *N = newSDNode<VPScatterSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
7968                                        VT, MMO, IndexType);
7969   createOperands(N, Ops);
7970 
7971   assert(N->getMask().getValueType().getVectorElementCount() ==
7972              N->getValue().getValueType().getVectorElementCount() &&
7973          "Vector width mismatch between mask and data");
7974   assert(
7975       N->getIndex().getValueType().getVectorElementCount().isScalable() ==
7976           N->getValue().getValueType().getVectorElementCount().isScalable() &&
7977       "Scalable flags of index and data do not match");
7978   assert(ElementCount::isKnownGE(
7979              N->getIndex().getValueType().getVectorElementCount(),
7980              N->getValue().getValueType().getVectorElementCount()) &&
7981          "Vector width mismatch between index and data");
7982   assert(isa<ConstantSDNode>(N->getScale()) &&
7983          cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() &&
7984          "Scale should be a constant power of 2");
7985 
7986   CSEMap.InsertNode(N, IP);
7987   InsertNode(N);
7988   SDValue V(N, 0);
7989   NewSDValueDbgMsg(V, "Creating new node: ", this);
7990   return V;
7991 }
7992 
7993 SDValue SelectionDAG::getMaskedLoad(EVT VT, const SDLoc &dl, SDValue Chain,
7994                                     SDValue Base, SDValue Offset, SDValue Mask,
7995                                     SDValue PassThru, EVT MemVT,
7996                                     MachineMemOperand *MMO,
7997                                     ISD::MemIndexedMode AM,
7998                                     ISD::LoadExtType ExtTy, bool isExpanding) {
7999   bool Indexed = AM != ISD::UNINDEXED;
8000   assert((Indexed || Offset.isUndef()) &&
8001          "Unindexed masked load with an offset!");
8002   SDVTList VTs = Indexed ? getVTList(VT, Base.getValueType(), MVT::Other)
8003                          : getVTList(VT, MVT::Other);
8004   SDValue Ops[] = {Chain, Base, Offset, Mask, PassThru};
8005   FoldingSetNodeID ID;
8006   AddNodeIDNode(ID, ISD::MLOAD, VTs, Ops);
8007   ID.AddInteger(MemVT.getRawBits());
8008   ID.AddInteger(getSyntheticNodeSubclassData<MaskedLoadSDNode>(
8009       dl.getIROrder(), VTs, AM, ExtTy, isExpanding, MemVT, MMO));
8010   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8011   void *IP = nullptr;
8012   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
8013     cast<MaskedLoadSDNode>(E)->refineAlignment(MMO);
8014     return SDValue(E, 0);
8015   }
8016   auto *N = newSDNode<MaskedLoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
8017                                         AM, ExtTy, isExpanding, MemVT, MMO);
8018   createOperands(N, Ops);
8019 
8020   CSEMap.InsertNode(N, IP);
8021   InsertNode(N);
8022   SDValue V(N, 0);
8023   NewSDValueDbgMsg(V, "Creating new node: ", this);
8024   return V;
8025 }
8026 
8027 SDValue SelectionDAG::getIndexedMaskedLoad(SDValue OrigLoad, const SDLoc &dl,
8028                                            SDValue Base, SDValue Offset,
8029                                            ISD::MemIndexedMode AM) {
8030   MaskedLoadSDNode *LD = cast<MaskedLoadSDNode>(OrigLoad);
8031   assert(LD->getOffset().isUndef() && "Masked load is already a indexed load!");
8032   return getMaskedLoad(OrigLoad.getValueType(), dl, LD->getChain(), Base,
8033                        Offset, LD->getMask(), LD->getPassThru(),
8034                        LD->getMemoryVT(), LD->getMemOperand(), AM,
8035                        LD->getExtensionType(), LD->isExpandingLoad());
8036 }
8037 
8038 SDValue SelectionDAG::getMaskedStore(SDValue Chain, const SDLoc &dl,
8039                                      SDValue Val, SDValue Base, SDValue Offset,
8040                                      SDValue Mask, EVT MemVT,
8041                                      MachineMemOperand *MMO,
8042                                      ISD::MemIndexedMode AM, bool IsTruncating,
8043                                      bool IsCompressing) {
8044   assert(Chain.getValueType() == MVT::Other &&
8045         "Invalid chain type");
8046   bool Indexed = AM != ISD::UNINDEXED;
8047   assert((Indexed || Offset.isUndef()) &&
8048          "Unindexed masked store with an offset!");
8049   SDVTList VTs = Indexed ? getVTList(Base.getValueType(), MVT::Other)
8050                          : getVTList(MVT::Other);
8051   SDValue Ops[] = {Chain, Val, Base, Offset, Mask};
8052   FoldingSetNodeID ID;
8053   AddNodeIDNode(ID, ISD::MSTORE, VTs, Ops);
8054   ID.AddInteger(MemVT.getRawBits());
8055   ID.AddInteger(getSyntheticNodeSubclassData<MaskedStoreSDNode>(
8056       dl.getIROrder(), VTs, AM, IsTruncating, IsCompressing, MemVT, MMO));
8057   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8058   void *IP = nullptr;
8059   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
8060     cast<MaskedStoreSDNode>(E)->refineAlignment(MMO);
8061     return SDValue(E, 0);
8062   }
8063   auto *N =
8064       newSDNode<MaskedStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
8065                                    IsTruncating, IsCompressing, MemVT, MMO);
8066   createOperands(N, Ops);
8067 
8068   CSEMap.InsertNode(N, IP);
8069   InsertNode(N);
8070   SDValue V(N, 0);
8071   NewSDValueDbgMsg(V, "Creating new node: ", this);
8072   return V;
8073 }
8074 
8075 SDValue SelectionDAG::getIndexedMaskedStore(SDValue OrigStore, const SDLoc &dl,
8076                                             SDValue Base, SDValue Offset,
8077                                             ISD::MemIndexedMode AM) {
8078   MaskedStoreSDNode *ST = cast<MaskedStoreSDNode>(OrigStore);
8079   assert(ST->getOffset().isUndef() &&
8080          "Masked store is already a indexed store!");
8081   return getMaskedStore(ST->getChain(), dl, ST->getValue(), Base, Offset,
8082                         ST->getMask(), ST->getMemoryVT(), ST->getMemOperand(),
8083                         AM, ST->isTruncatingStore(), ST->isCompressingStore());
8084 }
8085 
8086 SDValue SelectionDAG::getMaskedGather(SDVTList VTs, EVT MemVT, const SDLoc &dl,
8087                                       ArrayRef<SDValue> Ops,
8088                                       MachineMemOperand *MMO,
8089                                       ISD::MemIndexType IndexType,
8090                                       ISD::LoadExtType ExtTy) {
8091   assert(Ops.size() == 6 && "Incompatible number of operands");
8092 
8093   FoldingSetNodeID ID;
8094   AddNodeIDNode(ID, ISD::MGATHER, VTs, Ops);
8095   ID.AddInteger(MemVT.getRawBits());
8096   ID.AddInteger(getSyntheticNodeSubclassData<MaskedGatherSDNode>(
8097       dl.getIROrder(), VTs, MemVT, MMO, IndexType, ExtTy));
8098   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8099   void *IP = nullptr;
8100   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
8101     cast<MaskedGatherSDNode>(E)->refineAlignment(MMO);
8102     return SDValue(E, 0);
8103   }
8104 
8105   IndexType = TLI->getCanonicalIndexType(IndexType, MemVT, Ops[4]);
8106   auto *N = newSDNode<MaskedGatherSDNode>(dl.getIROrder(), dl.getDebugLoc(),
8107                                           VTs, MemVT, MMO, IndexType, ExtTy);
8108   createOperands(N, Ops);
8109 
8110   assert(N->getPassThru().getValueType() == N->getValueType(0) &&
8111          "Incompatible type of the PassThru value in MaskedGatherSDNode");
8112   assert(N->getMask().getValueType().getVectorElementCount() ==
8113              N->getValueType(0).getVectorElementCount() &&
8114          "Vector width mismatch between mask and data");
8115   assert(N->getIndex().getValueType().getVectorElementCount().isScalable() ==
8116              N->getValueType(0).getVectorElementCount().isScalable() &&
8117          "Scalable flags of index and data do not match");
8118   assert(ElementCount::isKnownGE(
8119              N->getIndex().getValueType().getVectorElementCount(),
8120              N->getValueType(0).getVectorElementCount()) &&
8121          "Vector width mismatch between index and data");
8122   assert(isa<ConstantSDNode>(N->getScale()) &&
8123          cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() &&
8124          "Scale should be a constant power of 2");
8125 
8126   CSEMap.InsertNode(N, IP);
8127   InsertNode(N);
8128   SDValue V(N, 0);
8129   NewSDValueDbgMsg(V, "Creating new node: ", this);
8130   return V;
8131 }
8132 
8133 SDValue SelectionDAG::getMaskedScatter(SDVTList VTs, EVT MemVT, const SDLoc &dl,
8134                                        ArrayRef<SDValue> Ops,
8135                                        MachineMemOperand *MMO,
8136                                        ISD::MemIndexType IndexType,
8137                                        bool IsTrunc) {
8138   assert(Ops.size() == 6 && "Incompatible number of operands");
8139 
8140   FoldingSetNodeID ID;
8141   AddNodeIDNode(ID, ISD::MSCATTER, VTs, Ops);
8142   ID.AddInteger(MemVT.getRawBits());
8143   ID.AddInteger(getSyntheticNodeSubclassData<MaskedScatterSDNode>(
8144       dl.getIROrder(), VTs, MemVT, MMO, IndexType, IsTrunc));
8145   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8146   void *IP = nullptr;
8147   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
8148     cast<MaskedScatterSDNode>(E)->refineAlignment(MMO);
8149     return SDValue(E, 0);
8150   }
8151 
8152   IndexType = TLI->getCanonicalIndexType(IndexType, MemVT, Ops[4]);
8153   auto *N = newSDNode<MaskedScatterSDNode>(dl.getIROrder(), dl.getDebugLoc(),
8154                                            VTs, MemVT, MMO, IndexType, IsTrunc);
8155   createOperands(N, Ops);
8156 
8157   assert(N->getMask().getValueType().getVectorElementCount() ==
8158              N->getValue().getValueType().getVectorElementCount() &&
8159          "Vector width mismatch between mask and data");
8160   assert(
8161       N->getIndex().getValueType().getVectorElementCount().isScalable() ==
8162           N->getValue().getValueType().getVectorElementCount().isScalable() &&
8163       "Scalable flags of index and data do not match");
8164   assert(ElementCount::isKnownGE(
8165              N->getIndex().getValueType().getVectorElementCount(),
8166              N->getValue().getValueType().getVectorElementCount()) &&
8167          "Vector width mismatch between index and data");
8168   assert(isa<ConstantSDNode>(N->getScale()) &&
8169          cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() &&
8170          "Scale should be a constant power of 2");
8171 
8172   CSEMap.InsertNode(N, IP);
8173   InsertNode(N);
8174   SDValue V(N, 0);
8175   NewSDValueDbgMsg(V, "Creating new node: ", this);
8176   return V;
8177 }
8178 
8179 SDValue SelectionDAG::simplifySelect(SDValue Cond, SDValue T, SDValue F) {
8180   // select undef, T, F --> T (if T is a constant), otherwise F
8181   // select, ?, undef, F --> F
8182   // select, ?, T, undef --> T
8183   if (Cond.isUndef())
8184     return isConstantValueOfAnyType(T) ? T : F;
8185   if (T.isUndef())
8186     return F;
8187   if (F.isUndef())
8188     return T;
8189 
8190   // select true, T, F --> T
8191   // select false, T, F --> F
8192   if (auto *CondC = dyn_cast<ConstantSDNode>(Cond))
8193     return CondC->isZero() ? F : T;
8194 
8195   // TODO: This should simplify VSELECT with constant condition using something
8196   // like this (but check boolean contents to be complete?):
8197   //  if (ISD::isBuildVectorAllOnes(Cond.getNode()))
8198   //    return T;
8199   //  if (ISD::isBuildVectorAllZeros(Cond.getNode()))
8200   //    return F;
8201 
8202   // select ?, T, T --> T
8203   if (T == F)
8204     return T;
8205 
8206   return SDValue();
8207 }
8208 
8209 SDValue SelectionDAG::simplifyShift(SDValue X, SDValue Y) {
8210   // shift undef, Y --> 0 (can always assume that the undef value is 0)
8211   if (X.isUndef())
8212     return getConstant(0, SDLoc(X.getNode()), X.getValueType());
8213   // shift X, undef --> undef (because it may shift by the bitwidth)
8214   if (Y.isUndef())
8215     return getUNDEF(X.getValueType());
8216 
8217   // shift 0, Y --> 0
8218   // shift X, 0 --> X
8219   if (isNullOrNullSplat(X) || isNullOrNullSplat(Y))
8220     return X;
8221 
8222   // shift X, C >= bitwidth(X) --> undef
8223   // All vector elements must be too big (or undef) to avoid partial undefs.
8224   auto isShiftTooBig = [X](ConstantSDNode *Val) {
8225     return !Val || Val->getAPIntValue().uge(X.getScalarValueSizeInBits());
8226   };
8227   if (ISD::matchUnaryPredicate(Y, isShiftTooBig, true))
8228     return getUNDEF(X.getValueType());
8229 
8230   return SDValue();
8231 }
8232 
8233 SDValue SelectionDAG::simplifyFPBinop(unsigned Opcode, SDValue X, SDValue Y,
8234                                       SDNodeFlags Flags) {
8235   // If this operation has 'nnan' or 'ninf' and at least 1 disallowed operand
8236   // (an undef operand can be chosen to be Nan/Inf), then the result of this
8237   // operation is poison. That result can be relaxed to undef.
8238   ConstantFPSDNode *XC = isConstOrConstSplatFP(X, /* AllowUndefs */ true);
8239   ConstantFPSDNode *YC = isConstOrConstSplatFP(Y, /* AllowUndefs */ true);
8240   bool HasNan = (XC && XC->getValueAPF().isNaN()) ||
8241                 (YC && YC->getValueAPF().isNaN());
8242   bool HasInf = (XC && XC->getValueAPF().isInfinity()) ||
8243                 (YC && YC->getValueAPF().isInfinity());
8244 
8245   if (Flags.hasNoNaNs() && (HasNan || X.isUndef() || Y.isUndef()))
8246     return getUNDEF(X.getValueType());
8247 
8248   if (Flags.hasNoInfs() && (HasInf || X.isUndef() || Y.isUndef()))
8249     return getUNDEF(X.getValueType());
8250 
8251   if (!YC)
8252     return SDValue();
8253 
8254   // X + -0.0 --> X
8255   if (Opcode == ISD::FADD)
8256     if (YC->getValueAPF().isNegZero())
8257       return X;
8258 
8259   // X - +0.0 --> X
8260   if (Opcode == ISD::FSUB)
8261     if (YC->getValueAPF().isPosZero())
8262       return X;
8263 
8264   // X * 1.0 --> X
8265   // X / 1.0 --> X
8266   if (Opcode == ISD::FMUL || Opcode == ISD::FDIV)
8267     if (YC->getValueAPF().isExactlyValue(1.0))
8268       return X;
8269 
8270   // X * 0.0 --> 0.0
8271   if (Opcode == ISD::FMUL && Flags.hasNoNaNs() && Flags.hasNoSignedZeros())
8272     if (YC->getValueAPF().isZero())
8273       return getConstantFP(0.0, SDLoc(Y), Y.getValueType());
8274 
8275   return SDValue();
8276 }
8277 
8278 SDValue SelectionDAG::getVAArg(EVT VT, const SDLoc &dl, SDValue Chain,
8279                                SDValue Ptr, SDValue SV, unsigned Align) {
8280   SDValue Ops[] = { Chain, Ptr, SV, getTargetConstant(Align, dl, MVT::i32) };
8281   return getNode(ISD::VAARG, dl, getVTList(VT, MVT::Other), Ops);
8282 }
8283 
8284 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
8285                               ArrayRef<SDUse> Ops) {
8286   switch (Ops.size()) {
8287   case 0: return getNode(Opcode, DL, VT);
8288   case 1: return getNode(Opcode, DL, VT, static_cast<const SDValue>(Ops[0]));
8289   case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1]);
8290   case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2]);
8291   default: break;
8292   }
8293 
8294   // Copy from an SDUse array into an SDValue array for use with
8295   // the regular getNode logic.
8296   SmallVector<SDValue, 8> NewOps(Ops.begin(), Ops.end());
8297   return getNode(Opcode, DL, VT, NewOps);
8298 }
8299 
8300 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
8301                               ArrayRef<SDValue> Ops) {
8302   SDNodeFlags Flags;
8303   if (Inserter)
8304     Flags = Inserter->getFlags();
8305   return getNode(Opcode, DL, VT, Ops, Flags);
8306 }
8307 
8308 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
8309                               ArrayRef<SDValue> Ops, const SDNodeFlags Flags) {
8310   unsigned NumOps = Ops.size();
8311   switch (NumOps) {
8312   case 0: return getNode(Opcode, DL, VT);
8313   case 1: return getNode(Opcode, DL, VT, Ops[0], Flags);
8314   case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Flags);
8315   case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2], Flags);
8316   default: break;
8317   }
8318 
8319 #ifndef NDEBUG
8320   for (auto &Op : Ops)
8321     assert(Op.getOpcode() != ISD::DELETED_NODE &&
8322            "Operand is DELETED_NODE!");
8323 #endif
8324 
8325   switch (Opcode) {
8326   default: break;
8327   case ISD::BUILD_VECTOR:
8328     // Attempt to simplify BUILD_VECTOR.
8329     if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
8330       return V;
8331     break;
8332   case ISD::CONCAT_VECTORS:
8333     if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this))
8334       return V;
8335     break;
8336   case ISD::SELECT_CC:
8337     assert(NumOps == 5 && "SELECT_CC takes 5 operands!");
8338     assert(Ops[0].getValueType() == Ops[1].getValueType() &&
8339            "LHS and RHS of condition must have same type!");
8340     assert(Ops[2].getValueType() == Ops[3].getValueType() &&
8341            "True and False arms of SelectCC must have same type!");
8342     assert(Ops[2].getValueType() == VT &&
8343            "select_cc node must be of same type as true and false value!");
8344     break;
8345   case ISD::BR_CC:
8346     assert(NumOps == 5 && "BR_CC takes 5 operands!");
8347     assert(Ops[2].getValueType() == Ops[3].getValueType() &&
8348            "LHS/RHS of comparison should match types!");
8349     break;
8350   }
8351 
8352   // Memoize nodes.
8353   SDNode *N;
8354   SDVTList VTs = getVTList(VT);
8355 
8356   if (VT != MVT::Glue) {
8357     FoldingSetNodeID ID;
8358     AddNodeIDNode(ID, Opcode, VTs, Ops);
8359     void *IP = nullptr;
8360 
8361     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
8362       return SDValue(E, 0);
8363 
8364     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
8365     createOperands(N, Ops);
8366 
8367     CSEMap.InsertNode(N, IP);
8368   } else {
8369     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
8370     createOperands(N, Ops);
8371   }
8372 
8373   N->setFlags(Flags);
8374   InsertNode(N);
8375   SDValue V(N, 0);
8376   NewSDValueDbgMsg(V, "Creating new node: ", this);
8377   return V;
8378 }
8379 
8380 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL,
8381                               ArrayRef<EVT> ResultTys, ArrayRef<SDValue> Ops) {
8382   return getNode(Opcode, DL, getVTList(ResultTys), Ops);
8383 }
8384 
8385 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
8386                               ArrayRef<SDValue> Ops) {
8387   SDNodeFlags Flags;
8388   if (Inserter)
8389     Flags = Inserter->getFlags();
8390   return getNode(Opcode, DL, VTList, Ops, Flags);
8391 }
8392 
8393 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
8394                               ArrayRef<SDValue> Ops, const SDNodeFlags Flags) {
8395   if (VTList.NumVTs == 1)
8396     return getNode(Opcode, DL, VTList.VTs[0], Ops);
8397 
8398 #ifndef NDEBUG
8399   for (auto &Op : Ops)
8400     assert(Op.getOpcode() != ISD::DELETED_NODE &&
8401            "Operand is DELETED_NODE!");
8402 #endif
8403 
8404   switch (Opcode) {
8405   case ISD::STRICT_FP_EXTEND:
8406     assert(VTList.NumVTs == 2 && Ops.size() == 2 &&
8407            "Invalid STRICT_FP_EXTEND!");
8408     assert(VTList.VTs[0].isFloatingPoint() &&
8409            Ops[1].getValueType().isFloatingPoint() && "Invalid FP cast!");
8410     assert(VTList.VTs[0].isVector() == Ops[1].getValueType().isVector() &&
8411            "STRICT_FP_EXTEND result type should be vector iff the operand "
8412            "type is vector!");
8413     assert((!VTList.VTs[0].isVector() ||
8414             VTList.VTs[0].getVectorNumElements() ==
8415             Ops[1].getValueType().getVectorNumElements()) &&
8416            "Vector element count mismatch!");
8417     assert(Ops[1].getValueType().bitsLT(VTList.VTs[0]) &&
8418            "Invalid fpext node, dst <= src!");
8419     break;
8420   case ISD::STRICT_FP_ROUND:
8421     assert(VTList.NumVTs == 2 && Ops.size() == 3 && "Invalid STRICT_FP_ROUND!");
8422     assert(VTList.VTs[0].isVector() == Ops[1].getValueType().isVector() &&
8423            "STRICT_FP_ROUND result type should be vector iff the operand "
8424            "type is vector!");
8425     assert((!VTList.VTs[0].isVector() ||
8426             VTList.VTs[0].getVectorNumElements() ==
8427             Ops[1].getValueType().getVectorNumElements()) &&
8428            "Vector element count mismatch!");
8429     assert(VTList.VTs[0].isFloatingPoint() &&
8430            Ops[1].getValueType().isFloatingPoint() &&
8431            VTList.VTs[0].bitsLT(Ops[1].getValueType()) &&
8432            isa<ConstantSDNode>(Ops[2]) &&
8433            (cast<ConstantSDNode>(Ops[2])->getZExtValue() == 0 ||
8434             cast<ConstantSDNode>(Ops[2])->getZExtValue() == 1) &&
8435            "Invalid STRICT_FP_ROUND!");
8436     break;
8437 #if 0
8438   // FIXME: figure out how to safely handle things like
8439   // int foo(int x) { return 1 << (x & 255); }
8440   // int bar() { return foo(256); }
8441   case ISD::SRA_PARTS:
8442   case ISD::SRL_PARTS:
8443   case ISD::SHL_PARTS:
8444     if (N3.getOpcode() == ISD::SIGN_EXTEND_INREG &&
8445         cast<VTSDNode>(N3.getOperand(1))->getVT() != MVT::i1)
8446       return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0));
8447     else if (N3.getOpcode() == ISD::AND)
8448       if (ConstantSDNode *AndRHS = dyn_cast<ConstantSDNode>(N3.getOperand(1))) {
8449         // If the and is only masking out bits that cannot effect the shift,
8450         // eliminate the and.
8451         unsigned NumBits = VT.getScalarSizeInBits()*2;
8452         if ((AndRHS->getValue() & (NumBits-1)) == NumBits-1)
8453           return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0));
8454       }
8455     break;
8456 #endif
8457   }
8458 
8459   // Memoize the node unless it returns a flag.
8460   SDNode *N;
8461   if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) {
8462     FoldingSetNodeID ID;
8463     AddNodeIDNode(ID, Opcode, VTList, Ops);
8464     void *IP = nullptr;
8465     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
8466       return SDValue(E, 0);
8467 
8468     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList);
8469     createOperands(N, Ops);
8470     CSEMap.InsertNode(N, IP);
8471   } else {
8472     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList);
8473     createOperands(N, Ops);
8474   }
8475 
8476   N->setFlags(Flags);
8477   InsertNode(N);
8478   SDValue V(N, 0);
8479   NewSDValueDbgMsg(V, "Creating new node: ", this);
8480   return V;
8481 }
8482 
8483 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL,
8484                               SDVTList VTList) {
8485   return getNode(Opcode, DL, VTList, None);
8486 }
8487 
8488 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
8489                               SDValue N1) {
8490   SDValue Ops[] = { N1 };
8491   return getNode(Opcode, DL, VTList, Ops);
8492 }
8493 
8494 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
8495                               SDValue N1, SDValue N2) {
8496   SDValue Ops[] = { N1, N2 };
8497   return getNode(Opcode, DL, VTList, Ops);
8498 }
8499 
8500 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
8501                               SDValue N1, SDValue N2, SDValue N3) {
8502   SDValue Ops[] = { N1, N2, N3 };
8503   return getNode(Opcode, DL, VTList, Ops);
8504 }
8505 
8506 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
8507                               SDValue N1, SDValue N2, SDValue N3, SDValue N4) {
8508   SDValue Ops[] = { N1, N2, N3, N4 };
8509   return getNode(Opcode, DL, VTList, Ops);
8510 }
8511 
8512 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
8513                               SDValue N1, SDValue N2, SDValue N3, SDValue N4,
8514                               SDValue N5) {
8515   SDValue Ops[] = { N1, N2, N3, N4, N5 };
8516   return getNode(Opcode, DL, VTList, Ops);
8517 }
8518 
8519 SDVTList SelectionDAG::getVTList(EVT VT) {
8520   return makeVTList(SDNode::getValueTypeList(VT), 1);
8521 }
8522 
8523 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2) {
8524   FoldingSetNodeID ID;
8525   ID.AddInteger(2U);
8526   ID.AddInteger(VT1.getRawBits());
8527   ID.AddInteger(VT2.getRawBits());
8528 
8529   void *IP = nullptr;
8530   SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
8531   if (!Result) {
8532     EVT *Array = Allocator.Allocate<EVT>(2);
8533     Array[0] = VT1;
8534     Array[1] = VT2;
8535     Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 2);
8536     VTListMap.InsertNode(Result, IP);
8537   }
8538   return Result->getSDVTList();
8539 }
8540 
8541 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3) {
8542   FoldingSetNodeID ID;
8543   ID.AddInteger(3U);
8544   ID.AddInteger(VT1.getRawBits());
8545   ID.AddInteger(VT2.getRawBits());
8546   ID.AddInteger(VT3.getRawBits());
8547 
8548   void *IP = nullptr;
8549   SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
8550   if (!Result) {
8551     EVT *Array = Allocator.Allocate<EVT>(3);
8552     Array[0] = VT1;
8553     Array[1] = VT2;
8554     Array[2] = VT3;
8555     Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 3);
8556     VTListMap.InsertNode(Result, IP);
8557   }
8558   return Result->getSDVTList();
8559 }
8560 
8561 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3, EVT VT4) {
8562   FoldingSetNodeID ID;
8563   ID.AddInteger(4U);
8564   ID.AddInteger(VT1.getRawBits());
8565   ID.AddInteger(VT2.getRawBits());
8566   ID.AddInteger(VT3.getRawBits());
8567   ID.AddInteger(VT4.getRawBits());
8568 
8569   void *IP = nullptr;
8570   SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
8571   if (!Result) {
8572     EVT *Array = Allocator.Allocate<EVT>(4);
8573     Array[0] = VT1;
8574     Array[1] = VT2;
8575     Array[2] = VT3;
8576     Array[3] = VT4;
8577     Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 4);
8578     VTListMap.InsertNode(Result, IP);
8579   }
8580   return Result->getSDVTList();
8581 }
8582 
8583 SDVTList SelectionDAG::getVTList(ArrayRef<EVT> VTs) {
8584   unsigned NumVTs = VTs.size();
8585   FoldingSetNodeID ID;
8586   ID.AddInteger(NumVTs);
8587   for (unsigned index = 0; index < NumVTs; index++) {
8588     ID.AddInteger(VTs[index].getRawBits());
8589   }
8590 
8591   void *IP = nullptr;
8592   SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
8593   if (!Result) {
8594     EVT *Array = Allocator.Allocate<EVT>(NumVTs);
8595     llvm::copy(VTs, Array);
8596     Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, NumVTs);
8597     VTListMap.InsertNode(Result, IP);
8598   }
8599   return Result->getSDVTList();
8600 }
8601 
8602 
8603 /// UpdateNodeOperands - *Mutate* the specified node in-place to have the
8604 /// specified operands.  If the resultant node already exists in the DAG,
8605 /// this does not modify the specified node, instead it returns the node that
8606 /// already exists.  If the resultant node does not exist in the DAG, the
8607 /// input node is returned.  As a degenerate case, if you specify the same
8608 /// input operands as the node already has, the input node is returned.
8609 SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op) {
8610   assert(N->getNumOperands() == 1 && "Update with wrong number of operands");
8611 
8612   // Check to see if there is no change.
8613   if (Op == N->getOperand(0)) return N;
8614 
8615   // See if the modified node already exists.
8616   void *InsertPos = nullptr;
8617   if (SDNode *Existing = FindModifiedNodeSlot(N, Op, InsertPos))
8618     return Existing;
8619 
8620   // Nope it doesn't.  Remove the node from its current place in the maps.
8621   if (InsertPos)
8622     if (!RemoveNodeFromCSEMaps(N))
8623       InsertPos = nullptr;
8624 
8625   // Now we update the operands.
8626   N->OperandList[0].set(Op);
8627 
8628   updateDivergence(N);
8629   // If this gets put into a CSE map, add it.
8630   if (InsertPos) CSEMap.InsertNode(N, InsertPos);
8631   return N;
8632 }
8633 
8634 SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2) {
8635   assert(N->getNumOperands() == 2 && "Update with wrong number of operands");
8636 
8637   // Check to see if there is no change.
8638   if (Op1 == N->getOperand(0) && Op2 == N->getOperand(1))
8639     return N;   // No operands changed, just return the input node.
8640 
8641   // See if the modified node already exists.
8642   void *InsertPos = nullptr;
8643   if (SDNode *Existing = FindModifiedNodeSlot(N, Op1, Op2, InsertPos))
8644     return Existing;
8645 
8646   // Nope it doesn't.  Remove the node from its current place in the maps.
8647   if (InsertPos)
8648     if (!RemoveNodeFromCSEMaps(N))
8649       InsertPos = nullptr;
8650 
8651   // Now we update the operands.
8652   if (N->OperandList[0] != Op1)
8653     N->OperandList[0].set(Op1);
8654   if (N->OperandList[1] != Op2)
8655     N->OperandList[1].set(Op2);
8656 
8657   updateDivergence(N);
8658   // If this gets put into a CSE map, add it.
8659   if (InsertPos) CSEMap.InsertNode(N, InsertPos);
8660   return N;
8661 }
8662 
8663 SDNode *SelectionDAG::
8664 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2, SDValue Op3) {
8665   SDValue Ops[] = { Op1, Op2, Op3 };
8666   return UpdateNodeOperands(N, Ops);
8667 }
8668 
8669 SDNode *SelectionDAG::
8670 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2,
8671                    SDValue Op3, SDValue Op4) {
8672   SDValue Ops[] = { Op1, Op2, Op3, Op4 };
8673   return UpdateNodeOperands(N, Ops);
8674 }
8675 
8676 SDNode *SelectionDAG::
8677 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2,
8678                    SDValue Op3, SDValue Op4, SDValue Op5) {
8679   SDValue Ops[] = { Op1, Op2, Op3, Op4, Op5 };
8680   return UpdateNodeOperands(N, Ops);
8681 }
8682 
8683 SDNode *SelectionDAG::
8684 UpdateNodeOperands(SDNode *N, ArrayRef<SDValue> Ops) {
8685   unsigned NumOps = Ops.size();
8686   assert(N->getNumOperands() == NumOps &&
8687          "Update with wrong number of operands");
8688 
8689   // If no operands changed just return the input node.
8690   if (std::equal(Ops.begin(), Ops.end(), N->op_begin()))
8691     return N;
8692 
8693   // See if the modified node already exists.
8694   void *InsertPos = nullptr;
8695   if (SDNode *Existing = FindModifiedNodeSlot(N, Ops, InsertPos))
8696     return Existing;
8697 
8698   // Nope it doesn't.  Remove the node from its current place in the maps.
8699   if (InsertPos)
8700     if (!RemoveNodeFromCSEMaps(N))
8701       InsertPos = nullptr;
8702 
8703   // Now we update the operands.
8704   for (unsigned i = 0; i != NumOps; ++i)
8705     if (N->OperandList[i] != Ops[i])
8706       N->OperandList[i].set(Ops[i]);
8707 
8708   updateDivergence(N);
8709   // If this gets put into a CSE map, add it.
8710   if (InsertPos) CSEMap.InsertNode(N, InsertPos);
8711   return N;
8712 }
8713 
8714 /// DropOperands - Release the operands and set this node to have
8715 /// zero operands.
8716 void SDNode::DropOperands() {
8717   // Unlike the code in MorphNodeTo that does this, we don't need to
8718   // watch for dead nodes here.
8719   for (op_iterator I = op_begin(), E = op_end(); I != E; ) {
8720     SDUse &Use = *I++;
8721     Use.set(SDValue());
8722   }
8723 }
8724 
8725 void SelectionDAG::setNodeMemRefs(MachineSDNode *N,
8726                                   ArrayRef<MachineMemOperand *> NewMemRefs) {
8727   if (NewMemRefs.empty()) {
8728     N->clearMemRefs();
8729     return;
8730   }
8731 
8732   // Check if we can avoid allocating by storing a single reference directly.
8733   if (NewMemRefs.size() == 1) {
8734     N->MemRefs = NewMemRefs[0];
8735     N->NumMemRefs = 1;
8736     return;
8737   }
8738 
8739   MachineMemOperand **MemRefsBuffer =
8740       Allocator.template Allocate<MachineMemOperand *>(NewMemRefs.size());
8741   llvm::copy(NewMemRefs, MemRefsBuffer);
8742   N->MemRefs = MemRefsBuffer;
8743   N->NumMemRefs = static_cast<int>(NewMemRefs.size());
8744 }
8745 
8746 /// SelectNodeTo - These are wrappers around MorphNodeTo that accept a
8747 /// machine opcode.
8748 ///
8749 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8750                                    EVT VT) {
8751   SDVTList VTs = getVTList(VT);
8752   return SelectNodeTo(N, MachineOpc, VTs, None);
8753 }
8754 
8755 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8756                                    EVT VT, SDValue Op1) {
8757   SDVTList VTs = getVTList(VT);
8758   SDValue Ops[] = { Op1 };
8759   return SelectNodeTo(N, MachineOpc, VTs, Ops);
8760 }
8761 
8762 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8763                                    EVT VT, SDValue Op1,
8764                                    SDValue Op2) {
8765   SDVTList VTs = getVTList(VT);
8766   SDValue Ops[] = { Op1, Op2 };
8767   return SelectNodeTo(N, MachineOpc, VTs, Ops);
8768 }
8769 
8770 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8771                                    EVT VT, SDValue Op1,
8772                                    SDValue Op2, SDValue Op3) {
8773   SDVTList VTs = getVTList(VT);
8774   SDValue Ops[] = { Op1, Op2, Op3 };
8775   return SelectNodeTo(N, MachineOpc, VTs, Ops);
8776 }
8777 
8778 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8779                                    EVT VT, ArrayRef<SDValue> Ops) {
8780   SDVTList VTs = getVTList(VT);
8781   return SelectNodeTo(N, MachineOpc, VTs, Ops);
8782 }
8783 
8784 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8785                                    EVT VT1, EVT VT2, ArrayRef<SDValue> Ops) {
8786   SDVTList VTs = getVTList(VT1, VT2);
8787   return SelectNodeTo(N, MachineOpc, VTs, Ops);
8788 }
8789 
8790 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8791                                    EVT VT1, EVT VT2) {
8792   SDVTList VTs = getVTList(VT1, VT2);
8793   return SelectNodeTo(N, MachineOpc, VTs, None);
8794 }
8795 
8796 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8797                                    EVT VT1, EVT VT2, EVT VT3,
8798                                    ArrayRef<SDValue> Ops) {
8799   SDVTList VTs = getVTList(VT1, VT2, VT3);
8800   return SelectNodeTo(N, MachineOpc, VTs, Ops);
8801 }
8802 
8803 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8804                                    EVT VT1, EVT VT2,
8805                                    SDValue Op1, SDValue Op2) {
8806   SDVTList VTs = getVTList(VT1, VT2);
8807   SDValue Ops[] = { Op1, Op2 };
8808   return SelectNodeTo(N, MachineOpc, VTs, Ops);
8809 }
8810 
8811 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8812                                    SDVTList VTs,ArrayRef<SDValue> Ops) {
8813   SDNode *New = MorphNodeTo(N, ~MachineOpc, VTs, Ops);
8814   // Reset the NodeID to -1.
8815   New->setNodeId(-1);
8816   if (New != N) {
8817     ReplaceAllUsesWith(N, New);
8818     RemoveDeadNode(N);
8819   }
8820   return New;
8821 }
8822 
8823 /// UpdateSDLocOnMergeSDNode - If the opt level is -O0 then it throws away
8824 /// the line number information on the merged node since it is not possible to
8825 /// preserve the information that operation is associated with multiple lines.
8826 /// This will make the debugger working better at -O0, were there is a higher
8827 /// probability having other instructions associated with that line.
8828 ///
8829 /// For IROrder, we keep the smaller of the two
8830 SDNode *SelectionDAG::UpdateSDLocOnMergeSDNode(SDNode *N, const SDLoc &OLoc) {
8831   DebugLoc NLoc = N->getDebugLoc();
8832   if (NLoc && OptLevel == CodeGenOpt::None && OLoc.getDebugLoc() != NLoc) {
8833     N->setDebugLoc(DebugLoc());
8834   }
8835   unsigned Order = std::min(N->getIROrder(), OLoc.getIROrder());
8836   N->setIROrder(Order);
8837   return N;
8838 }
8839 
8840 /// MorphNodeTo - This *mutates* the specified node to have the specified
8841 /// return type, opcode, and operands.
8842 ///
8843 /// Note that MorphNodeTo returns the resultant node.  If there is already a
8844 /// node of the specified opcode and operands, it returns that node instead of
8845 /// the current one.  Note that the SDLoc need not be the same.
8846 ///
8847 /// Using MorphNodeTo is faster than creating a new node and swapping it in
8848 /// with ReplaceAllUsesWith both because it often avoids allocating a new
8849 /// node, and because it doesn't require CSE recalculation for any of
8850 /// the node's users.
8851 ///
8852 /// However, note that MorphNodeTo recursively deletes dead nodes from the DAG.
8853 /// As a consequence it isn't appropriate to use from within the DAG combiner or
8854 /// the legalizer which maintain worklists that would need to be updated when
8855 /// deleting things.
8856 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
8857                                   SDVTList VTs, ArrayRef<SDValue> Ops) {
8858   // If an identical node already exists, use it.
8859   void *IP = nullptr;
8860   if (VTs.VTs[VTs.NumVTs-1] != MVT::Glue) {
8861     FoldingSetNodeID ID;
8862     AddNodeIDNode(ID, Opc, VTs, Ops);
8863     if (SDNode *ON = FindNodeOrInsertPos(ID, SDLoc(N), IP))
8864       return UpdateSDLocOnMergeSDNode(ON, SDLoc(N));
8865   }
8866 
8867   if (!RemoveNodeFromCSEMaps(N))
8868     IP = nullptr;
8869 
8870   // Start the morphing.
8871   N->NodeType = Opc;
8872   N->ValueList = VTs.VTs;
8873   N->NumValues = VTs.NumVTs;
8874 
8875   // Clear the operands list, updating used nodes to remove this from their
8876   // use list.  Keep track of any operands that become dead as a result.
8877   SmallPtrSet<SDNode*, 16> DeadNodeSet;
8878   for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) {
8879     SDUse &Use = *I++;
8880     SDNode *Used = Use.getNode();
8881     Use.set(SDValue());
8882     if (Used->use_empty())
8883       DeadNodeSet.insert(Used);
8884   }
8885 
8886   // For MachineNode, initialize the memory references information.
8887   if (MachineSDNode *MN = dyn_cast<MachineSDNode>(N))
8888     MN->clearMemRefs();
8889 
8890   // Swap for an appropriately sized array from the recycler.
8891   removeOperands(N);
8892   createOperands(N, Ops);
8893 
8894   // Delete any nodes that are still dead after adding the uses for the
8895   // new operands.
8896   if (!DeadNodeSet.empty()) {
8897     SmallVector<SDNode *, 16> DeadNodes;
8898     for (SDNode *N : DeadNodeSet)
8899       if (N->use_empty())
8900         DeadNodes.push_back(N);
8901     RemoveDeadNodes(DeadNodes);
8902   }
8903 
8904   if (IP)
8905     CSEMap.InsertNode(N, IP);   // Memoize the new node.
8906   return N;
8907 }
8908 
8909 SDNode* SelectionDAG::mutateStrictFPToFP(SDNode *Node) {
8910   unsigned OrigOpc = Node->getOpcode();
8911   unsigned NewOpc;
8912   switch (OrigOpc) {
8913   default:
8914     llvm_unreachable("mutateStrictFPToFP called with unexpected opcode!");
8915 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN)               \
8916   case ISD::STRICT_##DAGN: NewOpc = ISD::DAGN; break;
8917 #define CMP_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN)               \
8918   case ISD::STRICT_##DAGN: NewOpc = ISD::SETCC; break;
8919 #include "llvm/IR/ConstrainedOps.def"
8920   }
8921 
8922   assert(Node->getNumValues() == 2 && "Unexpected number of results!");
8923 
8924   // We're taking this node out of the chain, so we need to re-link things.
8925   SDValue InputChain = Node->getOperand(0);
8926   SDValue OutputChain = SDValue(Node, 1);
8927   ReplaceAllUsesOfValueWith(OutputChain, InputChain);
8928 
8929   SmallVector<SDValue, 3> Ops;
8930   for (unsigned i = 1, e = Node->getNumOperands(); i != e; ++i)
8931     Ops.push_back(Node->getOperand(i));
8932 
8933   SDVTList VTs = getVTList(Node->getValueType(0));
8934   SDNode *Res = MorphNodeTo(Node, NewOpc, VTs, Ops);
8935 
8936   // MorphNodeTo can operate in two ways: if an existing node with the
8937   // specified operands exists, it can just return it.  Otherwise, it
8938   // updates the node in place to have the requested operands.
8939   if (Res == Node) {
8940     // If we updated the node in place, reset the node ID.  To the isel,
8941     // this should be just like a newly allocated machine node.
8942     Res->setNodeId(-1);
8943   } else {
8944     ReplaceAllUsesWith(Node, Res);
8945     RemoveDeadNode(Node);
8946   }
8947 
8948   return Res;
8949 }
8950 
8951 /// getMachineNode - These are used for target selectors to create a new node
8952 /// with specified return type(s), MachineInstr opcode, and operands.
8953 ///
8954 /// Note that getMachineNode returns the resultant node.  If there is already a
8955 /// node of the specified opcode and operands, it returns that node instead of
8956 /// the current one.
8957 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
8958                                             EVT VT) {
8959   SDVTList VTs = getVTList(VT);
8960   return getMachineNode(Opcode, dl, VTs, None);
8961 }
8962 
8963 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
8964                                             EVT VT, SDValue Op1) {
8965   SDVTList VTs = getVTList(VT);
8966   SDValue Ops[] = { Op1 };
8967   return getMachineNode(Opcode, dl, VTs, Ops);
8968 }
8969 
8970 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
8971                                             EVT VT, SDValue Op1, SDValue Op2) {
8972   SDVTList VTs = getVTList(VT);
8973   SDValue Ops[] = { Op1, Op2 };
8974   return getMachineNode(Opcode, dl, VTs, Ops);
8975 }
8976 
8977 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
8978                                             EVT VT, SDValue Op1, SDValue Op2,
8979                                             SDValue Op3) {
8980   SDVTList VTs = getVTList(VT);
8981   SDValue Ops[] = { Op1, Op2, Op3 };
8982   return getMachineNode(Opcode, dl, VTs, Ops);
8983 }
8984 
8985 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
8986                                             EVT VT, ArrayRef<SDValue> Ops) {
8987   SDVTList VTs = getVTList(VT);
8988   return getMachineNode(Opcode, dl, VTs, Ops);
8989 }
8990 
8991 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
8992                                             EVT VT1, EVT VT2, SDValue Op1,
8993                                             SDValue Op2) {
8994   SDVTList VTs = getVTList(VT1, VT2);
8995   SDValue Ops[] = { Op1, Op2 };
8996   return getMachineNode(Opcode, dl, VTs, Ops);
8997 }
8998 
8999 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9000                                             EVT VT1, EVT VT2, SDValue Op1,
9001                                             SDValue Op2, SDValue Op3) {
9002   SDVTList VTs = getVTList(VT1, VT2);
9003   SDValue Ops[] = { Op1, Op2, Op3 };
9004   return getMachineNode(Opcode, dl, VTs, Ops);
9005 }
9006 
9007 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9008                                             EVT VT1, EVT VT2,
9009                                             ArrayRef<SDValue> Ops) {
9010   SDVTList VTs = getVTList(VT1, VT2);
9011   return getMachineNode(Opcode, dl, VTs, Ops);
9012 }
9013 
9014 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9015                                             EVT VT1, EVT VT2, EVT VT3,
9016                                             SDValue Op1, SDValue Op2) {
9017   SDVTList VTs = getVTList(VT1, VT2, VT3);
9018   SDValue Ops[] = { Op1, Op2 };
9019   return getMachineNode(Opcode, dl, VTs, Ops);
9020 }
9021 
9022 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9023                                             EVT VT1, EVT VT2, EVT VT3,
9024                                             SDValue Op1, SDValue Op2,
9025                                             SDValue Op3) {
9026   SDVTList VTs = getVTList(VT1, VT2, VT3);
9027   SDValue Ops[] = { Op1, Op2, Op3 };
9028   return getMachineNode(Opcode, dl, VTs, Ops);
9029 }
9030 
9031 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9032                                             EVT VT1, EVT VT2, EVT VT3,
9033                                             ArrayRef<SDValue> Ops) {
9034   SDVTList VTs = getVTList(VT1, VT2, VT3);
9035   return getMachineNode(Opcode, dl, VTs, Ops);
9036 }
9037 
9038 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9039                                             ArrayRef<EVT> ResultTys,
9040                                             ArrayRef<SDValue> Ops) {
9041   SDVTList VTs = getVTList(ResultTys);
9042   return getMachineNode(Opcode, dl, VTs, Ops);
9043 }
9044 
9045 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &DL,
9046                                             SDVTList VTs,
9047                                             ArrayRef<SDValue> Ops) {
9048   bool DoCSE = VTs.VTs[VTs.NumVTs-1] != MVT::Glue;
9049   MachineSDNode *N;
9050   void *IP = nullptr;
9051 
9052   if (DoCSE) {
9053     FoldingSetNodeID ID;
9054     AddNodeIDNode(ID, ~Opcode, VTs, Ops);
9055     IP = nullptr;
9056     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
9057       return cast<MachineSDNode>(UpdateSDLocOnMergeSDNode(E, DL));
9058     }
9059   }
9060 
9061   // Allocate a new MachineSDNode.
9062   N = newSDNode<MachineSDNode>(~Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
9063   createOperands(N, Ops);
9064 
9065   if (DoCSE)
9066     CSEMap.InsertNode(N, IP);
9067 
9068   InsertNode(N);
9069   NewSDValueDbgMsg(SDValue(N, 0), "Creating new machine node: ", this);
9070   return N;
9071 }
9072 
9073 /// getTargetExtractSubreg - A convenience function for creating
9074 /// TargetOpcode::EXTRACT_SUBREG nodes.
9075 SDValue SelectionDAG::getTargetExtractSubreg(int SRIdx, const SDLoc &DL, EVT VT,
9076                                              SDValue Operand) {
9077   SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32);
9078   SDNode *Subreg = getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL,
9079                                   VT, Operand, SRIdxVal);
9080   return SDValue(Subreg, 0);
9081 }
9082 
9083 /// getTargetInsertSubreg - A convenience function for creating
9084 /// TargetOpcode::INSERT_SUBREG nodes.
9085 SDValue SelectionDAG::getTargetInsertSubreg(int SRIdx, const SDLoc &DL, EVT VT,
9086                                             SDValue Operand, SDValue Subreg) {
9087   SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32);
9088   SDNode *Result = getMachineNode(TargetOpcode::INSERT_SUBREG, DL,
9089                                   VT, Operand, Subreg, SRIdxVal);
9090   return SDValue(Result, 0);
9091 }
9092 
9093 /// getNodeIfExists - Get the specified node if it's already available, or
9094 /// else return NULL.
9095 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList,
9096                                       ArrayRef<SDValue> Ops) {
9097   SDNodeFlags Flags;
9098   if (Inserter)
9099     Flags = Inserter->getFlags();
9100   return getNodeIfExists(Opcode, VTList, Ops, Flags);
9101 }
9102 
9103 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList,
9104                                       ArrayRef<SDValue> Ops,
9105                                       const SDNodeFlags Flags) {
9106   if (VTList.VTs[VTList.NumVTs - 1] != MVT::Glue) {
9107     FoldingSetNodeID ID;
9108     AddNodeIDNode(ID, Opcode, VTList, Ops);
9109     void *IP = nullptr;
9110     if (SDNode *E = FindNodeOrInsertPos(ID, SDLoc(), IP)) {
9111       E->intersectFlagsWith(Flags);
9112       return E;
9113     }
9114   }
9115   return nullptr;
9116 }
9117 
9118 /// doesNodeExist - Check if a node exists without modifying its flags.
9119 bool SelectionDAG::doesNodeExist(unsigned Opcode, SDVTList VTList,
9120                                  ArrayRef<SDValue> Ops) {
9121   if (VTList.VTs[VTList.NumVTs - 1] != MVT::Glue) {
9122     FoldingSetNodeID ID;
9123     AddNodeIDNode(ID, Opcode, VTList, Ops);
9124     void *IP = nullptr;
9125     if (FindNodeOrInsertPos(ID, SDLoc(), IP))
9126       return true;
9127   }
9128   return false;
9129 }
9130 
9131 /// getDbgValue - Creates a SDDbgValue node.
9132 ///
9133 /// SDNode
9134 SDDbgValue *SelectionDAG::getDbgValue(DIVariable *Var, DIExpression *Expr,
9135                                       SDNode *N, unsigned R, bool IsIndirect,
9136                                       const DebugLoc &DL, unsigned O) {
9137   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
9138          "Expected inlined-at fields to agree");
9139   return new (DbgInfo->getAlloc())
9140       SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromNode(N, R),
9141                  {}, IsIndirect, DL, O,
9142                  /*IsVariadic=*/false);
9143 }
9144 
9145 /// Constant
9146 SDDbgValue *SelectionDAG::getConstantDbgValue(DIVariable *Var,
9147                                               DIExpression *Expr,
9148                                               const Value *C,
9149                                               const DebugLoc &DL, unsigned O) {
9150   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
9151          "Expected inlined-at fields to agree");
9152   return new (DbgInfo->getAlloc())
9153       SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromConst(C), {},
9154                  /*IsIndirect=*/false, DL, O,
9155                  /*IsVariadic=*/false);
9156 }
9157 
9158 /// FrameIndex
9159 SDDbgValue *SelectionDAG::getFrameIndexDbgValue(DIVariable *Var,
9160                                                 DIExpression *Expr, unsigned FI,
9161                                                 bool IsIndirect,
9162                                                 const DebugLoc &DL,
9163                                                 unsigned O) {
9164   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
9165          "Expected inlined-at fields to agree");
9166   return getFrameIndexDbgValue(Var, Expr, FI, {}, IsIndirect, DL, O);
9167 }
9168 
9169 /// FrameIndex with dependencies
9170 SDDbgValue *SelectionDAG::getFrameIndexDbgValue(DIVariable *Var,
9171                                                 DIExpression *Expr, unsigned FI,
9172                                                 ArrayRef<SDNode *> Dependencies,
9173                                                 bool IsIndirect,
9174                                                 const DebugLoc &DL,
9175                                                 unsigned O) {
9176   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
9177          "Expected inlined-at fields to agree");
9178   return new (DbgInfo->getAlloc())
9179       SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromFrameIdx(FI),
9180                  Dependencies, IsIndirect, DL, O,
9181                  /*IsVariadic=*/false);
9182 }
9183 
9184 /// VReg
9185 SDDbgValue *SelectionDAG::getVRegDbgValue(DIVariable *Var, DIExpression *Expr,
9186                                           unsigned VReg, bool IsIndirect,
9187                                           const DebugLoc &DL, unsigned O) {
9188   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
9189          "Expected inlined-at fields to agree");
9190   return new (DbgInfo->getAlloc())
9191       SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromVReg(VReg),
9192                  {}, IsIndirect, DL, O,
9193                  /*IsVariadic=*/false);
9194 }
9195 
9196 SDDbgValue *SelectionDAG::getDbgValueList(DIVariable *Var, DIExpression *Expr,
9197                                           ArrayRef<SDDbgOperand> Locs,
9198                                           ArrayRef<SDNode *> Dependencies,
9199                                           bool IsIndirect, const DebugLoc &DL,
9200                                           unsigned O, bool IsVariadic) {
9201   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
9202          "Expected inlined-at fields to agree");
9203   return new (DbgInfo->getAlloc())
9204       SDDbgValue(DbgInfo->getAlloc(), Var, Expr, Locs, Dependencies, IsIndirect,
9205                  DL, O, IsVariadic);
9206 }
9207 
9208 void SelectionDAG::transferDbgValues(SDValue From, SDValue To,
9209                                      unsigned OffsetInBits, unsigned SizeInBits,
9210                                      bool InvalidateDbg) {
9211   SDNode *FromNode = From.getNode();
9212   SDNode *ToNode = To.getNode();
9213   assert(FromNode && ToNode && "Can't modify dbg values");
9214 
9215   // PR35338
9216   // TODO: assert(From != To && "Redundant dbg value transfer");
9217   // TODO: assert(FromNode != ToNode && "Intranode dbg value transfer");
9218   if (From == To || FromNode == ToNode)
9219     return;
9220 
9221   if (!FromNode->getHasDebugValue())
9222     return;
9223 
9224   SDDbgOperand FromLocOp =
9225       SDDbgOperand::fromNode(From.getNode(), From.getResNo());
9226   SDDbgOperand ToLocOp = SDDbgOperand::fromNode(To.getNode(), To.getResNo());
9227 
9228   SmallVector<SDDbgValue *, 2> ClonedDVs;
9229   for (SDDbgValue *Dbg : GetDbgValues(FromNode)) {
9230     if (Dbg->isInvalidated())
9231       continue;
9232 
9233     // TODO: assert(!Dbg->isInvalidated() && "Transfer of invalid dbg value");
9234 
9235     // Create a new location ops vector that is equal to the old vector, but
9236     // with each instance of FromLocOp replaced with ToLocOp.
9237     bool Changed = false;
9238     auto NewLocOps = Dbg->copyLocationOps();
9239     std::replace_if(
9240         NewLocOps.begin(), NewLocOps.end(),
9241         [&Changed, FromLocOp](const SDDbgOperand &Op) {
9242           bool Match = Op == FromLocOp;
9243           Changed |= Match;
9244           return Match;
9245         },
9246         ToLocOp);
9247     // Ignore this SDDbgValue if we didn't find a matching location.
9248     if (!Changed)
9249       continue;
9250 
9251     DIVariable *Var = Dbg->getVariable();
9252     auto *Expr = Dbg->getExpression();
9253     // If a fragment is requested, update the expression.
9254     if (SizeInBits) {
9255       // When splitting a larger (e.g., sign-extended) value whose
9256       // lower bits are described with an SDDbgValue, do not attempt
9257       // to transfer the SDDbgValue to the upper bits.
9258       if (auto FI = Expr->getFragmentInfo())
9259         if (OffsetInBits + SizeInBits > FI->SizeInBits)
9260           continue;
9261       auto Fragment = DIExpression::createFragmentExpression(Expr, OffsetInBits,
9262                                                              SizeInBits);
9263       if (!Fragment)
9264         continue;
9265       Expr = *Fragment;
9266     }
9267 
9268     auto AdditionalDependencies = Dbg->getAdditionalDependencies();
9269     // Clone the SDDbgValue and move it to To.
9270     SDDbgValue *Clone = getDbgValueList(
9271         Var, Expr, NewLocOps, AdditionalDependencies, Dbg->isIndirect(),
9272         Dbg->getDebugLoc(), std::max(ToNode->getIROrder(), Dbg->getOrder()),
9273         Dbg->isVariadic());
9274     ClonedDVs.push_back(Clone);
9275 
9276     if (InvalidateDbg) {
9277       // Invalidate value and indicate the SDDbgValue should not be emitted.
9278       Dbg->setIsInvalidated();
9279       Dbg->setIsEmitted();
9280     }
9281   }
9282 
9283   for (SDDbgValue *Dbg : ClonedDVs) {
9284     assert(is_contained(Dbg->getSDNodes(), ToNode) &&
9285            "Transferred DbgValues should depend on the new SDNode");
9286     AddDbgValue(Dbg, false);
9287   }
9288 }
9289 
9290 void SelectionDAG::salvageDebugInfo(SDNode &N) {
9291   if (!N.getHasDebugValue())
9292     return;
9293 
9294   SmallVector<SDDbgValue *, 2> ClonedDVs;
9295   for (auto DV : GetDbgValues(&N)) {
9296     if (DV->isInvalidated())
9297       continue;
9298     switch (N.getOpcode()) {
9299     default:
9300       break;
9301     case ISD::ADD:
9302       SDValue N0 = N.getOperand(0);
9303       SDValue N1 = N.getOperand(1);
9304       if (!isConstantIntBuildVectorOrConstantInt(N0) &&
9305           isConstantIntBuildVectorOrConstantInt(N1)) {
9306         uint64_t Offset = N.getConstantOperandVal(1);
9307 
9308         // Rewrite an ADD constant node into a DIExpression. Since we are
9309         // performing arithmetic to compute the variable's *value* in the
9310         // DIExpression, we need to mark the expression with a
9311         // DW_OP_stack_value.
9312         auto *DIExpr = DV->getExpression();
9313         auto NewLocOps = DV->copyLocationOps();
9314         bool Changed = false;
9315         for (size_t i = 0; i < NewLocOps.size(); ++i) {
9316           // We're not given a ResNo to compare against because the whole
9317           // node is going away. We know that any ISD::ADD only has one
9318           // result, so we can assume any node match is using the result.
9319           if (NewLocOps[i].getKind() != SDDbgOperand::SDNODE ||
9320               NewLocOps[i].getSDNode() != &N)
9321             continue;
9322           NewLocOps[i] = SDDbgOperand::fromNode(N0.getNode(), N0.getResNo());
9323           SmallVector<uint64_t, 3> ExprOps;
9324           DIExpression::appendOffset(ExprOps, Offset);
9325           DIExpr = DIExpression::appendOpsToArg(DIExpr, ExprOps, i, true);
9326           Changed = true;
9327         }
9328         (void)Changed;
9329         assert(Changed && "Salvage target doesn't use N");
9330 
9331         auto AdditionalDependencies = DV->getAdditionalDependencies();
9332         SDDbgValue *Clone = getDbgValueList(DV->getVariable(), DIExpr,
9333                                             NewLocOps, AdditionalDependencies,
9334                                             DV->isIndirect(), DV->getDebugLoc(),
9335                                             DV->getOrder(), DV->isVariadic());
9336         ClonedDVs.push_back(Clone);
9337         DV->setIsInvalidated();
9338         DV->setIsEmitted();
9339         LLVM_DEBUG(dbgs() << "SALVAGE: Rewriting";
9340                    N0.getNode()->dumprFull(this);
9341                    dbgs() << " into " << *DIExpr << '\n');
9342       }
9343     }
9344   }
9345 
9346   for (SDDbgValue *Dbg : ClonedDVs) {
9347     assert(!Dbg->getSDNodes().empty() &&
9348            "Salvaged DbgValue should depend on a new SDNode");
9349     AddDbgValue(Dbg, false);
9350   }
9351 }
9352 
9353 /// Creates a SDDbgLabel node.
9354 SDDbgLabel *SelectionDAG::getDbgLabel(DILabel *Label,
9355                                       const DebugLoc &DL, unsigned O) {
9356   assert(cast<DILabel>(Label)->isValidLocationForIntrinsic(DL) &&
9357          "Expected inlined-at fields to agree");
9358   return new (DbgInfo->getAlloc()) SDDbgLabel(Label, DL, O);
9359 }
9360 
9361 namespace {
9362 
9363 /// RAUWUpdateListener - Helper for ReplaceAllUsesWith - When the node
9364 /// pointed to by a use iterator is deleted, increment the use iterator
9365 /// so that it doesn't dangle.
9366 ///
9367 class RAUWUpdateListener : public SelectionDAG::DAGUpdateListener {
9368   SDNode::use_iterator &UI;
9369   SDNode::use_iterator &UE;
9370 
9371   void NodeDeleted(SDNode *N, SDNode *E) override {
9372     // Increment the iterator as needed.
9373     while (UI != UE && N == *UI)
9374       ++UI;
9375   }
9376 
9377 public:
9378   RAUWUpdateListener(SelectionDAG &d,
9379                      SDNode::use_iterator &ui,
9380                      SDNode::use_iterator &ue)
9381     : SelectionDAG::DAGUpdateListener(d), UI(ui), UE(ue) {}
9382 };
9383 
9384 } // end anonymous namespace
9385 
9386 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
9387 /// This can cause recursive merging of nodes in the DAG.
9388 ///
9389 /// This version assumes From has a single result value.
9390 ///
9391 void SelectionDAG::ReplaceAllUsesWith(SDValue FromN, SDValue To) {
9392   SDNode *From = FromN.getNode();
9393   assert(From->getNumValues() == 1 && FromN.getResNo() == 0 &&
9394          "Cannot replace with this method!");
9395   assert(From != To.getNode() && "Cannot replace uses of with self");
9396 
9397   // Preserve Debug Values
9398   transferDbgValues(FromN, To);
9399 
9400   // Iterate over all the existing uses of From. New uses will be added
9401   // to the beginning of the use list, which we avoid visiting.
9402   // This specifically avoids visiting uses of From that arise while the
9403   // replacement is happening, because any such uses would be the result
9404   // of CSE: If an existing node looks like From after one of its operands
9405   // is replaced by To, we don't want to replace of all its users with To
9406   // too. See PR3018 for more info.
9407   SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
9408   RAUWUpdateListener Listener(*this, UI, UE);
9409   while (UI != UE) {
9410     SDNode *User = *UI;
9411 
9412     // This node is about to morph, remove its old self from the CSE maps.
9413     RemoveNodeFromCSEMaps(User);
9414 
9415     // A user can appear in a use list multiple times, and when this
9416     // happens the uses are usually next to each other in the list.
9417     // To help reduce the number of CSE recomputations, process all
9418     // the uses of this user that we can find this way.
9419     do {
9420       SDUse &Use = UI.getUse();
9421       ++UI;
9422       Use.set(To);
9423       if (To->isDivergent() != From->isDivergent())
9424         updateDivergence(User);
9425     } while (UI != UE && *UI == User);
9426     // Now that we have modified User, add it back to the CSE maps.  If it
9427     // already exists there, recursively merge the results together.
9428     AddModifiedNodeToCSEMaps(User);
9429   }
9430 
9431   // If we just RAUW'd the root, take note.
9432   if (FromN == getRoot())
9433     setRoot(To);
9434 }
9435 
9436 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
9437 /// This can cause recursive merging of nodes in the DAG.
9438 ///
9439 /// This version assumes that for each value of From, there is a
9440 /// corresponding value in To in the same position with the same type.
9441 ///
9442 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, SDNode *To) {
9443 #ifndef NDEBUG
9444   for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
9445     assert((!From->hasAnyUseOfValue(i) ||
9446             From->getValueType(i) == To->getValueType(i)) &&
9447            "Cannot use this version of ReplaceAllUsesWith!");
9448 #endif
9449 
9450   // Handle the trivial case.
9451   if (From == To)
9452     return;
9453 
9454   // Preserve Debug Info. Only do this if there's a use.
9455   for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
9456     if (From->hasAnyUseOfValue(i)) {
9457       assert((i < To->getNumValues()) && "Invalid To location");
9458       transferDbgValues(SDValue(From, i), SDValue(To, i));
9459     }
9460 
9461   // Iterate over just the existing users of From. See the comments in
9462   // the ReplaceAllUsesWith above.
9463   SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
9464   RAUWUpdateListener Listener(*this, UI, UE);
9465   while (UI != UE) {
9466     SDNode *User = *UI;
9467 
9468     // This node is about to morph, remove its old self from the CSE maps.
9469     RemoveNodeFromCSEMaps(User);
9470 
9471     // A user can appear in a use list multiple times, and when this
9472     // happens the uses are usually next to each other in the list.
9473     // To help reduce the number of CSE recomputations, process all
9474     // the uses of this user that we can find this way.
9475     do {
9476       SDUse &Use = UI.getUse();
9477       ++UI;
9478       Use.setNode(To);
9479       if (To->isDivergent() != From->isDivergent())
9480         updateDivergence(User);
9481     } while (UI != UE && *UI == User);
9482 
9483     // Now that we have modified User, add it back to the CSE maps.  If it
9484     // already exists there, recursively merge the results together.
9485     AddModifiedNodeToCSEMaps(User);
9486   }
9487 
9488   // If we just RAUW'd the root, take note.
9489   if (From == getRoot().getNode())
9490     setRoot(SDValue(To, getRoot().getResNo()));
9491 }
9492 
9493 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
9494 /// This can cause recursive merging of nodes in the DAG.
9495 ///
9496 /// This version can replace From with any result values.  To must match the
9497 /// number and types of values returned by From.
9498 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, const SDValue *To) {
9499   if (From->getNumValues() == 1)  // Handle the simple case efficiently.
9500     return ReplaceAllUsesWith(SDValue(From, 0), To[0]);
9501 
9502   // Preserve Debug Info.
9503   for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
9504     transferDbgValues(SDValue(From, i), To[i]);
9505 
9506   // Iterate over just the existing users of From. See the comments in
9507   // the ReplaceAllUsesWith above.
9508   SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
9509   RAUWUpdateListener Listener(*this, UI, UE);
9510   while (UI != UE) {
9511     SDNode *User = *UI;
9512 
9513     // This node is about to morph, remove its old self from the CSE maps.
9514     RemoveNodeFromCSEMaps(User);
9515 
9516     // A user can appear in a use list multiple times, and when this happens the
9517     // uses are usually next to each other in the list.  To help reduce the
9518     // number of CSE and divergence recomputations, process all the uses of this
9519     // user that we can find this way.
9520     bool To_IsDivergent = false;
9521     do {
9522       SDUse &Use = UI.getUse();
9523       const SDValue &ToOp = To[Use.getResNo()];
9524       ++UI;
9525       Use.set(ToOp);
9526       To_IsDivergent |= ToOp->isDivergent();
9527     } while (UI != UE && *UI == User);
9528 
9529     if (To_IsDivergent != From->isDivergent())
9530       updateDivergence(User);
9531 
9532     // Now that we have modified User, add it back to the CSE maps.  If it
9533     // already exists there, recursively merge the results together.
9534     AddModifiedNodeToCSEMaps(User);
9535   }
9536 
9537   // If we just RAUW'd the root, take note.
9538   if (From == getRoot().getNode())
9539     setRoot(SDValue(To[getRoot().getResNo()]));
9540 }
9541 
9542 /// ReplaceAllUsesOfValueWith - Replace any uses of From with To, leaving
9543 /// uses of other values produced by From.getNode() alone.  The Deleted
9544 /// vector is handled the same way as for ReplaceAllUsesWith.
9545 void SelectionDAG::ReplaceAllUsesOfValueWith(SDValue From, SDValue To){
9546   // Handle the really simple, really trivial case efficiently.
9547   if (From == To) return;
9548 
9549   // Handle the simple, trivial, case efficiently.
9550   if (From.getNode()->getNumValues() == 1) {
9551     ReplaceAllUsesWith(From, To);
9552     return;
9553   }
9554 
9555   // Preserve Debug Info.
9556   transferDbgValues(From, To);
9557 
9558   // Iterate over just the existing users of From. See the comments in
9559   // the ReplaceAllUsesWith above.
9560   SDNode::use_iterator UI = From.getNode()->use_begin(),
9561                        UE = From.getNode()->use_end();
9562   RAUWUpdateListener Listener(*this, UI, UE);
9563   while (UI != UE) {
9564     SDNode *User = *UI;
9565     bool UserRemovedFromCSEMaps = false;
9566 
9567     // A user can appear in a use list multiple times, and when this
9568     // happens the uses are usually next to each other in the list.
9569     // To help reduce the number of CSE recomputations, process all
9570     // the uses of this user that we can find this way.
9571     do {
9572       SDUse &Use = UI.getUse();
9573 
9574       // Skip uses of different values from the same node.
9575       if (Use.getResNo() != From.getResNo()) {
9576         ++UI;
9577         continue;
9578       }
9579 
9580       // If this node hasn't been modified yet, it's still in the CSE maps,
9581       // so remove its old self from the CSE maps.
9582       if (!UserRemovedFromCSEMaps) {
9583         RemoveNodeFromCSEMaps(User);
9584         UserRemovedFromCSEMaps = true;
9585       }
9586 
9587       ++UI;
9588       Use.set(To);
9589       if (To->isDivergent() != From->isDivergent())
9590         updateDivergence(User);
9591     } while (UI != UE && *UI == User);
9592     // We are iterating over all uses of the From node, so if a use
9593     // doesn't use the specific value, no changes are made.
9594     if (!UserRemovedFromCSEMaps)
9595       continue;
9596 
9597     // Now that we have modified User, add it back to the CSE maps.  If it
9598     // already exists there, recursively merge the results together.
9599     AddModifiedNodeToCSEMaps(User);
9600   }
9601 
9602   // If we just RAUW'd the root, take note.
9603   if (From == getRoot())
9604     setRoot(To);
9605 }
9606 
9607 namespace {
9608 
9609   /// UseMemo - This class is used by SelectionDAG::ReplaceAllUsesOfValuesWith
9610   /// to record information about a use.
9611   struct UseMemo {
9612     SDNode *User;
9613     unsigned Index;
9614     SDUse *Use;
9615   };
9616 
9617   /// operator< - Sort Memos by User.
9618   bool operator<(const UseMemo &L, const UseMemo &R) {
9619     return (intptr_t)L.User < (intptr_t)R.User;
9620   }
9621 
9622 } // end anonymous namespace
9623 
9624 bool SelectionDAG::calculateDivergence(SDNode *N) {
9625   if (TLI->isSDNodeAlwaysUniform(N)) {
9626     assert(!TLI->isSDNodeSourceOfDivergence(N, FLI, DA) &&
9627            "Conflicting divergence information!");
9628     return false;
9629   }
9630   if (TLI->isSDNodeSourceOfDivergence(N, FLI, DA))
9631     return true;
9632   for (auto &Op : N->ops()) {
9633     if (Op.Val.getValueType() != MVT::Other && Op.getNode()->isDivergent())
9634       return true;
9635   }
9636   return false;
9637 }
9638 
9639 void SelectionDAG::updateDivergence(SDNode *N) {
9640   SmallVector<SDNode *, 16> Worklist(1, N);
9641   do {
9642     N = Worklist.pop_back_val();
9643     bool IsDivergent = calculateDivergence(N);
9644     if (N->SDNodeBits.IsDivergent != IsDivergent) {
9645       N->SDNodeBits.IsDivergent = IsDivergent;
9646       llvm::append_range(Worklist, N->uses());
9647     }
9648   } while (!Worklist.empty());
9649 }
9650 
9651 void SelectionDAG::CreateTopologicalOrder(std::vector<SDNode *> &Order) {
9652   DenseMap<SDNode *, unsigned> Degree;
9653   Order.reserve(AllNodes.size());
9654   for (auto &N : allnodes()) {
9655     unsigned NOps = N.getNumOperands();
9656     Degree[&N] = NOps;
9657     if (0 == NOps)
9658       Order.push_back(&N);
9659   }
9660   for (size_t I = 0; I != Order.size(); ++I) {
9661     SDNode *N = Order[I];
9662     for (auto U : N->uses()) {
9663       unsigned &UnsortedOps = Degree[U];
9664       if (0 == --UnsortedOps)
9665         Order.push_back(U);
9666     }
9667   }
9668 }
9669 
9670 #ifndef NDEBUG
9671 void SelectionDAG::VerifyDAGDivergence() {
9672   std::vector<SDNode *> TopoOrder;
9673   CreateTopologicalOrder(TopoOrder);
9674   for (auto *N : TopoOrder) {
9675     assert(calculateDivergence(N) == N->isDivergent() &&
9676            "Divergence bit inconsistency detected");
9677   }
9678 }
9679 #endif
9680 
9681 /// ReplaceAllUsesOfValuesWith - Replace any uses of From with To, leaving
9682 /// uses of other values produced by From.getNode() alone.  The same value
9683 /// may appear in both the From and To list.  The Deleted vector is
9684 /// handled the same way as for ReplaceAllUsesWith.
9685 void SelectionDAG::ReplaceAllUsesOfValuesWith(const SDValue *From,
9686                                               const SDValue *To,
9687                                               unsigned Num){
9688   // Handle the simple, trivial case efficiently.
9689   if (Num == 1)
9690     return ReplaceAllUsesOfValueWith(*From, *To);
9691 
9692   transferDbgValues(*From, *To);
9693 
9694   // Read up all the uses and make records of them. This helps
9695   // processing new uses that are introduced during the
9696   // replacement process.
9697   SmallVector<UseMemo, 4> Uses;
9698   for (unsigned i = 0; i != Num; ++i) {
9699     unsigned FromResNo = From[i].getResNo();
9700     SDNode *FromNode = From[i].getNode();
9701     for (SDNode::use_iterator UI = FromNode->use_begin(),
9702          E = FromNode->use_end(); UI != E; ++UI) {
9703       SDUse &Use = UI.getUse();
9704       if (Use.getResNo() == FromResNo) {
9705         UseMemo Memo = { *UI, i, &Use };
9706         Uses.push_back(Memo);
9707       }
9708     }
9709   }
9710 
9711   // Sort the uses, so that all the uses from a given User are together.
9712   llvm::sort(Uses);
9713 
9714   for (unsigned UseIndex = 0, UseIndexEnd = Uses.size();
9715        UseIndex != UseIndexEnd; ) {
9716     // We know that this user uses some value of From.  If it is the right
9717     // value, update it.
9718     SDNode *User = Uses[UseIndex].User;
9719 
9720     // This node is about to morph, remove its old self from the CSE maps.
9721     RemoveNodeFromCSEMaps(User);
9722 
9723     // The Uses array is sorted, so all the uses for a given User
9724     // are next to each other in the list.
9725     // To help reduce the number of CSE recomputations, process all
9726     // the uses of this user that we can find this way.
9727     do {
9728       unsigned i = Uses[UseIndex].Index;
9729       SDUse &Use = *Uses[UseIndex].Use;
9730       ++UseIndex;
9731 
9732       Use.set(To[i]);
9733     } while (UseIndex != UseIndexEnd && Uses[UseIndex].User == User);
9734 
9735     // Now that we have modified User, add it back to the CSE maps.  If it
9736     // already exists there, recursively merge the results together.
9737     AddModifiedNodeToCSEMaps(User);
9738   }
9739 }
9740 
9741 /// AssignTopologicalOrder - Assign a unique node id for each node in the DAG
9742 /// based on their topological order. It returns the maximum id and a vector
9743 /// of the SDNodes* in assigned order by reference.
9744 unsigned SelectionDAG::AssignTopologicalOrder() {
9745   unsigned DAGSize = 0;
9746 
9747   // SortedPos tracks the progress of the algorithm. Nodes before it are
9748   // sorted, nodes after it are unsorted. When the algorithm completes
9749   // it is at the end of the list.
9750   allnodes_iterator SortedPos = allnodes_begin();
9751 
9752   // Visit all the nodes. Move nodes with no operands to the front of
9753   // the list immediately. Annotate nodes that do have operands with their
9754   // operand count. Before we do this, the Node Id fields of the nodes
9755   // may contain arbitrary values. After, the Node Id fields for nodes
9756   // before SortedPos will contain the topological sort index, and the
9757   // Node Id fields for nodes At SortedPos and after will contain the
9758   // count of outstanding operands.
9759   for (SDNode &N : llvm::make_early_inc_range(allnodes())) {
9760     checkForCycles(&N, this);
9761     unsigned Degree = N.getNumOperands();
9762     if (Degree == 0) {
9763       // A node with no uses, add it to the result array immediately.
9764       N.setNodeId(DAGSize++);
9765       allnodes_iterator Q(&N);
9766       if (Q != SortedPos)
9767         SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(Q));
9768       assert(SortedPos != AllNodes.end() && "Overran node list");
9769       ++SortedPos;
9770     } else {
9771       // Temporarily use the Node Id as scratch space for the degree count.
9772       N.setNodeId(Degree);
9773     }
9774   }
9775 
9776   // Visit all the nodes. As we iterate, move nodes into sorted order,
9777   // such that by the time the end is reached all nodes will be sorted.
9778   for (SDNode &Node : allnodes()) {
9779     SDNode *N = &Node;
9780     checkForCycles(N, this);
9781     // N is in sorted position, so all its uses have one less operand
9782     // that needs to be sorted.
9783     for (SDNode *P : N->uses()) {
9784       unsigned Degree = P->getNodeId();
9785       assert(Degree != 0 && "Invalid node degree");
9786       --Degree;
9787       if (Degree == 0) {
9788         // All of P's operands are sorted, so P may sorted now.
9789         P->setNodeId(DAGSize++);
9790         if (P->getIterator() != SortedPos)
9791           SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(P));
9792         assert(SortedPos != AllNodes.end() && "Overran node list");
9793         ++SortedPos;
9794       } else {
9795         // Update P's outstanding operand count.
9796         P->setNodeId(Degree);
9797       }
9798     }
9799     if (Node.getIterator() == SortedPos) {
9800 #ifndef NDEBUG
9801       allnodes_iterator I(N);
9802       SDNode *S = &*++I;
9803       dbgs() << "Overran sorted position:\n";
9804       S->dumprFull(this); dbgs() << "\n";
9805       dbgs() << "Checking if this is due to cycles\n";
9806       checkForCycles(this, true);
9807 #endif
9808       llvm_unreachable(nullptr);
9809     }
9810   }
9811 
9812   assert(SortedPos == AllNodes.end() &&
9813          "Topological sort incomplete!");
9814   assert(AllNodes.front().getOpcode() == ISD::EntryToken &&
9815          "First node in topological sort is not the entry token!");
9816   assert(AllNodes.front().getNodeId() == 0 &&
9817          "First node in topological sort has non-zero id!");
9818   assert(AllNodes.front().getNumOperands() == 0 &&
9819          "First node in topological sort has operands!");
9820   assert(AllNodes.back().getNodeId() == (int)DAGSize-1 &&
9821          "Last node in topologic sort has unexpected id!");
9822   assert(AllNodes.back().use_empty() &&
9823          "Last node in topologic sort has users!");
9824   assert(DAGSize == allnodes_size() && "Node count mismatch!");
9825   return DAGSize;
9826 }
9827 
9828 /// AddDbgValue - Add a dbg_value SDNode. If SD is non-null that means the
9829 /// value is produced by SD.
9830 void SelectionDAG::AddDbgValue(SDDbgValue *DB, bool isParameter) {
9831   for (SDNode *SD : DB->getSDNodes()) {
9832     if (!SD)
9833       continue;
9834     assert(DbgInfo->getSDDbgValues(SD).empty() || SD->getHasDebugValue());
9835     SD->setHasDebugValue(true);
9836   }
9837   DbgInfo->add(DB, isParameter);
9838 }
9839 
9840 void SelectionDAG::AddDbgLabel(SDDbgLabel *DB) { DbgInfo->add(DB); }
9841 
9842 SDValue SelectionDAG::makeEquivalentMemoryOrdering(SDValue OldChain,
9843                                                    SDValue NewMemOpChain) {
9844   assert(isa<MemSDNode>(NewMemOpChain) && "Expected a memop node");
9845   assert(NewMemOpChain.getValueType() == MVT::Other && "Expected a token VT");
9846   // The new memory operation must have the same position as the old load in
9847   // terms of memory dependency. Create a TokenFactor for the old load and new
9848   // memory operation and update uses of the old load's output chain to use that
9849   // TokenFactor.
9850   if (OldChain == NewMemOpChain || OldChain.use_empty())
9851     return NewMemOpChain;
9852 
9853   SDValue TokenFactor = getNode(ISD::TokenFactor, SDLoc(OldChain), MVT::Other,
9854                                 OldChain, NewMemOpChain);
9855   ReplaceAllUsesOfValueWith(OldChain, TokenFactor);
9856   UpdateNodeOperands(TokenFactor.getNode(), OldChain, NewMemOpChain);
9857   return TokenFactor;
9858 }
9859 
9860 SDValue SelectionDAG::makeEquivalentMemoryOrdering(LoadSDNode *OldLoad,
9861                                                    SDValue NewMemOp) {
9862   assert(isa<MemSDNode>(NewMemOp.getNode()) && "Expected a memop node");
9863   SDValue OldChain = SDValue(OldLoad, 1);
9864   SDValue NewMemOpChain = NewMemOp.getValue(1);
9865   return makeEquivalentMemoryOrdering(OldChain, NewMemOpChain);
9866 }
9867 
9868 SDValue SelectionDAG::getSymbolFunctionGlobalAddress(SDValue Op,
9869                                                      Function **OutFunction) {
9870   assert(isa<ExternalSymbolSDNode>(Op) && "Node should be an ExternalSymbol");
9871 
9872   auto *Symbol = cast<ExternalSymbolSDNode>(Op)->getSymbol();
9873   auto *Module = MF->getFunction().getParent();
9874   auto *Function = Module->getFunction(Symbol);
9875 
9876   if (OutFunction != nullptr)
9877       *OutFunction = Function;
9878 
9879   if (Function != nullptr) {
9880     auto PtrTy = TLI->getPointerTy(getDataLayout(), Function->getAddressSpace());
9881     return getGlobalAddress(Function, SDLoc(Op), PtrTy);
9882   }
9883 
9884   std::string ErrorStr;
9885   raw_string_ostream ErrorFormatter(ErrorStr);
9886   ErrorFormatter << "Undefined external symbol ";
9887   ErrorFormatter << '"' << Symbol << '"';
9888   report_fatal_error(Twine(ErrorFormatter.str()));
9889 }
9890 
9891 //===----------------------------------------------------------------------===//
9892 //                              SDNode Class
9893 //===----------------------------------------------------------------------===//
9894 
9895 bool llvm::isNullConstant(SDValue V) {
9896   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
9897   return Const != nullptr && Const->isZero();
9898 }
9899 
9900 bool llvm::isNullFPConstant(SDValue V) {
9901   ConstantFPSDNode *Const = dyn_cast<ConstantFPSDNode>(V);
9902   return Const != nullptr && Const->isZero() && !Const->isNegative();
9903 }
9904 
9905 bool llvm::isAllOnesConstant(SDValue V) {
9906   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
9907   return Const != nullptr && Const->isAllOnes();
9908 }
9909 
9910 bool llvm::isOneConstant(SDValue V) {
9911   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
9912   return Const != nullptr && Const->isOne();
9913 }
9914 
9915 SDValue llvm::peekThroughBitcasts(SDValue V) {
9916   while (V.getOpcode() == ISD::BITCAST)
9917     V = V.getOperand(0);
9918   return V;
9919 }
9920 
9921 SDValue llvm::peekThroughOneUseBitcasts(SDValue V) {
9922   while (V.getOpcode() == ISD::BITCAST && V.getOperand(0).hasOneUse())
9923     V = V.getOperand(0);
9924   return V;
9925 }
9926 
9927 SDValue llvm::peekThroughExtractSubvectors(SDValue V) {
9928   while (V.getOpcode() == ISD::EXTRACT_SUBVECTOR)
9929     V = V.getOperand(0);
9930   return V;
9931 }
9932 
9933 bool llvm::isBitwiseNot(SDValue V, bool AllowUndefs) {
9934   if (V.getOpcode() != ISD::XOR)
9935     return false;
9936   V = peekThroughBitcasts(V.getOperand(1));
9937   unsigned NumBits = V.getScalarValueSizeInBits();
9938   ConstantSDNode *C =
9939       isConstOrConstSplat(V, AllowUndefs, /*AllowTruncation*/ true);
9940   return C && (C->getAPIntValue().countTrailingOnes() >= NumBits);
9941 }
9942 
9943 ConstantSDNode *llvm::isConstOrConstSplat(SDValue N, bool AllowUndefs,
9944                                           bool AllowTruncation) {
9945   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
9946     return CN;
9947 
9948   // SplatVectors can truncate their operands. Ignore that case here unless
9949   // AllowTruncation is set.
9950   if (N->getOpcode() == ISD::SPLAT_VECTOR) {
9951     EVT VecEltVT = N->getValueType(0).getVectorElementType();
9952     if (auto *CN = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
9953       EVT CVT = CN->getValueType(0);
9954       assert(CVT.bitsGE(VecEltVT) && "Illegal splat_vector element extension");
9955       if (AllowTruncation || CVT == VecEltVT)
9956         return CN;
9957     }
9958   }
9959 
9960   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
9961     BitVector UndefElements;
9962     ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
9963 
9964     // BuildVectors can truncate their operands. Ignore that case here unless
9965     // AllowTruncation is set.
9966     if (CN && (UndefElements.none() || AllowUndefs)) {
9967       EVT CVT = CN->getValueType(0);
9968       EVT NSVT = N.getValueType().getScalarType();
9969       assert(CVT.bitsGE(NSVT) && "Illegal build vector element extension");
9970       if (AllowTruncation || (CVT == NSVT))
9971         return CN;
9972     }
9973   }
9974 
9975   return nullptr;
9976 }
9977 
9978 ConstantSDNode *llvm::isConstOrConstSplat(SDValue N, const APInt &DemandedElts,
9979                                           bool AllowUndefs,
9980                                           bool AllowTruncation) {
9981   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
9982     return CN;
9983 
9984   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
9985     BitVector UndefElements;
9986     ConstantSDNode *CN = BV->getConstantSplatNode(DemandedElts, &UndefElements);
9987 
9988     // BuildVectors can truncate their operands. Ignore that case here unless
9989     // AllowTruncation is set.
9990     if (CN && (UndefElements.none() || AllowUndefs)) {
9991       EVT CVT = CN->getValueType(0);
9992       EVT NSVT = N.getValueType().getScalarType();
9993       assert(CVT.bitsGE(NSVT) && "Illegal build vector element extension");
9994       if (AllowTruncation || (CVT == NSVT))
9995         return CN;
9996     }
9997   }
9998 
9999   return nullptr;
10000 }
10001 
10002 ConstantFPSDNode *llvm::isConstOrConstSplatFP(SDValue N, bool AllowUndefs) {
10003   if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
10004     return CN;
10005 
10006   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
10007     BitVector UndefElements;
10008     ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements);
10009     if (CN && (UndefElements.none() || AllowUndefs))
10010       return CN;
10011   }
10012 
10013   if (N.getOpcode() == ISD::SPLAT_VECTOR)
10014     if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N.getOperand(0)))
10015       return CN;
10016 
10017   return nullptr;
10018 }
10019 
10020 ConstantFPSDNode *llvm::isConstOrConstSplatFP(SDValue N,
10021                                               const APInt &DemandedElts,
10022                                               bool AllowUndefs) {
10023   if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
10024     return CN;
10025 
10026   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
10027     BitVector UndefElements;
10028     ConstantFPSDNode *CN =
10029         BV->getConstantFPSplatNode(DemandedElts, &UndefElements);
10030     if (CN && (UndefElements.none() || AllowUndefs))
10031       return CN;
10032   }
10033 
10034   return nullptr;
10035 }
10036 
10037 bool llvm::isNullOrNullSplat(SDValue N, bool AllowUndefs) {
10038   // TODO: may want to use peekThroughBitcast() here.
10039   ConstantSDNode *C =
10040       isConstOrConstSplat(N, AllowUndefs, /*AllowTruncation=*/true);
10041   return C && C->isZero();
10042 }
10043 
10044 bool llvm::isOneOrOneSplat(SDValue N, bool AllowUndefs) {
10045   // TODO: may want to use peekThroughBitcast() here.
10046   unsigned BitWidth = N.getScalarValueSizeInBits();
10047   ConstantSDNode *C = isConstOrConstSplat(N, AllowUndefs);
10048   return C && C->isOne() && C->getValueSizeInBits(0) == BitWidth;
10049 }
10050 
10051 bool llvm::isAllOnesOrAllOnesSplat(SDValue N, bool AllowUndefs) {
10052   N = peekThroughBitcasts(N);
10053   unsigned BitWidth = N.getScalarValueSizeInBits();
10054   ConstantSDNode *C = isConstOrConstSplat(N, AllowUndefs);
10055   return C && C->isAllOnes() && C->getValueSizeInBits(0) == BitWidth;
10056 }
10057 
10058 HandleSDNode::~HandleSDNode() {
10059   DropOperands();
10060 }
10061 
10062 GlobalAddressSDNode::GlobalAddressSDNode(unsigned Opc, unsigned Order,
10063                                          const DebugLoc &DL,
10064                                          const GlobalValue *GA, EVT VT,
10065                                          int64_t o, unsigned TF)
10066     : SDNode(Opc, Order, DL, getSDVTList(VT)), Offset(o), TargetFlags(TF) {
10067   TheGlobal = GA;
10068 }
10069 
10070 AddrSpaceCastSDNode::AddrSpaceCastSDNode(unsigned Order, const DebugLoc &dl,
10071                                          EVT VT, unsigned SrcAS,
10072                                          unsigned DestAS)
10073     : SDNode(ISD::ADDRSPACECAST, Order, dl, getSDVTList(VT)),
10074       SrcAddrSpace(SrcAS), DestAddrSpace(DestAS) {}
10075 
10076 MemSDNode::MemSDNode(unsigned Opc, unsigned Order, const DebugLoc &dl,
10077                      SDVTList VTs, EVT memvt, MachineMemOperand *mmo)
10078     : SDNode(Opc, Order, dl, VTs), MemoryVT(memvt), MMO(mmo) {
10079   MemSDNodeBits.IsVolatile = MMO->isVolatile();
10080   MemSDNodeBits.IsNonTemporal = MMO->isNonTemporal();
10081   MemSDNodeBits.IsDereferenceable = MMO->isDereferenceable();
10082   MemSDNodeBits.IsInvariant = MMO->isInvariant();
10083 
10084   // We check here that the size of the memory operand fits within the size of
10085   // the MMO. This is because the MMO might indicate only a possible address
10086   // range instead of specifying the affected memory addresses precisely.
10087   // TODO: Make MachineMemOperands aware of scalable vectors.
10088   assert(memvt.getStoreSize().getKnownMinSize() <= MMO->getSize() &&
10089          "Size mismatch!");
10090 }
10091 
10092 /// Profile - Gather unique data for the node.
10093 ///
10094 void SDNode::Profile(FoldingSetNodeID &ID) const {
10095   AddNodeIDNode(ID, this);
10096 }
10097 
10098 namespace {
10099 
10100   struct EVTArray {
10101     std::vector<EVT> VTs;
10102 
10103     EVTArray() {
10104       VTs.reserve(MVT::VALUETYPE_SIZE);
10105       for (unsigned i = 0; i < MVT::VALUETYPE_SIZE; ++i)
10106         VTs.push_back(MVT((MVT::SimpleValueType)i));
10107     }
10108   };
10109 
10110 } // end anonymous namespace
10111 
10112 static ManagedStatic<std::set<EVT, EVT::compareRawBits>> EVTs;
10113 static ManagedStatic<EVTArray> SimpleVTArray;
10114 static ManagedStatic<sys::SmartMutex<true>> VTMutex;
10115 
10116 /// getValueTypeList - Return a pointer to the specified value type.
10117 ///
10118 const EVT *SDNode::getValueTypeList(EVT VT) {
10119   if (VT.isExtended()) {
10120     sys::SmartScopedLock<true> Lock(*VTMutex);
10121     return &(*EVTs->insert(VT).first);
10122   }
10123   assert(VT.getSimpleVT() < MVT::VALUETYPE_SIZE && "Value type out of range!");
10124   return &SimpleVTArray->VTs[VT.getSimpleVT().SimpleTy];
10125 }
10126 
10127 /// hasNUsesOfValue - Return true if there are exactly NUSES uses of the
10128 /// indicated value.  This method ignores uses of other values defined by this
10129 /// operation.
10130 bool SDNode::hasNUsesOfValue(unsigned NUses, unsigned Value) const {
10131   assert(Value < getNumValues() && "Bad value!");
10132 
10133   // TODO: Only iterate over uses of a given value of the node
10134   for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) {
10135     if (UI.getUse().getResNo() == Value) {
10136       if (NUses == 0)
10137         return false;
10138       --NUses;
10139     }
10140   }
10141 
10142   // Found exactly the right number of uses?
10143   return NUses == 0;
10144 }
10145 
10146 /// hasAnyUseOfValue - Return true if there are any use of the indicated
10147 /// value. This method ignores uses of other values defined by this operation.
10148 bool SDNode::hasAnyUseOfValue(unsigned Value) const {
10149   assert(Value < getNumValues() && "Bad value!");
10150 
10151   for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI)
10152     if (UI.getUse().getResNo() == Value)
10153       return true;
10154 
10155   return false;
10156 }
10157 
10158 /// isOnlyUserOf - Return true if this node is the only use of N.
10159 bool SDNode::isOnlyUserOf(const SDNode *N) const {
10160   bool Seen = false;
10161   for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) {
10162     SDNode *User = *I;
10163     if (User == this)
10164       Seen = true;
10165     else
10166       return false;
10167   }
10168 
10169   return Seen;
10170 }
10171 
10172 /// Return true if the only users of N are contained in Nodes.
10173 bool SDNode::areOnlyUsersOf(ArrayRef<const SDNode *> Nodes, const SDNode *N) {
10174   bool Seen = false;
10175   for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) {
10176     SDNode *User = *I;
10177     if (llvm::is_contained(Nodes, User))
10178       Seen = true;
10179     else
10180       return false;
10181   }
10182 
10183   return Seen;
10184 }
10185 
10186 /// isOperand - Return true if this node is an operand of N.
10187 bool SDValue::isOperandOf(const SDNode *N) const {
10188   return is_contained(N->op_values(), *this);
10189 }
10190 
10191 bool SDNode::isOperandOf(const SDNode *N) const {
10192   return any_of(N->op_values(),
10193                 [this](SDValue Op) { return this == Op.getNode(); });
10194 }
10195 
10196 /// reachesChainWithoutSideEffects - Return true if this operand (which must
10197 /// be a chain) reaches the specified operand without crossing any
10198 /// side-effecting instructions on any chain path.  In practice, this looks
10199 /// through token factors and non-volatile loads.  In order to remain efficient,
10200 /// this only looks a couple of nodes in, it does not do an exhaustive search.
10201 ///
10202 /// Note that we only need to examine chains when we're searching for
10203 /// side-effects; SelectionDAG requires that all side-effects are represented
10204 /// by chains, even if another operand would force a specific ordering. This
10205 /// constraint is necessary to allow transformations like splitting loads.
10206 bool SDValue::reachesChainWithoutSideEffects(SDValue Dest,
10207                                              unsigned Depth) const {
10208   if (*this == Dest) return true;
10209 
10210   // Don't search too deeply, we just want to be able to see through
10211   // TokenFactor's etc.
10212   if (Depth == 0) return false;
10213 
10214   // If this is a token factor, all inputs to the TF happen in parallel.
10215   if (getOpcode() == ISD::TokenFactor) {
10216     // First, try a shallow search.
10217     if (is_contained((*this)->ops(), Dest)) {
10218       // We found the chain we want as an operand of this TokenFactor.
10219       // Essentially, we reach the chain without side-effects if we could
10220       // serialize the TokenFactor into a simple chain of operations with
10221       // Dest as the last operation. This is automatically true if the
10222       // chain has one use: there are no other ordering constraints.
10223       // If the chain has more than one use, we give up: some other
10224       // use of Dest might force a side-effect between Dest and the current
10225       // node.
10226       if (Dest.hasOneUse())
10227         return true;
10228     }
10229     // Next, try a deep search: check whether every operand of the TokenFactor
10230     // reaches Dest.
10231     return llvm::all_of((*this)->ops(), [=](SDValue Op) {
10232       return Op.reachesChainWithoutSideEffects(Dest, Depth - 1);
10233     });
10234   }
10235 
10236   // Loads don't have side effects, look through them.
10237   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(*this)) {
10238     if (Ld->isUnordered())
10239       return Ld->getChain().reachesChainWithoutSideEffects(Dest, Depth-1);
10240   }
10241   return false;
10242 }
10243 
10244 bool SDNode::hasPredecessor(const SDNode *N) const {
10245   SmallPtrSet<const SDNode *, 32> Visited;
10246   SmallVector<const SDNode *, 16> Worklist;
10247   Worklist.push_back(this);
10248   return hasPredecessorHelper(N, Visited, Worklist);
10249 }
10250 
10251 void SDNode::intersectFlagsWith(const SDNodeFlags Flags) {
10252   this->Flags.intersectWith(Flags);
10253 }
10254 
10255 SDValue
10256 SelectionDAG::matchBinOpReduction(SDNode *Extract, ISD::NodeType &BinOp,
10257                                   ArrayRef<ISD::NodeType> CandidateBinOps,
10258                                   bool AllowPartials) {
10259   // The pattern must end in an extract from index 0.
10260   if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10261       !isNullConstant(Extract->getOperand(1)))
10262     return SDValue();
10263 
10264   // Match against one of the candidate binary ops.
10265   SDValue Op = Extract->getOperand(0);
10266   if (llvm::none_of(CandidateBinOps, [Op](ISD::NodeType BinOp) {
10267         return Op.getOpcode() == unsigned(BinOp);
10268       }))
10269     return SDValue();
10270 
10271   // Floating-point reductions may require relaxed constraints on the final step
10272   // of the reduction because they may reorder intermediate operations.
10273   unsigned CandidateBinOp = Op.getOpcode();
10274   if (Op.getValueType().isFloatingPoint()) {
10275     SDNodeFlags Flags = Op->getFlags();
10276     switch (CandidateBinOp) {
10277     case ISD::FADD:
10278       if (!Flags.hasNoSignedZeros() || !Flags.hasAllowReassociation())
10279         return SDValue();
10280       break;
10281     default:
10282       llvm_unreachable("Unhandled FP opcode for binop reduction");
10283     }
10284   }
10285 
10286   // Matching failed - attempt to see if we did enough stages that a partial
10287   // reduction from a subvector is possible.
10288   auto PartialReduction = [&](SDValue Op, unsigned NumSubElts) {
10289     if (!AllowPartials || !Op)
10290       return SDValue();
10291     EVT OpVT = Op.getValueType();
10292     EVT OpSVT = OpVT.getScalarType();
10293     EVT SubVT = EVT::getVectorVT(*getContext(), OpSVT, NumSubElts);
10294     if (!TLI->isExtractSubvectorCheap(SubVT, OpVT, 0))
10295       return SDValue();
10296     BinOp = (ISD::NodeType)CandidateBinOp;
10297     return getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(Op), SubVT, Op,
10298                    getVectorIdxConstant(0, SDLoc(Op)));
10299   };
10300 
10301   // At each stage, we're looking for something that looks like:
10302   // %s = shufflevector <8 x i32> %op, <8 x i32> undef,
10303   //                    <8 x i32> <i32 2, i32 3, i32 undef, i32 undef,
10304   //                               i32 undef, i32 undef, i32 undef, i32 undef>
10305   // %a = binop <8 x i32> %op, %s
10306   // Where the mask changes according to the stage. E.g. for a 3-stage pyramid,
10307   // we expect something like:
10308   // <4,5,6,7,u,u,u,u>
10309   // <2,3,u,u,u,u,u,u>
10310   // <1,u,u,u,u,u,u,u>
10311   // While a partial reduction match would be:
10312   // <2,3,u,u,u,u,u,u>
10313   // <1,u,u,u,u,u,u,u>
10314   unsigned Stages = Log2_32(Op.getValueType().getVectorNumElements());
10315   SDValue PrevOp;
10316   for (unsigned i = 0; i < Stages; ++i) {
10317     unsigned MaskEnd = (1 << i);
10318 
10319     if (Op.getOpcode() != CandidateBinOp)
10320       return PartialReduction(PrevOp, MaskEnd);
10321 
10322     SDValue Op0 = Op.getOperand(0);
10323     SDValue Op1 = Op.getOperand(1);
10324 
10325     ShuffleVectorSDNode *Shuffle = dyn_cast<ShuffleVectorSDNode>(Op0);
10326     if (Shuffle) {
10327       Op = Op1;
10328     } else {
10329       Shuffle = dyn_cast<ShuffleVectorSDNode>(Op1);
10330       Op = Op0;
10331     }
10332 
10333     // The first operand of the shuffle should be the same as the other operand
10334     // of the binop.
10335     if (!Shuffle || Shuffle->getOperand(0) != Op)
10336       return PartialReduction(PrevOp, MaskEnd);
10337 
10338     // Verify the shuffle has the expected (at this stage of the pyramid) mask.
10339     for (int Index = 0; Index < (int)MaskEnd; ++Index)
10340       if (Shuffle->getMaskElt(Index) != (int)(MaskEnd + Index))
10341         return PartialReduction(PrevOp, MaskEnd);
10342 
10343     PrevOp = Op;
10344   }
10345 
10346   // Handle subvector reductions, which tend to appear after the shuffle
10347   // reduction stages.
10348   while (Op.getOpcode() == CandidateBinOp) {
10349     unsigned NumElts = Op.getValueType().getVectorNumElements();
10350     SDValue Op0 = Op.getOperand(0);
10351     SDValue Op1 = Op.getOperand(1);
10352     if (Op0.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
10353         Op1.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
10354         Op0.getOperand(0) != Op1.getOperand(0))
10355       break;
10356     SDValue Src = Op0.getOperand(0);
10357     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
10358     if (NumSrcElts != (2 * NumElts))
10359       break;
10360     if (!(Op0.getConstantOperandAPInt(1) == 0 &&
10361           Op1.getConstantOperandAPInt(1) == NumElts) &&
10362         !(Op1.getConstantOperandAPInt(1) == 0 &&
10363           Op0.getConstantOperandAPInt(1) == NumElts))
10364       break;
10365     Op = Src;
10366   }
10367 
10368   BinOp = (ISD::NodeType)CandidateBinOp;
10369   return Op;
10370 }
10371 
10372 SDValue SelectionDAG::UnrollVectorOp(SDNode *N, unsigned ResNE) {
10373   assert(N->getNumValues() == 1 &&
10374          "Can't unroll a vector with multiple results!");
10375 
10376   EVT VT = N->getValueType(0);
10377   unsigned NE = VT.getVectorNumElements();
10378   EVT EltVT = VT.getVectorElementType();
10379   SDLoc dl(N);
10380 
10381   SmallVector<SDValue, 8> Scalars;
10382   SmallVector<SDValue, 4> Operands(N->getNumOperands());
10383 
10384   // If ResNE is 0, fully unroll the vector op.
10385   if (ResNE == 0)
10386     ResNE = NE;
10387   else if (NE > ResNE)
10388     NE = ResNE;
10389 
10390   unsigned i;
10391   for (i= 0; i != NE; ++i) {
10392     for (unsigned j = 0, e = N->getNumOperands(); j != e; ++j) {
10393       SDValue Operand = N->getOperand(j);
10394       EVT OperandVT = Operand.getValueType();
10395       if (OperandVT.isVector()) {
10396         // A vector operand; extract a single element.
10397         EVT OperandEltVT = OperandVT.getVectorElementType();
10398         Operands[j] = getNode(ISD::EXTRACT_VECTOR_ELT, dl, OperandEltVT,
10399                               Operand, getVectorIdxConstant(i, dl));
10400       } else {
10401         // A scalar operand; just use it as is.
10402         Operands[j] = Operand;
10403       }
10404     }
10405 
10406     switch (N->getOpcode()) {
10407     default: {
10408       Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands,
10409                                 N->getFlags()));
10410       break;
10411     }
10412     case ISD::VSELECT:
10413       Scalars.push_back(getNode(ISD::SELECT, dl, EltVT, Operands));
10414       break;
10415     case ISD::SHL:
10416     case ISD::SRA:
10417     case ISD::SRL:
10418     case ISD::ROTL:
10419     case ISD::ROTR:
10420       Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands[0],
10421                                getShiftAmountOperand(Operands[0].getValueType(),
10422                                                      Operands[1])));
10423       break;
10424     case ISD::SIGN_EXTEND_INREG: {
10425       EVT ExtVT = cast<VTSDNode>(Operands[1])->getVT().getVectorElementType();
10426       Scalars.push_back(getNode(N->getOpcode(), dl, EltVT,
10427                                 Operands[0],
10428                                 getValueType(ExtVT)));
10429     }
10430     }
10431   }
10432 
10433   for (; i < ResNE; ++i)
10434     Scalars.push_back(getUNDEF(EltVT));
10435 
10436   EVT VecVT = EVT::getVectorVT(*getContext(), EltVT, ResNE);
10437   return getBuildVector(VecVT, dl, Scalars);
10438 }
10439 
10440 std::pair<SDValue, SDValue> SelectionDAG::UnrollVectorOverflowOp(
10441     SDNode *N, unsigned ResNE) {
10442   unsigned Opcode = N->getOpcode();
10443   assert((Opcode == ISD::UADDO || Opcode == ISD::SADDO ||
10444           Opcode == ISD::USUBO || Opcode == ISD::SSUBO ||
10445           Opcode == ISD::UMULO || Opcode == ISD::SMULO) &&
10446          "Expected an overflow opcode");
10447 
10448   EVT ResVT = N->getValueType(0);
10449   EVT OvVT = N->getValueType(1);
10450   EVT ResEltVT = ResVT.getVectorElementType();
10451   EVT OvEltVT = OvVT.getVectorElementType();
10452   SDLoc dl(N);
10453 
10454   // If ResNE is 0, fully unroll the vector op.
10455   unsigned NE = ResVT.getVectorNumElements();
10456   if (ResNE == 0)
10457     ResNE = NE;
10458   else if (NE > ResNE)
10459     NE = ResNE;
10460 
10461   SmallVector<SDValue, 8> LHSScalars;
10462   SmallVector<SDValue, 8> RHSScalars;
10463   ExtractVectorElements(N->getOperand(0), LHSScalars, 0, NE);
10464   ExtractVectorElements(N->getOperand(1), RHSScalars, 0, NE);
10465 
10466   EVT SVT = TLI->getSetCCResultType(getDataLayout(), *getContext(), ResEltVT);
10467   SDVTList VTs = getVTList(ResEltVT, SVT);
10468   SmallVector<SDValue, 8> ResScalars;
10469   SmallVector<SDValue, 8> OvScalars;
10470   for (unsigned i = 0; i < NE; ++i) {
10471     SDValue Res = getNode(Opcode, dl, VTs, LHSScalars[i], RHSScalars[i]);
10472     SDValue Ov =
10473         getSelect(dl, OvEltVT, Res.getValue(1),
10474                   getBoolConstant(true, dl, OvEltVT, ResVT),
10475                   getConstant(0, dl, OvEltVT));
10476 
10477     ResScalars.push_back(Res);
10478     OvScalars.push_back(Ov);
10479   }
10480 
10481   ResScalars.append(ResNE - NE, getUNDEF(ResEltVT));
10482   OvScalars.append(ResNE - NE, getUNDEF(OvEltVT));
10483 
10484   EVT NewResVT = EVT::getVectorVT(*getContext(), ResEltVT, ResNE);
10485   EVT NewOvVT = EVT::getVectorVT(*getContext(), OvEltVT, ResNE);
10486   return std::make_pair(getBuildVector(NewResVT, dl, ResScalars),
10487                         getBuildVector(NewOvVT, dl, OvScalars));
10488 }
10489 
10490 bool SelectionDAG::areNonVolatileConsecutiveLoads(LoadSDNode *LD,
10491                                                   LoadSDNode *Base,
10492                                                   unsigned Bytes,
10493                                                   int Dist) const {
10494   if (LD->isVolatile() || Base->isVolatile())
10495     return false;
10496   // TODO: probably too restrictive for atomics, revisit
10497   if (!LD->isSimple())
10498     return false;
10499   if (LD->isIndexed() || Base->isIndexed())
10500     return false;
10501   if (LD->getChain() != Base->getChain())
10502     return false;
10503   EVT VT = LD->getValueType(0);
10504   if (VT.getSizeInBits() / 8 != Bytes)
10505     return false;
10506 
10507   auto BaseLocDecomp = BaseIndexOffset::match(Base, *this);
10508   auto LocDecomp = BaseIndexOffset::match(LD, *this);
10509 
10510   int64_t Offset = 0;
10511   if (BaseLocDecomp.equalBaseIndex(LocDecomp, *this, Offset))
10512     return (Dist * Bytes == Offset);
10513   return false;
10514 }
10515 
10516 /// InferPtrAlignment - Infer alignment of a load / store address. Return None
10517 /// if it cannot be inferred.
10518 MaybeAlign SelectionDAG::InferPtrAlign(SDValue Ptr) const {
10519   // If this is a GlobalAddress + cst, return the alignment.
10520   const GlobalValue *GV = nullptr;
10521   int64_t GVOffset = 0;
10522   if (TLI->isGAPlusOffset(Ptr.getNode(), GV, GVOffset)) {
10523     unsigned PtrWidth = getDataLayout().getPointerTypeSizeInBits(GV->getType());
10524     KnownBits Known(PtrWidth);
10525     llvm::computeKnownBits(GV, Known, getDataLayout());
10526     unsigned AlignBits = Known.countMinTrailingZeros();
10527     if (AlignBits)
10528       return commonAlignment(Align(1ull << std::min(31U, AlignBits)), GVOffset);
10529   }
10530 
10531   // If this is a direct reference to a stack slot, use information about the
10532   // stack slot's alignment.
10533   int FrameIdx = INT_MIN;
10534   int64_t FrameOffset = 0;
10535   if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr)) {
10536     FrameIdx = FI->getIndex();
10537   } else if (isBaseWithConstantOffset(Ptr) &&
10538              isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
10539     // Handle FI+Cst
10540     FrameIdx = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
10541     FrameOffset = Ptr.getConstantOperandVal(1);
10542   }
10543 
10544   if (FrameIdx != INT_MIN) {
10545     const MachineFrameInfo &MFI = getMachineFunction().getFrameInfo();
10546     return commonAlignment(MFI.getObjectAlign(FrameIdx), FrameOffset);
10547   }
10548 
10549   return None;
10550 }
10551 
10552 /// GetSplitDestVTs - Compute the VTs needed for the low/hi parts of a type
10553 /// which is split (or expanded) into two not necessarily identical pieces.
10554 std::pair<EVT, EVT> SelectionDAG::GetSplitDestVTs(const EVT &VT) const {
10555   // Currently all types are split in half.
10556   EVT LoVT, HiVT;
10557   if (!VT.isVector())
10558     LoVT = HiVT = TLI->getTypeToTransformTo(*getContext(), VT);
10559   else
10560     LoVT = HiVT = VT.getHalfNumVectorElementsVT(*getContext());
10561 
10562   return std::make_pair(LoVT, HiVT);
10563 }
10564 
10565 /// GetDependentSplitDestVTs - Compute the VTs needed for the low/hi parts of a
10566 /// type, dependent on an enveloping VT that has been split into two identical
10567 /// pieces. Sets the HiIsEmpty flag when hi type has zero storage size.
10568 std::pair<EVT, EVT>
10569 SelectionDAG::GetDependentSplitDestVTs(const EVT &VT, const EVT &EnvVT,
10570                                        bool *HiIsEmpty) const {
10571   EVT EltTp = VT.getVectorElementType();
10572   // Examples:
10573   //   custom VL=8  with enveloping VL=8/8 yields 8/0 (hi empty)
10574   //   custom VL=9  with enveloping VL=8/8 yields 8/1
10575   //   custom VL=10 with enveloping VL=8/8 yields 8/2
10576   //   etc.
10577   ElementCount VTNumElts = VT.getVectorElementCount();
10578   ElementCount EnvNumElts = EnvVT.getVectorElementCount();
10579   assert(VTNumElts.isScalable() == EnvNumElts.isScalable() &&
10580          "Mixing fixed width and scalable vectors when enveloping a type");
10581   EVT LoVT, HiVT;
10582   if (VTNumElts.getKnownMinValue() > EnvNumElts.getKnownMinValue()) {
10583     LoVT = EVT::getVectorVT(*getContext(), EltTp, EnvNumElts);
10584     HiVT = EVT::getVectorVT(*getContext(), EltTp, VTNumElts - EnvNumElts);
10585     *HiIsEmpty = false;
10586   } else {
10587     // Flag that hi type has zero storage size, but return split envelop type
10588     // (this would be easier if vector types with zero elements were allowed).
10589     LoVT = EVT::getVectorVT(*getContext(), EltTp, VTNumElts);
10590     HiVT = EVT::getVectorVT(*getContext(), EltTp, EnvNumElts);
10591     *HiIsEmpty = true;
10592   }
10593   return std::make_pair(LoVT, HiVT);
10594 }
10595 
10596 /// SplitVector - Split the vector with EXTRACT_SUBVECTOR and return the
10597 /// low/high part.
10598 std::pair<SDValue, SDValue>
10599 SelectionDAG::SplitVector(const SDValue &N, const SDLoc &DL, const EVT &LoVT,
10600                           const EVT &HiVT) {
10601   assert(LoVT.isScalableVector() == HiVT.isScalableVector() &&
10602          LoVT.isScalableVector() == N.getValueType().isScalableVector() &&
10603          "Splitting vector with an invalid mixture of fixed and scalable "
10604          "vector types");
10605   assert(LoVT.getVectorMinNumElements() + HiVT.getVectorMinNumElements() <=
10606              N.getValueType().getVectorMinNumElements() &&
10607          "More vector elements requested than available!");
10608   SDValue Lo, Hi;
10609   Lo =
10610       getNode(ISD::EXTRACT_SUBVECTOR, DL, LoVT, N, getVectorIdxConstant(0, DL));
10611   // For scalable vectors it is safe to use LoVT.getVectorMinNumElements()
10612   // (rather than having to use ElementCount), because EXTRACT_SUBVECTOR scales
10613   // IDX with the runtime scaling factor of the result vector type. For
10614   // fixed-width result vectors, that runtime scaling factor is 1.
10615   Hi = getNode(ISD::EXTRACT_SUBVECTOR, DL, HiVT, N,
10616                getVectorIdxConstant(LoVT.getVectorMinNumElements(), DL));
10617   return std::make_pair(Lo, Hi);
10618 }
10619 
10620 /// Widen the vector up to the next power of two using INSERT_SUBVECTOR.
10621 SDValue SelectionDAG::WidenVector(const SDValue &N, const SDLoc &DL) {
10622   EVT VT = N.getValueType();
10623   EVT WideVT = EVT::getVectorVT(*getContext(), VT.getVectorElementType(),
10624                                 NextPowerOf2(VT.getVectorNumElements()));
10625   return getNode(ISD::INSERT_SUBVECTOR, DL, WideVT, getUNDEF(WideVT), N,
10626                  getVectorIdxConstant(0, DL));
10627 }
10628 
10629 void SelectionDAG::ExtractVectorElements(SDValue Op,
10630                                          SmallVectorImpl<SDValue> &Args,
10631                                          unsigned Start, unsigned Count,
10632                                          EVT EltVT) {
10633   EVT VT = Op.getValueType();
10634   if (Count == 0)
10635     Count = VT.getVectorNumElements();
10636   if (EltVT == EVT())
10637     EltVT = VT.getVectorElementType();
10638   SDLoc SL(Op);
10639   for (unsigned i = Start, e = Start + Count; i != e; ++i) {
10640     Args.push_back(getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Op,
10641                            getVectorIdxConstant(i, SL)));
10642   }
10643 }
10644 
10645 // getAddressSpace - Return the address space this GlobalAddress belongs to.
10646 unsigned GlobalAddressSDNode::getAddressSpace() const {
10647   return getGlobal()->getType()->getAddressSpace();
10648 }
10649 
10650 Type *ConstantPoolSDNode::getType() const {
10651   if (isMachineConstantPoolEntry())
10652     return Val.MachineCPVal->getType();
10653   return Val.ConstVal->getType();
10654 }
10655 
10656 bool BuildVectorSDNode::isConstantSplat(APInt &SplatValue, APInt &SplatUndef,
10657                                         unsigned &SplatBitSize,
10658                                         bool &HasAnyUndefs,
10659                                         unsigned MinSplatBits,
10660                                         bool IsBigEndian) const {
10661   EVT VT = getValueType(0);
10662   assert(VT.isVector() && "Expected a vector type");
10663   unsigned VecWidth = VT.getSizeInBits();
10664   if (MinSplatBits > VecWidth)
10665     return false;
10666 
10667   // FIXME: The widths are based on this node's type, but build vectors can
10668   // truncate their operands.
10669   SplatValue = APInt(VecWidth, 0);
10670   SplatUndef = APInt(VecWidth, 0);
10671 
10672   // Get the bits. Bits with undefined values (when the corresponding element
10673   // of the vector is an ISD::UNDEF value) are set in SplatUndef and cleared
10674   // in SplatValue. If any of the values are not constant, give up and return
10675   // false.
10676   unsigned int NumOps = getNumOperands();
10677   assert(NumOps > 0 && "isConstantSplat has 0-size build vector");
10678   unsigned EltWidth = VT.getScalarSizeInBits();
10679 
10680   for (unsigned j = 0; j < NumOps; ++j) {
10681     unsigned i = IsBigEndian ? NumOps - 1 - j : j;
10682     SDValue OpVal = getOperand(i);
10683     unsigned BitPos = j * EltWidth;
10684 
10685     if (OpVal.isUndef())
10686       SplatUndef.setBits(BitPos, BitPos + EltWidth);
10687     else if (auto *CN = dyn_cast<ConstantSDNode>(OpVal))
10688       SplatValue.insertBits(CN->getAPIntValue().zextOrTrunc(EltWidth), BitPos);
10689     else if (auto *CN = dyn_cast<ConstantFPSDNode>(OpVal))
10690       SplatValue.insertBits(CN->getValueAPF().bitcastToAPInt(), BitPos);
10691     else
10692       return false;
10693   }
10694 
10695   // The build_vector is all constants or undefs. Find the smallest element
10696   // size that splats the vector.
10697   HasAnyUndefs = (SplatUndef != 0);
10698 
10699   // FIXME: This does not work for vectors with elements less than 8 bits.
10700   while (VecWidth > 8) {
10701     unsigned HalfSize = VecWidth / 2;
10702     APInt HighValue = SplatValue.extractBits(HalfSize, HalfSize);
10703     APInt LowValue = SplatValue.extractBits(HalfSize, 0);
10704     APInt HighUndef = SplatUndef.extractBits(HalfSize, HalfSize);
10705     APInt LowUndef = SplatUndef.extractBits(HalfSize, 0);
10706 
10707     // If the two halves do not match (ignoring undef bits), stop here.
10708     if ((HighValue & ~LowUndef) != (LowValue & ~HighUndef) ||
10709         MinSplatBits > HalfSize)
10710       break;
10711 
10712     SplatValue = HighValue | LowValue;
10713     SplatUndef = HighUndef & LowUndef;
10714 
10715     VecWidth = HalfSize;
10716   }
10717 
10718   SplatBitSize = VecWidth;
10719   return true;
10720 }
10721 
10722 SDValue BuildVectorSDNode::getSplatValue(const APInt &DemandedElts,
10723                                          BitVector *UndefElements) const {
10724   unsigned NumOps = getNumOperands();
10725   if (UndefElements) {
10726     UndefElements->clear();
10727     UndefElements->resize(NumOps);
10728   }
10729   assert(NumOps == DemandedElts.getBitWidth() && "Unexpected vector size");
10730   if (!DemandedElts)
10731     return SDValue();
10732   SDValue Splatted;
10733   for (unsigned i = 0; i != NumOps; ++i) {
10734     if (!DemandedElts[i])
10735       continue;
10736     SDValue Op = getOperand(i);
10737     if (Op.isUndef()) {
10738       if (UndefElements)
10739         (*UndefElements)[i] = true;
10740     } else if (!Splatted) {
10741       Splatted = Op;
10742     } else if (Splatted != Op) {
10743       return SDValue();
10744     }
10745   }
10746 
10747   if (!Splatted) {
10748     unsigned FirstDemandedIdx = DemandedElts.countTrailingZeros();
10749     assert(getOperand(FirstDemandedIdx).isUndef() &&
10750            "Can only have a splat without a constant for all undefs.");
10751     return getOperand(FirstDemandedIdx);
10752   }
10753 
10754   return Splatted;
10755 }
10756 
10757 SDValue BuildVectorSDNode::getSplatValue(BitVector *UndefElements) const {
10758   APInt DemandedElts = APInt::getAllOnes(getNumOperands());
10759   return getSplatValue(DemandedElts, UndefElements);
10760 }
10761 
10762 bool BuildVectorSDNode::getRepeatedSequence(const APInt &DemandedElts,
10763                                             SmallVectorImpl<SDValue> &Sequence,
10764                                             BitVector *UndefElements) const {
10765   unsigned NumOps = getNumOperands();
10766   Sequence.clear();
10767   if (UndefElements) {
10768     UndefElements->clear();
10769     UndefElements->resize(NumOps);
10770   }
10771   assert(NumOps == DemandedElts.getBitWidth() && "Unexpected vector size");
10772   if (!DemandedElts || NumOps < 2 || !isPowerOf2_32(NumOps))
10773     return false;
10774 
10775   // Set the undefs even if we don't find a sequence (like getSplatValue).
10776   if (UndefElements)
10777     for (unsigned I = 0; I != NumOps; ++I)
10778       if (DemandedElts[I] && getOperand(I).isUndef())
10779         (*UndefElements)[I] = true;
10780 
10781   // Iteratively widen the sequence length looking for repetitions.
10782   for (unsigned SeqLen = 1; SeqLen < NumOps; SeqLen *= 2) {
10783     Sequence.append(SeqLen, SDValue());
10784     for (unsigned I = 0; I != NumOps; ++I) {
10785       if (!DemandedElts[I])
10786         continue;
10787       SDValue &SeqOp = Sequence[I % SeqLen];
10788       SDValue Op = getOperand(I);
10789       if (Op.isUndef()) {
10790         if (!SeqOp)
10791           SeqOp = Op;
10792         continue;
10793       }
10794       if (SeqOp && !SeqOp.isUndef() && SeqOp != Op) {
10795         Sequence.clear();
10796         break;
10797       }
10798       SeqOp = Op;
10799     }
10800     if (!Sequence.empty())
10801       return true;
10802   }
10803 
10804   assert(Sequence.empty() && "Failed to empty non-repeating sequence pattern");
10805   return false;
10806 }
10807 
10808 bool BuildVectorSDNode::getRepeatedSequence(SmallVectorImpl<SDValue> &Sequence,
10809                                             BitVector *UndefElements) const {
10810   APInt DemandedElts = APInt::getAllOnes(getNumOperands());
10811   return getRepeatedSequence(DemandedElts, Sequence, UndefElements);
10812 }
10813 
10814 ConstantSDNode *
10815 BuildVectorSDNode::getConstantSplatNode(const APInt &DemandedElts,
10816                                         BitVector *UndefElements) const {
10817   return dyn_cast_or_null<ConstantSDNode>(
10818       getSplatValue(DemandedElts, UndefElements));
10819 }
10820 
10821 ConstantSDNode *
10822 BuildVectorSDNode::getConstantSplatNode(BitVector *UndefElements) const {
10823   return dyn_cast_or_null<ConstantSDNode>(getSplatValue(UndefElements));
10824 }
10825 
10826 ConstantFPSDNode *
10827 BuildVectorSDNode::getConstantFPSplatNode(const APInt &DemandedElts,
10828                                           BitVector *UndefElements) const {
10829   return dyn_cast_or_null<ConstantFPSDNode>(
10830       getSplatValue(DemandedElts, UndefElements));
10831 }
10832 
10833 ConstantFPSDNode *
10834 BuildVectorSDNode::getConstantFPSplatNode(BitVector *UndefElements) const {
10835   return dyn_cast_or_null<ConstantFPSDNode>(getSplatValue(UndefElements));
10836 }
10837 
10838 int32_t
10839 BuildVectorSDNode::getConstantFPSplatPow2ToLog2Int(BitVector *UndefElements,
10840                                                    uint32_t BitWidth) const {
10841   if (ConstantFPSDNode *CN =
10842           dyn_cast_or_null<ConstantFPSDNode>(getSplatValue(UndefElements))) {
10843     bool IsExact;
10844     APSInt IntVal(BitWidth);
10845     const APFloat &APF = CN->getValueAPF();
10846     if (APF.convertToInteger(IntVal, APFloat::rmTowardZero, &IsExact) !=
10847             APFloat::opOK ||
10848         !IsExact)
10849       return -1;
10850 
10851     return IntVal.exactLogBase2();
10852   }
10853   return -1;
10854 }
10855 
10856 bool BuildVectorSDNode::getConstantRawBits(
10857     bool IsLittleEndian, unsigned DstEltSizeInBits,
10858     SmallVectorImpl<APInt> &RawBitElements, BitVector &UndefElements) const {
10859   // Early-out if this contains anything but Undef/Constant/ConstantFP.
10860   if (!isConstant())
10861     return false;
10862 
10863   unsigned NumSrcOps = getNumOperands();
10864   unsigned SrcEltSizeInBits = getValueType(0).getScalarSizeInBits();
10865   assert(((NumSrcOps * SrcEltSizeInBits) % DstEltSizeInBits) == 0 &&
10866          "Invalid bitcast scale");
10867 
10868   // Extract raw src bits.
10869   SmallVector<APInt> SrcBitElements(NumSrcOps,
10870                                     APInt::getNullValue(SrcEltSizeInBits));
10871   BitVector SrcUndeElements(NumSrcOps, false);
10872 
10873   for (unsigned I = 0; I != NumSrcOps; ++I) {
10874     SDValue Op = getOperand(I);
10875     if (Op.isUndef()) {
10876       SrcUndeElements.set(I);
10877       continue;
10878     }
10879     auto *CInt = dyn_cast<ConstantSDNode>(Op);
10880     auto *CFP = dyn_cast<ConstantFPSDNode>(Op);
10881     assert((CInt || CFP) && "Unknown constant");
10882     SrcBitElements[I] =
10883         CInt ? CInt->getAPIntValue().truncOrSelf(SrcEltSizeInBits)
10884              : CFP->getValueAPF().bitcastToAPInt();
10885   }
10886 
10887   // Recast to dst width.
10888   recastRawBits(IsLittleEndian, DstEltSizeInBits, RawBitElements,
10889                 SrcBitElements, UndefElements, SrcUndeElements);
10890   return true;
10891 }
10892 
10893 void BuildVectorSDNode::recastRawBits(bool IsLittleEndian,
10894                                       unsigned DstEltSizeInBits,
10895                                       SmallVectorImpl<APInt> &DstBitElements,
10896                                       ArrayRef<APInt> SrcBitElements,
10897                                       BitVector &DstUndefElements,
10898                                       const BitVector &SrcUndefElements) {
10899   unsigned NumSrcOps = SrcBitElements.size();
10900   unsigned SrcEltSizeInBits = SrcBitElements[0].getBitWidth();
10901   assert(((NumSrcOps * SrcEltSizeInBits) % DstEltSizeInBits) == 0 &&
10902          "Invalid bitcast scale");
10903   assert(NumSrcOps == SrcUndefElements.size() &&
10904          "Vector size mismatch");
10905 
10906   unsigned NumDstOps = (NumSrcOps * SrcEltSizeInBits) / DstEltSizeInBits;
10907   DstUndefElements.clear();
10908   DstUndefElements.resize(NumDstOps, false);
10909   DstBitElements.assign(NumDstOps, APInt::getNullValue(DstEltSizeInBits));
10910 
10911   // Concatenate src elements constant bits together into dst element.
10912   if (SrcEltSizeInBits <= DstEltSizeInBits) {
10913     unsigned Scale = DstEltSizeInBits / SrcEltSizeInBits;
10914     for (unsigned I = 0; I != NumDstOps; ++I) {
10915       DstUndefElements.set(I);
10916       APInt &DstBits = DstBitElements[I];
10917       for (unsigned J = 0; J != Scale; ++J) {
10918         unsigned Idx = (I * Scale) + (IsLittleEndian ? J : (Scale - J - 1));
10919         if (SrcUndefElements[Idx])
10920           continue;
10921         DstUndefElements.reset(I);
10922         const APInt &SrcBits = SrcBitElements[Idx];
10923         assert(SrcBits.getBitWidth() == SrcEltSizeInBits &&
10924                "Illegal constant bitwidths");
10925         DstBits.insertBits(SrcBits, J * SrcEltSizeInBits);
10926       }
10927     }
10928     return;
10929   }
10930 
10931   // Split src element constant bits into dst elements.
10932   unsigned Scale = SrcEltSizeInBits / DstEltSizeInBits;
10933   for (unsigned I = 0; I != NumSrcOps; ++I) {
10934     if (SrcUndefElements[I]) {
10935       DstUndefElements.set(I * Scale, (I + 1) * Scale);
10936       continue;
10937     }
10938     const APInt &SrcBits = SrcBitElements[I];
10939     for (unsigned J = 0; J != Scale; ++J) {
10940       unsigned Idx = (I * Scale) + (IsLittleEndian ? J : (Scale - J - 1));
10941       APInt &DstBits = DstBitElements[Idx];
10942       DstBits = SrcBits.extractBits(DstEltSizeInBits, J * DstEltSizeInBits);
10943     }
10944   }
10945 }
10946 
10947 bool BuildVectorSDNode::isConstant() const {
10948   for (const SDValue &Op : op_values()) {
10949     unsigned Opc = Op.getOpcode();
10950     if (Opc != ISD::UNDEF && Opc != ISD::Constant && Opc != ISD::ConstantFP)
10951       return false;
10952   }
10953   return true;
10954 }
10955 
10956 bool ShuffleVectorSDNode::isSplatMask(const int *Mask, EVT VT) {
10957   // Find the first non-undef value in the shuffle mask.
10958   unsigned i, e;
10959   for (i = 0, e = VT.getVectorNumElements(); i != e && Mask[i] < 0; ++i)
10960     /* search */;
10961 
10962   // If all elements are undefined, this shuffle can be considered a splat
10963   // (although it should eventually get simplified away completely).
10964   if (i == e)
10965     return true;
10966 
10967   // Make sure all remaining elements are either undef or the same as the first
10968   // non-undef value.
10969   for (int Idx = Mask[i]; i != e; ++i)
10970     if (Mask[i] >= 0 && Mask[i] != Idx)
10971       return false;
10972   return true;
10973 }
10974 
10975 // Returns the SDNode if it is a constant integer BuildVector
10976 // or constant integer.
10977 SDNode *SelectionDAG::isConstantIntBuildVectorOrConstantInt(SDValue N) const {
10978   if (isa<ConstantSDNode>(N))
10979     return N.getNode();
10980   if (ISD::isBuildVectorOfConstantSDNodes(N.getNode()))
10981     return N.getNode();
10982   // Treat a GlobalAddress supporting constant offset folding as a
10983   // constant integer.
10984   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N))
10985     if (GA->getOpcode() == ISD::GlobalAddress &&
10986         TLI->isOffsetFoldingLegal(GA))
10987       return GA;
10988   if ((N.getOpcode() == ISD::SPLAT_VECTOR) &&
10989       isa<ConstantSDNode>(N.getOperand(0)))
10990     return N.getNode();
10991   return nullptr;
10992 }
10993 
10994 // Returns the SDNode if it is a constant float BuildVector
10995 // or constant float.
10996 SDNode *SelectionDAG::isConstantFPBuildVectorOrConstantFP(SDValue N) const {
10997   if (isa<ConstantFPSDNode>(N))
10998     return N.getNode();
10999 
11000   if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode()))
11001     return N.getNode();
11002 
11003   return nullptr;
11004 }
11005 
11006 void SelectionDAG::createOperands(SDNode *Node, ArrayRef<SDValue> Vals) {
11007   assert(!Node->OperandList && "Node already has operands");
11008   assert(SDNode::getMaxNumOperands() >= Vals.size() &&
11009          "too many operands to fit into SDNode");
11010   SDUse *Ops = OperandRecycler.allocate(
11011       ArrayRecycler<SDUse>::Capacity::get(Vals.size()), OperandAllocator);
11012 
11013   bool IsDivergent = false;
11014   for (unsigned I = 0; I != Vals.size(); ++I) {
11015     Ops[I].setUser(Node);
11016     Ops[I].setInitial(Vals[I]);
11017     if (Ops[I].Val.getValueType() != MVT::Other) // Skip Chain. It does not carry divergence.
11018       IsDivergent |= Ops[I].getNode()->isDivergent();
11019   }
11020   Node->NumOperands = Vals.size();
11021   Node->OperandList = Ops;
11022   if (!TLI->isSDNodeAlwaysUniform(Node)) {
11023     IsDivergent |= TLI->isSDNodeSourceOfDivergence(Node, FLI, DA);
11024     Node->SDNodeBits.IsDivergent = IsDivergent;
11025   }
11026   checkForCycles(Node);
11027 }
11028 
11029 SDValue SelectionDAG::getTokenFactor(const SDLoc &DL,
11030                                      SmallVectorImpl<SDValue> &Vals) {
11031   size_t Limit = SDNode::getMaxNumOperands();
11032   while (Vals.size() > Limit) {
11033     unsigned SliceIdx = Vals.size() - Limit;
11034     auto ExtractedTFs = ArrayRef<SDValue>(Vals).slice(SliceIdx, Limit);
11035     SDValue NewTF = getNode(ISD::TokenFactor, DL, MVT::Other, ExtractedTFs);
11036     Vals.erase(Vals.begin() + SliceIdx, Vals.end());
11037     Vals.emplace_back(NewTF);
11038   }
11039   return getNode(ISD::TokenFactor, DL, MVT::Other, Vals);
11040 }
11041 
11042 SDValue SelectionDAG::getNeutralElement(unsigned Opcode, const SDLoc &DL,
11043                                         EVT VT, SDNodeFlags Flags) {
11044   switch (Opcode) {
11045   default:
11046     return SDValue();
11047   case ISD::ADD:
11048   case ISD::OR:
11049   case ISD::XOR:
11050   case ISD::UMAX:
11051     return getConstant(0, DL, VT);
11052   case ISD::MUL:
11053     return getConstant(1, DL, VT);
11054   case ISD::AND:
11055   case ISD::UMIN:
11056     return getAllOnesConstant(DL, VT);
11057   case ISD::SMAX:
11058     return getConstant(APInt::getSignedMinValue(VT.getSizeInBits()), DL, VT);
11059   case ISD::SMIN:
11060     return getConstant(APInt::getSignedMaxValue(VT.getSizeInBits()), DL, VT);
11061   case ISD::FADD:
11062     return getConstantFP(-0.0, DL, VT);
11063   case ISD::FMUL:
11064     return getConstantFP(1.0, DL, VT);
11065   case ISD::FMINNUM:
11066   case ISD::FMAXNUM: {
11067     // Neutral element for fminnum is NaN, Inf or FLT_MAX, depending on FMF.
11068     const fltSemantics &Semantics = EVTToAPFloatSemantics(VT);
11069     APFloat NeutralAF = !Flags.hasNoNaNs() ? APFloat::getQNaN(Semantics) :
11070                         !Flags.hasNoInfs() ? APFloat::getInf(Semantics) :
11071                         APFloat::getLargest(Semantics);
11072     if (Opcode == ISD::FMAXNUM)
11073       NeutralAF.changeSign();
11074 
11075     return getConstantFP(NeutralAF, DL, VT);
11076   }
11077   }
11078 }
11079 
11080 #ifndef NDEBUG
11081 static void checkForCyclesHelper(const SDNode *N,
11082                                  SmallPtrSetImpl<const SDNode*> &Visited,
11083                                  SmallPtrSetImpl<const SDNode*> &Checked,
11084                                  const llvm::SelectionDAG *DAG) {
11085   // If this node has already been checked, don't check it again.
11086   if (Checked.count(N))
11087     return;
11088 
11089   // If a node has already been visited on this depth-first walk, reject it as
11090   // a cycle.
11091   if (!Visited.insert(N).second) {
11092     errs() << "Detected cycle in SelectionDAG\n";
11093     dbgs() << "Offending node:\n";
11094     N->dumprFull(DAG); dbgs() << "\n";
11095     abort();
11096   }
11097 
11098   for (const SDValue &Op : N->op_values())
11099     checkForCyclesHelper(Op.getNode(), Visited, Checked, DAG);
11100 
11101   Checked.insert(N);
11102   Visited.erase(N);
11103 }
11104 #endif
11105 
11106 void llvm::checkForCycles(const llvm::SDNode *N,
11107                           const llvm::SelectionDAG *DAG,
11108                           bool force) {
11109 #ifndef NDEBUG
11110   bool check = force;
11111 #ifdef EXPENSIVE_CHECKS
11112   check = true;
11113 #endif  // EXPENSIVE_CHECKS
11114   if (check) {
11115     assert(N && "Checking nonexistent SDNode");
11116     SmallPtrSet<const SDNode*, 32> visited;
11117     SmallPtrSet<const SDNode*, 32> checked;
11118     checkForCyclesHelper(N, visited, checked, DAG);
11119   }
11120 #endif  // !NDEBUG
11121 }
11122 
11123 void llvm::checkForCycles(const llvm::SelectionDAG *DAG, bool force) {
11124   checkForCycles(DAG->getRoot().getNode(), DAG, force);
11125 }
11126