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.extractBits(ViaEltSizeInBits, i * 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.extractBits(ViaEltSizeInBits, i * ViaEltSizeInBits), DL,
1418           ViaEltVT, isT, isO));
1419 
1420     // EltParts is currently in little endian order. If we actually want
1421     // big-endian order then reverse it now.
1422     if (getDataLayout().isBigEndian())
1423       std::reverse(EltParts.begin(), EltParts.end());
1424 
1425     // The elements must be reversed when the element order is different
1426     // to the endianness of the elements (because the BITCAST is itself a
1427     // vector shuffle in this situation). However, we do not need any code to
1428     // perform this reversal because getConstant() is producing a vector
1429     // splat.
1430     // This situation occurs in MIPS MSA.
1431 
1432     SmallVector<SDValue, 8> Ops;
1433     for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
1434       llvm::append_range(Ops, EltParts);
1435 
1436     SDValue V =
1437         getNode(ISD::BITCAST, DL, VT, getBuildVector(ViaVecVT, DL, Ops));
1438     return V;
1439   }
1440 
1441   assert(Elt->getBitWidth() == EltVT.getSizeInBits() &&
1442          "APInt size does not match type size!");
1443   unsigned Opc = isT ? ISD::TargetConstant : ISD::Constant;
1444   FoldingSetNodeID ID;
1445   AddNodeIDNode(ID, Opc, getVTList(EltVT), None);
1446   ID.AddPointer(Elt);
1447   ID.AddBoolean(isO);
1448   void *IP = nullptr;
1449   SDNode *N = nullptr;
1450   if ((N = FindNodeOrInsertPos(ID, DL, IP)))
1451     if (!VT.isVector())
1452       return SDValue(N, 0);
1453 
1454   if (!N) {
1455     N = newSDNode<ConstantSDNode>(isT, isO, Elt, EltVT);
1456     CSEMap.InsertNode(N, IP);
1457     InsertNode(N);
1458     NewSDValueDbgMsg(SDValue(N, 0), "Creating constant: ", this);
1459   }
1460 
1461   SDValue Result(N, 0);
1462   if (VT.isScalableVector())
1463     Result = getSplatVector(VT, DL, Result);
1464   else if (VT.isVector())
1465     Result = getSplatBuildVector(VT, DL, Result);
1466 
1467   return Result;
1468 }
1469 
1470 SDValue SelectionDAG::getIntPtrConstant(uint64_t Val, const SDLoc &DL,
1471                                         bool isTarget) {
1472   return getConstant(Val, DL, TLI->getPointerTy(getDataLayout()), isTarget);
1473 }
1474 
1475 SDValue SelectionDAG::getShiftAmountConstant(uint64_t Val, EVT VT,
1476                                              const SDLoc &DL, bool LegalTypes) {
1477   assert(VT.isInteger() && "Shift amount is not an integer type!");
1478   EVT ShiftVT = TLI->getShiftAmountTy(VT, getDataLayout(), LegalTypes);
1479   return getConstant(Val, DL, ShiftVT);
1480 }
1481 
1482 SDValue SelectionDAG::getVectorIdxConstant(uint64_t Val, const SDLoc &DL,
1483                                            bool isTarget) {
1484   return getConstant(Val, DL, TLI->getVectorIdxTy(getDataLayout()), isTarget);
1485 }
1486 
1487 SDValue SelectionDAG::getConstantFP(const APFloat &V, const SDLoc &DL, EVT VT,
1488                                     bool isTarget) {
1489   return getConstantFP(*ConstantFP::get(*getContext(), V), DL, VT, isTarget);
1490 }
1491 
1492 SDValue SelectionDAG::getConstantFP(const ConstantFP &V, const SDLoc &DL,
1493                                     EVT VT, bool isTarget) {
1494   assert(VT.isFloatingPoint() && "Cannot create integer FP constant!");
1495 
1496   EVT EltVT = VT.getScalarType();
1497 
1498   // Do the map lookup using the actual bit pattern for the floating point
1499   // value, so that we don't have problems with 0.0 comparing equal to -0.0, and
1500   // we don't have issues with SNANs.
1501   unsigned Opc = isTarget ? ISD::TargetConstantFP : ISD::ConstantFP;
1502   FoldingSetNodeID ID;
1503   AddNodeIDNode(ID, Opc, getVTList(EltVT), None);
1504   ID.AddPointer(&V);
1505   void *IP = nullptr;
1506   SDNode *N = nullptr;
1507   if ((N = FindNodeOrInsertPos(ID, DL, IP)))
1508     if (!VT.isVector())
1509       return SDValue(N, 0);
1510 
1511   if (!N) {
1512     N = newSDNode<ConstantFPSDNode>(isTarget, &V, EltVT);
1513     CSEMap.InsertNode(N, IP);
1514     InsertNode(N);
1515   }
1516 
1517   SDValue Result(N, 0);
1518   if (VT.isScalableVector())
1519     Result = getSplatVector(VT, DL, Result);
1520   else if (VT.isVector())
1521     Result = getSplatBuildVector(VT, DL, Result);
1522   NewSDValueDbgMsg(Result, "Creating fp constant: ", this);
1523   return Result;
1524 }
1525 
1526 SDValue SelectionDAG::getConstantFP(double Val, const SDLoc &DL, EVT VT,
1527                                     bool isTarget) {
1528   EVT EltVT = VT.getScalarType();
1529   if (EltVT == MVT::f32)
1530     return getConstantFP(APFloat((float)Val), DL, VT, isTarget);
1531   if (EltVT == MVT::f64)
1532     return getConstantFP(APFloat(Val), DL, VT, isTarget);
1533   if (EltVT == MVT::f80 || EltVT == MVT::f128 || EltVT == MVT::ppcf128 ||
1534       EltVT == MVT::f16 || EltVT == MVT::bf16) {
1535     bool Ignored;
1536     APFloat APF = APFloat(Val);
1537     APF.convert(EVTToAPFloatSemantics(EltVT), APFloat::rmNearestTiesToEven,
1538                 &Ignored);
1539     return getConstantFP(APF, DL, VT, isTarget);
1540   }
1541   llvm_unreachable("Unsupported type in getConstantFP");
1542 }
1543 
1544 SDValue SelectionDAG::getGlobalAddress(const GlobalValue *GV, const SDLoc &DL,
1545                                        EVT VT, int64_t Offset, bool isTargetGA,
1546                                        unsigned TargetFlags) {
1547   assert((TargetFlags == 0 || isTargetGA) &&
1548          "Cannot set target flags on target-independent globals");
1549 
1550   // Truncate (with sign-extension) the offset value to the pointer size.
1551   unsigned BitWidth = getDataLayout().getPointerTypeSizeInBits(GV->getType());
1552   if (BitWidth < 64)
1553     Offset = SignExtend64(Offset, BitWidth);
1554 
1555   unsigned Opc;
1556   if (GV->isThreadLocal())
1557     Opc = isTargetGA ? ISD::TargetGlobalTLSAddress : ISD::GlobalTLSAddress;
1558   else
1559     Opc = isTargetGA ? ISD::TargetGlobalAddress : ISD::GlobalAddress;
1560 
1561   FoldingSetNodeID ID;
1562   AddNodeIDNode(ID, Opc, getVTList(VT), None);
1563   ID.AddPointer(GV);
1564   ID.AddInteger(Offset);
1565   ID.AddInteger(TargetFlags);
1566   void *IP = nullptr;
1567   if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
1568     return SDValue(E, 0);
1569 
1570   auto *N = newSDNode<GlobalAddressSDNode>(
1571       Opc, DL.getIROrder(), DL.getDebugLoc(), GV, VT, Offset, TargetFlags);
1572   CSEMap.InsertNode(N, IP);
1573     InsertNode(N);
1574   return SDValue(N, 0);
1575 }
1576 
1577 SDValue SelectionDAG::getFrameIndex(int FI, EVT VT, bool isTarget) {
1578   unsigned Opc = isTarget ? ISD::TargetFrameIndex : ISD::FrameIndex;
1579   FoldingSetNodeID ID;
1580   AddNodeIDNode(ID, Opc, getVTList(VT), None);
1581   ID.AddInteger(FI);
1582   void *IP = nullptr;
1583   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1584     return SDValue(E, 0);
1585 
1586   auto *N = newSDNode<FrameIndexSDNode>(FI, VT, isTarget);
1587   CSEMap.InsertNode(N, IP);
1588   InsertNode(N);
1589   return SDValue(N, 0);
1590 }
1591 
1592 SDValue SelectionDAG::getJumpTable(int JTI, EVT VT, bool isTarget,
1593                                    unsigned TargetFlags) {
1594   assert((TargetFlags == 0 || isTarget) &&
1595          "Cannot set target flags on target-independent jump tables");
1596   unsigned Opc = isTarget ? ISD::TargetJumpTable : ISD::JumpTable;
1597   FoldingSetNodeID ID;
1598   AddNodeIDNode(ID, Opc, getVTList(VT), None);
1599   ID.AddInteger(JTI);
1600   ID.AddInteger(TargetFlags);
1601   void *IP = nullptr;
1602   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1603     return SDValue(E, 0);
1604 
1605   auto *N = newSDNode<JumpTableSDNode>(JTI, VT, isTarget, TargetFlags);
1606   CSEMap.InsertNode(N, IP);
1607   InsertNode(N);
1608   return SDValue(N, 0);
1609 }
1610 
1611 SDValue SelectionDAG::getConstantPool(const Constant *C, EVT VT,
1612                                       MaybeAlign Alignment, int Offset,
1613                                       bool isTarget, unsigned TargetFlags) {
1614   assert((TargetFlags == 0 || isTarget) &&
1615          "Cannot set target flags on target-independent globals");
1616   if (!Alignment)
1617     Alignment = shouldOptForSize()
1618                     ? getDataLayout().getABITypeAlign(C->getType())
1619                     : getDataLayout().getPrefTypeAlign(C->getType());
1620   unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
1621   FoldingSetNodeID ID;
1622   AddNodeIDNode(ID, Opc, getVTList(VT), None);
1623   ID.AddInteger(Alignment->value());
1624   ID.AddInteger(Offset);
1625   ID.AddPointer(C);
1626   ID.AddInteger(TargetFlags);
1627   void *IP = nullptr;
1628   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1629     return SDValue(E, 0);
1630 
1631   auto *N = newSDNode<ConstantPoolSDNode>(isTarget, C, VT, Offset, *Alignment,
1632                                           TargetFlags);
1633   CSEMap.InsertNode(N, IP);
1634   InsertNode(N);
1635   SDValue V = SDValue(N, 0);
1636   NewSDValueDbgMsg(V, "Creating new constant pool: ", this);
1637   return V;
1638 }
1639 
1640 SDValue SelectionDAG::getConstantPool(MachineConstantPoolValue *C, EVT VT,
1641                                       MaybeAlign Alignment, int Offset,
1642                                       bool isTarget, unsigned TargetFlags) {
1643   assert((TargetFlags == 0 || isTarget) &&
1644          "Cannot set target flags on target-independent globals");
1645   if (!Alignment)
1646     Alignment = getDataLayout().getPrefTypeAlign(C->getType());
1647   unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
1648   FoldingSetNodeID ID;
1649   AddNodeIDNode(ID, Opc, getVTList(VT), None);
1650   ID.AddInteger(Alignment->value());
1651   ID.AddInteger(Offset);
1652   C->addSelectionDAGCSEId(ID);
1653   ID.AddInteger(TargetFlags);
1654   void *IP = nullptr;
1655   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1656     return SDValue(E, 0);
1657 
1658   auto *N = newSDNode<ConstantPoolSDNode>(isTarget, C, VT, Offset, *Alignment,
1659                                           TargetFlags);
1660   CSEMap.InsertNode(N, IP);
1661   InsertNode(N);
1662   return SDValue(N, 0);
1663 }
1664 
1665 SDValue SelectionDAG::getTargetIndex(int Index, EVT VT, int64_t Offset,
1666                                      unsigned TargetFlags) {
1667   FoldingSetNodeID ID;
1668   AddNodeIDNode(ID, ISD::TargetIndex, getVTList(VT), None);
1669   ID.AddInteger(Index);
1670   ID.AddInteger(Offset);
1671   ID.AddInteger(TargetFlags);
1672   void *IP = nullptr;
1673   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1674     return SDValue(E, 0);
1675 
1676   auto *N = newSDNode<TargetIndexSDNode>(Index, VT, Offset, TargetFlags);
1677   CSEMap.InsertNode(N, IP);
1678   InsertNode(N);
1679   return SDValue(N, 0);
1680 }
1681 
1682 SDValue SelectionDAG::getBasicBlock(MachineBasicBlock *MBB) {
1683   FoldingSetNodeID ID;
1684   AddNodeIDNode(ID, ISD::BasicBlock, getVTList(MVT::Other), None);
1685   ID.AddPointer(MBB);
1686   void *IP = nullptr;
1687   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1688     return SDValue(E, 0);
1689 
1690   auto *N = newSDNode<BasicBlockSDNode>(MBB);
1691   CSEMap.InsertNode(N, IP);
1692   InsertNode(N);
1693   return SDValue(N, 0);
1694 }
1695 
1696 SDValue SelectionDAG::getValueType(EVT VT) {
1697   if (VT.isSimple() && (unsigned)VT.getSimpleVT().SimpleTy >=
1698       ValueTypeNodes.size())
1699     ValueTypeNodes.resize(VT.getSimpleVT().SimpleTy+1);
1700 
1701   SDNode *&N = VT.isExtended() ?
1702     ExtendedValueTypeNodes[VT] : ValueTypeNodes[VT.getSimpleVT().SimpleTy];
1703 
1704   if (N) return SDValue(N, 0);
1705   N = newSDNode<VTSDNode>(VT);
1706   InsertNode(N);
1707   return SDValue(N, 0);
1708 }
1709 
1710 SDValue SelectionDAG::getExternalSymbol(const char *Sym, EVT VT) {
1711   SDNode *&N = ExternalSymbols[Sym];
1712   if (N) return SDValue(N, 0);
1713   N = newSDNode<ExternalSymbolSDNode>(false, Sym, 0, VT);
1714   InsertNode(N);
1715   return SDValue(N, 0);
1716 }
1717 
1718 SDValue SelectionDAG::getMCSymbol(MCSymbol *Sym, EVT VT) {
1719   SDNode *&N = MCSymbols[Sym];
1720   if (N)
1721     return SDValue(N, 0);
1722   N = newSDNode<MCSymbolSDNode>(Sym, VT);
1723   InsertNode(N);
1724   return SDValue(N, 0);
1725 }
1726 
1727 SDValue SelectionDAG::getTargetExternalSymbol(const char *Sym, EVT VT,
1728                                               unsigned TargetFlags) {
1729   SDNode *&N =
1730       TargetExternalSymbols[std::pair<std::string, unsigned>(Sym, TargetFlags)];
1731   if (N) return SDValue(N, 0);
1732   N = newSDNode<ExternalSymbolSDNode>(true, Sym, TargetFlags, VT);
1733   InsertNode(N);
1734   return SDValue(N, 0);
1735 }
1736 
1737 SDValue SelectionDAG::getCondCode(ISD::CondCode Cond) {
1738   if ((unsigned)Cond >= CondCodeNodes.size())
1739     CondCodeNodes.resize(Cond+1);
1740 
1741   if (!CondCodeNodes[Cond]) {
1742     auto *N = newSDNode<CondCodeSDNode>(Cond);
1743     CondCodeNodes[Cond] = N;
1744     InsertNode(N);
1745   }
1746 
1747   return SDValue(CondCodeNodes[Cond], 0);
1748 }
1749 
1750 SDValue SelectionDAG::getStepVector(const SDLoc &DL, EVT ResVT) {
1751   APInt One(ResVT.getScalarSizeInBits(), 1);
1752   return getStepVector(DL, ResVT, One);
1753 }
1754 
1755 SDValue SelectionDAG::getStepVector(const SDLoc &DL, EVT ResVT, APInt StepVal) {
1756   assert(ResVT.getScalarSizeInBits() == StepVal.getBitWidth());
1757   if (ResVT.isScalableVector())
1758     return getNode(
1759         ISD::STEP_VECTOR, DL, ResVT,
1760         getTargetConstant(StepVal, DL, ResVT.getVectorElementType()));
1761 
1762   SmallVector<SDValue, 16> OpsStepConstants;
1763   for (uint64_t i = 0; i < ResVT.getVectorNumElements(); i++)
1764     OpsStepConstants.push_back(
1765         getConstant(StepVal * i, DL, ResVT.getVectorElementType()));
1766   return getBuildVector(ResVT, DL, OpsStepConstants);
1767 }
1768 
1769 /// Swaps the values of N1 and N2. Swaps all indices in the shuffle mask M that
1770 /// point at N1 to point at N2 and indices that point at N2 to point at N1.
1771 static void commuteShuffle(SDValue &N1, SDValue &N2, MutableArrayRef<int> M) {
1772   std::swap(N1, N2);
1773   ShuffleVectorSDNode::commuteMask(M);
1774 }
1775 
1776 SDValue SelectionDAG::getVectorShuffle(EVT VT, const SDLoc &dl, SDValue N1,
1777                                        SDValue N2, ArrayRef<int> Mask) {
1778   assert(VT.getVectorNumElements() == Mask.size() &&
1779          "Must have the same number of vector elements as mask elements!");
1780   assert(VT == N1.getValueType() && VT == N2.getValueType() &&
1781          "Invalid VECTOR_SHUFFLE");
1782 
1783   // Canonicalize shuffle undef, undef -> undef
1784   if (N1.isUndef() && N2.isUndef())
1785     return getUNDEF(VT);
1786 
1787   // Validate that all indices in Mask are within the range of the elements
1788   // input to the shuffle.
1789   int NElts = Mask.size();
1790   assert(llvm::all_of(Mask,
1791                       [&](int M) { return M < (NElts * 2) && M >= -1; }) &&
1792          "Index out of range");
1793 
1794   // Copy the mask so we can do any needed cleanup.
1795   SmallVector<int, 8> MaskVec(Mask.begin(), Mask.end());
1796 
1797   // Canonicalize shuffle v, v -> v, undef
1798   if (N1 == N2) {
1799     N2 = getUNDEF(VT);
1800     for (int i = 0; i != NElts; ++i)
1801       if (MaskVec[i] >= NElts) MaskVec[i] -= NElts;
1802   }
1803 
1804   // Canonicalize shuffle undef, v -> v, undef.  Commute the shuffle mask.
1805   if (N1.isUndef())
1806     commuteShuffle(N1, N2, MaskVec);
1807 
1808   if (TLI->hasVectorBlend()) {
1809     // If shuffling a splat, try to blend the splat instead. We do this here so
1810     // that even when this arises during lowering we don't have to re-handle it.
1811     auto BlendSplat = [&](BuildVectorSDNode *BV, int Offset) {
1812       BitVector UndefElements;
1813       SDValue Splat = BV->getSplatValue(&UndefElements);
1814       if (!Splat)
1815         return;
1816 
1817       for (int i = 0; i < NElts; ++i) {
1818         if (MaskVec[i] < Offset || MaskVec[i] >= (Offset + NElts))
1819           continue;
1820 
1821         // If this input comes from undef, mark it as such.
1822         if (UndefElements[MaskVec[i] - Offset]) {
1823           MaskVec[i] = -1;
1824           continue;
1825         }
1826 
1827         // If we can blend a non-undef lane, use that instead.
1828         if (!UndefElements[i])
1829           MaskVec[i] = i + Offset;
1830       }
1831     };
1832     if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
1833       BlendSplat(N1BV, 0);
1834     if (auto *N2BV = dyn_cast<BuildVectorSDNode>(N2))
1835       BlendSplat(N2BV, NElts);
1836   }
1837 
1838   // Canonicalize all index into lhs, -> shuffle lhs, undef
1839   // Canonicalize all index into rhs, -> shuffle rhs, undef
1840   bool AllLHS = true, AllRHS = true;
1841   bool N2Undef = N2.isUndef();
1842   for (int i = 0; i != NElts; ++i) {
1843     if (MaskVec[i] >= NElts) {
1844       if (N2Undef)
1845         MaskVec[i] = -1;
1846       else
1847         AllLHS = false;
1848     } else if (MaskVec[i] >= 0) {
1849       AllRHS = false;
1850     }
1851   }
1852   if (AllLHS && AllRHS)
1853     return getUNDEF(VT);
1854   if (AllLHS && !N2Undef)
1855     N2 = getUNDEF(VT);
1856   if (AllRHS) {
1857     N1 = getUNDEF(VT);
1858     commuteShuffle(N1, N2, MaskVec);
1859   }
1860   // Reset our undef status after accounting for the mask.
1861   N2Undef = N2.isUndef();
1862   // Re-check whether both sides ended up undef.
1863   if (N1.isUndef() && N2Undef)
1864     return getUNDEF(VT);
1865 
1866   // If Identity shuffle return that node.
1867   bool Identity = true, AllSame = true;
1868   for (int i = 0; i != NElts; ++i) {
1869     if (MaskVec[i] >= 0 && MaskVec[i] != i) Identity = false;
1870     if (MaskVec[i] != MaskVec[0]) AllSame = false;
1871   }
1872   if (Identity && NElts)
1873     return N1;
1874 
1875   // Shuffling a constant splat doesn't change the result.
1876   if (N2Undef) {
1877     SDValue V = N1;
1878 
1879     // Look through any bitcasts. We check that these don't change the number
1880     // (and size) of elements and just changes their types.
1881     while (V.getOpcode() == ISD::BITCAST)
1882       V = V->getOperand(0);
1883 
1884     // A splat should always show up as a build vector node.
1885     if (auto *BV = dyn_cast<BuildVectorSDNode>(V)) {
1886       BitVector UndefElements;
1887       SDValue Splat = BV->getSplatValue(&UndefElements);
1888       // If this is a splat of an undef, shuffling it is also undef.
1889       if (Splat && Splat.isUndef())
1890         return getUNDEF(VT);
1891 
1892       bool SameNumElts =
1893           V.getValueType().getVectorNumElements() == VT.getVectorNumElements();
1894 
1895       // We only have a splat which can skip shuffles if there is a splatted
1896       // value and no undef lanes rearranged by the shuffle.
1897       if (Splat && UndefElements.none()) {
1898         // Splat of <x, x, ..., x>, return <x, x, ..., x>, provided that the
1899         // number of elements match or the value splatted is a zero constant.
1900         if (SameNumElts)
1901           return N1;
1902         if (auto *C = dyn_cast<ConstantSDNode>(Splat))
1903           if (C->isNullValue())
1904             return N1;
1905       }
1906 
1907       // If the shuffle itself creates a splat, build the vector directly.
1908       if (AllSame && SameNumElts) {
1909         EVT BuildVT = BV->getValueType(0);
1910         const SDValue &Splatted = BV->getOperand(MaskVec[0]);
1911         SDValue NewBV = getSplatBuildVector(BuildVT, dl, Splatted);
1912 
1913         // We may have jumped through bitcasts, so the type of the
1914         // BUILD_VECTOR may not match the type of the shuffle.
1915         if (BuildVT != VT)
1916           NewBV = getNode(ISD::BITCAST, dl, VT, NewBV);
1917         return NewBV;
1918       }
1919     }
1920   }
1921 
1922   FoldingSetNodeID ID;
1923   SDValue Ops[2] = { N1, N2 };
1924   AddNodeIDNode(ID, ISD::VECTOR_SHUFFLE, getVTList(VT), Ops);
1925   for (int i = 0; i != NElts; ++i)
1926     ID.AddInteger(MaskVec[i]);
1927 
1928   void* IP = nullptr;
1929   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
1930     return SDValue(E, 0);
1931 
1932   // Allocate the mask array for the node out of the BumpPtrAllocator, since
1933   // SDNode doesn't have access to it.  This memory will be "leaked" when
1934   // the node is deallocated, but recovered when the NodeAllocator is released.
1935   int *MaskAlloc = OperandAllocator.Allocate<int>(NElts);
1936   llvm::copy(MaskVec, MaskAlloc);
1937 
1938   auto *N = newSDNode<ShuffleVectorSDNode>(VT, dl.getIROrder(),
1939                                            dl.getDebugLoc(), MaskAlloc);
1940   createOperands(N, Ops);
1941 
1942   CSEMap.InsertNode(N, IP);
1943   InsertNode(N);
1944   SDValue V = SDValue(N, 0);
1945   NewSDValueDbgMsg(V, "Creating new node: ", this);
1946   return V;
1947 }
1948 
1949 SDValue SelectionDAG::getCommutedVectorShuffle(const ShuffleVectorSDNode &SV) {
1950   EVT VT = SV.getValueType(0);
1951   SmallVector<int, 8> MaskVec(SV.getMask().begin(), SV.getMask().end());
1952   ShuffleVectorSDNode::commuteMask(MaskVec);
1953 
1954   SDValue Op0 = SV.getOperand(0);
1955   SDValue Op1 = SV.getOperand(1);
1956   return getVectorShuffle(VT, SDLoc(&SV), Op1, Op0, MaskVec);
1957 }
1958 
1959 SDValue SelectionDAG::getRegister(unsigned RegNo, EVT VT) {
1960   FoldingSetNodeID ID;
1961   AddNodeIDNode(ID, ISD::Register, getVTList(VT), None);
1962   ID.AddInteger(RegNo);
1963   void *IP = nullptr;
1964   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1965     return SDValue(E, 0);
1966 
1967   auto *N = newSDNode<RegisterSDNode>(RegNo, VT);
1968   N->SDNodeBits.IsDivergent = TLI->isSDNodeSourceOfDivergence(N, FLI, DA);
1969   CSEMap.InsertNode(N, IP);
1970   InsertNode(N);
1971   return SDValue(N, 0);
1972 }
1973 
1974 SDValue SelectionDAG::getRegisterMask(const uint32_t *RegMask) {
1975   FoldingSetNodeID ID;
1976   AddNodeIDNode(ID, ISD::RegisterMask, getVTList(MVT::Untyped), None);
1977   ID.AddPointer(RegMask);
1978   void *IP = nullptr;
1979   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1980     return SDValue(E, 0);
1981 
1982   auto *N = newSDNode<RegisterMaskSDNode>(RegMask);
1983   CSEMap.InsertNode(N, IP);
1984   InsertNode(N);
1985   return SDValue(N, 0);
1986 }
1987 
1988 SDValue SelectionDAG::getEHLabel(const SDLoc &dl, SDValue Root,
1989                                  MCSymbol *Label) {
1990   return getLabelNode(ISD::EH_LABEL, dl, Root, Label);
1991 }
1992 
1993 SDValue SelectionDAG::getLabelNode(unsigned Opcode, const SDLoc &dl,
1994                                    SDValue Root, MCSymbol *Label) {
1995   FoldingSetNodeID ID;
1996   SDValue Ops[] = { Root };
1997   AddNodeIDNode(ID, Opcode, getVTList(MVT::Other), Ops);
1998   ID.AddPointer(Label);
1999   void *IP = nullptr;
2000   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2001     return SDValue(E, 0);
2002 
2003   auto *N =
2004       newSDNode<LabelSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(), Label);
2005   createOperands(N, Ops);
2006 
2007   CSEMap.InsertNode(N, IP);
2008   InsertNode(N);
2009   return SDValue(N, 0);
2010 }
2011 
2012 SDValue SelectionDAG::getBlockAddress(const BlockAddress *BA, EVT VT,
2013                                       int64_t Offset, bool isTarget,
2014                                       unsigned TargetFlags) {
2015   unsigned Opc = isTarget ? ISD::TargetBlockAddress : ISD::BlockAddress;
2016 
2017   FoldingSetNodeID ID;
2018   AddNodeIDNode(ID, Opc, getVTList(VT), None);
2019   ID.AddPointer(BA);
2020   ID.AddInteger(Offset);
2021   ID.AddInteger(TargetFlags);
2022   void *IP = nullptr;
2023   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2024     return SDValue(E, 0);
2025 
2026   auto *N = newSDNode<BlockAddressSDNode>(Opc, VT, BA, Offset, TargetFlags);
2027   CSEMap.InsertNode(N, IP);
2028   InsertNode(N);
2029   return SDValue(N, 0);
2030 }
2031 
2032 SDValue SelectionDAG::getSrcValue(const Value *V) {
2033   FoldingSetNodeID ID;
2034   AddNodeIDNode(ID, ISD::SRCVALUE, getVTList(MVT::Other), None);
2035   ID.AddPointer(V);
2036 
2037   void *IP = nullptr;
2038   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2039     return SDValue(E, 0);
2040 
2041   auto *N = newSDNode<SrcValueSDNode>(V);
2042   CSEMap.InsertNode(N, IP);
2043   InsertNode(N);
2044   return SDValue(N, 0);
2045 }
2046 
2047 SDValue SelectionDAG::getMDNode(const MDNode *MD) {
2048   FoldingSetNodeID ID;
2049   AddNodeIDNode(ID, ISD::MDNODE_SDNODE, getVTList(MVT::Other), None);
2050   ID.AddPointer(MD);
2051 
2052   void *IP = nullptr;
2053   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2054     return SDValue(E, 0);
2055 
2056   auto *N = newSDNode<MDNodeSDNode>(MD);
2057   CSEMap.InsertNode(N, IP);
2058   InsertNode(N);
2059   return SDValue(N, 0);
2060 }
2061 
2062 SDValue SelectionDAG::getBitcast(EVT VT, SDValue V) {
2063   if (VT == V.getValueType())
2064     return V;
2065 
2066   return getNode(ISD::BITCAST, SDLoc(V), VT, V);
2067 }
2068 
2069 SDValue SelectionDAG::getAddrSpaceCast(const SDLoc &dl, EVT VT, SDValue Ptr,
2070                                        unsigned SrcAS, unsigned DestAS) {
2071   SDValue Ops[] = {Ptr};
2072   FoldingSetNodeID ID;
2073   AddNodeIDNode(ID, ISD::ADDRSPACECAST, getVTList(VT), Ops);
2074   ID.AddInteger(SrcAS);
2075   ID.AddInteger(DestAS);
2076 
2077   void *IP = nullptr;
2078   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
2079     return SDValue(E, 0);
2080 
2081   auto *N = newSDNode<AddrSpaceCastSDNode>(dl.getIROrder(), dl.getDebugLoc(),
2082                                            VT, SrcAS, DestAS);
2083   createOperands(N, Ops);
2084 
2085   CSEMap.InsertNode(N, IP);
2086   InsertNode(N);
2087   return SDValue(N, 0);
2088 }
2089 
2090 SDValue SelectionDAG::getFreeze(SDValue V) {
2091   return getNode(ISD::FREEZE, SDLoc(V), V.getValueType(), V);
2092 }
2093 
2094 /// getShiftAmountOperand - Return the specified value casted to
2095 /// the target's desired shift amount type.
2096 SDValue SelectionDAG::getShiftAmountOperand(EVT LHSTy, SDValue Op) {
2097   EVT OpTy = Op.getValueType();
2098   EVT ShTy = TLI->getShiftAmountTy(LHSTy, getDataLayout());
2099   if (OpTy == ShTy || OpTy.isVector()) return Op;
2100 
2101   return getZExtOrTrunc(Op, SDLoc(Op), ShTy);
2102 }
2103 
2104 SDValue SelectionDAG::expandVAArg(SDNode *Node) {
2105   SDLoc dl(Node);
2106   const TargetLowering &TLI = getTargetLoweringInfo();
2107   const Value *V = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
2108   EVT VT = Node->getValueType(0);
2109   SDValue Tmp1 = Node->getOperand(0);
2110   SDValue Tmp2 = Node->getOperand(1);
2111   const MaybeAlign MA(Node->getConstantOperandVal(3));
2112 
2113   SDValue VAListLoad = getLoad(TLI.getPointerTy(getDataLayout()), dl, Tmp1,
2114                                Tmp2, MachinePointerInfo(V));
2115   SDValue VAList = VAListLoad;
2116 
2117   if (MA && *MA > TLI.getMinStackArgumentAlignment()) {
2118     VAList = getNode(ISD::ADD, dl, VAList.getValueType(), VAList,
2119                      getConstant(MA->value() - 1, dl, VAList.getValueType()));
2120 
2121     VAList =
2122         getNode(ISD::AND, dl, VAList.getValueType(), VAList,
2123                 getConstant(-(int64_t)MA->value(), dl, VAList.getValueType()));
2124   }
2125 
2126   // Increment the pointer, VAList, to the next vaarg
2127   Tmp1 = getNode(ISD::ADD, dl, VAList.getValueType(), VAList,
2128                  getConstant(getDataLayout().getTypeAllocSize(
2129                                                VT.getTypeForEVT(*getContext())),
2130                              dl, VAList.getValueType()));
2131   // Store the incremented VAList to the legalized pointer
2132   Tmp1 =
2133       getStore(VAListLoad.getValue(1), dl, Tmp1, Tmp2, MachinePointerInfo(V));
2134   // Load the actual argument out of the pointer VAList
2135   return getLoad(VT, dl, Tmp1, VAList, MachinePointerInfo());
2136 }
2137 
2138 SDValue SelectionDAG::expandVACopy(SDNode *Node) {
2139   SDLoc dl(Node);
2140   const TargetLowering &TLI = getTargetLoweringInfo();
2141   // This defaults to loading a pointer from the input and storing it to the
2142   // output, returning the chain.
2143   const Value *VD = cast<SrcValueSDNode>(Node->getOperand(3))->getValue();
2144   const Value *VS = cast<SrcValueSDNode>(Node->getOperand(4))->getValue();
2145   SDValue Tmp1 =
2146       getLoad(TLI.getPointerTy(getDataLayout()), dl, Node->getOperand(0),
2147               Node->getOperand(2), MachinePointerInfo(VS));
2148   return getStore(Tmp1.getValue(1), dl, Tmp1, Node->getOperand(1),
2149                   MachinePointerInfo(VD));
2150 }
2151 
2152 Align SelectionDAG::getReducedAlign(EVT VT, bool UseABI) {
2153   const DataLayout &DL = getDataLayout();
2154   Type *Ty = VT.getTypeForEVT(*getContext());
2155   Align RedAlign = UseABI ? DL.getABITypeAlign(Ty) : DL.getPrefTypeAlign(Ty);
2156 
2157   if (TLI->isTypeLegal(VT) || !VT.isVector())
2158     return RedAlign;
2159 
2160   const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering();
2161   const Align StackAlign = TFI->getStackAlign();
2162 
2163   // See if we can choose a smaller ABI alignment in cases where it's an
2164   // illegal vector type that will get broken down.
2165   if (RedAlign > StackAlign) {
2166     EVT IntermediateVT;
2167     MVT RegisterVT;
2168     unsigned NumIntermediates;
2169     TLI->getVectorTypeBreakdown(*getContext(), VT, IntermediateVT,
2170                                 NumIntermediates, RegisterVT);
2171     Ty = IntermediateVT.getTypeForEVT(*getContext());
2172     Align RedAlign2 = UseABI ? DL.getABITypeAlign(Ty) : DL.getPrefTypeAlign(Ty);
2173     if (RedAlign2 < RedAlign)
2174       RedAlign = RedAlign2;
2175   }
2176 
2177   return RedAlign;
2178 }
2179 
2180 SDValue SelectionDAG::CreateStackTemporary(TypeSize Bytes, Align Alignment) {
2181   MachineFrameInfo &MFI = MF->getFrameInfo();
2182   const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering();
2183   int StackID = 0;
2184   if (Bytes.isScalable())
2185     StackID = TFI->getStackIDForScalableVectors();
2186   // The stack id gives an indication of whether the object is scalable or
2187   // not, so it's safe to pass in the minimum size here.
2188   int FrameIdx = MFI.CreateStackObject(Bytes.getKnownMinSize(), Alignment,
2189                                        false, nullptr, StackID);
2190   return getFrameIndex(FrameIdx, TLI->getFrameIndexTy(getDataLayout()));
2191 }
2192 
2193 SDValue SelectionDAG::CreateStackTemporary(EVT VT, unsigned minAlign) {
2194   Type *Ty = VT.getTypeForEVT(*getContext());
2195   Align StackAlign =
2196       std::max(getDataLayout().getPrefTypeAlign(Ty), Align(minAlign));
2197   return CreateStackTemporary(VT.getStoreSize(), StackAlign);
2198 }
2199 
2200 SDValue SelectionDAG::CreateStackTemporary(EVT VT1, EVT VT2) {
2201   TypeSize VT1Size = VT1.getStoreSize();
2202   TypeSize VT2Size = VT2.getStoreSize();
2203   assert(VT1Size.isScalable() == VT2Size.isScalable() &&
2204          "Don't know how to choose the maximum size when creating a stack "
2205          "temporary");
2206   TypeSize Bytes =
2207       VT1Size.getKnownMinSize() > VT2Size.getKnownMinSize() ? VT1Size : VT2Size;
2208 
2209   Type *Ty1 = VT1.getTypeForEVT(*getContext());
2210   Type *Ty2 = VT2.getTypeForEVT(*getContext());
2211   const DataLayout &DL = getDataLayout();
2212   Align Align = std::max(DL.getPrefTypeAlign(Ty1), DL.getPrefTypeAlign(Ty2));
2213   return CreateStackTemporary(Bytes, Align);
2214 }
2215 
2216 SDValue SelectionDAG::FoldSetCC(EVT VT, SDValue N1, SDValue N2,
2217                                 ISD::CondCode Cond, const SDLoc &dl) {
2218   EVT OpVT = N1.getValueType();
2219 
2220   // These setcc operations always fold.
2221   switch (Cond) {
2222   default: break;
2223   case ISD::SETFALSE:
2224   case ISD::SETFALSE2: return getBoolConstant(false, dl, VT, OpVT);
2225   case ISD::SETTRUE:
2226   case ISD::SETTRUE2: return getBoolConstant(true, dl, VT, OpVT);
2227 
2228   case ISD::SETOEQ:
2229   case ISD::SETOGT:
2230   case ISD::SETOGE:
2231   case ISD::SETOLT:
2232   case ISD::SETOLE:
2233   case ISD::SETONE:
2234   case ISD::SETO:
2235   case ISD::SETUO:
2236   case ISD::SETUEQ:
2237   case ISD::SETUNE:
2238     assert(!OpVT.isInteger() && "Illegal setcc for integer!");
2239     break;
2240   }
2241 
2242   if (OpVT.isInteger()) {
2243     // For EQ and NE, we can always pick a value for the undef to make the
2244     // predicate pass or fail, so we can return undef.
2245     // Matches behavior in llvm::ConstantFoldCompareInstruction.
2246     // icmp eq/ne X, undef -> undef.
2247     if ((N1.isUndef() || N2.isUndef()) &&
2248         (Cond == ISD::SETEQ || Cond == ISD::SETNE))
2249       return getUNDEF(VT);
2250 
2251     // If both operands are undef, we can return undef for int comparison.
2252     // icmp undef, undef -> undef.
2253     if (N1.isUndef() && N2.isUndef())
2254       return getUNDEF(VT);
2255 
2256     // icmp X, X -> true/false
2257     // icmp X, undef -> true/false because undef could be X.
2258     if (N1 == N2)
2259       return getBoolConstant(ISD::isTrueWhenEqual(Cond), dl, VT, OpVT);
2260   }
2261 
2262   if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2)) {
2263     const APInt &C2 = N2C->getAPIntValue();
2264     if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1)) {
2265       const APInt &C1 = N1C->getAPIntValue();
2266 
2267       switch (Cond) {
2268       default: llvm_unreachable("Unknown integer setcc!");
2269       case ISD::SETEQ:  return getBoolConstant(C1 == C2, dl, VT, OpVT);
2270       case ISD::SETNE:  return getBoolConstant(C1 != C2, dl, VT, OpVT);
2271       case ISD::SETULT: return getBoolConstant(C1.ult(C2), dl, VT, OpVT);
2272       case ISD::SETUGT: return getBoolConstant(C1.ugt(C2), dl, VT, OpVT);
2273       case ISD::SETULE: return getBoolConstant(C1.ule(C2), dl, VT, OpVT);
2274       case ISD::SETUGE: return getBoolConstant(C1.uge(C2), dl, VT, OpVT);
2275       case ISD::SETLT:  return getBoolConstant(C1.slt(C2), dl, VT, OpVT);
2276       case ISD::SETGT:  return getBoolConstant(C1.sgt(C2), dl, VT, OpVT);
2277       case ISD::SETLE:  return getBoolConstant(C1.sle(C2), dl, VT, OpVT);
2278       case ISD::SETGE:  return getBoolConstant(C1.sge(C2), dl, VT, OpVT);
2279       }
2280     }
2281   }
2282 
2283   auto *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
2284   auto *N2CFP = dyn_cast<ConstantFPSDNode>(N2);
2285 
2286   if (N1CFP && N2CFP) {
2287     APFloat::cmpResult R = N1CFP->getValueAPF().compare(N2CFP->getValueAPF());
2288     switch (Cond) {
2289     default: break;
2290     case ISD::SETEQ:  if (R==APFloat::cmpUnordered)
2291                         return getUNDEF(VT);
2292                       LLVM_FALLTHROUGH;
2293     case ISD::SETOEQ: return getBoolConstant(R==APFloat::cmpEqual, dl, VT,
2294                                              OpVT);
2295     case ISD::SETNE:  if (R==APFloat::cmpUnordered)
2296                         return getUNDEF(VT);
2297                       LLVM_FALLTHROUGH;
2298     case ISD::SETONE: return getBoolConstant(R==APFloat::cmpGreaterThan ||
2299                                              R==APFloat::cmpLessThan, dl, VT,
2300                                              OpVT);
2301     case ISD::SETLT:  if (R==APFloat::cmpUnordered)
2302                         return getUNDEF(VT);
2303                       LLVM_FALLTHROUGH;
2304     case ISD::SETOLT: return getBoolConstant(R==APFloat::cmpLessThan, dl, VT,
2305                                              OpVT);
2306     case ISD::SETGT:  if (R==APFloat::cmpUnordered)
2307                         return getUNDEF(VT);
2308                       LLVM_FALLTHROUGH;
2309     case ISD::SETOGT: return getBoolConstant(R==APFloat::cmpGreaterThan, dl,
2310                                              VT, OpVT);
2311     case ISD::SETLE:  if (R==APFloat::cmpUnordered)
2312                         return getUNDEF(VT);
2313                       LLVM_FALLTHROUGH;
2314     case ISD::SETOLE: return getBoolConstant(R==APFloat::cmpLessThan ||
2315                                              R==APFloat::cmpEqual, dl, VT,
2316                                              OpVT);
2317     case ISD::SETGE:  if (R==APFloat::cmpUnordered)
2318                         return getUNDEF(VT);
2319                       LLVM_FALLTHROUGH;
2320     case ISD::SETOGE: return getBoolConstant(R==APFloat::cmpGreaterThan ||
2321                                          R==APFloat::cmpEqual, dl, VT, OpVT);
2322     case ISD::SETO:   return getBoolConstant(R!=APFloat::cmpUnordered, dl, VT,
2323                                              OpVT);
2324     case ISD::SETUO:  return getBoolConstant(R==APFloat::cmpUnordered, dl, VT,
2325                                              OpVT);
2326     case ISD::SETUEQ: return getBoolConstant(R==APFloat::cmpUnordered ||
2327                                              R==APFloat::cmpEqual, dl, VT,
2328                                              OpVT);
2329     case ISD::SETUNE: return getBoolConstant(R!=APFloat::cmpEqual, dl, VT,
2330                                              OpVT);
2331     case ISD::SETULT: return getBoolConstant(R==APFloat::cmpUnordered ||
2332                                              R==APFloat::cmpLessThan, dl, VT,
2333                                              OpVT);
2334     case ISD::SETUGT: return getBoolConstant(R==APFloat::cmpGreaterThan ||
2335                                              R==APFloat::cmpUnordered, dl, VT,
2336                                              OpVT);
2337     case ISD::SETULE: return getBoolConstant(R!=APFloat::cmpGreaterThan, dl,
2338                                              VT, OpVT);
2339     case ISD::SETUGE: return getBoolConstant(R!=APFloat::cmpLessThan, dl, VT,
2340                                              OpVT);
2341     }
2342   } else if (N1CFP && OpVT.isSimple() && !N2.isUndef()) {
2343     // Ensure that the constant occurs on the RHS.
2344     ISD::CondCode SwappedCond = ISD::getSetCCSwappedOperands(Cond);
2345     if (!TLI->isCondCodeLegal(SwappedCond, OpVT.getSimpleVT()))
2346       return SDValue();
2347     return getSetCC(dl, VT, N2, N1, SwappedCond);
2348   } else if ((N2CFP && N2CFP->getValueAPF().isNaN()) ||
2349              (OpVT.isFloatingPoint() && (N1.isUndef() || N2.isUndef()))) {
2350     // If an operand is known to be a nan (or undef that could be a nan), we can
2351     // fold it.
2352     // Choosing NaN for the undef will always make unordered comparison succeed
2353     // and ordered comparison fails.
2354     // Matches behavior in llvm::ConstantFoldCompareInstruction.
2355     switch (ISD::getUnorderedFlavor(Cond)) {
2356     default:
2357       llvm_unreachable("Unknown flavor!");
2358     case 0: // Known false.
2359       return getBoolConstant(false, dl, VT, OpVT);
2360     case 1: // Known true.
2361       return getBoolConstant(true, dl, VT, OpVT);
2362     case 2: // Undefined.
2363       return getUNDEF(VT);
2364     }
2365   }
2366 
2367   // Could not fold it.
2368   return SDValue();
2369 }
2370 
2371 /// See if the specified operand can be simplified with the knowledge that only
2372 /// the bits specified by DemandedBits are used.
2373 /// TODO: really we should be making this into the DAG equivalent of
2374 /// SimplifyMultipleUseDemandedBits and not generate any new nodes.
2375 SDValue SelectionDAG::GetDemandedBits(SDValue V, const APInt &DemandedBits) {
2376   EVT VT = V.getValueType();
2377 
2378   if (VT.isScalableVector())
2379     return SDValue();
2380 
2381   APInt DemandedElts = VT.isVector()
2382                            ? APInt::getAllOnesValue(VT.getVectorNumElements())
2383                            : APInt(1, 1);
2384   return GetDemandedBits(V, DemandedBits, DemandedElts);
2385 }
2386 
2387 /// See if the specified operand can be simplified with the knowledge that only
2388 /// the bits specified by DemandedBits are used in the elements specified by
2389 /// DemandedElts.
2390 /// TODO: really we should be making this into the DAG equivalent of
2391 /// SimplifyMultipleUseDemandedBits and not generate any new nodes.
2392 SDValue SelectionDAG::GetDemandedBits(SDValue V, const APInt &DemandedBits,
2393                                       const APInt &DemandedElts) {
2394   switch (V.getOpcode()) {
2395   default:
2396     return TLI->SimplifyMultipleUseDemandedBits(V, DemandedBits, DemandedElts,
2397                                                 *this, 0);
2398   case ISD::Constant: {
2399     const APInt &CVal = cast<ConstantSDNode>(V)->getAPIntValue();
2400     APInt NewVal = CVal & DemandedBits;
2401     if (NewVal != CVal)
2402       return getConstant(NewVal, SDLoc(V), V.getValueType());
2403     break;
2404   }
2405   case ISD::SRL:
2406     // Only look at single-use SRLs.
2407     if (!V.getNode()->hasOneUse())
2408       break;
2409     if (auto *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
2410       // See if we can recursively simplify the LHS.
2411       unsigned Amt = RHSC->getZExtValue();
2412 
2413       // Watch out for shift count overflow though.
2414       if (Amt >= DemandedBits.getBitWidth())
2415         break;
2416       APInt SrcDemandedBits = DemandedBits << Amt;
2417       if (SDValue SimplifyLHS =
2418               GetDemandedBits(V.getOperand(0), SrcDemandedBits))
2419         return getNode(ISD::SRL, SDLoc(V), V.getValueType(), SimplifyLHS,
2420                        V.getOperand(1));
2421     }
2422     break;
2423   }
2424   return SDValue();
2425 }
2426 
2427 /// SignBitIsZero - Return true if the sign bit of Op is known to be zero.  We
2428 /// use this predicate to simplify operations downstream.
2429 bool SelectionDAG::SignBitIsZero(SDValue Op, unsigned Depth) const {
2430   unsigned BitWidth = Op.getScalarValueSizeInBits();
2431   return MaskedValueIsZero(Op, APInt::getSignMask(BitWidth), Depth);
2432 }
2433 
2434 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero.  We use
2435 /// this predicate to simplify operations downstream.  Mask is known to be zero
2436 /// for bits that V cannot have.
2437 bool SelectionDAG::MaskedValueIsZero(SDValue V, const APInt &Mask,
2438                                      unsigned Depth) const {
2439   return Mask.isSubsetOf(computeKnownBits(V, Depth).Zero);
2440 }
2441 
2442 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero in
2443 /// DemandedElts.  We use this predicate to simplify operations downstream.
2444 /// Mask is known to be zero for bits that V cannot have.
2445 bool SelectionDAG::MaskedValueIsZero(SDValue V, const APInt &Mask,
2446                                      const APInt &DemandedElts,
2447                                      unsigned Depth) const {
2448   return Mask.isSubsetOf(computeKnownBits(V, DemandedElts, Depth).Zero);
2449 }
2450 
2451 /// MaskedValueIsAllOnes - Return true if '(Op & Mask) == Mask'.
2452 bool SelectionDAG::MaskedValueIsAllOnes(SDValue V, const APInt &Mask,
2453                                         unsigned Depth) const {
2454   return Mask.isSubsetOf(computeKnownBits(V, Depth).One);
2455 }
2456 
2457 /// isSplatValue - Return true if the vector V has the same value
2458 /// across all DemandedElts. For scalable vectors it does not make
2459 /// sense to specify which elements are demanded or undefined, therefore
2460 /// they are simply ignored.
2461 bool SelectionDAG::isSplatValue(SDValue V, const APInt &DemandedElts,
2462                                 APInt &UndefElts, unsigned Depth) {
2463   EVT VT = V.getValueType();
2464   assert(VT.isVector() && "Vector type expected");
2465 
2466   if (!VT.isScalableVector() && !DemandedElts)
2467     return false; // No demanded elts, better to assume we don't know anything.
2468 
2469   if (Depth >= MaxRecursionDepth)
2470     return false; // Limit search depth.
2471 
2472   // Deal with some common cases here that work for both fixed and scalable
2473   // vector types.
2474   switch (V.getOpcode()) {
2475   case ISD::SPLAT_VECTOR:
2476     UndefElts = V.getOperand(0).isUndef()
2477                     ? APInt::getAllOnesValue(DemandedElts.getBitWidth())
2478                     : APInt(DemandedElts.getBitWidth(), 0);
2479     return true;
2480   case ISD::ADD:
2481   case ISD::SUB:
2482   case ISD::AND:
2483   case ISD::XOR:
2484   case ISD::OR: {
2485     APInt UndefLHS, UndefRHS;
2486     SDValue LHS = V.getOperand(0);
2487     SDValue RHS = V.getOperand(1);
2488     if (isSplatValue(LHS, DemandedElts, UndefLHS, Depth + 1) &&
2489         isSplatValue(RHS, DemandedElts, UndefRHS, Depth + 1)) {
2490       UndefElts = UndefLHS | UndefRHS;
2491       return true;
2492     }
2493     return false;
2494   }
2495   case ISD::ABS:
2496   case ISD::TRUNCATE:
2497   case ISD::SIGN_EXTEND:
2498   case ISD::ZERO_EXTEND:
2499     return isSplatValue(V.getOperand(0), DemandedElts, UndefElts, Depth + 1);
2500   }
2501 
2502   // We don't support other cases than those above for scalable vectors at
2503   // the moment.
2504   if (VT.isScalableVector())
2505     return false;
2506 
2507   unsigned NumElts = VT.getVectorNumElements();
2508   assert(NumElts == DemandedElts.getBitWidth() && "Vector size mismatch");
2509   UndefElts = APInt::getNullValue(NumElts);
2510 
2511   switch (V.getOpcode()) {
2512   case ISD::BUILD_VECTOR: {
2513     SDValue Scl;
2514     for (unsigned i = 0; i != NumElts; ++i) {
2515       SDValue Op = V.getOperand(i);
2516       if (Op.isUndef()) {
2517         UndefElts.setBit(i);
2518         continue;
2519       }
2520       if (!DemandedElts[i])
2521         continue;
2522       if (Scl && Scl != Op)
2523         return false;
2524       Scl = Op;
2525     }
2526     return true;
2527   }
2528   case ISD::VECTOR_SHUFFLE: {
2529     // Check if this is a shuffle node doing a splat.
2530     // TODO: Do we need to handle shuffle(splat, undef, mask)?
2531     int SplatIndex = -1;
2532     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(V)->getMask();
2533     for (int i = 0; i != (int)NumElts; ++i) {
2534       int M = Mask[i];
2535       if (M < 0) {
2536         UndefElts.setBit(i);
2537         continue;
2538       }
2539       if (!DemandedElts[i])
2540         continue;
2541       if (0 <= SplatIndex && SplatIndex != M)
2542         return false;
2543       SplatIndex = M;
2544     }
2545     return true;
2546   }
2547   case ISD::EXTRACT_SUBVECTOR: {
2548     // Offset the demanded elts by the subvector index.
2549     SDValue Src = V.getOperand(0);
2550     // We don't support scalable vectors at the moment.
2551     if (Src.getValueType().isScalableVector())
2552       return false;
2553     uint64_t Idx = V.getConstantOperandVal(1);
2554     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
2555     APInt UndefSrcElts;
2556     APInt DemandedSrcElts = DemandedElts.zextOrSelf(NumSrcElts).shl(Idx);
2557     if (isSplatValue(Src, DemandedSrcElts, UndefSrcElts, Depth + 1)) {
2558       UndefElts = UndefSrcElts.extractBits(NumElts, Idx);
2559       return true;
2560     }
2561     break;
2562   }
2563   }
2564 
2565   return false;
2566 }
2567 
2568 /// Helper wrapper to main isSplatValue function.
2569 bool SelectionDAG::isSplatValue(SDValue V, bool AllowUndefs) {
2570   EVT VT = V.getValueType();
2571   assert(VT.isVector() && "Vector type expected");
2572 
2573   APInt UndefElts;
2574   APInt DemandedElts;
2575 
2576   // For now we don't support this with scalable vectors.
2577   if (!VT.isScalableVector())
2578     DemandedElts = APInt::getAllOnesValue(VT.getVectorNumElements());
2579   return isSplatValue(V, DemandedElts, UndefElts) &&
2580          (AllowUndefs || !UndefElts);
2581 }
2582 
2583 SDValue SelectionDAG::getSplatSourceVector(SDValue V, int &SplatIdx) {
2584   V = peekThroughExtractSubvectors(V);
2585 
2586   EVT VT = V.getValueType();
2587   unsigned Opcode = V.getOpcode();
2588   switch (Opcode) {
2589   default: {
2590     APInt UndefElts;
2591     APInt DemandedElts;
2592 
2593     if (!VT.isScalableVector())
2594       DemandedElts = APInt::getAllOnesValue(VT.getVectorNumElements());
2595 
2596     if (isSplatValue(V, DemandedElts, UndefElts)) {
2597       if (VT.isScalableVector()) {
2598         // DemandedElts and UndefElts are ignored for scalable vectors, since
2599         // the only supported cases are SPLAT_VECTOR nodes.
2600         SplatIdx = 0;
2601       } else {
2602         // Handle case where all demanded elements are UNDEF.
2603         if (DemandedElts.isSubsetOf(UndefElts)) {
2604           SplatIdx = 0;
2605           return getUNDEF(VT);
2606         }
2607         SplatIdx = (UndefElts & DemandedElts).countTrailingOnes();
2608       }
2609       return V;
2610     }
2611     break;
2612   }
2613   case ISD::SPLAT_VECTOR:
2614     SplatIdx = 0;
2615     return V;
2616   case ISD::VECTOR_SHUFFLE: {
2617     if (VT.isScalableVector())
2618       return SDValue();
2619 
2620     // Check if this is a shuffle node doing a splat.
2621     // TODO - remove this and rely purely on SelectionDAG::isSplatValue,
2622     // getTargetVShiftNode currently struggles without the splat source.
2623     auto *SVN = cast<ShuffleVectorSDNode>(V);
2624     if (!SVN->isSplat())
2625       break;
2626     int Idx = SVN->getSplatIndex();
2627     int NumElts = V.getValueType().getVectorNumElements();
2628     SplatIdx = Idx % NumElts;
2629     return V.getOperand(Idx / NumElts);
2630   }
2631   }
2632 
2633   return SDValue();
2634 }
2635 
2636 SDValue SelectionDAG::getSplatValue(SDValue V, bool LegalTypes) {
2637   int SplatIdx;
2638   if (SDValue SrcVector = getSplatSourceVector(V, SplatIdx)) {
2639     EVT SVT = SrcVector.getValueType().getScalarType();
2640     EVT LegalSVT = SVT;
2641     if (LegalTypes && !TLI->isTypeLegal(SVT)) {
2642       if (!SVT.isInteger())
2643         return SDValue();
2644       LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT);
2645       if (LegalSVT.bitsLT(SVT))
2646         return SDValue();
2647     }
2648     return getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(V), LegalSVT, SrcVector,
2649                    getVectorIdxConstant(SplatIdx, SDLoc(V)));
2650   }
2651   return SDValue();
2652 }
2653 
2654 const APInt *
2655 SelectionDAG::getValidShiftAmountConstant(SDValue V,
2656                                           const APInt &DemandedElts) const {
2657   assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL ||
2658           V.getOpcode() == ISD::SRA) &&
2659          "Unknown shift node");
2660   unsigned BitWidth = V.getScalarValueSizeInBits();
2661   if (ConstantSDNode *SA = isConstOrConstSplat(V.getOperand(1), DemandedElts)) {
2662     // Shifting more than the bitwidth is not valid.
2663     const APInt &ShAmt = SA->getAPIntValue();
2664     if (ShAmt.ult(BitWidth))
2665       return &ShAmt;
2666   }
2667   return nullptr;
2668 }
2669 
2670 const APInt *SelectionDAG::getValidMinimumShiftAmountConstant(
2671     SDValue V, const APInt &DemandedElts) const {
2672   assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL ||
2673           V.getOpcode() == ISD::SRA) &&
2674          "Unknown shift node");
2675   if (const APInt *ValidAmt = getValidShiftAmountConstant(V, DemandedElts))
2676     return ValidAmt;
2677   unsigned BitWidth = V.getScalarValueSizeInBits();
2678   auto *BV = dyn_cast<BuildVectorSDNode>(V.getOperand(1));
2679   if (!BV)
2680     return nullptr;
2681   const APInt *MinShAmt = nullptr;
2682   for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
2683     if (!DemandedElts[i])
2684       continue;
2685     auto *SA = dyn_cast<ConstantSDNode>(BV->getOperand(i));
2686     if (!SA)
2687       return nullptr;
2688     // Shifting more than the bitwidth is not valid.
2689     const APInt &ShAmt = SA->getAPIntValue();
2690     if (ShAmt.uge(BitWidth))
2691       return nullptr;
2692     if (MinShAmt && MinShAmt->ule(ShAmt))
2693       continue;
2694     MinShAmt = &ShAmt;
2695   }
2696   return MinShAmt;
2697 }
2698 
2699 const APInt *SelectionDAG::getValidMaximumShiftAmountConstant(
2700     SDValue V, const APInt &DemandedElts) const {
2701   assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL ||
2702           V.getOpcode() == ISD::SRA) &&
2703          "Unknown shift node");
2704   if (const APInt *ValidAmt = getValidShiftAmountConstant(V, DemandedElts))
2705     return ValidAmt;
2706   unsigned BitWidth = V.getScalarValueSizeInBits();
2707   auto *BV = dyn_cast<BuildVectorSDNode>(V.getOperand(1));
2708   if (!BV)
2709     return nullptr;
2710   const APInt *MaxShAmt = nullptr;
2711   for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
2712     if (!DemandedElts[i])
2713       continue;
2714     auto *SA = dyn_cast<ConstantSDNode>(BV->getOperand(i));
2715     if (!SA)
2716       return nullptr;
2717     // Shifting more than the bitwidth is not valid.
2718     const APInt &ShAmt = SA->getAPIntValue();
2719     if (ShAmt.uge(BitWidth))
2720       return nullptr;
2721     if (MaxShAmt && MaxShAmt->uge(ShAmt))
2722       continue;
2723     MaxShAmt = &ShAmt;
2724   }
2725   return MaxShAmt;
2726 }
2727 
2728 /// Determine which bits of Op are known to be either zero or one and return
2729 /// them in Known. For vectors, the known bits are those that are shared by
2730 /// every vector element.
2731 KnownBits SelectionDAG::computeKnownBits(SDValue Op, unsigned Depth) const {
2732   EVT VT = Op.getValueType();
2733 
2734   // TOOD: Until we have a plan for how to represent demanded elements for
2735   // scalable vectors, we can just bail out for now.
2736   if (Op.getValueType().isScalableVector()) {
2737     unsigned BitWidth = Op.getScalarValueSizeInBits();
2738     return KnownBits(BitWidth);
2739   }
2740 
2741   APInt DemandedElts = VT.isVector()
2742                            ? APInt::getAllOnesValue(VT.getVectorNumElements())
2743                            : APInt(1, 1);
2744   return computeKnownBits(Op, DemandedElts, Depth);
2745 }
2746 
2747 /// Determine which bits of Op are known to be either zero or one and return
2748 /// them in Known. The DemandedElts argument allows us to only collect the known
2749 /// bits that are shared by the requested vector elements.
2750 KnownBits SelectionDAG::computeKnownBits(SDValue Op, const APInt &DemandedElts,
2751                                          unsigned Depth) const {
2752   unsigned BitWidth = Op.getScalarValueSizeInBits();
2753 
2754   KnownBits Known(BitWidth);   // Don't know anything.
2755 
2756   // TOOD: Until we have a plan for how to represent demanded elements for
2757   // scalable vectors, we can just bail out for now.
2758   if (Op.getValueType().isScalableVector())
2759     return Known;
2760 
2761   if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
2762     // We know all of the bits for a constant!
2763     return KnownBits::makeConstant(C->getAPIntValue());
2764   }
2765   if (auto *C = dyn_cast<ConstantFPSDNode>(Op)) {
2766     // We know all of the bits for a constant fp!
2767     return KnownBits::makeConstant(C->getValueAPF().bitcastToAPInt());
2768   }
2769 
2770   if (Depth >= MaxRecursionDepth)
2771     return Known;  // Limit search depth.
2772 
2773   KnownBits Known2;
2774   unsigned NumElts = DemandedElts.getBitWidth();
2775   assert((!Op.getValueType().isVector() ||
2776           NumElts == Op.getValueType().getVectorNumElements()) &&
2777          "Unexpected vector size");
2778 
2779   if (!DemandedElts)
2780     return Known;  // No demanded elts, better to assume we don't know anything.
2781 
2782   unsigned Opcode = Op.getOpcode();
2783   switch (Opcode) {
2784   case ISD::BUILD_VECTOR:
2785     // Collect the known bits that are shared by every demanded vector element.
2786     Known.Zero.setAllBits(); Known.One.setAllBits();
2787     for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
2788       if (!DemandedElts[i])
2789         continue;
2790 
2791       SDValue SrcOp = Op.getOperand(i);
2792       Known2 = computeKnownBits(SrcOp, Depth + 1);
2793 
2794       // BUILD_VECTOR can implicitly truncate sources, we must handle this.
2795       if (SrcOp.getValueSizeInBits() != BitWidth) {
2796         assert(SrcOp.getValueSizeInBits() > BitWidth &&
2797                "Expected BUILD_VECTOR implicit truncation");
2798         Known2 = Known2.trunc(BitWidth);
2799       }
2800 
2801       // Known bits are the values that are shared by every demanded element.
2802       Known = KnownBits::commonBits(Known, Known2);
2803 
2804       // If we don't know any bits, early out.
2805       if (Known.isUnknown())
2806         break;
2807     }
2808     break;
2809   case ISD::VECTOR_SHUFFLE: {
2810     // Collect the known bits that are shared by every vector element referenced
2811     // by the shuffle.
2812     APInt DemandedLHS(NumElts, 0), DemandedRHS(NumElts, 0);
2813     Known.Zero.setAllBits(); Known.One.setAllBits();
2814     const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op);
2815     assert(NumElts == SVN->getMask().size() && "Unexpected vector size");
2816     for (unsigned i = 0; i != NumElts; ++i) {
2817       if (!DemandedElts[i])
2818         continue;
2819 
2820       int M = SVN->getMaskElt(i);
2821       if (M < 0) {
2822         // For UNDEF elements, we don't know anything about the common state of
2823         // the shuffle result.
2824         Known.resetAll();
2825         DemandedLHS.clearAllBits();
2826         DemandedRHS.clearAllBits();
2827         break;
2828       }
2829 
2830       if ((unsigned)M < NumElts)
2831         DemandedLHS.setBit((unsigned)M % NumElts);
2832       else
2833         DemandedRHS.setBit((unsigned)M % NumElts);
2834     }
2835     // Known bits are the values that are shared by every demanded element.
2836     if (!!DemandedLHS) {
2837       SDValue LHS = Op.getOperand(0);
2838       Known2 = computeKnownBits(LHS, DemandedLHS, Depth + 1);
2839       Known = KnownBits::commonBits(Known, Known2);
2840     }
2841     // If we don't know any bits, early out.
2842     if (Known.isUnknown())
2843       break;
2844     if (!!DemandedRHS) {
2845       SDValue RHS = Op.getOperand(1);
2846       Known2 = computeKnownBits(RHS, DemandedRHS, Depth + 1);
2847       Known = KnownBits::commonBits(Known, Known2);
2848     }
2849     break;
2850   }
2851   case ISD::CONCAT_VECTORS: {
2852     // Split DemandedElts and test each of the demanded subvectors.
2853     Known.Zero.setAllBits(); Known.One.setAllBits();
2854     EVT SubVectorVT = Op.getOperand(0).getValueType();
2855     unsigned NumSubVectorElts = SubVectorVT.getVectorNumElements();
2856     unsigned NumSubVectors = Op.getNumOperands();
2857     for (unsigned i = 0; i != NumSubVectors; ++i) {
2858       APInt DemandedSub =
2859           DemandedElts.extractBits(NumSubVectorElts, i * NumSubVectorElts);
2860       if (!!DemandedSub) {
2861         SDValue Sub = Op.getOperand(i);
2862         Known2 = computeKnownBits(Sub, DemandedSub, Depth + 1);
2863         Known = KnownBits::commonBits(Known, Known2);
2864       }
2865       // If we don't know any bits, early out.
2866       if (Known.isUnknown())
2867         break;
2868     }
2869     break;
2870   }
2871   case ISD::INSERT_SUBVECTOR: {
2872     // Demand any elements from the subvector and the remainder from the src its
2873     // inserted into.
2874     SDValue Src = Op.getOperand(0);
2875     SDValue Sub = Op.getOperand(1);
2876     uint64_t Idx = Op.getConstantOperandVal(2);
2877     unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
2878     APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
2879     APInt DemandedSrcElts = DemandedElts;
2880     DemandedSrcElts.insertBits(APInt::getNullValue(NumSubElts), Idx);
2881 
2882     Known.One.setAllBits();
2883     Known.Zero.setAllBits();
2884     if (!!DemandedSubElts) {
2885       Known = computeKnownBits(Sub, DemandedSubElts, Depth + 1);
2886       if (Known.isUnknown())
2887         break; // early-out.
2888     }
2889     if (!!DemandedSrcElts) {
2890       Known2 = computeKnownBits(Src, DemandedSrcElts, Depth + 1);
2891       Known = KnownBits::commonBits(Known, Known2);
2892     }
2893     break;
2894   }
2895   case ISD::EXTRACT_SUBVECTOR: {
2896     // Offset the demanded elts by the subvector index.
2897     SDValue Src = Op.getOperand(0);
2898     // Bail until we can represent demanded elements for scalable vectors.
2899     if (Src.getValueType().isScalableVector())
2900       break;
2901     uint64_t Idx = Op.getConstantOperandVal(1);
2902     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
2903     APInt DemandedSrcElts = DemandedElts.zextOrSelf(NumSrcElts).shl(Idx);
2904     Known = computeKnownBits(Src, DemandedSrcElts, Depth + 1);
2905     break;
2906   }
2907   case ISD::SCALAR_TO_VECTOR: {
2908     // We know about scalar_to_vector as much as we know about it source,
2909     // which becomes the first element of otherwise unknown vector.
2910     if (DemandedElts != 1)
2911       break;
2912 
2913     SDValue N0 = Op.getOperand(0);
2914     Known = computeKnownBits(N0, Depth + 1);
2915     if (N0.getValueSizeInBits() != BitWidth)
2916       Known = Known.trunc(BitWidth);
2917 
2918     break;
2919   }
2920   case ISD::BITCAST: {
2921     SDValue N0 = Op.getOperand(0);
2922     EVT SubVT = N0.getValueType();
2923     unsigned SubBitWidth = SubVT.getScalarSizeInBits();
2924 
2925     // Ignore bitcasts from unsupported types.
2926     if (!(SubVT.isInteger() || SubVT.isFloatingPoint()))
2927       break;
2928 
2929     // Fast handling of 'identity' bitcasts.
2930     if (BitWidth == SubBitWidth) {
2931       Known = computeKnownBits(N0, DemandedElts, Depth + 1);
2932       break;
2933     }
2934 
2935     bool IsLE = getDataLayout().isLittleEndian();
2936 
2937     // Bitcast 'small element' vector to 'large element' scalar/vector.
2938     if ((BitWidth % SubBitWidth) == 0) {
2939       assert(N0.getValueType().isVector() && "Expected bitcast from vector");
2940 
2941       // Collect known bits for the (larger) output by collecting the known
2942       // bits from each set of sub elements and shift these into place.
2943       // We need to separately call computeKnownBits for each set of
2944       // sub elements as the knownbits for each is likely to be different.
2945       unsigned SubScale = BitWidth / SubBitWidth;
2946       APInt SubDemandedElts(NumElts * SubScale, 0);
2947       for (unsigned i = 0; i != NumElts; ++i)
2948         if (DemandedElts[i])
2949           SubDemandedElts.setBit(i * SubScale);
2950 
2951       for (unsigned i = 0; i != SubScale; ++i) {
2952         Known2 = computeKnownBits(N0, SubDemandedElts.shl(i),
2953                          Depth + 1);
2954         unsigned Shifts = IsLE ? i : SubScale - 1 - i;
2955         Known.insertBits(Known2, SubBitWidth * Shifts);
2956       }
2957     }
2958 
2959     // Bitcast 'large element' scalar/vector to 'small element' vector.
2960     if ((SubBitWidth % BitWidth) == 0) {
2961       assert(Op.getValueType().isVector() && "Expected bitcast to vector");
2962 
2963       // Collect known bits for the (smaller) output by collecting the known
2964       // bits from the overlapping larger input elements and extracting the
2965       // sub sections we actually care about.
2966       unsigned SubScale = SubBitWidth / BitWidth;
2967       APInt SubDemandedElts(NumElts / SubScale, 0);
2968       for (unsigned i = 0; i != NumElts; ++i)
2969         if (DemandedElts[i])
2970           SubDemandedElts.setBit(i / SubScale);
2971 
2972       Known2 = computeKnownBits(N0, SubDemandedElts, Depth + 1);
2973 
2974       Known.Zero.setAllBits(); Known.One.setAllBits();
2975       for (unsigned i = 0; i != NumElts; ++i)
2976         if (DemandedElts[i]) {
2977           unsigned Shifts = IsLE ? i : NumElts - 1 - i;
2978           unsigned Offset = (Shifts % SubScale) * BitWidth;
2979           Known = KnownBits::commonBits(Known,
2980                                         Known2.extractBits(BitWidth, Offset));
2981           // If we don't know any bits, early out.
2982           if (Known.isUnknown())
2983             break;
2984         }
2985     }
2986     break;
2987   }
2988   case ISD::AND:
2989     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
2990     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
2991 
2992     Known &= Known2;
2993     break;
2994   case ISD::OR:
2995     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
2996     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
2997 
2998     Known |= Known2;
2999     break;
3000   case ISD::XOR:
3001     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3002     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3003 
3004     Known ^= Known2;
3005     break;
3006   case ISD::MUL: {
3007     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3008     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3009     Known = KnownBits::mul(Known, Known2);
3010     break;
3011   }
3012   case ISD::MULHU: {
3013     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3014     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3015     Known = KnownBits::mulhu(Known, Known2);
3016     break;
3017   }
3018   case ISD::MULHS: {
3019     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3020     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3021     Known = KnownBits::mulhs(Known, Known2);
3022     break;
3023   }
3024   case ISD::UMUL_LOHI: {
3025     assert((Op.getResNo() == 0 || Op.getResNo() == 1) && "Unknown result");
3026     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3027     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3028     if (Op.getResNo() == 0)
3029       Known = KnownBits::mul(Known, Known2);
3030     else
3031       Known = KnownBits::mulhu(Known, Known2);
3032     break;
3033   }
3034   case ISD::SMUL_LOHI: {
3035     assert((Op.getResNo() == 0 || Op.getResNo() == 1) && "Unknown result");
3036     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3037     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3038     if (Op.getResNo() == 0)
3039       Known = KnownBits::mul(Known, Known2);
3040     else
3041       Known = KnownBits::mulhs(Known, Known2);
3042     break;
3043   }
3044   case ISD::UDIV: {
3045     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3046     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3047     Known = KnownBits::udiv(Known, Known2);
3048     break;
3049   }
3050   case ISD::SELECT:
3051   case ISD::VSELECT:
3052     Known = computeKnownBits(Op.getOperand(2), DemandedElts, Depth+1);
3053     // If we don't know any bits, early out.
3054     if (Known.isUnknown())
3055       break;
3056     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth+1);
3057 
3058     // Only known if known in both the LHS and RHS.
3059     Known = KnownBits::commonBits(Known, Known2);
3060     break;
3061   case ISD::SELECT_CC:
3062     Known = computeKnownBits(Op.getOperand(3), DemandedElts, Depth+1);
3063     // If we don't know any bits, early out.
3064     if (Known.isUnknown())
3065       break;
3066     Known2 = computeKnownBits(Op.getOperand(2), DemandedElts, Depth+1);
3067 
3068     // Only known if known in both the LHS and RHS.
3069     Known = KnownBits::commonBits(Known, Known2);
3070     break;
3071   case ISD::SMULO:
3072   case ISD::UMULO:
3073     if (Op.getResNo() != 1)
3074       break;
3075     // The boolean result conforms to getBooleanContents.
3076     // If we know the result of a setcc has the top bits zero, use this info.
3077     // We know that we have an integer-based boolean since these operations
3078     // are only available for integer.
3079     if (TLI->getBooleanContents(Op.getValueType().isVector(), false) ==
3080             TargetLowering::ZeroOrOneBooleanContent &&
3081         BitWidth > 1)
3082       Known.Zero.setBitsFrom(1);
3083     break;
3084   case ISD::SETCC:
3085   case ISD::STRICT_FSETCC:
3086   case ISD::STRICT_FSETCCS: {
3087     unsigned OpNo = Op->isStrictFPOpcode() ? 1 : 0;
3088     // If we know the result of a setcc has the top bits zero, use this info.
3089     if (TLI->getBooleanContents(Op.getOperand(OpNo).getValueType()) ==
3090             TargetLowering::ZeroOrOneBooleanContent &&
3091         BitWidth > 1)
3092       Known.Zero.setBitsFrom(1);
3093     break;
3094   }
3095   case ISD::SHL:
3096     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3097     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3098     Known = KnownBits::shl(Known, Known2);
3099 
3100     // Minimum shift low bits are known zero.
3101     if (const APInt *ShMinAmt =
3102             getValidMinimumShiftAmountConstant(Op, DemandedElts))
3103       Known.Zero.setLowBits(ShMinAmt->getZExtValue());
3104     break;
3105   case ISD::SRL:
3106     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3107     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3108     Known = KnownBits::lshr(Known, Known2);
3109 
3110     // Minimum shift high bits are known zero.
3111     if (const APInt *ShMinAmt =
3112             getValidMinimumShiftAmountConstant(Op, DemandedElts))
3113       Known.Zero.setHighBits(ShMinAmt->getZExtValue());
3114     break;
3115   case ISD::SRA:
3116     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3117     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3118     Known = KnownBits::ashr(Known, Known2);
3119     // TODO: Add minimum shift high known sign bits.
3120     break;
3121   case ISD::FSHL:
3122   case ISD::FSHR:
3123     if (ConstantSDNode *C = isConstOrConstSplat(Op.getOperand(2), DemandedElts)) {
3124       unsigned Amt = C->getAPIntValue().urem(BitWidth);
3125 
3126       // For fshl, 0-shift returns the 1st arg.
3127       // For fshr, 0-shift returns the 2nd arg.
3128       if (Amt == 0) {
3129         Known = computeKnownBits(Op.getOperand(Opcode == ISD::FSHL ? 0 : 1),
3130                                  DemandedElts, Depth + 1);
3131         break;
3132       }
3133 
3134       // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW)))
3135       // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW))
3136       Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3137       Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3138       if (Opcode == ISD::FSHL) {
3139         Known.One <<= Amt;
3140         Known.Zero <<= Amt;
3141         Known2.One.lshrInPlace(BitWidth - Amt);
3142         Known2.Zero.lshrInPlace(BitWidth - Amt);
3143       } else {
3144         Known.One <<= BitWidth - Amt;
3145         Known.Zero <<= BitWidth - Amt;
3146         Known2.One.lshrInPlace(Amt);
3147         Known2.Zero.lshrInPlace(Amt);
3148       }
3149       Known.One |= Known2.One;
3150       Known.Zero |= Known2.Zero;
3151     }
3152     break;
3153   case ISD::SIGN_EXTEND_INREG: {
3154     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3155     EVT EVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
3156     Known = Known.sextInReg(EVT.getScalarSizeInBits());
3157     break;
3158   }
3159   case ISD::CTTZ:
3160   case ISD::CTTZ_ZERO_UNDEF: {
3161     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3162     // If we have a known 1, its position is our upper bound.
3163     unsigned PossibleTZ = Known2.countMaxTrailingZeros();
3164     unsigned LowBits = Log2_32(PossibleTZ) + 1;
3165     Known.Zero.setBitsFrom(LowBits);
3166     break;
3167   }
3168   case ISD::CTLZ:
3169   case ISD::CTLZ_ZERO_UNDEF: {
3170     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3171     // If we have a known 1, its position is our upper bound.
3172     unsigned PossibleLZ = Known2.countMaxLeadingZeros();
3173     unsigned LowBits = Log2_32(PossibleLZ) + 1;
3174     Known.Zero.setBitsFrom(LowBits);
3175     break;
3176   }
3177   case ISD::CTPOP: {
3178     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3179     // If we know some of the bits are zero, they can't be one.
3180     unsigned PossibleOnes = Known2.countMaxPopulation();
3181     Known.Zero.setBitsFrom(Log2_32(PossibleOnes) + 1);
3182     break;
3183   }
3184   case ISD::PARITY: {
3185     // Parity returns 0 everywhere but the LSB.
3186     Known.Zero.setBitsFrom(1);
3187     break;
3188   }
3189   case ISD::LOAD: {
3190     LoadSDNode *LD = cast<LoadSDNode>(Op);
3191     const Constant *Cst = TLI->getTargetConstantFromLoad(LD);
3192     if (ISD::isNON_EXTLoad(LD) && Cst) {
3193       // Determine any common known bits from the loaded constant pool value.
3194       Type *CstTy = Cst->getType();
3195       if ((NumElts * BitWidth) == CstTy->getPrimitiveSizeInBits()) {
3196         // If its a vector splat, then we can (quickly) reuse the scalar path.
3197         // NOTE: We assume all elements match and none are UNDEF.
3198         if (CstTy->isVectorTy()) {
3199           if (const Constant *Splat = Cst->getSplatValue()) {
3200             Cst = Splat;
3201             CstTy = Cst->getType();
3202           }
3203         }
3204         // TODO - do we need to handle different bitwidths?
3205         if (CstTy->isVectorTy() && BitWidth == CstTy->getScalarSizeInBits()) {
3206           // Iterate across all vector elements finding common known bits.
3207           Known.One.setAllBits();
3208           Known.Zero.setAllBits();
3209           for (unsigned i = 0; i != NumElts; ++i) {
3210             if (!DemandedElts[i])
3211               continue;
3212             if (Constant *Elt = Cst->getAggregateElement(i)) {
3213               if (auto *CInt = dyn_cast<ConstantInt>(Elt)) {
3214                 const APInt &Value = CInt->getValue();
3215                 Known.One &= Value;
3216                 Known.Zero &= ~Value;
3217                 continue;
3218               }
3219               if (auto *CFP = dyn_cast<ConstantFP>(Elt)) {
3220                 APInt Value = CFP->getValueAPF().bitcastToAPInt();
3221                 Known.One &= Value;
3222                 Known.Zero &= ~Value;
3223                 continue;
3224               }
3225             }
3226             Known.One.clearAllBits();
3227             Known.Zero.clearAllBits();
3228             break;
3229           }
3230         } else if (BitWidth == CstTy->getPrimitiveSizeInBits()) {
3231           if (auto *CInt = dyn_cast<ConstantInt>(Cst)) {
3232             Known = KnownBits::makeConstant(CInt->getValue());
3233           } else if (auto *CFP = dyn_cast<ConstantFP>(Cst)) {
3234             Known =
3235                 KnownBits::makeConstant(CFP->getValueAPF().bitcastToAPInt());
3236           }
3237         }
3238       }
3239     } else if (ISD::isZEXTLoad(Op.getNode()) && Op.getResNo() == 0) {
3240       // If this is a ZEXTLoad and we are looking at the loaded value.
3241       EVT VT = LD->getMemoryVT();
3242       unsigned MemBits = VT.getScalarSizeInBits();
3243       Known.Zero.setBitsFrom(MemBits);
3244     } else if (const MDNode *Ranges = LD->getRanges()) {
3245       if (LD->getExtensionType() == ISD::NON_EXTLOAD)
3246         computeKnownBitsFromRangeMetadata(*Ranges, Known);
3247     }
3248     break;
3249   }
3250   case ISD::ZERO_EXTEND_VECTOR_INREG: {
3251     EVT InVT = Op.getOperand(0).getValueType();
3252     APInt InDemandedElts = DemandedElts.zextOrSelf(InVT.getVectorNumElements());
3253     Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1);
3254     Known = Known.zext(BitWidth);
3255     break;
3256   }
3257   case ISD::ZERO_EXTEND: {
3258     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3259     Known = Known.zext(BitWidth);
3260     break;
3261   }
3262   case ISD::SIGN_EXTEND_VECTOR_INREG: {
3263     EVT InVT = Op.getOperand(0).getValueType();
3264     APInt InDemandedElts = DemandedElts.zextOrSelf(InVT.getVectorNumElements());
3265     Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1);
3266     // If the sign bit is known to be zero or one, then sext will extend
3267     // it to the top bits, else it will just zext.
3268     Known = Known.sext(BitWidth);
3269     break;
3270   }
3271   case ISD::SIGN_EXTEND: {
3272     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3273     // If the sign bit is known to be zero or one, then sext will extend
3274     // it to the top bits, else it will just zext.
3275     Known = Known.sext(BitWidth);
3276     break;
3277   }
3278   case ISD::ANY_EXTEND_VECTOR_INREG: {
3279     EVT InVT = Op.getOperand(0).getValueType();
3280     APInt InDemandedElts = DemandedElts.zextOrSelf(InVT.getVectorNumElements());
3281     Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1);
3282     Known = Known.anyext(BitWidth);
3283     break;
3284   }
3285   case ISD::ANY_EXTEND: {
3286     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3287     Known = Known.anyext(BitWidth);
3288     break;
3289   }
3290   case ISD::TRUNCATE: {
3291     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3292     Known = Known.trunc(BitWidth);
3293     break;
3294   }
3295   case ISD::AssertZext: {
3296     EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
3297     APInt InMask = APInt::getLowBitsSet(BitWidth, VT.getSizeInBits());
3298     Known = computeKnownBits(Op.getOperand(0), Depth+1);
3299     Known.Zero |= (~InMask);
3300     Known.One  &= (~Known.Zero);
3301     break;
3302   }
3303   case ISD::AssertAlign: {
3304     unsigned LogOfAlign = Log2(cast<AssertAlignSDNode>(Op)->getAlign());
3305     assert(LogOfAlign != 0);
3306     // If a node is guaranteed to be aligned, set low zero bits accordingly as
3307     // well as clearing one bits.
3308     Known.Zero.setLowBits(LogOfAlign);
3309     Known.One.clearLowBits(LogOfAlign);
3310     break;
3311   }
3312   case ISD::FGETSIGN:
3313     // All bits are zero except the low bit.
3314     Known.Zero.setBitsFrom(1);
3315     break;
3316   case ISD::USUBO:
3317   case ISD::SSUBO:
3318     if (Op.getResNo() == 1) {
3319       // If we know the result of a setcc has the top bits zero, use this info.
3320       if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) ==
3321               TargetLowering::ZeroOrOneBooleanContent &&
3322           BitWidth > 1)
3323         Known.Zero.setBitsFrom(1);
3324       break;
3325     }
3326     LLVM_FALLTHROUGH;
3327   case ISD::SUB:
3328   case ISD::SUBC: {
3329     assert(Op.getResNo() == 0 &&
3330            "We only compute knownbits for the difference here.");
3331 
3332     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3333     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3334     Known = KnownBits::computeForAddSub(/* Add */ false, /* NSW */ false,
3335                                         Known, Known2);
3336     break;
3337   }
3338   case ISD::UADDO:
3339   case ISD::SADDO:
3340   case ISD::ADDCARRY:
3341     if (Op.getResNo() == 1) {
3342       // If we know the result of a setcc has the top bits zero, use this info.
3343       if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) ==
3344               TargetLowering::ZeroOrOneBooleanContent &&
3345           BitWidth > 1)
3346         Known.Zero.setBitsFrom(1);
3347       break;
3348     }
3349     LLVM_FALLTHROUGH;
3350   case ISD::ADD:
3351   case ISD::ADDC:
3352   case ISD::ADDE: {
3353     assert(Op.getResNo() == 0 && "We only compute knownbits for the sum here.");
3354 
3355     // With ADDE and ADDCARRY, a carry bit may be added in.
3356     KnownBits Carry(1);
3357     if (Opcode == ISD::ADDE)
3358       // Can't track carry from glue, set carry to unknown.
3359       Carry.resetAll();
3360     else if (Opcode == ISD::ADDCARRY)
3361       // TODO: Compute known bits for the carry operand. Not sure if it is worth
3362       // the trouble (how often will we find a known carry bit). And I haven't
3363       // tested this very much yet, but something like this might work:
3364       //   Carry = computeKnownBits(Op.getOperand(2), DemandedElts, Depth + 1);
3365       //   Carry = Carry.zextOrTrunc(1, false);
3366       Carry.resetAll();
3367     else
3368       Carry.setAllZero();
3369 
3370     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3371     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3372     Known = KnownBits::computeForAddCarry(Known, Known2, Carry);
3373     break;
3374   }
3375   case ISD::SREM: {
3376     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3377     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3378     Known = KnownBits::srem(Known, Known2);
3379     break;
3380   }
3381   case ISD::UREM: {
3382     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3383     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3384     Known = KnownBits::urem(Known, Known2);
3385     break;
3386   }
3387   case ISD::EXTRACT_ELEMENT: {
3388     Known = computeKnownBits(Op.getOperand(0), Depth+1);
3389     const unsigned Index = Op.getConstantOperandVal(1);
3390     const unsigned EltBitWidth = Op.getValueSizeInBits();
3391 
3392     // Remove low part of known bits mask
3393     Known.Zero = Known.Zero.getHiBits(Known.getBitWidth() - Index * EltBitWidth);
3394     Known.One = Known.One.getHiBits(Known.getBitWidth() - Index * EltBitWidth);
3395 
3396     // Remove high part of known bit mask
3397     Known = Known.trunc(EltBitWidth);
3398     break;
3399   }
3400   case ISD::EXTRACT_VECTOR_ELT: {
3401     SDValue InVec = Op.getOperand(0);
3402     SDValue EltNo = Op.getOperand(1);
3403     EVT VecVT = InVec.getValueType();
3404     // computeKnownBits not yet implemented for scalable vectors.
3405     if (VecVT.isScalableVector())
3406       break;
3407     const unsigned EltBitWidth = VecVT.getScalarSizeInBits();
3408     const unsigned NumSrcElts = VecVT.getVectorNumElements();
3409 
3410     // If BitWidth > EltBitWidth the value is anyext:ed. So we do not know
3411     // anything about the extended bits.
3412     if (BitWidth > EltBitWidth)
3413       Known = Known.trunc(EltBitWidth);
3414 
3415     // If we know the element index, just demand that vector element, else for
3416     // an unknown element index, ignore DemandedElts and demand them all.
3417     APInt DemandedSrcElts = APInt::getAllOnesValue(NumSrcElts);
3418     auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
3419     if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts))
3420       DemandedSrcElts =
3421           APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue());
3422 
3423     Known = computeKnownBits(InVec, DemandedSrcElts, Depth + 1);
3424     if (BitWidth > EltBitWidth)
3425       Known = Known.anyext(BitWidth);
3426     break;
3427   }
3428   case ISD::INSERT_VECTOR_ELT: {
3429     // If we know the element index, split the demand between the
3430     // source vector and the inserted element, otherwise assume we need
3431     // the original demanded vector elements and the value.
3432     SDValue InVec = Op.getOperand(0);
3433     SDValue InVal = Op.getOperand(1);
3434     SDValue EltNo = Op.getOperand(2);
3435     bool DemandedVal = true;
3436     APInt DemandedVecElts = DemandedElts;
3437     auto *CEltNo = dyn_cast<ConstantSDNode>(EltNo);
3438     if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) {
3439       unsigned EltIdx = CEltNo->getZExtValue();
3440       DemandedVal = !!DemandedElts[EltIdx];
3441       DemandedVecElts.clearBit(EltIdx);
3442     }
3443     Known.One.setAllBits();
3444     Known.Zero.setAllBits();
3445     if (DemandedVal) {
3446       Known2 = computeKnownBits(InVal, Depth + 1);
3447       Known = KnownBits::commonBits(Known, Known2.zextOrTrunc(BitWidth));
3448     }
3449     if (!!DemandedVecElts) {
3450       Known2 = computeKnownBits(InVec, DemandedVecElts, Depth + 1);
3451       Known = KnownBits::commonBits(Known, Known2);
3452     }
3453     break;
3454   }
3455   case ISD::BITREVERSE: {
3456     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3457     Known = Known2.reverseBits();
3458     break;
3459   }
3460   case ISD::BSWAP: {
3461     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3462     Known = Known2.byteSwap();
3463     break;
3464   }
3465   case ISD::ABS: {
3466     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3467     Known = Known2.abs();
3468     break;
3469   }
3470   case ISD::USUBSAT: {
3471     // The result of usubsat will never be larger than the LHS.
3472     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3473     Known.Zero.setHighBits(Known2.countMinLeadingZeros());
3474     break;
3475   }
3476   case ISD::UMIN: {
3477     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3478     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3479     Known = KnownBits::umin(Known, Known2);
3480     break;
3481   }
3482   case ISD::UMAX: {
3483     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3484     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3485     Known = KnownBits::umax(Known, Known2);
3486     break;
3487   }
3488   case ISD::SMIN:
3489   case ISD::SMAX: {
3490     // If we have a clamp pattern, we know that the number of sign bits will be
3491     // the minimum of the clamp min/max range.
3492     bool IsMax = (Opcode == ISD::SMAX);
3493     ConstantSDNode *CstLow = nullptr, *CstHigh = nullptr;
3494     if ((CstLow = isConstOrConstSplat(Op.getOperand(1), DemandedElts)))
3495       if (Op.getOperand(0).getOpcode() == (IsMax ? ISD::SMIN : ISD::SMAX))
3496         CstHigh =
3497             isConstOrConstSplat(Op.getOperand(0).getOperand(1), DemandedElts);
3498     if (CstLow && CstHigh) {
3499       if (!IsMax)
3500         std::swap(CstLow, CstHigh);
3501 
3502       const APInt &ValueLow = CstLow->getAPIntValue();
3503       const APInt &ValueHigh = CstHigh->getAPIntValue();
3504       if (ValueLow.sle(ValueHigh)) {
3505         unsigned LowSignBits = ValueLow.getNumSignBits();
3506         unsigned HighSignBits = ValueHigh.getNumSignBits();
3507         unsigned MinSignBits = std::min(LowSignBits, HighSignBits);
3508         if (ValueLow.isNegative() && ValueHigh.isNegative()) {
3509           Known.One.setHighBits(MinSignBits);
3510           break;
3511         }
3512         if (ValueLow.isNonNegative() && ValueHigh.isNonNegative()) {
3513           Known.Zero.setHighBits(MinSignBits);
3514           break;
3515         }
3516       }
3517     }
3518 
3519     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3520     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3521     if (IsMax)
3522       Known = KnownBits::smax(Known, Known2);
3523     else
3524       Known = KnownBits::smin(Known, Known2);
3525     break;
3526   }
3527   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
3528     if (Op.getResNo() == 1) {
3529       // The boolean result conforms to getBooleanContents.
3530       // If we know the result of a setcc has the top bits zero, use this info.
3531       // We know that we have an integer-based boolean since these operations
3532       // are only available for integer.
3533       if (TLI->getBooleanContents(Op.getValueType().isVector(), false) ==
3534               TargetLowering::ZeroOrOneBooleanContent &&
3535           BitWidth > 1)
3536         Known.Zero.setBitsFrom(1);
3537       break;
3538     }
3539     LLVM_FALLTHROUGH;
3540   case ISD::ATOMIC_CMP_SWAP:
3541   case ISD::ATOMIC_SWAP:
3542   case ISD::ATOMIC_LOAD_ADD:
3543   case ISD::ATOMIC_LOAD_SUB:
3544   case ISD::ATOMIC_LOAD_AND:
3545   case ISD::ATOMIC_LOAD_CLR:
3546   case ISD::ATOMIC_LOAD_OR:
3547   case ISD::ATOMIC_LOAD_XOR:
3548   case ISD::ATOMIC_LOAD_NAND:
3549   case ISD::ATOMIC_LOAD_MIN:
3550   case ISD::ATOMIC_LOAD_MAX:
3551   case ISD::ATOMIC_LOAD_UMIN:
3552   case ISD::ATOMIC_LOAD_UMAX:
3553   case ISD::ATOMIC_LOAD: {
3554     unsigned MemBits =
3555         cast<AtomicSDNode>(Op)->getMemoryVT().getScalarSizeInBits();
3556     // If we are looking at the loaded value.
3557     if (Op.getResNo() == 0) {
3558       if (TLI->getExtendForAtomicOps() == ISD::ZERO_EXTEND)
3559         Known.Zero.setBitsFrom(MemBits);
3560     }
3561     break;
3562   }
3563   case ISD::FrameIndex:
3564   case ISD::TargetFrameIndex:
3565     TLI->computeKnownBitsForFrameIndex(cast<FrameIndexSDNode>(Op)->getIndex(),
3566                                        Known, getMachineFunction());
3567     break;
3568 
3569   default:
3570     if (Opcode < ISD::BUILTIN_OP_END)
3571       break;
3572     LLVM_FALLTHROUGH;
3573   case ISD::INTRINSIC_WO_CHAIN:
3574   case ISD::INTRINSIC_W_CHAIN:
3575   case ISD::INTRINSIC_VOID:
3576     // Allow the target to implement this method for its nodes.
3577     TLI->computeKnownBitsForTargetNode(Op, Known, DemandedElts, *this, Depth);
3578     break;
3579   }
3580 
3581   assert(!Known.hasConflict() && "Bits known to be one AND zero?");
3582   return Known;
3583 }
3584 
3585 SelectionDAG::OverflowKind SelectionDAG::computeOverflowKind(SDValue N0,
3586                                                              SDValue N1) const {
3587   // X + 0 never overflow
3588   if (isNullConstant(N1))
3589     return OFK_Never;
3590 
3591   KnownBits N1Known = computeKnownBits(N1);
3592   if (N1Known.Zero.getBoolValue()) {
3593     KnownBits N0Known = computeKnownBits(N0);
3594 
3595     bool overflow;
3596     (void)N0Known.getMaxValue().uadd_ov(N1Known.getMaxValue(), overflow);
3597     if (!overflow)
3598       return OFK_Never;
3599   }
3600 
3601   // mulhi + 1 never overflow
3602   if (N0.getOpcode() == ISD::UMUL_LOHI && N0.getResNo() == 1 &&
3603       (N1Known.getMaxValue() & 0x01) == N1Known.getMaxValue())
3604     return OFK_Never;
3605 
3606   if (N1.getOpcode() == ISD::UMUL_LOHI && N1.getResNo() == 1) {
3607     KnownBits N0Known = computeKnownBits(N0);
3608 
3609     if ((N0Known.getMaxValue() & 0x01) == N0Known.getMaxValue())
3610       return OFK_Never;
3611   }
3612 
3613   return OFK_Sometime;
3614 }
3615 
3616 bool SelectionDAG::isKnownToBeAPowerOfTwo(SDValue Val) const {
3617   EVT OpVT = Val.getValueType();
3618   unsigned BitWidth = OpVT.getScalarSizeInBits();
3619 
3620   // Is the constant a known power of 2?
3621   if (ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Val))
3622     return Const->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2();
3623 
3624   // A left-shift of a constant one will have exactly one bit set because
3625   // shifting the bit off the end is undefined.
3626   if (Val.getOpcode() == ISD::SHL) {
3627     auto *C = isConstOrConstSplat(Val.getOperand(0));
3628     if (C && C->getAPIntValue() == 1)
3629       return true;
3630   }
3631 
3632   // Similarly, a logical right-shift of a constant sign-bit will have exactly
3633   // one bit set.
3634   if (Val.getOpcode() == ISD::SRL) {
3635     auto *C = isConstOrConstSplat(Val.getOperand(0));
3636     if (C && C->getAPIntValue().isSignMask())
3637       return true;
3638   }
3639 
3640   // Are all operands of a build vector constant powers of two?
3641   if (Val.getOpcode() == ISD::BUILD_VECTOR)
3642     if (llvm::all_of(Val->ops(), [BitWidth](SDValue E) {
3643           if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(E))
3644             return C->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2();
3645           return false;
3646         }))
3647       return true;
3648 
3649   // More could be done here, though the above checks are enough
3650   // to handle some common cases.
3651 
3652   // Fall back to computeKnownBits to catch other known cases.
3653   KnownBits Known = computeKnownBits(Val);
3654   return (Known.countMaxPopulation() == 1) && (Known.countMinPopulation() == 1);
3655 }
3656 
3657 unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, unsigned Depth) const {
3658   EVT VT = Op.getValueType();
3659 
3660   // TODO: Assume we don't know anything for now.
3661   if (VT.isScalableVector())
3662     return 1;
3663 
3664   APInt DemandedElts = VT.isVector()
3665                            ? APInt::getAllOnesValue(VT.getVectorNumElements())
3666                            : APInt(1, 1);
3667   return ComputeNumSignBits(Op, DemandedElts, Depth);
3668 }
3669 
3670 unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, const APInt &DemandedElts,
3671                                           unsigned Depth) const {
3672   EVT VT = Op.getValueType();
3673   assert((VT.isInteger() || VT.isFloatingPoint()) && "Invalid VT!");
3674   unsigned VTBits = VT.getScalarSizeInBits();
3675   unsigned NumElts = DemandedElts.getBitWidth();
3676   unsigned Tmp, Tmp2;
3677   unsigned FirstAnswer = 1;
3678 
3679   if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
3680     const APInt &Val = C->getAPIntValue();
3681     return Val.getNumSignBits();
3682   }
3683 
3684   if (Depth >= MaxRecursionDepth)
3685     return 1;  // Limit search depth.
3686 
3687   if (!DemandedElts || VT.isScalableVector())
3688     return 1;  // No demanded elts, better to assume we don't know anything.
3689 
3690   unsigned Opcode = Op.getOpcode();
3691   switch (Opcode) {
3692   default: break;
3693   case ISD::AssertSext:
3694     Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
3695     return VTBits-Tmp+1;
3696   case ISD::AssertZext:
3697     Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
3698     return VTBits-Tmp;
3699 
3700   case ISD::BUILD_VECTOR:
3701     Tmp = VTBits;
3702     for (unsigned i = 0, e = Op.getNumOperands(); (i < e) && (Tmp > 1); ++i) {
3703       if (!DemandedElts[i])
3704         continue;
3705 
3706       SDValue SrcOp = Op.getOperand(i);
3707       Tmp2 = ComputeNumSignBits(SrcOp, Depth + 1);
3708 
3709       // BUILD_VECTOR can implicitly truncate sources, we must handle this.
3710       if (SrcOp.getValueSizeInBits() != VTBits) {
3711         assert(SrcOp.getValueSizeInBits() > VTBits &&
3712                "Expected BUILD_VECTOR implicit truncation");
3713         unsigned ExtraBits = SrcOp.getValueSizeInBits() - VTBits;
3714         Tmp2 = (Tmp2 > ExtraBits ? Tmp2 - ExtraBits : 1);
3715       }
3716       Tmp = std::min(Tmp, Tmp2);
3717     }
3718     return Tmp;
3719 
3720   case ISD::VECTOR_SHUFFLE: {
3721     // Collect the minimum number of sign bits that are shared by every vector
3722     // element referenced by the shuffle.
3723     APInt DemandedLHS(NumElts, 0), DemandedRHS(NumElts, 0);
3724     const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op);
3725     assert(NumElts == SVN->getMask().size() && "Unexpected vector size");
3726     for (unsigned i = 0; i != NumElts; ++i) {
3727       int M = SVN->getMaskElt(i);
3728       if (!DemandedElts[i])
3729         continue;
3730       // For UNDEF elements, we don't know anything about the common state of
3731       // the shuffle result.
3732       if (M < 0)
3733         return 1;
3734       if ((unsigned)M < NumElts)
3735         DemandedLHS.setBit((unsigned)M % NumElts);
3736       else
3737         DemandedRHS.setBit((unsigned)M % NumElts);
3738     }
3739     Tmp = std::numeric_limits<unsigned>::max();
3740     if (!!DemandedLHS)
3741       Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedLHS, Depth + 1);
3742     if (!!DemandedRHS) {
3743       Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedRHS, Depth + 1);
3744       Tmp = std::min(Tmp, Tmp2);
3745     }
3746     // If we don't know anything, early out and try computeKnownBits fall-back.
3747     if (Tmp == 1)
3748       break;
3749     assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
3750     return Tmp;
3751   }
3752 
3753   case ISD::BITCAST: {
3754     SDValue N0 = Op.getOperand(0);
3755     EVT SrcVT = N0.getValueType();
3756     unsigned SrcBits = SrcVT.getScalarSizeInBits();
3757 
3758     // Ignore bitcasts from unsupported types..
3759     if (!(SrcVT.isInteger() || SrcVT.isFloatingPoint()))
3760       break;
3761 
3762     // Fast handling of 'identity' bitcasts.
3763     if (VTBits == SrcBits)
3764       return ComputeNumSignBits(N0, DemandedElts, Depth + 1);
3765 
3766     bool IsLE = getDataLayout().isLittleEndian();
3767 
3768     // Bitcast 'large element' scalar/vector to 'small element' vector.
3769     if ((SrcBits % VTBits) == 0) {
3770       assert(VT.isVector() && "Expected bitcast to vector");
3771 
3772       unsigned Scale = SrcBits / VTBits;
3773       APInt SrcDemandedElts(NumElts / Scale, 0);
3774       for (unsigned i = 0; i != NumElts; ++i)
3775         if (DemandedElts[i])
3776           SrcDemandedElts.setBit(i / Scale);
3777 
3778       // Fast case - sign splat can be simply split across the small elements.
3779       Tmp = ComputeNumSignBits(N0, SrcDemandedElts, Depth + 1);
3780       if (Tmp == SrcBits)
3781         return VTBits;
3782 
3783       // Slow case - determine how far the sign extends into each sub-element.
3784       Tmp2 = VTBits;
3785       for (unsigned i = 0; i != NumElts; ++i)
3786         if (DemandedElts[i]) {
3787           unsigned SubOffset = i % Scale;
3788           SubOffset = (IsLE ? ((Scale - 1) - SubOffset) : SubOffset);
3789           SubOffset = SubOffset * VTBits;
3790           if (Tmp <= SubOffset)
3791             return 1;
3792           Tmp2 = std::min(Tmp2, Tmp - SubOffset);
3793         }
3794       return Tmp2;
3795     }
3796     break;
3797   }
3798 
3799   case ISD::SIGN_EXTEND:
3800     Tmp = VTBits - Op.getOperand(0).getScalarValueSizeInBits();
3801     return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1) + Tmp;
3802   case ISD::SIGN_EXTEND_INREG:
3803     // Max of the input and what this extends.
3804     Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getScalarSizeInBits();
3805     Tmp = VTBits-Tmp+1;
3806     Tmp2 = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1);
3807     return std::max(Tmp, Tmp2);
3808   case ISD::SIGN_EXTEND_VECTOR_INREG: {
3809     SDValue Src = Op.getOperand(0);
3810     EVT SrcVT = Src.getValueType();
3811     APInt DemandedSrcElts = DemandedElts.zextOrSelf(SrcVT.getVectorNumElements());
3812     Tmp = VTBits - SrcVT.getScalarSizeInBits();
3813     return ComputeNumSignBits(Src, DemandedSrcElts, Depth+1) + Tmp;
3814   }
3815   case ISD::SRA:
3816     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
3817     // SRA X, C -> adds C sign bits.
3818     if (const APInt *ShAmt =
3819             getValidMinimumShiftAmountConstant(Op, DemandedElts))
3820       Tmp = std::min<uint64_t>(Tmp + ShAmt->getZExtValue(), VTBits);
3821     return Tmp;
3822   case ISD::SHL:
3823     if (const APInt *ShAmt =
3824             getValidMaximumShiftAmountConstant(Op, DemandedElts)) {
3825       // shl destroys sign bits, ensure it doesn't shift out all sign bits.
3826       Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
3827       if (ShAmt->ult(Tmp))
3828         return Tmp - ShAmt->getZExtValue();
3829     }
3830     break;
3831   case ISD::AND:
3832   case ISD::OR:
3833   case ISD::XOR:    // NOT is handled here.
3834     // Logical binary ops preserve the number of sign bits at the worst.
3835     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1);
3836     if (Tmp != 1) {
3837       Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth+1);
3838       FirstAnswer = std::min(Tmp, Tmp2);
3839       // We computed what we know about the sign bits as our first
3840       // answer. Now proceed to the generic code that uses
3841       // computeKnownBits, and pick whichever answer is better.
3842     }
3843     break;
3844 
3845   case ISD::SELECT:
3846   case ISD::VSELECT:
3847     Tmp = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth+1);
3848     if (Tmp == 1) return 1;  // Early out.
3849     Tmp2 = ComputeNumSignBits(Op.getOperand(2), DemandedElts, Depth+1);
3850     return std::min(Tmp, Tmp2);
3851   case ISD::SELECT_CC:
3852     Tmp = ComputeNumSignBits(Op.getOperand(2), DemandedElts, Depth+1);
3853     if (Tmp == 1) return 1;  // Early out.
3854     Tmp2 = ComputeNumSignBits(Op.getOperand(3), DemandedElts, Depth+1);
3855     return std::min(Tmp, Tmp2);
3856 
3857   case ISD::SMIN:
3858   case ISD::SMAX: {
3859     // If we have a clamp pattern, we know that the number of sign bits will be
3860     // the minimum of the clamp min/max range.
3861     bool IsMax = (Opcode == ISD::SMAX);
3862     ConstantSDNode *CstLow = nullptr, *CstHigh = nullptr;
3863     if ((CstLow = isConstOrConstSplat(Op.getOperand(1), DemandedElts)))
3864       if (Op.getOperand(0).getOpcode() == (IsMax ? ISD::SMIN : ISD::SMAX))
3865         CstHigh =
3866             isConstOrConstSplat(Op.getOperand(0).getOperand(1), DemandedElts);
3867     if (CstLow && CstHigh) {
3868       if (!IsMax)
3869         std::swap(CstLow, CstHigh);
3870       if (CstLow->getAPIntValue().sle(CstHigh->getAPIntValue())) {
3871         Tmp = CstLow->getAPIntValue().getNumSignBits();
3872         Tmp2 = CstHigh->getAPIntValue().getNumSignBits();
3873         return std::min(Tmp, Tmp2);
3874       }
3875     }
3876 
3877     // Fallback - just get the minimum number of sign bits of the operands.
3878     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
3879     if (Tmp == 1)
3880       return 1;  // Early out.
3881     Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
3882     return std::min(Tmp, Tmp2);
3883   }
3884   case ISD::UMIN:
3885   case ISD::UMAX:
3886     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
3887     if (Tmp == 1)
3888       return 1;  // Early out.
3889     Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
3890     return std::min(Tmp, Tmp2);
3891   case ISD::SADDO:
3892   case ISD::UADDO:
3893   case ISD::SSUBO:
3894   case ISD::USUBO:
3895   case ISD::SMULO:
3896   case ISD::UMULO:
3897     if (Op.getResNo() != 1)
3898       break;
3899     // The boolean result conforms to getBooleanContents.  Fall through.
3900     // If setcc returns 0/-1, all bits are sign bits.
3901     // We know that we have an integer-based boolean since these operations
3902     // are only available for integer.
3903     if (TLI->getBooleanContents(VT.isVector(), false) ==
3904         TargetLowering::ZeroOrNegativeOneBooleanContent)
3905       return VTBits;
3906     break;
3907   case ISD::SETCC:
3908   case ISD::STRICT_FSETCC:
3909   case ISD::STRICT_FSETCCS: {
3910     unsigned OpNo = Op->isStrictFPOpcode() ? 1 : 0;
3911     // If setcc returns 0/-1, all bits are sign bits.
3912     if (TLI->getBooleanContents(Op.getOperand(OpNo).getValueType()) ==
3913         TargetLowering::ZeroOrNegativeOneBooleanContent)
3914       return VTBits;
3915     break;
3916   }
3917   case ISD::ROTL:
3918   case ISD::ROTR:
3919     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
3920 
3921     // If we're rotating an 0/-1 value, then it stays an 0/-1 value.
3922     if (Tmp == VTBits)
3923       return VTBits;
3924 
3925     if (ConstantSDNode *C =
3926             isConstOrConstSplat(Op.getOperand(1), DemandedElts)) {
3927       unsigned RotAmt = C->getAPIntValue().urem(VTBits);
3928 
3929       // Handle rotate right by N like a rotate left by 32-N.
3930       if (Opcode == ISD::ROTR)
3931         RotAmt = (VTBits - RotAmt) % VTBits;
3932 
3933       // If we aren't rotating out all of the known-in sign bits, return the
3934       // number that are left.  This handles rotl(sext(x), 1) for example.
3935       if (Tmp > (RotAmt + 1)) return (Tmp - RotAmt);
3936     }
3937     break;
3938   case ISD::ADD:
3939   case ISD::ADDC:
3940     // Add 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 
3945     // Special case decrementing a value (ADD X, -1):
3946     if (ConstantSDNode *CRHS =
3947             isConstOrConstSplat(Op.getOperand(1), DemandedElts))
3948       if (CRHS->isAllOnesValue()) {
3949         KnownBits Known =
3950             computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3951 
3952         // If the input is known to be 0 or 1, the output is 0/-1, which is all
3953         // sign bits set.
3954         if ((Known.Zero | 1).isAllOnesValue())
3955           return VTBits;
3956 
3957         // If we are subtracting one from a positive number, there is no carry
3958         // out of the result.
3959         if (Known.isNonNegative())
3960           return Tmp;
3961       }
3962 
3963     Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
3964     if (Tmp2 == 1) return 1; // Early out.
3965     return std::min(Tmp, Tmp2) - 1;
3966   case ISD::SUB:
3967     Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
3968     if (Tmp2 == 1) return 1; // Early out.
3969 
3970     // Handle NEG.
3971     if (ConstantSDNode *CLHS =
3972             isConstOrConstSplat(Op.getOperand(0), DemandedElts))
3973       if (CLHS->isNullValue()) {
3974         KnownBits Known =
3975             computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3976         // If the input is known to be 0 or 1, the output is 0/-1, which is all
3977         // sign bits set.
3978         if ((Known.Zero | 1).isAllOnesValue())
3979           return VTBits;
3980 
3981         // If the input is known to be positive (the sign bit is known clear),
3982         // the output of the NEG has the same number of sign bits as the input.
3983         if (Known.isNonNegative())
3984           return Tmp2;
3985 
3986         // Otherwise, we treat this like a SUB.
3987       }
3988 
3989     // Sub can have at most one carry bit.  Thus we know that the output
3990     // is, at worst, one more bit than the inputs.
3991     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
3992     if (Tmp == 1) return 1; // Early out.
3993     return std::min(Tmp, Tmp2) - 1;
3994   case ISD::MUL: {
3995     // The output of the Mul can be at most twice the valid bits in the inputs.
3996     unsigned SignBitsOp0 = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
3997     if (SignBitsOp0 == 1)
3998       break;
3999     unsigned SignBitsOp1 = ComputeNumSignBits(Op.getOperand(1), Depth + 1);
4000     if (SignBitsOp1 == 1)
4001       break;
4002     unsigned OutValidBits =
4003         (VTBits - SignBitsOp0 + 1) + (VTBits - SignBitsOp1 + 1);
4004     return OutValidBits > VTBits ? 1 : VTBits - OutValidBits + 1;
4005   }
4006   case ISD::SREM:
4007     // The sign bit is the LHS's sign bit, except when the result of the
4008     // remainder is zero. The magnitude of the result should be less than or
4009     // equal to the magnitude of the LHS. Therefore, the result should have
4010     // at least as many sign bits as the left hand side.
4011     return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
4012   case ISD::TRUNCATE: {
4013     // Check if the sign bits of source go down as far as the truncated value.
4014     unsigned NumSrcBits = Op.getOperand(0).getScalarValueSizeInBits();
4015     unsigned NumSrcSignBits = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
4016     if (NumSrcSignBits > (NumSrcBits - VTBits))
4017       return NumSrcSignBits - (NumSrcBits - VTBits);
4018     break;
4019   }
4020   case ISD::EXTRACT_ELEMENT: {
4021     const int KnownSign = ComputeNumSignBits(Op.getOperand(0), Depth+1);
4022     const int BitWidth = Op.getValueSizeInBits();
4023     const int Items = Op.getOperand(0).getValueSizeInBits() / BitWidth;
4024 
4025     // Get reverse index (starting from 1), Op1 value indexes elements from
4026     // little end. Sign starts at big end.
4027     const int rIndex = Items - 1 - Op.getConstantOperandVal(1);
4028 
4029     // If the sign portion ends in our element the subtraction gives correct
4030     // result. Otherwise it gives either negative or > bitwidth result
4031     return std::max(std::min(KnownSign - rIndex * BitWidth, BitWidth), 0);
4032   }
4033   case ISD::INSERT_VECTOR_ELT: {
4034     // If we know the element index, split the demand between the
4035     // source vector and the inserted element, otherwise assume we need
4036     // the original demanded vector elements and the value.
4037     SDValue InVec = Op.getOperand(0);
4038     SDValue InVal = Op.getOperand(1);
4039     SDValue EltNo = Op.getOperand(2);
4040     bool DemandedVal = true;
4041     APInt DemandedVecElts = DemandedElts;
4042     auto *CEltNo = dyn_cast<ConstantSDNode>(EltNo);
4043     if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) {
4044       unsigned EltIdx = CEltNo->getZExtValue();
4045       DemandedVal = !!DemandedElts[EltIdx];
4046       DemandedVecElts.clearBit(EltIdx);
4047     }
4048     Tmp = std::numeric_limits<unsigned>::max();
4049     if (DemandedVal) {
4050       // TODO - handle implicit truncation of inserted elements.
4051       if (InVal.getScalarValueSizeInBits() != VTBits)
4052         break;
4053       Tmp2 = ComputeNumSignBits(InVal, Depth + 1);
4054       Tmp = std::min(Tmp, Tmp2);
4055     }
4056     if (!!DemandedVecElts) {
4057       Tmp2 = ComputeNumSignBits(InVec, DemandedVecElts, Depth + 1);
4058       Tmp = std::min(Tmp, Tmp2);
4059     }
4060     assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
4061     return Tmp;
4062   }
4063   case ISD::EXTRACT_VECTOR_ELT: {
4064     SDValue InVec = Op.getOperand(0);
4065     SDValue EltNo = Op.getOperand(1);
4066     EVT VecVT = InVec.getValueType();
4067     // ComputeNumSignBits not yet implemented for scalable vectors.
4068     if (VecVT.isScalableVector())
4069       break;
4070     const unsigned BitWidth = Op.getValueSizeInBits();
4071     const unsigned EltBitWidth = Op.getOperand(0).getScalarValueSizeInBits();
4072     const unsigned NumSrcElts = VecVT.getVectorNumElements();
4073 
4074     // If BitWidth > EltBitWidth the value is anyext:ed, and we do not know
4075     // anything about sign bits. But if the sizes match we can derive knowledge
4076     // about sign bits from the vector operand.
4077     if (BitWidth != EltBitWidth)
4078       break;
4079 
4080     // If we know the element index, just demand that vector element, else for
4081     // an unknown element index, ignore DemandedElts and demand them all.
4082     APInt DemandedSrcElts = APInt::getAllOnesValue(NumSrcElts);
4083     auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
4084     if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts))
4085       DemandedSrcElts =
4086           APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue());
4087 
4088     return ComputeNumSignBits(InVec, DemandedSrcElts, Depth + 1);
4089   }
4090   case ISD::EXTRACT_SUBVECTOR: {
4091     // Offset the demanded elts by the subvector index.
4092     SDValue Src = Op.getOperand(0);
4093     // Bail until we can represent demanded elements for scalable vectors.
4094     if (Src.getValueType().isScalableVector())
4095       break;
4096     uint64_t Idx = Op.getConstantOperandVal(1);
4097     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
4098     APInt DemandedSrcElts = DemandedElts.zextOrSelf(NumSrcElts).shl(Idx);
4099     return ComputeNumSignBits(Src, DemandedSrcElts, Depth + 1);
4100   }
4101   case ISD::CONCAT_VECTORS: {
4102     // Determine the minimum number of sign bits across all demanded
4103     // elts of the input vectors. Early out if the result is already 1.
4104     Tmp = std::numeric_limits<unsigned>::max();
4105     EVT SubVectorVT = Op.getOperand(0).getValueType();
4106     unsigned NumSubVectorElts = SubVectorVT.getVectorNumElements();
4107     unsigned NumSubVectors = Op.getNumOperands();
4108     for (unsigned i = 0; (i < NumSubVectors) && (Tmp > 1); ++i) {
4109       APInt DemandedSub =
4110           DemandedElts.extractBits(NumSubVectorElts, i * NumSubVectorElts);
4111       if (!DemandedSub)
4112         continue;
4113       Tmp2 = ComputeNumSignBits(Op.getOperand(i), DemandedSub, Depth + 1);
4114       Tmp = std::min(Tmp, Tmp2);
4115     }
4116     assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
4117     return Tmp;
4118   }
4119   case ISD::INSERT_SUBVECTOR: {
4120     // Demand any elements from the subvector and the remainder from the src its
4121     // inserted into.
4122     SDValue Src = Op.getOperand(0);
4123     SDValue Sub = Op.getOperand(1);
4124     uint64_t Idx = Op.getConstantOperandVal(2);
4125     unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
4126     APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
4127     APInt DemandedSrcElts = DemandedElts;
4128     DemandedSrcElts.insertBits(APInt::getNullValue(NumSubElts), Idx);
4129 
4130     Tmp = std::numeric_limits<unsigned>::max();
4131     if (!!DemandedSubElts) {
4132       Tmp = ComputeNumSignBits(Sub, DemandedSubElts, Depth + 1);
4133       if (Tmp == 1)
4134         return 1; // early-out
4135     }
4136     if (!!DemandedSrcElts) {
4137       Tmp2 = ComputeNumSignBits(Src, DemandedSrcElts, Depth + 1);
4138       Tmp = std::min(Tmp, Tmp2);
4139     }
4140     assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
4141     return Tmp;
4142   }
4143   case ISD::ATOMIC_CMP_SWAP:
4144   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
4145   case ISD::ATOMIC_SWAP:
4146   case ISD::ATOMIC_LOAD_ADD:
4147   case ISD::ATOMIC_LOAD_SUB:
4148   case ISD::ATOMIC_LOAD_AND:
4149   case ISD::ATOMIC_LOAD_CLR:
4150   case ISD::ATOMIC_LOAD_OR:
4151   case ISD::ATOMIC_LOAD_XOR:
4152   case ISD::ATOMIC_LOAD_NAND:
4153   case ISD::ATOMIC_LOAD_MIN:
4154   case ISD::ATOMIC_LOAD_MAX:
4155   case ISD::ATOMIC_LOAD_UMIN:
4156   case ISD::ATOMIC_LOAD_UMAX:
4157   case ISD::ATOMIC_LOAD: {
4158     Tmp = cast<AtomicSDNode>(Op)->getMemoryVT().getScalarSizeInBits();
4159     // If we are looking at the loaded value.
4160     if (Op.getResNo() == 0) {
4161       if (Tmp == VTBits)
4162         return 1; // early-out
4163       if (TLI->getExtendForAtomicOps() == ISD::SIGN_EXTEND)
4164         return VTBits - Tmp + 1;
4165       if (TLI->getExtendForAtomicOps() == ISD::ZERO_EXTEND)
4166         return VTBits - Tmp;
4167     }
4168     break;
4169   }
4170   }
4171 
4172   // If we are looking at the loaded value of the SDNode.
4173   if (Op.getResNo() == 0) {
4174     // Handle LOADX separately here. EXTLOAD case will fallthrough.
4175     if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
4176       unsigned ExtType = LD->getExtensionType();
4177       switch (ExtType) {
4178       default: break;
4179       case ISD::SEXTLOAD: // e.g. i16->i32 = '17' bits known.
4180         Tmp = LD->getMemoryVT().getScalarSizeInBits();
4181         return VTBits - Tmp + 1;
4182       case ISD::ZEXTLOAD: // e.g. i16->i32 = '16' bits known.
4183         Tmp = LD->getMemoryVT().getScalarSizeInBits();
4184         return VTBits - Tmp;
4185       case ISD::NON_EXTLOAD:
4186         if (const Constant *Cst = TLI->getTargetConstantFromLoad(LD)) {
4187           // We only need to handle vectors - computeKnownBits should handle
4188           // scalar cases.
4189           Type *CstTy = Cst->getType();
4190           if (CstTy->isVectorTy() &&
4191               (NumElts * VTBits) == CstTy->getPrimitiveSizeInBits()) {
4192             Tmp = VTBits;
4193             for (unsigned i = 0; i != NumElts; ++i) {
4194               if (!DemandedElts[i])
4195                 continue;
4196               if (Constant *Elt = Cst->getAggregateElement(i)) {
4197                 if (auto *CInt = dyn_cast<ConstantInt>(Elt)) {
4198                   const APInt &Value = CInt->getValue();
4199                   Tmp = std::min(Tmp, Value.getNumSignBits());
4200                   continue;
4201                 }
4202                 if (auto *CFP = dyn_cast<ConstantFP>(Elt)) {
4203                   APInt Value = CFP->getValueAPF().bitcastToAPInt();
4204                   Tmp = std::min(Tmp, Value.getNumSignBits());
4205                   continue;
4206                 }
4207               }
4208               // Unknown type. Conservatively assume no bits match sign bit.
4209               return 1;
4210             }
4211             return Tmp;
4212           }
4213         }
4214         break;
4215       }
4216     }
4217   }
4218 
4219   // Allow the target to implement this method for its nodes.
4220   if (Opcode >= ISD::BUILTIN_OP_END ||
4221       Opcode == ISD::INTRINSIC_WO_CHAIN ||
4222       Opcode == ISD::INTRINSIC_W_CHAIN ||
4223       Opcode == ISD::INTRINSIC_VOID) {
4224     unsigned NumBits =
4225         TLI->ComputeNumSignBitsForTargetNode(Op, DemandedElts, *this, Depth);
4226     if (NumBits > 1)
4227       FirstAnswer = std::max(FirstAnswer, NumBits);
4228   }
4229 
4230   // Finally, if we can prove that the top bits of the result are 0's or 1's,
4231   // use this information.
4232   KnownBits Known = computeKnownBits(Op, DemandedElts, Depth);
4233 
4234   APInt Mask;
4235   if (Known.isNonNegative()) {        // sign bit is 0
4236     Mask = Known.Zero;
4237   } else if (Known.isNegative()) {  // sign bit is 1;
4238     Mask = Known.One;
4239   } else {
4240     // Nothing known.
4241     return FirstAnswer;
4242   }
4243 
4244   // Okay, we know that the sign bit in Mask is set.  Use CLO to determine
4245   // the number of identical bits in the top of the input value.
4246   Mask <<= Mask.getBitWidth()-VTBits;
4247   return std::max(FirstAnswer, Mask.countLeadingOnes());
4248 }
4249 
4250 bool SelectionDAG::isBaseWithConstantOffset(SDValue Op) const {
4251   if ((Op.getOpcode() != ISD::ADD && Op.getOpcode() != ISD::OR) ||
4252       !isa<ConstantSDNode>(Op.getOperand(1)))
4253     return false;
4254 
4255   if (Op.getOpcode() == ISD::OR &&
4256       !MaskedValueIsZero(Op.getOperand(0), Op.getConstantOperandAPInt(1)))
4257     return false;
4258 
4259   return true;
4260 }
4261 
4262 bool SelectionDAG::isKnownNeverNaN(SDValue Op, bool SNaN, unsigned Depth) const {
4263   // If we're told that NaNs won't happen, assume they won't.
4264   if (getTarget().Options.NoNaNsFPMath || Op->getFlags().hasNoNaNs())
4265     return true;
4266 
4267   if (Depth >= MaxRecursionDepth)
4268     return false; // Limit search depth.
4269 
4270   // TODO: Handle vectors.
4271   // If the value is a constant, we can obviously see if it is a NaN or not.
4272   if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) {
4273     return !C->getValueAPF().isNaN() ||
4274            (SNaN && !C->getValueAPF().isSignaling());
4275   }
4276 
4277   unsigned Opcode = Op.getOpcode();
4278   switch (Opcode) {
4279   case ISD::FADD:
4280   case ISD::FSUB:
4281   case ISD::FMUL:
4282   case ISD::FDIV:
4283   case ISD::FREM:
4284   case ISD::FSIN:
4285   case ISD::FCOS: {
4286     if (SNaN)
4287       return true;
4288     // TODO: Need isKnownNeverInfinity
4289     return false;
4290   }
4291   case ISD::FCANONICALIZE:
4292   case ISD::FEXP:
4293   case ISD::FEXP2:
4294   case ISD::FTRUNC:
4295   case ISD::FFLOOR:
4296   case ISD::FCEIL:
4297   case ISD::FROUND:
4298   case ISD::FROUNDEVEN:
4299   case ISD::FRINT:
4300   case ISD::FNEARBYINT: {
4301     if (SNaN)
4302       return true;
4303     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
4304   }
4305   case ISD::FABS:
4306   case ISD::FNEG:
4307   case ISD::FCOPYSIGN: {
4308     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
4309   }
4310   case ISD::SELECT:
4311     return isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1) &&
4312            isKnownNeverNaN(Op.getOperand(2), SNaN, Depth + 1);
4313   case ISD::FP_EXTEND:
4314   case ISD::FP_ROUND: {
4315     if (SNaN)
4316       return true;
4317     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
4318   }
4319   case ISD::SINT_TO_FP:
4320   case ISD::UINT_TO_FP:
4321     return true;
4322   case ISD::FMA:
4323   case ISD::FMAD: {
4324     if (SNaN)
4325       return true;
4326     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) &&
4327            isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1) &&
4328            isKnownNeverNaN(Op.getOperand(2), SNaN, Depth + 1);
4329   }
4330   case ISD::FSQRT: // Need is known positive
4331   case ISD::FLOG:
4332   case ISD::FLOG2:
4333   case ISD::FLOG10:
4334   case ISD::FPOWI:
4335   case ISD::FPOW: {
4336     if (SNaN)
4337       return true;
4338     // TODO: Refine on operand
4339     return false;
4340   }
4341   case ISD::FMINNUM:
4342   case ISD::FMAXNUM: {
4343     // Only one needs to be known not-nan, since it will be returned if the
4344     // other ends up being one.
4345     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) ||
4346            isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1);
4347   }
4348   case ISD::FMINNUM_IEEE:
4349   case ISD::FMAXNUM_IEEE: {
4350     if (SNaN)
4351       return true;
4352     // This can return a NaN if either operand is an sNaN, or if both operands
4353     // are NaN.
4354     return (isKnownNeverNaN(Op.getOperand(0), false, Depth + 1) &&
4355             isKnownNeverSNaN(Op.getOperand(1), Depth + 1)) ||
4356            (isKnownNeverNaN(Op.getOperand(1), false, Depth + 1) &&
4357             isKnownNeverSNaN(Op.getOperand(0), Depth + 1));
4358   }
4359   case ISD::FMINIMUM:
4360   case ISD::FMAXIMUM: {
4361     // TODO: Does this quiet or return the origina NaN as-is?
4362     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) &&
4363            isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1);
4364   }
4365   case ISD::EXTRACT_VECTOR_ELT: {
4366     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
4367   }
4368   default:
4369     if (Opcode >= ISD::BUILTIN_OP_END ||
4370         Opcode == ISD::INTRINSIC_WO_CHAIN ||
4371         Opcode == ISD::INTRINSIC_W_CHAIN ||
4372         Opcode == ISD::INTRINSIC_VOID) {
4373       return TLI->isKnownNeverNaNForTargetNode(Op, *this, SNaN, Depth);
4374     }
4375 
4376     return false;
4377   }
4378 }
4379 
4380 bool SelectionDAG::isKnownNeverZeroFloat(SDValue Op) const {
4381   assert(Op.getValueType().isFloatingPoint() &&
4382          "Floating point type expected");
4383 
4384   // If the value is a constant, we can obviously see if it is a zero or not.
4385   // TODO: Add BuildVector support.
4386   if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op))
4387     return !C->isZero();
4388   return false;
4389 }
4390 
4391 bool SelectionDAG::isKnownNeverZero(SDValue Op) const {
4392   assert(!Op.getValueType().isFloatingPoint() &&
4393          "Floating point types unsupported - use isKnownNeverZeroFloat");
4394 
4395   // If the value is a constant, we can obviously see if it is a zero or not.
4396   if (ISD::matchUnaryPredicate(
4397           Op, [](ConstantSDNode *C) { return !C->isNullValue(); }))
4398     return true;
4399 
4400   // TODO: Recognize more cases here.
4401   switch (Op.getOpcode()) {
4402   default: break;
4403   case ISD::OR:
4404     if (isKnownNeverZero(Op.getOperand(1)) ||
4405         isKnownNeverZero(Op.getOperand(0)))
4406       return true;
4407     break;
4408   }
4409 
4410   return false;
4411 }
4412 
4413 bool SelectionDAG::isEqualTo(SDValue A, SDValue B) const {
4414   // Check the obvious case.
4415   if (A == B) return true;
4416 
4417   // For for negative and positive zero.
4418   if (const ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A))
4419     if (const ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B))
4420       if (CA->isZero() && CB->isZero()) return true;
4421 
4422   // Otherwise they may not be equal.
4423   return false;
4424 }
4425 
4426 // FIXME: unify with llvm::haveNoCommonBitsSet.
4427 // FIXME: could also handle masked merge pattern (X & ~M) op (Y & M)
4428 bool SelectionDAG::haveNoCommonBitsSet(SDValue A, SDValue B) const {
4429   assert(A.getValueType() == B.getValueType() &&
4430          "Values must have the same type");
4431   return KnownBits::haveNoCommonBitsSet(computeKnownBits(A),
4432                                         computeKnownBits(B));
4433 }
4434 
4435 static SDValue FoldSTEP_VECTOR(const SDLoc &DL, EVT VT, SDValue Step,
4436                                SelectionDAG &DAG) {
4437   if (cast<ConstantSDNode>(Step)->isNullValue())
4438     return DAG.getConstant(0, DL, VT);
4439 
4440   return SDValue();
4441 }
4442 
4443 static SDValue FoldBUILD_VECTOR(const SDLoc &DL, EVT VT,
4444                                 ArrayRef<SDValue> Ops,
4445                                 SelectionDAG &DAG) {
4446   int NumOps = Ops.size();
4447   assert(NumOps != 0 && "Can't build an empty vector!");
4448   assert(!VT.isScalableVector() &&
4449          "BUILD_VECTOR cannot be used with scalable types");
4450   assert(VT.getVectorNumElements() == (unsigned)NumOps &&
4451          "Incorrect element count in BUILD_VECTOR!");
4452 
4453   // BUILD_VECTOR of UNDEFs is UNDEF.
4454   if (llvm::all_of(Ops, [](SDValue Op) { return Op.isUndef(); }))
4455     return DAG.getUNDEF(VT);
4456 
4457   // BUILD_VECTOR of seq extract/insert from the same vector + type is Identity.
4458   SDValue IdentitySrc;
4459   bool IsIdentity = true;
4460   for (int i = 0; i != NumOps; ++i) {
4461     if (Ops[i].getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
4462         Ops[i].getOperand(0).getValueType() != VT ||
4463         (IdentitySrc && Ops[i].getOperand(0) != IdentitySrc) ||
4464         !isa<ConstantSDNode>(Ops[i].getOperand(1)) ||
4465         cast<ConstantSDNode>(Ops[i].getOperand(1))->getAPIntValue() != i) {
4466       IsIdentity = false;
4467       break;
4468     }
4469     IdentitySrc = Ops[i].getOperand(0);
4470   }
4471   if (IsIdentity)
4472     return IdentitySrc;
4473 
4474   return SDValue();
4475 }
4476 
4477 /// Try to simplify vector concatenation to an input value, undef, or build
4478 /// vector.
4479 static SDValue foldCONCAT_VECTORS(const SDLoc &DL, EVT VT,
4480                                   ArrayRef<SDValue> Ops,
4481                                   SelectionDAG &DAG) {
4482   assert(!Ops.empty() && "Can't concatenate an empty list of vectors!");
4483   assert(llvm::all_of(Ops,
4484                       [Ops](SDValue Op) {
4485                         return Ops[0].getValueType() == Op.getValueType();
4486                       }) &&
4487          "Concatenation of vectors with inconsistent value types!");
4488   assert((Ops[0].getValueType().getVectorElementCount() * Ops.size()) ==
4489              VT.getVectorElementCount() &&
4490          "Incorrect element count in vector concatenation!");
4491 
4492   if (Ops.size() == 1)
4493     return Ops[0];
4494 
4495   // Concat of UNDEFs is UNDEF.
4496   if (llvm::all_of(Ops, [](SDValue Op) { return Op.isUndef(); }))
4497     return DAG.getUNDEF(VT);
4498 
4499   // Scan the operands and look for extract operations from a single source
4500   // that correspond to insertion at the same location via this concatenation:
4501   // concat (extract X, 0*subvec_elts), (extract X, 1*subvec_elts), ...
4502   SDValue IdentitySrc;
4503   bool IsIdentity = true;
4504   for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
4505     SDValue Op = Ops[i];
4506     unsigned IdentityIndex = i * Op.getValueType().getVectorMinNumElements();
4507     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
4508         Op.getOperand(0).getValueType() != VT ||
4509         (IdentitySrc && Op.getOperand(0) != IdentitySrc) ||
4510         Op.getConstantOperandVal(1) != IdentityIndex) {
4511       IsIdentity = false;
4512       break;
4513     }
4514     assert((!IdentitySrc || IdentitySrc == Op.getOperand(0)) &&
4515            "Unexpected identity source vector for concat of extracts");
4516     IdentitySrc = Op.getOperand(0);
4517   }
4518   if (IsIdentity) {
4519     assert(IdentitySrc && "Failed to set source vector of extracts");
4520     return IdentitySrc;
4521   }
4522 
4523   // The code below this point is only designed to work for fixed width
4524   // vectors, so we bail out for now.
4525   if (VT.isScalableVector())
4526     return SDValue();
4527 
4528   // A CONCAT_VECTOR with all UNDEF/BUILD_VECTOR operands can be
4529   // simplified to one big BUILD_VECTOR.
4530   // FIXME: Add support for SCALAR_TO_VECTOR as well.
4531   EVT SVT = VT.getScalarType();
4532   SmallVector<SDValue, 16> Elts;
4533   for (SDValue Op : Ops) {
4534     EVT OpVT = Op.getValueType();
4535     if (Op.isUndef())
4536       Elts.append(OpVT.getVectorNumElements(), DAG.getUNDEF(SVT));
4537     else if (Op.getOpcode() == ISD::BUILD_VECTOR)
4538       Elts.append(Op->op_begin(), Op->op_end());
4539     else
4540       return SDValue();
4541   }
4542 
4543   // BUILD_VECTOR requires all inputs to be of the same type, find the
4544   // maximum type and extend them all.
4545   for (SDValue Op : Elts)
4546     SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
4547 
4548   if (SVT.bitsGT(VT.getScalarType())) {
4549     for (SDValue &Op : Elts) {
4550       if (Op.isUndef())
4551         Op = DAG.getUNDEF(SVT);
4552       else
4553         Op = DAG.getTargetLoweringInfo().isZExtFree(Op.getValueType(), SVT)
4554                  ? DAG.getZExtOrTrunc(Op, DL, SVT)
4555                  : DAG.getSExtOrTrunc(Op, DL, SVT);
4556     }
4557   }
4558 
4559   SDValue V = DAG.getBuildVector(VT, DL, Elts);
4560   NewSDValueDbgMsg(V, "New node fold concat vectors: ", &DAG);
4561   return V;
4562 }
4563 
4564 /// Gets or creates the specified node.
4565 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT) {
4566   FoldingSetNodeID ID;
4567   AddNodeIDNode(ID, Opcode, getVTList(VT), None);
4568   void *IP = nullptr;
4569   if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
4570     return SDValue(E, 0);
4571 
4572   auto *N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(),
4573                               getVTList(VT));
4574   CSEMap.InsertNode(N, IP);
4575 
4576   InsertNode(N);
4577   SDValue V = SDValue(N, 0);
4578   NewSDValueDbgMsg(V, "Creating new node: ", this);
4579   return V;
4580 }
4581 
4582 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
4583                               SDValue Operand) {
4584   SDNodeFlags Flags;
4585   if (Inserter)
4586     Flags = Inserter->getFlags();
4587   return getNode(Opcode, DL, VT, Operand, Flags);
4588 }
4589 
4590 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
4591                               SDValue Operand, const SDNodeFlags Flags) {
4592   assert(Operand.getOpcode() != ISD::DELETED_NODE &&
4593          "Operand is DELETED_NODE!");
4594   // Constant fold unary operations with an integer constant operand. Even
4595   // opaque constant will be folded, because the folding of unary operations
4596   // doesn't create new constants with different values. Nevertheless, the
4597   // opaque flag is preserved during folding to prevent future folding with
4598   // other constants.
4599   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Operand)) {
4600     const APInt &Val = C->getAPIntValue();
4601     switch (Opcode) {
4602     default: break;
4603     case ISD::SIGN_EXTEND:
4604       return getConstant(Val.sextOrTrunc(VT.getSizeInBits()), DL, VT,
4605                          C->isTargetOpcode(), C->isOpaque());
4606     case ISD::TRUNCATE:
4607       if (C->isOpaque())
4608         break;
4609       LLVM_FALLTHROUGH;
4610     case ISD::ZERO_EXTEND:
4611       return getConstant(Val.zextOrTrunc(VT.getSizeInBits()), DL, VT,
4612                          C->isTargetOpcode(), C->isOpaque());
4613     case ISD::ANY_EXTEND:
4614       // Some targets like RISCV prefer to sign extend some types.
4615       if (TLI->isSExtCheaperThanZExt(Operand.getValueType(), VT))
4616         return getConstant(Val.sextOrTrunc(VT.getSizeInBits()), DL, VT,
4617                            C->isTargetOpcode(), C->isOpaque());
4618       return getConstant(Val.zextOrTrunc(VT.getSizeInBits()), DL, VT,
4619                          C->isTargetOpcode(), C->isOpaque());
4620     case ISD::UINT_TO_FP:
4621     case ISD::SINT_TO_FP: {
4622       APFloat apf(EVTToAPFloatSemantics(VT),
4623                   APInt::getNullValue(VT.getSizeInBits()));
4624       (void)apf.convertFromAPInt(Val,
4625                                  Opcode==ISD::SINT_TO_FP,
4626                                  APFloat::rmNearestTiesToEven);
4627       return getConstantFP(apf, DL, VT);
4628     }
4629     case ISD::BITCAST:
4630       if (VT == MVT::f16 && C->getValueType(0) == MVT::i16)
4631         return getConstantFP(APFloat(APFloat::IEEEhalf(), Val), DL, VT);
4632       if (VT == MVT::f32 && C->getValueType(0) == MVT::i32)
4633         return getConstantFP(APFloat(APFloat::IEEEsingle(), Val), DL, VT);
4634       if (VT == MVT::f64 && C->getValueType(0) == MVT::i64)
4635         return getConstantFP(APFloat(APFloat::IEEEdouble(), Val), DL, VT);
4636       if (VT == MVT::f128 && C->getValueType(0) == MVT::i128)
4637         return getConstantFP(APFloat(APFloat::IEEEquad(), Val), DL, VT);
4638       break;
4639     case ISD::ABS:
4640       return getConstant(Val.abs(), DL, VT, C->isTargetOpcode(),
4641                          C->isOpaque());
4642     case ISD::BITREVERSE:
4643       return getConstant(Val.reverseBits(), DL, VT, C->isTargetOpcode(),
4644                          C->isOpaque());
4645     case ISD::BSWAP:
4646       return getConstant(Val.byteSwap(), DL, VT, C->isTargetOpcode(),
4647                          C->isOpaque());
4648     case ISD::CTPOP:
4649       return getConstant(Val.countPopulation(), DL, VT, C->isTargetOpcode(),
4650                          C->isOpaque());
4651     case ISD::CTLZ:
4652     case ISD::CTLZ_ZERO_UNDEF:
4653       return getConstant(Val.countLeadingZeros(), DL, VT, C->isTargetOpcode(),
4654                          C->isOpaque());
4655     case ISD::CTTZ:
4656     case ISD::CTTZ_ZERO_UNDEF:
4657       return getConstant(Val.countTrailingZeros(), DL, VT, C->isTargetOpcode(),
4658                          C->isOpaque());
4659     case ISD::FP16_TO_FP: {
4660       bool Ignored;
4661       APFloat FPV(APFloat::IEEEhalf(),
4662                   (Val.getBitWidth() == 16) ? Val : Val.trunc(16));
4663 
4664       // This can return overflow, underflow, or inexact; we don't care.
4665       // FIXME need to be more flexible about rounding mode.
4666       (void)FPV.convert(EVTToAPFloatSemantics(VT),
4667                         APFloat::rmNearestTiesToEven, &Ignored);
4668       return getConstantFP(FPV, DL, VT);
4669     }
4670     case ISD::STEP_VECTOR: {
4671       if (SDValue V = FoldSTEP_VECTOR(DL, VT, Operand, *this))
4672         return V;
4673       break;
4674     }
4675     }
4676   }
4677 
4678   // Constant fold unary operations with a floating point constant operand.
4679   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Operand)) {
4680     APFloat V = C->getValueAPF();    // make copy
4681     switch (Opcode) {
4682     case ISD::FNEG:
4683       V.changeSign();
4684       return getConstantFP(V, DL, VT);
4685     case ISD::FABS:
4686       V.clearSign();
4687       return getConstantFP(V, DL, VT);
4688     case ISD::FCEIL: {
4689       APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardPositive);
4690       if (fs == APFloat::opOK || fs == APFloat::opInexact)
4691         return getConstantFP(V, DL, VT);
4692       break;
4693     }
4694     case ISD::FTRUNC: {
4695       APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardZero);
4696       if (fs == APFloat::opOK || fs == APFloat::opInexact)
4697         return getConstantFP(V, DL, VT);
4698       break;
4699     }
4700     case ISD::FFLOOR: {
4701       APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardNegative);
4702       if (fs == APFloat::opOK || fs == APFloat::opInexact)
4703         return getConstantFP(V, DL, VT);
4704       break;
4705     }
4706     case ISD::FP_EXTEND: {
4707       bool ignored;
4708       // This can return overflow, underflow, or inexact; we don't care.
4709       // FIXME need to be more flexible about rounding mode.
4710       (void)V.convert(EVTToAPFloatSemantics(VT),
4711                       APFloat::rmNearestTiesToEven, &ignored);
4712       return getConstantFP(V, DL, VT);
4713     }
4714     case ISD::FP_TO_SINT:
4715     case ISD::FP_TO_UINT: {
4716       bool ignored;
4717       APSInt IntVal(VT.getSizeInBits(), Opcode == ISD::FP_TO_UINT);
4718       // FIXME need to be more flexible about rounding mode.
4719       APFloat::opStatus s =
4720           V.convertToInteger(IntVal, APFloat::rmTowardZero, &ignored);
4721       if (s == APFloat::opInvalidOp) // inexact is OK, in fact usual
4722         break;
4723       return getConstant(IntVal, DL, VT);
4724     }
4725     case ISD::BITCAST:
4726       if (VT == MVT::i16 && C->getValueType(0) == MVT::f16)
4727         return getConstant((uint16_t)V.bitcastToAPInt().getZExtValue(), DL, VT);
4728       if (VT == MVT::i16 && C->getValueType(0) == MVT::bf16)
4729         return getConstant((uint16_t)V.bitcastToAPInt().getZExtValue(), DL, VT);
4730       if (VT == MVT::i32 && C->getValueType(0) == MVT::f32)
4731         return getConstant((uint32_t)V.bitcastToAPInt().getZExtValue(), DL, VT);
4732       if (VT == MVT::i64 && C->getValueType(0) == MVT::f64)
4733         return getConstant(V.bitcastToAPInt().getZExtValue(), DL, VT);
4734       break;
4735     case ISD::FP_TO_FP16: {
4736       bool Ignored;
4737       // This can return overflow, underflow, or inexact; we don't care.
4738       // FIXME need to be more flexible about rounding mode.
4739       (void)V.convert(APFloat::IEEEhalf(),
4740                       APFloat::rmNearestTiesToEven, &Ignored);
4741       return getConstant(V.bitcastToAPInt().getZExtValue(), DL, VT);
4742     }
4743     }
4744   }
4745 
4746   // Constant fold unary operations with a vector integer or float operand.
4747   switch (Opcode) {
4748   default:
4749     // FIXME: Entirely reasonable to perform folding of other unary
4750     // operations here as the need arises.
4751     break;
4752   case ISD::FNEG:
4753   case ISD::FABS:
4754   case ISD::FCEIL:
4755   case ISD::FTRUNC:
4756   case ISD::FFLOOR:
4757   case ISD::FP_EXTEND:
4758   case ISD::FP_TO_SINT:
4759   case ISD::FP_TO_UINT:
4760   case ISD::TRUNCATE:
4761   case ISD::ANY_EXTEND:
4762   case ISD::ZERO_EXTEND:
4763   case ISD::SIGN_EXTEND:
4764   case ISD::UINT_TO_FP:
4765   case ISD::SINT_TO_FP:
4766   case ISD::ABS:
4767   case ISD::BITREVERSE:
4768   case ISD::BSWAP:
4769   case ISD::CTLZ:
4770   case ISD::CTLZ_ZERO_UNDEF:
4771   case ISD::CTTZ:
4772   case ISD::CTTZ_ZERO_UNDEF:
4773   case ISD::CTPOP: {
4774     SDValue Ops = {Operand};
4775     if (SDValue Fold = FoldConstantVectorArithmetic(Opcode, DL, VT, Ops))
4776       return Fold;
4777   }
4778   }
4779 
4780   unsigned OpOpcode = Operand.getNode()->getOpcode();
4781   switch (Opcode) {
4782   case ISD::STEP_VECTOR:
4783     assert(VT.isScalableVector() &&
4784            "STEP_VECTOR can only be used with scalable types");
4785     assert(OpOpcode == ISD::TargetConstant &&
4786            VT.getVectorElementType() == Operand.getValueType() &&
4787            "Unexpected step operand");
4788     break;
4789   case ISD::FREEZE:
4790     assert(VT == Operand.getValueType() && "Unexpected VT!");
4791     break;
4792   case ISD::TokenFactor:
4793   case ISD::MERGE_VALUES:
4794   case ISD::CONCAT_VECTORS:
4795     return Operand;         // Factor, merge or concat of one node?  No need.
4796   case ISD::BUILD_VECTOR: {
4797     // Attempt to simplify BUILD_VECTOR.
4798     SDValue Ops[] = {Operand};
4799     if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
4800       return V;
4801     break;
4802   }
4803   case ISD::FP_ROUND: llvm_unreachable("Invalid method to make FP_ROUND node");
4804   case ISD::FP_EXTEND:
4805     assert(VT.isFloatingPoint() &&
4806            Operand.getValueType().isFloatingPoint() && "Invalid FP cast!");
4807     if (Operand.getValueType() == VT) return Operand;  // noop conversion.
4808     assert((!VT.isVector() ||
4809             VT.getVectorElementCount() ==
4810             Operand.getValueType().getVectorElementCount()) &&
4811            "Vector element count mismatch!");
4812     assert(Operand.getValueType().bitsLT(VT) &&
4813            "Invalid fpext node, dst < src!");
4814     if (Operand.isUndef())
4815       return getUNDEF(VT);
4816     break;
4817   case ISD::FP_TO_SINT:
4818   case ISD::FP_TO_UINT:
4819     if (Operand.isUndef())
4820       return getUNDEF(VT);
4821     break;
4822   case ISD::SINT_TO_FP:
4823   case ISD::UINT_TO_FP:
4824     // [us]itofp(undef) = 0, because the result value is bounded.
4825     if (Operand.isUndef())
4826       return getConstantFP(0.0, DL, VT);
4827     break;
4828   case ISD::SIGN_EXTEND:
4829     assert(VT.isInteger() && Operand.getValueType().isInteger() &&
4830            "Invalid SIGN_EXTEND!");
4831     assert(VT.isVector() == Operand.getValueType().isVector() &&
4832            "SIGN_EXTEND result type type should be vector iff the operand "
4833            "type is vector!");
4834     if (Operand.getValueType() == VT) return Operand;   // noop extension
4835     assert((!VT.isVector() ||
4836             VT.getVectorElementCount() ==
4837                 Operand.getValueType().getVectorElementCount()) &&
4838            "Vector element count mismatch!");
4839     assert(Operand.getValueType().bitsLT(VT) &&
4840            "Invalid sext node, dst < src!");
4841     if (OpOpcode == ISD::SIGN_EXTEND || OpOpcode == ISD::ZERO_EXTEND)
4842       return getNode(OpOpcode, DL, VT, Operand.getOperand(0));
4843     if (OpOpcode == ISD::UNDEF)
4844       // sext(undef) = 0, because the top bits will all be the same.
4845       return getConstant(0, DL, VT);
4846     break;
4847   case ISD::ZERO_EXTEND:
4848     assert(VT.isInteger() && Operand.getValueType().isInteger() &&
4849            "Invalid ZERO_EXTEND!");
4850     assert(VT.isVector() == Operand.getValueType().isVector() &&
4851            "ZERO_EXTEND result type type should be vector iff the operand "
4852            "type is vector!");
4853     if (Operand.getValueType() == VT) return Operand;   // noop extension
4854     assert((!VT.isVector() ||
4855             VT.getVectorElementCount() ==
4856                 Operand.getValueType().getVectorElementCount()) &&
4857            "Vector element count mismatch!");
4858     assert(Operand.getValueType().bitsLT(VT) &&
4859            "Invalid zext node, dst < src!");
4860     if (OpOpcode == ISD::ZERO_EXTEND)   // (zext (zext x)) -> (zext x)
4861       return getNode(ISD::ZERO_EXTEND, DL, VT, Operand.getOperand(0));
4862     if (OpOpcode == ISD::UNDEF)
4863       // zext(undef) = 0, because the top bits will be zero.
4864       return getConstant(0, DL, VT);
4865     break;
4866   case ISD::ANY_EXTEND:
4867     assert(VT.isInteger() && Operand.getValueType().isInteger() &&
4868            "Invalid ANY_EXTEND!");
4869     assert(VT.isVector() == Operand.getValueType().isVector() &&
4870            "ANY_EXTEND result type type should be vector iff the operand "
4871            "type is vector!");
4872     if (Operand.getValueType() == VT) return Operand;   // noop extension
4873     assert((!VT.isVector() ||
4874             VT.getVectorElementCount() ==
4875                 Operand.getValueType().getVectorElementCount()) &&
4876            "Vector element count mismatch!");
4877     assert(Operand.getValueType().bitsLT(VT) &&
4878            "Invalid anyext node, dst < src!");
4879 
4880     if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
4881         OpOpcode == ISD::ANY_EXTEND)
4882       // (ext (zext x)) -> (zext x)  and  (ext (sext x)) -> (sext x)
4883       return getNode(OpOpcode, DL, VT, Operand.getOperand(0));
4884     if (OpOpcode == ISD::UNDEF)
4885       return getUNDEF(VT);
4886 
4887     // (ext (trunc x)) -> x
4888     if (OpOpcode == ISD::TRUNCATE) {
4889       SDValue OpOp = Operand.getOperand(0);
4890       if (OpOp.getValueType() == VT) {
4891         transferDbgValues(Operand, OpOp);
4892         return OpOp;
4893       }
4894     }
4895     break;
4896   case ISD::TRUNCATE:
4897     assert(VT.isInteger() && Operand.getValueType().isInteger() &&
4898            "Invalid TRUNCATE!");
4899     assert(VT.isVector() == Operand.getValueType().isVector() &&
4900            "TRUNCATE result type type should be vector iff the operand "
4901            "type is vector!");
4902     if (Operand.getValueType() == VT) return Operand;   // noop truncate
4903     assert((!VT.isVector() ||
4904             VT.getVectorElementCount() ==
4905                 Operand.getValueType().getVectorElementCount()) &&
4906            "Vector element count mismatch!");
4907     assert(Operand.getValueType().bitsGT(VT) &&
4908            "Invalid truncate node, src < dst!");
4909     if (OpOpcode == ISD::TRUNCATE)
4910       return getNode(ISD::TRUNCATE, DL, VT, Operand.getOperand(0));
4911     if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
4912         OpOpcode == ISD::ANY_EXTEND) {
4913       // If the source is smaller than the dest, we still need an extend.
4914       if (Operand.getOperand(0).getValueType().getScalarType()
4915             .bitsLT(VT.getScalarType()))
4916         return getNode(OpOpcode, DL, VT, Operand.getOperand(0));
4917       if (Operand.getOperand(0).getValueType().bitsGT(VT))
4918         return getNode(ISD::TRUNCATE, DL, VT, Operand.getOperand(0));
4919       return Operand.getOperand(0);
4920     }
4921     if (OpOpcode == ISD::UNDEF)
4922       return getUNDEF(VT);
4923     break;
4924   case ISD::ANY_EXTEND_VECTOR_INREG:
4925   case ISD::ZERO_EXTEND_VECTOR_INREG:
4926   case ISD::SIGN_EXTEND_VECTOR_INREG:
4927     assert(VT.isVector() && "This DAG node is restricted to vector types.");
4928     assert(Operand.getValueType().bitsLE(VT) &&
4929            "The input must be the same size or smaller than the result.");
4930     assert(VT.getVectorMinNumElements() <
4931                Operand.getValueType().getVectorMinNumElements() &&
4932            "The destination vector type must have fewer lanes than the input.");
4933     break;
4934   case ISD::ABS:
4935     assert(VT.isInteger() && VT == Operand.getValueType() &&
4936            "Invalid ABS!");
4937     if (OpOpcode == ISD::UNDEF)
4938       return getUNDEF(VT);
4939     break;
4940   case ISD::BSWAP:
4941     assert(VT.isInteger() && VT == Operand.getValueType() &&
4942            "Invalid BSWAP!");
4943     assert((VT.getScalarSizeInBits() % 16 == 0) &&
4944            "BSWAP types must be a multiple of 16 bits!");
4945     if (OpOpcode == ISD::UNDEF)
4946       return getUNDEF(VT);
4947     break;
4948   case ISD::BITREVERSE:
4949     assert(VT.isInteger() && VT == Operand.getValueType() &&
4950            "Invalid BITREVERSE!");
4951     if (OpOpcode == ISD::UNDEF)
4952       return getUNDEF(VT);
4953     break;
4954   case ISD::BITCAST:
4955     // Basic sanity checking.
4956     assert(VT.getSizeInBits() == Operand.getValueSizeInBits() &&
4957            "Cannot BITCAST between types of different sizes!");
4958     if (VT == Operand.getValueType()) return Operand;  // noop conversion.
4959     if (OpOpcode == ISD::BITCAST)  // bitconv(bitconv(x)) -> bitconv(x)
4960       return getNode(ISD::BITCAST, DL, VT, Operand.getOperand(0));
4961     if (OpOpcode == ISD::UNDEF)
4962       return getUNDEF(VT);
4963     break;
4964   case ISD::SCALAR_TO_VECTOR:
4965     assert(VT.isVector() && !Operand.getValueType().isVector() &&
4966            (VT.getVectorElementType() == Operand.getValueType() ||
4967             (VT.getVectorElementType().isInteger() &&
4968              Operand.getValueType().isInteger() &&
4969              VT.getVectorElementType().bitsLE(Operand.getValueType()))) &&
4970            "Illegal SCALAR_TO_VECTOR node!");
4971     if (OpOpcode == ISD::UNDEF)
4972       return getUNDEF(VT);
4973     // scalar_to_vector(extract_vector_elt V, 0) -> V, top bits are undefined.
4974     if (OpOpcode == ISD::EXTRACT_VECTOR_ELT &&
4975         isa<ConstantSDNode>(Operand.getOperand(1)) &&
4976         Operand.getConstantOperandVal(1) == 0 &&
4977         Operand.getOperand(0).getValueType() == VT)
4978       return Operand.getOperand(0);
4979     break;
4980   case ISD::FNEG:
4981     // Negation of an unknown bag of bits is still completely undefined.
4982     if (OpOpcode == ISD::UNDEF)
4983       return getUNDEF(VT);
4984 
4985     if (OpOpcode == ISD::FNEG)  // --X -> X
4986       return Operand.getOperand(0);
4987     break;
4988   case ISD::FABS:
4989     if (OpOpcode == ISD::FNEG)  // abs(-X) -> abs(X)
4990       return getNode(ISD::FABS, DL, VT, Operand.getOperand(0));
4991     break;
4992   case ISD::VSCALE:
4993     assert(VT == Operand.getValueType() && "Unexpected VT!");
4994     break;
4995   case ISD::CTPOP:
4996     if (Operand.getValueType().getScalarType() == MVT::i1)
4997       return Operand;
4998     break;
4999   case ISD::CTLZ:
5000   case ISD::CTTZ:
5001     if (Operand.getValueType().getScalarType() == MVT::i1)
5002       return getNOT(DL, Operand, Operand.getValueType());
5003     break;
5004   case ISD::VECREDUCE_SMIN:
5005   case ISD::VECREDUCE_UMAX:
5006     if (Operand.getValueType().getScalarType() == MVT::i1)
5007       return getNode(ISD::VECREDUCE_OR, DL, VT, Operand);
5008     break;
5009   case ISD::VECREDUCE_SMAX:
5010   case ISD::VECREDUCE_UMIN:
5011     if (Operand.getValueType().getScalarType() == MVT::i1)
5012       return getNode(ISD::VECREDUCE_AND, DL, VT, Operand);
5013     break;
5014   }
5015 
5016   SDNode *N;
5017   SDVTList VTs = getVTList(VT);
5018   SDValue Ops[] = {Operand};
5019   if (VT != MVT::Glue) { // Don't CSE flag producing nodes
5020     FoldingSetNodeID ID;
5021     AddNodeIDNode(ID, Opcode, VTs, Ops);
5022     void *IP = nullptr;
5023     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
5024       E->intersectFlagsWith(Flags);
5025       return SDValue(E, 0);
5026     }
5027 
5028     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
5029     N->setFlags(Flags);
5030     createOperands(N, Ops);
5031     CSEMap.InsertNode(N, IP);
5032   } else {
5033     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
5034     createOperands(N, Ops);
5035   }
5036 
5037   InsertNode(N);
5038   SDValue V = SDValue(N, 0);
5039   NewSDValueDbgMsg(V, "Creating new node: ", this);
5040   return V;
5041 }
5042 
5043 static llvm::Optional<APInt> FoldValue(unsigned Opcode, const APInt &C1,
5044                                        const APInt &C2) {
5045   switch (Opcode) {
5046   case ISD::ADD:  return C1 + C2;
5047   case ISD::SUB:  return C1 - C2;
5048   case ISD::MUL:  return C1 * C2;
5049   case ISD::AND:  return C1 & C2;
5050   case ISD::OR:   return C1 | C2;
5051   case ISD::XOR:  return C1 ^ C2;
5052   case ISD::SHL:  return C1 << C2;
5053   case ISD::SRL:  return C1.lshr(C2);
5054   case ISD::SRA:  return C1.ashr(C2);
5055   case ISD::ROTL: return C1.rotl(C2);
5056   case ISD::ROTR: return C1.rotr(C2);
5057   case ISD::SMIN: return C1.sle(C2) ? C1 : C2;
5058   case ISD::SMAX: return C1.sge(C2) ? C1 : C2;
5059   case ISD::UMIN: return C1.ule(C2) ? C1 : C2;
5060   case ISD::UMAX: return C1.uge(C2) ? C1 : C2;
5061   case ISD::SADDSAT: return C1.sadd_sat(C2);
5062   case ISD::UADDSAT: return C1.uadd_sat(C2);
5063   case ISD::SSUBSAT: return C1.ssub_sat(C2);
5064   case ISD::USUBSAT: return C1.usub_sat(C2);
5065   case ISD::UDIV:
5066     if (!C2.getBoolValue())
5067       break;
5068     return C1.udiv(C2);
5069   case ISD::UREM:
5070     if (!C2.getBoolValue())
5071       break;
5072     return C1.urem(C2);
5073   case ISD::SDIV:
5074     if (!C2.getBoolValue())
5075       break;
5076     return C1.sdiv(C2);
5077   case ISD::SREM:
5078     if (!C2.getBoolValue())
5079       break;
5080     return C1.srem(C2);
5081   case ISD::MULHS: {
5082     unsigned FullWidth = C1.getBitWidth() * 2;
5083     APInt C1Ext = C1.sext(FullWidth);
5084     APInt C2Ext = C2.sext(FullWidth);
5085     return (C1Ext * C2Ext).extractBits(C1.getBitWidth(), C1.getBitWidth());
5086   }
5087   case ISD::MULHU: {
5088     unsigned FullWidth = C1.getBitWidth() * 2;
5089     APInt C1Ext = C1.zext(FullWidth);
5090     APInt C2Ext = C2.zext(FullWidth);
5091     return (C1Ext * C2Ext).extractBits(C1.getBitWidth(), C1.getBitWidth());
5092   }
5093   }
5094   return llvm::None;
5095 }
5096 
5097 SDValue SelectionDAG::FoldSymbolOffset(unsigned Opcode, EVT VT,
5098                                        const GlobalAddressSDNode *GA,
5099                                        const SDNode *N2) {
5100   if (GA->getOpcode() != ISD::GlobalAddress)
5101     return SDValue();
5102   if (!TLI->isOffsetFoldingLegal(GA))
5103     return SDValue();
5104   auto *C2 = dyn_cast<ConstantSDNode>(N2);
5105   if (!C2)
5106     return SDValue();
5107   int64_t Offset = C2->getSExtValue();
5108   switch (Opcode) {
5109   case ISD::ADD: break;
5110   case ISD::SUB: Offset = -uint64_t(Offset); break;
5111   default: return SDValue();
5112   }
5113   return getGlobalAddress(GA->getGlobal(), SDLoc(C2), VT,
5114                           GA->getOffset() + uint64_t(Offset));
5115 }
5116 
5117 bool SelectionDAG::isUndef(unsigned Opcode, ArrayRef<SDValue> Ops) {
5118   switch (Opcode) {
5119   case ISD::SDIV:
5120   case ISD::UDIV:
5121   case ISD::SREM:
5122   case ISD::UREM: {
5123     // If a divisor is zero/undef or any element of a divisor vector is
5124     // zero/undef, the whole op is undef.
5125     assert(Ops.size() == 2 && "Div/rem should have 2 operands");
5126     SDValue Divisor = Ops[1];
5127     if (Divisor.isUndef() || isNullConstant(Divisor))
5128       return true;
5129 
5130     return ISD::isBuildVectorOfConstantSDNodes(Divisor.getNode()) &&
5131            llvm::any_of(Divisor->op_values(),
5132                         [](SDValue V) { return V.isUndef() ||
5133                                         isNullConstant(V); });
5134     // TODO: Handle signed overflow.
5135   }
5136   // TODO: Handle oversized shifts.
5137   default:
5138     return false;
5139   }
5140 }
5141 
5142 SDValue SelectionDAG::FoldConstantArithmetic(unsigned Opcode, const SDLoc &DL,
5143                                              EVT VT, ArrayRef<SDValue> Ops) {
5144   // If the opcode is a target-specific ISD node, there's nothing we can
5145   // do here and the operand rules may not line up with the below, so
5146   // bail early.
5147   // We can't create a scalar CONCAT_VECTORS so skip it. It will break
5148   // for concats involving SPLAT_VECTOR. Concats of BUILD_VECTORS are handled by
5149   // foldCONCAT_VECTORS in getNode before this is called.
5150   if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::CONCAT_VECTORS)
5151     return SDValue();
5152 
5153   // For now, the array Ops should only contain two values.
5154   // This enforcement will be removed once this function is merged with
5155   // FoldConstantVectorArithmetic
5156   if (Ops.size() != 2)
5157     return SDValue();
5158 
5159   if (isUndef(Opcode, Ops))
5160     return getUNDEF(VT);
5161 
5162   SDNode *N1 = Ops[0].getNode();
5163   SDNode *N2 = Ops[1].getNode();
5164 
5165   // Handle the case of two scalars.
5166   if (auto *C1 = dyn_cast<ConstantSDNode>(N1)) {
5167     if (auto *C2 = dyn_cast<ConstantSDNode>(N2)) {
5168       if (C1->isOpaque() || C2->isOpaque())
5169         return SDValue();
5170 
5171       Optional<APInt> FoldAttempt =
5172           FoldValue(Opcode, C1->getAPIntValue(), C2->getAPIntValue());
5173       if (!FoldAttempt)
5174         return SDValue();
5175 
5176       SDValue Folded = getConstant(FoldAttempt.getValue(), DL, VT);
5177       assert((!Folded || !VT.isVector()) &&
5178              "Can't fold vectors ops with scalar operands");
5179       return Folded;
5180     }
5181   }
5182 
5183   // fold (add Sym, c) -> Sym+c
5184   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N1))
5185     return FoldSymbolOffset(Opcode, VT, GA, N2);
5186   if (TLI->isCommutativeBinOp(Opcode))
5187     if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N2))
5188       return FoldSymbolOffset(Opcode, VT, GA, N1);
5189 
5190   // For fixed width vectors, extract each constant element and fold them
5191   // individually. Either input may be an undef value.
5192   bool IsBVOrSV1 = N1->getOpcode() == ISD::BUILD_VECTOR ||
5193                    N1->getOpcode() == ISD::SPLAT_VECTOR;
5194   if (!IsBVOrSV1 && !N1->isUndef())
5195     return SDValue();
5196   bool IsBVOrSV2 = N2->getOpcode() == ISD::BUILD_VECTOR ||
5197                    N2->getOpcode() == ISD::SPLAT_VECTOR;
5198   if (!IsBVOrSV2 && !N2->isUndef())
5199     return SDValue();
5200   // If both operands are undef, that's handled the same way as scalars.
5201   if (!IsBVOrSV1 && !IsBVOrSV2)
5202     return SDValue();
5203 
5204   EVT SVT = VT.getScalarType();
5205   EVT LegalSVT = SVT;
5206   if (NewNodesMustHaveLegalTypes && LegalSVT.isInteger()) {
5207     LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT);
5208     if (LegalSVT.bitsLT(SVT))
5209       return SDValue();
5210   }
5211 
5212   SmallVector<SDValue, 4> Outputs;
5213   unsigned NumOps = 0;
5214   if (IsBVOrSV1)
5215     NumOps = std::max(NumOps, N1->getNumOperands());
5216   if (IsBVOrSV2)
5217     NumOps = std::max(NumOps, N2->getNumOperands());
5218   assert(NumOps != 0 && "Expected non-zero operands");
5219   // Scalable vectors should only be SPLAT_VECTOR or UNDEF here. We only need
5220   // one iteration for that.
5221   assert((!VT.isScalableVector() || NumOps == 1) &&
5222          "Scalable vector should only have one scalar");
5223 
5224   for (unsigned I = 0; I != NumOps; ++I) {
5225     // We can have a fixed length SPLAT_VECTOR and a BUILD_VECTOR so we need
5226     // to use operand 0 of the SPLAT_VECTOR for each fixed element.
5227     SDValue V1;
5228     if (N1->getOpcode() == ISD::BUILD_VECTOR)
5229       V1 = N1->getOperand(I);
5230     else if (N1->getOpcode() == ISD::SPLAT_VECTOR)
5231       V1 = N1->getOperand(0);
5232     else
5233       V1 = getUNDEF(SVT);
5234 
5235     SDValue V2;
5236     if (N2->getOpcode() == ISD::BUILD_VECTOR)
5237       V2 = N2->getOperand(I);
5238     else if (N2->getOpcode() == ISD::SPLAT_VECTOR)
5239       V2 = N2->getOperand(0);
5240     else
5241       V2 = getUNDEF(SVT);
5242 
5243     if (SVT.isInteger()) {
5244       if (V1.getValueType().bitsGT(SVT))
5245         V1 = getNode(ISD::TRUNCATE, DL, SVT, V1);
5246       if (V2.getValueType().bitsGT(SVT))
5247         V2 = getNode(ISD::TRUNCATE, DL, SVT, V2);
5248     }
5249 
5250     if (V1.getValueType() != SVT || V2.getValueType() != SVT)
5251       return SDValue();
5252 
5253     // Fold one vector element.
5254     SDValue ScalarResult = getNode(Opcode, DL, SVT, V1, V2);
5255     if (LegalSVT != SVT)
5256       ScalarResult = getNode(ISD::SIGN_EXTEND, DL, LegalSVT, ScalarResult);
5257 
5258     // Scalar folding only succeeded if the result is a constant or UNDEF.
5259     if (!ScalarResult.isUndef() && ScalarResult.getOpcode() != ISD::Constant &&
5260         ScalarResult.getOpcode() != ISD::ConstantFP)
5261       return SDValue();
5262     Outputs.push_back(ScalarResult);
5263   }
5264 
5265   if (N1->getOpcode() == ISD::BUILD_VECTOR ||
5266       N2->getOpcode() == ISD::BUILD_VECTOR) {
5267     assert(VT.getVectorNumElements() == Outputs.size() &&
5268            "Vector size mismatch!");
5269 
5270     // Build a big vector out of the scalar elements we generated.
5271     return getBuildVector(VT, SDLoc(), Outputs);
5272   }
5273 
5274   assert((N1->getOpcode() == ISD::SPLAT_VECTOR ||
5275           N2->getOpcode() == ISD::SPLAT_VECTOR) &&
5276          "One operand should be a splat vector");
5277 
5278   assert(Outputs.size() == 1 && "Vector size mismatch!");
5279   return getSplatVector(VT, SDLoc(), Outputs[0]);
5280 }
5281 
5282 // TODO: Merge with FoldConstantArithmetic
5283 SDValue SelectionDAG::FoldConstantVectorArithmetic(unsigned Opcode,
5284                                                    const SDLoc &DL, EVT VT,
5285                                                    ArrayRef<SDValue> Ops,
5286                                                    const SDNodeFlags Flags) {
5287   // If the opcode is a target-specific ISD node, there's nothing we can
5288   // do here and the operand rules may not line up with the below, so
5289   // bail early.
5290   if (Opcode >= ISD::BUILTIN_OP_END)
5291     return SDValue();
5292 
5293   if (isUndef(Opcode, Ops))
5294     return getUNDEF(VT);
5295 
5296   // We can only fold vectors - maybe merge with FoldConstantArithmetic someday?
5297   if (!VT.isVector())
5298     return SDValue();
5299 
5300   ElementCount NumElts = VT.getVectorElementCount();
5301 
5302   auto IsScalarOrSameVectorSize = [NumElts](const SDValue &Op) {
5303     return !Op.getValueType().isVector() ||
5304            Op.getValueType().getVectorElementCount() == NumElts;
5305   };
5306 
5307   auto IsConstantBuildVectorSplatVectorOrUndef = [](const SDValue &Op) {
5308     APInt SplatVal;
5309     BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op);
5310     return Op.isUndef() || Op.getOpcode() == ISD::CONDCODE ||
5311            (BV && BV->isConstant()) ||
5312            (Op.getOpcode() == ISD::SPLAT_VECTOR &&
5313             ISD::isConstantSplatVector(Op.getNode(), SplatVal));
5314   };
5315 
5316   // All operands must be vector types with the same number of elements as
5317   // the result type and must be either UNDEF or a build vector of constant
5318   // or UNDEF scalars.
5319   if (!llvm::all_of(Ops, IsConstantBuildVectorSplatVectorOrUndef) ||
5320       !llvm::all_of(Ops, IsScalarOrSameVectorSize))
5321     return SDValue();
5322 
5323   // If we are comparing vectors, then the result needs to be a i1 boolean
5324   // that is then sign-extended back to the legal result type.
5325   EVT SVT = (Opcode == ISD::SETCC ? MVT::i1 : VT.getScalarType());
5326 
5327   // Find legal integer scalar type for constant promotion and
5328   // ensure that its scalar size is at least as large as source.
5329   EVT LegalSVT = VT.getScalarType();
5330   if (NewNodesMustHaveLegalTypes && LegalSVT.isInteger()) {
5331     LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT);
5332     if (LegalSVT.bitsLT(VT.getScalarType()))
5333       return SDValue();
5334   }
5335 
5336   // For scalable vector types we know we're dealing with SPLAT_VECTORs. We
5337   // only have one operand to check. For fixed-length vector types we may have
5338   // a combination of BUILD_VECTOR and SPLAT_VECTOR.
5339   unsigned NumOperands = NumElts.isScalable() ? 1 : NumElts.getFixedValue();
5340 
5341   // Constant fold each scalar lane separately.
5342   SmallVector<SDValue, 4> ScalarResults;
5343   for (unsigned I = 0; I != NumOperands; I++) {
5344     SmallVector<SDValue, 4> ScalarOps;
5345     for (SDValue Op : Ops) {
5346       EVT InSVT = Op.getValueType().getScalarType();
5347       if (Op.getOpcode() != ISD::BUILD_VECTOR &&
5348           Op.getOpcode() != ISD::SPLAT_VECTOR) {
5349         // We've checked that this is UNDEF or a constant of some kind.
5350         if (Op.isUndef())
5351           ScalarOps.push_back(getUNDEF(InSVT));
5352         else
5353           ScalarOps.push_back(Op);
5354         continue;
5355       }
5356 
5357       SDValue ScalarOp =
5358           Op.getOperand(Op.getOpcode() == ISD::SPLAT_VECTOR ? 0 : I);
5359       EVT ScalarVT = ScalarOp.getValueType();
5360 
5361       // Build vector (integer) scalar operands may need implicit
5362       // truncation - do this before constant folding.
5363       if (ScalarVT.isInteger() && ScalarVT.bitsGT(InSVT))
5364         ScalarOp = getNode(ISD::TRUNCATE, DL, InSVT, ScalarOp);
5365 
5366       ScalarOps.push_back(ScalarOp);
5367     }
5368 
5369     // Constant fold the scalar operands.
5370     SDValue ScalarResult = getNode(Opcode, DL, SVT, ScalarOps, Flags);
5371 
5372     // Legalize the (integer) scalar constant if necessary.
5373     if (LegalSVT != SVT)
5374       ScalarResult = getNode(ISD::SIGN_EXTEND, DL, LegalSVT, ScalarResult);
5375 
5376     // Scalar folding only succeeded if the result is a constant or UNDEF.
5377     if (!ScalarResult.isUndef() && ScalarResult.getOpcode() != ISD::Constant &&
5378         ScalarResult.getOpcode() != ISD::ConstantFP)
5379       return SDValue();
5380     ScalarResults.push_back(ScalarResult);
5381   }
5382 
5383   SDValue V = NumElts.isScalable() ? getSplatVector(VT, DL, ScalarResults[0])
5384                                    : getBuildVector(VT, DL, ScalarResults);
5385   NewSDValueDbgMsg(V, "New node fold constant vector: ", this);
5386   return V;
5387 }
5388 
5389 SDValue SelectionDAG::foldConstantFPMath(unsigned Opcode, const SDLoc &DL,
5390                                          EVT VT, SDValue N1, SDValue N2) {
5391   // TODO: We don't do any constant folding for strict FP opcodes here, but we
5392   //       should. That will require dealing with a potentially non-default
5393   //       rounding mode, checking the "opStatus" return value from the APFloat
5394   //       math calculations, and possibly other variations.
5395   auto *N1CFP = dyn_cast<ConstantFPSDNode>(N1.getNode());
5396   auto *N2CFP = dyn_cast<ConstantFPSDNode>(N2.getNode());
5397   if (N1CFP && N2CFP) {
5398     APFloat C1 = N1CFP->getValueAPF(), C2 = N2CFP->getValueAPF();
5399     switch (Opcode) {
5400     case ISD::FADD:
5401       C1.add(C2, APFloat::rmNearestTiesToEven);
5402       return getConstantFP(C1, DL, VT);
5403     case ISD::FSUB:
5404       C1.subtract(C2, APFloat::rmNearestTiesToEven);
5405       return getConstantFP(C1, DL, VT);
5406     case ISD::FMUL:
5407       C1.multiply(C2, APFloat::rmNearestTiesToEven);
5408       return getConstantFP(C1, DL, VT);
5409     case ISD::FDIV:
5410       C1.divide(C2, APFloat::rmNearestTiesToEven);
5411       return getConstantFP(C1, DL, VT);
5412     case ISD::FREM:
5413       C1.mod(C2);
5414       return getConstantFP(C1, DL, VT);
5415     case ISD::FCOPYSIGN:
5416       C1.copySign(C2);
5417       return getConstantFP(C1, DL, VT);
5418     default: break;
5419     }
5420   }
5421   if (N1CFP && Opcode == ISD::FP_ROUND) {
5422     APFloat C1 = N1CFP->getValueAPF();    // make copy
5423     bool Unused;
5424     // This can return overflow, underflow, or inexact; we don't care.
5425     // FIXME need to be more flexible about rounding mode.
5426     (void) C1.convert(EVTToAPFloatSemantics(VT), APFloat::rmNearestTiesToEven,
5427                       &Unused);
5428     return getConstantFP(C1, DL, VT);
5429   }
5430 
5431   switch (Opcode) {
5432   case ISD::FSUB:
5433     // -0.0 - undef --> undef (consistent with "fneg undef")
5434     if (N1CFP && N1CFP->getValueAPF().isNegZero() && N2.isUndef())
5435       return getUNDEF(VT);
5436     LLVM_FALLTHROUGH;
5437 
5438   case ISD::FADD:
5439   case ISD::FMUL:
5440   case ISD::FDIV:
5441   case ISD::FREM:
5442     // If both operands are undef, the result is undef. If 1 operand is undef,
5443     // the result is NaN. This should match the behavior of the IR optimizer.
5444     if (N1.isUndef() && N2.isUndef())
5445       return getUNDEF(VT);
5446     if (N1.isUndef() || N2.isUndef())
5447       return getConstantFP(APFloat::getNaN(EVTToAPFloatSemantics(VT)), DL, VT);
5448   }
5449   return SDValue();
5450 }
5451 
5452 SDValue SelectionDAG::getAssertAlign(const SDLoc &DL, SDValue Val, Align A) {
5453   assert(Val.getValueType().isInteger() && "Invalid AssertAlign!");
5454 
5455   // There's no need to assert on a byte-aligned pointer. All pointers are at
5456   // least byte aligned.
5457   if (A == Align(1))
5458     return Val;
5459 
5460   FoldingSetNodeID ID;
5461   AddNodeIDNode(ID, ISD::AssertAlign, getVTList(Val.getValueType()), {Val});
5462   ID.AddInteger(A.value());
5463 
5464   void *IP = nullptr;
5465   if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
5466     return SDValue(E, 0);
5467 
5468   auto *N = newSDNode<AssertAlignSDNode>(DL.getIROrder(), DL.getDebugLoc(),
5469                                          Val.getValueType(), A);
5470   createOperands(N, {Val});
5471 
5472   CSEMap.InsertNode(N, IP);
5473   InsertNode(N);
5474 
5475   SDValue V(N, 0);
5476   NewSDValueDbgMsg(V, "Creating new node: ", this);
5477   return V;
5478 }
5479 
5480 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
5481                               SDValue N1, SDValue N2) {
5482   SDNodeFlags Flags;
5483   if (Inserter)
5484     Flags = Inserter->getFlags();
5485   return getNode(Opcode, DL, VT, N1, N2, Flags);
5486 }
5487 
5488 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
5489                               SDValue N1, SDValue N2, const SDNodeFlags Flags) {
5490   assert(N1.getOpcode() != ISD::DELETED_NODE &&
5491          N2.getOpcode() != ISD::DELETED_NODE &&
5492          "Operand is DELETED_NODE!");
5493   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
5494   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
5495   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
5496   ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2);
5497 
5498   // Canonicalize constant to RHS if commutative.
5499   if (TLI->isCommutativeBinOp(Opcode)) {
5500     if (N1C && !N2C) {
5501       std::swap(N1C, N2C);
5502       std::swap(N1, N2);
5503     } else if (N1CFP && !N2CFP) {
5504       std::swap(N1CFP, N2CFP);
5505       std::swap(N1, N2);
5506     }
5507   }
5508 
5509   switch (Opcode) {
5510   default: break;
5511   case ISD::TokenFactor:
5512     assert(VT == MVT::Other && N1.getValueType() == MVT::Other &&
5513            N2.getValueType() == MVT::Other && "Invalid token factor!");
5514     // Fold trivial token factors.
5515     if (N1.getOpcode() == ISD::EntryToken) return N2;
5516     if (N2.getOpcode() == ISD::EntryToken) return N1;
5517     if (N1 == N2) return N1;
5518     break;
5519   case ISD::BUILD_VECTOR: {
5520     // Attempt to simplify BUILD_VECTOR.
5521     SDValue Ops[] = {N1, N2};
5522     if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
5523       return V;
5524     break;
5525   }
5526   case ISD::CONCAT_VECTORS: {
5527     SDValue Ops[] = {N1, N2};
5528     if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this))
5529       return V;
5530     break;
5531   }
5532   case ISD::AND:
5533     assert(VT.isInteger() && "This operator does not apply to FP types!");
5534     assert(N1.getValueType() == N2.getValueType() &&
5535            N1.getValueType() == VT && "Binary operator types must match!");
5536     // (X & 0) -> 0.  This commonly occurs when legalizing i64 values, so it's
5537     // worth handling here.
5538     if (N2C && N2C->isNullValue())
5539       return N2;
5540     if (N2C && N2C->isAllOnesValue())  // X & -1 -> X
5541       return N1;
5542     break;
5543   case ISD::OR:
5544   case ISD::XOR:
5545   case ISD::ADD:
5546   case ISD::SUB:
5547     assert(VT.isInteger() && "This operator does not apply to FP types!");
5548     assert(N1.getValueType() == N2.getValueType() &&
5549            N1.getValueType() == VT && "Binary operator types must match!");
5550     // (X ^|+- 0) -> X.  This commonly occurs when legalizing i64 values, so
5551     // it's worth handling here.
5552     if (N2C && N2C->isNullValue())
5553       return N1;
5554     if ((Opcode == ISD::ADD || Opcode == ISD::SUB) && VT.isVector() &&
5555         VT.getVectorElementType() == MVT::i1)
5556       return getNode(ISD::XOR, DL, VT, N1, N2);
5557     break;
5558   case ISD::MUL:
5559     assert(VT.isInteger() && "This operator does not apply to FP types!");
5560     assert(N1.getValueType() == N2.getValueType() &&
5561            N1.getValueType() == VT && "Binary operator types must match!");
5562     if (VT.isVector() && VT.getVectorElementType() == MVT::i1)
5563       return getNode(ISD::AND, DL, VT, N1, N2);
5564     if (N2C && (N1.getOpcode() == ISD::VSCALE) && Flags.hasNoSignedWrap()) {
5565       const APInt &MulImm = N1->getConstantOperandAPInt(0);
5566       const APInt &N2CImm = N2C->getAPIntValue();
5567       return getVScale(DL, VT, MulImm * N2CImm);
5568     }
5569     break;
5570   case ISD::UDIV:
5571   case ISD::UREM:
5572   case ISD::MULHU:
5573   case ISD::MULHS:
5574   case ISD::SDIV:
5575   case ISD::SREM:
5576   case ISD::SADDSAT:
5577   case ISD::SSUBSAT:
5578   case ISD::UADDSAT:
5579   case ISD::USUBSAT:
5580     assert(VT.isInteger() && "This operator does not apply to FP types!");
5581     assert(N1.getValueType() == N2.getValueType() &&
5582            N1.getValueType() == VT && "Binary operator types must match!");
5583     if (VT.isVector() && VT.getVectorElementType() == MVT::i1) {
5584       // fold (add_sat x, y) -> (or x, y) for bool types.
5585       if (Opcode == ISD::SADDSAT || Opcode == ISD::UADDSAT)
5586         return getNode(ISD::OR, DL, VT, N1, N2);
5587       // fold (sub_sat x, y) -> (and x, ~y) for bool types.
5588       if (Opcode == ISD::SSUBSAT || Opcode == ISD::USUBSAT)
5589         return getNode(ISD::AND, DL, VT, N1, getNOT(DL, N2, VT));
5590     }
5591     break;
5592   case ISD::SMIN:
5593   case ISD::UMAX:
5594     assert(VT.isInteger() && "This operator does not apply to FP types!");
5595     assert(N1.getValueType() == N2.getValueType() &&
5596            N1.getValueType() == VT && "Binary operator types must match!");
5597     if (VT.isVector() && VT.getVectorElementType() == MVT::i1)
5598       return getNode(ISD::OR, DL, VT, N1, N2);
5599     break;
5600   case ISD::SMAX:
5601   case ISD::UMIN:
5602     assert(VT.isInteger() && "This operator does not apply to FP types!");
5603     assert(N1.getValueType() == N2.getValueType() &&
5604            N1.getValueType() == VT && "Binary operator types must match!");
5605     if (VT.isVector() && VT.getVectorElementType() == MVT::i1)
5606       return getNode(ISD::AND, DL, VT, N1, N2);
5607     break;
5608   case ISD::FADD:
5609   case ISD::FSUB:
5610   case ISD::FMUL:
5611   case ISD::FDIV:
5612   case ISD::FREM:
5613     assert(VT.isFloatingPoint() && "This operator only applies to FP types!");
5614     assert(N1.getValueType() == N2.getValueType() &&
5615            N1.getValueType() == VT && "Binary operator types must match!");
5616     if (SDValue V = simplifyFPBinop(Opcode, N1, N2, Flags))
5617       return V;
5618     break;
5619   case ISD::FCOPYSIGN:   // N1 and result must match.  N1/N2 need not match.
5620     assert(N1.getValueType() == VT &&
5621            N1.getValueType().isFloatingPoint() &&
5622            N2.getValueType().isFloatingPoint() &&
5623            "Invalid FCOPYSIGN!");
5624     break;
5625   case ISD::SHL:
5626     if (N2C && (N1.getOpcode() == ISD::VSCALE) && Flags.hasNoSignedWrap()) {
5627       const APInt &MulImm = N1->getConstantOperandAPInt(0);
5628       const APInt &ShiftImm = N2C->getAPIntValue();
5629       return getVScale(DL, VT, MulImm << ShiftImm);
5630     }
5631     LLVM_FALLTHROUGH;
5632   case ISD::SRA:
5633   case ISD::SRL:
5634     if (SDValue V = simplifyShift(N1, N2))
5635       return V;
5636     LLVM_FALLTHROUGH;
5637   case ISD::ROTL:
5638   case ISD::ROTR:
5639     assert(VT == N1.getValueType() &&
5640            "Shift operators return type must be the same as their first arg");
5641     assert(VT.isInteger() && N2.getValueType().isInteger() &&
5642            "Shifts only work on integers");
5643     assert((!VT.isVector() || VT == N2.getValueType()) &&
5644            "Vector shift amounts must be in the same as their first arg");
5645     // Verify that the shift amount VT is big enough to hold valid shift
5646     // amounts.  This catches things like trying to shift an i1024 value by an
5647     // i8, which is easy to fall into in generic code that uses
5648     // TLI.getShiftAmount().
5649     assert(N2.getValueType().getScalarSizeInBits() >=
5650                Log2_32_Ceil(VT.getScalarSizeInBits()) &&
5651            "Invalid use of small shift amount with oversized value!");
5652 
5653     // Always fold shifts of i1 values so the code generator doesn't need to
5654     // handle them.  Since we know the size of the shift has to be less than the
5655     // size of the value, the shift/rotate count is guaranteed to be zero.
5656     if (VT == MVT::i1)
5657       return N1;
5658     if (N2C && N2C->isNullValue())
5659       return N1;
5660     break;
5661   case ISD::FP_ROUND:
5662     assert(VT.isFloatingPoint() &&
5663            N1.getValueType().isFloatingPoint() &&
5664            VT.bitsLE(N1.getValueType()) &&
5665            N2C && (N2C->getZExtValue() == 0 || N2C->getZExtValue() == 1) &&
5666            "Invalid FP_ROUND!");
5667     if (N1.getValueType() == VT) return N1;  // noop conversion.
5668     break;
5669   case ISD::AssertSext:
5670   case ISD::AssertZext: {
5671     EVT EVT = cast<VTSDNode>(N2)->getVT();
5672     assert(VT == N1.getValueType() && "Not an inreg extend!");
5673     assert(VT.isInteger() && EVT.isInteger() &&
5674            "Cannot *_EXTEND_INREG FP types");
5675     assert(!EVT.isVector() &&
5676            "AssertSExt/AssertZExt type should be the vector element type "
5677            "rather than the vector type!");
5678     assert(EVT.bitsLE(VT.getScalarType()) && "Not extending!");
5679     if (VT.getScalarType() == EVT) return N1; // noop assertion.
5680     break;
5681   }
5682   case ISD::SIGN_EXTEND_INREG: {
5683     EVT EVT = cast<VTSDNode>(N2)->getVT();
5684     assert(VT == N1.getValueType() && "Not an inreg extend!");
5685     assert(VT.isInteger() && EVT.isInteger() &&
5686            "Cannot *_EXTEND_INREG FP types");
5687     assert(EVT.isVector() == VT.isVector() &&
5688            "SIGN_EXTEND_INREG type should be vector iff the operand "
5689            "type is vector!");
5690     assert((!EVT.isVector() ||
5691             EVT.getVectorElementCount() == VT.getVectorElementCount()) &&
5692            "Vector element counts must match in SIGN_EXTEND_INREG");
5693     assert(EVT.bitsLE(VT) && "Not extending!");
5694     if (EVT == VT) return N1;  // Not actually extending
5695 
5696     auto SignExtendInReg = [&](APInt Val, llvm::EVT ConstantVT) {
5697       unsigned FromBits = EVT.getScalarSizeInBits();
5698       Val <<= Val.getBitWidth() - FromBits;
5699       Val.ashrInPlace(Val.getBitWidth() - FromBits);
5700       return getConstant(Val, DL, ConstantVT);
5701     };
5702 
5703     if (N1C) {
5704       const APInt &Val = N1C->getAPIntValue();
5705       return SignExtendInReg(Val, VT);
5706     }
5707 
5708     if (ISD::isBuildVectorOfConstantSDNodes(N1.getNode())) {
5709       SmallVector<SDValue, 8> Ops;
5710       llvm::EVT OpVT = N1.getOperand(0).getValueType();
5711       for (int i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
5712         SDValue Op = N1.getOperand(i);
5713         if (Op.isUndef()) {
5714           Ops.push_back(getUNDEF(OpVT));
5715           continue;
5716         }
5717         ConstantSDNode *C = cast<ConstantSDNode>(Op);
5718         APInt Val = C->getAPIntValue();
5719         Ops.push_back(SignExtendInReg(Val, OpVT));
5720       }
5721       return getBuildVector(VT, DL, Ops);
5722     }
5723     break;
5724   }
5725   case ISD::FP_TO_SINT_SAT:
5726   case ISD::FP_TO_UINT_SAT: {
5727     assert(VT.isInteger() && cast<VTSDNode>(N2)->getVT().isInteger() &&
5728            N1.getValueType().isFloatingPoint() && "Invalid FP_TO_*INT_SAT");
5729     assert(N1.getValueType().isVector() == VT.isVector() &&
5730            "FP_TO_*INT_SAT type should be vector iff the operand type is "
5731            "vector!");
5732     assert((!VT.isVector() || VT.getVectorNumElements() ==
5733                                   N1.getValueType().getVectorNumElements()) &&
5734            "Vector element counts must match in FP_TO_*INT_SAT");
5735     assert(!cast<VTSDNode>(N2)->getVT().isVector() &&
5736            "Type to saturate to must be a scalar.");
5737     assert(cast<VTSDNode>(N2)->getVT().bitsLE(VT.getScalarType()) &&
5738            "Not extending!");
5739     break;
5740   }
5741   case ISD::EXTRACT_VECTOR_ELT:
5742     assert(VT.getSizeInBits() >= N1.getValueType().getScalarSizeInBits() &&
5743            "The result of EXTRACT_VECTOR_ELT must be at least as wide as the \
5744              element type of the vector.");
5745 
5746     // Extract from an undefined value or using an undefined index is undefined.
5747     if (N1.isUndef() || N2.isUndef())
5748       return getUNDEF(VT);
5749 
5750     // EXTRACT_VECTOR_ELT of out-of-bounds element is an UNDEF for fixed length
5751     // vectors. For scalable vectors we will provide appropriate support for
5752     // dealing with arbitrary indices.
5753     if (N2C && N1.getValueType().isFixedLengthVector() &&
5754         N2C->getAPIntValue().uge(N1.getValueType().getVectorNumElements()))
5755       return getUNDEF(VT);
5756 
5757     // EXTRACT_VECTOR_ELT of CONCAT_VECTORS is often formed while lowering is
5758     // expanding copies of large vectors from registers. This only works for
5759     // fixed length vectors, since we need to know the exact number of
5760     // elements.
5761     if (N2C && N1.getOperand(0).getValueType().isFixedLengthVector() &&
5762         N1.getOpcode() == ISD::CONCAT_VECTORS && N1.getNumOperands() > 0) {
5763       unsigned Factor =
5764         N1.getOperand(0).getValueType().getVectorNumElements();
5765       return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
5766                      N1.getOperand(N2C->getZExtValue() / Factor),
5767                      getVectorIdxConstant(N2C->getZExtValue() % Factor, DL));
5768     }
5769 
5770     // EXTRACT_VECTOR_ELT of BUILD_VECTOR or SPLAT_VECTOR is often formed while
5771     // lowering is expanding large vector constants.
5772     if (N2C && (N1.getOpcode() == ISD::BUILD_VECTOR ||
5773                 N1.getOpcode() == ISD::SPLAT_VECTOR)) {
5774       assert((N1.getOpcode() != ISD::BUILD_VECTOR ||
5775               N1.getValueType().isFixedLengthVector()) &&
5776              "BUILD_VECTOR used for scalable vectors");
5777       unsigned Index =
5778           N1.getOpcode() == ISD::BUILD_VECTOR ? N2C->getZExtValue() : 0;
5779       SDValue Elt = N1.getOperand(Index);
5780 
5781       if (VT != Elt.getValueType())
5782         // If the vector element type is not legal, the BUILD_VECTOR operands
5783         // are promoted and implicitly truncated, and the result implicitly
5784         // extended. Make that explicit here.
5785         Elt = getAnyExtOrTrunc(Elt, DL, VT);
5786 
5787       return Elt;
5788     }
5789 
5790     // EXTRACT_VECTOR_ELT of INSERT_VECTOR_ELT is often formed when vector
5791     // operations are lowered to scalars.
5792     if (N1.getOpcode() == ISD::INSERT_VECTOR_ELT) {
5793       // If the indices are the same, return the inserted element else
5794       // if the indices are known different, extract the element from
5795       // the original vector.
5796       SDValue N1Op2 = N1.getOperand(2);
5797       ConstantSDNode *N1Op2C = dyn_cast<ConstantSDNode>(N1Op2);
5798 
5799       if (N1Op2C && N2C) {
5800         if (N1Op2C->getZExtValue() == N2C->getZExtValue()) {
5801           if (VT == N1.getOperand(1).getValueType())
5802             return N1.getOperand(1);
5803           return getSExtOrTrunc(N1.getOperand(1), DL, VT);
5804         }
5805         return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0), N2);
5806       }
5807     }
5808 
5809     // EXTRACT_VECTOR_ELT of v1iX EXTRACT_SUBVECTOR could be formed
5810     // when vector types are scalarized and v1iX is legal.
5811     // vextract (v1iX extract_subvector(vNiX, Idx)) -> vextract(vNiX,Idx).
5812     // Here we are completely ignoring the extract element index (N2),
5813     // which is fine for fixed width vectors, since any index other than 0
5814     // is undefined anyway. However, this cannot be ignored for scalable
5815     // vectors - in theory we could support this, but we don't want to do this
5816     // without a profitability check.
5817     if (N1.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
5818         N1.getValueType().isFixedLengthVector() &&
5819         N1.getValueType().getVectorNumElements() == 1) {
5820       return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0),
5821                      N1.getOperand(1));
5822     }
5823     break;
5824   case ISD::EXTRACT_ELEMENT:
5825     assert(N2C && (unsigned)N2C->getZExtValue() < 2 && "Bad EXTRACT_ELEMENT!");
5826     assert(!N1.getValueType().isVector() && !VT.isVector() &&
5827            (N1.getValueType().isInteger() == VT.isInteger()) &&
5828            N1.getValueType() != VT &&
5829            "Wrong types for EXTRACT_ELEMENT!");
5830 
5831     // EXTRACT_ELEMENT of BUILD_PAIR is often formed while legalize is expanding
5832     // 64-bit integers into 32-bit parts.  Instead of building the extract of
5833     // the BUILD_PAIR, only to have legalize rip it apart, just do it now.
5834     if (N1.getOpcode() == ISD::BUILD_PAIR)
5835       return N1.getOperand(N2C->getZExtValue());
5836 
5837     // EXTRACT_ELEMENT of a constant int is also very common.
5838     if (N1C) {
5839       unsigned ElementSize = VT.getSizeInBits();
5840       unsigned Shift = ElementSize * N2C->getZExtValue();
5841       const APInt &Val = N1C->getAPIntValue();
5842       return getConstant(Val.extractBits(ElementSize, Shift), DL, VT);
5843     }
5844     break;
5845   case ISD::EXTRACT_SUBVECTOR: {
5846     EVT N1VT = N1.getValueType();
5847     assert(VT.isVector() && N1VT.isVector() &&
5848            "Extract subvector VTs must be vectors!");
5849     assert(VT.getVectorElementType() == N1VT.getVectorElementType() &&
5850            "Extract subvector VTs must have the same element type!");
5851     assert((VT.isFixedLengthVector() || N1VT.isScalableVector()) &&
5852            "Cannot extract a scalable vector from a fixed length vector!");
5853     assert((VT.isScalableVector() != N1VT.isScalableVector() ||
5854             VT.getVectorMinNumElements() <= N1VT.getVectorMinNumElements()) &&
5855            "Extract subvector must be from larger vector to smaller vector!");
5856     assert(N2C && "Extract subvector index must be a constant");
5857     assert((VT.isScalableVector() != N1VT.isScalableVector() ||
5858             (VT.getVectorMinNumElements() + N2C->getZExtValue()) <=
5859                 N1VT.getVectorMinNumElements()) &&
5860            "Extract subvector overflow!");
5861     assert(N2C->getAPIntValue().getBitWidth() ==
5862                TLI->getVectorIdxTy(getDataLayout()).getFixedSizeInBits() &&
5863            "Constant index for EXTRACT_SUBVECTOR has an invalid size");
5864 
5865     // Trivial extraction.
5866     if (VT == N1VT)
5867       return N1;
5868 
5869     // EXTRACT_SUBVECTOR of an UNDEF is an UNDEF.
5870     if (N1.isUndef())
5871       return getUNDEF(VT);
5872 
5873     // EXTRACT_SUBVECTOR of CONCAT_VECTOR can be simplified if the pieces of
5874     // the concat have the same type as the extract.
5875     if (N1.getOpcode() == ISD::CONCAT_VECTORS && N1.getNumOperands() > 0 &&
5876         VT == N1.getOperand(0).getValueType()) {
5877       unsigned Factor = VT.getVectorMinNumElements();
5878       return N1.getOperand(N2C->getZExtValue() / Factor);
5879     }
5880 
5881     // EXTRACT_SUBVECTOR of INSERT_SUBVECTOR is often created
5882     // during shuffle legalization.
5883     if (N1.getOpcode() == ISD::INSERT_SUBVECTOR && N2 == N1.getOperand(2) &&
5884         VT == N1.getOperand(1).getValueType())
5885       return N1.getOperand(1);
5886     break;
5887   }
5888   }
5889 
5890   // Perform trivial constant folding.
5891   if (SDValue SV = FoldConstantArithmetic(Opcode, DL, VT, {N1, N2}))
5892     return SV;
5893 
5894   if (SDValue V = foldConstantFPMath(Opcode, DL, VT, N1, N2))
5895     return V;
5896 
5897   // Canonicalize an UNDEF to the RHS, even over a constant.
5898   if (N1.isUndef()) {
5899     if (TLI->isCommutativeBinOp(Opcode)) {
5900       std::swap(N1, N2);
5901     } else {
5902       switch (Opcode) {
5903       case ISD::SIGN_EXTEND_INREG:
5904       case ISD::SUB:
5905         return getUNDEF(VT);     // fold op(undef, arg2) -> undef
5906       case ISD::UDIV:
5907       case ISD::SDIV:
5908       case ISD::UREM:
5909       case ISD::SREM:
5910       case ISD::SSUBSAT:
5911       case ISD::USUBSAT:
5912         return getConstant(0, DL, VT);    // fold op(undef, arg2) -> 0
5913       }
5914     }
5915   }
5916 
5917   // Fold a bunch of operators when the RHS is undef.
5918   if (N2.isUndef()) {
5919     switch (Opcode) {
5920     case ISD::XOR:
5921       if (N1.isUndef())
5922         // Handle undef ^ undef -> 0 special case. This is a common
5923         // idiom (misuse).
5924         return getConstant(0, DL, VT);
5925       LLVM_FALLTHROUGH;
5926     case ISD::ADD:
5927     case ISD::SUB:
5928     case ISD::UDIV:
5929     case ISD::SDIV:
5930     case ISD::UREM:
5931     case ISD::SREM:
5932       return getUNDEF(VT);       // fold op(arg1, undef) -> undef
5933     case ISD::MUL:
5934     case ISD::AND:
5935     case ISD::SSUBSAT:
5936     case ISD::USUBSAT:
5937       return getConstant(0, DL, VT);  // fold op(arg1, undef) -> 0
5938     case ISD::OR:
5939     case ISD::SADDSAT:
5940     case ISD::UADDSAT:
5941       return getAllOnesConstant(DL, VT);
5942     }
5943   }
5944 
5945   // Memoize this node if possible.
5946   SDNode *N;
5947   SDVTList VTs = getVTList(VT);
5948   SDValue Ops[] = {N1, N2};
5949   if (VT != MVT::Glue) {
5950     FoldingSetNodeID ID;
5951     AddNodeIDNode(ID, Opcode, VTs, Ops);
5952     void *IP = nullptr;
5953     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
5954       E->intersectFlagsWith(Flags);
5955       return SDValue(E, 0);
5956     }
5957 
5958     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
5959     N->setFlags(Flags);
5960     createOperands(N, Ops);
5961     CSEMap.InsertNode(N, IP);
5962   } else {
5963     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
5964     createOperands(N, Ops);
5965   }
5966 
5967   InsertNode(N);
5968   SDValue V = SDValue(N, 0);
5969   NewSDValueDbgMsg(V, "Creating new node: ", this);
5970   return V;
5971 }
5972 
5973 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
5974                               SDValue N1, SDValue N2, SDValue N3) {
5975   SDNodeFlags Flags;
5976   if (Inserter)
5977     Flags = Inserter->getFlags();
5978   return getNode(Opcode, DL, VT, N1, N2, N3, Flags);
5979 }
5980 
5981 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
5982                               SDValue N1, SDValue N2, SDValue N3,
5983                               const SDNodeFlags Flags) {
5984   assert(N1.getOpcode() != ISD::DELETED_NODE &&
5985          N2.getOpcode() != ISD::DELETED_NODE &&
5986          N3.getOpcode() != ISD::DELETED_NODE &&
5987          "Operand is DELETED_NODE!");
5988   // Perform various simplifications.
5989   switch (Opcode) {
5990   case ISD::FMA: {
5991     assert(VT.isFloatingPoint() && "This operator only applies to FP types!");
5992     assert(N1.getValueType() == VT && N2.getValueType() == VT &&
5993            N3.getValueType() == VT && "FMA types must match!");
5994     ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
5995     ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2);
5996     ConstantFPSDNode *N3CFP = dyn_cast<ConstantFPSDNode>(N3);
5997     if (N1CFP && N2CFP && N3CFP) {
5998       APFloat  V1 = N1CFP->getValueAPF();
5999       const APFloat &V2 = N2CFP->getValueAPF();
6000       const APFloat &V3 = N3CFP->getValueAPF();
6001       V1.fusedMultiplyAdd(V2, V3, APFloat::rmNearestTiesToEven);
6002       return getConstantFP(V1, DL, VT);
6003     }
6004     break;
6005   }
6006   case ISD::BUILD_VECTOR: {
6007     // Attempt to simplify BUILD_VECTOR.
6008     SDValue Ops[] = {N1, N2, N3};
6009     if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
6010       return V;
6011     break;
6012   }
6013   case ISD::CONCAT_VECTORS: {
6014     SDValue Ops[] = {N1, N2, N3};
6015     if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this))
6016       return V;
6017     break;
6018   }
6019   case ISD::SETCC: {
6020     assert(VT.isInteger() && "SETCC result type must be an integer!");
6021     assert(N1.getValueType() == N2.getValueType() &&
6022            "SETCC operands must have the same type!");
6023     assert(VT.isVector() == N1.getValueType().isVector() &&
6024            "SETCC type should be vector iff the operand type is vector!");
6025     assert((!VT.isVector() || VT.getVectorElementCount() ==
6026                                   N1.getValueType().getVectorElementCount()) &&
6027            "SETCC vector element counts must match!");
6028     // Use FoldSetCC to simplify SETCC's.
6029     if (SDValue V = FoldSetCC(VT, N1, N2, cast<CondCodeSDNode>(N3)->get(), DL))
6030       return V;
6031     // Vector constant folding.
6032     SDValue Ops[] = {N1, N2, N3};
6033     if (SDValue V = FoldConstantVectorArithmetic(Opcode, DL, VT, Ops)) {
6034       NewSDValueDbgMsg(V, "New node vector constant folding: ", this);
6035       return V;
6036     }
6037     break;
6038   }
6039   case ISD::SELECT:
6040   case ISD::VSELECT:
6041     if (SDValue V = simplifySelect(N1, N2, N3))
6042       return V;
6043     break;
6044   case ISD::VECTOR_SHUFFLE:
6045     llvm_unreachable("should use getVectorShuffle constructor!");
6046   case ISD::INSERT_VECTOR_ELT: {
6047     ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3);
6048     // INSERT_VECTOR_ELT into out-of-bounds element is an UNDEF, except
6049     // for scalable vectors where we will generate appropriate code to
6050     // deal with out-of-bounds cases correctly.
6051     if (N3C && N1.getValueType().isFixedLengthVector() &&
6052         N3C->getZExtValue() >= N1.getValueType().getVectorNumElements())
6053       return getUNDEF(VT);
6054 
6055     // Undefined index can be assumed out-of-bounds, so that's UNDEF too.
6056     if (N3.isUndef())
6057       return getUNDEF(VT);
6058 
6059     // If the inserted element is an UNDEF, just use the input vector.
6060     if (N2.isUndef())
6061       return N1;
6062 
6063     break;
6064   }
6065   case ISD::INSERT_SUBVECTOR: {
6066     // Inserting undef into undef is still undef.
6067     if (N1.isUndef() && N2.isUndef())
6068       return getUNDEF(VT);
6069 
6070     EVT N2VT = N2.getValueType();
6071     assert(VT == N1.getValueType() &&
6072            "Dest and insert subvector source types must match!");
6073     assert(VT.isVector() && N2VT.isVector() &&
6074            "Insert subvector VTs must be vectors!");
6075     assert((VT.isScalableVector() || N2VT.isFixedLengthVector()) &&
6076            "Cannot insert a scalable vector into a fixed length vector!");
6077     assert((VT.isScalableVector() != N2VT.isScalableVector() ||
6078             VT.getVectorMinNumElements() >= N2VT.getVectorMinNumElements()) &&
6079            "Insert subvector must be from smaller vector to larger vector!");
6080     assert(isa<ConstantSDNode>(N3) &&
6081            "Insert subvector index must be constant");
6082     assert((VT.isScalableVector() != N2VT.isScalableVector() ||
6083             (N2VT.getVectorMinNumElements() +
6084              cast<ConstantSDNode>(N3)->getZExtValue()) <=
6085                 VT.getVectorMinNumElements()) &&
6086            "Insert subvector overflow!");
6087     assert(cast<ConstantSDNode>(N3)->getAPIntValue().getBitWidth() ==
6088                TLI->getVectorIdxTy(getDataLayout()).getFixedSizeInBits() &&
6089            "Constant index for INSERT_SUBVECTOR has an invalid size");
6090 
6091     // Trivial insertion.
6092     if (VT == N2VT)
6093       return N2;
6094 
6095     // If this is an insert of an extracted vector into an undef vector, we
6096     // can just use the input to the extract.
6097     if (N1.isUndef() && N2.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
6098         N2.getOperand(1) == N3 && N2.getOperand(0).getValueType() == VT)
6099       return N2.getOperand(0);
6100     break;
6101   }
6102   case ISD::BITCAST:
6103     // Fold bit_convert nodes from a type to themselves.
6104     if (N1.getValueType() == VT)
6105       return N1;
6106     break;
6107   }
6108 
6109   // Memoize node if it doesn't produce a flag.
6110   SDNode *N;
6111   SDVTList VTs = getVTList(VT);
6112   SDValue Ops[] = {N1, N2, N3};
6113   if (VT != MVT::Glue) {
6114     FoldingSetNodeID ID;
6115     AddNodeIDNode(ID, Opcode, VTs, Ops);
6116     void *IP = nullptr;
6117     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
6118       E->intersectFlagsWith(Flags);
6119       return SDValue(E, 0);
6120     }
6121 
6122     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
6123     N->setFlags(Flags);
6124     createOperands(N, Ops);
6125     CSEMap.InsertNode(N, IP);
6126   } else {
6127     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
6128     createOperands(N, Ops);
6129   }
6130 
6131   InsertNode(N);
6132   SDValue V = SDValue(N, 0);
6133   NewSDValueDbgMsg(V, "Creating new node: ", this);
6134   return V;
6135 }
6136 
6137 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
6138                               SDValue N1, SDValue N2, SDValue N3, SDValue N4) {
6139   SDValue Ops[] = { N1, N2, N3, N4 };
6140   return getNode(Opcode, DL, VT, Ops);
6141 }
6142 
6143 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
6144                               SDValue N1, SDValue N2, SDValue N3, SDValue N4,
6145                               SDValue N5) {
6146   SDValue Ops[] = { N1, N2, N3, N4, N5 };
6147   return getNode(Opcode, DL, VT, Ops);
6148 }
6149 
6150 /// getStackArgumentTokenFactor - Compute a TokenFactor to force all
6151 /// the incoming stack arguments to be loaded from the stack.
6152 SDValue SelectionDAG::getStackArgumentTokenFactor(SDValue Chain) {
6153   SmallVector<SDValue, 8> ArgChains;
6154 
6155   // Include the original chain at the beginning of the list. When this is
6156   // used by target LowerCall hooks, this helps legalize find the
6157   // CALLSEQ_BEGIN node.
6158   ArgChains.push_back(Chain);
6159 
6160   // Add a chain value for each stack argument.
6161   for (SDNode::use_iterator U = getEntryNode().getNode()->use_begin(),
6162        UE = getEntryNode().getNode()->use_end(); U != UE; ++U)
6163     if (LoadSDNode *L = dyn_cast<LoadSDNode>(*U))
6164       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
6165         if (FI->getIndex() < 0)
6166           ArgChains.push_back(SDValue(L, 1));
6167 
6168   // Build a tokenfactor for all the chains.
6169   return getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains);
6170 }
6171 
6172 /// getMemsetValue - Vectorized representation of the memset value
6173 /// operand.
6174 static SDValue getMemsetValue(SDValue Value, EVT VT, SelectionDAG &DAG,
6175                               const SDLoc &dl) {
6176   assert(!Value.isUndef());
6177 
6178   unsigned NumBits = VT.getScalarSizeInBits();
6179   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
6180     assert(C->getAPIntValue().getBitWidth() == 8);
6181     APInt Val = APInt::getSplat(NumBits, C->getAPIntValue());
6182     if (VT.isInteger()) {
6183       bool IsOpaque = VT.getSizeInBits() > 64 ||
6184           !DAG.getTargetLoweringInfo().isLegalStoreImmediate(C->getSExtValue());
6185       return DAG.getConstant(Val, dl, VT, false, IsOpaque);
6186     }
6187     return DAG.getConstantFP(APFloat(DAG.EVTToAPFloatSemantics(VT), Val), dl,
6188                              VT);
6189   }
6190 
6191   assert(Value.getValueType() == MVT::i8 && "memset with non-byte fill value?");
6192   EVT IntVT = VT.getScalarType();
6193   if (!IntVT.isInteger())
6194     IntVT = EVT::getIntegerVT(*DAG.getContext(), IntVT.getSizeInBits());
6195 
6196   Value = DAG.getNode(ISD::ZERO_EXTEND, dl, IntVT, Value);
6197   if (NumBits > 8) {
6198     // Use a multiplication with 0x010101... to extend the input to the
6199     // required length.
6200     APInt Magic = APInt::getSplat(NumBits, APInt(8, 0x01));
6201     Value = DAG.getNode(ISD::MUL, dl, IntVT, Value,
6202                         DAG.getConstant(Magic, dl, IntVT));
6203   }
6204 
6205   if (VT != Value.getValueType() && !VT.isInteger())
6206     Value = DAG.getBitcast(VT.getScalarType(), Value);
6207   if (VT != Value.getValueType())
6208     Value = DAG.getSplatBuildVector(VT, dl, Value);
6209 
6210   return Value;
6211 }
6212 
6213 /// getMemsetStringVal - Similar to getMemsetValue. Except this is only
6214 /// used when a memcpy is turned into a memset when the source is a constant
6215 /// string ptr.
6216 static SDValue getMemsetStringVal(EVT VT, const SDLoc &dl, SelectionDAG &DAG,
6217                                   const TargetLowering &TLI,
6218                                   const ConstantDataArraySlice &Slice) {
6219   // Handle vector with all elements zero.
6220   if (Slice.Array == nullptr) {
6221     if (VT.isInteger())
6222       return DAG.getConstant(0, dl, VT);
6223     if (VT == MVT::f32 || VT == MVT::f64 || VT == MVT::f128)
6224       return DAG.getConstantFP(0.0, dl, VT);
6225     if (VT.isVector()) {
6226       unsigned NumElts = VT.getVectorNumElements();
6227       MVT EltVT = (VT.getVectorElementType() == MVT::f32) ? MVT::i32 : MVT::i64;
6228       return DAG.getNode(ISD::BITCAST, dl, VT,
6229                          DAG.getConstant(0, dl,
6230                                          EVT::getVectorVT(*DAG.getContext(),
6231                                                           EltVT, NumElts)));
6232     }
6233     llvm_unreachable("Expected type!");
6234   }
6235 
6236   assert(!VT.isVector() && "Can't handle vector type here!");
6237   unsigned NumVTBits = VT.getSizeInBits();
6238   unsigned NumVTBytes = NumVTBits / 8;
6239   unsigned NumBytes = std::min(NumVTBytes, unsigned(Slice.Length));
6240 
6241   APInt Val(NumVTBits, 0);
6242   if (DAG.getDataLayout().isLittleEndian()) {
6243     for (unsigned i = 0; i != NumBytes; ++i)
6244       Val |= (uint64_t)(unsigned char)Slice[i] << i*8;
6245   } else {
6246     for (unsigned i = 0; i != NumBytes; ++i)
6247       Val |= (uint64_t)(unsigned char)Slice[i] << (NumVTBytes-i-1)*8;
6248   }
6249 
6250   // If the "cost" of materializing the integer immediate is less than the cost
6251   // of a load, then it is cost effective to turn the load into the immediate.
6252   Type *Ty = VT.getTypeForEVT(*DAG.getContext());
6253   if (TLI.shouldConvertConstantLoadToIntImm(Val, Ty))
6254     return DAG.getConstant(Val, dl, VT);
6255   return SDValue(nullptr, 0);
6256 }
6257 
6258 SDValue SelectionDAG::getMemBasePlusOffset(SDValue Base, TypeSize Offset,
6259                                            const SDLoc &DL,
6260                                            const SDNodeFlags Flags) {
6261   EVT VT = Base.getValueType();
6262   SDValue Index;
6263 
6264   if (Offset.isScalable())
6265     Index = getVScale(DL, Base.getValueType(),
6266                       APInt(Base.getValueSizeInBits().getFixedSize(),
6267                             Offset.getKnownMinSize()));
6268   else
6269     Index = getConstant(Offset.getFixedSize(), DL, VT);
6270 
6271   return getMemBasePlusOffset(Base, Index, DL, Flags);
6272 }
6273 
6274 SDValue SelectionDAG::getMemBasePlusOffset(SDValue Ptr, SDValue Offset,
6275                                            const SDLoc &DL,
6276                                            const SDNodeFlags Flags) {
6277   assert(Offset.getValueType().isInteger());
6278   EVT BasePtrVT = Ptr.getValueType();
6279   return getNode(ISD::ADD, DL, BasePtrVT, Ptr, Offset, Flags);
6280 }
6281 
6282 /// Returns true if memcpy source is constant data.
6283 static bool isMemSrcFromConstant(SDValue Src, ConstantDataArraySlice &Slice) {
6284   uint64_t SrcDelta = 0;
6285   GlobalAddressSDNode *G = nullptr;
6286   if (Src.getOpcode() == ISD::GlobalAddress)
6287     G = cast<GlobalAddressSDNode>(Src);
6288   else if (Src.getOpcode() == ISD::ADD &&
6289            Src.getOperand(0).getOpcode() == ISD::GlobalAddress &&
6290            Src.getOperand(1).getOpcode() == ISD::Constant) {
6291     G = cast<GlobalAddressSDNode>(Src.getOperand(0));
6292     SrcDelta = cast<ConstantSDNode>(Src.getOperand(1))->getZExtValue();
6293   }
6294   if (!G)
6295     return false;
6296 
6297   return getConstantDataArrayInfo(G->getGlobal(), Slice, 8,
6298                                   SrcDelta + G->getOffset());
6299 }
6300 
6301 static bool shouldLowerMemFuncForSize(const MachineFunction &MF,
6302                                       SelectionDAG &DAG) {
6303   // On Darwin, -Os means optimize for size without hurting performance, so
6304   // only really optimize for size when -Oz (MinSize) is used.
6305   if (MF.getTarget().getTargetTriple().isOSDarwin())
6306     return MF.getFunction().hasMinSize();
6307   return DAG.shouldOptForSize();
6308 }
6309 
6310 static void chainLoadsAndStoresForMemcpy(SelectionDAG &DAG, const SDLoc &dl,
6311                           SmallVector<SDValue, 32> &OutChains, unsigned From,
6312                           unsigned To, SmallVector<SDValue, 16> &OutLoadChains,
6313                           SmallVector<SDValue, 16> &OutStoreChains) {
6314   assert(OutLoadChains.size() && "Missing loads in memcpy inlining");
6315   assert(OutStoreChains.size() && "Missing stores in memcpy inlining");
6316   SmallVector<SDValue, 16> GluedLoadChains;
6317   for (unsigned i = From; i < To; ++i) {
6318     OutChains.push_back(OutLoadChains[i]);
6319     GluedLoadChains.push_back(OutLoadChains[i]);
6320   }
6321 
6322   // Chain for all loads.
6323   SDValue LoadToken = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
6324                                   GluedLoadChains);
6325 
6326   for (unsigned i = From; i < To; ++i) {
6327     StoreSDNode *ST = dyn_cast<StoreSDNode>(OutStoreChains[i]);
6328     SDValue NewStore = DAG.getTruncStore(LoadToken, dl, ST->getValue(),
6329                                   ST->getBasePtr(), ST->getMemoryVT(),
6330                                   ST->getMemOperand());
6331     OutChains.push_back(NewStore);
6332   }
6333 }
6334 
6335 static SDValue getMemcpyLoadsAndStores(SelectionDAG &DAG, const SDLoc &dl,
6336                                        SDValue Chain, SDValue Dst, SDValue Src,
6337                                        uint64_t Size, Align Alignment,
6338                                        bool isVol, bool AlwaysInline,
6339                                        MachinePointerInfo DstPtrInfo,
6340                                        MachinePointerInfo SrcPtrInfo,
6341                                        const AAMDNodes &AAInfo) {
6342   // Turn a memcpy of undef to nop.
6343   // FIXME: We need to honor volatile even is Src is undef.
6344   if (Src.isUndef())
6345     return Chain;
6346 
6347   // Expand memcpy to a series of load and store ops if the size operand falls
6348   // below a certain threshold.
6349   // TODO: In the AlwaysInline case, if the size is big then generate a loop
6350   // rather than maybe a humongous number of loads and stores.
6351   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6352   const DataLayout &DL = DAG.getDataLayout();
6353   LLVMContext &C = *DAG.getContext();
6354   std::vector<EVT> MemOps;
6355   bool DstAlignCanChange = false;
6356   MachineFunction &MF = DAG.getMachineFunction();
6357   MachineFrameInfo &MFI = MF.getFrameInfo();
6358   bool OptSize = shouldLowerMemFuncForSize(MF, DAG);
6359   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
6360   if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
6361     DstAlignCanChange = true;
6362   MaybeAlign SrcAlign = DAG.InferPtrAlign(Src);
6363   if (!SrcAlign || Alignment > *SrcAlign)
6364     SrcAlign = Alignment;
6365   assert(SrcAlign && "SrcAlign must be set");
6366   ConstantDataArraySlice Slice;
6367   // If marked as volatile, perform a copy even when marked as constant.
6368   bool CopyFromConstant = !isVol && isMemSrcFromConstant(Src, Slice);
6369   bool isZeroConstant = CopyFromConstant && Slice.Array == nullptr;
6370   unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemcpy(OptSize);
6371   const MemOp Op = isZeroConstant
6372                        ? MemOp::Set(Size, DstAlignCanChange, Alignment,
6373                                     /*IsZeroMemset*/ true, isVol)
6374                        : MemOp::Copy(Size, DstAlignCanChange, Alignment,
6375                                      *SrcAlign, isVol, CopyFromConstant);
6376   if (!TLI.findOptimalMemOpLowering(
6377           MemOps, Limit, Op, DstPtrInfo.getAddrSpace(),
6378           SrcPtrInfo.getAddrSpace(), MF.getFunction().getAttributes()))
6379     return SDValue();
6380 
6381   if (DstAlignCanChange) {
6382     Type *Ty = MemOps[0].getTypeForEVT(C);
6383     Align NewAlign = DL.getABITypeAlign(Ty);
6384 
6385     // Don't promote to an alignment that would require dynamic stack
6386     // realignment.
6387     const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
6388     if (!TRI->hasStackRealignment(MF))
6389       while (NewAlign > Alignment && DL.exceedsNaturalStackAlignment(NewAlign))
6390         NewAlign = NewAlign / 2;
6391 
6392     if (NewAlign > Alignment) {
6393       // Give the stack frame object a larger alignment if needed.
6394       if (MFI.getObjectAlign(FI->getIndex()) < NewAlign)
6395         MFI.setObjectAlignment(FI->getIndex(), NewAlign);
6396       Alignment = NewAlign;
6397     }
6398   }
6399 
6400   // Prepare AAInfo for loads/stores after lowering this memcpy.
6401   AAMDNodes NewAAInfo = AAInfo;
6402   NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr;
6403 
6404   MachineMemOperand::Flags MMOFlags =
6405       isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone;
6406   SmallVector<SDValue, 16> OutLoadChains;
6407   SmallVector<SDValue, 16> OutStoreChains;
6408   SmallVector<SDValue, 32> OutChains;
6409   unsigned NumMemOps = MemOps.size();
6410   uint64_t SrcOff = 0, DstOff = 0;
6411   for (unsigned i = 0; i != NumMemOps; ++i) {
6412     EVT VT = MemOps[i];
6413     unsigned VTSize = VT.getSizeInBits() / 8;
6414     SDValue Value, Store;
6415 
6416     if (VTSize > Size) {
6417       // Issuing an unaligned load / store pair  that overlaps with the previous
6418       // pair. Adjust the offset accordingly.
6419       assert(i == NumMemOps-1 && i != 0);
6420       SrcOff -= VTSize - Size;
6421       DstOff -= VTSize - Size;
6422     }
6423 
6424     if (CopyFromConstant &&
6425         (isZeroConstant || (VT.isInteger() && !VT.isVector()))) {
6426       // It's unlikely a store of a vector immediate can be done in a single
6427       // instruction. It would require a load from a constantpool first.
6428       // We only handle zero vectors here.
6429       // FIXME: Handle other cases where store of vector immediate is done in
6430       // a single instruction.
6431       ConstantDataArraySlice SubSlice;
6432       if (SrcOff < Slice.Length) {
6433         SubSlice = Slice;
6434         SubSlice.move(SrcOff);
6435       } else {
6436         // This is an out-of-bounds access and hence UB. Pretend we read zero.
6437         SubSlice.Array = nullptr;
6438         SubSlice.Offset = 0;
6439         SubSlice.Length = VTSize;
6440       }
6441       Value = getMemsetStringVal(VT, dl, DAG, TLI, SubSlice);
6442       if (Value.getNode()) {
6443         Store = DAG.getStore(
6444             Chain, dl, Value,
6445             DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl),
6446             DstPtrInfo.getWithOffset(DstOff), Alignment, MMOFlags, NewAAInfo);
6447         OutChains.push_back(Store);
6448       }
6449     }
6450 
6451     if (!Store.getNode()) {
6452       // The type might not be legal for the target.  This should only happen
6453       // if the type is smaller than a legal type, as on PPC, so the right
6454       // thing to do is generate a LoadExt/StoreTrunc pair.  These simplify
6455       // to Load/Store if NVT==VT.
6456       // FIXME does the case above also need this?
6457       EVT NVT = TLI.getTypeToTransformTo(C, VT);
6458       assert(NVT.bitsGE(VT));
6459 
6460       bool isDereferenceable =
6461         SrcPtrInfo.getWithOffset(SrcOff).isDereferenceable(VTSize, C, DL);
6462       MachineMemOperand::Flags SrcMMOFlags = MMOFlags;
6463       if (isDereferenceable)
6464         SrcMMOFlags |= MachineMemOperand::MODereferenceable;
6465 
6466       Value = DAG.getExtLoad(
6467           ISD::EXTLOAD, dl, NVT, Chain,
6468           DAG.getMemBasePlusOffset(Src, TypeSize::Fixed(SrcOff), dl),
6469           SrcPtrInfo.getWithOffset(SrcOff), VT,
6470           commonAlignment(*SrcAlign, SrcOff), SrcMMOFlags, NewAAInfo);
6471       OutLoadChains.push_back(Value.getValue(1));
6472 
6473       Store = DAG.getTruncStore(
6474           Chain, dl, Value,
6475           DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl),
6476           DstPtrInfo.getWithOffset(DstOff), VT, Alignment, MMOFlags, NewAAInfo);
6477       OutStoreChains.push_back(Store);
6478     }
6479     SrcOff += VTSize;
6480     DstOff += VTSize;
6481     Size -= VTSize;
6482   }
6483 
6484   unsigned GluedLdStLimit = MaxLdStGlue == 0 ?
6485                                 TLI.getMaxGluedStoresPerMemcpy() : MaxLdStGlue;
6486   unsigned NumLdStInMemcpy = OutStoreChains.size();
6487 
6488   if (NumLdStInMemcpy) {
6489     // It may be that memcpy might be converted to memset if it's memcpy
6490     // of constants. In such a case, we won't have loads and stores, but
6491     // just stores. In the absence of loads, there is nothing to gang up.
6492     if ((GluedLdStLimit <= 1) || !EnableMemCpyDAGOpt) {
6493       // If target does not care, just leave as it.
6494       for (unsigned i = 0; i < NumLdStInMemcpy; ++i) {
6495         OutChains.push_back(OutLoadChains[i]);
6496         OutChains.push_back(OutStoreChains[i]);
6497       }
6498     } else {
6499       // Ld/St less than/equal limit set by target.
6500       if (NumLdStInMemcpy <= GluedLdStLimit) {
6501           chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, 0,
6502                                         NumLdStInMemcpy, OutLoadChains,
6503                                         OutStoreChains);
6504       } else {
6505         unsigned NumberLdChain =  NumLdStInMemcpy / GluedLdStLimit;
6506         unsigned RemainingLdStInMemcpy = NumLdStInMemcpy % GluedLdStLimit;
6507         unsigned GlueIter = 0;
6508 
6509         for (unsigned cnt = 0; cnt < NumberLdChain; ++cnt) {
6510           unsigned IndexFrom = NumLdStInMemcpy - GlueIter - GluedLdStLimit;
6511           unsigned IndexTo   = NumLdStInMemcpy - GlueIter;
6512 
6513           chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, IndexFrom, IndexTo,
6514                                        OutLoadChains, OutStoreChains);
6515           GlueIter += GluedLdStLimit;
6516         }
6517 
6518         // Residual ld/st.
6519         if (RemainingLdStInMemcpy) {
6520           chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, 0,
6521                                         RemainingLdStInMemcpy, OutLoadChains,
6522                                         OutStoreChains);
6523         }
6524       }
6525     }
6526   }
6527   return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
6528 }
6529 
6530 static SDValue getMemmoveLoadsAndStores(SelectionDAG &DAG, const SDLoc &dl,
6531                                         SDValue Chain, SDValue Dst, SDValue Src,
6532                                         uint64_t Size, Align Alignment,
6533                                         bool isVol, bool AlwaysInline,
6534                                         MachinePointerInfo DstPtrInfo,
6535                                         MachinePointerInfo SrcPtrInfo,
6536                                         const AAMDNodes &AAInfo) {
6537   // Turn a memmove of undef to nop.
6538   // FIXME: We need to honor volatile even is Src is undef.
6539   if (Src.isUndef())
6540     return Chain;
6541 
6542   // Expand memmove to a series of load and store ops if the size operand falls
6543   // below a certain threshold.
6544   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6545   const DataLayout &DL = DAG.getDataLayout();
6546   LLVMContext &C = *DAG.getContext();
6547   std::vector<EVT> MemOps;
6548   bool DstAlignCanChange = false;
6549   MachineFunction &MF = DAG.getMachineFunction();
6550   MachineFrameInfo &MFI = MF.getFrameInfo();
6551   bool OptSize = shouldLowerMemFuncForSize(MF, DAG);
6552   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
6553   if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
6554     DstAlignCanChange = true;
6555   MaybeAlign SrcAlign = DAG.InferPtrAlign(Src);
6556   if (!SrcAlign || Alignment > *SrcAlign)
6557     SrcAlign = Alignment;
6558   assert(SrcAlign && "SrcAlign must be set");
6559   unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemmove(OptSize);
6560   if (!TLI.findOptimalMemOpLowering(
6561           MemOps, Limit,
6562           MemOp::Copy(Size, DstAlignCanChange, Alignment, *SrcAlign,
6563                       /*IsVolatile*/ true),
6564           DstPtrInfo.getAddrSpace(), SrcPtrInfo.getAddrSpace(),
6565           MF.getFunction().getAttributes()))
6566     return SDValue();
6567 
6568   if (DstAlignCanChange) {
6569     Type *Ty = MemOps[0].getTypeForEVT(C);
6570     Align NewAlign = DL.getABITypeAlign(Ty);
6571     if (NewAlign > Alignment) {
6572       // Give the stack frame object a larger alignment if needed.
6573       if (MFI.getObjectAlign(FI->getIndex()) < NewAlign)
6574         MFI.setObjectAlignment(FI->getIndex(), NewAlign);
6575       Alignment = NewAlign;
6576     }
6577   }
6578 
6579   // Prepare AAInfo for loads/stores after lowering this memmove.
6580   AAMDNodes NewAAInfo = AAInfo;
6581   NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr;
6582 
6583   MachineMemOperand::Flags MMOFlags =
6584       isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone;
6585   uint64_t SrcOff = 0, DstOff = 0;
6586   SmallVector<SDValue, 8> LoadValues;
6587   SmallVector<SDValue, 8> LoadChains;
6588   SmallVector<SDValue, 8> OutChains;
6589   unsigned NumMemOps = MemOps.size();
6590   for (unsigned i = 0; i < NumMemOps; i++) {
6591     EVT VT = MemOps[i];
6592     unsigned VTSize = VT.getSizeInBits() / 8;
6593     SDValue Value;
6594 
6595     bool isDereferenceable =
6596       SrcPtrInfo.getWithOffset(SrcOff).isDereferenceable(VTSize, C, DL);
6597     MachineMemOperand::Flags SrcMMOFlags = MMOFlags;
6598     if (isDereferenceable)
6599       SrcMMOFlags |= MachineMemOperand::MODereferenceable;
6600 
6601     Value = DAG.getLoad(
6602         VT, dl, Chain,
6603         DAG.getMemBasePlusOffset(Src, TypeSize::Fixed(SrcOff), dl),
6604         SrcPtrInfo.getWithOffset(SrcOff), *SrcAlign, SrcMMOFlags, NewAAInfo);
6605     LoadValues.push_back(Value);
6606     LoadChains.push_back(Value.getValue(1));
6607     SrcOff += VTSize;
6608   }
6609   Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
6610   OutChains.clear();
6611   for (unsigned i = 0; i < NumMemOps; i++) {
6612     EVT VT = MemOps[i];
6613     unsigned VTSize = VT.getSizeInBits() / 8;
6614     SDValue Store;
6615 
6616     Store = DAG.getStore(
6617         Chain, dl, LoadValues[i],
6618         DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl),
6619         DstPtrInfo.getWithOffset(DstOff), Alignment, MMOFlags, NewAAInfo);
6620     OutChains.push_back(Store);
6621     DstOff += VTSize;
6622   }
6623 
6624   return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
6625 }
6626 
6627 /// Lower the call to 'memset' intrinsic function into a series of store
6628 /// operations.
6629 ///
6630 /// \param DAG Selection DAG where lowered code is placed.
6631 /// \param dl Link to corresponding IR location.
6632 /// \param Chain Control flow dependency.
6633 /// \param Dst Pointer to destination memory location.
6634 /// \param Src Value of byte to write into the memory.
6635 /// \param Size Number of bytes to write.
6636 /// \param Alignment Alignment of the destination in bytes.
6637 /// \param isVol True if destination is volatile.
6638 /// \param DstPtrInfo IR information on the memory pointer.
6639 /// \returns New head in the control flow, if lowering was successful, empty
6640 /// SDValue otherwise.
6641 ///
6642 /// The function tries to replace 'llvm.memset' intrinsic with several store
6643 /// operations and value calculation code. This is usually profitable for small
6644 /// memory size.
6645 static SDValue getMemsetStores(SelectionDAG &DAG, const SDLoc &dl,
6646                                SDValue Chain, SDValue Dst, SDValue Src,
6647                                uint64_t Size, Align Alignment, bool isVol,
6648                                MachinePointerInfo DstPtrInfo,
6649                                const AAMDNodes &AAInfo) {
6650   // Turn a memset of undef to nop.
6651   // FIXME: We need to honor volatile even is Src is undef.
6652   if (Src.isUndef())
6653     return Chain;
6654 
6655   // Expand memset to a series of load/store ops if the size operand
6656   // falls below a certain threshold.
6657   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6658   std::vector<EVT> MemOps;
6659   bool DstAlignCanChange = false;
6660   MachineFunction &MF = DAG.getMachineFunction();
6661   MachineFrameInfo &MFI = MF.getFrameInfo();
6662   bool OptSize = shouldLowerMemFuncForSize(MF, DAG);
6663   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
6664   if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
6665     DstAlignCanChange = true;
6666   bool IsZeroVal =
6667     isa<ConstantSDNode>(Src) && cast<ConstantSDNode>(Src)->isNullValue();
6668   if (!TLI.findOptimalMemOpLowering(
6669           MemOps, TLI.getMaxStoresPerMemset(OptSize),
6670           MemOp::Set(Size, DstAlignCanChange, Alignment, IsZeroVal, isVol),
6671           DstPtrInfo.getAddrSpace(), ~0u, MF.getFunction().getAttributes()))
6672     return SDValue();
6673 
6674   if (DstAlignCanChange) {
6675     Type *Ty = MemOps[0].getTypeForEVT(*DAG.getContext());
6676     Align NewAlign = DAG.getDataLayout().getABITypeAlign(Ty);
6677     if (NewAlign > Alignment) {
6678       // Give the stack frame object a larger alignment if needed.
6679       if (MFI.getObjectAlign(FI->getIndex()) < NewAlign)
6680         MFI.setObjectAlignment(FI->getIndex(), NewAlign);
6681       Alignment = NewAlign;
6682     }
6683   }
6684 
6685   SmallVector<SDValue, 8> OutChains;
6686   uint64_t DstOff = 0;
6687   unsigned NumMemOps = MemOps.size();
6688 
6689   // Find the largest store and generate the bit pattern for it.
6690   EVT LargestVT = MemOps[0];
6691   for (unsigned i = 1; i < NumMemOps; i++)
6692     if (MemOps[i].bitsGT(LargestVT))
6693       LargestVT = MemOps[i];
6694   SDValue MemSetValue = getMemsetValue(Src, LargestVT, DAG, dl);
6695 
6696   // Prepare AAInfo for loads/stores after lowering this memset.
6697   AAMDNodes NewAAInfo = AAInfo;
6698   NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr;
6699 
6700   for (unsigned i = 0; i < NumMemOps; i++) {
6701     EVT VT = MemOps[i];
6702     unsigned VTSize = VT.getSizeInBits() / 8;
6703     if (VTSize > Size) {
6704       // Issuing an unaligned load / store pair  that overlaps with the previous
6705       // pair. Adjust the offset accordingly.
6706       assert(i == NumMemOps-1 && i != 0);
6707       DstOff -= VTSize - Size;
6708     }
6709 
6710     // If this store is smaller than the largest store see whether we can get
6711     // the smaller value for free with a truncate.
6712     SDValue Value = MemSetValue;
6713     if (VT.bitsLT(LargestVT)) {
6714       if (!LargestVT.isVector() && !VT.isVector() &&
6715           TLI.isTruncateFree(LargestVT, VT))
6716         Value = DAG.getNode(ISD::TRUNCATE, dl, VT, MemSetValue);
6717       else
6718         Value = getMemsetValue(Src, VT, DAG, dl);
6719     }
6720     assert(Value.getValueType() == VT && "Value with wrong type.");
6721     SDValue Store = DAG.getStore(
6722         Chain, dl, Value,
6723         DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl),
6724         DstPtrInfo.getWithOffset(DstOff), Alignment,
6725         isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone,
6726         NewAAInfo);
6727     OutChains.push_back(Store);
6728     DstOff += VT.getSizeInBits() / 8;
6729     Size -= VTSize;
6730   }
6731 
6732   return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
6733 }
6734 
6735 static void checkAddrSpaceIsValidForLibcall(const TargetLowering *TLI,
6736                                             unsigned AS) {
6737   // Lowering memcpy / memset / memmove intrinsics to calls is only valid if all
6738   // pointer operands can be losslessly bitcasted to pointers of address space 0
6739   if (AS != 0 && !TLI->getTargetMachine().isNoopAddrSpaceCast(AS, 0)) {
6740     report_fatal_error("cannot lower memory intrinsic in address space " +
6741                        Twine(AS));
6742   }
6743 }
6744 
6745 SDValue SelectionDAG::getMemcpy(SDValue Chain, const SDLoc &dl, SDValue Dst,
6746                                 SDValue Src, SDValue Size, Align Alignment,
6747                                 bool isVol, bool AlwaysInline, bool isTailCall,
6748                                 MachinePointerInfo DstPtrInfo,
6749                                 MachinePointerInfo SrcPtrInfo,
6750                                 const AAMDNodes &AAInfo) {
6751   // Check to see if we should lower the memcpy to loads and stores first.
6752   // For cases within the target-specified limits, this is the best choice.
6753   ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
6754   if (ConstantSize) {
6755     // Memcpy with size zero? Just return the original chain.
6756     if (ConstantSize->isNullValue())
6757       return Chain;
6758 
6759     SDValue Result = getMemcpyLoadsAndStores(
6760         *this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), Alignment,
6761         isVol, false, DstPtrInfo, SrcPtrInfo, AAInfo);
6762     if (Result.getNode())
6763       return Result;
6764   }
6765 
6766   // Then check to see if we should lower the memcpy with target-specific
6767   // code. If the target chooses to do this, this is the next best.
6768   if (TSI) {
6769     SDValue Result = TSI->EmitTargetCodeForMemcpy(
6770         *this, dl, Chain, Dst, Src, Size, Alignment, isVol, AlwaysInline,
6771         DstPtrInfo, SrcPtrInfo);
6772     if (Result.getNode())
6773       return Result;
6774   }
6775 
6776   // If we really need inline code and the target declined to provide it,
6777   // use a (potentially long) sequence of loads and stores.
6778   if (AlwaysInline) {
6779     assert(ConstantSize && "AlwaysInline requires a constant size!");
6780     return getMemcpyLoadsAndStores(*this, dl, Chain, Dst, Src,
6781                                    ConstantSize->getZExtValue(), Alignment,
6782                                    isVol, true, DstPtrInfo, SrcPtrInfo, AAInfo);
6783   }
6784 
6785   checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace());
6786   checkAddrSpaceIsValidForLibcall(TLI, SrcPtrInfo.getAddrSpace());
6787 
6788   // FIXME: If the memcpy is volatile (isVol), lowering it to a plain libc
6789   // memcpy is not guaranteed to be safe. libc memcpys aren't required to
6790   // respect volatile, so they may do things like read or write memory
6791   // beyond the given memory regions. But fixing this isn't easy, and most
6792   // people don't care.
6793 
6794   // Emit a library call.
6795   TargetLowering::ArgListTy Args;
6796   TargetLowering::ArgListEntry Entry;
6797   Entry.Ty = Type::getInt8PtrTy(*getContext());
6798   Entry.Node = Dst; Args.push_back(Entry);
6799   Entry.Node = Src; Args.push_back(Entry);
6800 
6801   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
6802   Entry.Node = Size; Args.push_back(Entry);
6803   // FIXME: pass in SDLoc
6804   TargetLowering::CallLoweringInfo CLI(*this);
6805   CLI.setDebugLoc(dl)
6806       .setChain(Chain)
6807       .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMCPY),
6808                     Dst.getValueType().getTypeForEVT(*getContext()),
6809                     getExternalSymbol(TLI->getLibcallName(RTLIB::MEMCPY),
6810                                       TLI->getPointerTy(getDataLayout())),
6811                     std::move(Args))
6812       .setDiscardResult()
6813       .setTailCall(isTailCall);
6814 
6815   std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
6816   return CallResult.second;
6817 }
6818 
6819 SDValue SelectionDAG::getAtomicMemcpy(SDValue Chain, const SDLoc &dl,
6820                                       SDValue Dst, unsigned DstAlign,
6821                                       SDValue Src, unsigned SrcAlign,
6822                                       SDValue Size, Type *SizeTy,
6823                                       unsigned ElemSz, bool isTailCall,
6824                                       MachinePointerInfo DstPtrInfo,
6825                                       MachinePointerInfo SrcPtrInfo) {
6826   // Emit a library call.
6827   TargetLowering::ArgListTy Args;
6828   TargetLowering::ArgListEntry Entry;
6829   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
6830   Entry.Node = Dst;
6831   Args.push_back(Entry);
6832 
6833   Entry.Node = Src;
6834   Args.push_back(Entry);
6835 
6836   Entry.Ty = SizeTy;
6837   Entry.Node = Size;
6838   Args.push_back(Entry);
6839 
6840   RTLIB::Libcall LibraryCall =
6841       RTLIB::getMEMCPY_ELEMENT_UNORDERED_ATOMIC(ElemSz);
6842   if (LibraryCall == RTLIB::UNKNOWN_LIBCALL)
6843     report_fatal_error("Unsupported element size");
6844 
6845   TargetLowering::CallLoweringInfo CLI(*this);
6846   CLI.setDebugLoc(dl)
6847       .setChain(Chain)
6848       .setLibCallee(TLI->getLibcallCallingConv(LibraryCall),
6849                     Type::getVoidTy(*getContext()),
6850                     getExternalSymbol(TLI->getLibcallName(LibraryCall),
6851                                       TLI->getPointerTy(getDataLayout())),
6852                     std::move(Args))
6853       .setDiscardResult()
6854       .setTailCall(isTailCall);
6855 
6856   std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
6857   return CallResult.second;
6858 }
6859 
6860 SDValue SelectionDAG::getMemmove(SDValue Chain, const SDLoc &dl, SDValue Dst,
6861                                  SDValue Src, SDValue Size, Align Alignment,
6862                                  bool isVol, bool isTailCall,
6863                                  MachinePointerInfo DstPtrInfo,
6864                                  MachinePointerInfo SrcPtrInfo,
6865                                  const AAMDNodes &AAInfo) {
6866   // Check to see if we should lower the memmove to loads and stores first.
6867   // For cases within the target-specified limits, this is the best choice.
6868   ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
6869   if (ConstantSize) {
6870     // Memmove with size zero? Just return the original chain.
6871     if (ConstantSize->isNullValue())
6872       return Chain;
6873 
6874     SDValue Result = getMemmoveLoadsAndStores(
6875         *this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), Alignment,
6876         isVol, false, DstPtrInfo, SrcPtrInfo, AAInfo);
6877     if (Result.getNode())
6878       return Result;
6879   }
6880 
6881   // Then check to see if we should lower the memmove with target-specific
6882   // code. If the target chooses to do this, this is the next best.
6883   if (TSI) {
6884     SDValue Result =
6885         TSI->EmitTargetCodeForMemmove(*this, dl, Chain, Dst, Src, Size,
6886                                       Alignment, isVol, DstPtrInfo, SrcPtrInfo);
6887     if (Result.getNode())
6888       return Result;
6889   }
6890 
6891   checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace());
6892   checkAddrSpaceIsValidForLibcall(TLI, SrcPtrInfo.getAddrSpace());
6893 
6894   // FIXME: If the memmove is volatile, lowering it to plain libc memmove may
6895   // not be safe.  See memcpy above for more details.
6896 
6897   // Emit a library call.
6898   TargetLowering::ArgListTy Args;
6899   TargetLowering::ArgListEntry Entry;
6900   Entry.Ty = Type::getInt8PtrTy(*getContext());
6901   Entry.Node = Dst; Args.push_back(Entry);
6902   Entry.Node = Src; Args.push_back(Entry);
6903 
6904   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
6905   Entry.Node = Size; Args.push_back(Entry);
6906   // FIXME:  pass in SDLoc
6907   TargetLowering::CallLoweringInfo CLI(*this);
6908   CLI.setDebugLoc(dl)
6909       .setChain(Chain)
6910       .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMMOVE),
6911                     Dst.getValueType().getTypeForEVT(*getContext()),
6912                     getExternalSymbol(TLI->getLibcallName(RTLIB::MEMMOVE),
6913                                       TLI->getPointerTy(getDataLayout())),
6914                     std::move(Args))
6915       .setDiscardResult()
6916       .setTailCall(isTailCall);
6917 
6918   std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
6919   return CallResult.second;
6920 }
6921 
6922 SDValue SelectionDAG::getAtomicMemmove(SDValue Chain, const SDLoc &dl,
6923                                        SDValue Dst, unsigned DstAlign,
6924                                        SDValue Src, unsigned SrcAlign,
6925                                        SDValue Size, Type *SizeTy,
6926                                        unsigned ElemSz, bool isTailCall,
6927                                        MachinePointerInfo DstPtrInfo,
6928                                        MachinePointerInfo SrcPtrInfo) {
6929   // Emit a library call.
6930   TargetLowering::ArgListTy Args;
6931   TargetLowering::ArgListEntry Entry;
6932   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
6933   Entry.Node = Dst;
6934   Args.push_back(Entry);
6935 
6936   Entry.Node = Src;
6937   Args.push_back(Entry);
6938 
6939   Entry.Ty = SizeTy;
6940   Entry.Node = Size;
6941   Args.push_back(Entry);
6942 
6943   RTLIB::Libcall LibraryCall =
6944       RTLIB::getMEMMOVE_ELEMENT_UNORDERED_ATOMIC(ElemSz);
6945   if (LibraryCall == RTLIB::UNKNOWN_LIBCALL)
6946     report_fatal_error("Unsupported element size");
6947 
6948   TargetLowering::CallLoweringInfo CLI(*this);
6949   CLI.setDebugLoc(dl)
6950       .setChain(Chain)
6951       .setLibCallee(TLI->getLibcallCallingConv(LibraryCall),
6952                     Type::getVoidTy(*getContext()),
6953                     getExternalSymbol(TLI->getLibcallName(LibraryCall),
6954                                       TLI->getPointerTy(getDataLayout())),
6955                     std::move(Args))
6956       .setDiscardResult()
6957       .setTailCall(isTailCall);
6958 
6959   std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
6960   return CallResult.second;
6961 }
6962 
6963 SDValue SelectionDAG::getMemset(SDValue Chain, const SDLoc &dl, SDValue Dst,
6964                                 SDValue Src, SDValue Size, Align Alignment,
6965                                 bool isVol, bool isTailCall,
6966                                 MachinePointerInfo DstPtrInfo,
6967                                 const AAMDNodes &AAInfo) {
6968   // Check to see if we should lower the memset to stores first.
6969   // For cases within the target-specified limits, this is the best choice.
6970   ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
6971   if (ConstantSize) {
6972     // Memset with size zero? Just return the original chain.
6973     if (ConstantSize->isNullValue())
6974       return Chain;
6975 
6976     SDValue Result = getMemsetStores(*this, dl, Chain, Dst, Src,
6977                                      ConstantSize->getZExtValue(), Alignment,
6978                                      isVol, DstPtrInfo, AAInfo);
6979 
6980     if (Result.getNode())
6981       return Result;
6982   }
6983 
6984   // Then check to see if we should lower the memset with target-specific
6985   // code. If the target chooses to do this, this is the next best.
6986   if (TSI) {
6987     SDValue Result = TSI->EmitTargetCodeForMemset(
6988         *this, dl, Chain, Dst, Src, Size, Alignment, isVol, DstPtrInfo);
6989     if (Result.getNode())
6990       return Result;
6991   }
6992 
6993   checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace());
6994 
6995   // Emit a library call.
6996   TargetLowering::ArgListTy Args;
6997   TargetLowering::ArgListEntry Entry;
6998   Entry.Node = Dst; Entry.Ty = Type::getInt8PtrTy(*getContext());
6999   Args.push_back(Entry);
7000   Entry.Node = Src;
7001   Entry.Ty = Src.getValueType().getTypeForEVT(*getContext());
7002   Args.push_back(Entry);
7003   Entry.Node = Size;
7004   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
7005   Args.push_back(Entry);
7006 
7007   // FIXME: pass in SDLoc
7008   TargetLowering::CallLoweringInfo CLI(*this);
7009   CLI.setDebugLoc(dl)
7010       .setChain(Chain)
7011       .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMSET),
7012                     Dst.getValueType().getTypeForEVT(*getContext()),
7013                     getExternalSymbol(TLI->getLibcallName(RTLIB::MEMSET),
7014                                       TLI->getPointerTy(getDataLayout())),
7015                     std::move(Args))
7016       .setDiscardResult()
7017       .setTailCall(isTailCall);
7018 
7019   std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
7020   return CallResult.second;
7021 }
7022 
7023 SDValue SelectionDAG::getAtomicMemset(SDValue Chain, const SDLoc &dl,
7024                                       SDValue Dst, unsigned DstAlign,
7025                                       SDValue Value, SDValue Size, Type *SizeTy,
7026                                       unsigned ElemSz, bool isTailCall,
7027                                       MachinePointerInfo DstPtrInfo) {
7028   // Emit a library call.
7029   TargetLowering::ArgListTy Args;
7030   TargetLowering::ArgListEntry Entry;
7031   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
7032   Entry.Node = Dst;
7033   Args.push_back(Entry);
7034 
7035   Entry.Ty = Type::getInt8Ty(*getContext());
7036   Entry.Node = Value;
7037   Args.push_back(Entry);
7038 
7039   Entry.Ty = SizeTy;
7040   Entry.Node = Size;
7041   Args.push_back(Entry);
7042 
7043   RTLIB::Libcall LibraryCall =
7044       RTLIB::getMEMSET_ELEMENT_UNORDERED_ATOMIC(ElemSz);
7045   if (LibraryCall == RTLIB::UNKNOWN_LIBCALL)
7046     report_fatal_error("Unsupported element size");
7047 
7048   TargetLowering::CallLoweringInfo CLI(*this);
7049   CLI.setDebugLoc(dl)
7050       .setChain(Chain)
7051       .setLibCallee(TLI->getLibcallCallingConv(LibraryCall),
7052                     Type::getVoidTy(*getContext()),
7053                     getExternalSymbol(TLI->getLibcallName(LibraryCall),
7054                                       TLI->getPointerTy(getDataLayout())),
7055                     std::move(Args))
7056       .setDiscardResult()
7057       .setTailCall(isTailCall);
7058 
7059   std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
7060   return CallResult.second;
7061 }
7062 
7063 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
7064                                 SDVTList VTList, ArrayRef<SDValue> Ops,
7065                                 MachineMemOperand *MMO) {
7066   FoldingSetNodeID ID;
7067   ID.AddInteger(MemVT.getRawBits());
7068   AddNodeIDNode(ID, Opcode, VTList, Ops);
7069   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7070   void* IP = nullptr;
7071   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7072     cast<AtomicSDNode>(E)->refineAlignment(MMO);
7073     return SDValue(E, 0);
7074   }
7075 
7076   auto *N = newSDNode<AtomicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
7077                                     VTList, MemVT, MMO);
7078   createOperands(N, Ops);
7079 
7080   CSEMap.InsertNode(N, IP);
7081   InsertNode(N);
7082   return SDValue(N, 0);
7083 }
7084 
7085 SDValue SelectionDAG::getAtomicCmpSwap(unsigned Opcode, const SDLoc &dl,
7086                                        EVT MemVT, SDVTList VTs, SDValue Chain,
7087                                        SDValue Ptr, SDValue Cmp, SDValue Swp,
7088                                        MachineMemOperand *MMO) {
7089   assert(Opcode == ISD::ATOMIC_CMP_SWAP ||
7090          Opcode == ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS);
7091   assert(Cmp.getValueType() == Swp.getValueType() && "Invalid Atomic Op Types");
7092 
7093   SDValue Ops[] = {Chain, Ptr, Cmp, Swp};
7094   return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
7095 }
7096 
7097 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
7098                                 SDValue Chain, SDValue Ptr, SDValue Val,
7099                                 MachineMemOperand *MMO) {
7100   assert((Opcode == ISD::ATOMIC_LOAD_ADD ||
7101           Opcode == ISD::ATOMIC_LOAD_SUB ||
7102           Opcode == ISD::ATOMIC_LOAD_AND ||
7103           Opcode == ISD::ATOMIC_LOAD_CLR ||
7104           Opcode == ISD::ATOMIC_LOAD_OR ||
7105           Opcode == ISD::ATOMIC_LOAD_XOR ||
7106           Opcode == ISD::ATOMIC_LOAD_NAND ||
7107           Opcode == ISD::ATOMIC_LOAD_MIN ||
7108           Opcode == ISD::ATOMIC_LOAD_MAX ||
7109           Opcode == ISD::ATOMIC_LOAD_UMIN ||
7110           Opcode == ISD::ATOMIC_LOAD_UMAX ||
7111           Opcode == ISD::ATOMIC_LOAD_FADD ||
7112           Opcode == ISD::ATOMIC_LOAD_FSUB ||
7113           Opcode == ISD::ATOMIC_SWAP ||
7114           Opcode == ISD::ATOMIC_STORE) &&
7115          "Invalid Atomic Op");
7116 
7117   EVT VT = Val.getValueType();
7118 
7119   SDVTList VTs = Opcode == ISD::ATOMIC_STORE ? getVTList(MVT::Other) :
7120                                                getVTList(VT, MVT::Other);
7121   SDValue Ops[] = {Chain, Ptr, Val};
7122   return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
7123 }
7124 
7125 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
7126                                 EVT VT, SDValue Chain, SDValue Ptr,
7127                                 MachineMemOperand *MMO) {
7128   assert(Opcode == ISD::ATOMIC_LOAD && "Invalid Atomic Op");
7129 
7130   SDVTList VTs = getVTList(VT, MVT::Other);
7131   SDValue Ops[] = {Chain, Ptr};
7132   return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
7133 }
7134 
7135 /// getMergeValues - Create a MERGE_VALUES node from the given operands.
7136 SDValue SelectionDAG::getMergeValues(ArrayRef<SDValue> Ops, const SDLoc &dl) {
7137   if (Ops.size() == 1)
7138     return Ops[0];
7139 
7140   SmallVector<EVT, 4> VTs;
7141   VTs.reserve(Ops.size());
7142   for (const SDValue &Op : Ops)
7143     VTs.push_back(Op.getValueType());
7144   return getNode(ISD::MERGE_VALUES, dl, getVTList(VTs), Ops);
7145 }
7146 
7147 SDValue SelectionDAG::getMemIntrinsicNode(
7148     unsigned Opcode, const SDLoc &dl, SDVTList VTList, ArrayRef<SDValue> Ops,
7149     EVT MemVT, MachinePointerInfo PtrInfo, Align Alignment,
7150     MachineMemOperand::Flags Flags, uint64_t Size, const AAMDNodes &AAInfo) {
7151   if (!Size && MemVT.isScalableVector())
7152     Size = MemoryLocation::UnknownSize;
7153   else if (!Size)
7154     Size = MemVT.getStoreSize();
7155 
7156   MachineFunction &MF = getMachineFunction();
7157   MachineMemOperand *MMO =
7158       MF.getMachineMemOperand(PtrInfo, Flags, Size, Alignment, AAInfo);
7159 
7160   return getMemIntrinsicNode(Opcode, dl, VTList, Ops, MemVT, MMO);
7161 }
7162 
7163 SDValue SelectionDAG::getMemIntrinsicNode(unsigned Opcode, const SDLoc &dl,
7164                                           SDVTList VTList,
7165                                           ArrayRef<SDValue> Ops, EVT MemVT,
7166                                           MachineMemOperand *MMO) {
7167   assert((Opcode == ISD::INTRINSIC_VOID ||
7168           Opcode == ISD::INTRINSIC_W_CHAIN ||
7169           Opcode == ISD::PREFETCH ||
7170           ((int)Opcode <= std::numeric_limits<int>::max() &&
7171            (int)Opcode >= ISD::FIRST_TARGET_MEMORY_OPCODE)) &&
7172          "Opcode is not a memory-accessing opcode!");
7173 
7174   // Memoize the node unless it returns a flag.
7175   MemIntrinsicSDNode *N;
7176   if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) {
7177     FoldingSetNodeID ID;
7178     AddNodeIDNode(ID, Opcode, VTList, Ops);
7179     ID.AddInteger(getSyntheticNodeSubclassData<MemIntrinsicSDNode>(
7180         Opcode, dl.getIROrder(), VTList, MemVT, MMO));
7181     ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7182     void *IP = nullptr;
7183     if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7184       cast<MemIntrinsicSDNode>(E)->refineAlignment(MMO);
7185       return SDValue(E, 0);
7186     }
7187 
7188     N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
7189                                       VTList, MemVT, MMO);
7190     createOperands(N, Ops);
7191 
7192   CSEMap.InsertNode(N, IP);
7193   } else {
7194     N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
7195                                       VTList, MemVT, MMO);
7196     createOperands(N, Ops);
7197   }
7198   InsertNode(N);
7199   SDValue V(N, 0);
7200   NewSDValueDbgMsg(V, "Creating new node: ", this);
7201   return V;
7202 }
7203 
7204 SDValue SelectionDAG::getLifetimeNode(bool IsStart, const SDLoc &dl,
7205                                       SDValue Chain, int FrameIndex,
7206                                       int64_t Size, int64_t Offset) {
7207   const unsigned Opcode = IsStart ? ISD::LIFETIME_START : ISD::LIFETIME_END;
7208   const auto VTs = getVTList(MVT::Other);
7209   SDValue Ops[2] = {
7210       Chain,
7211       getFrameIndex(FrameIndex,
7212                     getTargetLoweringInfo().getFrameIndexTy(getDataLayout()),
7213                     true)};
7214 
7215   FoldingSetNodeID ID;
7216   AddNodeIDNode(ID, Opcode, VTs, Ops);
7217   ID.AddInteger(FrameIndex);
7218   ID.AddInteger(Size);
7219   ID.AddInteger(Offset);
7220   void *IP = nullptr;
7221   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
7222     return SDValue(E, 0);
7223 
7224   LifetimeSDNode *N = newSDNode<LifetimeSDNode>(
7225       Opcode, dl.getIROrder(), dl.getDebugLoc(), VTs, Size, Offset);
7226   createOperands(N, Ops);
7227   CSEMap.InsertNode(N, IP);
7228   InsertNode(N);
7229   SDValue V(N, 0);
7230   NewSDValueDbgMsg(V, "Creating new node: ", this);
7231   return V;
7232 }
7233 
7234 SDValue SelectionDAG::getPseudoProbeNode(const SDLoc &Dl, SDValue Chain,
7235                                          uint64_t Guid, uint64_t Index,
7236                                          uint32_t Attr) {
7237   const unsigned Opcode = ISD::PSEUDO_PROBE;
7238   const auto VTs = getVTList(MVT::Other);
7239   SDValue Ops[] = {Chain};
7240   FoldingSetNodeID ID;
7241   AddNodeIDNode(ID, Opcode, VTs, Ops);
7242   ID.AddInteger(Guid);
7243   ID.AddInteger(Index);
7244   void *IP = nullptr;
7245   if (SDNode *E = FindNodeOrInsertPos(ID, Dl, IP))
7246     return SDValue(E, 0);
7247 
7248   auto *N = newSDNode<PseudoProbeSDNode>(
7249       Opcode, Dl.getIROrder(), Dl.getDebugLoc(), VTs, Guid, Index, Attr);
7250   createOperands(N, Ops);
7251   CSEMap.InsertNode(N, IP);
7252   InsertNode(N);
7253   SDValue V(N, 0);
7254   NewSDValueDbgMsg(V, "Creating new node: ", this);
7255   return V;
7256 }
7257 
7258 /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a
7259 /// MachinePointerInfo record from it.  This is particularly useful because the
7260 /// code generator has many cases where it doesn't bother passing in a
7261 /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst".
7262 static MachinePointerInfo InferPointerInfo(const MachinePointerInfo &Info,
7263                                            SelectionDAG &DAG, SDValue Ptr,
7264                                            int64_t Offset = 0) {
7265   // If this is FI+Offset, we can model it.
7266   if (const FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr))
7267     return MachinePointerInfo::getFixedStack(DAG.getMachineFunction(),
7268                                              FI->getIndex(), Offset);
7269 
7270   // If this is (FI+Offset1)+Offset2, we can model it.
7271   if (Ptr.getOpcode() != ISD::ADD ||
7272       !isa<ConstantSDNode>(Ptr.getOperand(1)) ||
7273       !isa<FrameIndexSDNode>(Ptr.getOperand(0)))
7274     return Info;
7275 
7276   int FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
7277   return MachinePointerInfo::getFixedStack(
7278       DAG.getMachineFunction(), FI,
7279       Offset + cast<ConstantSDNode>(Ptr.getOperand(1))->getSExtValue());
7280 }
7281 
7282 /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a
7283 /// MachinePointerInfo record from it.  This is particularly useful because the
7284 /// code generator has many cases where it doesn't bother passing in a
7285 /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst".
7286 static MachinePointerInfo InferPointerInfo(const MachinePointerInfo &Info,
7287                                            SelectionDAG &DAG, SDValue Ptr,
7288                                            SDValue OffsetOp) {
7289   // If the 'Offset' value isn't a constant, we can't handle this.
7290   if (ConstantSDNode *OffsetNode = dyn_cast<ConstantSDNode>(OffsetOp))
7291     return InferPointerInfo(Info, DAG, Ptr, OffsetNode->getSExtValue());
7292   if (OffsetOp.isUndef())
7293     return InferPointerInfo(Info, DAG, Ptr);
7294   return Info;
7295 }
7296 
7297 SDValue SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType,
7298                               EVT VT, const SDLoc &dl, SDValue Chain,
7299                               SDValue Ptr, SDValue Offset,
7300                               MachinePointerInfo PtrInfo, EVT MemVT,
7301                               Align Alignment,
7302                               MachineMemOperand::Flags MMOFlags,
7303                               const AAMDNodes &AAInfo, const MDNode *Ranges) {
7304   assert(Chain.getValueType() == MVT::Other &&
7305         "Invalid chain type");
7306 
7307   MMOFlags |= MachineMemOperand::MOLoad;
7308   assert((MMOFlags & MachineMemOperand::MOStore) == 0);
7309   // If we don't have a PtrInfo, infer the trivial frame index case to simplify
7310   // clients.
7311   if (PtrInfo.V.isNull())
7312     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr, Offset);
7313 
7314   uint64_t Size = MemoryLocation::getSizeOrUnknown(MemVT.getStoreSize());
7315   MachineFunction &MF = getMachineFunction();
7316   MachineMemOperand *MMO = MF.getMachineMemOperand(PtrInfo, MMOFlags, Size,
7317                                                    Alignment, AAInfo, Ranges);
7318   return getLoad(AM, ExtType, VT, dl, Chain, Ptr, Offset, MemVT, MMO);
7319 }
7320 
7321 SDValue SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType,
7322                               EVT VT, const SDLoc &dl, SDValue Chain,
7323                               SDValue Ptr, SDValue Offset, EVT MemVT,
7324                               MachineMemOperand *MMO) {
7325   if (VT == MemVT) {
7326     ExtType = ISD::NON_EXTLOAD;
7327   } else if (ExtType == ISD::NON_EXTLOAD) {
7328     assert(VT == MemVT && "Non-extending load from different memory type!");
7329   } else {
7330     // Extending load.
7331     assert(MemVT.getScalarType().bitsLT(VT.getScalarType()) &&
7332            "Should only be an extending load, not truncating!");
7333     assert(VT.isInteger() == MemVT.isInteger() &&
7334            "Cannot convert from FP to Int or Int -> FP!");
7335     assert(VT.isVector() == MemVT.isVector() &&
7336            "Cannot use an ext load to convert to or from a vector!");
7337     assert((!VT.isVector() ||
7338             VT.getVectorElementCount() == MemVT.getVectorElementCount()) &&
7339            "Cannot use an ext load to change the number of vector elements!");
7340   }
7341 
7342   bool Indexed = AM != ISD::UNINDEXED;
7343   assert((Indexed || Offset.isUndef()) && "Unindexed load with an offset!");
7344 
7345   SDVTList VTs = Indexed ?
7346     getVTList(VT, Ptr.getValueType(), MVT::Other) : getVTList(VT, MVT::Other);
7347   SDValue Ops[] = { Chain, Ptr, Offset };
7348   FoldingSetNodeID ID;
7349   AddNodeIDNode(ID, ISD::LOAD, VTs, Ops);
7350   ID.AddInteger(MemVT.getRawBits());
7351   ID.AddInteger(getSyntheticNodeSubclassData<LoadSDNode>(
7352       dl.getIROrder(), VTs, AM, ExtType, MemVT, MMO));
7353   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7354   void *IP = nullptr;
7355   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7356     cast<LoadSDNode>(E)->refineAlignment(MMO);
7357     return SDValue(E, 0);
7358   }
7359   auto *N = newSDNode<LoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
7360                                   ExtType, MemVT, MMO);
7361   createOperands(N, Ops);
7362 
7363   CSEMap.InsertNode(N, IP);
7364   InsertNode(N);
7365   SDValue V(N, 0);
7366   NewSDValueDbgMsg(V, "Creating new node: ", this);
7367   return V;
7368 }
7369 
7370 SDValue SelectionDAG::getLoad(EVT VT, const SDLoc &dl, SDValue Chain,
7371                               SDValue Ptr, MachinePointerInfo PtrInfo,
7372                               MaybeAlign Alignment,
7373                               MachineMemOperand::Flags MMOFlags,
7374                               const AAMDNodes &AAInfo, const MDNode *Ranges) {
7375   SDValue Undef = getUNDEF(Ptr.getValueType());
7376   return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
7377                  PtrInfo, VT, Alignment, MMOFlags, AAInfo, Ranges);
7378 }
7379 
7380 SDValue SelectionDAG::getLoad(EVT VT, const SDLoc &dl, SDValue Chain,
7381                               SDValue Ptr, MachineMemOperand *MMO) {
7382   SDValue Undef = getUNDEF(Ptr.getValueType());
7383   return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
7384                  VT, MMO);
7385 }
7386 
7387 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl,
7388                                  EVT VT, SDValue Chain, SDValue Ptr,
7389                                  MachinePointerInfo PtrInfo, EVT MemVT,
7390                                  MaybeAlign Alignment,
7391                                  MachineMemOperand::Flags MMOFlags,
7392                                  const AAMDNodes &AAInfo) {
7393   SDValue Undef = getUNDEF(Ptr.getValueType());
7394   return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, PtrInfo,
7395                  MemVT, Alignment, MMOFlags, AAInfo);
7396 }
7397 
7398 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl,
7399                                  EVT VT, SDValue Chain, SDValue Ptr, EVT MemVT,
7400                                  MachineMemOperand *MMO) {
7401   SDValue Undef = getUNDEF(Ptr.getValueType());
7402   return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef,
7403                  MemVT, MMO);
7404 }
7405 
7406 SDValue SelectionDAG::getIndexedLoad(SDValue OrigLoad, const SDLoc &dl,
7407                                      SDValue Base, SDValue Offset,
7408                                      ISD::MemIndexedMode AM) {
7409   LoadSDNode *LD = cast<LoadSDNode>(OrigLoad);
7410   assert(LD->getOffset().isUndef() && "Load is already a indexed load!");
7411   // Don't propagate the invariant or dereferenceable flags.
7412   auto MMOFlags =
7413       LD->getMemOperand()->getFlags() &
7414       ~(MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable);
7415   return getLoad(AM, LD->getExtensionType(), OrigLoad.getValueType(), dl,
7416                  LD->getChain(), Base, Offset, LD->getPointerInfo(),
7417                  LD->getMemoryVT(), LD->getAlign(), MMOFlags, LD->getAAInfo());
7418 }
7419 
7420 SDValue SelectionDAG::getStore(SDValue Chain, const SDLoc &dl, SDValue Val,
7421                                SDValue Ptr, MachinePointerInfo PtrInfo,
7422                                Align Alignment,
7423                                MachineMemOperand::Flags MMOFlags,
7424                                const AAMDNodes &AAInfo) {
7425   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
7426 
7427   MMOFlags |= MachineMemOperand::MOStore;
7428   assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
7429 
7430   if (PtrInfo.V.isNull())
7431     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
7432 
7433   MachineFunction &MF = getMachineFunction();
7434   uint64_t Size =
7435       MemoryLocation::getSizeOrUnknown(Val.getValueType().getStoreSize());
7436   MachineMemOperand *MMO =
7437       MF.getMachineMemOperand(PtrInfo, MMOFlags, Size, Alignment, AAInfo);
7438   return getStore(Chain, dl, Val, Ptr, MMO);
7439 }
7440 
7441 SDValue SelectionDAG::getStore(SDValue Chain, const SDLoc &dl, SDValue Val,
7442                                SDValue Ptr, MachineMemOperand *MMO) {
7443   assert(Chain.getValueType() == MVT::Other &&
7444         "Invalid chain type");
7445   EVT VT = Val.getValueType();
7446   SDVTList VTs = getVTList(MVT::Other);
7447   SDValue Undef = getUNDEF(Ptr.getValueType());
7448   SDValue Ops[] = { Chain, Val, Ptr, Undef };
7449   FoldingSetNodeID ID;
7450   AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
7451   ID.AddInteger(VT.getRawBits());
7452   ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>(
7453       dl.getIROrder(), VTs, ISD::UNINDEXED, false, VT, MMO));
7454   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7455   void *IP = nullptr;
7456   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7457     cast<StoreSDNode>(E)->refineAlignment(MMO);
7458     return SDValue(E, 0);
7459   }
7460   auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
7461                                    ISD::UNINDEXED, false, VT, MMO);
7462   createOperands(N, Ops);
7463 
7464   CSEMap.InsertNode(N, IP);
7465   InsertNode(N);
7466   SDValue V(N, 0);
7467   NewSDValueDbgMsg(V, "Creating new node: ", this);
7468   return V;
7469 }
7470 
7471 SDValue SelectionDAG::getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val,
7472                                     SDValue Ptr, MachinePointerInfo PtrInfo,
7473                                     EVT SVT, Align Alignment,
7474                                     MachineMemOperand::Flags MMOFlags,
7475                                     const AAMDNodes &AAInfo) {
7476   assert(Chain.getValueType() == MVT::Other &&
7477         "Invalid chain type");
7478 
7479   MMOFlags |= MachineMemOperand::MOStore;
7480   assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
7481 
7482   if (PtrInfo.V.isNull())
7483     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
7484 
7485   MachineFunction &MF = getMachineFunction();
7486   MachineMemOperand *MMO = MF.getMachineMemOperand(
7487       PtrInfo, MMOFlags, MemoryLocation::getSizeOrUnknown(SVT.getStoreSize()),
7488       Alignment, AAInfo);
7489   return getTruncStore(Chain, dl, Val, Ptr, SVT, MMO);
7490 }
7491 
7492 SDValue SelectionDAG::getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val,
7493                                     SDValue Ptr, EVT SVT,
7494                                     MachineMemOperand *MMO) {
7495   EVT VT = Val.getValueType();
7496 
7497   assert(Chain.getValueType() == MVT::Other &&
7498         "Invalid chain type");
7499   if (VT == SVT)
7500     return getStore(Chain, dl, Val, Ptr, MMO);
7501 
7502   assert(SVT.getScalarType().bitsLT(VT.getScalarType()) &&
7503          "Should only be a truncating store, not extending!");
7504   assert(VT.isInteger() == SVT.isInteger() &&
7505          "Can't do FP-INT conversion!");
7506   assert(VT.isVector() == SVT.isVector() &&
7507          "Cannot use trunc store to convert to or from a vector!");
7508   assert((!VT.isVector() ||
7509           VT.getVectorElementCount() == SVT.getVectorElementCount()) &&
7510          "Cannot use trunc store to change the number of vector elements!");
7511 
7512   SDVTList VTs = getVTList(MVT::Other);
7513   SDValue Undef = getUNDEF(Ptr.getValueType());
7514   SDValue Ops[] = { Chain, Val, Ptr, Undef };
7515   FoldingSetNodeID ID;
7516   AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
7517   ID.AddInteger(SVT.getRawBits());
7518   ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>(
7519       dl.getIROrder(), VTs, ISD::UNINDEXED, true, SVT, MMO));
7520   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7521   void *IP = nullptr;
7522   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7523     cast<StoreSDNode>(E)->refineAlignment(MMO);
7524     return SDValue(E, 0);
7525   }
7526   auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
7527                                    ISD::UNINDEXED, true, SVT, MMO);
7528   createOperands(N, Ops);
7529 
7530   CSEMap.InsertNode(N, IP);
7531   InsertNode(N);
7532   SDValue V(N, 0);
7533   NewSDValueDbgMsg(V, "Creating new node: ", this);
7534   return V;
7535 }
7536 
7537 SDValue SelectionDAG::getIndexedStore(SDValue OrigStore, const SDLoc &dl,
7538                                       SDValue Base, SDValue Offset,
7539                                       ISD::MemIndexedMode AM) {
7540   StoreSDNode *ST = cast<StoreSDNode>(OrigStore);
7541   assert(ST->getOffset().isUndef() && "Store is already a indexed store!");
7542   SDVTList VTs = getVTList(Base.getValueType(), MVT::Other);
7543   SDValue Ops[] = { ST->getChain(), ST->getValue(), Base, Offset };
7544   FoldingSetNodeID ID;
7545   AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
7546   ID.AddInteger(ST->getMemoryVT().getRawBits());
7547   ID.AddInteger(ST->getRawSubclassData());
7548   ID.AddInteger(ST->getPointerInfo().getAddrSpace());
7549   void *IP = nullptr;
7550   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
7551     return SDValue(E, 0);
7552 
7553   auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
7554                                    ST->isTruncatingStore(), ST->getMemoryVT(),
7555                                    ST->getMemOperand());
7556   createOperands(N, Ops);
7557 
7558   CSEMap.InsertNode(N, IP);
7559   InsertNode(N);
7560   SDValue V(N, 0);
7561   NewSDValueDbgMsg(V, "Creating new node: ", this);
7562   return V;
7563 }
7564 
7565 SDValue SelectionDAG::getMaskedLoad(EVT VT, const SDLoc &dl, SDValue Chain,
7566                                     SDValue Base, SDValue Offset, SDValue Mask,
7567                                     SDValue PassThru, EVT MemVT,
7568                                     MachineMemOperand *MMO,
7569                                     ISD::MemIndexedMode AM,
7570                                     ISD::LoadExtType ExtTy, bool isExpanding) {
7571   bool Indexed = AM != ISD::UNINDEXED;
7572   assert((Indexed || Offset.isUndef()) &&
7573          "Unindexed masked load with an offset!");
7574   SDVTList VTs = Indexed ? getVTList(VT, Base.getValueType(), MVT::Other)
7575                          : getVTList(VT, MVT::Other);
7576   SDValue Ops[] = {Chain, Base, Offset, Mask, PassThru};
7577   FoldingSetNodeID ID;
7578   AddNodeIDNode(ID, ISD::MLOAD, VTs, Ops);
7579   ID.AddInteger(MemVT.getRawBits());
7580   ID.AddInteger(getSyntheticNodeSubclassData<MaskedLoadSDNode>(
7581       dl.getIROrder(), VTs, AM, ExtTy, isExpanding, MemVT, MMO));
7582   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7583   void *IP = nullptr;
7584   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7585     cast<MaskedLoadSDNode>(E)->refineAlignment(MMO);
7586     return SDValue(E, 0);
7587   }
7588   auto *N = newSDNode<MaskedLoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
7589                                         AM, ExtTy, isExpanding, MemVT, MMO);
7590   createOperands(N, Ops);
7591 
7592   CSEMap.InsertNode(N, IP);
7593   InsertNode(N);
7594   SDValue V(N, 0);
7595   NewSDValueDbgMsg(V, "Creating new node: ", this);
7596   return V;
7597 }
7598 
7599 SDValue SelectionDAG::getIndexedMaskedLoad(SDValue OrigLoad, const SDLoc &dl,
7600                                            SDValue Base, SDValue Offset,
7601                                            ISD::MemIndexedMode AM) {
7602   MaskedLoadSDNode *LD = cast<MaskedLoadSDNode>(OrigLoad);
7603   assert(LD->getOffset().isUndef() && "Masked load is already a indexed load!");
7604   return getMaskedLoad(OrigLoad.getValueType(), dl, LD->getChain(), Base,
7605                        Offset, LD->getMask(), LD->getPassThru(),
7606                        LD->getMemoryVT(), LD->getMemOperand(), AM,
7607                        LD->getExtensionType(), LD->isExpandingLoad());
7608 }
7609 
7610 SDValue SelectionDAG::getMaskedStore(SDValue Chain, const SDLoc &dl,
7611                                      SDValue Val, SDValue Base, SDValue Offset,
7612                                      SDValue Mask, EVT MemVT,
7613                                      MachineMemOperand *MMO,
7614                                      ISD::MemIndexedMode AM, bool IsTruncating,
7615                                      bool IsCompressing) {
7616   assert(Chain.getValueType() == MVT::Other &&
7617         "Invalid chain type");
7618   bool Indexed = AM != ISD::UNINDEXED;
7619   assert((Indexed || Offset.isUndef()) &&
7620          "Unindexed masked store with an offset!");
7621   SDVTList VTs = Indexed ? getVTList(Base.getValueType(), MVT::Other)
7622                          : getVTList(MVT::Other);
7623   SDValue Ops[] = {Chain, Val, Base, Offset, Mask};
7624   FoldingSetNodeID ID;
7625   AddNodeIDNode(ID, ISD::MSTORE, VTs, Ops);
7626   ID.AddInteger(MemVT.getRawBits());
7627   ID.AddInteger(getSyntheticNodeSubclassData<MaskedStoreSDNode>(
7628       dl.getIROrder(), VTs, AM, IsTruncating, IsCompressing, MemVT, MMO));
7629   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7630   void *IP = nullptr;
7631   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7632     cast<MaskedStoreSDNode>(E)->refineAlignment(MMO);
7633     return SDValue(E, 0);
7634   }
7635   auto *N =
7636       newSDNode<MaskedStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
7637                                    IsTruncating, IsCompressing, MemVT, MMO);
7638   createOperands(N, Ops);
7639 
7640   CSEMap.InsertNode(N, IP);
7641   InsertNode(N);
7642   SDValue V(N, 0);
7643   NewSDValueDbgMsg(V, "Creating new node: ", this);
7644   return V;
7645 }
7646 
7647 SDValue SelectionDAG::getIndexedMaskedStore(SDValue OrigStore, const SDLoc &dl,
7648                                             SDValue Base, SDValue Offset,
7649                                             ISD::MemIndexedMode AM) {
7650   MaskedStoreSDNode *ST = cast<MaskedStoreSDNode>(OrigStore);
7651   assert(ST->getOffset().isUndef() &&
7652          "Masked store is already a indexed store!");
7653   return getMaskedStore(ST->getChain(), dl, ST->getValue(), Base, Offset,
7654                         ST->getMask(), ST->getMemoryVT(), ST->getMemOperand(),
7655                         AM, ST->isTruncatingStore(), ST->isCompressingStore());
7656 }
7657 
7658 SDValue SelectionDAG::getMaskedGather(SDVTList VTs, EVT MemVT, const SDLoc &dl,
7659                                       ArrayRef<SDValue> Ops,
7660                                       MachineMemOperand *MMO,
7661                                       ISD::MemIndexType IndexType,
7662                                       ISD::LoadExtType ExtTy) {
7663   assert(Ops.size() == 6 && "Incompatible number of operands");
7664 
7665   FoldingSetNodeID ID;
7666   AddNodeIDNode(ID, ISD::MGATHER, VTs, Ops);
7667   ID.AddInteger(MemVT.getRawBits());
7668   ID.AddInteger(getSyntheticNodeSubclassData<MaskedGatherSDNode>(
7669       dl.getIROrder(), VTs, MemVT, MMO, IndexType, ExtTy));
7670   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7671   void *IP = nullptr;
7672   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7673     cast<MaskedGatherSDNode>(E)->refineAlignment(MMO);
7674     return SDValue(E, 0);
7675   }
7676 
7677   IndexType = TLI->getCanonicalIndexType(IndexType, MemVT, Ops[4]);
7678   auto *N = newSDNode<MaskedGatherSDNode>(dl.getIROrder(), dl.getDebugLoc(),
7679                                           VTs, MemVT, MMO, IndexType, ExtTy);
7680   createOperands(N, Ops);
7681 
7682   assert(N->getPassThru().getValueType() == N->getValueType(0) &&
7683          "Incompatible type of the PassThru value in MaskedGatherSDNode");
7684   assert(N->getMask().getValueType().getVectorElementCount() ==
7685              N->getValueType(0).getVectorElementCount() &&
7686          "Vector width mismatch between mask and data");
7687   assert(N->getIndex().getValueType().getVectorElementCount().isScalable() ==
7688              N->getValueType(0).getVectorElementCount().isScalable() &&
7689          "Scalable flags of index and data do not match");
7690   assert(ElementCount::isKnownGE(
7691              N->getIndex().getValueType().getVectorElementCount(),
7692              N->getValueType(0).getVectorElementCount()) &&
7693          "Vector width mismatch between index and data");
7694   assert(isa<ConstantSDNode>(N->getScale()) &&
7695          cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() &&
7696          "Scale should be a constant power of 2");
7697 
7698   CSEMap.InsertNode(N, IP);
7699   InsertNode(N);
7700   SDValue V(N, 0);
7701   NewSDValueDbgMsg(V, "Creating new node: ", this);
7702   return V;
7703 }
7704 
7705 SDValue SelectionDAG::getMaskedScatter(SDVTList VTs, EVT MemVT, const SDLoc &dl,
7706                                        ArrayRef<SDValue> Ops,
7707                                        MachineMemOperand *MMO,
7708                                        ISD::MemIndexType IndexType,
7709                                        bool IsTrunc) {
7710   assert(Ops.size() == 6 && "Incompatible number of operands");
7711 
7712   FoldingSetNodeID ID;
7713   AddNodeIDNode(ID, ISD::MSCATTER, VTs, Ops);
7714   ID.AddInteger(MemVT.getRawBits());
7715   ID.AddInteger(getSyntheticNodeSubclassData<MaskedScatterSDNode>(
7716       dl.getIROrder(), VTs, MemVT, MMO, IndexType, IsTrunc));
7717   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7718   void *IP = nullptr;
7719   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7720     cast<MaskedScatterSDNode>(E)->refineAlignment(MMO);
7721     return SDValue(E, 0);
7722   }
7723 
7724   IndexType = TLI->getCanonicalIndexType(IndexType, MemVT, Ops[4]);
7725   auto *N = newSDNode<MaskedScatterSDNode>(dl.getIROrder(), dl.getDebugLoc(),
7726                                            VTs, MemVT, MMO, IndexType, IsTrunc);
7727   createOperands(N, Ops);
7728 
7729   assert(N->getMask().getValueType().getVectorElementCount() ==
7730              N->getValue().getValueType().getVectorElementCount() &&
7731          "Vector width mismatch between mask and data");
7732   assert(
7733       N->getIndex().getValueType().getVectorElementCount().isScalable() ==
7734           N->getValue().getValueType().getVectorElementCount().isScalable() &&
7735       "Scalable flags of index and data do not match");
7736   assert(ElementCount::isKnownGE(
7737              N->getIndex().getValueType().getVectorElementCount(),
7738              N->getValue().getValueType().getVectorElementCount()) &&
7739          "Vector width mismatch between index and data");
7740   assert(isa<ConstantSDNode>(N->getScale()) &&
7741          cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() &&
7742          "Scale should be a constant power of 2");
7743 
7744   CSEMap.InsertNode(N, IP);
7745   InsertNode(N);
7746   SDValue V(N, 0);
7747   NewSDValueDbgMsg(V, "Creating new node: ", this);
7748   return V;
7749 }
7750 
7751 SDValue SelectionDAG::simplifySelect(SDValue Cond, SDValue T, SDValue F) {
7752   // select undef, T, F --> T (if T is a constant), otherwise F
7753   // select, ?, undef, F --> F
7754   // select, ?, T, undef --> T
7755   if (Cond.isUndef())
7756     return isConstantValueOfAnyType(T) ? T : F;
7757   if (T.isUndef())
7758     return F;
7759   if (F.isUndef())
7760     return T;
7761 
7762   // select true, T, F --> T
7763   // select false, T, F --> F
7764   if (auto *CondC = dyn_cast<ConstantSDNode>(Cond))
7765     return CondC->isNullValue() ? F : T;
7766 
7767   // TODO: This should simplify VSELECT with constant condition using something
7768   // like this (but check boolean contents to be complete?):
7769   //  if (ISD::isBuildVectorAllOnes(Cond.getNode()))
7770   //    return T;
7771   //  if (ISD::isBuildVectorAllZeros(Cond.getNode()))
7772   //    return F;
7773 
7774   // select ?, T, T --> T
7775   if (T == F)
7776     return T;
7777 
7778   return SDValue();
7779 }
7780 
7781 SDValue SelectionDAG::simplifyShift(SDValue X, SDValue Y) {
7782   // shift undef, Y --> 0 (can always assume that the undef value is 0)
7783   if (X.isUndef())
7784     return getConstant(0, SDLoc(X.getNode()), X.getValueType());
7785   // shift X, undef --> undef (because it may shift by the bitwidth)
7786   if (Y.isUndef())
7787     return getUNDEF(X.getValueType());
7788 
7789   // shift 0, Y --> 0
7790   // shift X, 0 --> X
7791   if (isNullOrNullSplat(X) || isNullOrNullSplat(Y))
7792     return X;
7793 
7794   // shift X, C >= bitwidth(X) --> undef
7795   // All vector elements must be too big (or undef) to avoid partial undefs.
7796   auto isShiftTooBig = [X](ConstantSDNode *Val) {
7797     return !Val || Val->getAPIntValue().uge(X.getScalarValueSizeInBits());
7798   };
7799   if (ISD::matchUnaryPredicate(Y, isShiftTooBig, true))
7800     return getUNDEF(X.getValueType());
7801 
7802   return SDValue();
7803 }
7804 
7805 SDValue SelectionDAG::simplifyFPBinop(unsigned Opcode, SDValue X, SDValue Y,
7806                                       SDNodeFlags Flags) {
7807   // If this operation has 'nnan' or 'ninf' and at least 1 disallowed operand
7808   // (an undef operand can be chosen to be Nan/Inf), then the result of this
7809   // operation is poison. That result can be relaxed to undef.
7810   ConstantFPSDNode *XC = isConstOrConstSplatFP(X, /* AllowUndefs */ true);
7811   ConstantFPSDNode *YC = isConstOrConstSplatFP(Y, /* AllowUndefs */ true);
7812   bool HasNan = (XC && XC->getValueAPF().isNaN()) ||
7813                 (YC && YC->getValueAPF().isNaN());
7814   bool HasInf = (XC && XC->getValueAPF().isInfinity()) ||
7815                 (YC && YC->getValueAPF().isInfinity());
7816 
7817   if (Flags.hasNoNaNs() && (HasNan || X.isUndef() || Y.isUndef()))
7818     return getUNDEF(X.getValueType());
7819 
7820   if (Flags.hasNoInfs() && (HasInf || X.isUndef() || Y.isUndef()))
7821     return getUNDEF(X.getValueType());
7822 
7823   if (!YC)
7824     return SDValue();
7825 
7826   // X + -0.0 --> X
7827   if (Opcode == ISD::FADD)
7828     if (YC->getValueAPF().isNegZero())
7829       return X;
7830 
7831   // X - +0.0 --> X
7832   if (Opcode == ISD::FSUB)
7833     if (YC->getValueAPF().isPosZero())
7834       return X;
7835 
7836   // X * 1.0 --> X
7837   // X / 1.0 --> X
7838   if (Opcode == ISD::FMUL || Opcode == ISD::FDIV)
7839     if (YC->getValueAPF().isExactlyValue(1.0))
7840       return X;
7841 
7842   // X * 0.0 --> 0.0
7843   if (Opcode == ISD::FMUL && Flags.hasNoNaNs() && Flags.hasNoSignedZeros())
7844     if (YC->getValueAPF().isZero())
7845       return getConstantFP(0.0, SDLoc(Y), Y.getValueType());
7846 
7847   return SDValue();
7848 }
7849 
7850 SDValue SelectionDAG::getVAArg(EVT VT, const SDLoc &dl, SDValue Chain,
7851                                SDValue Ptr, SDValue SV, unsigned Align) {
7852   SDValue Ops[] = { Chain, Ptr, SV, getTargetConstant(Align, dl, MVT::i32) };
7853   return getNode(ISD::VAARG, dl, getVTList(VT, MVT::Other), Ops);
7854 }
7855 
7856 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
7857                               ArrayRef<SDUse> Ops) {
7858   switch (Ops.size()) {
7859   case 0: return getNode(Opcode, DL, VT);
7860   case 1: return getNode(Opcode, DL, VT, static_cast<const SDValue>(Ops[0]));
7861   case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1]);
7862   case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2]);
7863   default: break;
7864   }
7865 
7866   // Copy from an SDUse array into an SDValue array for use with
7867   // the regular getNode logic.
7868   SmallVector<SDValue, 8> NewOps(Ops.begin(), Ops.end());
7869   return getNode(Opcode, DL, VT, NewOps);
7870 }
7871 
7872 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
7873                               ArrayRef<SDValue> Ops) {
7874   SDNodeFlags Flags;
7875   if (Inserter)
7876     Flags = Inserter->getFlags();
7877   return getNode(Opcode, DL, VT, Ops, Flags);
7878 }
7879 
7880 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
7881                               ArrayRef<SDValue> Ops, const SDNodeFlags Flags) {
7882   unsigned NumOps = Ops.size();
7883   switch (NumOps) {
7884   case 0: return getNode(Opcode, DL, VT);
7885   case 1: return getNode(Opcode, DL, VT, Ops[0], Flags);
7886   case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Flags);
7887   case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2], Flags);
7888   default: break;
7889   }
7890 
7891 #ifndef NDEBUG
7892   for (auto &Op : Ops)
7893     assert(Op.getOpcode() != ISD::DELETED_NODE &&
7894            "Operand is DELETED_NODE!");
7895 #endif
7896 
7897   switch (Opcode) {
7898   default: break;
7899   case ISD::BUILD_VECTOR:
7900     // Attempt to simplify BUILD_VECTOR.
7901     if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
7902       return V;
7903     break;
7904   case ISD::CONCAT_VECTORS:
7905     if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this))
7906       return V;
7907     break;
7908   case ISD::SELECT_CC:
7909     assert(NumOps == 5 && "SELECT_CC takes 5 operands!");
7910     assert(Ops[0].getValueType() == Ops[1].getValueType() &&
7911            "LHS and RHS of condition must have same type!");
7912     assert(Ops[2].getValueType() == Ops[3].getValueType() &&
7913            "True and False arms of SelectCC must have same type!");
7914     assert(Ops[2].getValueType() == VT &&
7915            "select_cc node must be of same type as true and false value!");
7916     break;
7917   case ISD::BR_CC:
7918     assert(NumOps == 5 && "BR_CC takes 5 operands!");
7919     assert(Ops[2].getValueType() == Ops[3].getValueType() &&
7920            "LHS/RHS of comparison should match types!");
7921     break;
7922   }
7923 
7924   // Memoize nodes.
7925   SDNode *N;
7926   SDVTList VTs = getVTList(VT);
7927 
7928   if (VT != MVT::Glue) {
7929     FoldingSetNodeID ID;
7930     AddNodeIDNode(ID, Opcode, VTs, Ops);
7931     void *IP = nullptr;
7932 
7933     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
7934       return SDValue(E, 0);
7935 
7936     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
7937     createOperands(N, Ops);
7938 
7939     CSEMap.InsertNode(N, IP);
7940   } else {
7941     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
7942     createOperands(N, Ops);
7943   }
7944 
7945   N->setFlags(Flags);
7946   InsertNode(N);
7947   SDValue V(N, 0);
7948   NewSDValueDbgMsg(V, "Creating new node: ", this);
7949   return V;
7950 }
7951 
7952 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL,
7953                               ArrayRef<EVT> ResultTys, ArrayRef<SDValue> Ops) {
7954   return getNode(Opcode, DL, getVTList(ResultTys), Ops);
7955 }
7956 
7957 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
7958                               ArrayRef<SDValue> Ops) {
7959   SDNodeFlags Flags;
7960   if (Inserter)
7961     Flags = Inserter->getFlags();
7962   return getNode(Opcode, DL, VTList, Ops, Flags);
7963 }
7964 
7965 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
7966                               ArrayRef<SDValue> Ops, const SDNodeFlags Flags) {
7967   if (VTList.NumVTs == 1)
7968     return getNode(Opcode, DL, VTList.VTs[0], Ops);
7969 
7970 #ifndef NDEBUG
7971   for (auto &Op : Ops)
7972     assert(Op.getOpcode() != ISD::DELETED_NODE &&
7973            "Operand is DELETED_NODE!");
7974 #endif
7975 
7976   switch (Opcode) {
7977   case ISD::STRICT_FP_EXTEND:
7978     assert(VTList.NumVTs == 2 && Ops.size() == 2 &&
7979            "Invalid STRICT_FP_EXTEND!");
7980     assert(VTList.VTs[0].isFloatingPoint() &&
7981            Ops[1].getValueType().isFloatingPoint() && "Invalid FP cast!");
7982     assert(VTList.VTs[0].isVector() == Ops[1].getValueType().isVector() &&
7983            "STRICT_FP_EXTEND result type should be vector iff the operand "
7984            "type is vector!");
7985     assert((!VTList.VTs[0].isVector() ||
7986             VTList.VTs[0].getVectorNumElements() ==
7987             Ops[1].getValueType().getVectorNumElements()) &&
7988            "Vector element count mismatch!");
7989     assert(Ops[1].getValueType().bitsLT(VTList.VTs[0]) &&
7990            "Invalid fpext node, dst <= src!");
7991     break;
7992   case ISD::STRICT_FP_ROUND:
7993     assert(VTList.NumVTs == 2 && Ops.size() == 3 && "Invalid STRICT_FP_ROUND!");
7994     assert(VTList.VTs[0].isVector() == Ops[1].getValueType().isVector() &&
7995            "STRICT_FP_ROUND result type should be vector iff the operand "
7996            "type is vector!");
7997     assert((!VTList.VTs[0].isVector() ||
7998             VTList.VTs[0].getVectorNumElements() ==
7999             Ops[1].getValueType().getVectorNumElements()) &&
8000            "Vector element count mismatch!");
8001     assert(VTList.VTs[0].isFloatingPoint() &&
8002            Ops[1].getValueType().isFloatingPoint() &&
8003            VTList.VTs[0].bitsLT(Ops[1].getValueType()) &&
8004            isa<ConstantSDNode>(Ops[2]) &&
8005            (cast<ConstantSDNode>(Ops[2])->getZExtValue() == 0 ||
8006             cast<ConstantSDNode>(Ops[2])->getZExtValue() == 1) &&
8007            "Invalid STRICT_FP_ROUND!");
8008     break;
8009 #if 0
8010   // FIXME: figure out how to safely handle things like
8011   // int foo(int x) { return 1 << (x & 255); }
8012   // int bar() { return foo(256); }
8013   case ISD::SRA_PARTS:
8014   case ISD::SRL_PARTS:
8015   case ISD::SHL_PARTS:
8016     if (N3.getOpcode() == ISD::SIGN_EXTEND_INREG &&
8017         cast<VTSDNode>(N3.getOperand(1))->getVT() != MVT::i1)
8018       return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0));
8019     else if (N3.getOpcode() == ISD::AND)
8020       if (ConstantSDNode *AndRHS = dyn_cast<ConstantSDNode>(N3.getOperand(1))) {
8021         // If the and is only masking out bits that cannot effect the shift,
8022         // eliminate the and.
8023         unsigned NumBits = VT.getScalarSizeInBits()*2;
8024         if ((AndRHS->getValue() & (NumBits-1)) == NumBits-1)
8025           return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0));
8026       }
8027     break;
8028 #endif
8029   }
8030 
8031   // Memoize the node unless it returns a flag.
8032   SDNode *N;
8033   if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) {
8034     FoldingSetNodeID ID;
8035     AddNodeIDNode(ID, Opcode, VTList, Ops);
8036     void *IP = nullptr;
8037     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
8038       return SDValue(E, 0);
8039 
8040     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList);
8041     createOperands(N, Ops);
8042     CSEMap.InsertNode(N, IP);
8043   } else {
8044     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList);
8045     createOperands(N, Ops);
8046   }
8047 
8048   N->setFlags(Flags);
8049   InsertNode(N);
8050   SDValue V(N, 0);
8051   NewSDValueDbgMsg(V, "Creating new node: ", this);
8052   return V;
8053 }
8054 
8055 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL,
8056                               SDVTList VTList) {
8057   return getNode(Opcode, DL, VTList, None);
8058 }
8059 
8060 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
8061                               SDValue N1) {
8062   SDValue Ops[] = { N1 };
8063   return getNode(Opcode, DL, VTList, Ops);
8064 }
8065 
8066 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
8067                               SDValue N1, SDValue N2) {
8068   SDValue Ops[] = { N1, N2 };
8069   return getNode(Opcode, DL, VTList, Ops);
8070 }
8071 
8072 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
8073                               SDValue N1, SDValue N2, SDValue N3) {
8074   SDValue Ops[] = { N1, N2, N3 };
8075   return getNode(Opcode, DL, VTList, Ops);
8076 }
8077 
8078 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
8079                               SDValue N1, SDValue N2, SDValue N3, SDValue N4) {
8080   SDValue Ops[] = { N1, N2, N3, N4 };
8081   return getNode(Opcode, DL, VTList, Ops);
8082 }
8083 
8084 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
8085                               SDValue N1, SDValue N2, SDValue N3, SDValue N4,
8086                               SDValue N5) {
8087   SDValue Ops[] = { N1, N2, N3, N4, N5 };
8088   return getNode(Opcode, DL, VTList, Ops);
8089 }
8090 
8091 SDVTList SelectionDAG::getVTList(EVT VT) {
8092   return makeVTList(SDNode::getValueTypeList(VT), 1);
8093 }
8094 
8095 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2) {
8096   FoldingSetNodeID ID;
8097   ID.AddInteger(2U);
8098   ID.AddInteger(VT1.getRawBits());
8099   ID.AddInteger(VT2.getRawBits());
8100 
8101   void *IP = nullptr;
8102   SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
8103   if (!Result) {
8104     EVT *Array = Allocator.Allocate<EVT>(2);
8105     Array[0] = VT1;
8106     Array[1] = VT2;
8107     Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 2);
8108     VTListMap.InsertNode(Result, IP);
8109   }
8110   return Result->getSDVTList();
8111 }
8112 
8113 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3) {
8114   FoldingSetNodeID ID;
8115   ID.AddInteger(3U);
8116   ID.AddInteger(VT1.getRawBits());
8117   ID.AddInteger(VT2.getRawBits());
8118   ID.AddInteger(VT3.getRawBits());
8119 
8120   void *IP = nullptr;
8121   SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
8122   if (!Result) {
8123     EVT *Array = Allocator.Allocate<EVT>(3);
8124     Array[0] = VT1;
8125     Array[1] = VT2;
8126     Array[2] = VT3;
8127     Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 3);
8128     VTListMap.InsertNode(Result, IP);
8129   }
8130   return Result->getSDVTList();
8131 }
8132 
8133 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3, EVT VT4) {
8134   FoldingSetNodeID ID;
8135   ID.AddInteger(4U);
8136   ID.AddInteger(VT1.getRawBits());
8137   ID.AddInteger(VT2.getRawBits());
8138   ID.AddInteger(VT3.getRawBits());
8139   ID.AddInteger(VT4.getRawBits());
8140 
8141   void *IP = nullptr;
8142   SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
8143   if (!Result) {
8144     EVT *Array = Allocator.Allocate<EVT>(4);
8145     Array[0] = VT1;
8146     Array[1] = VT2;
8147     Array[2] = VT3;
8148     Array[3] = VT4;
8149     Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 4);
8150     VTListMap.InsertNode(Result, IP);
8151   }
8152   return Result->getSDVTList();
8153 }
8154 
8155 SDVTList SelectionDAG::getVTList(ArrayRef<EVT> VTs) {
8156   unsigned NumVTs = VTs.size();
8157   FoldingSetNodeID ID;
8158   ID.AddInteger(NumVTs);
8159   for (unsigned index = 0; index < NumVTs; index++) {
8160     ID.AddInteger(VTs[index].getRawBits());
8161   }
8162 
8163   void *IP = nullptr;
8164   SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
8165   if (!Result) {
8166     EVT *Array = Allocator.Allocate<EVT>(NumVTs);
8167     llvm::copy(VTs, Array);
8168     Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, NumVTs);
8169     VTListMap.InsertNode(Result, IP);
8170   }
8171   return Result->getSDVTList();
8172 }
8173 
8174 
8175 /// UpdateNodeOperands - *Mutate* the specified node in-place to have the
8176 /// specified operands.  If the resultant node already exists in the DAG,
8177 /// this does not modify the specified node, instead it returns the node that
8178 /// already exists.  If the resultant node does not exist in the DAG, the
8179 /// input node is returned.  As a degenerate case, if you specify the same
8180 /// input operands as the node already has, the input node is returned.
8181 SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op) {
8182   assert(N->getNumOperands() == 1 && "Update with wrong number of operands");
8183 
8184   // Check to see if there is no change.
8185   if (Op == N->getOperand(0)) return N;
8186 
8187   // See if the modified node already exists.
8188   void *InsertPos = nullptr;
8189   if (SDNode *Existing = FindModifiedNodeSlot(N, Op, InsertPos))
8190     return Existing;
8191 
8192   // Nope it doesn't.  Remove the node from its current place in the maps.
8193   if (InsertPos)
8194     if (!RemoveNodeFromCSEMaps(N))
8195       InsertPos = nullptr;
8196 
8197   // Now we update the operands.
8198   N->OperandList[0].set(Op);
8199 
8200   updateDivergence(N);
8201   // If this gets put into a CSE map, add it.
8202   if (InsertPos) CSEMap.InsertNode(N, InsertPos);
8203   return N;
8204 }
8205 
8206 SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2) {
8207   assert(N->getNumOperands() == 2 && "Update with wrong number of operands");
8208 
8209   // Check to see if there is no change.
8210   if (Op1 == N->getOperand(0) && Op2 == N->getOperand(1))
8211     return N;   // No operands changed, just return the input node.
8212 
8213   // See if the modified node already exists.
8214   void *InsertPos = nullptr;
8215   if (SDNode *Existing = FindModifiedNodeSlot(N, Op1, Op2, InsertPos))
8216     return Existing;
8217 
8218   // Nope it doesn't.  Remove the node from its current place in the maps.
8219   if (InsertPos)
8220     if (!RemoveNodeFromCSEMaps(N))
8221       InsertPos = nullptr;
8222 
8223   // Now we update the operands.
8224   if (N->OperandList[0] != Op1)
8225     N->OperandList[0].set(Op1);
8226   if (N->OperandList[1] != Op2)
8227     N->OperandList[1].set(Op2);
8228 
8229   updateDivergence(N);
8230   // If this gets put into a CSE map, add it.
8231   if (InsertPos) CSEMap.InsertNode(N, InsertPos);
8232   return N;
8233 }
8234 
8235 SDNode *SelectionDAG::
8236 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2, SDValue Op3) {
8237   SDValue Ops[] = { Op1, Op2, Op3 };
8238   return UpdateNodeOperands(N, Ops);
8239 }
8240 
8241 SDNode *SelectionDAG::
8242 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2,
8243                    SDValue Op3, SDValue Op4) {
8244   SDValue Ops[] = { Op1, Op2, Op3, Op4 };
8245   return UpdateNodeOperands(N, Ops);
8246 }
8247 
8248 SDNode *SelectionDAG::
8249 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2,
8250                    SDValue Op3, SDValue Op4, SDValue Op5) {
8251   SDValue Ops[] = { Op1, Op2, Op3, Op4, Op5 };
8252   return UpdateNodeOperands(N, Ops);
8253 }
8254 
8255 SDNode *SelectionDAG::
8256 UpdateNodeOperands(SDNode *N, ArrayRef<SDValue> Ops) {
8257   unsigned NumOps = Ops.size();
8258   assert(N->getNumOperands() == NumOps &&
8259          "Update with wrong number of operands");
8260 
8261   // If no operands changed just return the input node.
8262   if (std::equal(Ops.begin(), Ops.end(), N->op_begin()))
8263     return N;
8264 
8265   // See if the modified node already exists.
8266   void *InsertPos = nullptr;
8267   if (SDNode *Existing = FindModifiedNodeSlot(N, Ops, InsertPos))
8268     return Existing;
8269 
8270   // Nope it doesn't.  Remove the node from its current place in the maps.
8271   if (InsertPos)
8272     if (!RemoveNodeFromCSEMaps(N))
8273       InsertPos = nullptr;
8274 
8275   // Now we update the operands.
8276   for (unsigned i = 0; i != NumOps; ++i)
8277     if (N->OperandList[i] != Ops[i])
8278       N->OperandList[i].set(Ops[i]);
8279 
8280   updateDivergence(N);
8281   // If this gets put into a CSE map, add it.
8282   if (InsertPos) CSEMap.InsertNode(N, InsertPos);
8283   return N;
8284 }
8285 
8286 /// DropOperands - Release the operands and set this node to have
8287 /// zero operands.
8288 void SDNode::DropOperands() {
8289   // Unlike the code in MorphNodeTo that does this, we don't need to
8290   // watch for dead nodes here.
8291   for (op_iterator I = op_begin(), E = op_end(); I != E; ) {
8292     SDUse &Use = *I++;
8293     Use.set(SDValue());
8294   }
8295 }
8296 
8297 void SelectionDAG::setNodeMemRefs(MachineSDNode *N,
8298                                   ArrayRef<MachineMemOperand *> NewMemRefs) {
8299   if (NewMemRefs.empty()) {
8300     N->clearMemRefs();
8301     return;
8302   }
8303 
8304   // Check if we can avoid allocating by storing a single reference directly.
8305   if (NewMemRefs.size() == 1) {
8306     N->MemRefs = NewMemRefs[0];
8307     N->NumMemRefs = 1;
8308     return;
8309   }
8310 
8311   MachineMemOperand **MemRefsBuffer =
8312       Allocator.template Allocate<MachineMemOperand *>(NewMemRefs.size());
8313   llvm::copy(NewMemRefs, MemRefsBuffer);
8314   N->MemRefs = MemRefsBuffer;
8315   N->NumMemRefs = static_cast<int>(NewMemRefs.size());
8316 }
8317 
8318 /// SelectNodeTo - These are wrappers around MorphNodeTo that accept a
8319 /// machine opcode.
8320 ///
8321 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8322                                    EVT VT) {
8323   SDVTList VTs = getVTList(VT);
8324   return SelectNodeTo(N, MachineOpc, VTs, None);
8325 }
8326 
8327 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8328                                    EVT VT, SDValue Op1) {
8329   SDVTList VTs = getVTList(VT);
8330   SDValue Ops[] = { Op1 };
8331   return SelectNodeTo(N, MachineOpc, VTs, Ops);
8332 }
8333 
8334 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8335                                    EVT VT, SDValue Op1,
8336                                    SDValue Op2) {
8337   SDVTList VTs = getVTList(VT);
8338   SDValue Ops[] = { Op1, Op2 };
8339   return SelectNodeTo(N, MachineOpc, VTs, Ops);
8340 }
8341 
8342 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8343                                    EVT VT, SDValue Op1,
8344                                    SDValue Op2, SDValue Op3) {
8345   SDVTList VTs = getVTList(VT);
8346   SDValue Ops[] = { Op1, Op2, Op3 };
8347   return SelectNodeTo(N, MachineOpc, VTs, Ops);
8348 }
8349 
8350 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8351                                    EVT VT, ArrayRef<SDValue> Ops) {
8352   SDVTList VTs = getVTList(VT);
8353   return SelectNodeTo(N, MachineOpc, VTs, Ops);
8354 }
8355 
8356 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8357                                    EVT VT1, EVT VT2, ArrayRef<SDValue> Ops) {
8358   SDVTList VTs = getVTList(VT1, VT2);
8359   return SelectNodeTo(N, MachineOpc, VTs, Ops);
8360 }
8361 
8362 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8363                                    EVT VT1, EVT VT2) {
8364   SDVTList VTs = getVTList(VT1, VT2);
8365   return SelectNodeTo(N, MachineOpc, VTs, None);
8366 }
8367 
8368 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8369                                    EVT VT1, EVT VT2, EVT VT3,
8370                                    ArrayRef<SDValue> Ops) {
8371   SDVTList VTs = getVTList(VT1, VT2, VT3);
8372   return SelectNodeTo(N, MachineOpc, VTs, Ops);
8373 }
8374 
8375 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8376                                    EVT VT1, EVT VT2,
8377                                    SDValue Op1, SDValue Op2) {
8378   SDVTList VTs = getVTList(VT1, VT2);
8379   SDValue Ops[] = { Op1, Op2 };
8380   return SelectNodeTo(N, MachineOpc, VTs, Ops);
8381 }
8382 
8383 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8384                                    SDVTList VTs,ArrayRef<SDValue> Ops) {
8385   SDNode *New = MorphNodeTo(N, ~MachineOpc, VTs, Ops);
8386   // Reset the NodeID to -1.
8387   New->setNodeId(-1);
8388   if (New != N) {
8389     ReplaceAllUsesWith(N, New);
8390     RemoveDeadNode(N);
8391   }
8392   return New;
8393 }
8394 
8395 /// UpdateSDLocOnMergeSDNode - If the opt level is -O0 then it throws away
8396 /// the line number information on the merged node since it is not possible to
8397 /// preserve the information that operation is associated with multiple lines.
8398 /// This will make the debugger working better at -O0, were there is a higher
8399 /// probability having other instructions associated with that line.
8400 ///
8401 /// For IROrder, we keep the smaller of the two
8402 SDNode *SelectionDAG::UpdateSDLocOnMergeSDNode(SDNode *N, const SDLoc &OLoc) {
8403   DebugLoc NLoc = N->getDebugLoc();
8404   if (NLoc && OptLevel == CodeGenOpt::None && OLoc.getDebugLoc() != NLoc) {
8405     N->setDebugLoc(DebugLoc());
8406   }
8407   unsigned Order = std::min(N->getIROrder(), OLoc.getIROrder());
8408   N->setIROrder(Order);
8409   return N;
8410 }
8411 
8412 /// MorphNodeTo - This *mutates* the specified node to have the specified
8413 /// return type, opcode, and operands.
8414 ///
8415 /// Note that MorphNodeTo returns the resultant node.  If there is already a
8416 /// node of the specified opcode and operands, it returns that node instead of
8417 /// the current one.  Note that the SDLoc need not be the same.
8418 ///
8419 /// Using MorphNodeTo is faster than creating a new node and swapping it in
8420 /// with ReplaceAllUsesWith both because it often avoids allocating a new
8421 /// node, and because it doesn't require CSE recalculation for any of
8422 /// the node's users.
8423 ///
8424 /// However, note that MorphNodeTo recursively deletes dead nodes from the DAG.
8425 /// As a consequence it isn't appropriate to use from within the DAG combiner or
8426 /// the legalizer which maintain worklists that would need to be updated when
8427 /// deleting things.
8428 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
8429                                   SDVTList VTs, ArrayRef<SDValue> Ops) {
8430   // If an identical node already exists, use it.
8431   void *IP = nullptr;
8432   if (VTs.VTs[VTs.NumVTs-1] != MVT::Glue) {
8433     FoldingSetNodeID ID;
8434     AddNodeIDNode(ID, Opc, VTs, Ops);
8435     if (SDNode *ON = FindNodeOrInsertPos(ID, SDLoc(N), IP))
8436       return UpdateSDLocOnMergeSDNode(ON, SDLoc(N));
8437   }
8438 
8439   if (!RemoveNodeFromCSEMaps(N))
8440     IP = nullptr;
8441 
8442   // Start the morphing.
8443   N->NodeType = Opc;
8444   N->ValueList = VTs.VTs;
8445   N->NumValues = VTs.NumVTs;
8446 
8447   // Clear the operands list, updating used nodes to remove this from their
8448   // use list.  Keep track of any operands that become dead as a result.
8449   SmallPtrSet<SDNode*, 16> DeadNodeSet;
8450   for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) {
8451     SDUse &Use = *I++;
8452     SDNode *Used = Use.getNode();
8453     Use.set(SDValue());
8454     if (Used->use_empty())
8455       DeadNodeSet.insert(Used);
8456   }
8457 
8458   // For MachineNode, initialize the memory references information.
8459   if (MachineSDNode *MN = dyn_cast<MachineSDNode>(N))
8460     MN->clearMemRefs();
8461 
8462   // Swap for an appropriately sized array from the recycler.
8463   removeOperands(N);
8464   createOperands(N, Ops);
8465 
8466   // Delete any nodes that are still dead after adding the uses for the
8467   // new operands.
8468   if (!DeadNodeSet.empty()) {
8469     SmallVector<SDNode *, 16> DeadNodes;
8470     for (SDNode *N : DeadNodeSet)
8471       if (N->use_empty())
8472         DeadNodes.push_back(N);
8473     RemoveDeadNodes(DeadNodes);
8474   }
8475 
8476   if (IP)
8477     CSEMap.InsertNode(N, IP);   // Memoize the new node.
8478   return N;
8479 }
8480 
8481 SDNode* SelectionDAG::mutateStrictFPToFP(SDNode *Node) {
8482   unsigned OrigOpc = Node->getOpcode();
8483   unsigned NewOpc;
8484   switch (OrigOpc) {
8485   default:
8486     llvm_unreachable("mutateStrictFPToFP called with unexpected opcode!");
8487 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN)               \
8488   case ISD::STRICT_##DAGN: NewOpc = ISD::DAGN; break;
8489 #define CMP_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN)               \
8490   case ISD::STRICT_##DAGN: NewOpc = ISD::SETCC; break;
8491 #include "llvm/IR/ConstrainedOps.def"
8492   }
8493 
8494   assert(Node->getNumValues() == 2 && "Unexpected number of results!");
8495 
8496   // We're taking this node out of the chain, so we need to re-link things.
8497   SDValue InputChain = Node->getOperand(0);
8498   SDValue OutputChain = SDValue(Node, 1);
8499   ReplaceAllUsesOfValueWith(OutputChain, InputChain);
8500 
8501   SmallVector<SDValue, 3> Ops;
8502   for (unsigned i = 1, e = Node->getNumOperands(); i != e; ++i)
8503     Ops.push_back(Node->getOperand(i));
8504 
8505   SDVTList VTs = getVTList(Node->getValueType(0));
8506   SDNode *Res = MorphNodeTo(Node, NewOpc, VTs, Ops);
8507 
8508   // MorphNodeTo can operate in two ways: if an existing node with the
8509   // specified operands exists, it can just return it.  Otherwise, it
8510   // updates the node in place to have the requested operands.
8511   if (Res == Node) {
8512     // If we updated the node in place, reset the node ID.  To the isel,
8513     // this should be just like a newly allocated machine node.
8514     Res->setNodeId(-1);
8515   } else {
8516     ReplaceAllUsesWith(Node, Res);
8517     RemoveDeadNode(Node);
8518   }
8519 
8520   return Res;
8521 }
8522 
8523 /// getMachineNode - These are used for target selectors to create a new node
8524 /// with specified return type(s), MachineInstr opcode, and operands.
8525 ///
8526 /// Note that getMachineNode returns the resultant node.  If there is already a
8527 /// node of the specified opcode and operands, it returns that node instead of
8528 /// the current one.
8529 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
8530                                             EVT VT) {
8531   SDVTList VTs = getVTList(VT);
8532   return getMachineNode(Opcode, dl, VTs, None);
8533 }
8534 
8535 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
8536                                             EVT VT, SDValue Op1) {
8537   SDVTList VTs = getVTList(VT);
8538   SDValue Ops[] = { Op1 };
8539   return getMachineNode(Opcode, dl, VTs, Ops);
8540 }
8541 
8542 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
8543                                             EVT VT, SDValue Op1, SDValue Op2) {
8544   SDVTList VTs = getVTList(VT);
8545   SDValue Ops[] = { Op1, Op2 };
8546   return getMachineNode(Opcode, dl, VTs, Ops);
8547 }
8548 
8549 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
8550                                             EVT VT, SDValue Op1, SDValue Op2,
8551                                             SDValue Op3) {
8552   SDVTList VTs = getVTList(VT);
8553   SDValue Ops[] = { Op1, Op2, Op3 };
8554   return getMachineNode(Opcode, dl, VTs, Ops);
8555 }
8556 
8557 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
8558                                             EVT VT, ArrayRef<SDValue> Ops) {
8559   SDVTList VTs = getVTList(VT);
8560   return getMachineNode(Opcode, dl, VTs, Ops);
8561 }
8562 
8563 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
8564                                             EVT VT1, EVT VT2, SDValue Op1,
8565                                             SDValue Op2) {
8566   SDVTList VTs = getVTList(VT1, VT2);
8567   SDValue Ops[] = { Op1, Op2 };
8568   return getMachineNode(Opcode, dl, VTs, Ops);
8569 }
8570 
8571 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
8572                                             EVT VT1, EVT VT2, SDValue Op1,
8573                                             SDValue Op2, SDValue Op3) {
8574   SDVTList VTs = getVTList(VT1, VT2);
8575   SDValue Ops[] = { Op1, Op2, Op3 };
8576   return getMachineNode(Opcode, dl, VTs, Ops);
8577 }
8578 
8579 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
8580                                             EVT VT1, EVT VT2,
8581                                             ArrayRef<SDValue> Ops) {
8582   SDVTList VTs = getVTList(VT1, VT2);
8583   return getMachineNode(Opcode, dl, VTs, Ops);
8584 }
8585 
8586 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
8587                                             EVT VT1, EVT VT2, EVT VT3,
8588                                             SDValue Op1, SDValue Op2) {
8589   SDVTList VTs = getVTList(VT1, VT2, VT3);
8590   SDValue Ops[] = { Op1, Op2 };
8591   return getMachineNode(Opcode, dl, VTs, Ops);
8592 }
8593 
8594 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
8595                                             EVT VT1, EVT VT2, EVT VT3,
8596                                             SDValue Op1, SDValue Op2,
8597                                             SDValue Op3) {
8598   SDVTList VTs = getVTList(VT1, VT2, VT3);
8599   SDValue Ops[] = { Op1, Op2, Op3 };
8600   return getMachineNode(Opcode, dl, VTs, Ops);
8601 }
8602 
8603 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
8604                                             EVT VT1, EVT VT2, EVT VT3,
8605                                             ArrayRef<SDValue> Ops) {
8606   SDVTList VTs = getVTList(VT1, VT2, VT3);
8607   return getMachineNode(Opcode, dl, VTs, Ops);
8608 }
8609 
8610 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
8611                                             ArrayRef<EVT> ResultTys,
8612                                             ArrayRef<SDValue> Ops) {
8613   SDVTList VTs = getVTList(ResultTys);
8614   return getMachineNode(Opcode, dl, VTs, Ops);
8615 }
8616 
8617 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &DL,
8618                                             SDVTList VTs,
8619                                             ArrayRef<SDValue> Ops) {
8620   bool DoCSE = VTs.VTs[VTs.NumVTs-1] != MVT::Glue;
8621   MachineSDNode *N;
8622   void *IP = nullptr;
8623 
8624   if (DoCSE) {
8625     FoldingSetNodeID ID;
8626     AddNodeIDNode(ID, ~Opcode, VTs, Ops);
8627     IP = nullptr;
8628     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
8629       return cast<MachineSDNode>(UpdateSDLocOnMergeSDNode(E, DL));
8630     }
8631   }
8632 
8633   // Allocate a new MachineSDNode.
8634   N = newSDNode<MachineSDNode>(~Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
8635   createOperands(N, Ops);
8636 
8637   if (DoCSE)
8638     CSEMap.InsertNode(N, IP);
8639 
8640   InsertNode(N);
8641   NewSDValueDbgMsg(SDValue(N, 0), "Creating new machine node: ", this);
8642   return N;
8643 }
8644 
8645 /// getTargetExtractSubreg - A convenience function for creating
8646 /// TargetOpcode::EXTRACT_SUBREG nodes.
8647 SDValue SelectionDAG::getTargetExtractSubreg(int SRIdx, const SDLoc &DL, EVT VT,
8648                                              SDValue Operand) {
8649   SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32);
8650   SDNode *Subreg = getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL,
8651                                   VT, Operand, SRIdxVal);
8652   return SDValue(Subreg, 0);
8653 }
8654 
8655 /// getTargetInsertSubreg - A convenience function for creating
8656 /// TargetOpcode::INSERT_SUBREG nodes.
8657 SDValue SelectionDAG::getTargetInsertSubreg(int SRIdx, const SDLoc &DL, EVT VT,
8658                                             SDValue Operand, SDValue Subreg) {
8659   SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32);
8660   SDNode *Result = getMachineNode(TargetOpcode::INSERT_SUBREG, DL,
8661                                   VT, Operand, Subreg, SRIdxVal);
8662   return SDValue(Result, 0);
8663 }
8664 
8665 /// getNodeIfExists - Get the specified node if it's already available, or
8666 /// else return NULL.
8667 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList,
8668                                       ArrayRef<SDValue> Ops) {
8669   SDNodeFlags Flags;
8670   if (Inserter)
8671     Flags = Inserter->getFlags();
8672   return getNodeIfExists(Opcode, VTList, Ops, Flags);
8673 }
8674 
8675 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList,
8676                                       ArrayRef<SDValue> Ops,
8677                                       const SDNodeFlags Flags) {
8678   if (VTList.VTs[VTList.NumVTs - 1] != MVT::Glue) {
8679     FoldingSetNodeID ID;
8680     AddNodeIDNode(ID, Opcode, VTList, Ops);
8681     void *IP = nullptr;
8682     if (SDNode *E = FindNodeOrInsertPos(ID, SDLoc(), IP)) {
8683       E->intersectFlagsWith(Flags);
8684       return E;
8685     }
8686   }
8687   return nullptr;
8688 }
8689 
8690 /// doesNodeExist - Check if a node exists without modifying its flags.
8691 bool SelectionDAG::doesNodeExist(unsigned Opcode, SDVTList VTList,
8692                                  ArrayRef<SDValue> Ops) {
8693   if (VTList.VTs[VTList.NumVTs - 1] != MVT::Glue) {
8694     FoldingSetNodeID ID;
8695     AddNodeIDNode(ID, Opcode, VTList, Ops);
8696     void *IP = nullptr;
8697     if (FindNodeOrInsertPos(ID, SDLoc(), IP))
8698       return true;
8699   }
8700   return false;
8701 }
8702 
8703 /// getDbgValue - Creates a SDDbgValue node.
8704 ///
8705 /// SDNode
8706 SDDbgValue *SelectionDAG::getDbgValue(DIVariable *Var, DIExpression *Expr,
8707                                       SDNode *N, unsigned R, bool IsIndirect,
8708                                       const DebugLoc &DL, unsigned O) {
8709   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
8710          "Expected inlined-at fields to agree");
8711   return new (DbgInfo->getAlloc())
8712       SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromNode(N, R),
8713                  {}, IsIndirect, DL, O,
8714                  /*IsVariadic=*/false);
8715 }
8716 
8717 /// Constant
8718 SDDbgValue *SelectionDAG::getConstantDbgValue(DIVariable *Var,
8719                                               DIExpression *Expr,
8720                                               const Value *C,
8721                                               const DebugLoc &DL, unsigned O) {
8722   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
8723          "Expected inlined-at fields to agree");
8724   return new (DbgInfo->getAlloc())
8725       SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromConst(C), {},
8726                  /*IsIndirect=*/false, DL, O,
8727                  /*IsVariadic=*/false);
8728 }
8729 
8730 /// FrameIndex
8731 SDDbgValue *SelectionDAG::getFrameIndexDbgValue(DIVariable *Var,
8732                                                 DIExpression *Expr, unsigned FI,
8733                                                 bool IsIndirect,
8734                                                 const DebugLoc &DL,
8735                                                 unsigned O) {
8736   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
8737          "Expected inlined-at fields to agree");
8738   return getFrameIndexDbgValue(Var, Expr, FI, {}, IsIndirect, DL, O);
8739 }
8740 
8741 /// FrameIndex with dependencies
8742 SDDbgValue *SelectionDAG::getFrameIndexDbgValue(DIVariable *Var,
8743                                                 DIExpression *Expr, unsigned FI,
8744                                                 ArrayRef<SDNode *> Dependencies,
8745                                                 bool IsIndirect,
8746                                                 const DebugLoc &DL,
8747                                                 unsigned O) {
8748   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
8749          "Expected inlined-at fields to agree");
8750   return new (DbgInfo->getAlloc())
8751       SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromFrameIdx(FI),
8752                  Dependencies, IsIndirect, DL, O,
8753                  /*IsVariadic=*/false);
8754 }
8755 
8756 /// VReg
8757 SDDbgValue *SelectionDAG::getVRegDbgValue(DIVariable *Var, DIExpression *Expr,
8758                                           unsigned VReg, bool IsIndirect,
8759                                           const DebugLoc &DL, unsigned O) {
8760   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
8761          "Expected inlined-at fields to agree");
8762   return new (DbgInfo->getAlloc())
8763       SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromVReg(VReg),
8764                  {}, IsIndirect, DL, O,
8765                  /*IsVariadic=*/false);
8766 }
8767 
8768 SDDbgValue *SelectionDAG::getDbgValueList(DIVariable *Var, DIExpression *Expr,
8769                                           ArrayRef<SDDbgOperand> Locs,
8770                                           ArrayRef<SDNode *> Dependencies,
8771                                           bool IsIndirect, const DebugLoc &DL,
8772                                           unsigned O, bool IsVariadic) {
8773   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
8774          "Expected inlined-at fields to agree");
8775   return new (DbgInfo->getAlloc())
8776       SDDbgValue(DbgInfo->getAlloc(), Var, Expr, Locs, Dependencies, IsIndirect,
8777                  DL, O, IsVariadic);
8778 }
8779 
8780 void SelectionDAG::transferDbgValues(SDValue From, SDValue To,
8781                                      unsigned OffsetInBits, unsigned SizeInBits,
8782                                      bool InvalidateDbg) {
8783   SDNode *FromNode = From.getNode();
8784   SDNode *ToNode = To.getNode();
8785   assert(FromNode && ToNode && "Can't modify dbg values");
8786 
8787   // PR35338
8788   // TODO: assert(From != To && "Redundant dbg value transfer");
8789   // TODO: assert(FromNode != ToNode && "Intranode dbg value transfer");
8790   if (From == To || FromNode == ToNode)
8791     return;
8792 
8793   if (!FromNode->getHasDebugValue())
8794     return;
8795 
8796   SDDbgOperand FromLocOp =
8797       SDDbgOperand::fromNode(From.getNode(), From.getResNo());
8798   SDDbgOperand ToLocOp = SDDbgOperand::fromNode(To.getNode(), To.getResNo());
8799 
8800   SmallVector<SDDbgValue *, 2> ClonedDVs;
8801   for (SDDbgValue *Dbg : GetDbgValues(FromNode)) {
8802     if (Dbg->isInvalidated())
8803       continue;
8804 
8805     // TODO: assert(!Dbg->isInvalidated() && "Transfer of invalid dbg value");
8806 
8807     // Create a new location ops vector that is equal to the old vector, but
8808     // with each instance of FromLocOp replaced with ToLocOp.
8809     bool Changed = false;
8810     auto NewLocOps = Dbg->copyLocationOps();
8811     std::replace_if(
8812         NewLocOps.begin(), NewLocOps.end(),
8813         [&Changed, FromLocOp](const SDDbgOperand &Op) {
8814           bool Match = Op == FromLocOp;
8815           Changed |= Match;
8816           return Match;
8817         },
8818         ToLocOp);
8819     // Ignore this SDDbgValue if we didn't find a matching location.
8820     if (!Changed)
8821       continue;
8822 
8823     DIVariable *Var = Dbg->getVariable();
8824     auto *Expr = Dbg->getExpression();
8825     // If a fragment is requested, update the expression.
8826     if (SizeInBits) {
8827       // When splitting a larger (e.g., sign-extended) value whose
8828       // lower bits are described with an SDDbgValue, do not attempt
8829       // to transfer the SDDbgValue to the upper bits.
8830       if (auto FI = Expr->getFragmentInfo())
8831         if (OffsetInBits + SizeInBits > FI->SizeInBits)
8832           continue;
8833       auto Fragment = DIExpression::createFragmentExpression(Expr, OffsetInBits,
8834                                                              SizeInBits);
8835       if (!Fragment)
8836         continue;
8837       Expr = *Fragment;
8838     }
8839 
8840     auto AdditionalDependencies = Dbg->getAdditionalDependencies();
8841     // Clone the SDDbgValue and move it to To.
8842     SDDbgValue *Clone = getDbgValueList(
8843         Var, Expr, NewLocOps, AdditionalDependencies, Dbg->isIndirect(),
8844         Dbg->getDebugLoc(), std::max(ToNode->getIROrder(), Dbg->getOrder()),
8845         Dbg->isVariadic());
8846     ClonedDVs.push_back(Clone);
8847 
8848     if (InvalidateDbg) {
8849       // Invalidate value and indicate the SDDbgValue should not be emitted.
8850       Dbg->setIsInvalidated();
8851       Dbg->setIsEmitted();
8852     }
8853   }
8854 
8855   for (SDDbgValue *Dbg : ClonedDVs) {
8856     assert(is_contained(Dbg->getSDNodes(), ToNode) &&
8857            "Transferred DbgValues should depend on the new SDNode");
8858     AddDbgValue(Dbg, false);
8859   }
8860 }
8861 
8862 void SelectionDAG::salvageDebugInfo(SDNode &N) {
8863   if (!N.getHasDebugValue())
8864     return;
8865 
8866   SmallVector<SDDbgValue *, 2> ClonedDVs;
8867   for (auto DV : GetDbgValues(&N)) {
8868     if (DV->isInvalidated())
8869       continue;
8870     switch (N.getOpcode()) {
8871     default:
8872       break;
8873     case ISD::ADD:
8874       SDValue N0 = N.getOperand(0);
8875       SDValue N1 = N.getOperand(1);
8876       if (!isConstantIntBuildVectorOrConstantInt(N0) &&
8877           isConstantIntBuildVectorOrConstantInt(N1)) {
8878         uint64_t Offset = N.getConstantOperandVal(1);
8879 
8880         // Rewrite an ADD constant node into a DIExpression. Since we are
8881         // performing arithmetic to compute the variable's *value* in the
8882         // DIExpression, we need to mark the expression with a
8883         // DW_OP_stack_value.
8884         auto *DIExpr = DV->getExpression();
8885         auto NewLocOps = DV->copyLocationOps();
8886         bool Changed = false;
8887         for (size_t i = 0; i < NewLocOps.size(); ++i) {
8888           // We're not given a ResNo to compare against because the whole
8889           // node is going away. We know that any ISD::ADD only has one
8890           // result, so we can assume any node match is using the result.
8891           if (NewLocOps[i].getKind() != SDDbgOperand::SDNODE ||
8892               NewLocOps[i].getSDNode() != &N)
8893             continue;
8894           NewLocOps[i] = SDDbgOperand::fromNode(N0.getNode(), N0.getResNo());
8895           SmallVector<uint64_t, 3> ExprOps;
8896           DIExpression::appendOffset(ExprOps, Offset);
8897           DIExpr = DIExpression::appendOpsToArg(DIExpr, ExprOps, i, true);
8898           Changed = true;
8899         }
8900         (void)Changed;
8901         assert(Changed && "Salvage target doesn't use N");
8902 
8903         auto AdditionalDependencies = DV->getAdditionalDependencies();
8904         SDDbgValue *Clone = getDbgValueList(DV->getVariable(), DIExpr,
8905                                             NewLocOps, AdditionalDependencies,
8906                                             DV->isIndirect(), DV->getDebugLoc(),
8907                                             DV->getOrder(), DV->isVariadic());
8908         ClonedDVs.push_back(Clone);
8909         DV->setIsInvalidated();
8910         DV->setIsEmitted();
8911         LLVM_DEBUG(dbgs() << "SALVAGE: Rewriting";
8912                    N0.getNode()->dumprFull(this);
8913                    dbgs() << " into " << *DIExpr << '\n');
8914       }
8915     }
8916   }
8917 
8918   for (SDDbgValue *Dbg : ClonedDVs) {
8919     assert(!Dbg->getSDNodes().empty() &&
8920            "Salvaged DbgValue should depend on a new SDNode");
8921     AddDbgValue(Dbg, false);
8922   }
8923 }
8924 
8925 /// Creates a SDDbgLabel node.
8926 SDDbgLabel *SelectionDAG::getDbgLabel(DILabel *Label,
8927                                       const DebugLoc &DL, unsigned O) {
8928   assert(cast<DILabel>(Label)->isValidLocationForIntrinsic(DL) &&
8929          "Expected inlined-at fields to agree");
8930   return new (DbgInfo->getAlloc()) SDDbgLabel(Label, DL, O);
8931 }
8932 
8933 namespace {
8934 
8935 /// RAUWUpdateListener - Helper for ReplaceAllUsesWith - When the node
8936 /// pointed to by a use iterator is deleted, increment the use iterator
8937 /// so that it doesn't dangle.
8938 ///
8939 class RAUWUpdateListener : public SelectionDAG::DAGUpdateListener {
8940   SDNode::use_iterator &UI;
8941   SDNode::use_iterator &UE;
8942 
8943   void NodeDeleted(SDNode *N, SDNode *E) override {
8944     // Increment the iterator as needed.
8945     while (UI != UE && N == *UI)
8946       ++UI;
8947   }
8948 
8949 public:
8950   RAUWUpdateListener(SelectionDAG &d,
8951                      SDNode::use_iterator &ui,
8952                      SDNode::use_iterator &ue)
8953     : SelectionDAG::DAGUpdateListener(d), UI(ui), UE(ue) {}
8954 };
8955 
8956 } // end anonymous namespace
8957 
8958 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
8959 /// This can cause recursive merging of nodes in the DAG.
8960 ///
8961 /// This version assumes From has a single result value.
8962 ///
8963 void SelectionDAG::ReplaceAllUsesWith(SDValue FromN, SDValue To) {
8964   SDNode *From = FromN.getNode();
8965   assert(From->getNumValues() == 1 && FromN.getResNo() == 0 &&
8966          "Cannot replace with this method!");
8967   assert(From != To.getNode() && "Cannot replace uses of with self");
8968 
8969   // Preserve Debug Values
8970   transferDbgValues(FromN, To);
8971 
8972   // Iterate over all the existing uses of From. New uses will be added
8973   // to the beginning of the use list, which we avoid visiting.
8974   // This specifically avoids visiting uses of From that arise while the
8975   // replacement is happening, because any such uses would be the result
8976   // of CSE: If an existing node looks like From after one of its operands
8977   // is replaced by To, we don't want to replace of all its users with To
8978   // too. See PR3018 for more info.
8979   SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
8980   RAUWUpdateListener Listener(*this, UI, UE);
8981   while (UI != UE) {
8982     SDNode *User = *UI;
8983 
8984     // This node is about to morph, remove its old self from the CSE maps.
8985     RemoveNodeFromCSEMaps(User);
8986 
8987     // A user can appear in a use list multiple times, and when this
8988     // happens the uses are usually next to each other in the list.
8989     // To help reduce the number of CSE recomputations, process all
8990     // the uses of this user that we can find this way.
8991     do {
8992       SDUse &Use = UI.getUse();
8993       ++UI;
8994       Use.set(To);
8995       if (To->isDivergent() != From->isDivergent())
8996         updateDivergence(User);
8997     } while (UI != UE && *UI == User);
8998     // Now that we have modified User, add it back to the CSE maps.  If it
8999     // already exists there, recursively merge the results together.
9000     AddModifiedNodeToCSEMaps(User);
9001   }
9002 
9003   // If we just RAUW'd the root, take note.
9004   if (FromN == getRoot())
9005     setRoot(To);
9006 }
9007 
9008 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
9009 /// This can cause recursive merging of nodes in the DAG.
9010 ///
9011 /// This version assumes that for each value of From, there is a
9012 /// corresponding value in To in the same position with the same type.
9013 ///
9014 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, SDNode *To) {
9015 #ifndef NDEBUG
9016   for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
9017     assert((!From->hasAnyUseOfValue(i) ||
9018             From->getValueType(i) == To->getValueType(i)) &&
9019            "Cannot use this version of ReplaceAllUsesWith!");
9020 #endif
9021 
9022   // Handle the trivial case.
9023   if (From == To)
9024     return;
9025 
9026   // Preserve Debug Info. Only do this if there's a use.
9027   for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
9028     if (From->hasAnyUseOfValue(i)) {
9029       assert((i < To->getNumValues()) && "Invalid To location");
9030       transferDbgValues(SDValue(From, i), SDValue(To, i));
9031     }
9032 
9033   // Iterate over just the existing users of From. See the comments in
9034   // the ReplaceAllUsesWith above.
9035   SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
9036   RAUWUpdateListener Listener(*this, UI, UE);
9037   while (UI != UE) {
9038     SDNode *User = *UI;
9039 
9040     // This node is about to morph, remove its old self from the CSE maps.
9041     RemoveNodeFromCSEMaps(User);
9042 
9043     // A user can appear in a use list multiple times, and when this
9044     // happens the uses are usually next to each other in the list.
9045     // To help reduce the number of CSE recomputations, process all
9046     // the uses of this user that we can find this way.
9047     do {
9048       SDUse &Use = UI.getUse();
9049       ++UI;
9050       Use.setNode(To);
9051       if (To->isDivergent() != From->isDivergent())
9052         updateDivergence(User);
9053     } while (UI != UE && *UI == User);
9054 
9055     // Now that we have modified User, add it back to the CSE maps.  If it
9056     // already exists there, recursively merge the results together.
9057     AddModifiedNodeToCSEMaps(User);
9058   }
9059 
9060   // If we just RAUW'd the root, take note.
9061   if (From == getRoot().getNode())
9062     setRoot(SDValue(To, getRoot().getResNo()));
9063 }
9064 
9065 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
9066 /// This can cause recursive merging of nodes in the DAG.
9067 ///
9068 /// This version can replace From with any result values.  To must match the
9069 /// number and types of values returned by From.
9070 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, const SDValue *To) {
9071   if (From->getNumValues() == 1)  // Handle the simple case efficiently.
9072     return ReplaceAllUsesWith(SDValue(From, 0), To[0]);
9073 
9074   // Preserve Debug Info.
9075   for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
9076     transferDbgValues(SDValue(From, i), To[i]);
9077 
9078   // Iterate over just the existing users of From. See the comments in
9079   // the ReplaceAllUsesWith above.
9080   SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
9081   RAUWUpdateListener Listener(*this, UI, UE);
9082   while (UI != UE) {
9083     SDNode *User = *UI;
9084 
9085     // This node is about to morph, remove its old self from the CSE maps.
9086     RemoveNodeFromCSEMaps(User);
9087 
9088     // A user can appear in a use list multiple times, and when this happens the
9089     // uses are usually next to each other in the list.  To help reduce the
9090     // number of CSE and divergence recomputations, process all the uses of this
9091     // user that we can find this way.
9092     bool To_IsDivergent = false;
9093     do {
9094       SDUse &Use = UI.getUse();
9095       const SDValue &ToOp = To[Use.getResNo()];
9096       ++UI;
9097       Use.set(ToOp);
9098       To_IsDivergent |= ToOp->isDivergent();
9099     } while (UI != UE && *UI == User);
9100 
9101     if (To_IsDivergent != From->isDivergent())
9102       updateDivergence(User);
9103 
9104     // Now that we have modified User, add it back to the CSE maps.  If it
9105     // already exists there, recursively merge the results together.
9106     AddModifiedNodeToCSEMaps(User);
9107   }
9108 
9109   // If we just RAUW'd the root, take note.
9110   if (From == getRoot().getNode())
9111     setRoot(SDValue(To[getRoot().getResNo()]));
9112 }
9113 
9114 /// ReplaceAllUsesOfValueWith - Replace any uses of From with To, leaving
9115 /// uses of other values produced by From.getNode() alone.  The Deleted
9116 /// vector is handled the same way as for ReplaceAllUsesWith.
9117 void SelectionDAG::ReplaceAllUsesOfValueWith(SDValue From, SDValue To){
9118   // Handle the really simple, really trivial case efficiently.
9119   if (From == To) return;
9120 
9121   // Handle the simple, trivial, case efficiently.
9122   if (From.getNode()->getNumValues() == 1) {
9123     ReplaceAllUsesWith(From, To);
9124     return;
9125   }
9126 
9127   // Preserve Debug Info.
9128   transferDbgValues(From, To);
9129 
9130   // Iterate over just the existing users of From. See the comments in
9131   // the ReplaceAllUsesWith above.
9132   SDNode::use_iterator UI = From.getNode()->use_begin(),
9133                        UE = From.getNode()->use_end();
9134   RAUWUpdateListener Listener(*this, UI, UE);
9135   while (UI != UE) {
9136     SDNode *User = *UI;
9137     bool UserRemovedFromCSEMaps = false;
9138 
9139     // A user can appear in a use list multiple times, and when this
9140     // happens the uses are usually next to each other in the list.
9141     // To help reduce the number of CSE recomputations, process all
9142     // the uses of this user that we can find this way.
9143     do {
9144       SDUse &Use = UI.getUse();
9145 
9146       // Skip uses of different values from the same node.
9147       if (Use.getResNo() != From.getResNo()) {
9148         ++UI;
9149         continue;
9150       }
9151 
9152       // If this node hasn't been modified yet, it's still in the CSE maps,
9153       // so remove its old self from the CSE maps.
9154       if (!UserRemovedFromCSEMaps) {
9155         RemoveNodeFromCSEMaps(User);
9156         UserRemovedFromCSEMaps = true;
9157       }
9158 
9159       ++UI;
9160       Use.set(To);
9161       if (To->isDivergent() != From->isDivergent())
9162         updateDivergence(User);
9163     } while (UI != UE && *UI == User);
9164     // We are iterating over all uses of the From node, so if a use
9165     // doesn't use the specific value, no changes are made.
9166     if (!UserRemovedFromCSEMaps)
9167       continue;
9168 
9169     // Now that we have modified User, add it back to the CSE maps.  If it
9170     // already exists there, recursively merge the results together.
9171     AddModifiedNodeToCSEMaps(User);
9172   }
9173 
9174   // If we just RAUW'd the root, take note.
9175   if (From == getRoot())
9176     setRoot(To);
9177 }
9178 
9179 namespace {
9180 
9181   /// UseMemo - This class is used by SelectionDAG::ReplaceAllUsesOfValuesWith
9182   /// to record information about a use.
9183   struct UseMemo {
9184     SDNode *User;
9185     unsigned Index;
9186     SDUse *Use;
9187   };
9188 
9189   /// operator< - Sort Memos by User.
9190   bool operator<(const UseMemo &L, const UseMemo &R) {
9191     return (intptr_t)L.User < (intptr_t)R.User;
9192   }
9193 
9194 } // end anonymous namespace
9195 
9196 bool SelectionDAG::calculateDivergence(SDNode *N) {
9197   if (TLI->isSDNodeAlwaysUniform(N)) {
9198     assert(!TLI->isSDNodeSourceOfDivergence(N, FLI, DA) &&
9199            "Conflicting divergence information!");
9200     return false;
9201   }
9202   if (TLI->isSDNodeSourceOfDivergence(N, FLI, DA))
9203     return true;
9204   for (auto &Op : N->ops()) {
9205     if (Op.Val.getValueType() != MVT::Other && Op.getNode()->isDivergent())
9206       return true;
9207   }
9208   return false;
9209 }
9210 
9211 void SelectionDAG::updateDivergence(SDNode *N) {
9212   SmallVector<SDNode *, 16> Worklist(1, N);
9213   do {
9214     N = Worklist.pop_back_val();
9215     bool IsDivergent = calculateDivergence(N);
9216     if (N->SDNodeBits.IsDivergent != IsDivergent) {
9217       N->SDNodeBits.IsDivergent = IsDivergent;
9218       llvm::append_range(Worklist, N->uses());
9219     }
9220   } while (!Worklist.empty());
9221 }
9222 
9223 void SelectionDAG::CreateTopologicalOrder(std::vector<SDNode *> &Order) {
9224   DenseMap<SDNode *, unsigned> Degree;
9225   Order.reserve(AllNodes.size());
9226   for (auto &N : allnodes()) {
9227     unsigned NOps = N.getNumOperands();
9228     Degree[&N] = NOps;
9229     if (0 == NOps)
9230       Order.push_back(&N);
9231   }
9232   for (size_t I = 0; I != Order.size(); ++I) {
9233     SDNode *N = Order[I];
9234     for (auto U : N->uses()) {
9235       unsigned &UnsortedOps = Degree[U];
9236       if (0 == --UnsortedOps)
9237         Order.push_back(U);
9238     }
9239   }
9240 }
9241 
9242 #ifndef NDEBUG
9243 void SelectionDAG::VerifyDAGDiverence() {
9244   std::vector<SDNode *> TopoOrder;
9245   CreateTopologicalOrder(TopoOrder);
9246   for (auto *N : TopoOrder) {
9247     assert(calculateDivergence(N) == N->isDivergent() &&
9248            "Divergence bit inconsistency detected");
9249   }
9250 }
9251 #endif
9252 
9253 /// ReplaceAllUsesOfValuesWith - Replace any uses of From with To, leaving
9254 /// uses of other values produced by From.getNode() alone.  The same value
9255 /// may appear in both the From and To list.  The Deleted vector is
9256 /// handled the same way as for ReplaceAllUsesWith.
9257 void SelectionDAG::ReplaceAllUsesOfValuesWith(const SDValue *From,
9258                                               const SDValue *To,
9259                                               unsigned Num){
9260   // Handle the simple, trivial case efficiently.
9261   if (Num == 1)
9262     return ReplaceAllUsesOfValueWith(*From, *To);
9263 
9264   transferDbgValues(*From, *To);
9265 
9266   // Read up all the uses and make records of them. This helps
9267   // processing new uses that are introduced during the
9268   // replacement process.
9269   SmallVector<UseMemo, 4> Uses;
9270   for (unsigned i = 0; i != Num; ++i) {
9271     unsigned FromResNo = From[i].getResNo();
9272     SDNode *FromNode = From[i].getNode();
9273     for (SDNode::use_iterator UI = FromNode->use_begin(),
9274          E = FromNode->use_end(); UI != E; ++UI) {
9275       SDUse &Use = UI.getUse();
9276       if (Use.getResNo() == FromResNo) {
9277         UseMemo Memo = { *UI, i, &Use };
9278         Uses.push_back(Memo);
9279       }
9280     }
9281   }
9282 
9283   // Sort the uses, so that all the uses from a given User are together.
9284   llvm::sort(Uses);
9285 
9286   for (unsigned UseIndex = 0, UseIndexEnd = Uses.size();
9287        UseIndex != UseIndexEnd; ) {
9288     // We know that this user uses some value of From.  If it is the right
9289     // value, update it.
9290     SDNode *User = Uses[UseIndex].User;
9291 
9292     // This node is about to morph, remove its old self from the CSE maps.
9293     RemoveNodeFromCSEMaps(User);
9294 
9295     // The Uses array is sorted, so all the uses for a given User
9296     // are next to each other in the list.
9297     // To help reduce the number of CSE recomputations, process all
9298     // the uses of this user that we can find this way.
9299     do {
9300       unsigned i = Uses[UseIndex].Index;
9301       SDUse &Use = *Uses[UseIndex].Use;
9302       ++UseIndex;
9303 
9304       Use.set(To[i]);
9305     } while (UseIndex != UseIndexEnd && Uses[UseIndex].User == User);
9306 
9307     // Now that we have modified User, add it back to the CSE maps.  If it
9308     // already exists there, recursively merge the results together.
9309     AddModifiedNodeToCSEMaps(User);
9310   }
9311 }
9312 
9313 /// AssignTopologicalOrder - Assign a unique node id for each node in the DAG
9314 /// based on their topological order. It returns the maximum id and a vector
9315 /// of the SDNodes* in assigned order by reference.
9316 unsigned SelectionDAG::AssignTopologicalOrder() {
9317   unsigned DAGSize = 0;
9318 
9319   // SortedPos tracks the progress of the algorithm. Nodes before it are
9320   // sorted, nodes after it are unsorted. When the algorithm completes
9321   // it is at the end of the list.
9322   allnodes_iterator SortedPos = allnodes_begin();
9323 
9324   // Visit all the nodes. Move nodes with no operands to the front of
9325   // the list immediately. Annotate nodes that do have operands with their
9326   // operand count. Before we do this, the Node Id fields of the nodes
9327   // may contain arbitrary values. After, the Node Id fields for nodes
9328   // before SortedPos will contain the topological sort index, and the
9329   // Node Id fields for nodes At SortedPos and after will contain the
9330   // count of outstanding operands.
9331   for (allnodes_iterator I = allnodes_begin(),E = allnodes_end(); I != E; ) {
9332     SDNode *N = &*I++;
9333     checkForCycles(N, this);
9334     unsigned Degree = N->getNumOperands();
9335     if (Degree == 0) {
9336       // A node with no uses, add it to the result array immediately.
9337       N->setNodeId(DAGSize++);
9338       allnodes_iterator Q(N);
9339       if (Q != SortedPos)
9340         SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(Q));
9341       assert(SortedPos != AllNodes.end() && "Overran node list");
9342       ++SortedPos;
9343     } else {
9344       // Temporarily use the Node Id as scratch space for the degree count.
9345       N->setNodeId(Degree);
9346     }
9347   }
9348 
9349   // Visit all the nodes. As we iterate, move nodes into sorted order,
9350   // such that by the time the end is reached all nodes will be sorted.
9351   for (SDNode &Node : allnodes()) {
9352     SDNode *N = &Node;
9353     checkForCycles(N, this);
9354     // N is in sorted position, so all its uses have one less operand
9355     // that needs to be sorted.
9356     for (SDNode *P : N->uses()) {
9357       unsigned Degree = P->getNodeId();
9358       assert(Degree != 0 && "Invalid node degree");
9359       --Degree;
9360       if (Degree == 0) {
9361         // All of P's operands are sorted, so P may sorted now.
9362         P->setNodeId(DAGSize++);
9363         if (P->getIterator() != SortedPos)
9364           SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(P));
9365         assert(SortedPos != AllNodes.end() && "Overran node list");
9366         ++SortedPos;
9367       } else {
9368         // Update P's outstanding operand count.
9369         P->setNodeId(Degree);
9370       }
9371     }
9372     if (Node.getIterator() == SortedPos) {
9373 #ifndef NDEBUG
9374       allnodes_iterator I(N);
9375       SDNode *S = &*++I;
9376       dbgs() << "Overran sorted position:\n";
9377       S->dumprFull(this); dbgs() << "\n";
9378       dbgs() << "Checking if this is due to cycles\n";
9379       checkForCycles(this, true);
9380 #endif
9381       llvm_unreachable(nullptr);
9382     }
9383   }
9384 
9385   assert(SortedPos == AllNodes.end() &&
9386          "Topological sort incomplete!");
9387   assert(AllNodes.front().getOpcode() == ISD::EntryToken &&
9388          "First node in topological sort is not the entry token!");
9389   assert(AllNodes.front().getNodeId() == 0 &&
9390          "First node in topological sort has non-zero id!");
9391   assert(AllNodes.front().getNumOperands() == 0 &&
9392          "First node in topological sort has operands!");
9393   assert(AllNodes.back().getNodeId() == (int)DAGSize-1 &&
9394          "Last node in topologic sort has unexpected id!");
9395   assert(AllNodes.back().use_empty() &&
9396          "Last node in topologic sort has users!");
9397   assert(DAGSize == allnodes_size() && "Node count mismatch!");
9398   return DAGSize;
9399 }
9400 
9401 /// AddDbgValue - Add a dbg_value SDNode. If SD is non-null that means the
9402 /// value is produced by SD.
9403 void SelectionDAG::AddDbgValue(SDDbgValue *DB, bool isParameter) {
9404   for (SDNode *SD : DB->getSDNodes()) {
9405     if (!SD)
9406       continue;
9407     assert(DbgInfo->getSDDbgValues(SD).empty() || SD->getHasDebugValue());
9408     SD->setHasDebugValue(true);
9409   }
9410   DbgInfo->add(DB, isParameter);
9411 }
9412 
9413 void SelectionDAG::AddDbgLabel(SDDbgLabel *DB) { DbgInfo->add(DB); }
9414 
9415 SDValue SelectionDAG::makeEquivalentMemoryOrdering(SDValue OldChain,
9416                                                    SDValue NewMemOpChain) {
9417   assert(isa<MemSDNode>(NewMemOpChain) && "Expected a memop node");
9418   assert(NewMemOpChain.getValueType() == MVT::Other && "Expected a token VT");
9419   // The new memory operation must have the same position as the old load in
9420   // terms of memory dependency. Create a TokenFactor for the old load and new
9421   // memory operation and update uses of the old load's output chain to use that
9422   // TokenFactor.
9423   if (OldChain == NewMemOpChain || OldChain.use_empty())
9424     return NewMemOpChain;
9425 
9426   SDValue TokenFactor = getNode(ISD::TokenFactor, SDLoc(OldChain), MVT::Other,
9427                                 OldChain, NewMemOpChain);
9428   ReplaceAllUsesOfValueWith(OldChain, TokenFactor);
9429   UpdateNodeOperands(TokenFactor.getNode(), OldChain, NewMemOpChain);
9430   return TokenFactor;
9431 }
9432 
9433 SDValue SelectionDAG::makeEquivalentMemoryOrdering(LoadSDNode *OldLoad,
9434                                                    SDValue NewMemOp) {
9435   assert(isa<MemSDNode>(NewMemOp.getNode()) && "Expected a memop node");
9436   SDValue OldChain = SDValue(OldLoad, 1);
9437   SDValue NewMemOpChain = NewMemOp.getValue(1);
9438   return makeEquivalentMemoryOrdering(OldChain, NewMemOpChain);
9439 }
9440 
9441 SDValue SelectionDAG::getSymbolFunctionGlobalAddress(SDValue Op,
9442                                                      Function **OutFunction) {
9443   assert(isa<ExternalSymbolSDNode>(Op) && "Node should be an ExternalSymbol");
9444 
9445   auto *Symbol = cast<ExternalSymbolSDNode>(Op)->getSymbol();
9446   auto *Module = MF->getFunction().getParent();
9447   auto *Function = Module->getFunction(Symbol);
9448 
9449   if (OutFunction != nullptr)
9450       *OutFunction = Function;
9451 
9452   if (Function != nullptr) {
9453     auto PtrTy = TLI->getPointerTy(getDataLayout(), Function->getAddressSpace());
9454     return getGlobalAddress(Function, SDLoc(Op), PtrTy);
9455   }
9456 
9457   std::string ErrorStr;
9458   raw_string_ostream ErrorFormatter(ErrorStr);
9459 
9460   ErrorFormatter << "Undefined external symbol ";
9461   ErrorFormatter << '"' << Symbol << '"';
9462   ErrorFormatter.flush();
9463 
9464   report_fatal_error(ErrorStr);
9465 }
9466 
9467 //===----------------------------------------------------------------------===//
9468 //                              SDNode Class
9469 //===----------------------------------------------------------------------===//
9470 
9471 bool llvm::isNullConstant(SDValue V) {
9472   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
9473   return Const != nullptr && Const->isNullValue();
9474 }
9475 
9476 bool llvm::isNullFPConstant(SDValue V) {
9477   ConstantFPSDNode *Const = dyn_cast<ConstantFPSDNode>(V);
9478   return Const != nullptr && Const->isZero() && !Const->isNegative();
9479 }
9480 
9481 bool llvm::isAllOnesConstant(SDValue V) {
9482   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
9483   return Const != nullptr && Const->isAllOnesValue();
9484 }
9485 
9486 bool llvm::isOneConstant(SDValue V) {
9487   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
9488   return Const != nullptr && Const->isOne();
9489 }
9490 
9491 SDValue llvm::peekThroughBitcasts(SDValue V) {
9492   while (V.getOpcode() == ISD::BITCAST)
9493     V = V.getOperand(0);
9494   return V;
9495 }
9496 
9497 SDValue llvm::peekThroughOneUseBitcasts(SDValue V) {
9498   while (V.getOpcode() == ISD::BITCAST && V.getOperand(0).hasOneUse())
9499     V = V.getOperand(0);
9500   return V;
9501 }
9502 
9503 SDValue llvm::peekThroughExtractSubvectors(SDValue V) {
9504   while (V.getOpcode() == ISD::EXTRACT_SUBVECTOR)
9505     V = V.getOperand(0);
9506   return V;
9507 }
9508 
9509 bool llvm::isBitwiseNot(SDValue V, bool AllowUndefs) {
9510   if (V.getOpcode() != ISD::XOR)
9511     return false;
9512   V = peekThroughBitcasts(V.getOperand(1));
9513   unsigned NumBits = V.getScalarValueSizeInBits();
9514   ConstantSDNode *C =
9515       isConstOrConstSplat(V, AllowUndefs, /*AllowTruncation*/ true);
9516   return C && (C->getAPIntValue().countTrailingOnes() >= NumBits);
9517 }
9518 
9519 ConstantSDNode *llvm::isConstOrConstSplat(SDValue N, bool AllowUndefs,
9520                                           bool AllowTruncation) {
9521   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
9522     return CN;
9523 
9524   // SplatVectors can truncate their operands. Ignore that case here unless
9525   // AllowTruncation is set.
9526   if (N->getOpcode() == ISD::SPLAT_VECTOR) {
9527     EVT VecEltVT = N->getValueType(0).getVectorElementType();
9528     if (auto *CN = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
9529       EVT CVT = CN->getValueType(0);
9530       assert(CVT.bitsGE(VecEltVT) && "Illegal splat_vector element extension");
9531       if (AllowTruncation || CVT == VecEltVT)
9532         return CN;
9533     }
9534   }
9535 
9536   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
9537     BitVector UndefElements;
9538     ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
9539 
9540     // BuildVectors can truncate their operands. Ignore that case here unless
9541     // AllowTruncation is set.
9542     if (CN && (UndefElements.none() || AllowUndefs)) {
9543       EVT CVT = CN->getValueType(0);
9544       EVT NSVT = N.getValueType().getScalarType();
9545       assert(CVT.bitsGE(NSVT) && "Illegal build vector element extension");
9546       if (AllowTruncation || (CVT == NSVT))
9547         return CN;
9548     }
9549   }
9550 
9551   return nullptr;
9552 }
9553 
9554 ConstantSDNode *llvm::isConstOrConstSplat(SDValue N, const APInt &DemandedElts,
9555                                           bool AllowUndefs,
9556                                           bool AllowTruncation) {
9557   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
9558     return CN;
9559 
9560   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
9561     BitVector UndefElements;
9562     ConstantSDNode *CN = BV->getConstantSplatNode(DemandedElts, &UndefElements);
9563 
9564     // BuildVectors can truncate their operands. Ignore that case here unless
9565     // AllowTruncation is set.
9566     if (CN && (UndefElements.none() || AllowUndefs)) {
9567       EVT CVT = CN->getValueType(0);
9568       EVT NSVT = N.getValueType().getScalarType();
9569       assert(CVT.bitsGE(NSVT) && "Illegal build vector element extension");
9570       if (AllowTruncation || (CVT == NSVT))
9571         return CN;
9572     }
9573   }
9574 
9575   return nullptr;
9576 }
9577 
9578 ConstantFPSDNode *llvm::isConstOrConstSplatFP(SDValue N, bool AllowUndefs) {
9579   if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
9580     return CN;
9581 
9582   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
9583     BitVector UndefElements;
9584     ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements);
9585     if (CN && (UndefElements.none() || AllowUndefs))
9586       return CN;
9587   }
9588 
9589   if (N.getOpcode() == ISD::SPLAT_VECTOR)
9590     if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N.getOperand(0)))
9591       return CN;
9592 
9593   return nullptr;
9594 }
9595 
9596 ConstantFPSDNode *llvm::isConstOrConstSplatFP(SDValue N,
9597                                               const APInt &DemandedElts,
9598                                               bool AllowUndefs) {
9599   if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
9600     return CN;
9601 
9602   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
9603     BitVector UndefElements;
9604     ConstantFPSDNode *CN =
9605         BV->getConstantFPSplatNode(DemandedElts, &UndefElements);
9606     if (CN && (UndefElements.none() || AllowUndefs))
9607       return CN;
9608   }
9609 
9610   return nullptr;
9611 }
9612 
9613 bool llvm::isNullOrNullSplat(SDValue N, bool AllowUndefs) {
9614   // TODO: may want to use peekThroughBitcast() here.
9615   ConstantSDNode *C =
9616       isConstOrConstSplat(N, AllowUndefs, /*AllowTruncation=*/true);
9617   return C && C->isNullValue();
9618 }
9619 
9620 bool llvm::isOneOrOneSplat(SDValue N, bool AllowUndefs) {
9621   // TODO: may want to use peekThroughBitcast() here.
9622   unsigned BitWidth = N.getScalarValueSizeInBits();
9623   ConstantSDNode *C = isConstOrConstSplat(N, AllowUndefs);
9624   return C && C->isOne() && C->getValueSizeInBits(0) == BitWidth;
9625 }
9626 
9627 bool llvm::isAllOnesOrAllOnesSplat(SDValue N, bool AllowUndefs) {
9628   N = peekThroughBitcasts(N);
9629   unsigned BitWidth = N.getScalarValueSizeInBits();
9630   ConstantSDNode *C = isConstOrConstSplat(N, AllowUndefs);
9631   return C && C->isAllOnesValue() && C->getValueSizeInBits(0) == BitWidth;
9632 }
9633 
9634 HandleSDNode::~HandleSDNode() {
9635   DropOperands();
9636 }
9637 
9638 GlobalAddressSDNode::GlobalAddressSDNode(unsigned Opc, unsigned Order,
9639                                          const DebugLoc &DL,
9640                                          const GlobalValue *GA, EVT VT,
9641                                          int64_t o, unsigned TF)
9642     : SDNode(Opc, Order, DL, getSDVTList(VT)), Offset(o), TargetFlags(TF) {
9643   TheGlobal = GA;
9644 }
9645 
9646 AddrSpaceCastSDNode::AddrSpaceCastSDNode(unsigned Order, const DebugLoc &dl,
9647                                          EVT VT, unsigned SrcAS,
9648                                          unsigned DestAS)
9649     : SDNode(ISD::ADDRSPACECAST, Order, dl, getSDVTList(VT)),
9650       SrcAddrSpace(SrcAS), DestAddrSpace(DestAS) {}
9651 
9652 MemSDNode::MemSDNode(unsigned Opc, unsigned Order, const DebugLoc &dl,
9653                      SDVTList VTs, EVT memvt, MachineMemOperand *mmo)
9654     : SDNode(Opc, Order, dl, VTs), MemoryVT(memvt), MMO(mmo) {
9655   MemSDNodeBits.IsVolatile = MMO->isVolatile();
9656   MemSDNodeBits.IsNonTemporal = MMO->isNonTemporal();
9657   MemSDNodeBits.IsDereferenceable = MMO->isDereferenceable();
9658   MemSDNodeBits.IsInvariant = MMO->isInvariant();
9659 
9660   // We check here that the size of the memory operand fits within the size of
9661   // the MMO. This is because the MMO might indicate only a possible address
9662   // range instead of specifying the affected memory addresses precisely.
9663   // TODO: Make MachineMemOperands aware of scalable vectors.
9664   assert(memvt.getStoreSize().getKnownMinSize() <= MMO->getSize() &&
9665          "Size mismatch!");
9666 }
9667 
9668 /// Profile - Gather unique data for the node.
9669 ///
9670 void SDNode::Profile(FoldingSetNodeID &ID) const {
9671   AddNodeIDNode(ID, this);
9672 }
9673 
9674 namespace {
9675 
9676   struct EVTArray {
9677     std::vector<EVT> VTs;
9678 
9679     EVTArray() {
9680       VTs.reserve(MVT::VALUETYPE_SIZE);
9681       for (unsigned i = 0; i < MVT::VALUETYPE_SIZE; ++i)
9682         VTs.push_back(MVT((MVT::SimpleValueType)i));
9683     }
9684   };
9685 
9686 } // end anonymous namespace
9687 
9688 static ManagedStatic<std::set<EVT, EVT::compareRawBits>> EVTs;
9689 static ManagedStatic<EVTArray> SimpleVTArray;
9690 static ManagedStatic<sys::SmartMutex<true>> VTMutex;
9691 
9692 /// getValueTypeList - Return a pointer to the specified value type.
9693 ///
9694 const EVT *SDNode::getValueTypeList(EVT VT) {
9695   if (VT.isExtended()) {
9696     sys::SmartScopedLock<true> Lock(*VTMutex);
9697     return &(*EVTs->insert(VT).first);
9698   }
9699   assert(VT.getSimpleVT() < MVT::VALUETYPE_SIZE && "Value type out of range!");
9700   return &SimpleVTArray->VTs[VT.getSimpleVT().SimpleTy];
9701 }
9702 
9703 /// hasNUsesOfValue - Return true if there are exactly NUSES uses of the
9704 /// indicated value.  This method ignores uses of other values defined by this
9705 /// operation.
9706 bool SDNode::hasNUsesOfValue(unsigned NUses, unsigned Value) const {
9707   assert(Value < getNumValues() && "Bad value!");
9708 
9709   // TODO: Only iterate over uses of a given value of the node
9710   for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) {
9711     if (UI.getUse().getResNo() == Value) {
9712       if (NUses == 0)
9713         return false;
9714       --NUses;
9715     }
9716   }
9717 
9718   // Found exactly the right number of uses?
9719   return NUses == 0;
9720 }
9721 
9722 /// hasAnyUseOfValue - Return true if there are any use of the indicated
9723 /// value. This method ignores uses of other values defined by this operation.
9724 bool SDNode::hasAnyUseOfValue(unsigned Value) const {
9725   assert(Value < getNumValues() && "Bad value!");
9726 
9727   for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI)
9728     if (UI.getUse().getResNo() == Value)
9729       return true;
9730 
9731   return false;
9732 }
9733 
9734 /// isOnlyUserOf - Return true if this node is the only use of N.
9735 bool SDNode::isOnlyUserOf(const SDNode *N) const {
9736   bool Seen = false;
9737   for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) {
9738     SDNode *User = *I;
9739     if (User == this)
9740       Seen = true;
9741     else
9742       return false;
9743   }
9744 
9745   return Seen;
9746 }
9747 
9748 /// Return true if the only users of N are contained in Nodes.
9749 bool SDNode::areOnlyUsersOf(ArrayRef<const SDNode *> Nodes, const SDNode *N) {
9750   bool Seen = false;
9751   for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) {
9752     SDNode *User = *I;
9753     if (llvm::is_contained(Nodes, User))
9754       Seen = true;
9755     else
9756       return false;
9757   }
9758 
9759   return Seen;
9760 }
9761 
9762 /// isOperand - Return true if this node is an operand of N.
9763 bool SDValue::isOperandOf(const SDNode *N) const {
9764   return is_contained(N->op_values(), *this);
9765 }
9766 
9767 bool SDNode::isOperandOf(const SDNode *N) const {
9768   return any_of(N->op_values(),
9769                 [this](SDValue Op) { return this == Op.getNode(); });
9770 }
9771 
9772 /// reachesChainWithoutSideEffects - Return true if this operand (which must
9773 /// be a chain) reaches the specified operand without crossing any
9774 /// side-effecting instructions on any chain path.  In practice, this looks
9775 /// through token factors and non-volatile loads.  In order to remain efficient,
9776 /// this only looks a couple of nodes in, it does not do an exhaustive search.
9777 ///
9778 /// Note that we only need to examine chains when we're searching for
9779 /// side-effects; SelectionDAG requires that all side-effects are represented
9780 /// by chains, even if another operand would force a specific ordering. This
9781 /// constraint is necessary to allow transformations like splitting loads.
9782 bool SDValue::reachesChainWithoutSideEffects(SDValue Dest,
9783                                              unsigned Depth) const {
9784   if (*this == Dest) return true;
9785 
9786   // Don't search too deeply, we just want to be able to see through
9787   // TokenFactor's etc.
9788   if (Depth == 0) return false;
9789 
9790   // If this is a token factor, all inputs to the TF happen in parallel.
9791   if (getOpcode() == ISD::TokenFactor) {
9792     // First, try a shallow search.
9793     if (is_contained((*this)->ops(), Dest)) {
9794       // We found the chain we want as an operand of this TokenFactor.
9795       // Essentially, we reach the chain without side-effects if we could
9796       // serialize the TokenFactor into a simple chain of operations with
9797       // Dest as the last operation. This is automatically true if the
9798       // chain has one use: there are no other ordering constraints.
9799       // If the chain has more than one use, we give up: some other
9800       // use of Dest might force a side-effect between Dest and the current
9801       // node.
9802       if (Dest.hasOneUse())
9803         return true;
9804     }
9805     // Next, try a deep search: check whether every operand of the TokenFactor
9806     // reaches Dest.
9807     return llvm::all_of((*this)->ops(), [=](SDValue Op) {
9808       return Op.reachesChainWithoutSideEffects(Dest, Depth - 1);
9809     });
9810   }
9811 
9812   // Loads don't have side effects, look through them.
9813   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(*this)) {
9814     if (Ld->isUnordered())
9815       return Ld->getChain().reachesChainWithoutSideEffects(Dest, Depth-1);
9816   }
9817   return false;
9818 }
9819 
9820 bool SDNode::hasPredecessor(const SDNode *N) const {
9821   SmallPtrSet<const SDNode *, 32> Visited;
9822   SmallVector<const SDNode *, 16> Worklist;
9823   Worklist.push_back(this);
9824   return hasPredecessorHelper(N, Visited, Worklist);
9825 }
9826 
9827 void SDNode::intersectFlagsWith(const SDNodeFlags Flags) {
9828   this->Flags.intersectWith(Flags);
9829 }
9830 
9831 SDValue
9832 SelectionDAG::matchBinOpReduction(SDNode *Extract, ISD::NodeType &BinOp,
9833                                   ArrayRef<ISD::NodeType> CandidateBinOps,
9834                                   bool AllowPartials) {
9835   // The pattern must end in an extract from index 0.
9836   if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
9837       !isNullConstant(Extract->getOperand(1)))
9838     return SDValue();
9839 
9840   // Match against one of the candidate binary ops.
9841   SDValue Op = Extract->getOperand(0);
9842   if (llvm::none_of(CandidateBinOps, [Op](ISD::NodeType BinOp) {
9843         return Op.getOpcode() == unsigned(BinOp);
9844       }))
9845     return SDValue();
9846 
9847   // Floating-point reductions may require relaxed constraints on the final step
9848   // of the reduction because they may reorder intermediate operations.
9849   unsigned CandidateBinOp = Op.getOpcode();
9850   if (Op.getValueType().isFloatingPoint()) {
9851     SDNodeFlags Flags = Op->getFlags();
9852     switch (CandidateBinOp) {
9853     case ISD::FADD:
9854       if (!Flags.hasNoSignedZeros() || !Flags.hasAllowReassociation())
9855         return SDValue();
9856       break;
9857     default:
9858       llvm_unreachable("Unhandled FP opcode for binop reduction");
9859     }
9860   }
9861 
9862   // Matching failed - attempt to see if we did enough stages that a partial
9863   // reduction from a subvector is possible.
9864   auto PartialReduction = [&](SDValue Op, unsigned NumSubElts) {
9865     if (!AllowPartials || !Op)
9866       return SDValue();
9867     EVT OpVT = Op.getValueType();
9868     EVT OpSVT = OpVT.getScalarType();
9869     EVT SubVT = EVT::getVectorVT(*getContext(), OpSVT, NumSubElts);
9870     if (!TLI->isExtractSubvectorCheap(SubVT, OpVT, 0))
9871       return SDValue();
9872     BinOp = (ISD::NodeType)CandidateBinOp;
9873     return getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(Op), SubVT, Op,
9874                    getVectorIdxConstant(0, SDLoc(Op)));
9875   };
9876 
9877   // At each stage, we're looking for something that looks like:
9878   // %s = shufflevector <8 x i32> %op, <8 x i32> undef,
9879   //                    <8 x i32> <i32 2, i32 3, i32 undef, i32 undef,
9880   //                               i32 undef, i32 undef, i32 undef, i32 undef>
9881   // %a = binop <8 x i32> %op, %s
9882   // Where the mask changes according to the stage. E.g. for a 3-stage pyramid,
9883   // we expect something like:
9884   // <4,5,6,7,u,u,u,u>
9885   // <2,3,u,u,u,u,u,u>
9886   // <1,u,u,u,u,u,u,u>
9887   // While a partial reduction match would be:
9888   // <2,3,u,u,u,u,u,u>
9889   // <1,u,u,u,u,u,u,u>
9890   unsigned Stages = Log2_32(Op.getValueType().getVectorNumElements());
9891   SDValue PrevOp;
9892   for (unsigned i = 0; i < Stages; ++i) {
9893     unsigned MaskEnd = (1 << i);
9894 
9895     if (Op.getOpcode() != CandidateBinOp)
9896       return PartialReduction(PrevOp, MaskEnd);
9897 
9898     SDValue Op0 = Op.getOperand(0);
9899     SDValue Op1 = Op.getOperand(1);
9900 
9901     ShuffleVectorSDNode *Shuffle = dyn_cast<ShuffleVectorSDNode>(Op0);
9902     if (Shuffle) {
9903       Op = Op1;
9904     } else {
9905       Shuffle = dyn_cast<ShuffleVectorSDNode>(Op1);
9906       Op = Op0;
9907     }
9908 
9909     // The first operand of the shuffle should be the same as the other operand
9910     // of the binop.
9911     if (!Shuffle || Shuffle->getOperand(0) != Op)
9912       return PartialReduction(PrevOp, MaskEnd);
9913 
9914     // Verify the shuffle has the expected (at this stage of the pyramid) mask.
9915     for (int Index = 0; Index < (int)MaskEnd; ++Index)
9916       if (Shuffle->getMaskElt(Index) != (int)(MaskEnd + Index))
9917         return PartialReduction(PrevOp, MaskEnd);
9918 
9919     PrevOp = Op;
9920   }
9921 
9922   // Handle subvector reductions, which tend to appear after the shuffle
9923   // reduction stages.
9924   while (Op.getOpcode() == CandidateBinOp) {
9925     unsigned NumElts = Op.getValueType().getVectorNumElements();
9926     SDValue Op0 = Op.getOperand(0);
9927     SDValue Op1 = Op.getOperand(1);
9928     if (Op0.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
9929         Op1.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
9930         Op0.getOperand(0) != Op1.getOperand(0))
9931       break;
9932     SDValue Src = Op0.getOperand(0);
9933     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
9934     if (NumSrcElts != (2 * NumElts))
9935       break;
9936     if (!(Op0.getConstantOperandAPInt(1) == 0 &&
9937           Op1.getConstantOperandAPInt(1) == NumElts) &&
9938         !(Op1.getConstantOperandAPInt(1) == 0 &&
9939           Op0.getConstantOperandAPInt(1) == NumElts))
9940       break;
9941     Op = Src;
9942   }
9943 
9944   BinOp = (ISD::NodeType)CandidateBinOp;
9945   return Op;
9946 }
9947 
9948 SDValue SelectionDAG::UnrollVectorOp(SDNode *N, unsigned ResNE) {
9949   assert(N->getNumValues() == 1 &&
9950          "Can't unroll a vector with multiple results!");
9951 
9952   EVT VT = N->getValueType(0);
9953   unsigned NE = VT.getVectorNumElements();
9954   EVT EltVT = VT.getVectorElementType();
9955   SDLoc dl(N);
9956 
9957   SmallVector<SDValue, 8> Scalars;
9958   SmallVector<SDValue, 4> Operands(N->getNumOperands());
9959 
9960   // If ResNE is 0, fully unroll the vector op.
9961   if (ResNE == 0)
9962     ResNE = NE;
9963   else if (NE > ResNE)
9964     NE = ResNE;
9965 
9966   unsigned i;
9967   for (i= 0; i != NE; ++i) {
9968     for (unsigned j = 0, e = N->getNumOperands(); j != e; ++j) {
9969       SDValue Operand = N->getOperand(j);
9970       EVT OperandVT = Operand.getValueType();
9971       if (OperandVT.isVector()) {
9972         // A vector operand; extract a single element.
9973         EVT OperandEltVT = OperandVT.getVectorElementType();
9974         Operands[j] = getNode(ISD::EXTRACT_VECTOR_ELT, dl, OperandEltVT,
9975                               Operand, getVectorIdxConstant(i, dl));
9976       } else {
9977         // A scalar operand; just use it as is.
9978         Operands[j] = Operand;
9979       }
9980     }
9981 
9982     switch (N->getOpcode()) {
9983     default: {
9984       Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands,
9985                                 N->getFlags()));
9986       break;
9987     }
9988     case ISD::VSELECT:
9989       Scalars.push_back(getNode(ISD::SELECT, dl, EltVT, Operands));
9990       break;
9991     case ISD::SHL:
9992     case ISD::SRA:
9993     case ISD::SRL:
9994     case ISD::ROTL:
9995     case ISD::ROTR:
9996       Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands[0],
9997                                getShiftAmountOperand(Operands[0].getValueType(),
9998                                                      Operands[1])));
9999       break;
10000     case ISD::SIGN_EXTEND_INREG: {
10001       EVT ExtVT = cast<VTSDNode>(Operands[1])->getVT().getVectorElementType();
10002       Scalars.push_back(getNode(N->getOpcode(), dl, EltVT,
10003                                 Operands[0],
10004                                 getValueType(ExtVT)));
10005     }
10006     }
10007   }
10008 
10009   for (; i < ResNE; ++i)
10010     Scalars.push_back(getUNDEF(EltVT));
10011 
10012   EVT VecVT = EVT::getVectorVT(*getContext(), EltVT, ResNE);
10013   return getBuildVector(VecVT, dl, Scalars);
10014 }
10015 
10016 std::pair<SDValue, SDValue> SelectionDAG::UnrollVectorOverflowOp(
10017     SDNode *N, unsigned ResNE) {
10018   unsigned Opcode = N->getOpcode();
10019   assert((Opcode == ISD::UADDO || Opcode == ISD::SADDO ||
10020           Opcode == ISD::USUBO || Opcode == ISD::SSUBO ||
10021           Opcode == ISD::UMULO || Opcode == ISD::SMULO) &&
10022          "Expected an overflow opcode");
10023 
10024   EVT ResVT = N->getValueType(0);
10025   EVT OvVT = N->getValueType(1);
10026   EVT ResEltVT = ResVT.getVectorElementType();
10027   EVT OvEltVT = OvVT.getVectorElementType();
10028   SDLoc dl(N);
10029 
10030   // If ResNE is 0, fully unroll the vector op.
10031   unsigned NE = ResVT.getVectorNumElements();
10032   if (ResNE == 0)
10033     ResNE = NE;
10034   else if (NE > ResNE)
10035     NE = ResNE;
10036 
10037   SmallVector<SDValue, 8> LHSScalars;
10038   SmallVector<SDValue, 8> RHSScalars;
10039   ExtractVectorElements(N->getOperand(0), LHSScalars, 0, NE);
10040   ExtractVectorElements(N->getOperand(1), RHSScalars, 0, NE);
10041 
10042   EVT SVT = TLI->getSetCCResultType(getDataLayout(), *getContext(), ResEltVT);
10043   SDVTList VTs = getVTList(ResEltVT, SVT);
10044   SmallVector<SDValue, 8> ResScalars;
10045   SmallVector<SDValue, 8> OvScalars;
10046   for (unsigned i = 0; i < NE; ++i) {
10047     SDValue Res = getNode(Opcode, dl, VTs, LHSScalars[i], RHSScalars[i]);
10048     SDValue Ov =
10049         getSelect(dl, OvEltVT, Res.getValue(1),
10050                   getBoolConstant(true, dl, OvEltVT, ResVT),
10051                   getConstant(0, dl, OvEltVT));
10052 
10053     ResScalars.push_back(Res);
10054     OvScalars.push_back(Ov);
10055   }
10056 
10057   ResScalars.append(ResNE - NE, getUNDEF(ResEltVT));
10058   OvScalars.append(ResNE - NE, getUNDEF(OvEltVT));
10059 
10060   EVT NewResVT = EVT::getVectorVT(*getContext(), ResEltVT, ResNE);
10061   EVT NewOvVT = EVT::getVectorVT(*getContext(), OvEltVT, ResNE);
10062   return std::make_pair(getBuildVector(NewResVT, dl, ResScalars),
10063                         getBuildVector(NewOvVT, dl, OvScalars));
10064 }
10065 
10066 bool SelectionDAG::areNonVolatileConsecutiveLoads(LoadSDNode *LD,
10067                                                   LoadSDNode *Base,
10068                                                   unsigned Bytes,
10069                                                   int Dist) const {
10070   if (LD->isVolatile() || Base->isVolatile())
10071     return false;
10072   // TODO: probably too restrictive for atomics, revisit
10073   if (!LD->isSimple())
10074     return false;
10075   if (LD->isIndexed() || Base->isIndexed())
10076     return false;
10077   if (LD->getChain() != Base->getChain())
10078     return false;
10079   EVT VT = LD->getValueType(0);
10080   if (VT.getSizeInBits() / 8 != Bytes)
10081     return false;
10082 
10083   auto BaseLocDecomp = BaseIndexOffset::match(Base, *this);
10084   auto LocDecomp = BaseIndexOffset::match(LD, *this);
10085 
10086   int64_t Offset = 0;
10087   if (BaseLocDecomp.equalBaseIndex(LocDecomp, *this, Offset))
10088     return (Dist * Bytes == Offset);
10089   return false;
10090 }
10091 
10092 /// InferPtrAlignment - Infer alignment of a load / store address. Return None
10093 /// if it cannot be inferred.
10094 MaybeAlign SelectionDAG::InferPtrAlign(SDValue Ptr) const {
10095   // If this is a GlobalAddress + cst, return the alignment.
10096   const GlobalValue *GV = nullptr;
10097   int64_t GVOffset = 0;
10098   if (TLI->isGAPlusOffset(Ptr.getNode(), GV, GVOffset)) {
10099     unsigned PtrWidth = getDataLayout().getPointerTypeSizeInBits(GV->getType());
10100     KnownBits Known(PtrWidth);
10101     llvm::computeKnownBits(GV, Known, getDataLayout());
10102     unsigned AlignBits = Known.countMinTrailingZeros();
10103     if (AlignBits)
10104       return commonAlignment(Align(1ull << std::min(31U, AlignBits)), GVOffset);
10105   }
10106 
10107   // If this is a direct reference to a stack slot, use information about the
10108   // stack slot's alignment.
10109   int FrameIdx = INT_MIN;
10110   int64_t FrameOffset = 0;
10111   if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr)) {
10112     FrameIdx = FI->getIndex();
10113   } else if (isBaseWithConstantOffset(Ptr) &&
10114              isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
10115     // Handle FI+Cst
10116     FrameIdx = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
10117     FrameOffset = Ptr.getConstantOperandVal(1);
10118   }
10119 
10120   if (FrameIdx != INT_MIN) {
10121     const MachineFrameInfo &MFI = getMachineFunction().getFrameInfo();
10122     return commonAlignment(MFI.getObjectAlign(FrameIdx), FrameOffset);
10123   }
10124 
10125   return None;
10126 }
10127 
10128 /// GetSplitDestVTs - Compute the VTs needed for the low/hi parts of a type
10129 /// which is split (or expanded) into two not necessarily identical pieces.
10130 std::pair<EVT, EVT> SelectionDAG::GetSplitDestVTs(const EVT &VT) const {
10131   // Currently all types are split in half.
10132   EVT LoVT, HiVT;
10133   if (!VT.isVector())
10134     LoVT = HiVT = TLI->getTypeToTransformTo(*getContext(), VT);
10135   else
10136     LoVT = HiVT = VT.getHalfNumVectorElementsVT(*getContext());
10137 
10138   return std::make_pair(LoVT, HiVT);
10139 }
10140 
10141 /// GetDependentSplitDestVTs - Compute the VTs needed for the low/hi parts of a
10142 /// type, dependent on an enveloping VT that has been split into two identical
10143 /// pieces. Sets the HiIsEmpty flag when hi type has zero storage size.
10144 std::pair<EVT, EVT>
10145 SelectionDAG::GetDependentSplitDestVTs(const EVT &VT, const EVT &EnvVT,
10146                                        bool *HiIsEmpty) const {
10147   EVT EltTp = VT.getVectorElementType();
10148   // Examples:
10149   //   custom VL=8  with enveloping VL=8/8 yields 8/0 (hi empty)
10150   //   custom VL=9  with enveloping VL=8/8 yields 8/1
10151   //   custom VL=10 with enveloping VL=8/8 yields 8/2
10152   //   etc.
10153   ElementCount VTNumElts = VT.getVectorElementCount();
10154   ElementCount EnvNumElts = EnvVT.getVectorElementCount();
10155   assert(VTNumElts.isScalable() == EnvNumElts.isScalable() &&
10156          "Mixing fixed width and scalable vectors when enveloping a type");
10157   EVT LoVT, HiVT;
10158   if (VTNumElts.getKnownMinValue() > EnvNumElts.getKnownMinValue()) {
10159     LoVT = EnvVT;
10160     HiVT = EVT::getVectorVT(*getContext(), EltTp, VTNumElts - EnvNumElts);
10161     *HiIsEmpty = false;
10162   } else {
10163     // Flag that hi type has zero storage size, but return split envelop type
10164     // (this would be easier if vector types with zero elements were allowed).
10165     LoVT = EVT::getVectorVT(*getContext(), EltTp, VTNumElts);
10166     HiVT = EnvVT;
10167     *HiIsEmpty = true;
10168   }
10169   return std::make_pair(LoVT, HiVT);
10170 }
10171 
10172 /// SplitVector - Split the vector with EXTRACT_SUBVECTOR and return the
10173 /// low/high part.
10174 std::pair<SDValue, SDValue>
10175 SelectionDAG::SplitVector(const SDValue &N, const SDLoc &DL, const EVT &LoVT,
10176                           const EVT &HiVT) {
10177   assert(LoVT.isScalableVector() == HiVT.isScalableVector() &&
10178          LoVT.isScalableVector() == N.getValueType().isScalableVector() &&
10179          "Splitting vector with an invalid mixture of fixed and scalable "
10180          "vector types");
10181   assert(LoVT.getVectorMinNumElements() + HiVT.getVectorMinNumElements() <=
10182              N.getValueType().getVectorMinNumElements() &&
10183          "More vector elements requested than available!");
10184   SDValue Lo, Hi;
10185   Lo =
10186       getNode(ISD::EXTRACT_SUBVECTOR, DL, LoVT, N, getVectorIdxConstant(0, DL));
10187   // For scalable vectors it is safe to use LoVT.getVectorMinNumElements()
10188   // (rather than having to use ElementCount), because EXTRACT_SUBVECTOR scales
10189   // IDX with the runtime scaling factor of the result vector type. For
10190   // fixed-width result vectors, that runtime scaling factor is 1.
10191   Hi = getNode(ISD::EXTRACT_SUBVECTOR, DL, HiVT, N,
10192                getVectorIdxConstant(LoVT.getVectorMinNumElements(), DL));
10193   return std::make_pair(Lo, Hi);
10194 }
10195 
10196 /// Widen the vector up to the next power of two using INSERT_SUBVECTOR.
10197 SDValue SelectionDAG::WidenVector(const SDValue &N, const SDLoc &DL) {
10198   EVT VT = N.getValueType();
10199   EVT WideVT = EVT::getVectorVT(*getContext(), VT.getVectorElementType(),
10200                                 NextPowerOf2(VT.getVectorNumElements()));
10201   return getNode(ISD::INSERT_SUBVECTOR, DL, WideVT, getUNDEF(WideVT), N,
10202                  getVectorIdxConstant(0, DL));
10203 }
10204 
10205 void SelectionDAG::ExtractVectorElements(SDValue Op,
10206                                          SmallVectorImpl<SDValue> &Args,
10207                                          unsigned Start, unsigned Count,
10208                                          EVT EltVT) {
10209   EVT VT = Op.getValueType();
10210   if (Count == 0)
10211     Count = VT.getVectorNumElements();
10212   if (EltVT == EVT())
10213     EltVT = VT.getVectorElementType();
10214   SDLoc SL(Op);
10215   for (unsigned i = Start, e = Start + Count; i != e; ++i) {
10216     Args.push_back(getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Op,
10217                            getVectorIdxConstant(i, SL)));
10218   }
10219 }
10220 
10221 // getAddressSpace - Return the address space this GlobalAddress belongs to.
10222 unsigned GlobalAddressSDNode::getAddressSpace() const {
10223   return getGlobal()->getType()->getAddressSpace();
10224 }
10225 
10226 Type *ConstantPoolSDNode::getType() const {
10227   if (isMachineConstantPoolEntry())
10228     return Val.MachineCPVal->getType();
10229   return Val.ConstVal->getType();
10230 }
10231 
10232 bool BuildVectorSDNode::isConstantSplat(APInt &SplatValue, APInt &SplatUndef,
10233                                         unsigned &SplatBitSize,
10234                                         bool &HasAnyUndefs,
10235                                         unsigned MinSplatBits,
10236                                         bool IsBigEndian) const {
10237   EVT VT = getValueType(0);
10238   assert(VT.isVector() && "Expected a vector type");
10239   unsigned VecWidth = VT.getSizeInBits();
10240   if (MinSplatBits > VecWidth)
10241     return false;
10242 
10243   // FIXME: The widths are based on this node's type, but build vectors can
10244   // truncate their operands.
10245   SplatValue = APInt(VecWidth, 0);
10246   SplatUndef = APInt(VecWidth, 0);
10247 
10248   // Get the bits. Bits with undefined values (when the corresponding element
10249   // of the vector is an ISD::UNDEF value) are set in SplatUndef and cleared
10250   // in SplatValue. If any of the values are not constant, give up and return
10251   // false.
10252   unsigned int NumOps = getNumOperands();
10253   assert(NumOps > 0 && "isConstantSplat has 0-size build vector");
10254   unsigned EltWidth = VT.getScalarSizeInBits();
10255 
10256   for (unsigned j = 0; j < NumOps; ++j) {
10257     unsigned i = IsBigEndian ? NumOps - 1 - j : j;
10258     SDValue OpVal = getOperand(i);
10259     unsigned BitPos = j * EltWidth;
10260 
10261     if (OpVal.isUndef())
10262       SplatUndef.setBits(BitPos, BitPos + EltWidth);
10263     else if (auto *CN = dyn_cast<ConstantSDNode>(OpVal))
10264       SplatValue.insertBits(CN->getAPIntValue().zextOrTrunc(EltWidth), BitPos);
10265     else if (auto *CN = dyn_cast<ConstantFPSDNode>(OpVal))
10266       SplatValue.insertBits(CN->getValueAPF().bitcastToAPInt(), BitPos);
10267     else
10268       return false;
10269   }
10270 
10271   // The build_vector is all constants or undefs. Find the smallest element
10272   // size that splats the vector.
10273   HasAnyUndefs = (SplatUndef != 0);
10274 
10275   // FIXME: This does not work for vectors with elements less than 8 bits.
10276   while (VecWidth > 8) {
10277     unsigned HalfSize = VecWidth / 2;
10278     APInt HighValue = SplatValue.extractBits(HalfSize, HalfSize);
10279     APInt LowValue = SplatValue.extractBits(HalfSize, 0);
10280     APInt HighUndef = SplatUndef.extractBits(HalfSize, HalfSize);
10281     APInt LowUndef = SplatUndef.extractBits(HalfSize, 0);
10282 
10283     // If the two halves do not match (ignoring undef bits), stop here.
10284     if ((HighValue & ~LowUndef) != (LowValue & ~HighUndef) ||
10285         MinSplatBits > HalfSize)
10286       break;
10287 
10288     SplatValue = HighValue | LowValue;
10289     SplatUndef = HighUndef & LowUndef;
10290 
10291     VecWidth = HalfSize;
10292   }
10293 
10294   SplatBitSize = VecWidth;
10295   return true;
10296 }
10297 
10298 SDValue BuildVectorSDNode::getSplatValue(const APInt &DemandedElts,
10299                                          BitVector *UndefElements) const {
10300   unsigned NumOps = getNumOperands();
10301   if (UndefElements) {
10302     UndefElements->clear();
10303     UndefElements->resize(NumOps);
10304   }
10305   assert(NumOps == DemandedElts.getBitWidth() && "Unexpected vector size");
10306   if (!DemandedElts)
10307     return SDValue();
10308   SDValue Splatted;
10309   for (unsigned i = 0; i != NumOps; ++i) {
10310     if (!DemandedElts[i])
10311       continue;
10312     SDValue Op = getOperand(i);
10313     if (Op.isUndef()) {
10314       if (UndefElements)
10315         (*UndefElements)[i] = true;
10316     } else if (!Splatted) {
10317       Splatted = Op;
10318     } else if (Splatted != Op) {
10319       return SDValue();
10320     }
10321   }
10322 
10323   if (!Splatted) {
10324     unsigned FirstDemandedIdx = DemandedElts.countTrailingZeros();
10325     assert(getOperand(FirstDemandedIdx).isUndef() &&
10326            "Can only have a splat without a constant for all undefs.");
10327     return getOperand(FirstDemandedIdx);
10328   }
10329 
10330   return Splatted;
10331 }
10332 
10333 SDValue BuildVectorSDNode::getSplatValue(BitVector *UndefElements) const {
10334   APInt DemandedElts = APInt::getAllOnesValue(getNumOperands());
10335   return getSplatValue(DemandedElts, UndefElements);
10336 }
10337 
10338 bool BuildVectorSDNode::getRepeatedSequence(const APInt &DemandedElts,
10339                                             SmallVectorImpl<SDValue> &Sequence,
10340                                             BitVector *UndefElements) const {
10341   unsigned NumOps = getNumOperands();
10342   Sequence.clear();
10343   if (UndefElements) {
10344     UndefElements->clear();
10345     UndefElements->resize(NumOps);
10346   }
10347   assert(NumOps == DemandedElts.getBitWidth() && "Unexpected vector size");
10348   if (!DemandedElts || NumOps < 2 || !isPowerOf2_32(NumOps))
10349     return false;
10350 
10351   // Set the undefs even if we don't find a sequence (like getSplatValue).
10352   if (UndefElements)
10353     for (unsigned I = 0; I != NumOps; ++I)
10354       if (DemandedElts[I] && getOperand(I).isUndef())
10355         (*UndefElements)[I] = true;
10356 
10357   // Iteratively widen the sequence length looking for repetitions.
10358   for (unsigned SeqLen = 1; SeqLen < NumOps; SeqLen *= 2) {
10359     Sequence.append(SeqLen, SDValue());
10360     for (unsigned I = 0; I != NumOps; ++I) {
10361       if (!DemandedElts[I])
10362         continue;
10363       SDValue &SeqOp = Sequence[I % SeqLen];
10364       SDValue Op = getOperand(I);
10365       if (Op.isUndef()) {
10366         if (!SeqOp)
10367           SeqOp = Op;
10368         continue;
10369       }
10370       if (SeqOp && !SeqOp.isUndef() && SeqOp != Op) {
10371         Sequence.clear();
10372         break;
10373       }
10374       SeqOp = Op;
10375     }
10376     if (!Sequence.empty())
10377       return true;
10378   }
10379 
10380   assert(Sequence.empty() && "Failed to empty non-repeating sequence pattern");
10381   return false;
10382 }
10383 
10384 bool BuildVectorSDNode::getRepeatedSequence(SmallVectorImpl<SDValue> &Sequence,
10385                                             BitVector *UndefElements) const {
10386   APInt DemandedElts = APInt::getAllOnesValue(getNumOperands());
10387   return getRepeatedSequence(DemandedElts, Sequence, UndefElements);
10388 }
10389 
10390 ConstantSDNode *
10391 BuildVectorSDNode::getConstantSplatNode(const APInt &DemandedElts,
10392                                         BitVector *UndefElements) const {
10393   return dyn_cast_or_null<ConstantSDNode>(
10394       getSplatValue(DemandedElts, UndefElements));
10395 }
10396 
10397 ConstantSDNode *
10398 BuildVectorSDNode::getConstantSplatNode(BitVector *UndefElements) const {
10399   return dyn_cast_or_null<ConstantSDNode>(getSplatValue(UndefElements));
10400 }
10401 
10402 ConstantFPSDNode *
10403 BuildVectorSDNode::getConstantFPSplatNode(const APInt &DemandedElts,
10404                                           BitVector *UndefElements) const {
10405   return dyn_cast_or_null<ConstantFPSDNode>(
10406       getSplatValue(DemandedElts, UndefElements));
10407 }
10408 
10409 ConstantFPSDNode *
10410 BuildVectorSDNode::getConstantFPSplatNode(BitVector *UndefElements) const {
10411   return dyn_cast_or_null<ConstantFPSDNode>(getSplatValue(UndefElements));
10412 }
10413 
10414 int32_t
10415 BuildVectorSDNode::getConstantFPSplatPow2ToLog2Int(BitVector *UndefElements,
10416                                                    uint32_t BitWidth) const {
10417   if (ConstantFPSDNode *CN =
10418           dyn_cast_or_null<ConstantFPSDNode>(getSplatValue(UndefElements))) {
10419     bool IsExact;
10420     APSInt IntVal(BitWidth);
10421     const APFloat &APF = CN->getValueAPF();
10422     if (APF.convertToInteger(IntVal, APFloat::rmTowardZero, &IsExact) !=
10423             APFloat::opOK ||
10424         !IsExact)
10425       return -1;
10426 
10427     return IntVal.exactLogBase2();
10428   }
10429   return -1;
10430 }
10431 
10432 bool BuildVectorSDNode::isConstant() const {
10433   for (const SDValue &Op : op_values()) {
10434     unsigned Opc = Op.getOpcode();
10435     if (Opc != ISD::UNDEF && Opc != ISD::Constant && Opc != ISD::ConstantFP)
10436       return false;
10437   }
10438   return true;
10439 }
10440 
10441 bool ShuffleVectorSDNode::isSplatMask(const int *Mask, EVT VT) {
10442   // Find the first non-undef value in the shuffle mask.
10443   unsigned i, e;
10444   for (i = 0, e = VT.getVectorNumElements(); i != e && Mask[i] < 0; ++i)
10445     /* search */;
10446 
10447   // If all elements are undefined, this shuffle can be considered a splat
10448   // (although it should eventually get simplified away completely).
10449   if (i == e)
10450     return true;
10451 
10452   // Make sure all remaining elements are either undef or the same as the first
10453   // non-undef value.
10454   for (int Idx = Mask[i]; i != e; ++i)
10455     if (Mask[i] >= 0 && Mask[i] != Idx)
10456       return false;
10457   return true;
10458 }
10459 
10460 // Returns the SDNode if it is a constant integer BuildVector
10461 // or constant integer.
10462 SDNode *SelectionDAG::isConstantIntBuildVectorOrConstantInt(SDValue N) const {
10463   if (isa<ConstantSDNode>(N))
10464     return N.getNode();
10465   if (ISD::isBuildVectorOfConstantSDNodes(N.getNode()))
10466     return N.getNode();
10467   // Treat a GlobalAddress supporting constant offset folding as a
10468   // constant integer.
10469   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N))
10470     if (GA->getOpcode() == ISD::GlobalAddress &&
10471         TLI->isOffsetFoldingLegal(GA))
10472       return GA;
10473   if ((N.getOpcode() == ISD::SPLAT_VECTOR) &&
10474       isa<ConstantSDNode>(N.getOperand(0)))
10475     return N.getNode();
10476   return nullptr;
10477 }
10478 
10479 // Returns the SDNode if it is a constant float BuildVector
10480 // or constant float.
10481 SDNode *SelectionDAG::isConstantFPBuildVectorOrConstantFP(SDValue N) const {
10482   if (isa<ConstantFPSDNode>(N))
10483     return N.getNode();
10484 
10485   if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode()))
10486     return N.getNode();
10487 
10488   return nullptr;
10489 }
10490 
10491 void SelectionDAG::createOperands(SDNode *Node, ArrayRef<SDValue> Vals) {
10492   assert(!Node->OperandList && "Node already has operands");
10493   assert(SDNode::getMaxNumOperands() >= Vals.size() &&
10494          "too many operands to fit into SDNode");
10495   SDUse *Ops = OperandRecycler.allocate(
10496       ArrayRecycler<SDUse>::Capacity::get(Vals.size()), OperandAllocator);
10497 
10498   bool IsDivergent = false;
10499   for (unsigned I = 0; I != Vals.size(); ++I) {
10500     Ops[I].setUser(Node);
10501     Ops[I].setInitial(Vals[I]);
10502     if (Ops[I].Val.getValueType() != MVT::Other) // Skip Chain. It does not carry divergence.
10503       IsDivergent |= Ops[I].getNode()->isDivergent();
10504   }
10505   Node->NumOperands = Vals.size();
10506   Node->OperandList = Ops;
10507   if (!TLI->isSDNodeAlwaysUniform(Node)) {
10508     IsDivergent |= TLI->isSDNodeSourceOfDivergence(Node, FLI, DA);
10509     Node->SDNodeBits.IsDivergent = IsDivergent;
10510   }
10511   checkForCycles(Node);
10512 }
10513 
10514 SDValue SelectionDAG::getTokenFactor(const SDLoc &DL,
10515                                      SmallVectorImpl<SDValue> &Vals) {
10516   size_t Limit = SDNode::getMaxNumOperands();
10517   while (Vals.size() > Limit) {
10518     unsigned SliceIdx = Vals.size() - Limit;
10519     auto ExtractedTFs = ArrayRef<SDValue>(Vals).slice(SliceIdx, Limit);
10520     SDValue NewTF = getNode(ISD::TokenFactor, DL, MVT::Other, ExtractedTFs);
10521     Vals.erase(Vals.begin() + SliceIdx, Vals.end());
10522     Vals.emplace_back(NewTF);
10523   }
10524   return getNode(ISD::TokenFactor, DL, MVT::Other, Vals);
10525 }
10526 
10527 SDValue SelectionDAG::getNeutralElement(unsigned Opcode, const SDLoc &DL,
10528                                         EVT VT, SDNodeFlags Flags) {
10529   switch (Opcode) {
10530   default:
10531     return SDValue();
10532   case ISD::ADD:
10533   case ISD::OR:
10534   case ISD::XOR:
10535   case ISD::UMAX:
10536     return getConstant(0, DL, VT);
10537   case ISD::MUL:
10538     return getConstant(1, DL, VT);
10539   case ISD::AND:
10540   case ISD::UMIN:
10541     return getAllOnesConstant(DL, VT);
10542   case ISD::SMAX:
10543     return getConstant(APInt::getSignedMinValue(VT.getSizeInBits()), DL, VT);
10544   case ISD::SMIN:
10545     return getConstant(APInt::getSignedMaxValue(VT.getSizeInBits()), DL, VT);
10546   case ISD::FADD:
10547     return getConstantFP(-0.0, DL, VT);
10548   case ISD::FMUL:
10549     return getConstantFP(1.0, DL, VT);
10550   case ISD::FMINNUM:
10551   case ISD::FMAXNUM: {
10552     // Neutral element for fminnum is NaN, Inf or FLT_MAX, depending on FMF.
10553     const fltSemantics &Semantics = EVTToAPFloatSemantics(VT);
10554     APFloat NeutralAF = !Flags.hasNoNaNs() ? APFloat::getQNaN(Semantics) :
10555                         !Flags.hasNoInfs() ? APFloat::getInf(Semantics) :
10556                         APFloat::getLargest(Semantics);
10557     if (Opcode == ISD::FMAXNUM)
10558       NeutralAF.changeSign();
10559 
10560     return getConstantFP(NeutralAF, DL, VT);
10561   }
10562   }
10563 }
10564 
10565 #ifndef NDEBUG
10566 static void checkForCyclesHelper(const SDNode *N,
10567                                  SmallPtrSetImpl<const SDNode*> &Visited,
10568                                  SmallPtrSetImpl<const SDNode*> &Checked,
10569                                  const llvm::SelectionDAG *DAG) {
10570   // If this node has already been checked, don't check it again.
10571   if (Checked.count(N))
10572     return;
10573 
10574   // If a node has already been visited on this depth-first walk, reject it as
10575   // a cycle.
10576   if (!Visited.insert(N).second) {
10577     errs() << "Detected cycle in SelectionDAG\n";
10578     dbgs() << "Offending node:\n";
10579     N->dumprFull(DAG); dbgs() << "\n";
10580     abort();
10581   }
10582 
10583   for (const SDValue &Op : N->op_values())
10584     checkForCyclesHelper(Op.getNode(), Visited, Checked, DAG);
10585 
10586   Checked.insert(N);
10587   Visited.erase(N);
10588 }
10589 #endif
10590 
10591 void llvm::checkForCycles(const llvm::SDNode *N,
10592                           const llvm::SelectionDAG *DAG,
10593                           bool force) {
10594 #ifndef NDEBUG
10595   bool check = force;
10596 #ifdef EXPENSIVE_CHECKS
10597   check = true;
10598 #endif  // EXPENSIVE_CHECKS
10599   if (check) {
10600     assert(N && "Checking nonexistent SDNode");
10601     SmallPtrSet<const SDNode*, 32> visited;
10602     SmallPtrSet<const SDNode*, 32> checked;
10603     checkForCyclesHelper(N, visited, checked, DAG);
10604   }
10605 #endif  // !NDEBUG
10606 }
10607 
10608 void llvm::checkForCycles(const llvm::SelectionDAG *DAG, bool force) {
10609   checkForCycles(DAG->getRoot().getNode(), DAG, force);
10610 }
10611