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