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/FunctionLoweringInfo.h"
32 #include "llvm/CodeGen/ISDOpcodes.h"
33 #include "llvm/CodeGen/MachineBasicBlock.h"
34 #include "llvm/CodeGen/MachineConstantPool.h"
35 #include "llvm/CodeGen/MachineFrameInfo.h"
36 #include "llvm/CodeGen/MachineFunction.h"
37 #include "llvm/CodeGen/MachineMemOperand.h"
38 #include "llvm/CodeGen/RuntimeLibcalls.h"
39 #include "llvm/CodeGen/SelectionDAGAddressAnalysis.h"
40 #include "llvm/CodeGen/SelectionDAGNodes.h"
41 #include "llvm/CodeGen/SelectionDAGTargetInfo.h"
42 #include "llvm/CodeGen/TargetFrameLowering.h"
43 #include "llvm/CodeGen/TargetLowering.h"
44 #include "llvm/CodeGen/TargetRegisterInfo.h"
45 #include "llvm/CodeGen/TargetSubtargetInfo.h"
46 #include "llvm/CodeGen/ValueTypes.h"
47 #include "llvm/IR/Constant.h"
48 #include "llvm/IR/Constants.h"
49 #include "llvm/IR/DataLayout.h"
50 #include "llvm/IR/DebugInfoMetadata.h"
51 #include "llvm/IR/DebugLoc.h"
52 #include "llvm/IR/DerivedTypes.h"
53 #include "llvm/IR/Function.h"
54 #include "llvm/IR/GlobalValue.h"
55 #include "llvm/IR/Metadata.h"
56 #include "llvm/IR/Type.h"
57 #include "llvm/IR/Value.h"
58 #include "llvm/Support/Casting.h"
59 #include "llvm/Support/CodeGen.h"
60 #include "llvm/Support/Compiler.h"
61 #include "llvm/Support/Debug.h"
62 #include "llvm/Support/ErrorHandling.h"
63 #include "llvm/Support/KnownBits.h"
64 #include "llvm/Support/MachineValueType.h"
65 #include "llvm/Support/ManagedStatic.h"
66 #include "llvm/Support/MathExtras.h"
67 #include "llvm/Support/Mutex.h"
68 #include "llvm/Support/raw_ostream.h"
69 #include "llvm/Target/TargetMachine.h"
70 #include "llvm/Target/TargetOptions.h"
71 #include "llvm/Transforms/Utils/SizeOpts.h"
72 #include <algorithm>
73 #include <cassert>
74 #include <cstdint>
75 #include <cstdlib>
76 #include <limits>
77 #include <set>
78 #include <string>
79 #include <utility>
80 #include <vector>
81 
82 using namespace llvm;
83 
84 /// makeVTList - Return an instance of the SDVTList struct initialized with the
85 /// specified members.
86 static SDVTList makeVTList(const EVT *VTs, unsigned NumVTs) {
87   SDVTList Res = {VTs, NumVTs};
88   return Res;
89 }
90 
91 // Default null implementations of the callbacks.
92 void SelectionDAG::DAGUpdateListener::NodeDeleted(SDNode*, SDNode*) {}
93 void SelectionDAG::DAGUpdateListener::NodeUpdated(SDNode*) {}
94 void SelectionDAG::DAGUpdateListener::NodeInserted(SDNode *) {}
95 
96 void SelectionDAG::DAGNodeDeletedListener::anchor() {}
97 
98 #define DEBUG_TYPE "selectiondag"
99 
100 static cl::opt<bool> EnableMemCpyDAGOpt("enable-memcpy-dag-opt",
101        cl::Hidden, cl::init(true),
102        cl::desc("Gang up loads and stores generated by inlining of memcpy"));
103 
104 static cl::opt<int> MaxLdStGlue("ldstmemcpy-glue-max",
105        cl::desc("Number limit for gluing ld/st of memcpy."),
106        cl::Hidden, cl::init(0));
107 
108 static void NewSDValueDbgMsg(SDValue V, StringRef Msg, SelectionDAG *G) {
109   LLVM_DEBUG(dbgs() << Msg; V.getNode()->dump(G););
110 }
111 
112 //===----------------------------------------------------------------------===//
113 //                              ConstantFPSDNode Class
114 //===----------------------------------------------------------------------===//
115 
116 /// isExactlyValue - We don't rely on operator== working on double values, as
117 /// it returns true for things that are clearly not equal, like -0.0 and 0.0.
118 /// As such, this method can be used to do an exact bit-for-bit comparison of
119 /// two floating point values.
120 bool ConstantFPSDNode::isExactlyValue(const APFloat& V) const {
121   return getValueAPF().bitwiseIsEqual(V);
122 }
123 
124 bool ConstantFPSDNode::isValueValidForType(EVT VT,
125                                            const APFloat& Val) {
126   assert(VT.isFloatingPoint() && "Can only convert between FP types");
127 
128   // convert modifies in place, so make a copy.
129   APFloat Val2 = APFloat(Val);
130   bool losesInfo;
131   (void) Val2.convert(SelectionDAG::EVTToAPFloatSemantics(VT),
132                       APFloat::rmNearestTiesToEven,
133                       &losesInfo);
134   return !losesInfo;
135 }
136 
137 //===----------------------------------------------------------------------===//
138 //                              ISD Namespace
139 //===----------------------------------------------------------------------===//
140 
141 bool ISD::isConstantSplatVector(const SDNode *N, APInt &SplatVal) {
142   if (N->getOpcode() == ISD::SPLAT_VECTOR) {
143     unsigned EltSize =
144         N->getValueType(0).getVectorElementType().getSizeInBits();
145     if (auto *Op0 = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
146       SplatVal = Op0->getAPIntValue().truncOrSelf(EltSize);
147       return true;
148     }
149     if (auto *Op0 = dyn_cast<ConstantFPSDNode>(N->getOperand(0))) {
150       SplatVal = Op0->getValueAPF().bitcastToAPInt().truncOrSelf(EltSize);
151       return true;
152     }
153   }
154 
155   auto *BV = dyn_cast<BuildVectorSDNode>(N);
156   if (!BV)
157     return false;
158 
159   APInt SplatUndef;
160   unsigned SplatBitSize;
161   bool HasUndefs;
162   unsigned EltSize = N->getValueType(0).getVectorElementType().getSizeInBits();
163   return BV->isConstantSplat(SplatVal, SplatUndef, SplatBitSize, HasUndefs,
164                              EltSize) &&
165          EltSize == SplatBitSize;
166 }
167 
168 // FIXME: AllOnes and AllZeros duplicate a lot of code. Could these be
169 // specializations of the more general isConstantSplatVector()?
170 
171 bool ISD::isConstantSplatVectorAllOnes(const SDNode *N, bool BuildVectorOnly) {
172   // Look through a bit convert.
173   while (N->getOpcode() == ISD::BITCAST)
174     N = N->getOperand(0).getNode();
175 
176   if (!BuildVectorOnly && N->getOpcode() == ISD::SPLAT_VECTOR) {
177     APInt SplatVal;
178     return isConstantSplatVector(N, SplatVal) && SplatVal.isAllOnesValue();
179   }
180 
181   if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
182 
183   unsigned i = 0, e = N->getNumOperands();
184 
185   // Skip over all of the undef values.
186   while (i != e && N->getOperand(i).isUndef())
187     ++i;
188 
189   // Do not accept an all-undef vector.
190   if (i == e) return false;
191 
192   // Do not accept build_vectors that aren't all constants or which have non-~0
193   // elements. We have to be a bit careful here, as the type of the constant
194   // may not be the same as the type of the vector elements due to type
195   // legalization (the elements are promoted to a legal type for the target and
196   // a vector of a type may be legal when the base element type is not).
197   // We only want to check enough bits to cover the vector elements, because
198   // we care if the resultant vector is all ones, not whether the individual
199   // constants are.
200   SDValue NotZero = N->getOperand(i);
201   unsigned EltSize = N->getValueType(0).getScalarSizeInBits();
202   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(NotZero)) {
203     if (CN->getAPIntValue().countTrailingOnes() < EltSize)
204       return false;
205   } else if (ConstantFPSDNode *CFPN = dyn_cast<ConstantFPSDNode>(NotZero)) {
206     if (CFPN->getValueAPF().bitcastToAPInt().countTrailingOnes() < EltSize)
207       return false;
208   } else
209     return false;
210 
211   // Okay, we have at least one ~0 value, check to see if the rest match or are
212   // undefs. Even with the above element type twiddling, this should be OK, as
213   // the same type legalization should have applied to all the elements.
214   for (++i; i != e; ++i)
215     if (N->getOperand(i) != NotZero && !N->getOperand(i).isUndef())
216       return false;
217   return true;
218 }
219 
220 bool ISD::isConstantSplatVectorAllZeros(const SDNode *N, bool BuildVectorOnly) {
221   // Look through a bit convert.
222   while (N->getOpcode() == ISD::BITCAST)
223     N = N->getOperand(0).getNode();
224 
225   if (!BuildVectorOnly && N->getOpcode() == ISD::SPLAT_VECTOR) {
226     APInt SplatVal;
227     return isConstantSplatVector(N, SplatVal) && SplatVal.isNullValue();
228   }
229 
230   if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
231 
232   bool IsAllUndef = true;
233   for (const SDValue &Op : N->op_values()) {
234     if (Op.isUndef())
235       continue;
236     IsAllUndef = false;
237     // Do not accept build_vectors that aren't all constants or which have non-0
238     // elements. We have to be a bit careful here, as the type of the constant
239     // may not be the same as the type of the vector elements due to type
240     // legalization (the elements are promoted to a legal type for the target
241     // and a vector of a type may be legal when the base element type is not).
242     // We only want to check enough bits to cover the vector elements, because
243     // we care if the resultant vector is all zeros, not whether the individual
244     // constants are.
245     unsigned EltSize = N->getValueType(0).getScalarSizeInBits();
246     if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Op)) {
247       if (CN->getAPIntValue().countTrailingZeros() < EltSize)
248         return false;
249     } else if (ConstantFPSDNode *CFPN = dyn_cast<ConstantFPSDNode>(Op)) {
250       if (CFPN->getValueAPF().bitcastToAPInt().countTrailingZeros() < EltSize)
251         return false;
252     } else
253       return false;
254   }
255 
256   // Do not accept an all-undef vector.
257   if (IsAllUndef)
258     return false;
259   return true;
260 }
261 
262 bool ISD::isBuildVectorAllOnes(const SDNode *N) {
263   return isConstantSplatVectorAllOnes(N, /*BuildVectorOnly*/ true);
264 }
265 
266 bool ISD::isBuildVectorAllZeros(const SDNode *N) {
267   return isConstantSplatVectorAllZeros(N, /*BuildVectorOnly*/ true);
268 }
269 
270 bool ISD::isBuildVectorOfConstantSDNodes(const SDNode *N) {
271   if (N->getOpcode() != ISD::BUILD_VECTOR)
272     return false;
273 
274   for (const SDValue &Op : N->op_values()) {
275     if (Op.isUndef())
276       continue;
277     if (!isa<ConstantSDNode>(Op))
278       return false;
279   }
280   return true;
281 }
282 
283 bool ISD::isBuildVectorOfConstantFPSDNodes(const SDNode *N) {
284   if (N->getOpcode() != ISD::BUILD_VECTOR)
285     return false;
286 
287   for (const SDValue &Op : N->op_values()) {
288     if (Op.isUndef())
289       continue;
290     if (!isa<ConstantFPSDNode>(Op))
291       return false;
292   }
293   return true;
294 }
295 
296 bool ISD::allOperandsUndef(const SDNode *N) {
297   // Return false if the node has no operands.
298   // This is "logically inconsistent" with the definition of "all" but
299   // is probably the desired behavior.
300   if (N->getNumOperands() == 0)
301     return false;
302   return all_of(N->op_values(), [](SDValue Op) { return Op.isUndef(); });
303 }
304 
305 bool ISD::matchUnaryPredicate(SDValue Op,
306                               std::function<bool(ConstantSDNode *)> Match,
307                               bool AllowUndefs) {
308   // FIXME: Add support for scalar UNDEF cases?
309   if (auto *Cst = dyn_cast<ConstantSDNode>(Op))
310     return Match(Cst);
311 
312   // FIXME: Add support for vector UNDEF cases?
313   if (ISD::BUILD_VECTOR != Op.getOpcode() &&
314       ISD::SPLAT_VECTOR != Op.getOpcode())
315     return false;
316 
317   EVT SVT = Op.getValueType().getScalarType();
318   for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
319     if (AllowUndefs && Op.getOperand(i).isUndef()) {
320       if (!Match(nullptr))
321         return false;
322       continue;
323     }
324 
325     auto *Cst = dyn_cast<ConstantSDNode>(Op.getOperand(i));
326     if (!Cst || Cst->getValueType(0) != SVT || !Match(Cst))
327       return false;
328   }
329   return true;
330 }
331 
332 bool ISD::matchBinaryPredicate(
333     SDValue LHS, SDValue RHS,
334     std::function<bool(ConstantSDNode *, ConstantSDNode *)> Match,
335     bool AllowUndefs, bool AllowTypeMismatch) {
336   if (!AllowTypeMismatch && LHS.getValueType() != RHS.getValueType())
337     return false;
338 
339   // TODO: Add support for scalar UNDEF cases?
340   if (auto *LHSCst = dyn_cast<ConstantSDNode>(LHS))
341     if (auto *RHSCst = dyn_cast<ConstantSDNode>(RHS))
342       return Match(LHSCst, RHSCst);
343 
344   // TODO: Add support for vector UNDEF cases?
345   if (ISD::BUILD_VECTOR != LHS.getOpcode() ||
346       ISD::BUILD_VECTOR != RHS.getOpcode())
347     return false;
348 
349   EVT SVT = LHS.getValueType().getScalarType();
350   for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
351     SDValue LHSOp = LHS.getOperand(i);
352     SDValue RHSOp = RHS.getOperand(i);
353     bool LHSUndef = AllowUndefs && LHSOp.isUndef();
354     bool RHSUndef = AllowUndefs && RHSOp.isUndef();
355     auto *LHSCst = dyn_cast<ConstantSDNode>(LHSOp);
356     auto *RHSCst = dyn_cast<ConstantSDNode>(RHSOp);
357     if ((!LHSCst && !LHSUndef) || (!RHSCst && !RHSUndef))
358       return false;
359     if (!AllowTypeMismatch && (LHSOp.getValueType() != SVT ||
360                                LHSOp.getValueType() != RHSOp.getValueType()))
361       return false;
362     if (!Match(LHSCst, RHSCst))
363       return false;
364   }
365   return true;
366 }
367 
368 ISD::NodeType ISD::getVecReduceBaseOpcode(unsigned VecReduceOpcode) {
369   switch (VecReduceOpcode) {
370   default:
371     llvm_unreachable("Expected VECREDUCE opcode");
372   case ISD::VECREDUCE_FADD:
373   case ISD::VECREDUCE_SEQ_FADD:
374     return ISD::FADD;
375   case ISD::VECREDUCE_FMUL:
376   case ISD::VECREDUCE_SEQ_FMUL:
377     return ISD::FMUL;
378   case ISD::VECREDUCE_ADD:
379     return ISD::ADD;
380   case ISD::VECREDUCE_MUL:
381     return ISD::MUL;
382   case ISD::VECREDUCE_AND:
383     return ISD::AND;
384   case ISD::VECREDUCE_OR:
385     return ISD::OR;
386   case ISD::VECREDUCE_XOR:
387     return ISD::XOR;
388   case ISD::VECREDUCE_SMAX:
389     return ISD::SMAX;
390   case ISD::VECREDUCE_SMIN:
391     return ISD::SMIN;
392   case ISD::VECREDUCE_UMAX:
393     return ISD::UMAX;
394   case ISD::VECREDUCE_UMIN:
395     return ISD::UMIN;
396   case ISD::VECREDUCE_FMAX:
397     return ISD::FMAXNUM;
398   case ISD::VECREDUCE_FMIN:
399     return ISD::FMINNUM;
400   }
401 }
402 
403 bool ISD::isVPOpcode(unsigned Opcode) {
404   switch (Opcode) {
405   default:
406     return false;
407 #define BEGIN_REGISTER_VP_SDNODE(SDOPC, ...)                                   \
408   case ISD::SDOPC:                                                             \
409     return true;
410 #include "llvm/IR/VPIntrinsics.def"
411   }
412 }
413 
414 /// The operand position of the vector mask.
415 Optional<unsigned> ISD::getVPMaskIdx(unsigned Opcode) {
416   switch (Opcode) {
417   default:
418     return None;
419 #define BEGIN_REGISTER_VP_SDNODE(SDOPC, LEGALPOS, TDNAME, MASKPOS, ...)        \
420   case ISD::SDOPC:                                                             \
421     return MASKPOS;
422 #include "llvm/IR/VPIntrinsics.def"
423   }
424 }
425 
426 /// The operand position of the explicit vector length parameter.
427 Optional<unsigned> ISD::getVPExplicitVectorLengthIdx(unsigned Opcode) {
428   switch (Opcode) {
429   default:
430     return None;
431 #define BEGIN_REGISTER_VP_SDNODE(SDOPC, LEGALPOS, TDNAME, MASKPOS, EVLPOS)     \
432   case ISD::SDOPC:                                                             \
433     return EVLPOS;
434 #include "llvm/IR/VPIntrinsics.def"
435   }
436 }
437 
438 ISD::NodeType ISD::getExtForLoadExtType(bool IsFP, ISD::LoadExtType ExtType) {
439   switch (ExtType) {
440   case ISD::EXTLOAD:
441     return IsFP ? ISD::FP_EXTEND : ISD::ANY_EXTEND;
442   case ISD::SEXTLOAD:
443     return ISD::SIGN_EXTEND;
444   case ISD::ZEXTLOAD:
445     return ISD::ZERO_EXTEND;
446   default:
447     break;
448   }
449 
450   llvm_unreachable("Invalid LoadExtType");
451 }
452 
453 ISD::CondCode ISD::getSetCCSwappedOperands(ISD::CondCode Operation) {
454   // To perform this operation, we just need to swap the L and G bits of the
455   // operation.
456   unsigned OldL = (Operation >> 2) & 1;
457   unsigned OldG = (Operation >> 1) & 1;
458   return ISD::CondCode((Operation & ~6) |  // Keep the N, U, E bits
459                        (OldL << 1) |       // New G bit
460                        (OldG << 2));       // New L bit.
461 }
462 
463 static ISD::CondCode getSetCCInverseImpl(ISD::CondCode Op, bool isIntegerLike) {
464   unsigned Operation = Op;
465   if (isIntegerLike)
466     Operation ^= 7;   // Flip L, G, E bits, but not U.
467   else
468     Operation ^= 15;  // Flip all of the condition bits.
469 
470   if (Operation > ISD::SETTRUE2)
471     Operation &= ~8;  // Don't let N and U bits get set.
472 
473   return ISD::CondCode(Operation);
474 }
475 
476 ISD::CondCode ISD::getSetCCInverse(ISD::CondCode Op, EVT Type) {
477   return getSetCCInverseImpl(Op, Type.isInteger());
478 }
479 
480 ISD::CondCode ISD::GlobalISel::getSetCCInverse(ISD::CondCode Op,
481                                                bool isIntegerLike) {
482   return getSetCCInverseImpl(Op, isIntegerLike);
483 }
484 
485 /// For an integer comparison, return 1 if the comparison is a signed operation
486 /// and 2 if the result is an unsigned comparison. Return zero if the operation
487 /// does not depend on the sign of the input (setne and seteq).
488 static int isSignedOp(ISD::CondCode Opcode) {
489   switch (Opcode) {
490   default: llvm_unreachable("Illegal integer setcc operation!");
491   case ISD::SETEQ:
492   case ISD::SETNE: return 0;
493   case ISD::SETLT:
494   case ISD::SETLE:
495   case ISD::SETGT:
496   case ISD::SETGE: return 1;
497   case ISD::SETULT:
498   case ISD::SETULE:
499   case ISD::SETUGT:
500   case ISD::SETUGE: return 2;
501   }
502 }
503 
504 ISD::CondCode ISD::getSetCCOrOperation(ISD::CondCode Op1, ISD::CondCode Op2,
505                                        EVT Type) {
506   bool IsInteger = Type.isInteger();
507   if (IsInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
508     // Cannot fold a signed integer setcc with an unsigned integer setcc.
509     return ISD::SETCC_INVALID;
510 
511   unsigned Op = Op1 | Op2;  // Combine all of the condition bits.
512 
513   // If the N and U bits get set, then the resultant comparison DOES suddenly
514   // care about orderedness, and it is true when ordered.
515   if (Op > ISD::SETTRUE2)
516     Op &= ~16;     // Clear the U bit if the N bit is set.
517 
518   // Canonicalize illegal integer setcc's.
519   if (IsInteger && Op == ISD::SETUNE)  // e.g. SETUGT | SETULT
520     Op = ISD::SETNE;
521 
522   return ISD::CondCode(Op);
523 }
524 
525 ISD::CondCode ISD::getSetCCAndOperation(ISD::CondCode Op1, ISD::CondCode Op2,
526                                         EVT Type) {
527   bool IsInteger = Type.isInteger();
528   if (IsInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
529     // Cannot fold a signed setcc with an unsigned setcc.
530     return ISD::SETCC_INVALID;
531 
532   // Combine all of the condition bits.
533   ISD::CondCode Result = ISD::CondCode(Op1 & Op2);
534 
535   // Canonicalize illegal integer setcc's.
536   if (IsInteger) {
537     switch (Result) {
538     default: break;
539     case ISD::SETUO : Result = ISD::SETFALSE; break;  // SETUGT & SETULT
540     case ISD::SETOEQ:                                 // SETEQ  & SETU[LG]E
541     case ISD::SETUEQ: Result = ISD::SETEQ   ; break;  // SETUGE & SETULE
542     case ISD::SETOLT: Result = ISD::SETULT  ; break;  // SETULT & SETNE
543     case ISD::SETOGT: Result = ISD::SETUGT  ; break;  // SETUGT & SETNE
544     }
545   }
546 
547   return Result;
548 }
549 
550 //===----------------------------------------------------------------------===//
551 //                           SDNode Profile Support
552 //===----------------------------------------------------------------------===//
553 
554 /// AddNodeIDOpcode - Add the node opcode to the NodeID data.
555 static void AddNodeIDOpcode(FoldingSetNodeID &ID, unsigned OpC)  {
556   ID.AddInteger(OpC);
557 }
558 
559 /// AddNodeIDValueTypes - Value type lists are intern'd so we can represent them
560 /// solely with their pointer.
561 static void AddNodeIDValueTypes(FoldingSetNodeID &ID, SDVTList VTList) {
562   ID.AddPointer(VTList.VTs);
563 }
564 
565 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data.
566 static void AddNodeIDOperands(FoldingSetNodeID &ID,
567                               ArrayRef<SDValue> Ops) {
568   for (auto& Op : Ops) {
569     ID.AddPointer(Op.getNode());
570     ID.AddInteger(Op.getResNo());
571   }
572 }
573 
574 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data.
575 static void AddNodeIDOperands(FoldingSetNodeID &ID,
576                               ArrayRef<SDUse> Ops) {
577   for (auto& Op : Ops) {
578     ID.AddPointer(Op.getNode());
579     ID.AddInteger(Op.getResNo());
580   }
581 }
582 
583 static void AddNodeIDNode(FoldingSetNodeID &ID, unsigned short OpC,
584                           SDVTList VTList, ArrayRef<SDValue> OpList) {
585   AddNodeIDOpcode(ID, OpC);
586   AddNodeIDValueTypes(ID, VTList);
587   AddNodeIDOperands(ID, OpList);
588 }
589 
590 /// If this is an SDNode with special info, add this info to the NodeID data.
591 static void AddNodeIDCustom(FoldingSetNodeID &ID, const SDNode *N) {
592   switch (N->getOpcode()) {
593   case ISD::TargetExternalSymbol:
594   case ISD::ExternalSymbol:
595   case ISD::MCSymbol:
596     llvm_unreachable("Should only be used on nodes with operands");
597   default: break;  // Normal nodes don't need extra info.
598   case ISD::TargetConstant:
599   case ISD::Constant: {
600     const ConstantSDNode *C = cast<ConstantSDNode>(N);
601     ID.AddPointer(C->getConstantIntValue());
602     ID.AddBoolean(C->isOpaque());
603     break;
604   }
605   case ISD::TargetConstantFP:
606   case ISD::ConstantFP:
607     ID.AddPointer(cast<ConstantFPSDNode>(N)->getConstantFPValue());
608     break;
609   case ISD::TargetGlobalAddress:
610   case ISD::GlobalAddress:
611   case ISD::TargetGlobalTLSAddress:
612   case ISD::GlobalTLSAddress: {
613     const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(N);
614     ID.AddPointer(GA->getGlobal());
615     ID.AddInteger(GA->getOffset());
616     ID.AddInteger(GA->getTargetFlags());
617     break;
618   }
619   case ISD::BasicBlock:
620     ID.AddPointer(cast<BasicBlockSDNode>(N)->getBasicBlock());
621     break;
622   case ISD::Register:
623     ID.AddInteger(cast<RegisterSDNode>(N)->getReg());
624     break;
625   case ISD::RegisterMask:
626     ID.AddPointer(cast<RegisterMaskSDNode>(N)->getRegMask());
627     break;
628   case ISD::SRCVALUE:
629     ID.AddPointer(cast<SrcValueSDNode>(N)->getValue());
630     break;
631   case ISD::FrameIndex:
632   case ISD::TargetFrameIndex:
633     ID.AddInteger(cast<FrameIndexSDNode>(N)->getIndex());
634     break;
635   case ISD::LIFETIME_START:
636   case ISD::LIFETIME_END:
637     if (cast<LifetimeSDNode>(N)->hasOffset()) {
638       ID.AddInteger(cast<LifetimeSDNode>(N)->getSize());
639       ID.AddInteger(cast<LifetimeSDNode>(N)->getOffset());
640     }
641     break;
642   case ISD::PSEUDO_PROBE:
643     ID.AddInteger(cast<PseudoProbeSDNode>(N)->getGuid());
644     ID.AddInteger(cast<PseudoProbeSDNode>(N)->getIndex());
645     ID.AddInteger(cast<PseudoProbeSDNode>(N)->getAttributes());
646     break;
647   case ISD::JumpTable:
648   case ISD::TargetJumpTable:
649     ID.AddInteger(cast<JumpTableSDNode>(N)->getIndex());
650     ID.AddInteger(cast<JumpTableSDNode>(N)->getTargetFlags());
651     break;
652   case ISD::ConstantPool:
653   case ISD::TargetConstantPool: {
654     const ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(N);
655     ID.AddInteger(CP->getAlign().value());
656     ID.AddInteger(CP->getOffset());
657     if (CP->isMachineConstantPoolEntry())
658       CP->getMachineCPVal()->addSelectionDAGCSEId(ID);
659     else
660       ID.AddPointer(CP->getConstVal());
661     ID.AddInteger(CP->getTargetFlags());
662     break;
663   }
664   case ISD::TargetIndex: {
665     const TargetIndexSDNode *TI = cast<TargetIndexSDNode>(N);
666     ID.AddInteger(TI->getIndex());
667     ID.AddInteger(TI->getOffset());
668     ID.AddInteger(TI->getTargetFlags());
669     break;
670   }
671   case ISD::LOAD: {
672     const LoadSDNode *LD = cast<LoadSDNode>(N);
673     ID.AddInteger(LD->getMemoryVT().getRawBits());
674     ID.AddInteger(LD->getRawSubclassData());
675     ID.AddInteger(LD->getPointerInfo().getAddrSpace());
676     break;
677   }
678   case ISD::STORE: {
679     const StoreSDNode *ST = cast<StoreSDNode>(N);
680     ID.AddInteger(ST->getMemoryVT().getRawBits());
681     ID.AddInteger(ST->getRawSubclassData());
682     ID.AddInteger(ST->getPointerInfo().getAddrSpace());
683     break;
684   }
685   case ISD::MLOAD: {
686     const MaskedLoadSDNode *MLD = cast<MaskedLoadSDNode>(N);
687     ID.AddInteger(MLD->getMemoryVT().getRawBits());
688     ID.AddInteger(MLD->getRawSubclassData());
689     ID.AddInteger(MLD->getPointerInfo().getAddrSpace());
690     break;
691   }
692   case ISD::MSTORE: {
693     const MaskedStoreSDNode *MST = cast<MaskedStoreSDNode>(N);
694     ID.AddInteger(MST->getMemoryVT().getRawBits());
695     ID.AddInteger(MST->getRawSubclassData());
696     ID.AddInteger(MST->getPointerInfo().getAddrSpace());
697     break;
698   }
699   case ISD::MGATHER: {
700     const MaskedGatherSDNode *MG = cast<MaskedGatherSDNode>(N);
701     ID.AddInteger(MG->getMemoryVT().getRawBits());
702     ID.AddInteger(MG->getRawSubclassData());
703     ID.AddInteger(MG->getPointerInfo().getAddrSpace());
704     break;
705   }
706   case ISD::MSCATTER: {
707     const MaskedScatterSDNode *MS = cast<MaskedScatterSDNode>(N);
708     ID.AddInteger(MS->getMemoryVT().getRawBits());
709     ID.AddInteger(MS->getRawSubclassData());
710     ID.AddInteger(MS->getPointerInfo().getAddrSpace());
711     break;
712   }
713   case ISD::ATOMIC_CMP_SWAP:
714   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
715   case ISD::ATOMIC_SWAP:
716   case ISD::ATOMIC_LOAD_ADD:
717   case ISD::ATOMIC_LOAD_SUB:
718   case ISD::ATOMIC_LOAD_AND:
719   case ISD::ATOMIC_LOAD_CLR:
720   case ISD::ATOMIC_LOAD_OR:
721   case ISD::ATOMIC_LOAD_XOR:
722   case ISD::ATOMIC_LOAD_NAND:
723   case ISD::ATOMIC_LOAD_MIN:
724   case ISD::ATOMIC_LOAD_MAX:
725   case ISD::ATOMIC_LOAD_UMIN:
726   case ISD::ATOMIC_LOAD_UMAX:
727   case ISD::ATOMIC_LOAD:
728   case ISD::ATOMIC_STORE: {
729     const AtomicSDNode *AT = cast<AtomicSDNode>(N);
730     ID.AddInteger(AT->getMemoryVT().getRawBits());
731     ID.AddInteger(AT->getRawSubclassData());
732     ID.AddInteger(AT->getPointerInfo().getAddrSpace());
733     break;
734   }
735   case ISD::PREFETCH: {
736     const MemSDNode *PF = cast<MemSDNode>(N);
737     ID.AddInteger(PF->getPointerInfo().getAddrSpace());
738     break;
739   }
740   case ISD::VECTOR_SHUFFLE: {
741     const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
742     for (unsigned i = 0, e = N->getValueType(0).getVectorNumElements();
743          i != e; ++i)
744       ID.AddInteger(SVN->getMaskElt(i));
745     break;
746   }
747   case ISD::TargetBlockAddress:
748   case ISD::BlockAddress: {
749     const BlockAddressSDNode *BA = cast<BlockAddressSDNode>(N);
750     ID.AddPointer(BA->getBlockAddress());
751     ID.AddInteger(BA->getOffset());
752     ID.AddInteger(BA->getTargetFlags());
753     break;
754   }
755   } // end switch (N->getOpcode())
756 
757   // Target specific memory nodes could also have address spaces to check.
758   if (N->isTargetMemoryOpcode())
759     ID.AddInteger(cast<MemSDNode>(N)->getPointerInfo().getAddrSpace());
760 }
761 
762 /// AddNodeIDNode - Generic routine for adding a nodes info to the NodeID
763 /// data.
764 static void AddNodeIDNode(FoldingSetNodeID &ID, const SDNode *N) {
765   AddNodeIDOpcode(ID, N->getOpcode());
766   // Add the return value info.
767   AddNodeIDValueTypes(ID, N->getVTList());
768   // Add the operand info.
769   AddNodeIDOperands(ID, N->ops());
770 
771   // Handle SDNode leafs with special info.
772   AddNodeIDCustom(ID, N);
773 }
774 
775 //===----------------------------------------------------------------------===//
776 //                              SelectionDAG Class
777 //===----------------------------------------------------------------------===//
778 
779 /// doNotCSE - Return true if CSE should not be performed for this node.
780 static bool doNotCSE(SDNode *N) {
781   if (N->getValueType(0) == MVT::Glue)
782     return true; // Never CSE anything that produces a flag.
783 
784   switch (N->getOpcode()) {
785   default: break;
786   case ISD::HANDLENODE:
787   case ISD::EH_LABEL:
788     return true;   // Never CSE these nodes.
789   }
790 
791   // Check that remaining values produced are not flags.
792   for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
793     if (N->getValueType(i) == MVT::Glue)
794       return true; // Never CSE anything that produces a flag.
795 
796   return false;
797 }
798 
799 /// RemoveDeadNodes - This method deletes all unreachable nodes in the
800 /// SelectionDAG.
801 void SelectionDAG::RemoveDeadNodes() {
802   // Create a dummy node (which is not added to allnodes), that adds a reference
803   // to the root node, preventing it from being deleted.
804   HandleSDNode Dummy(getRoot());
805 
806   SmallVector<SDNode*, 128> DeadNodes;
807 
808   // Add all obviously-dead nodes to the DeadNodes worklist.
809   for (SDNode &Node : allnodes())
810     if (Node.use_empty())
811       DeadNodes.push_back(&Node);
812 
813   RemoveDeadNodes(DeadNodes);
814 
815   // If the root changed (e.g. it was a dead load, update the root).
816   setRoot(Dummy.getValue());
817 }
818 
819 /// RemoveDeadNodes - This method deletes the unreachable nodes in the
820 /// given list, and any nodes that become unreachable as a result.
821 void SelectionDAG::RemoveDeadNodes(SmallVectorImpl<SDNode *> &DeadNodes) {
822 
823   // Process the worklist, deleting the nodes and adding their uses to the
824   // worklist.
825   while (!DeadNodes.empty()) {
826     SDNode *N = DeadNodes.pop_back_val();
827     // Skip to next node if we've already managed to delete the node. This could
828     // happen if replacing a node causes a node previously added to the node to
829     // be deleted.
830     if (N->getOpcode() == ISD::DELETED_NODE)
831       continue;
832 
833     for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
834       DUL->NodeDeleted(N, nullptr);
835 
836     // Take the node out of the appropriate CSE map.
837     RemoveNodeFromCSEMaps(N);
838 
839     // Next, brutally remove the operand list.  This is safe to do, as there are
840     // no cycles in the graph.
841     for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) {
842       SDUse &Use = *I++;
843       SDNode *Operand = Use.getNode();
844       Use.set(SDValue());
845 
846       // Now that we removed this operand, see if there are no uses of it left.
847       if (Operand->use_empty())
848         DeadNodes.push_back(Operand);
849     }
850 
851     DeallocateNode(N);
852   }
853 }
854 
855 void SelectionDAG::RemoveDeadNode(SDNode *N){
856   SmallVector<SDNode*, 16> DeadNodes(1, N);
857 
858   // Create a dummy node that adds a reference to the root node, preventing
859   // it from being deleted.  (This matters if the root is an operand of the
860   // dead node.)
861   HandleSDNode Dummy(getRoot());
862 
863   RemoveDeadNodes(DeadNodes);
864 }
865 
866 void SelectionDAG::DeleteNode(SDNode *N) {
867   // First take this out of the appropriate CSE map.
868   RemoveNodeFromCSEMaps(N);
869 
870   // Finally, remove uses due to operands of this node, remove from the
871   // AllNodes list, and delete the node.
872   DeleteNodeNotInCSEMaps(N);
873 }
874 
875 void SelectionDAG::DeleteNodeNotInCSEMaps(SDNode *N) {
876   assert(N->getIterator() != AllNodes.begin() &&
877          "Cannot delete the entry node!");
878   assert(N->use_empty() && "Cannot delete a node that is not dead!");
879 
880   // Drop all of the operands and decrement used node's use counts.
881   N->DropOperands();
882 
883   DeallocateNode(N);
884 }
885 
886 void SDDbgInfo::add(SDDbgValue *V, bool isParameter) {
887   assert(!(V->isVariadic() && isParameter));
888   if (isParameter)
889     ByvalParmDbgValues.push_back(V);
890   else
891     DbgValues.push_back(V);
892   for (const SDNode *Node : V->getSDNodes())
893     if (Node)
894       DbgValMap[Node].push_back(V);
895 }
896 
897 void SDDbgInfo::erase(const SDNode *Node) {
898   DbgValMapType::iterator I = DbgValMap.find(Node);
899   if (I == DbgValMap.end())
900     return;
901   for (auto &Val: I->second)
902     Val->setIsInvalidated();
903   DbgValMap.erase(I);
904 }
905 
906 void SelectionDAG::DeallocateNode(SDNode *N) {
907   // If we have operands, deallocate them.
908   removeOperands(N);
909 
910   NodeAllocator.Deallocate(AllNodes.remove(N));
911 
912   // Set the opcode to DELETED_NODE to help catch bugs when node
913   // memory is reallocated.
914   // FIXME: There are places in SDag that have grown a dependency on the opcode
915   // value in the released node.
916   __asan_unpoison_memory_region(&N->NodeType, sizeof(N->NodeType));
917   N->NodeType = ISD::DELETED_NODE;
918 
919   // If any of the SDDbgValue nodes refer to this SDNode, invalidate
920   // them and forget about that node.
921   DbgInfo->erase(N);
922 }
923 
924 #ifndef NDEBUG
925 /// VerifySDNode - Sanity check the given SDNode.  Aborts if it is invalid.
926 static void VerifySDNode(SDNode *N) {
927   switch (N->getOpcode()) {
928   default:
929     break;
930   case ISD::BUILD_PAIR: {
931     EVT VT = N->getValueType(0);
932     assert(N->getNumValues() == 1 && "Too many results!");
933     assert(!VT.isVector() && (VT.isInteger() || VT.isFloatingPoint()) &&
934            "Wrong return type!");
935     assert(N->getNumOperands() == 2 && "Wrong number of operands!");
936     assert(N->getOperand(0).getValueType() == N->getOperand(1).getValueType() &&
937            "Mismatched operand types!");
938     assert(N->getOperand(0).getValueType().isInteger() == VT.isInteger() &&
939            "Wrong operand type!");
940     assert(VT.getSizeInBits() == 2 * N->getOperand(0).getValueSizeInBits() &&
941            "Wrong return type size");
942     break;
943   }
944   case ISD::BUILD_VECTOR: {
945     assert(N->getNumValues() == 1 && "Too many results!");
946     assert(N->getValueType(0).isVector() && "Wrong return type!");
947     assert(N->getNumOperands() == N->getValueType(0).getVectorNumElements() &&
948            "Wrong number of operands!");
949     EVT EltVT = N->getValueType(0).getVectorElementType();
950     for (const SDUse &Op : N->ops()) {
951       assert((Op.getValueType() == EltVT ||
952               (EltVT.isInteger() && Op.getValueType().isInteger() &&
953                EltVT.bitsLE(Op.getValueType()))) &&
954              "Wrong operand type!");
955       assert(Op.getValueType() == N->getOperand(0).getValueType() &&
956              "Operands must all have the same type");
957     }
958     break;
959   }
960   }
961 }
962 #endif // NDEBUG
963 
964 /// Insert a newly allocated node into the DAG.
965 ///
966 /// Handles insertion into the all nodes list and CSE map, as well as
967 /// verification and other common operations when a new node is allocated.
968 void SelectionDAG::InsertNode(SDNode *N) {
969   AllNodes.push_back(N);
970 #ifndef NDEBUG
971   N->PersistentId = NextPersistentId++;
972   VerifySDNode(N);
973 #endif
974   for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
975     DUL->NodeInserted(N);
976 }
977 
978 /// RemoveNodeFromCSEMaps - Take the specified node out of the CSE map that
979 /// correspond to it.  This is useful when we're about to delete or repurpose
980 /// the node.  We don't want future request for structurally identical nodes
981 /// to return N anymore.
982 bool SelectionDAG::RemoveNodeFromCSEMaps(SDNode *N) {
983   bool Erased = false;
984   switch (N->getOpcode()) {
985   case ISD::HANDLENODE: return false;  // noop.
986   case ISD::CONDCODE:
987     assert(CondCodeNodes[cast<CondCodeSDNode>(N)->get()] &&
988            "Cond code doesn't exist!");
989     Erased = CondCodeNodes[cast<CondCodeSDNode>(N)->get()] != nullptr;
990     CondCodeNodes[cast<CondCodeSDNode>(N)->get()] = nullptr;
991     break;
992   case ISD::ExternalSymbol:
993     Erased = ExternalSymbols.erase(cast<ExternalSymbolSDNode>(N)->getSymbol());
994     break;
995   case ISD::TargetExternalSymbol: {
996     ExternalSymbolSDNode *ESN = cast<ExternalSymbolSDNode>(N);
997     Erased = TargetExternalSymbols.erase(std::pair<std::string, unsigned>(
998         ESN->getSymbol(), ESN->getTargetFlags()));
999     break;
1000   }
1001   case ISD::MCSymbol: {
1002     auto *MCSN = cast<MCSymbolSDNode>(N);
1003     Erased = MCSymbols.erase(MCSN->getMCSymbol());
1004     break;
1005   }
1006   case ISD::VALUETYPE: {
1007     EVT VT = cast<VTSDNode>(N)->getVT();
1008     if (VT.isExtended()) {
1009       Erased = ExtendedValueTypeNodes.erase(VT);
1010     } else {
1011       Erased = ValueTypeNodes[VT.getSimpleVT().SimpleTy] != nullptr;
1012       ValueTypeNodes[VT.getSimpleVT().SimpleTy] = nullptr;
1013     }
1014     break;
1015   }
1016   default:
1017     // Remove it from the CSE Map.
1018     assert(N->getOpcode() != ISD::DELETED_NODE && "DELETED_NODE in CSEMap!");
1019     assert(N->getOpcode() != ISD::EntryToken && "EntryToken in CSEMap!");
1020     Erased = CSEMap.RemoveNode(N);
1021     break;
1022   }
1023 #ifndef NDEBUG
1024   // Verify that the node was actually in one of the CSE maps, unless it has a
1025   // flag result (which cannot be CSE'd) or is one of the special cases that are
1026   // not subject to CSE.
1027   if (!Erased && N->getValueType(N->getNumValues()-1) != MVT::Glue &&
1028       !N->isMachineOpcode() && !doNotCSE(N)) {
1029     N->dump(this);
1030     dbgs() << "\n";
1031     llvm_unreachable("Node is not in map!");
1032   }
1033 #endif
1034   return Erased;
1035 }
1036 
1037 /// AddModifiedNodeToCSEMaps - The specified node has been removed from the CSE
1038 /// maps and modified in place. Add it back to the CSE maps, unless an identical
1039 /// node already exists, in which case transfer all its users to the existing
1040 /// node. This transfer can potentially trigger recursive merging.
1041 void
1042 SelectionDAG::AddModifiedNodeToCSEMaps(SDNode *N) {
1043   // For node types that aren't CSE'd, just act as if no identical node
1044   // already exists.
1045   if (!doNotCSE(N)) {
1046     SDNode *Existing = CSEMap.GetOrInsertNode(N);
1047     if (Existing != N) {
1048       // If there was already an existing matching node, use ReplaceAllUsesWith
1049       // to replace the dead one with the existing one.  This can cause
1050       // recursive merging of other unrelated nodes down the line.
1051       ReplaceAllUsesWith(N, Existing);
1052 
1053       // N is now dead. Inform the listeners and delete it.
1054       for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
1055         DUL->NodeDeleted(N, Existing);
1056       DeleteNodeNotInCSEMaps(N);
1057       return;
1058     }
1059   }
1060 
1061   // If the node doesn't already exist, we updated it.  Inform listeners.
1062   for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
1063     DUL->NodeUpdated(N);
1064 }
1065 
1066 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
1067 /// were replaced with those specified.  If this node is never memoized,
1068 /// return null, otherwise return a pointer to the slot it would take.  If a
1069 /// node already exists with these operands, the slot will be non-null.
1070 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, SDValue Op,
1071                                            void *&InsertPos) {
1072   if (doNotCSE(N))
1073     return nullptr;
1074 
1075   SDValue Ops[] = { Op };
1076   FoldingSetNodeID ID;
1077   AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops);
1078   AddNodeIDCustom(ID, N);
1079   SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos);
1080   if (Node)
1081     Node->intersectFlagsWith(N->getFlags());
1082   return Node;
1083 }
1084 
1085 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
1086 /// were replaced with those specified.  If this node is never memoized,
1087 /// return null, otherwise return a pointer to the slot it would take.  If a
1088 /// node already exists with these operands, the slot will be non-null.
1089 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N,
1090                                            SDValue Op1, SDValue Op2,
1091                                            void *&InsertPos) {
1092   if (doNotCSE(N))
1093     return nullptr;
1094 
1095   SDValue Ops[] = { Op1, Op2 };
1096   FoldingSetNodeID ID;
1097   AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops);
1098   AddNodeIDCustom(ID, N);
1099   SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos);
1100   if (Node)
1101     Node->intersectFlagsWith(N->getFlags());
1102   return Node;
1103 }
1104 
1105 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
1106 /// were replaced with those specified.  If this node is never memoized,
1107 /// return null, otherwise return a pointer to the slot it would take.  If a
1108 /// node already exists with these operands, the slot will be non-null.
1109 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, ArrayRef<SDValue> Ops,
1110                                            void *&InsertPos) {
1111   if (doNotCSE(N))
1112     return nullptr;
1113 
1114   FoldingSetNodeID ID;
1115   AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops);
1116   AddNodeIDCustom(ID, N);
1117   SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos);
1118   if (Node)
1119     Node->intersectFlagsWith(N->getFlags());
1120   return Node;
1121 }
1122 
1123 Align SelectionDAG::getEVTAlign(EVT VT) const {
1124   Type *Ty = VT == MVT::iPTR ?
1125                    PointerType::get(Type::getInt8Ty(*getContext()), 0) :
1126                    VT.getTypeForEVT(*getContext());
1127 
1128   return getDataLayout().getABITypeAlign(Ty);
1129 }
1130 
1131 // EntryNode could meaningfully have debug info if we can find it...
1132 SelectionDAG::SelectionDAG(const TargetMachine &tm, CodeGenOpt::Level OL)
1133     : TM(tm), OptLevel(OL),
1134       EntryNode(ISD::EntryToken, 0, DebugLoc(), getVTList(MVT::Other)),
1135       Root(getEntryNode()) {
1136   InsertNode(&EntryNode);
1137   DbgInfo = new SDDbgInfo();
1138 }
1139 
1140 void SelectionDAG::init(MachineFunction &NewMF,
1141                         OptimizationRemarkEmitter &NewORE,
1142                         Pass *PassPtr, const TargetLibraryInfo *LibraryInfo,
1143                         LegacyDivergenceAnalysis * Divergence,
1144                         ProfileSummaryInfo *PSIin,
1145                         BlockFrequencyInfo *BFIin) {
1146   MF = &NewMF;
1147   SDAGISelPass = PassPtr;
1148   ORE = &NewORE;
1149   TLI = getSubtarget().getTargetLowering();
1150   TSI = getSubtarget().getSelectionDAGInfo();
1151   LibInfo = LibraryInfo;
1152   Context = &MF->getFunction().getContext();
1153   DA = Divergence;
1154   PSI = PSIin;
1155   BFI = BFIin;
1156 }
1157 
1158 SelectionDAG::~SelectionDAG() {
1159   assert(!UpdateListeners && "Dangling registered DAGUpdateListeners");
1160   allnodes_clear();
1161   OperandRecycler.clear(OperandAllocator);
1162   delete DbgInfo;
1163 }
1164 
1165 bool SelectionDAG::shouldOptForSize() const {
1166   return MF->getFunction().hasOptSize() ||
1167       llvm::shouldOptimizeForSize(FLI->MBB->getBasicBlock(), PSI, BFI);
1168 }
1169 
1170 void SelectionDAG::allnodes_clear() {
1171   assert(&*AllNodes.begin() == &EntryNode);
1172   AllNodes.remove(AllNodes.begin());
1173   while (!AllNodes.empty())
1174     DeallocateNode(&AllNodes.front());
1175 #ifndef NDEBUG
1176   NextPersistentId = 0;
1177 #endif
1178 }
1179 
1180 SDNode *SelectionDAG::FindNodeOrInsertPos(const FoldingSetNodeID &ID,
1181                                           void *&InsertPos) {
1182   SDNode *N = CSEMap.FindNodeOrInsertPos(ID, InsertPos);
1183   if (N) {
1184     switch (N->getOpcode()) {
1185     default: break;
1186     case ISD::Constant:
1187     case ISD::ConstantFP:
1188       llvm_unreachable("Querying for Constant and ConstantFP nodes requires "
1189                        "debug location.  Use another overload.");
1190     }
1191   }
1192   return N;
1193 }
1194 
1195 SDNode *SelectionDAG::FindNodeOrInsertPos(const FoldingSetNodeID &ID,
1196                                           const SDLoc &DL, void *&InsertPos) {
1197   SDNode *N = CSEMap.FindNodeOrInsertPos(ID, InsertPos);
1198   if (N) {
1199     switch (N->getOpcode()) {
1200     case ISD::Constant:
1201     case ISD::ConstantFP:
1202       // Erase debug location from the node if the node is used at several
1203       // different places. Do not propagate one location to all uses as it
1204       // will cause a worse single stepping debugging experience.
1205       if (N->getDebugLoc() != DL.getDebugLoc())
1206         N->setDebugLoc(DebugLoc());
1207       break;
1208     default:
1209       // When the node's point of use is located earlier in the instruction
1210       // sequence than its prior point of use, update its debug info to the
1211       // earlier location.
1212       if (DL.getIROrder() && DL.getIROrder() < N->getIROrder())
1213         N->setDebugLoc(DL.getDebugLoc());
1214       break;
1215     }
1216   }
1217   return N;
1218 }
1219 
1220 void SelectionDAG::clear() {
1221   allnodes_clear();
1222   OperandRecycler.clear(OperandAllocator);
1223   OperandAllocator.Reset();
1224   CSEMap.clear();
1225 
1226   ExtendedValueTypeNodes.clear();
1227   ExternalSymbols.clear();
1228   TargetExternalSymbols.clear();
1229   MCSymbols.clear();
1230   SDCallSiteDbgInfo.clear();
1231   std::fill(CondCodeNodes.begin(), CondCodeNodes.end(),
1232             static_cast<CondCodeSDNode*>(nullptr));
1233   std::fill(ValueTypeNodes.begin(), ValueTypeNodes.end(),
1234             static_cast<SDNode*>(nullptr));
1235 
1236   EntryNode.UseList = nullptr;
1237   InsertNode(&EntryNode);
1238   Root = getEntryNode();
1239   DbgInfo->clear();
1240 }
1241 
1242 SDValue SelectionDAG::getFPExtendOrRound(SDValue Op, const SDLoc &DL, EVT VT) {
1243   return VT.bitsGT(Op.getValueType())
1244              ? getNode(ISD::FP_EXTEND, DL, VT, Op)
1245              : getNode(ISD::FP_ROUND, DL, VT, Op, getIntPtrConstant(0, DL));
1246 }
1247 
1248 std::pair<SDValue, SDValue>
1249 SelectionDAG::getStrictFPExtendOrRound(SDValue Op, SDValue Chain,
1250                                        const SDLoc &DL, EVT VT) {
1251   assert(!VT.bitsEq(Op.getValueType()) &&
1252          "Strict no-op FP extend/round not allowed.");
1253   SDValue Res =
1254       VT.bitsGT(Op.getValueType())
1255           ? getNode(ISD::STRICT_FP_EXTEND, DL, {VT, MVT::Other}, {Chain, Op})
1256           : getNode(ISD::STRICT_FP_ROUND, DL, {VT, MVT::Other},
1257                     {Chain, Op, getIntPtrConstant(0, DL)});
1258 
1259   return std::pair<SDValue, SDValue>(Res, SDValue(Res.getNode(), 1));
1260 }
1261 
1262 SDValue SelectionDAG::getAnyExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
1263   return VT.bitsGT(Op.getValueType()) ?
1264     getNode(ISD::ANY_EXTEND, DL, VT, Op) :
1265     getNode(ISD::TRUNCATE, DL, VT, Op);
1266 }
1267 
1268 SDValue SelectionDAG::getSExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
1269   return VT.bitsGT(Op.getValueType()) ?
1270     getNode(ISD::SIGN_EXTEND, DL, VT, Op) :
1271     getNode(ISD::TRUNCATE, DL, VT, Op);
1272 }
1273 
1274 SDValue SelectionDAG::getZExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
1275   return VT.bitsGT(Op.getValueType()) ?
1276     getNode(ISD::ZERO_EXTEND, DL, VT, Op) :
1277     getNode(ISD::TRUNCATE, DL, VT, Op);
1278 }
1279 
1280 SDValue SelectionDAG::getBoolExtOrTrunc(SDValue Op, const SDLoc &SL, EVT VT,
1281                                         EVT OpVT) {
1282   if (VT.bitsLE(Op.getValueType()))
1283     return getNode(ISD::TRUNCATE, SL, VT, Op);
1284 
1285   TargetLowering::BooleanContent BType = TLI->getBooleanContents(OpVT);
1286   return getNode(TLI->getExtendForContent(BType), SL, VT, Op);
1287 }
1288 
1289 SDValue SelectionDAG::getZeroExtendInReg(SDValue Op, const SDLoc &DL, EVT VT) {
1290   EVT OpVT = Op.getValueType();
1291   assert(VT.isInteger() && OpVT.isInteger() &&
1292          "Cannot getZeroExtendInReg FP types");
1293   assert(VT.isVector() == OpVT.isVector() &&
1294          "getZeroExtendInReg type should be vector iff the operand "
1295          "type is vector!");
1296   assert((!VT.isVector() ||
1297           VT.getVectorElementCount() == OpVT.getVectorElementCount()) &&
1298          "Vector element counts must match in getZeroExtendInReg");
1299   assert(VT.bitsLE(OpVT) && "Not extending!");
1300   if (OpVT == VT)
1301     return Op;
1302   APInt Imm = APInt::getLowBitsSet(OpVT.getScalarSizeInBits(),
1303                                    VT.getScalarSizeInBits());
1304   return getNode(ISD::AND, DL, OpVT, Op, getConstant(Imm, DL, OpVT));
1305 }
1306 
1307 SDValue SelectionDAG::getPtrExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
1308   // Only unsigned pointer semantics are supported right now. In the future this
1309   // might delegate to TLI to check pointer signedness.
1310   return getZExtOrTrunc(Op, DL, VT);
1311 }
1312 
1313 SDValue SelectionDAG::getPtrExtendInReg(SDValue Op, const SDLoc &DL, EVT VT) {
1314   // Only unsigned pointer semantics are supported right now. In the future this
1315   // might delegate to TLI to check pointer signedness.
1316   return getZeroExtendInReg(Op, DL, VT);
1317 }
1318 
1319 /// getNOT - Create a bitwise NOT operation as (XOR Val, -1).
1320 SDValue SelectionDAG::getNOT(const SDLoc &DL, SDValue Val, EVT VT) {
1321   EVT EltVT = VT.getScalarType();
1322   SDValue NegOne =
1323     getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), DL, VT);
1324   return getNode(ISD::XOR, DL, VT, Val, NegOne);
1325 }
1326 
1327 SDValue SelectionDAG::getLogicalNOT(const SDLoc &DL, SDValue Val, EVT VT) {
1328   SDValue TrueValue = getBoolConstant(true, DL, VT, VT);
1329   return getNode(ISD::XOR, DL, VT, Val, TrueValue);
1330 }
1331 
1332 SDValue SelectionDAG::getBoolConstant(bool V, const SDLoc &DL, EVT VT,
1333                                       EVT OpVT) {
1334   if (!V)
1335     return getConstant(0, DL, VT);
1336 
1337   switch (TLI->getBooleanContents(OpVT)) {
1338   case TargetLowering::ZeroOrOneBooleanContent:
1339   case TargetLowering::UndefinedBooleanContent:
1340     return getConstant(1, DL, VT);
1341   case TargetLowering::ZeroOrNegativeOneBooleanContent:
1342     return getAllOnesConstant(DL, VT);
1343   }
1344   llvm_unreachable("Unexpected boolean content enum!");
1345 }
1346 
1347 SDValue SelectionDAG::getConstant(uint64_t Val, const SDLoc &DL, EVT VT,
1348                                   bool isT, bool isO) {
1349   EVT EltVT = VT.getScalarType();
1350   assert((EltVT.getSizeInBits() >= 64 ||
1351           (uint64_t)((int64_t)Val >> EltVT.getSizeInBits()) + 1 < 2) &&
1352          "getConstant with a uint64_t value that doesn't fit in the type!");
1353   return getConstant(APInt(EltVT.getSizeInBits(), Val), DL, VT, isT, isO);
1354 }
1355 
1356 SDValue SelectionDAG::getConstant(const APInt &Val, const SDLoc &DL, EVT VT,
1357                                   bool isT, bool isO) {
1358   return getConstant(*ConstantInt::get(*Context, Val), DL, VT, isT, isO);
1359 }
1360 
1361 SDValue SelectionDAG::getConstant(const ConstantInt &Val, const SDLoc &DL,
1362                                   EVT VT, bool isT, bool isO) {
1363   assert(VT.isInteger() && "Cannot create FP integer constant!");
1364 
1365   EVT EltVT = VT.getScalarType();
1366   const ConstantInt *Elt = &Val;
1367 
1368   // In some cases the vector type is legal but the element type is illegal and
1369   // needs to be promoted, for example v8i8 on ARM.  In this case, promote the
1370   // inserted value (the type does not need to match the vector element type).
1371   // Any extra bits introduced will be truncated away.
1372   if (VT.isVector() && TLI->getTypeAction(*getContext(), EltVT) ==
1373                            TargetLowering::TypePromoteInteger) {
1374     EltVT = TLI->getTypeToTransformTo(*getContext(), EltVT);
1375     APInt NewVal = Elt->getValue().zextOrTrunc(EltVT.getSizeInBits());
1376     Elt = ConstantInt::get(*getContext(), NewVal);
1377   }
1378   // In other cases the element type is illegal and needs to be expanded, for
1379   // example v2i64 on MIPS32. In this case, find the nearest legal type, split
1380   // the value into n parts and use a vector type with n-times the elements.
1381   // Then bitcast to the type requested.
1382   // Legalizing constants too early makes the DAGCombiner's job harder so we
1383   // only legalize if the DAG tells us we must produce legal types.
1384   else if (NewNodesMustHaveLegalTypes && VT.isVector() &&
1385            TLI->getTypeAction(*getContext(), EltVT) ==
1386                TargetLowering::TypeExpandInteger) {
1387     const APInt &NewVal = Elt->getValue();
1388     EVT ViaEltVT = TLI->getTypeToTransformTo(*getContext(), EltVT);
1389     unsigned ViaEltSizeInBits = ViaEltVT.getSizeInBits();
1390 
1391     // For scalable vectors, try to use a SPLAT_VECTOR_PARTS node.
1392     if (VT.isScalableVector()) {
1393       assert(EltVT.getSizeInBits() % ViaEltSizeInBits == 0 &&
1394              "Can only handle an even split!");
1395       unsigned Parts = EltVT.getSizeInBits() / ViaEltSizeInBits;
1396 
1397       SmallVector<SDValue, 2> ScalarParts;
1398       for (unsigned i = 0; i != Parts; ++i)
1399         ScalarParts.push_back(getConstant(
1400             NewVal.lshr(i * ViaEltSizeInBits).trunc(ViaEltSizeInBits), DL,
1401             ViaEltVT, isT, isO));
1402 
1403       return getNode(ISD::SPLAT_VECTOR_PARTS, DL, VT, ScalarParts);
1404     }
1405 
1406     unsigned ViaVecNumElts = VT.getSizeInBits() / ViaEltSizeInBits;
1407     EVT ViaVecVT = EVT::getVectorVT(*getContext(), ViaEltVT, ViaVecNumElts);
1408 
1409     // Check the temporary vector is the correct size. If this fails then
1410     // getTypeToTransformTo() probably returned a type whose size (in bits)
1411     // isn't a power-of-2 factor of the requested type size.
1412     assert(ViaVecVT.getSizeInBits() == VT.getSizeInBits());
1413 
1414     SmallVector<SDValue, 2> EltParts;
1415     for (unsigned i = 0; i < ViaVecNumElts / VT.getVectorNumElements(); ++i) {
1416       EltParts.push_back(getConstant(
1417           NewVal.lshr(i * ViaEltSizeInBits).zextOrTrunc(ViaEltSizeInBits), DL,
1418           ViaEltVT, isT, isO));
1419     }
1420 
1421     // EltParts is currently in little endian order. If we actually want
1422     // big-endian order then reverse it now.
1423     if (getDataLayout().isBigEndian())
1424       std::reverse(EltParts.begin(), EltParts.end());
1425 
1426     // The elements must be reversed when the element order is different
1427     // to the endianness of the elements (because the BITCAST is itself a
1428     // vector shuffle in this situation). However, we do not need any code to
1429     // perform this reversal because getConstant() is producing a vector
1430     // splat.
1431     // This situation occurs in MIPS MSA.
1432 
1433     SmallVector<SDValue, 8> Ops;
1434     for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
1435       llvm::append_range(Ops, EltParts);
1436 
1437     SDValue V =
1438         getNode(ISD::BITCAST, DL, VT, getBuildVector(ViaVecVT, DL, Ops));
1439     return V;
1440   }
1441 
1442   assert(Elt->getBitWidth() == EltVT.getSizeInBits() &&
1443          "APInt size does not match type size!");
1444   unsigned Opc = isT ? ISD::TargetConstant : ISD::Constant;
1445   FoldingSetNodeID ID;
1446   AddNodeIDNode(ID, Opc, getVTList(EltVT), None);
1447   ID.AddPointer(Elt);
1448   ID.AddBoolean(isO);
1449   void *IP = nullptr;
1450   SDNode *N = nullptr;
1451   if ((N = FindNodeOrInsertPos(ID, DL, IP)))
1452     if (!VT.isVector())
1453       return SDValue(N, 0);
1454 
1455   if (!N) {
1456     N = newSDNode<ConstantSDNode>(isT, isO, Elt, EltVT);
1457     CSEMap.InsertNode(N, IP);
1458     InsertNode(N);
1459     NewSDValueDbgMsg(SDValue(N, 0), "Creating constant: ", this);
1460   }
1461 
1462   SDValue Result(N, 0);
1463   if (VT.isScalableVector())
1464     Result = getSplatVector(VT, DL, Result);
1465   else if (VT.isVector())
1466     Result = getSplatBuildVector(VT, DL, Result);
1467 
1468   return Result;
1469 }
1470 
1471 SDValue SelectionDAG::getIntPtrConstant(uint64_t Val, const SDLoc &DL,
1472                                         bool isTarget) {
1473   return getConstant(Val, DL, TLI->getPointerTy(getDataLayout()), isTarget);
1474 }
1475 
1476 SDValue SelectionDAG::getShiftAmountConstant(uint64_t Val, EVT VT,
1477                                              const SDLoc &DL, bool LegalTypes) {
1478   assert(VT.isInteger() && "Shift amount is not an integer type!");
1479   EVT ShiftVT = TLI->getShiftAmountTy(VT, getDataLayout(), LegalTypes);
1480   return getConstant(Val, DL, ShiftVT);
1481 }
1482 
1483 SDValue SelectionDAG::getVectorIdxConstant(uint64_t Val, const SDLoc &DL,
1484                                            bool isTarget) {
1485   return getConstant(Val, DL, TLI->getVectorIdxTy(getDataLayout()), isTarget);
1486 }
1487 
1488 SDValue SelectionDAG::getConstantFP(const APFloat &V, const SDLoc &DL, EVT VT,
1489                                     bool isTarget) {
1490   return getConstantFP(*ConstantFP::get(*getContext(), V), DL, VT, isTarget);
1491 }
1492 
1493 SDValue SelectionDAG::getConstantFP(const ConstantFP &V, const SDLoc &DL,
1494                                     EVT VT, bool isTarget) {
1495   assert(VT.isFloatingPoint() && "Cannot create integer FP constant!");
1496 
1497   EVT EltVT = VT.getScalarType();
1498 
1499   // Do the map lookup using the actual bit pattern for the floating point
1500   // value, so that we don't have problems with 0.0 comparing equal to -0.0, and
1501   // we don't have issues with SNANs.
1502   unsigned Opc = isTarget ? ISD::TargetConstantFP : ISD::ConstantFP;
1503   FoldingSetNodeID ID;
1504   AddNodeIDNode(ID, Opc, getVTList(EltVT), None);
1505   ID.AddPointer(&V);
1506   void *IP = nullptr;
1507   SDNode *N = nullptr;
1508   if ((N = FindNodeOrInsertPos(ID, DL, IP)))
1509     if (!VT.isVector())
1510       return SDValue(N, 0);
1511 
1512   if (!N) {
1513     N = newSDNode<ConstantFPSDNode>(isTarget, &V, EltVT);
1514     CSEMap.InsertNode(N, IP);
1515     InsertNode(N);
1516   }
1517 
1518   SDValue Result(N, 0);
1519   if (VT.isScalableVector())
1520     Result = getSplatVector(VT, DL, Result);
1521   else if (VT.isVector())
1522     Result = getSplatBuildVector(VT, DL, Result);
1523   NewSDValueDbgMsg(Result, "Creating fp constant: ", this);
1524   return Result;
1525 }
1526 
1527 SDValue SelectionDAG::getConstantFP(double Val, const SDLoc &DL, EVT VT,
1528                                     bool isTarget) {
1529   EVT EltVT = VT.getScalarType();
1530   if (EltVT == MVT::f32)
1531     return getConstantFP(APFloat((float)Val), DL, VT, isTarget);
1532   if (EltVT == MVT::f64)
1533     return getConstantFP(APFloat(Val), DL, VT, isTarget);
1534   if (EltVT == MVT::f80 || EltVT == MVT::f128 || EltVT == MVT::ppcf128 ||
1535       EltVT == MVT::f16 || EltVT == MVT::bf16) {
1536     bool Ignored;
1537     APFloat APF = APFloat(Val);
1538     APF.convert(EVTToAPFloatSemantics(EltVT), APFloat::rmNearestTiesToEven,
1539                 &Ignored);
1540     return getConstantFP(APF, DL, VT, isTarget);
1541   }
1542   llvm_unreachable("Unsupported type in getConstantFP");
1543 }
1544 
1545 SDValue SelectionDAG::getGlobalAddress(const GlobalValue *GV, const SDLoc &DL,
1546                                        EVT VT, int64_t Offset, bool isTargetGA,
1547                                        unsigned TargetFlags) {
1548   assert((TargetFlags == 0 || isTargetGA) &&
1549          "Cannot set target flags on target-independent globals");
1550 
1551   // Truncate (with sign-extension) the offset value to the pointer size.
1552   unsigned BitWidth = getDataLayout().getPointerTypeSizeInBits(GV->getType());
1553   if (BitWidth < 64)
1554     Offset = SignExtend64(Offset, BitWidth);
1555 
1556   unsigned Opc;
1557   if (GV->isThreadLocal())
1558     Opc = isTargetGA ? ISD::TargetGlobalTLSAddress : ISD::GlobalTLSAddress;
1559   else
1560     Opc = isTargetGA ? ISD::TargetGlobalAddress : ISD::GlobalAddress;
1561 
1562   FoldingSetNodeID ID;
1563   AddNodeIDNode(ID, Opc, getVTList(VT), None);
1564   ID.AddPointer(GV);
1565   ID.AddInteger(Offset);
1566   ID.AddInteger(TargetFlags);
1567   void *IP = nullptr;
1568   if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
1569     return SDValue(E, 0);
1570 
1571   auto *N = newSDNode<GlobalAddressSDNode>(
1572       Opc, DL.getIROrder(), DL.getDebugLoc(), GV, VT, Offset, TargetFlags);
1573   CSEMap.InsertNode(N, IP);
1574     InsertNode(N);
1575   return SDValue(N, 0);
1576 }
1577 
1578 SDValue SelectionDAG::getFrameIndex(int FI, EVT VT, bool isTarget) {
1579   unsigned Opc = isTarget ? ISD::TargetFrameIndex : ISD::FrameIndex;
1580   FoldingSetNodeID ID;
1581   AddNodeIDNode(ID, Opc, getVTList(VT), None);
1582   ID.AddInteger(FI);
1583   void *IP = nullptr;
1584   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1585     return SDValue(E, 0);
1586 
1587   auto *N = newSDNode<FrameIndexSDNode>(FI, VT, isTarget);
1588   CSEMap.InsertNode(N, IP);
1589   InsertNode(N);
1590   return SDValue(N, 0);
1591 }
1592 
1593 SDValue SelectionDAG::getJumpTable(int JTI, EVT VT, bool isTarget,
1594                                    unsigned TargetFlags) {
1595   assert((TargetFlags == 0 || isTarget) &&
1596          "Cannot set target flags on target-independent jump tables");
1597   unsigned Opc = isTarget ? ISD::TargetJumpTable : ISD::JumpTable;
1598   FoldingSetNodeID ID;
1599   AddNodeIDNode(ID, Opc, getVTList(VT), None);
1600   ID.AddInteger(JTI);
1601   ID.AddInteger(TargetFlags);
1602   void *IP = nullptr;
1603   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1604     return SDValue(E, 0);
1605 
1606   auto *N = newSDNode<JumpTableSDNode>(JTI, VT, isTarget, TargetFlags);
1607   CSEMap.InsertNode(N, IP);
1608   InsertNode(N);
1609   return SDValue(N, 0);
1610 }
1611 
1612 SDValue SelectionDAG::getConstantPool(const Constant *C, EVT VT,
1613                                       MaybeAlign Alignment, int Offset,
1614                                       bool isTarget, unsigned TargetFlags) {
1615   assert((TargetFlags == 0 || isTarget) &&
1616          "Cannot set target flags on target-independent globals");
1617   if (!Alignment)
1618     Alignment = shouldOptForSize()
1619                     ? getDataLayout().getABITypeAlign(C->getType())
1620                     : getDataLayout().getPrefTypeAlign(C->getType());
1621   unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
1622   FoldingSetNodeID ID;
1623   AddNodeIDNode(ID, Opc, getVTList(VT), None);
1624   ID.AddInteger(Alignment->value());
1625   ID.AddInteger(Offset);
1626   ID.AddPointer(C);
1627   ID.AddInteger(TargetFlags);
1628   void *IP = nullptr;
1629   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1630     return SDValue(E, 0);
1631 
1632   auto *N = newSDNode<ConstantPoolSDNode>(isTarget, C, VT, Offset, *Alignment,
1633                                           TargetFlags);
1634   CSEMap.InsertNode(N, IP);
1635   InsertNode(N);
1636   SDValue V = SDValue(N, 0);
1637   NewSDValueDbgMsg(V, "Creating new constant pool: ", this);
1638   return V;
1639 }
1640 
1641 SDValue SelectionDAG::getConstantPool(MachineConstantPoolValue *C, EVT VT,
1642                                       MaybeAlign Alignment, int Offset,
1643                                       bool isTarget, unsigned TargetFlags) {
1644   assert((TargetFlags == 0 || isTarget) &&
1645          "Cannot set target flags on target-independent globals");
1646   if (!Alignment)
1647     Alignment = getDataLayout().getPrefTypeAlign(C->getType());
1648   unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
1649   FoldingSetNodeID ID;
1650   AddNodeIDNode(ID, Opc, getVTList(VT), None);
1651   ID.AddInteger(Alignment->value());
1652   ID.AddInteger(Offset);
1653   C->addSelectionDAGCSEId(ID);
1654   ID.AddInteger(TargetFlags);
1655   void *IP = nullptr;
1656   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1657     return SDValue(E, 0);
1658 
1659   auto *N = newSDNode<ConstantPoolSDNode>(isTarget, C, VT, Offset, *Alignment,
1660                                           TargetFlags);
1661   CSEMap.InsertNode(N, IP);
1662   InsertNode(N);
1663   return SDValue(N, 0);
1664 }
1665 
1666 SDValue SelectionDAG::getTargetIndex(int Index, EVT VT, int64_t Offset,
1667                                      unsigned TargetFlags) {
1668   FoldingSetNodeID ID;
1669   AddNodeIDNode(ID, ISD::TargetIndex, getVTList(VT), None);
1670   ID.AddInteger(Index);
1671   ID.AddInteger(Offset);
1672   ID.AddInteger(TargetFlags);
1673   void *IP = nullptr;
1674   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1675     return SDValue(E, 0);
1676 
1677   auto *N = newSDNode<TargetIndexSDNode>(Index, VT, Offset, TargetFlags);
1678   CSEMap.InsertNode(N, IP);
1679   InsertNode(N);
1680   return SDValue(N, 0);
1681 }
1682 
1683 SDValue SelectionDAG::getBasicBlock(MachineBasicBlock *MBB) {
1684   FoldingSetNodeID ID;
1685   AddNodeIDNode(ID, ISD::BasicBlock, getVTList(MVT::Other), None);
1686   ID.AddPointer(MBB);
1687   void *IP = nullptr;
1688   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1689     return SDValue(E, 0);
1690 
1691   auto *N = newSDNode<BasicBlockSDNode>(MBB);
1692   CSEMap.InsertNode(N, IP);
1693   InsertNode(N);
1694   return SDValue(N, 0);
1695 }
1696 
1697 SDValue SelectionDAG::getValueType(EVT VT) {
1698   if (VT.isSimple() && (unsigned)VT.getSimpleVT().SimpleTy >=
1699       ValueTypeNodes.size())
1700     ValueTypeNodes.resize(VT.getSimpleVT().SimpleTy+1);
1701 
1702   SDNode *&N = VT.isExtended() ?
1703     ExtendedValueTypeNodes[VT] : ValueTypeNodes[VT.getSimpleVT().SimpleTy];
1704 
1705   if (N) return SDValue(N, 0);
1706   N = newSDNode<VTSDNode>(VT);
1707   InsertNode(N);
1708   return SDValue(N, 0);
1709 }
1710 
1711 SDValue SelectionDAG::getExternalSymbol(const char *Sym, EVT VT) {
1712   SDNode *&N = ExternalSymbols[Sym];
1713   if (N) return SDValue(N, 0);
1714   N = newSDNode<ExternalSymbolSDNode>(false, Sym, 0, VT);
1715   InsertNode(N);
1716   return SDValue(N, 0);
1717 }
1718 
1719 SDValue SelectionDAG::getMCSymbol(MCSymbol *Sym, EVT VT) {
1720   SDNode *&N = MCSymbols[Sym];
1721   if (N)
1722     return SDValue(N, 0);
1723   N = newSDNode<MCSymbolSDNode>(Sym, VT);
1724   InsertNode(N);
1725   return SDValue(N, 0);
1726 }
1727 
1728 SDValue SelectionDAG::getTargetExternalSymbol(const char *Sym, EVT VT,
1729                                               unsigned TargetFlags) {
1730   SDNode *&N =
1731       TargetExternalSymbols[std::pair<std::string, unsigned>(Sym, TargetFlags)];
1732   if (N) return SDValue(N, 0);
1733   N = newSDNode<ExternalSymbolSDNode>(true, Sym, TargetFlags, VT);
1734   InsertNode(N);
1735   return SDValue(N, 0);
1736 }
1737 
1738 SDValue SelectionDAG::getCondCode(ISD::CondCode Cond) {
1739   if ((unsigned)Cond >= CondCodeNodes.size())
1740     CondCodeNodes.resize(Cond+1);
1741 
1742   if (!CondCodeNodes[Cond]) {
1743     auto *N = newSDNode<CondCodeSDNode>(Cond);
1744     CondCodeNodes[Cond] = N;
1745     InsertNode(N);
1746   }
1747 
1748   return SDValue(CondCodeNodes[Cond], 0);
1749 }
1750 
1751 SDValue SelectionDAG::getStepVector(const SDLoc &DL, EVT ResVT, SDValue Step) {
1752   if (ResVT.isScalableVector())
1753     return getNode(ISD::STEP_VECTOR, DL, ResVT, Step);
1754 
1755   EVT OpVT = Step.getValueType();
1756   APInt StepVal = cast<ConstantSDNode>(Step)->getAPIntValue();
1757   SmallVector<SDValue, 16> OpsStepConstants;
1758   for (uint64_t i = 0; i < ResVT.getVectorNumElements(); i++)
1759     OpsStepConstants.push_back(getConstant(StepVal * i, DL, OpVT));
1760   return getBuildVector(ResVT, DL, OpsStepConstants);
1761 }
1762 
1763 /// Swaps the values of N1 and N2. Swaps all indices in the shuffle mask M that
1764 /// point at N1 to point at N2 and indices that point at N2 to point at N1.
1765 static void commuteShuffle(SDValue &N1, SDValue &N2, MutableArrayRef<int> M) {
1766   std::swap(N1, N2);
1767   ShuffleVectorSDNode::commuteMask(M);
1768 }
1769 
1770 SDValue SelectionDAG::getVectorShuffle(EVT VT, const SDLoc &dl, SDValue N1,
1771                                        SDValue N2, ArrayRef<int> Mask) {
1772   assert(VT.getVectorNumElements() == Mask.size() &&
1773            "Must have the same number of vector elements as mask elements!");
1774   assert(VT == N1.getValueType() && VT == N2.getValueType() &&
1775          "Invalid VECTOR_SHUFFLE");
1776 
1777   // Canonicalize shuffle undef, undef -> undef
1778   if (N1.isUndef() && N2.isUndef())
1779     return getUNDEF(VT);
1780 
1781   // Validate that all indices in Mask are within the range of the elements
1782   // input to the shuffle.
1783   int NElts = Mask.size();
1784   assert(llvm::all_of(Mask,
1785                       [&](int M) { return M < (NElts * 2) && M >= -1; }) &&
1786          "Index out of range");
1787 
1788   // Copy the mask so we can do any needed cleanup.
1789   SmallVector<int, 8> MaskVec(Mask.begin(), Mask.end());
1790 
1791   // Canonicalize shuffle v, v -> v, undef
1792   if (N1 == N2) {
1793     N2 = getUNDEF(VT);
1794     for (int i = 0; i != NElts; ++i)
1795       if (MaskVec[i] >= NElts) MaskVec[i] -= NElts;
1796   }
1797 
1798   // Canonicalize shuffle undef, v -> v, undef.  Commute the shuffle mask.
1799   if (N1.isUndef())
1800     commuteShuffle(N1, N2, MaskVec);
1801 
1802   if (TLI->hasVectorBlend()) {
1803     // If shuffling a splat, try to blend the splat instead. We do this here so
1804     // that even when this arises during lowering we don't have to re-handle it.
1805     auto BlendSplat = [&](BuildVectorSDNode *BV, int Offset) {
1806       BitVector UndefElements;
1807       SDValue Splat = BV->getSplatValue(&UndefElements);
1808       if (!Splat)
1809         return;
1810 
1811       for (int i = 0; i < NElts; ++i) {
1812         if (MaskVec[i] < Offset || MaskVec[i] >= (Offset + NElts))
1813           continue;
1814 
1815         // If this input comes from undef, mark it as such.
1816         if (UndefElements[MaskVec[i] - Offset]) {
1817           MaskVec[i] = -1;
1818           continue;
1819         }
1820 
1821         // If we can blend a non-undef lane, use that instead.
1822         if (!UndefElements[i])
1823           MaskVec[i] = i + Offset;
1824       }
1825     };
1826     if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
1827       BlendSplat(N1BV, 0);
1828     if (auto *N2BV = dyn_cast<BuildVectorSDNode>(N2))
1829       BlendSplat(N2BV, NElts);
1830   }
1831 
1832   // Canonicalize all index into lhs, -> shuffle lhs, undef
1833   // Canonicalize all index into rhs, -> shuffle rhs, undef
1834   bool AllLHS = true, AllRHS = true;
1835   bool N2Undef = N2.isUndef();
1836   for (int i = 0; i != NElts; ++i) {
1837     if (MaskVec[i] >= NElts) {
1838       if (N2Undef)
1839         MaskVec[i] = -1;
1840       else
1841         AllLHS = false;
1842     } else if (MaskVec[i] >= 0) {
1843       AllRHS = false;
1844     }
1845   }
1846   if (AllLHS && AllRHS)
1847     return getUNDEF(VT);
1848   if (AllLHS && !N2Undef)
1849     N2 = getUNDEF(VT);
1850   if (AllRHS) {
1851     N1 = getUNDEF(VT);
1852     commuteShuffle(N1, N2, MaskVec);
1853   }
1854   // Reset our undef status after accounting for the mask.
1855   N2Undef = N2.isUndef();
1856   // Re-check whether both sides ended up undef.
1857   if (N1.isUndef() && N2Undef)
1858     return getUNDEF(VT);
1859 
1860   // If Identity shuffle return that node.
1861   bool Identity = true, AllSame = true;
1862   for (int i = 0; i != NElts; ++i) {
1863     if (MaskVec[i] >= 0 && MaskVec[i] != i) Identity = false;
1864     if (MaskVec[i] != MaskVec[0]) AllSame = false;
1865   }
1866   if (Identity && NElts)
1867     return N1;
1868 
1869   // Shuffling a constant splat doesn't change the result.
1870   if (N2Undef) {
1871     SDValue V = N1;
1872 
1873     // Look through any bitcasts. We check that these don't change the number
1874     // (and size) of elements and just changes their types.
1875     while (V.getOpcode() == ISD::BITCAST)
1876       V = V->getOperand(0);
1877 
1878     // A splat should always show up as a build vector node.
1879     if (auto *BV = dyn_cast<BuildVectorSDNode>(V)) {
1880       BitVector UndefElements;
1881       SDValue Splat = BV->getSplatValue(&UndefElements);
1882       // If this is a splat of an undef, shuffling it is also undef.
1883       if (Splat && Splat.isUndef())
1884         return getUNDEF(VT);
1885 
1886       bool SameNumElts =
1887           V.getValueType().getVectorNumElements() == VT.getVectorNumElements();
1888 
1889       // We only have a splat which can skip shuffles if there is a splatted
1890       // value and no undef lanes rearranged by the shuffle.
1891       if (Splat && UndefElements.none()) {
1892         // Splat of <x, x, ..., x>, return <x, x, ..., x>, provided that the
1893         // number of elements match or the value splatted is a zero constant.
1894         if (SameNumElts)
1895           return N1;
1896         if (auto *C = dyn_cast<ConstantSDNode>(Splat))
1897           if (C->isNullValue())
1898             return N1;
1899       }
1900 
1901       // If the shuffle itself creates a splat, build the vector directly.
1902       if (AllSame && SameNumElts) {
1903         EVT BuildVT = BV->getValueType(0);
1904         const SDValue &Splatted = BV->getOperand(MaskVec[0]);
1905         SDValue NewBV = getSplatBuildVector(BuildVT, dl, Splatted);
1906 
1907         // We may have jumped through bitcasts, so the type of the
1908         // BUILD_VECTOR may not match the type of the shuffle.
1909         if (BuildVT != VT)
1910           NewBV = getNode(ISD::BITCAST, dl, VT, NewBV);
1911         return NewBV;
1912       }
1913     }
1914   }
1915 
1916   FoldingSetNodeID ID;
1917   SDValue Ops[2] = { N1, N2 };
1918   AddNodeIDNode(ID, ISD::VECTOR_SHUFFLE, getVTList(VT), Ops);
1919   for (int i = 0; i != NElts; ++i)
1920     ID.AddInteger(MaskVec[i]);
1921 
1922   void* IP = nullptr;
1923   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
1924     return SDValue(E, 0);
1925 
1926   // Allocate the mask array for the node out of the BumpPtrAllocator, since
1927   // SDNode doesn't have access to it.  This memory will be "leaked" when
1928   // the node is deallocated, but recovered when the NodeAllocator is released.
1929   int *MaskAlloc = OperandAllocator.Allocate<int>(NElts);
1930   llvm::copy(MaskVec, MaskAlloc);
1931 
1932   auto *N = newSDNode<ShuffleVectorSDNode>(VT, dl.getIROrder(),
1933                                            dl.getDebugLoc(), MaskAlloc);
1934   createOperands(N, Ops);
1935 
1936   CSEMap.InsertNode(N, IP);
1937   InsertNode(N);
1938   SDValue V = SDValue(N, 0);
1939   NewSDValueDbgMsg(V, "Creating new node: ", this);
1940   return V;
1941 }
1942 
1943 SDValue SelectionDAG::getCommutedVectorShuffle(const ShuffleVectorSDNode &SV) {
1944   EVT VT = SV.getValueType(0);
1945   SmallVector<int, 8> MaskVec(SV.getMask().begin(), SV.getMask().end());
1946   ShuffleVectorSDNode::commuteMask(MaskVec);
1947 
1948   SDValue Op0 = SV.getOperand(0);
1949   SDValue Op1 = SV.getOperand(1);
1950   return getVectorShuffle(VT, SDLoc(&SV), Op1, Op0, MaskVec);
1951 }
1952 
1953 SDValue SelectionDAG::getRegister(unsigned RegNo, EVT VT) {
1954   FoldingSetNodeID ID;
1955   AddNodeIDNode(ID, ISD::Register, getVTList(VT), None);
1956   ID.AddInteger(RegNo);
1957   void *IP = nullptr;
1958   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1959     return SDValue(E, 0);
1960 
1961   auto *N = newSDNode<RegisterSDNode>(RegNo, VT);
1962   N->SDNodeBits.IsDivergent = TLI->isSDNodeSourceOfDivergence(N, FLI, DA);
1963   CSEMap.InsertNode(N, IP);
1964   InsertNode(N);
1965   return SDValue(N, 0);
1966 }
1967 
1968 SDValue SelectionDAG::getRegisterMask(const uint32_t *RegMask) {
1969   FoldingSetNodeID ID;
1970   AddNodeIDNode(ID, ISD::RegisterMask, getVTList(MVT::Untyped), None);
1971   ID.AddPointer(RegMask);
1972   void *IP = nullptr;
1973   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1974     return SDValue(E, 0);
1975 
1976   auto *N = newSDNode<RegisterMaskSDNode>(RegMask);
1977   CSEMap.InsertNode(N, IP);
1978   InsertNode(N);
1979   return SDValue(N, 0);
1980 }
1981 
1982 SDValue SelectionDAG::getEHLabel(const SDLoc &dl, SDValue Root,
1983                                  MCSymbol *Label) {
1984   return getLabelNode(ISD::EH_LABEL, dl, Root, Label);
1985 }
1986 
1987 SDValue SelectionDAG::getLabelNode(unsigned Opcode, const SDLoc &dl,
1988                                    SDValue Root, MCSymbol *Label) {
1989   FoldingSetNodeID ID;
1990   SDValue Ops[] = { Root };
1991   AddNodeIDNode(ID, Opcode, getVTList(MVT::Other), Ops);
1992   ID.AddPointer(Label);
1993   void *IP = nullptr;
1994   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1995     return SDValue(E, 0);
1996 
1997   auto *N =
1998       newSDNode<LabelSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(), Label);
1999   createOperands(N, Ops);
2000 
2001   CSEMap.InsertNode(N, IP);
2002   InsertNode(N);
2003   return SDValue(N, 0);
2004 }
2005 
2006 SDValue SelectionDAG::getBlockAddress(const BlockAddress *BA, EVT VT,
2007                                       int64_t Offset, bool isTarget,
2008                                       unsigned TargetFlags) {
2009   unsigned Opc = isTarget ? ISD::TargetBlockAddress : ISD::BlockAddress;
2010 
2011   FoldingSetNodeID ID;
2012   AddNodeIDNode(ID, Opc, getVTList(VT), None);
2013   ID.AddPointer(BA);
2014   ID.AddInteger(Offset);
2015   ID.AddInteger(TargetFlags);
2016   void *IP = nullptr;
2017   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2018     return SDValue(E, 0);
2019 
2020   auto *N = newSDNode<BlockAddressSDNode>(Opc, VT, BA, Offset, TargetFlags);
2021   CSEMap.InsertNode(N, IP);
2022   InsertNode(N);
2023   return SDValue(N, 0);
2024 }
2025 
2026 SDValue SelectionDAG::getSrcValue(const Value *V) {
2027   FoldingSetNodeID ID;
2028   AddNodeIDNode(ID, ISD::SRCVALUE, getVTList(MVT::Other), None);
2029   ID.AddPointer(V);
2030 
2031   void *IP = nullptr;
2032   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2033     return SDValue(E, 0);
2034 
2035   auto *N = newSDNode<SrcValueSDNode>(V);
2036   CSEMap.InsertNode(N, IP);
2037   InsertNode(N);
2038   return SDValue(N, 0);
2039 }
2040 
2041 SDValue SelectionDAG::getMDNode(const MDNode *MD) {
2042   FoldingSetNodeID ID;
2043   AddNodeIDNode(ID, ISD::MDNODE_SDNODE, getVTList(MVT::Other), None);
2044   ID.AddPointer(MD);
2045 
2046   void *IP = nullptr;
2047   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2048     return SDValue(E, 0);
2049 
2050   auto *N = newSDNode<MDNodeSDNode>(MD);
2051   CSEMap.InsertNode(N, IP);
2052   InsertNode(N);
2053   return SDValue(N, 0);
2054 }
2055 
2056 SDValue SelectionDAG::getBitcast(EVT VT, SDValue V) {
2057   if (VT == V.getValueType())
2058     return V;
2059 
2060   return getNode(ISD::BITCAST, SDLoc(V), VT, V);
2061 }
2062 
2063 SDValue SelectionDAG::getAddrSpaceCast(const SDLoc &dl, EVT VT, SDValue Ptr,
2064                                        unsigned SrcAS, unsigned DestAS) {
2065   SDValue Ops[] = {Ptr};
2066   FoldingSetNodeID ID;
2067   AddNodeIDNode(ID, ISD::ADDRSPACECAST, getVTList(VT), Ops);
2068   ID.AddInteger(SrcAS);
2069   ID.AddInteger(DestAS);
2070 
2071   void *IP = nullptr;
2072   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
2073     return SDValue(E, 0);
2074 
2075   auto *N = newSDNode<AddrSpaceCastSDNode>(dl.getIROrder(), dl.getDebugLoc(),
2076                                            VT, SrcAS, DestAS);
2077   createOperands(N, Ops);
2078 
2079   CSEMap.InsertNode(N, IP);
2080   InsertNode(N);
2081   return SDValue(N, 0);
2082 }
2083 
2084 SDValue SelectionDAG::getFreeze(SDValue V) {
2085   return getNode(ISD::FREEZE, SDLoc(V), V.getValueType(), V);
2086 }
2087 
2088 /// getShiftAmountOperand - Return the specified value casted to
2089 /// the target's desired shift amount type.
2090 SDValue SelectionDAG::getShiftAmountOperand(EVT LHSTy, SDValue Op) {
2091   EVT OpTy = Op.getValueType();
2092   EVT ShTy = TLI->getShiftAmountTy(LHSTy, getDataLayout());
2093   if (OpTy == ShTy || OpTy.isVector()) return Op;
2094 
2095   return getZExtOrTrunc(Op, SDLoc(Op), ShTy);
2096 }
2097 
2098 SDValue SelectionDAG::expandVAArg(SDNode *Node) {
2099   SDLoc dl(Node);
2100   const TargetLowering &TLI = getTargetLoweringInfo();
2101   const Value *V = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
2102   EVT VT = Node->getValueType(0);
2103   SDValue Tmp1 = Node->getOperand(0);
2104   SDValue Tmp2 = Node->getOperand(1);
2105   const MaybeAlign MA(Node->getConstantOperandVal(3));
2106 
2107   SDValue VAListLoad = getLoad(TLI.getPointerTy(getDataLayout()), dl, Tmp1,
2108                                Tmp2, MachinePointerInfo(V));
2109   SDValue VAList = VAListLoad;
2110 
2111   if (MA && *MA > TLI.getMinStackArgumentAlignment()) {
2112     VAList = getNode(ISD::ADD, dl, VAList.getValueType(), VAList,
2113                      getConstant(MA->value() - 1, dl, VAList.getValueType()));
2114 
2115     VAList =
2116         getNode(ISD::AND, dl, VAList.getValueType(), VAList,
2117                 getConstant(-(int64_t)MA->value(), dl, VAList.getValueType()));
2118   }
2119 
2120   // Increment the pointer, VAList, to the next vaarg
2121   Tmp1 = getNode(ISD::ADD, dl, VAList.getValueType(), VAList,
2122                  getConstant(getDataLayout().getTypeAllocSize(
2123                                                VT.getTypeForEVT(*getContext())),
2124                              dl, VAList.getValueType()));
2125   // Store the incremented VAList to the legalized pointer
2126   Tmp1 =
2127       getStore(VAListLoad.getValue(1), dl, Tmp1, Tmp2, MachinePointerInfo(V));
2128   // Load the actual argument out of the pointer VAList
2129   return getLoad(VT, dl, Tmp1, VAList, MachinePointerInfo());
2130 }
2131 
2132 SDValue SelectionDAG::expandVACopy(SDNode *Node) {
2133   SDLoc dl(Node);
2134   const TargetLowering &TLI = getTargetLoweringInfo();
2135   // This defaults to loading a pointer from the input and storing it to the
2136   // output, returning the chain.
2137   const Value *VD = cast<SrcValueSDNode>(Node->getOperand(3))->getValue();
2138   const Value *VS = cast<SrcValueSDNode>(Node->getOperand(4))->getValue();
2139   SDValue Tmp1 =
2140       getLoad(TLI.getPointerTy(getDataLayout()), dl, Node->getOperand(0),
2141               Node->getOperand(2), MachinePointerInfo(VS));
2142   return getStore(Tmp1.getValue(1), dl, Tmp1, Node->getOperand(1),
2143                   MachinePointerInfo(VD));
2144 }
2145 
2146 Align SelectionDAG::getReducedAlign(EVT VT, bool UseABI) {
2147   const DataLayout &DL = getDataLayout();
2148   Type *Ty = VT.getTypeForEVT(*getContext());
2149   Align RedAlign = UseABI ? DL.getABITypeAlign(Ty) : DL.getPrefTypeAlign(Ty);
2150 
2151   if (TLI->isTypeLegal(VT) || !VT.isVector())
2152     return RedAlign;
2153 
2154   const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering();
2155   const Align StackAlign = TFI->getStackAlign();
2156 
2157   // See if we can choose a smaller ABI alignment in cases where it's an
2158   // illegal vector type that will get broken down.
2159   if (RedAlign > StackAlign) {
2160     EVT IntermediateVT;
2161     MVT RegisterVT;
2162     unsigned NumIntermediates;
2163     TLI->getVectorTypeBreakdown(*getContext(), VT, IntermediateVT,
2164                                 NumIntermediates, RegisterVT);
2165     Ty = IntermediateVT.getTypeForEVT(*getContext());
2166     Align RedAlign2 = UseABI ? DL.getABITypeAlign(Ty) : DL.getPrefTypeAlign(Ty);
2167     if (RedAlign2 < RedAlign)
2168       RedAlign = RedAlign2;
2169   }
2170 
2171   return RedAlign;
2172 }
2173 
2174 SDValue SelectionDAG::CreateStackTemporary(TypeSize Bytes, Align Alignment) {
2175   MachineFrameInfo &MFI = MF->getFrameInfo();
2176   const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering();
2177   int StackID = 0;
2178   if (Bytes.isScalable())
2179     StackID = TFI->getStackIDForScalableVectors();
2180   // The stack id gives an indication of whether the object is scalable or
2181   // not, so it's safe to pass in the minimum size here.
2182   int FrameIdx = MFI.CreateStackObject(Bytes.getKnownMinSize(), Alignment,
2183                                        false, nullptr, StackID);
2184   return getFrameIndex(FrameIdx, TLI->getFrameIndexTy(getDataLayout()));
2185 }
2186 
2187 SDValue SelectionDAG::CreateStackTemporary(EVT VT, unsigned minAlign) {
2188   Type *Ty = VT.getTypeForEVT(*getContext());
2189   Align StackAlign =
2190       std::max(getDataLayout().getPrefTypeAlign(Ty), Align(minAlign));
2191   return CreateStackTemporary(VT.getStoreSize(), StackAlign);
2192 }
2193 
2194 SDValue SelectionDAG::CreateStackTemporary(EVT VT1, EVT VT2) {
2195   TypeSize VT1Size = VT1.getStoreSize();
2196   TypeSize VT2Size = VT2.getStoreSize();
2197   assert(VT1Size.isScalable() == VT2Size.isScalable() &&
2198          "Don't know how to choose the maximum size when creating a stack "
2199          "temporary");
2200   TypeSize Bytes =
2201       VT1Size.getKnownMinSize() > VT2Size.getKnownMinSize() ? VT1Size : VT2Size;
2202 
2203   Type *Ty1 = VT1.getTypeForEVT(*getContext());
2204   Type *Ty2 = VT2.getTypeForEVT(*getContext());
2205   const DataLayout &DL = getDataLayout();
2206   Align Align = std::max(DL.getPrefTypeAlign(Ty1), DL.getPrefTypeAlign(Ty2));
2207   return CreateStackTemporary(Bytes, Align);
2208 }
2209 
2210 SDValue SelectionDAG::FoldSetCC(EVT VT, SDValue N1, SDValue N2,
2211                                 ISD::CondCode Cond, const SDLoc &dl) {
2212   EVT OpVT = N1.getValueType();
2213 
2214   // These setcc operations always fold.
2215   switch (Cond) {
2216   default: break;
2217   case ISD::SETFALSE:
2218   case ISD::SETFALSE2: return getBoolConstant(false, dl, VT, OpVT);
2219   case ISD::SETTRUE:
2220   case ISD::SETTRUE2: return getBoolConstant(true, dl, VT, OpVT);
2221 
2222   case ISD::SETOEQ:
2223   case ISD::SETOGT:
2224   case ISD::SETOGE:
2225   case ISD::SETOLT:
2226   case ISD::SETOLE:
2227   case ISD::SETONE:
2228   case ISD::SETO:
2229   case ISD::SETUO:
2230   case ISD::SETUEQ:
2231   case ISD::SETUNE:
2232     assert(!OpVT.isInteger() && "Illegal setcc for integer!");
2233     break;
2234   }
2235 
2236   if (OpVT.isInteger()) {
2237     // For EQ and NE, we can always pick a value for the undef to make the
2238     // predicate pass or fail, so we can return undef.
2239     // Matches behavior in llvm::ConstantFoldCompareInstruction.
2240     // icmp eq/ne X, undef -> undef.
2241     if ((N1.isUndef() || N2.isUndef()) &&
2242         (Cond == ISD::SETEQ || Cond == ISD::SETNE))
2243       return getUNDEF(VT);
2244 
2245     // If both operands are undef, we can return undef for int comparison.
2246     // icmp undef, undef -> undef.
2247     if (N1.isUndef() && N2.isUndef())
2248       return getUNDEF(VT);
2249 
2250     // icmp X, X -> true/false
2251     // icmp X, undef -> true/false because undef could be X.
2252     if (N1 == N2)
2253       return getBoolConstant(ISD::isTrueWhenEqual(Cond), dl, VT, OpVT);
2254   }
2255 
2256   if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2)) {
2257     const APInt &C2 = N2C->getAPIntValue();
2258     if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1)) {
2259       const APInt &C1 = N1C->getAPIntValue();
2260 
2261       switch (Cond) {
2262       default: llvm_unreachable("Unknown integer setcc!");
2263       case ISD::SETEQ:  return getBoolConstant(C1 == C2, dl, VT, OpVT);
2264       case ISD::SETNE:  return getBoolConstant(C1 != C2, dl, VT, OpVT);
2265       case ISD::SETULT: return getBoolConstant(C1.ult(C2), dl, VT, OpVT);
2266       case ISD::SETUGT: return getBoolConstant(C1.ugt(C2), dl, VT, OpVT);
2267       case ISD::SETULE: return getBoolConstant(C1.ule(C2), dl, VT, OpVT);
2268       case ISD::SETUGE: return getBoolConstant(C1.uge(C2), dl, VT, OpVT);
2269       case ISD::SETLT:  return getBoolConstant(C1.slt(C2), dl, VT, OpVT);
2270       case ISD::SETGT:  return getBoolConstant(C1.sgt(C2), dl, VT, OpVT);
2271       case ISD::SETLE:  return getBoolConstant(C1.sle(C2), dl, VT, OpVT);
2272       case ISD::SETGE:  return getBoolConstant(C1.sge(C2), dl, VT, OpVT);
2273       }
2274     }
2275   }
2276 
2277   auto *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
2278   auto *N2CFP = dyn_cast<ConstantFPSDNode>(N2);
2279 
2280   if (N1CFP && N2CFP) {
2281     APFloat::cmpResult R = N1CFP->getValueAPF().compare(N2CFP->getValueAPF());
2282     switch (Cond) {
2283     default: break;
2284     case ISD::SETEQ:  if (R==APFloat::cmpUnordered)
2285                         return getUNDEF(VT);
2286                       LLVM_FALLTHROUGH;
2287     case ISD::SETOEQ: return getBoolConstant(R==APFloat::cmpEqual, dl, VT,
2288                                              OpVT);
2289     case ISD::SETNE:  if (R==APFloat::cmpUnordered)
2290                         return getUNDEF(VT);
2291                       LLVM_FALLTHROUGH;
2292     case ISD::SETONE: return getBoolConstant(R==APFloat::cmpGreaterThan ||
2293                                              R==APFloat::cmpLessThan, dl, VT,
2294                                              OpVT);
2295     case ISD::SETLT:  if (R==APFloat::cmpUnordered)
2296                         return getUNDEF(VT);
2297                       LLVM_FALLTHROUGH;
2298     case ISD::SETOLT: return getBoolConstant(R==APFloat::cmpLessThan, dl, VT,
2299                                              OpVT);
2300     case ISD::SETGT:  if (R==APFloat::cmpUnordered)
2301                         return getUNDEF(VT);
2302                       LLVM_FALLTHROUGH;
2303     case ISD::SETOGT: return getBoolConstant(R==APFloat::cmpGreaterThan, dl,
2304                                              VT, OpVT);
2305     case ISD::SETLE:  if (R==APFloat::cmpUnordered)
2306                         return getUNDEF(VT);
2307                       LLVM_FALLTHROUGH;
2308     case ISD::SETOLE: return getBoolConstant(R==APFloat::cmpLessThan ||
2309                                              R==APFloat::cmpEqual, dl, VT,
2310                                              OpVT);
2311     case ISD::SETGE:  if (R==APFloat::cmpUnordered)
2312                         return getUNDEF(VT);
2313                       LLVM_FALLTHROUGH;
2314     case ISD::SETOGE: return getBoolConstant(R==APFloat::cmpGreaterThan ||
2315                                          R==APFloat::cmpEqual, dl, VT, OpVT);
2316     case ISD::SETO:   return getBoolConstant(R!=APFloat::cmpUnordered, dl, VT,
2317                                              OpVT);
2318     case ISD::SETUO:  return getBoolConstant(R==APFloat::cmpUnordered, dl, VT,
2319                                              OpVT);
2320     case ISD::SETUEQ: return getBoolConstant(R==APFloat::cmpUnordered ||
2321                                              R==APFloat::cmpEqual, dl, VT,
2322                                              OpVT);
2323     case ISD::SETUNE: return getBoolConstant(R!=APFloat::cmpEqual, dl, VT,
2324                                              OpVT);
2325     case ISD::SETULT: return getBoolConstant(R==APFloat::cmpUnordered ||
2326                                              R==APFloat::cmpLessThan, dl, VT,
2327                                              OpVT);
2328     case ISD::SETUGT: return getBoolConstant(R==APFloat::cmpGreaterThan ||
2329                                              R==APFloat::cmpUnordered, dl, VT,
2330                                              OpVT);
2331     case ISD::SETULE: return getBoolConstant(R!=APFloat::cmpGreaterThan, dl,
2332                                              VT, OpVT);
2333     case ISD::SETUGE: return getBoolConstant(R!=APFloat::cmpLessThan, dl, VT,
2334                                              OpVT);
2335     }
2336   } else if (N1CFP && OpVT.isSimple() && !N2.isUndef()) {
2337     // Ensure that the constant occurs on the RHS.
2338     ISD::CondCode SwappedCond = ISD::getSetCCSwappedOperands(Cond);
2339     if (!TLI->isCondCodeLegal(SwappedCond, OpVT.getSimpleVT()))
2340       return SDValue();
2341     return getSetCC(dl, VT, N2, N1, SwappedCond);
2342   } else if ((N2CFP && N2CFP->getValueAPF().isNaN()) ||
2343              (OpVT.isFloatingPoint() && (N1.isUndef() || N2.isUndef()))) {
2344     // If an operand is known to be a nan (or undef that could be a nan), we can
2345     // fold it.
2346     // Choosing NaN for the undef will always make unordered comparison succeed
2347     // and ordered comparison fails.
2348     // Matches behavior in llvm::ConstantFoldCompareInstruction.
2349     switch (ISD::getUnorderedFlavor(Cond)) {
2350     default:
2351       llvm_unreachable("Unknown flavor!");
2352     case 0: // Known false.
2353       return getBoolConstant(false, dl, VT, OpVT);
2354     case 1: // Known true.
2355       return getBoolConstant(true, dl, VT, OpVT);
2356     case 2: // Undefined.
2357       return getUNDEF(VT);
2358     }
2359   }
2360 
2361   // Could not fold it.
2362   return SDValue();
2363 }
2364 
2365 /// See if the specified operand can be simplified with the knowledge that only
2366 /// the bits specified by DemandedBits are used.
2367 /// TODO: really we should be making this into the DAG equivalent of
2368 /// SimplifyMultipleUseDemandedBits and not generate any new nodes.
2369 SDValue SelectionDAG::GetDemandedBits(SDValue V, const APInt &DemandedBits) {
2370   EVT VT = V.getValueType();
2371 
2372   if (VT.isScalableVector())
2373     return SDValue();
2374 
2375   APInt DemandedElts = VT.isVector()
2376                            ? APInt::getAllOnesValue(VT.getVectorNumElements())
2377                            : APInt(1, 1);
2378   return GetDemandedBits(V, DemandedBits, DemandedElts);
2379 }
2380 
2381 /// See if the specified operand can be simplified with the knowledge that only
2382 /// the bits specified by DemandedBits are used in the elements specified by
2383 /// DemandedElts.
2384 /// TODO: really we should be making this into the DAG equivalent of
2385 /// SimplifyMultipleUseDemandedBits and not generate any new nodes.
2386 SDValue SelectionDAG::GetDemandedBits(SDValue V, const APInt &DemandedBits,
2387                                       const APInt &DemandedElts) {
2388   switch (V.getOpcode()) {
2389   default:
2390     return TLI->SimplifyMultipleUseDemandedBits(V, DemandedBits, DemandedElts,
2391                                                 *this, 0);
2392   case ISD::Constant: {
2393     const APInt &CVal = cast<ConstantSDNode>(V)->getAPIntValue();
2394     APInt NewVal = CVal & DemandedBits;
2395     if (NewVal != CVal)
2396       return getConstant(NewVal, SDLoc(V), V.getValueType());
2397     break;
2398   }
2399   case ISD::SRL:
2400     // Only look at single-use SRLs.
2401     if (!V.getNode()->hasOneUse())
2402       break;
2403     if (auto *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
2404       // See if we can recursively simplify the LHS.
2405       unsigned Amt = RHSC->getZExtValue();
2406 
2407       // Watch out for shift count overflow though.
2408       if (Amt >= DemandedBits.getBitWidth())
2409         break;
2410       APInt SrcDemandedBits = DemandedBits << Amt;
2411       if (SDValue SimplifyLHS =
2412               GetDemandedBits(V.getOperand(0), SrcDemandedBits))
2413         return getNode(ISD::SRL, SDLoc(V), V.getValueType(), SimplifyLHS,
2414                        V.getOperand(1));
2415     }
2416     break;
2417   }
2418   return SDValue();
2419 }
2420 
2421 /// SignBitIsZero - Return true if the sign bit of Op is known to be zero.  We
2422 /// use this predicate to simplify operations downstream.
2423 bool SelectionDAG::SignBitIsZero(SDValue Op, unsigned Depth) const {
2424   unsigned BitWidth = Op.getScalarValueSizeInBits();
2425   return MaskedValueIsZero(Op, APInt::getSignMask(BitWidth), Depth);
2426 }
2427 
2428 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero.  We use
2429 /// this predicate to simplify operations downstream.  Mask is known to be zero
2430 /// for bits that V cannot have.
2431 bool SelectionDAG::MaskedValueIsZero(SDValue V, const APInt &Mask,
2432                                      unsigned Depth) const {
2433   return Mask.isSubsetOf(computeKnownBits(V, Depth).Zero);
2434 }
2435 
2436 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero in
2437 /// DemandedElts.  We use this predicate to simplify operations downstream.
2438 /// Mask is known to be zero for bits that V cannot have.
2439 bool SelectionDAG::MaskedValueIsZero(SDValue V, const APInt &Mask,
2440                                      const APInt &DemandedElts,
2441                                      unsigned Depth) const {
2442   return Mask.isSubsetOf(computeKnownBits(V, DemandedElts, Depth).Zero);
2443 }
2444 
2445 /// MaskedValueIsAllOnes - Return true if '(Op & Mask) == Mask'.
2446 bool SelectionDAG::MaskedValueIsAllOnes(SDValue V, const APInt &Mask,
2447                                         unsigned Depth) const {
2448   return Mask.isSubsetOf(computeKnownBits(V, Depth).One);
2449 }
2450 
2451 /// isSplatValue - Return true if the vector V has the same value
2452 /// across all DemandedElts. For scalable vectors it does not make
2453 /// sense to specify which elements are demanded or undefined, therefore
2454 /// they are simply ignored.
2455 bool SelectionDAG::isSplatValue(SDValue V, const APInt &DemandedElts,
2456                                 APInt &UndefElts, unsigned Depth) {
2457   EVT VT = V.getValueType();
2458   assert(VT.isVector() && "Vector type expected");
2459 
2460   if (!VT.isScalableVector() && !DemandedElts)
2461     return false; // No demanded elts, better to assume we don't know anything.
2462 
2463   if (Depth >= MaxRecursionDepth)
2464     return false; // Limit search depth.
2465 
2466   // Deal with some common cases here that work for both fixed and scalable
2467   // vector types.
2468   switch (V.getOpcode()) {
2469   case ISD::SPLAT_VECTOR:
2470     UndefElts = V.getOperand(0).isUndef()
2471                     ? APInt::getAllOnesValue(DemandedElts.getBitWidth())
2472                     : APInt(DemandedElts.getBitWidth(), 0);
2473     return true;
2474   case ISD::ADD:
2475   case ISD::SUB:
2476   case ISD::AND:
2477   case ISD::XOR:
2478   case ISD::OR: {
2479     APInt UndefLHS, UndefRHS;
2480     SDValue LHS = V.getOperand(0);
2481     SDValue RHS = V.getOperand(1);
2482     if (isSplatValue(LHS, DemandedElts, UndefLHS, Depth + 1) &&
2483         isSplatValue(RHS, DemandedElts, UndefRHS, Depth + 1)) {
2484       UndefElts = UndefLHS | UndefRHS;
2485       return true;
2486     }
2487     return false;
2488   }
2489   case ISD::ABS:
2490   case ISD::TRUNCATE:
2491   case ISD::SIGN_EXTEND:
2492   case ISD::ZERO_EXTEND:
2493     return isSplatValue(V.getOperand(0), DemandedElts, UndefElts, Depth + 1);
2494   }
2495 
2496   // We don't support other cases than those above for scalable vectors at
2497   // the moment.
2498   if (VT.isScalableVector())
2499     return false;
2500 
2501   unsigned NumElts = VT.getVectorNumElements();
2502   assert(NumElts == DemandedElts.getBitWidth() && "Vector size mismatch");
2503   UndefElts = APInt::getNullValue(NumElts);
2504 
2505   switch (V.getOpcode()) {
2506   case ISD::BUILD_VECTOR: {
2507     SDValue Scl;
2508     for (unsigned i = 0; i != NumElts; ++i) {
2509       SDValue Op = V.getOperand(i);
2510       if (Op.isUndef()) {
2511         UndefElts.setBit(i);
2512         continue;
2513       }
2514       if (!DemandedElts[i])
2515         continue;
2516       if (Scl && Scl != Op)
2517         return false;
2518       Scl = Op;
2519     }
2520     return true;
2521   }
2522   case ISD::VECTOR_SHUFFLE: {
2523     // Check if this is a shuffle node doing a splat.
2524     // TODO: Do we need to handle shuffle(splat, undef, mask)?
2525     int SplatIndex = -1;
2526     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(V)->getMask();
2527     for (int i = 0; i != (int)NumElts; ++i) {
2528       int M = Mask[i];
2529       if (M < 0) {
2530         UndefElts.setBit(i);
2531         continue;
2532       }
2533       if (!DemandedElts[i])
2534         continue;
2535       if (0 <= SplatIndex && SplatIndex != M)
2536         return false;
2537       SplatIndex = M;
2538     }
2539     return true;
2540   }
2541   case ISD::EXTRACT_SUBVECTOR: {
2542     // Offset the demanded elts by the subvector index.
2543     SDValue Src = V.getOperand(0);
2544     // We don't support scalable vectors at the moment.
2545     if (Src.getValueType().isScalableVector())
2546       return false;
2547     uint64_t Idx = V.getConstantOperandVal(1);
2548     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
2549     APInt UndefSrcElts;
2550     APInt DemandedSrcElts = DemandedElts.zextOrSelf(NumSrcElts).shl(Idx);
2551     if (isSplatValue(Src, DemandedSrcElts, UndefSrcElts, Depth + 1)) {
2552       UndefElts = UndefSrcElts.extractBits(NumElts, Idx);
2553       return true;
2554     }
2555     break;
2556   }
2557   }
2558 
2559   return false;
2560 }
2561 
2562 /// Helper wrapper to main isSplatValue function.
2563 bool SelectionDAG::isSplatValue(SDValue V, bool AllowUndefs) {
2564   EVT VT = V.getValueType();
2565   assert(VT.isVector() && "Vector type expected");
2566 
2567   APInt UndefElts;
2568   APInt DemandedElts;
2569 
2570   // For now we don't support this with scalable vectors.
2571   if (!VT.isScalableVector())
2572     DemandedElts = APInt::getAllOnesValue(VT.getVectorNumElements());
2573   return isSplatValue(V, DemandedElts, UndefElts) &&
2574          (AllowUndefs || !UndefElts);
2575 }
2576 
2577 SDValue SelectionDAG::getSplatSourceVector(SDValue V, int &SplatIdx) {
2578   V = peekThroughExtractSubvectors(V);
2579 
2580   EVT VT = V.getValueType();
2581   unsigned Opcode = V.getOpcode();
2582   switch (Opcode) {
2583   default: {
2584     APInt UndefElts;
2585     APInt DemandedElts;
2586 
2587     if (!VT.isScalableVector())
2588       DemandedElts = APInt::getAllOnesValue(VT.getVectorNumElements());
2589 
2590     if (isSplatValue(V, DemandedElts, UndefElts)) {
2591       if (VT.isScalableVector()) {
2592         // DemandedElts and UndefElts are ignored for scalable vectors, since
2593         // the only supported cases are SPLAT_VECTOR nodes.
2594         SplatIdx = 0;
2595       } else {
2596         // Handle case where all demanded elements are UNDEF.
2597         if (DemandedElts.isSubsetOf(UndefElts)) {
2598           SplatIdx = 0;
2599           return getUNDEF(VT);
2600         }
2601         SplatIdx = (UndefElts & DemandedElts).countTrailingOnes();
2602       }
2603       return V;
2604     }
2605     break;
2606   }
2607   case ISD::SPLAT_VECTOR:
2608     SplatIdx = 0;
2609     return V;
2610   case ISD::VECTOR_SHUFFLE: {
2611     if (VT.isScalableVector())
2612       return SDValue();
2613 
2614     // Check if this is a shuffle node doing a splat.
2615     // TODO - remove this and rely purely on SelectionDAG::isSplatValue,
2616     // getTargetVShiftNode currently struggles without the splat source.
2617     auto *SVN = cast<ShuffleVectorSDNode>(V);
2618     if (!SVN->isSplat())
2619       break;
2620     int Idx = SVN->getSplatIndex();
2621     int NumElts = V.getValueType().getVectorNumElements();
2622     SplatIdx = Idx % NumElts;
2623     return V.getOperand(Idx / NumElts);
2624   }
2625   }
2626 
2627   return SDValue();
2628 }
2629 
2630 SDValue SelectionDAG::getSplatValue(SDValue V) {
2631   int SplatIdx;
2632   if (SDValue SrcVector = getSplatSourceVector(V, SplatIdx))
2633     return getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(V),
2634                    SrcVector.getValueType().getScalarType(), SrcVector,
2635                    getVectorIdxConstant(SplatIdx, SDLoc(V)));
2636   return SDValue();
2637 }
2638 
2639 const APInt *
2640 SelectionDAG::getValidShiftAmountConstant(SDValue V,
2641                                           const APInt &DemandedElts) const {
2642   assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL ||
2643           V.getOpcode() == ISD::SRA) &&
2644          "Unknown shift node");
2645   unsigned BitWidth = V.getScalarValueSizeInBits();
2646   if (ConstantSDNode *SA = isConstOrConstSplat(V.getOperand(1), DemandedElts)) {
2647     // Shifting more than the bitwidth is not valid.
2648     const APInt &ShAmt = SA->getAPIntValue();
2649     if (ShAmt.ult(BitWidth))
2650       return &ShAmt;
2651   }
2652   return nullptr;
2653 }
2654 
2655 const APInt *SelectionDAG::getValidMinimumShiftAmountConstant(
2656     SDValue V, const APInt &DemandedElts) const {
2657   assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL ||
2658           V.getOpcode() == ISD::SRA) &&
2659          "Unknown shift node");
2660   if (const APInt *ValidAmt = getValidShiftAmountConstant(V, DemandedElts))
2661     return ValidAmt;
2662   unsigned BitWidth = V.getScalarValueSizeInBits();
2663   auto *BV = dyn_cast<BuildVectorSDNode>(V.getOperand(1));
2664   if (!BV)
2665     return nullptr;
2666   const APInt *MinShAmt = nullptr;
2667   for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
2668     if (!DemandedElts[i])
2669       continue;
2670     auto *SA = dyn_cast<ConstantSDNode>(BV->getOperand(i));
2671     if (!SA)
2672       return nullptr;
2673     // Shifting more than the bitwidth is not valid.
2674     const APInt &ShAmt = SA->getAPIntValue();
2675     if (ShAmt.uge(BitWidth))
2676       return nullptr;
2677     if (MinShAmt && MinShAmt->ule(ShAmt))
2678       continue;
2679     MinShAmt = &ShAmt;
2680   }
2681   return MinShAmt;
2682 }
2683 
2684 const APInt *SelectionDAG::getValidMaximumShiftAmountConstant(
2685     SDValue V, const APInt &DemandedElts) const {
2686   assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL ||
2687           V.getOpcode() == ISD::SRA) &&
2688          "Unknown shift node");
2689   if (const APInt *ValidAmt = getValidShiftAmountConstant(V, DemandedElts))
2690     return ValidAmt;
2691   unsigned BitWidth = V.getScalarValueSizeInBits();
2692   auto *BV = dyn_cast<BuildVectorSDNode>(V.getOperand(1));
2693   if (!BV)
2694     return nullptr;
2695   const APInt *MaxShAmt = nullptr;
2696   for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
2697     if (!DemandedElts[i])
2698       continue;
2699     auto *SA = dyn_cast<ConstantSDNode>(BV->getOperand(i));
2700     if (!SA)
2701       return nullptr;
2702     // Shifting more than the bitwidth is not valid.
2703     const APInt &ShAmt = SA->getAPIntValue();
2704     if (ShAmt.uge(BitWidth))
2705       return nullptr;
2706     if (MaxShAmt && MaxShAmt->uge(ShAmt))
2707       continue;
2708     MaxShAmt = &ShAmt;
2709   }
2710   return MaxShAmt;
2711 }
2712 
2713 /// Determine which bits of Op are known to be either zero or one and return
2714 /// them in Known. For vectors, the known bits are those that are shared by
2715 /// every vector element.
2716 KnownBits SelectionDAG::computeKnownBits(SDValue Op, unsigned Depth) const {
2717   EVT VT = Op.getValueType();
2718 
2719   // TOOD: Until we have a plan for how to represent demanded elements for
2720   // scalable vectors, we can just bail out for now.
2721   if (Op.getValueType().isScalableVector()) {
2722     unsigned BitWidth = Op.getScalarValueSizeInBits();
2723     return KnownBits(BitWidth);
2724   }
2725 
2726   APInt DemandedElts = VT.isVector()
2727                            ? APInt::getAllOnesValue(VT.getVectorNumElements())
2728                            : APInt(1, 1);
2729   return computeKnownBits(Op, DemandedElts, Depth);
2730 }
2731 
2732 /// Determine which bits of Op are known to be either zero or one and return
2733 /// them in Known. The DemandedElts argument allows us to only collect the known
2734 /// bits that are shared by the requested vector elements.
2735 KnownBits SelectionDAG::computeKnownBits(SDValue Op, const APInt &DemandedElts,
2736                                          unsigned Depth) const {
2737   unsigned BitWidth = Op.getScalarValueSizeInBits();
2738 
2739   KnownBits Known(BitWidth);   // Don't know anything.
2740 
2741   // TOOD: Until we have a plan for how to represent demanded elements for
2742   // scalable vectors, we can just bail out for now.
2743   if (Op.getValueType().isScalableVector())
2744     return Known;
2745 
2746   if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
2747     // We know all of the bits for a constant!
2748     return KnownBits::makeConstant(C->getAPIntValue());
2749   }
2750   if (auto *C = dyn_cast<ConstantFPSDNode>(Op)) {
2751     // We know all of the bits for a constant fp!
2752     return KnownBits::makeConstant(C->getValueAPF().bitcastToAPInt());
2753   }
2754 
2755   if (Depth >= MaxRecursionDepth)
2756     return Known;  // Limit search depth.
2757 
2758   KnownBits Known2;
2759   unsigned NumElts = DemandedElts.getBitWidth();
2760   assert((!Op.getValueType().isVector() ||
2761           NumElts == Op.getValueType().getVectorNumElements()) &&
2762          "Unexpected vector size");
2763 
2764   if (!DemandedElts)
2765     return Known;  // No demanded elts, better to assume we don't know anything.
2766 
2767   unsigned Opcode = Op.getOpcode();
2768   switch (Opcode) {
2769   case ISD::BUILD_VECTOR:
2770     // Collect the known bits that are shared by every demanded vector element.
2771     Known.Zero.setAllBits(); Known.One.setAllBits();
2772     for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
2773       if (!DemandedElts[i])
2774         continue;
2775 
2776       SDValue SrcOp = Op.getOperand(i);
2777       Known2 = computeKnownBits(SrcOp, Depth + 1);
2778 
2779       // BUILD_VECTOR can implicitly truncate sources, we must handle this.
2780       if (SrcOp.getValueSizeInBits() != BitWidth) {
2781         assert(SrcOp.getValueSizeInBits() > BitWidth &&
2782                "Expected BUILD_VECTOR implicit truncation");
2783         Known2 = Known2.trunc(BitWidth);
2784       }
2785 
2786       // Known bits are the values that are shared by every demanded element.
2787       Known = KnownBits::commonBits(Known, Known2);
2788 
2789       // If we don't know any bits, early out.
2790       if (Known.isUnknown())
2791         break;
2792     }
2793     break;
2794   case ISD::VECTOR_SHUFFLE: {
2795     // Collect the known bits that are shared by every vector element referenced
2796     // by the shuffle.
2797     APInt DemandedLHS(NumElts, 0), DemandedRHS(NumElts, 0);
2798     Known.Zero.setAllBits(); Known.One.setAllBits();
2799     const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op);
2800     assert(NumElts == SVN->getMask().size() && "Unexpected vector size");
2801     for (unsigned i = 0; i != NumElts; ++i) {
2802       if (!DemandedElts[i])
2803         continue;
2804 
2805       int M = SVN->getMaskElt(i);
2806       if (M < 0) {
2807         // For UNDEF elements, we don't know anything about the common state of
2808         // the shuffle result.
2809         Known.resetAll();
2810         DemandedLHS.clearAllBits();
2811         DemandedRHS.clearAllBits();
2812         break;
2813       }
2814 
2815       if ((unsigned)M < NumElts)
2816         DemandedLHS.setBit((unsigned)M % NumElts);
2817       else
2818         DemandedRHS.setBit((unsigned)M % NumElts);
2819     }
2820     // Known bits are the values that are shared by every demanded element.
2821     if (!!DemandedLHS) {
2822       SDValue LHS = Op.getOperand(0);
2823       Known2 = computeKnownBits(LHS, DemandedLHS, Depth + 1);
2824       Known = KnownBits::commonBits(Known, Known2);
2825     }
2826     // If we don't know any bits, early out.
2827     if (Known.isUnknown())
2828       break;
2829     if (!!DemandedRHS) {
2830       SDValue RHS = Op.getOperand(1);
2831       Known2 = computeKnownBits(RHS, DemandedRHS, Depth + 1);
2832       Known = KnownBits::commonBits(Known, Known2);
2833     }
2834     break;
2835   }
2836   case ISD::CONCAT_VECTORS: {
2837     // Split DemandedElts and test each of the demanded subvectors.
2838     Known.Zero.setAllBits(); Known.One.setAllBits();
2839     EVT SubVectorVT = Op.getOperand(0).getValueType();
2840     unsigned NumSubVectorElts = SubVectorVT.getVectorNumElements();
2841     unsigned NumSubVectors = Op.getNumOperands();
2842     for (unsigned i = 0; i != NumSubVectors; ++i) {
2843       APInt DemandedSub = DemandedElts.lshr(i * NumSubVectorElts);
2844       DemandedSub = DemandedSub.trunc(NumSubVectorElts);
2845       if (!!DemandedSub) {
2846         SDValue Sub = Op.getOperand(i);
2847         Known2 = computeKnownBits(Sub, DemandedSub, Depth + 1);
2848         Known = KnownBits::commonBits(Known, Known2);
2849       }
2850       // If we don't know any bits, early out.
2851       if (Known.isUnknown())
2852         break;
2853     }
2854     break;
2855   }
2856   case ISD::INSERT_SUBVECTOR: {
2857     // Demand any elements from the subvector and the remainder from the src its
2858     // inserted into.
2859     SDValue Src = Op.getOperand(0);
2860     SDValue Sub = Op.getOperand(1);
2861     uint64_t Idx = Op.getConstantOperandVal(2);
2862     unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
2863     APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
2864     APInt DemandedSrcElts = DemandedElts;
2865     DemandedSrcElts.insertBits(APInt::getNullValue(NumSubElts), Idx);
2866 
2867     Known.One.setAllBits();
2868     Known.Zero.setAllBits();
2869     if (!!DemandedSubElts) {
2870       Known = computeKnownBits(Sub, DemandedSubElts, Depth + 1);
2871       if (Known.isUnknown())
2872         break; // early-out.
2873     }
2874     if (!!DemandedSrcElts) {
2875       Known2 = computeKnownBits(Src, DemandedSrcElts, Depth + 1);
2876       Known = KnownBits::commonBits(Known, Known2);
2877     }
2878     break;
2879   }
2880   case ISD::EXTRACT_SUBVECTOR: {
2881     // Offset the demanded elts by the subvector index.
2882     SDValue Src = Op.getOperand(0);
2883     // Bail until we can represent demanded elements for scalable vectors.
2884     if (Src.getValueType().isScalableVector())
2885       break;
2886     uint64_t Idx = Op.getConstantOperandVal(1);
2887     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
2888     APInt DemandedSrcElts = DemandedElts.zextOrSelf(NumSrcElts).shl(Idx);
2889     Known = computeKnownBits(Src, DemandedSrcElts, Depth + 1);
2890     break;
2891   }
2892   case ISD::SCALAR_TO_VECTOR: {
2893     // We know about scalar_to_vector as much as we know about it source,
2894     // which becomes the first element of otherwise unknown vector.
2895     if (DemandedElts != 1)
2896       break;
2897 
2898     SDValue N0 = Op.getOperand(0);
2899     Known = computeKnownBits(N0, Depth + 1);
2900     if (N0.getValueSizeInBits() != BitWidth)
2901       Known = Known.trunc(BitWidth);
2902 
2903     break;
2904   }
2905   case ISD::BITCAST: {
2906     SDValue N0 = Op.getOperand(0);
2907     EVT SubVT = N0.getValueType();
2908     unsigned SubBitWidth = SubVT.getScalarSizeInBits();
2909 
2910     // Ignore bitcasts from unsupported types.
2911     if (!(SubVT.isInteger() || SubVT.isFloatingPoint()))
2912       break;
2913 
2914     // Fast handling of 'identity' bitcasts.
2915     if (BitWidth == SubBitWidth) {
2916       Known = computeKnownBits(N0, DemandedElts, Depth + 1);
2917       break;
2918     }
2919 
2920     bool IsLE = getDataLayout().isLittleEndian();
2921 
2922     // Bitcast 'small element' vector to 'large element' scalar/vector.
2923     if ((BitWidth % SubBitWidth) == 0) {
2924       assert(N0.getValueType().isVector() && "Expected bitcast from vector");
2925 
2926       // Collect known bits for the (larger) output by collecting the known
2927       // bits from each set of sub elements and shift these into place.
2928       // We need to separately call computeKnownBits for each set of
2929       // sub elements as the knownbits for each is likely to be different.
2930       unsigned SubScale = BitWidth / SubBitWidth;
2931       APInt SubDemandedElts(NumElts * SubScale, 0);
2932       for (unsigned i = 0; i != NumElts; ++i)
2933         if (DemandedElts[i])
2934           SubDemandedElts.setBit(i * SubScale);
2935 
2936       for (unsigned i = 0; i != SubScale; ++i) {
2937         Known2 = computeKnownBits(N0, SubDemandedElts.shl(i),
2938                          Depth + 1);
2939         unsigned Shifts = IsLE ? i : SubScale - 1 - i;
2940         Known.One |= Known2.One.zext(BitWidth).shl(SubBitWidth * Shifts);
2941         Known.Zero |= Known2.Zero.zext(BitWidth).shl(SubBitWidth * Shifts);
2942       }
2943     }
2944 
2945     // Bitcast 'large element' scalar/vector to 'small element' vector.
2946     if ((SubBitWidth % BitWidth) == 0) {
2947       assert(Op.getValueType().isVector() && "Expected bitcast to vector");
2948 
2949       // Collect known bits for the (smaller) output by collecting the known
2950       // bits from the overlapping larger input elements and extracting the
2951       // sub sections we actually care about.
2952       unsigned SubScale = SubBitWidth / BitWidth;
2953       APInt SubDemandedElts(NumElts / SubScale, 0);
2954       for (unsigned i = 0; i != NumElts; ++i)
2955         if (DemandedElts[i])
2956           SubDemandedElts.setBit(i / SubScale);
2957 
2958       Known2 = computeKnownBits(N0, SubDemandedElts, Depth + 1);
2959 
2960       Known.Zero.setAllBits(); Known.One.setAllBits();
2961       for (unsigned i = 0; i != NumElts; ++i)
2962         if (DemandedElts[i]) {
2963           unsigned Shifts = IsLE ? i : NumElts - 1 - i;
2964           unsigned Offset = (Shifts % SubScale) * BitWidth;
2965           Known.One &= Known2.One.lshr(Offset).trunc(BitWidth);
2966           Known.Zero &= Known2.Zero.lshr(Offset).trunc(BitWidth);
2967           // If we don't know any bits, early out.
2968           if (Known.isUnknown())
2969             break;
2970         }
2971     }
2972     break;
2973   }
2974   case ISD::AND:
2975     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
2976     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
2977 
2978     Known &= Known2;
2979     break;
2980   case ISD::OR:
2981     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
2982     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
2983 
2984     Known |= Known2;
2985     break;
2986   case ISD::XOR:
2987     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
2988     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
2989 
2990     Known ^= Known2;
2991     break;
2992   case ISD::MUL: {
2993     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
2994     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
2995     Known = KnownBits::mul(Known, Known2);
2996     break;
2997   }
2998   case ISD::MULHU: {
2999     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3000     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3001     Known = KnownBits::mulhu(Known, Known2);
3002     break;
3003   }
3004   case ISD::MULHS: {
3005     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3006     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3007     Known = KnownBits::mulhs(Known, Known2);
3008     break;
3009   }
3010   case ISD::UMUL_LOHI: {
3011     assert((Op.getResNo() == 0 || Op.getResNo() == 1) && "Unknown result");
3012     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3013     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3014     if (Op.getResNo() == 0)
3015       Known = KnownBits::mul(Known, Known2);
3016     else
3017       Known = KnownBits::mulhu(Known, Known2);
3018     break;
3019   }
3020   case ISD::SMUL_LOHI: {
3021     assert((Op.getResNo() == 0 || Op.getResNo() == 1) && "Unknown result");
3022     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3023     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3024     if (Op.getResNo() == 0)
3025       Known = KnownBits::mul(Known, Known2);
3026     else
3027       Known = KnownBits::mulhs(Known, Known2);
3028     break;
3029   }
3030   case ISD::UDIV: {
3031     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3032     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3033     Known = KnownBits::udiv(Known, Known2);
3034     break;
3035   }
3036   case ISD::SELECT:
3037   case ISD::VSELECT:
3038     Known = computeKnownBits(Op.getOperand(2), DemandedElts, Depth+1);
3039     // If we don't know any bits, early out.
3040     if (Known.isUnknown())
3041       break;
3042     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth+1);
3043 
3044     // Only known if known in both the LHS and RHS.
3045     Known = KnownBits::commonBits(Known, Known2);
3046     break;
3047   case ISD::SELECT_CC:
3048     Known = computeKnownBits(Op.getOperand(3), DemandedElts, Depth+1);
3049     // If we don't know any bits, early out.
3050     if (Known.isUnknown())
3051       break;
3052     Known2 = computeKnownBits(Op.getOperand(2), DemandedElts, Depth+1);
3053 
3054     // Only known if known in both the LHS and RHS.
3055     Known = KnownBits::commonBits(Known, Known2);
3056     break;
3057   case ISD::SMULO:
3058   case ISD::UMULO:
3059   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
3060     if (Op.getResNo() != 1)
3061       break;
3062     // The boolean result conforms to getBooleanContents.
3063     // If we know the result of a setcc has the top bits zero, use this info.
3064     // We know that we have an integer-based boolean since these operations
3065     // are only available for integer.
3066     if (TLI->getBooleanContents(Op.getValueType().isVector(), false) ==
3067             TargetLowering::ZeroOrOneBooleanContent &&
3068         BitWidth > 1)
3069       Known.Zero.setBitsFrom(1);
3070     break;
3071   case ISD::SETCC:
3072   case ISD::STRICT_FSETCC:
3073   case ISD::STRICT_FSETCCS: {
3074     unsigned OpNo = Op->isStrictFPOpcode() ? 1 : 0;
3075     // If we know the result of a setcc has the top bits zero, use this info.
3076     if (TLI->getBooleanContents(Op.getOperand(OpNo).getValueType()) ==
3077             TargetLowering::ZeroOrOneBooleanContent &&
3078         BitWidth > 1)
3079       Known.Zero.setBitsFrom(1);
3080     break;
3081   }
3082   case ISD::SHL:
3083     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3084     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3085     Known = KnownBits::shl(Known, Known2);
3086 
3087     // Minimum shift low bits are known zero.
3088     if (const APInt *ShMinAmt =
3089             getValidMinimumShiftAmountConstant(Op, DemandedElts))
3090       Known.Zero.setLowBits(ShMinAmt->getZExtValue());
3091     break;
3092   case ISD::SRL:
3093     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3094     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3095     Known = KnownBits::lshr(Known, Known2);
3096 
3097     // Minimum shift high bits are known zero.
3098     if (const APInt *ShMinAmt =
3099             getValidMinimumShiftAmountConstant(Op, DemandedElts))
3100       Known.Zero.setHighBits(ShMinAmt->getZExtValue());
3101     break;
3102   case ISD::SRA:
3103     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3104     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3105     Known = KnownBits::ashr(Known, Known2);
3106     // TODO: Add minimum shift high known sign bits.
3107     break;
3108   case ISD::FSHL:
3109   case ISD::FSHR:
3110     if (ConstantSDNode *C = isConstOrConstSplat(Op.getOperand(2), DemandedElts)) {
3111       unsigned Amt = C->getAPIntValue().urem(BitWidth);
3112 
3113       // For fshl, 0-shift returns the 1st arg.
3114       // For fshr, 0-shift returns the 2nd arg.
3115       if (Amt == 0) {
3116         Known = computeKnownBits(Op.getOperand(Opcode == ISD::FSHL ? 0 : 1),
3117                                  DemandedElts, Depth + 1);
3118         break;
3119       }
3120 
3121       // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW)))
3122       // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW))
3123       Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3124       Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3125       if (Opcode == ISD::FSHL) {
3126         Known.One <<= Amt;
3127         Known.Zero <<= Amt;
3128         Known2.One.lshrInPlace(BitWidth - Amt);
3129         Known2.Zero.lshrInPlace(BitWidth - Amt);
3130       } else {
3131         Known.One <<= BitWidth - Amt;
3132         Known.Zero <<= BitWidth - Amt;
3133         Known2.One.lshrInPlace(Amt);
3134         Known2.Zero.lshrInPlace(Amt);
3135       }
3136       Known.One |= Known2.One;
3137       Known.Zero |= Known2.Zero;
3138     }
3139     break;
3140   case ISD::SIGN_EXTEND_INREG: {
3141     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3142     EVT EVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
3143     Known = Known.sextInReg(EVT.getScalarSizeInBits());
3144     break;
3145   }
3146   case ISD::CTTZ:
3147   case ISD::CTTZ_ZERO_UNDEF: {
3148     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3149     // If we have a known 1, its position is our upper bound.
3150     unsigned PossibleTZ = Known2.countMaxTrailingZeros();
3151     unsigned LowBits = Log2_32(PossibleTZ) + 1;
3152     Known.Zero.setBitsFrom(LowBits);
3153     break;
3154   }
3155   case ISD::CTLZ:
3156   case ISD::CTLZ_ZERO_UNDEF: {
3157     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3158     // If we have a known 1, its position is our upper bound.
3159     unsigned PossibleLZ = Known2.countMaxLeadingZeros();
3160     unsigned LowBits = Log2_32(PossibleLZ) + 1;
3161     Known.Zero.setBitsFrom(LowBits);
3162     break;
3163   }
3164   case ISD::CTPOP: {
3165     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3166     // If we know some of the bits are zero, they can't be one.
3167     unsigned PossibleOnes = Known2.countMaxPopulation();
3168     Known.Zero.setBitsFrom(Log2_32(PossibleOnes) + 1);
3169     break;
3170   }
3171   case ISD::PARITY: {
3172     // Parity returns 0 everywhere but the LSB.
3173     Known.Zero.setBitsFrom(1);
3174     break;
3175   }
3176   case ISD::LOAD: {
3177     LoadSDNode *LD = cast<LoadSDNode>(Op);
3178     const Constant *Cst = TLI->getTargetConstantFromLoad(LD);
3179     if (ISD::isNON_EXTLoad(LD) && Cst) {
3180       // Determine any common known bits from the loaded constant pool value.
3181       Type *CstTy = Cst->getType();
3182       if ((NumElts * BitWidth) == CstTy->getPrimitiveSizeInBits()) {
3183         // If its a vector splat, then we can (quickly) reuse the scalar path.
3184         // NOTE: We assume all elements match and none are UNDEF.
3185         if (CstTy->isVectorTy()) {
3186           if (const Constant *Splat = Cst->getSplatValue()) {
3187             Cst = Splat;
3188             CstTy = Cst->getType();
3189           }
3190         }
3191         // TODO - do we need to handle different bitwidths?
3192         if (CstTy->isVectorTy() && BitWidth == CstTy->getScalarSizeInBits()) {
3193           // Iterate across all vector elements finding common known bits.
3194           Known.One.setAllBits();
3195           Known.Zero.setAllBits();
3196           for (unsigned i = 0; i != NumElts; ++i) {
3197             if (!DemandedElts[i])
3198               continue;
3199             if (Constant *Elt = Cst->getAggregateElement(i)) {
3200               if (auto *CInt = dyn_cast<ConstantInt>(Elt)) {
3201                 const APInt &Value = CInt->getValue();
3202                 Known.One &= Value;
3203                 Known.Zero &= ~Value;
3204                 continue;
3205               }
3206               if (auto *CFP = dyn_cast<ConstantFP>(Elt)) {
3207                 APInt Value = CFP->getValueAPF().bitcastToAPInt();
3208                 Known.One &= Value;
3209                 Known.Zero &= ~Value;
3210                 continue;
3211               }
3212             }
3213             Known.One.clearAllBits();
3214             Known.Zero.clearAllBits();
3215             break;
3216           }
3217         } else if (BitWidth == CstTy->getPrimitiveSizeInBits()) {
3218           if (auto *CInt = dyn_cast<ConstantInt>(Cst)) {
3219             Known = KnownBits::makeConstant(CInt->getValue());
3220           } else if (auto *CFP = dyn_cast<ConstantFP>(Cst)) {
3221             Known =
3222                 KnownBits::makeConstant(CFP->getValueAPF().bitcastToAPInt());
3223           }
3224         }
3225       }
3226     } else if (ISD::isZEXTLoad(Op.getNode()) && Op.getResNo() == 0) {
3227       // If this is a ZEXTLoad and we are looking at the loaded value.
3228       EVT VT = LD->getMemoryVT();
3229       unsigned MemBits = VT.getScalarSizeInBits();
3230       Known.Zero.setBitsFrom(MemBits);
3231     } else if (const MDNode *Ranges = LD->getRanges()) {
3232       if (LD->getExtensionType() == ISD::NON_EXTLOAD)
3233         computeKnownBitsFromRangeMetadata(*Ranges, Known);
3234     }
3235     break;
3236   }
3237   case ISD::ZERO_EXTEND_VECTOR_INREG: {
3238     EVT InVT = Op.getOperand(0).getValueType();
3239     APInt InDemandedElts = DemandedElts.zextOrSelf(InVT.getVectorNumElements());
3240     Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1);
3241     Known = Known.zext(BitWidth);
3242     break;
3243   }
3244   case ISD::ZERO_EXTEND: {
3245     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3246     Known = Known.zext(BitWidth);
3247     break;
3248   }
3249   case ISD::SIGN_EXTEND_VECTOR_INREG: {
3250     EVT InVT = Op.getOperand(0).getValueType();
3251     APInt InDemandedElts = DemandedElts.zextOrSelf(InVT.getVectorNumElements());
3252     Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1);
3253     // If the sign bit is known to be zero or one, then sext will extend
3254     // it to the top bits, else it will just zext.
3255     Known = Known.sext(BitWidth);
3256     break;
3257   }
3258   case ISD::SIGN_EXTEND: {
3259     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3260     // If the sign bit is known to be zero or one, then sext will extend
3261     // it to the top bits, else it will just zext.
3262     Known = Known.sext(BitWidth);
3263     break;
3264   }
3265   case ISD::ANY_EXTEND_VECTOR_INREG: {
3266     EVT InVT = Op.getOperand(0).getValueType();
3267     APInt InDemandedElts = DemandedElts.zextOrSelf(InVT.getVectorNumElements());
3268     Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1);
3269     Known = Known.anyext(BitWidth);
3270     break;
3271   }
3272   case ISD::ANY_EXTEND: {
3273     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3274     Known = Known.anyext(BitWidth);
3275     break;
3276   }
3277   case ISD::TRUNCATE: {
3278     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3279     Known = Known.trunc(BitWidth);
3280     break;
3281   }
3282   case ISD::AssertZext: {
3283     EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
3284     APInt InMask = APInt::getLowBitsSet(BitWidth, VT.getSizeInBits());
3285     Known = computeKnownBits(Op.getOperand(0), Depth+1);
3286     Known.Zero |= (~InMask);
3287     Known.One  &= (~Known.Zero);
3288     break;
3289   }
3290   case ISD::AssertAlign: {
3291     unsigned LogOfAlign = Log2(cast<AssertAlignSDNode>(Op)->getAlign());
3292     assert(LogOfAlign != 0);
3293     // If a node is guaranteed to be aligned, set low zero bits accordingly as
3294     // well as clearing one bits.
3295     Known.Zero.setLowBits(LogOfAlign);
3296     Known.One.clearLowBits(LogOfAlign);
3297     break;
3298   }
3299   case ISD::FGETSIGN:
3300     // All bits are zero except the low bit.
3301     Known.Zero.setBitsFrom(1);
3302     break;
3303   case ISD::USUBO:
3304   case ISD::SSUBO:
3305     if (Op.getResNo() == 1) {
3306       // If we know the result of a setcc has the top bits zero, use this info.
3307       if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) ==
3308               TargetLowering::ZeroOrOneBooleanContent &&
3309           BitWidth > 1)
3310         Known.Zero.setBitsFrom(1);
3311       break;
3312     }
3313     LLVM_FALLTHROUGH;
3314   case ISD::SUB:
3315   case ISD::SUBC: {
3316     assert(Op.getResNo() == 0 &&
3317            "We only compute knownbits for the difference here.");
3318 
3319     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3320     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3321     Known = KnownBits::computeForAddSub(/* Add */ false, /* NSW */ false,
3322                                         Known, Known2);
3323     break;
3324   }
3325   case ISD::UADDO:
3326   case ISD::SADDO:
3327   case ISD::ADDCARRY:
3328     if (Op.getResNo() == 1) {
3329       // If we know the result of a setcc has the top bits zero, use this info.
3330       if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) ==
3331               TargetLowering::ZeroOrOneBooleanContent &&
3332           BitWidth > 1)
3333         Known.Zero.setBitsFrom(1);
3334       break;
3335     }
3336     LLVM_FALLTHROUGH;
3337   case ISD::ADD:
3338   case ISD::ADDC:
3339   case ISD::ADDE: {
3340     assert(Op.getResNo() == 0 && "We only compute knownbits for the sum here.");
3341 
3342     // With ADDE and ADDCARRY, a carry bit may be added in.
3343     KnownBits Carry(1);
3344     if (Opcode == ISD::ADDE)
3345       // Can't track carry from glue, set carry to unknown.
3346       Carry.resetAll();
3347     else if (Opcode == ISD::ADDCARRY)
3348       // TODO: Compute known bits for the carry operand. Not sure if it is worth
3349       // the trouble (how often will we find a known carry bit). And I haven't
3350       // tested this very much yet, but something like this might work:
3351       //   Carry = computeKnownBits(Op.getOperand(2), DemandedElts, Depth + 1);
3352       //   Carry = Carry.zextOrTrunc(1, false);
3353       Carry.resetAll();
3354     else
3355       Carry.setAllZero();
3356 
3357     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3358     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3359     Known = KnownBits::computeForAddCarry(Known, Known2, Carry);
3360     break;
3361   }
3362   case ISD::SREM: {
3363     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3364     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3365     Known = KnownBits::srem(Known, Known2);
3366     break;
3367   }
3368   case ISD::UREM: {
3369     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3370     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3371     Known = KnownBits::urem(Known, Known2);
3372     break;
3373   }
3374   case ISD::EXTRACT_ELEMENT: {
3375     Known = computeKnownBits(Op.getOperand(0), Depth+1);
3376     const unsigned Index = Op.getConstantOperandVal(1);
3377     const unsigned EltBitWidth = Op.getValueSizeInBits();
3378 
3379     // Remove low part of known bits mask
3380     Known.Zero = Known.Zero.getHiBits(Known.getBitWidth() - Index * EltBitWidth);
3381     Known.One = Known.One.getHiBits(Known.getBitWidth() - Index * EltBitWidth);
3382 
3383     // Remove high part of known bit mask
3384     Known = Known.trunc(EltBitWidth);
3385     break;
3386   }
3387   case ISD::EXTRACT_VECTOR_ELT: {
3388     SDValue InVec = Op.getOperand(0);
3389     SDValue EltNo = Op.getOperand(1);
3390     EVT VecVT = InVec.getValueType();
3391     // computeKnownBits not yet implemented for scalable vectors.
3392     if (VecVT.isScalableVector())
3393       break;
3394     const unsigned EltBitWidth = VecVT.getScalarSizeInBits();
3395     const unsigned NumSrcElts = VecVT.getVectorNumElements();
3396 
3397     // If BitWidth > EltBitWidth the value is anyext:ed. So we do not know
3398     // anything about the extended bits.
3399     if (BitWidth > EltBitWidth)
3400       Known = Known.trunc(EltBitWidth);
3401 
3402     // If we know the element index, just demand that vector element, else for
3403     // an unknown element index, ignore DemandedElts and demand them all.
3404     APInt DemandedSrcElts = APInt::getAllOnesValue(NumSrcElts);
3405     auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
3406     if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts))
3407       DemandedSrcElts =
3408           APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue());
3409 
3410     Known = computeKnownBits(InVec, DemandedSrcElts, Depth + 1);
3411     if (BitWidth > EltBitWidth)
3412       Known = Known.anyext(BitWidth);
3413     break;
3414   }
3415   case ISD::INSERT_VECTOR_ELT: {
3416     // If we know the element index, split the demand between the
3417     // source vector and the inserted element, otherwise assume we need
3418     // the original demanded vector elements and the value.
3419     SDValue InVec = Op.getOperand(0);
3420     SDValue InVal = Op.getOperand(1);
3421     SDValue EltNo = Op.getOperand(2);
3422     bool DemandedVal = true;
3423     APInt DemandedVecElts = DemandedElts;
3424     auto *CEltNo = dyn_cast<ConstantSDNode>(EltNo);
3425     if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) {
3426       unsigned EltIdx = CEltNo->getZExtValue();
3427       DemandedVal = !!DemandedElts[EltIdx];
3428       DemandedVecElts.clearBit(EltIdx);
3429     }
3430     Known.One.setAllBits();
3431     Known.Zero.setAllBits();
3432     if (DemandedVal) {
3433       Known2 = computeKnownBits(InVal, Depth + 1);
3434       Known = KnownBits::commonBits(Known, Known2.zextOrTrunc(BitWidth));
3435     }
3436     if (!!DemandedVecElts) {
3437       Known2 = computeKnownBits(InVec, DemandedVecElts, Depth + 1);
3438       Known = KnownBits::commonBits(Known, Known2);
3439     }
3440     break;
3441   }
3442   case ISD::BITREVERSE: {
3443     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3444     Known = Known2.reverseBits();
3445     break;
3446   }
3447   case ISD::BSWAP: {
3448     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3449     Known = Known2.byteSwap();
3450     break;
3451   }
3452   case ISD::ABS: {
3453     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3454     Known = Known2.abs();
3455     break;
3456   }
3457   case ISD::USUBSAT: {
3458     // The result of usubsat will never be larger than the LHS.
3459     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3460     Known.Zero.setHighBits(Known2.countMinLeadingZeros());
3461     break;
3462   }
3463   case ISD::UMIN: {
3464     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3465     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3466     Known = KnownBits::umin(Known, Known2);
3467     break;
3468   }
3469   case ISD::UMAX: {
3470     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3471     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3472     Known = KnownBits::umax(Known, Known2);
3473     break;
3474   }
3475   case ISD::SMIN:
3476   case ISD::SMAX: {
3477     // If we have a clamp pattern, we know that the number of sign bits will be
3478     // the minimum of the clamp min/max range.
3479     bool IsMax = (Opcode == ISD::SMAX);
3480     ConstantSDNode *CstLow = nullptr, *CstHigh = nullptr;
3481     if ((CstLow = isConstOrConstSplat(Op.getOperand(1), DemandedElts)))
3482       if (Op.getOperand(0).getOpcode() == (IsMax ? ISD::SMIN : ISD::SMAX))
3483         CstHigh =
3484             isConstOrConstSplat(Op.getOperand(0).getOperand(1), DemandedElts);
3485     if (CstLow && CstHigh) {
3486       if (!IsMax)
3487         std::swap(CstLow, CstHigh);
3488 
3489       const APInt &ValueLow = CstLow->getAPIntValue();
3490       const APInt &ValueHigh = CstHigh->getAPIntValue();
3491       if (ValueLow.sle(ValueHigh)) {
3492         unsigned LowSignBits = ValueLow.getNumSignBits();
3493         unsigned HighSignBits = ValueHigh.getNumSignBits();
3494         unsigned MinSignBits = std::min(LowSignBits, HighSignBits);
3495         if (ValueLow.isNegative() && ValueHigh.isNegative()) {
3496           Known.One.setHighBits(MinSignBits);
3497           break;
3498         }
3499         if (ValueLow.isNonNegative() && ValueHigh.isNonNegative()) {
3500           Known.Zero.setHighBits(MinSignBits);
3501           break;
3502         }
3503       }
3504     }
3505 
3506     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3507     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3508     if (IsMax)
3509       Known = KnownBits::smax(Known, Known2);
3510     else
3511       Known = KnownBits::smin(Known, Known2);
3512     break;
3513   }
3514   case ISD::FrameIndex:
3515   case ISD::TargetFrameIndex:
3516     TLI->computeKnownBitsForFrameIndex(cast<FrameIndexSDNode>(Op)->getIndex(),
3517                                        Known, getMachineFunction());
3518     break;
3519 
3520   default:
3521     if (Opcode < ISD::BUILTIN_OP_END)
3522       break;
3523     LLVM_FALLTHROUGH;
3524   case ISD::INTRINSIC_WO_CHAIN:
3525   case ISD::INTRINSIC_W_CHAIN:
3526   case ISD::INTRINSIC_VOID:
3527     // Allow the target to implement this method for its nodes.
3528     TLI->computeKnownBitsForTargetNode(Op, Known, DemandedElts, *this, Depth);
3529     break;
3530   }
3531 
3532   assert(!Known.hasConflict() && "Bits known to be one AND zero?");
3533   return Known;
3534 }
3535 
3536 SelectionDAG::OverflowKind SelectionDAG::computeOverflowKind(SDValue N0,
3537                                                              SDValue N1) const {
3538   // X + 0 never overflow
3539   if (isNullConstant(N1))
3540     return OFK_Never;
3541 
3542   KnownBits N1Known = computeKnownBits(N1);
3543   if (N1Known.Zero.getBoolValue()) {
3544     KnownBits N0Known = computeKnownBits(N0);
3545 
3546     bool overflow;
3547     (void)N0Known.getMaxValue().uadd_ov(N1Known.getMaxValue(), overflow);
3548     if (!overflow)
3549       return OFK_Never;
3550   }
3551 
3552   // mulhi + 1 never overflow
3553   if (N0.getOpcode() == ISD::UMUL_LOHI && N0.getResNo() == 1 &&
3554       (N1Known.getMaxValue() & 0x01) == N1Known.getMaxValue())
3555     return OFK_Never;
3556 
3557   if (N1.getOpcode() == ISD::UMUL_LOHI && N1.getResNo() == 1) {
3558     KnownBits N0Known = computeKnownBits(N0);
3559 
3560     if ((N0Known.getMaxValue() & 0x01) == N0Known.getMaxValue())
3561       return OFK_Never;
3562   }
3563 
3564   return OFK_Sometime;
3565 }
3566 
3567 bool SelectionDAG::isKnownToBeAPowerOfTwo(SDValue Val) const {
3568   EVT OpVT = Val.getValueType();
3569   unsigned BitWidth = OpVT.getScalarSizeInBits();
3570 
3571   // Is the constant a known power of 2?
3572   if (ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Val))
3573     return Const->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2();
3574 
3575   // A left-shift of a constant one will have exactly one bit set because
3576   // shifting the bit off the end is undefined.
3577   if (Val.getOpcode() == ISD::SHL) {
3578     auto *C = isConstOrConstSplat(Val.getOperand(0));
3579     if (C && C->getAPIntValue() == 1)
3580       return true;
3581   }
3582 
3583   // Similarly, a logical right-shift of a constant sign-bit will have exactly
3584   // one bit set.
3585   if (Val.getOpcode() == ISD::SRL) {
3586     auto *C = isConstOrConstSplat(Val.getOperand(0));
3587     if (C && C->getAPIntValue().isSignMask())
3588       return true;
3589   }
3590 
3591   // Are all operands of a build vector constant powers of two?
3592   if (Val.getOpcode() == ISD::BUILD_VECTOR)
3593     if (llvm::all_of(Val->ops(), [BitWidth](SDValue E) {
3594           if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(E))
3595             return C->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2();
3596           return false;
3597         }))
3598       return true;
3599 
3600   // More could be done here, though the above checks are enough
3601   // to handle some common cases.
3602 
3603   // Fall back to computeKnownBits to catch other known cases.
3604   KnownBits Known = computeKnownBits(Val);
3605   return (Known.countMaxPopulation() == 1) && (Known.countMinPopulation() == 1);
3606 }
3607 
3608 unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, unsigned Depth) const {
3609   EVT VT = Op.getValueType();
3610 
3611   // TODO: Assume we don't know anything for now.
3612   if (VT.isScalableVector())
3613     return 1;
3614 
3615   APInt DemandedElts = VT.isVector()
3616                            ? APInt::getAllOnesValue(VT.getVectorNumElements())
3617                            : APInt(1, 1);
3618   return ComputeNumSignBits(Op, DemandedElts, Depth);
3619 }
3620 
3621 unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, const APInt &DemandedElts,
3622                                           unsigned Depth) const {
3623   EVT VT = Op.getValueType();
3624   assert((VT.isInteger() || VT.isFloatingPoint()) && "Invalid VT!");
3625   unsigned VTBits = VT.getScalarSizeInBits();
3626   unsigned NumElts = DemandedElts.getBitWidth();
3627   unsigned Tmp, Tmp2;
3628   unsigned FirstAnswer = 1;
3629 
3630   if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
3631     const APInt &Val = C->getAPIntValue();
3632     return Val.getNumSignBits();
3633   }
3634 
3635   if (Depth >= MaxRecursionDepth)
3636     return 1;  // Limit search depth.
3637 
3638   if (!DemandedElts || VT.isScalableVector())
3639     return 1;  // No demanded elts, better to assume we don't know anything.
3640 
3641   unsigned Opcode = Op.getOpcode();
3642   switch (Opcode) {
3643   default: break;
3644   case ISD::AssertSext:
3645     Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
3646     return VTBits-Tmp+1;
3647   case ISD::AssertZext:
3648     Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
3649     return VTBits-Tmp;
3650 
3651   case ISD::BUILD_VECTOR:
3652     Tmp = VTBits;
3653     for (unsigned i = 0, e = Op.getNumOperands(); (i < e) && (Tmp > 1); ++i) {
3654       if (!DemandedElts[i])
3655         continue;
3656 
3657       SDValue SrcOp = Op.getOperand(i);
3658       Tmp2 = ComputeNumSignBits(SrcOp, Depth + 1);
3659 
3660       // BUILD_VECTOR can implicitly truncate sources, we must handle this.
3661       if (SrcOp.getValueSizeInBits() != VTBits) {
3662         assert(SrcOp.getValueSizeInBits() > VTBits &&
3663                "Expected BUILD_VECTOR implicit truncation");
3664         unsigned ExtraBits = SrcOp.getValueSizeInBits() - VTBits;
3665         Tmp2 = (Tmp2 > ExtraBits ? Tmp2 - ExtraBits : 1);
3666       }
3667       Tmp = std::min(Tmp, Tmp2);
3668     }
3669     return Tmp;
3670 
3671   case ISD::VECTOR_SHUFFLE: {
3672     // Collect the minimum number of sign bits that are shared by every vector
3673     // element referenced by the shuffle.
3674     APInt DemandedLHS(NumElts, 0), DemandedRHS(NumElts, 0);
3675     const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op);
3676     assert(NumElts == SVN->getMask().size() && "Unexpected vector size");
3677     for (unsigned i = 0; i != NumElts; ++i) {
3678       int M = SVN->getMaskElt(i);
3679       if (!DemandedElts[i])
3680         continue;
3681       // For UNDEF elements, we don't know anything about the common state of
3682       // the shuffle result.
3683       if (M < 0)
3684         return 1;
3685       if ((unsigned)M < NumElts)
3686         DemandedLHS.setBit((unsigned)M % NumElts);
3687       else
3688         DemandedRHS.setBit((unsigned)M % NumElts);
3689     }
3690     Tmp = std::numeric_limits<unsigned>::max();
3691     if (!!DemandedLHS)
3692       Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedLHS, Depth + 1);
3693     if (!!DemandedRHS) {
3694       Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedRHS, Depth + 1);
3695       Tmp = std::min(Tmp, Tmp2);
3696     }
3697     // If we don't know anything, early out and try computeKnownBits fall-back.
3698     if (Tmp == 1)
3699       break;
3700     assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
3701     return Tmp;
3702   }
3703 
3704   case ISD::BITCAST: {
3705     SDValue N0 = Op.getOperand(0);
3706     EVT SrcVT = N0.getValueType();
3707     unsigned SrcBits = SrcVT.getScalarSizeInBits();
3708 
3709     // Ignore bitcasts from unsupported types..
3710     if (!(SrcVT.isInteger() || SrcVT.isFloatingPoint()))
3711       break;
3712 
3713     // Fast handling of 'identity' bitcasts.
3714     if (VTBits == SrcBits)
3715       return ComputeNumSignBits(N0, DemandedElts, Depth + 1);
3716 
3717     bool IsLE = getDataLayout().isLittleEndian();
3718 
3719     // Bitcast 'large element' scalar/vector to 'small element' vector.
3720     if ((SrcBits % VTBits) == 0) {
3721       assert(VT.isVector() && "Expected bitcast to vector");
3722 
3723       unsigned Scale = SrcBits / VTBits;
3724       APInt SrcDemandedElts(NumElts / Scale, 0);
3725       for (unsigned i = 0; i != NumElts; ++i)
3726         if (DemandedElts[i])
3727           SrcDemandedElts.setBit(i / Scale);
3728 
3729       // Fast case - sign splat can be simply split across the small elements.
3730       Tmp = ComputeNumSignBits(N0, SrcDemandedElts, Depth + 1);
3731       if (Tmp == SrcBits)
3732         return VTBits;
3733 
3734       // Slow case - determine how far the sign extends into each sub-element.
3735       Tmp2 = VTBits;
3736       for (unsigned i = 0; i != NumElts; ++i)
3737         if (DemandedElts[i]) {
3738           unsigned SubOffset = i % Scale;
3739           SubOffset = (IsLE ? ((Scale - 1) - SubOffset) : SubOffset);
3740           SubOffset = SubOffset * VTBits;
3741           if (Tmp <= SubOffset)
3742             return 1;
3743           Tmp2 = std::min(Tmp2, Tmp - SubOffset);
3744         }
3745       return Tmp2;
3746     }
3747     break;
3748   }
3749 
3750   case ISD::SIGN_EXTEND:
3751     Tmp = VTBits - Op.getOperand(0).getScalarValueSizeInBits();
3752     return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1) + Tmp;
3753   case ISD::SIGN_EXTEND_INREG:
3754     // Max of the input and what this extends.
3755     Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getScalarSizeInBits();
3756     Tmp = VTBits-Tmp+1;
3757     Tmp2 = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1);
3758     return std::max(Tmp, Tmp2);
3759   case ISD::SIGN_EXTEND_VECTOR_INREG: {
3760     SDValue Src = Op.getOperand(0);
3761     EVT SrcVT = Src.getValueType();
3762     APInt DemandedSrcElts = DemandedElts.zextOrSelf(SrcVT.getVectorNumElements());
3763     Tmp = VTBits - SrcVT.getScalarSizeInBits();
3764     return ComputeNumSignBits(Src, DemandedSrcElts, Depth+1) + Tmp;
3765   }
3766   case ISD::SRA:
3767     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
3768     // SRA X, C -> adds C sign bits.
3769     if (const APInt *ShAmt =
3770             getValidMinimumShiftAmountConstant(Op, DemandedElts))
3771       Tmp = std::min<uint64_t>(Tmp + ShAmt->getZExtValue(), VTBits);
3772     return Tmp;
3773   case ISD::SHL:
3774     if (const APInt *ShAmt =
3775             getValidMaximumShiftAmountConstant(Op, DemandedElts)) {
3776       // shl destroys sign bits, ensure it doesn't shift out all sign bits.
3777       Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
3778       if (ShAmt->ult(Tmp))
3779         return Tmp - ShAmt->getZExtValue();
3780     }
3781     break;
3782   case ISD::AND:
3783   case ISD::OR:
3784   case ISD::XOR:    // NOT is handled here.
3785     // Logical binary ops preserve the number of sign bits at the worst.
3786     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1);
3787     if (Tmp != 1) {
3788       Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth+1);
3789       FirstAnswer = std::min(Tmp, Tmp2);
3790       // We computed what we know about the sign bits as our first
3791       // answer. Now proceed to the generic code that uses
3792       // computeKnownBits, and pick whichever answer is better.
3793     }
3794     break;
3795 
3796   case ISD::SELECT:
3797   case ISD::VSELECT:
3798     Tmp = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth+1);
3799     if (Tmp == 1) return 1;  // Early out.
3800     Tmp2 = ComputeNumSignBits(Op.getOperand(2), DemandedElts, Depth+1);
3801     return std::min(Tmp, Tmp2);
3802   case ISD::SELECT_CC:
3803     Tmp = ComputeNumSignBits(Op.getOperand(2), DemandedElts, Depth+1);
3804     if (Tmp == 1) return 1;  // Early out.
3805     Tmp2 = ComputeNumSignBits(Op.getOperand(3), DemandedElts, Depth+1);
3806     return std::min(Tmp, Tmp2);
3807 
3808   case ISD::SMIN:
3809   case ISD::SMAX: {
3810     // If we have a clamp pattern, we know that the number of sign bits will be
3811     // the minimum of the clamp min/max range.
3812     bool IsMax = (Opcode == ISD::SMAX);
3813     ConstantSDNode *CstLow = nullptr, *CstHigh = nullptr;
3814     if ((CstLow = isConstOrConstSplat(Op.getOperand(1), DemandedElts)))
3815       if (Op.getOperand(0).getOpcode() == (IsMax ? ISD::SMIN : ISD::SMAX))
3816         CstHigh =
3817             isConstOrConstSplat(Op.getOperand(0).getOperand(1), DemandedElts);
3818     if (CstLow && CstHigh) {
3819       if (!IsMax)
3820         std::swap(CstLow, CstHigh);
3821       if (CstLow->getAPIntValue().sle(CstHigh->getAPIntValue())) {
3822         Tmp = CstLow->getAPIntValue().getNumSignBits();
3823         Tmp2 = CstHigh->getAPIntValue().getNumSignBits();
3824         return std::min(Tmp, Tmp2);
3825       }
3826     }
3827 
3828     // Fallback - just get the minimum number of sign bits of the operands.
3829     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
3830     if (Tmp == 1)
3831       return 1;  // Early out.
3832     Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
3833     return std::min(Tmp, Tmp2);
3834   }
3835   case ISD::UMIN:
3836   case ISD::UMAX:
3837     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
3838     if (Tmp == 1)
3839       return 1;  // Early out.
3840     Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
3841     return std::min(Tmp, Tmp2);
3842   case ISD::SADDO:
3843   case ISD::UADDO:
3844   case ISD::SSUBO:
3845   case ISD::USUBO:
3846   case ISD::SMULO:
3847   case ISD::UMULO:
3848     if (Op.getResNo() != 1)
3849       break;
3850     // The boolean result conforms to getBooleanContents.  Fall through.
3851     // If setcc returns 0/-1, all bits are sign bits.
3852     // We know that we have an integer-based boolean since these operations
3853     // are only available for integer.
3854     if (TLI->getBooleanContents(VT.isVector(), false) ==
3855         TargetLowering::ZeroOrNegativeOneBooleanContent)
3856       return VTBits;
3857     break;
3858   case ISD::SETCC:
3859   case ISD::STRICT_FSETCC:
3860   case ISD::STRICT_FSETCCS: {
3861     unsigned OpNo = Op->isStrictFPOpcode() ? 1 : 0;
3862     // If setcc returns 0/-1, all bits are sign bits.
3863     if (TLI->getBooleanContents(Op.getOperand(OpNo).getValueType()) ==
3864         TargetLowering::ZeroOrNegativeOneBooleanContent)
3865       return VTBits;
3866     break;
3867   }
3868   case ISD::ROTL:
3869   case ISD::ROTR:
3870     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
3871 
3872     // If we're rotating an 0/-1 value, then it stays an 0/-1 value.
3873     if (Tmp == VTBits)
3874       return VTBits;
3875 
3876     if (ConstantSDNode *C =
3877             isConstOrConstSplat(Op.getOperand(1), DemandedElts)) {
3878       unsigned RotAmt = C->getAPIntValue().urem(VTBits);
3879 
3880       // Handle rotate right by N like a rotate left by 32-N.
3881       if (Opcode == ISD::ROTR)
3882         RotAmt = (VTBits - RotAmt) % VTBits;
3883 
3884       // If we aren't rotating out all of the known-in sign bits, return the
3885       // number that are left.  This handles rotl(sext(x), 1) for example.
3886       if (Tmp > (RotAmt + 1)) return (Tmp - RotAmt);
3887     }
3888     break;
3889   case ISD::ADD:
3890   case ISD::ADDC:
3891     // Add can have at most one carry bit.  Thus we know that the output
3892     // is, at worst, one more bit than the inputs.
3893     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
3894     if (Tmp == 1) return 1; // Early out.
3895 
3896     // Special case decrementing a value (ADD X, -1):
3897     if (ConstantSDNode *CRHS =
3898             isConstOrConstSplat(Op.getOperand(1), DemandedElts))
3899       if (CRHS->isAllOnesValue()) {
3900         KnownBits Known =
3901             computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3902 
3903         // If the input is known to be 0 or 1, the output is 0/-1, which is all
3904         // sign bits set.
3905         if ((Known.Zero | 1).isAllOnesValue())
3906           return VTBits;
3907 
3908         // If we are subtracting one from a positive number, there is no carry
3909         // out of the result.
3910         if (Known.isNonNegative())
3911           return Tmp;
3912       }
3913 
3914     Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
3915     if (Tmp2 == 1) return 1; // Early out.
3916     return std::min(Tmp, Tmp2) - 1;
3917   case ISD::SUB:
3918     Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
3919     if (Tmp2 == 1) return 1; // Early out.
3920 
3921     // Handle NEG.
3922     if (ConstantSDNode *CLHS =
3923             isConstOrConstSplat(Op.getOperand(0), DemandedElts))
3924       if (CLHS->isNullValue()) {
3925         KnownBits Known =
3926             computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3927         // If the input is known to be 0 or 1, the output is 0/-1, which is all
3928         // sign bits set.
3929         if ((Known.Zero | 1).isAllOnesValue())
3930           return VTBits;
3931 
3932         // If the input is known to be positive (the sign bit is known clear),
3933         // the output of the NEG has the same number of sign bits as the input.
3934         if (Known.isNonNegative())
3935           return Tmp2;
3936 
3937         // Otherwise, we treat this like a SUB.
3938       }
3939 
3940     // Sub can have at most one carry bit.  Thus we know that the output
3941     // is, at worst, one more bit than the inputs.
3942     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
3943     if (Tmp == 1) return 1; // Early out.
3944     return std::min(Tmp, Tmp2) - 1;
3945   case ISD::MUL: {
3946     // The output of the Mul can be at most twice the valid bits in the inputs.
3947     unsigned SignBitsOp0 = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
3948     if (SignBitsOp0 == 1)
3949       break;
3950     unsigned SignBitsOp1 = ComputeNumSignBits(Op.getOperand(1), Depth + 1);
3951     if (SignBitsOp1 == 1)
3952       break;
3953     unsigned OutValidBits =
3954         (VTBits - SignBitsOp0 + 1) + (VTBits - SignBitsOp1 + 1);
3955     return OutValidBits > VTBits ? 1 : VTBits - OutValidBits + 1;
3956   }
3957   case ISD::SREM:
3958     // The sign bit is the LHS's sign bit, except when the result of the
3959     // remainder is zero. The magnitude of the result should be less than or
3960     // equal to the magnitude of the LHS. Therefore, the result should have
3961     // at least as many sign bits as the left hand side.
3962     return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
3963   case ISD::TRUNCATE: {
3964     // Check if the sign bits of source go down as far as the truncated value.
3965     unsigned NumSrcBits = Op.getOperand(0).getScalarValueSizeInBits();
3966     unsigned NumSrcSignBits = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
3967     if (NumSrcSignBits > (NumSrcBits - VTBits))
3968       return NumSrcSignBits - (NumSrcBits - VTBits);
3969     break;
3970   }
3971   case ISD::EXTRACT_ELEMENT: {
3972     const int KnownSign = ComputeNumSignBits(Op.getOperand(0), Depth+1);
3973     const int BitWidth = Op.getValueSizeInBits();
3974     const int Items = Op.getOperand(0).getValueSizeInBits() / BitWidth;
3975 
3976     // Get reverse index (starting from 1), Op1 value indexes elements from
3977     // little end. Sign starts at big end.
3978     const int rIndex = Items - 1 - Op.getConstantOperandVal(1);
3979 
3980     // If the sign portion ends in our element the subtraction gives correct
3981     // result. Otherwise it gives either negative or > bitwidth result
3982     return std::max(std::min(KnownSign - rIndex * BitWidth, BitWidth), 0);
3983   }
3984   case ISD::INSERT_VECTOR_ELT: {
3985     // If we know the element index, split the demand between the
3986     // source vector and the inserted element, otherwise assume we need
3987     // the original demanded vector elements and the value.
3988     SDValue InVec = Op.getOperand(0);
3989     SDValue InVal = Op.getOperand(1);
3990     SDValue EltNo = Op.getOperand(2);
3991     bool DemandedVal = true;
3992     APInt DemandedVecElts = DemandedElts;
3993     auto *CEltNo = dyn_cast<ConstantSDNode>(EltNo);
3994     if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) {
3995       unsigned EltIdx = CEltNo->getZExtValue();
3996       DemandedVal = !!DemandedElts[EltIdx];
3997       DemandedVecElts.clearBit(EltIdx);
3998     }
3999     Tmp = std::numeric_limits<unsigned>::max();
4000     if (DemandedVal) {
4001       // TODO - handle implicit truncation of inserted elements.
4002       if (InVal.getScalarValueSizeInBits() != VTBits)
4003         break;
4004       Tmp2 = ComputeNumSignBits(InVal, Depth + 1);
4005       Tmp = std::min(Tmp, Tmp2);
4006     }
4007     if (!!DemandedVecElts) {
4008       Tmp2 = ComputeNumSignBits(InVec, DemandedVecElts, Depth + 1);
4009       Tmp = std::min(Tmp, Tmp2);
4010     }
4011     assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
4012     return Tmp;
4013   }
4014   case ISD::EXTRACT_VECTOR_ELT: {
4015     SDValue InVec = Op.getOperand(0);
4016     SDValue EltNo = Op.getOperand(1);
4017     EVT VecVT = InVec.getValueType();
4018     // ComputeNumSignBits not yet implemented for scalable vectors.
4019     if (VecVT.isScalableVector())
4020       break;
4021     const unsigned BitWidth = Op.getValueSizeInBits();
4022     const unsigned EltBitWidth = Op.getOperand(0).getScalarValueSizeInBits();
4023     const unsigned NumSrcElts = VecVT.getVectorNumElements();
4024 
4025     // If BitWidth > EltBitWidth the value is anyext:ed, and we do not know
4026     // anything about sign bits. But if the sizes match we can derive knowledge
4027     // about sign bits from the vector operand.
4028     if (BitWidth != EltBitWidth)
4029       break;
4030 
4031     // If we know the element index, just demand that vector element, else for
4032     // an unknown element index, ignore DemandedElts and demand them all.
4033     APInt DemandedSrcElts = APInt::getAllOnesValue(NumSrcElts);
4034     auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
4035     if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts))
4036       DemandedSrcElts =
4037           APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue());
4038 
4039     return ComputeNumSignBits(InVec, DemandedSrcElts, Depth + 1);
4040   }
4041   case ISD::EXTRACT_SUBVECTOR: {
4042     // Offset the demanded elts by the subvector index.
4043     SDValue Src = Op.getOperand(0);
4044     // Bail until we can represent demanded elements for scalable vectors.
4045     if (Src.getValueType().isScalableVector())
4046       break;
4047     uint64_t Idx = Op.getConstantOperandVal(1);
4048     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
4049     APInt DemandedSrcElts = DemandedElts.zextOrSelf(NumSrcElts).shl(Idx);
4050     return ComputeNumSignBits(Src, DemandedSrcElts, Depth + 1);
4051   }
4052   case ISD::CONCAT_VECTORS: {
4053     // Determine the minimum number of sign bits across all demanded
4054     // elts of the input vectors. Early out if the result is already 1.
4055     Tmp = std::numeric_limits<unsigned>::max();
4056     EVT SubVectorVT = Op.getOperand(0).getValueType();
4057     unsigned NumSubVectorElts = SubVectorVT.getVectorNumElements();
4058     unsigned NumSubVectors = Op.getNumOperands();
4059     for (unsigned i = 0; (i < NumSubVectors) && (Tmp > 1); ++i) {
4060       APInt DemandedSub = DemandedElts.lshr(i * NumSubVectorElts);
4061       DemandedSub = DemandedSub.trunc(NumSubVectorElts);
4062       if (!DemandedSub)
4063         continue;
4064       Tmp2 = ComputeNumSignBits(Op.getOperand(i), DemandedSub, Depth + 1);
4065       Tmp = std::min(Tmp, Tmp2);
4066     }
4067     assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
4068     return Tmp;
4069   }
4070   case ISD::INSERT_SUBVECTOR: {
4071     // Demand any elements from the subvector and the remainder from the src its
4072     // inserted into.
4073     SDValue Src = Op.getOperand(0);
4074     SDValue Sub = Op.getOperand(1);
4075     uint64_t Idx = Op.getConstantOperandVal(2);
4076     unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
4077     APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
4078     APInt DemandedSrcElts = DemandedElts;
4079     DemandedSrcElts.insertBits(APInt::getNullValue(NumSubElts), Idx);
4080 
4081     Tmp = std::numeric_limits<unsigned>::max();
4082     if (!!DemandedSubElts) {
4083       Tmp = ComputeNumSignBits(Sub, DemandedSubElts, Depth + 1);
4084       if (Tmp == 1)
4085         return 1; // early-out
4086     }
4087     if (!!DemandedSrcElts) {
4088       Tmp2 = ComputeNumSignBits(Src, DemandedSrcElts, Depth + 1);
4089       Tmp = std::min(Tmp, Tmp2);
4090     }
4091     assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
4092     return Tmp;
4093   }
4094   }
4095 
4096   // If we are looking at the loaded value of the SDNode.
4097   if (Op.getResNo() == 0) {
4098     // Handle LOADX separately here. EXTLOAD case will fallthrough.
4099     if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
4100       unsigned ExtType = LD->getExtensionType();
4101       switch (ExtType) {
4102       default: break;
4103       case ISD::SEXTLOAD: // e.g. i16->i32 = '17' bits known.
4104         Tmp = LD->getMemoryVT().getScalarSizeInBits();
4105         return VTBits - Tmp + 1;
4106       case ISD::ZEXTLOAD: // e.g. i16->i32 = '16' bits known.
4107         Tmp = LD->getMemoryVT().getScalarSizeInBits();
4108         return VTBits - Tmp;
4109       case ISD::NON_EXTLOAD:
4110         if (const Constant *Cst = TLI->getTargetConstantFromLoad(LD)) {
4111           // We only need to handle vectors - computeKnownBits should handle
4112           // scalar cases.
4113           Type *CstTy = Cst->getType();
4114           if (CstTy->isVectorTy() &&
4115               (NumElts * VTBits) == CstTy->getPrimitiveSizeInBits()) {
4116             Tmp = VTBits;
4117             for (unsigned i = 0; i != NumElts; ++i) {
4118               if (!DemandedElts[i])
4119                 continue;
4120               if (Constant *Elt = Cst->getAggregateElement(i)) {
4121                 if (auto *CInt = dyn_cast<ConstantInt>(Elt)) {
4122                   const APInt &Value = CInt->getValue();
4123                   Tmp = std::min(Tmp, Value.getNumSignBits());
4124                   continue;
4125                 }
4126                 if (auto *CFP = dyn_cast<ConstantFP>(Elt)) {
4127                   APInt Value = CFP->getValueAPF().bitcastToAPInt();
4128                   Tmp = std::min(Tmp, Value.getNumSignBits());
4129                   continue;
4130                 }
4131               }
4132               // Unknown type. Conservatively assume no bits match sign bit.
4133               return 1;
4134             }
4135             return Tmp;
4136           }
4137         }
4138         break;
4139       }
4140     }
4141   }
4142 
4143   // Allow the target to implement this method for its nodes.
4144   if (Opcode >= ISD::BUILTIN_OP_END ||
4145       Opcode == ISD::INTRINSIC_WO_CHAIN ||
4146       Opcode == ISD::INTRINSIC_W_CHAIN ||
4147       Opcode == ISD::INTRINSIC_VOID) {
4148     unsigned NumBits =
4149         TLI->ComputeNumSignBitsForTargetNode(Op, DemandedElts, *this, Depth);
4150     if (NumBits > 1)
4151       FirstAnswer = std::max(FirstAnswer, NumBits);
4152   }
4153 
4154   // Finally, if we can prove that the top bits of the result are 0's or 1's,
4155   // use this information.
4156   KnownBits Known = computeKnownBits(Op, DemandedElts, Depth);
4157 
4158   APInt Mask;
4159   if (Known.isNonNegative()) {        // sign bit is 0
4160     Mask = Known.Zero;
4161   } else if (Known.isNegative()) {  // sign bit is 1;
4162     Mask = Known.One;
4163   } else {
4164     // Nothing known.
4165     return FirstAnswer;
4166   }
4167 
4168   // Okay, we know that the sign bit in Mask is set.  Use CLO to determine
4169   // the number of identical bits in the top of the input value.
4170   Mask <<= Mask.getBitWidth()-VTBits;
4171   return std::max(FirstAnswer, Mask.countLeadingOnes());
4172 }
4173 
4174 bool SelectionDAG::isBaseWithConstantOffset(SDValue Op) const {
4175   if ((Op.getOpcode() != ISD::ADD && Op.getOpcode() != ISD::OR) ||
4176       !isa<ConstantSDNode>(Op.getOperand(1)))
4177     return false;
4178 
4179   if (Op.getOpcode() == ISD::OR &&
4180       !MaskedValueIsZero(Op.getOperand(0), Op.getConstantOperandAPInt(1)))
4181     return false;
4182 
4183   return true;
4184 }
4185 
4186 bool SelectionDAG::isKnownNeverNaN(SDValue Op, bool SNaN, unsigned Depth) const {
4187   // If we're told that NaNs won't happen, assume they won't.
4188   if (getTarget().Options.NoNaNsFPMath || Op->getFlags().hasNoNaNs())
4189     return true;
4190 
4191   if (Depth >= MaxRecursionDepth)
4192     return false; // Limit search depth.
4193 
4194   // TODO: Handle vectors.
4195   // If the value is a constant, we can obviously see if it is a NaN or not.
4196   if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) {
4197     return !C->getValueAPF().isNaN() ||
4198            (SNaN && !C->getValueAPF().isSignaling());
4199   }
4200 
4201   unsigned Opcode = Op.getOpcode();
4202   switch (Opcode) {
4203   case ISD::FADD:
4204   case ISD::FSUB:
4205   case ISD::FMUL:
4206   case ISD::FDIV:
4207   case ISD::FREM:
4208   case ISD::FSIN:
4209   case ISD::FCOS: {
4210     if (SNaN)
4211       return true;
4212     // TODO: Need isKnownNeverInfinity
4213     return false;
4214   }
4215   case ISD::FCANONICALIZE:
4216   case ISD::FEXP:
4217   case ISD::FEXP2:
4218   case ISD::FTRUNC:
4219   case ISD::FFLOOR:
4220   case ISD::FCEIL:
4221   case ISD::FROUND:
4222   case ISD::FROUNDEVEN:
4223   case ISD::FRINT:
4224   case ISD::FNEARBYINT: {
4225     if (SNaN)
4226       return true;
4227     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
4228   }
4229   case ISD::FABS:
4230   case ISD::FNEG:
4231   case ISD::FCOPYSIGN: {
4232     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
4233   }
4234   case ISD::SELECT:
4235     return isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1) &&
4236            isKnownNeverNaN(Op.getOperand(2), SNaN, Depth + 1);
4237   case ISD::FP_EXTEND:
4238   case ISD::FP_ROUND: {
4239     if (SNaN)
4240       return true;
4241     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
4242   }
4243   case ISD::SINT_TO_FP:
4244   case ISD::UINT_TO_FP:
4245     return true;
4246   case ISD::FMA:
4247   case ISD::FMAD: {
4248     if (SNaN)
4249       return true;
4250     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) &&
4251            isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1) &&
4252            isKnownNeverNaN(Op.getOperand(2), SNaN, Depth + 1);
4253   }
4254   case ISD::FSQRT: // Need is known positive
4255   case ISD::FLOG:
4256   case ISD::FLOG2:
4257   case ISD::FLOG10:
4258   case ISD::FPOWI:
4259   case ISD::FPOW: {
4260     if (SNaN)
4261       return true;
4262     // TODO: Refine on operand
4263     return false;
4264   }
4265   case ISD::FMINNUM:
4266   case ISD::FMAXNUM: {
4267     // Only one needs to be known not-nan, since it will be returned if the
4268     // other ends up being one.
4269     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) ||
4270            isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1);
4271   }
4272   case ISD::FMINNUM_IEEE:
4273   case ISD::FMAXNUM_IEEE: {
4274     if (SNaN)
4275       return true;
4276     // This can return a NaN if either operand is an sNaN, or if both operands
4277     // are NaN.
4278     return (isKnownNeverNaN(Op.getOperand(0), false, Depth + 1) &&
4279             isKnownNeverSNaN(Op.getOperand(1), Depth + 1)) ||
4280            (isKnownNeverNaN(Op.getOperand(1), false, Depth + 1) &&
4281             isKnownNeverSNaN(Op.getOperand(0), Depth + 1));
4282   }
4283   case ISD::FMINIMUM:
4284   case ISD::FMAXIMUM: {
4285     // TODO: Does this quiet or return the origina NaN as-is?
4286     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) &&
4287            isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1);
4288   }
4289   case ISD::EXTRACT_VECTOR_ELT: {
4290     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
4291   }
4292   default:
4293     if (Opcode >= ISD::BUILTIN_OP_END ||
4294         Opcode == ISD::INTRINSIC_WO_CHAIN ||
4295         Opcode == ISD::INTRINSIC_W_CHAIN ||
4296         Opcode == ISD::INTRINSIC_VOID) {
4297       return TLI->isKnownNeverNaNForTargetNode(Op, *this, SNaN, Depth);
4298     }
4299 
4300     return false;
4301   }
4302 }
4303 
4304 bool SelectionDAG::isKnownNeverZeroFloat(SDValue Op) const {
4305   assert(Op.getValueType().isFloatingPoint() &&
4306          "Floating point type expected");
4307 
4308   // If the value is a constant, we can obviously see if it is a zero or not.
4309   // TODO: Add BuildVector support.
4310   if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op))
4311     return !C->isZero();
4312   return false;
4313 }
4314 
4315 bool SelectionDAG::isKnownNeverZero(SDValue Op) const {
4316   assert(!Op.getValueType().isFloatingPoint() &&
4317          "Floating point types unsupported - use isKnownNeverZeroFloat");
4318 
4319   // If the value is a constant, we can obviously see if it is a zero or not.
4320   if (ISD::matchUnaryPredicate(
4321           Op, [](ConstantSDNode *C) { return !C->isNullValue(); }))
4322     return true;
4323 
4324   // TODO: Recognize more cases here.
4325   switch (Op.getOpcode()) {
4326   default: break;
4327   case ISD::OR:
4328     if (isKnownNeverZero(Op.getOperand(1)) ||
4329         isKnownNeverZero(Op.getOperand(0)))
4330       return true;
4331     break;
4332   }
4333 
4334   return false;
4335 }
4336 
4337 bool SelectionDAG::isEqualTo(SDValue A, SDValue B) const {
4338   // Check the obvious case.
4339   if (A == B) return true;
4340 
4341   // For for negative and positive zero.
4342   if (const ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A))
4343     if (const ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B))
4344       if (CA->isZero() && CB->isZero()) return true;
4345 
4346   // Otherwise they may not be equal.
4347   return false;
4348 }
4349 
4350 // FIXME: unify with llvm::haveNoCommonBitsSet.
4351 // FIXME: could also handle masked merge pattern (X & ~M) op (Y & M)
4352 bool SelectionDAG::haveNoCommonBitsSet(SDValue A, SDValue B) const {
4353   assert(A.getValueType() == B.getValueType() &&
4354          "Values must have the same type");
4355   return KnownBits::haveNoCommonBitsSet(computeKnownBits(A),
4356                                         computeKnownBits(B));
4357 }
4358 
4359 static SDValue FoldSTEP_VECTOR(const SDLoc &DL, EVT VT, SDValue Step,
4360                                SelectionDAG &DAG) {
4361   if (cast<ConstantSDNode>(Step)->isNullValue())
4362     return DAG.getConstant(0, DL, VT);
4363 
4364   return SDValue();
4365 }
4366 
4367 static SDValue FoldBUILD_VECTOR(const SDLoc &DL, EVT VT,
4368                                 ArrayRef<SDValue> Ops,
4369                                 SelectionDAG &DAG) {
4370   int NumOps = Ops.size();
4371   assert(NumOps != 0 && "Can't build an empty vector!");
4372   assert(!VT.isScalableVector() &&
4373          "BUILD_VECTOR cannot be used with scalable types");
4374   assert(VT.getVectorNumElements() == (unsigned)NumOps &&
4375          "Incorrect element count in BUILD_VECTOR!");
4376 
4377   // BUILD_VECTOR of UNDEFs is UNDEF.
4378   if (llvm::all_of(Ops, [](SDValue Op) { return Op.isUndef(); }))
4379     return DAG.getUNDEF(VT);
4380 
4381   // BUILD_VECTOR of seq extract/insert from the same vector + type is Identity.
4382   SDValue IdentitySrc;
4383   bool IsIdentity = true;
4384   for (int i = 0; i != NumOps; ++i) {
4385     if (Ops[i].getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
4386         Ops[i].getOperand(0).getValueType() != VT ||
4387         (IdentitySrc && Ops[i].getOperand(0) != IdentitySrc) ||
4388         !isa<ConstantSDNode>(Ops[i].getOperand(1)) ||
4389         cast<ConstantSDNode>(Ops[i].getOperand(1))->getAPIntValue() != i) {
4390       IsIdentity = false;
4391       break;
4392     }
4393     IdentitySrc = Ops[i].getOperand(0);
4394   }
4395   if (IsIdentity)
4396     return IdentitySrc;
4397 
4398   return SDValue();
4399 }
4400 
4401 /// Try to simplify vector concatenation to an input value, undef, or build
4402 /// vector.
4403 static SDValue foldCONCAT_VECTORS(const SDLoc &DL, EVT VT,
4404                                   ArrayRef<SDValue> Ops,
4405                                   SelectionDAG &DAG) {
4406   assert(!Ops.empty() && "Can't concatenate an empty list of vectors!");
4407   assert(llvm::all_of(Ops,
4408                       [Ops](SDValue Op) {
4409                         return Ops[0].getValueType() == Op.getValueType();
4410                       }) &&
4411          "Concatenation of vectors with inconsistent value types!");
4412   assert((Ops[0].getValueType().getVectorElementCount() * Ops.size()) ==
4413              VT.getVectorElementCount() &&
4414          "Incorrect element count in vector concatenation!");
4415 
4416   if (Ops.size() == 1)
4417     return Ops[0];
4418 
4419   // Concat of UNDEFs is UNDEF.
4420   if (llvm::all_of(Ops, [](SDValue Op) { return Op.isUndef(); }))
4421     return DAG.getUNDEF(VT);
4422 
4423   // Scan the operands and look for extract operations from a single source
4424   // that correspond to insertion at the same location via this concatenation:
4425   // concat (extract X, 0*subvec_elts), (extract X, 1*subvec_elts), ...
4426   SDValue IdentitySrc;
4427   bool IsIdentity = true;
4428   for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
4429     SDValue Op = Ops[i];
4430     unsigned IdentityIndex = i * Op.getValueType().getVectorMinNumElements();
4431     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
4432         Op.getOperand(0).getValueType() != VT ||
4433         (IdentitySrc && Op.getOperand(0) != IdentitySrc) ||
4434         Op.getConstantOperandVal(1) != IdentityIndex) {
4435       IsIdentity = false;
4436       break;
4437     }
4438     assert((!IdentitySrc || IdentitySrc == Op.getOperand(0)) &&
4439            "Unexpected identity source vector for concat of extracts");
4440     IdentitySrc = Op.getOperand(0);
4441   }
4442   if (IsIdentity) {
4443     assert(IdentitySrc && "Failed to set source vector of extracts");
4444     return IdentitySrc;
4445   }
4446 
4447   // The code below this point is only designed to work for fixed width
4448   // vectors, so we bail out for now.
4449   if (VT.isScalableVector())
4450     return SDValue();
4451 
4452   // A CONCAT_VECTOR with all UNDEF/BUILD_VECTOR operands can be
4453   // simplified to one big BUILD_VECTOR.
4454   // FIXME: Add support for SCALAR_TO_VECTOR as well.
4455   EVT SVT = VT.getScalarType();
4456   SmallVector<SDValue, 16> Elts;
4457   for (SDValue Op : Ops) {
4458     EVT OpVT = Op.getValueType();
4459     if (Op.isUndef())
4460       Elts.append(OpVT.getVectorNumElements(), DAG.getUNDEF(SVT));
4461     else if (Op.getOpcode() == ISD::BUILD_VECTOR)
4462       Elts.append(Op->op_begin(), Op->op_end());
4463     else
4464       return SDValue();
4465   }
4466 
4467   // BUILD_VECTOR requires all inputs to be of the same type, find the
4468   // maximum type and extend them all.
4469   for (SDValue Op : Elts)
4470     SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
4471 
4472   if (SVT.bitsGT(VT.getScalarType())) {
4473     for (SDValue &Op : Elts) {
4474       if (Op.isUndef())
4475         Op = DAG.getUNDEF(SVT);
4476       else
4477         Op = DAG.getTargetLoweringInfo().isZExtFree(Op.getValueType(), SVT)
4478                  ? DAG.getZExtOrTrunc(Op, DL, SVT)
4479                  : DAG.getSExtOrTrunc(Op, DL, SVT);
4480     }
4481   }
4482 
4483   SDValue V = DAG.getBuildVector(VT, DL, Elts);
4484   NewSDValueDbgMsg(V, "New node fold concat vectors: ", &DAG);
4485   return V;
4486 }
4487 
4488 /// Gets or creates the specified node.
4489 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT) {
4490   FoldingSetNodeID ID;
4491   AddNodeIDNode(ID, Opcode, getVTList(VT), None);
4492   void *IP = nullptr;
4493   if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
4494     return SDValue(E, 0);
4495 
4496   auto *N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(),
4497                               getVTList(VT));
4498   CSEMap.InsertNode(N, IP);
4499 
4500   InsertNode(N);
4501   SDValue V = SDValue(N, 0);
4502   NewSDValueDbgMsg(V, "Creating new node: ", this);
4503   return V;
4504 }
4505 
4506 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
4507                               SDValue Operand) {
4508   SDNodeFlags Flags;
4509   if (Inserter)
4510     Flags = Inserter->getFlags();
4511   return getNode(Opcode, DL, VT, Operand, Flags);
4512 }
4513 
4514 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
4515                               SDValue Operand, const SDNodeFlags Flags) {
4516   assert(Operand.getOpcode() != ISD::DELETED_NODE &&
4517          "Operand is DELETED_NODE!");
4518   // Constant fold unary operations with an integer constant operand. Even
4519   // opaque constant will be folded, because the folding of unary operations
4520   // doesn't create new constants with different values. Nevertheless, the
4521   // opaque flag is preserved during folding to prevent future folding with
4522   // other constants.
4523   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Operand)) {
4524     const APInt &Val = C->getAPIntValue();
4525     switch (Opcode) {
4526     default: break;
4527     case ISD::SIGN_EXTEND:
4528       return getConstant(Val.sextOrTrunc(VT.getSizeInBits()), DL, VT,
4529                          C->isTargetOpcode(), C->isOpaque());
4530     case ISD::TRUNCATE:
4531       if (C->isOpaque())
4532         break;
4533       LLVM_FALLTHROUGH;
4534     case ISD::ANY_EXTEND:
4535     case ISD::ZERO_EXTEND:
4536       return getConstant(Val.zextOrTrunc(VT.getSizeInBits()), DL, VT,
4537                          C->isTargetOpcode(), C->isOpaque());
4538     case ISD::UINT_TO_FP:
4539     case ISD::SINT_TO_FP: {
4540       APFloat apf(EVTToAPFloatSemantics(VT),
4541                   APInt::getNullValue(VT.getSizeInBits()));
4542       (void)apf.convertFromAPInt(Val,
4543                                  Opcode==ISD::SINT_TO_FP,
4544                                  APFloat::rmNearestTiesToEven);
4545       return getConstantFP(apf, DL, VT);
4546     }
4547     case ISD::BITCAST:
4548       if (VT == MVT::f16 && C->getValueType(0) == MVT::i16)
4549         return getConstantFP(APFloat(APFloat::IEEEhalf(), Val), DL, VT);
4550       if (VT == MVT::f32 && C->getValueType(0) == MVT::i32)
4551         return getConstantFP(APFloat(APFloat::IEEEsingle(), Val), DL, VT);
4552       if (VT == MVT::f64 && C->getValueType(0) == MVT::i64)
4553         return getConstantFP(APFloat(APFloat::IEEEdouble(), Val), DL, VT);
4554       if (VT == MVT::f128 && C->getValueType(0) == MVT::i128)
4555         return getConstantFP(APFloat(APFloat::IEEEquad(), Val), DL, VT);
4556       break;
4557     case ISD::ABS:
4558       return getConstant(Val.abs(), DL, VT, C->isTargetOpcode(),
4559                          C->isOpaque());
4560     case ISD::BITREVERSE:
4561       return getConstant(Val.reverseBits(), DL, VT, C->isTargetOpcode(),
4562                          C->isOpaque());
4563     case ISD::BSWAP:
4564       return getConstant(Val.byteSwap(), DL, VT, C->isTargetOpcode(),
4565                          C->isOpaque());
4566     case ISD::CTPOP:
4567       return getConstant(Val.countPopulation(), DL, VT, C->isTargetOpcode(),
4568                          C->isOpaque());
4569     case ISD::CTLZ:
4570     case ISD::CTLZ_ZERO_UNDEF:
4571       return getConstant(Val.countLeadingZeros(), DL, VT, C->isTargetOpcode(),
4572                          C->isOpaque());
4573     case ISD::CTTZ:
4574     case ISD::CTTZ_ZERO_UNDEF:
4575       return getConstant(Val.countTrailingZeros(), DL, VT, C->isTargetOpcode(),
4576                          C->isOpaque());
4577     case ISD::FP16_TO_FP: {
4578       bool Ignored;
4579       APFloat FPV(APFloat::IEEEhalf(),
4580                   (Val.getBitWidth() == 16) ? Val : Val.trunc(16));
4581 
4582       // This can return overflow, underflow, or inexact; we don't care.
4583       // FIXME need to be more flexible about rounding mode.
4584       (void)FPV.convert(EVTToAPFloatSemantics(VT),
4585                         APFloat::rmNearestTiesToEven, &Ignored);
4586       return getConstantFP(FPV, DL, VT);
4587     }
4588     case ISD::STEP_VECTOR: {
4589       if (SDValue V = FoldSTEP_VECTOR(DL, VT, Operand, *this))
4590         return V;
4591       break;
4592     }
4593     }
4594   }
4595 
4596   // Constant fold unary operations with a floating point constant operand.
4597   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Operand)) {
4598     APFloat V = C->getValueAPF();    // make copy
4599     switch (Opcode) {
4600     case ISD::FNEG:
4601       V.changeSign();
4602       return getConstantFP(V, DL, VT);
4603     case ISD::FABS:
4604       V.clearSign();
4605       return getConstantFP(V, DL, VT);
4606     case ISD::FCEIL: {
4607       APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardPositive);
4608       if (fs == APFloat::opOK || fs == APFloat::opInexact)
4609         return getConstantFP(V, DL, VT);
4610       break;
4611     }
4612     case ISD::FTRUNC: {
4613       APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardZero);
4614       if (fs == APFloat::opOK || fs == APFloat::opInexact)
4615         return getConstantFP(V, DL, VT);
4616       break;
4617     }
4618     case ISD::FFLOOR: {
4619       APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardNegative);
4620       if (fs == APFloat::opOK || fs == APFloat::opInexact)
4621         return getConstantFP(V, DL, VT);
4622       break;
4623     }
4624     case ISD::FP_EXTEND: {
4625       bool ignored;
4626       // This can return overflow, underflow, or inexact; we don't care.
4627       // FIXME need to be more flexible about rounding mode.
4628       (void)V.convert(EVTToAPFloatSemantics(VT),
4629                       APFloat::rmNearestTiesToEven, &ignored);
4630       return getConstantFP(V, DL, VT);
4631     }
4632     case ISD::FP_TO_SINT:
4633     case ISD::FP_TO_UINT: {
4634       bool ignored;
4635       APSInt IntVal(VT.getSizeInBits(), Opcode == ISD::FP_TO_UINT);
4636       // FIXME need to be more flexible about rounding mode.
4637       APFloat::opStatus s =
4638           V.convertToInteger(IntVal, APFloat::rmTowardZero, &ignored);
4639       if (s == APFloat::opInvalidOp) // inexact is OK, in fact usual
4640         break;
4641       return getConstant(IntVal, DL, VT);
4642     }
4643     case ISD::BITCAST:
4644       if (VT == MVT::i16 && C->getValueType(0) == MVT::f16)
4645         return getConstant((uint16_t)V.bitcastToAPInt().getZExtValue(), DL, VT);
4646       if (VT == MVT::i16 && C->getValueType(0) == MVT::bf16)
4647         return getConstant((uint16_t)V.bitcastToAPInt().getZExtValue(), DL, VT);
4648       if (VT == MVT::i32 && C->getValueType(0) == MVT::f32)
4649         return getConstant((uint32_t)V.bitcastToAPInt().getZExtValue(), DL, VT);
4650       if (VT == MVT::i64 && C->getValueType(0) == MVT::f64)
4651         return getConstant(V.bitcastToAPInt().getZExtValue(), DL, VT);
4652       break;
4653     case ISD::FP_TO_FP16: {
4654       bool Ignored;
4655       // This can return overflow, underflow, or inexact; we don't care.
4656       // FIXME need to be more flexible about rounding mode.
4657       (void)V.convert(APFloat::IEEEhalf(),
4658                       APFloat::rmNearestTiesToEven, &Ignored);
4659       return getConstant(V.bitcastToAPInt().getZExtValue(), DL, VT);
4660     }
4661     }
4662   }
4663 
4664   // Constant fold unary operations with a vector integer or float operand.
4665   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Operand)) {
4666     if (BV->isConstant()) {
4667       switch (Opcode) {
4668       default:
4669         // FIXME: Entirely reasonable to perform folding of other unary
4670         // operations here as the need arises.
4671         break;
4672       case ISD::FNEG:
4673       case ISD::FABS:
4674       case ISD::FCEIL:
4675       case ISD::FTRUNC:
4676       case ISD::FFLOOR:
4677       case ISD::FP_EXTEND:
4678       case ISD::FP_TO_SINT:
4679       case ISD::FP_TO_UINT:
4680       case ISD::TRUNCATE:
4681       case ISD::ANY_EXTEND:
4682       case ISD::ZERO_EXTEND:
4683       case ISD::SIGN_EXTEND:
4684       case ISD::UINT_TO_FP:
4685       case ISD::SINT_TO_FP:
4686       case ISD::ABS:
4687       case ISD::BITREVERSE:
4688       case ISD::BSWAP:
4689       case ISD::CTLZ:
4690       case ISD::CTLZ_ZERO_UNDEF:
4691       case ISD::CTTZ:
4692       case ISD::CTTZ_ZERO_UNDEF:
4693       case ISD::CTPOP: {
4694         SDValue Ops = { Operand };
4695         if (SDValue Fold = FoldConstantVectorArithmetic(Opcode, DL, VT, Ops))
4696           return Fold;
4697       }
4698       }
4699     }
4700   }
4701 
4702   unsigned OpOpcode = Operand.getNode()->getOpcode();
4703   switch (Opcode) {
4704   case ISD::STEP_VECTOR:
4705     assert(VT.isScalableVector() &&
4706            "STEP_VECTOR can only be used with scalable types");
4707     assert(VT.getScalarSizeInBits() >= 8 &&
4708            "STEP_VECTOR can only be used with vectors of integers that are at "
4709            "least 8 bits wide");
4710     assert(isa<ConstantSDNode>(Operand) &&
4711            cast<ConstantSDNode>(Operand)->getAPIntValue().isNonNegative() &&
4712            cast<ConstantSDNode>(Operand)->getAPIntValue().isSignedIntN(
4713                VT.getScalarSizeInBits()) &&
4714            "Expected STEP_VECTOR integer constant to be positive and fit in "
4715            "the vector element type");
4716     break;
4717   case ISD::FREEZE:
4718     assert(VT == Operand.getValueType() && "Unexpected VT!");
4719     break;
4720   case ISD::TokenFactor:
4721   case ISD::MERGE_VALUES:
4722   case ISD::CONCAT_VECTORS:
4723     return Operand;         // Factor, merge or concat of one node?  No need.
4724   case ISD::BUILD_VECTOR: {
4725     // Attempt to simplify BUILD_VECTOR.
4726     SDValue Ops[] = {Operand};
4727     if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
4728       return V;
4729     break;
4730   }
4731   case ISD::FP_ROUND: llvm_unreachable("Invalid method to make FP_ROUND node");
4732   case ISD::FP_EXTEND:
4733     assert(VT.isFloatingPoint() &&
4734            Operand.getValueType().isFloatingPoint() && "Invalid FP cast!");
4735     if (Operand.getValueType() == VT) return Operand;  // noop conversion.
4736     assert((!VT.isVector() ||
4737             VT.getVectorElementCount() ==
4738             Operand.getValueType().getVectorElementCount()) &&
4739            "Vector element count mismatch!");
4740     assert(Operand.getValueType().bitsLT(VT) &&
4741            "Invalid fpext node, dst < src!");
4742     if (Operand.isUndef())
4743       return getUNDEF(VT);
4744     break;
4745   case ISD::FP_TO_SINT:
4746   case ISD::FP_TO_UINT:
4747     if (Operand.isUndef())
4748       return getUNDEF(VT);
4749     break;
4750   case ISD::SINT_TO_FP:
4751   case ISD::UINT_TO_FP:
4752     // [us]itofp(undef) = 0, because the result value is bounded.
4753     if (Operand.isUndef())
4754       return getConstantFP(0.0, DL, VT);
4755     break;
4756   case ISD::SIGN_EXTEND:
4757     assert(VT.isInteger() && Operand.getValueType().isInteger() &&
4758            "Invalid SIGN_EXTEND!");
4759     assert(VT.isVector() == Operand.getValueType().isVector() &&
4760            "SIGN_EXTEND result type type should be vector iff the operand "
4761            "type is vector!");
4762     if (Operand.getValueType() == VT) return Operand;   // noop extension
4763     assert((!VT.isVector() ||
4764             VT.getVectorElementCount() ==
4765                 Operand.getValueType().getVectorElementCount()) &&
4766            "Vector element count mismatch!");
4767     assert(Operand.getValueType().bitsLT(VT) &&
4768            "Invalid sext node, dst < src!");
4769     if (OpOpcode == ISD::SIGN_EXTEND || OpOpcode == ISD::ZERO_EXTEND)
4770       return getNode(OpOpcode, DL, VT, Operand.getOperand(0));
4771     if (OpOpcode == ISD::UNDEF)
4772       // sext(undef) = 0, because the top bits will all be the same.
4773       return getConstant(0, DL, VT);
4774     break;
4775   case ISD::ZERO_EXTEND:
4776     assert(VT.isInteger() && Operand.getValueType().isInteger() &&
4777            "Invalid ZERO_EXTEND!");
4778     assert(VT.isVector() == Operand.getValueType().isVector() &&
4779            "ZERO_EXTEND result type type should be vector iff the operand "
4780            "type is vector!");
4781     if (Operand.getValueType() == VT) return Operand;   // noop extension
4782     assert((!VT.isVector() ||
4783             VT.getVectorElementCount() ==
4784                 Operand.getValueType().getVectorElementCount()) &&
4785            "Vector element count mismatch!");
4786     assert(Operand.getValueType().bitsLT(VT) &&
4787            "Invalid zext node, dst < src!");
4788     if (OpOpcode == ISD::ZERO_EXTEND)   // (zext (zext x)) -> (zext x)
4789       return getNode(ISD::ZERO_EXTEND, DL, VT, Operand.getOperand(0));
4790     if (OpOpcode == ISD::UNDEF)
4791       // zext(undef) = 0, because the top bits will be zero.
4792       return getConstant(0, DL, VT);
4793     break;
4794   case ISD::ANY_EXTEND:
4795     assert(VT.isInteger() && Operand.getValueType().isInteger() &&
4796            "Invalid ANY_EXTEND!");
4797     assert(VT.isVector() == Operand.getValueType().isVector() &&
4798            "ANY_EXTEND result type type should be vector iff the operand "
4799            "type is vector!");
4800     if (Operand.getValueType() == VT) return Operand;   // noop extension
4801     assert((!VT.isVector() ||
4802             VT.getVectorElementCount() ==
4803                 Operand.getValueType().getVectorElementCount()) &&
4804            "Vector element count mismatch!");
4805     assert(Operand.getValueType().bitsLT(VT) &&
4806            "Invalid anyext node, dst < src!");
4807 
4808     if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
4809         OpOpcode == ISD::ANY_EXTEND)
4810       // (ext (zext x)) -> (zext x)  and  (ext (sext x)) -> (sext x)
4811       return getNode(OpOpcode, DL, VT, Operand.getOperand(0));
4812     if (OpOpcode == ISD::UNDEF)
4813       return getUNDEF(VT);
4814 
4815     // (ext (trunc x)) -> x
4816     if (OpOpcode == ISD::TRUNCATE) {
4817       SDValue OpOp = Operand.getOperand(0);
4818       if (OpOp.getValueType() == VT) {
4819         transferDbgValues(Operand, OpOp);
4820         return OpOp;
4821       }
4822     }
4823     break;
4824   case ISD::TRUNCATE:
4825     assert(VT.isInteger() && Operand.getValueType().isInteger() &&
4826            "Invalid TRUNCATE!");
4827     assert(VT.isVector() == Operand.getValueType().isVector() &&
4828            "TRUNCATE result type type should be vector iff the operand "
4829            "type is vector!");
4830     if (Operand.getValueType() == VT) return Operand;   // noop truncate
4831     assert((!VT.isVector() ||
4832             VT.getVectorElementCount() ==
4833                 Operand.getValueType().getVectorElementCount()) &&
4834            "Vector element count mismatch!");
4835     assert(Operand.getValueType().bitsGT(VT) &&
4836            "Invalid truncate node, src < dst!");
4837     if (OpOpcode == ISD::TRUNCATE)
4838       return getNode(ISD::TRUNCATE, DL, VT, Operand.getOperand(0));
4839     if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
4840         OpOpcode == ISD::ANY_EXTEND) {
4841       // If the source is smaller than the dest, we still need an extend.
4842       if (Operand.getOperand(0).getValueType().getScalarType()
4843             .bitsLT(VT.getScalarType()))
4844         return getNode(OpOpcode, DL, VT, Operand.getOperand(0));
4845       if (Operand.getOperand(0).getValueType().bitsGT(VT))
4846         return getNode(ISD::TRUNCATE, DL, VT, Operand.getOperand(0));
4847       return Operand.getOperand(0);
4848     }
4849     if (OpOpcode == ISD::UNDEF)
4850       return getUNDEF(VT);
4851     break;
4852   case ISD::ANY_EXTEND_VECTOR_INREG:
4853   case ISD::ZERO_EXTEND_VECTOR_INREG:
4854   case ISD::SIGN_EXTEND_VECTOR_INREG:
4855     assert(VT.isVector() && "This DAG node is restricted to vector types.");
4856     assert(Operand.getValueType().bitsLE(VT) &&
4857            "The input must be the same size or smaller than the result.");
4858     assert(VT.getVectorMinNumElements() <
4859                Operand.getValueType().getVectorMinNumElements() &&
4860            "The destination vector type must have fewer lanes than the input.");
4861     break;
4862   case ISD::ABS:
4863     assert(VT.isInteger() && VT == Operand.getValueType() &&
4864            "Invalid ABS!");
4865     if (OpOpcode == ISD::UNDEF)
4866       return getUNDEF(VT);
4867     break;
4868   case ISD::BSWAP:
4869     assert(VT.isInteger() && VT == Operand.getValueType() &&
4870            "Invalid BSWAP!");
4871     assert((VT.getScalarSizeInBits() % 16 == 0) &&
4872            "BSWAP types must be a multiple of 16 bits!");
4873     if (OpOpcode == ISD::UNDEF)
4874       return getUNDEF(VT);
4875     break;
4876   case ISD::BITREVERSE:
4877     assert(VT.isInteger() && VT == Operand.getValueType() &&
4878            "Invalid BITREVERSE!");
4879     if (OpOpcode == ISD::UNDEF)
4880       return getUNDEF(VT);
4881     break;
4882   case ISD::BITCAST:
4883     // Basic sanity checking.
4884     assert(VT.getSizeInBits() == Operand.getValueSizeInBits() &&
4885            "Cannot BITCAST between types of different sizes!");
4886     if (VT == Operand.getValueType()) return Operand;  // noop conversion.
4887     if (OpOpcode == ISD::BITCAST)  // bitconv(bitconv(x)) -> bitconv(x)
4888       return getNode(ISD::BITCAST, DL, VT, Operand.getOperand(0));
4889     if (OpOpcode == ISD::UNDEF)
4890       return getUNDEF(VT);
4891     break;
4892   case ISD::SCALAR_TO_VECTOR:
4893     assert(VT.isVector() && !Operand.getValueType().isVector() &&
4894            (VT.getVectorElementType() == Operand.getValueType() ||
4895             (VT.getVectorElementType().isInteger() &&
4896              Operand.getValueType().isInteger() &&
4897              VT.getVectorElementType().bitsLE(Operand.getValueType()))) &&
4898            "Illegal SCALAR_TO_VECTOR node!");
4899     if (OpOpcode == ISD::UNDEF)
4900       return getUNDEF(VT);
4901     // scalar_to_vector(extract_vector_elt V, 0) -> V, top bits are undefined.
4902     if (OpOpcode == ISD::EXTRACT_VECTOR_ELT &&
4903         isa<ConstantSDNode>(Operand.getOperand(1)) &&
4904         Operand.getConstantOperandVal(1) == 0 &&
4905         Operand.getOperand(0).getValueType() == VT)
4906       return Operand.getOperand(0);
4907     break;
4908   case ISD::FNEG:
4909     // Negation of an unknown bag of bits is still completely undefined.
4910     if (OpOpcode == ISD::UNDEF)
4911       return getUNDEF(VT);
4912 
4913     if (OpOpcode == ISD::FNEG)  // --X -> X
4914       return Operand.getOperand(0);
4915     break;
4916   case ISD::FABS:
4917     if (OpOpcode == ISD::FNEG)  // abs(-X) -> abs(X)
4918       return getNode(ISD::FABS, DL, VT, Operand.getOperand(0));
4919     break;
4920   case ISD::VSCALE:
4921     assert(VT == Operand.getValueType() && "Unexpected VT!");
4922     break;
4923   case ISD::CTPOP:
4924     if (Operand.getValueType().getScalarType() == MVT::i1)
4925       return Operand;
4926     break;
4927   case ISD::CTLZ:
4928   case ISD::CTTZ:
4929     if (Operand.getValueType().getScalarType() == MVT::i1)
4930       return getNOT(DL, Operand, Operand.getValueType());
4931     break;
4932   case ISD::VECREDUCE_SMIN:
4933   case ISD::VECREDUCE_UMAX:
4934     if (Operand.getValueType().getScalarType() == MVT::i1)
4935       return getNode(ISD::VECREDUCE_OR, DL, VT, Operand);
4936     break;
4937   case ISD::VECREDUCE_SMAX:
4938   case ISD::VECREDUCE_UMIN:
4939     if (Operand.getValueType().getScalarType() == MVT::i1)
4940       return getNode(ISD::VECREDUCE_AND, DL, VT, Operand);
4941     break;
4942   }
4943 
4944   SDNode *N;
4945   SDVTList VTs = getVTList(VT);
4946   SDValue Ops[] = {Operand};
4947   if (VT != MVT::Glue) { // Don't CSE flag producing nodes
4948     FoldingSetNodeID ID;
4949     AddNodeIDNode(ID, Opcode, VTs, Ops);
4950     void *IP = nullptr;
4951     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
4952       E->intersectFlagsWith(Flags);
4953       return SDValue(E, 0);
4954     }
4955 
4956     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
4957     N->setFlags(Flags);
4958     createOperands(N, Ops);
4959     CSEMap.InsertNode(N, IP);
4960   } else {
4961     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
4962     createOperands(N, Ops);
4963   }
4964 
4965   InsertNode(N);
4966   SDValue V = SDValue(N, 0);
4967   NewSDValueDbgMsg(V, "Creating new node: ", this);
4968   return V;
4969 }
4970 
4971 static llvm::Optional<APInt> FoldValue(unsigned Opcode, const APInt &C1,
4972                                        const APInt &C2) {
4973   switch (Opcode) {
4974   case ISD::ADD:  return C1 + C2;
4975   case ISD::SUB:  return C1 - C2;
4976   case ISD::MUL:  return C1 * C2;
4977   case ISD::AND:  return C1 & C2;
4978   case ISD::OR:   return C1 | C2;
4979   case ISD::XOR:  return C1 ^ C2;
4980   case ISD::SHL:  return C1 << C2;
4981   case ISD::SRL:  return C1.lshr(C2);
4982   case ISD::SRA:  return C1.ashr(C2);
4983   case ISD::ROTL: return C1.rotl(C2);
4984   case ISD::ROTR: return C1.rotr(C2);
4985   case ISD::SMIN: return C1.sle(C2) ? C1 : C2;
4986   case ISD::SMAX: return C1.sge(C2) ? C1 : C2;
4987   case ISD::UMIN: return C1.ule(C2) ? C1 : C2;
4988   case ISD::UMAX: return C1.uge(C2) ? C1 : C2;
4989   case ISD::SADDSAT: return C1.sadd_sat(C2);
4990   case ISD::UADDSAT: return C1.uadd_sat(C2);
4991   case ISD::SSUBSAT: return C1.ssub_sat(C2);
4992   case ISD::USUBSAT: return C1.usub_sat(C2);
4993   case ISD::UDIV:
4994     if (!C2.getBoolValue())
4995       break;
4996     return C1.udiv(C2);
4997   case ISD::UREM:
4998     if (!C2.getBoolValue())
4999       break;
5000     return C1.urem(C2);
5001   case ISD::SDIV:
5002     if (!C2.getBoolValue())
5003       break;
5004     return C1.sdiv(C2);
5005   case ISD::SREM:
5006     if (!C2.getBoolValue())
5007       break;
5008     return C1.srem(C2);
5009   }
5010   return llvm::None;
5011 }
5012 
5013 SDValue SelectionDAG::FoldSymbolOffset(unsigned Opcode, EVT VT,
5014                                        const GlobalAddressSDNode *GA,
5015                                        const SDNode *N2) {
5016   if (GA->getOpcode() != ISD::GlobalAddress)
5017     return SDValue();
5018   if (!TLI->isOffsetFoldingLegal(GA))
5019     return SDValue();
5020   auto *C2 = dyn_cast<ConstantSDNode>(N2);
5021   if (!C2)
5022     return SDValue();
5023   int64_t Offset = C2->getSExtValue();
5024   switch (Opcode) {
5025   case ISD::ADD: break;
5026   case ISD::SUB: Offset = -uint64_t(Offset); break;
5027   default: return SDValue();
5028   }
5029   return getGlobalAddress(GA->getGlobal(), SDLoc(C2), VT,
5030                           GA->getOffset() + uint64_t(Offset));
5031 }
5032 
5033 bool SelectionDAG::isUndef(unsigned Opcode, ArrayRef<SDValue> Ops) {
5034   switch (Opcode) {
5035   case ISD::SDIV:
5036   case ISD::UDIV:
5037   case ISD::SREM:
5038   case ISD::UREM: {
5039     // If a divisor is zero/undef or any element of a divisor vector is
5040     // zero/undef, the whole op is undef.
5041     assert(Ops.size() == 2 && "Div/rem should have 2 operands");
5042     SDValue Divisor = Ops[1];
5043     if (Divisor.isUndef() || isNullConstant(Divisor))
5044       return true;
5045 
5046     return ISD::isBuildVectorOfConstantSDNodes(Divisor.getNode()) &&
5047            llvm::any_of(Divisor->op_values(),
5048                         [](SDValue V) { return V.isUndef() ||
5049                                         isNullConstant(V); });
5050     // TODO: Handle signed overflow.
5051   }
5052   // TODO: Handle oversized shifts.
5053   default:
5054     return false;
5055   }
5056 }
5057 
5058 SDValue SelectionDAG::FoldConstantArithmetic(unsigned Opcode, const SDLoc &DL,
5059                                              EVT VT, ArrayRef<SDValue> Ops) {
5060   // If the opcode is a target-specific ISD node, there's nothing we can
5061   // do here and the operand rules may not line up with the below, so
5062   // bail early.
5063   // We can't create a scalar CONCAT_VECTORS so skip it. It will break
5064   // for concats involving SPLAT_VECTOR. Concats of BUILD_VECTORS are handled by
5065   // foldCONCAT_VECTORS in getNode before this is called.
5066   if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::CONCAT_VECTORS)
5067     return SDValue();
5068 
5069   // For now, the array Ops should only contain two values.
5070   // This enforcement will be removed once this function is merged with
5071   // FoldConstantVectorArithmetic
5072   if (Ops.size() != 2)
5073     return SDValue();
5074 
5075   if (isUndef(Opcode, Ops))
5076     return getUNDEF(VT);
5077 
5078   SDNode *N1 = Ops[0].getNode();
5079   SDNode *N2 = Ops[1].getNode();
5080 
5081   // Handle the case of two scalars.
5082   if (auto *C1 = dyn_cast<ConstantSDNode>(N1)) {
5083     if (auto *C2 = dyn_cast<ConstantSDNode>(N2)) {
5084       if (C1->isOpaque() || C2->isOpaque())
5085         return SDValue();
5086 
5087       Optional<APInt> FoldAttempt =
5088           FoldValue(Opcode, C1->getAPIntValue(), C2->getAPIntValue());
5089       if (!FoldAttempt)
5090         return SDValue();
5091 
5092       SDValue Folded = getConstant(FoldAttempt.getValue(), DL, VT);
5093       assert((!Folded || !VT.isVector()) &&
5094              "Can't fold vectors ops with scalar operands");
5095       return Folded;
5096     }
5097   }
5098 
5099   // fold (add Sym, c) -> Sym+c
5100   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N1))
5101     return FoldSymbolOffset(Opcode, VT, GA, N2);
5102   if (TLI->isCommutativeBinOp(Opcode))
5103     if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N2))
5104       return FoldSymbolOffset(Opcode, VT, GA, N1);
5105 
5106   // For fixed width vectors, extract each constant element and fold them
5107   // individually. Either input may be an undef value.
5108   bool IsBVOrSV1 = N1->getOpcode() == ISD::BUILD_VECTOR ||
5109                    N1->getOpcode() == ISD::SPLAT_VECTOR;
5110   if (!IsBVOrSV1 && !N1->isUndef())
5111     return SDValue();
5112   bool IsBVOrSV2 = N2->getOpcode() == ISD::BUILD_VECTOR ||
5113                    N2->getOpcode() == ISD::SPLAT_VECTOR;
5114   if (!IsBVOrSV2 && !N2->isUndef())
5115     return SDValue();
5116   // If both operands are undef, that's handled the same way as scalars.
5117   if (!IsBVOrSV1 && !IsBVOrSV2)
5118     return SDValue();
5119 
5120   EVT SVT = VT.getScalarType();
5121   EVT LegalSVT = SVT;
5122   if (NewNodesMustHaveLegalTypes && LegalSVT.isInteger()) {
5123     LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT);
5124     if (LegalSVT.bitsLT(SVT))
5125       return SDValue();
5126   }
5127 
5128   SmallVector<SDValue, 4> Outputs;
5129   unsigned NumOps = 0;
5130   if (IsBVOrSV1)
5131     NumOps = std::max(NumOps, N1->getNumOperands());
5132   if (IsBVOrSV2)
5133     NumOps = std::max(NumOps, N2->getNumOperands());
5134   assert(NumOps != 0 && "Expected non-zero operands");
5135   // Scalable vectors should only be SPLAT_VECTOR or UNDEF here. We only need
5136   // one iteration for that.
5137   assert((!VT.isScalableVector() || NumOps == 1) &&
5138          "Scalar vector should only have one scalar");
5139 
5140   for (unsigned I = 0; I != NumOps; ++I) {
5141     // We can have a fixed length SPLAT_VECTOR and a BUILD_VECTOR so we need
5142     // to use operand 0 of the SPLAT_VECTOR for each fixed element.
5143     SDValue V1;
5144     if (N1->getOpcode() == ISD::BUILD_VECTOR)
5145       V1 = N1->getOperand(I);
5146     else if (N1->getOpcode() == ISD::SPLAT_VECTOR)
5147       V1 = N1->getOperand(0);
5148     else
5149       V1 = getUNDEF(SVT);
5150 
5151     SDValue V2;
5152     if (N2->getOpcode() == ISD::BUILD_VECTOR)
5153       V2 = N2->getOperand(I);
5154     else if (N2->getOpcode() == ISD::SPLAT_VECTOR)
5155       V2 = N2->getOperand(0);
5156     else
5157       V2 = getUNDEF(SVT);
5158 
5159     if (SVT.isInteger()) {
5160       if (V1.getValueType().bitsGT(SVT))
5161         V1 = getNode(ISD::TRUNCATE, DL, SVT, V1);
5162       if (V2.getValueType().bitsGT(SVT))
5163         V2 = getNode(ISD::TRUNCATE, DL, SVT, V2);
5164     }
5165 
5166     if (V1.getValueType() != SVT || V2.getValueType() != SVT)
5167       return SDValue();
5168 
5169     // Fold one vector element.
5170     SDValue ScalarResult = getNode(Opcode, DL, SVT, V1, V2);
5171     if (LegalSVT != SVT)
5172       ScalarResult = getNode(ISD::SIGN_EXTEND, DL, LegalSVT, ScalarResult);
5173 
5174     // Scalar folding only succeeded if the result is a constant or UNDEF.
5175     if (!ScalarResult.isUndef() && ScalarResult.getOpcode() != ISD::Constant &&
5176         ScalarResult.getOpcode() != ISD::ConstantFP)
5177       return SDValue();
5178     Outputs.push_back(ScalarResult);
5179   }
5180 
5181   if (N1->getOpcode() == ISD::BUILD_VECTOR ||
5182       N2->getOpcode() == ISD::BUILD_VECTOR) {
5183     assert(VT.getVectorNumElements() == Outputs.size() &&
5184            "Vector size mismatch!");
5185 
5186     // Build a big vector out of the scalar elements we generated.
5187     return getBuildVector(VT, SDLoc(), Outputs);
5188   }
5189 
5190   assert((N1->getOpcode() == ISD::SPLAT_VECTOR ||
5191           N2->getOpcode() == ISD::SPLAT_VECTOR) &&
5192          "One operand should be a splat vector");
5193 
5194   assert(Outputs.size() == 1 && "Vector size mismatch!");
5195   return getSplatVector(VT, SDLoc(), Outputs[0]);
5196 }
5197 
5198 // TODO: Merge with FoldConstantArithmetic
5199 SDValue SelectionDAG::FoldConstantVectorArithmetic(unsigned Opcode,
5200                                                    const SDLoc &DL, EVT VT,
5201                                                    ArrayRef<SDValue> Ops,
5202                                                    const SDNodeFlags Flags) {
5203   // If the opcode is a target-specific ISD node, there's nothing we can
5204   // do here and the operand rules may not line up with the below, so
5205   // bail early.
5206   if (Opcode >= ISD::BUILTIN_OP_END)
5207     return SDValue();
5208 
5209   if (isUndef(Opcode, Ops))
5210     return getUNDEF(VT);
5211 
5212   // We can only fold vectors - maybe merge with FoldConstantArithmetic someday?
5213   if (!VT.isVector())
5214     return SDValue();
5215 
5216   // TODO: All the folds below are performed lane-by-lane and assume a fixed
5217   // vector width, however we should be able to do constant folds involving
5218   // splat vector nodes too.
5219   if (VT.isScalableVector())
5220     return SDValue();
5221 
5222   // From this point onwards all vectors are assumed to be fixed width.
5223   unsigned NumElts = VT.getVectorNumElements();
5224 
5225   auto IsScalarOrSameVectorSize = [&](const SDValue &Op) {
5226     return !Op.getValueType().isVector() ||
5227            Op.getValueType().getVectorNumElements() == NumElts;
5228   };
5229 
5230   auto IsConstantBuildVectorOrUndef = [&](const SDValue &Op) {
5231     BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op);
5232     return (Op.isUndef()) || (Op.getOpcode() == ISD::CONDCODE) ||
5233            (BV && BV->isConstant());
5234   };
5235 
5236   // All operands must be vector types with the same number of elements as
5237   // the result type and must be either UNDEF or a build vector of constant
5238   // or UNDEF scalars.
5239   if (!llvm::all_of(Ops, IsConstantBuildVectorOrUndef) ||
5240       !llvm::all_of(Ops, IsScalarOrSameVectorSize))
5241     return SDValue();
5242 
5243   // If we are comparing vectors, then the result needs to be a i1 boolean
5244   // that is then sign-extended back to the legal result type.
5245   EVT SVT = (Opcode == ISD::SETCC ? MVT::i1 : VT.getScalarType());
5246 
5247   // Find legal integer scalar type for constant promotion and
5248   // ensure that its scalar size is at least as large as source.
5249   EVT LegalSVT = VT.getScalarType();
5250   if (NewNodesMustHaveLegalTypes && LegalSVT.isInteger()) {
5251     LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT);
5252     if (LegalSVT.bitsLT(VT.getScalarType()))
5253       return SDValue();
5254   }
5255 
5256   // Constant fold each scalar lane separately.
5257   SmallVector<SDValue, 4> ScalarResults;
5258   for (unsigned i = 0; i != NumElts; i++) {
5259     SmallVector<SDValue, 4> ScalarOps;
5260     for (SDValue Op : Ops) {
5261       EVT InSVT = Op.getValueType().getScalarType();
5262       BuildVectorSDNode *InBV = dyn_cast<BuildVectorSDNode>(Op);
5263       if (!InBV) {
5264         // We've checked that this is UNDEF or a constant of some kind.
5265         if (Op.isUndef())
5266           ScalarOps.push_back(getUNDEF(InSVT));
5267         else
5268           ScalarOps.push_back(Op);
5269         continue;
5270       }
5271 
5272       SDValue ScalarOp = InBV->getOperand(i);
5273       EVT ScalarVT = ScalarOp.getValueType();
5274 
5275       // Build vector (integer) scalar operands may need implicit
5276       // truncation - do this before constant folding.
5277       if (ScalarVT.isInteger() && ScalarVT.bitsGT(InSVT))
5278         ScalarOp = getNode(ISD::TRUNCATE, DL, InSVT, ScalarOp);
5279 
5280       ScalarOps.push_back(ScalarOp);
5281     }
5282 
5283     // Constant fold the scalar operands.
5284     SDValue ScalarResult = getNode(Opcode, DL, SVT, ScalarOps, Flags);
5285 
5286     // Legalize the (integer) scalar constant if necessary.
5287     if (LegalSVT != SVT)
5288       ScalarResult = getNode(ISD::SIGN_EXTEND, DL, LegalSVT, ScalarResult);
5289 
5290     // Scalar folding only succeeded if the result is a constant or UNDEF.
5291     if (!ScalarResult.isUndef() && ScalarResult.getOpcode() != ISD::Constant &&
5292         ScalarResult.getOpcode() != ISD::ConstantFP)
5293       return SDValue();
5294     ScalarResults.push_back(ScalarResult);
5295   }
5296 
5297   SDValue V = getBuildVector(VT, DL, ScalarResults);
5298   NewSDValueDbgMsg(V, "New node fold constant vector: ", this);
5299   return V;
5300 }
5301 
5302 SDValue SelectionDAG::foldConstantFPMath(unsigned Opcode, const SDLoc &DL,
5303                                          EVT VT, SDValue N1, SDValue N2) {
5304   // TODO: We don't do any constant folding for strict FP opcodes here, but we
5305   //       should. That will require dealing with a potentially non-default
5306   //       rounding mode, checking the "opStatus" return value from the APFloat
5307   //       math calculations, and possibly other variations.
5308   auto *N1CFP = dyn_cast<ConstantFPSDNode>(N1.getNode());
5309   auto *N2CFP = dyn_cast<ConstantFPSDNode>(N2.getNode());
5310   if (N1CFP && N2CFP) {
5311     APFloat C1 = N1CFP->getValueAPF(), C2 = N2CFP->getValueAPF();
5312     switch (Opcode) {
5313     case ISD::FADD:
5314       C1.add(C2, APFloat::rmNearestTiesToEven);
5315       return getConstantFP(C1, DL, VT);
5316     case ISD::FSUB:
5317       C1.subtract(C2, APFloat::rmNearestTiesToEven);
5318       return getConstantFP(C1, DL, VT);
5319     case ISD::FMUL:
5320       C1.multiply(C2, APFloat::rmNearestTiesToEven);
5321       return getConstantFP(C1, DL, VT);
5322     case ISD::FDIV:
5323       C1.divide(C2, APFloat::rmNearestTiesToEven);
5324       return getConstantFP(C1, DL, VT);
5325     case ISD::FREM:
5326       C1.mod(C2);
5327       return getConstantFP(C1, DL, VT);
5328     case ISD::FCOPYSIGN:
5329       C1.copySign(C2);
5330       return getConstantFP(C1, DL, VT);
5331     default: break;
5332     }
5333   }
5334   if (N1CFP && Opcode == ISD::FP_ROUND) {
5335     APFloat C1 = N1CFP->getValueAPF();    // make copy
5336     bool Unused;
5337     // This can return overflow, underflow, or inexact; we don't care.
5338     // FIXME need to be more flexible about rounding mode.
5339     (void) C1.convert(EVTToAPFloatSemantics(VT), APFloat::rmNearestTiesToEven,
5340                       &Unused);
5341     return getConstantFP(C1, DL, VT);
5342   }
5343 
5344   switch (Opcode) {
5345   case ISD::FSUB:
5346     // -0.0 - undef --> undef (consistent with "fneg undef")
5347     if (N1CFP && N1CFP->getValueAPF().isNegZero() && N2.isUndef())
5348       return getUNDEF(VT);
5349     LLVM_FALLTHROUGH;
5350 
5351   case ISD::FADD:
5352   case ISD::FMUL:
5353   case ISD::FDIV:
5354   case ISD::FREM:
5355     // If both operands are undef, the result is undef. If 1 operand is undef,
5356     // the result is NaN. This should match the behavior of the IR optimizer.
5357     if (N1.isUndef() && N2.isUndef())
5358       return getUNDEF(VT);
5359     if (N1.isUndef() || N2.isUndef())
5360       return getConstantFP(APFloat::getNaN(EVTToAPFloatSemantics(VT)), DL, VT);
5361   }
5362   return SDValue();
5363 }
5364 
5365 SDValue SelectionDAG::getAssertAlign(const SDLoc &DL, SDValue Val, Align A) {
5366   assert(Val.getValueType().isInteger() && "Invalid AssertAlign!");
5367 
5368   // There's no need to assert on a byte-aligned pointer. All pointers are at
5369   // least byte aligned.
5370   if (A == Align(1))
5371     return Val;
5372 
5373   FoldingSetNodeID ID;
5374   AddNodeIDNode(ID, ISD::AssertAlign, getVTList(Val.getValueType()), {Val});
5375   ID.AddInteger(A.value());
5376 
5377   void *IP = nullptr;
5378   if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
5379     return SDValue(E, 0);
5380 
5381   auto *N = newSDNode<AssertAlignSDNode>(DL.getIROrder(), DL.getDebugLoc(),
5382                                          Val.getValueType(), A);
5383   createOperands(N, {Val});
5384 
5385   CSEMap.InsertNode(N, IP);
5386   InsertNode(N);
5387 
5388   SDValue V(N, 0);
5389   NewSDValueDbgMsg(V, "Creating new node: ", this);
5390   return V;
5391 }
5392 
5393 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
5394                               SDValue N1, SDValue N2) {
5395   SDNodeFlags Flags;
5396   if (Inserter)
5397     Flags = Inserter->getFlags();
5398   return getNode(Opcode, DL, VT, N1, N2, Flags);
5399 }
5400 
5401 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
5402                               SDValue N1, SDValue N2, const SDNodeFlags Flags) {
5403   assert(N1.getOpcode() != ISD::DELETED_NODE &&
5404          N2.getOpcode() != ISD::DELETED_NODE &&
5405          "Operand is DELETED_NODE!");
5406   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
5407   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
5408   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
5409   ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2);
5410 
5411   // Canonicalize constant to RHS if commutative.
5412   if (TLI->isCommutativeBinOp(Opcode)) {
5413     if (N1C && !N2C) {
5414       std::swap(N1C, N2C);
5415       std::swap(N1, N2);
5416     } else if (N1CFP && !N2CFP) {
5417       std::swap(N1CFP, N2CFP);
5418       std::swap(N1, N2);
5419     }
5420   }
5421 
5422   switch (Opcode) {
5423   default: break;
5424   case ISD::TokenFactor:
5425     assert(VT == MVT::Other && N1.getValueType() == MVT::Other &&
5426            N2.getValueType() == MVT::Other && "Invalid token factor!");
5427     // Fold trivial token factors.
5428     if (N1.getOpcode() == ISD::EntryToken) return N2;
5429     if (N2.getOpcode() == ISD::EntryToken) return N1;
5430     if (N1 == N2) return N1;
5431     break;
5432   case ISD::BUILD_VECTOR: {
5433     // Attempt to simplify BUILD_VECTOR.
5434     SDValue Ops[] = {N1, N2};
5435     if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
5436       return V;
5437     break;
5438   }
5439   case ISD::CONCAT_VECTORS: {
5440     SDValue Ops[] = {N1, N2};
5441     if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this))
5442       return V;
5443     break;
5444   }
5445   case ISD::AND:
5446     assert(VT.isInteger() && "This operator does not apply to FP types!");
5447     assert(N1.getValueType() == N2.getValueType() &&
5448            N1.getValueType() == VT && "Binary operator types must match!");
5449     // (X & 0) -> 0.  This commonly occurs when legalizing i64 values, so it's
5450     // worth handling here.
5451     if (N2C && N2C->isNullValue())
5452       return N2;
5453     if (N2C && N2C->isAllOnesValue())  // X & -1 -> X
5454       return N1;
5455     break;
5456   case ISD::OR:
5457   case ISD::XOR:
5458   case ISD::ADD:
5459   case ISD::SUB:
5460     assert(VT.isInteger() && "This operator does not apply to FP types!");
5461     assert(N1.getValueType() == N2.getValueType() &&
5462            N1.getValueType() == VT && "Binary operator types must match!");
5463     // (X ^|+- 0) -> X.  This commonly occurs when legalizing i64 values, so
5464     // it's worth handling here.
5465     if (N2C && N2C->isNullValue())
5466       return N1;
5467     if ((Opcode == ISD::ADD || Opcode == ISD::SUB) && VT.isVector() &&
5468         VT.getVectorElementType() == MVT::i1)
5469       return getNode(ISD::XOR, DL, VT, N1, N2);
5470     break;
5471   case ISD::MUL:
5472     assert(VT.isInteger() && "This operator does not apply to FP types!");
5473     assert(N1.getValueType() == N2.getValueType() &&
5474            N1.getValueType() == VT && "Binary operator types must match!");
5475     if (VT.isVector() && VT.getVectorElementType() == MVT::i1)
5476       return getNode(ISD::AND, DL, VT, N1, N2);
5477     if (N2C && (N1.getOpcode() == ISD::VSCALE) && Flags.hasNoSignedWrap()) {
5478       const APInt &MulImm = N1->getConstantOperandAPInt(0);
5479       const APInt &N2CImm = N2C->getAPIntValue();
5480       return getVScale(DL, VT, MulImm * N2CImm);
5481     }
5482     break;
5483   case ISD::UDIV:
5484   case ISD::UREM:
5485   case ISD::MULHU:
5486   case ISD::MULHS:
5487   case ISD::SDIV:
5488   case ISD::SREM:
5489   case ISD::SADDSAT:
5490   case ISD::SSUBSAT:
5491   case ISD::UADDSAT:
5492   case ISD::USUBSAT:
5493     assert(VT.isInteger() && "This operator does not apply to FP types!");
5494     assert(N1.getValueType() == N2.getValueType() &&
5495            N1.getValueType() == VT && "Binary operator types must match!");
5496     if (VT.isVector() && VT.getVectorElementType() == MVT::i1) {
5497       // fold (add_sat x, y) -> (or x, y) for bool types.
5498       if (Opcode == ISD::SADDSAT || Opcode == ISD::UADDSAT)
5499         return getNode(ISD::OR, DL, VT, N1, N2);
5500       // fold (sub_sat x, y) -> (and x, ~y) for bool types.
5501       if (Opcode == ISD::SSUBSAT || Opcode == ISD::USUBSAT)
5502         return getNode(ISD::AND, DL, VT, N1, getNOT(DL, N2, VT));
5503     }
5504     break;
5505   case ISD::SMIN:
5506   case ISD::UMAX:
5507     assert(VT.isInteger() && "This operator does not apply to FP types!");
5508     assert(N1.getValueType() == N2.getValueType() &&
5509            N1.getValueType() == VT && "Binary operator types must match!");
5510     if (VT.isVector() && VT.getVectorElementType() == MVT::i1)
5511       return getNode(ISD::OR, DL, VT, N1, N2);
5512     break;
5513   case ISD::SMAX:
5514   case ISD::UMIN:
5515     assert(VT.isInteger() && "This operator does not apply to FP types!");
5516     assert(N1.getValueType() == N2.getValueType() &&
5517            N1.getValueType() == VT && "Binary operator types must match!");
5518     if (VT.isVector() && VT.getVectorElementType() == MVT::i1)
5519       return getNode(ISD::AND, DL, VT, N1, N2);
5520     break;
5521   case ISD::FADD:
5522   case ISD::FSUB:
5523   case ISD::FMUL:
5524   case ISD::FDIV:
5525   case ISD::FREM:
5526     assert(VT.isFloatingPoint() && "This operator only applies to FP types!");
5527     assert(N1.getValueType() == N2.getValueType() &&
5528            N1.getValueType() == VT && "Binary operator types must match!");
5529     if (SDValue V = simplifyFPBinop(Opcode, N1, N2, Flags))
5530       return V;
5531     break;
5532   case ISD::FCOPYSIGN:   // N1 and result must match.  N1/N2 need not match.
5533     assert(N1.getValueType() == VT &&
5534            N1.getValueType().isFloatingPoint() &&
5535            N2.getValueType().isFloatingPoint() &&
5536            "Invalid FCOPYSIGN!");
5537     break;
5538   case ISD::SHL:
5539     if (N2C && (N1.getOpcode() == ISD::VSCALE) && Flags.hasNoSignedWrap()) {
5540       const APInt &MulImm = N1->getConstantOperandAPInt(0);
5541       const APInt &ShiftImm = N2C->getAPIntValue();
5542       return getVScale(DL, VT, MulImm << ShiftImm);
5543     }
5544     LLVM_FALLTHROUGH;
5545   case ISD::SRA:
5546   case ISD::SRL:
5547     if (SDValue V = simplifyShift(N1, N2))
5548       return V;
5549     LLVM_FALLTHROUGH;
5550   case ISD::ROTL:
5551   case ISD::ROTR:
5552     assert(VT == N1.getValueType() &&
5553            "Shift operators return type must be the same as their first arg");
5554     assert(VT.isInteger() && N2.getValueType().isInteger() &&
5555            "Shifts only work on integers");
5556     assert((!VT.isVector() || VT == N2.getValueType()) &&
5557            "Vector shift amounts must be in the same as their first arg");
5558     // Verify that the shift amount VT is big enough to hold valid shift
5559     // amounts.  This catches things like trying to shift an i1024 value by an
5560     // i8, which is easy to fall into in generic code that uses
5561     // TLI.getShiftAmount().
5562     assert(N2.getValueType().getScalarSizeInBits() >=
5563                Log2_32_Ceil(VT.getScalarSizeInBits()) &&
5564            "Invalid use of small shift amount with oversized value!");
5565 
5566     // Always fold shifts of i1 values so the code generator doesn't need to
5567     // handle them.  Since we know the size of the shift has to be less than the
5568     // size of the value, the shift/rotate count is guaranteed to be zero.
5569     if (VT == MVT::i1)
5570       return N1;
5571     if (N2C && N2C->isNullValue())
5572       return N1;
5573     break;
5574   case ISD::FP_ROUND:
5575     assert(VT.isFloatingPoint() &&
5576            N1.getValueType().isFloatingPoint() &&
5577            VT.bitsLE(N1.getValueType()) &&
5578            N2C && (N2C->getZExtValue() == 0 || N2C->getZExtValue() == 1) &&
5579            "Invalid FP_ROUND!");
5580     if (N1.getValueType() == VT) return N1;  // noop conversion.
5581     break;
5582   case ISD::AssertSext:
5583   case ISD::AssertZext: {
5584     EVT EVT = cast<VTSDNode>(N2)->getVT();
5585     assert(VT == N1.getValueType() && "Not an inreg extend!");
5586     assert(VT.isInteger() && EVT.isInteger() &&
5587            "Cannot *_EXTEND_INREG FP types");
5588     assert(!EVT.isVector() &&
5589            "AssertSExt/AssertZExt type should be the vector element type "
5590            "rather than the vector type!");
5591     assert(EVT.bitsLE(VT.getScalarType()) && "Not extending!");
5592     if (VT.getScalarType() == EVT) return N1; // noop assertion.
5593     break;
5594   }
5595   case ISD::SIGN_EXTEND_INREG: {
5596     EVT EVT = cast<VTSDNode>(N2)->getVT();
5597     assert(VT == N1.getValueType() && "Not an inreg extend!");
5598     assert(VT.isInteger() && EVT.isInteger() &&
5599            "Cannot *_EXTEND_INREG FP types");
5600     assert(EVT.isVector() == VT.isVector() &&
5601            "SIGN_EXTEND_INREG type should be vector iff the operand "
5602            "type is vector!");
5603     assert((!EVT.isVector() ||
5604             EVT.getVectorElementCount() == VT.getVectorElementCount()) &&
5605            "Vector element counts must match in SIGN_EXTEND_INREG");
5606     assert(EVT.bitsLE(VT) && "Not extending!");
5607     if (EVT == VT) return N1;  // Not actually extending
5608 
5609     auto SignExtendInReg = [&](APInt Val, llvm::EVT ConstantVT) {
5610       unsigned FromBits = EVT.getScalarSizeInBits();
5611       Val <<= Val.getBitWidth() - FromBits;
5612       Val.ashrInPlace(Val.getBitWidth() - FromBits);
5613       return getConstant(Val, DL, ConstantVT);
5614     };
5615 
5616     if (N1C) {
5617       const APInt &Val = N1C->getAPIntValue();
5618       return SignExtendInReg(Val, VT);
5619     }
5620     if (ISD::isBuildVectorOfConstantSDNodes(N1.getNode())) {
5621       SmallVector<SDValue, 8> Ops;
5622       llvm::EVT OpVT = N1.getOperand(0).getValueType();
5623       for (int i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
5624         SDValue Op = N1.getOperand(i);
5625         if (Op.isUndef()) {
5626           Ops.push_back(getUNDEF(OpVT));
5627           continue;
5628         }
5629         ConstantSDNode *C = cast<ConstantSDNode>(Op);
5630         APInt Val = C->getAPIntValue();
5631         Ops.push_back(SignExtendInReg(Val, OpVT));
5632       }
5633       return getBuildVector(VT, DL, Ops);
5634     }
5635     break;
5636   }
5637   case ISD::EXTRACT_VECTOR_ELT:
5638     assert(VT.getSizeInBits() >= N1.getValueType().getScalarSizeInBits() &&
5639            "The result of EXTRACT_VECTOR_ELT must be at least as wide as the \
5640              element type of the vector.");
5641 
5642     // Extract from an undefined value or using an undefined index is undefined.
5643     if (N1.isUndef() || N2.isUndef())
5644       return getUNDEF(VT);
5645 
5646     // EXTRACT_VECTOR_ELT of out-of-bounds element is an UNDEF for fixed length
5647     // vectors. For scalable vectors we will provide appropriate support for
5648     // dealing with arbitrary indices.
5649     if (N2C && N1.getValueType().isFixedLengthVector() &&
5650         N2C->getAPIntValue().uge(N1.getValueType().getVectorNumElements()))
5651       return getUNDEF(VT);
5652 
5653     // EXTRACT_VECTOR_ELT of CONCAT_VECTORS is often formed while lowering is
5654     // expanding copies of large vectors from registers. This only works for
5655     // fixed length vectors, since we need to know the exact number of
5656     // elements.
5657     if (N2C && N1.getOperand(0).getValueType().isFixedLengthVector() &&
5658         N1.getOpcode() == ISD::CONCAT_VECTORS && N1.getNumOperands() > 0) {
5659       unsigned Factor =
5660         N1.getOperand(0).getValueType().getVectorNumElements();
5661       return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
5662                      N1.getOperand(N2C->getZExtValue() / Factor),
5663                      getVectorIdxConstant(N2C->getZExtValue() % Factor, DL));
5664     }
5665 
5666     // EXTRACT_VECTOR_ELT of BUILD_VECTOR or SPLAT_VECTOR is often formed while
5667     // lowering is expanding large vector constants.
5668     if (N2C && (N1.getOpcode() == ISD::BUILD_VECTOR ||
5669                 N1.getOpcode() == ISD::SPLAT_VECTOR)) {
5670       assert((N1.getOpcode() != ISD::BUILD_VECTOR ||
5671               N1.getValueType().isFixedLengthVector()) &&
5672              "BUILD_VECTOR used for scalable vectors");
5673       unsigned Index =
5674           N1.getOpcode() == ISD::BUILD_VECTOR ? N2C->getZExtValue() : 0;
5675       SDValue Elt = N1.getOperand(Index);
5676 
5677       if (VT != Elt.getValueType())
5678         // If the vector element type is not legal, the BUILD_VECTOR operands
5679         // are promoted and implicitly truncated, and the result implicitly
5680         // extended. Make that explicit here.
5681         Elt = getAnyExtOrTrunc(Elt, DL, VT);
5682 
5683       return Elt;
5684     }
5685 
5686     // EXTRACT_VECTOR_ELT of INSERT_VECTOR_ELT is often formed when vector
5687     // operations are lowered to scalars.
5688     if (N1.getOpcode() == ISD::INSERT_VECTOR_ELT) {
5689       // If the indices are the same, return the inserted element else
5690       // if the indices are known different, extract the element from
5691       // the original vector.
5692       SDValue N1Op2 = N1.getOperand(2);
5693       ConstantSDNode *N1Op2C = dyn_cast<ConstantSDNode>(N1Op2);
5694 
5695       if (N1Op2C && N2C) {
5696         if (N1Op2C->getZExtValue() == N2C->getZExtValue()) {
5697           if (VT == N1.getOperand(1).getValueType())
5698             return N1.getOperand(1);
5699           return getSExtOrTrunc(N1.getOperand(1), DL, VT);
5700         }
5701         return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0), N2);
5702       }
5703     }
5704 
5705     // EXTRACT_VECTOR_ELT of v1iX EXTRACT_SUBVECTOR could be formed
5706     // when vector types are scalarized and v1iX is legal.
5707     // vextract (v1iX extract_subvector(vNiX, Idx)) -> vextract(vNiX,Idx).
5708     // Here we are completely ignoring the extract element index (N2),
5709     // which is fine for fixed width vectors, since any index other than 0
5710     // is undefined anyway. However, this cannot be ignored for scalable
5711     // vectors - in theory we could support this, but we don't want to do this
5712     // without a profitability check.
5713     if (N1.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
5714         N1.getValueType().isFixedLengthVector() &&
5715         N1.getValueType().getVectorNumElements() == 1) {
5716       return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0),
5717                      N1.getOperand(1));
5718     }
5719     break;
5720   case ISD::EXTRACT_ELEMENT:
5721     assert(N2C && (unsigned)N2C->getZExtValue() < 2 && "Bad EXTRACT_ELEMENT!");
5722     assert(!N1.getValueType().isVector() && !VT.isVector() &&
5723            (N1.getValueType().isInteger() == VT.isInteger()) &&
5724            N1.getValueType() != VT &&
5725            "Wrong types for EXTRACT_ELEMENT!");
5726 
5727     // EXTRACT_ELEMENT of BUILD_PAIR is often formed while legalize is expanding
5728     // 64-bit integers into 32-bit parts.  Instead of building the extract of
5729     // the BUILD_PAIR, only to have legalize rip it apart, just do it now.
5730     if (N1.getOpcode() == ISD::BUILD_PAIR)
5731       return N1.getOperand(N2C->getZExtValue());
5732 
5733     // EXTRACT_ELEMENT of a constant int is also very common.
5734     if (N1C) {
5735       unsigned ElementSize = VT.getSizeInBits();
5736       unsigned Shift = ElementSize * N2C->getZExtValue();
5737       const APInt &Val = N1C->getAPIntValue();
5738       return getConstant(Val.extractBits(ElementSize, Shift), DL, VT);
5739     }
5740     break;
5741   case ISD::EXTRACT_SUBVECTOR:
5742     EVT N1VT = N1.getValueType();
5743     assert(VT.isVector() && N1VT.isVector() &&
5744            "Extract subvector VTs must be vectors!");
5745     assert(VT.getVectorElementType() == N1VT.getVectorElementType() &&
5746            "Extract subvector VTs must have the same element type!");
5747     assert((VT.isFixedLengthVector() || N1VT.isScalableVector()) &&
5748            "Cannot extract a scalable vector from a fixed length vector!");
5749     assert((VT.isScalableVector() != N1VT.isScalableVector() ||
5750             VT.getVectorMinNumElements() <= N1VT.getVectorMinNumElements()) &&
5751            "Extract subvector must be from larger vector to smaller vector!");
5752     assert(N2C && "Extract subvector index must be a constant");
5753     assert((VT.isScalableVector() != N1VT.isScalableVector() ||
5754             (VT.getVectorMinNumElements() + N2C->getZExtValue()) <=
5755                 N1VT.getVectorMinNumElements()) &&
5756            "Extract subvector overflow!");
5757     assert(N2C->getAPIntValue().getBitWidth() ==
5758                TLI->getVectorIdxTy(getDataLayout()).getFixedSizeInBits() &&
5759            "Constant index for EXTRACT_SUBVECTOR has an invalid size");
5760 
5761     // Trivial extraction.
5762     if (VT == N1VT)
5763       return N1;
5764 
5765     // EXTRACT_SUBVECTOR of an UNDEF is an UNDEF.
5766     if (N1.isUndef())
5767       return getUNDEF(VT);
5768 
5769     // EXTRACT_SUBVECTOR of CONCAT_VECTOR can be simplified if the pieces of
5770     // the concat have the same type as the extract.
5771     if (N1.getOpcode() == ISD::CONCAT_VECTORS && N1.getNumOperands() > 0 &&
5772         VT == N1.getOperand(0).getValueType()) {
5773       unsigned Factor = VT.getVectorMinNumElements();
5774       return N1.getOperand(N2C->getZExtValue() / Factor);
5775     }
5776 
5777     // EXTRACT_SUBVECTOR of INSERT_SUBVECTOR is often created
5778     // during shuffle legalization.
5779     if (N1.getOpcode() == ISD::INSERT_SUBVECTOR && N2 == N1.getOperand(2) &&
5780         VT == N1.getOperand(1).getValueType())
5781       return N1.getOperand(1);
5782     break;
5783   }
5784 
5785   // Perform trivial constant folding.
5786   if (SDValue SV = FoldConstantArithmetic(Opcode, DL, VT, {N1, N2}))
5787     return SV;
5788 
5789   if (SDValue V = foldConstantFPMath(Opcode, DL, VT, N1, N2))
5790     return V;
5791 
5792   // Canonicalize an UNDEF to the RHS, even over a constant.
5793   if (N1.isUndef()) {
5794     if (TLI->isCommutativeBinOp(Opcode)) {
5795       std::swap(N1, N2);
5796     } else {
5797       switch (Opcode) {
5798       case ISD::SIGN_EXTEND_INREG:
5799       case ISD::SUB:
5800         return getUNDEF(VT);     // fold op(undef, arg2) -> undef
5801       case ISD::UDIV:
5802       case ISD::SDIV:
5803       case ISD::UREM:
5804       case ISD::SREM:
5805       case ISD::SSUBSAT:
5806       case ISD::USUBSAT:
5807         return getConstant(0, DL, VT);    // fold op(undef, arg2) -> 0
5808       }
5809     }
5810   }
5811 
5812   // Fold a bunch of operators when the RHS is undef.
5813   if (N2.isUndef()) {
5814     switch (Opcode) {
5815     case ISD::XOR:
5816       if (N1.isUndef())
5817         // Handle undef ^ undef -> 0 special case. This is a common
5818         // idiom (misuse).
5819         return getConstant(0, DL, VT);
5820       LLVM_FALLTHROUGH;
5821     case ISD::ADD:
5822     case ISD::SUB:
5823     case ISD::UDIV:
5824     case ISD::SDIV:
5825     case ISD::UREM:
5826     case ISD::SREM:
5827       return getUNDEF(VT);       // fold op(arg1, undef) -> undef
5828     case ISD::MUL:
5829     case ISD::AND:
5830     case ISD::SSUBSAT:
5831     case ISD::USUBSAT:
5832       return getConstant(0, DL, VT);  // fold op(arg1, undef) -> 0
5833     case ISD::OR:
5834     case ISD::SADDSAT:
5835     case ISD::UADDSAT:
5836       return getAllOnesConstant(DL, VT);
5837     }
5838   }
5839 
5840   // Memoize this node if possible.
5841   SDNode *N;
5842   SDVTList VTs = getVTList(VT);
5843   SDValue Ops[] = {N1, N2};
5844   if (VT != MVT::Glue) {
5845     FoldingSetNodeID ID;
5846     AddNodeIDNode(ID, Opcode, VTs, Ops);
5847     void *IP = nullptr;
5848     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
5849       E->intersectFlagsWith(Flags);
5850       return SDValue(E, 0);
5851     }
5852 
5853     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
5854     N->setFlags(Flags);
5855     createOperands(N, Ops);
5856     CSEMap.InsertNode(N, IP);
5857   } else {
5858     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
5859     createOperands(N, Ops);
5860   }
5861 
5862   InsertNode(N);
5863   SDValue V = SDValue(N, 0);
5864   NewSDValueDbgMsg(V, "Creating new node: ", this);
5865   return V;
5866 }
5867 
5868 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
5869                               SDValue N1, SDValue N2, SDValue N3) {
5870   SDNodeFlags Flags;
5871   if (Inserter)
5872     Flags = Inserter->getFlags();
5873   return getNode(Opcode, DL, VT, N1, N2, N3, Flags);
5874 }
5875 
5876 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
5877                               SDValue N1, SDValue N2, SDValue N3,
5878                               const SDNodeFlags Flags) {
5879   assert(N1.getOpcode() != ISD::DELETED_NODE &&
5880          N2.getOpcode() != ISD::DELETED_NODE &&
5881          N3.getOpcode() != ISD::DELETED_NODE &&
5882          "Operand is DELETED_NODE!");
5883   // Perform various simplifications.
5884   switch (Opcode) {
5885   case ISD::FMA: {
5886     assert(VT.isFloatingPoint() && "This operator only applies to FP types!");
5887     assert(N1.getValueType() == VT && N2.getValueType() == VT &&
5888            N3.getValueType() == VT && "FMA types must match!");
5889     ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
5890     ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2);
5891     ConstantFPSDNode *N3CFP = dyn_cast<ConstantFPSDNode>(N3);
5892     if (N1CFP && N2CFP && N3CFP) {
5893       APFloat  V1 = N1CFP->getValueAPF();
5894       const APFloat &V2 = N2CFP->getValueAPF();
5895       const APFloat &V3 = N3CFP->getValueAPF();
5896       V1.fusedMultiplyAdd(V2, V3, APFloat::rmNearestTiesToEven);
5897       return getConstantFP(V1, DL, VT);
5898     }
5899     break;
5900   }
5901   case ISD::BUILD_VECTOR: {
5902     // Attempt to simplify BUILD_VECTOR.
5903     SDValue Ops[] = {N1, N2, N3};
5904     if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
5905       return V;
5906     break;
5907   }
5908   case ISD::CONCAT_VECTORS: {
5909     SDValue Ops[] = {N1, N2, N3};
5910     if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this))
5911       return V;
5912     break;
5913   }
5914   case ISD::SETCC: {
5915     assert(VT.isInteger() && "SETCC result type must be an integer!");
5916     assert(N1.getValueType() == N2.getValueType() &&
5917            "SETCC operands must have the same type!");
5918     assert(VT.isVector() == N1.getValueType().isVector() &&
5919            "SETCC type should be vector iff the operand type is vector!");
5920     assert((!VT.isVector() || VT.getVectorElementCount() ==
5921                                   N1.getValueType().getVectorElementCount()) &&
5922            "SETCC vector element counts must match!");
5923     // Use FoldSetCC to simplify SETCC's.
5924     if (SDValue V = FoldSetCC(VT, N1, N2, cast<CondCodeSDNode>(N3)->get(), DL))
5925       return V;
5926     // Vector constant folding.
5927     SDValue Ops[] = {N1, N2, N3};
5928     if (SDValue V = FoldConstantVectorArithmetic(Opcode, DL, VT, Ops)) {
5929       NewSDValueDbgMsg(V, "New node vector constant folding: ", this);
5930       return V;
5931     }
5932     break;
5933   }
5934   case ISD::SELECT:
5935   case ISD::VSELECT:
5936     if (SDValue V = simplifySelect(N1, N2, N3))
5937       return V;
5938     break;
5939   case ISD::VECTOR_SHUFFLE:
5940     llvm_unreachable("should use getVectorShuffle constructor!");
5941   case ISD::INSERT_VECTOR_ELT: {
5942     ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3);
5943     // INSERT_VECTOR_ELT into out-of-bounds element is an UNDEF, except
5944     // for scalable vectors where we will generate appropriate code to
5945     // deal with out-of-bounds cases correctly.
5946     if (N3C && N1.getValueType().isFixedLengthVector() &&
5947         N3C->getZExtValue() >= N1.getValueType().getVectorNumElements())
5948       return getUNDEF(VT);
5949 
5950     // Undefined index can be assumed out-of-bounds, so that's UNDEF too.
5951     if (N3.isUndef())
5952       return getUNDEF(VT);
5953 
5954     // If the inserted element is an UNDEF, just use the input vector.
5955     if (N2.isUndef())
5956       return N1;
5957 
5958     break;
5959   }
5960   case ISD::INSERT_SUBVECTOR: {
5961     // Inserting undef into undef is still undef.
5962     if (N1.isUndef() && N2.isUndef())
5963       return getUNDEF(VT);
5964 
5965     EVT N2VT = N2.getValueType();
5966     assert(VT == N1.getValueType() &&
5967            "Dest and insert subvector source types must match!");
5968     assert(VT.isVector() && N2VT.isVector() &&
5969            "Insert subvector VTs must be vectors!");
5970     assert((VT.isScalableVector() || N2VT.isFixedLengthVector()) &&
5971            "Cannot insert a scalable vector into a fixed length vector!");
5972     assert((VT.isScalableVector() != N2VT.isScalableVector() ||
5973             VT.getVectorMinNumElements() >= N2VT.getVectorMinNumElements()) &&
5974            "Insert subvector must be from smaller vector to larger vector!");
5975     assert(isa<ConstantSDNode>(N3) &&
5976            "Insert subvector index must be constant");
5977     assert((VT.isScalableVector() != N2VT.isScalableVector() ||
5978             (N2VT.getVectorMinNumElements() +
5979              cast<ConstantSDNode>(N3)->getZExtValue()) <=
5980                 VT.getVectorMinNumElements()) &&
5981            "Insert subvector overflow!");
5982     assert(cast<ConstantSDNode>(N3)->getAPIntValue().getBitWidth() ==
5983                TLI->getVectorIdxTy(getDataLayout()).getFixedSizeInBits() &&
5984            "Constant index for INSERT_SUBVECTOR has an invalid size");
5985 
5986     // Trivial insertion.
5987     if (VT == N2VT)
5988       return N2;
5989 
5990     // If this is an insert of an extracted vector into an undef vector, we
5991     // can just use the input to the extract.
5992     if (N1.isUndef() && N2.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
5993         N2.getOperand(1) == N3 && N2.getOperand(0).getValueType() == VT)
5994       return N2.getOperand(0);
5995     break;
5996   }
5997   case ISD::BITCAST:
5998     // Fold bit_convert nodes from a type to themselves.
5999     if (N1.getValueType() == VT)
6000       return N1;
6001     break;
6002   }
6003 
6004   // Memoize node if it doesn't produce a flag.
6005   SDNode *N;
6006   SDVTList VTs = getVTList(VT);
6007   SDValue Ops[] = {N1, N2, N3};
6008   if (VT != MVT::Glue) {
6009     FoldingSetNodeID ID;
6010     AddNodeIDNode(ID, Opcode, VTs, Ops);
6011     void *IP = nullptr;
6012     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
6013       E->intersectFlagsWith(Flags);
6014       return SDValue(E, 0);
6015     }
6016 
6017     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
6018     N->setFlags(Flags);
6019     createOperands(N, Ops);
6020     CSEMap.InsertNode(N, IP);
6021   } else {
6022     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
6023     createOperands(N, Ops);
6024   }
6025 
6026   InsertNode(N);
6027   SDValue V = SDValue(N, 0);
6028   NewSDValueDbgMsg(V, "Creating new node: ", this);
6029   return V;
6030 }
6031 
6032 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
6033                               SDValue N1, SDValue N2, SDValue N3, SDValue N4) {
6034   SDValue Ops[] = { N1, N2, N3, N4 };
6035   return getNode(Opcode, DL, VT, Ops);
6036 }
6037 
6038 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
6039                               SDValue N1, SDValue N2, SDValue N3, SDValue N4,
6040                               SDValue N5) {
6041   SDValue Ops[] = { N1, N2, N3, N4, N5 };
6042   return getNode(Opcode, DL, VT, Ops);
6043 }
6044 
6045 /// getStackArgumentTokenFactor - Compute a TokenFactor to force all
6046 /// the incoming stack arguments to be loaded from the stack.
6047 SDValue SelectionDAG::getStackArgumentTokenFactor(SDValue Chain) {
6048   SmallVector<SDValue, 8> ArgChains;
6049 
6050   // Include the original chain at the beginning of the list. When this is
6051   // used by target LowerCall hooks, this helps legalize find the
6052   // CALLSEQ_BEGIN node.
6053   ArgChains.push_back(Chain);
6054 
6055   // Add a chain value for each stack argument.
6056   for (SDNode::use_iterator U = getEntryNode().getNode()->use_begin(),
6057        UE = getEntryNode().getNode()->use_end(); U != UE; ++U)
6058     if (LoadSDNode *L = dyn_cast<LoadSDNode>(*U))
6059       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
6060         if (FI->getIndex() < 0)
6061           ArgChains.push_back(SDValue(L, 1));
6062 
6063   // Build a tokenfactor for all the chains.
6064   return getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains);
6065 }
6066 
6067 /// getMemsetValue - Vectorized representation of the memset value
6068 /// operand.
6069 static SDValue getMemsetValue(SDValue Value, EVT VT, SelectionDAG &DAG,
6070                               const SDLoc &dl) {
6071   assert(!Value.isUndef());
6072 
6073   unsigned NumBits = VT.getScalarSizeInBits();
6074   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
6075     assert(C->getAPIntValue().getBitWidth() == 8);
6076     APInt Val = APInt::getSplat(NumBits, C->getAPIntValue());
6077     if (VT.isInteger()) {
6078       bool IsOpaque = VT.getSizeInBits() > 64 ||
6079           !DAG.getTargetLoweringInfo().isLegalStoreImmediate(C->getSExtValue());
6080       return DAG.getConstant(Val, dl, VT, false, IsOpaque);
6081     }
6082     return DAG.getConstantFP(APFloat(DAG.EVTToAPFloatSemantics(VT), Val), dl,
6083                              VT);
6084   }
6085 
6086   assert(Value.getValueType() == MVT::i8 && "memset with non-byte fill value?");
6087   EVT IntVT = VT.getScalarType();
6088   if (!IntVT.isInteger())
6089     IntVT = EVT::getIntegerVT(*DAG.getContext(), IntVT.getSizeInBits());
6090 
6091   Value = DAG.getNode(ISD::ZERO_EXTEND, dl, IntVT, Value);
6092   if (NumBits > 8) {
6093     // Use a multiplication with 0x010101... to extend the input to the
6094     // required length.
6095     APInt Magic = APInt::getSplat(NumBits, APInt(8, 0x01));
6096     Value = DAG.getNode(ISD::MUL, dl, IntVT, Value,
6097                         DAG.getConstant(Magic, dl, IntVT));
6098   }
6099 
6100   if (VT != Value.getValueType() && !VT.isInteger())
6101     Value = DAG.getBitcast(VT.getScalarType(), Value);
6102   if (VT != Value.getValueType())
6103     Value = DAG.getSplatBuildVector(VT, dl, Value);
6104 
6105   return Value;
6106 }
6107 
6108 /// getMemsetStringVal - Similar to getMemsetValue. Except this is only
6109 /// used when a memcpy is turned into a memset when the source is a constant
6110 /// string ptr.
6111 static SDValue getMemsetStringVal(EVT VT, const SDLoc &dl, SelectionDAG &DAG,
6112                                   const TargetLowering &TLI,
6113                                   const ConstantDataArraySlice &Slice) {
6114   // Handle vector with all elements zero.
6115   if (Slice.Array == nullptr) {
6116     if (VT.isInteger())
6117       return DAG.getConstant(0, dl, VT);
6118     if (VT == MVT::f32 || VT == MVT::f64 || VT == MVT::f128)
6119       return DAG.getConstantFP(0.0, dl, VT);
6120     if (VT.isVector()) {
6121       unsigned NumElts = VT.getVectorNumElements();
6122       MVT EltVT = (VT.getVectorElementType() == MVT::f32) ? MVT::i32 : MVT::i64;
6123       return DAG.getNode(ISD::BITCAST, dl, VT,
6124                          DAG.getConstant(0, dl,
6125                                          EVT::getVectorVT(*DAG.getContext(),
6126                                                           EltVT, NumElts)));
6127     }
6128     llvm_unreachable("Expected type!");
6129   }
6130 
6131   assert(!VT.isVector() && "Can't handle vector type here!");
6132   unsigned NumVTBits = VT.getSizeInBits();
6133   unsigned NumVTBytes = NumVTBits / 8;
6134   unsigned NumBytes = std::min(NumVTBytes, unsigned(Slice.Length));
6135 
6136   APInt Val(NumVTBits, 0);
6137   if (DAG.getDataLayout().isLittleEndian()) {
6138     for (unsigned i = 0; i != NumBytes; ++i)
6139       Val |= (uint64_t)(unsigned char)Slice[i] << i*8;
6140   } else {
6141     for (unsigned i = 0; i != NumBytes; ++i)
6142       Val |= (uint64_t)(unsigned char)Slice[i] << (NumVTBytes-i-1)*8;
6143   }
6144 
6145   // If the "cost" of materializing the integer immediate is less than the cost
6146   // of a load, then it is cost effective to turn the load into the immediate.
6147   Type *Ty = VT.getTypeForEVT(*DAG.getContext());
6148   if (TLI.shouldConvertConstantLoadToIntImm(Val, Ty))
6149     return DAG.getConstant(Val, dl, VT);
6150   return SDValue(nullptr, 0);
6151 }
6152 
6153 SDValue SelectionDAG::getMemBasePlusOffset(SDValue Base, TypeSize Offset,
6154                                            const SDLoc &DL,
6155                                            const SDNodeFlags Flags) {
6156   EVT VT = Base.getValueType();
6157   SDValue Index;
6158 
6159   if (Offset.isScalable())
6160     Index = getVScale(DL, Base.getValueType(),
6161                       APInt(Base.getValueSizeInBits().getFixedSize(),
6162                             Offset.getKnownMinSize()));
6163   else
6164     Index = getConstant(Offset.getFixedSize(), DL, VT);
6165 
6166   return getMemBasePlusOffset(Base, Index, DL, Flags);
6167 }
6168 
6169 SDValue SelectionDAG::getMemBasePlusOffset(SDValue Ptr, SDValue Offset,
6170                                            const SDLoc &DL,
6171                                            const SDNodeFlags Flags) {
6172   assert(Offset.getValueType().isInteger());
6173   EVT BasePtrVT = Ptr.getValueType();
6174   return getNode(ISD::ADD, DL, BasePtrVT, Ptr, Offset, Flags);
6175 }
6176 
6177 /// Returns true if memcpy source is constant data.
6178 static bool isMemSrcFromConstant(SDValue Src, ConstantDataArraySlice &Slice) {
6179   uint64_t SrcDelta = 0;
6180   GlobalAddressSDNode *G = nullptr;
6181   if (Src.getOpcode() == ISD::GlobalAddress)
6182     G = cast<GlobalAddressSDNode>(Src);
6183   else if (Src.getOpcode() == ISD::ADD &&
6184            Src.getOperand(0).getOpcode() == ISD::GlobalAddress &&
6185            Src.getOperand(1).getOpcode() == ISD::Constant) {
6186     G = cast<GlobalAddressSDNode>(Src.getOperand(0));
6187     SrcDelta = cast<ConstantSDNode>(Src.getOperand(1))->getZExtValue();
6188   }
6189   if (!G)
6190     return false;
6191 
6192   return getConstantDataArrayInfo(G->getGlobal(), Slice, 8,
6193                                   SrcDelta + G->getOffset());
6194 }
6195 
6196 static bool shouldLowerMemFuncForSize(const MachineFunction &MF,
6197                                       SelectionDAG &DAG) {
6198   // On Darwin, -Os means optimize for size without hurting performance, so
6199   // only really optimize for size when -Oz (MinSize) is used.
6200   if (MF.getTarget().getTargetTriple().isOSDarwin())
6201     return MF.getFunction().hasMinSize();
6202   return DAG.shouldOptForSize();
6203 }
6204 
6205 static void chainLoadsAndStoresForMemcpy(SelectionDAG &DAG, const SDLoc &dl,
6206                           SmallVector<SDValue, 32> &OutChains, unsigned From,
6207                           unsigned To, SmallVector<SDValue, 16> &OutLoadChains,
6208                           SmallVector<SDValue, 16> &OutStoreChains) {
6209   assert(OutLoadChains.size() && "Missing loads in memcpy inlining");
6210   assert(OutStoreChains.size() && "Missing stores in memcpy inlining");
6211   SmallVector<SDValue, 16> GluedLoadChains;
6212   for (unsigned i = From; i < To; ++i) {
6213     OutChains.push_back(OutLoadChains[i]);
6214     GluedLoadChains.push_back(OutLoadChains[i]);
6215   }
6216 
6217   // Chain for all loads.
6218   SDValue LoadToken = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
6219                                   GluedLoadChains);
6220 
6221   for (unsigned i = From; i < To; ++i) {
6222     StoreSDNode *ST = dyn_cast<StoreSDNode>(OutStoreChains[i]);
6223     SDValue NewStore = DAG.getTruncStore(LoadToken, dl, ST->getValue(),
6224                                   ST->getBasePtr(), ST->getMemoryVT(),
6225                                   ST->getMemOperand());
6226     OutChains.push_back(NewStore);
6227   }
6228 }
6229 
6230 static SDValue getMemcpyLoadsAndStores(SelectionDAG &DAG, const SDLoc &dl,
6231                                        SDValue Chain, SDValue Dst, SDValue Src,
6232                                        uint64_t Size, Align Alignment,
6233                                        bool isVol, bool AlwaysInline,
6234                                        MachinePointerInfo DstPtrInfo,
6235                                        MachinePointerInfo SrcPtrInfo) {
6236   // Turn a memcpy of undef to nop.
6237   // FIXME: We need to honor volatile even is Src is undef.
6238   if (Src.isUndef())
6239     return Chain;
6240 
6241   // Expand memcpy to a series of load and store ops if the size operand falls
6242   // below a certain threshold.
6243   // TODO: In the AlwaysInline case, if the size is big then generate a loop
6244   // rather than maybe a humongous number of loads and stores.
6245   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6246   const DataLayout &DL = DAG.getDataLayout();
6247   LLVMContext &C = *DAG.getContext();
6248   std::vector<EVT> MemOps;
6249   bool DstAlignCanChange = false;
6250   MachineFunction &MF = DAG.getMachineFunction();
6251   MachineFrameInfo &MFI = MF.getFrameInfo();
6252   bool OptSize = shouldLowerMemFuncForSize(MF, DAG);
6253   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
6254   if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
6255     DstAlignCanChange = true;
6256   MaybeAlign SrcAlign = DAG.InferPtrAlign(Src);
6257   if (!SrcAlign || Alignment > *SrcAlign)
6258     SrcAlign = Alignment;
6259   assert(SrcAlign && "SrcAlign must be set");
6260   ConstantDataArraySlice Slice;
6261   // If marked as volatile, perform a copy even when marked as constant.
6262   bool CopyFromConstant = !isVol && isMemSrcFromConstant(Src, Slice);
6263   bool isZeroConstant = CopyFromConstant && Slice.Array == nullptr;
6264   unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemcpy(OptSize);
6265   const MemOp Op = isZeroConstant
6266                        ? MemOp::Set(Size, DstAlignCanChange, Alignment,
6267                                     /*IsZeroMemset*/ true, isVol)
6268                        : MemOp::Copy(Size, DstAlignCanChange, Alignment,
6269                                      *SrcAlign, isVol, CopyFromConstant);
6270   if (!TLI.findOptimalMemOpLowering(
6271           MemOps, Limit, Op, DstPtrInfo.getAddrSpace(),
6272           SrcPtrInfo.getAddrSpace(), MF.getFunction().getAttributes()))
6273     return SDValue();
6274 
6275   if (DstAlignCanChange) {
6276     Type *Ty = MemOps[0].getTypeForEVT(C);
6277     Align NewAlign = DL.getABITypeAlign(Ty);
6278 
6279     // Don't promote to an alignment that would require dynamic stack
6280     // realignment.
6281     const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
6282     if (!TRI->hasStackRealignment(MF))
6283       while (NewAlign > Alignment && DL.exceedsNaturalStackAlignment(NewAlign))
6284         NewAlign = NewAlign / 2;
6285 
6286     if (NewAlign > Alignment) {
6287       // Give the stack frame object a larger alignment if needed.
6288       if (MFI.getObjectAlign(FI->getIndex()) < NewAlign)
6289         MFI.setObjectAlignment(FI->getIndex(), NewAlign);
6290       Alignment = NewAlign;
6291     }
6292   }
6293 
6294   MachineMemOperand::Flags MMOFlags =
6295       isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone;
6296   SmallVector<SDValue, 16> OutLoadChains;
6297   SmallVector<SDValue, 16> OutStoreChains;
6298   SmallVector<SDValue, 32> OutChains;
6299   unsigned NumMemOps = MemOps.size();
6300   uint64_t SrcOff = 0, DstOff = 0;
6301   for (unsigned i = 0; i != NumMemOps; ++i) {
6302     EVT VT = MemOps[i];
6303     unsigned VTSize = VT.getSizeInBits() / 8;
6304     SDValue Value, Store;
6305 
6306     if (VTSize > Size) {
6307       // Issuing an unaligned load / store pair  that overlaps with the previous
6308       // pair. Adjust the offset accordingly.
6309       assert(i == NumMemOps-1 && i != 0);
6310       SrcOff -= VTSize - Size;
6311       DstOff -= VTSize - Size;
6312     }
6313 
6314     if (CopyFromConstant &&
6315         (isZeroConstant || (VT.isInteger() && !VT.isVector()))) {
6316       // It's unlikely a store of a vector immediate can be done in a single
6317       // instruction. It would require a load from a constantpool first.
6318       // We only handle zero vectors here.
6319       // FIXME: Handle other cases where store of vector immediate is done in
6320       // a single instruction.
6321       ConstantDataArraySlice SubSlice;
6322       if (SrcOff < Slice.Length) {
6323         SubSlice = Slice;
6324         SubSlice.move(SrcOff);
6325       } else {
6326         // This is an out-of-bounds access and hence UB. Pretend we read zero.
6327         SubSlice.Array = nullptr;
6328         SubSlice.Offset = 0;
6329         SubSlice.Length = VTSize;
6330       }
6331       Value = getMemsetStringVal(VT, dl, DAG, TLI, SubSlice);
6332       if (Value.getNode()) {
6333         Store = DAG.getStore(
6334             Chain, dl, Value,
6335             DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl),
6336             DstPtrInfo.getWithOffset(DstOff), Alignment, MMOFlags);
6337         OutChains.push_back(Store);
6338       }
6339     }
6340 
6341     if (!Store.getNode()) {
6342       // The type might not be legal for the target.  This should only happen
6343       // if the type is smaller than a legal type, as on PPC, so the right
6344       // thing to do is generate a LoadExt/StoreTrunc pair.  These simplify
6345       // to Load/Store if NVT==VT.
6346       // FIXME does the case above also need this?
6347       EVT NVT = TLI.getTypeToTransformTo(C, VT);
6348       assert(NVT.bitsGE(VT));
6349 
6350       bool isDereferenceable =
6351         SrcPtrInfo.getWithOffset(SrcOff).isDereferenceable(VTSize, C, DL);
6352       MachineMemOperand::Flags SrcMMOFlags = MMOFlags;
6353       if (isDereferenceable)
6354         SrcMMOFlags |= MachineMemOperand::MODereferenceable;
6355 
6356       Value = DAG.getExtLoad(
6357           ISD::EXTLOAD, dl, NVT, Chain,
6358           DAG.getMemBasePlusOffset(Src, TypeSize::Fixed(SrcOff), dl),
6359           SrcPtrInfo.getWithOffset(SrcOff), VT,
6360           commonAlignment(*SrcAlign, SrcOff), SrcMMOFlags);
6361       OutLoadChains.push_back(Value.getValue(1));
6362 
6363       Store = DAG.getTruncStore(
6364           Chain, dl, Value,
6365           DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl),
6366           DstPtrInfo.getWithOffset(DstOff), VT, Alignment, MMOFlags);
6367       OutStoreChains.push_back(Store);
6368     }
6369     SrcOff += VTSize;
6370     DstOff += VTSize;
6371     Size -= VTSize;
6372   }
6373 
6374   unsigned GluedLdStLimit = MaxLdStGlue == 0 ?
6375                                 TLI.getMaxGluedStoresPerMemcpy() : MaxLdStGlue;
6376   unsigned NumLdStInMemcpy = OutStoreChains.size();
6377 
6378   if (NumLdStInMemcpy) {
6379     // It may be that memcpy might be converted to memset if it's memcpy
6380     // of constants. In such a case, we won't have loads and stores, but
6381     // just stores. In the absence of loads, there is nothing to gang up.
6382     if ((GluedLdStLimit <= 1) || !EnableMemCpyDAGOpt) {
6383       // If target does not care, just leave as it.
6384       for (unsigned i = 0; i < NumLdStInMemcpy; ++i) {
6385         OutChains.push_back(OutLoadChains[i]);
6386         OutChains.push_back(OutStoreChains[i]);
6387       }
6388     } else {
6389       // Ld/St less than/equal limit set by target.
6390       if (NumLdStInMemcpy <= GluedLdStLimit) {
6391           chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, 0,
6392                                         NumLdStInMemcpy, OutLoadChains,
6393                                         OutStoreChains);
6394       } else {
6395         unsigned NumberLdChain =  NumLdStInMemcpy / GluedLdStLimit;
6396         unsigned RemainingLdStInMemcpy = NumLdStInMemcpy % GluedLdStLimit;
6397         unsigned GlueIter = 0;
6398 
6399         for (unsigned cnt = 0; cnt < NumberLdChain; ++cnt) {
6400           unsigned IndexFrom = NumLdStInMemcpy - GlueIter - GluedLdStLimit;
6401           unsigned IndexTo   = NumLdStInMemcpy - GlueIter;
6402 
6403           chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, IndexFrom, IndexTo,
6404                                        OutLoadChains, OutStoreChains);
6405           GlueIter += GluedLdStLimit;
6406         }
6407 
6408         // Residual ld/st.
6409         if (RemainingLdStInMemcpy) {
6410           chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, 0,
6411                                         RemainingLdStInMemcpy, OutLoadChains,
6412                                         OutStoreChains);
6413         }
6414       }
6415     }
6416   }
6417   return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
6418 }
6419 
6420 static SDValue getMemmoveLoadsAndStores(SelectionDAG &DAG, const SDLoc &dl,
6421                                         SDValue Chain, SDValue Dst, SDValue Src,
6422                                         uint64_t Size, Align Alignment,
6423                                         bool isVol, bool AlwaysInline,
6424                                         MachinePointerInfo DstPtrInfo,
6425                                         MachinePointerInfo SrcPtrInfo) {
6426   // Turn a memmove of undef to nop.
6427   // FIXME: We need to honor volatile even is Src is undef.
6428   if (Src.isUndef())
6429     return Chain;
6430 
6431   // Expand memmove to a series of load and store ops if the size operand falls
6432   // below a certain threshold.
6433   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6434   const DataLayout &DL = DAG.getDataLayout();
6435   LLVMContext &C = *DAG.getContext();
6436   std::vector<EVT> MemOps;
6437   bool DstAlignCanChange = false;
6438   MachineFunction &MF = DAG.getMachineFunction();
6439   MachineFrameInfo &MFI = MF.getFrameInfo();
6440   bool OptSize = shouldLowerMemFuncForSize(MF, DAG);
6441   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
6442   if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
6443     DstAlignCanChange = true;
6444   MaybeAlign SrcAlign = DAG.InferPtrAlign(Src);
6445   if (!SrcAlign || Alignment > *SrcAlign)
6446     SrcAlign = Alignment;
6447   assert(SrcAlign && "SrcAlign must be set");
6448   unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemmove(OptSize);
6449   if (!TLI.findOptimalMemOpLowering(
6450           MemOps, Limit,
6451           MemOp::Copy(Size, DstAlignCanChange, Alignment, *SrcAlign,
6452                       /*IsVolatile*/ true),
6453           DstPtrInfo.getAddrSpace(), SrcPtrInfo.getAddrSpace(),
6454           MF.getFunction().getAttributes()))
6455     return SDValue();
6456 
6457   if (DstAlignCanChange) {
6458     Type *Ty = MemOps[0].getTypeForEVT(C);
6459     Align NewAlign = DL.getABITypeAlign(Ty);
6460     if (NewAlign > Alignment) {
6461       // Give the stack frame object a larger alignment if needed.
6462       if (MFI.getObjectAlign(FI->getIndex()) < NewAlign)
6463         MFI.setObjectAlignment(FI->getIndex(), NewAlign);
6464       Alignment = NewAlign;
6465     }
6466   }
6467 
6468   MachineMemOperand::Flags MMOFlags =
6469       isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone;
6470   uint64_t SrcOff = 0, DstOff = 0;
6471   SmallVector<SDValue, 8> LoadValues;
6472   SmallVector<SDValue, 8> LoadChains;
6473   SmallVector<SDValue, 8> OutChains;
6474   unsigned NumMemOps = MemOps.size();
6475   for (unsigned i = 0; i < NumMemOps; i++) {
6476     EVT VT = MemOps[i];
6477     unsigned VTSize = VT.getSizeInBits() / 8;
6478     SDValue Value;
6479 
6480     bool isDereferenceable =
6481       SrcPtrInfo.getWithOffset(SrcOff).isDereferenceable(VTSize, C, DL);
6482     MachineMemOperand::Flags SrcMMOFlags = MMOFlags;
6483     if (isDereferenceable)
6484       SrcMMOFlags |= MachineMemOperand::MODereferenceable;
6485 
6486     Value =
6487         DAG.getLoad(VT, dl, Chain,
6488                     DAG.getMemBasePlusOffset(Src, TypeSize::Fixed(SrcOff), dl),
6489                     SrcPtrInfo.getWithOffset(SrcOff), *SrcAlign, SrcMMOFlags);
6490     LoadValues.push_back(Value);
6491     LoadChains.push_back(Value.getValue(1));
6492     SrcOff += VTSize;
6493   }
6494   Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
6495   OutChains.clear();
6496   for (unsigned i = 0; i < NumMemOps; i++) {
6497     EVT VT = MemOps[i];
6498     unsigned VTSize = VT.getSizeInBits() / 8;
6499     SDValue Store;
6500 
6501     Store =
6502         DAG.getStore(Chain, dl, LoadValues[i],
6503                      DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl),
6504                      DstPtrInfo.getWithOffset(DstOff), Alignment, MMOFlags);
6505     OutChains.push_back(Store);
6506     DstOff += VTSize;
6507   }
6508 
6509   return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
6510 }
6511 
6512 /// Lower the call to 'memset' intrinsic function into a series of store
6513 /// operations.
6514 ///
6515 /// \param DAG Selection DAG where lowered code is placed.
6516 /// \param dl Link to corresponding IR location.
6517 /// \param Chain Control flow dependency.
6518 /// \param Dst Pointer to destination memory location.
6519 /// \param Src Value of byte to write into the memory.
6520 /// \param Size Number of bytes to write.
6521 /// \param Alignment Alignment of the destination in bytes.
6522 /// \param isVol True if destination is volatile.
6523 /// \param DstPtrInfo IR information on the memory pointer.
6524 /// \returns New head in the control flow, if lowering was successful, empty
6525 /// SDValue otherwise.
6526 ///
6527 /// The function tries to replace 'llvm.memset' intrinsic with several store
6528 /// operations and value calculation code. This is usually profitable for small
6529 /// memory size.
6530 static SDValue getMemsetStores(SelectionDAG &DAG, const SDLoc &dl,
6531                                SDValue Chain, SDValue Dst, SDValue Src,
6532                                uint64_t Size, Align Alignment, bool isVol,
6533                                MachinePointerInfo DstPtrInfo) {
6534   // Turn a memset of undef to nop.
6535   // FIXME: We need to honor volatile even is Src is undef.
6536   if (Src.isUndef())
6537     return Chain;
6538 
6539   // Expand memset to a series of load/store ops if the size operand
6540   // falls below a certain threshold.
6541   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6542   std::vector<EVT> MemOps;
6543   bool DstAlignCanChange = false;
6544   MachineFunction &MF = DAG.getMachineFunction();
6545   MachineFrameInfo &MFI = MF.getFrameInfo();
6546   bool OptSize = shouldLowerMemFuncForSize(MF, DAG);
6547   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
6548   if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
6549     DstAlignCanChange = true;
6550   bool IsZeroVal =
6551     isa<ConstantSDNode>(Src) && cast<ConstantSDNode>(Src)->isNullValue();
6552   if (!TLI.findOptimalMemOpLowering(
6553           MemOps, TLI.getMaxStoresPerMemset(OptSize),
6554           MemOp::Set(Size, DstAlignCanChange, Alignment, IsZeroVal, isVol),
6555           DstPtrInfo.getAddrSpace(), ~0u, MF.getFunction().getAttributes()))
6556     return SDValue();
6557 
6558   if (DstAlignCanChange) {
6559     Type *Ty = MemOps[0].getTypeForEVT(*DAG.getContext());
6560     Align NewAlign = DAG.getDataLayout().getABITypeAlign(Ty);
6561     if (NewAlign > Alignment) {
6562       // Give the stack frame object a larger alignment if needed.
6563       if (MFI.getObjectAlign(FI->getIndex()) < NewAlign)
6564         MFI.setObjectAlignment(FI->getIndex(), NewAlign);
6565       Alignment = NewAlign;
6566     }
6567   }
6568 
6569   SmallVector<SDValue, 8> OutChains;
6570   uint64_t DstOff = 0;
6571   unsigned NumMemOps = MemOps.size();
6572 
6573   // Find the largest store and generate the bit pattern for it.
6574   EVT LargestVT = MemOps[0];
6575   for (unsigned i = 1; i < NumMemOps; i++)
6576     if (MemOps[i].bitsGT(LargestVT))
6577       LargestVT = MemOps[i];
6578   SDValue MemSetValue = getMemsetValue(Src, LargestVT, DAG, dl);
6579 
6580   for (unsigned i = 0; i < NumMemOps; i++) {
6581     EVT VT = MemOps[i];
6582     unsigned VTSize = VT.getSizeInBits() / 8;
6583     if (VTSize > Size) {
6584       // Issuing an unaligned load / store pair  that overlaps with the previous
6585       // pair. Adjust the offset accordingly.
6586       assert(i == NumMemOps-1 && i != 0);
6587       DstOff -= VTSize - Size;
6588     }
6589 
6590     // If this store is smaller than the largest store see whether we can get
6591     // the smaller value for free with a truncate.
6592     SDValue Value = MemSetValue;
6593     if (VT.bitsLT(LargestVT)) {
6594       if (!LargestVT.isVector() && !VT.isVector() &&
6595           TLI.isTruncateFree(LargestVT, VT))
6596         Value = DAG.getNode(ISD::TRUNCATE, dl, VT, MemSetValue);
6597       else
6598         Value = getMemsetValue(Src, VT, DAG, dl);
6599     }
6600     assert(Value.getValueType() == VT && "Value with wrong type.");
6601     SDValue Store = DAG.getStore(
6602         Chain, dl, Value,
6603         DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl),
6604         DstPtrInfo.getWithOffset(DstOff), Alignment,
6605         isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone);
6606     OutChains.push_back(Store);
6607     DstOff += VT.getSizeInBits() / 8;
6608     Size -= VTSize;
6609   }
6610 
6611   return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
6612 }
6613 
6614 static void checkAddrSpaceIsValidForLibcall(const TargetLowering *TLI,
6615                                             unsigned AS) {
6616   // Lowering memcpy / memset / memmove intrinsics to calls is only valid if all
6617   // pointer operands can be losslessly bitcasted to pointers of address space 0
6618   if (AS != 0 && !TLI->getTargetMachine().isNoopAddrSpaceCast(AS, 0)) {
6619     report_fatal_error("cannot lower memory intrinsic in address space " +
6620                        Twine(AS));
6621   }
6622 }
6623 
6624 SDValue SelectionDAG::getMemcpy(SDValue Chain, const SDLoc &dl, SDValue Dst,
6625                                 SDValue Src, SDValue Size, Align Alignment,
6626                                 bool isVol, bool AlwaysInline, bool isTailCall,
6627                                 MachinePointerInfo DstPtrInfo,
6628                                 MachinePointerInfo SrcPtrInfo) {
6629   // Check to see if we should lower the memcpy to loads and stores first.
6630   // For cases within the target-specified limits, this is the best choice.
6631   ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
6632   if (ConstantSize) {
6633     // Memcpy with size zero? Just return the original chain.
6634     if (ConstantSize->isNullValue())
6635       return Chain;
6636 
6637     SDValue Result = getMemcpyLoadsAndStores(
6638         *this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), Alignment,
6639         isVol, false, DstPtrInfo, SrcPtrInfo);
6640     if (Result.getNode())
6641       return Result;
6642   }
6643 
6644   // Then check to see if we should lower the memcpy with target-specific
6645   // code. If the target chooses to do this, this is the next best.
6646   if (TSI) {
6647     SDValue Result = TSI->EmitTargetCodeForMemcpy(
6648         *this, dl, Chain, Dst, Src, Size, Alignment, isVol, AlwaysInline,
6649         DstPtrInfo, SrcPtrInfo);
6650     if (Result.getNode())
6651       return Result;
6652   }
6653 
6654   // If we really need inline code and the target declined to provide it,
6655   // use a (potentially long) sequence of loads and stores.
6656   if (AlwaysInline) {
6657     assert(ConstantSize && "AlwaysInline requires a constant size!");
6658     return getMemcpyLoadsAndStores(*this, dl, Chain, Dst, Src,
6659                                    ConstantSize->getZExtValue(), Alignment,
6660                                    isVol, true, DstPtrInfo, SrcPtrInfo);
6661   }
6662 
6663   checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace());
6664   checkAddrSpaceIsValidForLibcall(TLI, SrcPtrInfo.getAddrSpace());
6665 
6666   // FIXME: If the memcpy is volatile (isVol), lowering it to a plain libc
6667   // memcpy is not guaranteed to be safe. libc memcpys aren't required to
6668   // respect volatile, so they may do things like read or write memory
6669   // beyond the given memory regions. But fixing this isn't easy, and most
6670   // people don't care.
6671 
6672   // Emit a library call.
6673   TargetLowering::ArgListTy Args;
6674   TargetLowering::ArgListEntry Entry;
6675   Entry.Ty = Type::getInt8PtrTy(*getContext());
6676   Entry.Node = Dst; Args.push_back(Entry);
6677   Entry.Node = Src; Args.push_back(Entry);
6678 
6679   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
6680   Entry.Node = Size; Args.push_back(Entry);
6681   // FIXME: pass in SDLoc
6682   TargetLowering::CallLoweringInfo CLI(*this);
6683   CLI.setDebugLoc(dl)
6684       .setChain(Chain)
6685       .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMCPY),
6686                     Dst.getValueType().getTypeForEVT(*getContext()),
6687                     getExternalSymbol(TLI->getLibcallName(RTLIB::MEMCPY),
6688                                       TLI->getPointerTy(getDataLayout())),
6689                     std::move(Args))
6690       .setDiscardResult()
6691       .setTailCall(isTailCall);
6692 
6693   std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
6694   return CallResult.second;
6695 }
6696 
6697 SDValue SelectionDAG::getAtomicMemcpy(SDValue Chain, const SDLoc &dl,
6698                                       SDValue Dst, unsigned DstAlign,
6699                                       SDValue Src, unsigned SrcAlign,
6700                                       SDValue Size, Type *SizeTy,
6701                                       unsigned ElemSz, bool isTailCall,
6702                                       MachinePointerInfo DstPtrInfo,
6703                                       MachinePointerInfo SrcPtrInfo) {
6704   // Emit a library call.
6705   TargetLowering::ArgListTy Args;
6706   TargetLowering::ArgListEntry Entry;
6707   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
6708   Entry.Node = Dst;
6709   Args.push_back(Entry);
6710 
6711   Entry.Node = Src;
6712   Args.push_back(Entry);
6713 
6714   Entry.Ty = SizeTy;
6715   Entry.Node = Size;
6716   Args.push_back(Entry);
6717 
6718   RTLIB::Libcall LibraryCall =
6719       RTLIB::getMEMCPY_ELEMENT_UNORDERED_ATOMIC(ElemSz);
6720   if (LibraryCall == RTLIB::UNKNOWN_LIBCALL)
6721     report_fatal_error("Unsupported element size");
6722 
6723   TargetLowering::CallLoweringInfo CLI(*this);
6724   CLI.setDebugLoc(dl)
6725       .setChain(Chain)
6726       .setLibCallee(TLI->getLibcallCallingConv(LibraryCall),
6727                     Type::getVoidTy(*getContext()),
6728                     getExternalSymbol(TLI->getLibcallName(LibraryCall),
6729                                       TLI->getPointerTy(getDataLayout())),
6730                     std::move(Args))
6731       .setDiscardResult()
6732       .setTailCall(isTailCall);
6733 
6734   std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
6735   return CallResult.second;
6736 }
6737 
6738 SDValue SelectionDAG::getMemmove(SDValue Chain, const SDLoc &dl, SDValue Dst,
6739                                  SDValue Src, SDValue Size, Align Alignment,
6740                                  bool isVol, bool isTailCall,
6741                                  MachinePointerInfo DstPtrInfo,
6742                                  MachinePointerInfo SrcPtrInfo) {
6743   // Check to see if we should lower the memmove to loads and stores first.
6744   // For cases within the target-specified limits, this is the best choice.
6745   ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
6746   if (ConstantSize) {
6747     // Memmove with size zero? Just return the original chain.
6748     if (ConstantSize->isNullValue())
6749       return Chain;
6750 
6751     SDValue Result = getMemmoveLoadsAndStores(
6752         *this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), Alignment,
6753         isVol, false, DstPtrInfo, SrcPtrInfo);
6754     if (Result.getNode())
6755       return Result;
6756   }
6757 
6758   // Then check to see if we should lower the memmove with target-specific
6759   // code. If the target chooses to do this, this is the next best.
6760   if (TSI) {
6761     SDValue Result =
6762         TSI->EmitTargetCodeForMemmove(*this, dl, Chain, Dst, Src, Size,
6763                                       Alignment, isVol, DstPtrInfo, SrcPtrInfo);
6764     if (Result.getNode())
6765       return Result;
6766   }
6767 
6768   checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace());
6769   checkAddrSpaceIsValidForLibcall(TLI, SrcPtrInfo.getAddrSpace());
6770 
6771   // FIXME: If the memmove is volatile, lowering it to plain libc memmove may
6772   // not be safe.  See memcpy above for more details.
6773 
6774   // Emit a library call.
6775   TargetLowering::ArgListTy Args;
6776   TargetLowering::ArgListEntry Entry;
6777   Entry.Ty = Type::getInt8PtrTy(*getContext());
6778   Entry.Node = Dst; Args.push_back(Entry);
6779   Entry.Node = Src; Args.push_back(Entry);
6780 
6781   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
6782   Entry.Node = Size; Args.push_back(Entry);
6783   // FIXME:  pass in SDLoc
6784   TargetLowering::CallLoweringInfo CLI(*this);
6785   CLI.setDebugLoc(dl)
6786       .setChain(Chain)
6787       .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMMOVE),
6788                     Dst.getValueType().getTypeForEVT(*getContext()),
6789                     getExternalSymbol(TLI->getLibcallName(RTLIB::MEMMOVE),
6790                                       TLI->getPointerTy(getDataLayout())),
6791                     std::move(Args))
6792       .setDiscardResult()
6793       .setTailCall(isTailCall);
6794 
6795   std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
6796   return CallResult.second;
6797 }
6798 
6799 SDValue SelectionDAG::getAtomicMemmove(SDValue Chain, const SDLoc &dl,
6800                                        SDValue Dst, unsigned DstAlign,
6801                                        SDValue Src, unsigned SrcAlign,
6802                                        SDValue Size, Type *SizeTy,
6803                                        unsigned ElemSz, bool isTailCall,
6804                                        MachinePointerInfo DstPtrInfo,
6805                                        MachinePointerInfo SrcPtrInfo) {
6806   // Emit a library call.
6807   TargetLowering::ArgListTy Args;
6808   TargetLowering::ArgListEntry Entry;
6809   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
6810   Entry.Node = Dst;
6811   Args.push_back(Entry);
6812 
6813   Entry.Node = Src;
6814   Args.push_back(Entry);
6815 
6816   Entry.Ty = SizeTy;
6817   Entry.Node = Size;
6818   Args.push_back(Entry);
6819 
6820   RTLIB::Libcall LibraryCall =
6821       RTLIB::getMEMMOVE_ELEMENT_UNORDERED_ATOMIC(ElemSz);
6822   if (LibraryCall == RTLIB::UNKNOWN_LIBCALL)
6823     report_fatal_error("Unsupported element size");
6824 
6825   TargetLowering::CallLoweringInfo CLI(*this);
6826   CLI.setDebugLoc(dl)
6827       .setChain(Chain)
6828       .setLibCallee(TLI->getLibcallCallingConv(LibraryCall),
6829                     Type::getVoidTy(*getContext()),
6830                     getExternalSymbol(TLI->getLibcallName(LibraryCall),
6831                                       TLI->getPointerTy(getDataLayout())),
6832                     std::move(Args))
6833       .setDiscardResult()
6834       .setTailCall(isTailCall);
6835 
6836   std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
6837   return CallResult.second;
6838 }
6839 
6840 SDValue SelectionDAG::getMemset(SDValue Chain, const SDLoc &dl, SDValue Dst,
6841                                 SDValue Src, SDValue Size, Align Alignment,
6842                                 bool isVol, bool isTailCall,
6843                                 MachinePointerInfo DstPtrInfo) {
6844   // Check to see if we should lower the memset to stores first.
6845   // For cases within the target-specified limits, this is the best choice.
6846   ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
6847   if (ConstantSize) {
6848     // Memset with size zero? Just return the original chain.
6849     if (ConstantSize->isNullValue())
6850       return Chain;
6851 
6852     SDValue Result = getMemsetStores(*this, dl, Chain, Dst, Src,
6853                                      ConstantSize->getZExtValue(), Alignment,
6854                                      isVol, DstPtrInfo);
6855 
6856     if (Result.getNode())
6857       return Result;
6858   }
6859 
6860   // Then check to see if we should lower the memset with target-specific
6861   // code. If the target chooses to do this, this is the next best.
6862   if (TSI) {
6863     SDValue Result = TSI->EmitTargetCodeForMemset(
6864         *this, dl, Chain, Dst, Src, Size, Alignment, isVol, DstPtrInfo);
6865     if (Result.getNode())
6866       return Result;
6867   }
6868 
6869   checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace());
6870 
6871   // Emit a library call.
6872   TargetLowering::ArgListTy Args;
6873   TargetLowering::ArgListEntry Entry;
6874   Entry.Node = Dst; Entry.Ty = Type::getInt8PtrTy(*getContext());
6875   Args.push_back(Entry);
6876   Entry.Node = Src;
6877   Entry.Ty = Src.getValueType().getTypeForEVT(*getContext());
6878   Args.push_back(Entry);
6879   Entry.Node = Size;
6880   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
6881   Args.push_back(Entry);
6882 
6883   // FIXME: pass in SDLoc
6884   TargetLowering::CallLoweringInfo CLI(*this);
6885   CLI.setDebugLoc(dl)
6886       .setChain(Chain)
6887       .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMSET),
6888                     Dst.getValueType().getTypeForEVT(*getContext()),
6889                     getExternalSymbol(TLI->getLibcallName(RTLIB::MEMSET),
6890                                       TLI->getPointerTy(getDataLayout())),
6891                     std::move(Args))
6892       .setDiscardResult()
6893       .setTailCall(isTailCall);
6894 
6895   std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
6896   return CallResult.second;
6897 }
6898 
6899 SDValue SelectionDAG::getAtomicMemset(SDValue Chain, const SDLoc &dl,
6900                                       SDValue Dst, unsigned DstAlign,
6901                                       SDValue Value, SDValue Size, Type *SizeTy,
6902                                       unsigned ElemSz, bool isTailCall,
6903                                       MachinePointerInfo DstPtrInfo) {
6904   // Emit a library call.
6905   TargetLowering::ArgListTy Args;
6906   TargetLowering::ArgListEntry Entry;
6907   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
6908   Entry.Node = Dst;
6909   Args.push_back(Entry);
6910 
6911   Entry.Ty = Type::getInt8Ty(*getContext());
6912   Entry.Node = Value;
6913   Args.push_back(Entry);
6914 
6915   Entry.Ty = SizeTy;
6916   Entry.Node = Size;
6917   Args.push_back(Entry);
6918 
6919   RTLIB::Libcall LibraryCall =
6920       RTLIB::getMEMSET_ELEMENT_UNORDERED_ATOMIC(ElemSz);
6921   if (LibraryCall == RTLIB::UNKNOWN_LIBCALL)
6922     report_fatal_error("Unsupported element size");
6923 
6924   TargetLowering::CallLoweringInfo CLI(*this);
6925   CLI.setDebugLoc(dl)
6926       .setChain(Chain)
6927       .setLibCallee(TLI->getLibcallCallingConv(LibraryCall),
6928                     Type::getVoidTy(*getContext()),
6929                     getExternalSymbol(TLI->getLibcallName(LibraryCall),
6930                                       TLI->getPointerTy(getDataLayout())),
6931                     std::move(Args))
6932       .setDiscardResult()
6933       .setTailCall(isTailCall);
6934 
6935   std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
6936   return CallResult.second;
6937 }
6938 
6939 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
6940                                 SDVTList VTList, ArrayRef<SDValue> Ops,
6941                                 MachineMemOperand *MMO) {
6942   FoldingSetNodeID ID;
6943   ID.AddInteger(MemVT.getRawBits());
6944   AddNodeIDNode(ID, Opcode, VTList, Ops);
6945   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
6946   void* IP = nullptr;
6947   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
6948     cast<AtomicSDNode>(E)->refineAlignment(MMO);
6949     return SDValue(E, 0);
6950   }
6951 
6952   auto *N = newSDNode<AtomicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
6953                                     VTList, MemVT, MMO);
6954   createOperands(N, Ops);
6955 
6956   CSEMap.InsertNode(N, IP);
6957   InsertNode(N);
6958   return SDValue(N, 0);
6959 }
6960 
6961 SDValue SelectionDAG::getAtomicCmpSwap(unsigned Opcode, const SDLoc &dl,
6962                                        EVT MemVT, SDVTList VTs, SDValue Chain,
6963                                        SDValue Ptr, SDValue Cmp, SDValue Swp,
6964                                        MachineMemOperand *MMO) {
6965   assert(Opcode == ISD::ATOMIC_CMP_SWAP ||
6966          Opcode == ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS);
6967   assert(Cmp.getValueType() == Swp.getValueType() && "Invalid Atomic Op Types");
6968 
6969   SDValue Ops[] = {Chain, Ptr, Cmp, Swp};
6970   return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
6971 }
6972 
6973 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
6974                                 SDValue Chain, SDValue Ptr, SDValue Val,
6975                                 MachineMemOperand *MMO) {
6976   assert((Opcode == ISD::ATOMIC_LOAD_ADD ||
6977           Opcode == ISD::ATOMIC_LOAD_SUB ||
6978           Opcode == ISD::ATOMIC_LOAD_AND ||
6979           Opcode == ISD::ATOMIC_LOAD_CLR ||
6980           Opcode == ISD::ATOMIC_LOAD_OR ||
6981           Opcode == ISD::ATOMIC_LOAD_XOR ||
6982           Opcode == ISD::ATOMIC_LOAD_NAND ||
6983           Opcode == ISD::ATOMIC_LOAD_MIN ||
6984           Opcode == ISD::ATOMIC_LOAD_MAX ||
6985           Opcode == ISD::ATOMIC_LOAD_UMIN ||
6986           Opcode == ISD::ATOMIC_LOAD_UMAX ||
6987           Opcode == ISD::ATOMIC_LOAD_FADD ||
6988           Opcode == ISD::ATOMIC_LOAD_FSUB ||
6989           Opcode == ISD::ATOMIC_SWAP ||
6990           Opcode == ISD::ATOMIC_STORE) &&
6991          "Invalid Atomic Op");
6992 
6993   EVT VT = Val.getValueType();
6994 
6995   SDVTList VTs = Opcode == ISD::ATOMIC_STORE ? getVTList(MVT::Other) :
6996                                                getVTList(VT, MVT::Other);
6997   SDValue Ops[] = {Chain, Ptr, Val};
6998   return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
6999 }
7000 
7001 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
7002                                 EVT VT, SDValue Chain, SDValue Ptr,
7003                                 MachineMemOperand *MMO) {
7004   assert(Opcode == ISD::ATOMIC_LOAD && "Invalid Atomic Op");
7005 
7006   SDVTList VTs = getVTList(VT, MVT::Other);
7007   SDValue Ops[] = {Chain, Ptr};
7008   return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
7009 }
7010 
7011 /// getMergeValues - Create a MERGE_VALUES node from the given operands.
7012 SDValue SelectionDAG::getMergeValues(ArrayRef<SDValue> Ops, const SDLoc &dl) {
7013   if (Ops.size() == 1)
7014     return Ops[0];
7015 
7016   SmallVector<EVT, 4> VTs;
7017   VTs.reserve(Ops.size());
7018   for (const SDValue &Op : Ops)
7019     VTs.push_back(Op.getValueType());
7020   return getNode(ISD::MERGE_VALUES, dl, getVTList(VTs), Ops);
7021 }
7022 
7023 SDValue SelectionDAG::getMemIntrinsicNode(
7024     unsigned Opcode, const SDLoc &dl, SDVTList VTList, ArrayRef<SDValue> Ops,
7025     EVT MemVT, MachinePointerInfo PtrInfo, Align Alignment,
7026     MachineMemOperand::Flags Flags, uint64_t Size, const AAMDNodes &AAInfo) {
7027   if (!Size && MemVT.isScalableVector())
7028     Size = MemoryLocation::UnknownSize;
7029   else if (!Size)
7030     Size = MemVT.getStoreSize();
7031 
7032   MachineFunction &MF = getMachineFunction();
7033   MachineMemOperand *MMO =
7034       MF.getMachineMemOperand(PtrInfo, Flags, Size, Alignment, AAInfo);
7035 
7036   return getMemIntrinsicNode(Opcode, dl, VTList, Ops, MemVT, MMO);
7037 }
7038 
7039 SDValue SelectionDAG::getMemIntrinsicNode(unsigned Opcode, const SDLoc &dl,
7040                                           SDVTList VTList,
7041                                           ArrayRef<SDValue> Ops, EVT MemVT,
7042                                           MachineMemOperand *MMO) {
7043   assert((Opcode == ISD::INTRINSIC_VOID ||
7044           Opcode == ISD::INTRINSIC_W_CHAIN ||
7045           Opcode == ISD::PREFETCH ||
7046           ((int)Opcode <= std::numeric_limits<int>::max() &&
7047            (int)Opcode >= ISD::FIRST_TARGET_MEMORY_OPCODE)) &&
7048          "Opcode is not a memory-accessing opcode!");
7049 
7050   // Memoize the node unless it returns a flag.
7051   MemIntrinsicSDNode *N;
7052   if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) {
7053     FoldingSetNodeID ID;
7054     AddNodeIDNode(ID, Opcode, VTList, Ops);
7055     ID.AddInteger(getSyntheticNodeSubclassData<MemIntrinsicSDNode>(
7056         Opcode, dl.getIROrder(), VTList, MemVT, MMO));
7057     ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7058     void *IP = nullptr;
7059     if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7060       cast<MemIntrinsicSDNode>(E)->refineAlignment(MMO);
7061       return SDValue(E, 0);
7062     }
7063 
7064     N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
7065                                       VTList, MemVT, MMO);
7066     createOperands(N, Ops);
7067 
7068   CSEMap.InsertNode(N, IP);
7069   } else {
7070     N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
7071                                       VTList, MemVT, MMO);
7072     createOperands(N, Ops);
7073   }
7074   InsertNode(N);
7075   SDValue V(N, 0);
7076   NewSDValueDbgMsg(V, "Creating new node: ", this);
7077   return V;
7078 }
7079 
7080 SDValue SelectionDAG::getLifetimeNode(bool IsStart, const SDLoc &dl,
7081                                       SDValue Chain, int FrameIndex,
7082                                       int64_t Size, int64_t Offset) {
7083   const unsigned Opcode = IsStart ? ISD::LIFETIME_START : ISD::LIFETIME_END;
7084   const auto VTs = getVTList(MVT::Other);
7085   SDValue Ops[2] = {
7086       Chain,
7087       getFrameIndex(FrameIndex,
7088                     getTargetLoweringInfo().getFrameIndexTy(getDataLayout()),
7089                     true)};
7090 
7091   FoldingSetNodeID ID;
7092   AddNodeIDNode(ID, Opcode, VTs, Ops);
7093   ID.AddInteger(FrameIndex);
7094   ID.AddInteger(Size);
7095   ID.AddInteger(Offset);
7096   void *IP = nullptr;
7097   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
7098     return SDValue(E, 0);
7099 
7100   LifetimeSDNode *N = newSDNode<LifetimeSDNode>(
7101       Opcode, dl.getIROrder(), dl.getDebugLoc(), VTs, Size, Offset);
7102   createOperands(N, Ops);
7103   CSEMap.InsertNode(N, IP);
7104   InsertNode(N);
7105   SDValue V(N, 0);
7106   NewSDValueDbgMsg(V, "Creating new node: ", this);
7107   return V;
7108 }
7109 
7110 SDValue SelectionDAG::getPseudoProbeNode(const SDLoc &Dl, SDValue Chain,
7111                                          uint64_t Guid, uint64_t Index,
7112                                          uint32_t Attr) {
7113   const unsigned Opcode = ISD::PSEUDO_PROBE;
7114   const auto VTs = getVTList(MVT::Other);
7115   SDValue Ops[] = {Chain};
7116   FoldingSetNodeID ID;
7117   AddNodeIDNode(ID, Opcode, VTs, Ops);
7118   ID.AddInteger(Guid);
7119   ID.AddInteger(Index);
7120   void *IP = nullptr;
7121   if (SDNode *E = FindNodeOrInsertPos(ID, Dl, IP))
7122     return SDValue(E, 0);
7123 
7124   auto *N = newSDNode<PseudoProbeSDNode>(
7125       Opcode, Dl.getIROrder(), Dl.getDebugLoc(), VTs, Guid, Index, Attr);
7126   createOperands(N, Ops);
7127   CSEMap.InsertNode(N, IP);
7128   InsertNode(N);
7129   SDValue V(N, 0);
7130   NewSDValueDbgMsg(V, "Creating new node: ", this);
7131   return V;
7132 }
7133 
7134 /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a
7135 /// MachinePointerInfo record from it.  This is particularly useful because the
7136 /// code generator has many cases where it doesn't bother passing in a
7137 /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst".
7138 static MachinePointerInfo InferPointerInfo(const MachinePointerInfo &Info,
7139                                            SelectionDAG &DAG, SDValue Ptr,
7140                                            int64_t Offset = 0) {
7141   // If this is FI+Offset, we can model it.
7142   if (const FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr))
7143     return MachinePointerInfo::getFixedStack(DAG.getMachineFunction(),
7144                                              FI->getIndex(), Offset);
7145 
7146   // If this is (FI+Offset1)+Offset2, we can model it.
7147   if (Ptr.getOpcode() != ISD::ADD ||
7148       !isa<ConstantSDNode>(Ptr.getOperand(1)) ||
7149       !isa<FrameIndexSDNode>(Ptr.getOperand(0)))
7150     return Info;
7151 
7152   int FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
7153   return MachinePointerInfo::getFixedStack(
7154       DAG.getMachineFunction(), FI,
7155       Offset + cast<ConstantSDNode>(Ptr.getOperand(1))->getSExtValue());
7156 }
7157 
7158 /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a
7159 /// MachinePointerInfo record from it.  This is particularly useful because the
7160 /// code generator has many cases where it doesn't bother passing in a
7161 /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst".
7162 static MachinePointerInfo InferPointerInfo(const MachinePointerInfo &Info,
7163                                            SelectionDAG &DAG, SDValue Ptr,
7164                                            SDValue OffsetOp) {
7165   // If the 'Offset' value isn't a constant, we can't handle this.
7166   if (ConstantSDNode *OffsetNode = dyn_cast<ConstantSDNode>(OffsetOp))
7167     return InferPointerInfo(Info, DAG, Ptr, OffsetNode->getSExtValue());
7168   if (OffsetOp.isUndef())
7169     return InferPointerInfo(Info, DAG, Ptr);
7170   return Info;
7171 }
7172 
7173 SDValue SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType,
7174                               EVT VT, const SDLoc &dl, SDValue Chain,
7175                               SDValue Ptr, SDValue Offset,
7176                               MachinePointerInfo PtrInfo, EVT MemVT,
7177                               Align Alignment,
7178                               MachineMemOperand::Flags MMOFlags,
7179                               const AAMDNodes &AAInfo, const MDNode *Ranges) {
7180   assert(Chain.getValueType() == MVT::Other &&
7181         "Invalid chain type");
7182 
7183   MMOFlags |= MachineMemOperand::MOLoad;
7184   assert((MMOFlags & MachineMemOperand::MOStore) == 0);
7185   // If we don't have a PtrInfo, infer the trivial frame index case to simplify
7186   // clients.
7187   if (PtrInfo.V.isNull())
7188     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr, Offset);
7189 
7190   uint64_t Size = MemoryLocation::getSizeOrUnknown(MemVT.getStoreSize());
7191   MachineFunction &MF = getMachineFunction();
7192   MachineMemOperand *MMO = MF.getMachineMemOperand(PtrInfo, MMOFlags, Size,
7193                                                    Alignment, AAInfo, Ranges);
7194   return getLoad(AM, ExtType, VT, dl, Chain, Ptr, Offset, MemVT, MMO);
7195 }
7196 
7197 SDValue SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType,
7198                               EVT VT, const SDLoc &dl, SDValue Chain,
7199                               SDValue Ptr, SDValue Offset, EVT MemVT,
7200                               MachineMemOperand *MMO) {
7201   if (VT == MemVT) {
7202     ExtType = ISD::NON_EXTLOAD;
7203   } else if (ExtType == ISD::NON_EXTLOAD) {
7204     assert(VT == MemVT && "Non-extending load from different memory type!");
7205   } else {
7206     // Extending load.
7207     assert(MemVT.getScalarType().bitsLT(VT.getScalarType()) &&
7208            "Should only be an extending load, not truncating!");
7209     assert(VT.isInteger() == MemVT.isInteger() &&
7210            "Cannot convert from FP to Int or Int -> FP!");
7211     assert(VT.isVector() == MemVT.isVector() &&
7212            "Cannot use an ext load to convert to or from a vector!");
7213     assert((!VT.isVector() ||
7214             VT.getVectorElementCount() == MemVT.getVectorElementCount()) &&
7215            "Cannot use an ext load to change the number of vector elements!");
7216   }
7217 
7218   bool Indexed = AM != ISD::UNINDEXED;
7219   assert((Indexed || Offset.isUndef()) && "Unindexed load with an offset!");
7220 
7221   SDVTList VTs = Indexed ?
7222     getVTList(VT, Ptr.getValueType(), MVT::Other) : getVTList(VT, MVT::Other);
7223   SDValue Ops[] = { Chain, Ptr, Offset };
7224   FoldingSetNodeID ID;
7225   AddNodeIDNode(ID, ISD::LOAD, VTs, Ops);
7226   ID.AddInteger(MemVT.getRawBits());
7227   ID.AddInteger(getSyntheticNodeSubclassData<LoadSDNode>(
7228       dl.getIROrder(), VTs, AM, ExtType, MemVT, MMO));
7229   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7230   void *IP = nullptr;
7231   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7232     cast<LoadSDNode>(E)->refineAlignment(MMO);
7233     return SDValue(E, 0);
7234   }
7235   auto *N = newSDNode<LoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
7236                                   ExtType, MemVT, MMO);
7237   createOperands(N, Ops);
7238 
7239   CSEMap.InsertNode(N, IP);
7240   InsertNode(N);
7241   SDValue V(N, 0);
7242   NewSDValueDbgMsg(V, "Creating new node: ", this);
7243   return V;
7244 }
7245 
7246 SDValue SelectionDAG::getLoad(EVT VT, const SDLoc &dl, SDValue Chain,
7247                               SDValue Ptr, MachinePointerInfo PtrInfo,
7248                               MaybeAlign Alignment,
7249                               MachineMemOperand::Flags MMOFlags,
7250                               const AAMDNodes &AAInfo, const MDNode *Ranges) {
7251   SDValue Undef = getUNDEF(Ptr.getValueType());
7252   return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
7253                  PtrInfo, VT, Alignment, MMOFlags, AAInfo, Ranges);
7254 }
7255 
7256 SDValue SelectionDAG::getLoad(EVT VT, const SDLoc &dl, SDValue Chain,
7257                               SDValue Ptr, MachineMemOperand *MMO) {
7258   SDValue Undef = getUNDEF(Ptr.getValueType());
7259   return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
7260                  VT, MMO);
7261 }
7262 
7263 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl,
7264                                  EVT VT, SDValue Chain, SDValue Ptr,
7265                                  MachinePointerInfo PtrInfo, EVT MemVT,
7266                                  MaybeAlign Alignment,
7267                                  MachineMemOperand::Flags MMOFlags,
7268                                  const AAMDNodes &AAInfo) {
7269   SDValue Undef = getUNDEF(Ptr.getValueType());
7270   return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, PtrInfo,
7271                  MemVT, Alignment, MMOFlags, AAInfo);
7272 }
7273 
7274 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl,
7275                                  EVT VT, SDValue Chain, SDValue Ptr, EVT MemVT,
7276                                  MachineMemOperand *MMO) {
7277   SDValue Undef = getUNDEF(Ptr.getValueType());
7278   return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef,
7279                  MemVT, MMO);
7280 }
7281 
7282 SDValue SelectionDAG::getIndexedLoad(SDValue OrigLoad, const SDLoc &dl,
7283                                      SDValue Base, SDValue Offset,
7284                                      ISD::MemIndexedMode AM) {
7285   LoadSDNode *LD = cast<LoadSDNode>(OrigLoad);
7286   assert(LD->getOffset().isUndef() && "Load is already a indexed load!");
7287   // Don't propagate the invariant or dereferenceable flags.
7288   auto MMOFlags =
7289       LD->getMemOperand()->getFlags() &
7290       ~(MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable);
7291   return getLoad(AM, LD->getExtensionType(), OrigLoad.getValueType(), dl,
7292                  LD->getChain(), Base, Offset, LD->getPointerInfo(),
7293                  LD->getMemoryVT(), LD->getAlign(), MMOFlags, LD->getAAInfo());
7294 }
7295 
7296 SDValue SelectionDAG::getStore(SDValue Chain, const SDLoc &dl, SDValue Val,
7297                                SDValue Ptr, MachinePointerInfo PtrInfo,
7298                                Align Alignment,
7299                                MachineMemOperand::Flags MMOFlags,
7300                                const AAMDNodes &AAInfo) {
7301   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
7302 
7303   MMOFlags |= MachineMemOperand::MOStore;
7304   assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
7305 
7306   if (PtrInfo.V.isNull())
7307     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
7308 
7309   MachineFunction &MF = getMachineFunction();
7310   uint64_t Size =
7311       MemoryLocation::getSizeOrUnknown(Val.getValueType().getStoreSize());
7312   MachineMemOperand *MMO =
7313       MF.getMachineMemOperand(PtrInfo, MMOFlags, Size, Alignment, AAInfo);
7314   return getStore(Chain, dl, Val, Ptr, MMO);
7315 }
7316 
7317 SDValue SelectionDAG::getStore(SDValue Chain, const SDLoc &dl, SDValue Val,
7318                                SDValue Ptr, MachineMemOperand *MMO) {
7319   assert(Chain.getValueType() == MVT::Other &&
7320         "Invalid chain type");
7321   EVT VT = Val.getValueType();
7322   SDVTList VTs = getVTList(MVT::Other);
7323   SDValue Undef = getUNDEF(Ptr.getValueType());
7324   SDValue Ops[] = { Chain, Val, Ptr, Undef };
7325   FoldingSetNodeID ID;
7326   AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
7327   ID.AddInteger(VT.getRawBits());
7328   ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>(
7329       dl.getIROrder(), VTs, ISD::UNINDEXED, false, VT, MMO));
7330   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7331   void *IP = nullptr;
7332   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7333     cast<StoreSDNode>(E)->refineAlignment(MMO);
7334     return SDValue(E, 0);
7335   }
7336   auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
7337                                    ISD::UNINDEXED, false, VT, MMO);
7338   createOperands(N, Ops);
7339 
7340   CSEMap.InsertNode(N, IP);
7341   InsertNode(N);
7342   SDValue V(N, 0);
7343   NewSDValueDbgMsg(V, "Creating new node: ", this);
7344   return V;
7345 }
7346 
7347 SDValue SelectionDAG::getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val,
7348                                     SDValue Ptr, MachinePointerInfo PtrInfo,
7349                                     EVT SVT, Align Alignment,
7350                                     MachineMemOperand::Flags MMOFlags,
7351                                     const AAMDNodes &AAInfo) {
7352   assert(Chain.getValueType() == MVT::Other &&
7353         "Invalid chain type");
7354 
7355   MMOFlags |= MachineMemOperand::MOStore;
7356   assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
7357 
7358   if (PtrInfo.V.isNull())
7359     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
7360 
7361   MachineFunction &MF = getMachineFunction();
7362   MachineMemOperand *MMO = MF.getMachineMemOperand(
7363       PtrInfo, MMOFlags, MemoryLocation::getSizeOrUnknown(SVT.getStoreSize()),
7364       Alignment, AAInfo);
7365   return getTruncStore(Chain, dl, Val, Ptr, SVT, MMO);
7366 }
7367 
7368 SDValue SelectionDAG::getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val,
7369                                     SDValue Ptr, EVT SVT,
7370                                     MachineMemOperand *MMO) {
7371   EVT VT = Val.getValueType();
7372 
7373   assert(Chain.getValueType() == MVT::Other &&
7374         "Invalid chain type");
7375   if (VT == SVT)
7376     return getStore(Chain, dl, Val, Ptr, MMO);
7377 
7378   assert(SVT.getScalarType().bitsLT(VT.getScalarType()) &&
7379          "Should only be a truncating store, not extending!");
7380   assert(VT.isInteger() == SVT.isInteger() &&
7381          "Can't do FP-INT conversion!");
7382   assert(VT.isVector() == SVT.isVector() &&
7383          "Cannot use trunc store to convert to or from a vector!");
7384   assert((!VT.isVector() ||
7385           VT.getVectorElementCount() == SVT.getVectorElementCount()) &&
7386          "Cannot use trunc store to change the number of vector elements!");
7387 
7388   SDVTList VTs = getVTList(MVT::Other);
7389   SDValue Undef = getUNDEF(Ptr.getValueType());
7390   SDValue Ops[] = { Chain, Val, Ptr, Undef };
7391   FoldingSetNodeID ID;
7392   AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
7393   ID.AddInteger(SVT.getRawBits());
7394   ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>(
7395       dl.getIROrder(), VTs, ISD::UNINDEXED, true, SVT, MMO));
7396   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7397   void *IP = nullptr;
7398   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7399     cast<StoreSDNode>(E)->refineAlignment(MMO);
7400     return SDValue(E, 0);
7401   }
7402   auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
7403                                    ISD::UNINDEXED, true, SVT, MMO);
7404   createOperands(N, Ops);
7405 
7406   CSEMap.InsertNode(N, IP);
7407   InsertNode(N);
7408   SDValue V(N, 0);
7409   NewSDValueDbgMsg(V, "Creating new node: ", this);
7410   return V;
7411 }
7412 
7413 SDValue SelectionDAG::getIndexedStore(SDValue OrigStore, const SDLoc &dl,
7414                                       SDValue Base, SDValue Offset,
7415                                       ISD::MemIndexedMode AM) {
7416   StoreSDNode *ST = cast<StoreSDNode>(OrigStore);
7417   assert(ST->getOffset().isUndef() && "Store is already a indexed store!");
7418   SDVTList VTs = getVTList(Base.getValueType(), MVT::Other);
7419   SDValue Ops[] = { ST->getChain(), ST->getValue(), Base, Offset };
7420   FoldingSetNodeID ID;
7421   AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
7422   ID.AddInteger(ST->getMemoryVT().getRawBits());
7423   ID.AddInteger(ST->getRawSubclassData());
7424   ID.AddInteger(ST->getPointerInfo().getAddrSpace());
7425   void *IP = nullptr;
7426   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
7427     return SDValue(E, 0);
7428 
7429   auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
7430                                    ST->isTruncatingStore(), ST->getMemoryVT(),
7431                                    ST->getMemOperand());
7432   createOperands(N, Ops);
7433 
7434   CSEMap.InsertNode(N, IP);
7435   InsertNode(N);
7436   SDValue V(N, 0);
7437   NewSDValueDbgMsg(V, "Creating new node: ", this);
7438   return V;
7439 }
7440 
7441 SDValue SelectionDAG::getMaskedLoad(EVT VT, const SDLoc &dl, SDValue Chain,
7442                                     SDValue Base, SDValue Offset, SDValue Mask,
7443                                     SDValue PassThru, EVT MemVT,
7444                                     MachineMemOperand *MMO,
7445                                     ISD::MemIndexedMode AM,
7446                                     ISD::LoadExtType ExtTy, bool isExpanding) {
7447   bool Indexed = AM != ISD::UNINDEXED;
7448   assert((Indexed || Offset.isUndef()) &&
7449          "Unindexed masked load with an offset!");
7450   SDVTList VTs = Indexed ? getVTList(VT, Base.getValueType(), MVT::Other)
7451                          : getVTList(VT, MVT::Other);
7452   SDValue Ops[] = {Chain, Base, Offset, Mask, PassThru};
7453   FoldingSetNodeID ID;
7454   AddNodeIDNode(ID, ISD::MLOAD, VTs, Ops);
7455   ID.AddInteger(MemVT.getRawBits());
7456   ID.AddInteger(getSyntheticNodeSubclassData<MaskedLoadSDNode>(
7457       dl.getIROrder(), VTs, AM, ExtTy, isExpanding, MemVT, MMO));
7458   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7459   void *IP = nullptr;
7460   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7461     cast<MaskedLoadSDNode>(E)->refineAlignment(MMO);
7462     return SDValue(E, 0);
7463   }
7464   auto *N = newSDNode<MaskedLoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
7465                                         AM, ExtTy, isExpanding, MemVT, MMO);
7466   createOperands(N, Ops);
7467 
7468   CSEMap.InsertNode(N, IP);
7469   InsertNode(N);
7470   SDValue V(N, 0);
7471   NewSDValueDbgMsg(V, "Creating new node: ", this);
7472   return V;
7473 }
7474 
7475 SDValue SelectionDAG::getIndexedMaskedLoad(SDValue OrigLoad, const SDLoc &dl,
7476                                            SDValue Base, SDValue Offset,
7477                                            ISD::MemIndexedMode AM) {
7478   MaskedLoadSDNode *LD = cast<MaskedLoadSDNode>(OrigLoad);
7479   assert(LD->getOffset().isUndef() && "Masked load is already a indexed load!");
7480   return getMaskedLoad(OrigLoad.getValueType(), dl, LD->getChain(), Base,
7481                        Offset, LD->getMask(), LD->getPassThru(),
7482                        LD->getMemoryVT(), LD->getMemOperand(), AM,
7483                        LD->getExtensionType(), LD->isExpandingLoad());
7484 }
7485 
7486 SDValue SelectionDAG::getMaskedStore(SDValue Chain, const SDLoc &dl,
7487                                      SDValue Val, SDValue Base, SDValue Offset,
7488                                      SDValue Mask, EVT MemVT,
7489                                      MachineMemOperand *MMO,
7490                                      ISD::MemIndexedMode AM, bool IsTruncating,
7491                                      bool IsCompressing) {
7492   assert(Chain.getValueType() == MVT::Other &&
7493         "Invalid chain type");
7494   bool Indexed = AM != ISD::UNINDEXED;
7495   assert((Indexed || Offset.isUndef()) &&
7496          "Unindexed masked store with an offset!");
7497   SDVTList VTs = Indexed ? getVTList(Base.getValueType(), MVT::Other)
7498                          : getVTList(MVT::Other);
7499   SDValue Ops[] = {Chain, Val, Base, Offset, Mask};
7500   FoldingSetNodeID ID;
7501   AddNodeIDNode(ID, ISD::MSTORE, VTs, Ops);
7502   ID.AddInteger(MemVT.getRawBits());
7503   ID.AddInteger(getSyntheticNodeSubclassData<MaskedStoreSDNode>(
7504       dl.getIROrder(), VTs, AM, IsTruncating, IsCompressing, MemVT, MMO));
7505   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7506   void *IP = nullptr;
7507   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7508     cast<MaskedStoreSDNode>(E)->refineAlignment(MMO);
7509     return SDValue(E, 0);
7510   }
7511   auto *N =
7512       newSDNode<MaskedStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
7513                                    IsTruncating, IsCompressing, MemVT, MMO);
7514   createOperands(N, Ops);
7515 
7516   CSEMap.InsertNode(N, IP);
7517   InsertNode(N);
7518   SDValue V(N, 0);
7519   NewSDValueDbgMsg(V, "Creating new node: ", this);
7520   return V;
7521 }
7522 
7523 SDValue SelectionDAG::getIndexedMaskedStore(SDValue OrigStore, const SDLoc &dl,
7524                                             SDValue Base, SDValue Offset,
7525                                             ISD::MemIndexedMode AM) {
7526   MaskedStoreSDNode *ST = cast<MaskedStoreSDNode>(OrigStore);
7527   assert(ST->getOffset().isUndef() &&
7528          "Masked store is already a indexed store!");
7529   return getMaskedStore(ST->getChain(), dl, ST->getValue(), Base, Offset,
7530                         ST->getMask(), ST->getMemoryVT(), ST->getMemOperand(),
7531                         AM, ST->isTruncatingStore(), ST->isCompressingStore());
7532 }
7533 
7534 SDValue SelectionDAG::getMaskedGather(SDVTList VTs, EVT VT, const SDLoc &dl,
7535                                       ArrayRef<SDValue> Ops,
7536                                       MachineMemOperand *MMO,
7537                                       ISD::MemIndexType IndexType,
7538                                       ISD::LoadExtType ExtTy) {
7539   assert(Ops.size() == 6 && "Incompatible number of operands");
7540 
7541   FoldingSetNodeID ID;
7542   AddNodeIDNode(ID, ISD::MGATHER, VTs, Ops);
7543   ID.AddInteger(VT.getRawBits());
7544   ID.AddInteger(getSyntheticNodeSubclassData<MaskedGatherSDNode>(
7545       dl.getIROrder(), VTs, VT, MMO, IndexType, ExtTy));
7546   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7547   void *IP = nullptr;
7548   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7549     cast<MaskedGatherSDNode>(E)->refineAlignment(MMO);
7550     return SDValue(E, 0);
7551   }
7552 
7553   IndexType = TLI->getCanonicalIndexType(IndexType, VT, Ops[4]);
7554   auto *N = newSDNode<MaskedGatherSDNode>(dl.getIROrder(), dl.getDebugLoc(),
7555                                           VTs, VT, MMO, IndexType, ExtTy);
7556   createOperands(N, Ops);
7557 
7558   assert(N->getPassThru().getValueType() == N->getValueType(0) &&
7559          "Incompatible type of the PassThru value in MaskedGatherSDNode");
7560   assert(N->getMask().getValueType().getVectorElementCount() ==
7561              N->getValueType(0).getVectorElementCount() &&
7562          "Vector width mismatch between mask and data");
7563   assert(N->getIndex().getValueType().getVectorElementCount().isScalable() ==
7564              N->getValueType(0).getVectorElementCount().isScalable() &&
7565          "Scalable flags of index and data do not match");
7566   assert(ElementCount::isKnownGE(
7567              N->getIndex().getValueType().getVectorElementCount(),
7568              N->getValueType(0).getVectorElementCount()) &&
7569          "Vector width mismatch between index and data");
7570   assert(isa<ConstantSDNode>(N->getScale()) &&
7571          cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() &&
7572          "Scale should be a constant power of 2");
7573 
7574   CSEMap.InsertNode(N, IP);
7575   InsertNode(N);
7576   SDValue V(N, 0);
7577   NewSDValueDbgMsg(V, "Creating new node: ", this);
7578   return V;
7579 }
7580 
7581 SDValue SelectionDAG::getMaskedScatter(SDVTList VTs, EVT VT, const SDLoc &dl,
7582                                        ArrayRef<SDValue> Ops,
7583                                        MachineMemOperand *MMO,
7584                                        ISD::MemIndexType IndexType,
7585                                        bool IsTrunc) {
7586   assert(Ops.size() == 6 && "Incompatible number of operands");
7587 
7588   FoldingSetNodeID ID;
7589   AddNodeIDNode(ID, ISD::MSCATTER, VTs, Ops);
7590   ID.AddInteger(VT.getRawBits());
7591   ID.AddInteger(getSyntheticNodeSubclassData<MaskedScatterSDNode>(
7592       dl.getIROrder(), VTs, VT, MMO, IndexType, IsTrunc));
7593   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7594   void *IP = nullptr;
7595   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7596     cast<MaskedScatterSDNode>(E)->refineAlignment(MMO);
7597     return SDValue(E, 0);
7598   }
7599 
7600   IndexType = TLI->getCanonicalIndexType(IndexType, VT, Ops[4]);
7601   auto *N = newSDNode<MaskedScatterSDNode>(dl.getIROrder(), dl.getDebugLoc(),
7602                                            VTs, VT, MMO, IndexType, IsTrunc);
7603   createOperands(N, Ops);
7604 
7605   assert(N->getMask().getValueType().getVectorElementCount() ==
7606              N->getValue().getValueType().getVectorElementCount() &&
7607          "Vector width mismatch between mask and data");
7608   assert(
7609       N->getIndex().getValueType().getVectorElementCount().isScalable() ==
7610           N->getValue().getValueType().getVectorElementCount().isScalable() &&
7611       "Scalable flags of index and data do not match");
7612   assert(ElementCount::isKnownGE(
7613              N->getIndex().getValueType().getVectorElementCount(),
7614              N->getValue().getValueType().getVectorElementCount()) &&
7615          "Vector width mismatch between index and data");
7616   assert(isa<ConstantSDNode>(N->getScale()) &&
7617          cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() &&
7618          "Scale should be a constant power of 2");
7619 
7620   CSEMap.InsertNode(N, IP);
7621   InsertNode(N);
7622   SDValue V(N, 0);
7623   NewSDValueDbgMsg(V, "Creating new node: ", this);
7624   return V;
7625 }
7626 
7627 SDValue SelectionDAG::simplifySelect(SDValue Cond, SDValue T, SDValue F) {
7628   // select undef, T, F --> T (if T is a constant), otherwise F
7629   // select, ?, undef, F --> F
7630   // select, ?, T, undef --> T
7631   if (Cond.isUndef())
7632     return isConstantValueOfAnyType(T) ? T : F;
7633   if (T.isUndef())
7634     return F;
7635   if (F.isUndef())
7636     return T;
7637 
7638   // select true, T, F --> T
7639   // select false, T, F --> F
7640   if (auto *CondC = dyn_cast<ConstantSDNode>(Cond))
7641     return CondC->isNullValue() ? F : T;
7642 
7643   // TODO: This should simplify VSELECT with constant condition using something
7644   // like this (but check boolean contents to be complete?):
7645   //  if (ISD::isBuildVectorAllOnes(Cond.getNode()))
7646   //    return T;
7647   //  if (ISD::isBuildVectorAllZeros(Cond.getNode()))
7648   //    return F;
7649 
7650   // select ?, T, T --> T
7651   if (T == F)
7652     return T;
7653 
7654   return SDValue();
7655 }
7656 
7657 SDValue SelectionDAG::simplifyShift(SDValue X, SDValue Y) {
7658   // shift undef, Y --> 0 (can always assume that the undef value is 0)
7659   if (X.isUndef())
7660     return getConstant(0, SDLoc(X.getNode()), X.getValueType());
7661   // shift X, undef --> undef (because it may shift by the bitwidth)
7662   if (Y.isUndef())
7663     return getUNDEF(X.getValueType());
7664 
7665   // shift 0, Y --> 0
7666   // shift X, 0 --> X
7667   if (isNullOrNullSplat(X) || isNullOrNullSplat(Y))
7668     return X;
7669 
7670   // shift X, C >= bitwidth(X) --> undef
7671   // All vector elements must be too big (or undef) to avoid partial undefs.
7672   auto isShiftTooBig = [X](ConstantSDNode *Val) {
7673     return !Val || Val->getAPIntValue().uge(X.getScalarValueSizeInBits());
7674   };
7675   if (ISD::matchUnaryPredicate(Y, isShiftTooBig, true))
7676     return getUNDEF(X.getValueType());
7677 
7678   return SDValue();
7679 }
7680 
7681 SDValue SelectionDAG::simplifyFPBinop(unsigned Opcode, SDValue X, SDValue Y,
7682                                       SDNodeFlags Flags) {
7683   // If this operation has 'nnan' or 'ninf' and at least 1 disallowed operand
7684   // (an undef operand can be chosen to be Nan/Inf), then the result of this
7685   // operation is poison. That result can be relaxed to undef.
7686   ConstantFPSDNode *XC = isConstOrConstSplatFP(X, /* AllowUndefs */ true);
7687   ConstantFPSDNode *YC = isConstOrConstSplatFP(Y, /* AllowUndefs */ true);
7688   bool HasNan = (XC && XC->getValueAPF().isNaN()) ||
7689                 (YC && YC->getValueAPF().isNaN());
7690   bool HasInf = (XC && XC->getValueAPF().isInfinity()) ||
7691                 (YC && YC->getValueAPF().isInfinity());
7692 
7693   if (Flags.hasNoNaNs() && (HasNan || X.isUndef() || Y.isUndef()))
7694     return getUNDEF(X.getValueType());
7695 
7696   if (Flags.hasNoInfs() && (HasInf || X.isUndef() || Y.isUndef()))
7697     return getUNDEF(X.getValueType());
7698 
7699   if (!YC)
7700     return SDValue();
7701 
7702   // X + -0.0 --> X
7703   if (Opcode == ISD::FADD)
7704     if (YC->getValueAPF().isNegZero())
7705       return X;
7706 
7707   // X - +0.0 --> X
7708   if (Opcode == ISD::FSUB)
7709     if (YC->getValueAPF().isPosZero())
7710       return X;
7711 
7712   // X * 1.0 --> X
7713   // X / 1.0 --> X
7714   if (Opcode == ISD::FMUL || Opcode == ISD::FDIV)
7715     if (YC->getValueAPF().isExactlyValue(1.0))
7716       return X;
7717 
7718   // X * 0.0 --> 0.0
7719   if (Opcode == ISD::FMUL && Flags.hasNoNaNs() && Flags.hasNoSignedZeros())
7720     if (YC->getValueAPF().isZero())
7721       return getConstantFP(0.0, SDLoc(Y), Y.getValueType());
7722 
7723   return SDValue();
7724 }
7725 
7726 SDValue SelectionDAG::getVAArg(EVT VT, const SDLoc &dl, SDValue Chain,
7727                                SDValue Ptr, SDValue SV, unsigned Align) {
7728   SDValue Ops[] = { Chain, Ptr, SV, getTargetConstant(Align, dl, MVT::i32) };
7729   return getNode(ISD::VAARG, dl, getVTList(VT, MVT::Other), Ops);
7730 }
7731 
7732 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
7733                               ArrayRef<SDUse> Ops) {
7734   switch (Ops.size()) {
7735   case 0: return getNode(Opcode, DL, VT);
7736   case 1: return getNode(Opcode, DL, VT, static_cast<const SDValue>(Ops[0]));
7737   case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1]);
7738   case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2]);
7739   default: break;
7740   }
7741 
7742   // Copy from an SDUse array into an SDValue array for use with
7743   // the regular getNode logic.
7744   SmallVector<SDValue, 8> NewOps(Ops.begin(), Ops.end());
7745   return getNode(Opcode, DL, VT, NewOps);
7746 }
7747 
7748 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
7749                               ArrayRef<SDValue> Ops) {
7750   SDNodeFlags Flags;
7751   if (Inserter)
7752     Flags = Inserter->getFlags();
7753   return getNode(Opcode, DL, VT, Ops, Flags);
7754 }
7755 
7756 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
7757                               ArrayRef<SDValue> Ops, const SDNodeFlags Flags) {
7758   unsigned NumOps = Ops.size();
7759   switch (NumOps) {
7760   case 0: return getNode(Opcode, DL, VT);
7761   case 1: return getNode(Opcode, DL, VT, Ops[0], Flags);
7762   case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Flags);
7763   case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2], Flags);
7764   default: break;
7765   }
7766 
7767 #ifndef NDEBUG
7768   for (auto &Op : Ops)
7769     assert(Op.getOpcode() != ISD::DELETED_NODE &&
7770            "Operand is DELETED_NODE!");
7771 #endif
7772 
7773   switch (Opcode) {
7774   default: break;
7775   case ISD::BUILD_VECTOR:
7776     // Attempt to simplify BUILD_VECTOR.
7777     if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
7778       return V;
7779     break;
7780   case ISD::CONCAT_VECTORS:
7781     if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this))
7782       return V;
7783     break;
7784   case ISD::SELECT_CC:
7785     assert(NumOps == 5 && "SELECT_CC takes 5 operands!");
7786     assert(Ops[0].getValueType() == Ops[1].getValueType() &&
7787            "LHS and RHS of condition must have same type!");
7788     assert(Ops[2].getValueType() == Ops[3].getValueType() &&
7789            "True and False arms of SelectCC must have same type!");
7790     assert(Ops[2].getValueType() == VT &&
7791            "select_cc node must be of same type as true and false value!");
7792     break;
7793   case ISD::BR_CC:
7794     assert(NumOps == 5 && "BR_CC takes 5 operands!");
7795     assert(Ops[2].getValueType() == Ops[3].getValueType() &&
7796            "LHS/RHS of comparison should match types!");
7797     break;
7798   }
7799 
7800   // Memoize nodes.
7801   SDNode *N;
7802   SDVTList VTs = getVTList(VT);
7803 
7804   if (VT != MVT::Glue) {
7805     FoldingSetNodeID ID;
7806     AddNodeIDNode(ID, Opcode, VTs, Ops);
7807     void *IP = nullptr;
7808 
7809     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
7810       return SDValue(E, 0);
7811 
7812     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
7813     createOperands(N, Ops);
7814 
7815     CSEMap.InsertNode(N, IP);
7816   } else {
7817     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
7818     createOperands(N, Ops);
7819   }
7820 
7821   N->setFlags(Flags);
7822   InsertNode(N);
7823   SDValue V(N, 0);
7824   NewSDValueDbgMsg(V, "Creating new node: ", this);
7825   return V;
7826 }
7827 
7828 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL,
7829                               ArrayRef<EVT> ResultTys, ArrayRef<SDValue> Ops) {
7830   return getNode(Opcode, DL, getVTList(ResultTys), Ops);
7831 }
7832 
7833 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
7834                               ArrayRef<SDValue> Ops) {
7835   SDNodeFlags Flags;
7836   if (Inserter)
7837     Flags = Inserter->getFlags();
7838   return getNode(Opcode, DL, VTList, Ops, Flags);
7839 }
7840 
7841 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
7842                               ArrayRef<SDValue> Ops, const SDNodeFlags Flags) {
7843   if (VTList.NumVTs == 1)
7844     return getNode(Opcode, DL, VTList.VTs[0], Ops);
7845 
7846 #ifndef NDEBUG
7847   for (auto &Op : Ops)
7848     assert(Op.getOpcode() != ISD::DELETED_NODE &&
7849            "Operand is DELETED_NODE!");
7850 #endif
7851 
7852   switch (Opcode) {
7853   case ISD::STRICT_FP_EXTEND:
7854     assert(VTList.NumVTs == 2 && Ops.size() == 2 &&
7855            "Invalid STRICT_FP_EXTEND!");
7856     assert(VTList.VTs[0].isFloatingPoint() &&
7857            Ops[1].getValueType().isFloatingPoint() && "Invalid FP cast!");
7858     assert(VTList.VTs[0].isVector() == Ops[1].getValueType().isVector() &&
7859            "STRICT_FP_EXTEND result type should be vector iff the operand "
7860            "type is vector!");
7861     assert((!VTList.VTs[0].isVector() ||
7862             VTList.VTs[0].getVectorNumElements() ==
7863             Ops[1].getValueType().getVectorNumElements()) &&
7864            "Vector element count mismatch!");
7865     assert(Ops[1].getValueType().bitsLT(VTList.VTs[0]) &&
7866            "Invalid fpext node, dst <= src!");
7867     break;
7868   case ISD::STRICT_FP_ROUND:
7869     assert(VTList.NumVTs == 2 && Ops.size() == 3 && "Invalid STRICT_FP_ROUND!");
7870     assert(VTList.VTs[0].isVector() == Ops[1].getValueType().isVector() &&
7871            "STRICT_FP_ROUND result type should be vector iff the operand "
7872            "type is vector!");
7873     assert((!VTList.VTs[0].isVector() ||
7874             VTList.VTs[0].getVectorNumElements() ==
7875             Ops[1].getValueType().getVectorNumElements()) &&
7876            "Vector element count mismatch!");
7877     assert(VTList.VTs[0].isFloatingPoint() &&
7878            Ops[1].getValueType().isFloatingPoint() &&
7879            VTList.VTs[0].bitsLT(Ops[1].getValueType()) &&
7880            isa<ConstantSDNode>(Ops[2]) &&
7881            (cast<ConstantSDNode>(Ops[2])->getZExtValue() == 0 ||
7882             cast<ConstantSDNode>(Ops[2])->getZExtValue() == 1) &&
7883            "Invalid STRICT_FP_ROUND!");
7884     break;
7885 #if 0
7886   // FIXME: figure out how to safely handle things like
7887   // int foo(int x) { return 1 << (x & 255); }
7888   // int bar() { return foo(256); }
7889   case ISD::SRA_PARTS:
7890   case ISD::SRL_PARTS:
7891   case ISD::SHL_PARTS:
7892     if (N3.getOpcode() == ISD::SIGN_EXTEND_INREG &&
7893         cast<VTSDNode>(N3.getOperand(1))->getVT() != MVT::i1)
7894       return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0));
7895     else if (N3.getOpcode() == ISD::AND)
7896       if (ConstantSDNode *AndRHS = dyn_cast<ConstantSDNode>(N3.getOperand(1))) {
7897         // If the and is only masking out bits that cannot effect the shift,
7898         // eliminate the and.
7899         unsigned NumBits = VT.getScalarSizeInBits()*2;
7900         if ((AndRHS->getValue() & (NumBits-1)) == NumBits-1)
7901           return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0));
7902       }
7903     break;
7904 #endif
7905   }
7906 
7907   // Memoize the node unless it returns a flag.
7908   SDNode *N;
7909   if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) {
7910     FoldingSetNodeID ID;
7911     AddNodeIDNode(ID, Opcode, VTList, Ops);
7912     void *IP = nullptr;
7913     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
7914       return SDValue(E, 0);
7915 
7916     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList);
7917     createOperands(N, Ops);
7918     CSEMap.InsertNode(N, IP);
7919   } else {
7920     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList);
7921     createOperands(N, Ops);
7922   }
7923 
7924   N->setFlags(Flags);
7925   InsertNode(N);
7926   SDValue V(N, 0);
7927   NewSDValueDbgMsg(V, "Creating new node: ", this);
7928   return V;
7929 }
7930 
7931 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL,
7932                               SDVTList VTList) {
7933   return getNode(Opcode, DL, VTList, None);
7934 }
7935 
7936 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
7937                               SDValue N1) {
7938   SDValue Ops[] = { N1 };
7939   return getNode(Opcode, DL, VTList, Ops);
7940 }
7941 
7942 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
7943                               SDValue N1, SDValue N2) {
7944   SDValue Ops[] = { N1, N2 };
7945   return getNode(Opcode, DL, VTList, Ops);
7946 }
7947 
7948 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
7949                               SDValue N1, SDValue N2, SDValue N3) {
7950   SDValue Ops[] = { N1, N2, N3 };
7951   return getNode(Opcode, DL, VTList, Ops);
7952 }
7953 
7954 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
7955                               SDValue N1, SDValue N2, SDValue N3, SDValue N4) {
7956   SDValue Ops[] = { N1, N2, N3, N4 };
7957   return getNode(Opcode, DL, VTList, Ops);
7958 }
7959 
7960 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
7961                               SDValue N1, SDValue N2, SDValue N3, SDValue N4,
7962                               SDValue N5) {
7963   SDValue Ops[] = { N1, N2, N3, N4, N5 };
7964   return getNode(Opcode, DL, VTList, Ops);
7965 }
7966 
7967 SDVTList SelectionDAG::getVTList(EVT VT) {
7968   return makeVTList(SDNode::getValueTypeList(VT), 1);
7969 }
7970 
7971 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2) {
7972   FoldingSetNodeID ID;
7973   ID.AddInteger(2U);
7974   ID.AddInteger(VT1.getRawBits());
7975   ID.AddInteger(VT2.getRawBits());
7976 
7977   void *IP = nullptr;
7978   SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
7979   if (!Result) {
7980     EVT *Array = Allocator.Allocate<EVT>(2);
7981     Array[0] = VT1;
7982     Array[1] = VT2;
7983     Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 2);
7984     VTListMap.InsertNode(Result, IP);
7985   }
7986   return Result->getSDVTList();
7987 }
7988 
7989 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3) {
7990   FoldingSetNodeID ID;
7991   ID.AddInteger(3U);
7992   ID.AddInteger(VT1.getRawBits());
7993   ID.AddInteger(VT2.getRawBits());
7994   ID.AddInteger(VT3.getRawBits());
7995 
7996   void *IP = nullptr;
7997   SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
7998   if (!Result) {
7999     EVT *Array = Allocator.Allocate<EVT>(3);
8000     Array[0] = VT1;
8001     Array[1] = VT2;
8002     Array[2] = VT3;
8003     Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 3);
8004     VTListMap.InsertNode(Result, IP);
8005   }
8006   return Result->getSDVTList();
8007 }
8008 
8009 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3, EVT VT4) {
8010   FoldingSetNodeID ID;
8011   ID.AddInteger(4U);
8012   ID.AddInteger(VT1.getRawBits());
8013   ID.AddInteger(VT2.getRawBits());
8014   ID.AddInteger(VT3.getRawBits());
8015   ID.AddInteger(VT4.getRawBits());
8016 
8017   void *IP = nullptr;
8018   SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
8019   if (!Result) {
8020     EVT *Array = Allocator.Allocate<EVT>(4);
8021     Array[0] = VT1;
8022     Array[1] = VT2;
8023     Array[2] = VT3;
8024     Array[3] = VT4;
8025     Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 4);
8026     VTListMap.InsertNode(Result, IP);
8027   }
8028   return Result->getSDVTList();
8029 }
8030 
8031 SDVTList SelectionDAG::getVTList(ArrayRef<EVT> VTs) {
8032   unsigned NumVTs = VTs.size();
8033   FoldingSetNodeID ID;
8034   ID.AddInteger(NumVTs);
8035   for (unsigned index = 0; index < NumVTs; index++) {
8036     ID.AddInteger(VTs[index].getRawBits());
8037   }
8038 
8039   void *IP = nullptr;
8040   SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
8041   if (!Result) {
8042     EVT *Array = Allocator.Allocate<EVT>(NumVTs);
8043     llvm::copy(VTs, Array);
8044     Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, NumVTs);
8045     VTListMap.InsertNode(Result, IP);
8046   }
8047   return Result->getSDVTList();
8048 }
8049 
8050 
8051 /// UpdateNodeOperands - *Mutate* the specified node in-place to have the
8052 /// specified operands.  If the resultant node already exists in the DAG,
8053 /// this does not modify the specified node, instead it returns the node that
8054 /// already exists.  If the resultant node does not exist in the DAG, the
8055 /// input node is returned.  As a degenerate case, if you specify the same
8056 /// input operands as the node already has, the input node is returned.
8057 SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op) {
8058   assert(N->getNumOperands() == 1 && "Update with wrong number of operands");
8059 
8060   // Check to see if there is no change.
8061   if (Op == N->getOperand(0)) return N;
8062 
8063   // See if the modified node already exists.
8064   void *InsertPos = nullptr;
8065   if (SDNode *Existing = FindModifiedNodeSlot(N, Op, InsertPos))
8066     return Existing;
8067 
8068   // Nope it doesn't.  Remove the node from its current place in the maps.
8069   if (InsertPos)
8070     if (!RemoveNodeFromCSEMaps(N))
8071       InsertPos = nullptr;
8072 
8073   // Now we update the operands.
8074   N->OperandList[0].set(Op);
8075 
8076   updateDivergence(N);
8077   // If this gets put into a CSE map, add it.
8078   if (InsertPos) CSEMap.InsertNode(N, InsertPos);
8079   return N;
8080 }
8081 
8082 SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2) {
8083   assert(N->getNumOperands() == 2 && "Update with wrong number of operands");
8084 
8085   // Check to see if there is no change.
8086   if (Op1 == N->getOperand(0) && Op2 == N->getOperand(1))
8087     return N;   // No operands changed, just return the input node.
8088 
8089   // See if the modified node already exists.
8090   void *InsertPos = nullptr;
8091   if (SDNode *Existing = FindModifiedNodeSlot(N, Op1, Op2, InsertPos))
8092     return Existing;
8093 
8094   // Nope it doesn't.  Remove the node from its current place in the maps.
8095   if (InsertPos)
8096     if (!RemoveNodeFromCSEMaps(N))
8097       InsertPos = nullptr;
8098 
8099   // Now we update the operands.
8100   if (N->OperandList[0] != Op1)
8101     N->OperandList[0].set(Op1);
8102   if (N->OperandList[1] != Op2)
8103     N->OperandList[1].set(Op2);
8104 
8105   updateDivergence(N);
8106   // If this gets put into a CSE map, add it.
8107   if (InsertPos) CSEMap.InsertNode(N, InsertPos);
8108   return N;
8109 }
8110 
8111 SDNode *SelectionDAG::
8112 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2, SDValue Op3) {
8113   SDValue Ops[] = { Op1, Op2, Op3 };
8114   return UpdateNodeOperands(N, Ops);
8115 }
8116 
8117 SDNode *SelectionDAG::
8118 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2,
8119                    SDValue Op3, SDValue Op4) {
8120   SDValue Ops[] = { Op1, Op2, Op3, Op4 };
8121   return UpdateNodeOperands(N, Ops);
8122 }
8123 
8124 SDNode *SelectionDAG::
8125 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2,
8126                    SDValue Op3, SDValue Op4, SDValue Op5) {
8127   SDValue Ops[] = { Op1, Op2, Op3, Op4, Op5 };
8128   return UpdateNodeOperands(N, Ops);
8129 }
8130 
8131 SDNode *SelectionDAG::
8132 UpdateNodeOperands(SDNode *N, ArrayRef<SDValue> Ops) {
8133   unsigned NumOps = Ops.size();
8134   assert(N->getNumOperands() == NumOps &&
8135          "Update with wrong number of operands");
8136 
8137   // If no operands changed just return the input node.
8138   if (std::equal(Ops.begin(), Ops.end(), N->op_begin()))
8139     return N;
8140 
8141   // See if the modified node already exists.
8142   void *InsertPos = nullptr;
8143   if (SDNode *Existing = FindModifiedNodeSlot(N, Ops, InsertPos))
8144     return Existing;
8145 
8146   // Nope it doesn't.  Remove the node from its current place in the maps.
8147   if (InsertPos)
8148     if (!RemoveNodeFromCSEMaps(N))
8149       InsertPos = nullptr;
8150 
8151   // Now we update the operands.
8152   for (unsigned i = 0; i != NumOps; ++i)
8153     if (N->OperandList[i] != Ops[i])
8154       N->OperandList[i].set(Ops[i]);
8155 
8156   updateDivergence(N);
8157   // If this gets put into a CSE map, add it.
8158   if (InsertPos) CSEMap.InsertNode(N, InsertPos);
8159   return N;
8160 }
8161 
8162 /// DropOperands - Release the operands and set this node to have
8163 /// zero operands.
8164 void SDNode::DropOperands() {
8165   // Unlike the code in MorphNodeTo that does this, we don't need to
8166   // watch for dead nodes here.
8167   for (op_iterator I = op_begin(), E = op_end(); I != E; ) {
8168     SDUse &Use = *I++;
8169     Use.set(SDValue());
8170   }
8171 }
8172 
8173 void SelectionDAG::setNodeMemRefs(MachineSDNode *N,
8174                                   ArrayRef<MachineMemOperand *> NewMemRefs) {
8175   if (NewMemRefs.empty()) {
8176     N->clearMemRefs();
8177     return;
8178   }
8179 
8180   // Check if we can avoid allocating by storing a single reference directly.
8181   if (NewMemRefs.size() == 1) {
8182     N->MemRefs = NewMemRefs[0];
8183     N->NumMemRefs = 1;
8184     return;
8185   }
8186 
8187   MachineMemOperand **MemRefsBuffer =
8188       Allocator.template Allocate<MachineMemOperand *>(NewMemRefs.size());
8189   llvm::copy(NewMemRefs, MemRefsBuffer);
8190   N->MemRefs = MemRefsBuffer;
8191   N->NumMemRefs = static_cast<int>(NewMemRefs.size());
8192 }
8193 
8194 /// SelectNodeTo - These are wrappers around MorphNodeTo that accept a
8195 /// machine opcode.
8196 ///
8197 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8198                                    EVT VT) {
8199   SDVTList VTs = getVTList(VT);
8200   return SelectNodeTo(N, MachineOpc, VTs, None);
8201 }
8202 
8203 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8204                                    EVT VT, SDValue Op1) {
8205   SDVTList VTs = getVTList(VT);
8206   SDValue Ops[] = { Op1 };
8207   return SelectNodeTo(N, MachineOpc, VTs, Ops);
8208 }
8209 
8210 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8211                                    EVT VT, SDValue Op1,
8212                                    SDValue Op2) {
8213   SDVTList VTs = getVTList(VT);
8214   SDValue Ops[] = { Op1, Op2 };
8215   return SelectNodeTo(N, MachineOpc, VTs, Ops);
8216 }
8217 
8218 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8219                                    EVT VT, SDValue Op1,
8220                                    SDValue Op2, SDValue Op3) {
8221   SDVTList VTs = getVTList(VT);
8222   SDValue Ops[] = { Op1, Op2, Op3 };
8223   return SelectNodeTo(N, MachineOpc, VTs, Ops);
8224 }
8225 
8226 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8227                                    EVT VT, ArrayRef<SDValue> Ops) {
8228   SDVTList VTs = getVTList(VT);
8229   return SelectNodeTo(N, MachineOpc, VTs, Ops);
8230 }
8231 
8232 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8233                                    EVT VT1, EVT VT2, ArrayRef<SDValue> Ops) {
8234   SDVTList VTs = getVTList(VT1, VT2);
8235   return SelectNodeTo(N, MachineOpc, VTs, Ops);
8236 }
8237 
8238 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8239                                    EVT VT1, EVT VT2) {
8240   SDVTList VTs = getVTList(VT1, VT2);
8241   return SelectNodeTo(N, MachineOpc, VTs, None);
8242 }
8243 
8244 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8245                                    EVT VT1, EVT VT2, EVT VT3,
8246                                    ArrayRef<SDValue> Ops) {
8247   SDVTList VTs = getVTList(VT1, VT2, VT3);
8248   return SelectNodeTo(N, MachineOpc, VTs, Ops);
8249 }
8250 
8251 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8252                                    EVT VT1, EVT VT2,
8253                                    SDValue Op1, SDValue Op2) {
8254   SDVTList VTs = getVTList(VT1, VT2);
8255   SDValue Ops[] = { Op1, Op2 };
8256   return SelectNodeTo(N, MachineOpc, VTs, Ops);
8257 }
8258 
8259 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8260                                    SDVTList VTs,ArrayRef<SDValue> Ops) {
8261   SDNode *New = MorphNodeTo(N, ~MachineOpc, VTs, Ops);
8262   // Reset the NodeID to -1.
8263   New->setNodeId(-1);
8264   if (New != N) {
8265     ReplaceAllUsesWith(N, New);
8266     RemoveDeadNode(N);
8267   }
8268   return New;
8269 }
8270 
8271 /// UpdateSDLocOnMergeSDNode - If the opt level is -O0 then it throws away
8272 /// the line number information on the merged node since it is not possible to
8273 /// preserve the information that operation is associated with multiple lines.
8274 /// This will make the debugger working better at -O0, were there is a higher
8275 /// probability having other instructions associated with that line.
8276 ///
8277 /// For IROrder, we keep the smaller of the two
8278 SDNode *SelectionDAG::UpdateSDLocOnMergeSDNode(SDNode *N, const SDLoc &OLoc) {
8279   DebugLoc NLoc = N->getDebugLoc();
8280   if (NLoc && OptLevel == CodeGenOpt::None && OLoc.getDebugLoc() != NLoc) {
8281     N->setDebugLoc(DebugLoc());
8282   }
8283   unsigned Order = std::min(N->getIROrder(), OLoc.getIROrder());
8284   N->setIROrder(Order);
8285   return N;
8286 }
8287 
8288 /// MorphNodeTo - This *mutates* the specified node to have the specified
8289 /// return type, opcode, and operands.
8290 ///
8291 /// Note that MorphNodeTo returns the resultant node.  If there is already a
8292 /// node of the specified opcode and operands, it returns that node instead of
8293 /// the current one.  Note that the SDLoc need not be the same.
8294 ///
8295 /// Using MorphNodeTo is faster than creating a new node and swapping it in
8296 /// with ReplaceAllUsesWith both because it often avoids allocating a new
8297 /// node, and because it doesn't require CSE recalculation for any of
8298 /// the node's users.
8299 ///
8300 /// However, note that MorphNodeTo recursively deletes dead nodes from the DAG.
8301 /// As a consequence it isn't appropriate to use from within the DAG combiner or
8302 /// the legalizer which maintain worklists that would need to be updated when
8303 /// deleting things.
8304 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
8305                                   SDVTList VTs, ArrayRef<SDValue> Ops) {
8306   // If an identical node already exists, use it.
8307   void *IP = nullptr;
8308   if (VTs.VTs[VTs.NumVTs-1] != MVT::Glue) {
8309     FoldingSetNodeID ID;
8310     AddNodeIDNode(ID, Opc, VTs, Ops);
8311     if (SDNode *ON = FindNodeOrInsertPos(ID, SDLoc(N), IP))
8312       return UpdateSDLocOnMergeSDNode(ON, SDLoc(N));
8313   }
8314 
8315   if (!RemoveNodeFromCSEMaps(N))
8316     IP = nullptr;
8317 
8318   // Start the morphing.
8319   N->NodeType = Opc;
8320   N->ValueList = VTs.VTs;
8321   N->NumValues = VTs.NumVTs;
8322 
8323   // Clear the operands list, updating used nodes to remove this from their
8324   // use list.  Keep track of any operands that become dead as a result.
8325   SmallPtrSet<SDNode*, 16> DeadNodeSet;
8326   for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) {
8327     SDUse &Use = *I++;
8328     SDNode *Used = Use.getNode();
8329     Use.set(SDValue());
8330     if (Used->use_empty())
8331       DeadNodeSet.insert(Used);
8332   }
8333 
8334   // For MachineNode, initialize the memory references information.
8335   if (MachineSDNode *MN = dyn_cast<MachineSDNode>(N))
8336     MN->clearMemRefs();
8337 
8338   // Swap for an appropriately sized array from the recycler.
8339   removeOperands(N);
8340   createOperands(N, Ops);
8341 
8342   // Delete any nodes that are still dead after adding the uses for the
8343   // new operands.
8344   if (!DeadNodeSet.empty()) {
8345     SmallVector<SDNode *, 16> DeadNodes;
8346     for (SDNode *N : DeadNodeSet)
8347       if (N->use_empty())
8348         DeadNodes.push_back(N);
8349     RemoveDeadNodes(DeadNodes);
8350   }
8351 
8352   if (IP)
8353     CSEMap.InsertNode(N, IP);   // Memoize the new node.
8354   return N;
8355 }
8356 
8357 SDNode* SelectionDAG::mutateStrictFPToFP(SDNode *Node) {
8358   unsigned OrigOpc = Node->getOpcode();
8359   unsigned NewOpc;
8360   switch (OrigOpc) {
8361   default:
8362     llvm_unreachable("mutateStrictFPToFP called with unexpected opcode!");
8363 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN)               \
8364   case ISD::STRICT_##DAGN: NewOpc = ISD::DAGN; break;
8365 #define CMP_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN)               \
8366   case ISD::STRICT_##DAGN: NewOpc = ISD::SETCC; break;
8367 #include "llvm/IR/ConstrainedOps.def"
8368   }
8369 
8370   assert(Node->getNumValues() == 2 && "Unexpected number of results!");
8371 
8372   // We're taking this node out of the chain, so we need to re-link things.
8373   SDValue InputChain = Node->getOperand(0);
8374   SDValue OutputChain = SDValue(Node, 1);
8375   ReplaceAllUsesOfValueWith(OutputChain, InputChain);
8376 
8377   SmallVector<SDValue, 3> Ops;
8378   for (unsigned i = 1, e = Node->getNumOperands(); i != e; ++i)
8379     Ops.push_back(Node->getOperand(i));
8380 
8381   SDVTList VTs = getVTList(Node->getValueType(0));
8382   SDNode *Res = MorphNodeTo(Node, NewOpc, VTs, Ops);
8383 
8384   // MorphNodeTo can operate in two ways: if an existing node with the
8385   // specified operands exists, it can just return it.  Otherwise, it
8386   // updates the node in place to have the requested operands.
8387   if (Res == Node) {
8388     // If we updated the node in place, reset the node ID.  To the isel,
8389     // this should be just like a newly allocated machine node.
8390     Res->setNodeId(-1);
8391   } else {
8392     ReplaceAllUsesWith(Node, Res);
8393     RemoveDeadNode(Node);
8394   }
8395 
8396   return Res;
8397 }
8398 
8399 /// getMachineNode - These are used for target selectors to create a new node
8400 /// with specified return type(s), MachineInstr opcode, and operands.
8401 ///
8402 /// Note that getMachineNode returns the resultant node.  If there is already a
8403 /// node of the specified opcode and operands, it returns that node instead of
8404 /// the current one.
8405 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
8406                                             EVT VT) {
8407   SDVTList VTs = getVTList(VT);
8408   return getMachineNode(Opcode, dl, VTs, None);
8409 }
8410 
8411 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
8412                                             EVT VT, SDValue Op1) {
8413   SDVTList VTs = getVTList(VT);
8414   SDValue Ops[] = { Op1 };
8415   return getMachineNode(Opcode, dl, VTs, Ops);
8416 }
8417 
8418 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
8419                                             EVT VT, SDValue Op1, SDValue Op2) {
8420   SDVTList VTs = getVTList(VT);
8421   SDValue Ops[] = { Op1, Op2 };
8422   return getMachineNode(Opcode, dl, VTs, Ops);
8423 }
8424 
8425 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
8426                                             EVT VT, SDValue Op1, SDValue Op2,
8427                                             SDValue Op3) {
8428   SDVTList VTs = getVTList(VT);
8429   SDValue Ops[] = { Op1, Op2, Op3 };
8430   return getMachineNode(Opcode, dl, VTs, Ops);
8431 }
8432 
8433 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
8434                                             EVT VT, ArrayRef<SDValue> Ops) {
8435   SDVTList VTs = getVTList(VT);
8436   return getMachineNode(Opcode, dl, VTs, Ops);
8437 }
8438 
8439 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
8440                                             EVT VT1, EVT VT2, SDValue Op1,
8441                                             SDValue Op2) {
8442   SDVTList VTs = getVTList(VT1, VT2);
8443   SDValue Ops[] = { Op1, Op2 };
8444   return getMachineNode(Opcode, dl, VTs, Ops);
8445 }
8446 
8447 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
8448                                             EVT VT1, EVT VT2, SDValue Op1,
8449                                             SDValue Op2, SDValue Op3) {
8450   SDVTList VTs = getVTList(VT1, VT2);
8451   SDValue Ops[] = { Op1, Op2, Op3 };
8452   return getMachineNode(Opcode, dl, VTs, Ops);
8453 }
8454 
8455 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
8456                                             EVT VT1, EVT VT2,
8457                                             ArrayRef<SDValue> Ops) {
8458   SDVTList VTs = getVTList(VT1, VT2);
8459   return getMachineNode(Opcode, dl, VTs, Ops);
8460 }
8461 
8462 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
8463                                             EVT VT1, EVT VT2, EVT VT3,
8464                                             SDValue Op1, SDValue Op2) {
8465   SDVTList VTs = getVTList(VT1, VT2, VT3);
8466   SDValue Ops[] = { Op1, Op2 };
8467   return getMachineNode(Opcode, dl, VTs, Ops);
8468 }
8469 
8470 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
8471                                             EVT VT1, EVT VT2, EVT VT3,
8472                                             SDValue Op1, SDValue Op2,
8473                                             SDValue Op3) {
8474   SDVTList VTs = getVTList(VT1, VT2, VT3);
8475   SDValue Ops[] = { Op1, Op2, Op3 };
8476   return getMachineNode(Opcode, dl, VTs, Ops);
8477 }
8478 
8479 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
8480                                             EVT VT1, EVT VT2, EVT VT3,
8481                                             ArrayRef<SDValue> Ops) {
8482   SDVTList VTs = getVTList(VT1, VT2, VT3);
8483   return getMachineNode(Opcode, dl, VTs, Ops);
8484 }
8485 
8486 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
8487                                             ArrayRef<EVT> ResultTys,
8488                                             ArrayRef<SDValue> Ops) {
8489   SDVTList VTs = getVTList(ResultTys);
8490   return getMachineNode(Opcode, dl, VTs, Ops);
8491 }
8492 
8493 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &DL,
8494                                             SDVTList VTs,
8495                                             ArrayRef<SDValue> Ops) {
8496   bool DoCSE = VTs.VTs[VTs.NumVTs-1] != MVT::Glue;
8497   MachineSDNode *N;
8498   void *IP = nullptr;
8499 
8500   if (DoCSE) {
8501     FoldingSetNodeID ID;
8502     AddNodeIDNode(ID, ~Opcode, VTs, Ops);
8503     IP = nullptr;
8504     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
8505       return cast<MachineSDNode>(UpdateSDLocOnMergeSDNode(E, DL));
8506     }
8507   }
8508 
8509   // Allocate a new MachineSDNode.
8510   N = newSDNode<MachineSDNode>(~Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
8511   createOperands(N, Ops);
8512 
8513   if (DoCSE)
8514     CSEMap.InsertNode(N, IP);
8515 
8516   InsertNode(N);
8517   NewSDValueDbgMsg(SDValue(N, 0), "Creating new machine node: ", this);
8518   return N;
8519 }
8520 
8521 /// getTargetExtractSubreg - A convenience function for creating
8522 /// TargetOpcode::EXTRACT_SUBREG nodes.
8523 SDValue SelectionDAG::getTargetExtractSubreg(int SRIdx, const SDLoc &DL, EVT VT,
8524                                              SDValue Operand) {
8525   SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32);
8526   SDNode *Subreg = getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL,
8527                                   VT, Operand, SRIdxVal);
8528   return SDValue(Subreg, 0);
8529 }
8530 
8531 /// getTargetInsertSubreg - A convenience function for creating
8532 /// TargetOpcode::INSERT_SUBREG nodes.
8533 SDValue SelectionDAG::getTargetInsertSubreg(int SRIdx, const SDLoc &DL, EVT VT,
8534                                             SDValue Operand, SDValue Subreg) {
8535   SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32);
8536   SDNode *Result = getMachineNode(TargetOpcode::INSERT_SUBREG, DL,
8537                                   VT, Operand, Subreg, SRIdxVal);
8538   return SDValue(Result, 0);
8539 }
8540 
8541 /// getNodeIfExists - Get the specified node if it's already available, or
8542 /// else return NULL.
8543 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList,
8544                                       ArrayRef<SDValue> Ops) {
8545   SDNodeFlags Flags;
8546   if (Inserter)
8547     Flags = Inserter->getFlags();
8548   return getNodeIfExists(Opcode, VTList, Ops, Flags);
8549 }
8550 
8551 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList,
8552                                       ArrayRef<SDValue> Ops,
8553                                       const SDNodeFlags Flags) {
8554   if (VTList.VTs[VTList.NumVTs - 1] != MVT::Glue) {
8555     FoldingSetNodeID ID;
8556     AddNodeIDNode(ID, Opcode, VTList, Ops);
8557     void *IP = nullptr;
8558     if (SDNode *E = FindNodeOrInsertPos(ID, SDLoc(), IP)) {
8559       E->intersectFlagsWith(Flags);
8560       return E;
8561     }
8562   }
8563   return nullptr;
8564 }
8565 
8566 /// doesNodeExist - Check if a node exists without modifying its flags.
8567 bool SelectionDAG::doesNodeExist(unsigned Opcode, SDVTList VTList,
8568                                  ArrayRef<SDValue> Ops) {
8569   if (VTList.VTs[VTList.NumVTs - 1] != MVT::Glue) {
8570     FoldingSetNodeID ID;
8571     AddNodeIDNode(ID, Opcode, VTList, Ops);
8572     void *IP = nullptr;
8573     if (FindNodeOrInsertPos(ID, SDLoc(), IP))
8574       return true;
8575   }
8576   return false;
8577 }
8578 
8579 /// getDbgValue - Creates a SDDbgValue node.
8580 ///
8581 /// SDNode
8582 SDDbgValue *SelectionDAG::getDbgValue(DIVariable *Var, DIExpression *Expr,
8583                                       SDNode *N, unsigned R, bool IsIndirect,
8584                                       const DebugLoc &DL, unsigned O) {
8585   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
8586          "Expected inlined-at fields to agree");
8587   return new (DbgInfo->getAlloc())
8588       SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromNode(N, R),
8589                  {}, IsIndirect, DL, O,
8590                  /*IsVariadic=*/false);
8591 }
8592 
8593 /// Constant
8594 SDDbgValue *SelectionDAG::getConstantDbgValue(DIVariable *Var,
8595                                               DIExpression *Expr,
8596                                               const Value *C,
8597                                               const DebugLoc &DL, unsigned O) {
8598   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
8599          "Expected inlined-at fields to agree");
8600   return new (DbgInfo->getAlloc())
8601       SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromConst(C), {},
8602                  /*IsIndirect=*/false, DL, O,
8603                  /*IsVariadic=*/false);
8604 }
8605 
8606 /// FrameIndex
8607 SDDbgValue *SelectionDAG::getFrameIndexDbgValue(DIVariable *Var,
8608                                                 DIExpression *Expr, unsigned FI,
8609                                                 bool IsIndirect,
8610                                                 const DebugLoc &DL,
8611                                                 unsigned O) {
8612   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
8613          "Expected inlined-at fields to agree");
8614   return getFrameIndexDbgValue(Var, Expr, FI, {}, IsIndirect, DL, O);
8615 }
8616 
8617 /// FrameIndex with dependencies
8618 SDDbgValue *SelectionDAG::getFrameIndexDbgValue(DIVariable *Var,
8619                                                 DIExpression *Expr, unsigned FI,
8620                                                 ArrayRef<SDNode *> Dependencies,
8621                                                 bool IsIndirect,
8622                                                 const DebugLoc &DL,
8623                                                 unsigned O) {
8624   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
8625          "Expected inlined-at fields to agree");
8626   return new (DbgInfo->getAlloc())
8627       SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromFrameIdx(FI),
8628                  Dependencies, IsIndirect, DL, O,
8629                  /*IsVariadic=*/false);
8630 }
8631 
8632 /// VReg
8633 SDDbgValue *SelectionDAG::getVRegDbgValue(DIVariable *Var, DIExpression *Expr,
8634                                           unsigned VReg, bool IsIndirect,
8635                                           const DebugLoc &DL, unsigned O) {
8636   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
8637          "Expected inlined-at fields to agree");
8638   return new (DbgInfo->getAlloc())
8639       SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromVReg(VReg),
8640                  {}, IsIndirect, DL, O,
8641                  /*IsVariadic=*/false);
8642 }
8643 
8644 SDDbgValue *SelectionDAG::getDbgValueList(DIVariable *Var, DIExpression *Expr,
8645                                           ArrayRef<SDDbgOperand> Locs,
8646                                           ArrayRef<SDNode *> Dependencies,
8647                                           bool IsIndirect, const DebugLoc &DL,
8648                                           unsigned O, bool IsVariadic) {
8649   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
8650          "Expected inlined-at fields to agree");
8651   return new (DbgInfo->getAlloc())
8652       SDDbgValue(DbgInfo->getAlloc(), Var, Expr, Locs, Dependencies, IsIndirect,
8653                  DL, O, IsVariadic);
8654 }
8655 
8656 void SelectionDAG::transferDbgValues(SDValue From, SDValue To,
8657                                      unsigned OffsetInBits, unsigned SizeInBits,
8658                                      bool InvalidateDbg) {
8659   SDNode *FromNode = From.getNode();
8660   SDNode *ToNode = To.getNode();
8661   assert(FromNode && ToNode && "Can't modify dbg values");
8662 
8663   // PR35338
8664   // TODO: assert(From != To && "Redundant dbg value transfer");
8665   // TODO: assert(FromNode != ToNode && "Intranode dbg value transfer");
8666   if (From == To || FromNode == ToNode)
8667     return;
8668 
8669   if (!FromNode->getHasDebugValue())
8670     return;
8671 
8672   SDDbgOperand FromLocOp =
8673       SDDbgOperand::fromNode(From.getNode(), From.getResNo());
8674   SDDbgOperand ToLocOp = SDDbgOperand::fromNode(To.getNode(), To.getResNo());
8675 
8676   SmallVector<SDDbgValue *, 2> ClonedDVs;
8677   for (SDDbgValue *Dbg : GetDbgValues(FromNode)) {
8678     if (Dbg->isInvalidated())
8679       continue;
8680 
8681     // TODO: assert(!Dbg->isInvalidated() && "Transfer of invalid dbg value");
8682 
8683     // Create a new location ops vector that is equal to the old vector, but
8684     // with each instance of FromLocOp replaced with ToLocOp.
8685     bool Changed = false;
8686     auto NewLocOps = Dbg->copyLocationOps();
8687     std::replace_if(
8688         NewLocOps.begin(), NewLocOps.end(),
8689         [&Changed, FromLocOp](const SDDbgOperand &Op) {
8690           bool Match = Op == FromLocOp;
8691           Changed |= Match;
8692           return Match;
8693         },
8694         ToLocOp);
8695     // Ignore this SDDbgValue if we didn't find a matching location.
8696     if (!Changed)
8697       continue;
8698 
8699     DIVariable *Var = Dbg->getVariable();
8700     auto *Expr = Dbg->getExpression();
8701     // If a fragment is requested, update the expression.
8702     if (SizeInBits) {
8703       // When splitting a larger (e.g., sign-extended) value whose
8704       // lower bits are described with an SDDbgValue, do not attempt
8705       // to transfer the SDDbgValue to the upper bits.
8706       if (auto FI = Expr->getFragmentInfo())
8707         if (OffsetInBits + SizeInBits > FI->SizeInBits)
8708           continue;
8709       auto Fragment = DIExpression::createFragmentExpression(Expr, OffsetInBits,
8710                                                              SizeInBits);
8711       if (!Fragment)
8712         continue;
8713       Expr = *Fragment;
8714     }
8715 
8716     auto AdditionalDependencies = Dbg->getAdditionalDependencies();
8717     // Clone the SDDbgValue and move it to To.
8718     SDDbgValue *Clone = getDbgValueList(
8719         Var, Expr, NewLocOps, AdditionalDependencies, Dbg->isIndirect(),
8720         Dbg->getDebugLoc(), std::max(ToNode->getIROrder(), Dbg->getOrder()),
8721         Dbg->isVariadic());
8722     ClonedDVs.push_back(Clone);
8723 
8724     if (InvalidateDbg) {
8725       // Invalidate value and indicate the SDDbgValue should not be emitted.
8726       Dbg->setIsInvalidated();
8727       Dbg->setIsEmitted();
8728     }
8729   }
8730 
8731   for (SDDbgValue *Dbg : ClonedDVs) {
8732     assert(is_contained(Dbg->getSDNodes(), ToNode) &&
8733            "Transferred DbgValues should depend on the new SDNode");
8734     AddDbgValue(Dbg, false);
8735   }
8736 }
8737 
8738 void SelectionDAG::salvageDebugInfo(SDNode &N) {
8739   if (!N.getHasDebugValue())
8740     return;
8741 
8742   SmallVector<SDDbgValue *, 2> ClonedDVs;
8743   for (auto DV : GetDbgValues(&N)) {
8744     if (DV->isInvalidated())
8745       continue;
8746     switch (N.getOpcode()) {
8747     default:
8748       break;
8749     case ISD::ADD:
8750       SDValue N0 = N.getOperand(0);
8751       SDValue N1 = N.getOperand(1);
8752       if (!isConstantIntBuildVectorOrConstantInt(N0) &&
8753           isConstantIntBuildVectorOrConstantInt(N1)) {
8754         uint64_t Offset = N.getConstantOperandVal(1);
8755 
8756         // Rewrite an ADD constant node into a DIExpression. Since we are
8757         // performing arithmetic to compute the variable's *value* in the
8758         // DIExpression, we need to mark the expression with a
8759         // DW_OP_stack_value.
8760         auto *DIExpr = DV->getExpression();
8761         auto NewLocOps = DV->copyLocationOps();
8762         bool Changed = false;
8763         for (size_t i = 0; i < NewLocOps.size(); ++i) {
8764           // We're not given a ResNo to compare against because the whole
8765           // node is going away. We know that any ISD::ADD only has one
8766           // result, so we can assume any node match is using the result.
8767           if (NewLocOps[i].getKind() != SDDbgOperand::SDNODE ||
8768               NewLocOps[i].getSDNode() != &N)
8769             continue;
8770           NewLocOps[i] = SDDbgOperand::fromNode(N0.getNode(), N0.getResNo());
8771           SmallVector<uint64_t, 3> ExprOps;
8772           DIExpression::appendOffset(ExprOps, Offset);
8773           DIExpr = DIExpression::appendOpsToArg(DIExpr, ExprOps, i, true);
8774           Changed = true;
8775         }
8776         (void)Changed;
8777         assert(Changed && "Salvage target doesn't use N");
8778 
8779         auto AdditionalDependencies = DV->getAdditionalDependencies();
8780         SDDbgValue *Clone = getDbgValueList(DV->getVariable(), DIExpr,
8781                                             NewLocOps, AdditionalDependencies,
8782                                             DV->isIndirect(), DV->getDebugLoc(),
8783                                             DV->getOrder(), DV->isVariadic());
8784         ClonedDVs.push_back(Clone);
8785         DV->setIsInvalidated();
8786         DV->setIsEmitted();
8787         LLVM_DEBUG(dbgs() << "SALVAGE: Rewriting";
8788                    N0.getNode()->dumprFull(this);
8789                    dbgs() << " into " << *DIExpr << '\n');
8790       }
8791     }
8792   }
8793 
8794   for (SDDbgValue *Dbg : ClonedDVs) {
8795     assert(!Dbg->getSDNodes().empty() &&
8796            "Salvaged DbgValue should depend on a new SDNode");
8797     AddDbgValue(Dbg, false);
8798   }
8799 }
8800 
8801 /// Creates a SDDbgLabel node.
8802 SDDbgLabel *SelectionDAG::getDbgLabel(DILabel *Label,
8803                                       const DebugLoc &DL, unsigned O) {
8804   assert(cast<DILabel>(Label)->isValidLocationForIntrinsic(DL) &&
8805          "Expected inlined-at fields to agree");
8806   return new (DbgInfo->getAlloc()) SDDbgLabel(Label, DL, O);
8807 }
8808 
8809 namespace {
8810 
8811 /// RAUWUpdateListener - Helper for ReplaceAllUsesWith - When the node
8812 /// pointed to by a use iterator is deleted, increment the use iterator
8813 /// so that it doesn't dangle.
8814 ///
8815 class RAUWUpdateListener : public SelectionDAG::DAGUpdateListener {
8816   SDNode::use_iterator &UI;
8817   SDNode::use_iterator &UE;
8818 
8819   void NodeDeleted(SDNode *N, SDNode *E) override {
8820     // Increment the iterator as needed.
8821     while (UI != UE && N == *UI)
8822       ++UI;
8823   }
8824 
8825 public:
8826   RAUWUpdateListener(SelectionDAG &d,
8827                      SDNode::use_iterator &ui,
8828                      SDNode::use_iterator &ue)
8829     : SelectionDAG::DAGUpdateListener(d), UI(ui), UE(ue) {}
8830 };
8831 
8832 } // end anonymous namespace
8833 
8834 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
8835 /// This can cause recursive merging of nodes in the DAG.
8836 ///
8837 /// This version assumes From has a single result value.
8838 ///
8839 void SelectionDAG::ReplaceAllUsesWith(SDValue FromN, SDValue To) {
8840   SDNode *From = FromN.getNode();
8841   assert(From->getNumValues() == 1 && FromN.getResNo() == 0 &&
8842          "Cannot replace with this method!");
8843   assert(From != To.getNode() && "Cannot replace uses of with self");
8844 
8845   // Preserve Debug Values
8846   transferDbgValues(FromN, To);
8847 
8848   // Iterate over all the existing uses of From. New uses will be added
8849   // to the beginning of the use list, which we avoid visiting.
8850   // This specifically avoids visiting uses of From that arise while the
8851   // replacement is happening, because any such uses would be the result
8852   // of CSE: If an existing node looks like From after one of its operands
8853   // is replaced by To, we don't want to replace of all its users with To
8854   // too. See PR3018 for more info.
8855   SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
8856   RAUWUpdateListener Listener(*this, UI, UE);
8857   while (UI != UE) {
8858     SDNode *User = *UI;
8859 
8860     // This node is about to morph, remove its old self from the CSE maps.
8861     RemoveNodeFromCSEMaps(User);
8862 
8863     // A user can appear in a use list multiple times, and when this
8864     // happens the uses are usually next to each other in the list.
8865     // To help reduce the number of CSE recomputations, process all
8866     // the uses of this user that we can find this way.
8867     do {
8868       SDUse &Use = UI.getUse();
8869       ++UI;
8870       Use.set(To);
8871       if (To->isDivergent() != From->isDivergent())
8872         updateDivergence(User);
8873     } while (UI != UE && *UI == User);
8874     // Now that we have modified User, add it back to the CSE maps.  If it
8875     // already exists there, recursively merge the results together.
8876     AddModifiedNodeToCSEMaps(User);
8877   }
8878 
8879   // If we just RAUW'd the root, take note.
8880   if (FromN == getRoot())
8881     setRoot(To);
8882 }
8883 
8884 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
8885 /// This can cause recursive merging of nodes in the DAG.
8886 ///
8887 /// This version assumes that for each value of From, there is a
8888 /// corresponding value in To in the same position with the same type.
8889 ///
8890 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, SDNode *To) {
8891 #ifndef NDEBUG
8892   for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
8893     assert((!From->hasAnyUseOfValue(i) ||
8894             From->getValueType(i) == To->getValueType(i)) &&
8895            "Cannot use this version of ReplaceAllUsesWith!");
8896 #endif
8897 
8898   // Handle the trivial case.
8899   if (From == To)
8900     return;
8901 
8902   // Preserve Debug Info. Only do this if there's a use.
8903   for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
8904     if (From->hasAnyUseOfValue(i)) {
8905       assert((i < To->getNumValues()) && "Invalid To location");
8906       transferDbgValues(SDValue(From, i), SDValue(To, i));
8907     }
8908 
8909   // Iterate over just the existing users of From. See the comments in
8910   // the ReplaceAllUsesWith above.
8911   SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
8912   RAUWUpdateListener Listener(*this, UI, UE);
8913   while (UI != UE) {
8914     SDNode *User = *UI;
8915 
8916     // This node is about to morph, remove its old self from the CSE maps.
8917     RemoveNodeFromCSEMaps(User);
8918 
8919     // A user can appear in a use list multiple times, and when this
8920     // happens the uses are usually next to each other in the list.
8921     // To help reduce the number of CSE recomputations, process all
8922     // the uses of this user that we can find this way.
8923     do {
8924       SDUse &Use = UI.getUse();
8925       ++UI;
8926       Use.setNode(To);
8927       if (To->isDivergent() != From->isDivergent())
8928         updateDivergence(User);
8929     } while (UI != UE && *UI == User);
8930 
8931     // Now that we have modified User, add it back to the CSE maps.  If it
8932     // already exists there, recursively merge the results together.
8933     AddModifiedNodeToCSEMaps(User);
8934   }
8935 
8936   // If we just RAUW'd the root, take note.
8937   if (From == getRoot().getNode())
8938     setRoot(SDValue(To, getRoot().getResNo()));
8939 }
8940 
8941 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
8942 /// This can cause recursive merging of nodes in the DAG.
8943 ///
8944 /// This version can replace From with any result values.  To must match the
8945 /// number and types of values returned by From.
8946 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, const SDValue *To) {
8947   if (From->getNumValues() == 1)  // Handle the simple case efficiently.
8948     return ReplaceAllUsesWith(SDValue(From, 0), To[0]);
8949 
8950   // Preserve Debug Info.
8951   for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
8952     transferDbgValues(SDValue(From, i), To[i]);
8953 
8954   // Iterate over just the existing users of From. See the comments in
8955   // the ReplaceAllUsesWith above.
8956   SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
8957   RAUWUpdateListener Listener(*this, UI, UE);
8958   while (UI != UE) {
8959     SDNode *User = *UI;
8960 
8961     // This node is about to morph, remove its old self from the CSE maps.
8962     RemoveNodeFromCSEMaps(User);
8963 
8964     // A user can appear in a use list multiple times, and when this happens the
8965     // uses are usually next to each other in the list.  To help reduce the
8966     // number of CSE and divergence recomputations, process all the uses of this
8967     // user that we can find this way.
8968     bool To_IsDivergent = false;
8969     do {
8970       SDUse &Use = UI.getUse();
8971       const SDValue &ToOp = To[Use.getResNo()];
8972       ++UI;
8973       Use.set(ToOp);
8974       To_IsDivergent |= ToOp->isDivergent();
8975     } while (UI != UE && *UI == User);
8976 
8977     if (To_IsDivergent != From->isDivergent())
8978       updateDivergence(User);
8979 
8980     // Now that we have modified User, add it back to the CSE maps.  If it
8981     // already exists there, recursively merge the results together.
8982     AddModifiedNodeToCSEMaps(User);
8983   }
8984 
8985   // If we just RAUW'd the root, take note.
8986   if (From == getRoot().getNode())
8987     setRoot(SDValue(To[getRoot().getResNo()]));
8988 }
8989 
8990 /// ReplaceAllUsesOfValueWith - Replace any uses of From with To, leaving
8991 /// uses of other values produced by From.getNode() alone.  The Deleted
8992 /// vector is handled the same way as for ReplaceAllUsesWith.
8993 void SelectionDAG::ReplaceAllUsesOfValueWith(SDValue From, SDValue To){
8994   // Handle the really simple, really trivial case efficiently.
8995   if (From == To) return;
8996 
8997   // Handle the simple, trivial, case efficiently.
8998   if (From.getNode()->getNumValues() == 1) {
8999     ReplaceAllUsesWith(From, To);
9000     return;
9001   }
9002 
9003   // Preserve Debug Info.
9004   transferDbgValues(From, To);
9005 
9006   // Iterate over just the existing users of From. See the comments in
9007   // the ReplaceAllUsesWith above.
9008   SDNode::use_iterator UI = From.getNode()->use_begin(),
9009                        UE = From.getNode()->use_end();
9010   RAUWUpdateListener Listener(*this, UI, UE);
9011   while (UI != UE) {
9012     SDNode *User = *UI;
9013     bool UserRemovedFromCSEMaps = false;
9014 
9015     // A user can appear in a use list multiple times, and when this
9016     // happens the uses are usually next to each other in the list.
9017     // To help reduce the number of CSE recomputations, process all
9018     // the uses of this user that we can find this way.
9019     do {
9020       SDUse &Use = UI.getUse();
9021 
9022       // Skip uses of different values from the same node.
9023       if (Use.getResNo() != From.getResNo()) {
9024         ++UI;
9025         continue;
9026       }
9027 
9028       // If this node hasn't been modified yet, it's still in the CSE maps,
9029       // so remove its old self from the CSE maps.
9030       if (!UserRemovedFromCSEMaps) {
9031         RemoveNodeFromCSEMaps(User);
9032         UserRemovedFromCSEMaps = true;
9033       }
9034 
9035       ++UI;
9036       Use.set(To);
9037       if (To->isDivergent() != From->isDivergent())
9038         updateDivergence(User);
9039     } while (UI != UE && *UI == User);
9040     // We are iterating over all uses of the From node, so if a use
9041     // doesn't use the specific value, no changes are made.
9042     if (!UserRemovedFromCSEMaps)
9043       continue;
9044 
9045     // Now that we have modified User, add it back to the CSE maps.  If it
9046     // already exists there, recursively merge the results together.
9047     AddModifiedNodeToCSEMaps(User);
9048   }
9049 
9050   // If we just RAUW'd the root, take note.
9051   if (From == getRoot())
9052     setRoot(To);
9053 }
9054 
9055 namespace {
9056 
9057   /// UseMemo - This class is used by SelectionDAG::ReplaceAllUsesOfValuesWith
9058   /// to record information about a use.
9059   struct UseMemo {
9060     SDNode *User;
9061     unsigned Index;
9062     SDUse *Use;
9063   };
9064 
9065   /// operator< - Sort Memos by User.
9066   bool operator<(const UseMemo &L, const UseMemo &R) {
9067     return (intptr_t)L.User < (intptr_t)R.User;
9068   }
9069 
9070 } // end anonymous namespace
9071 
9072 bool SelectionDAG::calculateDivergence(SDNode *N) {
9073   if (TLI->isSDNodeAlwaysUniform(N)) {
9074     assert(!TLI->isSDNodeSourceOfDivergence(N, FLI, DA) &&
9075            "Conflicting divergence information!");
9076     return false;
9077   }
9078   if (TLI->isSDNodeSourceOfDivergence(N, FLI, DA))
9079     return true;
9080   for (auto &Op : N->ops()) {
9081     if (Op.Val.getValueType() != MVT::Other && Op.getNode()->isDivergent())
9082       return true;
9083   }
9084   return false;
9085 }
9086 
9087 void SelectionDAG::updateDivergence(SDNode *N) {
9088   SmallVector<SDNode *, 16> Worklist(1, N);
9089   do {
9090     N = Worklist.pop_back_val();
9091     bool IsDivergent = calculateDivergence(N);
9092     if (N->SDNodeBits.IsDivergent != IsDivergent) {
9093       N->SDNodeBits.IsDivergent = IsDivergent;
9094       llvm::append_range(Worklist, N->uses());
9095     }
9096   } while (!Worklist.empty());
9097 }
9098 
9099 void SelectionDAG::CreateTopologicalOrder(std::vector<SDNode *> &Order) {
9100   DenseMap<SDNode *, unsigned> Degree;
9101   Order.reserve(AllNodes.size());
9102   for (auto &N : allnodes()) {
9103     unsigned NOps = N.getNumOperands();
9104     Degree[&N] = NOps;
9105     if (0 == NOps)
9106       Order.push_back(&N);
9107   }
9108   for (size_t I = 0; I != Order.size(); ++I) {
9109     SDNode *N = Order[I];
9110     for (auto U : N->uses()) {
9111       unsigned &UnsortedOps = Degree[U];
9112       if (0 == --UnsortedOps)
9113         Order.push_back(U);
9114     }
9115   }
9116 }
9117 
9118 #ifndef NDEBUG
9119 void SelectionDAG::VerifyDAGDiverence() {
9120   std::vector<SDNode *> TopoOrder;
9121   CreateTopologicalOrder(TopoOrder);
9122   for (auto *N : TopoOrder) {
9123     assert(calculateDivergence(N) == N->isDivergent() &&
9124            "Divergence bit inconsistency detected");
9125   }
9126 }
9127 #endif
9128 
9129 /// ReplaceAllUsesOfValuesWith - Replace any uses of From with To, leaving
9130 /// uses of other values produced by From.getNode() alone.  The same value
9131 /// may appear in both the From and To list.  The Deleted vector is
9132 /// handled the same way as for ReplaceAllUsesWith.
9133 void SelectionDAG::ReplaceAllUsesOfValuesWith(const SDValue *From,
9134                                               const SDValue *To,
9135                                               unsigned Num){
9136   // Handle the simple, trivial case efficiently.
9137   if (Num == 1)
9138     return ReplaceAllUsesOfValueWith(*From, *To);
9139 
9140   transferDbgValues(*From, *To);
9141 
9142   // Read up all the uses and make records of them. This helps
9143   // processing new uses that are introduced during the
9144   // replacement process.
9145   SmallVector<UseMemo, 4> Uses;
9146   for (unsigned i = 0; i != Num; ++i) {
9147     unsigned FromResNo = From[i].getResNo();
9148     SDNode *FromNode = From[i].getNode();
9149     for (SDNode::use_iterator UI = FromNode->use_begin(),
9150          E = FromNode->use_end(); UI != E; ++UI) {
9151       SDUse &Use = UI.getUse();
9152       if (Use.getResNo() == FromResNo) {
9153         UseMemo Memo = { *UI, i, &Use };
9154         Uses.push_back(Memo);
9155       }
9156     }
9157   }
9158 
9159   // Sort the uses, so that all the uses from a given User are together.
9160   llvm::sort(Uses);
9161 
9162   for (unsigned UseIndex = 0, UseIndexEnd = Uses.size();
9163        UseIndex != UseIndexEnd; ) {
9164     // We know that this user uses some value of From.  If it is the right
9165     // value, update it.
9166     SDNode *User = Uses[UseIndex].User;
9167 
9168     // This node is about to morph, remove its old self from the CSE maps.
9169     RemoveNodeFromCSEMaps(User);
9170 
9171     // The Uses array is sorted, so all the uses for a given User
9172     // are next to each other in the list.
9173     // To help reduce the number of CSE recomputations, process all
9174     // the uses of this user that we can find this way.
9175     do {
9176       unsigned i = Uses[UseIndex].Index;
9177       SDUse &Use = *Uses[UseIndex].Use;
9178       ++UseIndex;
9179 
9180       Use.set(To[i]);
9181     } while (UseIndex != UseIndexEnd && Uses[UseIndex].User == User);
9182 
9183     // Now that we have modified User, add it back to the CSE maps.  If it
9184     // already exists there, recursively merge the results together.
9185     AddModifiedNodeToCSEMaps(User);
9186   }
9187 }
9188 
9189 /// AssignTopologicalOrder - Assign a unique node id for each node in the DAG
9190 /// based on their topological order. It returns the maximum id and a vector
9191 /// of the SDNodes* in assigned order by reference.
9192 unsigned SelectionDAG::AssignTopologicalOrder() {
9193   unsigned DAGSize = 0;
9194 
9195   // SortedPos tracks the progress of the algorithm. Nodes before it are
9196   // sorted, nodes after it are unsorted. When the algorithm completes
9197   // it is at the end of the list.
9198   allnodes_iterator SortedPos = allnodes_begin();
9199 
9200   // Visit all the nodes. Move nodes with no operands to the front of
9201   // the list immediately. Annotate nodes that do have operands with their
9202   // operand count. Before we do this, the Node Id fields of the nodes
9203   // may contain arbitrary values. After, the Node Id fields for nodes
9204   // before SortedPos will contain the topological sort index, and the
9205   // Node Id fields for nodes At SortedPos and after will contain the
9206   // count of outstanding operands.
9207   for (allnodes_iterator I = allnodes_begin(),E = allnodes_end(); I != E; ) {
9208     SDNode *N = &*I++;
9209     checkForCycles(N, this);
9210     unsigned Degree = N->getNumOperands();
9211     if (Degree == 0) {
9212       // A node with no uses, add it to the result array immediately.
9213       N->setNodeId(DAGSize++);
9214       allnodes_iterator Q(N);
9215       if (Q != SortedPos)
9216         SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(Q));
9217       assert(SortedPos != AllNodes.end() && "Overran node list");
9218       ++SortedPos;
9219     } else {
9220       // Temporarily use the Node Id as scratch space for the degree count.
9221       N->setNodeId(Degree);
9222     }
9223   }
9224 
9225   // Visit all the nodes. As we iterate, move nodes into sorted order,
9226   // such that by the time the end is reached all nodes will be sorted.
9227   for (SDNode &Node : allnodes()) {
9228     SDNode *N = &Node;
9229     checkForCycles(N, this);
9230     // N is in sorted position, so all its uses have one less operand
9231     // that needs to be sorted.
9232     for (SDNode *P : N->uses()) {
9233       unsigned Degree = P->getNodeId();
9234       assert(Degree != 0 && "Invalid node degree");
9235       --Degree;
9236       if (Degree == 0) {
9237         // All of P's operands are sorted, so P may sorted now.
9238         P->setNodeId(DAGSize++);
9239         if (P->getIterator() != SortedPos)
9240           SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(P));
9241         assert(SortedPos != AllNodes.end() && "Overran node list");
9242         ++SortedPos;
9243       } else {
9244         // Update P's outstanding operand count.
9245         P->setNodeId(Degree);
9246       }
9247     }
9248     if (Node.getIterator() == SortedPos) {
9249 #ifndef NDEBUG
9250       allnodes_iterator I(N);
9251       SDNode *S = &*++I;
9252       dbgs() << "Overran sorted position:\n";
9253       S->dumprFull(this); dbgs() << "\n";
9254       dbgs() << "Checking if this is due to cycles\n";
9255       checkForCycles(this, true);
9256 #endif
9257       llvm_unreachable(nullptr);
9258     }
9259   }
9260 
9261   assert(SortedPos == AllNodes.end() &&
9262          "Topological sort incomplete!");
9263   assert(AllNodes.front().getOpcode() == ISD::EntryToken &&
9264          "First node in topological sort is not the entry token!");
9265   assert(AllNodes.front().getNodeId() == 0 &&
9266          "First node in topological sort has non-zero id!");
9267   assert(AllNodes.front().getNumOperands() == 0 &&
9268          "First node in topological sort has operands!");
9269   assert(AllNodes.back().getNodeId() == (int)DAGSize-1 &&
9270          "Last node in topologic sort has unexpected id!");
9271   assert(AllNodes.back().use_empty() &&
9272          "Last node in topologic sort has users!");
9273   assert(DAGSize == allnodes_size() && "Node count mismatch!");
9274   return DAGSize;
9275 }
9276 
9277 /// AddDbgValue - Add a dbg_value SDNode. If SD is non-null that means the
9278 /// value is produced by SD.
9279 void SelectionDAG::AddDbgValue(SDDbgValue *DB, bool isParameter) {
9280   for (SDNode *SD : DB->getSDNodes()) {
9281     if (!SD)
9282       continue;
9283     assert(DbgInfo->getSDDbgValues(SD).empty() || SD->getHasDebugValue());
9284     SD->setHasDebugValue(true);
9285   }
9286   DbgInfo->add(DB, isParameter);
9287 }
9288 
9289 void SelectionDAG::AddDbgLabel(SDDbgLabel *DB) { DbgInfo->add(DB); }
9290 
9291 SDValue SelectionDAG::makeEquivalentMemoryOrdering(SDValue OldChain,
9292                                                    SDValue NewMemOpChain) {
9293   assert(isa<MemSDNode>(NewMemOpChain) && "Expected a memop node");
9294   assert(NewMemOpChain.getValueType() == MVT::Other && "Expected a token VT");
9295   // The new memory operation must have the same position as the old load in
9296   // terms of memory dependency. Create a TokenFactor for the old load and new
9297   // memory operation and update uses of the old load's output chain to use that
9298   // TokenFactor.
9299   if (OldChain == NewMemOpChain || OldChain.use_empty())
9300     return NewMemOpChain;
9301 
9302   SDValue TokenFactor = getNode(ISD::TokenFactor, SDLoc(OldChain), MVT::Other,
9303                                 OldChain, NewMemOpChain);
9304   ReplaceAllUsesOfValueWith(OldChain, TokenFactor);
9305   UpdateNodeOperands(TokenFactor.getNode(), OldChain, NewMemOpChain);
9306   return TokenFactor;
9307 }
9308 
9309 SDValue SelectionDAG::makeEquivalentMemoryOrdering(LoadSDNode *OldLoad,
9310                                                    SDValue NewMemOp) {
9311   assert(isa<MemSDNode>(NewMemOp.getNode()) && "Expected a memop node");
9312   SDValue OldChain = SDValue(OldLoad, 1);
9313   SDValue NewMemOpChain = NewMemOp.getValue(1);
9314   return makeEquivalentMemoryOrdering(OldChain, NewMemOpChain);
9315 }
9316 
9317 SDValue SelectionDAG::getSymbolFunctionGlobalAddress(SDValue Op,
9318                                                      Function **OutFunction) {
9319   assert(isa<ExternalSymbolSDNode>(Op) && "Node should be an ExternalSymbol");
9320 
9321   auto *Symbol = cast<ExternalSymbolSDNode>(Op)->getSymbol();
9322   auto *Module = MF->getFunction().getParent();
9323   auto *Function = Module->getFunction(Symbol);
9324 
9325   if (OutFunction != nullptr)
9326       *OutFunction = Function;
9327 
9328   if (Function != nullptr) {
9329     auto PtrTy = TLI->getPointerTy(getDataLayout(), Function->getAddressSpace());
9330     return getGlobalAddress(Function, SDLoc(Op), PtrTy);
9331   }
9332 
9333   std::string ErrorStr;
9334   raw_string_ostream ErrorFormatter(ErrorStr);
9335 
9336   ErrorFormatter << "Undefined external symbol ";
9337   ErrorFormatter << '"' << Symbol << '"';
9338   ErrorFormatter.flush();
9339 
9340   report_fatal_error(ErrorStr);
9341 }
9342 
9343 //===----------------------------------------------------------------------===//
9344 //                              SDNode Class
9345 //===----------------------------------------------------------------------===//
9346 
9347 bool llvm::isNullConstant(SDValue V) {
9348   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
9349   return Const != nullptr && Const->isNullValue();
9350 }
9351 
9352 bool llvm::isNullFPConstant(SDValue V) {
9353   ConstantFPSDNode *Const = dyn_cast<ConstantFPSDNode>(V);
9354   return Const != nullptr && Const->isZero() && !Const->isNegative();
9355 }
9356 
9357 bool llvm::isAllOnesConstant(SDValue V) {
9358   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
9359   return Const != nullptr && Const->isAllOnesValue();
9360 }
9361 
9362 bool llvm::isOneConstant(SDValue V) {
9363   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
9364   return Const != nullptr && Const->isOne();
9365 }
9366 
9367 SDValue llvm::peekThroughBitcasts(SDValue V) {
9368   while (V.getOpcode() == ISD::BITCAST)
9369     V = V.getOperand(0);
9370   return V;
9371 }
9372 
9373 SDValue llvm::peekThroughOneUseBitcasts(SDValue V) {
9374   while (V.getOpcode() == ISD::BITCAST && V.getOperand(0).hasOneUse())
9375     V = V.getOperand(0);
9376   return V;
9377 }
9378 
9379 SDValue llvm::peekThroughExtractSubvectors(SDValue V) {
9380   while (V.getOpcode() == ISD::EXTRACT_SUBVECTOR)
9381     V = V.getOperand(0);
9382   return V;
9383 }
9384 
9385 bool llvm::isBitwiseNot(SDValue V, bool AllowUndefs) {
9386   if (V.getOpcode() != ISD::XOR)
9387     return false;
9388   V = peekThroughBitcasts(V.getOperand(1));
9389   unsigned NumBits = V.getScalarValueSizeInBits();
9390   ConstantSDNode *C =
9391       isConstOrConstSplat(V, AllowUndefs, /*AllowTruncation*/ true);
9392   return C && (C->getAPIntValue().countTrailingOnes() >= NumBits);
9393 }
9394 
9395 ConstantSDNode *llvm::isConstOrConstSplat(SDValue N, bool AllowUndefs,
9396                                           bool AllowTruncation) {
9397   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
9398     return CN;
9399 
9400   // SplatVectors can truncate their operands. Ignore that case here unless
9401   // AllowTruncation is set.
9402   if (N->getOpcode() == ISD::SPLAT_VECTOR) {
9403     EVT VecEltVT = N->getValueType(0).getVectorElementType();
9404     if (auto *CN = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
9405       EVT CVT = CN->getValueType(0);
9406       assert(CVT.bitsGE(VecEltVT) && "Illegal splat_vector element extension");
9407       if (AllowTruncation || CVT == VecEltVT)
9408         return CN;
9409     }
9410   }
9411 
9412   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
9413     BitVector UndefElements;
9414     ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
9415 
9416     // BuildVectors can truncate their operands. Ignore that case here unless
9417     // AllowTruncation is set.
9418     if (CN && (UndefElements.none() || AllowUndefs)) {
9419       EVT CVT = CN->getValueType(0);
9420       EVT NSVT = N.getValueType().getScalarType();
9421       assert(CVT.bitsGE(NSVT) && "Illegal build vector element extension");
9422       if (AllowTruncation || (CVT == NSVT))
9423         return CN;
9424     }
9425   }
9426 
9427   return nullptr;
9428 }
9429 
9430 ConstantSDNode *llvm::isConstOrConstSplat(SDValue N, const APInt &DemandedElts,
9431                                           bool AllowUndefs,
9432                                           bool AllowTruncation) {
9433   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
9434     return CN;
9435 
9436   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
9437     BitVector UndefElements;
9438     ConstantSDNode *CN = BV->getConstantSplatNode(DemandedElts, &UndefElements);
9439 
9440     // BuildVectors can truncate their operands. Ignore that case here unless
9441     // AllowTruncation is set.
9442     if (CN && (UndefElements.none() || AllowUndefs)) {
9443       EVT CVT = CN->getValueType(0);
9444       EVT NSVT = N.getValueType().getScalarType();
9445       assert(CVT.bitsGE(NSVT) && "Illegal build vector element extension");
9446       if (AllowTruncation || (CVT == NSVT))
9447         return CN;
9448     }
9449   }
9450 
9451   return nullptr;
9452 }
9453 
9454 ConstantFPSDNode *llvm::isConstOrConstSplatFP(SDValue N, bool AllowUndefs) {
9455   if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
9456     return CN;
9457 
9458   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
9459     BitVector UndefElements;
9460     ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements);
9461     if (CN && (UndefElements.none() || AllowUndefs))
9462       return CN;
9463   }
9464 
9465   if (N.getOpcode() == ISD::SPLAT_VECTOR)
9466     if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N.getOperand(0)))
9467       return CN;
9468 
9469   return nullptr;
9470 }
9471 
9472 ConstantFPSDNode *llvm::isConstOrConstSplatFP(SDValue N,
9473                                               const APInt &DemandedElts,
9474                                               bool AllowUndefs) {
9475   if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
9476     return CN;
9477 
9478   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
9479     BitVector UndefElements;
9480     ConstantFPSDNode *CN =
9481         BV->getConstantFPSplatNode(DemandedElts, &UndefElements);
9482     if (CN && (UndefElements.none() || AllowUndefs))
9483       return CN;
9484   }
9485 
9486   return nullptr;
9487 }
9488 
9489 bool llvm::isNullOrNullSplat(SDValue N, bool AllowUndefs) {
9490   // TODO: may want to use peekThroughBitcast() here.
9491   ConstantSDNode *C = isConstOrConstSplat(N, AllowUndefs);
9492   return C && C->isNullValue();
9493 }
9494 
9495 bool llvm::isOneOrOneSplat(SDValue N, bool AllowUndefs) {
9496   // TODO: may want to use peekThroughBitcast() here.
9497   unsigned BitWidth = N.getScalarValueSizeInBits();
9498   ConstantSDNode *C = isConstOrConstSplat(N, AllowUndefs);
9499   return C && C->isOne() && C->getValueSizeInBits(0) == BitWidth;
9500 }
9501 
9502 bool llvm::isAllOnesOrAllOnesSplat(SDValue N, bool AllowUndefs) {
9503   N = peekThroughBitcasts(N);
9504   unsigned BitWidth = N.getScalarValueSizeInBits();
9505   ConstantSDNode *C = isConstOrConstSplat(N, AllowUndefs);
9506   return C && C->isAllOnesValue() && C->getValueSizeInBits(0) == BitWidth;
9507 }
9508 
9509 HandleSDNode::~HandleSDNode() {
9510   DropOperands();
9511 }
9512 
9513 GlobalAddressSDNode::GlobalAddressSDNode(unsigned Opc, unsigned Order,
9514                                          const DebugLoc &DL,
9515                                          const GlobalValue *GA, EVT VT,
9516                                          int64_t o, unsigned TF)
9517     : SDNode(Opc, Order, DL, getSDVTList(VT)), Offset(o), TargetFlags(TF) {
9518   TheGlobal = GA;
9519 }
9520 
9521 AddrSpaceCastSDNode::AddrSpaceCastSDNode(unsigned Order, const DebugLoc &dl,
9522                                          EVT VT, unsigned SrcAS,
9523                                          unsigned DestAS)
9524     : SDNode(ISD::ADDRSPACECAST, Order, dl, getSDVTList(VT)),
9525       SrcAddrSpace(SrcAS), DestAddrSpace(DestAS) {}
9526 
9527 MemSDNode::MemSDNode(unsigned Opc, unsigned Order, const DebugLoc &dl,
9528                      SDVTList VTs, EVT memvt, MachineMemOperand *mmo)
9529     : SDNode(Opc, Order, dl, VTs), MemoryVT(memvt), MMO(mmo) {
9530   MemSDNodeBits.IsVolatile = MMO->isVolatile();
9531   MemSDNodeBits.IsNonTemporal = MMO->isNonTemporal();
9532   MemSDNodeBits.IsDereferenceable = MMO->isDereferenceable();
9533   MemSDNodeBits.IsInvariant = MMO->isInvariant();
9534 
9535   // We check here that the size of the memory operand fits within the size of
9536   // the MMO. This is because the MMO might indicate only a possible address
9537   // range instead of specifying the affected memory addresses precisely.
9538   // TODO: Make MachineMemOperands aware of scalable vectors.
9539   assert(memvt.getStoreSize().getKnownMinSize() <= MMO->getSize() &&
9540          "Size mismatch!");
9541 }
9542 
9543 /// Profile - Gather unique data for the node.
9544 ///
9545 void SDNode::Profile(FoldingSetNodeID &ID) const {
9546   AddNodeIDNode(ID, this);
9547 }
9548 
9549 namespace {
9550 
9551   struct EVTArray {
9552     std::vector<EVT> VTs;
9553 
9554     EVTArray() {
9555       VTs.reserve(MVT::LAST_VALUETYPE);
9556       for (unsigned i = 0; i < MVT::LAST_VALUETYPE; ++i)
9557         VTs.push_back(MVT((MVT::SimpleValueType)i));
9558     }
9559   };
9560 
9561 } // end anonymous namespace
9562 
9563 static ManagedStatic<std::set<EVT, EVT::compareRawBits>> EVTs;
9564 static ManagedStatic<EVTArray> SimpleVTArray;
9565 static ManagedStatic<sys::SmartMutex<true>> VTMutex;
9566 
9567 /// getValueTypeList - Return a pointer to the specified value type.
9568 ///
9569 const EVT *SDNode::getValueTypeList(EVT VT) {
9570   if (VT.isExtended()) {
9571     sys::SmartScopedLock<true> Lock(*VTMutex);
9572     return &(*EVTs->insert(VT).first);
9573   }
9574   assert(VT.getSimpleVT() < MVT::LAST_VALUETYPE && "Value type out of range!");
9575   return &SimpleVTArray->VTs[VT.getSimpleVT().SimpleTy];
9576 }
9577 
9578 /// hasNUsesOfValue - Return true if there are exactly NUSES uses of the
9579 /// indicated value.  This method ignores uses of other values defined by this
9580 /// operation.
9581 bool SDNode::hasNUsesOfValue(unsigned NUses, unsigned Value) const {
9582   assert(Value < getNumValues() && "Bad value!");
9583 
9584   // TODO: Only iterate over uses of a given value of the node
9585   for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) {
9586     if (UI.getUse().getResNo() == Value) {
9587       if (NUses == 0)
9588         return false;
9589       --NUses;
9590     }
9591   }
9592 
9593   // Found exactly the right number of uses?
9594   return NUses == 0;
9595 }
9596 
9597 /// hasAnyUseOfValue - Return true if there are any use of the indicated
9598 /// value. This method ignores uses of other values defined by this operation.
9599 bool SDNode::hasAnyUseOfValue(unsigned Value) const {
9600   assert(Value < getNumValues() && "Bad value!");
9601 
9602   for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI)
9603     if (UI.getUse().getResNo() == Value)
9604       return true;
9605 
9606   return false;
9607 }
9608 
9609 /// isOnlyUserOf - Return true if this node is the only use of N.
9610 bool SDNode::isOnlyUserOf(const SDNode *N) const {
9611   bool Seen = false;
9612   for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) {
9613     SDNode *User = *I;
9614     if (User == this)
9615       Seen = true;
9616     else
9617       return false;
9618   }
9619 
9620   return Seen;
9621 }
9622 
9623 /// Return true if the only users of N are contained in Nodes.
9624 bool SDNode::areOnlyUsersOf(ArrayRef<const SDNode *> Nodes, const SDNode *N) {
9625   bool Seen = false;
9626   for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) {
9627     SDNode *User = *I;
9628     if (llvm::is_contained(Nodes, User))
9629       Seen = true;
9630     else
9631       return false;
9632   }
9633 
9634   return Seen;
9635 }
9636 
9637 /// isOperand - Return true if this node is an operand of N.
9638 bool SDValue::isOperandOf(const SDNode *N) const {
9639   return is_contained(N->op_values(), *this);
9640 }
9641 
9642 bool SDNode::isOperandOf(const SDNode *N) const {
9643   return any_of(N->op_values(),
9644                 [this](SDValue Op) { return this == Op.getNode(); });
9645 }
9646 
9647 /// reachesChainWithoutSideEffects - Return true if this operand (which must
9648 /// be a chain) reaches the specified operand without crossing any
9649 /// side-effecting instructions on any chain path.  In practice, this looks
9650 /// through token factors and non-volatile loads.  In order to remain efficient,
9651 /// this only looks a couple of nodes in, it does not do an exhaustive search.
9652 ///
9653 /// Note that we only need to examine chains when we're searching for
9654 /// side-effects; SelectionDAG requires that all side-effects are represented
9655 /// by chains, even if another operand would force a specific ordering. This
9656 /// constraint is necessary to allow transformations like splitting loads.
9657 bool SDValue::reachesChainWithoutSideEffects(SDValue Dest,
9658                                              unsigned Depth) const {
9659   if (*this == Dest) return true;
9660 
9661   // Don't search too deeply, we just want to be able to see through
9662   // TokenFactor's etc.
9663   if (Depth == 0) return false;
9664 
9665   // If this is a token factor, all inputs to the TF happen in parallel.
9666   if (getOpcode() == ISD::TokenFactor) {
9667     // First, try a shallow search.
9668     if (is_contained((*this)->ops(), Dest)) {
9669       // We found the chain we want as an operand of this TokenFactor.
9670       // Essentially, we reach the chain without side-effects if we could
9671       // serialize the TokenFactor into a simple chain of operations with
9672       // Dest as the last operation. This is automatically true if the
9673       // chain has one use: there are no other ordering constraints.
9674       // If the chain has more than one use, we give up: some other
9675       // use of Dest might force a side-effect between Dest and the current
9676       // node.
9677       if (Dest.hasOneUse())
9678         return true;
9679     }
9680     // Next, try a deep search: check whether every operand of the TokenFactor
9681     // reaches Dest.
9682     return llvm::all_of((*this)->ops(), [=](SDValue Op) {
9683       return Op.reachesChainWithoutSideEffects(Dest, Depth - 1);
9684     });
9685   }
9686 
9687   // Loads don't have side effects, look through them.
9688   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(*this)) {
9689     if (Ld->isUnordered())
9690       return Ld->getChain().reachesChainWithoutSideEffects(Dest, Depth-1);
9691   }
9692   return false;
9693 }
9694 
9695 bool SDNode::hasPredecessor(const SDNode *N) const {
9696   SmallPtrSet<const SDNode *, 32> Visited;
9697   SmallVector<const SDNode *, 16> Worklist;
9698   Worklist.push_back(this);
9699   return hasPredecessorHelper(N, Visited, Worklist);
9700 }
9701 
9702 void SDNode::intersectFlagsWith(const SDNodeFlags Flags) {
9703   this->Flags.intersectWith(Flags);
9704 }
9705 
9706 SDValue
9707 SelectionDAG::matchBinOpReduction(SDNode *Extract, ISD::NodeType &BinOp,
9708                                   ArrayRef<ISD::NodeType> CandidateBinOps,
9709                                   bool AllowPartials) {
9710   // The pattern must end in an extract from index 0.
9711   if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
9712       !isNullConstant(Extract->getOperand(1)))
9713     return SDValue();
9714 
9715   // Match against one of the candidate binary ops.
9716   SDValue Op = Extract->getOperand(0);
9717   if (llvm::none_of(CandidateBinOps, [Op](ISD::NodeType BinOp) {
9718         return Op.getOpcode() == unsigned(BinOp);
9719       }))
9720     return SDValue();
9721 
9722   // Floating-point reductions may require relaxed constraints on the final step
9723   // of the reduction because they may reorder intermediate operations.
9724   unsigned CandidateBinOp = Op.getOpcode();
9725   if (Op.getValueType().isFloatingPoint()) {
9726     SDNodeFlags Flags = Op->getFlags();
9727     switch (CandidateBinOp) {
9728     case ISD::FADD:
9729       if (!Flags.hasNoSignedZeros() || !Flags.hasAllowReassociation())
9730         return SDValue();
9731       break;
9732     default:
9733       llvm_unreachable("Unhandled FP opcode for binop reduction");
9734     }
9735   }
9736 
9737   // Matching failed - attempt to see if we did enough stages that a partial
9738   // reduction from a subvector is possible.
9739   auto PartialReduction = [&](SDValue Op, unsigned NumSubElts) {
9740     if (!AllowPartials || !Op)
9741       return SDValue();
9742     EVT OpVT = Op.getValueType();
9743     EVT OpSVT = OpVT.getScalarType();
9744     EVT SubVT = EVT::getVectorVT(*getContext(), OpSVT, NumSubElts);
9745     if (!TLI->isExtractSubvectorCheap(SubVT, OpVT, 0))
9746       return SDValue();
9747     BinOp = (ISD::NodeType)CandidateBinOp;
9748     return getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(Op), SubVT, Op,
9749                    getVectorIdxConstant(0, SDLoc(Op)));
9750   };
9751 
9752   // At each stage, we're looking for something that looks like:
9753   // %s = shufflevector <8 x i32> %op, <8 x i32> undef,
9754   //                    <8 x i32> <i32 2, i32 3, i32 undef, i32 undef,
9755   //                               i32 undef, i32 undef, i32 undef, i32 undef>
9756   // %a = binop <8 x i32> %op, %s
9757   // Where the mask changes according to the stage. E.g. for a 3-stage pyramid,
9758   // we expect something like:
9759   // <4,5,6,7,u,u,u,u>
9760   // <2,3,u,u,u,u,u,u>
9761   // <1,u,u,u,u,u,u,u>
9762   // While a partial reduction match would be:
9763   // <2,3,u,u,u,u,u,u>
9764   // <1,u,u,u,u,u,u,u>
9765   unsigned Stages = Log2_32(Op.getValueType().getVectorNumElements());
9766   SDValue PrevOp;
9767   for (unsigned i = 0; i < Stages; ++i) {
9768     unsigned MaskEnd = (1 << i);
9769 
9770     if (Op.getOpcode() != CandidateBinOp)
9771       return PartialReduction(PrevOp, MaskEnd);
9772 
9773     SDValue Op0 = Op.getOperand(0);
9774     SDValue Op1 = Op.getOperand(1);
9775 
9776     ShuffleVectorSDNode *Shuffle = dyn_cast<ShuffleVectorSDNode>(Op0);
9777     if (Shuffle) {
9778       Op = Op1;
9779     } else {
9780       Shuffle = dyn_cast<ShuffleVectorSDNode>(Op1);
9781       Op = Op0;
9782     }
9783 
9784     // The first operand of the shuffle should be the same as the other operand
9785     // of the binop.
9786     if (!Shuffle || Shuffle->getOperand(0) != Op)
9787       return PartialReduction(PrevOp, MaskEnd);
9788 
9789     // Verify the shuffle has the expected (at this stage of the pyramid) mask.
9790     for (int Index = 0; Index < (int)MaskEnd; ++Index)
9791       if (Shuffle->getMaskElt(Index) != (int)(MaskEnd + Index))
9792         return PartialReduction(PrevOp, MaskEnd);
9793 
9794     PrevOp = Op;
9795   }
9796 
9797   // Handle subvector reductions, which tend to appear after the shuffle
9798   // reduction stages.
9799   while (Op.getOpcode() == CandidateBinOp) {
9800     unsigned NumElts = Op.getValueType().getVectorNumElements();
9801     SDValue Op0 = Op.getOperand(0);
9802     SDValue Op1 = Op.getOperand(1);
9803     if (Op0.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
9804         Op1.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
9805         Op0.getOperand(0) != Op1.getOperand(0))
9806       break;
9807     SDValue Src = Op0.getOperand(0);
9808     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
9809     if (NumSrcElts != (2 * NumElts))
9810       break;
9811     if (!(Op0.getConstantOperandAPInt(1) == 0 &&
9812           Op1.getConstantOperandAPInt(1) == NumElts) &&
9813         !(Op1.getConstantOperandAPInt(1) == 0 &&
9814           Op0.getConstantOperandAPInt(1) == NumElts))
9815       break;
9816     Op = Src;
9817   }
9818 
9819   BinOp = (ISD::NodeType)CandidateBinOp;
9820   return Op;
9821 }
9822 
9823 SDValue SelectionDAG::UnrollVectorOp(SDNode *N, unsigned ResNE) {
9824   assert(N->getNumValues() == 1 &&
9825          "Can't unroll a vector with multiple results!");
9826 
9827   EVT VT = N->getValueType(0);
9828   unsigned NE = VT.getVectorNumElements();
9829   EVT EltVT = VT.getVectorElementType();
9830   SDLoc dl(N);
9831 
9832   SmallVector<SDValue, 8> Scalars;
9833   SmallVector<SDValue, 4> Operands(N->getNumOperands());
9834 
9835   // If ResNE is 0, fully unroll the vector op.
9836   if (ResNE == 0)
9837     ResNE = NE;
9838   else if (NE > ResNE)
9839     NE = ResNE;
9840 
9841   unsigned i;
9842   for (i= 0; i != NE; ++i) {
9843     for (unsigned j = 0, e = N->getNumOperands(); j != e; ++j) {
9844       SDValue Operand = N->getOperand(j);
9845       EVT OperandVT = Operand.getValueType();
9846       if (OperandVT.isVector()) {
9847         // A vector operand; extract a single element.
9848         EVT OperandEltVT = OperandVT.getVectorElementType();
9849         Operands[j] = getNode(ISD::EXTRACT_VECTOR_ELT, dl, OperandEltVT,
9850                               Operand, getVectorIdxConstant(i, dl));
9851       } else {
9852         // A scalar operand; just use it as is.
9853         Operands[j] = Operand;
9854       }
9855     }
9856 
9857     switch (N->getOpcode()) {
9858     default: {
9859       Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands,
9860                                 N->getFlags()));
9861       break;
9862     }
9863     case ISD::VSELECT:
9864       Scalars.push_back(getNode(ISD::SELECT, dl, EltVT, Operands));
9865       break;
9866     case ISD::SHL:
9867     case ISD::SRA:
9868     case ISD::SRL:
9869     case ISD::ROTL:
9870     case ISD::ROTR:
9871       Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands[0],
9872                                getShiftAmountOperand(Operands[0].getValueType(),
9873                                                      Operands[1])));
9874       break;
9875     case ISD::SIGN_EXTEND_INREG: {
9876       EVT ExtVT = cast<VTSDNode>(Operands[1])->getVT().getVectorElementType();
9877       Scalars.push_back(getNode(N->getOpcode(), dl, EltVT,
9878                                 Operands[0],
9879                                 getValueType(ExtVT)));
9880     }
9881     }
9882   }
9883 
9884   for (; i < ResNE; ++i)
9885     Scalars.push_back(getUNDEF(EltVT));
9886 
9887   EVT VecVT = EVT::getVectorVT(*getContext(), EltVT, ResNE);
9888   return getBuildVector(VecVT, dl, Scalars);
9889 }
9890 
9891 std::pair<SDValue, SDValue> SelectionDAG::UnrollVectorOverflowOp(
9892     SDNode *N, unsigned ResNE) {
9893   unsigned Opcode = N->getOpcode();
9894   assert((Opcode == ISD::UADDO || Opcode == ISD::SADDO ||
9895           Opcode == ISD::USUBO || Opcode == ISD::SSUBO ||
9896           Opcode == ISD::UMULO || Opcode == ISD::SMULO) &&
9897          "Expected an overflow opcode");
9898 
9899   EVT ResVT = N->getValueType(0);
9900   EVT OvVT = N->getValueType(1);
9901   EVT ResEltVT = ResVT.getVectorElementType();
9902   EVT OvEltVT = OvVT.getVectorElementType();
9903   SDLoc dl(N);
9904 
9905   // If ResNE is 0, fully unroll the vector op.
9906   unsigned NE = ResVT.getVectorNumElements();
9907   if (ResNE == 0)
9908     ResNE = NE;
9909   else if (NE > ResNE)
9910     NE = ResNE;
9911 
9912   SmallVector<SDValue, 8> LHSScalars;
9913   SmallVector<SDValue, 8> RHSScalars;
9914   ExtractVectorElements(N->getOperand(0), LHSScalars, 0, NE);
9915   ExtractVectorElements(N->getOperand(1), RHSScalars, 0, NE);
9916 
9917   EVT SVT = TLI->getSetCCResultType(getDataLayout(), *getContext(), ResEltVT);
9918   SDVTList VTs = getVTList(ResEltVT, SVT);
9919   SmallVector<SDValue, 8> ResScalars;
9920   SmallVector<SDValue, 8> OvScalars;
9921   for (unsigned i = 0; i < NE; ++i) {
9922     SDValue Res = getNode(Opcode, dl, VTs, LHSScalars[i], RHSScalars[i]);
9923     SDValue Ov =
9924         getSelect(dl, OvEltVT, Res.getValue(1),
9925                   getBoolConstant(true, dl, OvEltVT, ResVT),
9926                   getConstant(0, dl, OvEltVT));
9927 
9928     ResScalars.push_back(Res);
9929     OvScalars.push_back(Ov);
9930   }
9931 
9932   ResScalars.append(ResNE - NE, getUNDEF(ResEltVT));
9933   OvScalars.append(ResNE - NE, getUNDEF(OvEltVT));
9934 
9935   EVT NewResVT = EVT::getVectorVT(*getContext(), ResEltVT, ResNE);
9936   EVT NewOvVT = EVT::getVectorVT(*getContext(), OvEltVT, ResNE);
9937   return std::make_pair(getBuildVector(NewResVT, dl, ResScalars),
9938                         getBuildVector(NewOvVT, dl, OvScalars));
9939 }
9940 
9941 bool SelectionDAG::areNonVolatileConsecutiveLoads(LoadSDNode *LD,
9942                                                   LoadSDNode *Base,
9943                                                   unsigned Bytes,
9944                                                   int Dist) const {
9945   if (LD->isVolatile() || Base->isVolatile())
9946     return false;
9947   // TODO: probably too restrictive for atomics, revisit
9948   if (!LD->isSimple())
9949     return false;
9950   if (LD->isIndexed() || Base->isIndexed())
9951     return false;
9952   if (LD->getChain() != Base->getChain())
9953     return false;
9954   EVT VT = LD->getValueType(0);
9955   if (VT.getSizeInBits() / 8 != Bytes)
9956     return false;
9957 
9958   auto BaseLocDecomp = BaseIndexOffset::match(Base, *this);
9959   auto LocDecomp = BaseIndexOffset::match(LD, *this);
9960 
9961   int64_t Offset = 0;
9962   if (BaseLocDecomp.equalBaseIndex(LocDecomp, *this, Offset))
9963     return (Dist * Bytes == Offset);
9964   return false;
9965 }
9966 
9967 /// InferPtrAlignment - Infer alignment of a load / store address. Return None
9968 /// if it cannot be inferred.
9969 MaybeAlign SelectionDAG::InferPtrAlign(SDValue Ptr) const {
9970   // If this is a GlobalAddress + cst, return the alignment.
9971   const GlobalValue *GV = nullptr;
9972   int64_t GVOffset = 0;
9973   if (TLI->isGAPlusOffset(Ptr.getNode(), GV, GVOffset)) {
9974     unsigned PtrWidth = getDataLayout().getPointerTypeSizeInBits(GV->getType());
9975     KnownBits Known(PtrWidth);
9976     llvm::computeKnownBits(GV, Known, getDataLayout());
9977     unsigned AlignBits = Known.countMinTrailingZeros();
9978     if (AlignBits)
9979       return commonAlignment(Align(1ull << std::min(31U, AlignBits)), GVOffset);
9980   }
9981 
9982   // If this is a direct reference to a stack slot, use information about the
9983   // stack slot's alignment.
9984   int FrameIdx = INT_MIN;
9985   int64_t FrameOffset = 0;
9986   if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr)) {
9987     FrameIdx = FI->getIndex();
9988   } else if (isBaseWithConstantOffset(Ptr) &&
9989              isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
9990     // Handle FI+Cst
9991     FrameIdx = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
9992     FrameOffset = Ptr.getConstantOperandVal(1);
9993   }
9994 
9995   if (FrameIdx != INT_MIN) {
9996     const MachineFrameInfo &MFI = getMachineFunction().getFrameInfo();
9997     return commonAlignment(MFI.getObjectAlign(FrameIdx), FrameOffset);
9998   }
9999 
10000   return None;
10001 }
10002 
10003 /// GetSplitDestVTs - Compute the VTs needed for the low/hi parts of a type
10004 /// which is split (or expanded) into two not necessarily identical pieces.
10005 std::pair<EVT, EVT> SelectionDAG::GetSplitDestVTs(const EVT &VT) const {
10006   // Currently all types are split in half.
10007   EVT LoVT, HiVT;
10008   if (!VT.isVector())
10009     LoVT = HiVT = TLI->getTypeToTransformTo(*getContext(), VT);
10010   else
10011     LoVT = HiVT = VT.getHalfNumVectorElementsVT(*getContext());
10012 
10013   return std::make_pair(LoVT, HiVT);
10014 }
10015 
10016 /// GetDependentSplitDestVTs - Compute the VTs needed for the low/hi parts of a
10017 /// type, dependent on an enveloping VT that has been split into two identical
10018 /// pieces. Sets the HiIsEmpty flag when hi type has zero storage size.
10019 std::pair<EVT, EVT>
10020 SelectionDAG::GetDependentSplitDestVTs(const EVT &VT, const EVT &EnvVT,
10021                                        bool *HiIsEmpty) const {
10022   EVT EltTp = VT.getVectorElementType();
10023   // Examples:
10024   //   custom VL=8  with enveloping VL=8/8 yields 8/0 (hi empty)
10025   //   custom VL=9  with enveloping VL=8/8 yields 8/1
10026   //   custom VL=10 with enveloping VL=8/8 yields 8/2
10027   //   etc.
10028   ElementCount VTNumElts = VT.getVectorElementCount();
10029   ElementCount EnvNumElts = EnvVT.getVectorElementCount();
10030   assert(VTNumElts.isScalable() == EnvNumElts.isScalable() &&
10031          "Mixing fixed width and scalable vectors when enveloping a type");
10032   EVT LoVT, HiVT;
10033   if (VTNumElts.getKnownMinValue() > EnvNumElts.getKnownMinValue()) {
10034     LoVT = EnvVT;
10035     HiVT = EVT::getVectorVT(*getContext(), EltTp, VTNumElts - EnvNumElts);
10036     *HiIsEmpty = false;
10037   } else {
10038     // Flag that hi type has zero storage size, but return split envelop type
10039     // (this would be easier if vector types with zero elements were allowed).
10040     LoVT = EVT::getVectorVT(*getContext(), EltTp, VTNumElts);
10041     HiVT = EnvVT;
10042     *HiIsEmpty = true;
10043   }
10044   return std::make_pair(LoVT, HiVT);
10045 }
10046 
10047 /// SplitVector - Split the vector with EXTRACT_SUBVECTOR and return the
10048 /// low/high part.
10049 std::pair<SDValue, SDValue>
10050 SelectionDAG::SplitVector(const SDValue &N, const SDLoc &DL, const EVT &LoVT,
10051                           const EVT &HiVT) {
10052   assert(LoVT.isScalableVector() == HiVT.isScalableVector() &&
10053          LoVT.isScalableVector() == N.getValueType().isScalableVector() &&
10054          "Splitting vector with an invalid mixture of fixed and scalable "
10055          "vector types");
10056   assert(LoVT.getVectorMinNumElements() + HiVT.getVectorMinNumElements() <=
10057              N.getValueType().getVectorMinNumElements() &&
10058          "More vector elements requested than available!");
10059   SDValue Lo, Hi;
10060   Lo =
10061       getNode(ISD::EXTRACT_SUBVECTOR, DL, LoVT, N, getVectorIdxConstant(0, DL));
10062   // For scalable vectors it is safe to use LoVT.getVectorMinNumElements()
10063   // (rather than having to use ElementCount), because EXTRACT_SUBVECTOR scales
10064   // IDX with the runtime scaling factor of the result vector type. For
10065   // fixed-width result vectors, that runtime scaling factor is 1.
10066   Hi = getNode(ISD::EXTRACT_SUBVECTOR, DL, HiVT, N,
10067                getVectorIdxConstant(LoVT.getVectorMinNumElements(), DL));
10068   return std::make_pair(Lo, Hi);
10069 }
10070 
10071 /// Widen the vector up to the next power of two using INSERT_SUBVECTOR.
10072 SDValue SelectionDAG::WidenVector(const SDValue &N, const SDLoc &DL) {
10073   EVT VT = N.getValueType();
10074   EVT WideVT = EVT::getVectorVT(*getContext(), VT.getVectorElementType(),
10075                                 NextPowerOf2(VT.getVectorNumElements()));
10076   return getNode(ISD::INSERT_SUBVECTOR, DL, WideVT, getUNDEF(WideVT), N,
10077                  getVectorIdxConstant(0, DL));
10078 }
10079 
10080 void SelectionDAG::ExtractVectorElements(SDValue Op,
10081                                          SmallVectorImpl<SDValue> &Args,
10082                                          unsigned Start, unsigned Count,
10083                                          EVT EltVT) {
10084   EVT VT = Op.getValueType();
10085   if (Count == 0)
10086     Count = VT.getVectorNumElements();
10087   if (EltVT == EVT())
10088     EltVT = VT.getVectorElementType();
10089   SDLoc SL(Op);
10090   for (unsigned i = Start, e = Start + Count; i != e; ++i) {
10091     Args.push_back(getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Op,
10092                            getVectorIdxConstant(i, SL)));
10093   }
10094 }
10095 
10096 // getAddressSpace - Return the address space this GlobalAddress belongs to.
10097 unsigned GlobalAddressSDNode::getAddressSpace() const {
10098   return getGlobal()->getType()->getAddressSpace();
10099 }
10100 
10101 Type *ConstantPoolSDNode::getType() const {
10102   if (isMachineConstantPoolEntry())
10103     return Val.MachineCPVal->getType();
10104   return Val.ConstVal->getType();
10105 }
10106 
10107 bool BuildVectorSDNode::isConstantSplat(APInt &SplatValue, APInt &SplatUndef,
10108                                         unsigned &SplatBitSize,
10109                                         bool &HasAnyUndefs,
10110                                         unsigned MinSplatBits,
10111                                         bool IsBigEndian) const {
10112   EVT VT = getValueType(0);
10113   assert(VT.isVector() && "Expected a vector type");
10114   unsigned VecWidth = VT.getSizeInBits();
10115   if (MinSplatBits > VecWidth)
10116     return false;
10117 
10118   // FIXME: The widths are based on this node's type, but build vectors can
10119   // truncate their operands.
10120   SplatValue = APInt(VecWidth, 0);
10121   SplatUndef = APInt(VecWidth, 0);
10122 
10123   // Get the bits. Bits with undefined values (when the corresponding element
10124   // of the vector is an ISD::UNDEF value) are set in SplatUndef and cleared
10125   // in SplatValue. If any of the values are not constant, give up and return
10126   // false.
10127   unsigned int NumOps = getNumOperands();
10128   assert(NumOps > 0 && "isConstantSplat has 0-size build vector");
10129   unsigned EltWidth = VT.getScalarSizeInBits();
10130 
10131   for (unsigned j = 0; j < NumOps; ++j) {
10132     unsigned i = IsBigEndian ? NumOps - 1 - j : j;
10133     SDValue OpVal = getOperand(i);
10134     unsigned BitPos = j * EltWidth;
10135 
10136     if (OpVal.isUndef())
10137       SplatUndef.setBits(BitPos, BitPos + EltWidth);
10138     else if (auto *CN = dyn_cast<ConstantSDNode>(OpVal))
10139       SplatValue.insertBits(CN->getAPIntValue().zextOrTrunc(EltWidth), BitPos);
10140     else if (auto *CN = dyn_cast<ConstantFPSDNode>(OpVal))
10141       SplatValue.insertBits(CN->getValueAPF().bitcastToAPInt(), BitPos);
10142     else
10143       return false;
10144   }
10145 
10146   // The build_vector is all constants or undefs. Find the smallest element
10147   // size that splats the vector.
10148   HasAnyUndefs = (SplatUndef != 0);
10149 
10150   // FIXME: This does not work for vectors with elements less than 8 bits.
10151   while (VecWidth > 8) {
10152     unsigned HalfSize = VecWidth / 2;
10153     APInt HighValue = SplatValue.lshr(HalfSize).trunc(HalfSize);
10154     APInt LowValue = SplatValue.trunc(HalfSize);
10155     APInt HighUndef = SplatUndef.lshr(HalfSize).trunc(HalfSize);
10156     APInt LowUndef = SplatUndef.trunc(HalfSize);
10157 
10158     // If the two halves do not match (ignoring undef bits), stop here.
10159     if ((HighValue & ~LowUndef) != (LowValue & ~HighUndef) ||
10160         MinSplatBits > HalfSize)
10161       break;
10162 
10163     SplatValue = HighValue | LowValue;
10164     SplatUndef = HighUndef & LowUndef;
10165 
10166     VecWidth = HalfSize;
10167   }
10168 
10169   SplatBitSize = VecWidth;
10170   return true;
10171 }
10172 
10173 SDValue BuildVectorSDNode::getSplatValue(const APInt &DemandedElts,
10174                                          BitVector *UndefElements) const {
10175   unsigned NumOps = getNumOperands();
10176   if (UndefElements) {
10177     UndefElements->clear();
10178     UndefElements->resize(NumOps);
10179   }
10180   assert(NumOps == DemandedElts.getBitWidth() && "Unexpected vector size");
10181   if (!DemandedElts)
10182     return SDValue();
10183   SDValue Splatted;
10184   for (unsigned i = 0; i != NumOps; ++i) {
10185     if (!DemandedElts[i])
10186       continue;
10187     SDValue Op = getOperand(i);
10188     if (Op.isUndef()) {
10189       if (UndefElements)
10190         (*UndefElements)[i] = true;
10191     } else if (!Splatted) {
10192       Splatted = Op;
10193     } else if (Splatted != Op) {
10194       return SDValue();
10195     }
10196   }
10197 
10198   if (!Splatted) {
10199     unsigned FirstDemandedIdx = DemandedElts.countTrailingZeros();
10200     assert(getOperand(FirstDemandedIdx).isUndef() &&
10201            "Can only have a splat without a constant for all undefs.");
10202     return getOperand(FirstDemandedIdx);
10203   }
10204 
10205   return Splatted;
10206 }
10207 
10208 SDValue BuildVectorSDNode::getSplatValue(BitVector *UndefElements) const {
10209   APInt DemandedElts = APInt::getAllOnesValue(getNumOperands());
10210   return getSplatValue(DemandedElts, UndefElements);
10211 }
10212 
10213 bool BuildVectorSDNode::getRepeatedSequence(const APInt &DemandedElts,
10214                                             SmallVectorImpl<SDValue> &Sequence,
10215                                             BitVector *UndefElements) const {
10216   unsigned NumOps = getNumOperands();
10217   Sequence.clear();
10218   if (UndefElements) {
10219     UndefElements->clear();
10220     UndefElements->resize(NumOps);
10221   }
10222   assert(NumOps == DemandedElts.getBitWidth() && "Unexpected vector size");
10223   if (!DemandedElts || NumOps < 2 || !isPowerOf2_32(NumOps))
10224     return false;
10225 
10226   // Set the undefs even if we don't find a sequence (like getSplatValue).
10227   if (UndefElements)
10228     for (unsigned I = 0; I != NumOps; ++I)
10229       if (DemandedElts[I] && getOperand(I).isUndef())
10230         (*UndefElements)[I] = true;
10231 
10232   // Iteratively widen the sequence length looking for repetitions.
10233   for (unsigned SeqLen = 1; SeqLen < NumOps; SeqLen *= 2) {
10234     Sequence.append(SeqLen, SDValue());
10235     for (unsigned I = 0; I != NumOps; ++I) {
10236       if (!DemandedElts[I])
10237         continue;
10238       SDValue &SeqOp = Sequence[I % SeqLen];
10239       SDValue Op = getOperand(I);
10240       if (Op.isUndef()) {
10241         if (!SeqOp)
10242           SeqOp = Op;
10243         continue;
10244       }
10245       if (SeqOp && !SeqOp.isUndef() && SeqOp != Op) {
10246         Sequence.clear();
10247         break;
10248       }
10249       SeqOp = Op;
10250     }
10251     if (!Sequence.empty())
10252       return true;
10253   }
10254 
10255   assert(Sequence.empty() && "Failed to empty non-repeating sequence pattern");
10256   return false;
10257 }
10258 
10259 bool BuildVectorSDNode::getRepeatedSequence(SmallVectorImpl<SDValue> &Sequence,
10260                                             BitVector *UndefElements) const {
10261   APInt DemandedElts = APInt::getAllOnesValue(getNumOperands());
10262   return getRepeatedSequence(DemandedElts, Sequence, UndefElements);
10263 }
10264 
10265 ConstantSDNode *
10266 BuildVectorSDNode::getConstantSplatNode(const APInt &DemandedElts,
10267                                         BitVector *UndefElements) const {
10268   return dyn_cast_or_null<ConstantSDNode>(
10269       getSplatValue(DemandedElts, UndefElements));
10270 }
10271 
10272 ConstantSDNode *
10273 BuildVectorSDNode::getConstantSplatNode(BitVector *UndefElements) const {
10274   return dyn_cast_or_null<ConstantSDNode>(getSplatValue(UndefElements));
10275 }
10276 
10277 ConstantFPSDNode *
10278 BuildVectorSDNode::getConstantFPSplatNode(const APInt &DemandedElts,
10279                                           BitVector *UndefElements) const {
10280   return dyn_cast_or_null<ConstantFPSDNode>(
10281       getSplatValue(DemandedElts, UndefElements));
10282 }
10283 
10284 ConstantFPSDNode *
10285 BuildVectorSDNode::getConstantFPSplatNode(BitVector *UndefElements) const {
10286   return dyn_cast_or_null<ConstantFPSDNode>(getSplatValue(UndefElements));
10287 }
10288 
10289 int32_t
10290 BuildVectorSDNode::getConstantFPSplatPow2ToLog2Int(BitVector *UndefElements,
10291                                                    uint32_t BitWidth) const {
10292   if (ConstantFPSDNode *CN =
10293           dyn_cast_or_null<ConstantFPSDNode>(getSplatValue(UndefElements))) {
10294     bool IsExact;
10295     APSInt IntVal(BitWidth);
10296     const APFloat &APF = CN->getValueAPF();
10297     if (APF.convertToInteger(IntVal, APFloat::rmTowardZero, &IsExact) !=
10298             APFloat::opOK ||
10299         !IsExact)
10300       return -1;
10301 
10302     return IntVal.exactLogBase2();
10303   }
10304   return -1;
10305 }
10306 
10307 bool BuildVectorSDNode::isConstant() const {
10308   for (const SDValue &Op : op_values()) {
10309     unsigned Opc = Op.getOpcode();
10310     if (Opc != ISD::UNDEF && Opc != ISD::Constant && Opc != ISD::ConstantFP)
10311       return false;
10312   }
10313   return true;
10314 }
10315 
10316 bool ShuffleVectorSDNode::isSplatMask(const int *Mask, EVT VT) {
10317   // Find the first non-undef value in the shuffle mask.
10318   unsigned i, e;
10319   for (i = 0, e = VT.getVectorNumElements(); i != e && Mask[i] < 0; ++i)
10320     /* search */;
10321 
10322   // If all elements are undefined, this shuffle can be considered a splat
10323   // (although it should eventually get simplified away completely).
10324   if (i == e)
10325     return true;
10326 
10327   // Make sure all remaining elements are either undef or the same as the first
10328   // non-undef value.
10329   for (int Idx = Mask[i]; i != e; ++i)
10330     if (Mask[i] >= 0 && Mask[i] != Idx)
10331       return false;
10332   return true;
10333 }
10334 
10335 // Returns the SDNode if it is a constant integer BuildVector
10336 // or constant integer.
10337 SDNode *SelectionDAG::isConstantIntBuildVectorOrConstantInt(SDValue N) const {
10338   if (isa<ConstantSDNode>(N))
10339     return N.getNode();
10340   if (ISD::isBuildVectorOfConstantSDNodes(N.getNode()))
10341     return N.getNode();
10342   // Treat a GlobalAddress supporting constant offset folding as a
10343   // constant integer.
10344   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N))
10345     if (GA->getOpcode() == ISD::GlobalAddress &&
10346         TLI->isOffsetFoldingLegal(GA))
10347       return GA;
10348   if ((N.getOpcode() == ISD::SPLAT_VECTOR) &&
10349       isa<ConstantSDNode>(N.getOperand(0)))
10350     return N.getNode();
10351   return nullptr;
10352 }
10353 
10354 // Returns the SDNode if it is a constant float BuildVector
10355 // or constant float.
10356 SDNode *SelectionDAG::isConstantFPBuildVectorOrConstantFP(SDValue N) const {
10357   if (isa<ConstantFPSDNode>(N))
10358     return N.getNode();
10359 
10360   if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode()))
10361     return N.getNode();
10362 
10363   return nullptr;
10364 }
10365 
10366 void SelectionDAG::createOperands(SDNode *Node, ArrayRef<SDValue> Vals) {
10367   assert(!Node->OperandList && "Node already has operands");
10368   assert(SDNode::getMaxNumOperands() >= Vals.size() &&
10369          "too many operands to fit into SDNode");
10370   SDUse *Ops = OperandRecycler.allocate(
10371       ArrayRecycler<SDUse>::Capacity::get(Vals.size()), OperandAllocator);
10372 
10373   bool IsDivergent = false;
10374   for (unsigned I = 0; I != Vals.size(); ++I) {
10375     Ops[I].setUser(Node);
10376     Ops[I].setInitial(Vals[I]);
10377     if (Ops[I].Val.getValueType() != MVT::Other) // Skip Chain. It does not carry divergence.
10378       IsDivergent |= Ops[I].getNode()->isDivergent();
10379   }
10380   Node->NumOperands = Vals.size();
10381   Node->OperandList = Ops;
10382   if (!TLI->isSDNodeAlwaysUniform(Node)) {
10383     IsDivergent |= TLI->isSDNodeSourceOfDivergence(Node, FLI, DA);
10384     Node->SDNodeBits.IsDivergent = IsDivergent;
10385   }
10386   checkForCycles(Node);
10387 }
10388 
10389 SDValue SelectionDAG::getTokenFactor(const SDLoc &DL,
10390                                      SmallVectorImpl<SDValue> &Vals) {
10391   size_t Limit = SDNode::getMaxNumOperands();
10392   while (Vals.size() > Limit) {
10393     unsigned SliceIdx = Vals.size() - Limit;
10394     auto ExtractedTFs = ArrayRef<SDValue>(Vals).slice(SliceIdx, Limit);
10395     SDValue NewTF = getNode(ISD::TokenFactor, DL, MVT::Other, ExtractedTFs);
10396     Vals.erase(Vals.begin() + SliceIdx, Vals.end());
10397     Vals.emplace_back(NewTF);
10398   }
10399   return getNode(ISD::TokenFactor, DL, MVT::Other, Vals);
10400 }
10401 
10402 SDValue SelectionDAG::getNeutralElement(unsigned Opcode, const SDLoc &DL,
10403                                         EVT VT, SDNodeFlags Flags) {
10404   switch (Opcode) {
10405   default:
10406     return SDValue();
10407   case ISD::ADD:
10408   case ISD::OR:
10409   case ISD::XOR:
10410   case ISD::UMAX:
10411     return getConstant(0, DL, VT);
10412   case ISD::MUL:
10413     return getConstant(1, DL, VT);
10414   case ISD::AND:
10415   case ISD::UMIN:
10416     return getAllOnesConstant(DL, VT);
10417   case ISD::SMAX:
10418     return getConstant(APInt::getSignedMinValue(VT.getSizeInBits()), DL, VT);
10419   case ISD::SMIN:
10420     return getConstant(APInt::getSignedMaxValue(VT.getSizeInBits()), DL, VT);
10421   case ISD::FADD:
10422     return getConstantFP(-0.0, DL, VT);
10423   case ISD::FMUL:
10424     return getConstantFP(1.0, DL, VT);
10425   case ISD::FMINNUM:
10426   case ISD::FMAXNUM: {
10427     // Neutral element for fminnum is NaN, Inf or FLT_MAX, depending on FMF.
10428     const fltSemantics &Semantics = EVTToAPFloatSemantics(VT);
10429     APFloat NeutralAF = !Flags.hasNoNaNs() ? APFloat::getQNaN(Semantics) :
10430                         !Flags.hasNoInfs() ? APFloat::getInf(Semantics) :
10431                         APFloat::getLargest(Semantics);
10432     if (Opcode == ISD::FMAXNUM)
10433       NeutralAF.changeSign();
10434 
10435     return getConstantFP(NeutralAF, DL, VT);
10436   }
10437   }
10438 }
10439 
10440 #ifndef NDEBUG
10441 static void checkForCyclesHelper(const SDNode *N,
10442                                  SmallPtrSetImpl<const SDNode*> &Visited,
10443                                  SmallPtrSetImpl<const SDNode*> &Checked,
10444                                  const llvm::SelectionDAG *DAG) {
10445   // If this node has already been checked, don't check it again.
10446   if (Checked.count(N))
10447     return;
10448 
10449   // If a node has already been visited on this depth-first walk, reject it as
10450   // a cycle.
10451   if (!Visited.insert(N).second) {
10452     errs() << "Detected cycle in SelectionDAG\n";
10453     dbgs() << "Offending node:\n";
10454     N->dumprFull(DAG); dbgs() << "\n";
10455     abort();
10456   }
10457 
10458   for (const SDValue &Op : N->op_values())
10459     checkForCyclesHelper(Op.getNode(), Visited, Checked, DAG);
10460 
10461   Checked.insert(N);
10462   Visited.erase(N);
10463 }
10464 #endif
10465 
10466 void llvm::checkForCycles(const llvm::SDNode *N,
10467                           const llvm::SelectionDAG *DAG,
10468                           bool force) {
10469 #ifndef NDEBUG
10470   bool check = force;
10471 #ifdef EXPENSIVE_CHECKS
10472   check = true;
10473 #endif  // EXPENSIVE_CHECKS
10474   if (check) {
10475     assert(N && "Checking nonexistent SDNode");
10476     SmallPtrSet<const SDNode*, 32> visited;
10477     SmallPtrSet<const SDNode*, 32> checked;
10478     checkForCyclesHelper(N, visited, checked, DAG);
10479   }
10480 #endif  // !NDEBUG
10481 }
10482 
10483 void llvm::checkForCycles(const llvm::SelectionDAG *DAG, bool force) {
10484   checkForCycles(DAG->getRoot().getNode(), DAG, force);
10485 }
10486