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