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   }
150 
151   auto *BV = dyn_cast<BuildVectorSDNode>(N);
152   if (!BV)
153     return false;
154 
155   APInt SplatUndef;
156   unsigned SplatBitSize;
157   bool HasUndefs;
158   unsigned EltSize = N->getValueType(0).getVectorElementType().getSizeInBits();
159   return BV->isConstantSplat(SplatVal, SplatUndef, SplatBitSize, HasUndefs,
160                              EltSize) &&
161          EltSize == SplatBitSize;
162 }
163 
164 // FIXME: AllOnes and AllZeros duplicate a lot of code. Could these be
165 // specializations of the more general isConstantSplatVector()?
166 
167 bool ISD::isConstantSplatVectorAllOnes(const SDNode *N, bool BuildVectorOnly) {
168   // Look through a bit convert.
169   while (N->getOpcode() == ISD::BITCAST)
170     N = N->getOperand(0).getNode();
171 
172   if (!BuildVectorOnly && N->getOpcode() == ISD::SPLAT_VECTOR) {
173     APInt SplatVal;
174     return isConstantSplatVector(N, SplatVal) && SplatVal.isAllOnesValue();
175   }
176 
177   if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
178 
179   unsigned i = 0, e = N->getNumOperands();
180 
181   // Skip over all of the undef values.
182   while (i != e && N->getOperand(i).isUndef())
183     ++i;
184 
185   // Do not accept an all-undef vector.
186   if (i == e) return false;
187 
188   // Do not accept build_vectors that aren't all constants or which have non-~0
189   // elements. We have to be a bit careful here, as the type of the constant
190   // may not be the same as the type of the vector elements due to type
191   // legalization (the elements are promoted to a legal type for the target and
192   // a vector of a type may be legal when the base element type is not).
193   // We only want to check enough bits to cover the vector elements, because
194   // we care if the resultant vector is all ones, not whether the individual
195   // constants are.
196   SDValue NotZero = N->getOperand(i);
197   unsigned EltSize = N->getValueType(0).getScalarSizeInBits();
198   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(NotZero)) {
199     if (CN->getAPIntValue().countTrailingOnes() < EltSize)
200       return false;
201   } else if (ConstantFPSDNode *CFPN = dyn_cast<ConstantFPSDNode>(NotZero)) {
202     if (CFPN->getValueAPF().bitcastToAPInt().countTrailingOnes() < EltSize)
203       return false;
204   } else
205     return false;
206 
207   // Okay, we have at least one ~0 value, check to see if the rest match or are
208   // undefs. Even with the above element type twiddling, this should be OK, as
209   // the same type legalization should have applied to all the elements.
210   for (++i; i != e; ++i)
211     if (N->getOperand(i) != NotZero && !N->getOperand(i).isUndef())
212       return false;
213   return true;
214 }
215 
216 bool ISD::isConstantSplatVectorAllZeros(const SDNode *N, bool BuildVectorOnly) {
217   // Look through a bit convert.
218   while (N->getOpcode() == ISD::BITCAST)
219     N = N->getOperand(0).getNode();
220 
221   if (!BuildVectorOnly && N->getOpcode() == ISD::SPLAT_VECTOR) {
222     APInt SplatVal;
223     return isConstantSplatVector(N, SplatVal) && SplatVal.isNullValue();
224   }
225 
226   if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
227 
228   bool IsAllUndef = true;
229   for (const SDValue &Op : N->op_values()) {
230     if (Op.isUndef())
231       continue;
232     IsAllUndef = false;
233     // Do not accept build_vectors that aren't all constants or which have non-0
234     // elements. We have to be a bit careful here, as the type of the constant
235     // may not be the same as the type of the vector elements due to type
236     // legalization (the elements are promoted to a legal type for the target
237     // and a vector of a type may be legal when the base element type is not).
238     // We only want to check enough bits to cover the vector elements, because
239     // we care if the resultant vector is all zeros, not whether the individual
240     // constants are.
241     unsigned EltSize = N->getValueType(0).getScalarSizeInBits();
242     if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Op)) {
243       if (CN->getAPIntValue().countTrailingZeros() < EltSize)
244         return false;
245     } else if (ConstantFPSDNode *CFPN = dyn_cast<ConstantFPSDNode>(Op)) {
246       if (CFPN->getValueAPF().bitcastToAPInt().countTrailingZeros() < EltSize)
247         return false;
248     } else
249       return false;
250   }
251 
252   // Do not accept an all-undef vector.
253   if (IsAllUndef)
254     return false;
255   return true;
256 }
257 
258 bool ISD::isBuildVectorAllOnes(const SDNode *N) {
259   return isConstantSplatVectorAllOnes(N, /*BuildVectorOnly*/ true);
260 }
261 
262 bool ISD::isBuildVectorAllZeros(const SDNode *N) {
263   return isConstantSplatVectorAllZeros(N, /*BuildVectorOnly*/ true);
264 }
265 
266 bool ISD::isBuildVectorOfConstantSDNodes(const SDNode *N) {
267   if (N->getOpcode() != ISD::BUILD_VECTOR)
268     return false;
269 
270   for (const SDValue &Op : N->op_values()) {
271     if (Op.isUndef())
272       continue;
273     if (!isa<ConstantSDNode>(Op))
274       return false;
275   }
276   return true;
277 }
278 
279 bool ISD::isBuildVectorOfConstantFPSDNodes(const SDNode *N) {
280   if (N->getOpcode() != ISD::BUILD_VECTOR)
281     return false;
282 
283   for (const SDValue &Op : N->op_values()) {
284     if (Op.isUndef())
285       continue;
286     if (!isa<ConstantFPSDNode>(Op))
287       return false;
288   }
289   return true;
290 }
291 
292 bool ISD::allOperandsUndef(const SDNode *N) {
293   // Return false if the node has no operands.
294   // This is "logically inconsistent" with the definition of "all" but
295   // is probably the desired behavior.
296   if (N->getNumOperands() == 0)
297     return false;
298   return all_of(N->op_values(), [](SDValue Op) { return Op.isUndef(); });
299 }
300 
301 bool ISD::matchUnaryPredicate(SDValue Op,
302                               std::function<bool(ConstantSDNode *)> Match,
303                               bool AllowUndefs) {
304   // FIXME: Add support for scalar UNDEF cases?
305   if (auto *Cst = dyn_cast<ConstantSDNode>(Op))
306     return Match(Cst);
307 
308   // FIXME: Add support for vector UNDEF cases?
309   if (ISD::BUILD_VECTOR != Op.getOpcode() &&
310       ISD::SPLAT_VECTOR != Op.getOpcode())
311     return false;
312 
313   EVT SVT = Op.getValueType().getScalarType();
314   for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
315     if (AllowUndefs && Op.getOperand(i).isUndef()) {
316       if (!Match(nullptr))
317         return false;
318       continue;
319     }
320 
321     auto *Cst = dyn_cast<ConstantSDNode>(Op.getOperand(i));
322     if (!Cst || Cst->getValueType(0) != SVT || !Match(Cst))
323       return false;
324   }
325   return true;
326 }
327 
328 bool ISD::matchBinaryPredicate(
329     SDValue LHS, SDValue RHS,
330     std::function<bool(ConstantSDNode *, ConstantSDNode *)> Match,
331     bool AllowUndefs, bool AllowTypeMismatch) {
332   if (!AllowTypeMismatch && LHS.getValueType() != RHS.getValueType())
333     return false;
334 
335   // TODO: Add support for scalar UNDEF cases?
336   if (auto *LHSCst = dyn_cast<ConstantSDNode>(LHS))
337     if (auto *RHSCst = dyn_cast<ConstantSDNode>(RHS))
338       return Match(LHSCst, RHSCst);
339 
340   // TODO: Add support for vector UNDEF cases?
341   if (ISD::BUILD_VECTOR != LHS.getOpcode() ||
342       ISD::BUILD_VECTOR != RHS.getOpcode())
343     return false;
344 
345   EVT SVT = LHS.getValueType().getScalarType();
346   for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
347     SDValue LHSOp = LHS.getOperand(i);
348     SDValue RHSOp = RHS.getOperand(i);
349     bool LHSUndef = AllowUndefs && LHSOp.isUndef();
350     bool RHSUndef = AllowUndefs && RHSOp.isUndef();
351     auto *LHSCst = dyn_cast<ConstantSDNode>(LHSOp);
352     auto *RHSCst = dyn_cast<ConstantSDNode>(RHSOp);
353     if ((!LHSCst && !LHSUndef) || (!RHSCst && !RHSUndef))
354       return false;
355     if (!AllowTypeMismatch && (LHSOp.getValueType() != SVT ||
356                                LHSOp.getValueType() != RHSOp.getValueType()))
357       return false;
358     if (!Match(LHSCst, RHSCst))
359       return false;
360   }
361   return true;
362 }
363 
364 ISD::NodeType ISD::getVecReduceBaseOpcode(unsigned VecReduceOpcode) {
365   switch (VecReduceOpcode) {
366   default:
367     llvm_unreachable("Expected VECREDUCE opcode");
368   case ISD::VECREDUCE_FADD:
369   case ISD::VECREDUCE_SEQ_FADD:
370     return ISD::FADD;
371   case ISD::VECREDUCE_FMUL:
372   case ISD::VECREDUCE_SEQ_FMUL:
373     return ISD::FMUL;
374   case ISD::VECREDUCE_ADD:
375     return ISD::ADD;
376   case ISD::VECREDUCE_MUL:
377     return ISD::MUL;
378   case ISD::VECREDUCE_AND:
379     return ISD::AND;
380   case ISD::VECREDUCE_OR:
381     return ISD::OR;
382   case ISD::VECREDUCE_XOR:
383     return ISD::XOR;
384   case ISD::VECREDUCE_SMAX:
385     return ISD::SMAX;
386   case ISD::VECREDUCE_SMIN:
387     return ISD::SMIN;
388   case ISD::VECREDUCE_UMAX:
389     return ISD::UMAX;
390   case ISD::VECREDUCE_UMIN:
391     return ISD::UMIN;
392   case ISD::VECREDUCE_FMAX:
393     return ISD::FMAXNUM;
394   case ISD::VECREDUCE_FMIN:
395     return ISD::FMINNUM;
396   }
397 }
398 
399 bool ISD::isVPOpcode(unsigned Opcode) {
400   switch (Opcode) {
401   default:
402     return false;
403 #define BEGIN_REGISTER_VP_SDNODE(SDOPC, ...)                                   \
404   case ISD::SDOPC:                                                             \
405     return true;
406 #include "llvm/IR/VPIntrinsics.def"
407   }
408 }
409 
410 /// The operand position of the vector mask.
411 Optional<unsigned> ISD::getVPMaskIdx(unsigned Opcode) {
412   switch (Opcode) {
413   default:
414     return None;
415 #define BEGIN_REGISTER_VP_SDNODE(SDOPC, LEGALPOS, TDNAME, MASKPOS, ...)        \
416   case ISD::SDOPC:                                                             \
417     return MASKPOS;
418 #include "llvm/IR/VPIntrinsics.def"
419   }
420 }
421 
422 /// The operand position of the explicit vector length parameter.
423 Optional<unsigned> ISD::getVPExplicitVectorLengthIdx(unsigned Opcode) {
424   switch (Opcode) {
425   default:
426     return None;
427 #define BEGIN_REGISTER_VP_SDNODE(SDOPC, LEGALPOS, TDNAME, MASKPOS, EVLPOS)     \
428   case ISD::SDOPC:                                                             \
429     return EVLPOS;
430 #include "llvm/IR/VPIntrinsics.def"
431   }
432 }
433 
434 ISD::NodeType ISD::getExtForLoadExtType(bool IsFP, ISD::LoadExtType ExtType) {
435   switch (ExtType) {
436   case ISD::EXTLOAD:
437     return IsFP ? ISD::FP_EXTEND : ISD::ANY_EXTEND;
438   case ISD::SEXTLOAD:
439     return ISD::SIGN_EXTEND;
440   case ISD::ZEXTLOAD:
441     return ISD::ZERO_EXTEND;
442   default:
443     break;
444   }
445 
446   llvm_unreachable("Invalid LoadExtType");
447 }
448 
449 ISD::CondCode ISD::getSetCCSwappedOperands(ISD::CondCode Operation) {
450   // To perform this operation, we just need to swap the L and G bits of the
451   // operation.
452   unsigned OldL = (Operation >> 2) & 1;
453   unsigned OldG = (Operation >> 1) & 1;
454   return ISD::CondCode((Operation & ~6) |  // Keep the N, U, E bits
455                        (OldL << 1) |       // New G bit
456                        (OldG << 2));       // New L bit.
457 }
458 
459 static ISD::CondCode getSetCCInverseImpl(ISD::CondCode Op, bool isIntegerLike) {
460   unsigned Operation = Op;
461   if (isIntegerLike)
462     Operation ^= 7;   // Flip L, G, E bits, but not U.
463   else
464     Operation ^= 15;  // Flip all of the condition bits.
465 
466   if (Operation > ISD::SETTRUE2)
467     Operation &= ~8;  // Don't let N and U bits get set.
468 
469   return ISD::CondCode(Operation);
470 }
471 
472 ISD::CondCode ISD::getSetCCInverse(ISD::CondCode Op, EVT Type) {
473   return getSetCCInverseImpl(Op, Type.isInteger());
474 }
475 
476 ISD::CondCode ISD::GlobalISel::getSetCCInverse(ISD::CondCode Op,
477                                                bool isIntegerLike) {
478   return getSetCCInverseImpl(Op, isIntegerLike);
479 }
480 
481 /// For an integer comparison, return 1 if the comparison is a signed operation
482 /// and 2 if the result is an unsigned comparison. Return zero if the operation
483 /// does not depend on the sign of the input (setne and seteq).
484 static int isSignedOp(ISD::CondCode Opcode) {
485   switch (Opcode) {
486   default: llvm_unreachable("Illegal integer setcc operation!");
487   case ISD::SETEQ:
488   case ISD::SETNE: return 0;
489   case ISD::SETLT:
490   case ISD::SETLE:
491   case ISD::SETGT:
492   case ISD::SETGE: return 1;
493   case ISD::SETULT:
494   case ISD::SETULE:
495   case ISD::SETUGT:
496   case ISD::SETUGE: return 2;
497   }
498 }
499 
500 ISD::CondCode ISD::getSetCCOrOperation(ISD::CondCode Op1, ISD::CondCode Op2,
501                                        EVT Type) {
502   bool IsInteger = Type.isInteger();
503   if (IsInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
504     // Cannot fold a signed integer setcc with an unsigned integer setcc.
505     return ISD::SETCC_INVALID;
506 
507   unsigned Op = Op1 | Op2;  // Combine all of the condition bits.
508 
509   // If the N and U bits get set, then the resultant comparison DOES suddenly
510   // care about orderedness, and it is true when ordered.
511   if (Op > ISD::SETTRUE2)
512     Op &= ~16;     // Clear the U bit if the N bit is set.
513 
514   // Canonicalize illegal integer setcc's.
515   if (IsInteger && Op == ISD::SETUNE)  // e.g. SETUGT | SETULT
516     Op = ISD::SETNE;
517 
518   return ISD::CondCode(Op);
519 }
520 
521 ISD::CondCode ISD::getSetCCAndOperation(ISD::CondCode Op1, ISD::CondCode Op2,
522                                         EVT Type) {
523   bool IsInteger = Type.isInteger();
524   if (IsInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
525     // Cannot fold a signed setcc with an unsigned setcc.
526     return ISD::SETCC_INVALID;
527 
528   // Combine all of the condition bits.
529   ISD::CondCode Result = ISD::CondCode(Op1 & Op2);
530 
531   // Canonicalize illegal integer setcc's.
532   if (IsInteger) {
533     switch (Result) {
534     default: break;
535     case ISD::SETUO : Result = ISD::SETFALSE; break;  // SETUGT & SETULT
536     case ISD::SETOEQ:                                 // SETEQ  & SETU[LG]E
537     case ISD::SETUEQ: Result = ISD::SETEQ   ; break;  // SETUGE & SETULE
538     case ISD::SETOLT: Result = ISD::SETULT  ; break;  // SETULT & SETNE
539     case ISD::SETOGT: Result = ISD::SETUGT  ; break;  // SETUGT & SETNE
540     }
541   }
542 
543   return Result;
544 }
545 
546 //===----------------------------------------------------------------------===//
547 //                           SDNode Profile Support
548 //===----------------------------------------------------------------------===//
549 
550 /// AddNodeIDOpcode - Add the node opcode to the NodeID data.
551 static void AddNodeIDOpcode(FoldingSetNodeID &ID, unsigned OpC)  {
552   ID.AddInteger(OpC);
553 }
554 
555 /// AddNodeIDValueTypes - Value type lists are intern'd so we can represent them
556 /// solely with their pointer.
557 static void AddNodeIDValueTypes(FoldingSetNodeID &ID, SDVTList VTList) {
558   ID.AddPointer(VTList.VTs);
559 }
560 
561 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data.
562 static void AddNodeIDOperands(FoldingSetNodeID &ID,
563                               ArrayRef<SDValue> Ops) {
564   for (auto& Op : Ops) {
565     ID.AddPointer(Op.getNode());
566     ID.AddInteger(Op.getResNo());
567   }
568 }
569 
570 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data.
571 static void AddNodeIDOperands(FoldingSetNodeID &ID,
572                               ArrayRef<SDUse> Ops) {
573   for (auto& Op : Ops) {
574     ID.AddPointer(Op.getNode());
575     ID.AddInteger(Op.getResNo());
576   }
577 }
578 
579 static void AddNodeIDNode(FoldingSetNodeID &ID, unsigned short OpC,
580                           SDVTList VTList, ArrayRef<SDValue> OpList) {
581   AddNodeIDOpcode(ID, OpC);
582   AddNodeIDValueTypes(ID, VTList);
583   AddNodeIDOperands(ID, OpList);
584 }
585 
586 /// If this is an SDNode with special info, add this info to the NodeID data.
587 static void AddNodeIDCustom(FoldingSetNodeID &ID, const SDNode *N) {
588   switch (N->getOpcode()) {
589   case ISD::TargetExternalSymbol:
590   case ISD::ExternalSymbol:
591   case ISD::MCSymbol:
592     llvm_unreachable("Should only be used on nodes with operands");
593   default: break;  // Normal nodes don't need extra info.
594   case ISD::TargetConstant:
595   case ISD::Constant: {
596     const ConstantSDNode *C = cast<ConstantSDNode>(N);
597     ID.AddPointer(C->getConstantIntValue());
598     ID.AddBoolean(C->isOpaque());
599     break;
600   }
601   case ISD::TargetConstantFP:
602   case ISD::ConstantFP:
603     ID.AddPointer(cast<ConstantFPSDNode>(N)->getConstantFPValue());
604     break;
605   case ISD::TargetGlobalAddress:
606   case ISD::GlobalAddress:
607   case ISD::TargetGlobalTLSAddress:
608   case ISD::GlobalTLSAddress: {
609     const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(N);
610     ID.AddPointer(GA->getGlobal());
611     ID.AddInteger(GA->getOffset());
612     ID.AddInteger(GA->getTargetFlags());
613     break;
614   }
615   case ISD::BasicBlock:
616     ID.AddPointer(cast<BasicBlockSDNode>(N)->getBasicBlock());
617     break;
618   case ISD::Register:
619     ID.AddInteger(cast<RegisterSDNode>(N)->getReg());
620     break;
621   case ISD::RegisterMask:
622     ID.AddPointer(cast<RegisterMaskSDNode>(N)->getRegMask());
623     break;
624   case ISD::SRCVALUE:
625     ID.AddPointer(cast<SrcValueSDNode>(N)->getValue());
626     break;
627   case ISD::FrameIndex:
628   case ISD::TargetFrameIndex:
629     ID.AddInteger(cast<FrameIndexSDNode>(N)->getIndex());
630     break;
631   case ISD::LIFETIME_START:
632   case ISD::LIFETIME_END:
633     if (cast<LifetimeSDNode>(N)->hasOffset()) {
634       ID.AddInteger(cast<LifetimeSDNode>(N)->getSize());
635       ID.AddInteger(cast<LifetimeSDNode>(N)->getOffset());
636     }
637     break;
638   case ISD::PSEUDO_PROBE:
639     ID.AddInteger(cast<PseudoProbeSDNode>(N)->getGuid());
640     ID.AddInteger(cast<PseudoProbeSDNode>(N)->getIndex());
641     ID.AddInteger(cast<PseudoProbeSDNode>(N)->getAttributes());
642     break;
643   case ISD::JumpTable:
644   case ISD::TargetJumpTable:
645     ID.AddInteger(cast<JumpTableSDNode>(N)->getIndex());
646     ID.AddInteger(cast<JumpTableSDNode>(N)->getTargetFlags());
647     break;
648   case ISD::ConstantPool:
649   case ISD::TargetConstantPool: {
650     const ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(N);
651     ID.AddInteger(CP->getAlign().value());
652     ID.AddInteger(CP->getOffset());
653     if (CP->isMachineConstantPoolEntry())
654       CP->getMachineCPVal()->addSelectionDAGCSEId(ID);
655     else
656       ID.AddPointer(CP->getConstVal());
657     ID.AddInteger(CP->getTargetFlags());
658     break;
659   }
660   case ISD::TargetIndex: {
661     const TargetIndexSDNode *TI = cast<TargetIndexSDNode>(N);
662     ID.AddInteger(TI->getIndex());
663     ID.AddInteger(TI->getOffset());
664     ID.AddInteger(TI->getTargetFlags());
665     break;
666   }
667   case ISD::LOAD: {
668     const LoadSDNode *LD = cast<LoadSDNode>(N);
669     ID.AddInteger(LD->getMemoryVT().getRawBits());
670     ID.AddInteger(LD->getRawSubclassData());
671     ID.AddInteger(LD->getPointerInfo().getAddrSpace());
672     break;
673   }
674   case ISD::STORE: {
675     const StoreSDNode *ST = cast<StoreSDNode>(N);
676     ID.AddInteger(ST->getMemoryVT().getRawBits());
677     ID.AddInteger(ST->getRawSubclassData());
678     ID.AddInteger(ST->getPointerInfo().getAddrSpace());
679     break;
680   }
681   case ISD::MLOAD: {
682     const MaskedLoadSDNode *MLD = cast<MaskedLoadSDNode>(N);
683     ID.AddInteger(MLD->getMemoryVT().getRawBits());
684     ID.AddInteger(MLD->getRawSubclassData());
685     ID.AddInteger(MLD->getPointerInfo().getAddrSpace());
686     break;
687   }
688   case ISD::MSTORE: {
689     const MaskedStoreSDNode *MST = cast<MaskedStoreSDNode>(N);
690     ID.AddInteger(MST->getMemoryVT().getRawBits());
691     ID.AddInteger(MST->getRawSubclassData());
692     ID.AddInteger(MST->getPointerInfo().getAddrSpace());
693     break;
694   }
695   case ISD::MGATHER: {
696     const MaskedGatherSDNode *MG = cast<MaskedGatherSDNode>(N);
697     ID.AddInteger(MG->getMemoryVT().getRawBits());
698     ID.AddInteger(MG->getRawSubclassData());
699     ID.AddInteger(MG->getPointerInfo().getAddrSpace());
700     break;
701   }
702   case ISD::MSCATTER: {
703     const MaskedScatterSDNode *MS = cast<MaskedScatterSDNode>(N);
704     ID.AddInteger(MS->getMemoryVT().getRawBits());
705     ID.AddInteger(MS->getRawSubclassData());
706     ID.AddInteger(MS->getPointerInfo().getAddrSpace());
707     break;
708   }
709   case ISD::ATOMIC_CMP_SWAP:
710   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
711   case ISD::ATOMIC_SWAP:
712   case ISD::ATOMIC_LOAD_ADD:
713   case ISD::ATOMIC_LOAD_SUB:
714   case ISD::ATOMIC_LOAD_AND:
715   case ISD::ATOMIC_LOAD_CLR:
716   case ISD::ATOMIC_LOAD_OR:
717   case ISD::ATOMIC_LOAD_XOR:
718   case ISD::ATOMIC_LOAD_NAND:
719   case ISD::ATOMIC_LOAD_MIN:
720   case ISD::ATOMIC_LOAD_MAX:
721   case ISD::ATOMIC_LOAD_UMIN:
722   case ISD::ATOMIC_LOAD_UMAX:
723   case ISD::ATOMIC_LOAD:
724   case ISD::ATOMIC_STORE: {
725     const AtomicSDNode *AT = cast<AtomicSDNode>(N);
726     ID.AddInteger(AT->getMemoryVT().getRawBits());
727     ID.AddInteger(AT->getRawSubclassData());
728     ID.AddInteger(AT->getPointerInfo().getAddrSpace());
729     break;
730   }
731   case ISD::PREFETCH: {
732     const MemSDNode *PF = cast<MemSDNode>(N);
733     ID.AddInteger(PF->getPointerInfo().getAddrSpace());
734     break;
735   }
736   case ISD::VECTOR_SHUFFLE: {
737     const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
738     for (unsigned i = 0, e = N->getValueType(0).getVectorNumElements();
739          i != e; ++i)
740       ID.AddInteger(SVN->getMaskElt(i));
741     break;
742   }
743   case ISD::TargetBlockAddress:
744   case ISD::BlockAddress: {
745     const BlockAddressSDNode *BA = cast<BlockAddressSDNode>(N);
746     ID.AddPointer(BA->getBlockAddress());
747     ID.AddInteger(BA->getOffset());
748     ID.AddInteger(BA->getTargetFlags());
749     break;
750   }
751   } // end switch (N->getOpcode())
752 
753   // Target specific memory nodes could also have address spaces to check.
754   if (N->isTargetMemoryOpcode())
755     ID.AddInteger(cast<MemSDNode>(N)->getPointerInfo().getAddrSpace());
756 }
757 
758 /// AddNodeIDNode - Generic routine for adding a nodes info to the NodeID
759 /// data.
760 static void AddNodeIDNode(FoldingSetNodeID &ID, const SDNode *N) {
761   AddNodeIDOpcode(ID, N->getOpcode());
762   // Add the return value info.
763   AddNodeIDValueTypes(ID, N->getVTList());
764   // Add the operand info.
765   AddNodeIDOperands(ID, N->ops());
766 
767   // Handle SDNode leafs with special info.
768   AddNodeIDCustom(ID, N);
769 }
770 
771 //===----------------------------------------------------------------------===//
772 //                              SelectionDAG Class
773 //===----------------------------------------------------------------------===//
774 
775 /// doNotCSE - Return true if CSE should not be performed for this node.
776 static bool doNotCSE(SDNode *N) {
777   if (N->getValueType(0) == MVT::Glue)
778     return true; // Never CSE anything that produces a flag.
779 
780   switch (N->getOpcode()) {
781   default: break;
782   case ISD::HANDLENODE:
783   case ISD::EH_LABEL:
784     return true;   // Never CSE these nodes.
785   }
786 
787   // Check that remaining values produced are not flags.
788   for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
789     if (N->getValueType(i) == MVT::Glue)
790       return true; // Never CSE anything that produces a flag.
791 
792   return false;
793 }
794 
795 /// RemoveDeadNodes - This method deletes all unreachable nodes in the
796 /// SelectionDAG.
797 void SelectionDAG::RemoveDeadNodes() {
798   // Create a dummy node (which is not added to allnodes), that adds a reference
799   // to the root node, preventing it from being deleted.
800   HandleSDNode Dummy(getRoot());
801 
802   SmallVector<SDNode*, 128> DeadNodes;
803 
804   // Add all obviously-dead nodes to the DeadNodes worklist.
805   for (SDNode &Node : allnodes())
806     if (Node.use_empty())
807       DeadNodes.push_back(&Node);
808 
809   RemoveDeadNodes(DeadNodes);
810 
811   // If the root changed (e.g. it was a dead load, update the root).
812   setRoot(Dummy.getValue());
813 }
814 
815 /// RemoveDeadNodes - This method deletes the unreachable nodes in the
816 /// given list, and any nodes that become unreachable as a result.
817 void SelectionDAG::RemoveDeadNodes(SmallVectorImpl<SDNode *> &DeadNodes) {
818 
819   // Process the worklist, deleting the nodes and adding their uses to the
820   // worklist.
821   while (!DeadNodes.empty()) {
822     SDNode *N = DeadNodes.pop_back_val();
823     // Skip to next node if we've already managed to delete the node. This could
824     // happen if replacing a node causes a node previously added to the node to
825     // be deleted.
826     if (N->getOpcode() == ISD::DELETED_NODE)
827       continue;
828 
829     for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
830       DUL->NodeDeleted(N, nullptr);
831 
832     // Take the node out of the appropriate CSE map.
833     RemoveNodeFromCSEMaps(N);
834 
835     // Next, brutally remove the operand list.  This is safe to do, as there are
836     // no cycles in the graph.
837     for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) {
838       SDUse &Use = *I++;
839       SDNode *Operand = Use.getNode();
840       Use.set(SDValue());
841 
842       // Now that we removed this operand, see if there are no uses of it left.
843       if (Operand->use_empty())
844         DeadNodes.push_back(Operand);
845     }
846 
847     DeallocateNode(N);
848   }
849 }
850 
851 void SelectionDAG::RemoveDeadNode(SDNode *N){
852   SmallVector<SDNode*, 16> DeadNodes(1, N);
853 
854   // Create a dummy node that adds a reference to the root node, preventing
855   // it from being deleted.  (This matters if the root is an operand of the
856   // dead node.)
857   HandleSDNode Dummy(getRoot());
858 
859   RemoveDeadNodes(DeadNodes);
860 }
861 
862 void SelectionDAG::DeleteNode(SDNode *N) {
863   // First take this out of the appropriate CSE map.
864   RemoveNodeFromCSEMaps(N);
865 
866   // Finally, remove uses due to operands of this node, remove from the
867   // AllNodes list, and delete the node.
868   DeleteNodeNotInCSEMaps(N);
869 }
870 
871 void SelectionDAG::DeleteNodeNotInCSEMaps(SDNode *N) {
872   assert(N->getIterator() != AllNodes.begin() &&
873          "Cannot delete the entry node!");
874   assert(N->use_empty() && "Cannot delete a node that is not dead!");
875 
876   // Drop all of the operands and decrement used node's use counts.
877   N->DropOperands();
878 
879   DeallocateNode(N);
880 }
881 
882 void SDDbgInfo::add(SDDbgValue *V, bool isParameter) {
883   assert(!(V->isVariadic() && isParameter));
884   if (isParameter)
885     ByvalParmDbgValues.push_back(V);
886   else
887     DbgValues.push_back(V);
888   for (const SDNode *Node : V->getSDNodes())
889     if (Node)
890       DbgValMap[Node].push_back(V);
891 }
892 
893 void SDDbgInfo::erase(const SDNode *Node) {
894   DbgValMapType::iterator I = DbgValMap.find(Node);
895   if (I == DbgValMap.end())
896     return;
897   for (auto &Val: I->second)
898     Val->setIsInvalidated();
899   DbgValMap.erase(I);
900 }
901 
902 void SelectionDAG::DeallocateNode(SDNode *N) {
903   // If we have operands, deallocate them.
904   removeOperands(N);
905 
906   NodeAllocator.Deallocate(AllNodes.remove(N));
907 
908   // Set the opcode to DELETED_NODE to help catch bugs when node
909   // memory is reallocated.
910   // FIXME: There are places in SDag that have grown a dependency on the opcode
911   // value in the released node.
912   __asan_unpoison_memory_region(&N->NodeType, sizeof(N->NodeType));
913   N->NodeType = ISD::DELETED_NODE;
914 
915   // If any of the SDDbgValue nodes refer to this SDNode, invalidate
916   // them and forget about that node.
917   DbgInfo->erase(N);
918 }
919 
920 #ifndef NDEBUG
921 /// VerifySDNode - Sanity check the given SDNode.  Aborts if it is invalid.
922 static void VerifySDNode(SDNode *N) {
923   switch (N->getOpcode()) {
924   default:
925     break;
926   case ISD::BUILD_PAIR: {
927     EVT VT = N->getValueType(0);
928     assert(N->getNumValues() == 1 && "Too many results!");
929     assert(!VT.isVector() && (VT.isInteger() || VT.isFloatingPoint()) &&
930            "Wrong return type!");
931     assert(N->getNumOperands() == 2 && "Wrong number of operands!");
932     assert(N->getOperand(0).getValueType() == N->getOperand(1).getValueType() &&
933            "Mismatched operand types!");
934     assert(N->getOperand(0).getValueType().isInteger() == VT.isInteger() &&
935            "Wrong operand type!");
936     assert(VT.getSizeInBits() == 2 * N->getOperand(0).getValueSizeInBits() &&
937            "Wrong return type size");
938     break;
939   }
940   case ISD::BUILD_VECTOR: {
941     assert(N->getNumValues() == 1 && "Too many results!");
942     assert(N->getValueType(0).isVector() && "Wrong return type!");
943     assert(N->getNumOperands() == N->getValueType(0).getVectorNumElements() &&
944            "Wrong number of operands!");
945     EVT EltVT = N->getValueType(0).getVectorElementType();
946     for (const SDUse &Op : N->ops()) {
947       assert((Op.getValueType() == EltVT ||
948               (EltVT.isInteger() && Op.getValueType().isInteger() &&
949                EltVT.bitsLE(Op.getValueType()))) &&
950              "Wrong operand type!");
951       assert(Op.getValueType() == N->getOperand(0).getValueType() &&
952              "Operands must all have the same type");
953     }
954     break;
955   }
956   }
957 }
958 #endif // NDEBUG
959 
960 /// Insert a newly allocated node into the DAG.
961 ///
962 /// Handles insertion into the all nodes list and CSE map, as well as
963 /// verification and other common operations when a new node is allocated.
964 void SelectionDAG::InsertNode(SDNode *N) {
965   AllNodes.push_back(N);
966 #ifndef NDEBUG
967   N->PersistentId = NextPersistentId++;
968   VerifySDNode(N);
969 #endif
970   for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
971     DUL->NodeInserted(N);
972 }
973 
974 /// RemoveNodeFromCSEMaps - Take the specified node out of the CSE map that
975 /// correspond to it.  This is useful when we're about to delete or repurpose
976 /// the node.  We don't want future request for structurally identical nodes
977 /// to return N anymore.
978 bool SelectionDAG::RemoveNodeFromCSEMaps(SDNode *N) {
979   bool Erased = false;
980   switch (N->getOpcode()) {
981   case ISD::HANDLENODE: return false;  // noop.
982   case ISD::CONDCODE:
983     assert(CondCodeNodes[cast<CondCodeSDNode>(N)->get()] &&
984            "Cond code doesn't exist!");
985     Erased = CondCodeNodes[cast<CondCodeSDNode>(N)->get()] != nullptr;
986     CondCodeNodes[cast<CondCodeSDNode>(N)->get()] = nullptr;
987     break;
988   case ISD::ExternalSymbol:
989     Erased = ExternalSymbols.erase(cast<ExternalSymbolSDNode>(N)->getSymbol());
990     break;
991   case ISD::TargetExternalSymbol: {
992     ExternalSymbolSDNode *ESN = cast<ExternalSymbolSDNode>(N);
993     Erased = TargetExternalSymbols.erase(std::pair<std::string, unsigned>(
994         ESN->getSymbol(), ESN->getTargetFlags()));
995     break;
996   }
997   case ISD::MCSymbol: {
998     auto *MCSN = cast<MCSymbolSDNode>(N);
999     Erased = MCSymbols.erase(MCSN->getMCSymbol());
1000     break;
1001   }
1002   case ISD::VALUETYPE: {
1003     EVT VT = cast<VTSDNode>(N)->getVT();
1004     if (VT.isExtended()) {
1005       Erased = ExtendedValueTypeNodes.erase(VT);
1006     } else {
1007       Erased = ValueTypeNodes[VT.getSimpleVT().SimpleTy] != nullptr;
1008       ValueTypeNodes[VT.getSimpleVT().SimpleTy] = nullptr;
1009     }
1010     break;
1011   }
1012   default:
1013     // Remove it from the CSE Map.
1014     assert(N->getOpcode() != ISD::DELETED_NODE && "DELETED_NODE in CSEMap!");
1015     assert(N->getOpcode() != ISD::EntryToken && "EntryToken in CSEMap!");
1016     Erased = CSEMap.RemoveNode(N);
1017     break;
1018   }
1019 #ifndef NDEBUG
1020   // Verify that the node was actually in one of the CSE maps, unless it has a
1021   // flag result (which cannot be CSE'd) or is one of the special cases that are
1022   // not subject to CSE.
1023   if (!Erased && N->getValueType(N->getNumValues()-1) != MVT::Glue &&
1024       !N->isMachineOpcode() && !doNotCSE(N)) {
1025     N->dump(this);
1026     dbgs() << "\n";
1027     llvm_unreachable("Node is not in map!");
1028   }
1029 #endif
1030   return Erased;
1031 }
1032 
1033 /// AddModifiedNodeToCSEMaps - The specified node has been removed from the CSE
1034 /// maps and modified in place. Add it back to the CSE maps, unless an identical
1035 /// node already exists, in which case transfer all its users to the existing
1036 /// node. This transfer can potentially trigger recursive merging.
1037 void
1038 SelectionDAG::AddModifiedNodeToCSEMaps(SDNode *N) {
1039   // For node types that aren't CSE'd, just act as if no identical node
1040   // already exists.
1041   if (!doNotCSE(N)) {
1042     SDNode *Existing = CSEMap.GetOrInsertNode(N);
1043     if (Existing != N) {
1044       // If there was already an existing matching node, use ReplaceAllUsesWith
1045       // to replace the dead one with the existing one.  This can cause
1046       // recursive merging of other unrelated nodes down the line.
1047       ReplaceAllUsesWith(N, Existing);
1048 
1049       // N is now dead. Inform the listeners and delete it.
1050       for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
1051         DUL->NodeDeleted(N, Existing);
1052       DeleteNodeNotInCSEMaps(N);
1053       return;
1054     }
1055   }
1056 
1057   // If the node doesn't already exist, we updated it.  Inform listeners.
1058   for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
1059     DUL->NodeUpdated(N);
1060 }
1061 
1062 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
1063 /// were replaced with those specified.  If this node is never memoized,
1064 /// return null, otherwise return a pointer to the slot it would take.  If a
1065 /// node already exists with these operands, the slot will be non-null.
1066 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, SDValue Op,
1067                                            void *&InsertPos) {
1068   if (doNotCSE(N))
1069     return nullptr;
1070 
1071   SDValue Ops[] = { Op };
1072   FoldingSetNodeID ID;
1073   AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops);
1074   AddNodeIDCustom(ID, N);
1075   SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos);
1076   if (Node)
1077     Node->intersectFlagsWith(N->getFlags());
1078   return Node;
1079 }
1080 
1081 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
1082 /// were replaced with those specified.  If this node is never memoized,
1083 /// return null, otherwise return a pointer to the slot it would take.  If a
1084 /// node already exists with these operands, the slot will be non-null.
1085 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N,
1086                                            SDValue Op1, SDValue Op2,
1087                                            void *&InsertPos) {
1088   if (doNotCSE(N))
1089     return nullptr;
1090 
1091   SDValue Ops[] = { Op1, Op2 };
1092   FoldingSetNodeID ID;
1093   AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops);
1094   AddNodeIDCustom(ID, N);
1095   SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos);
1096   if (Node)
1097     Node->intersectFlagsWith(N->getFlags());
1098   return Node;
1099 }
1100 
1101 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
1102 /// were replaced with those specified.  If this node is never memoized,
1103 /// return null, otherwise return a pointer to the slot it would take.  If a
1104 /// node already exists with these operands, the slot will be non-null.
1105 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, ArrayRef<SDValue> Ops,
1106                                            void *&InsertPos) {
1107   if (doNotCSE(N))
1108     return nullptr;
1109 
1110   FoldingSetNodeID ID;
1111   AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops);
1112   AddNodeIDCustom(ID, N);
1113   SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos);
1114   if (Node)
1115     Node->intersectFlagsWith(N->getFlags());
1116   return Node;
1117 }
1118 
1119 Align SelectionDAG::getEVTAlign(EVT VT) const {
1120   Type *Ty = VT == MVT::iPTR ?
1121                    PointerType::get(Type::getInt8Ty(*getContext()), 0) :
1122                    VT.getTypeForEVT(*getContext());
1123 
1124   return getDataLayout().getABITypeAlign(Ty);
1125 }
1126 
1127 // EntryNode could meaningfully have debug info if we can find it...
1128 SelectionDAG::SelectionDAG(const TargetMachine &tm, CodeGenOpt::Level OL)
1129     : TM(tm), OptLevel(OL),
1130       EntryNode(ISD::EntryToken, 0, DebugLoc(), getVTList(MVT::Other)),
1131       Root(getEntryNode()) {
1132   InsertNode(&EntryNode);
1133   DbgInfo = new SDDbgInfo();
1134 }
1135 
1136 void SelectionDAG::init(MachineFunction &NewMF,
1137                         OptimizationRemarkEmitter &NewORE,
1138                         Pass *PassPtr, const TargetLibraryInfo *LibraryInfo,
1139                         LegacyDivergenceAnalysis * Divergence,
1140                         ProfileSummaryInfo *PSIin,
1141                         BlockFrequencyInfo *BFIin) {
1142   MF = &NewMF;
1143   SDAGISelPass = PassPtr;
1144   ORE = &NewORE;
1145   TLI = getSubtarget().getTargetLowering();
1146   TSI = getSubtarget().getSelectionDAGInfo();
1147   LibInfo = LibraryInfo;
1148   Context = &MF->getFunction().getContext();
1149   DA = Divergence;
1150   PSI = PSIin;
1151   BFI = BFIin;
1152 }
1153 
1154 SelectionDAG::~SelectionDAG() {
1155   assert(!UpdateListeners && "Dangling registered DAGUpdateListeners");
1156   allnodes_clear();
1157   OperandRecycler.clear(OperandAllocator);
1158   delete DbgInfo;
1159 }
1160 
1161 bool SelectionDAG::shouldOptForSize() const {
1162   return MF->getFunction().hasOptSize() ||
1163       llvm::shouldOptimizeForSize(FLI->MBB->getBasicBlock(), PSI, BFI);
1164 }
1165 
1166 void SelectionDAG::allnodes_clear() {
1167   assert(&*AllNodes.begin() == &EntryNode);
1168   AllNodes.remove(AllNodes.begin());
1169   while (!AllNodes.empty())
1170     DeallocateNode(&AllNodes.front());
1171 #ifndef NDEBUG
1172   NextPersistentId = 0;
1173 #endif
1174 }
1175 
1176 SDNode *SelectionDAG::FindNodeOrInsertPos(const FoldingSetNodeID &ID,
1177                                           void *&InsertPos) {
1178   SDNode *N = CSEMap.FindNodeOrInsertPos(ID, InsertPos);
1179   if (N) {
1180     switch (N->getOpcode()) {
1181     default: break;
1182     case ISD::Constant:
1183     case ISD::ConstantFP:
1184       llvm_unreachable("Querying for Constant and ConstantFP nodes requires "
1185                        "debug location.  Use another overload.");
1186     }
1187   }
1188   return N;
1189 }
1190 
1191 SDNode *SelectionDAG::FindNodeOrInsertPos(const FoldingSetNodeID &ID,
1192                                           const SDLoc &DL, void *&InsertPos) {
1193   SDNode *N = CSEMap.FindNodeOrInsertPos(ID, InsertPos);
1194   if (N) {
1195     switch (N->getOpcode()) {
1196     case ISD::Constant:
1197     case ISD::ConstantFP:
1198       // Erase debug location from the node if the node is used at several
1199       // different places. Do not propagate one location to all uses as it
1200       // will cause a worse single stepping debugging experience.
1201       if (N->getDebugLoc() != DL.getDebugLoc())
1202         N->setDebugLoc(DebugLoc());
1203       break;
1204     default:
1205       // When the node's point of use is located earlier in the instruction
1206       // sequence than its prior point of use, update its debug info to the
1207       // earlier location.
1208       if (DL.getIROrder() && DL.getIROrder() < N->getIROrder())
1209         N->setDebugLoc(DL.getDebugLoc());
1210       break;
1211     }
1212   }
1213   return N;
1214 }
1215 
1216 void SelectionDAG::clear() {
1217   allnodes_clear();
1218   OperandRecycler.clear(OperandAllocator);
1219   OperandAllocator.Reset();
1220   CSEMap.clear();
1221 
1222   ExtendedValueTypeNodes.clear();
1223   ExternalSymbols.clear();
1224   TargetExternalSymbols.clear();
1225   MCSymbols.clear();
1226   SDCallSiteDbgInfo.clear();
1227   std::fill(CondCodeNodes.begin(), CondCodeNodes.end(),
1228             static_cast<CondCodeSDNode*>(nullptr));
1229   std::fill(ValueTypeNodes.begin(), ValueTypeNodes.end(),
1230             static_cast<SDNode*>(nullptr));
1231 
1232   EntryNode.UseList = nullptr;
1233   InsertNode(&EntryNode);
1234   Root = getEntryNode();
1235   DbgInfo->clear();
1236 }
1237 
1238 SDValue SelectionDAG::getFPExtendOrRound(SDValue Op, const SDLoc &DL, EVT VT) {
1239   return VT.bitsGT(Op.getValueType())
1240              ? getNode(ISD::FP_EXTEND, DL, VT, Op)
1241              : getNode(ISD::FP_ROUND, DL, VT, Op, getIntPtrConstant(0, DL));
1242 }
1243 
1244 std::pair<SDValue, SDValue>
1245 SelectionDAG::getStrictFPExtendOrRound(SDValue Op, SDValue Chain,
1246                                        const SDLoc &DL, EVT VT) {
1247   assert(!VT.bitsEq(Op.getValueType()) &&
1248          "Strict no-op FP extend/round not allowed.");
1249   SDValue Res =
1250       VT.bitsGT(Op.getValueType())
1251           ? getNode(ISD::STRICT_FP_EXTEND, DL, {VT, MVT::Other}, {Chain, Op})
1252           : getNode(ISD::STRICT_FP_ROUND, DL, {VT, MVT::Other},
1253                     {Chain, Op, getIntPtrConstant(0, DL)});
1254 
1255   return std::pair<SDValue, SDValue>(Res, SDValue(Res.getNode(), 1));
1256 }
1257 
1258 SDValue SelectionDAG::getAnyExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
1259   return VT.bitsGT(Op.getValueType()) ?
1260     getNode(ISD::ANY_EXTEND, DL, VT, Op) :
1261     getNode(ISD::TRUNCATE, DL, VT, Op);
1262 }
1263 
1264 SDValue SelectionDAG::getSExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
1265   return VT.bitsGT(Op.getValueType()) ?
1266     getNode(ISD::SIGN_EXTEND, DL, VT, Op) :
1267     getNode(ISD::TRUNCATE, DL, VT, Op);
1268 }
1269 
1270 SDValue SelectionDAG::getZExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
1271   return VT.bitsGT(Op.getValueType()) ?
1272     getNode(ISD::ZERO_EXTEND, DL, VT, Op) :
1273     getNode(ISD::TRUNCATE, DL, VT, Op);
1274 }
1275 
1276 SDValue SelectionDAG::getBoolExtOrTrunc(SDValue Op, const SDLoc &SL, EVT VT,
1277                                         EVT OpVT) {
1278   if (VT.bitsLE(Op.getValueType()))
1279     return getNode(ISD::TRUNCATE, SL, VT, Op);
1280 
1281   TargetLowering::BooleanContent BType = TLI->getBooleanContents(OpVT);
1282   return getNode(TLI->getExtendForContent(BType), SL, VT, Op);
1283 }
1284 
1285 SDValue SelectionDAG::getZeroExtendInReg(SDValue Op, const SDLoc &DL, EVT VT) {
1286   EVT OpVT = Op.getValueType();
1287   assert(VT.isInteger() && OpVT.isInteger() &&
1288          "Cannot getZeroExtendInReg FP types");
1289   assert(VT.isVector() == OpVT.isVector() &&
1290          "getZeroExtendInReg type should be vector iff the operand "
1291          "type is vector!");
1292   assert((!VT.isVector() ||
1293           VT.getVectorElementCount() == OpVT.getVectorElementCount()) &&
1294          "Vector element counts must match in getZeroExtendInReg");
1295   assert(VT.bitsLE(OpVT) && "Not extending!");
1296   if (OpVT == VT)
1297     return Op;
1298   APInt Imm = APInt::getLowBitsSet(OpVT.getScalarSizeInBits(),
1299                                    VT.getScalarSizeInBits());
1300   return getNode(ISD::AND, DL, OpVT, Op, getConstant(Imm, DL, OpVT));
1301 }
1302 
1303 SDValue SelectionDAG::getPtrExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
1304   // Only unsigned pointer semantics are supported right now. In the future this
1305   // might delegate to TLI to check pointer signedness.
1306   return getZExtOrTrunc(Op, DL, VT);
1307 }
1308 
1309 SDValue SelectionDAG::getPtrExtendInReg(SDValue Op, const SDLoc &DL, EVT VT) {
1310   // Only unsigned pointer semantics are supported right now. In the future this
1311   // might delegate to TLI to check pointer signedness.
1312   return getZeroExtendInReg(Op, DL, VT);
1313 }
1314 
1315 /// getNOT - Create a bitwise NOT operation as (XOR Val, -1).
1316 SDValue SelectionDAG::getNOT(const SDLoc &DL, SDValue Val, EVT VT) {
1317   EVT EltVT = VT.getScalarType();
1318   SDValue NegOne =
1319     getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), DL, VT);
1320   return getNode(ISD::XOR, DL, VT, Val, NegOne);
1321 }
1322 
1323 SDValue SelectionDAG::getLogicalNOT(const SDLoc &DL, SDValue Val, EVT VT) {
1324   SDValue TrueValue = getBoolConstant(true, DL, VT, VT);
1325   return getNode(ISD::XOR, DL, VT, Val, TrueValue);
1326 }
1327 
1328 SDValue SelectionDAG::getBoolConstant(bool V, const SDLoc &DL, EVT VT,
1329                                       EVT OpVT) {
1330   if (!V)
1331     return getConstant(0, DL, VT);
1332 
1333   switch (TLI->getBooleanContents(OpVT)) {
1334   case TargetLowering::ZeroOrOneBooleanContent:
1335   case TargetLowering::UndefinedBooleanContent:
1336     return getConstant(1, DL, VT);
1337   case TargetLowering::ZeroOrNegativeOneBooleanContent:
1338     return getAllOnesConstant(DL, VT);
1339   }
1340   llvm_unreachable("Unexpected boolean content enum!");
1341 }
1342 
1343 SDValue SelectionDAG::getConstant(uint64_t Val, const SDLoc &DL, EVT VT,
1344                                   bool isT, bool isO) {
1345   EVT EltVT = VT.getScalarType();
1346   assert((EltVT.getSizeInBits() >= 64 ||
1347           (uint64_t)((int64_t)Val >> EltVT.getSizeInBits()) + 1 < 2) &&
1348          "getConstant with a uint64_t value that doesn't fit in the type!");
1349   return getConstant(APInt(EltVT.getSizeInBits(), Val), DL, VT, isT, isO);
1350 }
1351 
1352 SDValue SelectionDAG::getConstant(const APInt &Val, const SDLoc &DL, EVT VT,
1353                                   bool isT, bool isO) {
1354   return getConstant(*ConstantInt::get(*Context, Val), DL, VT, isT, isO);
1355 }
1356 
1357 SDValue SelectionDAG::getConstant(const ConstantInt &Val, const SDLoc &DL,
1358                                   EVT VT, bool isT, bool isO) {
1359   assert(VT.isInteger() && "Cannot create FP integer constant!");
1360 
1361   EVT EltVT = VT.getScalarType();
1362   const ConstantInt *Elt = &Val;
1363 
1364   // In some cases the vector type is legal but the element type is illegal and
1365   // needs to be promoted, for example v8i8 on ARM.  In this case, promote the
1366   // inserted value (the type does not need to match the vector element type).
1367   // Any extra bits introduced will be truncated away.
1368   if (VT.isVector() && TLI->getTypeAction(*getContext(), EltVT) ==
1369                            TargetLowering::TypePromoteInteger) {
1370     EltVT = TLI->getTypeToTransformTo(*getContext(), EltVT);
1371     APInt NewVal = Elt->getValue().zextOrTrunc(EltVT.getSizeInBits());
1372     Elt = ConstantInt::get(*getContext(), NewVal);
1373   }
1374   // In other cases the element type is illegal and needs to be expanded, for
1375   // example v2i64 on MIPS32. In this case, find the nearest legal type, split
1376   // the value into n parts and use a vector type with n-times the elements.
1377   // Then bitcast to the type requested.
1378   // Legalizing constants too early makes the DAGCombiner's job harder so we
1379   // only legalize if the DAG tells us we must produce legal types.
1380   else if (NewNodesMustHaveLegalTypes && VT.isVector() &&
1381            TLI->getTypeAction(*getContext(), EltVT) ==
1382                TargetLowering::TypeExpandInteger) {
1383     const APInt &NewVal = Elt->getValue();
1384     EVT ViaEltVT = TLI->getTypeToTransformTo(*getContext(), EltVT);
1385     unsigned ViaEltSizeInBits = ViaEltVT.getSizeInBits();
1386 
1387     // For scalable vectors, try to use a SPLAT_VECTOR_PARTS node.
1388     if (VT.isScalableVector()) {
1389       assert(EltVT.getSizeInBits() % ViaEltSizeInBits == 0 &&
1390              "Can only handle an even split!");
1391       unsigned Parts = EltVT.getSizeInBits() / ViaEltSizeInBits;
1392 
1393       SmallVector<SDValue, 2> ScalarParts;
1394       for (unsigned i = 0; i != Parts; ++i)
1395         ScalarParts.push_back(getConstant(
1396             NewVal.lshr(i * ViaEltSizeInBits).trunc(ViaEltSizeInBits), DL,
1397             ViaEltVT, isT, isO));
1398 
1399       return getNode(ISD::SPLAT_VECTOR_PARTS, DL, VT, ScalarParts);
1400     }
1401 
1402     unsigned ViaVecNumElts = VT.getSizeInBits() / ViaEltSizeInBits;
1403     EVT ViaVecVT = EVT::getVectorVT(*getContext(), ViaEltVT, ViaVecNumElts);
1404 
1405     // Check the temporary vector is the correct size. If this fails then
1406     // getTypeToTransformTo() probably returned a type whose size (in bits)
1407     // isn't a power-of-2 factor of the requested type size.
1408     assert(ViaVecVT.getSizeInBits() == VT.getSizeInBits());
1409 
1410     SmallVector<SDValue, 2> EltParts;
1411     for (unsigned i = 0; i < ViaVecNumElts / VT.getVectorNumElements(); ++i) {
1412       EltParts.push_back(getConstant(
1413           NewVal.lshr(i * ViaEltSizeInBits).zextOrTrunc(ViaEltSizeInBits), DL,
1414           ViaEltVT, isT, isO));
1415     }
1416 
1417     // EltParts is currently in little endian order. If we actually want
1418     // big-endian order then reverse it now.
1419     if (getDataLayout().isBigEndian())
1420       std::reverse(EltParts.begin(), EltParts.end());
1421 
1422     // The elements must be reversed when the element order is different
1423     // to the endianness of the elements (because the BITCAST is itself a
1424     // vector shuffle in this situation). However, we do not need any code to
1425     // perform this reversal because getConstant() is producing a vector
1426     // splat.
1427     // This situation occurs in MIPS MSA.
1428 
1429     SmallVector<SDValue, 8> Ops;
1430     for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
1431       llvm::append_range(Ops, EltParts);
1432 
1433     SDValue V =
1434         getNode(ISD::BITCAST, DL, VT, getBuildVector(ViaVecVT, DL, Ops));
1435     return V;
1436   }
1437 
1438   assert(Elt->getBitWidth() == EltVT.getSizeInBits() &&
1439          "APInt size does not match type size!");
1440   unsigned Opc = isT ? ISD::TargetConstant : ISD::Constant;
1441   FoldingSetNodeID ID;
1442   AddNodeIDNode(ID, Opc, getVTList(EltVT), None);
1443   ID.AddPointer(Elt);
1444   ID.AddBoolean(isO);
1445   void *IP = nullptr;
1446   SDNode *N = nullptr;
1447   if ((N = FindNodeOrInsertPos(ID, DL, IP)))
1448     if (!VT.isVector())
1449       return SDValue(N, 0);
1450 
1451   if (!N) {
1452     N = newSDNode<ConstantSDNode>(isT, isO, Elt, EltVT);
1453     CSEMap.InsertNode(N, IP);
1454     InsertNode(N);
1455     NewSDValueDbgMsg(SDValue(N, 0), "Creating constant: ", this);
1456   }
1457 
1458   SDValue Result(N, 0);
1459   if (VT.isScalableVector())
1460     Result = getSplatVector(VT, DL, Result);
1461   else if (VT.isVector())
1462     Result = getSplatBuildVector(VT, DL, Result);
1463 
1464   return Result;
1465 }
1466 
1467 SDValue SelectionDAG::getIntPtrConstant(uint64_t Val, const SDLoc &DL,
1468                                         bool isTarget) {
1469   return getConstant(Val, DL, TLI->getPointerTy(getDataLayout()), isTarget);
1470 }
1471 
1472 SDValue SelectionDAG::getShiftAmountConstant(uint64_t Val, EVT VT,
1473                                              const SDLoc &DL, bool LegalTypes) {
1474   assert(VT.isInteger() && "Shift amount is not an integer type!");
1475   EVT ShiftVT = TLI->getShiftAmountTy(VT, getDataLayout(), LegalTypes);
1476   return getConstant(Val, DL, ShiftVT);
1477 }
1478 
1479 SDValue SelectionDAG::getVectorIdxConstant(uint64_t Val, const SDLoc &DL,
1480                                            bool isTarget) {
1481   return getConstant(Val, DL, TLI->getVectorIdxTy(getDataLayout()), isTarget);
1482 }
1483 
1484 SDValue SelectionDAG::getConstantFP(const APFloat &V, const SDLoc &DL, EVT VT,
1485                                     bool isTarget) {
1486   return getConstantFP(*ConstantFP::get(*getContext(), V), DL, VT, isTarget);
1487 }
1488 
1489 SDValue SelectionDAG::getConstantFP(const ConstantFP &V, const SDLoc &DL,
1490                                     EVT VT, bool isTarget) {
1491   assert(VT.isFloatingPoint() && "Cannot create integer FP constant!");
1492 
1493   EVT EltVT = VT.getScalarType();
1494 
1495   // Do the map lookup using the actual bit pattern for the floating point
1496   // value, so that we don't have problems with 0.0 comparing equal to -0.0, and
1497   // we don't have issues with SNANs.
1498   unsigned Opc = isTarget ? ISD::TargetConstantFP : ISD::ConstantFP;
1499   FoldingSetNodeID ID;
1500   AddNodeIDNode(ID, Opc, getVTList(EltVT), None);
1501   ID.AddPointer(&V);
1502   void *IP = nullptr;
1503   SDNode *N = nullptr;
1504   if ((N = FindNodeOrInsertPos(ID, DL, IP)))
1505     if (!VT.isVector())
1506       return SDValue(N, 0);
1507 
1508   if (!N) {
1509     N = newSDNode<ConstantFPSDNode>(isTarget, &V, EltVT);
1510     CSEMap.InsertNode(N, IP);
1511     InsertNode(N);
1512   }
1513 
1514   SDValue Result(N, 0);
1515   if (VT.isScalableVector())
1516     Result = getSplatVector(VT, DL, Result);
1517   else if (VT.isVector())
1518     Result = getSplatBuildVector(VT, DL, Result);
1519   NewSDValueDbgMsg(Result, "Creating fp constant: ", this);
1520   return Result;
1521 }
1522 
1523 SDValue SelectionDAG::getConstantFP(double Val, const SDLoc &DL, EVT VT,
1524                                     bool isTarget) {
1525   EVT EltVT = VT.getScalarType();
1526   if (EltVT == MVT::f32)
1527     return getConstantFP(APFloat((float)Val), DL, VT, isTarget);
1528   else if (EltVT == MVT::f64)
1529     return getConstantFP(APFloat(Val), DL, VT, isTarget);
1530   else if (EltVT == MVT::f80 || EltVT == MVT::f128 || EltVT == MVT::ppcf128 ||
1531            EltVT == MVT::f16 || EltVT == MVT::bf16) {
1532     bool Ignored;
1533     APFloat APF = APFloat(Val);
1534     APF.convert(EVTToAPFloatSemantics(EltVT), APFloat::rmNearestTiesToEven,
1535                 &Ignored);
1536     return getConstantFP(APF, DL, VT, isTarget);
1537   } else
1538     llvm_unreachable("Unsupported type in getConstantFP");
1539 }
1540 
1541 SDValue SelectionDAG::getGlobalAddress(const GlobalValue *GV, const SDLoc &DL,
1542                                        EVT VT, int64_t Offset, bool isTargetGA,
1543                                        unsigned TargetFlags) {
1544   assert((TargetFlags == 0 || isTargetGA) &&
1545          "Cannot set target flags on target-independent globals");
1546 
1547   // Truncate (with sign-extension) the offset value to the pointer size.
1548   unsigned BitWidth = getDataLayout().getPointerTypeSizeInBits(GV->getType());
1549   if (BitWidth < 64)
1550     Offset = SignExtend64(Offset, BitWidth);
1551 
1552   unsigned Opc;
1553   if (GV->isThreadLocal())
1554     Opc = isTargetGA ? ISD::TargetGlobalTLSAddress : ISD::GlobalTLSAddress;
1555   else
1556     Opc = isTargetGA ? ISD::TargetGlobalAddress : ISD::GlobalAddress;
1557 
1558   FoldingSetNodeID ID;
1559   AddNodeIDNode(ID, Opc, getVTList(VT), None);
1560   ID.AddPointer(GV);
1561   ID.AddInteger(Offset);
1562   ID.AddInteger(TargetFlags);
1563   void *IP = nullptr;
1564   if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
1565     return SDValue(E, 0);
1566 
1567   auto *N = newSDNode<GlobalAddressSDNode>(
1568       Opc, DL.getIROrder(), DL.getDebugLoc(), GV, VT, Offset, TargetFlags);
1569   CSEMap.InsertNode(N, IP);
1570     InsertNode(N);
1571   return SDValue(N, 0);
1572 }
1573 
1574 SDValue SelectionDAG::getFrameIndex(int FI, EVT VT, bool isTarget) {
1575   unsigned Opc = isTarget ? ISD::TargetFrameIndex : ISD::FrameIndex;
1576   FoldingSetNodeID ID;
1577   AddNodeIDNode(ID, Opc, getVTList(VT), None);
1578   ID.AddInteger(FI);
1579   void *IP = nullptr;
1580   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1581     return SDValue(E, 0);
1582 
1583   auto *N = newSDNode<FrameIndexSDNode>(FI, VT, isTarget);
1584   CSEMap.InsertNode(N, IP);
1585   InsertNode(N);
1586   return SDValue(N, 0);
1587 }
1588 
1589 SDValue SelectionDAG::getJumpTable(int JTI, EVT VT, bool isTarget,
1590                                    unsigned TargetFlags) {
1591   assert((TargetFlags == 0 || isTarget) &&
1592          "Cannot set target flags on target-independent jump tables");
1593   unsigned Opc = isTarget ? ISD::TargetJumpTable : ISD::JumpTable;
1594   FoldingSetNodeID ID;
1595   AddNodeIDNode(ID, Opc, getVTList(VT), None);
1596   ID.AddInteger(JTI);
1597   ID.AddInteger(TargetFlags);
1598   void *IP = nullptr;
1599   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1600     return SDValue(E, 0);
1601 
1602   auto *N = newSDNode<JumpTableSDNode>(JTI, VT, isTarget, TargetFlags);
1603   CSEMap.InsertNode(N, IP);
1604   InsertNode(N);
1605   return SDValue(N, 0);
1606 }
1607 
1608 SDValue SelectionDAG::getConstantPool(const Constant *C, EVT VT,
1609                                       MaybeAlign Alignment, int Offset,
1610                                       bool isTarget, unsigned TargetFlags) {
1611   assert((TargetFlags == 0 || isTarget) &&
1612          "Cannot set target flags on target-independent globals");
1613   if (!Alignment)
1614     Alignment = shouldOptForSize()
1615                     ? getDataLayout().getABITypeAlign(C->getType())
1616                     : getDataLayout().getPrefTypeAlign(C->getType());
1617   unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
1618   FoldingSetNodeID ID;
1619   AddNodeIDNode(ID, Opc, getVTList(VT), None);
1620   ID.AddInteger(Alignment->value());
1621   ID.AddInteger(Offset);
1622   ID.AddPointer(C);
1623   ID.AddInteger(TargetFlags);
1624   void *IP = nullptr;
1625   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1626     return SDValue(E, 0);
1627 
1628   auto *N = newSDNode<ConstantPoolSDNode>(isTarget, C, VT, Offset, *Alignment,
1629                                           TargetFlags);
1630   CSEMap.InsertNode(N, IP);
1631   InsertNode(N);
1632   SDValue V = SDValue(N, 0);
1633   NewSDValueDbgMsg(V, "Creating new constant pool: ", this);
1634   return V;
1635 }
1636 
1637 SDValue SelectionDAG::getConstantPool(MachineConstantPoolValue *C, EVT VT,
1638                                       MaybeAlign Alignment, int Offset,
1639                                       bool isTarget, unsigned TargetFlags) {
1640   assert((TargetFlags == 0 || isTarget) &&
1641          "Cannot set target flags on target-independent globals");
1642   if (!Alignment)
1643     Alignment = getDataLayout().getPrefTypeAlign(C->getType());
1644   unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
1645   FoldingSetNodeID ID;
1646   AddNodeIDNode(ID, Opc, getVTList(VT), None);
1647   ID.AddInteger(Alignment->value());
1648   ID.AddInteger(Offset);
1649   C->addSelectionDAGCSEId(ID);
1650   ID.AddInteger(TargetFlags);
1651   void *IP = nullptr;
1652   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1653     return SDValue(E, 0);
1654 
1655   auto *N = newSDNode<ConstantPoolSDNode>(isTarget, C, VT, Offset, *Alignment,
1656                                           TargetFlags);
1657   CSEMap.InsertNode(N, IP);
1658   InsertNode(N);
1659   return SDValue(N, 0);
1660 }
1661 
1662 SDValue SelectionDAG::getTargetIndex(int Index, EVT VT, int64_t Offset,
1663                                      unsigned TargetFlags) {
1664   FoldingSetNodeID ID;
1665   AddNodeIDNode(ID, ISD::TargetIndex, getVTList(VT), None);
1666   ID.AddInteger(Index);
1667   ID.AddInteger(Offset);
1668   ID.AddInteger(TargetFlags);
1669   void *IP = nullptr;
1670   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1671     return SDValue(E, 0);
1672 
1673   auto *N = newSDNode<TargetIndexSDNode>(Index, VT, Offset, TargetFlags);
1674   CSEMap.InsertNode(N, IP);
1675   InsertNode(N);
1676   return SDValue(N, 0);
1677 }
1678 
1679 SDValue SelectionDAG::getBasicBlock(MachineBasicBlock *MBB) {
1680   FoldingSetNodeID ID;
1681   AddNodeIDNode(ID, ISD::BasicBlock, getVTList(MVT::Other), None);
1682   ID.AddPointer(MBB);
1683   void *IP = nullptr;
1684   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1685     return SDValue(E, 0);
1686 
1687   auto *N = newSDNode<BasicBlockSDNode>(MBB);
1688   CSEMap.InsertNode(N, IP);
1689   InsertNode(N);
1690   return SDValue(N, 0);
1691 }
1692 
1693 SDValue SelectionDAG::getValueType(EVT VT) {
1694   if (VT.isSimple() && (unsigned)VT.getSimpleVT().SimpleTy >=
1695       ValueTypeNodes.size())
1696     ValueTypeNodes.resize(VT.getSimpleVT().SimpleTy+1);
1697 
1698   SDNode *&N = VT.isExtended() ?
1699     ExtendedValueTypeNodes[VT] : ValueTypeNodes[VT.getSimpleVT().SimpleTy];
1700 
1701   if (N) return SDValue(N, 0);
1702   N = newSDNode<VTSDNode>(VT);
1703   InsertNode(N);
1704   return SDValue(N, 0);
1705 }
1706 
1707 SDValue SelectionDAG::getExternalSymbol(const char *Sym, EVT VT) {
1708   SDNode *&N = ExternalSymbols[Sym];
1709   if (N) return SDValue(N, 0);
1710   N = newSDNode<ExternalSymbolSDNode>(false, Sym, 0, VT);
1711   InsertNode(N);
1712   return SDValue(N, 0);
1713 }
1714 
1715 SDValue SelectionDAG::getMCSymbol(MCSymbol *Sym, EVT VT) {
1716   SDNode *&N = MCSymbols[Sym];
1717   if (N)
1718     return SDValue(N, 0);
1719   N = newSDNode<MCSymbolSDNode>(Sym, VT);
1720   InsertNode(N);
1721   return SDValue(N, 0);
1722 }
1723 
1724 SDValue SelectionDAG::getTargetExternalSymbol(const char *Sym, EVT VT,
1725                                               unsigned TargetFlags) {
1726   SDNode *&N =
1727       TargetExternalSymbols[std::pair<std::string, unsigned>(Sym, TargetFlags)];
1728   if (N) return SDValue(N, 0);
1729   N = newSDNode<ExternalSymbolSDNode>(true, Sym, TargetFlags, VT);
1730   InsertNode(N);
1731   return SDValue(N, 0);
1732 }
1733 
1734 SDValue SelectionDAG::getCondCode(ISD::CondCode Cond) {
1735   if ((unsigned)Cond >= CondCodeNodes.size())
1736     CondCodeNodes.resize(Cond+1);
1737 
1738   if (!CondCodeNodes[Cond]) {
1739     auto *N = newSDNode<CondCodeSDNode>(Cond);
1740     CondCodeNodes[Cond] = N;
1741     InsertNode(N);
1742   }
1743 
1744   return SDValue(CondCodeNodes[Cond], 0);
1745 }
1746 
1747 /// Swaps the values of N1 and N2. Swaps all indices in the shuffle mask M that
1748 /// point at N1 to point at N2 and indices that point at N2 to point at N1.
1749 static void commuteShuffle(SDValue &N1, SDValue &N2, MutableArrayRef<int> M) {
1750   std::swap(N1, N2);
1751   ShuffleVectorSDNode::commuteMask(M);
1752 }
1753 
1754 SDValue SelectionDAG::getVectorShuffle(EVT VT, const SDLoc &dl, SDValue N1,
1755                                        SDValue N2, ArrayRef<int> Mask) {
1756   assert(VT.getVectorNumElements() == Mask.size() &&
1757            "Must have the same number of vector elements as mask elements!");
1758   assert(VT == N1.getValueType() && VT == N2.getValueType() &&
1759          "Invalid VECTOR_SHUFFLE");
1760 
1761   // Canonicalize shuffle undef, undef -> undef
1762   if (N1.isUndef() && N2.isUndef())
1763     return getUNDEF(VT);
1764 
1765   // Validate that all indices in Mask are within the range of the elements
1766   // input to the shuffle.
1767   int NElts = Mask.size();
1768   assert(llvm::all_of(Mask,
1769                       [&](int M) { return M < (NElts * 2) && M >= -1; }) &&
1770          "Index out of range");
1771 
1772   // Copy the mask so we can do any needed cleanup.
1773   SmallVector<int, 8> MaskVec(Mask.begin(), Mask.end());
1774 
1775   // Canonicalize shuffle v, v -> v, undef
1776   if (N1 == N2) {
1777     N2 = getUNDEF(VT);
1778     for (int i = 0; i != NElts; ++i)
1779       if (MaskVec[i] >= NElts) MaskVec[i] -= NElts;
1780   }
1781 
1782   // Canonicalize shuffle undef, v -> v, undef.  Commute the shuffle mask.
1783   if (N1.isUndef())
1784     commuteShuffle(N1, N2, MaskVec);
1785 
1786   if (TLI->hasVectorBlend()) {
1787     // If shuffling a splat, try to blend the splat instead. We do this here so
1788     // that even when this arises during lowering we don't have to re-handle it.
1789     auto BlendSplat = [&](BuildVectorSDNode *BV, int Offset) {
1790       BitVector UndefElements;
1791       SDValue Splat = BV->getSplatValue(&UndefElements);
1792       if (!Splat)
1793         return;
1794 
1795       for (int i = 0; i < NElts; ++i) {
1796         if (MaskVec[i] < Offset || MaskVec[i] >= (Offset + NElts))
1797           continue;
1798 
1799         // If this input comes from undef, mark it as such.
1800         if (UndefElements[MaskVec[i] - Offset]) {
1801           MaskVec[i] = -1;
1802           continue;
1803         }
1804 
1805         // If we can blend a non-undef lane, use that instead.
1806         if (!UndefElements[i])
1807           MaskVec[i] = i + Offset;
1808       }
1809     };
1810     if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
1811       BlendSplat(N1BV, 0);
1812     if (auto *N2BV = dyn_cast<BuildVectorSDNode>(N2))
1813       BlendSplat(N2BV, NElts);
1814   }
1815 
1816   // Canonicalize all index into lhs, -> shuffle lhs, undef
1817   // Canonicalize all index into rhs, -> shuffle rhs, undef
1818   bool AllLHS = true, AllRHS = true;
1819   bool N2Undef = N2.isUndef();
1820   for (int i = 0; i != NElts; ++i) {
1821     if (MaskVec[i] >= NElts) {
1822       if (N2Undef)
1823         MaskVec[i] = -1;
1824       else
1825         AllLHS = false;
1826     } else if (MaskVec[i] >= 0) {
1827       AllRHS = false;
1828     }
1829   }
1830   if (AllLHS && AllRHS)
1831     return getUNDEF(VT);
1832   if (AllLHS && !N2Undef)
1833     N2 = getUNDEF(VT);
1834   if (AllRHS) {
1835     N1 = getUNDEF(VT);
1836     commuteShuffle(N1, N2, MaskVec);
1837   }
1838   // Reset our undef status after accounting for the mask.
1839   N2Undef = N2.isUndef();
1840   // Re-check whether both sides ended up undef.
1841   if (N1.isUndef() && N2Undef)
1842     return getUNDEF(VT);
1843 
1844   // If Identity shuffle return that node.
1845   bool Identity = true, AllSame = true;
1846   for (int i = 0; i != NElts; ++i) {
1847     if (MaskVec[i] >= 0 && MaskVec[i] != i) Identity = false;
1848     if (MaskVec[i] != MaskVec[0]) AllSame = false;
1849   }
1850   if (Identity && NElts)
1851     return N1;
1852 
1853   // Shuffling a constant splat doesn't change the result.
1854   if (N2Undef) {
1855     SDValue V = N1;
1856 
1857     // Look through any bitcasts. We check that these don't change the number
1858     // (and size) of elements and just changes their types.
1859     while (V.getOpcode() == ISD::BITCAST)
1860       V = V->getOperand(0);
1861 
1862     // A splat should always show up as a build vector node.
1863     if (auto *BV = dyn_cast<BuildVectorSDNode>(V)) {
1864       BitVector UndefElements;
1865       SDValue Splat = BV->getSplatValue(&UndefElements);
1866       // If this is a splat of an undef, shuffling it is also undef.
1867       if (Splat && Splat.isUndef())
1868         return getUNDEF(VT);
1869 
1870       bool SameNumElts =
1871           V.getValueType().getVectorNumElements() == VT.getVectorNumElements();
1872 
1873       // We only have a splat which can skip shuffles if there is a splatted
1874       // value and no undef lanes rearranged by the shuffle.
1875       if (Splat && UndefElements.none()) {
1876         // Splat of <x, x, ..., x>, return <x, x, ..., x>, provided that the
1877         // number of elements match or the value splatted is a zero constant.
1878         if (SameNumElts)
1879           return N1;
1880         if (auto *C = dyn_cast<ConstantSDNode>(Splat))
1881           if (C->isNullValue())
1882             return N1;
1883       }
1884 
1885       // If the shuffle itself creates a splat, build the vector directly.
1886       if (AllSame && SameNumElts) {
1887         EVT BuildVT = BV->getValueType(0);
1888         const SDValue &Splatted = BV->getOperand(MaskVec[0]);
1889         SDValue NewBV = getSplatBuildVector(BuildVT, dl, Splatted);
1890 
1891         // We may have jumped through bitcasts, so the type of the
1892         // BUILD_VECTOR may not match the type of the shuffle.
1893         if (BuildVT != VT)
1894           NewBV = getNode(ISD::BITCAST, dl, VT, NewBV);
1895         return NewBV;
1896       }
1897     }
1898   }
1899 
1900   FoldingSetNodeID ID;
1901   SDValue Ops[2] = { N1, N2 };
1902   AddNodeIDNode(ID, ISD::VECTOR_SHUFFLE, getVTList(VT), Ops);
1903   for (int i = 0; i != NElts; ++i)
1904     ID.AddInteger(MaskVec[i]);
1905 
1906   void* IP = nullptr;
1907   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
1908     return SDValue(E, 0);
1909 
1910   // Allocate the mask array for the node out of the BumpPtrAllocator, since
1911   // SDNode doesn't have access to it.  This memory will be "leaked" when
1912   // the node is deallocated, but recovered when the NodeAllocator is released.
1913   int *MaskAlloc = OperandAllocator.Allocate<int>(NElts);
1914   llvm::copy(MaskVec, MaskAlloc);
1915 
1916   auto *N = newSDNode<ShuffleVectorSDNode>(VT, dl.getIROrder(),
1917                                            dl.getDebugLoc(), MaskAlloc);
1918   createOperands(N, Ops);
1919 
1920   CSEMap.InsertNode(N, IP);
1921   InsertNode(N);
1922   SDValue V = SDValue(N, 0);
1923   NewSDValueDbgMsg(V, "Creating new node: ", this);
1924   return V;
1925 }
1926 
1927 SDValue SelectionDAG::getCommutedVectorShuffle(const ShuffleVectorSDNode &SV) {
1928   EVT VT = SV.getValueType(0);
1929   SmallVector<int, 8> MaskVec(SV.getMask().begin(), SV.getMask().end());
1930   ShuffleVectorSDNode::commuteMask(MaskVec);
1931 
1932   SDValue Op0 = SV.getOperand(0);
1933   SDValue Op1 = SV.getOperand(1);
1934   return getVectorShuffle(VT, SDLoc(&SV), Op1, Op0, MaskVec);
1935 }
1936 
1937 SDValue SelectionDAG::getRegister(unsigned RegNo, EVT VT) {
1938   FoldingSetNodeID ID;
1939   AddNodeIDNode(ID, ISD::Register, getVTList(VT), None);
1940   ID.AddInteger(RegNo);
1941   void *IP = nullptr;
1942   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1943     return SDValue(E, 0);
1944 
1945   auto *N = newSDNode<RegisterSDNode>(RegNo, VT);
1946   N->SDNodeBits.IsDivergent = TLI->isSDNodeSourceOfDivergence(N, FLI, DA);
1947   CSEMap.InsertNode(N, IP);
1948   InsertNode(N);
1949   return SDValue(N, 0);
1950 }
1951 
1952 SDValue SelectionDAG::getRegisterMask(const uint32_t *RegMask) {
1953   FoldingSetNodeID ID;
1954   AddNodeIDNode(ID, ISD::RegisterMask, getVTList(MVT::Untyped), None);
1955   ID.AddPointer(RegMask);
1956   void *IP = nullptr;
1957   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1958     return SDValue(E, 0);
1959 
1960   auto *N = newSDNode<RegisterMaskSDNode>(RegMask);
1961   CSEMap.InsertNode(N, IP);
1962   InsertNode(N);
1963   return SDValue(N, 0);
1964 }
1965 
1966 SDValue SelectionDAG::getEHLabel(const SDLoc &dl, SDValue Root,
1967                                  MCSymbol *Label) {
1968   return getLabelNode(ISD::EH_LABEL, dl, Root, Label);
1969 }
1970 
1971 SDValue SelectionDAG::getLabelNode(unsigned Opcode, const SDLoc &dl,
1972                                    SDValue Root, MCSymbol *Label) {
1973   FoldingSetNodeID ID;
1974   SDValue Ops[] = { Root };
1975   AddNodeIDNode(ID, Opcode, getVTList(MVT::Other), Ops);
1976   ID.AddPointer(Label);
1977   void *IP = nullptr;
1978   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1979     return SDValue(E, 0);
1980 
1981   auto *N =
1982       newSDNode<LabelSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(), Label);
1983   createOperands(N, Ops);
1984 
1985   CSEMap.InsertNode(N, IP);
1986   InsertNode(N);
1987   return SDValue(N, 0);
1988 }
1989 
1990 SDValue SelectionDAG::getBlockAddress(const BlockAddress *BA, EVT VT,
1991                                       int64_t Offset, bool isTarget,
1992                                       unsigned TargetFlags) {
1993   unsigned Opc = isTarget ? ISD::TargetBlockAddress : ISD::BlockAddress;
1994 
1995   FoldingSetNodeID ID;
1996   AddNodeIDNode(ID, Opc, getVTList(VT), None);
1997   ID.AddPointer(BA);
1998   ID.AddInteger(Offset);
1999   ID.AddInteger(TargetFlags);
2000   void *IP = nullptr;
2001   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2002     return SDValue(E, 0);
2003 
2004   auto *N = newSDNode<BlockAddressSDNode>(Opc, VT, BA, Offset, TargetFlags);
2005   CSEMap.InsertNode(N, IP);
2006   InsertNode(N);
2007   return SDValue(N, 0);
2008 }
2009 
2010 SDValue SelectionDAG::getSrcValue(const Value *V) {
2011   FoldingSetNodeID ID;
2012   AddNodeIDNode(ID, ISD::SRCVALUE, getVTList(MVT::Other), None);
2013   ID.AddPointer(V);
2014 
2015   void *IP = nullptr;
2016   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2017     return SDValue(E, 0);
2018 
2019   auto *N = newSDNode<SrcValueSDNode>(V);
2020   CSEMap.InsertNode(N, IP);
2021   InsertNode(N);
2022   return SDValue(N, 0);
2023 }
2024 
2025 SDValue SelectionDAG::getMDNode(const MDNode *MD) {
2026   FoldingSetNodeID ID;
2027   AddNodeIDNode(ID, ISD::MDNODE_SDNODE, getVTList(MVT::Other), None);
2028   ID.AddPointer(MD);
2029 
2030   void *IP = nullptr;
2031   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2032     return SDValue(E, 0);
2033 
2034   auto *N = newSDNode<MDNodeSDNode>(MD);
2035   CSEMap.InsertNode(N, IP);
2036   InsertNode(N);
2037   return SDValue(N, 0);
2038 }
2039 
2040 SDValue SelectionDAG::getBitcast(EVT VT, SDValue V) {
2041   if (VT == V.getValueType())
2042     return V;
2043 
2044   return getNode(ISD::BITCAST, SDLoc(V), VT, V);
2045 }
2046 
2047 SDValue SelectionDAG::getAddrSpaceCast(const SDLoc &dl, EVT VT, SDValue Ptr,
2048                                        unsigned SrcAS, unsigned DestAS) {
2049   SDValue Ops[] = {Ptr};
2050   FoldingSetNodeID ID;
2051   AddNodeIDNode(ID, ISD::ADDRSPACECAST, getVTList(VT), Ops);
2052   ID.AddInteger(SrcAS);
2053   ID.AddInteger(DestAS);
2054 
2055   void *IP = nullptr;
2056   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
2057     return SDValue(E, 0);
2058 
2059   auto *N = newSDNode<AddrSpaceCastSDNode>(dl.getIROrder(), dl.getDebugLoc(),
2060                                            VT, SrcAS, DestAS);
2061   createOperands(N, Ops);
2062 
2063   CSEMap.InsertNode(N, IP);
2064   InsertNode(N);
2065   return SDValue(N, 0);
2066 }
2067 
2068 SDValue SelectionDAG::getFreeze(SDValue V) {
2069   return getNode(ISD::FREEZE, SDLoc(V), V.getValueType(), V);
2070 }
2071 
2072 /// getShiftAmountOperand - Return the specified value casted to
2073 /// the target's desired shift amount type.
2074 SDValue SelectionDAG::getShiftAmountOperand(EVT LHSTy, SDValue Op) {
2075   EVT OpTy = Op.getValueType();
2076   EVT ShTy = TLI->getShiftAmountTy(LHSTy, getDataLayout());
2077   if (OpTy == ShTy || OpTy.isVector()) return Op;
2078 
2079   return getZExtOrTrunc(Op, SDLoc(Op), ShTy);
2080 }
2081 
2082 SDValue SelectionDAG::expandVAArg(SDNode *Node) {
2083   SDLoc dl(Node);
2084   const TargetLowering &TLI = getTargetLoweringInfo();
2085   const Value *V = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
2086   EVT VT = Node->getValueType(0);
2087   SDValue Tmp1 = Node->getOperand(0);
2088   SDValue Tmp2 = Node->getOperand(1);
2089   const MaybeAlign MA(Node->getConstantOperandVal(3));
2090 
2091   SDValue VAListLoad = getLoad(TLI.getPointerTy(getDataLayout()), dl, Tmp1,
2092                                Tmp2, MachinePointerInfo(V));
2093   SDValue VAList = VAListLoad;
2094 
2095   if (MA && *MA > TLI.getMinStackArgumentAlignment()) {
2096     VAList = getNode(ISD::ADD, dl, VAList.getValueType(), VAList,
2097                      getConstant(MA->value() - 1, dl, VAList.getValueType()));
2098 
2099     VAList =
2100         getNode(ISD::AND, dl, VAList.getValueType(), VAList,
2101                 getConstant(-(int64_t)MA->value(), dl, VAList.getValueType()));
2102   }
2103 
2104   // Increment the pointer, VAList, to the next vaarg
2105   Tmp1 = getNode(ISD::ADD, dl, VAList.getValueType(), VAList,
2106                  getConstant(getDataLayout().getTypeAllocSize(
2107                                                VT.getTypeForEVT(*getContext())),
2108                              dl, VAList.getValueType()));
2109   // Store the incremented VAList to the legalized pointer
2110   Tmp1 =
2111       getStore(VAListLoad.getValue(1), dl, Tmp1, Tmp2, MachinePointerInfo(V));
2112   // Load the actual argument out of the pointer VAList
2113   return getLoad(VT, dl, Tmp1, VAList, MachinePointerInfo());
2114 }
2115 
2116 SDValue SelectionDAG::expandVACopy(SDNode *Node) {
2117   SDLoc dl(Node);
2118   const TargetLowering &TLI = getTargetLoweringInfo();
2119   // This defaults to loading a pointer from the input and storing it to the
2120   // output, returning the chain.
2121   const Value *VD = cast<SrcValueSDNode>(Node->getOperand(3))->getValue();
2122   const Value *VS = cast<SrcValueSDNode>(Node->getOperand(4))->getValue();
2123   SDValue Tmp1 =
2124       getLoad(TLI.getPointerTy(getDataLayout()), dl, Node->getOperand(0),
2125               Node->getOperand(2), MachinePointerInfo(VS));
2126   return getStore(Tmp1.getValue(1), dl, Tmp1, Node->getOperand(1),
2127                   MachinePointerInfo(VD));
2128 }
2129 
2130 Align SelectionDAG::getReducedAlign(EVT VT, bool UseABI) {
2131   const DataLayout &DL = getDataLayout();
2132   Type *Ty = VT.getTypeForEVT(*getContext());
2133   Align RedAlign = UseABI ? DL.getABITypeAlign(Ty) : DL.getPrefTypeAlign(Ty);
2134 
2135   if (TLI->isTypeLegal(VT) || !VT.isVector())
2136     return RedAlign;
2137 
2138   const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering();
2139   const Align StackAlign = TFI->getStackAlign();
2140 
2141   // See if we can choose a smaller ABI alignment in cases where it's an
2142   // illegal vector type that will get broken down.
2143   if (RedAlign > StackAlign) {
2144     EVT IntermediateVT;
2145     MVT RegisterVT;
2146     unsigned NumIntermediates;
2147     TLI->getVectorTypeBreakdown(*getContext(), VT, IntermediateVT,
2148                                 NumIntermediates, RegisterVT);
2149     Ty = IntermediateVT.getTypeForEVT(*getContext());
2150     Align RedAlign2 = UseABI ? DL.getABITypeAlign(Ty) : DL.getPrefTypeAlign(Ty);
2151     if (RedAlign2 < RedAlign)
2152       RedAlign = RedAlign2;
2153   }
2154 
2155   return RedAlign;
2156 }
2157 
2158 SDValue SelectionDAG::CreateStackTemporary(TypeSize Bytes, Align Alignment) {
2159   MachineFrameInfo &MFI = MF->getFrameInfo();
2160   const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering();
2161   int StackID = 0;
2162   if (Bytes.isScalable())
2163     StackID = TFI->getStackIDForScalableVectors();
2164   // The stack id gives an indication of whether the object is scalable or
2165   // not, so it's safe to pass in the minimum size here.
2166   int FrameIdx = MFI.CreateStackObject(Bytes.getKnownMinSize(), Alignment,
2167                                        false, nullptr, StackID);
2168   return getFrameIndex(FrameIdx, TLI->getFrameIndexTy(getDataLayout()));
2169 }
2170 
2171 SDValue SelectionDAG::CreateStackTemporary(EVT VT, unsigned minAlign) {
2172   Type *Ty = VT.getTypeForEVT(*getContext());
2173   Align StackAlign =
2174       std::max(getDataLayout().getPrefTypeAlign(Ty), Align(minAlign));
2175   return CreateStackTemporary(VT.getStoreSize(), StackAlign);
2176 }
2177 
2178 SDValue SelectionDAG::CreateStackTemporary(EVT VT1, EVT VT2) {
2179   TypeSize VT1Size = VT1.getStoreSize();
2180   TypeSize VT2Size = VT2.getStoreSize();
2181   assert(VT1Size.isScalable() == VT2Size.isScalable() &&
2182          "Don't know how to choose the maximum size when creating a stack "
2183          "temporary");
2184   TypeSize Bytes =
2185       VT1Size.getKnownMinSize() > VT2Size.getKnownMinSize() ? VT1Size : VT2Size;
2186 
2187   Type *Ty1 = VT1.getTypeForEVT(*getContext());
2188   Type *Ty2 = VT2.getTypeForEVT(*getContext());
2189   const DataLayout &DL = getDataLayout();
2190   Align Align = std::max(DL.getPrefTypeAlign(Ty1), DL.getPrefTypeAlign(Ty2));
2191   return CreateStackTemporary(Bytes, Align);
2192 }
2193 
2194 SDValue SelectionDAG::FoldSetCC(EVT VT, SDValue N1, SDValue N2,
2195                                 ISD::CondCode Cond, const SDLoc &dl) {
2196   EVT OpVT = N1.getValueType();
2197 
2198   // These setcc operations always fold.
2199   switch (Cond) {
2200   default: break;
2201   case ISD::SETFALSE:
2202   case ISD::SETFALSE2: return getBoolConstant(false, dl, VT, OpVT);
2203   case ISD::SETTRUE:
2204   case ISD::SETTRUE2: return getBoolConstant(true, dl, VT, OpVT);
2205 
2206   case ISD::SETOEQ:
2207   case ISD::SETOGT:
2208   case ISD::SETOGE:
2209   case ISD::SETOLT:
2210   case ISD::SETOLE:
2211   case ISD::SETONE:
2212   case ISD::SETO:
2213   case ISD::SETUO:
2214   case ISD::SETUEQ:
2215   case ISD::SETUNE:
2216     assert(!OpVT.isInteger() && "Illegal setcc for integer!");
2217     break;
2218   }
2219 
2220   if (OpVT.isInteger()) {
2221     // For EQ and NE, we can always pick a value for the undef to make the
2222     // predicate pass or fail, so we can return undef.
2223     // Matches behavior in llvm::ConstantFoldCompareInstruction.
2224     // icmp eq/ne X, undef -> undef.
2225     if ((N1.isUndef() || N2.isUndef()) &&
2226         (Cond == ISD::SETEQ || Cond == ISD::SETNE))
2227       return getUNDEF(VT);
2228 
2229     // If both operands are undef, we can return undef for int comparison.
2230     // icmp undef, undef -> undef.
2231     if (N1.isUndef() && N2.isUndef())
2232       return getUNDEF(VT);
2233 
2234     // icmp X, X -> true/false
2235     // icmp X, undef -> true/false because undef could be X.
2236     if (N1 == N2)
2237       return getBoolConstant(ISD::isTrueWhenEqual(Cond), dl, VT, OpVT);
2238   }
2239 
2240   if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2)) {
2241     const APInt &C2 = N2C->getAPIntValue();
2242     if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1)) {
2243       const APInt &C1 = N1C->getAPIntValue();
2244 
2245       switch (Cond) {
2246       default: llvm_unreachable("Unknown integer setcc!");
2247       case ISD::SETEQ:  return getBoolConstant(C1 == C2, dl, VT, OpVT);
2248       case ISD::SETNE:  return getBoolConstant(C1 != C2, dl, VT, OpVT);
2249       case ISD::SETULT: return getBoolConstant(C1.ult(C2), dl, VT, OpVT);
2250       case ISD::SETUGT: return getBoolConstant(C1.ugt(C2), dl, VT, OpVT);
2251       case ISD::SETULE: return getBoolConstant(C1.ule(C2), dl, VT, OpVT);
2252       case ISD::SETUGE: return getBoolConstant(C1.uge(C2), dl, VT, OpVT);
2253       case ISD::SETLT:  return getBoolConstant(C1.slt(C2), dl, VT, OpVT);
2254       case ISD::SETGT:  return getBoolConstant(C1.sgt(C2), dl, VT, OpVT);
2255       case ISD::SETLE:  return getBoolConstant(C1.sle(C2), dl, VT, OpVT);
2256       case ISD::SETGE:  return getBoolConstant(C1.sge(C2), dl, VT, OpVT);
2257       }
2258     }
2259   }
2260 
2261   auto *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
2262   auto *N2CFP = dyn_cast<ConstantFPSDNode>(N2);
2263 
2264   if (N1CFP && N2CFP) {
2265     APFloat::cmpResult R = N1CFP->getValueAPF().compare(N2CFP->getValueAPF());
2266     switch (Cond) {
2267     default: break;
2268     case ISD::SETEQ:  if (R==APFloat::cmpUnordered)
2269                         return getUNDEF(VT);
2270                       LLVM_FALLTHROUGH;
2271     case ISD::SETOEQ: return getBoolConstant(R==APFloat::cmpEqual, dl, VT,
2272                                              OpVT);
2273     case ISD::SETNE:  if (R==APFloat::cmpUnordered)
2274                         return getUNDEF(VT);
2275                       LLVM_FALLTHROUGH;
2276     case ISD::SETONE: return getBoolConstant(R==APFloat::cmpGreaterThan ||
2277                                              R==APFloat::cmpLessThan, dl, VT,
2278                                              OpVT);
2279     case ISD::SETLT:  if (R==APFloat::cmpUnordered)
2280                         return getUNDEF(VT);
2281                       LLVM_FALLTHROUGH;
2282     case ISD::SETOLT: return getBoolConstant(R==APFloat::cmpLessThan, dl, VT,
2283                                              OpVT);
2284     case ISD::SETGT:  if (R==APFloat::cmpUnordered)
2285                         return getUNDEF(VT);
2286                       LLVM_FALLTHROUGH;
2287     case ISD::SETOGT: return getBoolConstant(R==APFloat::cmpGreaterThan, dl,
2288                                              VT, OpVT);
2289     case ISD::SETLE:  if (R==APFloat::cmpUnordered)
2290                         return getUNDEF(VT);
2291                       LLVM_FALLTHROUGH;
2292     case ISD::SETOLE: return getBoolConstant(R==APFloat::cmpLessThan ||
2293                                              R==APFloat::cmpEqual, dl, VT,
2294                                              OpVT);
2295     case ISD::SETGE:  if (R==APFloat::cmpUnordered)
2296                         return getUNDEF(VT);
2297                       LLVM_FALLTHROUGH;
2298     case ISD::SETOGE: return getBoolConstant(R==APFloat::cmpGreaterThan ||
2299                                          R==APFloat::cmpEqual, dl, VT, OpVT);
2300     case ISD::SETO:   return getBoolConstant(R!=APFloat::cmpUnordered, dl, VT,
2301                                              OpVT);
2302     case ISD::SETUO:  return getBoolConstant(R==APFloat::cmpUnordered, dl, VT,
2303                                              OpVT);
2304     case ISD::SETUEQ: return getBoolConstant(R==APFloat::cmpUnordered ||
2305                                              R==APFloat::cmpEqual, dl, VT,
2306                                              OpVT);
2307     case ISD::SETUNE: return getBoolConstant(R!=APFloat::cmpEqual, dl, VT,
2308                                              OpVT);
2309     case ISD::SETULT: return getBoolConstant(R==APFloat::cmpUnordered ||
2310                                              R==APFloat::cmpLessThan, dl, VT,
2311                                              OpVT);
2312     case ISD::SETUGT: return getBoolConstant(R==APFloat::cmpGreaterThan ||
2313                                              R==APFloat::cmpUnordered, dl, VT,
2314                                              OpVT);
2315     case ISD::SETULE: return getBoolConstant(R!=APFloat::cmpGreaterThan, dl,
2316                                              VT, OpVT);
2317     case ISD::SETUGE: return getBoolConstant(R!=APFloat::cmpLessThan, dl, VT,
2318                                              OpVT);
2319     }
2320   } else if (N1CFP && OpVT.isSimple() && !N2.isUndef()) {
2321     // Ensure that the constant occurs on the RHS.
2322     ISD::CondCode SwappedCond = ISD::getSetCCSwappedOperands(Cond);
2323     if (!TLI->isCondCodeLegal(SwappedCond, OpVT.getSimpleVT()))
2324       return SDValue();
2325     return getSetCC(dl, VT, N2, N1, SwappedCond);
2326   } else if ((N2CFP && N2CFP->getValueAPF().isNaN()) ||
2327              (OpVT.isFloatingPoint() && (N1.isUndef() || N2.isUndef()))) {
2328     // If an operand is known to be a nan (or undef that could be a nan), we can
2329     // fold it.
2330     // Choosing NaN for the undef will always make unordered comparison succeed
2331     // and ordered comparison fails.
2332     // Matches behavior in llvm::ConstantFoldCompareInstruction.
2333     switch (ISD::getUnorderedFlavor(Cond)) {
2334     default:
2335       llvm_unreachable("Unknown flavor!");
2336     case 0: // Known false.
2337       return getBoolConstant(false, dl, VT, OpVT);
2338     case 1: // Known true.
2339       return getBoolConstant(true, dl, VT, OpVT);
2340     case 2: // Undefined.
2341       return getUNDEF(VT);
2342     }
2343   }
2344 
2345   // Could not fold it.
2346   return SDValue();
2347 }
2348 
2349 /// See if the specified operand can be simplified with the knowledge that only
2350 /// the bits specified by DemandedBits are used.
2351 /// TODO: really we should be making this into the DAG equivalent of
2352 /// SimplifyMultipleUseDemandedBits and not generate any new nodes.
2353 SDValue SelectionDAG::GetDemandedBits(SDValue V, const APInt &DemandedBits) {
2354   EVT VT = V.getValueType();
2355 
2356   if (VT.isScalableVector())
2357     return SDValue();
2358 
2359   APInt DemandedElts = VT.isVector()
2360                            ? APInt::getAllOnesValue(VT.getVectorNumElements())
2361                            : APInt(1, 1);
2362   return GetDemandedBits(V, DemandedBits, DemandedElts);
2363 }
2364 
2365 /// See if the specified operand can be simplified with the knowledge that only
2366 /// the bits specified by DemandedBits are used in the elements specified by
2367 /// DemandedElts.
2368 /// TODO: really we should be making this into the DAG equivalent of
2369 /// SimplifyMultipleUseDemandedBits and not generate any new nodes.
2370 SDValue SelectionDAG::GetDemandedBits(SDValue V, const APInt &DemandedBits,
2371                                       const APInt &DemandedElts) {
2372   switch (V.getOpcode()) {
2373   default:
2374     return TLI->SimplifyMultipleUseDemandedBits(V, DemandedBits, DemandedElts,
2375                                                 *this, 0);
2376   case ISD::Constant: {
2377     const APInt &CVal = cast<ConstantSDNode>(V)->getAPIntValue();
2378     APInt NewVal = CVal & DemandedBits;
2379     if (NewVal != CVal)
2380       return getConstant(NewVal, SDLoc(V), V.getValueType());
2381     break;
2382   }
2383   case ISD::SRL:
2384     // Only look at single-use SRLs.
2385     if (!V.getNode()->hasOneUse())
2386       break;
2387     if (auto *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
2388       // See if we can recursively simplify the LHS.
2389       unsigned Amt = RHSC->getZExtValue();
2390 
2391       // Watch out for shift count overflow though.
2392       if (Amt >= DemandedBits.getBitWidth())
2393         break;
2394       APInt SrcDemandedBits = DemandedBits << Amt;
2395       if (SDValue SimplifyLHS =
2396               GetDemandedBits(V.getOperand(0), SrcDemandedBits))
2397         return getNode(ISD::SRL, SDLoc(V), V.getValueType(), SimplifyLHS,
2398                        V.getOperand(1));
2399     }
2400     break;
2401   }
2402   return SDValue();
2403 }
2404 
2405 /// SignBitIsZero - Return true if the sign bit of Op is known to be zero.  We
2406 /// use this predicate to simplify operations downstream.
2407 bool SelectionDAG::SignBitIsZero(SDValue Op, unsigned Depth) const {
2408   unsigned BitWidth = Op.getScalarValueSizeInBits();
2409   return MaskedValueIsZero(Op, APInt::getSignMask(BitWidth), Depth);
2410 }
2411 
2412 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero.  We use
2413 /// this predicate to simplify operations downstream.  Mask is known to be zero
2414 /// for bits that V cannot have.
2415 bool SelectionDAG::MaskedValueIsZero(SDValue V, const APInt &Mask,
2416                                      unsigned Depth) const {
2417   return Mask.isSubsetOf(computeKnownBits(V, Depth).Zero);
2418 }
2419 
2420 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero in
2421 /// DemandedElts.  We use this predicate to simplify operations downstream.
2422 /// Mask is known to be zero for bits that V cannot have.
2423 bool SelectionDAG::MaskedValueIsZero(SDValue V, const APInt &Mask,
2424                                      const APInt &DemandedElts,
2425                                      unsigned Depth) const {
2426   return Mask.isSubsetOf(computeKnownBits(V, DemandedElts, Depth).Zero);
2427 }
2428 
2429 /// MaskedValueIsAllOnes - Return true if '(Op & Mask) == Mask'.
2430 bool SelectionDAG::MaskedValueIsAllOnes(SDValue V, const APInt &Mask,
2431                                         unsigned Depth) const {
2432   return Mask.isSubsetOf(computeKnownBits(V, Depth).One);
2433 }
2434 
2435 /// isSplatValue - Return true if the vector V has the same value
2436 /// across all DemandedElts. For scalable vectors it does not make
2437 /// sense to specify which elements are demanded or undefined, therefore
2438 /// they are simply ignored.
2439 bool SelectionDAG::isSplatValue(SDValue V, const APInt &DemandedElts,
2440                                 APInt &UndefElts, unsigned Depth) {
2441   EVT VT = V.getValueType();
2442   assert(VT.isVector() && "Vector type expected");
2443 
2444   if (!VT.isScalableVector() && !DemandedElts)
2445     return false; // No demanded elts, better to assume we don't know anything.
2446 
2447   if (Depth >= MaxRecursionDepth)
2448     return false; // Limit search depth.
2449 
2450   // Deal with some common cases here that work for both fixed and scalable
2451   // vector types.
2452   switch (V.getOpcode()) {
2453   case ISD::SPLAT_VECTOR:
2454     UndefElts = V.getOperand(0).isUndef()
2455                     ? APInt::getAllOnesValue(DemandedElts.getBitWidth())
2456                     : APInt(DemandedElts.getBitWidth(), 0);
2457     return true;
2458   case ISD::ADD:
2459   case ISD::SUB:
2460   case ISD::AND:
2461   case ISD::XOR:
2462   case ISD::OR: {
2463     APInt UndefLHS, UndefRHS;
2464     SDValue LHS = V.getOperand(0);
2465     SDValue RHS = V.getOperand(1);
2466     if (isSplatValue(LHS, DemandedElts, UndefLHS, Depth + 1) &&
2467         isSplatValue(RHS, DemandedElts, UndefRHS, Depth + 1)) {
2468       UndefElts = UndefLHS | UndefRHS;
2469       return true;
2470     }
2471     break;
2472   }
2473   case ISD::ABS:
2474   case ISD::TRUNCATE:
2475   case ISD::SIGN_EXTEND:
2476   case ISD::ZERO_EXTEND:
2477     return isSplatValue(V.getOperand(0), DemandedElts, UndefElts, Depth + 1);
2478   }
2479 
2480   // We don't support other cases than those above for scalable vectors at
2481   // the moment.
2482   if (VT.isScalableVector())
2483     return false;
2484 
2485   unsigned NumElts = VT.getVectorNumElements();
2486   assert(NumElts == DemandedElts.getBitWidth() && "Vector size mismatch");
2487   UndefElts = APInt::getNullValue(NumElts);
2488 
2489   switch (V.getOpcode()) {
2490   case ISD::BUILD_VECTOR: {
2491     SDValue Scl;
2492     for (unsigned i = 0; i != NumElts; ++i) {
2493       SDValue Op = V.getOperand(i);
2494       if (Op.isUndef()) {
2495         UndefElts.setBit(i);
2496         continue;
2497       }
2498       if (!DemandedElts[i])
2499         continue;
2500       if (Scl && Scl != Op)
2501         return false;
2502       Scl = Op;
2503     }
2504     return true;
2505   }
2506   case ISD::VECTOR_SHUFFLE: {
2507     // Check if this is a shuffle node doing a splat.
2508     // TODO: Do we need to handle shuffle(splat, undef, mask)?
2509     int SplatIndex = -1;
2510     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(V)->getMask();
2511     for (int i = 0; i != (int)NumElts; ++i) {
2512       int M = Mask[i];
2513       if (M < 0) {
2514         UndefElts.setBit(i);
2515         continue;
2516       }
2517       if (!DemandedElts[i])
2518         continue;
2519       if (0 <= SplatIndex && SplatIndex != M)
2520         return false;
2521       SplatIndex = M;
2522     }
2523     return true;
2524   }
2525   case ISD::EXTRACT_SUBVECTOR: {
2526     // Offset the demanded elts by the subvector index.
2527     SDValue Src = V.getOperand(0);
2528     // We don't support scalable vectors at the moment.
2529     if (Src.getValueType().isScalableVector())
2530       return false;
2531     uint64_t Idx = V.getConstantOperandVal(1);
2532     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
2533     APInt UndefSrcElts;
2534     APInt DemandedSrcElts = DemandedElts.zextOrSelf(NumSrcElts).shl(Idx);
2535     if (isSplatValue(Src, DemandedSrcElts, UndefSrcElts, Depth + 1)) {
2536       UndefElts = UndefSrcElts.extractBits(NumElts, Idx);
2537       return true;
2538     }
2539     break;
2540   }
2541   }
2542 
2543   return false;
2544 }
2545 
2546 /// Helper wrapper to main isSplatValue function.
2547 bool SelectionDAG::isSplatValue(SDValue V, bool AllowUndefs) {
2548   EVT VT = V.getValueType();
2549   assert(VT.isVector() && "Vector type expected");
2550 
2551   APInt UndefElts;
2552   APInt DemandedElts;
2553 
2554   // For now we don't support this with scalable vectors.
2555   if (!VT.isScalableVector())
2556     DemandedElts = APInt::getAllOnesValue(VT.getVectorNumElements());
2557   return isSplatValue(V, DemandedElts, UndefElts) &&
2558          (AllowUndefs || !UndefElts);
2559 }
2560 
2561 SDValue SelectionDAG::getSplatSourceVector(SDValue V, int &SplatIdx) {
2562   V = peekThroughExtractSubvectors(V);
2563 
2564   EVT VT = V.getValueType();
2565   unsigned Opcode = V.getOpcode();
2566   switch (Opcode) {
2567   default: {
2568     APInt UndefElts;
2569     APInt DemandedElts;
2570 
2571     if (!VT.isScalableVector())
2572       DemandedElts = APInt::getAllOnesValue(VT.getVectorNumElements());
2573 
2574     if (isSplatValue(V, DemandedElts, UndefElts)) {
2575       if (VT.isScalableVector()) {
2576         // DemandedElts and UndefElts are ignored for scalable vectors, since
2577         // the only supported cases are SPLAT_VECTOR nodes.
2578         SplatIdx = 0;
2579       } else {
2580         // Handle case where all demanded elements are UNDEF.
2581         if (DemandedElts.isSubsetOf(UndefElts)) {
2582           SplatIdx = 0;
2583           return getUNDEF(VT);
2584         }
2585         SplatIdx = (UndefElts & DemandedElts).countTrailingOnes();
2586       }
2587       return V;
2588     }
2589     break;
2590   }
2591   case ISD::SPLAT_VECTOR:
2592     SplatIdx = 0;
2593     return V;
2594   case ISD::VECTOR_SHUFFLE: {
2595     if (VT.isScalableVector())
2596       return SDValue();
2597 
2598     // Check if this is a shuffle node doing a splat.
2599     // TODO - remove this and rely purely on SelectionDAG::isSplatValue,
2600     // getTargetVShiftNode currently struggles without the splat source.
2601     auto *SVN = cast<ShuffleVectorSDNode>(V);
2602     if (!SVN->isSplat())
2603       break;
2604     int Idx = SVN->getSplatIndex();
2605     int NumElts = V.getValueType().getVectorNumElements();
2606     SplatIdx = Idx % NumElts;
2607     return V.getOperand(Idx / NumElts);
2608   }
2609   }
2610 
2611   return SDValue();
2612 }
2613 
2614 SDValue SelectionDAG::getSplatValue(SDValue V) {
2615   int SplatIdx;
2616   if (SDValue SrcVector = getSplatSourceVector(V, SplatIdx))
2617     return getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(V),
2618                    SrcVector.getValueType().getScalarType(), SrcVector,
2619                    getVectorIdxConstant(SplatIdx, SDLoc(V)));
2620   return SDValue();
2621 }
2622 
2623 const APInt *
2624 SelectionDAG::getValidShiftAmountConstant(SDValue V,
2625                                           const APInt &DemandedElts) const {
2626   assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL ||
2627           V.getOpcode() == ISD::SRA) &&
2628          "Unknown shift node");
2629   unsigned BitWidth = V.getScalarValueSizeInBits();
2630   if (ConstantSDNode *SA = isConstOrConstSplat(V.getOperand(1), DemandedElts)) {
2631     // Shifting more than the bitwidth is not valid.
2632     const APInt &ShAmt = SA->getAPIntValue();
2633     if (ShAmt.ult(BitWidth))
2634       return &ShAmt;
2635   }
2636   return nullptr;
2637 }
2638 
2639 const APInt *SelectionDAG::getValidMinimumShiftAmountConstant(
2640     SDValue V, const APInt &DemandedElts) const {
2641   assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL ||
2642           V.getOpcode() == ISD::SRA) &&
2643          "Unknown shift node");
2644   if (const APInt *ValidAmt = getValidShiftAmountConstant(V, DemandedElts))
2645     return ValidAmt;
2646   unsigned BitWidth = V.getScalarValueSizeInBits();
2647   auto *BV = dyn_cast<BuildVectorSDNode>(V.getOperand(1));
2648   if (!BV)
2649     return nullptr;
2650   const APInt *MinShAmt = nullptr;
2651   for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
2652     if (!DemandedElts[i])
2653       continue;
2654     auto *SA = dyn_cast<ConstantSDNode>(BV->getOperand(i));
2655     if (!SA)
2656       return nullptr;
2657     // Shifting more than the bitwidth is not valid.
2658     const APInt &ShAmt = SA->getAPIntValue();
2659     if (ShAmt.uge(BitWidth))
2660       return nullptr;
2661     if (MinShAmt && MinShAmt->ule(ShAmt))
2662       continue;
2663     MinShAmt = &ShAmt;
2664   }
2665   return MinShAmt;
2666 }
2667 
2668 const APInt *SelectionDAG::getValidMaximumShiftAmountConstant(
2669     SDValue V, const APInt &DemandedElts) const {
2670   assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL ||
2671           V.getOpcode() == ISD::SRA) &&
2672          "Unknown shift node");
2673   if (const APInt *ValidAmt = getValidShiftAmountConstant(V, DemandedElts))
2674     return ValidAmt;
2675   unsigned BitWidth = V.getScalarValueSizeInBits();
2676   auto *BV = dyn_cast<BuildVectorSDNode>(V.getOperand(1));
2677   if (!BV)
2678     return nullptr;
2679   const APInt *MaxShAmt = nullptr;
2680   for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
2681     if (!DemandedElts[i])
2682       continue;
2683     auto *SA = dyn_cast<ConstantSDNode>(BV->getOperand(i));
2684     if (!SA)
2685       return nullptr;
2686     // Shifting more than the bitwidth is not valid.
2687     const APInt &ShAmt = SA->getAPIntValue();
2688     if (ShAmt.uge(BitWidth))
2689       return nullptr;
2690     if (MaxShAmt && MaxShAmt->uge(ShAmt))
2691       continue;
2692     MaxShAmt = &ShAmt;
2693   }
2694   return MaxShAmt;
2695 }
2696 
2697 /// Determine which bits of Op are known to be either zero or one and return
2698 /// them in Known. For vectors, the known bits are those that are shared by
2699 /// every vector element.
2700 KnownBits SelectionDAG::computeKnownBits(SDValue Op, unsigned Depth) const {
2701   EVT VT = Op.getValueType();
2702 
2703   // TOOD: Until we have a plan for how to represent demanded elements for
2704   // scalable vectors, we can just bail out for now.
2705   if (Op.getValueType().isScalableVector()) {
2706     unsigned BitWidth = Op.getScalarValueSizeInBits();
2707     return KnownBits(BitWidth);
2708   }
2709 
2710   APInt DemandedElts = VT.isVector()
2711                            ? APInt::getAllOnesValue(VT.getVectorNumElements())
2712                            : APInt(1, 1);
2713   return computeKnownBits(Op, DemandedElts, Depth);
2714 }
2715 
2716 /// Determine which bits of Op are known to be either zero or one and return
2717 /// them in Known. The DemandedElts argument allows us to only collect the known
2718 /// bits that are shared by the requested vector elements.
2719 KnownBits SelectionDAG::computeKnownBits(SDValue Op, const APInt &DemandedElts,
2720                                          unsigned Depth) const {
2721   unsigned BitWidth = Op.getScalarValueSizeInBits();
2722 
2723   KnownBits Known(BitWidth);   // Don't know anything.
2724 
2725   // TOOD: Until we have a plan for how to represent demanded elements for
2726   // scalable vectors, we can just bail out for now.
2727   if (Op.getValueType().isScalableVector())
2728     return Known;
2729 
2730   if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
2731     // We know all of the bits for a constant!
2732     return KnownBits::makeConstant(C->getAPIntValue());
2733   }
2734   if (auto *C = dyn_cast<ConstantFPSDNode>(Op)) {
2735     // We know all of the bits for a constant fp!
2736     return KnownBits::makeConstant(C->getValueAPF().bitcastToAPInt());
2737   }
2738 
2739   if (Depth >= MaxRecursionDepth)
2740     return Known;  // Limit search depth.
2741 
2742   KnownBits Known2;
2743   unsigned NumElts = DemandedElts.getBitWidth();
2744   assert((!Op.getValueType().isVector() ||
2745           NumElts == Op.getValueType().getVectorNumElements()) &&
2746          "Unexpected vector size");
2747 
2748   if (!DemandedElts)
2749     return Known;  // No demanded elts, better to assume we don't know anything.
2750 
2751   unsigned Opcode = Op.getOpcode();
2752   switch (Opcode) {
2753   case ISD::BUILD_VECTOR:
2754     // Collect the known bits that are shared by every demanded vector element.
2755     Known.Zero.setAllBits(); Known.One.setAllBits();
2756     for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
2757       if (!DemandedElts[i])
2758         continue;
2759 
2760       SDValue SrcOp = Op.getOperand(i);
2761       Known2 = computeKnownBits(SrcOp, Depth + 1);
2762 
2763       // BUILD_VECTOR can implicitly truncate sources, we must handle this.
2764       if (SrcOp.getValueSizeInBits() != BitWidth) {
2765         assert(SrcOp.getValueSizeInBits() > BitWidth &&
2766                "Expected BUILD_VECTOR implicit truncation");
2767         Known2 = Known2.trunc(BitWidth);
2768       }
2769 
2770       // Known bits are the values that are shared by every demanded element.
2771       Known = KnownBits::commonBits(Known, Known2);
2772 
2773       // If we don't know any bits, early out.
2774       if (Known.isUnknown())
2775         break;
2776     }
2777     break;
2778   case ISD::VECTOR_SHUFFLE: {
2779     // Collect the known bits that are shared by every vector element referenced
2780     // by the shuffle.
2781     APInt DemandedLHS(NumElts, 0), DemandedRHS(NumElts, 0);
2782     Known.Zero.setAllBits(); Known.One.setAllBits();
2783     const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op);
2784     assert(NumElts == SVN->getMask().size() && "Unexpected vector size");
2785     for (unsigned i = 0; i != NumElts; ++i) {
2786       if (!DemandedElts[i])
2787         continue;
2788 
2789       int M = SVN->getMaskElt(i);
2790       if (M < 0) {
2791         // For UNDEF elements, we don't know anything about the common state of
2792         // the shuffle result.
2793         Known.resetAll();
2794         DemandedLHS.clearAllBits();
2795         DemandedRHS.clearAllBits();
2796         break;
2797       }
2798 
2799       if ((unsigned)M < NumElts)
2800         DemandedLHS.setBit((unsigned)M % NumElts);
2801       else
2802         DemandedRHS.setBit((unsigned)M % NumElts);
2803     }
2804     // Known bits are the values that are shared by every demanded element.
2805     if (!!DemandedLHS) {
2806       SDValue LHS = Op.getOperand(0);
2807       Known2 = computeKnownBits(LHS, DemandedLHS, Depth + 1);
2808       Known = KnownBits::commonBits(Known, Known2);
2809     }
2810     // If we don't know any bits, early out.
2811     if (Known.isUnknown())
2812       break;
2813     if (!!DemandedRHS) {
2814       SDValue RHS = Op.getOperand(1);
2815       Known2 = computeKnownBits(RHS, DemandedRHS, Depth + 1);
2816       Known = KnownBits::commonBits(Known, Known2);
2817     }
2818     break;
2819   }
2820   case ISD::CONCAT_VECTORS: {
2821     // Split DemandedElts and test each of the demanded subvectors.
2822     Known.Zero.setAllBits(); Known.One.setAllBits();
2823     EVT SubVectorVT = Op.getOperand(0).getValueType();
2824     unsigned NumSubVectorElts = SubVectorVT.getVectorNumElements();
2825     unsigned NumSubVectors = Op.getNumOperands();
2826     for (unsigned i = 0; i != NumSubVectors; ++i) {
2827       APInt DemandedSub = DemandedElts.lshr(i * NumSubVectorElts);
2828       DemandedSub = DemandedSub.trunc(NumSubVectorElts);
2829       if (!!DemandedSub) {
2830         SDValue Sub = Op.getOperand(i);
2831         Known2 = computeKnownBits(Sub, DemandedSub, Depth + 1);
2832         Known = KnownBits::commonBits(Known, Known2);
2833       }
2834       // If we don't know any bits, early out.
2835       if (Known.isUnknown())
2836         break;
2837     }
2838     break;
2839   }
2840   case ISD::INSERT_SUBVECTOR: {
2841     // Demand any elements from the subvector and the remainder from the src its
2842     // inserted into.
2843     SDValue Src = Op.getOperand(0);
2844     SDValue Sub = Op.getOperand(1);
2845     uint64_t Idx = Op.getConstantOperandVal(2);
2846     unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
2847     APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
2848     APInt DemandedSrcElts = DemandedElts;
2849     DemandedSrcElts.insertBits(APInt::getNullValue(NumSubElts), Idx);
2850 
2851     Known.One.setAllBits();
2852     Known.Zero.setAllBits();
2853     if (!!DemandedSubElts) {
2854       Known = computeKnownBits(Sub, DemandedSubElts, Depth + 1);
2855       if (Known.isUnknown())
2856         break; // early-out.
2857     }
2858     if (!!DemandedSrcElts) {
2859       Known2 = computeKnownBits(Src, DemandedSrcElts, Depth + 1);
2860       Known = KnownBits::commonBits(Known, Known2);
2861     }
2862     break;
2863   }
2864   case ISD::EXTRACT_SUBVECTOR: {
2865     // Offset the demanded elts by the subvector index.
2866     SDValue Src = Op.getOperand(0);
2867     // Bail until we can represent demanded elements for scalable vectors.
2868     if (Src.getValueType().isScalableVector())
2869       break;
2870     uint64_t Idx = Op.getConstantOperandVal(1);
2871     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
2872     APInt DemandedSrcElts = DemandedElts.zextOrSelf(NumSrcElts).shl(Idx);
2873     Known = computeKnownBits(Src, DemandedSrcElts, Depth + 1);
2874     break;
2875   }
2876   case ISD::SCALAR_TO_VECTOR: {
2877     // We know about scalar_to_vector as much as we know about it source,
2878     // which becomes the first element of otherwise unknown vector.
2879     if (DemandedElts != 1)
2880       break;
2881 
2882     SDValue N0 = Op.getOperand(0);
2883     Known = computeKnownBits(N0, Depth + 1);
2884     if (N0.getValueSizeInBits() != BitWidth)
2885       Known = Known.trunc(BitWidth);
2886 
2887     break;
2888   }
2889   case ISD::BITCAST: {
2890     SDValue N0 = Op.getOperand(0);
2891     EVT SubVT = N0.getValueType();
2892     unsigned SubBitWidth = SubVT.getScalarSizeInBits();
2893 
2894     // Ignore bitcasts from unsupported types.
2895     if (!(SubVT.isInteger() || SubVT.isFloatingPoint()))
2896       break;
2897 
2898     // Fast handling of 'identity' bitcasts.
2899     if (BitWidth == SubBitWidth) {
2900       Known = computeKnownBits(N0, DemandedElts, Depth + 1);
2901       break;
2902     }
2903 
2904     bool IsLE = getDataLayout().isLittleEndian();
2905 
2906     // Bitcast 'small element' vector to 'large element' scalar/vector.
2907     if ((BitWidth % SubBitWidth) == 0) {
2908       assert(N0.getValueType().isVector() && "Expected bitcast from vector");
2909 
2910       // Collect known bits for the (larger) output by collecting the known
2911       // bits from each set of sub elements and shift these into place.
2912       // We need to separately call computeKnownBits for each set of
2913       // sub elements as the knownbits for each is likely to be different.
2914       unsigned SubScale = BitWidth / SubBitWidth;
2915       APInt SubDemandedElts(NumElts * SubScale, 0);
2916       for (unsigned i = 0; i != NumElts; ++i)
2917         if (DemandedElts[i])
2918           SubDemandedElts.setBit(i * SubScale);
2919 
2920       for (unsigned i = 0; i != SubScale; ++i) {
2921         Known2 = computeKnownBits(N0, SubDemandedElts.shl(i),
2922                          Depth + 1);
2923         unsigned Shifts = IsLE ? i : SubScale - 1 - i;
2924         Known.One |= Known2.One.zext(BitWidth).shl(SubBitWidth * Shifts);
2925         Known.Zero |= Known2.Zero.zext(BitWidth).shl(SubBitWidth * Shifts);
2926       }
2927     }
2928 
2929     // Bitcast 'large element' scalar/vector to 'small element' vector.
2930     if ((SubBitWidth % BitWidth) == 0) {
2931       assert(Op.getValueType().isVector() && "Expected bitcast to vector");
2932 
2933       // Collect known bits for the (smaller) output by collecting the known
2934       // bits from the overlapping larger input elements and extracting the
2935       // sub sections we actually care about.
2936       unsigned SubScale = SubBitWidth / BitWidth;
2937       APInt SubDemandedElts(NumElts / SubScale, 0);
2938       for (unsigned i = 0; i != NumElts; ++i)
2939         if (DemandedElts[i])
2940           SubDemandedElts.setBit(i / SubScale);
2941 
2942       Known2 = computeKnownBits(N0, SubDemandedElts, Depth + 1);
2943 
2944       Known.Zero.setAllBits(); Known.One.setAllBits();
2945       for (unsigned i = 0; i != NumElts; ++i)
2946         if (DemandedElts[i]) {
2947           unsigned Shifts = IsLE ? i : NumElts - 1 - i;
2948           unsigned Offset = (Shifts % SubScale) * BitWidth;
2949           Known.One &= Known2.One.lshr(Offset).trunc(BitWidth);
2950           Known.Zero &= Known2.Zero.lshr(Offset).trunc(BitWidth);
2951           // If we don't know any bits, early out.
2952           if (Known.isUnknown())
2953             break;
2954         }
2955     }
2956     break;
2957   }
2958   case ISD::AND:
2959     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
2960     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
2961 
2962     Known &= Known2;
2963     break;
2964   case ISD::OR:
2965     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
2966     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
2967 
2968     Known |= Known2;
2969     break;
2970   case ISD::XOR:
2971     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
2972     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
2973 
2974     Known ^= Known2;
2975     break;
2976   case ISD::MUL: {
2977     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
2978     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
2979     Known = KnownBits::computeForMul(Known, Known2);
2980     break;
2981   }
2982   case ISD::UDIV: {
2983     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
2984     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
2985     Known = KnownBits::udiv(Known, Known2);
2986     break;
2987   }
2988   case ISD::SELECT:
2989   case ISD::VSELECT:
2990     Known = computeKnownBits(Op.getOperand(2), DemandedElts, Depth+1);
2991     // If we don't know any bits, early out.
2992     if (Known.isUnknown())
2993       break;
2994     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth+1);
2995 
2996     // Only known if known in both the LHS and RHS.
2997     Known = KnownBits::commonBits(Known, Known2);
2998     break;
2999   case ISD::SELECT_CC:
3000     Known = computeKnownBits(Op.getOperand(3), DemandedElts, Depth+1);
3001     // If we don't know any bits, early out.
3002     if (Known.isUnknown())
3003       break;
3004     Known2 = computeKnownBits(Op.getOperand(2), DemandedElts, Depth+1);
3005 
3006     // Only known if known in both the LHS and RHS.
3007     Known = KnownBits::commonBits(Known, Known2);
3008     break;
3009   case ISD::SMULO:
3010   case ISD::UMULO:
3011   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
3012     if (Op.getResNo() != 1)
3013       break;
3014     // The boolean result conforms to getBooleanContents.
3015     // If we know the result of a setcc has the top bits zero, use this info.
3016     // We know that we have an integer-based boolean since these operations
3017     // are only available for integer.
3018     if (TLI->getBooleanContents(Op.getValueType().isVector(), false) ==
3019             TargetLowering::ZeroOrOneBooleanContent &&
3020         BitWidth > 1)
3021       Known.Zero.setBitsFrom(1);
3022     break;
3023   case ISD::SETCC:
3024   case ISD::STRICT_FSETCC:
3025   case ISD::STRICT_FSETCCS: {
3026     unsigned OpNo = Op->isStrictFPOpcode() ? 1 : 0;
3027     // If we know the result of a setcc has the top bits zero, use this info.
3028     if (TLI->getBooleanContents(Op.getOperand(OpNo).getValueType()) ==
3029             TargetLowering::ZeroOrOneBooleanContent &&
3030         BitWidth > 1)
3031       Known.Zero.setBitsFrom(1);
3032     break;
3033   }
3034   case ISD::SHL:
3035     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3036     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3037     Known = KnownBits::shl(Known, Known2);
3038 
3039     // Minimum shift low bits are known zero.
3040     if (const APInt *ShMinAmt =
3041             getValidMinimumShiftAmountConstant(Op, DemandedElts))
3042       Known.Zero.setLowBits(ShMinAmt->getZExtValue());
3043     break;
3044   case ISD::SRL:
3045     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3046     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3047     Known = KnownBits::lshr(Known, Known2);
3048 
3049     // Minimum shift high bits are known zero.
3050     if (const APInt *ShMinAmt =
3051             getValidMinimumShiftAmountConstant(Op, DemandedElts))
3052       Known.Zero.setHighBits(ShMinAmt->getZExtValue());
3053     break;
3054   case ISD::SRA:
3055     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3056     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3057     Known = KnownBits::ashr(Known, Known2);
3058     // TODO: Add minimum shift high known sign bits.
3059     break;
3060   case ISD::FSHL:
3061   case ISD::FSHR:
3062     if (ConstantSDNode *C = isConstOrConstSplat(Op.getOperand(2), DemandedElts)) {
3063       unsigned Amt = C->getAPIntValue().urem(BitWidth);
3064 
3065       // For fshl, 0-shift returns the 1st arg.
3066       // For fshr, 0-shift returns the 2nd arg.
3067       if (Amt == 0) {
3068         Known = computeKnownBits(Op.getOperand(Opcode == ISD::FSHL ? 0 : 1),
3069                                  DemandedElts, Depth + 1);
3070         break;
3071       }
3072 
3073       // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW)))
3074       // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW))
3075       Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3076       Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3077       if (Opcode == ISD::FSHL) {
3078         Known.One <<= Amt;
3079         Known.Zero <<= Amt;
3080         Known2.One.lshrInPlace(BitWidth - Amt);
3081         Known2.Zero.lshrInPlace(BitWidth - Amt);
3082       } else {
3083         Known.One <<= BitWidth - Amt;
3084         Known.Zero <<= BitWidth - Amt;
3085         Known2.One.lshrInPlace(Amt);
3086         Known2.Zero.lshrInPlace(Amt);
3087       }
3088       Known.One |= Known2.One;
3089       Known.Zero |= Known2.Zero;
3090     }
3091     break;
3092   case ISD::SIGN_EXTEND_INREG: {
3093     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3094     EVT EVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
3095     Known = Known.sextInReg(EVT.getScalarSizeInBits());
3096     break;
3097   }
3098   case ISD::CTTZ:
3099   case ISD::CTTZ_ZERO_UNDEF: {
3100     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3101     // If we have a known 1, its position is our upper bound.
3102     unsigned PossibleTZ = Known2.countMaxTrailingZeros();
3103     unsigned LowBits = Log2_32(PossibleTZ) + 1;
3104     Known.Zero.setBitsFrom(LowBits);
3105     break;
3106   }
3107   case ISD::CTLZ:
3108   case ISD::CTLZ_ZERO_UNDEF: {
3109     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3110     // If we have a known 1, its position is our upper bound.
3111     unsigned PossibleLZ = Known2.countMaxLeadingZeros();
3112     unsigned LowBits = Log2_32(PossibleLZ) + 1;
3113     Known.Zero.setBitsFrom(LowBits);
3114     break;
3115   }
3116   case ISD::CTPOP: {
3117     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3118     // If we know some of the bits are zero, they can't be one.
3119     unsigned PossibleOnes = Known2.countMaxPopulation();
3120     Known.Zero.setBitsFrom(Log2_32(PossibleOnes) + 1);
3121     break;
3122   }
3123   case ISD::PARITY: {
3124     // Parity returns 0 everywhere but the LSB.
3125     Known.Zero.setBitsFrom(1);
3126     break;
3127   }
3128   case ISD::LOAD: {
3129     LoadSDNode *LD = cast<LoadSDNode>(Op);
3130     const Constant *Cst = TLI->getTargetConstantFromLoad(LD);
3131     if (ISD::isNON_EXTLoad(LD) && Cst) {
3132       // Determine any common known bits from the loaded constant pool value.
3133       Type *CstTy = Cst->getType();
3134       if ((NumElts * BitWidth) == CstTy->getPrimitiveSizeInBits()) {
3135         // If its a vector splat, then we can (quickly) reuse the scalar path.
3136         // NOTE: We assume all elements match and none are UNDEF.
3137         if (CstTy->isVectorTy()) {
3138           if (const Constant *Splat = Cst->getSplatValue()) {
3139             Cst = Splat;
3140             CstTy = Cst->getType();
3141           }
3142         }
3143         // TODO - do we need to handle different bitwidths?
3144         if (CstTy->isVectorTy() && BitWidth == CstTy->getScalarSizeInBits()) {
3145           // Iterate across all vector elements finding common known bits.
3146           Known.One.setAllBits();
3147           Known.Zero.setAllBits();
3148           for (unsigned i = 0; i != NumElts; ++i) {
3149             if (!DemandedElts[i])
3150               continue;
3151             if (Constant *Elt = Cst->getAggregateElement(i)) {
3152               if (auto *CInt = dyn_cast<ConstantInt>(Elt)) {
3153                 const APInt &Value = CInt->getValue();
3154                 Known.One &= Value;
3155                 Known.Zero &= ~Value;
3156                 continue;
3157               }
3158               if (auto *CFP = dyn_cast<ConstantFP>(Elt)) {
3159                 APInt Value = CFP->getValueAPF().bitcastToAPInt();
3160                 Known.One &= Value;
3161                 Known.Zero &= ~Value;
3162                 continue;
3163               }
3164             }
3165             Known.One.clearAllBits();
3166             Known.Zero.clearAllBits();
3167             break;
3168           }
3169         } else if (BitWidth == CstTy->getPrimitiveSizeInBits()) {
3170           if (auto *CInt = dyn_cast<ConstantInt>(Cst)) {
3171             Known = KnownBits::makeConstant(CInt->getValue());
3172           } else if (auto *CFP = dyn_cast<ConstantFP>(Cst)) {
3173             Known =
3174                 KnownBits::makeConstant(CFP->getValueAPF().bitcastToAPInt());
3175           }
3176         }
3177       }
3178     } else if (ISD::isZEXTLoad(Op.getNode()) && Op.getResNo() == 0) {
3179       // If this is a ZEXTLoad and we are looking at the loaded value.
3180       EVT VT = LD->getMemoryVT();
3181       unsigned MemBits = VT.getScalarSizeInBits();
3182       Known.Zero.setBitsFrom(MemBits);
3183     } else if (const MDNode *Ranges = LD->getRanges()) {
3184       if (LD->getExtensionType() == ISD::NON_EXTLOAD)
3185         computeKnownBitsFromRangeMetadata(*Ranges, Known);
3186     }
3187     break;
3188   }
3189   case ISD::ZERO_EXTEND_VECTOR_INREG: {
3190     EVT InVT = Op.getOperand(0).getValueType();
3191     APInt InDemandedElts = DemandedElts.zextOrSelf(InVT.getVectorNumElements());
3192     Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1);
3193     Known = Known.zext(BitWidth);
3194     break;
3195   }
3196   case ISD::ZERO_EXTEND: {
3197     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3198     Known = Known.zext(BitWidth);
3199     break;
3200   }
3201   case ISD::SIGN_EXTEND_VECTOR_INREG: {
3202     EVT InVT = Op.getOperand(0).getValueType();
3203     APInt InDemandedElts = DemandedElts.zextOrSelf(InVT.getVectorNumElements());
3204     Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1);
3205     // If the sign bit is known to be zero or one, then sext will extend
3206     // it to the top bits, else it will just zext.
3207     Known = Known.sext(BitWidth);
3208     break;
3209   }
3210   case ISD::SIGN_EXTEND: {
3211     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3212     // If the sign bit is known to be zero or one, then sext will extend
3213     // it to the top bits, else it will just zext.
3214     Known = Known.sext(BitWidth);
3215     break;
3216   }
3217   case ISD::ANY_EXTEND_VECTOR_INREG: {
3218     EVT InVT = Op.getOperand(0).getValueType();
3219     APInt InDemandedElts = DemandedElts.zextOrSelf(InVT.getVectorNumElements());
3220     Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1);
3221     Known = Known.anyext(BitWidth);
3222     break;
3223   }
3224   case ISD::ANY_EXTEND: {
3225     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3226     Known = Known.anyext(BitWidth);
3227     break;
3228   }
3229   case ISD::TRUNCATE: {
3230     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3231     Known = Known.trunc(BitWidth);
3232     break;
3233   }
3234   case ISD::AssertZext: {
3235     EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
3236     APInt InMask = APInt::getLowBitsSet(BitWidth, VT.getSizeInBits());
3237     Known = computeKnownBits(Op.getOperand(0), Depth+1);
3238     Known.Zero |= (~InMask);
3239     Known.One  &= (~Known.Zero);
3240     break;
3241   }
3242   case ISD::AssertAlign: {
3243     unsigned LogOfAlign = Log2(cast<AssertAlignSDNode>(Op)->getAlign());
3244     assert(LogOfAlign != 0);
3245     // If a node is guaranteed to be aligned, set low zero bits accordingly as
3246     // well as clearing one bits.
3247     Known.Zero.setLowBits(LogOfAlign);
3248     Known.One.clearLowBits(LogOfAlign);
3249     break;
3250   }
3251   case ISD::FGETSIGN:
3252     // All bits are zero except the low bit.
3253     Known.Zero.setBitsFrom(1);
3254     break;
3255   case ISD::USUBO:
3256   case ISD::SSUBO:
3257     if (Op.getResNo() == 1) {
3258       // If we know the result of a setcc has the top bits zero, use this info.
3259       if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) ==
3260               TargetLowering::ZeroOrOneBooleanContent &&
3261           BitWidth > 1)
3262         Known.Zero.setBitsFrom(1);
3263       break;
3264     }
3265     LLVM_FALLTHROUGH;
3266   case ISD::SUB:
3267   case ISD::SUBC: {
3268     assert(Op.getResNo() == 0 &&
3269            "We only compute knownbits for the difference here.");
3270 
3271     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3272     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3273     Known = KnownBits::computeForAddSub(/* Add */ false, /* NSW */ false,
3274                                         Known, Known2);
3275     break;
3276   }
3277   case ISD::UADDO:
3278   case ISD::SADDO:
3279   case ISD::ADDCARRY:
3280     if (Op.getResNo() == 1) {
3281       // If we know the result of a setcc has the top bits zero, use this info.
3282       if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) ==
3283               TargetLowering::ZeroOrOneBooleanContent &&
3284           BitWidth > 1)
3285         Known.Zero.setBitsFrom(1);
3286       break;
3287     }
3288     LLVM_FALLTHROUGH;
3289   case ISD::ADD:
3290   case ISD::ADDC:
3291   case ISD::ADDE: {
3292     assert(Op.getResNo() == 0 && "We only compute knownbits for the sum here.");
3293 
3294     // With ADDE and ADDCARRY, a carry bit may be added in.
3295     KnownBits Carry(1);
3296     if (Opcode == ISD::ADDE)
3297       // Can't track carry from glue, set carry to unknown.
3298       Carry.resetAll();
3299     else if (Opcode == ISD::ADDCARRY)
3300       // TODO: Compute known bits for the carry operand. Not sure if it is worth
3301       // the trouble (how often will we find a known carry bit). And I haven't
3302       // tested this very much yet, but something like this might work:
3303       //   Carry = computeKnownBits(Op.getOperand(2), DemandedElts, Depth + 1);
3304       //   Carry = Carry.zextOrTrunc(1, false);
3305       Carry.resetAll();
3306     else
3307       Carry.setAllZero();
3308 
3309     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3310     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3311     Known = KnownBits::computeForAddCarry(Known, Known2, Carry);
3312     break;
3313   }
3314   case ISD::SREM: {
3315     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3316     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3317     Known = KnownBits::srem(Known, Known2);
3318     break;
3319   }
3320   case ISD::UREM: {
3321     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3322     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3323     Known = KnownBits::urem(Known, Known2);
3324     break;
3325   }
3326   case ISD::EXTRACT_ELEMENT: {
3327     Known = computeKnownBits(Op.getOperand(0), Depth+1);
3328     const unsigned Index = Op.getConstantOperandVal(1);
3329     const unsigned EltBitWidth = Op.getValueSizeInBits();
3330 
3331     // Remove low part of known bits mask
3332     Known.Zero = Known.Zero.getHiBits(Known.getBitWidth() - Index * EltBitWidth);
3333     Known.One = Known.One.getHiBits(Known.getBitWidth() - Index * EltBitWidth);
3334 
3335     // Remove high part of known bit mask
3336     Known = Known.trunc(EltBitWidth);
3337     break;
3338   }
3339   case ISD::EXTRACT_VECTOR_ELT: {
3340     SDValue InVec = Op.getOperand(0);
3341     SDValue EltNo = Op.getOperand(1);
3342     EVT VecVT = InVec.getValueType();
3343     // computeKnownBits not yet implemented for scalable vectors.
3344     if (VecVT.isScalableVector())
3345       break;
3346     const unsigned EltBitWidth = VecVT.getScalarSizeInBits();
3347     const unsigned NumSrcElts = VecVT.getVectorNumElements();
3348 
3349     // If BitWidth > EltBitWidth the value is anyext:ed. So we do not know
3350     // anything about the extended bits.
3351     if (BitWidth > EltBitWidth)
3352       Known = Known.trunc(EltBitWidth);
3353 
3354     // If we know the element index, just demand that vector element, else for
3355     // an unknown element index, ignore DemandedElts and demand them all.
3356     APInt DemandedSrcElts = APInt::getAllOnesValue(NumSrcElts);
3357     auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
3358     if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts))
3359       DemandedSrcElts =
3360           APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue());
3361 
3362     Known = computeKnownBits(InVec, DemandedSrcElts, Depth + 1);
3363     if (BitWidth > EltBitWidth)
3364       Known = Known.anyext(BitWidth);
3365     break;
3366   }
3367   case ISD::INSERT_VECTOR_ELT: {
3368     // If we know the element index, split the demand between the
3369     // source vector and the inserted element, otherwise assume we need
3370     // the original demanded vector elements and the value.
3371     SDValue InVec = Op.getOperand(0);
3372     SDValue InVal = Op.getOperand(1);
3373     SDValue EltNo = Op.getOperand(2);
3374     bool DemandedVal = true;
3375     APInt DemandedVecElts = DemandedElts;
3376     auto *CEltNo = dyn_cast<ConstantSDNode>(EltNo);
3377     if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) {
3378       unsigned EltIdx = CEltNo->getZExtValue();
3379       DemandedVal = !!DemandedElts[EltIdx];
3380       DemandedVecElts.clearBit(EltIdx);
3381     }
3382     Known.One.setAllBits();
3383     Known.Zero.setAllBits();
3384     if (DemandedVal) {
3385       Known2 = computeKnownBits(InVal, Depth + 1);
3386       Known = KnownBits::commonBits(Known, Known2.zextOrTrunc(BitWidth));
3387     }
3388     if (!!DemandedVecElts) {
3389       Known2 = computeKnownBits(InVec, DemandedVecElts, Depth + 1);
3390       Known = KnownBits::commonBits(Known, Known2);
3391     }
3392     break;
3393   }
3394   case ISD::BITREVERSE: {
3395     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3396     Known = Known2.reverseBits();
3397     break;
3398   }
3399   case ISD::BSWAP: {
3400     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3401     Known = Known2.byteSwap();
3402     break;
3403   }
3404   case ISD::ABS: {
3405     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3406     Known = Known2.abs();
3407     break;
3408   }
3409   case ISD::USUBSAT: {
3410     // The result of usubsat will never be larger than the LHS.
3411     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3412     Known.Zero.setHighBits(Known2.countMinLeadingZeros());
3413     break;
3414   }
3415   case ISD::UMIN: {
3416     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3417     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3418     Known = KnownBits::umin(Known, Known2);
3419     break;
3420   }
3421   case ISD::UMAX: {
3422     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3423     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3424     Known = KnownBits::umax(Known, Known2);
3425     break;
3426   }
3427   case ISD::SMIN:
3428   case ISD::SMAX: {
3429     // If we have a clamp pattern, we know that the number of sign bits will be
3430     // the minimum of the clamp min/max range.
3431     bool IsMax = (Opcode == ISD::SMAX);
3432     ConstantSDNode *CstLow = nullptr, *CstHigh = nullptr;
3433     if ((CstLow = isConstOrConstSplat(Op.getOperand(1), DemandedElts)))
3434       if (Op.getOperand(0).getOpcode() == (IsMax ? ISD::SMIN : ISD::SMAX))
3435         CstHigh =
3436             isConstOrConstSplat(Op.getOperand(0).getOperand(1), DemandedElts);
3437     if (CstLow && CstHigh) {
3438       if (!IsMax)
3439         std::swap(CstLow, CstHigh);
3440 
3441       const APInt &ValueLow = CstLow->getAPIntValue();
3442       const APInt &ValueHigh = CstHigh->getAPIntValue();
3443       if (ValueLow.sle(ValueHigh)) {
3444         unsigned LowSignBits = ValueLow.getNumSignBits();
3445         unsigned HighSignBits = ValueHigh.getNumSignBits();
3446         unsigned MinSignBits = std::min(LowSignBits, HighSignBits);
3447         if (ValueLow.isNegative() && ValueHigh.isNegative()) {
3448           Known.One.setHighBits(MinSignBits);
3449           break;
3450         }
3451         if (ValueLow.isNonNegative() && ValueHigh.isNonNegative()) {
3452           Known.Zero.setHighBits(MinSignBits);
3453           break;
3454         }
3455       }
3456     }
3457 
3458     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3459     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3460     if (IsMax)
3461       Known = KnownBits::smax(Known, Known2);
3462     else
3463       Known = KnownBits::smin(Known, Known2);
3464     break;
3465   }
3466   case ISD::FrameIndex:
3467   case ISD::TargetFrameIndex:
3468     TLI->computeKnownBitsForFrameIndex(cast<FrameIndexSDNode>(Op)->getIndex(),
3469                                        Known, getMachineFunction());
3470     break;
3471 
3472   default:
3473     if (Opcode < ISD::BUILTIN_OP_END)
3474       break;
3475     LLVM_FALLTHROUGH;
3476   case ISD::INTRINSIC_WO_CHAIN:
3477   case ISD::INTRINSIC_W_CHAIN:
3478   case ISD::INTRINSIC_VOID:
3479     // Allow the target to implement this method for its nodes.
3480     TLI->computeKnownBitsForTargetNode(Op, Known, DemandedElts, *this, Depth);
3481     break;
3482   }
3483 
3484   assert(!Known.hasConflict() && "Bits known to be one AND zero?");
3485   return Known;
3486 }
3487 
3488 SelectionDAG::OverflowKind SelectionDAG::computeOverflowKind(SDValue N0,
3489                                                              SDValue N1) const {
3490   // X + 0 never overflow
3491   if (isNullConstant(N1))
3492     return OFK_Never;
3493 
3494   KnownBits N1Known = computeKnownBits(N1);
3495   if (N1Known.Zero.getBoolValue()) {
3496     KnownBits N0Known = computeKnownBits(N0);
3497 
3498     bool overflow;
3499     (void)N0Known.getMaxValue().uadd_ov(N1Known.getMaxValue(), overflow);
3500     if (!overflow)
3501       return OFK_Never;
3502   }
3503 
3504   // mulhi + 1 never overflow
3505   if (N0.getOpcode() == ISD::UMUL_LOHI && N0.getResNo() == 1 &&
3506       (N1Known.getMaxValue() & 0x01) == N1Known.getMaxValue())
3507     return OFK_Never;
3508 
3509   if (N1.getOpcode() == ISD::UMUL_LOHI && N1.getResNo() == 1) {
3510     KnownBits N0Known = computeKnownBits(N0);
3511 
3512     if ((N0Known.getMaxValue() & 0x01) == N0Known.getMaxValue())
3513       return OFK_Never;
3514   }
3515 
3516   return OFK_Sometime;
3517 }
3518 
3519 bool SelectionDAG::isKnownToBeAPowerOfTwo(SDValue Val) const {
3520   EVT OpVT = Val.getValueType();
3521   unsigned BitWidth = OpVT.getScalarSizeInBits();
3522 
3523   // Is the constant a known power of 2?
3524   if (ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Val))
3525     return Const->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2();
3526 
3527   // A left-shift of a constant one will have exactly one bit set because
3528   // shifting the bit off the end is undefined.
3529   if (Val.getOpcode() == ISD::SHL) {
3530     auto *C = isConstOrConstSplat(Val.getOperand(0));
3531     if (C && C->getAPIntValue() == 1)
3532       return true;
3533   }
3534 
3535   // Similarly, a logical right-shift of a constant sign-bit will have exactly
3536   // one bit set.
3537   if (Val.getOpcode() == ISD::SRL) {
3538     auto *C = isConstOrConstSplat(Val.getOperand(0));
3539     if (C && C->getAPIntValue().isSignMask())
3540       return true;
3541   }
3542 
3543   // Are all operands of a build vector constant powers of two?
3544   if (Val.getOpcode() == ISD::BUILD_VECTOR)
3545     if (llvm::all_of(Val->ops(), [BitWidth](SDValue E) {
3546           if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(E))
3547             return C->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2();
3548           return false;
3549         }))
3550       return true;
3551 
3552   // More could be done here, though the above checks are enough
3553   // to handle some common cases.
3554 
3555   // Fall back to computeKnownBits to catch other known cases.
3556   KnownBits Known = computeKnownBits(Val);
3557   return (Known.countMaxPopulation() == 1) && (Known.countMinPopulation() == 1);
3558 }
3559 
3560 unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, unsigned Depth) const {
3561   EVT VT = Op.getValueType();
3562 
3563   // TODO: Assume we don't know anything for now.
3564   if (VT.isScalableVector())
3565     return 1;
3566 
3567   APInt DemandedElts = VT.isVector()
3568                            ? APInt::getAllOnesValue(VT.getVectorNumElements())
3569                            : APInt(1, 1);
3570   return ComputeNumSignBits(Op, DemandedElts, Depth);
3571 }
3572 
3573 unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, const APInt &DemandedElts,
3574                                           unsigned Depth) const {
3575   EVT VT = Op.getValueType();
3576   assert((VT.isInteger() || VT.isFloatingPoint()) && "Invalid VT!");
3577   unsigned VTBits = VT.getScalarSizeInBits();
3578   unsigned NumElts = DemandedElts.getBitWidth();
3579   unsigned Tmp, Tmp2;
3580   unsigned FirstAnswer = 1;
3581 
3582   if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
3583     const APInt &Val = C->getAPIntValue();
3584     return Val.getNumSignBits();
3585   }
3586 
3587   if (Depth >= MaxRecursionDepth)
3588     return 1;  // Limit search depth.
3589 
3590   if (!DemandedElts || VT.isScalableVector())
3591     return 1;  // No demanded elts, better to assume we don't know anything.
3592 
3593   unsigned Opcode = Op.getOpcode();
3594   switch (Opcode) {
3595   default: break;
3596   case ISD::AssertSext:
3597     Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
3598     return VTBits-Tmp+1;
3599   case ISD::AssertZext:
3600     Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
3601     return VTBits-Tmp;
3602 
3603   case ISD::BUILD_VECTOR:
3604     Tmp = VTBits;
3605     for (unsigned i = 0, e = Op.getNumOperands(); (i < e) && (Tmp > 1); ++i) {
3606       if (!DemandedElts[i])
3607         continue;
3608 
3609       SDValue SrcOp = Op.getOperand(i);
3610       Tmp2 = ComputeNumSignBits(SrcOp, Depth + 1);
3611 
3612       // BUILD_VECTOR can implicitly truncate sources, we must handle this.
3613       if (SrcOp.getValueSizeInBits() != VTBits) {
3614         assert(SrcOp.getValueSizeInBits() > VTBits &&
3615                "Expected BUILD_VECTOR implicit truncation");
3616         unsigned ExtraBits = SrcOp.getValueSizeInBits() - VTBits;
3617         Tmp2 = (Tmp2 > ExtraBits ? Tmp2 - ExtraBits : 1);
3618       }
3619       Tmp = std::min(Tmp, Tmp2);
3620     }
3621     return Tmp;
3622 
3623   case ISD::VECTOR_SHUFFLE: {
3624     // Collect the minimum number of sign bits that are shared by every vector
3625     // element referenced by the shuffle.
3626     APInt DemandedLHS(NumElts, 0), DemandedRHS(NumElts, 0);
3627     const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op);
3628     assert(NumElts == SVN->getMask().size() && "Unexpected vector size");
3629     for (unsigned i = 0; i != NumElts; ++i) {
3630       int M = SVN->getMaskElt(i);
3631       if (!DemandedElts[i])
3632         continue;
3633       // For UNDEF elements, we don't know anything about the common state of
3634       // the shuffle result.
3635       if (M < 0)
3636         return 1;
3637       if ((unsigned)M < NumElts)
3638         DemandedLHS.setBit((unsigned)M % NumElts);
3639       else
3640         DemandedRHS.setBit((unsigned)M % NumElts);
3641     }
3642     Tmp = std::numeric_limits<unsigned>::max();
3643     if (!!DemandedLHS)
3644       Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedLHS, Depth + 1);
3645     if (!!DemandedRHS) {
3646       Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedRHS, Depth + 1);
3647       Tmp = std::min(Tmp, Tmp2);
3648     }
3649     // If we don't know anything, early out and try computeKnownBits fall-back.
3650     if (Tmp == 1)
3651       break;
3652     assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
3653     return Tmp;
3654   }
3655 
3656   case ISD::BITCAST: {
3657     SDValue N0 = Op.getOperand(0);
3658     EVT SrcVT = N0.getValueType();
3659     unsigned SrcBits = SrcVT.getScalarSizeInBits();
3660 
3661     // Ignore bitcasts from unsupported types..
3662     if (!(SrcVT.isInteger() || SrcVT.isFloatingPoint()))
3663       break;
3664 
3665     // Fast handling of 'identity' bitcasts.
3666     if (VTBits == SrcBits)
3667       return ComputeNumSignBits(N0, DemandedElts, Depth + 1);
3668 
3669     bool IsLE = getDataLayout().isLittleEndian();
3670 
3671     // Bitcast 'large element' scalar/vector to 'small element' vector.
3672     if ((SrcBits % VTBits) == 0) {
3673       assert(VT.isVector() && "Expected bitcast to vector");
3674 
3675       unsigned Scale = SrcBits / VTBits;
3676       APInt SrcDemandedElts(NumElts / Scale, 0);
3677       for (unsigned i = 0; i != NumElts; ++i)
3678         if (DemandedElts[i])
3679           SrcDemandedElts.setBit(i / Scale);
3680 
3681       // Fast case - sign splat can be simply split across the small elements.
3682       Tmp = ComputeNumSignBits(N0, SrcDemandedElts, Depth + 1);
3683       if (Tmp == SrcBits)
3684         return VTBits;
3685 
3686       // Slow case - determine how far the sign extends into each sub-element.
3687       Tmp2 = VTBits;
3688       for (unsigned i = 0; i != NumElts; ++i)
3689         if (DemandedElts[i]) {
3690           unsigned SubOffset = i % Scale;
3691           SubOffset = (IsLE ? ((Scale - 1) - SubOffset) : SubOffset);
3692           SubOffset = SubOffset * VTBits;
3693           if (Tmp <= SubOffset)
3694             return 1;
3695           Tmp2 = std::min(Tmp2, Tmp - SubOffset);
3696         }
3697       return Tmp2;
3698     }
3699     break;
3700   }
3701 
3702   case ISD::SIGN_EXTEND:
3703     Tmp = VTBits - Op.getOperand(0).getScalarValueSizeInBits();
3704     return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1) + Tmp;
3705   case ISD::SIGN_EXTEND_INREG:
3706     // Max of the input and what this extends.
3707     Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getScalarSizeInBits();
3708     Tmp = VTBits-Tmp+1;
3709     Tmp2 = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1);
3710     return std::max(Tmp, Tmp2);
3711   case ISD::SIGN_EXTEND_VECTOR_INREG: {
3712     SDValue Src = Op.getOperand(0);
3713     EVT SrcVT = Src.getValueType();
3714     APInt DemandedSrcElts = DemandedElts.zextOrSelf(SrcVT.getVectorNumElements());
3715     Tmp = VTBits - SrcVT.getScalarSizeInBits();
3716     return ComputeNumSignBits(Src, DemandedSrcElts, Depth+1) + Tmp;
3717   }
3718   case ISD::SRA:
3719     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
3720     // SRA X, C -> adds C sign bits.
3721     if (const APInt *ShAmt =
3722             getValidMinimumShiftAmountConstant(Op, DemandedElts))
3723       Tmp = std::min<uint64_t>(Tmp + ShAmt->getZExtValue(), VTBits);
3724     return Tmp;
3725   case ISD::SHL:
3726     if (const APInt *ShAmt =
3727             getValidMaximumShiftAmountConstant(Op, DemandedElts)) {
3728       // shl destroys sign bits, ensure it doesn't shift out all sign bits.
3729       Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
3730       if (ShAmt->ult(Tmp))
3731         return Tmp - ShAmt->getZExtValue();
3732     }
3733     break;
3734   case ISD::AND:
3735   case ISD::OR:
3736   case ISD::XOR:    // NOT is handled here.
3737     // Logical binary ops preserve the number of sign bits at the worst.
3738     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1);
3739     if (Tmp != 1) {
3740       Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth+1);
3741       FirstAnswer = std::min(Tmp, Tmp2);
3742       // We computed what we know about the sign bits as our first
3743       // answer. Now proceed to the generic code that uses
3744       // computeKnownBits, and pick whichever answer is better.
3745     }
3746     break;
3747 
3748   case ISD::SELECT:
3749   case ISD::VSELECT:
3750     Tmp = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth+1);
3751     if (Tmp == 1) return 1;  // Early out.
3752     Tmp2 = ComputeNumSignBits(Op.getOperand(2), DemandedElts, Depth+1);
3753     return std::min(Tmp, Tmp2);
3754   case ISD::SELECT_CC:
3755     Tmp = ComputeNumSignBits(Op.getOperand(2), DemandedElts, Depth+1);
3756     if (Tmp == 1) return 1;  // Early out.
3757     Tmp2 = ComputeNumSignBits(Op.getOperand(3), DemandedElts, Depth+1);
3758     return std::min(Tmp, Tmp2);
3759 
3760   case ISD::SMIN:
3761   case ISD::SMAX: {
3762     // If we have a clamp pattern, we know that the number of sign bits will be
3763     // the minimum of the clamp min/max range.
3764     bool IsMax = (Opcode == ISD::SMAX);
3765     ConstantSDNode *CstLow = nullptr, *CstHigh = nullptr;
3766     if ((CstLow = isConstOrConstSplat(Op.getOperand(1), DemandedElts)))
3767       if (Op.getOperand(0).getOpcode() == (IsMax ? ISD::SMIN : ISD::SMAX))
3768         CstHigh =
3769             isConstOrConstSplat(Op.getOperand(0).getOperand(1), DemandedElts);
3770     if (CstLow && CstHigh) {
3771       if (!IsMax)
3772         std::swap(CstLow, CstHigh);
3773       if (CstLow->getAPIntValue().sle(CstHigh->getAPIntValue())) {
3774         Tmp = CstLow->getAPIntValue().getNumSignBits();
3775         Tmp2 = CstHigh->getAPIntValue().getNumSignBits();
3776         return std::min(Tmp, Tmp2);
3777       }
3778     }
3779 
3780     // Fallback - just get the minimum number of sign bits of the operands.
3781     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
3782     if (Tmp == 1)
3783       return 1;  // Early out.
3784     Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
3785     return std::min(Tmp, Tmp2);
3786   }
3787   case ISD::UMIN:
3788   case ISD::UMAX:
3789     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
3790     if (Tmp == 1)
3791       return 1;  // Early out.
3792     Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
3793     return std::min(Tmp, Tmp2);
3794   case ISD::SADDO:
3795   case ISD::UADDO:
3796   case ISD::SSUBO:
3797   case ISD::USUBO:
3798   case ISD::SMULO:
3799   case ISD::UMULO:
3800     if (Op.getResNo() != 1)
3801       break;
3802     // The boolean result conforms to getBooleanContents.  Fall through.
3803     // If setcc returns 0/-1, all bits are sign bits.
3804     // We know that we have an integer-based boolean since these operations
3805     // are only available for integer.
3806     if (TLI->getBooleanContents(VT.isVector(), false) ==
3807         TargetLowering::ZeroOrNegativeOneBooleanContent)
3808       return VTBits;
3809     break;
3810   case ISD::SETCC:
3811   case ISD::STRICT_FSETCC:
3812   case ISD::STRICT_FSETCCS: {
3813     unsigned OpNo = Op->isStrictFPOpcode() ? 1 : 0;
3814     // If setcc returns 0/-1, all bits are sign bits.
3815     if (TLI->getBooleanContents(Op.getOperand(OpNo).getValueType()) ==
3816         TargetLowering::ZeroOrNegativeOneBooleanContent)
3817       return VTBits;
3818     break;
3819   }
3820   case ISD::ROTL:
3821   case ISD::ROTR:
3822     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
3823 
3824     // If we're rotating an 0/-1 value, then it stays an 0/-1 value.
3825     if (Tmp == VTBits)
3826       return VTBits;
3827 
3828     if (ConstantSDNode *C =
3829             isConstOrConstSplat(Op.getOperand(1), DemandedElts)) {
3830       unsigned RotAmt = C->getAPIntValue().urem(VTBits);
3831 
3832       // Handle rotate right by N like a rotate left by 32-N.
3833       if (Opcode == ISD::ROTR)
3834         RotAmt = (VTBits - RotAmt) % VTBits;
3835 
3836       // If we aren't rotating out all of the known-in sign bits, return the
3837       // number that are left.  This handles rotl(sext(x), 1) for example.
3838       if (Tmp > (RotAmt + 1)) return (Tmp - RotAmt);
3839     }
3840     break;
3841   case ISD::ADD:
3842   case ISD::ADDC:
3843     // Add can have at most one carry bit.  Thus we know that the output
3844     // is, at worst, one more bit than the inputs.
3845     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
3846     if (Tmp == 1) return 1; // Early out.
3847 
3848     // Special case decrementing a value (ADD X, -1):
3849     if (ConstantSDNode *CRHS =
3850             isConstOrConstSplat(Op.getOperand(1), DemandedElts))
3851       if (CRHS->isAllOnesValue()) {
3852         KnownBits Known =
3853             computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3854 
3855         // If the input is known to be 0 or 1, the output is 0/-1, which is all
3856         // sign bits set.
3857         if ((Known.Zero | 1).isAllOnesValue())
3858           return VTBits;
3859 
3860         // If we are subtracting one from a positive number, there is no carry
3861         // out of the result.
3862         if (Known.isNonNegative())
3863           return Tmp;
3864       }
3865 
3866     Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
3867     if (Tmp2 == 1) return 1; // Early out.
3868     return std::min(Tmp, Tmp2) - 1;
3869   case ISD::SUB:
3870     Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
3871     if (Tmp2 == 1) return 1; // Early out.
3872 
3873     // Handle NEG.
3874     if (ConstantSDNode *CLHS =
3875             isConstOrConstSplat(Op.getOperand(0), DemandedElts))
3876       if (CLHS->isNullValue()) {
3877         KnownBits Known =
3878             computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3879         // If the input is known to be 0 or 1, the output is 0/-1, which is all
3880         // sign bits set.
3881         if ((Known.Zero | 1).isAllOnesValue())
3882           return VTBits;
3883 
3884         // If the input is known to be positive (the sign bit is known clear),
3885         // the output of the NEG has the same number of sign bits as the input.
3886         if (Known.isNonNegative())
3887           return Tmp2;
3888 
3889         // Otherwise, we treat this like a SUB.
3890       }
3891 
3892     // Sub can have at most one carry bit.  Thus we know that the output
3893     // is, at worst, one more bit than the inputs.
3894     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
3895     if (Tmp == 1) return 1; // Early out.
3896     return std::min(Tmp, Tmp2) - 1;
3897   case ISD::MUL: {
3898     // The output of the Mul can be at most twice the valid bits in the inputs.
3899     unsigned SignBitsOp0 = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
3900     if (SignBitsOp0 == 1)
3901       break;
3902     unsigned SignBitsOp1 = ComputeNumSignBits(Op.getOperand(1), Depth + 1);
3903     if (SignBitsOp1 == 1)
3904       break;
3905     unsigned OutValidBits =
3906         (VTBits - SignBitsOp0 + 1) + (VTBits - SignBitsOp1 + 1);
3907     return OutValidBits > VTBits ? 1 : VTBits - OutValidBits + 1;
3908   }
3909   case ISD::SREM:
3910     // The sign bit is the LHS's sign bit, except when the result of the
3911     // remainder is zero. The magnitude of the result should be less than or
3912     // equal to the magnitude of the LHS. Therefore, the result should have
3913     // at least as many sign bits as the left hand side.
3914     return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
3915   case ISD::TRUNCATE: {
3916     // Check if the sign bits of source go down as far as the truncated value.
3917     unsigned NumSrcBits = Op.getOperand(0).getScalarValueSizeInBits();
3918     unsigned NumSrcSignBits = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
3919     if (NumSrcSignBits > (NumSrcBits - VTBits))
3920       return NumSrcSignBits - (NumSrcBits - VTBits);
3921     break;
3922   }
3923   case ISD::EXTRACT_ELEMENT: {
3924     const int KnownSign = ComputeNumSignBits(Op.getOperand(0), Depth+1);
3925     const int BitWidth = Op.getValueSizeInBits();
3926     const int Items = Op.getOperand(0).getValueSizeInBits() / BitWidth;
3927 
3928     // Get reverse index (starting from 1), Op1 value indexes elements from
3929     // little end. Sign starts at big end.
3930     const int rIndex = Items - 1 - Op.getConstantOperandVal(1);
3931 
3932     // If the sign portion ends in our element the subtraction gives correct
3933     // result. Otherwise it gives either negative or > bitwidth result
3934     return std::max(std::min(KnownSign - rIndex * BitWidth, BitWidth), 0);
3935   }
3936   case ISD::INSERT_VECTOR_ELT: {
3937     // If we know the element index, split the demand between the
3938     // source vector and the inserted element, otherwise assume we need
3939     // the original demanded vector elements and the value.
3940     SDValue InVec = Op.getOperand(0);
3941     SDValue InVal = Op.getOperand(1);
3942     SDValue EltNo = Op.getOperand(2);
3943     bool DemandedVal = true;
3944     APInt DemandedVecElts = DemandedElts;
3945     auto *CEltNo = dyn_cast<ConstantSDNode>(EltNo);
3946     if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) {
3947       unsigned EltIdx = CEltNo->getZExtValue();
3948       DemandedVal = !!DemandedElts[EltIdx];
3949       DemandedVecElts.clearBit(EltIdx);
3950     }
3951     Tmp = std::numeric_limits<unsigned>::max();
3952     if (DemandedVal) {
3953       // TODO - handle implicit truncation of inserted elements.
3954       if (InVal.getScalarValueSizeInBits() != VTBits)
3955         break;
3956       Tmp2 = ComputeNumSignBits(InVal, Depth + 1);
3957       Tmp = std::min(Tmp, Tmp2);
3958     }
3959     if (!!DemandedVecElts) {
3960       Tmp2 = ComputeNumSignBits(InVec, DemandedVecElts, Depth + 1);
3961       Tmp = std::min(Tmp, Tmp2);
3962     }
3963     assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
3964     return Tmp;
3965   }
3966   case ISD::EXTRACT_VECTOR_ELT: {
3967     SDValue InVec = Op.getOperand(0);
3968     SDValue EltNo = Op.getOperand(1);
3969     EVT VecVT = InVec.getValueType();
3970     // ComputeNumSignBits not yet implemented for scalable vectors.
3971     if (VecVT.isScalableVector())
3972       break;
3973     const unsigned BitWidth = Op.getValueSizeInBits();
3974     const unsigned EltBitWidth = Op.getOperand(0).getScalarValueSizeInBits();
3975     const unsigned NumSrcElts = VecVT.getVectorNumElements();
3976 
3977     // If BitWidth > EltBitWidth the value is anyext:ed, and we do not know
3978     // anything about sign bits. But if the sizes match we can derive knowledge
3979     // about sign bits from the vector operand.
3980     if (BitWidth != EltBitWidth)
3981       break;
3982 
3983     // If we know the element index, just demand that vector element, else for
3984     // an unknown element index, ignore DemandedElts and demand them all.
3985     APInt DemandedSrcElts = APInt::getAllOnesValue(NumSrcElts);
3986     auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
3987     if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts))
3988       DemandedSrcElts =
3989           APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue());
3990 
3991     return ComputeNumSignBits(InVec, DemandedSrcElts, Depth + 1);
3992   }
3993   case ISD::EXTRACT_SUBVECTOR: {
3994     // Offset the demanded elts by the subvector index.
3995     SDValue Src = Op.getOperand(0);
3996     // Bail until we can represent demanded elements for scalable vectors.
3997     if (Src.getValueType().isScalableVector())
3998       break;
3999     uint64_t Idx = Op.getConstantOperandVal(1);
4000     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
4001     APInt DemandedSrcElts = DemandedElts.zextOrSelf(NumSrcElts).shl(Idx);
4002     return ComputeNumSignBits(Src, DemandedSrcElts, Depth + 1);
4003   }
4004   case ISD::CONCAT_VECTORS: {
4005     // Determine the minimum number of sign bits across all demanded
4006     // elts of the input vectors. Early out if the result is already 1.
4007     Tmp = std::numeric_limits<unsigned>::max();
4008     EVT SubVectorVT = Op.getOperand(0).getValueType();
4009     unsigned NumSubVectorElts = SubVectorVT.getVectorNumElements();
4010     unsigned NumSubVectors = Op.getNumOperands();
4011     for (unsigned i = 0; (i < NumSubVectors) && (Tmp > 1); ++i) {
4012       APInt DemandedSub = DemandedElts.lshr(i * NumSubVectorElts);
4013       DemandedSub = DemandedSub.trunc(NumSubVectorElts);
4014       if (!DemandedSub)
4015         continue;
4016       Tmp2 = ComputeNumSignBits(Op.getOperand(i), DemandedSub, Depth + 1);
4017       Tmp = std::min(Tmp, Tmp2);
4018     }
4019     assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
4020     return Tmp;
4021   }
4022   case ISD::INSERT_SUBVECTOR: {
4023     // Demand any elements from the subvector and the remainder from the src its
4024     // inserted into.
4025     SDValue Src = Op.getOperand(0);
4026     SDValue Sub = Op.getOperand(1);
4027     uint64_t Idx = Op.getConstantOperandVal(2);
4028     unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
4029     APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
4030     APInt DemandedSrcElts = DemandedElts;
4031     DemandedSrcElts.insertBits(APInt::getNullValue(NumSubElts), Idx);
4032 
4033     Tmp = std::numeric_limits<unsigned>::max();
4034     if (!!DemandedSubElts) {
4035       Tmp = ComputeNumSignBits(Sub, DemandedSubElts, Depth + 1);
4036       if (Tmp == 1)
4037         return 1; // early-out
4038     }
4039     if (!!DemandedSrcElts) {
4040       Tmp2 = ComputeNumSignBits(Src, DemandedSrcElts, Depth + 1);
4041       Tmp = std::min(Tmp, Tmp2);
4042     }
4043     assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
4044     return Tmp;
4045   }
4046   }
4047 
4048   // If we are looking at the loaded value of the SDNode.
4049   if (Op.getResNo() == 0) {
4050     // Handle LOADX separately here. EXTLOAD case will fallthrough.
4051     if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
4052       unsigned ExtType = LD->getExtensionType();
4053       switch (ExtType) {
4054       default: break;
4055       case ISD::SEXTLOAD: // e.g. i16->i32 = '17' bits known.
4056         Tmp = LD->getMemoryVT().getScalarSizeInBits();
4057         return VTBits - Tmp + 1;
4058       case ISD::ZEXTLOAD: // e.g. i16->i32 = '16' bits known.
4059         Tmp = LD->getMemoryVT().getScalarSizeInBits();
4060         return VTBits - Tmp;
4061       case ISD::NON_EXTLOAD:
4062         if (const Constant *Cst = TLI->getTargetConstantFromLoad(LD)) {
4063           // We only need to handle vectors - computeKnownBits should handle
4064           // scalar cases.
4065           Type *CstTy = Cst->getType();
4066           if (CstTy->isVectorTy() &&
4067               (NumElts * VTBits) == CstTy->getPrimitiveSizeInBits()) {
4068             Tmp = VTBits;
4069             for (unsigned i = 0; i != NumElts; ++i) {
4070               if (!DemandedElts[i])
4071                 continue;
4072               if (Constant *Elt = Cst->getAggregateElement(i)) {
4073                 if (auto *CInt = dyn_cast<ConstantInt>(Elt)) {
4074                   const APInt &Value = CInt->getValue();
4075                   Tmp = std::min(Tmp, Value.getNumSignBits());
4076                   continue;
4077                 }
4078                 if (auto *CFP = dyn_cast<ConstantFP>(Elt)) {
4079                   APInt Value = CFP->getValueAPF().bitcastToAPInt();
4080                   Tmp = std::min(Tmp, Value.getNumSignBits());
4081                   continue;
4082                 }
4083               }
4084               // Unknown type. Conservatively assume no bits match sign bit.
4085               return 1;
4086             }
4087             return Tmp;
4088           }
4089         }
4090         break;
4091       }
4092     }
4093   }
4094 
4095   // Allow the target to implement this method for its nodes.
4096   if (Opcode >= ISD::BUILTIN_OP_END ||
4097       Opcode == ISD::INTRINSIC_WO_CHAIN ||
4098       Opcode == ISD::INTRINSIC_W_CHAIN ||
4099       Opcode == ISD::INTRINSIC_VOID) {
4100     unsigned NumBits =
4101         TLI->ComputeNumSignBitsForTargetNode(Op, DemandedElts, *this, Depth);
4102     if (NumBits > 1)
4103       FirstAnswer = std::max(FirstAnswer, NumBits);
4104   }
4105 
4106   // Finally, if we can prove that the top bits of the result are 0's or 1's,
4107   // use this information.
4108   KnownBits Known = computeKnownBits(Op, DemandedElts, Depth);
4109 
4110   APInt Mask;
4111   if (Known.isNonNegative()) {        // sign bit is 0
4112     Mask = Known.Zero;
4113   } else if (Known.isNegative()) {  // sign bit is 1;
4114     Mask = Known.One;
4115   } else {
4116     // Nothing known.
4117     return FirstAnswer;
4118   }
4119 
4120   // Okay, we know that the sign bit in Mask is set.  Use CLO to determine
4121   // the number of identical bits in the top of the input value.
4122   Mask <<= Mask.getBitWidth()-VTBits;
4123   return std::max(FirstAnswer, Mask.countLeadingOnes());
4124 }
4125 
4126 bool SelectionDAG::isBaseWithConstantOffset(SDValue Op) const {
4127   if ((Op.getOpcode() != ISD::ADD && Op.getOpcode() != ISD::OR) ||
4128       !isa<ConstantSDNode>(Op.getOperand(1)))
4129     return false;
4130 
4131   if (Op.getOpcode() == ISD::OR &&
4132       !MaskedValueIsZero(Op.getOperand(0), Op.getConstantOperandAPInt(1)))
4133     return false;
4134 
4135   return true;
4136 }
4137 
4138 bool SelectionDAG::isKnownNeverNaN(SDValue Op, bool SNaN, unsigned Depth) const {
4139   // If we're told that NaNs won't happen, assume they won't.
4140   if (getTarget().Options.NoNaNsFPMath || Op->getFlags().hasNoNaNs())
4141     return true;
4142 
4143   if (Depth >= MaxRecursionDepth)
4144     return false; // Limit search depth.
4145 
4146   // TODO: Handle vectors.
4147   // If the value is a constant, we can obviously see if it is a NaN or not.
4148   if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) {
4149     return !C->getValueAPF().isNaN() ||
4150            (SNaN && !C->getValueAPF().isSignaling());
4151   }
4152 
4153   unsigned Opcode = Op.getOpcode();
4154   switch (Opcode) {
4155   case ISD::FADD:
4156   case ISD::FSUB:
4157   case ISD::FMUL:
4158   case ISD::FDIV:
4159   case ISD::FREM:
4160   case ISD::FSIN:
4161   case ISD::FCOS: {
4162     if (SNaN)
4163       return true;
4164     // TODO: Need isKnownNeverInfinity
4165     return false;
4166   }
4167   case ISD::FCANONICALIZE:
4168   case ISD::FEXP:
4169   case ISD::FEXP2:
4170   case ISD::FTRUNC:
4171   case ISD::FFLOOR:
4172   case ISD::FCEIL:
4173   case ISD::FROUND:
4174   case ISD::FROUNDEVEN:
4175   case ISD::FRINT:
4176   case ISD::FNEARBYINT: {
4177     if (SNaN)
4178       return true;
4179     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
4180   }
4181   case ISD::FABS:
4182   case ISD::FNEG:
4183   case ISD::FCOPYSIGN: {
4184     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
4185   }
4186   case ISD::SELECT:
4187     return isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1) &&
4188            isKnownNeverNaN(Op.getOperand(2), SNaN, Depth + 1);
4189   case ISD::FP_EXTEND:
4190   case ISD::FP_ROUND: {
4191     if (SNaN)
4192       return true;
4193     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
4194   }
4195   case ISD::SINT_TO_FP:
4196   case ISD::UINT_TO_FP:
4197     return true;
4198   case ISD::FMA:
4199   case ISD::FMAD: {
4200     if (SNaN)
4201       return true;
4202     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) &&
4203            isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1) &&
4204            isKnownNeverNaN(Op.getOperand(2), SNaN, Depth + 1);
4205   }
4206   case ISD::FSQRT: // Need is known positive
4207   case ISD::FLOG:
4208   case ISD::FLOG2:
4209   case ISD::FLOG10:
4210   case ISD::FPOWI:
4211   case ISD::FPOW: {
4212     if (SNaN)
4213       return true;
4214     // TODO: Refine on operand
4215     return false;
4216   }
4217   case ISD::FMINNUM:
4218   case ISD::FMAXNUM: {
4219     // Only one needs to be known not-nan, since it will be returned if the
4220     // other ends up being one.
4221     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) ||
4222            isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1);
4223   }
4224   case ISD::FMINNUM_IEEE:
4225   case ISD::FMAXNUM_IEEE: {
4226     if (SNaN)
4227       return true;
4228     // This can return a NaN if either operand is an sNaN, or if both operands
4229     // are NaN.
4230     return (isKnownNeverNaN(Op.getOperand(0), false, Depth + 1) &&
4231             isKnownNeverSNaN(Op.getOperand(1), Depth + 1)) ||
4232            (isKnownNeverNaN(Op.getOperand(1), false, Depth + 1) &&
4233             isKnownNeverSNaN(Op.getOperand(0), Depth + 1));
4234   }
4235   case ISD::FMINIMUM:
4236   case ISD::FMAXIMUM: {
4237     // TODO: Does this quiet or return the origina NaN as-is?
4238     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) &&
4239            isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1);
4240   }
4241   case ISD::EXTRACT_VECTOR_ELT: {
4242     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
4243   }
4244   default:
4245     if (Opcode >= ISD::BUILTIN_OP_END ||
4246         Opcode == ISD::INTRINSIC_WO_CHAIN ||
4247         Opcode == ISD::INTRINSIC_W_CHAIN ||
4248         Opcode == ISD::INTRINSIC_VOID) {
4249       return TLI->isKnownNeverNaNForTargetNode(Op, *this, SNaN, Depth);
4250     }
4251 
4252     return false;
4253   }
4254 }
4255 
4256 bool SelectionDAG::isKnownNeverZeroFloat(SDValue Op) const {
4257   assert(Op.getValueType().isFloatingPoint() &&
4258          "Floating point type expected");
4259 
4260   // If the value is a constant, we can obviously see if it is a zero or not.
4261   // TODO: Add BuildVector support.
4262   if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op))
4263     return !C->isZero();
4264   return false;
4265 }
4266 
4267 bool SelectionDAG::isKnownNeverZero(SDValue Op) const {
4268   assert(!Op.getValueType().isFloatingPoint() &&
4269          "Floating point types unsupported - use isKnownNeverZeroFloat");
4270 
4271   // If the value is a constant, we can obviously see if it is a zero or not.
4272   if (ISD::matchUnaryPredicate(
4273           Op, [](ConstantSDNode *C) { return !C->isNullValue(); }))
4274     return true;
4275 
4276   // TODO: Recognize more cases here.
4277   switch (Op.getOpcode()) {
4278   default: break;
4279   case ISD::OR:
4280     if (isKnownNeverZero(Op.getOperand(1)) ||
4281         isKnownNeverZero(Op.getOperand(0)))
4282       return true;
4283     break;
4284   }
4285 
4286   return false;
4287 }
4288 
4289 bool SelectionDAG::isEqualTo(SDValue A, SDValue B) const {
4290   // Check the obvious case.
4291   if (A == B) return true;
4292 
4293   // For for negative and positive zero.
4294   if (const ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A))
4295     if (const ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B))
4296       if (CA->isZero() && CB->isZero()) return true;
4297 
4298   // Otherwise they may not be equal.
4299   return false;
4300 }
4301 
4302 // FIXME: unify with llvm::haveNoCommonBitsSet.
4303 // FIXME: could also handle masked merge pattern (X & ~M) op (Y & M)
4304 bool SelectionDAG::haveNoCommonBitsSet(SDValue A, SDValue B) const {
4305   assert(A.getValueType() == B.getValueType() &&
4306          "Values must have the same type");
4307   return (computeKnownBits(A).Zero | computeKnownBits(B).Zero).isAllOnesValue();
4308 }
4309 
4310 static SDValue FoldBUILD_VECTOR(const SDLoc &DL, EVT VT,
4311                                 ArrayRef<SDValue> Ops,
4312                                 SelectionDAG &DAG) {
4313   int NumOps = Ops.size();
4314   assert(NumOps != 0 && "Can't build an empty vector!");
4315   assert(!VT.isScalableVector() &&
4316          "BUILD_VECTOR cannot be used with scalable types");
4317   assert(VT.getVectorNumElements() == (unsigned)NumOps &&
4318          "Incorrect element count in BUILD_VECTOR!");
4319 
4320   // BUILD_VECTOR of UNDEFs is UNDEF.
4321   if (llvm::all_of(Ops, [](SDValue Op) { return Op.isUndef(); }))
4322     return DAG.getUNDEF(VT);
4323 
4324   // BUILD_VECTOR of seq extract/insert from the same vector + type is Identity.
4325   SDValue IdentitySrc;
4326   bool IsIdentity = true;
4327   for (int i = 0; i != NumOps; ++i) {
4328     if (Ops[i].getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
4329         Ops[i].getOperand(0).getValueType() != VT ||
4330         (IdentitySrc && Ops[i].getOperand(0) != IdentitySrc) ||
4331         !isa<ConstantSDNode>(Ops[i].getOperand(1)) ||
4332         cast<ConstantSDNode>(Ops[i].getOperand(1))->getAPIntValue() != i) {
4333       IsIdentity = false;
4334       break;
4335     }
4336     IdentitySrc = Ops[i].getOperand(0);
4337   }
4338   if (IsIdentity)
4339     return IdentitySrc;
4340 
4341   return SDValue();
4342 }
4343 
4344 /// Try to simplify vector concatenation to an input value, undef, or build
4345 /// vector.
4346 static SDValue foldCONCAT_VECTORS(const SDLoc &DL, EVT VT,
4347                                   ArrayRef<SDValue> Ops,
4348                                   SelectionDAG &DAG) {
4349   assert(!Ops.empty() && "Can't concatenate an empty list of vectors!");
4350   assert(llvm::all_of(Ops,
4351                       [Ops](SDValue Op) {
4352                         return Ops[0].getValueType() == Op.getValueType();
4353                       }) &&
4354          "Concatenation of vectors with inconsistent value types!");
4355   assert((Ops[0].getValueType().getVectorElementCount() * Ops.size()) ==
4356              VT.getVectorElementCount() &&
4357          "Incorrect element count in vector concatenation!");
4358 
4359   if (Ops.size() == 1)
4360     return Ops[0];
4361 
4362   // Concat of UNDEFs is UNDEF.
4363   if (llvm::all_of(Ops, [](SDValue Op) { return Op.isUndef(); }))
4364     return DAG.getUNDEF(VT);
4365 
4366   // Scan the operands and look for extract operations from a single source
4367   // that correspond to insertion at the same location via this concatenation:
4368   // concat (extract X, 0*subvec_elts), (extract X, 1*subvec_elts), ...
4369   SDValue IdentitySrc;
4370   bool IsIdentity = true;
4371   for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
4372     SDValue Op = Ops[i];
4373     unsigned IdentityIndex = i * Op.getValueType().getVectorMinNumElements();
4374     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
4375         Op.getOperand(0).getValueType() != VT ||
4376         (IdentitySrc && Op.getOperand(0) != IdentitySrc) ||
4377         Op.getConstantOperandVal(1) != IdentityIndex) {
4378       IsIdentity = false;
4379       break;
4380     }
4381     assert((!IdentitySrc || IdentitySrc == Op.getOperand(0)) &&
4382            "Unexpected identity source vector for concat of extracts");
4383     IdentitySrc = Op.getOperand(0);
4384   }
4385   if (IsIdentity) {
4386     assert(IdentitySrc && "Failed to set source vector of extracts");
4387     return IdentitySrc;
4388   }
4389 
4390   // The code below this point is only designed to work for fixed width
4391   // vectors, so we bail out for now.
4392   if (VT.isScalableVector())
4393     return SDValue();
4394 
4395   // A CONCAT_VECTOR with all UNDEF/BUILD_VECTOR operands can be
4396   // simplified to one big BUILD_VECTOR.
4397   // FIXME: Add support for SCALAR_TO_VECTOR as well.
4398   EVT SVT = VT.getScalarType();
4399   SmallVector<SDValue, 16> Elts;
4400   for (SDValue Op : Ops) {
4401     EVT OpVT = Op.getValueType();
4402     if (Op.isUndef())
4403       Elts.append(OpVT.getVectorNumElements(), DAG.getUNDEF(SVT));
4404     else if (Op.getOpcode() == ISD::BUILD_VECTOR)
4405       Elts.append(Op->op_begin(), Op->op_end());
4406     else
4407       return SDValue();
4408   }
4409 
4410   // BUILD_VECTOR requires all inputs to be of the same type, find the
4411   // maximum type and extend them all.
4412   for (SDValue Op : Elts)
4413     SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
4414 
4415   if (SVT.bitsGT(VT.getScalarType())) {
4416     for (SDValue &Op : Elts) {
4417       if (Op.isUndef())
4418         Op = DAG.getUNDEF(SVT);
4419       else
4420         Op = DAG.getTargetLoweringInfo().isZExtFree(Op.getValueType(), SVT)
4421                  ? DAG.getZExtOrTrunc(Op, DL, SVT)
4422                  : DAG.getSExtOrTrunc(Op, DL, SVT);
4423     }
4424   }
4425 
4426   SDValue V = DAG.getBuildVector(VT, DL, Elts);
4427   NewSDValueDbgMsg(V, "New node fold concat vectors: ", &DAG);
4428   return V;
4429 }
4430 
4431 /// Gets or creates the specified node.
4432 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT) {
4433   FoldingSetNodeID ID;
4434   AddNodeIDNode(ID, Opcode, getVTList(VT), None);
4435   void *IP = nullptr;
4436   if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
4437     return SDValue(E, 0);
4438 
4439   auto *N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(),
4440                               getVTList(VT));
4441   CSEMap.InsertNode(N, IP);
4442 
4443   InsertNode(N);
4444   SDValue V = SDValue(N, 0);
4445   NewSDValueDbgMsg(V, "Creating new node: ", this);
4446   return V;
4447 }
4448 
4449 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
4450                               SDValue Operand) {
4451   SDNodeFlags Flags;
4452   if (Inserter)
4453     Flags = Inserter->getFlags();
4454   return getNode(Opcode, DL, VT, Operand, Flags);
4455 }
4456 
4457 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
4458                               SDValue Operand, const SDNodeFlags Flags) {
4459   assert(Operand.getOpcode() != ISD::DELETED_NODE &&
4460          "Operand is DELETED_NODE!");
4461   // Constant fold unary operations with an integer constant operand. Even
4462   // opaque constant will be folded, because the folding of unary operations
4463   // doesn't create new constants with different values. Nevertheless, the
4464   // opaque flag is preserved during folding to prevent future folding with
4465   // other constants.
4466   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Operand)) {
4467     const APInt &Val = C->getAPIntValue();
4468     switch (Opcode) {
4469     default: break;
4470     case ISD::SIGN_EXTEND:
4471       return getConstant(Val.sextOrTrunc(VT.getSizeInBits()), DL, VT,
4472                          C->isTargetOpcode(), C->isOpaque());
4473     case ISD::TRUNCATE:
4474       if (C->isOpaque())
4475         break;
4476       LLVM_FALLTHROUGH;
4477     case ISD::ANY_EXTEND:
4478     case ISD::ZERO_EXTEND:
4479       return getConstant(Val.zextOrTrunc(VT.getSizeInBits()), DL, VT,
4480                          C->isTargetOpcode(), C->isOpaque());
4481     case ISD::UINT_TO_FP:
4482     case ISD::SINT_TO_FP: {
4483       APFloat apf(EVTToAPFloatSemantics(VT),
4484                   APInt::getNullValue(VT.getSizeInBits()));
4485       (void)apf.convertFromAPInt(Val,
4486                                  Opcode==ISD::SINT_TO_FP,
4487                                  APFloat::rmNearestTiesToEven);
4488       return getConstantFP(apf, DL, VT);
4489     }
4490     case ISD::BITCAST:
4491       if (VT == MVT::f16 && C->getValueType(0) == MVT::i16)
4492         return getConstantFP(APFloat(APFloat::IEEEhalf(), Val), DL, VT);
4493       if (VT == MVT::f32 && C->getValueType(0) == MVT::i32)
4494         return getConstantFP(APFloat(APFloat::IEEEsingle(), Val), DL, VT);
4495       if (VT == MVT::f64 && C->getValueType(0) == MVT::i64)
4496         return getConstantFP(APFloat(APFloat::IEEEdouble(), Val), DL, VT);
4497       if (VT == MVT::f128 && C->getValueType(0) == MVT::i128)
4498         return getConstantFP(APFloat(APFloat::IEEEquad(), Val), DL, VT);
4499       break;
4500     case ISD::ABS:
4501       return getConstant(Val.abs(), DL, VT, C->isTargetOpcode(),
4502                          C->isOpaque());
4503     case ISD::BITREVERSE:
4504       return getConstant(Val.reverseBits(), DL, VT, C->isTargetOpcode(),
4505                          C->isOpaque());
4506     case ISD::BSWAP:
4507       return getConstant(Val.byteSwap(), DL, VT, C->isTargetOpcode(),
4508                          C->isOpaque());
4509     case ISD::CTPOP:
4510       return getConstant(Val.countPopulation(), DL, VT, C->isTargetOpcode(),
4511                          C->isOpaque());
4512     case ISD::CTLZ:
4513     case ISD::CTLZ_ZERO_UNDEF:
4514       return getConstant(Val.countLeadingZeros(), DL, VT, C->isTargetOpcode(),
4515                          C->isOpaque());
4516     case ISD::CTTZ:
4517     case ISD::CTTZ_ZERO_UNDEF:
4518       return getConstant(Val.countTrailingZeros(), DL, VT, C->isTargetOpcode(),
4519                          C->isOpaque());
4520     case ISD::FP16_TO_FP: {
4521       bool Ignored;
4522       APFloat FPV(APFloat::IEEEhalf(),
4523                   (Val.getBitWidth() == 16) ? Val : Val.trunc(16));
4524 
4525       // This can return overflow, underflow, or inexact; we don't care.
4526       // FIXME need to be more flexible about rounding mode.
4527       (void)FPV.convert(EVTToAPFloatSemantics(VT),
4528                         APFloat::rmNearestTiesToEven, &Ignored);
4529       return getConstantFP(FPV, DL, VT);
4530     }
4531     }
4532   }
4533 
4534   // Constant fold unary operations with a floating point constant operand.
4535   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Operand)) {
4536     APFloat V = C->getValueAPF();    // make copy
4537     switch (Opcode) {
4538     case ISD::FNEG:
4539       V.changeSign();
4540       return getConstantFP(V, DL, VT);
4541     case ISD::FABS:
4542       V.clearSign();
4543       return getConstantFP(V, DL, VT);
4544     case ISD::FCEIL: {
4545       APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardPositive);
4546       if (fs == APFloat::opOK || fs == APFloat::opInexact)
4547         return getConstantFP(V, DL, VT);
4548       break;
4549     }
4550     case ISD::FTRUNC: {
4551       APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardZero);
4552       if (fs == APFloat::opOK || fs == APFloat::opInexact)
4553         return getConstantFP(V, DL, VT);
4554       break;
4555     }
4556     case ISD::FFLOOR: {
4557       APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardNegative);
4558       if (fs == APFloat::opOK || fs == APFloat::opInexact)
4559         return getConstantFP(V, DL, VT);
4560       break;
4561     }
4562     case ISD::FP_EXTEND: {
4563       bool ignored;
4564       // This can return overflow, underflow, or inexact; we don't care.
4565       // FIXME need to be more flexible about rounding mode.
4566       (void)V.convert(EVTToAPFloatSemantics(VT),
4567                       APFloat::rmNearestTiesToEven, &ignored);
4568       return getConstantFP(V, DL, VT);
4569     }
4570     case ISD::FP_TO_SINT:
4571     case ISD::FP_TO_UINT: {
4572       bool ignored;
4573       APSInt IntVal(VT.getSizeInBits(), Opcode == ISD::FP_TO_UINT);
4574       // FIXME need to be more flexible about rounding mode.
4575       APFloat::opStatus s =
4576           V.convertToInteger(IntVal, APFloat::rmTowardZero, &ignored);
4577       if (s == APFloat::opInvalidOp) // inexact is OK, in fact usual
4578         break;
4579       return getConstant(IntVal, DL, VT);
4580     }
4581     case ISD::BITCAST:
4582       if (VT == MVT::i16 && C->getValueType(0) == MVT::f16)
4583         return getConstant((uint16_t)V.bitcastToAPInt().getZExtValue(), DL, VT);
4584       else if (VT == MVT::i32 && C->getValueType(0) == MVT::f32)
4585         return getConstant((uint32_t)V.bitcastToAPInt().getZExtValue(), DL, VT);
4586       else if (VT == MVT::i64 && C->getValueType(0) == MVT::f64)
4587         return getConstant(V.bitcastToAPInt().getZExtValue(), DL, VT);
4588       break;
4589     case ISD::FP_TO_FP16: {
4590       bool Ignored;
4591       // This can return overflow, underflow, or inexact; we don't care.
4592       // FIXME need to be more flexible about rounding mode.
4593       (void)V.convert(APFloat::IEEEhalf(),
4594                       APFloat::rmNearestTiesToEven, &Ignored);
4595       return getConstant(V.bitcastToAPInt().getZExtValue(), DL, VT);
4596     }
4597     }
4598   }
4599 
4600   // Constant fold unary operations with a vector integer or float operand.
4601   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Operand)) {
4602     if (BV->isConstant()) {
4603       switch (Opcode) {
4604       default:
4605         // FIXME: Entirely reasonable to perform folding of other unary
4606         // operations here as the need arises.
4607         break;
4608       case ISD::FNEG:
4609       case ISD::FABS:
4610       case ISD::FCEIL:
4611       case ISD::FTRUNC:
4612       case ISD::FFLOOR:
4613       case ISD::FP_EXTEND:
4614       case ISD::FP_TO_SINT:
4615       case ISD::FP_TO_UINT:
4616       case ISD::TRUNCATE:
4617       case ISD::ANY_EXTEND:
4618       case ISD::ZERO_EXTEND:
4619       case ISD::SIGN_EXTEND:
4620       case ISD::UINT_TO_FP:
4621       case ISD::SINT_TO_FP:
4622       case ISD::ABS:
4623       case ISD::BITREVERSE:
4624       case ISD::BSWAP:
4625       case ISD::CTLZ:
4626       case ISD::CTLZ_ZERO_UNDEF:
4627       case ISD::CTTZ:
4628       case ISD::CTTZ_ZERO_UNDEF:
4629       case ISD::CTPOP: {
4630         SDValue Ops = { Operand };
4631         if (SDValue Fold = FoldConstantVectorArithmetic(Opcode, DL, VT, Ops))
4632           return Fold;
4633       }
4634       }
4635     }
4636   }
4637 
4638   unsigned OpOpcode = Operand.getNode()->getOpcode();
4639   switch (Opcode) {
4640   case ISD::FREEZE:
4641     assert(VT == Operand.getValueType() && "Unexpected VT!");
4642     break;
4643   case ISD::TokenFactor:
4644   case ISD::MERGE_VALUES:
4645   case ISD::CONCAT_VECTORS:
4646     return Operand;         // Factor, merge or concat of one node?  No need.
4647   case ISD::BUILD_VECTOR: {
4648     // Attempt to simplify BUILD_VECTOR.
4649     SDValue Ops[] = {Operand};
4650     if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
4651       return V;
4652     break;
4653   }
4654   case ISD::FP_ROUND: llvm_unreachable("Invalid method to make FP_ROUND node");
4655   case ISD::FP_EXTEND:
4656     assert(VT.isFloatingPoint() &&
4657            Operand.getValueType().isFloatingPoint() && "Invalid FP cast!");
4658     if (Operand.getValueType() == VT) return Operand;  // noop conversion.
4659     assert((!VT.isVector() ||
4660             VT.getVectorElementCount() ==
4661             Operand.getValueType().getVectorElementCount()) &&
4662            "Vector element count mismatch!");
4663     assert(Operand.getValueType().bitsLT(VT) &&
4664            "Invalid fpext node, dst < src!");
4665     if (Operand.isUndef())
4666       return getUNDEF(VT);
4667     break;
4668   case ISD::FP_TO_SINT:
4669   case ISD::FP_TO_UINT:
4670     if (Operand.isUndef())
4671       return getUNDEF(VT);
4672     break;
4673   case ISD::SINT_TO_FP:
4674   case ISD::UINT_TO_FP:
4675     // [us]itofp(undef) = 0, because the result value is bounded.
4676     if (Operand.isUndef())
4677       return getConstantFP(0.0, DL, VT);
4678     break;
4679   case ISD::SIGN_EXTEND:
4680     assert(VT.isInteger() && Operand.getValueType().isInteger() &&
4681            "Invalid SIGN_EXTEND!");
4682     assert(VT.isVector() == Operand.getValueType().isVector() &&
4683            "SIGN_EXTEND result type type should be vector iff the operand "
4684            "type is vector!");
4685     if (Operand.getValueType() == VT) return Operand;   // noop extension
4686     assert((!VT.isVector() ||
4687             VT.getVectorElementCount() ==
4688                 Operand.getValueType().getVectorElementCount()) &&
4689            "Vector element count mismatch!");
4690     assert(Operand.getValueType().bitsLT(VT) &&
4691            "Invalid sext node, dst < src!");
4692     if (OpOpcode == ISD::SIGN_EXTEND || OpOpcode == ISD::ZERO_EXTEND)
4693       return getNode(OpOpcode, DL, VT, Operand.getOperand(0));
4694     else if (OpOpcode == ISD::UNDEF)
4695       // sext(undef) = 0, because the top bits will all be the same.
4696       return getConstant(0, DL, VT);
4697     break;
4698   case ISD::ZERO_EXTEND:
4699     assert(VT.isInteger() && Operand.getValueType().isInteger() &&
4700            "Invalid ZERO_EXTEND!");
4701     assert(VT.isVector() == Operand.getValueType().isVector() &&
4702            "ZERO_EXTEND result type type should be vector iff the operand "
4703            "type is vector!");
4704     if (Operand.getValueType() == VT) return Operand;   // noop extension
4705     assert((!VT.isVector() ||
4706             VT.getVectorElementCount() ==
4707                 Operand.getValueType().getVectorElementCount()) &&
4708            "Vector element count mismatch!");
4709     assert(Operand.getValueType().bitsLT(VT) &&
4710            "Invalid zext node, dst < src!");
4711     if (OpOpcode == ISD::ZERO_EXTEND)   // (zext (zext x)) -> (zext x)
4712       return getNode(ISD::ZERO_EXTEND, DL, VT, Operand.getOperand(0));
4713     else if (OpOpcode == ISD::UNDEF)
4714       // zext(undef) = 0, because the top bits will be zero.
4715       return getConstant(0, DL, VT);
4716     break;
4717   case ISD::ANY_EXTEND:
4718     assert(VT.isInteger() && Operand.getValueType().isInteger() &&
4719            "Invalid ANY_EXTEND!");
4720     assert(VT.isVector() == Operand.getValueType().isVector() &&
4721            "ANY_EXTEND result type type should be vector iff the operand "
4722            "type is vector!");
4723     if (Operand.getValueType() == VT) return Operand;   // noop extension
4724     assert((!VT.isVector() ||
4725             VT.getVectorElementCount() ==
4726                 Operand.getValueType().getVectorElementCount()) &&
4727            "Vector element count mismatch!");
4728     assert(Operand.getValueType().bitsLT(VT) &&
4729            "Invalid anyext node, dst < src!");
4730 
4731     if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
4732         OpOpcode == ISD::ANY_EXTEND)
4733       // (ext (zext x)) -> (zext x)  and  (ext (sext x)) -> (sext x)
4734       return getNode(OpOpcode, DL, VT, Operand.getOperand(0));
4735     else if (OpOpcode == ISD::UNDEF)
4736       return getUNDEF(VT);
4737 
4738     // (ext (trunc x)) -> x
4739     if (OpOpcode == ISD::TRUNCATE) {
4740       SDValue OpOp = Operand.getOperand(0);
4741       if (OpOp.getValueType() == VT) {
4742         transferDbgValues(Operand, OpOp);
4743         return OpOp;
4744       }
4745     }
4746     break;
4747   case ISD::TRUNCATE:
4748     assert(VT.isInteger() && Operand.getValueType().isInteger() &&
4749            "Invalid TRUNCATE!");
4750     assert(VT.isVector() == Operand.getValueType().isVector() &&
4751            "TRUNCATE result type type should be vector iff the operand "
4752            "type is vector!");
4753     if (Operand.getValueType() == VT) return Operand;   // noop truncate
4754     assert((!VT.isVector() ||
4755             VT.getVectorElementCount() ==
4756                 Operand.getValueType().getVectorElementCount()) &&
4757            "Vector element count mismatch!");
4758     assert(Operand.getValueType().bitsGT(VT) &&
4759            "Invalid truncate node, src < dst!");
4760     if (OpOpcode == ISD::TRUNCATE)
4761       return getNode(ISD::TRUNCATE, DL, VT, Operand.getOperand(0));
4762     if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
4763         OpOpcode == ISD::ANY_EXTEND) {
4764       // If the source is smaller than the dest, we still need an extend.
4765       if (Operand.getOperand(0).getValueType().getScalarType()
4766             .bitsLT(VT.getScalarType()))
4767         return getNode(OpOpcode, DL, VT, Operand.getOperand(0));
4768       if (Operand.getOperand(0).getValueType().bitsGT(VT))
4769         return getNode(ISD::TRUNCATE, DL, VT, Operand.getOperand(0));
4770       return Operand.getOperand(0);
4771     }
4772     if (OpOpcode == ISD::UNDEF)
4773       return getUNDEF(VT);
4774     break;
4775   case ISD::ANY_EXTEND_VECTOR_INREG:
4776   case ISD::ZERO_EXTEND_VECTOR_INREG:
4777   case ISD::SIGN_EXTEND_VECTOR_INREG:
4778     assert(VT.isVector() && "This DAG node is restricted to vector types.");
4779     assert(Operand.getValueType().bitsLE(VT) &&
4780            "The input must be the same size or smaller than the result.");
4781     assert(VT.getVectorNumElements() <
4782              Operand.getValueType().getVectorNumElements() &&
4783            "The destination vector type must have fewer lanes than the input.");
4784     break;
4785   case ISD::ABS:
4786     assert(VT.isInteger() && VT == Operand.getValueType() &&
4787            "Invalid ABS!");
4788     if (OpOpcode == ISD::UNDEF)
4789       return getUNDEF(VT);
4790     break;
4791   case ISD::BSWAP:
4792     assert(VT.isInteger() && VT == Operand.getValueType() &&
4793            "Invalid BSWAP!");
4794     assert((VT.getScalarSizeInBits() % 16 == 0) &&
4795            "BSWAP types must be a multiple of 16 bits!");
4796     if (OpOpcode == ISD::UNDEF)
4797       return getUNDEF(VT);
4798     break;
4799   case ISD::BITREVERSE:
4800     assert(VT.isInteger() && VT == Operand.getValueType() &&
4801            "Invalid BITREVERSE!");
4802     if (OpOpcode == ISD::UNDEF)
4803       return getUNDEF(VT);
4804     break;
4805   case ISD::BITCAST:
4806     // Basic sanity checking.
4807     assert(VT.getSizeInBits() == Operand.getValueSizeInBits() &&
4808            "Cannot BITCAST between types of different sizes!");
4809     if (VT == Operand.getValueType()) return Operand;  // noop conversion.
4810     if (OpOpcode == ISD::BITCAST)  // bitconv(bitconv(x)) -> bitconv(x)
4811       return getNode(ISD::BITCAST, DL, VT, Operand.getOperand(0));
4812     if (OpOpcode == ISD::UNDEF)
4813       return getUNDEF(VT);
4814     break;
4815   case ISD::SCALAR_TO_VECTOR:
4816     assert(VT.isVector() && !Operand.getValueType().isVector() &&
4817            (VT.getVectorElementType() == Operand.getValueType() ||
4818             (VT.getVectorElementType().isInteger() &&
4819              Operand.getValueType().isInteger() &&
4820              VT.getVectorElementType().bitsLE(Operand.getValueType()))) &&
4821            "Illegal SCALAR_TO_VECTOR node!");
4822     if (OpOpcode == ISD::UNDEF)
4823       return getUNDEF(VT);
4824     // scalar_to_vector(extract_vector_elt V, 0) -> V, top bits are undefined.
4825     if (OpOpcode == ISD::EXTRACT_VECTOR_ELT &&
4826         isa<ConstantSDNode>(Operand.getOperand(1)) &&
4827         Operand.getConstantOperandVal(1) == 0 &&
4828         Operand.getOperand(0).getValueType() == VT)
4829       return Operand.getOperand(0);
4830     break;
4831   case ISD::FNEG:
4832     // Negation of an unknown bag of bits is still completely undefined.
4833     if (OpOpcode == ISD::UNDEF)
4834       return getUNDEF(VT);
4835 
4836     if (OpOpcode == ISD::FNEG)  // --X -> X
4837       return Operand.getOperand(0);
4838     break;
4839   case ISD::FABS:
4840     if (OpOpcode == ISD::FNEG)  // abs(-X) -> abs(X)
4841       return getNode(ISD::FABS, DL, VT, Operand.getOperand(0));
4842     break;
4843   case ISD::VSCALE:
4844     assert(VT == Operand.getValueType() && "Unexpected VT!");
4845     break;
4846   case ISD::CTPOP:
4847     if (Operand.getValueType().getScalarType() == MVT::i1)
4848       return Operand;
4849     break;
4850   case ISD::CTLZ:
4851   case ISD::CTTZ:
4852     if (Operand.getValueType().getScalarType() == MVT::i1)
4853       return getNOT(DL, Operand, Operand.getValueType());
4854     break;
4855   case ISD::VECREDUCE_SMIN:
4856   case ISD::VECREDUCE_UMAX:
4857     if (Operand.getValueType().getScalarType() == MVT::i1)
4858       return getNode(ISD::VECREDUCE_OR, DL, VT, Operand);
4859     break;
4860   case ISD::VECREDUCE_SMAX:
4861   case ISD::VECREDUCE_UMIN:
4862     if (Operand.getValueType().getScalarType() == MVT::i1)
4863       return getNode(ISD::VECREDUCE_AND, DL, VT, Operand);
4864     break;
4865   }
4866 
4867   SDNode *N;
4868   SDVTList VTs = getVTList(VT);
4869   SDValue Ops[] = {Operand};
4870   if (VT != MVT::Glue) { // Don't CSE flag producing nodes
4871     FoldingSetNodeID ID;
4872     AddNodeIDNode(ID, Opcode, VTs, Ops);
4873     void *IP = nullptr;
4874     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
4875       E->intersectFlagsWith(Flags);
4876       return SDValue(E, 0);
4877     }
4878 
4879     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
4880     N->setFlags(Flags);
4881     createOperands(N, Ops);
4882     CSEMap.InsertNode(N, IP);
4883   } else {
4884     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
4885     createOperands(N, Ops);
4886   }
4887 
4888   InsertNode(N);
4889   SDValue V = SDValue(N, 0);
4890   NewSDValueDbgMsg(V, "Creating new node: ", this);
4891   return V;
4892 }
4893 
4894 static llvm::Optional<APInt> FoldValue(unsigned Opcode, const APInt &C1,
4895                                        const APInt &C2) {
4896   switch (Opcode) {
4897   case ISD::ADD:  return C1 + C2;
4898   case ISD::SUB:  return C1 - C2;
4899   case ISD::MUL:  return C1 * C2;
4900   case ISD::AND:  return C1 & C2;
4901   case ISD::OR:   return C1 | C2;
4902   case ISD::XOR:  return C1 ^ C2;
4903   case ISD::SHL:  return C1 << C2;
4904   case ISD::SRL:  return C1.lshr(C2);
4905   case ISD::SRA:  return C1.ashr(C2);
4906   case ISD::ROTL: return C1.rotl(C2);
4907   case ISD::ROTR: return C1.rotr(C2);
4908   case ISD::SMIN: return C1.sle(C2) ? C1 : C2;
4909   case ISD::SMAX: return C1.sge(C2) ? C1 : C2;
4910   case ISD::UMIN: return C1.ule(C2) ? C1 : C2;
4911   case ISD::UMAX: return C1.uge(C2) ? C1 : C2;
4912   case ISD::SADDSAT: return C1.sadd_sat(C2);
4913   case ISD::UADDSAT: return C1.uadd_sat(C2);
4914   case ISD::SSUBSAT: return C1.ssub_sat(C2);
4915   case ISD::USUBSAT: return C1.usub_sat(C2);
4916   case ISD::UDIV:
4917     if (!C2.getBoolValue())
4918       break;
4919     return C1.udiv(C2);
4920   case ISD::UREM:
4921     if (!C2.getBoolValue())
4922       break;
4923     return C1.urem(C2);
4924   case ISD::SDIV:
4925     if (!C2.getBoolValue())
4926       break;
4927     return C1.sdiv(C2);
4928   case ISD::SREM:
4929     if (!C2.getBoolValue())
4930       break;
4931     return C1.srem(C2);
4932   }
4933   return llvm::None;
4934 }
4935 
4936 SDValue SelectionDAG::FoldSymbolOffset(unsigned Opcode, EVT VT,
4937                                        const GlobalAddressSDNode *GA,
4938                                        const SDNode *N2) {
4939   if (GA->getOpcode() != ISD::GlobalAddress)
4940     return SDValue();
4941   if (!TLI->isOffsetFoldingLegal(GA))
4942     return SDValue();
4943   auto *C2 = dyn_cast<ConstantSDNode>(N2);
4944   if (!C2)
4945     return SDValue();
4946   int64_t Offset = C2->getSExtValue();
4947   switch (Opcode) {
4948   case ISD::ADD: break;
4949   case ISD::SUB: Offset = -uint64_t(Offset); break;
4950   default: return SDValue();
4951   }
4952   return getGlobalAddress(GA->getGlobal(), SDLoc(C2), VT,
4953                           GA->getOffset() + uint64_t(Offset));
4954 }
4955 
4956 bool SelectionDAG::isUndef(unsigned Opcode, ArrayRef<SDValue> Ops) {
4957   switch (Opcode) {
4958   case ISD::SDIV:
4959   case ISD::UDIV:
4960   case ISD::SREM:
4961   case ISD::UREM: {
4962     // If a divisor is zero/undef or any element of a divisor vector is
4963     // zero/undef, the whole op is undef.
4964     assert(Ops.size() == 2 && "Div/rem should have 2 operands");
4965     SDValue Divisor = Ops[1];
4966     if (Divisor.isUndef() || isNullConstant(Divisor))
4967       return true;
4968 
4969     return ISD::isBuildVectorOfConstantSDNodes(Divisor.getNode()) &&
4970            llvm::any_of(Divisor->op_values(),
4971                         [](SDValue V) { return V.isUndef() ||
4972                                         isNullConstant(V); });
4973     // TODO: Handle signed overflow.
4974   }
4975   // TODO: Handle oversized shifts.
4976   default:
4977     return false;
4978   }
4979 }
4980 
4981 SDValue SelectionDAG::FoldConstantArithmetic(unsigned Opcode, const SDLoc &DL,
4982                                              EVT VT, ArrayRef<SDValue> Ops) {
4983   // If the opcode is a target-specific ISD node, there's nothing we can
4984   // do here and the operand rules may not line up with the below, so
4985   // bail early.
4986   if (Opcode >= ISD::BUILTIN_OP_END)
4987     return SDValue();
4988 
4989   // For now, the array Ops should only contain two values.
4990   // This enforcement will be removed once this function is merged with
4991   // FoldConstantVectorArithmetic
4992   if (Ops.size() != 2)
4993     return SDValue();
4994 
4995   if (isUndef(Opcode, Ops))
4996     return getUNDEF(VT);
4997 
4998   SDNode *N1 = Ops[0].getNode();
4999   SDNode *N2 = Ops[1].getNode();
5000 
5001   // Handle the case of two scalars.
5002   if (auto *C1 = dyn_cast<ConstantSDNode>(N1)) {
5003     if (auto *C2 = dyn_cast<ConstantSDNode>(N2)) {
5004       if (C1->isOpaque() || C2->isOpaque())
5005         return SDValue();
5006 
5007       Optional<APInt> FoldAttempt =
5008           FoldValue(Opcode, C1->getAPIntValue(), C2->getAPIntValue());
5009       if (!FoldAttempt)
5010         return SDValue();
5011 
5012       SDValue Folded = getConstant(FoldAttempt.getValue(), DL, VT);
5013       assert((!Folded || !VT.isVector()) &&
5014              "Can't fold vectors ops with scalar operands");
5015       return Folded;
5016     }
5017   }
5018 
5019   // fold (add Sym, c) -> Sym+c
5020   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N1))
5021     return FoldSymbolOffset(Opcode, VT, GA, N2);
5022   if (TLI->isCommutativeBinOp(Opcode))
5023     if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N2))
5024       return FoldSymbolOffset(Opcode, VT, GA, N1);
5025 
5026   // TODO: All the folds below are performed lane-by-lane and assume a fixed
5027   // vector width, however we should be able to do constant folds involving
5028   // splat vector nodes too.
5029   if (VT.isScalableVector())
5030     return SDValue();
5031 
5032   // For fixed width vectors, extract each constant element and fold them
5033   // individually. Either input may be an undef value.
5034   auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
5035   if (!BV1 && !N1->isUndef())
5036     return SDValue();
5037   auto *BV2 = dyn_cast<BuildVectorSDNode>(N2);
5038   if (!BV2 && !N2->isUndef())
5039     return SDValue();
5040   // If both operands are undef, that's handled the same way as scalars.
5041   if (!BV1 && !BV2)
5042     return SDValue();
5043 
5044   assert((!BV1 || !BV2 || BV1->getNumOperands() == BV2->getNumOperands()) &&
5045          "Vector binop with different number of elements in operands?");
5046 
5047   EVT SVT = VT.getScalarType();
5048   EVT LegalSVT = SVT;
5049   if (NewNodesMustHaveLegalTypes && LegalSVT.isInteger()) {
5050     LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT);
5051     if (LegalSVT.bitsLT(SVT))
5052       return SDValue();
5053   }
5054   SmallVector<SDValue, 4> Outputs;
5055   unsigned NumOps = BV1 ? BV1->getNumOperands() : BV2->getNumOperands();
5056   for (unsigned I = 0; I != NumOps; ++I) {
5057     SDValue V1 = BV1 ? BV1->getOperand(I) : getUNDEF(SVT);
5058     SDValue V2 = BV2 ? BV2->getOperand(I) : getUNDEF(SVT);
5059     if (SVT.isInteger()) {
5060       if (V1->getValueType(0).bitsGT(SVT))
5061         V1 = getNode(ISD::TRUNCATE, DL, SVT, V1);
5062       if (V2->getValueType(0).bitsGT(SVT))
5063         V2 = getNode(ISD::TRUNCATE, DL, SVT, V2);
5064     }
5065 
5066     if (V1->getValueType(0) != SVT || V2->getValueType(0) != SVT)
5067       return SDValue();
5068 
5069     // Fold one vector element.
5070     SDValue ScalarResult = getNode(Opcode, DL, SVT, V1, V2);
5071     if (LegalSVT != SVT)
5072       ScalarResult = getNode(ISD::SIGN_EXTEND, DL, LegalSVT, ScalarResult);
5073 
5074     // Scalar folding only succeeded if the result is a constant or UNDEF.
5075     if (!ScalarResult.isUndef() && ScalarResult.getOpcode() != ISD::Constant &&
5076         ScalarResult.getOpcode() != ISD::ConstantFP)
5077       return SDValue();
5078     Outputs.push_back(ScalarResult);
5079   }
5080 
5081   assert(VT.getVectorNumElements() == Outputs.size() &&
5082          "Vector size mismatch!");
5083 
5084   // We may have a vector type but a scalar result. Create a splat.
5085   Outputs.resize(VT.getVectorNumElements(), Outputs.back());
5086 
5087   // Build a big vector out of the scalar elements we generated.
5088   return getBuildVector(VT, SDLoc(), Outputs);
5089 }
5090 
5091 // TODO: Merge with FoldConstantArithmetic
5092 SDValue SelectionDAG::FoldConstantVectorArithmetic(unsigned Opcode,
5093                                                    const SDLoc &DL, EVT VT,
5094                                                    ArrayRef<SDValue> Ops,
5095                                                    const SDNodeFlags Flags) {
5096   // If the opcode is a target-specific ISD node, there's nothing we can
5097   // do here and the operand rules may not line up with the below, so
5098   // bail early.
5099   if (Opcode >= ISD::BUILTIN_OP_END)
5100     return SDValue();
5101 
5102   if (isUndef(Opcode, Ops))
5103     return getUNDEF(VT);
5104 
5105   // We can only fold vectors - maybe merge with FoldConstantArithmetic someday?
5106   if (!VT.isVector())
5107     return SDValue();
5108 
5109   // TODO: All the folds below are performed lane-by-lane and assume a fixed
5110   // vector width, however we should be able to do constant folds involving
5111   // splat vector nodes too.
5112   if (VT.isScalableVector())
5113     return SDValue();
5114 
5115   // From this point onwards all vectors are assumed to be fixed width.
5116   unsigned NumElts = VT.getVectorNumElements();
5117 
5118   auto IsScalarOrSameVectorSize = [&](const SDValue &Op) {
5119     return !Op.getValueType().isVector() ||
5120            Op.getValueType().getVectorNumElements() == NumElts;
5121   };
5122 
5123   auto IsConstantBuildVectorOrUndef = [&](const SDValue &Op) {
5124     BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op);
5125     return (Op.isUndef()) || (Op.getOpcode() == ISD::CONDCODE) ||
5126            (BV && BV->isConstant());
5127   };
5128 
5129   // All operands must be vector types with the same number of elements as
5130   // the result type and must be either UNDEF or a build vector of constant
5131   // or UNDEF scalars.
5132   if (!llvm::all_of(Ops, IsConstantBuildVectorOrUndef) ||
5133       !llvm::all_of(Ops, IsScalarOrSameVectorSize))
5134     return SDValue();
5135 
5136   // If we are comparing vectors, then the result needs to be a i1 boolean
5137   // that is then sign-extended back to the legal result type.
5138   EVT SVT = (Opcode == ISD::SETCC ? MVT::i1 : VT.getScalarType());
5139 
5140   // Find legal integer scalar type for constant promotion and
5141   // ensure that its scalar size is at least as large as source.
5142   EVT LegalSVT = VT.getScalarType();
5143   if (NewNodesMustHaveLegalTypes && LegalSVT.isInteger()) {
5144     LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT);
5145     if (LegalSVT.bitsLT(VT.getScalarType()))
5146       return SDValue();
5147   }
5148 
5149   // Constant fold each scalar lane separately.
5150   SmallVector<SDValue, 4> ScalarResults;
5151   for (unsigned i = 0; i != NumElts; i++) {
5152     SmallVector<SDValue, 4> ScalarOps;
5153     for (SDValue Op : Ops) {
5154       EVT InSVT = Op.getValueType().getScalarType();
5155       BuildVectorSDNode *InBV = dyn_cast<BuildVectorSDNode>(Op);
5156       if (!InBV) {
5157         // We've checked that this is UNDEF or a constant of some kind.
5158         if (Op.isUndef())
5159           ScalarOps.push_back(getUNDEF(InSVT));
5160         else
5161           ScalarOps.push_back(Op);
5162         continue;
5163       }
5164 
5165       SDValue ScalarOp = InBV->getOperand(i);
5166       EVT ScalarVT = ScalarOp.getValueType();
5167 
5168       // Build vector (integer) scalar operands may need implicit
5169       // truncation - do this before constant folding.
5170       if (ScalarVT.isInteger() && ScalarVT.bitsGT(InSVT))
5171         ScalarOp = getNode(ISD::TRUNCATE, DL, InSVT, ScalarOp);
5172 
5173       ScalarOps.push_back(ScalarOp);
5174     }
5175 
5176     // Constant fold the scalar operands.
5177     SDValue ScalarResult = getNode(Opcode, DL, SVT, ScalarOps, Flags);
5178 
5179     // Legalize the (integer) scalar constant if necessary.
5180     if (LegalSVT != SVT)
5181       ScalarResult = getNode(ISD::SIGN_EXTEND, DL, LegalSVT, ScalarResult);
5182 
5183     // Scalar folding only succeeded if the result is a constant or UNDEF.
5184     if (!ScalarResult.isUndef() && ScalarResult.getOpcode() != ISD::Constant &&
5185         ScalarResult.getOpcode() != ISD::ConstantFP)
5186       return SDValue();
5187     ScalarResults.push_back(ScalarResult);
5188   }
5189 
5190   SDValue V = getBuildVector(VT, DL, ScalarResults);
5191   NewSDValueDbgMsg(V, "New node fold constant vector: ", this);
5192   return V;
5193 }
5194 
5195 SDValue SelectionDAG::foldConstantFPMath(unsigned Opcode, const SDLoc &DL,
5196                                          EVT VT, SDValue N1, SDValue N2) {
5197   // TODO: We don't do any constant folding for strict FP opcodes here, but we
5198   //       should. That will require dealing with a potentially non-default
5199   //       rounding mode, checking the "opStatus" return value from the APFloat
5200   //       math calculations, and possibly other variations.
5201   auto *N1CFP = dyn_cast<ConstantFPSDNode>(N1.getNode());
5202   auto *N2CFP = dyn_cast<ConstantFPSDNode>(N2.getNode());
5203   if (N1CFP && N2CFP) {
5204     APFloat C1 = N1CFP->getValueAPF(), C2 = N2CFP->getValueAPF();
5205     switch (Opcode) {
5206     case ISD::FADD:
5207       C1.add(C2, APFloat::rmNearestTiesToEven);
5208       return getConstantFP(C1, DL, VT);
5209     case ISD::FSUB:
5210       C1.subtract(C2, APFloat::rmNearestTiesToEven);
5211       return getConstantFP(C1, DL, VT);
5212     case ISD::FMUL:
5213       C1.multiply(C2, APFloat::rmNearestTiesToEven);
5214       return getConstantFP(C1, DL, VT);
5215     case ISD::FDIV:
5216       C1.divide(C2, APFloat::rmNearestTiesToEven);
5217       return getConstantFP(C1, DL, VT);
5218     case ISD::FREM:
5219       C1.mod(C2);
5220       return getConstantFP(C1, DL, VT);
5221     case ISD::FCOPYSIGN:
5222       C1.copySign(C2);
5223       return getConstantFP(C1, DL, VT);
5224     default: break;
5225     }
5226   }
5227   if (N1CFP && Opcode == ISD::FP_ROUND) {
5228     APFloat C1 = N1CFP->getValueAPF();    // make copy
5229     bool Unused;
5230     // This can return overflow, underflow, or inexact; we don't care.
5231     // FIXME need to be more flexible about rounding mode.
5232     (void) C1.convert(EVTToAPFloatSemantics(VT), APFloat::rmNearestTiesToEven,
5233                       &Unused);
5234     return getConstantFP(C1, DL, VT);
5235   }
5236 
5237   switch (Opcode) {
5238   case ISD::FSUB:
5239     // -0.0 - undef --> undef (consistent with "fneg undef")
5240     if (N1CFP && N1CFP->getValueAPF().isNegZero() && N2.isUndef())
5241       return getUNDEF(VT);
5242     LLVM_FALLTHROUGH;
5243 
5244   case ISD::FADD:
5245   case ISD::FMUL:
5246   case ISD::FDIV:
5247   case ISD::FREM:
5248     // If both operands are undef, the result is undef. If 1 operand is undef,
5249     // the result is NaN. This should match the behavior of the IR optimizer.
5250     if (N1.isUndef() && N2.isUndef())
5251       return getUNDEF(VT);
5252     if (N1.isUndef() || N2.isUndef())
5253       return getConstantFP(APFloat::getNaN(EVTToAPFloatSemantics(VT)), DL, VT);
5254   }
5255   return SDValue();
5256 }
5257 
5258 SDValue SelectionDAG::getAssertAlign(const SDLoc &DL, SDValue Val, Align A) {
5259   assert(Val.getValueType().isInteger() && "Invalid AssertAlign!");
5260 
5261   // There's no need to assert on a byte-aligned pointer. All pointers are at
5262   // least byte aligned.
5263   if (A == Align(1))
5264     return Val;
5265 
5266   FoldingSetNodeID ID;
5267   AddNodeIDNode(ID, ISD::AssertAlign, getVTList(Val.getValueType()), {Val});
5268   ID.AddInteger(A.value());
5269 
5270   void *IP = nullptr;
5271   if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
5272     return SDValue(E, 0);
5273 
5274   auto *N = newSDNode<AssertAlignSDNode>(DL.getIROrder(), DL.getDebugLoc(),
5275                                          Val.getValueType(), A);
5276   createOperands(N, {Val});
5277 
5278   CSEMap.InsertNode(N, IP);
5279   InsertNode(N);
5280 
5281   SDValue V(N, 0);
5282   NewSDValueDbgMsg(V, "Creating new node: ", this);
5283   return V;
5284 }
5285 
5286 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
5287                               SDValue N1, SDValue N2) {
5288   SDNodeFlags Flags;
5289   if (Inserter)
5290     Flags = Inserter->getFlags();
5291   return getNode(Opcode, DL, VT, N1, N2, Flags);
5292 }
5293 
5294 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
5295                               SDValue N1, SDValue N2, const SDNodeFlags Flags) {
5296   assert(N1.getOpcode() != ISD::DELETED_NODE &&
5297          N2.getOpcode() != ISD::DELETED_NODE &&
5298          "Operand is DELETED_NODE!");
5299   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
5300   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
5301   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
5302   ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2);
5303 
5304   // Canonicalize constant to RHS if commutative.
5305   if (TLI->isCommutativeBinOp(Opcode)) {
5306     if (N1C && !N2C) {
5307       std::swap(N1C, N2C);
5308       std::swap(N1, N2);
5309     } else if (N1CFP && !N2CFP) {
5310       std::swap(N1CFP, N2CFP);
5311       std::swap(N1, N2);
5312     }
5313   }
5314 
5315   switch (Opcode) {
5316   default: break;
5317   case ISD::TokenFactor:
5318     assert(VT == MVT::Other && N1.getValueType() == MVT::Other &&
5319            N2.getValueType() == MVT::Other && "Invalid token factor!");
5320     // Fold trivial token factors.
5321     if (N1.getOpcode() == ISD::EntryToken) return N2;
5322     if (N2.getOpcode() == ISD::EntryToken) return N1;
5323     if (N1 == N2) return N1;
5324     break;
5325   case ISD::BUILD_VECTOR: {
5326     // Attempt to simplify BUILD_VECTOR.
5327     SDValue Ops[] = {N1, N2};
5328     if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
5329       return V;
5330     break;
5331   }
5332   case ISD::CONCAT_VECTORS: {
5333     SDValue Ops[] = {N1, N2};
5334     if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this))
5335       return V;
5336     break;
5337   }
5338   case ISD::AND:
5339     assert(VT.isInteger() && "This operator does not apply to FP types!");
5340     assert(N1.getValueType() == N2.getValueType() &&
5341            N1.getValueType() == VT && "Binary operator types must match!");
5342     // (X & 0) -> 0.  This commonly occurs when legalizing i64 values, so it's
5343     // worth handling here.
5344     if (N2C && N2C->isNullValue())
5345       return N2;
5346     if (N2C && N2C->isAllOnesValue())  // X & -1 -> X
5347       return N1;
5348     break;
5349   case ISD::OR:
5350   case ISD::XOR:
5351   case ISD::ADD:
5352   case ISD::SUB:
5353     assert(VT.isInteger() && "This operator does not apply to FP types!");
5354     assert(N1.getValueType() == N2.getValueType() &&
5355            N1.getValueType() == VT && "Binary operator types must match!");
5356     // (X ^|+- 0) -> X.  This commonly occurs when legalizing i64 values, so
5357     // it's worth handling here.
5358     if (N2C && N2C->isNullValue())
5359       return N1;
5360     if ((Opcode == ISD::ADD || Opcode == ISD::SUB) && VT.isVector() &&
5361         VT.getVectorElementType() == MVT::i1)
5362       return getNode(ISD::XOR, DL, VT, N1, N2);
5363     break;
5364   case ISD::MUL:
5365     assert(VT.isInteger() && "This operator does not apply to FP types!");
5366     assert(N1.getValueType() == N2.getValueType() &&
5367            N1.getValueType() == VT && "Binary operator types must match!");
5368     if (VT.isVector() && VT.getVectorElementType() == MVT::i1)
5369       return getNode(ISD::AND, DL, VT, N1, N2);
5370     if (N2C && (N1.getOpcode() == ISD::VSCALE) && Flags.hasNoSignedWrap()) {
5371       const APInt &MulImm = N1->getConstantOperandAPInt(0);
5372       const APInt &N2CImm = N2C->getAPIntValue();
5373       return getVScale(DL, VT, MulImm * N2CImm);
5374     }
5375     break;
5376   case ISD::UDIV:
5377   case ISD::UREM:
5378   case ISD::MULHU:
5379   case ISD::MULHS:
5380   case ISD::SDIV:
5381   case ISD::SREM:
5382   case ISD::SADDSAT:
5383   case ISD::SSUBSAT:
5384   case ISD::UADDSAT:
5385   case ISD::USUBSAT:
5386     assert(VT.isInteger() && "This operator does not apply to FP types!");
5387     assert(N1.getValueType() == N2.getValueType() &&
5388            N1.getValueType() == VT && "Binary operator types must match!");
5389     if (VT.isVector() && VT.getVectorElementType() == MVT::i1) {
5390       // fold (add_sat x, y) -> (or x, y) for bool types.
5391       if (Opcode == ISD::SADDSAT || Opcode == ISD::UADDSAT)
5392         return getNode(ISD::OR, DL, VT, N1, N2);
5393       // fold (sub_sat x, y) -> (and x, ~y) for bool types.
5394       if (Opcode == ISD::SSUBSAT || Opcode == ISD::USUBSAT)
5395         return getNode(ISD::AND, DL, VT, N1, getNOT(DL, N2, VT));
5396     }
5397     break;
5398   case ISD::SMIN:
5399   case ISD::UMAX:
5400     assert(VT.isInteger() && "This operator does not apply to FP types!");
5401     assert(N1.getValueType() == N2.getValueType() &&
5402            N1.getValueType() == VT && "Binary operator types must match!");
5403     if (VT.isVector() && VT.getVectorElementType() == MVT::i1)
5404       return getNode(ISD::OR, DL, VT, N1, N2);
5405     break;
5406   case ISD::SMAX:
5407   case ISD::UMIN:
5408     assert(VT.isInteger() && "This operator does not apply to FP types!");
5409     assert(N1.getValueType() == N2.getValueType() &&
5410            N1.getValueType() == VT && "Binary operator types must match!");
5411     if (VT.isVector() && VT.getVectorElementType() == MVT::i1)
5412       return getNode(ISD::AND, DL, VT, N1, N2);
5413     break;
5414   case ISD::FADD:
5415   case ISD::FSUB:
5416   case ISD::FMUL:
5417   case ISD::FDIV:
5418   case ISD::FREM:
5419     assert(VT.isFloatingPoint() && "This operator only applies to FP types!");
5420     assert(N1.getValueType() == N2.getValueType() &&
5421            N1.getValueType() == VT && "Binary operator types must match!");
5422     if (SDValue V = simplifyFPBinop(Opcode, N1, N2, Flags))
5423       return V;
5424     break;
5425   case ISD::FCOPYSIGN:   // N1 and result must match.  N1/N2 need not match.
5426     assert(N1.getValueType() == VT &&
5427            N1.getValueType().isFloatingPoint() &&
5428            N2.getValueType().isFloatingPoint() &&
5429            "Invalid FCOPYSIGN!");
5430     break;
5431   case ISD::SHL:
5432     if (N2C && (N1.getOpcode() == ISD::VSCALE) && Flags.hasNoSignedWrap()) {
5433       const APInt &MulImm = N1->getConstantOperandAPInt(0);
5434       const APInt &ShiftImm = N2C->getAPIntValue();
5435       return getVScale(DL, VT, MulImm << ShiftImm);
5436     }
5437     LLVM_FALLTHROUGH;
5438   case ISD::SRA:
5439   case ISD::SRL:
5440     if (SDValue V = simplifyShift(N1, N2))
5441       return V;
5442     LLVM_FALLTHROUGH;
5443   case ISD::ROTL:
5444   case ISD::ROTR:
5445     assert(VT == N1.getValueType() &&
5446            "Shift operators return type must be the same as their first arg");
5447     assert(VT.isInteger() && N2.getValueType().isInteger() &&
5448            "Shifts only work on integers");
5449     assert((!VT.isVector() || VT == N2.getValueType()) &&
5450            "Vector shift amounts must be in the same as their first arg");
5451     // Verify that the shift amount VT is big enough to hold valid shift
5452     // amounts.  This catches things like trying to shift an i1024 value by an
5453     // i8, which is easy to fall into in generic code that uses
5454     // TLI.getShiftAmount().
5455     assert(N2.getValueType().getScalarSizeInBits() >=
5456                Log2_32_Ceil(VT.getScalarSizeInBits()) &&
5457            "Invalid use of small shift amount with oversized value!");
5458 
5459     // Always fold shifts of i1 values so the code generator doesn't need to
5460     // handle them.  Since we know the size of the shift has to be less than the
5461     // size of the value, the shift/rotate count is guaranteed to be zero.
5462     if (VT == MVT::i1)
5463       return N1;
5464     if (N2C && N2C->isNullValue())
5465       return N1;
5466     break;
5467   case ISD::FP_ROUND:
5468     assert(VT.isFloatingPoint() &&
5469            N1.getValueType().isFloatingPoint() &&
5470            VT.bitsLE(N1.getValueType()) &&
5471            N2C && (N2C->getZExtValue() == 0 || N2C->getZExtValue() == 1) &&
5472            "Invalid FP_ROUND!");
5473     if (N1.getValueType() == VT) return N1;  // noop conversion.
5474     break;
5475   case ISD::AssertSext:
5476   case ISD::AssertZext: {
5477     EVT EVT = cast<VTSDNode>(N2)->getVT();
5478     assert(VT == N1.getValueType() && "Not an inreg extend!");
5479     assert(VT.isInteger() && EVT.isInteger() &&
5480            "Cannot *_EXTEND_INREG FP types");
5481     assert(!EVT.isVector() &&
5482            "AssertSExt/AssertZExt type should be the vector element type "
5483            "rather than the vector type!");
5484     assert(EVT.bitsLE(VT.getScalarType()) && "Not extending!");
5485     if (VT.getScalarType() == EVT) return N1; // noop assertion.
5486     break;
5487   }
5488   case ISD::SIGN_EXTEND_INREG: {
5489     EVT EVT = cast<VTSDNode>(N2)->getVT();
5490     assert(VT == N1.getValueType() && "Not an inreg extend!");
5491     assert(VT.isInteger() && EVT.isInteger() &&
5492            "Cannot *_EXTEND_INREG FP types");
5493     assert(EVT.isVector() == VT.isVector() &&
5494            "SIGN_EXTEND_INREG type should be vector iff the operand "
5495            "type is vector!");
5496     assert((!EVT.isVector() ||
5497             EVT.getVectorElementCount() == VT.getVectorElementCount()) &&
5498            "Vector element counts must match in SIGN_EXTEND_INREG");
5499     assert(EVT.bitsLE(VT) && "Not extending!");
5500     if (EVT == VT) return N1;  // Not actually extending
5501 
5502     auto SignExtendInReg = [&](APInt Val, llvm::EVT ConstantVT) {
5503       unsigned FromBits = EVT.getScalarSizeInBits();
5504       Val <<= Val.getBitWidth() - FromBits;
5505       Val.ashrInPlace(Val.getBitWidth() - FromBits);
5506       return getConstant(Val, DL, ConstantVT);
5507     };
5508 
5509     if (N1C) {
5510       const APInt &Val = N1C->getAPIntValue();
5511       return SignExtendInReg(Val, VT);
5512     }
5513     if (ISD::isBuildVectorOfConstantSDNodes(N1.getNode())) {
5514       SmallVector<SDValue, 8> Ops;
5515       llvm::EVT OpVT = N1.getOperand(0).getValueType();
5516       for (int i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
5517         SDValue Op = N1.getOperand(i);
5518         if (Op.isUndef()) {
5519           Ops.push_back(getUNDEF(OpVT));
5520           continue;
5521         }
5522         ConstantSDNode *C = cast<ConstantSDNode>(Op);
5523         APInt Val = C->getAPIntValue();
5524         Ops.push_back(SignExtendInReg(Val, OpVT));
5525       }
5526       return getBuildVector(VT, DL, Ops);
5527     }
5528     break;
5529   }
5530   case ISD::EXTRACT_VECTOR_ELT:
5531     assert(VT.getSizeInBits() >= N1.getValueType().getScalarSizeInBits() &&
5532            "The result of EXTRACT_VECTOR_ELT must be at least as wide as the \
5533              element type of the vector.");
5534 
5535     // Extract from an undefined value or using an undefined index is undefined.
5536     if (N1.isUndef() || N2.isUndef())
5537       return getUNDEF(VT);
5538 
5539     // EXTRACT_VECTOR_ELT of out-of-bounds element is an UNDEF for fixed length
5540     // vectors. For scalable vectors we will provide appropriate support for
5541     // dealing with arbitrary indices.
5542     if (N2C && N1.getValueType().isFixedLengthVector() &&
5543         N2C->getAPIntValue().uge(N1.getValueType().getVectorNumElements()))
5544       return getUNDEF(VT);
5545 
5546     // EXTRACT_VECTOR_ELT of CONCAT_VECTORS is often formed while lowering is
5547     // expanding copies of large vectors from registers. This only works for
5548     // fixed length vectors, since we need to know the exact number of
5549     // elements.
5550     if (N2C && N1.getOperand(0).getValueType().isFixedLengthVector() &&
5551         N1.getOpcode() == ISD::CONCAT_VECTORS && N1.getNumOperands() > 0) {
5552       unsigned Factor =
5553         N1.getOperand(0).getValueType().getVectorNumElements();
5554       return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
5555                      N1.getOperand(N2C->getZExtValue() / Factor),
5556                      getVectorIdxConstant(N2C->getZExtValue() % Factor, DL));
5557     }
5558 
5559     // EXTRACT_VECTOR_ELT of BUILD_VECTOR or SPLAT_VECTOR is often formed while
5560     // lowering is expanding large vector constants.
5561     if (N2C && (N1.getOpcode() == ISD::BUILD_VECTOR ||
5562                 N1.getOpcode() == ISD::SPLAT_VECTOR)) {
5563       assert((N1.getOpcode() != ISD::BUILD_VECTOR ||
5564               N1.getValueType().isFixedLengthVector()) &&
5565              "BUILD_VECTOR used for scalable vectors");
5566       unsigned Index =
5567           N1.getOpcode() == ISD::BUILD_VECTOR ? N2C->getZExtValue() : 0;
5568       SDValue Elt = N1.getOperand(Index);
5569 
5570       if (VT != Elt.getValueType())
5571         // If the vector element type is not legal, the BUILD_VECTOR operands
5572         // are promoted and implicitly truncated, and the result implicitly
5573         // extended. Make that explicit here.
5574         Elt = getAnyExtOrTrunc(Elt, DL, VT);
5575 
5576       return Elt;
5577     }
5578 
5579     // EXTRACT_VECTOR_ELT of INSERT_VECTOR_ELT is often formed when vector
5580     // operations are lowered to scalars.
5581     if (N1.getOpcode() == ISD::INSERT_VECTOR_ELT) {
5582       // If the indices are the same, return the inserted element else
5583       // if the indices are known different, extract the element from
5584       // the original vector.
5585       SDValue N1Op2 = N1.getOperand(2);
5586       ConstantSDNode *N1Op2C = dyn_cast<ConstantSDNode>(N1Op2);
5587 
5588       if (N1Op2C && N2C) {
5589         if (N1Op2C->getZExtValue() == N2C->getZExtValue()) {
5590           if (VT == N1.getOperand(1).getValueType())
5591             return N1.getOperand(1);
5592           else
5593             return getSExtOrTrunc(N1.getOperand(1), DL, VT);
5594         }
5595 
5596         return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0), N2);
5597       }
5598     }
5599 
5600     // EXTRACT_VECTOR_ELT of v1iX EXTRACT_SUBVECTOR could be formed
5601     // when vector types are scalarized and v1iX is legal.
5602     // vextract (v1iX extract_subvector(vNiX, Idx)) -> vextract(vNiX,Idx).
5603     // Here we are completely ignoring the extract element index (N2),
5604     // which is fine for fixed width vectors, since any index other than 0
5605     // is undefined anyway. However, this cannot be ignored for scalable
5606     // vectors - in theory we could support this, but we don't want to do this
5607     // without a profitability check.
5608     if (N1.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
5609         N1.getValueType().isFixedLengthVector() &&
5610         N1.getValueType().getVectorNumElements() == 1) {
5611       return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0),
5612                      N1.getOperand(1));
5613     }
5614     break;
5615   case ISD::EXTRACT_ELEMENT:
5616     assert(N2C && (unsigned)N2C->getZExtValue() < 2 && "Bad EXTRACT_ELEMENT!");
5617     assert(!N1.getValueType().isVector() && !VT.isVector() &&
5618            (N1.getValueType().isInteger() == VT.isInteger()) &&
5619            N1.getValueType() != VT &&
5620            "Wrong types for EXTRACT_ELEMENT!");
5621 
5622     // EXTRACT_ELEMENT of BUILD_PAIR is often formed while legalize is expanding
5623     // 64-bit integers into 32-bit parts.  Instead of building the extract of
5624     // the BUILD_PAIR, only to have legalize rip it apart, just do it now.
5625     if (N1.getOpcode() == ISD::BUILD_PAIR)
5626       return N1.getOperand(N2C->getZExtValue());
5627 
5628     // EXTRACT_ELEMENT of a constant int is also very common.
5629     if (N1C) {
5630       unsigned ElementSize = VT.getSizeInBits();
5631       unsigned Shift = ElementSize * N2C->getZExtValue();
5632       const APInt &Val = N1C->getAPIntValue();
5633       return getConstant(Val.extractBits(ElementSize, Shift), DL, VT);
5634     }
5635     break;
5636   case ISD::EXTRACT_SUBVECTOR:
5637     EVT N1VT = N1.getValueType();
5638     assert(VT.isVector() && N1VT.isVector() &&
5639            "Extract subvector VTs must be vectors!");
5640     assert(VT.getVectorElementType() == N1VT.getVectorElementType() &&
5641            "Extract subvector VTs must have the same element type!");
5642     assert((VT.isFixedLengthVector() || N1VT.isScalableVector()) &&
5643            "Cannot extract a scalable vector from a fixed length vector!");
5644     assert((VT.isScalableVector() != N1VT.isScalableVector() ||
5645             VT.getVectorMinNumElements() <= N1VT.getVectorMinNumElements()) &&
5646            "Extract subvector must be from larger vector to smaller vector!");
5647     assert(N2C && "Extract subvector index must be a constant");
5648     assert((VT.isScalableVector() != N1VT.isScalableVector() ||
5649             (VT.getVectorMinNumElements() + N2C->getZExtValue()) <=
5650                 N1VT.getVectorMinNumElements()) &&
5651            "Extract subvector overflow!");
5652     assert(N2C->getAPIntValue().getBitWidth() ==
5653                TLI->getVectorIdxTy(getDataLayout()).getFixedSizeInBits() &&
5654            "Constant index for EXTRACT_SUBVECTOR has an invalid size");
5655 
5656     // Trivial extraction.
5657     if (VT == N1VT)
5658       return N1;
5659 
5660     // EXTRACT_SUBVECTOR of an UNDEF is an UNDEF.
5661     if (N1.isUndef())
5662       return getUNDEF(VT);
5663 
5664     // EXTRACT_SUBVECTOR of CONCAT_VECTOR can be simplified if the pieces of
5665     // the concat have the same type as the extract.
5666     if (N1.getOpcode() == ISD::CONCAT_VECTORS && N1.getNumOperands() > 0 &&
5667         VT == N1.getOperand(0).getValueType()) {
5668       unsigned Factor = VT.getVectorMinNumElements();
5669       return N1.getOperand(N2C->getZExtValue() / Factor);
5670     }
5671 
5672     // EXTRACT_SUBVECTOR of INSERT_SUBVECTOR is often created
5673     // during shuffle legalization.
5674     if (N1.getOpcode() == ISD::INSERT_SUBVECTOR && N2 == N1.getOperand(2) &&
5675         VT == N1.getOperand(1).getValueType())
5676       return N1.getOperand(1);
5677     break;
5678   }
5679 
5680   // Perform trivial constant folding.
5681   if (SDValue SV = FoldConstantArithmetic(Opcode, DL, VT, {N1, N2}))
5682     return SV;
5683 
5684   if (SDValue V = foldConstantFPMath(Opcode, DL, VT, N1, N2))
5685     return V;
5686 
5687   // Canonicalize an UNDEF to the RHS, even over a constant.
5688   if (N1.isUndef()) {
5689     if (TLI->isCommutativeBinOp(Opcode)) {
5690       std::swap(N1, N2);
5691     } else {
5692       switch (Opcode) {
5693       case ISD::SIGN_EXTEND_INREG:
5694       case ISD::SUB:
5695         return getUNDEF(VT);     // fold op(undef, arg2) -> undef
5696       case ISD::UDIV:
5697       case ISD::SDIV:
5698       case ISD::UREM:
5699       case ISD::SREM:
5700       case ISD::SSUBSAT:
5701       case ISD::USUBSAT:
5702         return getConstant(0, DL, VT);    // fold op(undef, arg2) -> 0
5703       }
5704     }
5705   }
5706 
5707   // Fold a bunch of operators when the RHS is undef.
5708   if (N2.isUndef()) {
5709     switch (Opcode) {
5710     case ISD::XOR:
5711       if (N1.isUndef())
5712         // Handle undef ^ undef -> 0 special case. This is a common
5713         // idiom (misuse).
5714         return getConstant(0, DL, VT);
5715       LLVM_FALLTHROUGH;
5716     case ISD::ADD:
5717     case ISD::SUB:
5718     case ISD::UDIV:
5719     case ISD::SDIV:
5720     case ISD::UREM:
5721     case ISD::SREM:
5722       return getUNDEF(VT);       // fold op(arg1, undef) -> undef
5723     case ISD::MUL:
5724     case ISD::AND:
5725     case ISD::SSUBSAT:
5726     case ISD::USUBSAT:
5727       return getConstant(0, DL, VT);  // fold op(arg1, undef) -> 0
5728     case ISD::OR:
5729     case ISD::SADDSAT:
5730     case ISD::UADDSAT:
5731       return getAllOnesConstant(DL, VT);
5732     }
5733   }
5734 
5735   // Memoize this node if possible.
5736   SDNode *N;
5737   SDVTList VTs = getVTList(VT);
5738   SDValue Ops[] = {N1, N2};
5739   if (VT != MVT::Glue) {
5740     FoldingSetNodeID ID;
5741     AddNodeIDNode(ID, Opcode, VTs, Ops);
5742     void *IP = nullptr;
5743     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
5744       E->intersectFlagsWith(Flags);
5745       return SDValue(E, 0);
5746     }
5747 
5748     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
5749     N->setFlags(Flags);
5750     createOperands(N, Ops);
5751     CSEMap.InsertNode(N, IP);
5752   } else {
5753     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
5754     createOperands(N, Ops);
5755   }
5756 
5757   InsertNode(N);
5758   SDValue V = SDValue(N, 0);
5759   NewSDValueDbgMsg(V, "Creating new node: ", this);
5760   return V;
5761 }
5762 
5763 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
5764                               SDValue N1, SDValue N2, SDValue N3) {
5765   SDNodeFlags Flags;
5766   if (Inserter)
5767     Flags = Inserter->getFlags();
5768   return getNode(Opcode, DL, VT, N1, N2, N3, Flags);
5769 }
5770 
5771 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
5772                               SDValue N1, SDValue N2, SDValue N3,
5773                               const SDNodeFlags Flags) {
5774   assert(N1.getOpcode() != ISD::DELETED_NODE &&
5775          N2.getOpcode() != ISD::DELETED_NODE &&
5776          N3.getOpcode() != ISD::DELETED_NODE &&
5777          "Operand is DELETED_NODE!");
5778   // Perform various simplifications.
5779   switch (Opcode) {
5780   case ISD::FMA: {
5781     assert(VT.isFloatingPoint() && "This operator only applies to FP types!");
5782     assert(N1.getValueType() == VT && N2.getValueType() == VT &&
5783            N3.getValueType() == VT && "FMA types must match!");
5784     ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
5785     ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2);
5786     ConstantFPSDNode *N3CFP = dyn_cast<ConstantFPSDNode>(N3);
5787     if (N1CFP && N2CFP && N3CFP) {
5788       APFloat  V1 = N1CFP->getValueAPF();
5789       const APFloat &V2 = N2CFP->getValueAPF();
5790       const APFloat &V3 = N3CFP->getValueAPF();
5791       V1.fusedMultiplyAdd(V2, V3, APFloat::rmNearestTiesToEven);
5792       return getConstantFP(V1, DL, VT);
5793     }
5794     break;
5795   }
5796   case ISD::BUILD_VECTOR: {
5797     // Attempt to simplify BUILD_VECTOR.
5798     SDValue Ops[] = {N1, N2, N3};
5799     if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
5800       return V;
5801     break;
5802   }
5803   case ISD::CONCAT_VECTORS: {
5804     SDValue Ops[] = {N1, N2, N3};
5805     if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this))
5806       return V;
5807     break;
5808   }
5809   case ISD::SETCC: {
5810     assert(VT.isInteger() && "SETCC result type must be an integer!");
5811     assert(N1.getValueType() == N2.getValueType() &&
5812            "SETCC operands must have the same type!");
5813     assert(VT.isVector() == N1.getValueType().isVector() &&
5814            "SETCC type should be vector iff the operand type is vector!");
5815     assert((!VT.isVector() || VT.getVectorElementCount() ==
5816                                   N1.getValueType().getVectorElementCount()) &&
5817            "SETCC vector element counts must match!");
5818     // Use FoldSetCC to simplify SETCC's.
5819     if (SDValue V = FoldSetCC(VT, N1, N2, cast<CondCodeSDNode>(N3)->get(), DL))
5820       return V;
5821     // Vector constant folding.
5822     SDValue Ops[] = {N1, N2, N3};
5823     if (SDValue V = FoldConstantVectorArithmetic(Opcode, DL, VT, Ops)) {
5824       NewSDValueDbgMsg(V, "New node vector constant folding: ", this);
5825       return V;
5826     }
5827     break;
5828   }
5829   case ISD::SELECT:
5830   case ISD::VSELECT:
5831     if (SDValue V = simplifySelect(N1, N2, N3))
5832       return V;
5833     break;
5834   case ISD::VECTOR_SHUFFLE:
5835     llvm_unreachable("should use getVectorShuffle constructor!");
5836   case ISD::INSERT_VECTOR_ELT: {
5837     ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3);
5838     // INSERT_VECTOR_ELT into out-of-bounds element is an UNDEF, except
5839     // for scalable vectors where we will generate appropriate code to
5840     // deal with out-of-bounds cases correctly.
5841     if (N3C && N1.getValueType().isFixedLengthVector() &&
5842         N3C->getZExtValue() >= N1.getValueType().getVectorNumElements())
5843       return getUNDEF(VT);
5844 
5845     // Undefined index can be assumed out-of-bounds, so that's UNDEF too.
5846     if (N3.isUndef())
5847       return getUNDEF(VT);
5848 
5849     // If the inserted element is an UNDEF, just use the input vector.
5850     if (N2.isUndef())
5851       return N1;
5852 
5853     break;
5854   }
5855   case ISD::INSERT_SUBVECTOR: {
5856     // Inserting undef into undef is still undef.
5857     if (N1.isUndef() && N2.isUndef())
5858       return getUNDEF(VT);
5859 
5860     EVT N2VT = N2.getValueType();
5861     assert(VT == N1.getValueType() &&
5862            "Dest and insert subvector source types must match!");
5863     assert(VT.isVector() && N2VT.isVector() &&
5864            "Insert subvector VTs must be vectors!");
5865     assert((VT.isScalableVector() || N2VT.isFixedLengthVector()) &&
5866            "Cannot insert a scalable vector into a fixed length vector!");
5867     assert((VT.isScalableVector() != N2VT.isScalableVector() ||
5868             VT.getVectorMinNumElements() >= N2VT.getVectorMinNumElements()) &&
5869            "Insert subvector must be from smaller vector to larger vector!");
5870     assert(isa<ConstantSDNode>(N3) &&
5871            "Insert subvector index must be constant");
5872     assert((VT.isScalableVector() != N2VT.isScalableVector() ||
5873             (N2VT.getVectorMinNumElements() +
5874              cast<ConstantSDNode>(N3)->getZExtValue()) <=
5875                 VT.getVectorMinNumElements()) &&
5876            "Insert subvector overflow!");
5877     assert(cast<ConstantSDNode>(N3)->getAPIntValue().getBitWidth() ==
5878                TLI->getVectorIdxTy(getDataLayout()).getFixedSizeInBits() &&
5879            "Constant index for INSERT_SUBVECTOR has an invalid size");
5880 
5881     // Trivial insertion.
5882     if (VT == N2VT)
5883       return N2;
5884 
5885     // If this is an insert of an extracted vector into an undef vector, we
5886     // can just use the input to the extract.
5887     if (N1.isUndef() && N2.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
5888         N2.getOperand(1) == N3 && N2.getOperand(0).getValueType() == VT)
5889       return N2.getOperand(0);
5890     break;
5891   }
5892   case ISD::BITCAST:
5893     // Fold bit_convert nodes from a type to themselves.
5894     if (N1.getValueType() == VT)
5895       return N1;
5896     break;
5897   }
5898 
5899   // Memoize node if it doesn't produce a flag.
5900   SDNode *N;
5901   SDVTList VTs = getVTList(VT);
5902   SDValue Ops[] = {N1, N2, N3};
5903   if (VT != MVT::Glue) {
5904     FoldingSetNodeID ID;
5905     AddNodeIDNode(ID, Opcode, VTs, Ops);
5906     void *IP = nullptr;
5907     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
5908       E->intersectFlagsWith(Flags);
5909       return SDValue(E, 0);
5910     }
5911 
5912     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
5913     N->setFlags(Flags);
5914     createOperands(N, Ops);
5915     CSEMap.InsertNode(N, IP);
5916   } else {
5917     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
5918     createOperands(N, Ops);
5919   }
5920 
5921   InsertNode(N);
5922   SDValue V = SDValue(N, 0);
5923   NewSDValueDbgMsg(V, "Creating new node: ", this);
5924   return V;
5925 }
5926 
5927 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
5928                               SDValue N1, SDValue N2, SDValue N3, SDValue N4) {
5929   SDValue Ops[] = { N1, N2, N3, N4 };
5930   return getNode(Opcode, DL, VT, Ops);
5931 }
5932 
5933 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
5934                               SDValue N1, SDValue N2, SDValue N3, SDValue N4,
5935                               SDValue N5) {
5936   SDValue Ops[] = { N1, N2, N3, N4, N5 };
5937   return getNode(Opcode, DL, VT, Ops);
5938 }
5939 
5940 /// getStackArgumentTokenFactor - Compute a TokenFactor to force all
5941 /// the incoming stack arguments to be loaded from the stack.
5942 SDValue SelectionDAG::getStackArgumentTokenFactor(SDValue Chain) {
5943   SmallVector<SDValue, 8> ArgChains;
5944 
5945   // Include the original chain at the beginning of the list. When this is
5946   // used by target LowerCall hooks, this helps legalize find the
5947   // CALLSEQ_BEGIN node.
5948   ArgChains.push_back(Chain);
5949 
5950   // Add a chain value for each stack argument.
5951   for (SDNode::use_iterator U = getEntryNode().getNode()->use_begin(),
5952        UE = getEntryNode().getNode()->use_end(); U != UE; ++U)
5953     if (LoadSDNode *L = dyn_cast<LoadSDNode>(*U))
5954       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
5955         if (FI->getIndex() < 0)
5956           ArgChains.push_back(SDValue(L, 1));
5957 
5958   // Build a tokenfactor for all the chains.
5959   return getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains);
5960 }
5961 
5962 /// getMemsetValue - Vectorized representation of the memset value
5963 /// operand.
5964 static SDValue getMemsetValue(SDValue Value, EVT VT, SelectionDAG &DAG,
5965                               const SDLoc &dl) {
5966   assert(!Value.isUndef());
5967 
5968   unsigned NumBits = VT.getScalarSizeInBits();
5969   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
5970     assert(C->getAPIntValue().getBitWidth() == 8);
5971     APInt Val = APInt::getSplat(NumBits, C->getAPIntValue());
5972     if (VT.isInteger()) {
5973       bool IsOpaque = VT.getSizeInBits() > 64 ||
5974           !DAG.getTargetLoweringInfo().isLegalStoreImmediate(C->getSExtValue());
5975       return DAG.getConstant(Val, dl, VT, false, IsOpaque);
5976     }
5977     return DAG.getConstantFP(APFloat(DAG.EVTToAPFloatSemantics(VT), Val), dl,
5978                              VT);
5979   }
5980 
5981   assert(Value.getValueType() == MVT::i8 && "memset with non-byte fill value?");
5982   EVT IntVT = VT.getScalarType();
5983   if (!IntVT.isInteger())
5984     IntVT = EVT::getIntegerVT(*DAG.getContext(), IntVT.getSizeInBits());
5985 
5986   Value = DAG.getNode(ISD::ZERO_EXTEND, dl, IntVT, Value);
5987   if (NumBits > 8) {
5988     // Use a multiplication with 0x010101... to extend the input to the
5989     // required length.
5990     APInt Magic = APInt::getSplat(NumBits, APInt(8, 0x01));
5991     Value = DAG.getNode(ISD::MUL, dl, IntVT, Value,
5992                         DAG.getConstant(Magic, dl, IntVT));
5993   }
5994 
5995   if (VT != Value.getValueType() && !VT.isInteger())
5996     Value = DAG.getBitcast(VT.getScalarType(), Value);
5997   if (VT != Value.getValueType())
5998     Value = DAG.getSplatBuildVector(VT, dl, Value);
5999 
6000   return Value;
6001 }
6002 
6003 /// getMemsetStringVal - Similar to getMemsetValue. Except this is only
6004 /// used when a memcpy is turned into a memset when the source is a constant
6005 /// string ptr.
6006 static SDValue getMemsetStringVal(EVT VT, const SDLoc &dl, SelectionDAG &DAG,
6007                                   const TargetLowering &TLI,
6008                                   const ConstantDataArraySlice &Slice) {
6009   // Handle vector with all elements zero.
6010   if (Slice.Array == nullptr) {
6011     if (VT.isInteger())
6012       return DAG.getConstant(0, dl, VT);
6013     else if (VT == MVT::f32 || VT == MVT::f64 || VT == MVT::f128)
6014       return DAG.getConstantFP(0.0, dl, VT);
6015     else if (VT.isVector()) {
6016       unsigned NumElts = VT.getVectorNumElements();
6017       MVT EltVT = (VT.getVectorElementType() == MVT::f32) ? MVT::i32 : MVT::i64;
6018       return DAG.getNode(ISD::BITCAST, dl, VT,
6019                          DAG.getConstant(0, dl,
6020                                          EVT::getVectorVT(*DAG.getContext(),
6021                                                           EltVT, NumElts)));
6022     } else
6023       llvm_unreachable("Expected type!");
6024   }
6025 
6026   assert(!VT.isVector() && "Can't handle vector type here!");
6027   unsigned NumVTBits = VT.getSizeInBits();
6028   unsigned NumVTBytes = NumVTBits / 8;
6029   unsigned NumBytes = std::min(NumVTBytes, unsigned(Slice.Length));
6030 
6031   APInt Val(NumVTBits, 0);
6032   if (DAG.getDataLayout().isLittleEndian()) {
6033     for (unsigned i = 0; i != NumBytes; ++i)
6034       Val |= (uint64_t)(unsigned char)Slice[i] << i*8;
6035   } else {
6036     for (unsigned i = 0; i != NumBytes; ++i)
6037       Val |= (uint64_t)(unsigned char)Slice[i] << (NumVTBytes-i-1)*8;
6038   }
6039 
6040   // If the "cost" of materializing the integer immediate is less than the cost
6041   // of a load, then it is cost effective to turn the load into the immediate.
6042   Type *Ty = VT.getTypeForEVT(*DAG.getContext());
6043   if (TLI.shouldConvertConstantLoadToIntImm(Val, Ty))
6044     return DAG.getConstant(Val, dl, VT);
6045   return SDValue(nullptr, 0);
6046 }
6047 
6048 SDValue SelectionDAG::getMemBasePlusOffset(SDValue Base, TypeSize Offset,
6049                                            const SDLoc &DL,
6050                                            const SDNodeFlags Flags) {
6051   EVT VT = Base.getValueType();
6052   SDValue Index;
6053 
6054   if (Offset.isScalable())
6055     Index = getVScale(DL, Base.getValueType(),
6056                       APInt(Base.getValueSizeInBits().getFixedSize(),
6057                             Offset.getKnownMinSize()));
6058   else
6059     Index = getConstant(Offset.getFixedSize(), DL, VT);
6060 
6061   return getMemBasePlusOffset(Base, Index, DL, Flags);
6062 }
6063 
6064 SDValue SelectionDAG::getMemBasePlusOffset(SDValue Ptr, SDValue Offset,
6065                                            const SDLoc &DL,
6066                                            const SDNodeFlags Flags) {
6067   assert(Offset.getValueType().isInteger());
6068   EVT BasePtrVT = Ptr.getValueType();
6069   return getNode(ISD::ADD, DL, BasePtrVT, Ptr, Offset, Flags);
6070 }
6071 
6072 /// Returns true if memcpy source is constant data.
6073 static bool isMemSrcFromConstant(SDValue Src, ConstantDataArraySlice &Slice) {
6074   uint64_t SrcDelta = 0;
6075   GlobalAddressSDNode *G = nullptr;
6076   if (Src.getOpcode() == ISD::GlobalAddress)
6077     G = cast<GlobalAddressSDNode>(Src);
6078   else if (Src.getOpcode() == ISD::ADD &&
6079            Src.getOperand(0).getOpcode() == ISD::GlobalAddress &&
6080            Src.getOperand(1).getOpcode() == ISD::Constant) {
6081     G = cast<GlobalAddressSDNode>(Src.getOperand(0));
6082     SrcDelta = cast<ConstantSDNode>(Src.getOperand(1))->getZExtValue();
6083   }
6084   if (!G)
6085     return false;
6086 
6087   return getConstantDataArrayInfo(G->getGlobal(), Slice, 8,
6088                                   SrcDelta + G->getOffset());
6089 }
6090 
6091 static bool shouldLowerMemFuncForSize(const MachineFunction &MF,
6092                                       SelectionDAG &DAG) {
6093   // On Darwin, -Os means optimize for size without hurting performance, so
6094   // only really optimize for size when -Oz (MinSize) is used.
6095   if (MF.getTarget().getTargetTriple().isOSDarwin())
6096     return MF.getFunction().hasMinSize();
6097   return DAG.shouldOptForSize();
6098 }
6099 
6100 static void chainLoadsAndStoresForMemcpy(SelectionDAG &DAG, const SDLoc &dl,
6101                           SmallVector<SDValue, 32> &OutChains, unsigned From,
6102                           unsigned To, SmallVector<SDValue, 16> &OutLoadChains,
6103                           SmallVector<SDValue, 16> &OutStoreChains) {
6104   assert(OutLoadChains.size() && "Missing loads in memcpy inlining");
6105   assert(OutStoreChains.size() && "Missing stores in memcpy inlining");
6106   SmallVector<SDValue, 16> GluedLoadChains;
6107   for (unsigned i = From; i < To; ++i) {
6108     OutChains.push_back(OutLoadChains[i]);
6109     GluedLoadChains.push_back(OutLoadChains[i]);
6110   }
6111 
6112   // Chain for all loads.
6113   SDValue LoadToken = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
6114                                   GluedLoadChains);
6115 
6116   for (unsigned i = From; i < To; ++i) {
6117     StoreSDNode *ST = dyn_cast<StoreSDNode>(OutStoreChains[i]);
6118     SDValue NewStore = DAG.getTruncStore(LoadToken, dl, ST->getValue(),
6119                                   ST->getBasePtr(), ST->getMemoryVT(),
6120                                   ST->getMemOperand());
6121     OutChains.push_back(NewStore);
6122   }
6123 }
6124 
6125 static SDValue getMemcpyLoadsAndStores(SelectionDAG &DAG, const SDLoc &dl,
6126                                        SDValue Chain, SDValue Dst, SDValue Src,
6127                                        uint64_t Size, Align Alignment,
6128                                        bool isVol, bool AlwaysInline,
6129                                        MachinePointerInfo DstPtrInfo,
6130                                        MachinePointerInfo SrcPtrInfo) {
6131   // Turn a memcpy of undef to nop.
6132   // FIXME: We need to honor volatile even is Src is undef.
6133   if (Src.isUndef())
6134     return Chain;
6135 
6136   // Expand memcpy to a series of load and store ops if the size operand falls
6137   // below a certain threshold.
6138   // TODO: In the AlwaysInline case, if the size is big then generate a loop
6139   // rather than maybe a humongous number of loads and stores.
6140   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6141   const DataLayout &DL = DAG.getDataLayout();
6142   LLVMContext &C = *DAG.getContext();
6143   std::vector<EVT> MemOps;
6144   bool DstAlignCanChange = false;
6145   MachineFunction &MF = DAG.getMachineFunction();
6146   MachineFrameInfo &MFI = MF.getFrameInfo();
6147   bool OptSize = shouldLowerMemFuncForSize(MF, DAG);
6148   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
6149   if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
6150     DstAlignCanChange = true;
6151   MaybeAlign SrcAlign = DAG.InferPtrAlign(Src);
6152   if (!SrcAlign || Alignment > *SrcAlign)
6153     SrcAlign = Alignment;
6154   assert(SrcAlign && "SrcAlign must be set");
6155   ConstantDataArraySlice Slice;
6156   // If marked as volatile, perform a copy even when marked as constant.
6157   bool CopyFromConstant = !isVol && isMemSrcFromConstant(Src, Slice);
6158   bool isZeroConstant = CopyFromConstant && Slice.Array == nullptr;
6159   unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemcpy(OptSize);
6160   const MemOp Op = isZeroConstant
6161                        ? MemOp::Set(Size, DstAlignCanChange, Alignment,
6162                                     /*IsZeroMemset*/ true, isVol)
6163                        : MemOp::Copy(Size, DstAlignCanChange, Alignment,
6164                                      *SrcAlign, isVol, CopyFromConstant);
6165   if (!TLI.findOptimalMemOpLowering(
6166           MemOps, Limit, Op, DstPtrInfo.getAddrSpace(),
6167           SrcPtrInfo.getAddrSpace(), MF.getFunction().getAttributes()))
6168     return SDValue();
6169 
6170   if (DstAlignCanChange) {
6171     Type *Ty = MemOps[0].getTypeForEVT(C);
6172     Align NewAlign = DL.getABITypeAlign(Ty);
6173 
6174     // Don't promote to an alignment that would require dynamic stack
6175     // realignment.
6176     const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
6177     if (!TRI->needsStackRealignment(MF))
6178       while (NewAlign > Alignment && DL.exceedsNaturalStackAlignment(NewAlign))
6179         NewAlign = NewAlign / 2;
6180 
6181     if (NewAlign > Alignment) {
6182       // Give the stack frame object a larger alignment if needed.
6183       if (MFI.getObjectAlign(FI->getIndex()) < NewAlign)
6184         MFI.setObjectAlignment(FI->getIndex(), NewAlign);
6185       Alignment = NewAlign;
6186     }
6187   }
6188 
6189   MachineMemOperand::Flags MMOFlags =
6190       isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone;
6191   SmallVector<SDValue, 16> OutLoadChains;
6192   SmallVector<SDValue, 16> OutStoreChains;
6193   SmallVector<SDValue, 32> OutChains;
6194   unsigned NumMemOps = MemOps.size();
6195   uint64_t SrcOff = 0, DstOff = 0;
6196   for (unsigned i = 0; i != NumMemOps; ++i) {
6197     EVT VT = MemOps[i];
6198     unsigned VTSize = VT.getSizeInBits() / 8;
6199     SDValue Value, Store;
6200 
6201     if (VTSize > Size) {
6202       // Issuing an unaligned load / store pair  that overlaps with the previous
6203       // pair. Adjust the offset accordingly.
6204       assert(i == NumMemOps-1 && i != 0);
6205       SrcOff -= VTSize - Size;
6206       DstOff -= VTSize - Size;
6207     }
6208 
6209     if (CopyFromConstant &&
6210         (isZeroConstant || (VT.isInteger() && !VT.isVector()))) {
6211       // It's unlikely a store of a vector immediate can be done in a single
6212       // instruction. It would require a load from a constantpool first.
6213       // We only handle zero vectors here.
6214       // FIXME: Handle other cases where store of vector immediate is done in
6215       // a single instruction.
6216       ConstantDataArraySlice SubSlice;
6217       if (SrcOff < Slice.Length) {
6218         SubSlice = Slice;
6219         SubSlice.move(SrcOff);
6220       } else {
6221         // This is an out-of-bounds access and hence UB. Pretend we read zero.
6222         SubSlice.Array = nullptr;
6223         SubSlice.Offset = 0;
6224         SubSlice.Length = VTSize;
6225       }
6226       Value = getMemsetStringVal(VT, dl, DAG, TLI, SubSlice);
6227       if (Value.getNode()) {
6228         Store = DAG.getStore(
6229             Chain, dl, Value,
6230             DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl),
6231             DstPtrInfo.getWithOffset(DstOff), Alignment, MMOFlags);
6232         OutChains.push_back(Store);
6233       }
6234     }
6235 
6236     if (!Store.getNode()) {
6237       // The type might not be legal for the target.  This should only happen
6238       // if the type is smaller than a legal type, as on PPC, so the right
6239       // thing to do is generate a LoadExt/StoreTrunc pair.  These simplify
6240       // to Load/Store if NVT==VT.
6241       // FIXME does the case above also need this?
6242       EVT NVT = TLI.getTypeToTransformTo(C, VT);
6243       assert(NVT.bitsGE(VT));
6244 
6245       bool isDereferenceable =
6246         SrcPtrInfo.getWithOffset(SrcOff).isDereferenceable(VTSize, C, DL);
6247       MachineMemOperand::Flags SrcMMOFlags = MMOFlags;
6248       if (isDereferenceable)
6249         SrcMMOFlags |= MachineMemOperand::MODereferenceable;
6250 
6251       Value = DAG.getExtLoad(
6252           ISD::EXTLOAD, dl, NVT, Chain,
6253           DAG.getMemBasePlusOffset(Src, TypeSize::Fixed(SrcOff), dl),
6254           SrcPtrInfo.getWithOffset(SrcOff), VT,
6255           commonAlignment(*SrcAlign, SrcOff), SrcMMOFlags);
6256       OutLoadChains.push_back(Value.getValue(1));
6257 
6258       Store = DAG.getTruncStore(
6259           Chain, dl, Value,
6260           DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl),
6261           DstPtrInfo.getWithOffset(DstOff), VT, Alignment, MMOFlags);
6262       OutStoreChains.push_back(Store);
6263     }
6264     SrcOff += VTSize;
6265     DstOff += VTSize;
6266     Size -= VTSize;
6267   }
6268 
6269   unsigned GluedLdStLimit = MaxLdStGlue == 0 ?
6270                                 TLI.getMaxGluedStoresPerMemcpy() : MaxLdStGlue;
6271   unsigned NumLdStInMemcpy = OutStoreChains.size();
6272 
6273   if (NumLdStInMemcpy) {
6274     // It may be that memcpy might be converted to memset if it's memcpy
6275     // of constants. In such a case, we won't have loads and stores, but
6276     // just stores. In the absence of loads, there is nothing to gang up.
6277     if ((GluedLdStLimit <= 1) || !EnableMemCpyDAGOpt) {
6278       // If target does not care, just leave as it.
6279       for (unsigned i = 0; i < NumLdStInMemcpy; ++i) {
6280         OutChains.push_back(OutLoadChains[i]);
6281         OutChains.push_back(OutStoreChains[i]);
6282       }
6283     } else {
6284       // Ld/St less than/equal limit set by target.
6285       if (NumLdStInMemcpy <= GluedLdStLimit) {
6286           chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, 0,
6287                                         NumLdStInMemcpy, OutLoadChains,
6288                                         OutStoreChains);
6289       } else {
6290         unsigned NumberLdChain =  NumLdStInMemcpy / GluedLdStLimit;
6291         unsigned RemainingLdStInMemcpy = NumLdStInMemcpy % GluedLdStLimit;
6292         unsigned GlueIter = 0;
6293 
6294         for (unsigned cnt = 0; cnt < NumberLdChain; ++cnt) {
6295           unsigned IndexFrom = NumLdStInMemcpy - GlueIter - GluedLdStLimit;
6296           unsigned IndexTo   = NumLdStInMemcpy - GlueIter;
6297 
6298           chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, IndexFrom, IndexTo,
6299                                        OutLoadChains, OutStoreChains);
6300           GlueIter += GluedLdStLimit;
6301         }
6302 
6303         // Residual ld/st.
6304         if (RemainingLdStInMemcpy) {
6305           chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, 0,
6306                                         RemainingLdStInMemcpy, OutLoadChains,
6307                                         OutStoreChains);
6308         }
6309       }
6310     }
6311   }
6312   return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
6313 }
6314 
6315 static SDValue getMemmoveLoadsAndStores(SelectionDAG &DAG, const SDLoc &dl,
6316                                         SDValue Chain, SDValue Dst, SDValue Src,
6317                                         uint64_t Size, Align Alignment,
6318                                         bool isVol, bool AlwaysInline,
6319                                         MachinePointerInfo DstPtrInfo,
6320                                         MachinePointerInfo SrcPtrInfo) {
6321   // Turn a memmove of undef to nop.
6322   // FIXME: We need to honor volatile even is Src is undef.
6323   if (Src.isUndef())
6324     return Chain;
6325 
6326   // Expand memmove to a series of load and store ops if the size operand falls
6327   // below a certain threshold.
6328   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6329   const DataLayout &DL = DAG.getDataLayout();
6330   LLVMContext &C = *DAG.getContext();
6331   std::vector<EVT> MemOps;
6332   bool DstAlignCanChange = false;
6333   MachineFunction &MF = DAG.getMachineFunction();
6334   MachineFrameInfo &MFI = MF.getFrameInfo();
6335   bool OptSize = shouldLowerMemFuncForSize(MF, DAG);
6336   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
6337   if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
6338     DstAlignCanChange = true;
6339   MaybeAlign SrcAlign = DAG.InferPtrAlign(Src);
6340   if (!SrcAlign || Alignment > *SrcAlign)
6341     SrcAlign = Alignment;
6342   assert(SrcAlign && "SrcAlign must be set");
6343   unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemmove(OptSize);
6344   if (!TLI.findOptimalMemOpLowering(
6345           MemOps, Limit,
6346           MemOp::Copy(Size, DstAlignCanChange, Alignment, *SrcAlign,
6347                       /*IsVolatile*/ true),
6348           DstPtrInfo.getAddrSpace(), SrcPtrInfo.getAddrSpace(),
6349           MF.getFunction().getAttributes()))
6350     return SDValue();
6351 
6352   if (DstAlignCanChange) {
6353     Type *Ty = MemOps[0].getTypeForEVT(C);
6354     Align NewAlign = DL.getABITypeAlign(Ty);
6355     if (NewAlign > Alignment) {
6356       // Give the stack frame object a larger alignment if needed.
6357       if (MFI.getObjectAlign(FI->getIndex()) < NewAlign)
6358         MFI.setObjectAlignment(FI->getIndex(), NewAlign);
6359       Alignment = NewAlign;
6360     }
6361   }
6362 
6363   MachineMemOperand::Flags MMOFlags =
6364       isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone;
6365   uint64_t SrcOff = 0, DstOff = 0;
6366   SmallVector<SDValue, 8> LoadValues;
6367   SmallVector<SDValue, 8> LoadChains;
6368   SmallVector<SDValue, 8> OutChains;
6369   unsigned NumMemOps = MemOps.size();
6370   for (unsigned i = 0; i < NumMemOps; i++) {
6371     EVT VT = MemOps[i];
6372     unsigned VTSize = VT.getSizeInBits() / 8;
6373     SDValue Value;
6374 
6375     bool isDereferenceable =
6376       SrcPtrInfo.getWithOffset(SrcOff).isDereferenceable(VTSize, C, DL);
6377     MachineMemOperand::Flags SrcMMOFlags = MMOFlags;
6378     if (isDereferenceable)
6379       SrcMMOFlags |= MachineMemOperand::MODereferenceable;
6380 
6381     Value =
6382         DAG.getLoad(VT, dl, Chain,
6383                     DAG.getMemBasePlusOffset(Src, TypeSize::Fixed(SrcOff), dl),
6384                     SrcPtrInfo.getWithOffset(SrcOff), *SrcAlign, SrcMMOFlags);
6385     LoadValues.push_back(Value);
6386     LoadChains.push_back(Value.getValue(1));
6387     SrcOff += VTSize;
6388   }
6389   Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
6390   OutChains.clear();
6391   for (unsigned i = 0; i < NumMemOps; i++) {
6392     EVT VT = MemOps[i];
6393     unsigned VTSize = VT.getSizeInBits() / 8;
6394     SDValue Store;
6395 
6396     Store =
6397         DAG.getStore(Chain, dl, LoadValues[i],
6398                      DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl),
6399                      DstPtrInfo.getWithOffset(DstOff), Alignment, MMOFlags);
6400     OutChains.push_back(Store);
6401     DstOff += VTSize;
6402   }
6403 
6404   return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
6405 }
6406 
6407 /// Lower the call to 'memset' intrinsic function into a series of store
6408 /// operations.
6409 ///
6410 /// \param DAG Selection DAG where lowered code is placed.
6411 /// \param dl Link to corresponding IR location.
6412 /// \param Chain Control flow dependency.
6413 /// \param Dst Pointer to destination memory location.
6414 /// \param Src Value of byte to write into the memory.
6415 /// \param Size Number of bytes to write.
6416 /// \param Alignment Alignment of the destination in bytes.
6417 /// \param isVol True if destination is volatile.
6418 /// \param DstPtrInfo IR information on the memory pointer.
6419 /// \returns New head in the control flow, if lowering was successful, empty
6420 /// SDValue otherwise.
6421 ///
6422 /// The function tries to replace 'llvm.memset' intrinsic with several store
6423 /// operations and value calculation code. This is usually profitable for small
6424 /// memory size.
6425 static SDValue getMemsetStores(SelectionDAG &DAG, const SDLoc &dl,
6426                                SDValue Chain, SDValue Dst, SDValue Src,
6427                                uint64_t Size, Align Alignment, bool isVol,
6428                                MachinePointerInfo DstPtrInfo) {
6429   // Turn a memset of undef to nop.
6430   // FIXME: We need to honor volatile even is Src is undef.
6431   if (Src.isUndef())
6432     return Chain;
6433 
6434   // Expand memset to a series of load/store ops if the size operand
6435   // falls below a certain threshold.
6436   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6437   std::vector<EVT> MemOps;
6438   bool DstAlignCanChange = false;
6439   MachineFunction &MF = DAG.getMachineFunction();
6440   MachineFrameInfo &MFI = MF.getFrameInfo();
6441   bool OptSize = shouldLowerMemFuncForSize(MF, DAG);
6442   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
6443   if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
6444     DstAlignCanChange = true;
6445   bool IsZeroVal =
6446     isa<ConstantSDNode>(Src) && cast<ConstantSDNode>(Src)->isNullValue();
6447   if (!TLI.findOptimalMemOpLowering(
6448           MemOps, TLI.getMaxStoresPerMemset(OptSize),
6449           MemOp::Set(Size, DstAlignCanChange, Alignment, IsZeroVal, isVol),
6450           DstPtrInfo.getAddrSpace(), ~0u, MF.getFunction().getAttributes()))
6451     return SDValue();
6452 
6453   if (DstAlignCanChange) {
6454     Type *Ty = MemOps[0].getTypeForEVT(*DAG.getContext());
6455     Align NewAlign = DAG.getDataLayout().getABITypeAlign(Ty);
6456     if (NewAlign > Alignment) {
6457       // Give the stack frame object a larger alignment if needed.
6458       if (MFI.getObjectAlign(FI->getIndex()) < NewAlign)
6459         MFI.setObjectAlignment(FI->getIndex(), NewAlign);
6460       Alignment = NewAlign;
6461     }
6462   }
6463 
6464   SmallVector<SDValue, 8> OutChains;
6465   uint64_t DstOff = 0;
6466   unsigned NumMemOps = MemOps.size();
6467 
6468   // Find the largest store and generate the bit pattern for it.
6469   EVT LargestVT = MemOps[0];
6470   for (unsigned i = 1; i < NumMemOps; i++)
6471     if (MemOps[i].bitsGT(LargestVT))
6472       LargestVT = MemOps[i];
6473   SDValue MemSetValue = getMemsetValue(Src, LargestVT, DAG, dl);
6474 
6475   for (unsigned i = 0; i < NumMemOps; i++) {
6476     EVT VT = MemOps[i];
6477     unsigned VTSize = VT.getSizeInBits() / 8;
6478     if (VTSize > Size) {
6479       // Issuing an unaligned load / store pair  that overlaps with the previous
6480       // pair. Adjust the offset accordingly.
6481       assert(i == NumMemOps-1 && i != 0);
6482       DstOff -= VTSize - Size;
6483     }
6484 
6485     // If this store is smaller than the largest store see whether we can get
6486     // the smaller value for free with a truncate.
6487     SDValue Value = MemSetValue;
6488     if (VT.bitsLT(LargestVT)) {
6489       if (!LargestVT.isVector() && !VT.isVector() &&
6490           TLI.isTruncateFree(LargestVT, VT))
6491         Value = DAG.getNode(ISD::TRUNCATE, dl, VT, MemSetValue);
6492       else
6493         Value = getMemsetValue(Src, VT, DAG, dl);
6494     }
6495     assert(Value.getValueType() == VT && "Value with wrong type.");
6496     SDValue Store = DAG.getStore(
6497         Chain, dl, Value,
6498         DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl),
6499         DstPtrInfo.getWithOffset(DstOff), Alignment,
6500         isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone);
6501     OutChains.push_back(Store);
6502     DstOff += VT.getSizeInBits() / 8;
6503     Size -= VTSize;
6504   }
6505 
6506   return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
6507 }
6508 
6509 static void checkAddrSpaceIsValidForLibcall(const TargetLowering *TLI,
6510                                             unsigned AS) {
6511   // Lowering memcpy / memset / memmove intrinsics to calls is only valid if all
6512   // pointer operands can be losslessly bitcasted to pointers of address space 0
6513   if (AS != 0 && !TLI->getTargetMachine().isNoopAddrSpaceCast(AS, 0)) {
6514     report_fatal_error("cannot lower memory intrinsic in address space " +
6515                        Twine(AS));
6516   }
6517 }
6518 
6519 SDValue SelectionDAG::getMemcpy(SDValue Chain, const SDLoc &dl, SDValue Dst,
6520                                 SDValue Src, SDValue Size, Align Alignment,
6521                                 bool isVol, bool AlwaysInline, bool isTailCall,
6522                                 MachinePointerInfo DstPtrInfo,
6523                                 MachinePointerInfo SrcPtrInfo) {
6524   // Check to see if we should lower the memcpy to loads and stores first.
6525   // For cases within the target-specified limits, this is the best choice.
6526   ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
6527   if (ConstantSize) {
6528     // Memcpy with size zero? Just return the original chain.
6529     if (ConstantSize->isNullValue())
6530       return Chain;
6531 
6532     SDValue Result = getMemcpyLoadsAndStores(
6533         *this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), Alignment,
6534         isVol, false, DstPtrInfo, SrcPtrInfo);
6535     if (Result.getNode())
6536       return Result;
6537   }
6538 
6539   // Then check to see if we should lower the memcpy with target-specific
6540   // code. If the target chooses to do this, this is the next best.
6541   if (TSI) {
6542     SDValue Result = TSI->EmitTargetCodeForMemcpy(
6543         *this, dl, Chain, Dst, Src, Size, Alignment, isVol, AlwaysInline,
6544         DstPtrInfo, SrcPtrInfo);
6545     if (Result.getNode())
6546       return Result;
6547   }
6548 
6549   // If we really need inline code and the target declined to provide it,
6550   // use a (potentially long) sequence of loads and stores.
6551   if (AlwaysInline) {
6552     assert(ConstantSize && "AlwaysInline requires a constant size!");
6553     return getMemcpyLoadsAndStores(*this, dl, Chain, Dst, Src,
6554                                    ConstantSize->getZExtValue(), Alignment,
6555                                    isVol, true, DstPtrInfo, SrcPtrInfo);
6556   }
6557 
6558   checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace());
6559   checkAddrSpaceIsValidForLibcall(TLI, SrcPtrInfo.getAddrSpace());
6560 
6561   // FIXME: If the memcpy is volatile (isVol), lowering it to a plain libc
6562   // memcpy is not guaranteed to be safe. libc memcpys aren't required to
6563   // respect volatile, so they may do things like read or write memory
6564   // beyond the given memory regions. But fixing this isn't easy, and most
6565   // people don't care.
6566 
6567   // Emit a library call.
6568   TargetLowering::ArgListTy Args;
6569   TargetLowering::ArgListEntry Entry;
6570   Entry.Ty = Type::getInt8PtrTy(*getContext());
6571   Entry.Node = Dst; Args.push_back(Entry);
6572   Entry.Node = Src; Args.push_back(Entry);
6573 
6574   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
6575   Entry.Node = Size; Args.push_back(Entry);
6576   // FIXME: pass in SDLoc
6577   TargetLowering::CallLoweringInfo CLI(*this);
6578   CLI.setDebugLoc(dl)
6579       .setChain(Chain)
6580       .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMCPY),
6581                     Dst.getValueType().getTypeForEVT(*getContext()),
6582                     getExternalSymbol(TLI->getLibcallName(RTLIB::MEMCPY),
6583                                       TLI->getPointerTy(getDataLayout())),
6584                     std::move(Args))
6585       .setDiscardResult()
6586       .setTailCall(isTailCall);
6587 
6588   std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
6589   return CallResult.second;
6590 }
6591 
6592 SDValue SelectionDAG::getAtomicMemcpy(SDValue Chain, const SDLoc &dl,
6593                                       SDValue Dst, unsigned DstAlign,
6594                                       SDValue Src, unsigned SrcAlign,
6595                                       SDValue Size, Type *SizeTy,
6596                                       unsigned ElemSz, bool isTailCall,
6597                                       MachinePointerInfo DstPtrInfo,
6598                                       MachinePointerInfo SrcPtrInfo) {
6599   // Emit a library call.
6600   TargetLowering::ArgListTy Args;
6601   TargetLowering::ArgListEntry Entry;
6602   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
6603   Entry.Node = Dst;
6604   Args.push_back(Entry);
6605 
6606   Entry.Node = Src;
6607   Args.push_back(Entry);
6608 
6609   Entry.Ty = SizeTy;
6610   Entry.Node = Size;
6611   Args.push_back(Entry);
6612 
6613   RTLIB::Libcall LibraryCall =
6614       RTLIB::getMEMCPY_ELEMENT_UNORDERED_ATOMIC(ElemSz);
6615   if (LibraryCall == RTLIB::UNKNOWN_LIBCALL)
6616     report_fatal_error("Unsupported element size");
6617 
6618   TargetLowering::CallLoweringInfo CLI(*this);
6619   CLI.setDebugLoc(dl)
6620       .setChain(Chain)
6621       .setLibCallee(TLI->getLibcallCallingConv(LibraryCall),
6622                     Type::getVoidTy(*getContext()),
6623                     getExternalSymbol(TLI->getLibcallName(LibraryCall),
6624                                       TLI->getPointerTy(getDataLayout())),
6625                     std::move(Args))
6626       .setDiscardResult()
6627       .setTailCall(isTailCall);
6628 
6629   std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
6630   return CallResult.second;
6631 }
6632 
6633 SDValue SelectionDAG::getMemmove(SDValue Chain, const SDLoc &dl, SDValue Dst,
6634                                  SDValue Src, SDValue Size, Align Alignment,
6635                                  bool isVol, bool isTailCall,
6636                                  MachinePointerInfo DstPtrInfo,
6637                                  MachinePointerInfo SrcPtrInfo) {
6638   // Check to see if we should lower the memmove to loads and stores first.
6639   // For cases within the target-specified limits, this is the best choice.
6640   ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
6641   if (ConstantSize) {
6642     // Memmove with size zero? Just return the original chain.
6643     if (ConstantSize->isNullValue())
6644       return Chain;
6645 
6646     SDValue Result = getMemmoveLoadsAndStores(
6647         *this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), Alignment,
6648         isVol, false, DstPtrInfo, SrcPtrInfo);
6649     if (Result.getNode())
6650       return Result;
6651   }
6652 
6653   // Then check to see if we should lower the memmove with target-specific
6654   // code. If the target chooses to do this, this is the next best.
6655   if (TSI) {
6656     SDValue Result =
6657         TSI->EmitTargetCodeForMemmove(*this, dl, Chain, Dst, Src, Size,
6658                                       Alignment, isVol, DstPtrInfo, SrcPtrInfo);
6659     if (Result.getNode())
6660       return Result;
6661   }
6662 
6663   checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace());
6664   checkAddrSpaceIsValidForLibcall(TLI, SrcPtrInfo.getAddrSpace());
6665 
6666   // FIXME: If the memmove is volatile, lowering it to plain libc memmove may
6667   // not be safe.  See memcpy above for more details.
6668 
6669   // Emit a library call.
6670   TargetLowering::ArgListTy Args;
6671   TargetLowering::ArgListEntry Entry;
6672   Entry.Ty = Type::getInt8PtrTy(*getContext());
6673   Entry.Node = Dst; Args.push_back(Entry);
6674   Entry.Node = Src; Args.push_back(Entry);
6675 
6676   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
6677   Entry.Node = Size; Args.push_back(Entry);
6678   // FIXME:  pass in SDLoc
6679   TargetLowering::CallLoweringInfo CLI(*this);
6680   CLI.setDebugLoc(dl)
6681       .setChain(Chain)
6682       .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMMOVE),
6683                     Dst.getValueType().getTypeForEVT(*getContext()),
6684                     getExternalSymbol(TLI->getLibcallName(RTLIB::MEMMOVE),
6685                                       TLI->getPointerTy(getDataLayout())),
6686                     std::move(Args))
6687       .setDiscardResult()
6688       .setTailCall(isTailCall);
6689 
6690   std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
6691   return CallResult.second;
6692 }
6693 
6694 SDValue SelectionDAG::getAtomicMemmove(SDValue Chain, const SDLoc &dl,
6695                                        SDValue Dst, unsigned DstAlign,
6696                                        SDValue Src, unsigned SrcAlign,
6697                                        SDValue Size, Type *SizeTy,
6698                                        unsigned ElemSz, bool isTailCall,
6699                                        MachinePointerInfo DstPtrInfo,
6700                                        MachinePointerInfo SrcPtrInfo) {
6701   // Emit a library call.
6702   TargetLowering::ArgListTy Args;
6703   TargetLowering::ArgListEntry Entry;
6704   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
6705   Entry.Node = Dst;
6706   Args.push_back(Entry);
6707 
6708   Entry.Node = Src;
6709   Args.push_back(Entry);
6710 
6711   Entry.Ty = SizeTy;
6712   Entry.Node = Size;
6713   Args.push_back(Entry);
6714 
6715   RTLIB::Libcall LibraryCall =
6716       RTLIB::getMEMMOVE_ELEMENT_UNORDERED_ATOMIC(ElemSz);
6717   if (LibraryCall == RTLIB::UNKNOWN_LIBCALL)
6718     report_fatal_error("Unsupported element size");
6719 
6720   TargetLowering::CallLoweringInfo CLI(*this);
6721   CLI.setDebugLoc(dl)
6722       .setChain(Chain)
6723       .setLibCallee(TLI->getLibcallCallingConv(LibraryCall),
6724                     Type::getVoidTy(*getContext()),
6725                     getExternalSymbol(TLI->getLibcallName(LibraryCall),
6726                                       TLI->getPointerTy(getDataLayout())),
6727                     std::move(Args))
6728       .setDiscardResult()
6729       .setTailCall(isTailCall);
6730 
6731   std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
6732   return CallResult.second;
6733 }
6734 
6735 SDValue SelectionDAG::getMemset(SDValue Chain, const SDLoc &dl, SDValue Dst,
6736                                 SDValue Src, SDValue Size, Align Alignment,
6737                                 bool isVol, bool isTailCall,
6738                                 MachinePointerInfo DstPtrInfo) {
6739   // Check to see if we should lower the memset to stores first.
6740   // For cases within the target-specified limits, this is the best choice.
6741   ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
6742   if (ConstantSize) {
6743     // Memset with size zero? Just return the original chain.
6744     if (ConstantSize->isNullValue())
6745       return Chain;
6746 
6747     SDValue Result = getMemsetStores(*this, dl, Chain, Dst, Src,
6748                                      ConstantSize->getZExtValue(), Alignment,
6749                                      isVol, DstPtrInfo);
6750 
6751     if (Result.getNode())
6752       return Result;
6753   }
6754 
6755   // Then check to see if we should lower the memset with target-specific
6756   // code. If the target chooses to do this, this is the next best.
6757   if (TSI) {
6758     SDValue Result = TSI->EmitTargetCodeForMemset(
6759         *this, dl, Chain, Dst, Src, Size, Alignment, isVol, DstPtrInfo);
6760     if (Result.getNode())
6761       return Result;
6762   }
6763 
6764   checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace());
6765 
6766   // Emit a library call.
6767   TargetLowering::ArgListTy Args;
6768   TargetLowering::ArgListEntry Entry;
6769   Entry.Node = Dst; Entry.Ty = Type::getInt8PtrTy(*getContext());
6770   Args.push_back(Entry);
6771   Entry.Node = Src;
6772   Entry.Ty = Src.getValueType().getTypeForEVT(*getContext());
6773   Args.push_back(Entry);
6774   Entry.Node = Size;
6775   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
6776   Args.push_back(Entry);
6777 
6778   // FIXME: pass in SDLoc
6779   TargetLowering::CallLoweringInfo CLI(*this);
6780   CLI.setDebugLoc(dl)
6781       .setChain(Chain)
6782       .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMSET),
6783                     Dst.getValueType().getTypeForEVT(*getContext()),
6784                     getExternalSymbol(TLI->getLibcallName(RTLIB::MEMSET),
6785                                       TLI->getPointerTy(getDataLayout())),
6786                     std::move(Args))
6787       .setDiscardResult()
6788       .setTailCall(isTailCall);
6789 
6790   std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
6791   return CallResult.second;
6792 }
6793 
6794 SDValue SelectionDAG::getAtomicMemset(SDValue Chain, const SDLoc &dl,
6795                                       SDValue Dst, unsigned DstAlign,
6796                                       SDValue Value, SDValue Size, Type *SizeTy,
6797                                       unsigned ElemSz, bool isTailCall,
6798                                       MachinePointerInfo DstPtrInfo) {
6799   // Emit a library call.
6800   TargetLowering::ArgListTy Args;
6801   TargetLowering::ArgListEntry Entry;
6802   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
6803   Entry.Node = Dst;
6804   Args.push_back(Entry);
6805 
6806   Entry.Ty = Type::getInt8Ty(*getContext());
6807   Entry.Node = Value;
6808   Args.push_back(Entry);
6809 
6810   Entry.Ty = SizeTy;
6811   Entry.Node = Size;
6812   Args.push_back(Entry);
6813 
6814   RTLIB::Libcall LibraryCall =
6815       RTLIB::getMEMSET_ELEMENT_UNORDERED_ATOMIC(ElemSz);
6816   if (LibraryCall == RTLIB::UNKNOWN_LIBCALL)
6817     report_fatal_error("Unsupported element size");
6818 
6819   TargetLowering::CallLoweringInfo CLI(*this);
6820   CLI.setDebugLoc(dl)
6821       .setChain(Chain)
6822       .setLibCallee(TLI->getLibcallCallingConv(LibraryCall),
6823                     Type::getVoidTy(*getContext()),
6824                     getExternalSymbol(TLI->getLibcallName(LibraryCall),
6825                                       TLI->getPointerTy(getDataLayout())),
6826                     std::move(Args))
6827       .setDiscardResult()
6828       .setTailCall(isTailCall);
6829 
6830   std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
6831   return CallResult.second;
6832 }
6833 
6834 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
6835                                 SDVTList VTList, ArrayRef<SDValue> Ops,
6836                                 MachineMemOperand *MMO) {
6837   FoldingSetNodeID ID;
6838   ID.AddInteger(MemVT.getRawBits());
6839   AddNodeIDNode(ID, Opcode, VTList, Ops);
6840   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
6841   void* IP = nullptr;
6842   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
6843     cast<AtomicSDNode>(E)->refineAlignment(MMO);
6844     return SDValue(E, 0);
6845   }
6846 
6847   auto *N = newSDNode<AtomicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
6848                                     VTList, MemVT, MMO);
6849   createOperands(N, Ops);
6850 
6851   CSEMap.InsertNode(N, IP);
6852   InsertNode(N);
6853   return SDValue(N, 0);
6854 }
6855 
6856 SDValue SelectionDAG::getAtomicCmpSwap(unsigned Opcode, const SDLoc &dl,
6857                                        EVT MemVT, SDVTList VTs, SDValue Chain,
6858                                        SDValue Ptr, SDValue Cmp, SDValue Swp,
6859                                        MachineMemOperand *MMO) {
6860   assert(Opcode == ISD::ATOMIC_CMP_SWAP ||
6861          Opcode == ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS);
6862   assert(Cmp.getValueType() == Swp.getValueType() && "Invalid Atomic Op Types");
6863 
6864   SDValue Ops[] = {Chain, Ptr, Cmp, Swp};
6865   return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
6866 }
6867 
6868 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
6869                                 SDValue Chain, SDValue Ptr, SDValue Val,
6870                                 MachineMemOperand *MMO) {
6871   assert((Opcode == ISD::ATOMIC_LOAD_ADD ||
6872           Opcode == ISD::ATOMIC_LOAD_SUB ||
6873           Opcode == ISD::ATOMIC_LOAD_AND ||
6874           Opcode == ISD::ATOMIC_LOAD_CLR ||
6875           Opcode == ISD::ATOMIC_LOAD_OR ||
6876           Opcode == ISD::ATOMIC_LOAD_XOR ||
6877           Opcode == ISD::ATOMIC_LOAD_NAND ||
6878           Opcode == ISD::ATOMIC_LOAD_MIN ||
6879           Opcode == ISD::ATOMIC_LOAD_MAX ||
6880           Opcode == ISD::ATOMIC_LOAD_UMIN ||
6881           Opcode == ISD::ATOMIC_LOAD_UMAX ||
6882           Opcode == ISD::ATOMIC_LOAD_FADD ||
6883           Opcode == ISD::ATOMIC_LOAD_FSUB ||
6884           Opcode == ISD::ATOMIC_SWAP ||
6885           Opcode == ISD::ATOMIC_STORE) &&
6886          "Invalid Atomic Op");
6887 
6888   EVT VT = Val.getValueType();
6889 
6890   SDVTList VTs = Opcode == ISD::ATOMIC_STORE ? getVTList(MVT::Other) :
6891                                                getVTList(VT, MVT::Other);
6892   SDValue Ops[] = {Chain, Ptr, Val};
6893   return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
6894 }
6895 
6896 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
6897                                 EVT VT, SDValue Chain, SDValue Ptr,
6898                                 MachineMemOperand *MMO) {
6899   assert(Opcode == ISD::ATOMIC_LOAD && "Invalid Atomic Op");
6900 
6901   SDVTList VTs = getVTList(VT, MVT::Other);
6902   SDValue Ops[] = {Chain, Ptr};
6903   return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
6904 }
6905 
6906 /// getMergeValues - Create a MERGE_VALUES node from the given operands.
6907 SDValue SelectionDAG::getMergeValues(ArrayRef<SDValue> Ops, const SDLoc &dl) {
6908   if (Ops.size() == 1)
6909     return Ops[0];
6910 
6911   SmallVector<EVT, 4> VTs;
6912   VTs.reserve(Ops.size());
6913   for (const SDValue &Op : Ops)
6914     VTs.push_back(Op.getValueType());
6915   return getNode(ISD::MERGE_VALUES, dl, getVTList(VTs), Ops);
6916 }
6917 
6918 SDValue SelectionDAG::getMemIntrinsicNode(
6919     unsigned Opcode, const SDLoc &dl, SDVTList VTList, ArrayRef<SDValue> Ops,
6920     EVT MemVT, MachinePointerInfo PtrInfo, Align Alignment,
6921     MachineMemOperand::Flags Flags, uint64_t Size, const AAMDNodes &AAInfo) {
6922   if (!Size && MemVT.isScalableVector())
6923     Size = MemoryLocation::UnknownSize;
6924   else if (!Size)
6925     Size = MemVT.getStoreSize();
6926 
6927   MachineFunction &MF = getMachineFunction();
6928   MachineMemOperand *MMO =
6929       MF.getMachineMemOperand(PtrInfo, Flags, Size, Alignment, AAInfo);
6930 
6931   return getMemIntrinsicNode(Opcode, dl, VTList, Ops, MemVT, MMO);
6932 }
6933 
6934 SDValue SelectionDAG::getMemIntrinsicNode(unsigned Opcode, const SDLoc &dl,
6935                                           SDVTList VTList,
6936                                           ArrayRef<SDValue> Ops, EVT MemVT,
6937                                           MachineMemOperand *MMO) {
6938   assert((Opcode == ISD::INTRINSIC_VOID ||
6939           Opcode == ISD::INTRINSIC_W_CHAIN ||
6940           Opcode == ISD::PREFETCH ||
6941           ((int)Opcode <= std::numeric_limits<int>::max() &&
6942            (int)Opcode >= ISD::FIRST_TARGET_MEMORY_OPCODE)) &&
6943          "Opcode is not a memory-accessing opcode!");
6944 
6945   // Memoize the node unless it returns a flag.
6946   MemIntrinsicSDNode *N;
6947   if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) {
6948     FoldingSetNodeID ID;
6949     AddNodeIDNode(ID, Opcode, VTList, Ops);
6950     ID.AddInteger(getSyntheticNodeSubclassData<MemIntrinsicSDNode>(
6951         Opcode, dl.getIROrder(), VTList, MemVT, MMO));
6952     ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
6953     void *IP = nullptr;
6954     if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
6955       cast<MemIntrinsicSDNode>(E)->refineAlignment(MMO);
6956       return SDValue(E, 0);
6957     }
6958 
6959     N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
6960                                       VTList, MemVT, MMO);
6961     createOperands(N, Ops);
6962 
6963   CSEMap.InsertNode(N, IP);
6964   } else {
6965     N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
6966                                       VTList, MemVT, MMO);
6967     createOperands(N, Ops);
6968   }
6969   InsertNode(N);
6970   SDValue V(N, 0);
6971   NewSDValueDbgMsg(V, "Creating new node: ", this);
6972   return V;
6973 }
6974 
6975 SDValue SelectionDAG::getLifetimeNode(bool IsStart, const SDLoc &dl,
6976                                       SDValue Chain, int FrameIndex,
6977                                       int64_t Size, int64_t Offset) {
6978   const unsigned Opcode = IsStart ? ISD::LIFETIME_START : ISD::LIFETIME_END;
6979   const auto VTs = getVTList(MVT::Other);
6980   SDValue Ops[2] = {
6981       Chain,
6982       getFrameIndex(FrameIndex,
6983                     getTargetLoweringInfo().getFrameIndexTy(getDataLayout()),
6984                     true)};
6985 
6986   FoldingSetNodeID ID;
6987   AddNodeIDNode(ID, Opcode, VTs, Ops);
6988   ID.AddInteger(FrameIndex);
6989   ID.AddInteger(Size);
6990   ID.AddInteger(Offset);
6991   void *IP = nullptr;
6992   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
6993     return SDValue(E, 0);
6994 
6995   LifetimeSDNode *N = newSDNode<LifetimeSDNode>(
6996       Opcode, dl.getIROrder(), dl.getDebugLoc(), VTs, Size, Offset);
6997   createOperands(N, Ops);
6998   CSEMap.InsertNode(N, IP);
6999   InsertNode(N);
7000   SDValue V(N, 0);
7001   NewSDValueDbgMsg(V, "Creating new node: ", this);
7002   return V;
7003 }
7004 
7005 SDValue SelectionDAG::getPseudoProbeNode(const SDLoc &Dl, SDValue Chain,
7006                                          uint64_t Guid, uint64_t Index,
7007                                          uint32_t Attr) {
7008   const unsigned Opcode = ISD::PSEUDO_PROBE;
7009   const auto VTs = getVTList(MVT::Other);
7010   SDValue Ops[] = {Chain};
7011   FoldingSetNodeID ID;
7012   AddNodeIDNode(ID, Opcode, VTs, Ops);
7013   ID.AddInteger(Guid);
7014   ID.AddInteger(Index);
7015   void *IP = nullptr;
7016   if (SDNode *E = FindNodeOrInsertPos(ID, Dl, IP))
7017     return SDValue(E, 0);
7018 
7019   auto *N = newSDNode<PseudoProbeSDNode>(
7020       Opcode, Dl.getIROrder(), Dl.getDebugLoc(), VTs, Guid, Index, Attr);
7021   createOperands(N, Ops);
7022   CSEMap.InsertNode(N, IP);
7023   InsertNode(N);
7024   SDValue V(N, 0);
7025   NewSDValueDbgMsg(V, "Creating new node: ", this);
7026   return V;
7027 }
7028 
7029 /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a
7030 /// MachinePointerInfo record from it.  This is particularly useful because the
7031 /// code generator has many cases where it doesn't bother passing in a
7032 /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst".
7033 static MachinePointerInfo InferPointerInfo(const MachinePointerInfo &Info,
7034                                            SelectionDAG &DAG, SDValue Ptr,
7035                                            int64_t Offset = 0) {
7036   // If this is FI+Offset, we can model it.
7037   if (const FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr))
7038     return MachinePointerInfo::getFixedStack(DAG.getMachineFunction(),
7039                                              FI->getIndex(), Offset);
7040 
7041   // If this is (FI+Offset1)+Offset2, we can model it.
7042   if (Ptr.getOpcode() != ISD::ADD ||
7043       !isa<ConstantSDNode>(Ptr.getOperand(1)) ||
7044       !isa<FrameIndexSDNode>(Ptr.getOperand(0)))
7045     return Info;
7046 
7047   int FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
7048   return MachinePointerInfo::getFixedStack(
7049       DAG.getMachineFunction(), FI,
7050       Offset + cast<ConstantSDNode>(Ptr.getOperand(1))->getSExtValue());
7051 }
7052 
7053 /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a
7054 /// MachinePointerInfo record from it.  This is particularly useful because the
7055 /// code generator has many cases where it doesn't bother passing in a
7056 /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst".
7057 static MachinePointerInfo InferPointerInfo(const MachinePointerInfo &Info,
7058                                            SelectionDAG &DAG, SDValue Ptr,
7059                                            SDValue OffsetOp) {
7060   // If the 'Offset' value isn't a constant, we can't handle this.
7061   if (ConstantSDNode *OffsetNode = dyn_cast<ConstantSDNode>(OffsetOp))
7062     return InferPointerInfo(Info, DAG, Ptr, OffsetNode->getSExtValue());
7063   if (OffsetOp.isUndef())
7064     return InferPointerInfo(Info, DAG, Ptr);
7065   return Info;
7066 }
7067 
7068 SDValue SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType,
7069                               EVT VT, const SDLoc &dl, SDValue Chain,
7070                               SDValue Ptr, SDValue Offset,
7071                               MachinePointerInfo PtrInfo, EVT MemVT,
7072                               Align Alignment,
7073                               MachineMemOperand::Flags MMOFlags,
7074                               const AAMDNodes &AAInfo, const MDNode *Ranges) {
7075   assert(Chain.getValueType() == MVT::Other &&
7076         "Invalid chain type");
7077 
7078   MMOFlags |= MachineMemOperand::MOLoad;
7079   assert((MMOFlags & MachineMemOperand::MOStore) == 0);
7080   // If we don't have a PtrInfo, infer the trivial frame index case to simplify
7081   // clients.
7082   if (PtrInfo.V.isNull())
7083     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr, Offset);
7084 
7085   uint64_t Size = MemoryLocation::getSizeOrUnknown(MemVT.getStoreSize());
7086   MachineFunction &MF = getMachineFunction();
7087   MachineMemOperand *MMO = MF.getMachineMemOperand(PtrInfo, MMOFlags, Size,
7088                                                    Alignment, AAInfo, Ranges);
7089   return getLoad(AM, ExtType, VT, dl, Chain, Ptr, Offset, MemVT, MMO);
7090 }
7091 
7092 SDValue SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType,
7093                               EVT VT, const SDLoc &dl, SDValue Chain,
7094                               SDValue Ptr, SDValue Offset, EVT MemVT,
7095                               MachineMemOperand *MMO) {
7096   if (VT == MemVT) {
7097     ExtType = ISD::NON_EXTLOAD;
7098   } else if (ExtType == ISD::NON_EXTLOAD) {
7099     assert(VT == MemVT && "Non-extending load from different memory type!");
7100   } else {
7101     // Extending load.
7102     assert(MemVT.getScalarType().bitsLT(VT.getScalarType()) &&
7103            "Should only be an extending load, not truncating!");
7104     assert(VT.isInteger() == MemVT.isInteger() &&
7105            "Cannot convert from FP to Int or Int -> FP!");
7106     assert(VT.isVector() == MemVT.isVector() &&
7107            "Cannot use an ext load to convert to or from a vector!");
7108     assert((!VT.isVector() ||
7109             VT.getVectorElementCount() == MemVT.getVectorElementCount()) &&
7110            "Cannot use an ext load to change the number of vector elements!");
7111   }
7112 
7113   bool Indexed = AM != ISD::UNINDEXED;
7114   assert((Indexed || Offset.isUndef()) && "Unindexed load with an offset!");
7115 
7116   SDVTList VTs = Indexed ?
7117     getVTList(VT, Ptr.getValueType(), MVT::Other) : getVTList(VT, MVT::Other);
7118   SDValue Ops[] = { Chain, Ptr, Offset };
7119   FoldingSetNodeID ID;
7120   AddNodeIDNode(ID, ISD::LOAD, VTs, Ops);
7121   ID.AddInteger(MemVT.getRawBits());
7122   ID.AddInteger(getSyntheticNodeSubclassData<LoadSDNode>(
7123       dl.getIROrder(), VTs, AM, ExtType, MemVT, MMO));
7124   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7125   void *IP = nullptr;
7126   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7127     cast<LoadSDNode>(E)->refineAlignment(MMO);
7128     return SDValue(E, 0);
7129   }
7130   auto *N = newSDNode<LoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
7131                                   ExtType, MemVT, MMO);
7132   createOperands(N, Ops);
7133 
7134   CSEMap.InsertNode(N, IP);
7135   InsertNode(N);
7136   SDValue V(N, 0);
7137   NewSDValueDbgMsg(V, "Creating new node: ", this);
7138   return V;
7139 }
7140 
7141 SDValue SelectionDAG::getLoad(EVT VT, const SDLoc &dl, SDValue Chain,
7142                               SDValue Ptr, MachinePointerInfo PtrInfo,
7143                               MaybeAlign Alignment,
7144                               MachineMemOperand::Flags MMOFlags,
7145                               const AAMDNodes &AAInfo, const MDNode *Ranges) {
7146   SDValue Undef = getUNDEF(Ptr.getValueType());
7147   return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
7148                  PtrInfo, VT, Alignment, MMOFlags, AAInfo, Ranges);
7149 }
7150 
7151 SDValue SelectionDAG::getLoad(EVT VT, const SDLoc &dl, SDValue Chain,
7152                               SDValue Ptr, MachineMemOperand *MMO) {
7153   SDValue Undef = getUNDEF(Ptr.getValueType());
7154   return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
7155                  VT, MMO);
7156 }
7157 
7158 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl,
7159                                  EVT VT, SDValue Chain, SDValue Ptr,
7160                                  MachinePointerInfo PtrInfo, EVT MemVT,
7161                                  MaybeAlign Alignment,
7162                                  MachineMemOperand::Flags MMOFlags,
7163                                  const AAMDNodes &AAInfo) {
7164   SDValue Undef = getUNDEF(Ptr.getValueType());
7165   return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, PtrInfo,
7166                  MemVT, Alignment, MMOFlags, AAInfo);
7167 }
7168 
7169 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl,
7170                                  EVT VT, SDValue Chain, SDValue Ptr, EVT MemVT,
7171                                  MachineMemOperand *MMO) {
7172   SDValue Undef = getUNDEF(Ptr.getValueType());
7173   return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef,
7174                  MemVT, MMO);
7175 }
7176 
7177 SDValue SelectionDAG::getIndexedLoad(SDValue OrigLoad, const SDLoc &dl,
7178                                      SDValue Base, SDValue Offset,
7179                                      ISD::MemIndexedMode AM) {
7180   LoadSDNode *LD = cast<LoadSDNode>(OrigLoad);
7181   assert(LD->getOffset().isUndef() && "Load is already a indexed load!");
7182   // Don't propagate the invariant or dereferenceable flags.
7183   auto MMOFlags =
7184       LD->getMemOperand()->getFlags() &
7185       ~(MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable);
7186   return getLoad(AM, LD->getExtensionType(), OrigLoad.getValueType(), dl,
7187                  LD->getChain(), Base, Offset, LD->getPointerInfo(),
7188                  LD->getMemoryVT(), LD->getAlign(), MMOFlags, LD->getAAInfo());
7189 }
7190 
7191 SDValue SelectionDAG::getStore(SDValue Chain, const SDLoc &dl, SDValue Val,
7192                                SDValue Ptr, MachinePointerInfo PtrInfo,
7193                                Align Alignment,
7194                                MachineMemOperand::Flags MMOFlags,
7195                                const AAMDNodes &AAInfo) {
7196   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
7197 
7198   MMOFlags |= MachineMemOperand::MOStore;
7199   assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
7200 
7201   if (PtrInfo.V.isNull())
7202     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
7203 
7204   MachineFunction &MF = getMachineFunction();
7205   uint64_t Size =
7206       MemoryLocation::getSizeOrUnknown(Val.getValueType().getStoreSize());
7207   MachineMemOperand *MMO =
7208       MF.getMachineMemOperand(PtrInfo, MMOFlags, Size, Alignment, AAInfo);
7209   return getStore(Chain, dl, Val, Ptr, MMO);
7210 }
7211 
7212 SDValue SelectionDAG::getStore(SDValue Chain, const SDLoc &dl, SDValue Val,
7213                                SDValue Ptr, MachineMemOperand *MMO) {
7214   assert(Chain.getValueType() == MVT::Other &&
7215         "Invalid chain type");
7216   EVT VT = Val.getValueType();
7217   SDVTList VTs = getVTList(MVT::Other);
7218   SDValue Undef = getUNDEF(Ptr.getValueType());
7219   SDValue Ops[] = { Chain, Val, Ptr, Undef };
7220   FoldingSetNodeID ID;
7221   AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
7222   ID.AddInteger(VT.getRawBits());
7223   ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>(
7224       dl.getIROrder(), VTs, ISD::UNINDEXED, false, VT, MMO));
7225   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7226   void *IP = nullptr;
7227   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7228     cast<StoreSDNode>(E)->refineAlignment(MMO);
7229     return SDValue(E, 0);
7230   }
7231   auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
7232                                    ISD::UNINDEXED, false, VT, MMO);
7233   createOperands(N, Ops);
7234 
7235   CSEMap.InsertNode(N, IP);
7236   InsertNode(N);
7237   SDValue V(N, 0);
7238   NewSDValueDbgMsg(V, "Creating new node: ", this);
7239   return V;
7240 }
7241 
7242 SDValue SelectionDAG::getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val,
7243                                     SDValue Ptr, MachinePointerInfo PtrInfo,
7244                                     EVT SVT, Align Alignment,
7245                                     MachineMemOperand::Flags MMOFlags,
7246                                     const AAMDNodes &AAInfo) {
7247   assert(Chain.getValueType() == MVT::Other &&
7248         "Invalid chain type");
7249 
7250   MMOFlags |= MachineMemOperand::MOStore;
7251   assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
7252 
7253   if (PtrInfo.V.isNull())
7254     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
7255 
7256   MachineFunction &MF = getMachineFunction();
7257   MachineMemOperand *MMO = MF.getMachineMemOperand(
7258       PtrInfo, MMOFlags, MemoryLocation::getSizeOrUnknown(SVT.getStoreSize()),
7259       Alignment, AAInfo);
7260   return getTruncStore(Chain, dl, Val, Ptr, SVT, MMO);
7261 }
7262 
7263 SDValue SelectionDAG::getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val,
7264                                     SDValue Ptr, EVT SVT,
7265                                     MachineMemOperand *MMO) {
7266   EVT VT = Val.getValueType();
7267 
7268   assert(Chain.getValueType() == MVT::Other &&
7269         "Invalid chain type");
7270   if (VT == SVT)
7271     return getStore(Chain, dl, Val, Ptr, MMO);
7272 
7273   assert(SVT.getScalarType().bitsLT(VT.getScalarType()) &&
7274          "Should only be a truncating store, not extending!");
7275   assert(VT.isInteger() == SVT.isInteger() &&
7276          "Can't do FP-INT conversion!");
7277   assert(VT.isVector() == SVT.isVector() &&
7278          "Cannot use trunc store to convert to or from a vector!");
7279   assert((!VT.isVector() ||
7280           VT.getVectorElementCount() == SVT.getVectorElementCount()) &&
7281          "Cannot use trunc store to change the number of vector elements!");
7282 
7283   SDVTList VTs = getVTList(MVT::Other);
7284   SDValue Undef = getUNDEF(Ptr.getValueType());
7285   SDValue Ops[] = { Chain, Val, Ptr, Undef };
7286   FoldingSetNodeID ID;
7287   AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
7288   ID.AddInteger(SVT.getRawBits());
7289   ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>(
7290       dl.getIROrder(), VTs, ISD::UNINDEXED, true, SVT, MMO));
7291   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7292   void *IP = nullptr;
7293   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7294     cast<StoreSDNode>(E)->refineAlignment(MMO);
7295     return SDValue(E, 0);
7296   }
7297   auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
7298                                    ISD::UNINDEXED, true, SVT, MMO);
7299   createOperands(N, Ops);
7300 
7301   CSEMap.InsertNode(N, IP);
7302   InsertNode(N);
7303   SDValue V(N, 0);
7304   NewSDValueDbgMsg(V, "Creating new node: ", this);
7305   return V;
7306 }
7307 
7308 SDValue SelectionDAG::getIndexedStore(SDValue OrigStore, const SDLoc &dl,
7309                                       SDValue Base, SDValue Offset,
7310                                       ISD::MemIndexedMode AM) {
7311   StoreSDNode *ST = cast<StoreSDNode>(OrigStore);
7312   assert(ST->getOffset().isUndef() && "Store is already a indexed store!");
7313   SDVTList VTs = getVTList(Base.getValueType(), MVT::Other);
7314   SDValue Ops[] = { ST->getChain(), ST->getValue(), Base, Offset };
7315   FoldingSetNodeID ID;
7316   AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
7317   ID.AddInteger(ST->getMemoryVT().getRawBits());
7318   ID.AddInteger(ST->getRawSubclassData());
7319   ID.AddInteger(ST->getPointerInfo().getAddrSpace());
7320   void *IP = nullptr;
7321   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
7322     return SDValue(E, 0);
7323 
7324   auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
7325                                    ST->isTruncatingStore(), ST->getMemoryVT(),
7326                                    ST->getMemOperand());
7327   createOperands(N, Ops);
7328 
7329   CSEMap.InsertNode(N, IP);
7330   InsertNode(N);
7331   SDValue V(N, 0);
7332   NewSDValueDbgMsg(V, "Creating new node: ", this);
7333   return V;
7334 }
7335 
7336 SDValue SelectionDAG::getMaskedLoad(EVT VT, const SDLoc &dl, SDValue Chain,
7337                                     SDValue Base, SDValue Offset, SDValue Mask,
7338                                     SDValue PassThru, EVT MemVT,
7339                                     MachineMemOperand *MMO,
7340                                     ISD::MemIndexedMode AM,
7341                                     ISD::LoadExtType ExtTy, bool isExpanding) {
7342   bool Indexed = AM != ISD::UNINDEXED;
7343   assert((Indexed || Offset.isUndef()) &&
7344          "Unindexed masked load with an offset!");
7345   SDVTList VTs = Indexed ? getVTList(VT, Base.getValueType(), MVT::Other)
7346                          : getVTList(VT, MVT::Other);
7347   SDValue Ops[] = {Chain, Base, Offset, Mask, PassThru};
7348   FoldingSetNodeID ID;
7349   AddNodeIDNode(ID, ISD::MLOAD, VTs, Ops);
7350   ID.AddInteger(MemVT.getRawBits());
7351   ID.AddInteger(getSyntheticNodeSubclassData<MaskedLoadSDNode>(
7352       dl.getIROrder(), VTs, AM, ExtTy, isExpanding, MemVT, MMO));
7353   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7354   void *IP = nullptr;
7355   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7356     cast<MaskedLoadSDNode>(E)->refineAlignment(MMO);
7357     return SDValue(E, 0);
7358   }
7359   auto *N = newSDNode<MaskedLoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
7360                                         AM, ExtTy, isExpanding, 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::getIndexedMaskedLoad(SDValue OrigLoad, const SDLoc &dl,
7371                                            SDValue Base, SDValue Offset,
7372                                            ISD::MemIndexedMode AM) {
7373   MaskedLoadSDNode *LD = cast<MaskedLoadSDNode>(OrigLoad);
7374   assert(LD->getOffset().isUndef() && "Masked load is already a indexed load!");
7375   return getMaskedLoad(OrigLoad.getValueType(), dl, LD->getChain(), Base,
7376                        Offset, LD->getMask(), LD->getPassThru(),
7377                        LD->getMemoryVT(), LD->getMemOperand(), AM,
7378                        LD->getExtensionType(), LD->isExpandingLoad());
7379 }
7380 
7381 SDValue SelectionDAG::getMaskedStore(SDValue Chain, const SDLoc &dl,
7382                                      SDValue Val, SDValue Base, SDValue Offset,
7383                                      SDValue Mask, EVT MemVT,
7384                                      MachineMemOperand *MMO,
7385                                      ISD::MemIndexedMode AM, bool IsTruncating,
7386                                      bool IsCompressing) {
7387   assert(Chain.getValueType() == MVT::Other &&
7388         "Invalid chain type");
7389   bool Indexed = AM != ISD::UNINDEXED;
7390   assert((Indexed || Offset.isUndef()) &&
7391          "Unindexed masked store with an offset!");
7392   SDVTList VTs = Indexed ? getVTList(Base.getValueType(), MVT::Other)
7393                          : getVTList(MVT::Other);
7394   SDValue Ops[] = {Chain, Val, Base, Offset, Mask};
7395   FoldingSetNodeID ID;
7396   AddNodeIDNode(ID, ISD::MSTORE, VTs, Ops);
7397   ID.AddInteger(MemVT.getRawBits());
7398   ID.AddInteger(getSyntheticNodeSubclassData<MaskedStoreSDNode>(
7399       dl.getIROrder(), VTs, AM, IsTruncating, IsCompressing, MemVT, MMO));
7400   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7401   void *IP = nullptr;
7402   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7403     cast<MaskedStoreSDNode>(E)->refineAlignment(MMO);
7404     return SDValue(E, 0);
7405   }
7406   auto *N =
7407       newSDNode<MaskedStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
7408                                    IsTruncating, IsCompressing, MemVT, MMO);
7409   createOperands(N, Ops);
7410 
7411   CSEMap.InsertNode(N, IP);
7412   InsertNode(N);
7413   SDValue V(N, 0);
7414   NewSDValueDbgMsg(V, "Creating new node: ", this);
7415   return V;
7416 }
7417 
7418 SDValue SelectionDAG::getIndexedMaskedStore(SDValue OrigStore, const SDLoc &dl,
7419                                             SDValue Base, SDValue Offset,
7420                                             ISD::MemIndexedMode AM) {
7421   MaskedStoreSDNode *ST = cast<MaskedStoreSDNode>(OrigStore);
7422   assert(ST->getOffset().isUndef() &&
7423          "Masked store is already a indexed store!");
7424   return getMaskedStore(ST->getChain(), dl, ST->getValue(), Base, Offset,
7425                         ST->getMask(), ST->getMemoryVT(), ST->getMemOperand(),
7426                         AM, ST->isTruncatingStore(), ST->isCompressingStore());
7427 }
7428 
7429 SDValue SelectionDAG::getMaskedGather(SDVTList VTs, EVT VT, const SDLoc &dl,
7430                                       ArrayRef<SDValue> Ops,
7431                                       MachineMemOperand *MMO,
7432                                       ISD::MemIndexType IndexType,
7433                                       ISD::LoadExtType ExtTy) {
7434   assert(Ops.size() == 6 && "Incompatible number of operands");
7435 
7436   FoldingSetNodeID ID;
7437   AddNodeIDNode(ID, ISD::MGATHER, VTs, Ops);
7438   ID.AddInteger(VT.getRawBits());
7439   ID.AddInteger(getSyntheticNodeSubclassData<MaskedGatherSDNode>(
7440       dl.getIROrder(), VTs, VT, MMO, IndexType, ExtTy));
7441   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7442   void *IP = nullptr;
7443   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7444     cast<MaskedGatherSDNode>(E)->refineAlignment(MMO);
7445     return SDValue(E, 0);
7446   }
7447 
7448   IndexType = TLI->getCanonicalIndexType(IndexType, VT, Ops[4]);
7449   auto *N = newSDNode<MaskedGatherSDNode>(dl.getIROrder(), dl.getDebugLoc(),
7450                                           VTs, VT, MMO, IndexType, ExtTy);
7451   createOperands(N, Ops);
7452 
7453   assert(N->getPassThru().getValueType() == N->getValueType(0) &&
7454          "Incompatible type of the PassThru value in MaskedGatherSDNode");
7455   assert(N->getMask().getValueType().getVectorElementCount() ==
7456              N->getValueType(0).getVectorElementCount() &&
7457          "Vector width mismatch between mask and data");
7458   assert(N->getIndex().getValueType().getVectorElementCount().isScalable() ==
7459              N->getValueType(0).getVectorElementCount().isScalable() &&
7460          "Scalable flags of index and data do not match");
7461   assert(ElementCount::isKnownGE(
7462              N->getIndex().getValueType().getVectorElementCount(),
7463              N->getValueType(0).getVectorElementCount()) &&
7464          "Vector width mismatch between index and data");
7465   assert(isa<ConstantSDNode>(N->getScale()) &&
7466          cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() &&
7467          "Scale should be a constant power of 2");
7468 
7469   CSEMap.InsertNode(N, IP);
7470   InsertNode(N);
7471   SDValue V(N, 0);
7472   NewSDValueDbgMsg(V, "Creating new node: ", this);
7473   return V;
7474 }
7475 
7476 SDValue SelectionDAG::getMaskedScatter(SDVTList VTs, EVT VT, const SDLoc &dl,
7477                                        ArrayRef<SDValue> Ops,
7478                                        MachineMemOperand *MMO,
7479                                        ISD::MemIndexType IndexType,
7480                                        bool IsTrunc) {
7481   assert(Ops.size() == 6 && "Incompatible number of operands");
7482 
7483   FoldingSetNodeID ID;
7484   AddNodeIDNode(ID, ISD::MSCATTER, VTs, Ops);
7485   ID.AddInteger(VT.getRawBits());
7486   ID.AddInteger(getSyntheticNodeSubclassData<MaskedScatterSDNode>(
7487       dl.getIROrder(), VTs, VT, MMO, IndexType, IsTrunc));
7488   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7489   void *IP = nullptr;
7490   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7491     cast<MaskedScatterSDNode>(E)->refineAlignment(MMO);
7492     return SDValue(E, 0);
7493   }
7494 
7495   IndexType = TLI->getCanonicalIndexType(IndexType, VT, Ops[4]);
7496   auto *N = newSDNode<MaskedScatterSDNode>(dl.getIROrder(), dl.getDebugLoc(),
7497                                            VTs, VT, MMO, IndexType, IsTrunc);
7498   createOperands(N, Ops);
7499 
7500   assert(N->getMask().getValueType().getVectorElementCount() ==
7501              N->getValue().getValueType().getVectorElementCount() &&
7502          "Vector width mismatch between mask and data");
7503   assert(
7504       N->getIndex().getValueType().getVectorElementCount().isScalable() ==
7505           N->getValue().getValueType().getVectorElementCount().isScalable() &&
7506       "Scalable flags of index and data do not match");
7507   assert(ElementCount::isKnownGE(
7508              N->getIndex().getValueType().getVectorElementCount(),
7509              N->getValue().getValueType().getVectorElementCount()) &&
7510          "Vector width mismatch between index and data");
7511   assert(isa<ConstantSDNode>(N->getScale()) &&
7512          cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() &&
7513          "Scale should be a constant power of 2");
7514 
7515   CSEMap.InsertNode(N, IP);
7516   InsertNode(N);
7517   SDValue V(N, 0);
7518   NewSDValueDbgMsg(V, "Creating new node: ", this);
7519   return V;
7520 }
7521 
7522 SDValue SelectionDAG::simplifySelect(SDValue Cond, SDValue T, SDValue F) {
7523   // select undef, T, F --> T (if T is a constant), otherwise F
7524   // select, ?, undef, F --> F
7525   // select, ?, T, undef --> T
7526   if (Cond.isUndef())
7527     return isConstantValueOfAnyType(T) ? T : F;
7528   if (T.isUndef())
7529     return F;
7530   if (F.isUndef())
7531     return T;
7532 
7533   // select true, T, F --> T
7534   // select false, T, F --> F
7535   if (auto *CondC = dyn_cast<ConstantSDNode>(Cond))
7536     return CondC->isNullValue() ? F : T;
7537 
7538   // TODO: This should simplify VSELECT with constant condition using something
7539   // like this (but check boolean contents to be complete?):
7540   //  if (ISD::isBuildVectorAllOnes(Cond.getNode()))
7541   //    return T;
7542   //  if (ISD::isBuildVectorAllZeros(Cond.getNode()))
7543   //    return F;
7544 
7545   // select ?, T, T --> T
7546   if (T == F)
7547     return T;
7548 
7549   return SDValue();
7550 }
7551 
7552 SDValue SelectionDAG::simplifyShift(SDValue X, SDValue Y) {
7553   // shift undef, Y --> 0 (can always assume that the undef value is 0)
7554   if (X.isUndef())
7555     return getConstant(0, SDLoc(X.getNode()), X.getValueType());
7556   // shift X, undef --> undef (because it may shift by the bitwidth)
7557   if (Y.isUndef())
7558     return getUNDEF(X.getValueType());
7559 
7560   // shift 0, Y --> 0
7561   // shift X, 0 --> X
7562   if (isNullOrNullSplat(X) || isNullOrNullSplat(Y))
7563     return X;
7564 
7565   // shift X, C >= bitwidth(X) --> undef
7566   // All vector elements must be too big (or undef) to avoid partial undefs.
7567   auto isShiftTooBig = [X](ConstantSDNode *Val) {
7568     return !Val || Val->getAPIntValue().uge(X.getScalarValueSizeInBits());
7569   };
7570   if (ISD::matchUnaryPredicate(Y, isShiftTooBig, true))
7571     return getUNDEF(X.getValueType());
7572 
7573   return SDValue();
7574 }
7575 
7576 SDValue SelectionDAG::simplifyFPBinop(unsigned Opcode, SDValue X, SDValue Y,
7577                                       SDNodeFlags Flags) {
7578   // If this operation has 'nnan' or 'ninf' and at least 1 disallowed operand
7579   // (an undef operand can be chosen to be Nan/Inf), then the result of this
7580   // operation is poison. That result can be relaxed to undef.
7581   ConstantFPSDNode *XC = isConstOrConstSplatFP(X, /* AllowUndefs */ true);
7582   ConstantFPSDNode *YC = isConstOrConstSplatFP(Y, /* AllowUndefs */ true);
7583   bool HasNan = (XC && XC->getValueAPF().isNaN()) ||
7584                 (YC && YC->getValueAPF().isNaN());
7585   bool HasInf = (XC && XC->getValueAPF().isInfinity()) ||
7586                 (YC && YC->getValueAPF().isInfinity());
7587 
7588   if (Flags.hasNoNaNs() && (HasNan || X.isUndef() || Y.isUndef()))
7589     return getUNDEF(X.getValueType());
7590 
7591   if (Flags.hasNoInfs() && (HasInf || X.isUndef() || Y.isUndef()))
7592     return getUNDEF(X.getValueType());
7593 
7594   if (!YC)
7595     return SDValue();
7596 
7597   // X + -0.0 --> X
7598   if (Opcode == ISD::FADD)
7599     if (YC->getValueAPF().isNegZero())
7600       return X;
7601 
7602   // X - +0.0 --> X
7603   if (Opcode == ISD::FSUB)
7604     if (YC->getValueAPF().isPosZero())
7605       return X;
7606 
7607   // X * 1.0 --> X
7608   // X / 1.0 --> X
7609   if (Opcode == ISD::FMUL || Opcode == ISD::FDIV)
7610     if (YC->getValueAPF().isExactlyValue(1.0))
7611       return X;
7612 
7613   // X * 0.0 --> 0.0
7614   if (Opcode == ISD::FMUL && Flags.hasNoNaNs() && Flags.hasNoSignedZeros())
7615     if (YC->getValueAPF().isZero())
7616       return getConstantFP(0.0, SDLoc(Y), Y.getValueType());
7617 
7618   return SDValue();
7619 }
7620 
7621 SDValue SelectionDAG::getVAArg(EVT VT, const SDLoc &dl, SDValue Chain,
7622                                SDValue Ptr, SDValue SV, unsigned Align) {
7623   SDValue Ops[] = { Chain, Ptr, SV, getTargetConstant(Align, dl, MVT::i32) };
7624   return getNode(ISD::VAARG, dl, getVTList(VT, MVT::Other), Ops);
7625 }
7626 
7627 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
7628                               ArrayRef<SDUse> Ops) {
7629   switch (Ops.size()) {
7630   case 0: return getNode(Opcode, DL, VT);
7631   case 1: return getNode(Opcode, DL, VT, static_cast<const SDValue>(Ops[0]));
7632   case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1]);
7633   case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2]);
7634   default: break;
7635   }
7636 
7637   // Copy from an SDUse array into an SDValue array for use with
7638   // the regular getNode logic.
7639   SmallVector<SDValue, 8> NewOps(Ops.begin(), Ops.end());
7640   return getNode(Opcode, DL, VT, NewOps);
7641 }
7642 
7643 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
7644                               ArrayRef<SDValue> Ops) {
7645   SDNodeFlags Flags;
7646   if (Inserter)
7647     Flags = Inserter->getFlags();
7648   return getNode(Opcode, DL, VT, Ops, Flags);
7649 }
7650 
7651 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
7652                               ArrayRef<SDValue> Ops, const SDNodeFlags Flags) {
7653   unsigned NumOps = Ops.size();
7654   switch (NumOps) {
7655   case 0: return getNode(Opcode, DL, VT);
7656   case 1: return getNode(Opcode, DL, VT, Ops[0], Flags);
7657   case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Flags);
7658   case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2], Flags);
7659   default: break;
7660   }
7661 
7662 #ifndef NDEBUG
7663   for (auto &Op : Ops)
7664     assert(Op.getOpcode() != ISD::DELETED_NODE &&
7665            "Operand is DELETED_NODE!");
7666 #endif
7667 
7668   switch (Opcode) {
7669   default: break;
7670   case ISD::BUILD_VECTOR:
7671     // Attempt to simplify BUILD_VECTOR.
7672     if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
7673       return V;
7674     break;
7675   case ISD::CONCAT_VECTORS:
7676     if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this))
7677       return V;
7678     break;
7679   case ISD::SELECT_CC:
7680     assert(NumOps == 5 && "SELECT_CC takes 5 operands!");
7681     assert(Ops[0].getValueType() == Ops[1].getValueType() &&
7682            "LHS and RHS of condition must have same type!");
7683     assert(Ops[2].getValueType() == Ops[3].getValueType() &&
7684            "True and False arms of SelectCC must have same type!");
7685     assert(Ops[2].getValueType() == VT &&
7686            "select_cc node must be of same type as true and false value!");
7687     break;
7688   case ISD::BR_CC:
7689     assert(NumOps == 5 && "BR_CC takes 5 operands!");
7690     assert(Ops[2].getValueType() == Ops[3].getValueType() &&
7691            "LHS/RHS of comparison should match types!");
7692     break;
7693   }
7694 
7695   // Memoize nodes.
7696   SDNode *N;
7697   SDVTList VTs = getVTList(VT);
7698 
7699   if (VT != MVT::Glue) {
7700     FoldingSetNodeID ID;
7701     AddNodeIDNode(ID, Opcode, VTs, Ops);
7702     void *IP = nullptr;
7703 
7704     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
7705       return SDValue(E, 0);
7706 
7707     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
7708     createOperands(N, Ops);
7709 
7710     CSEMap.InsertNode(N, IP);
7711   } else {
7712     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
7713     createOperands(N, Ops);
7714   }
7715 
7716   N->setFlags(Flags);
7717   InsertNode(N);
7718   SDValue V(N, 0);
7719   NewSDValueDbgMsg(V, "Creating new node: ", this);
7720   return V;
7721 }
7722 
7723 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL,
7724                               ArrayRef<EVT> ResultTys, ArrayRef<SDValue> Ops) {
7725   return getNode(Opcode, DL, getVTList(ResultTys), Ops);
7726 }
7727 
7728 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
7729                               ArrayRef<SDValue> Ops) {
7730   SDNodeFlags Flags;
7731   if (Inserter)
7732     Flags = Inserter->getFlags();
7733   return getNode(Opcode, DL, VTList, Ops, Flags);
7734 }
7735 
7736 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
7737                               ArrayRef<SDValue> Ops, const SDNodeFlags Flags) {
7738   if (VTList.NumVTs == 1)
7739     return getNode(Opcode, DL, VTList.VTs[0], Ops);
7740 
7741 #ifndef NDEBUG
7742   for (auto &Op : Ops)
7743     assert(Op.getOpcode() != ISD::DELETED_NODE &&
7744            "Operand is DELETED_NODE!");
7745 #endif
7746 
7747   switch (Opcode) {
7748   case ISD::STRICT_FP_EXTEND:
7749     assert(VTList.NumVTs == 2 && Ops.size() == 2 &&
7750            "Invalid STRICT_FP_EXTEND!");
7751     assert(VTList.VTs[0].isFloatingPoint() &&
7752            Ops[1].getValueType().isFloatingPoint() && "Invalid FP cast!");
7753     assert(VTList.VTs[0].isVector() == Ops[1].getValueType().isVector() &&
7754            "STRICT_FP_EXTEND result type should be vector iff the operand "
7755            "type is vector!");
7756     assert((!VTList.VTs[0].isVector() ||
7757             VTList.VTs[0].getVectorNumElements() ==
7758             Ops[1].getValueType().getVectorNumElements()) &&
7759            "Vector element count mismatch!");
7760     assert(Ops[1].getValueType().bitsLT(VTList.VTs[0]) &&
7761            "Invalid fpext node, dst <= src!");
7762     break;
7763   case ISD::STRICT_FP_ROUND:
7764     assert(VTList.NumVTs == 2 && Ops.size() == 3 && "Invalid STRICT_FP_ROUND!");
7765     assert(VTList.VTs[0].isVector() == Ops[1].getValueType().isVector() &&
7766            "STRICT_FP_ROUND result type should be vector iff the operand "
7767            "type is vector!");
7768     assert((!VTList.VTs[0].isVector() ||
7769             VTList.VTs[0].getVectorNumElements() ==
7770             Ops[1].getValueType().getVectorNumElements()) &&
7771            "Vector element count mismatch!");
7772     assert(VTList.VTs[0].isFloatingPoint() &&
7773            Ops[1].getValueType().isFloatingPoint() &&
7774            VTList.VTs[0].bitsLT(Ops[1].getValueType()) &&
7775            isa<ConstantSDNode>(Ops[2]) &&
7776            (cast<ConstantSDNode>(Ops[2])->getZExtValue() == 0 ||
7777             cast<ConstantSDNode>(Ops[2])->getZExtValue() == 1) &&
7778            "Invalid STRICT_FP_ROUND!");
7779     break;
7780 #if 0
7781   // FIXME: figure out how to safely handle things like
7782   // int foo(int x) { return 1 << (x & 255); }
7783   // int bar() { return foo(256); }
7784   case ISD::SRA_PARTS:
7785   case ISD::SRL_PARTS:
7786   case ISD::SHL_PARTS:
7787     if (N3.getOpcode() == ISD::SIGN_EXTEND_INREG &&
7788         cast<VTSDNode>(N3.getOperand(1))->getVT() != MVT::i1)
7789       return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0));
7790     else if (N3.getOpcode() == ISD::AND)
7791       if (ConstantSDNode *AndRHS = dyn_cast<ConstantSDNode>(N3.getOperand(1))) {
7792         // If the and is only masking out bits that cannot effect the shift,
7793         // eliminate the and.
7794         unsigned NumBits = VT.getScalarSizeInBits()*2;
7795         if ((AndRHS->getValue() & (NumBits-1)) == NumBits-1)
7796           return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0));
7797       }
7798     break;
7799 #endif
7800   }
7801 
7802   // Memoize the node unless it returns a flag.
7803   SDNode *N;
7804   if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) {
7805     FoldingSetNodeID ID;
7806     AddNodeIDNode(ID, Opcode, VTList, Ops);
7807     void *IP = nullptr;
7808     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
7809       return SDValue(E, 0);
7810 
7811     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList);
7812     createOperands(N, Ops);
7813     CSEMap.InsertNode(N, IP);
7814   } else {
7815     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList);
7816     createOperands(N, Ops);
7817   }
7818 
7819   N->setFlags(Flags);
7820   InsertNode(N);
7821   SDValue V(N, 0);
7822   NewSDValueDbgMsg(V, "Creating new node: ", this);
7823   return V;
7824 }
7825 
7826 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL,
7827                               SDVTList VTList) {
7828   return getNode(Opcode, DL, VTList, None);
7829 }
7830 
7831 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
7832                               SDValue N1) {
7833   SDValue Ops[] = { N1 };
7834   return getNode(Opcode, DL, VTList, Ops);
7835 }
7836 
7837 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
7838                               SDValue N1, SDValue N2) {
7839   SDValue Ops[] = { N1, N2 };
7840   return getNode(Opcode, DL, VTList, Ops);
7841 }
7842 
7843 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
7844                               SDValue N1, SDValue N2, SDValue N3) {
7845   SDValue Ops[] = { N1, N2, N3 };
7846   return getNode(Opcode, DL, VTList, Ops);
7847 }
7848 
7849 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
7850                               SDValue N1, SDValue N2, SDValue N3, SDValue N4) {
7851   SDValue Ops[] = { N1, N2, N3, N4 };
7852   return getNode(Opcode, DL, VTList, Ops);
7853 }
7854 
7855 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
7856                               SDValue N1, SDValue N2, SDValue N3, SDValue N4,
7857                               SDValue N5) {
7858   SDValue Ops[] = { N1, N2, N3, N4, N5 };
7859   return getNode(Opcode, DL, VTList, Ops);
7860 }
7861 
7862 SDVTList SelectionDAG::getVTList(EVT VT) {
7863   return makeVTList(SDNode::getValueTypeList(VT), 1);
7864 }
7865 
7866 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2) {
7867   FoldingSetNodeID ID;
7868   ID.AddInteger(2U);
7869   ID.AddInteger(VT1.getRawBits());
7870   ID.AddInteger(VT2.getRawBits());
7871 
7872   void *IP = nullptr;
7873   SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
7874   if (!Result) {
7875     EVT *Array = Allocator.Allocate<EVT>(2);
7876     Array[0] = VT1;
7877     Array[1] = VT2;
7878     Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 2);
7879     VTListMap.InsertNode(Result, IP);
7880   }
7881   return Result->getSDVTList();
7882 }
7883 
7884 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3) {
7885   FoldingSetNodeID ID;
7886   ID.AddInteger(3U);
7887   ID.AddInteger(VT1.getRawBits());
7888   ID.AddInteger(VT2.getRawBits());
7889   ID.AddInteger(VT3.getRawBits());
7890 
7891   void *IP = nullptr;
7892   SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
7893   if (!Result) {
7894     EVT *Array = Allocator.Allocate<EVT>(3);
7895     Array[0] = VT1;
7896     Array[1] = VT2;
7897     Array[2] = VT3;
7898     Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 3);
7899     VTListMap.InsertNode(Result, IP);
7900   }
7901   return Result->getSDVTList();
7902 }
7903 
7904 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3, EVT VT4) {
7905   FoldingSetNodeID ID;
7906   ID.AddInteger(4U);
7907   ID.AddInteger(VT1.getRawBits());
7908   ID.AddInteger(VT2.getRawBits());
7909   ID.AddInteger(VT3.getRawBits());
7910   ID.AddInteger(VT4.getRawBits());
7911 
7912   void *IP = nullptr;
7913   SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
7914   if (!Result) {
7915     EVT *Array = Allocator.Allocate<EVT>(4);
7916     Array[0] = VT1;
7917     Array[1] = VT2;
7918     Array[2] = VT3;
7919     Array[3] = VT4;
7920     Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 4);
7921     VTListMap.InsertNode(Result, IP);
7922   }
7923   return Result->getSDVTList();
7924 }
7925 
7926 SDVTList SelectionDAG::getVTList(ArrayRef<EVT> VTs) {
7927   unsigned NumVTs = VTs.size();
7928   FoldingSetNodeID ID;
7929   ID.AddInteger(NumVTs);
7930   for (unsigned index = 0; index < NumVTs; index++) {
7931     ID.AddInteger(VTs[index].getRawBits());
7932   }
7933 
7934   void *IP = nullptr;
7935   SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
7936   if (!Result) {
7937     EVT *Array = Allocator.Allocate<EVT>(NumVTs);
7938     llvm::copy(VTs, Array);
7939     Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, NumVTs);
7940     VTListMap.InsertNode(Result, IP);
7941   }
7942   return Result->getSDVTList();
7943 }
7944 
7945 
7946 /// UpdateNodeOperands - *Mutate* the specified node in-place to have the
7947 /// specified operands.  If the resultant node already exists in the DAG,
7948 /// this does not modify the specified node, instead it returns the node that
7949 /// already exists.  If the resultant node does not exist in the DAG, the
7950 /// input node is returned.  As a degenerate case, if you specify the same
7951 /// input operands as the node already has, the input node is returned.
7952 SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op) {
7953   assert(N->getNumOperands() == 1 && "Update with wrong number of operands");
7954 
7955   // Check to see if there is no change.
7956   if (Op == N->getOperand(0)) return N;
7957 
7958   // See if the modified node already exists.
7959   void *InsertPos = nullptr;
7960   if (SDNode *Existing = FindModifiedNodeSlot(N, Op, InsertPos))
7961     return Existing;
7962 
7963   // Nope it doesn't.  Remove the node from its current place in the maps.
7964   if (InsertPos)
7965     if (!RemoveNodeFromCSEMaps(N))
7966       InsertPos = nullptr;
7967 
7968   // Now we update the operands.
7969   N->OperandList[0].set(Op);
7970 
7971   updateDivergence(N);
7972   // If this gets put into a CSE map, add it.
7973   if (InsertPos) CSEMap.InsertNode(N, InsertPos);
7974   return N;
7975 }
7976 
7977 SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2) {
7978   assert(N->getNumOperands() == 2 && "Update with wrong number of operands");
7979 
7980   // Check to see if there is no change.
7981   if (Op1 == N->getOperand(0) && Op2 == N->getOperand(1))
7982     return N;   // No operands changed, just return the input node.
7983 
7984   // See if the modified node already exists.
7985   void *InsertPos = nullptr;
7986   if (SDNode *Existing = FindModifiedNodeSlot(N, Op1, Op2, InsertPos))
7987     return Existing;
7988 
7989   // Nope it doesn't.  Remove the node from its current place in the maps.
7990   if (InsertPos)
7991     if (!RemoveNodeFromCSEMaps(N))
7992       InsertPos = nullptr;
7993 
7994   // Now we update the operands.
7995   if (N->OperandList[0] != Op1)
7996     N->OperandList[0].set(Op1);
7997   if (N->OperandList[1] != Op2)
7998     N->OperandList[1].set(Op2);
7999 
8000   updateDivergence(N);
8001   // If this gets put into a CSE map, add it.
8002   if (InsertPos) CSEMap.InsertNode(N, InsertPos);
8003   return N;
8004 }
8005 
8006 SDNode *SelectionDAG::
8007 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2, SDValue Op3) {
8008   SDValue Ops[] = { Op1, Op2, Op3 };
8009   return UpdateNodeOperands(N, Ops);
8010 }
8011 
8012 SDNode *SelectionDAG::
8013 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2,
8014                    SDValue Op3, SDValue Op4) {
8015   SDValue Ops[] = { Op1, Op2, Op3, Op4 };
8016   return UpdateNodeOperands(N, Ops);
8017 }
8018 
8019 SDNode *SelectionDAG::
8020 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2,
8021                    SDValue Op3, SDValue Op4, SDValue Op5) {
8022   SDValue Ops[] = { Op1, Op2, Op3, Op4, Op5 };
8023   return UpdateNodeOperands(N, Ops);
8024 }
8025 
8026 SDNode *SelectionDAG::
8027 UpdateNodeOperands(SDNode *N, ArrayRef<SDValue> Ops) {
8028   unsigned NumOps = Ops.size();
8029   assert(N->getNumOperands() == NumOps &&
8030          "Update with wrong number of operands");
8031 
8032   // If no operands changed just return the input node.
8033   if (std::equal(Ops.begin(), Ops.end(), N->op_begin()))
8034     return N;
8035 
8036   // See if the modified node already exists.
8037   void *InsertPos = nullptr;
8038   if (SDNode *Existing = FindModifiedNodeSlot(N, Ops, InsertPos))
8039     return Existing;
8040 
8041   // Nope it doesn't.  Remove the node from its current place in the maps.
8042   if (InsertPos)
8043     if (!RemoveNodeFromCSEMaps(N))
8044       InsertPos = nullptr;
8045 
8046   // Now we update the operands.
8047   for (unsigned i = 0; i != NumOps; ++i)
8048     if (N->OperandList[i] != Ops[i])
8049       N->OperandList[i].set(Ops[i]);
8050 
8051   updateDivergence(N);
8052   // If this gets put into a CSE map, add it.
8053   if (InsertPos) CSEMap.InsertNode(N, InsertPos);
8054   return N;
8055 }
8056 
8057 /// DropOperands - Release the operands and set this node to have
8058 /// zero operands.
8059 void SDNode::DropOperands() {
8060   // Unlike the code in MorphNodeTo that does this, we don't need to
8061   // watch for dead nodes here.
8062   for (op_iterator I = op_begin(), E = op_end(); I != E; ) {
8063     SDUse &Use = *I++;
8064     Use.set(SDValue());
8065   }
8066 }
8067 
8068 void SelectionDAG::setNodeMemRefs(MachineSDNode *N,
8069                                   ArrayRef<MachineMemOperand *> NewMemRefs) {
8070   if (NewMemRefs.empty()) {
8071     N->clearMemRefs();
8072     return;
8073   }
8074 
8075   // Check if we can avoid allocating by storing a single reference directly.
8076   if (NewMemRefs.size() == 1) {
8077     N->MemRefs = NewMemRefs[0];
8078     N->NumMemRefs = 1;
8079     return;
8080   }
8081 
8082   MachineMemOperand **MemRefsBuffer =
8083       Allocator.template Allocate<MachineMemOperand *>(NewMemRefs.size());
8084   llvm::copy(NewMemRefs, MemRefsBuffer);
8085   N->MemRefs = MemRefsBuffer;
8086   N->NumMemRefs = static_cast<int>(NewMemRefs.size());
8087 }
8088 
8089 /// SelectNodeTo - These are wrappers around MorphNodeTo that accept a
8090 /// machine opcode.
8091 ///
8092 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8093                                    EVT VT) {
8094   SDVTList VTs = getVTList(VT);
8095   return SelectNodeTo(N, MachineOpc, VTs, None);
8096 }
8097 
8098 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8099                                    EVT VT, SDValue Op1) {
8100   SDVTList VTs = getVTList(VT);
8101   SDValue Ops[] = { Op1 };
8102   return SelectNodeTo(N, MachineOpc, VTs, Ops);
8103 }
8104 
8105 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8106                                    EVT VT, SDValue Op1,
8107                                    SDValue Op2) {
8108   SDVTList VTs = getVTList(VT);
8109   SDValue Ops[] = { Op1, Op2 };
8110   return SelectNodeTo(N, MachineOpc, VTs, Ops);
8111 }
8112 
8113 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8114                                    EVT VT, SDValue Op1,
8115                                    SDValue Op2, SDValue Op3) {
8116   SDVTList VTs = getVTList(VT);
8117   SDValue Ops[] = { Op1, Op2, Op3 };
8118   return SelectNodeTo(N, MachineOpc, VTs, Ops);
8119 }
8120 
8121 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8122                                    EVT VT, ArrayRef<SDValue> Ops) {
8123   SDVTList VTs = getVTList(VT);
8124   return SelectNodeTo(N, MachineOpc, VTs, Ops);
8125 }
8126 
8127 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8128                                    EVT VT1, EVT VT2, ArrayRef<SDValue> Ops) {
8129   SDVTList VTs = getVTList(VT1, VT2);
8130   return SelectNodeTo(N, MachineOpc, VTs, Ops);
8131 }
8132 
8133 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8134                                    EVT VT1, EVT VT2) {
8135   SDVTList VTs = getVTList(VT1, VT2);
8136   return SelectNodeTo(N, MachineOpc, VTs, None);
8137 }
8138 
8139 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8140                                    EVT VT1, EVT VT2, EVT VT3,
8141                                    ArrayRef<SDValue> Ops) {
8142   SDVTList VTs = getVTList(VT1, VT2, VT3);
8143   return SelectNodeTo(N, MachineOpc, VTs, Ops);
8144 }
8145 
8146 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8147                                    EVT VT1, EVT VT2,
8148                                    SDValue Op1, SDValue Op2) {
8149   SDVTList VTs = getVTList(VT1, VT2);
8150   SDValue Ops[] = { Op1, Op2 };
8151   return SelectNodeTo(N, MachineOpc, VTs, Ops);
8152 }
8153 
8154 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8155                                    SDVTList VTs,ArrayRef<SDValue> Ops) {
8156   SDNode *New = MorphNodeTo(N, ~MachineOpc, VTs, Ops);
8157   // Reset the NodeID to -1.
8158   New->setNodeId(-1);
8159   if (New != N) {
8160     ReplaceAllUsesWith(N, New);
8161     RemoveDeadNode(N);
8162   }
8163   return New;
8164 }
8165 
8166 /// UpdateSDLocOnMergeSDNode - If the opt level is -O0 then it throws away
8167 /// the line number information on the merged node since it is not possible to
8168 /// preserve the information that operation is associated with multiple lines.
8169 /// This will make the debugger working better at -O0, were there is a higher
8170 /// probability having other instructions associated with that line.
8171 ///
8172 /// For IROrder, we keep the smaller of the two
8173 SDNode *SelectionDAG::UpdateSDLocOnMergeSDNode(SDNode *N, const SDLoc &OLoc) {
8174   DebugLoc NLoc = N->getDebugLoc();
8175   if (NLoc && OptLevel == CodeGenOpt::None && OLoc.getDebugLoc() != NLoc) {
8176     N->setDebugLoc(DebugLoc());
8177   }
8178   unsigned Order = std::min(N->getIROrder(), OLoc.getIROrder());
8179   N->setIROrder(Order);
8180   return N;
8181 }
8182 
8183 /// MorphNodeTo - This *mutates* the specified node to have the specified
8184 /// return type, opcode, and operands.
8185 ///
8186 /// Note that MorphNodeTo returns the resultant node.  If there is already a
8187 /// node of the specified opcode and operands, it returns that node instead of
8188 /// the current one.  Note that the SDLoc need not be the same.
8189 ///
8190 /// Using MorphNodeTo is faster than creating a new node and swapping it in
8191 /// with ReplaceAllUsesWith both because it often avoids allocating a new
8192 /// node, and because it doesn't require CSE recalculation for any of
8193 /// the node's users.
8194 ///
8195 /// However, note that MorphNodeTo recursively deletes dead nodes from the DAG.
8196 /// As a consequence it isn't appropriate to use from within the DAG combiner or
8197 /// the legalizer which maintain worklists that would need to be updated when
8198 /// deleting things.
8199 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
8200                                   SDVTList VTs, ArrayRef<SDValue> Ops) {
8201   // If an identical node already exists, use it.
8202   void *IP = nullptr;
8203   if (VTs.VTs[VTs.NumVTs-1] != MVT::Glue) {
8204     FoldingSetNodeID ID;
8205     AddNodeIDNode(ID, Opc, VTs, Ops);
8206     if (SDNode *ON = FindNodeOrInsertPos(ID, SDLoc(N), IP))
8207       return UpdateSDLocOnMergeSDNode(ON, SDLoc(N));
8208   }
8209 
8210   if (!RemoveNodeFromCSEMaps(N))
8211     IP = nullptr;
8212 
8213   // Start the morphing.
8214   N->NodeType = Opc;
8215   N->ValueList = VTs.VTs;
8216   N->NumValues = VTs.NumVTs;
8217 
8218   // Clear the operands list, updating used nodes to remove this from their
8219   // use list.  Keep track of any operands that become dead as a result.
8220   SmallPtrSet<SDNode*, 16> DeadNodeSet;
8221   for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) {
8222     SDUse &Use = *I++;
8223     SDNode *Used = Use.getNode();
8224     Use.set(SDValue());
8225     if (Used->use_empty())
8226       DeadNodeSet.insert(Used);
8227   }
8228 
8229   // For MachineNode, initialize the memory references information.
8230   if (MachineSDNode *MN = dyn_cast<MachineSDNode>(N))
8231     MN->clearMemRefs();
8232 
8233   // Swap for an appropriately sized array from the recycler.
8234   removeOperands(N);
8235   createOperands(N, Ops);
8236 
8237   // Delete any nodes that are still dead after adding the uses for the
8238   // new operands.
8239   if (!DeadNodeSet.empty()) {
8240     SmallVector<SDNode *, 16> DeadNodes;
8241     for (SDNode *N : DeadNodeSet)
8242       if (N->use_empty())
8243         DeadNodes.push_back(N);
8244     RemoveDeadNodes(DeadNodes);
8245   }
8246 
8247   if (IP)
8248     CSEMap.InsertNode(N, IP);   // Memoize the new node.
8249   return N;
8250 }
8251 
8252 SDNode* SelectionDAG::mutateStrictFPToFP(SDNode *Node) {
8253   unsigned OrigOpc = Node->getOpcode();
8254   unsigned NewOpc;
8255   switch (OrigOpc) {
8256   default:
8257     llvm_unreachable("mutateStrictFPToFP called with unexpected opcode!");
8258 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN)               \
8259   case ISD::STRICT_##DAGN: NewOpc = ISD::DAGN; break;
8260 #define CMP_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN)               \
8261   case ISD::STRICT_##DAGN: NewOpc = ISD::SETCC; break;
8262 #include "llvm/IR/ConstrainedOps.def"
8263   }
8264 
8265   assert(Node->getNumValues() == 2 && "Unexpected number of results!");
8266 
8267   // We're taking this node out of the chain, so we need to re-link things.
8268   SDValue InputChain = Node->getOperand(0);
8269   SDValue OutputChain = SDValue(Node, 1);
8270   ReplaceAllUsesOfValueWith(OutputChain, InputChain);
8271 
8272   SmallVector<SDValue, 3> Ops;
8273   for (unsigned i = 1, e = Node->getNumOperands(); i != e; ++i)
8274     Ops.push_back(Node->getOperand(i));
8275 
8276   SDVTList VTs = getVTList(Node->getValueType(0));
8277   SDNode *Res = MorphNodeTo(Node, NewOpc, VTs, Ops);
8278 
8279   // MorphNodeTo can operate in two ways: if an existing node with the
8280   // specified operands exists, it can just return it.  Otherwise, it
8281   // updates the node in place to have the requested operands.
8282   if (Res == Node) {
8283     // If we updated the node in place, reset the node ID.  To the isel,
8284     // this should be just like a newly allocated machine node.
8285     Res->setNodeId(-1);
8286   } else {
8287     ReplaceAllUsesWith(Node, Res);
8288     RemoveDeadNode(Node);
8289   }
8290 
8291   return Res;
8292 }
8293 
8294 /// getMachineNode - These are used for target selectors to create a new node
8295 /// with specified return type(s), MachineInstr opcode, and operands.
8296 ///
8297 /// Note that getMachineNode returns the resultant node.  If there is already a
8298 /// node of the specified opcode and operands, it returns that node instead of
8299 /// the current one.
8300 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
8301                                             EVT VT) {
8302   SDVTList VTs = getVTList(VT);
8303   return getMachineNode(Opcode, dl, VTs, None);
8304 }
8305 
8306 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
8307                                             EVT VT, SDValue Op1) {
8308   SDVTList VTs = getVTList(VT);
8309   SDValue Ops[] = { Op1 };
8310   return getMachineNode(Opcode, dl, VTs, Ops);
8311 }
8312 
8313 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
8314                                             EVT VT, SDValue Op1, SDValue Op2) {
8315   SDVTList VTs = getVTList(VT);
8316   SDValue Ops[] = { Op1, Op2 };
8317   return getMachineNode(Opcode, dl, VTs, Ops);
8318 }
8319 
8320 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
8321                                             EVT VT, SDValue Op1, SDValue Op2,
8322                                             SDValue Op3) {
8323   SDVTList VTs = getVTList(VT);
8324   SDValue Ops[] = { Op1, Op2, Op3 };
8325   return getMachineNode(Opcode, dl, VTs, Ops);
8326 }
8327 
8328 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
8329                                             EVT VT, ArrayRef<SDValue> Ops) {
8330   SDVTList VTs = getVTList(VT);
8331   return getMachineNode(Opcode, dl, VTs, Ops);
8332 }
8333 
8334 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
8335                                             EVT VT1, EVT VT2, SDValue Op1,
8336                                             SDValue Op2) {
8337   SDVTList VTs = getVTList(VT1, VT2);
8338   SDValue Ops[] = { Op1, Op2 };
8339   return getMachineNode(Opcode, dl, VTs, Ops);
8340 }
8341 
8342 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
8343                                             EVT VT1, EVT VT2, SDValue Op1,
8344                                             SDValue Op2, SDValue Op3) {
8345   SDVTList VTs = getVTList(VT1, VT2);
8346   SDValue Ops[] = { Op1, Op2, Op3 };
8347   return getMachineNode(Opcode, dl, VTs, Ops);
8348 }
8349 
8350 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
8351                                             EVT VT1, EVT VT2,
8352                                             ArrayRef<SDValue> Ops) {
8353   SDVTList VTs = getVTList(VT1, VT2);
8354   return getMachineNode(Opcode, dl, VTs, Ops);
8355 }
8356 
8357 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
8358                                             EVT VT1, EVT VT2, EVT VT3,
8359                                             SDValue Op1, SDValue Op2) {
8360   SDVTList VTs = getVTList(VT1, VT2, VT3);
8361   SDValue Ops[] = { Op1, Op2 };
8362   return getMachineNode(Opcode, dl, VTs, Ops);
8363 }
8364 
8365 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
8366                                             EVT VT1, EVT VT2, EVT VT3,
8367                                             SDValue Op1, SDValue Op2,
8368                                             SDValue Op3) {
8369   SDVTList VTs = getVTList(VT1, VT2, VT3);
8370   SDValue Ops[] = { Op1, Op2, Op3 };
8371   return getMachineNode(Opcode, dl, VTs, Ops);
8372 }
8373 
8374 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
8375                                             EVT VT1, EVT VT2, EVT VT3,
8376                                             ArrayRef<SDValue> Ops) {
8377   SDVTList VTs = getVTList(VT1, VT2, VT3);
8378   return getMachineNode(Opcode, dl, VTs, Ops);
8379 }
8380 
8381 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
8382                                             ArrayRef<EVT> ResultTys,
8383                                             ArrayRef<SDValue> Ops) {
8384   SDVTList VTs = getVTList(ResultTys);
8385   return getMachineNode(Opcode, dl, VTs, Ops);
8386 }
8387 
8388 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &DL,
8389                                             SDVTList VTs,
8390                                             ArrayRef<SDValue> Ops) {
8391   bool DoCSE = VTs.VTs[VTs.NumVTs-1] != MVT::Glue;
8392   MachineSDNode *N;
8393   void *IP = nullptr;
8394 
8395   if (DoCSE) {
8396     FoldingSetNodeID ID;
8397     AddNodeIDNode(ID, ~Opcode, VTs, Ops);
8398     IP = nullptr;
8399     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
8400       return cast<MachineSDNode>(UpdateSDLocOnMergeSDNode(E, DL));
8401     }
8402   }
8403 
8404   // Allocate a new MachineSDNode.
8405   N = newSDNode<MachineSDNode>(~Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
8406   createOperands(N, Ops);
8407 
8408   if (DoCSE)
8409     CSEMap.InsertNode(N, IP);
8410 
8411   InsertNode(N);
8412   NewSDValueDbgMsg(SDValue(N, 0), "Creating new machine node: ", this);
8413   return N;
8414 }
8415 
8416 /// getTargetExtractSubreg - A convenience function for creating
8417 /// TargetOpcode::EXTRACT_SUBREG nodes.
8418 SDValue SelectionDAG::getTargetExtractSubreg(int SRIdx, const SDLoc &DL, EVT VT,
8419                                              SDValue Operand) {
8420   SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32);
8421   SDNode *Subreg = getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL,
8422                                   VT, Operand, SRIdxVal);
8423   return SDValue(Subreg, 0);
8424 }
8425 
8426 /// getTargetInsertSubreg - A convenience function for creating
8427 /// TargetOpcode::INSERT_SUBREG nodes.
8428 SDValue SelectionDAG::getTargetInsertSubreg(int SRIdx, const SDLoc &DL, EVT VT,
8429                                             SDValue Operand, SDValue Subreg) {
8430   SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32);
8431   SDNode *Result = getMachineNode(TargetOpcode::INSERT_SUBREG, DL,
8432                                   VT, Operand, Subreg, SRIdxVal);
8433   return SDValue(Result, 0);
8434 }
8435 
8436 /// getNodeIfExists - Get the specified node if it's already available, or
8437 /// else return NULL.
8438 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList,
8439                                       ArrayRef<SDValue> Ops) {
8440   SDNodeFlags Flags;
8441   if (Inserter)
8442     Flags = Inserter->getFlags();
8443   return getNodeIfExists(Opcode, VTList, Ops, Flags);
8444 }
8445 
8446 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList,
8447                                       ArrayRef<SDValue> Ops,
8448                                       const SDNodeFlags Flags) {
8449   if (VTList.VTs[VTList.NumVTs - 1] != MVT::Glue) {
8450     FoldingSetNodeID ID;
8451     AddNodeIDNode(ID, Opcode, VTList, Ops);
8452     void *IP = nullptr;
8453     if (SDNode *E = FindNodeOrInsertPos(ID, SDLoc(), IP)) {
8454       E->intersectFlagsWith(Flags);
8455       return E;
8456     }
8457   }
8458   return nullptr;
8459 }
8460 
8461 /// doesNodeExist - Check if a node exists without modifying its flags.
8462 bool SelectionDAG::doesNodeExist(unsigned Opcode, SDVTList VTList,
8463                                  ArrayRef<SDValue> Ops) {
8464   if (VTList.VTs[VTList.NumVTs - 1] != MVT::Glue) {
8465     FoldingSetNodeID ID;
8466     AddNodeIDNode(ID, Opcode, VTList, Ops);
8467     void *IP = nullptr;
8468     if (FindNodeOrInsertPos(ID, SDLoc(), IP))
8469       return true;
8470   }
8471   return false;
8472 }
8473 
8474 /// getDbgValue - Creates a SDDbgValue node.
8475 ///
8476 /// SDNode
8477 SDDbgValue *SelectionDAG::getDbgValue(DIVariable *Var, DIExpression *Expr,
8478                                       SDNode *N, unsigned R, bool IsIndirect,
8479                                       const DebugLoc &DL, unsigned O) {
8480   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
8481          "Expected inlined-at fields to agree");
8482   return new (DbgInfo->getAlloc())
8483       SDDbgValue(Var, Expr, SDDbgOperand::fromNode(N, R), N, IsIndirect, DL, O,
8484                  /*IsVariadic=*/false);
8485 }
8486 
8487 /// Constant
8488 SDDbgValue *SelectionDAG::getConstantDbgValue(DIVariable *Var,
8489                                               DIExpression *Expr,
8490                                               const Value *C,
8491                                               const DebugLoc &DL, unsigned O) {
8492   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
8493          "Expected inlined-at fields to agree");
8494   return new (DbgInfo->getAlloc()) SDDbgValue(
8495       Var, Expr, SDDbgOperand::fromConst(C), {}, /*IsIndirect=*/false, DL, O,
8496       /*IsVariadic=*/false);
8497 }
8498 
8499 /// FrameIndex
8500 SDDbgValue *SelectionDAG::getFrameIndexDbgValue(DIVariable *Var,
8501                                                 DIExpression *Expr, unsigned FI,
8502                                                 bool IsIndirect,
8503                                                 const DebugLoc &DL,
8504                                                 unsigned O) {
8505   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
8506          "Expected inlined-at fields to agree");
8507   return getFrameIndexDbgValue(Var, Expr, FI, {}, IsIndirect, DL, O);
8508 }
8509 
8510 /// FrameIndex with dependencies
8511 SDDbgValue *SelectionDAG::getFrameIndexDbgValue(DIVariable *Var,
8512                                                 DIExpression *Expr, unsigned FI,
8513                                                 ArrayRef<SDNode *> Dependencies,
8514                                                 bool IsIndirect,
8515                                                 const DebugLoc &DL,
8516                                                 unsigned O) {
8517   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
8518          "Expected inlined-at fields to agree");
8519   return new (DbgInfo->getAlloc())
8520       SDDbgValue(Var, Expr, SDDbgOperand::fromFrameIdx(FI), Dependencies,
8521                  IsIndirect, DL, O,
8522                  /*IsVariadic=*/false);
8523 }
8524 
8525 /// VReg
8526 SDDbgValue *SelectionDAG::getVRegDbgValue(DIVariable *Var, DIExpression *Expr,
8527                                           unsigned VReg, bool IsIndirect,
8528                                           const DebugLoc &DL, unsigned O) {
8529   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
8530          "Expected inlined-at fields to agree");
8531   return new (DbgInfo->getAlloc())
8532       SDDbgValue(Var, Expr, SDDbgOperand::fromVReg(VReg), {}, IsIndirect, DL, O,
8533                  /*IsVariadic=*/false);
8534 }
8535 
8536 SDDbgValue *SelectionDAG::getDbgValueList(DIVariable *Var, DIExpression *Expr,
8537                                           ArrayRef<SDDbgOperand> Locs,
8538                                           ArrayRef<SDNode *> Dependencies,
8539                                           bool IsIndirect, const DebugLoc &DL,
8540                                           unsigned O, bool IsVariadic) {
8541   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
8542          "Expected inlined-at fields to agree");
8543   return new (DbgInfo->getAlloc())
8544       SDDbgValue(Var, Expr, Locs, Dependencies, IsIndirect, DL, O, IsVariadic);
8545 }
8546 
8547 void SelectionDAG::transferDbgValues(SDValue From, SDValue To,
8548                                      unsigned OffsetInBits, unsigned SizeInBits,
8549                                      bool InvalidateDbg) {
8550   SDNode *FromNode = From.getNode();
8551   SDNode *ToNode = To.getNode();
8552   assert(FromNode && ToNode && "Can't modify dbg values");
8553 
8554   // PR35338
8555   // TODO: assert(From != To && "Redundant dbg value transfer");
8556   // TODO: assert(FromNode != ToNode && "Intranode dbg value transfer");
8557   if (From == To || FromNode == ToNode)
8558     return;
8559 
8560   if (!FromNode->getHasDebugValue())
8561     return;
8562 
8563   SDDbgOperand FromLocOp =
8564       SDDbgOperand::fromNode(From.getNode(), From.getResNo());
8565   SDDbgOperand ToLocOp = SDDbgOperand::fromNode(To.getNode(), To.getResNo());
8566 
8567   SmallVector<SDDbgValue *, 2> ClonedDVs;
8568   for (SDDbgValue *Dbg : GetDbgValues(FromNode)) {
8569     if (Dbg->isInvalidated())
8570       continue;
8571 
8572     // TODO: assert(!Dbg->isInvalidated() && "Transfer of invalid dbg value");
8573 
8574     // Create a new location ops vector that is equal to the old vector, but
8575     // with each instance of FromLocOp replaced with ToLocOp.
8576     bool Changed = false;
8577     auto NewLocOps = Dbg->copyLocationOps();
8578     std::replace_if(
8579         NewLocOps.begin(), NewLocOps.end(),
8580         [&Changed, FromLocOp](const SDDbgOperand &Op) {
8581           bool Match = Op == FromLocOp;
8582           Changed |= Match;
8583           return Match;
8584         },
8585         ToLocOp);
8586     // Ignore this SDDbgValue if we didn't find a matching location.
8587     if (!Changed)
8588       continue;
8589 
8590     DIVariable *Var = Dbg->getVariable();
8591     auto *Expr = Dbg->getExpression();
8592     // If a fragment is requested, update the expression.
8593     if (SizeInBits) {
8594       // When splitting a larger (e.g., sign-extended) value whose
8595       // lower bits are described with an SDDbgValue, do not attempt
8596       // to transfer the SDDbgValue to the upper bits.
8597       if (auto FI = Expr->getFragmentInfo())
8598         if (OffsetInBits + SizeInBits > FI->SizeInBits)
8599           continue;
8600       auto Fragment = DIExpression::createFragmentExpression(Expr, OffsetInBits,
8601                                                              SizeInBits);
8602       if (!Fragment)
8603         continue;
8604       Expr = *Fragment;
8605     }
8606 
8607     auto NewDependencies = Dbg->copySDNodes();
8608     std::replace(NewDependencies.begin(), NewDependencies.end(), FromNode,
8609                  ToNode);
8610     // Clone the SDDbgValue and move it to To.
8611     SDDbgValue *Clone = getDbgValueList(
8612         Var, Expr, NewLocOps, NewDependencies, Dbg->isIndirect(),
8613         Dbg->getDebugLoc(), std::max(ToNode->getIROrder(), Dbg->getOrder()),
8614         Dbg->isVariadic());
8615     ClonedDVs.push_back(Clone);
8616 
8617     if (InvalidateDbg) {
8618       // Invalidate value and indicate the SDDbgValue should not be emitted.
8619       Dbg->setIsInvalidated();
8620       Dbg->setIsEmitted();
8621     }
8622   }
8623 
8624   for (SDDbgValue *Dbg : ClonedDVs) {
8625     assert(is_contained(Dbg->getSDNodes(), ToNode) &&
8626            "Transferred DbgValues should depend on the new SDNode");
8627     AddDbgValue(Dbg, false);
8628   }
8629 }
8630 
8631 void SelectionDAG::salvageDebugInfo(SDNode &N) {
8632   if (!N.getHasDebugValue())
8633     return;
8634 
8635   SmallVector<SDDbgValue *, 2> ClonedDVs;
8636   for (auto DV : GetDbgValues(&N)) {
8637     if (DV->isInvalidated())
8638       continue;
8639     switch (N.getOpcode()) {
8640     default:
8641       break;
8642     case ISD::ADD:
8643       SDValue N0 = N.getOperand(0);
8644       SDValue N1 = N.getOperand(1);
8645       if (!isConstantIntBuildVectorOrConstantInt(N0) &&
8646           isConstantIntBuildVectorOrConstantInt(N1)) {
8647         uint64_t Offset = N.getConstantOperandVal(1);
8648 
8649         // Rewrite an ADD constant node into a DIExpression. Since we are
8650         // performing arithmetic to compute the variable's *value* in the
8651         // DIExpression, we need to mark the expression with a
8652         // DW_OP_stack_value.
8653         auto *DIExpr = DV->getExpression();
8654         auto NewLocOps = DV->copyLocationOps();
8655         bool Changed = false;
8656         for (size_t i = 0; i < NewLocOps.size(); ++i) {
8657           // We're not given a ResNo to compare against because the whole
8658           // node is going away. We know that any ISD::ADD only has one
8659           // result, so we can assume any node match is using the result.
8660           if (NewLocOps[i].getKind() != SDDbgOperand::SDNODE ||
8661               NewLocOps[i].getSDNode() != &N)
8662             continue;
8663           NewLocOps[i] = SDDbgOperand::fromNode(N0.getNode(), N0.getResNo());
8664           SmallVector<uint64_t, 3> ExprOps;
8665           DIExpression::appendOffset(ExprOps, Offset);
8666           DIExpr = DIExpression::appendOpsToArg(DIExpr, ExprOps, i, true);
8667           Changed = true;
8668         }
8669         (void)Changed;
8670         assert(Changed && "Salvage target doesn't use N");
8671 
8672         auto NewDependencies = DV->copySDNodes();
8673         std::replace(NewDependencies.begin(), NewDependencies.end(), &N,
8674                      N0.getNode());
8675         SDDbgValue *Clone = getDbgValueList(DV->getVariable(), DIExpr,
8676                                             NewLocOps, NewDependencies,
8677                                             DV->isIndirect(), DV->getDebugLoc(),
8678                                             DV->getOrder(), DV->isVariadic());
8679         ClonedDVs.push_back(Clone);
8680         DV->setIsInvalidated();
8681         DV->setIsEmitted();
8682         LLVM_DEBUG(dbgs() << "SALVAGE: Rewriting";
8683                    N0.getNode()->dumprFull(this);
8684                    dbgs() << " into " << *DIExpr << '\n');
8685       }
8686     }
8687   }
8688 
8689   for (SDDbgValue *Dbg : ClonedDVs) {
8690     assert(!Dbg->getSDNodes().empty() &&
8691            "Salvaged DbgValue should depend on a new SDNode");
8692     AddDbgValue(Dbg, false);
8693   }
8694 }
8695 
8696 /// Creates a SDDbgLabel node.
8697 SDDbgLabel *SelectionDAG::getDbgLabel(DILabel *Label,
8698                                       const DebugLoc &DL, unsigned O) {
8699   assert(cast<DILabel>(Label)->isValidLocationForIntrinsic(DL) &&
8700          "Expected inlined-at fields to agree");
8701   return new (DbgInfo->getAlloc()) SDDbgLabel(Label, DL, O);
8702 }
8703 
8704 namespace {
8705 
8706 /// RAUWUpdateListener - Helper for ReplaceAllUsesWith - When the node
8707 /// pointed to by a use iterator is deleted, increment the use iterator
8708 /// so that it doesn't dangle.
8709 ///
8710 class RAUWUpdateListener : public SelectionDAG::DAGUpdateListener {
8711   SDNode::use_iterator &UI;
8712   SDNode::use_iterator &UE;
8713 
8714   void NodeDeleted(SDNode *N, SDNode *E) override {
8715     // Increment the iterator as needed.
8716     while (UI != UE && N == *UI)
8717       ++UI;
8718   }
8719 
8720 public:
8721   RAUWUpdateListener(SelectionDAG &d,
8722                      SDNode::use_iterator &ui,
8723                      SDNode::use_iterator &ue)
8724     : SelectionDAG::DAGUpdateListener(d), UI(ui), UE(ue) {}
8725 };
8726 
8727 } // end anonymous namespace
8728 
8729 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
8730 /// This can cause recursive merging of nodes in the DAG.
8731 ///
8732 /// This version assumes From has a single result value.
8733 ///
8734 void SelectionDAG::ReplaceAllUsesWith(SDValue FromN, SDValue To) {
8735   SDNode *From = FromN.getNode();
8736   assert(From->getNumValues() == 1 && FromN.getResNo() == 0 &&
8737          "Cannot replace with this method!");
8738   assert(From != To.getNode() && "Cannot replace uses of with self");
8739 
8740   // Preserve Debug Values
8741   transferDbgValues(FromN, To);
8742 
8743   // Iterate over all the existing uses of From. New uses will be added
8744   // to the beginning of the use list, which we avoid visiting.
8745   // This specifically avoids visiting uses of From that arise while the
8746   // replacement is happening, because any such uses would be the result
8747   // of CSE: If an existing node looks like From after one of its operands
8748   // is replaced by To, we don't want to replace of all its users with To
8749   // too. See PR3018 for more info.
8750   SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
8751   RAUWUpdateListener Listener(*this, UI, UE);
8752   while (UI != UE) {
8753     SDNode *User = *UI;
8754 
8755     // This node is about to morph, remove its old self from the CSE maps.
8756     RemoveNodeFromCSEMaps(User);
8757 
8758     // A user can appear in a use list multiple times, and when this
8759     // happens the uses are usually next to each other in the list.
8760     // To help reduce the number of CSE recomputations, process all
8761     // the uses of this user that we can find this way.
8762     do {
8763       SDUse &Use = UI.getUse();
8764       ++UI;
8765       Use.set(To);
8766       if (To->isDivergent() != From->isDivergent())
8767         updateDivergence(User);
8768     } while (UI != UE && *UI == User);
8769     // Now that we have modified User, add it back to the CSE maps.  If it
8770     // already exists there, recursively merge the results together.
8771     AddModifiedNodeToCSEMaps(User);
8772   }
8773 
8774   // If we just RAUW'd the root, take note.
8775   if (FromN == getRoot())
8776     setRoot(To);
8777 }
8778 
8779 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
8780 /// This can cause recursive merging of nodes in the DAG.
8781 ///
8782 /// This version assumes that for each value of From, there is a
8783 /// corresponding value in To in the same position with the same type.
8784 ///
8785 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, SDNode *To) {
8786 #ifndef NDEBUG
8787   for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
8788     assert((!From->hasAnyUseOfValue(i) ||
8789             From->getValueType(i) == To->getValueType(i)) &&
8790            "Cannot use this version of ReplaceAllUsesWith!");
8791 #endif
8792 
8793   // Handle the trivial case.
8794   if (From == To)
8795     return;
8796 
8797   // Preserve Debug Info. Only do this if there's a use.
8798   for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
8799     if (From->hasAnyUseOfValue(i)) {
8800       assert((i < To->getNumValues()) && "Invalid To location");
8801       transferDbgValues(SDValue(From, i), SDValue(To, i));
8802     }
8803 
8804   // Iterate over just the existing users of From. See the comments in
8805   // the ReplaceAllUsesWith above.
8806   SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
8807   RAUWUpdateListener Listener(*this, UI, UE);
8808   while (UI != UE) {
8809     SDNode *User = *UI;
8810 
8811     // This node is about to morph, remove its old self from the CSE maps.
8812     RemoveNodeFromCSEMaps(User);
8813 
8814     // A user can appear in a use list multiple times, and when this
8815     // happens the uses are usually next to each other in the list.
8816     // To help reduce the number of CSE recomputations, process all
8817     // the uses of this user that we can find this way.
8818     do {
8819       SDUse &Use = UI.getUse();
8820       ++UI;
8821       Use.setNode(To);
8822       if (To->isDivergent() != From->isDivergent())
8823         updateDivergence(User);
8824     } while (UI != UE && *UI == User);
8825 
8826     // Now that we have modified User, add it back to the CSE maps.  If it
8827     // already exists there, recursively merge the results together.
8828     AddModifiedNodeToCSEMaps(User);
8829   }
8830 
8831   // If we just RAUW'd the root, take note.
8832   if (From == getRoot().getNode())
8833     setRoot(SDValue(To, getRoot().getResNo()));
8834 }
8835 
8836 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
8837 /// This can cause recursive merging of nodes in the DAG.
8838 ///
8839 /// This version can replace From with any result values.  To must match the
8840 /// number and types of values returned by From.
8841 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, const SDValue *To) {
8842   if (From->getNumValues() == 1)  // Handle the simple case efficiently.
8843     return ReplaceAllUsesWith(SDValue(From, 0), To[0]);
8844 
8845   // Preserve Debug Info.
8846   for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
8847     transferDbgValues(SDValue(From, i), To[i]);
8848 
8849   // Iterate over just the existing users of From. See the comments in
8850   // the ReplaceAllUsesWith above.
8851   SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
8852   RAUWUpdateListener Listener(*this, UI, UE);
8853   while (UI != UE) {
8854     SDNode *User = *UI;
8855 
8856     // This node is about to morph, remove its old self from the CSE maps.
8857     RemoveNodeFromCSEMaps(User);
8858 
8859     // A user can appear in a use list multiple times, and when this happens the
8860     // uses are usually next to each other in the list.  To help reduce the
8861     // number of CSE and divergence recomputations, process all the uses of this
8862     // user that we can find this way.
8863     bool To_IsDivergent = false;
8864     do {
8865       SDUse &Use = UI.getUse();
8866       const SDValue &ToOp = To[Use.getResNo()];
8867       ++UI;
8868       Use.set(ToOp);
8869       To_IsDivergent |= ToOp->isDivergent();
8870     } while (UI != UE && *UI == User);
8871 
8872     if (To_IsDivergent != From->isDivergent())
8873       updateDivergence(User);
8874 
8875     // Now that we have modified User, add it back to the CSE maps.  If it
8876     // already exists there, recursively merge the results together.
8877     AddModifiedNodeToCSEMaps(User);
8878   }
8879 
8880   // If we just RAUW'd the root, take note.
8881   if (From == getRoot().getNode())
8882     setRoot(SDValue(To[getRoot().getResNo()]));
8883 }
8884 
8885 /// ReplaceAllUsesOfValueWith - Replace any uses of From with To, leaving
8886 /// uses of other values produced by From.getNode() alone.  The Deleted
8887 /// vector is handled the same way as for ReplaceAllUsesWith.
8888 void SelectionDAG::ReplaceAllUsesOfValueWith(SDValue From, SDValue To){
8889   // Handle the really simple, really trivial case efficiently.
8890   if (From == To) return;
8891 
8892   // Handle the simple, trivial, case efficiently.
8893   if (From.getNode()->getNumValues() == 1) {
8894     ReplaceAllUsesWith(From, To);
8895     return;
8896   }
8897 
8898   // Preserve Debug Info.
8899   transferDbgValues(From, To);
8900 
8901   // Iterate over just the existing users of From. See the comments in
8902   // the ReplaceAllUsesWith above.
8903   SDNode::use_iterator UI = From.getNode()->use_begin(),
8904                        UE = From.getNode()->use_end();
8905   RAUWUpdateListener Listener(*this, UI, UE);
8906   while (UI != UE) {
8907     SDNode *User = *UI;
8908     bool UserRemovedFromCSEMaps = false;
8909 
8910     // A user can appear in a use list multiple times, and when this
8911     // happens the uses are usually next to each other in the list.
8912     // To help reduce the number of CSE recomputations, process all
8913     // the uses of this user that we can find this way.
8914     do {
8915       SDUse &Use = UI.getUse();
8916 
8917       // Skip uses of different values from the same node.
8918       if (Use.getResNo() != From.getResNo()) {
8919         ++UI;
8920         continue;
8921       }
8922 
8923       // If this node hasn't been modified yet, it's still in the CSE maps,
8924       // so remove its old self from the CSE maps.
8925       if (!UserRemovedFromCSEMaps) {
8926         RemoveNodeFromCSEMaps(User);
8927         UserRemovedFromCSEMaps = true;
8928       }
8929 
8930       ++UI;
8931       Use.set(To);
8932       if (To->isDivergent() != From->isDivergent())
8933         updateDivergence(User);
8934     } while (UI != UE && *UI == User);
8935     // We are iterating over all uses of the From node, so if a use
8936     // doesn't use the specific value, no changes are made.
8937     if (!UserRemovedFromCSEMaps)
8938       continue;
8939 
8940     // Now that we have modified User, add it back to the CSE maps.  If it
8941     // already exists there, recursively merge the results together.
8942     AddModifiedNodeToCSEMaps(User);
8943   }
8944 
8945   // If we just RAUW'd the root, take note.
8946   if (From == getRoot())
8947     setRoot(To);
8948 }
8949 
8950 namespace {
8951 
8952   /// UseMemo - This class is used by SelectionDAG::ReplaceAllUsesOfValuesWith
8953   /// to record information about a use.
8954   struct UseMemo {
8955     SDNode *User;
8956     unsigned Index;
8957     SDUse *Use;
8958   };
8959 
8960   /// operator< - Sort Memos by User.
8961   bool operator<(const UseMemo &L, const UseMemo &R) {
8962     return (intptr_t)L.User < (intptr_t)R.User;
8963   }
8964 
8965 } // end anonymous namespace
8966 
8967 bool SelectionDAG::calculateDivergence(SDNode *N) {
8968   if (TLI->isSDNodeAlwaysUniform(N)) {
8969     assert(!TLI->isSDNodeSourceOfDivergence(N, FLI, DA) &&
8970            "Conflicting divergence information!");
8971     return false;
8972   }
8973   if (TLI->isSDNodeSourceOfDivergence(N, FLI, DA))
8974     return true;
8975   for (auto &Op : N->ops()) {
8976     if (Op.Val.getValueType() != MVT::Other && Op.getNode()->isDivergent())
8977       return true;
8978   }
8979   return false;
8980 }
8981 
8982 void SelectionDAG::updateDivergence(SDNode *N) {
8983   SmallVector<SDNode *, 16> Worklist(1, N);
8984   do {
8985     N = Worklist.pop_back_val();
8986     bool IsDivergent = calculateDivergence(N);
8987     if (N->SDNodeBits.IsDivergent != IsDivergent) {
8988       N->SDNodeBits.IsDivergent = IsDivergent;
8989       llvm::append_range(Worklist, N->uses());
8990     }
8991   } while (!Worklist.empty());
8992 }
8993 
8994 void SelectionDAG::CreateTopologicalOrder(std::vector<SDNode *> &Order) {
8995   DenseMap<SDNode *, unsigned> Degree;
8996   Order.reserve(AllNodes.size());
8997   for (auto &N : allnodes()) {
8998     unsigned NOps = N.getNumOperands();
8999     Degree[&N] = NOps;
9000     if (0 == NOps)
9001       Order.push_back(&N);
9002   }
9003   for (size_t I = 0; I != Order.size(); ++I) {
9004     SDNode *N = Order[I];
9005     for (auto U : N->uses()) {
9006       unsigned &UnsortedOps = Degree[U];
9007       if (0 == --UnsortedOps)
9008         Order.push_back(U);
9009     }
9010   }
9011 }
9012 
9013 #ifndef NDEBUG
9014 void SelectionDAG::VerifyDAGDiverence() {
9015   std::vector<SDNode *> TopoOrder;
9016   CreateTopologicalOrder(TopoOrder);
9017   for (auto *N : TopoOrder) {
9018     assert(calculateDivergence(N) == N->isDivergent() &&
9019            "Divergence bit inconsistency detected");
9020   }
9021 }
9022 #endif
9023 
9024 /// ReplaceAllUsesOfValuesWith - Replace any uses of From with To, leaving
9025 /// uses of other values produced by From.getNode() alone.  The same value
9026 /// may appear in both the From and To list.  The Deleted vector is
9027 /// handled the same way as for ReplaceAllUsesWith.
9028 void SelectionDAG::ReplaceAllUsesOfValuesWith(const SDValue *From,
9029                                               const SDValue *To,
9030                                               unsigned Num){
9031   // Handle the simple, trivial case efficiently.
9032   if (Num == 1)
9033     return ReplaceAllUsesOfValueWith(*From, *To);
9034 
9035   transferDbgValues(*From, *To);
9036 
9037   // Read up all the uses and make records of them. This helps
9038   // processing new uses that are introduced during the
9039   // replacement process.
9040   SmallVector<UseMemo, 4> Uses;
9041   for (unsigned i = 0; i != Num; ++i) {
9042     unsigned FromResNo = From[i].getResNo();
9043     SDNode *FromNode = From[i].getNode();
9044     for (SDNode::use_iterator UI = FromNode->use_begin(),
9045          E = FromNode->use_end(); UI != E; ++UI) {
9046       SDUse &Use = UI.getUse();
9047       if (Use.getResNo() == FromResNo) {
9048         UseMemo Memo = { *UI, i, &Use };
9049         Uses.push_back(Memo);
9050       }
9051     }
9052   }
9053 
9054   // Sort the uses, so that all the uses from a given User are together.
9055   llvm::sort(Uses);
9056 
9057   for (unsigned UseIndex = 0, UseIndexEnd = Uses.size();
9058        UseIndex != UseIndexEnd; ) {
9059     // We know that this user uses some value of From.  If it is the right
9060     // value, update it.
9061     SDNode *User = Uses[UseIndex].User;
9062 
9063     // This node is about to morph, remove its old self from the CSE maps.
9064     RemoveNodeFromCSEMaps(User);
9065 
9066     // The Uses array is sorted, so all the uses for a given User
9067     // are next to each other in the list.
9068     // To help reduce the number of CSE recomputations, process all
9069     // the uses of this user that we can find this way.
9070     do {
9071       unsigned i = Uses[UseIndex].Index;
9072       SDUse &Use = *Uses[UseIndex].Use;
9073       ++UseIndex;
9074 
9075       Use.set(To[i]);
9076     } while (UseIndex != UseIndexEnd && Uses[UseIndex].User == User);
9077 
9078     // Now that we have modified User, add it back to the CSE maps.  If it
9079     // already exists there, recursively merge the results together.
9080     AddModifiedNodeToCSEMaps(User);
9081   }
9082 }
9083 
9084 /// AssignTopologicalOrder - Assign a unique node id for each node in the DAG
9085 /// based on their topological order. It returns the maximum id and a vector
9086 /// of the SDNodes* in assigned order by reference.
9087 unsigned SelectionDAG::AssignTopologicalOrder() {
9088   unsigned DAGSize = 0;
9089 
9090   // SortedPos tracks the progress of the algorithm. Nodes before it are
9091   // sorted, nodes after it are unsorted. When the algorithm completes
9092   // it is at the end of the list.
9093   allnodes_iterator SortedPos = allnodes_begin();
9094 
9095   // Visit all the nodes. Move nodes with no operands to the front of
9096   // the list immediately. Annotate nodes that do have operands with their
9097   // operand count. Before we do this, the Node Id fields of the nodes
9098   // may contain arbitrary values. After, the Node Id fields for nodes
9099   // before SortedPos will contain the topological sort index, and the
9100   // Node Id fields for nodes At SortedPos and after will contain the
9101   // count of outstanding operands.
9102   for (allnodes_iterator I = allnodes_begin(),E = allnodes_end(); I != E; ) {
9103     SDNode *N = &*I++;
9104     checkForCycles(N, this);
9105     unsigned Degree = N->getNumOperands();
9106     if (Degree == 0) {
9107       // A node with no uses, add it to the result array immediately.
9108       N->setNodeId(DAGSize++);
9109       allnodes_iterator Q(N);
9110       if (Q != SortedPos)
9111         SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(Q));
9112       assert(SortedPos != AllNodes.end() && "Overran node list");
9113       ++SortedPos;
9114     } else {
9115       // Temporarily use the Node Id as scratch space for the degree count.
9116       N->setNodeId(Degree);
9117     }
9118   }
9119 
9120   // Visit all the nodes. As we iterate, move nodes into sorted order,
9121   // such that by the time the end is reached all nodes will be sorted.
9122   for (SDNode &Node : allnodes()) {
9123     SDNode *N = &Node;
9124     checkForCycles(N, this);
9125     // N is in sorted position, so all its uses have one less operand
9126     // that needs to be sorted.
9127     for (SDNode *P : N->uses()) {
9128       unsigned Degree = P->getNodeId();
9129       assert(Degree != 0 && "Invalid node degree");
9130       --Degree;
9131       if (Degree == 0) {
9132         // All of P's operands are sorted, so P may sorted now.
9133         P->setNodeId(DAGSize++);
9134         if (P->getIterator() != SortedPos)
9135           SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(P));
9136         assert(SortedPos != AllNodes.end() && "Overran node list");
9137         ++SortedPos;
9138       } else {
9139         // Update P's outstanding operand count.
9140         P->setNodeId(Degree);
9141       }
9142     }
9143     if (Node.getIterator() == SortedPos) {
9144 #ifndef NDEBUG
9145       allnodes_iterator I(N);
9146       SDNode *S = &*++I;
9147       dbgs() << "Overran sorted position:\n";
9148       S->dumprFull(this); dbgs() << "\n";
9149       dbgs() << "Checking if this is due to cycles\n";
9150       checkForCycles(this, true);
9151 #endif
9152       llvm_unreachable(nullptr);
9153     }
9154   }
9155 
9156   assert(SortedPos == AllNodes.end() &&
9157          "Topological sort incomplete!");
9158   assert(AllNodes.front().getOpcode() == ISD::EntryToken &&
9159          "First node in topological sort is not the entry token!");
9160   assert(AllNodes.front().getNodeId() == 0 &&
9161          "First node in topological sort has non-zero id!");
9162   assert(AllNodes.front().getNumOperands() == 0 &&
9163          "First node in topological sort has operands!");
9164   assert(AllNodes.back().getNodeId() == (int)DAGSize-1 &&
9165          "Last node in topologic sort has unexpected id!");
9166   assert(AllNodes.back().use_empty() &&
9167          "Last node in topologic sort has users!");
9168   assert(DAGSize == allnodes_size() && "Node count mismatch!");
9169   return DAGSize;
9170 }
9171 
9172 /// AddDbgValue - Add a dbg_value SDNode. If SD is non-null that means the
9173 /// value is produced by SD.
9174 void SelectionDAG::AddDbgValue(SDDbgValue *DB, bool isParameter) {
9175   for (SDNode *SD : DB->getSDNodes()) {
9176     if (!SD)
9177       continue;
9178     assert(DbgInfo->getSDDbgValues(SD).empty() || SD->getHasDebugValue());
9179     SD->setHasDebugValue(true);
9180   }
9181   DbgInfo->add(DB, isParameter);
9182 }
9183 
9184 void SelectionDAG::AddDbgLabel(SDDbgLabel *DB) { DbgInfo->add(DB); }
9185 
9186 SDValue SelectionDAG::makeEquivalentMemoryOrdering(SDValue OldChain,
9187                                                    SDValue NewMemOpChain) {
9188   assert(isa<MemSDNode>(NewMemOpChain) && "Expected a memop node");
9189   assert(NewMemOpChain.getValueType() == MVT::Other && "Expected a token VT");
9190   // The new memory operation must have the same position as the old load in
9191   // terms of memory dependency. Create a TokenFactor for the old load and new
9192   // memory operation and update uses of the old load's output chain to use that
9193   // TokenFactor.
9194   if (OldChain == NewMemOpChain || OldChain.use_empty())
9195     return NewMemOpChain;
9196 
9197   SDValue TokenFactor = getNode(ISD::TokenFactor, SDLoc(OldChain), MVT::Other,
9198                                 OldChain, NewMemOpChain);
9199   ReplaceAllUsesOfValueWith(OldChain, TokenFactor);
9200   UpdateNodeOperands(TokenFactor.getNode(), OldChain, NewMemOpChain);
9201   return TokenFactor;
9202 }
9203 
9204 SDValue SelectionDAG::makeEquivalentMemoryOrdering(LoadSDNode *OldLoad,
9205                                                    SDValue NewMemOp) {
9206   assert(isa<MemSDNode>(NewMemOp.getNode()) && "Expected a memop node");
9207   SDValue OldChain = SDValue(OldLoad, 1);
9208   SDValue NewMemOpChain = NewMemOp.getValue(1);
9209   return makeEquivalentMemoryOrdering(OldChain, NewMemOpChain);
9210 }
9211 
9212 SDValue SelectionDAG::getSymbolFunctionGlobalAddress(SDValue Op,
9213                                                      Function **OutFunction) {
9214   assert(isa<ExternalSymbolSDNode>(Op) && "Node should be an ExternalSymbol");
9215 
9216   auto *Symbol = cast<ExternalSymbolSDNode>(Op)->getSymbol();
9217   auto *Module = MF->getFunction().getParent();
9218   auto *Function = Module->getFunction(Symbol);
9219 
9220   if (OutFunction != nullptr)
9221       *OutFunction = Function;
9222 
9223   if (Function != nullptr) {
9224     auto PtrTy = TLI->getPointerTy(getDataLayout(), Function->getAddressSpace());
9225     return getGlobalAddress(Function, SDLoc(Op), PtrTy);
9226   }
9227 
9228   std::string ErrorStr;
9229   raw_string_ostream ErrorFormatter(ErrorStr);
9230 
9231   ErrorFormatter << "Undefined external symbol ";
9232   ErrorFormatter << '"' << Symbol << '"';
9233   ErrorFormatter.flush();
9234 
9235   report_fatal_error(ErrorStr);
9236 }
9237 
9238 //===----------------------------------------------------------------------===//
9239 //                              SDNode Class
9240 //===----------------------------------------------------------------------===//
9241 
9242 bool llvm::isNullConstant(SDValue V) {
9243   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
9244   return Const != nullptr && Const->isNullValue();
9245 }
9246 
9247 bool llvm::isNullFPConstant(SDValue V) {
9248   ConstantFPSDNode *Const = dyn_cast<ConstantFPSDNode>(V);
9249   return Const != nullptr && Const->isZero() && !Const->isNegative();
9250 }
9251 
9252 bool llvm::isAllOnesConstant(SDValue V) {
9253   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
9254   return Const != nullptr && Const->isAllOnesValue();
9255 }
9256 
9257 bool llvm::isOneConstant(SDValue V) {
9258   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
9259   return Const != nullptr && Const->isOne();
9260 }
9261 
9262 SDValue llvm::peekThroughBitcasts(SDValue V) {
9263   while (V.getOpcode() == ISD::BITCAST)
9264     V = V.getOperand(0);
9265   return V;
9266 }
9267 
9268 SDValue llvm::peekThroughOneUseBitcasts(SDValue V) {
9269   while (V.getOpcode() == ISD::BITCAST && V.getOperand(0).hasOneUse())
9270     V = V.getOperand(0);
9271   return V;
9272 }
9273 
9274 SDValue llvm::peekThroughExtractSubvectors(SDValue V) {
9275   while (V.getOpcode() == ISD::EXTRACT_SUBVECTOR)
9276     V = V.getOperand(0);
9277   return V;
9278 }
9279 
9280 bool llvm::isBitwiseNot(SDValue V, bool AllowUndefs) {
9281   if (V.getOpcode() != ISD::XOR)
9282     return false;
9283   V = peekThroughBitcasts(V.getOperand(1));
9284   unsigned NumBits = V.getScalarValueSizeInBits();
9285   ConstantSDNode *C =
9286       isConstOrConstSplat(V, AllowUndefs, /*AllowTruncation*/ true);
9287   return C && (C->getAPIntValue().countTrailingOnes() >= NumBits);
9288 }
9289 
9290 ConstantSDNode *llvm::isConstOrConstSplat(SDValue N, bool AllowUndefs,
9291                                           bool AllowTruncation) {
9292   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
9293     return CN;
9294 
9295   // SplatVectors can truncate their operands. Ignore that case here unless
9296   // AllowTruncation is set.
9297   if (N->getOpcode() == ISD::SPLAT_VECTOR) {
9298     EVT VecEltVT = N->getValueType(0).getVectorElementType();
9299     if (auto *CN = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
9300       EVT CVT = CN->getValueType(0);
9301       assert(CVT.bitsGE(VecEltVT) && "Illegal splat_vector element extension");
9302       if (AllowTruncation || CVT == VecEltVT)
9303         return CN;
9304     }
9305   }
9306 
9307   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
9308     BitVector UndefElements;
9309     ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
9310 
9311     // BuildVectors can truncate their operands. Ignore that case here unless
9312     // AllowTruncation is set.
9313     if (CN && (UndefElements.none() || AllowUndefs)) {
9314       EVT CVT = CN->getValueType(0);
9315       EVT NSVT = N.getValueType().getScalarType();
9316       assert(CVT.bitsGE(NSVT) && "Illegal build vector element extension");
9317       if (AllowTruncation || (CVT == NSVT))
9318         return CN;
9319     }
9320   }
9321 
9322   return nullptr;
9323 }
9324 
9325 ConstantSDNode *llvm::isConstOrConstSplat(SDValue N, const APInt &DemandedElts,
9326                                           bool AllowUndefs,
9327                                           bool AllowTruncation) {
9328   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
9329     return CN;
9330 
9331   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
9332     BitVector UndefElements;
9333     ConstantSDNode *CN = BV->getConstantSplatNode(DemandedElts, &UndefElements);
9334 
9335     // BuildVectors can truncate their operands. Ignore that case here unless
9336     // AllowTruncation is set.
9337     if (CN && (UndefElements.none() || AllowUndefs)) {
9338       EVT CVT = CN->getValueType(0);
9339       EVT NSVT = N.getValueType().getScalarType();
9340       assert(CVT.bitsGE(NSVT) && "Illegal build vector element extension");
9341       if (AllowTruncation || (CVT == NSVT))
9342         return CN;
9343     }
9344   }
9345 
9346   return nullptr;
9347 }
9348 
9349 ConstantFPSDNode *llvm::isConstOrConstSplatFP(SDValue N, bool AllowUndefs) {
9350   if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
9351     return CN;
9352 
9353   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
9354     BitVector UndefElements;
9355     ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements);
9356     if (CN && (UndefElements.none() || AllowUndefs))
9357       return CN;
9358   }
9359 
9360   if (N.getOpcode() == ISD::SPLAT_VECTOR)
9361     if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N.getOperand(0)))
9362       return CN;
9363 
9364   return nullptr;
9365 }
9366 
9367 ConstantFPSDNode *llvm::isConstOrConstSplatFP(SDValue N,
9368                                               const APInt &DemandedElts,
9369                                               bool AllowUndefs) {
9370   if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
9371     return CN;
9372 
9373   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
9374     BitVector UndefElements;
9375     ConstantFPSDNode *CN =
9376         BV->getConstantFPSplatNode(DemandedElts, &UndefElements);
9377     if (CN && (UndefElements.none() || AllowUndefs))
9378       return CN;
9379   }
9380 
9381   return nullptr;
9382 }
9383 
9384 bool llvm::isNullOrNullSplat(SDValue N, bool AllowUndefs) {
9385   // TODO: may want to use peekThroughBitcast() here.
9386   ConstantSDNode *C = isConstOrConstSplat(N, AllowUndefs);
9387   return C && C->isNullValue();
9388 }
9389 
9390 bool llvm::isOneOrOneSplat(SDValue N, bool AllowUndefs) {
9391   // TODO: may want to use peekThroughBitcast() here.
9392   unsigned BitWidth = N.getScalarValueSizeInBits();
9393   ConstantSDNode *C = isConstOrConstSplat(N, AllowUndefs);
9394   return C && C->isOne() && C->getValueSizeInBits(0) == BitWidth;
9395 }
9396 
9397 bool llvm::isAllOnesOrAllOnesSplat(SDValue N, bool AllowUndefs) {
9398   N = peekThroughBitcasts(N);
9399   unsigned BitWidth = N.getScalarValueSizeInBits();
9400   ConstantSDNode *C = isConstOrConstSplat(N, AllowUndefs);
9401   return C && C->isAllOnesValue() && C->getValueSizeInBits(0) == BitWidth;
9402 }
9403 
9404 HandleSDNode::~HandleSDNode() {
9405   DropOperands();
9406 }
9407 
9408 GlobalAddressSDNode::GlobalAddressSDNode(unsigned Opc, unsigned Order,
9409                                          const DebugLoc &DL,
9410                                          const GlobalValue *GA, EVT VT,
9411                                          int64_t o, unsigned TF)
9412     : SDNode(Opc, Order, DL, getSDVTList(VT)), Offset(o), TargetFlags(TF) {
9413   TheGlobal = GA;
9414 }
9415 
9416 AddrSpaceCastSDNode::AddrSpaceCastSDNode(unsigned Order, const DebugLoc &dl,
9417                                          EVT VT, unsigned SrcAS,
9418                                          unsigned DestAS)
9419     : SDNode(ISD::ADDRSPACECAST, Order, dl, getSDVTList(VT)),
9420       SrcAddrSpace(SrcAS), DestAddrSpace(DestAS) {}
9421 
9422 MemSDNode::MemSDNode(unsigned Opc, unsigned Order, const DebugLoc &dl,
9423                      SDVTList VTs, EVT memvt, MachineMemOperand *mmo)
9424     : SDNode(Opc, Order, dl, VTs), MemoryVT(memvt), MMO(mmo) {
9425   MemSDNodeBits.IsVolatile = MMO->isVolatile();
9426   MemSDNodeBits.IsNonTemporal = MMO->isNonTemporal();
9427   MemSDNodeBits.IsDereferenceable = MMO->isDereferenceable();
9428   MemSDNodeBits.IsInvariant = MMO->isInvariant();
9429 
9430   // We check here that the size of the memory operand fits within the size of
9431   // the MMO. This is because the MMO might indicate only a possible address
9432   // range instead of specifying the affected memory addresses precisely.
9433   // TODO: Make MachineMemOperands aware of scalable vectors.
9434   assert(memvt.getStoreSize().getKnownMinSize() <= MMO->getSize() &&
9435          "Size mismatch!");
9436 }
9437 
9438 /// Profile - Gather unique data for the node.
9439 ///
9440 void SDNode::Profile(FoldingSetNodeID &ID) const {
9441   AddNodeIDNode(ID, this);
9442 }
9443 
9444 namespace {
9445 
9446   struct EVTArray {
9447     std::vector<EVT> VTs;
9448 
9449     EVTArray() {
9450       VTs.reserve(MVT::LAST_VALUETYPE);
9451       for (unsigned i = 0; i < MVT::LAST_VALUETYPE; ++i)
9452         VTs.push_back(MVT((MVT::SimpleValueType)i));
9453     }
9454   };
9455 
9456 } // end anonymous namespace
9457 
9458 static ManagedStatic<std::set<EVT, EVT::compareRawBits>> EVTs;
9459 static ManagedStatic<EVTArray> SimpleVTArray;
9460 static ManagedStatic<sys::SmartMutex<true>> VTMutex;
9461 
9462 /// getValueTypeList - Return a pointer to the specified value type.
9463 ///
9464 const EVT *SDNode::getValueTypeList(EVT VT) {
9465   if (VT.isExtended()) {
9466     sys::SmartScopedLock<true> Lock(*VTMutex);
9467     return &(*EVTs->insert(VT).first);
9468   } else {
9469     assert(VT.getSimpleVT() < MVT::LAST_VALUETYPE &&
9470            "Value type out of range!");
9471     return &SimpleVTArray->VTs[VT.getSimpleVT().SimpleTy];
9472   }
9473 }
9474 
9475 /// hasNUsesOfValue - Return true if there are exactly NUSES uses of the
9476 /// indicated value.  This method ignores uses of other values defined by this
9477 /// operation.
9478 bool SDNode::hasNUsesOfValue(unsigned NUses, unsigned Value) const {
9479   assert(Value < getNumValues() && "Bad value!");
9480 
9481   // TODO: Only iterate over uses of a given value of the node
9482   for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) {
9483     if (UI.getUse().getResNo() == Value) {
9484       if (NUses == 0)
9485         return false;
9486       --NUses;
9487     }
9488   }
9489 
9490   // Found exactly the right number of uses?
9491   return NUses == 0;
9492 }
9493 
9494 /// hasAnyUseOfValue - Return true if there are any use of the indicated
9495 /// value. This method ignores uses of other values defined by this operation.
9496 bool SDNode::hasAnyUseOfValue(unsigned Value) const {
9497   assert(Value < getNumValues() && "Bad value!");
9498 
9499   for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI)
9500     if (UI.getUse().getResNo() == Value)
9501       return true;
9502 
9503   return false;
9504 }
9505 
9506 /// isOnlyUserOf - Return true if this node is the only use of N.
9507 bool SDNode::isOnlyUserOf(const SDNode *N) const {
9508   bool Seen = false;
9509   for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) {
9510     SDNode *User = *I;
9511     if (User == this)
9512       Seen = true;
9513     else
9514       return false;
9515   }
9516 
9517   return Seen;
9518 }
9519 
9520 /// Return true if the only users of N are contained in Nodes.
9521 bool SDNode::areOnlyUsersOf(ArrayRef<const SDNode *> Nodes, const SDNode *N) {
9522   bool Seen = false;
9523   for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) {
9524     SDNode *User = *I;
9525     if (llvm::is_contained(Nodes, User))
9526       Seen = true;
9527     else
9528       return false;
9529   }
9530 
9531   return Seen;
9532 }
9533 
9534 /// isOperand - Return true if this node is an operand of N.
9535 bool SDValue::isOperandOf(const SDNode *N) const {
9536   return is_contained(N->op_values(), *this);
9537 }
9538 
9539 bool SDNode::isOperandOf(const SDNode *N) const {
9540   return any_of(N->op_values(),
9541                 [this](SDValue Op) { return this == Op.getNode(); });
9542 }
9543 
9544 /// reachesChainWithoutSideEffects - Return true if this operand (which must
9545 /// be a chain) reaches the specified operand without crossing any
9546 /// side-effecting instructions on any chain path.  In practice, this looks
9547 /// through token factors and non-volatile loads.  In order to remain efficient,
9548 /// this only looks a couple of nodes in, it does not do an exhaustive search.
9549 ///
9550 /// Note that we only need to examine chains when we're searching for
9551 /// side-effects; SelectionDAG requires that all side-effects are represented
9552 /// by chains, even if another operand would force a specific ordering. This
9553 /// constraint is necessary to allow transformations like splitting loads.
9554 bool SDValue::reachesChainWithoutSideEffects(SDValue Dest,
9555                                              unsigned Depth) const {
9556   if (*this == Dest) return true;
9557 
9558   // Don't search too deeply, we just want to be able to see through
9559   // TokenFactor's etc.
9560   if (Depth == 0) return false;
9561 
9562   // If this is a token factor, all inputs to the TF happen in parallel.
9563   if (getOpcode() == ISD::TokenFactor) {
9564     // First, try a shallow search.
9565     if (is_contained((*this)->ops(), Dest)) {
9566       // We found the chain we want as an operand of this TokenFactor.
9567       // Essentially, we reach the chain without side-effects if we could
9568       // serialize the TokenFactor into a simple chain of operations with
9569       // Dest as the last operation. This is automatically true if the
9570       // chain has one use: there are no other ordering constraints.
9571       // If the chain has more than one use, we give up: some other
9572       // use of Dest might force a side-effect between Dest and the current
9573       // node.
9574       if (Dest.hasOneUse())
9575         return true;
9576     }
9577     // Next, try a deep search: check whether every operand of the TokenFactor
9578     // reaches Dest.
9579     return llvm::all_of((*this)->ops(), [=](SDValue Op) {
9580       return Op.reachesChainWithoutSideEffects(Dest, Depth - 1);
9581     });
9582   }
9583 
9584   // Loads don't have side effects, look through them.
9585   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(*this)) {
9586     if (Ld->isUnordered())
9587       return Ld->getChain().reachesChainWithoutSideEffects(Dest, Depth-1);
9588   }
9589   return false;
9590 }
9591 
9592 bool SDNode::hasPredecessor(const SDNode *N) const {
9593   SmallPtrSet<const SDNode *, 32> Visited;
9594   SmallVector<const SDNode *, 16> Worklist;
9595   Worklist.push_back(this);
9596   return hasPredecessorHelper(N, Visited, Worklist);
9597 }
9598 
9599 void SDNode::intersectFlagsWith(const SDNodeFlags Flags) {
9600   this->Flags.intersectWith(Flags);
9601 }
9602 
9603 SDValue
9604 SelectionDAG::matchBinOpReduction(SDNode *Extract, ISD::NodeType &BinOp,
9605                                   ArrayRef<ISD::NodeType> CandidateBinOps,
9606                                   bool AllowPartials) {
9607   // The pattern must end in an extract from index 0.
9608   if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
9609       !isNullConstant(Extract->getOperand(1)))
9610     return SDValue();
9611 
9612   // Match against one of the candidate binary ops.
9613   SDValue Op = Extract->getOperand(0);
9614   if (llvm::none_of(CandidateBinOps, [Op](ISD::NodeType BinOp) {
9615         return Op.getOpcode() == unsigned(BinOp);
9616       }))
9617     return SDValue();
9618 
9619   // Floating-point reductions may require relaxed constraints on the final step
9620   // of the reduction because they may reorder intermediate operations.
9621   unsigned CandidateBinOp = Op.getOpcode();
9622   if (Op.getValueType().isFloatingPoint()) {
9623     SDNodeFlags Flags = Op->getFlags();
9624     switch (CandidateBinOp) {
9625     case ISD::FADD:
9626       if (!Flags.hasNoSignedZeros() || !Flags.hasAllowReassociation())
9627         return SDValue();
9628       break;
9629     default:
9630       llvm_unreachable("Unhandled FP opcode for binop reduction");
9631     }
9632   }
9633 
9634   // Matching failed - attempt to see if we did enough stages that a partial
9635   // reduction from a subvector is possible.
9636   auto PartialReduction = [&](SDValue Op, unsigned NumSubElts) {
9637     if (!AllowPartials || !Op)
9638       return SDValue();
9639     EVT OpVT = Op.getValueType();
9640     EVT OpSVT = OpVT.getScalarType();
9641     EVT SubVT = EVT::getVectorVT(*getContext(), OpSVT, NumSubElts);
9642     if (!TLI->isExtractSubvectorCheap(SubVT, OpVT, 0))
9643       return SDValue();
9644     BinOp = (ISD::NodeType)CandidateBinOp;
9645     return getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(Op), SubVT, Op,
9646                    getVectorIdxConstant(0, SDLoc(Op)));
9647   };
9648 
9649   // At each stage, we're looking for something that looks like:
9650   // %s = shufflevector <8 x i32> %op, <8 x i32> undef,
9651   //                    <8 x i32> <i32 2, i32 3, i32 undef, i32 undef,
9652   //                               i32 undef, i32 undef, i32 undef, i32 undef>
9653   // %a = binop <8 x i32> %op, %s
9654   // Where the mask changes according to the stage. E.g. for a 3-stage pyramid,
9655   // we expect something like:
9656   // <4,5,6,7,u,u,u,u>
9657   // <2,3,u,u,u,u,u,u>
9658   // <1,u,u,u,u,u,u,u>
9659   // While a partial reduction match would be:
9660   // <2,3,u,u,u,u,u,u>
9661   // <1,u,u,u,u,u,u,u>
9662   unsigned Stages = Log2_32(Op.getValueType().getVectorNumElements());
9663   SDValue PrevOp;
9664   for (unsigned i = 0; i < Stages; ++i) {
9665     unsigned MaskEnd = (1 << i);
9666 
9667     if (Op.getOpcode() != CandidateBinOp)
9668       return PartialReduction(PrevOp, MaskEnd);
9669 
9670     SDValue Op0 = Op.getOperand(0);
9671     SDValue Op1 = Op.getOperand(1);
9672 
9673     ShuffleVectorSDNode *Shuffle = dyn_cast<ShuffleVectorSDNode>(Op0);
9674     if (Shuffle) {
9675       Op = Op1;
9676     } else {
9677       Shuffle = dyn_cast<ShuffleVectorSDNode>(Op1);
9678       Op = Op0;
9679     }
9680 
9681     // The first operand of the shuffle should be the same as the other operand
9682     // of the binop.
9683     if (!Shuffle || Shuffle->getOperand(0) != Op)
9684       return PartialReduction(PrevOp, MaskEnd);
9685 
9686     // Verify the shuffle has the expected (at this stage of the pyramid) mask.
9687     for (int Index = 0; Index < (int)MaskEnd; ++Index)
9688       if (Shuffle->getMaskElt(Index) != (int)(MaskEnd + Index))
9689         return PartialReduction(PrevOp, MaskEnd);
9690 
9691     PrevOp = Op;
9692   }
9693 
9694   // Handle subvector reductions, which tend to appear after the shuffle
9695   // reduction stages.
9696   while (Op.getOpcode() == CandidateBinOp) {
9697     unsigned NumElts = Op.getValueType().getVectorNumElements();
9698     SDValue Op0 = Op.getOperand(0);
9699     SDValue Op1 = Op.getOperand(1);
9700     if (Op0.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
9701         Op1.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
9702         Op0.getOperand(0) != Op1.getOperand(0))
9703       break;
9704     SDValue Src = Op0.getOperand(0);
9705     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
9706     if (NumSrcElts != (2 * NumElts))
9707       break;
9708     if (!(Op0.getConstantOperandAPInt(1) == 0 &&
9709           Op1.getConstantOperandAPInt(1) == NumElts) &&
9710         !(Op1.getConstantOperandAPInt(1) == 0 &&
9711           Op0.getConstantOperandAPInt(1) == NumElts))
9712       break;
9713     Op = Src;
9714   }
9715 
9716   BinOp = (ISD::NodeType)CandidateBinOp;
9717   return Op;
9718 }
9719 
9720 SDValue SelectionDAG::UnrollVectorOp(SDNode *N, unsigned ResNE) {
9721   assert(N->getNumValues() == 1 &&
9722          "Can't unroll a vector with multiple results!");
9723 
9724   EVT VT = N->getValueType(0);
9725   unsigned NE = VT.getVectorNumElements();
9726   EVT EltVT = VT.getVectorElementType();
9727   SDLoc dl(N);
9728 
9729   SmallVector<SDValue, 8> Scalars;
9730   SmallVector<SDValue, 4> Operands(N->getNumOperands());
9731 
9732   // If ResNE is 0, fully unroll the vector op.
9733   if (ResNE == 0)
9734     ResNE = NE;
9735   else if (NE > ResNE)
9736     NE = ResNE;
9737 
9738   unsigned i;
9739   for (i= 0; i != NE; ++i) {
9740     for (unsigned j = 0, e = N->getNumOperands(); j != e; ++j) {
9741       SDValue Operand = N->getOperand(j);
9742       EVT OperandVT = Operand.getValueType();
9743       if (OperandVT.isVector()) {
9744         // A vector operand; extract a single element.
9745         EVT OperandEltVT = OperandVT.getVectorElementType();
9746         Operands[j] = getNode(ISD::EXTRACT_VECTOR_ELT, dl, OperandEltVT,
9747                               Operand, getVectorIdxConstant(i, dl));
9748       } else {
9749         // A scalar operand; just use it as is.
9750         Operands[j] = Operand;
9751       }
9752     }
9753 
9754     switch (N->getOpcode()) {
9755     default: {
9756       Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands,
9757                                 N->getFlags()));
9758       break;
9759     }
9760     case ISD::VSELECT:
9761       Scalars.push_back(getNode(ISD::SELECT, dl, EltVT, Operands));
9762       break;
9763     case ISD::SHL:
9764     case ISD::SRA:
9765     case ISD::SRL:
9766     case ISD::ROTL:
9767     case ISD::ROTR:
9768       Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands[0],
9769                                getShiftAmountOperand(Operands[0].getValueType(),
9770                                                      Operands[1])));
9771       break;
9772     case ISD::SIGN_EXTEND_INREG: {
9773       EVT ExtVT = cast<VTSDNode>(Operands[1])->getVT().getVectorElementType();
9774       Scalars.push_back(getNode(N->getOpcode(), dl, EltVT,
9775                                 Operands[0],
9776                                 getValueType(ExtVT)));
9777     }
9778     }
9779   }
9780 
9781   for (; i < ResNE; ++i)
9782     Scalars.push_back(getUNDEF(EltVT));
9783 
9784   EVT VecVT = EVT::getVectorVT(*getContext(), EltVT, ResNE);
9785   return getBuildVector(VecVT, dl, Scalars);
9786 }
9787 
9788 std::pair<SDValue, SDValue> SelectionDAG::UnrollVectorOverflowOp(
9789     SDNode *N, unsigned ResNE) {
9790   unsigned Opcode = N->getOpcode();
9791   assert((Opcode == ISD::UADDO || Opcode == ISD::SADDO ||
9792           Opcode == ISD::USUBO || Opcode == ISD::SSUBO ||
9793           Opcode == ISD::UMULO || Opcode == ISD::SMULO) &&
9794          "Expected an overflow opcode");
9795 
9796   EVT ResVT = N->getValueType(0);
9797   EVT OvVT = N->getValueType(1);
9798   EVT ResEltVT = ResVT.getVectorElementType();
9799   EVT OvEltVT = OvVT.getVectorElementType();
9800   SDLoc dl(N);
9801 
9802   // If ResNE is 0, fully unroll the vector op.
9803   unsigned NE = ResVT.getVectorNumElements();
9804   if (ResNE == 0)
9805     ResNE = NE;
9806   else if (NE > ResNE)
9807     NE = ResNE;
9808 
9809   SmallVector<SDValue, 8> LHSScalars;
9810   SmallVector<SDValue, 8> RHSScalars;
9811   ExtractVectorElements(N->getOperand(0), LHSScalars, 0, NE);
9812   ExtractVectorElements(N->getOperand(1), RHSScalars, 0, NE);
9813 
9814   EVT SVT = TLI->getSetCCResultType(getDataLayout(), *getContext(), ResEltVT);
9815   SDVTList VTs = getVTList(ResEltVT, SVT);
9816   SmallVector<SDValue, 8> ResScalars;
9817   SmallVector<SDValue, 8> OvScalars;
9818   for (unsigned i = 0; i < NE; ++i) {
9819     SDValue Res = getNode(Opcode, dl, VTs, LHSScalars[i], RHSScalars[i]);
9820     SDValue Ov =
9821         getSelect(dl, OvEltVT, Res.getValue(1),
9822                   getBoolConstant(true, dl, OvEltVT, ResVT),
9823                   getConstant(0, dl, OvEltVT));
9824 
9825     ResScalars.push_back(Res);
9826     OvScalars.push_back(Ov);
9827   }
9828 
9829   ResScalars.append(ResNE - NE, getUNDEF(ResEltVT));
9830   OvScalars.append(ResNE - NE, getUNDEF(OvEltVT));
9831 
9832   EVT NewResVT = EVT::getVectorVT(*getContext(), ResEltVT, ResNE);
9833   EVT NewOvVT = EVT::getVectorVT(*getContext(), OvEltVT, ResNE);
9834   return std::make_pair(getBuildVector(NewResVT, dl, ResScalars),
9835                         getBuildVector(NewOvVT, dl, OvScalars));
9836 }
9837 
9838 bool SelectionDAG::areNonVolatileConsecutiveLoads(LoadSDNode *LD,
9839                                                   LoadSDNode *Base,
9840                                                   unsigned Bytes,
9841                                                   int Dist) const {
9842   if (LD->isVolatile() || Base->isVolatile())
9843     return false;
9844   // TODO: probably too restrictive for atomics, revisit
9845   if (!LD->isSimple())
9846     return false;
9847   if (LD->isIndexed() || Base->isIndexed())
9848     return false;
9849   if (LD->getChain() != Base->getChain())
9850     return false;
9851   EVT VT = LD->getValueType(0);
9852   if (VT.getSizeInBits() / 8 != Bytes)
9853     return false;
9854 
9855   auto BaseLocDecomp = BaseIndexOffset::match(Base, *this);
9856   auto LocDecomp = BaseIndexOffset::match(LD, *this);
9857 
9858   int64_t Offset = 0;
9859   if (BaseLocDecomp.equalBaseIndex(LocDecomp, *this, Offset))
9860     return (Dist * Bytes == Offset);
9861   return false;
9862 }
9863 
9864 /// InferPtrAlignment - Infer alignment of a load / store address. Return None
9865 /// if it cannot be inferred.
9866 MaybeAlign SelectionDAG::InferPtrAlign(SDValue Ptr) const {
9867   // If this is a GlobalAddress + cst, return the alignment.
9868   const GlobalValue *GV = nullptr;
9869   int64_t GVOffset = 0;
9870   if (TLI->isGAPlusOffset(Ptr.getNode(), GV, GVOffset)) {
9871     unsigned PtrWidth = getDataLayout().getPointerTypeSizeInBits(GV->getType());
9872     KnownBits Known(PtrWidth);
9873     llvm::computeKnownBits(GV, Known, getDataLayout());
9874     unsigned AlignBits = Known.countMinTrailingZeros();
9875     if (AlignBits)
9876       return commonAlignment(Align(1ull << std::min(31U, AlignBits)), GVOffset);
9877   }
9878 
9879   // If this is a direct reference to a stack slot, use information about the
9880   // stack slot's alignment.
9881   int FrameIdx = INT_MIN;
9882   int64_t FrameOffset = 0;
9883   if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr)) {
9884     FrameIdx = FI->getIndex();
9885   } else if (isBaseWithConstantOffset(Ptr) &&
9886              isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
9887     // Handle FI+Cst
9888     FrameIdx = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
9889     FrameOffset = Ptr.getConstantOperandVal(1);
9890   }
9891 
9892   if (FrameIdx != INT_MIN) {
9893     const MachineFrameInfo &MFI = getMachineFunction().getFrameInfo();
9894     return commonAlignment(MFI.getObjectAlign(FrameIdx), FrameOffset);
9895   }
9896 
9897   return None;
9898 }
9899 
9900 /// GetSplitDestVTs - Compute the VTs needed for the low/hi parts of a type
9901 /// which is split (or expanded) into two not necessarily identical pieces.
9902 std::pair<EVT, EVT> SelectionDAG::GetSplitDestVTs(const EVT &VT) const {
9903   // Currently all types are split in half.
9904   EVT LoVT, HiVT;
9905   if (!VT.isVector())
9906     LoVT = HiVT = TLI->getTypeToTransformTo(*getContext(), VT);
9907   else
9908     LoVT = HiVT = VT.getHalfNumVectorElementsVT(*getContext());
9909 
9910   return std::make_pair(LoVT, HiVT);
9911 }
9912 
9913 /// GetDependentSplitDestVTs - Compute the VTs needed for the low/hi parts of a
9914 /// type, dependent on an enveloping VT that has been split into two identical
9915 /// pieces. Sets the HiIsEmpty flag when hi type has zero storage size.
9916 std::pair<EVT, EVT>
9917 SelectionDAG::GetDependentSplitDestVTs(const EVT &VT, const EVT &EnvVT,
9918                                        bool *HiIsEmpty) const {
9919   EVT EltTp = VT.getVectorElementType();
9920   // Examples:
9921   //   custom VL=8  with enveloping VL=8/8 yields 8/0 (hi empty)
9922   //   custom VL=9  with enveloping VL=8/8 yields 8/1
9923   //   custom VL=10 with enveloping VL=8/8 yields 8/2
9924   //   etc.
9925   ElementCount VTNumElts = VT.getVectorElementCount();
9926   ElementCount EnvNumElts = EnvVT.getVectorElementCount();
9927   assert(VTNumElts.isScalable() == EnvNumElts.isScalable() &&
9928          "Mixing fixed width and scalable vectors when enveloping a type");
9929   EVT LoVT, HiVT;
9930   if (VTNumElts.getKnownMinValue() > EnvNumElts.getKnownMinValue()) {
9931     LoVT = EnvVT;
9932     HiVT = EVT::getVectorVT(*getContext(), EltTp, VTNumElts - EnvNumElts);
9933     *HiIsEmpty = false;
9934   } else {
9935     // Flag that hi type has zero storage size, but return split envelop type
9936     // (this would be easier if vector types with zero elements were allowed).
9937     LoVT = EVT::getVectorVT(*getContext(), EltTp, VTNumElts);
9938     HiVT = EnvVT;
9939     *HiIsEmpty = true;
9940   }
9941   return std::make_pair(LoVT, HiVT);
9942 }
9943 
9944 /// SplitVector - Split the vector with EXTRACT_SUBVECTOR and return the
9945 /// low/high part.
9946 std::pair<SDValue, SDValue>
9947 SelectionDAG::SplitVector(const SDValue &N, const SDLoc &DL, const EVT &LoVT,
9948                           const EVT &HiVT) {
9949   assert(LoVT.isScalableVector() == HiVT.isScalableVector() &&
9950          LoVT.isScalableVector() == N.getValueType().isScalableVector() &&
9951          "Splitting vector with an invalid mixture of fixed and scalable "
9952          "vector types");
9953   assert(LoVT.getVectorMinNumElements() + HiVT.getVectorMinNumElements() <=
9954              N.getValueType().getVectorMinNumElements() &&
9955          "More vector elements requested than available!");
9956   SDValue Lo, Hi;
9957   Lo =
9958       getNode(ISD::EXTRACT_SUBVECTOR, DL, LoVT, N, getVectorIdxConstant(0, DL));
9959   // For scalable vectors it is safe to use LoVT.getVectorMinNumElements()
9960   // (rather than having to use ElementCount), because EXTRACT_SUBVECTOR scales
9961   // IDX with the runtime scaling factor of the result vector type. For
9962   // fixed-width result vectors, that runtime scaling factor is 1.
9963   Hi = getNode(ISD::EXTRACT_SUBVECTOR, DL, HiVT, N,
9964                getVectorIdxConstant(LoVT.getVectorMinNumElements(), DL));
9965   return std::make_pair(Lo, Hi);
9966 }
9967 
9968 /// Widen the vector up to the next power of two using INSERT_SUBVECTOR.
9969 SDValue SelectionDAG::WidenVector(const SDValue &N, const SDLoc &DL) {
9970   EVT VT = N.getValueType();
9971   EVT WideVT = EVT::getVectorVT(*getContext(), VT.getVectorElementType(),
9972                                 NextPowerOf2(VT.getVectorNumElements()));
9973   return getNode(ISD::INSERT_SUBVECTOR, DL, WideVT, getUNDEF(WideVT), N,
9974                  getVectorIdxConstant(0, DL));
9975 }
9976 
9977 void SelectionDAG::ExtractVectorElements(SDValue Op,
9978                                          SmallVectorImpl<SDValue> &Args,
9979                                          unsigned Start, unsigned Count,
9980                                          EVT EltVT) {
9981   EVT VT = Op.getValueType();
9982   if (Count == 0)
9983     Count = VT.getVectorNumElements();
9984   if (EltVT == EVT())
9985     EltVT = VT.getVectorElementType();
9986   SDLoc SL(Op);
9987   for (unsigned i = Start, e = Start + Count; i != e; ++i) {
9988     Args.push_back(getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Op,
9989                            getVectorIdxConstant(i, SL)));
9990   }
9991 }
9992 
9993 // getAddressSpace - Return the address space this GlobalAddress belongs to.
9994 unsigned GlobalAddressSDNode::getAddressSpace() const {
9995   return getGlobal()->getType()->getAddressSpace();
9996 }
9997 
9998 Type *ConstantPoolSDNode::getType() const {
9999   if (isMachineConstantPoolEntry())
10000     return Val.MachineCPVal->getType();
10001   return Val.ConstVal->getType();
10002 }
10003 
10004 bool BuildVectorSDNode::isConstantSplat(APInt &SplatValue, APInt &SplatUndef,
10005                                         unsigned &SplatBitSize,
10006                                         bool &HasAnyUndefs,
10007                                         unsigned MinSplatBits,
10008                                         bool IsBigEndian) const {
10009   EVT VT = getValueType(0);
10010   assert(VT.isVector() && "Expected a vector type");
10011   unsigned VecWidth = VT.getSizeInBits();
10012   if (MinSplatBits > VecWidth)
10013     return false;
10014 
10015   // FIXME: The widths are based on this node's type, but build vectors can
10016   // truncate their operands.
10017   SplatValue = APInt(VecWidth, 0);
10018   SplatUndef = APInt(VecWidth, 0);
10019 
10020   // Get the bits. Bits with undefined values (when the corresponding element
10021   // of the vector is an ISD::UNDEF value) are set in SplatUndef and cleared
10022   // in SplatValue. If any of the values are not constant, give up and return
10023   // false.
10024   unsigned int NumOps = getNumOperands();
10025   assert(NumOps > 0 && "isConstantSplat has 0-size build vector");
10026   unsigned EltWidth = VT.getScalarSizeInBits();
10027 
10028   for (unsigned j = 0; j < NumOps; ++j) {
10029     unsigned i = IsBigEndian ? NumOps - 1 - j : j;
10030     SDValue OpVal = getOperand(i);
10031     unsigned BitPos = j * EltWidth;
10032 
10033     if (OpVal.isUndef())
10034       SplatUndef.setBits(BitPos, BitPos + EltWidth);
10035     else if (auto *CN = dyn_cast<ConstantSDNode>(OpVal))
10036       SplatValue.insertBits(CN->getAPIntValue().zextOrTrunc(EltWidth), BitPos);
10037     else if (auto *CN = dyn_cast<ConstantFPSDNode>(OpVal))
10038       SplatValue.insertBits(CN->getValueAPF().bitcastToAPInt(), BitPos);
10039     else
10040       return false;
10041   }
10042 
10043   // The build_vector is all constants or undefs. Find the smallest element
10044   // size that splats the vector.
10045   HasAnyUndefs = (SplatUndef != 0);
10046 
10047   // FIXME: This does not work for vectors with elements less than 8 bits.
10048   while (VecWidth > 8) {
10049     unsigned HalfSize = VecWidth / 2;
10050     APInt HighValue = SplatValue.lshr(HalfSize).trunc(HalfSize);
10051     APInt LowValue = SplatValue.trunc(HalfSize);
10052     APInt HighUndef = SplatUndef.lshr(HalfSize).trunc(HalfSize);
10053     APInt LowUndef = SplatUndef.trunc(HalfSize);
10054 
10055     // If the two halves do not match (ignoring undef bits), stop here.
10056     if ((HighValue & ~LowUndef) != (LowValue & ~HighUndef) ||
10057         MinSplatBits > HalfSize)
10058       break;
10059 
10060     SplatValue = HighValue | LowValue;
10061     SplatUndef = HighUndef & LowUndef;
10062 
10063     VecWidth = HalfSize;
10064   }
10065 
10066   SplatBitSize = VecWidth;
10067   return true;
10068 }
10069 
10070 SDValue BuildVectorSDNode::getSplatValue(const APInt &DemandedElts,
10071                                          BitVector *UndefElements) const {
10072   unsigned NumOps = getNumOperands();
10073   if (UndefElements) {
10074     UndefElements->clear();
10075     UndefElements->resize(NumOps);
10076   }
10077   assert(NumOps == DemandedElts.getBitWidth() && "Unexpected vector size");
10078   if (!DemandedElts)
10079     return SDValue();
10080   SDValue Splatted;
10081   for (unsigned i = 0; i != NumOps; ++i) {
10082     if (!DemandedElts[i])
10083       continue;
10084     SDValue Op = getOperand(i);
10085     if (Op.isUndef()) {
10086       if (UndefElements)
10087         (*UndefElements)[i] = true;
10088     } else if (!Splatted) {
10089       Splatted = Op;
10090     } else if (Splatted != Op) {
10091       return SDValue();
10092     }
10093   }
10094 
10095   if (!Splatted) {
10096     unsigned FirstDemandedIdx = DemandedElts.countTrailingZeros();
10097     assert(getOperand(FirstDemandedIdx).isUndef() &&
10098            "Can only have a splat without a constant for all undefs.");
10099     return getOperand(FirstDemandedIdx);
10100   }
10101 
10102   return Splatted;
10103 }
10104 
10105 SDValue BuildVectorSDNode::getSplatValue(BitVector *UndefElements) const {
10106   APInt DemandedElts = APInt::getAllOnesValue(getNumOperands());
10107   return getSplatValue(DemandedElts, UndefElements);
10108 }
10109 
10110 bool BuildVectorSDNode::getRepeatedSequence(const APInt &DemandedElts,
10111                                             SmallVectorImpl<SDValue> &Sequence,
10112                                             BitVector *UndefElements) const {
10113   unsigned NumOps = getNumOperands();
10114   Sequence.clear();
10115   if (UndefElements) {
10116     UndefElements->clear();
10117     UndefElements->resize(NumOps);
10118   }
10119   assert(NumOps == DemandedElts.getBitWidth() && "Unexpected vector size");
10120   if (!DemandedElts || NumOps < 2 || !isPowerOf2_32(NumOps))
10121     return false;
10122 
10123   // Set the undefs even if we don't find a sequence (like getSplatValue).
10124   if (UndefElements)
10125     for (unsigned I = 0; I != NumOps; ++I)
10126       if (DemandedElts[I] && getOperand(I).isUndef())
10127         (*UndefElements)[I] = true;
10128 
10129   // Iteratively widen the sequence length looking for repetitions.
10130   for (unsigned SeqLen = 1; SeqLen < NumOps; SeqLen *= 2) {
10131     Sequence.append(SeqLen, SDValue());
10132     for (unsigned I = 0; I != NumOps; ++I) {
10133       if (!DemandedElts[I])
10134         continue;
10135       SDValue &SeqOp = Sequence[I % SeqLen];
10136       SDValue Op = getOperand(I);
10137       if (Op.isUndef()) {
10138         if (!SeqOp)
10139           SeqOp = Op;
10140         continue;
10141       }
10142       if (SeqOp && !SeqOp.isUndef() && SeqOp != Op) {
10143         Sequence.clear();
10144         break;
10145       }
10146       SeqOp = Op;
10147     }
10148     if (!Sequence.empty())
10149       return true;
10150   }
10151 
10152   assert(Sequence.empty() && "Failed to empty non-repeating sequence pattern");
10153   return false;
10154 }
10155 
10156 bool BuildVectorSDNode::getRepeatedSequence(SmallVectorImpl<SDValue> &Sequence,
10157                                             BitVector *UndefElements) const {
10158   APInt DemandedElts = APInt::getAllOnesValue(getNumOperands());
10159   return getRepeatedSequence(DemandedElts, Sequence, UndefElements);
10160 }
10161 
10162 ConstantSDNode *
10163 BuildVectorSDNode::getConstantSplatNode(const APInt &DemandedElts,
10164                                         BitVector *UndefElements) const {
10165   return dyn_cast_or_null<ConstantSDNode>(
10166       getSplatValue(DemandedElts, UndefElements));
10167 }
10168 
10169 ConstantSDNode *
10170 BuildVectorSDNode::getConstantSplatNode(BitVector *UndefElements) const {
10171   return dyn_cast_or_null<ConstantSDNode>(getSplatValue(UndefElements));
10172 }
10173 
10174 ConstantFPSDNode *
10175 BuildVectorSDNode::getConstantFPSplatNode(const APInt &DemandedElts,
10176                                           BitVector *UndefElements) const {
10177   return dyn_cast_or_null<ConstantFPSDNode>(
10178       getSplatValue(DemandedElts, UndefElements));
10179 }
10180 
10181 ConstantFPSDNode *
10182 BuildVectorSDNode::getConstantFPSplatNode(BitVector *UndefElements) const {
10183   return dyn_cast_or_null<ConstantFPSDNode>(getSplatValue(UndefElements));
10184 }
10185 
10186 int32_t
10187 BuildVectorSDNode::getConstantFPSplatPow2ToLog2Int(BitVector *UndefElements,
10188                                                    uint32_t BitWidth) const {
10189   if (ConstantFPSDNode *CN =
10190           dyn_cast_or_null<ConstantFPSDNode>(getSplatValue(UndefElements))) {
10191     bool IsExact;
10192     APSInt IntVal(BitWidth);
10193     const APFloat &APF = CN->getValueAPF();
10194     if (APF.convertToInteger(IntVal, APFloat::rmTowardZero, &IsExact) !=
10195             APFloat::opOK ||
10196         !IsExact)
10197       return -1;
10198 
10199     return IntVal.exactLogBase2();
10200   }
10201   return -1;
10202 }
10203 
10204 bool BuildVectorSDNode::isConstant() const {
10205   for (const SDValue &Op : op_values()) {
10206     unsigned Opc = Op.getOpcode();
10207     if (Opc != ISD::UNDEF && Opc != ISD::Constant && Opc != ISD::ConstantFP)
10208       return false;
10209   }
10210   return true;
10211 }
10212 
10213 bool ShuffleVectorSDNode::isSplatMask(const int *Mask, EVT VT) {
10214   // Find the first non-undef value in the shuffle mask.
10215   unsigned i, e;
10216   for (i = 0, e = VT.getVectorNumElements(); i != e && Mask[i] < 0; ++i)
10217     /* search */;
10218 
10219   // If all elements are undefined, this shuffle can be considered a splat
10220   // (although it should eventually get simplified away completely).
10221   if (i == e)
10222     return true;
10223 
10224   // Make sure all remaining elements are either undef or the same as the first
10225   // non-undef value.
10226   for (int Idx = Mask[i]; i != e; ++i)
10227     if (Mask[i] >= 0 && Mask[i] != Idx)
10228       return false;
10229   return true;
10230 }
10231 
10232 // Returns the SDNode if it is a constant integer BuildVector
10233 // or constant integer.
10234 SDNode *SelectionDAG::isConstantIntBuildVectorOrConstantInt(SDValue N) const {
10235   if (isa<ConstantSDNode>(N))
10236     return N.getNode();
10237   if (ISD::isBuildVectorOfConstantSDNodes(N.getNode()))
10238     return N.getNode();
10239   // Treat a GlobalAddress supporting constant offset folding as a
10240   // constant integer.
10241   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N))
10242     if (GA->getOpcode() == ISD::GlobalAddress &&
10243         TLI->isOffsetFoldingLegal(GA))
10244       return GA;
10245   if ((N.getOpcode() == ISD::SPLAT_VECTOR) &&
10246       isa<ConstantSDNode>(N.getOperand(0)))
10247     return N.getNode();
10248   return nullptr;
10249 }
10250 
10251 // Returns the SDNode if it is a constant float BuildVector
10252 // or constant float.
10253 SDNode *SelectionDAG::isConstantFPBuildVectorOrConstantFP(SDValue N) const {
10254   if (isa<ConstantFPSDNode>(N))
10255     return N.getNode();
10256 
10257   if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode()))
10258     return N.getNode();
10259 
10260   return nullptr;
10261 }
10262 
10263 void SelectionDAG::createOperands(SDNode *Node, ArrayRef<SDValue> Vals) {
10264   assert(!Node->OperandList && "Node already has operands");
10265   assert(SDNode::getMaxNumOperands() >= Vals.size() &&
10266          "too many operands to fit into SDNode");
10267   SDUse *Ops = OperandRecycler.allocate(
10268       ArrayRecycler<SDUse>::Capacity::get(Vals.size()), OperandAllocator);
10269 
10270   bool IsDivergent = false;
10271   for (unsigned I = 0; I != Vals.size(); ++I) {
10272     Ops[I].setUser(Node);
10273     Ops[I].setInitial(Vals[I]);
10274     if (Ops[I].Val.getValueType() != MVT::Other) // Skip Chain. It does not carry divergence.
10275       IsDivergent |= Ops[I].getNode()->isDivergent();
10276   }
10277   Node->NumOperands = Vals.size();
10278   Node->OperandList = Ops;
10279   if (!TLI->isSDNodeAlwaysUniform(Node)) {
10280     IsDivergent |= TLI->isSDNodeSourceOfDivergence(Node, FLI, DA);
10281     Node->SDNodeBits.IsDivergent = IsDivergent;
10282   }
10283   checkForCycles(Node);
10284 }
10285 
10286 SDValue SelectionDAG::getTokenFactor(const SDLoc &DL,
10287                                      SmallVectorImpl<SDValue> &Vals) {
10288   size_t Limit = SDNode::getMaxNumOperands();
10289   while (Vals.size() > Limit) {
10290     unsigned SliceIdx = Vals.size() - Limit;
10291     auto ExtractedTFs = ArrayRef<SDValue>(Vals).slice(SliceIdx, Limit);
10292     SDValue NewTF = getNode(ISD::TokenFactor, DL, MVT::Other, ExtractedTFs);
10293     Vals.erase(Vals.begin() + SliceIdx, Vals.end());
10294     Vals.emplace_back(NewTF);
10295   }
10296   return getNode(ISD::TokenFactor, DL, MVT::Other, Vals);
10297 }
10298 
10299 SDValue SelectionDAG::getNeutralElement(unsigned Opcode, const SDLoc &DL,
10300                                         EVT VT, SDNodeFlags Flags) {
10301   switch (Opcode) {
10302   default:
10303     return SDValue();
10304   case ISD::ADD:
10305   case ISD::OR:
10306   case ISD::XOR:
10307   case ISD::UMAX:
10308     return getConstant(0, DL, VT);
10309   case ISD::MUL:
10310     return getConstant(1, DL, VT);
10311   case ISD::AND:
10312   case ISD::UMIN:
10313     return getAllOnesConstant(DL, VT);
10314   case ISD::SMAX:
10315     return getConstant(APInt::getSignedMinValue(VT.getSizeInBits()), DL, VT);
10316   case ISD::SMIN:
10317     return getConstant(APInt::getSignedMaxValue(VT.getSizeInBits()), DL, VT);
10318   case ISD::FADD:
10319     return getConstantFP(-0.0, DL, VT);
10320   case ISD::FMUL:
10321     return getConstantFP(1.0, DL, VT);
10322   case ISD::FMINNUM:
10323   case ISD::FMAXNUM: {
10324     // Neutral element for fminnum is NaN, Inf or FLT_MAX, depending on FMF.
10325     const fltSemantics &Semantics = EVTToAPFloatSemantics(VT);
10326     APFloat NeutralAF = !Flags.hasNoNaNs() ? APFloat::getQNaN(Semantics) :
10327                         !Flags.hasNoInfs() ? APFloat::getInf(Semantics) :
10328                         APFloat::getLargest(Semantics);
10329     if (Opcode == ISD::FMAXNUM)
10330       NeutralAF.changeSign();
10331 
10332     return getConstantFP(NeutralAF, DL, VT);
10333   }
10334   }
10335 }
10336 
10337 #ifndef NDEBUG
10338 static void checkForCyclesHelper(const SDNode *N,
10339                                  SmallPtrSetImpl<const SDNode*> &Visited,
10340                                  SmallPtrSetImpl<const SDNode*> &Checked,
10341                                  const llvm::SelectionDAG *DAG) {
10342   // If this node has already been checked, don't check it again.
10343   if (Checked.count(N))
10344     return;
10345 
10346   // If a node has already been visited on this depth-first walk, reject it as
10347   // a cycle.
10348   if (!Visited.insert(N).second) {
10349     errs() << "Detected cycle in SelectionDAG\n";
10350     dbgs() << "Offending node:\n";
10351     N->dumprFull(DAG); dbgs() << "\n";
10352     abort();
10353   }
10354 
10355   for (const SDValue &Op : N->op_values())
10356     checkForCyclesHelper(Op.getNode(), Visited, Checked, DAG);
10357 
10358   Checked.insert(N);
10359   Visited.erase(N);
10360 }
10361 #endif
10362 
10363 void llvm::checkForCycles(const llvm::SDNode *N,
10364                           const llvm::SelectionDAG *DAG,
10365                           bool force) {
10366 #ifndef NDEBUG
10367   bool check = force;
10368 #ifdef EXPENSIVE_CHECKS
10369   check = true;
10370 #endif  // EXPENSIVE_CHECKS
10371   if (check) {
10372     assert(N && "Checking nonexistent SDNode");
10373     SmallPtrSet<const SDNode*, 32> visited;
10374     SmallPtrSet<const SDNode*, 32> checked;
10375     checkForCyclesHelper(N, visited, checked, DAG);
10376   }
10377 #endif  // !NDEBUG
10378 }
10379 
10380 void llvm::checkForCycles(const llvm::SelectionDAG *DAG, bool force) {
10381   checkForCycles(DAG->getRoot().getNode(), DAG, force);
10382 }
10383