1 //===- SelectionDAG.cpp - Implement the SelectionDAG data structures ------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This implements the SelectionDAG class.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "llvm/CodeGen/SelectionDAG.h"
14 #include "SDNodeDbgValue.h"
15 #include "llvm/ADT/APFloat.h"
16 #include "llvm/ADT/APInt.h"
17 #include "llvm/ADT/APSInt.h"
18 #include "llvm/ADT/ArrayRef.h"
19 #include "llvm/ADT/BitVector.h"
20 #include "llvm/ADT/FoldingSet.h"
21 #include "llvm/ADT/None.h"
22 #include "llvm/ADT/STLExtras.h"
23 #include "llvm/ADT/SmallPtrSet.h"
24 #include "llvm/ADT/SmallVector.h"
25 #include "llvm/ADT/Triple.h"
26 #include "llvm/ADT/Twine.h"
27 #include "llvm/Analysis/BlockFrequencyInfo.h"
28 #include "llvm/Analysis/MemoryLocation.h"
29 #include "llvm/Analysis/ProfileSummaryInfo.h"
30 #include "llvm/Analysis/ValueTracking.h"
31 #include "llvm/CodeGen/Analysis.h"
32 #include "llvm/CodeGen/FunctionLoweringInfo.h"
33 #include "llvm/CodeGen/ISDOpcodes.h"
34 #include "llvm/CodeGen/MachineBasicBlock.h"
35 #include "llvm/CodeGen/MachineConstantPool.h"
36 #include "llvm/CodeGen/MachineFrameInfo.h"
37 #include "llvm/CodeGen/MachineFunction.h"
38 #include "llvm/CodeGen/MachineMemOperand.h"
39 #include "llvm/CodeGen/RuntimeLibcalls.h"
40 #include "llvm/CodeGen/SelectionDAGAddressAnalysis.h"
41 #include "llvm/CodeGen/SelectionDAGNodes.h"
42 #include "llvm/CodeGen/SelectionDAGTargetInfo.h"
43 #include "llvm/CodeGen/TargetFrameLowering.h"
44 #include "llvm/CodeGen/TargetLowering.h"
45 #include "llvm/CodeGen/TargetRegisterInfo.h"
46 #include "llvm/CodeGen/TargetSubtargetInfo.h"
47 #include "llvm/CodeGen/ValueTypes.h"
48 #include "llvm/IR/Constant.h"
49 #include "llvm/IR/Constants.h"
50 #include "llvm/IR/DataLayout.h"
51 #include "llvm/IR/DebugInfoMetadata.h"
52 #include "llvm/IR/DebugLoc.h"
53 #include "llvm/IR/DerivedTypes.h"
54 #include "llvm/IR/Function.h"
55 #include "llvm/IR/GlobalValue.h"
56 #include "llvm/IR/Metadata.h"
57 #include "llvm/IR/Type.h"
58 #include "llvm/IR/Value.h"
59 #include "llvm/Support/Casting.h"
60 #include "llvm/Support/CodeGen.h"
61 #include "llvm/Support/Compiler.h"
62 #include "llvm/Support/Debug.h"
63 #include "llvm/Support/ErrorHandling.h"
64 #include "llvm/Support/KnownBits.h"
65 #include "llvm/Support/MachineValueType.h"
66 #include "llvm/Support/ManagedStatic.h"
67 #include "llvm/Support/MathExtras.h"
68 #include "llvm/Support/Mutex.h"
69 #include "llvm/Support/raw_ostream.h"
70 #include "llvm/Target/TargetMachine.h"
71 #include "llvm/Target/TargetOptions.h"
72 #include "llvm/Transforms/Utils/SizeOpts.h"
73 #include <algorithm>
74 #include <cassert>
75 #include <cstdint>
76 #include <cstdlib>
77 #include <limits>
78 #include <set>
79 #include <string>
80 #include <utility>
81 #include <vector>
82 
83 using namespace llvm;
84 
85 /// makeVTList - Return an instance of the SDVTList struct initialized with the
86 /// specified members.
87 static SDVTList makeVTList(const EVT *VTs, unsigned NumVTs) {
88   SDVTList Res = {VTs, NumVTs};
89   return Res;
90 }
91 
92 // Default null implementations of the callbacks.
93 void SelectionDAG::DAGUpdateListener::NodeDeleted(SDNode*, SDNode*) {}
94 void SelectionDAG::DAGUpdateListener::NodeUpdated(SDNode*) {}
95 void SelectionDAG::DAGUpdateListener::NodeInserted(SDNode *) {}
96 
97 void SelectionDAG::DAGNodeDeletedListener::anchor() {}
98 
99 #define DEBUG_TYPE "selectiondag"
100 
101 static cl::opt<bool> EnableMemCpyDAGOpt("enable-memcpy-dag-opt",
102        cl::Hidden, cl::init(true),
103        cl::desc("Gang up loads and stores generated by inlining of memcpy"));
104 
105 static cl::opt<int> MaxLdStGlue("ldstmemcpy-glue-max",
106        cl::desc("Number limit for gluing ld/st of memcpy."),
107        cl::Hidden, cl::init(0));
108 
109 static void NewSDValueDbgMsg(SDValue V, StringRef Msg, SelectionDAG *G) {
110   LLVM_DEBUG(dbgs() << Msg; V.getNode()->dump(G););
111 }
112 
113 //===----------------------------------------------------------------------===//
114 //                              ConstantFPSDNode Class
115 //===----------------------------------------------------------------------===//
116 
117 /// isExactlyValue - We don't rely on operator== working on double values, as
118 /// it returns true for things that are clearly not equal, like -0.0 and 0.0.
119 /// As such, this method can be used to do an exact bit-for-bit comparison of
120 /// two floating point values.
121 bool ConstantFPSDNode::isExactlyValue(const APFloat& V) const {
122   return getValueAPF().bitwiseIsEqual(V);
123 }
124 
125 bool ConstantFPSDNode::isValueValidForType(EVT VT,
126                                            const APFloat& Val) {
127   assert(VT.isFloatingPoint() && "Can only convert between FP types");
128 
129   // convert modifies in place, so make a copy.
130   APFloat Val2 = APFloat(Val);
131   bool losesInfo;
132   (void) Val2.convert(SelectionDAG::EVTToAPFloatSemantics(VT),
133                       APFloat::rmNearestTiesToEven,
134                       &losesInfo);
135   return !losesInfo;
136 }
137 
138 //===----------------------------------------------------------------------===//
139 //                              ISD Namespace
140 //===----------------------------------------------------------------------===//
141 
142 bool ISD::isConstantSplatVector(const SDNode *N, APInt &SplatVal) {
143   if (N->getOpcode() == ISD::SPLAT_VECTOR) {
144     unsigned EltSize =
145         N->getValueType(0).getVectorElementType().getSizeInBits();
146     if (auto *Op0 = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
147       SplatVal = Op0->getAPIntValue().truncOrSelf(EltSize);
148       return true;
149     }
150     if (auto *Op0 = dyn_cast<ConstantFPSDNode>(N->getOperand(0))) {
151       SplatVal = Op0->getValueAPF().bitcastToAPInt().truncOrSelf(EltSize);
152       return true;
153     }
154   }
155 
156   auto *BV = dyn_cast<BuildVectorSDNode>(N);
157   if (!BV)
158     return false;
159 
160   APInt SplatUndef;
161   unsigned SplatBitSize;
162   bool HasUndefs;
163   unsigned EltSize = N->getValueType(0).getVectorElementType().getSizeInBits();
164   return BV->isConstantSplat(SplatVal, SplatUndef, SplatBitSize, HasUndefs,
165                              EltSize) &&
166          EltSize == SplatBitSize;
167 }
168 
169 // FIXME: AllOnes and AllZeros duplicate a lot of code. Could these be
170 // specializations of the more general isConstantSplatVector()?
171 
172 bool ISD::isConstantSplatVectorAllOnes(const SDNode *N, bool BuildVectorOnly) {
173   // Look through a bit convert.
174   while (N->getOpcode() == ISD::BITCAST)
175     N = N->getOperand(0).getNode();
176 
177   if (!BuildVectorOnly && N->getOpcode() == ISD::SPLAT_VECTOR) {
178     APInt SplatVal;
179     return isConstantSplatVector(N, SplatVal) && SplatVal.isAllOnes();
180   }
181 
182   if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
183 
184   unsigned i = 0, e = N->getNumOperands();
185 
186   // Skip over all of the undef values.
187   while (i != e && N->getOperand(i).isUndef())
188     ++i;
189 
190   // Do not accept an all-undef vector.
191   if (i == e) return false;
192 
193   // Do not accept build_vectors that aren't all constants or which have non-~0
194   // elements. We have to be a bit careful here, as the type of the constant
195   // may not be the same as the type of the vector elements due to type
196   // legalization (the elements are promoted to a legal type for the target and
197   // a vector of a type may be legal when the base element type is not).
198   // We only want to check enough bits to cover the vector elements, because
199   // we care if the resultant vector is all ones, not whether the individual
200   // constants are.
201   SDValue NotZero = N->getOperand(i);
202   unsigned EltSize = N->getValueType(0).getScalarSizeInBits();
203   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(NotZero)) {
204     if (CN->getAPIntValue().countTrailingOnes() < EltSize)
205       return false;
206   } else if (ConstantFPSDNode *CFPN = dyn_cast<ConstantFPSDNode>(NotZero)) {
207     if (CFPN->getValueAPF().bitcastToAPInt().countTrailingOnes() < EltSize)
208       return false;
209   } else
210     return false;
211 
212   // Okay, we have at least one ~0 value, check to see if the rest match or are
213   // undefs. Even with the above element type twiddling, this should be OK, as
214   // the same type legalization should have applied to all the elements.
215   for (++i; i != e; ++i)
216     if (N->getOperand(i) != NotZero && !N->getOperand(i).isUndef())
217       return false;
218   return true;
219 }
220 
221 bool ISD::isConstantSplatVectorAllZeros(const SDNode *N, bool BuildVectorOnly) {
222   // Look through a bit convert.
223   while (N->getOpcode() == ISD::BITCAST)
224     N = N->getOperand(0).getNode();
225 
226   if (!BuildVectorOnly && N->getOpcode() == ISD::SPLAT_VECTOR) {
227     APInt SplatVal;
228     return isConstantSplatVector(N, SplatVal) && SplatVal.isZero();
229   }
230 
231   if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
232 
233   bool IsAllUndef = true;
234   for (const SDValue &Op : N->op_values()) {
235     if (Op.isUndef())
236       continue;
237     IsAllUndef = false;
238     // Do not accept build_vectors that aren't all constants or which have non-0
239     // elements. We have to be a bit careful here, as the type of the constant
240     // may not be the same as the type of the vector elements due to type
241     // legalization (the elements are promoted to a legal type for the target
242     // and a vector of a type may be legal when the base element type is not).
243     // We only want to check enough bits to cover the vector elements, because
244     // we care if the resultant vector is all zeros, not whether the individual
245     // constants are.
246     unsigned EltSize = N->getValueType(0).getScalarSizeInBits();
247     if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Op)) {
248       if (CN->getAPIntValue().countTrailingZeros() < EltSize)
249         return false;
250     } else if (ConstantFPSDNode *CFPN = dyn_cast<ConstantFPSDNode>(Op)) {
251       if (CFPN->getValueAPF().bitcastToAPInt().countTrailingZeros() < EltSize)
252         return false;
253     } else
254       return false;
255   }
256 
257   // Do not accept an all-undef vector.
258   if (IsAllUndef)
259     return false;
260   return true;
261 }
262 
263 bool ISD::isBuildVectorAllOnes(const SDNode *N) {
264   return isConstantSplatVectorAllOnes(N, /*BuildVectorOnly*/ true);
265 }
266 
267 bool ISD::isBuildVectorAllZeros(const SDNode *N) {
268   return isConstantSplatVectorAllZeros(N, /*BuildVectorOnly*/ true);
269 }
270 
271 bool ISD::isBuildVectorOfConstantSDNodes(const SDNode *N) {
272   if (N->getOpcode() != ISD::BUILD_VECTOR)
273     return false;
274 
275   for (const SDValue &Op : N->op_values()) {
276     if (Op.isUndef())
277       continue;
278     if (!isa<ConstantSDNode>(Op))
279       return false;
280   }
281   return true;
282 }
283 
284 bool ISD::isBuildVectorOfConstantFPSDNodes(const SDNode *N) {
285   if (N->getOpcode() != ISD::BUILD_VECTOR)
286     return false;
287 
288   for (const SDValue &Op : N->op_values()) {
289     if (Op.isUndef())
290       continue;
291     if (!isa<ConstantFPSDNode>(Op))
292       return false;
293   }
294   return true;
295 }
296 
297 bool ISD::allOperandsUndef(const SDNode *N) {
298   // Return false if the node has no operands.
299   // This is "logically inconsistent" with the definition of "all" but
300   // is probably the desired behavior.
301   if (N->getNumOperands() == 0)
302     return false;
303   return all_of(N->op_values(), [](SDValue Op) { return Op.isUndef(); });
304 }
305 
306 bool ISD::matchUnaryPredicate(SDValue Op,
307                               std::function<bool(ConstantSDNode *)> Match,
308                               bool AllowUndefs) {
309   // FIXME: Add support for scalar UNDEF cases?
310   if (auto *Cst = dyn_cast<ConstantSDNode>(Op))
311     return Match(Cst);
312 
313   // FIXME: Add support for vector UNDEF cases?
314   if (ISD::BUILD_VECTOR != Op.getOpcode() &&
315       ISD::SPLAT_VECTOR != Op.getOpcode())
316     return false;
317 
318   EVT SVT = Op.getValueType().getScalarType();
319   for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
320     if (AllowUndefs && Op.getOperand(i).isUndef()) {
321       if (!Match(nullptr))
322         return false;
323       continue;
324     }
325 
326     auto *Cst = dyn_cast<ConstantSDNode>(Op.getOperand(i));
327     if (!Cst || Cst->getValueType(0) != SVT || !Match(Cst))
328       return false;
329   }
330   return true;
331 }
332 
333 bool ISD::matchBinaryPredicate(
334     SDValue LHS, SDValue RHS,
335     std::function<bool(ConstantSDNode *, ConstantSDNode *)> Match,
336     bool AllowUndefs, bool AllowTypeMismatch) {
337   if (!AllowTypeMismatch && LHS.getValueType() != RHS.getValueType())
338     return false;
339 
340   // TODO: Add support for scalar UNDEF cases?
341   if (auto *LHSCst = dyn_cast<ConstantSDNode>(LHS))
342     if (auto *RHSCst = dyn_cast<ConstantSDNode>(RHS))
343       return Match(LHSCst, RHSCst);
344 
345   // TODO: Add support for vector UNDEF cases?
346   if (LHS.getOpcode() != RHS.getOpcode() ||
347       (LHS.getOpcode() != ISD::BUILD_VECTOR &&
348        LHS.getOpcode() != ISD::SPLAT_VECTOR))
349     return false;
350 
351   EVT SVT = LHS.getValueType().getScalarType();
352   for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
353     SDValue LHSOp = LHS.getOperand(i);
354     SDValue RHSOp = RHS.getOperand(i);
355     bool LHSUndef = AllowUndefs && LHSOp.isUndef();
356     bool RHSUndef = AllowUndefs && RHSOp.isUndef();
357     auto *LHSCst = dyn_cast<ConstantSDNode>(LHSOp);
358     auto *RHSCst = dyn_cast<ConstantSDNode>(RHSOp);
359     if ((!LHSCst && !LHSUndef) || (!RHSCst && !RHSUndef))
360       return false;
361     if (!AllowTypeMismatch && (LHSOp.getValueType() != SVT ||
362                                LHSOp.getValueType() != RHSOp.getValueType()))
363       return false;
364     if (!Match(LHSCst, RHSCst))
365       return false;
366   }
367   return true;
368 }
369 
370 ISD::NodeType ISD::getVecReduceBaseOpcode(unsigned VecReduceOpcode) {
371   switch (VecReduceOpcode) {
372   default:
373     llvm_unreachable("Expected VECREDUCE opcode");
374   case ISD::VECREDUCE_FADD:
375   case ISD::VECREDUCE_SEQ_FADD:
376   case ISD::VP_REDUCE_FADD:
377   case ISD::VP_REDUCE_SEQ_FADD:
378     return ISD::FADD;
379   case ISD::VECREDUCE_FMUL:
380   case ISD::VECREDUCE_SEQ_FMUL:
381   case ISD::VP_REDUCE_FMUL:
382   case ISD::VP_REDUCE_SEQ_FMUL:
383     return ISD::FMUL;
384   case ISD::VECREDUCE_ADD:
385   case ISD::VP_REDUCE_ADD:
386     return ISD::ADD;
387   case ISD::VECREDUCE_MUL:
388   case ISD::VP_REDUCE_MUL:
389     return ISD::MUL;
390   case ISD::VECREDUCE_AND:
391   case ISD::VP_REDUCE_AND:
392     return ISD::AND;
393   case ISD::VECREDUCE_OR:
394   case ISD::VP_REDUCE_OR:
395     return ISD::OR;
396   case ISD::VECREDUCE_XOR:
397   case ISD::VP_REDUCE_XOR:
398     return ISD::XOR;
399   case ISD::VECREDUCE_SMAX:
400   case ISD::VP_REDUCE_SMAX:
401     return ISD::SMAX;
402   case ISD::VECREDUCE_SMIN:
403   case ISD::VP_REDUCE_SMIN:
404     return ISD::SMIN;
405   case ISD::VECREDUCE_UMAX:
406   case ISD::VP_REDUCE_UMAX:
407     return ISD::UMAX;
408   case ISD::VECREDUCE_UMIN:
409   case ISD::VP_REDUCE_UMIN:
410     return ISD::UMIN;
411   case ISD::VECREDUCE_FMAX:
412   case ISD::VP_REDUCE_FMAX:
413     return ISD::FMAXNUM;
414   case ISD::VECREDUCE_FMIN:
415   case ISD::VP_REDUCE_FMIN:
416     return ISD::FMINNUM;
417   }
418 }
419 
420 bool ISD::isVPOpcode(unsigned Opcode) {
421   switch (Opcode) {
422   default:
423     return false;
424 #define BEGIN_REGISTER_VP_SDNODE(VPSD, ...)                                    \
425   case ISD::VPSD:                                                              \
426     return true;
427 #include "llvm/IR/VPIntrinsics.def"
428   }
429 }
430 
431 bool ISD::isVPBinaryOp(unsigned Opcode) {
432   switch (Opcode) {
433   default:
434     break;
435 #define BEGIN_REGISTER_VP_SDNODE(VPSD, ...) case ISD::VPSD:
436 #define VP_PROPERTY_BINARYOP return true;
437 #define END_REGISTER_VP_SDNODE(VPSD) break;
438 #include "llvm/IR/VPIntrinsics.def"
439   }
440   return false;
441 }
442 
443 bool ISD::isVPReduction(unsigned Opcode) {
444   switch (Opcode) {
445   default:
446     break;
447 #define BEGIN_REGISTER_VP_SDNODE(VPSD, ...) case ISD::VPSD:
448 #define VP_PROPERTY_REDUCTION(STARTPOS, ...) return true;
449 #define END_REGISTER_VP_SDNODE(VPSD) break;
450 #include "llvm/IR/VPIntrinsics.def"
451   }
452   return false;
453 }
454 
455 /// The operand position of the vector mask.
456 Optional<unsigned> ISD::getVPMaskIdx(unsigned Opcode) {
457   switch (Opcode) {
458   default:
459     return None;
460 #define BEGIN_REGISTER_VP_SDNODE(VPSD, LEGALPOS, TDNAME, MASKPOS, ...)         \
461   case ISD::VPSD:                                                              \
462     return MASKPOS;
463 #include "llvm/IR/VPIntrinsics.def"
464   }
465 }
466 
467 /// The operand position of the explicit vector length parameter.
468 Optional<unsigned> ISD::getVPExplicitVectorLengthIdx(unsigned Opcode) {
469   switch (Opcode) {
470   default:
471     return None;
472 #define BEGIN_REGISTER_VP_SDNODE(VPSD, LEGALPOS, TDNAME, MASKPOS, EVLPOS)      \
473   case ISD::VPSD:                                                              \
474     return EVLPOS;
475 #include "llvm/IR/VPIntrinsics.def"
476   }
477 }
478 
479 ISD::NodeType ISD::getExtForLoadExtType(bool IsFP, ISD::LoadExtType ExtType) {
480   switch (ExtType) {
481   case ISD::EXTLOAD:
482     return IsFP ? ISD::FP_EXTEND : ISD::ANY_EXTEND;
483   case ISD::SEXTLOAD:
484     return ISD::SIGN_EXTEND;
485   case ISD::ZEXTLOAD:
486     return ISD::ZERO_EXTEND;
487   default:
488     break;
489   }
490 
491   llvm_unreachable("Invalid LoadExtType");
492 }
493 
494 ISD::CondCode ISD::getSetCCSwappedOperands(ISD::CondCode Operation) {
495   // To perform this operation, we just need to swap the L and G bits of the
496   // operation.
497   unsigned OldL = (Operation >> 2) & 1;
498   unsigned OldG = (Operation >> 1) & 1;
499   return ISD::CondCode((Operation & ~6) |  // Keep the N, U, E bits
500                        (OldL << 1) |       // New G bit
501                        (OldG << 2));       // New L bit.
502 }
503 
504 static ISD::CondCode getSetCCInverseImpl(ISD::CondCode Op, bool isIntegerLike) {
505   unsigned Operation = Op;
506   if (isIntegerLike)
507     Operation ^= 7;   // Flip L, G, E bits, but not U.
508   else
509     Operation ^= 15;  // Flip all of the condition bits.
510 
511   if (Operation > ISD::SETTRUE2)
512     Operation &= ~8;  // Don't let N and U bits get set.
513 
514   return ISD::CondCode(Operation);
515 }
516 
517 ISD::CondCode ISD::getSetCCInverse(ISD::CondCode Op, EVT Type) {
518   return getSetCCInverseImpl(Op, Type.isInteger());
519 }
520 
521 ISD::CondCode ISD::GlobalISel::getSetCCInverse(ISD::CondCode Op,
522                                                bool isIntegerLike) {
523   return getSetCCInverseImpl(Op, isIntegerLike);
524 }
525 
526 /// For an integer comparison, return 1 if the comparison is a signed operation
527 /// and 2 if the result is an unsigned comparison. Return zero if the operation
528 /// does not depend on the sign of the input (setne and seteq).
529 static int isSignedOp(ISD::CondCode Opcode) {
530   switch (Opcode) {
531   default: llvm_unreachable("Illegal integer setcc operation!");
532   case ISD::SETEQ:
533   case ISD::SETNE: return 0;
534   case ISD::SETLT:
535   case ISD::SETLE:
536   case ISD::SETGT:
537   case ISD::SETGE: return 1;
538   case ISD::SETULT:
539   case ISD::SETULE:
540   case ISD::SETUGT:
541   case ISD::SETUGE: return 2;
542   }
543 }
544 
545 ISD::CondCode ISD::getSetCCOrOperation(ISD::CondCode Op1, ISD::CondCode Op2,
546                                        EVT Type) {
547   bool IsInteger = Type.isInteger();
548   if (IsInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
549     // Cannot fold a signed integer setcc with an unsigned integer setcc.
550     return ISD::SETCC_INVALID;
551 
552   unsigned Op = Op1 | Op2;  // Combine all of the condition bits.
553 
554   // If the N and U bits get set, then the resultant comparison DOES suddenly
555   // care about orderedness, and it is true when ordered.
556   if (Op > ISD::SETTRUE2)
557     Op &= ~16;     // Clear the U bit if the N bit is set.
558 
559   // Canonicalize illegal integer setcc's.
560   if (IsInteger && Op == ISD::SETUNE)  // e.g. SETUGT | SETULT
561     Op = ISD::SETNE;
562 
563   return ISD::CondCode(Op);
564 }
565 
566 ISD::CondCode ISD::getSetCCAndOperation(ISD::CondCode Op1, ISD::CondCode Op2,
567                                         EVT Type) {
568   bool IsInteger = Type.isInteger();
569   if (IsInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
570     // Cannot fold a signed setcc with an unsigned setcc.
571     return ISD::SETCC_INVALID;
572 
573   // Combine all of the condition bits.
574   ISD::CondCode Result = ISD::CondCode(Op1 & Op2);
575 
576   // Canonicalize illegal integer setcc's.
577   if (IsInteger) {
578     switch (Result) {
579     default: break;
580     case ISD::SETUO : Result = ISD::SETFALSE; break;  // SETUGT & SETULT
581     case ISD::SETOEQ:                                 // SETEQ  & SETU[LG]E
582     case ISD::SETUEQ: Result = ISD::SETEQ   ; break;  // SETUGE & SETULE
583     case ISD::SETOLT: Result = ISD::SETULT  ; break;  // SETULT & SETNE
584     case ISD::SETOGT: Result = ISD::SETUGT  ; break;  // SETUGT & SETNE
585     }
586   }
587 
588   return Result;
589 }
590 
591 //===----------------------------------------------------------------------===//
592 //                           SDNode Profile Support
593 //===----------------------------------------------------------------------===//
594 
595 /// AddNodeIDOpcode - Add the node opcode to the NodeID data.
596 static void AddNodeIDOpcode(FoldingSetNodeID &ID, unsigned OpC)  {
597   ID.AddInteger(OpC);
598 }
599 
600 /// AddNodeIDValueTypes - Value type lists are intern'd so we can represent them
601 /// solely with their pointer.
602 static void AddNodeIDValueTypes(FoldingSetNodeID &ID, SDVTList VTList) {
603   ID.AddPointer(VTList.VTs);
604 }
605 
606 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data.
607 static void AddNodeIDOperands(FoldingSetNodeID &ID,
608                               ArrayRef<SDValue> Ops) {
609   for (auto& Op : Ops) {
610     ID.AddPointer(Op.getNode());
611     ID.AddInteger(Op.getResNo());
612   }
613 }
614 
615 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data.
616 static void AddNodeIDOperands(FoldingSetNodeID &ID,
617                               ArrayRef<SDUse> Ops) {
618   for (auto& Op : Ops) {
619     ID.AddPointer(Op.getNode());
620     ID.AddInteger(Op.getResNo());
621   }
622 }
623 
624 static void AddNodeIDNode(FoldingSetNodeID &ID, unsigned short OpC,
625                           SDVTList VTList, ArrayRef<SDValue> OpList) {
626   AddNodeIDOpcode(ID, OpC);
627   AddNodeIDValueTypes(ID, VTList);
628   AddNodeIDOperands(ID, OpList);
629 }
630 
631 /// If this is an SDNode with special info, add this info to the NodeID data.
632 static void AddNodeIDCustom(FoldingSetNodeID &ID, const SDNode *N) {
633   switch (N->getOpcode()) {
634   case ISD::TargetExternalSymbol:
635   case ISD::ExternalSymbol:
636   case ISD::MCSymbol:
637     llvm_unreachable("Should only be used on nodes with operands");
638   default: break;  // Normal nodes don't need extra info.
639   case ISD::TargetConstant:
640   case ISD::Constant: {
641     const ConstantSDNode *C = cast<ConstantSDNode>(N);
642     ID.AddPointer(C->getConstantIntValue());
643     ID.AddBoolean(C->isOpaque());
644     break;
645   }
646   case ISD::TargetConstantFP:
647   case ISD::ConstantFP:
648     ID.AddPointer(cast<ConstantFPSDNode>(N)->getConstantFPValue());
649     break;
650   case ISD::TargetGlobalAddress:
651   case ISD::GlobalAddress:
652   case ISD::TargetGlobalTLSAddress:
653   case ISD::GlobalTLSAddress: {
654     const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(N);
655     ID.AddPointer(GA->getGlobal());
656     ID.AddInteger(GA->getOffset());
657     ID.AddInteger(GA->getTargetFlags());
658     break;
659   }
660   case ISD::BasicBlock:
661     ID.AddPointer(cast<BasicBlockSDNode>(N)->getBasicBlock());
662     break;
663   case ISD::Register:
664     ID.AddInteger(cast<RegisterSDNode>(N)->getReg());
665     break;
666   case ISD::RegisterMask:
667     ID.AddPointer(cast<RegisterMaskSDNode>(N)->getRegMask());
668     break;
669   case ISD::SRCVALUE:
670     ID.AddPointer(cast<SrcValueSDNode>(N)->getValue());
671     break;
672   case ISD::FrameIndex:
673   case ISD::TargetFrameIndex:
674     ID.AddInteger(cast<FrameIndexSDNode>(N)->getIndex());
675     break;
676   case ISD::LIFETIME_START:
677   case ISD::LIFETIME_END:
678     if (cast<LifetimeSDNode>(N)->hasOffset()) {
679       ID.AddInteger(cast<LifetimeSDNode>(N)->getSize());
680       ID.AddInteger(cast<LifetimeSDNode>(N)->getOffset());
681     }
682     break;
683   case ISD::PSEUDO_PROBE:
684     ID.AddInteger(cast<PseudoProbeSDNode>(N)->getGuid());
685     ID.AddInteger(cast<PseudoProbeSDNode>(N)->getIndex());
686     ID.AddInteger(cast<PseudoProbeSDNode>(N)->getAttributes());
687     break;
688   case ISD::JumpTable:
689   case ISD::TargetJumpTable:
690     ID.AddInteger(cast<JumpTableSDNode>(N)->getIndex());
691     ID.AddInteger(cast<JumpTableSDNode>(N)->getTargetFlags());
692     break;
693   case ISD::ConstantPool:
694   case ISD::TargetConstantPool: {
695     const ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(N);
696     ID.AddInteger(CP->getAlign().value());
697     ID.AddInteger(CP->getOffset());
698     if (CP->isMachineConstantPoolEntry())
699       CP->getMachineCPVal()->addSelectionDAGCSEId(ID);
700     else
701       ID.AddPointer(CP->getConstVal());
702     ID.AddInteger(CP->getTargetFlags());
703     break;
704   }
705   case ISD::TargetIndex: {
706     const TargetIndexSDNode *TI = cast<TargetIndexSDNode>(N);
707     ID.AddInteger(TI->getIndex());
708     ID.AddInteger(TI->getOffset());
709     ID.AddInteger(TI->getTargetFlags());
710     break;
711   }
712   case ISD::LOAD: {
713     const LoadSDNode *LD = cast<LoadSDNode>(N);
714     ID.AddInteger(LD->getMemoryVT().getRawBits());
715     ID.AddInteger(LD->getRawSubclassData());
716     ID.AddInteger(LD->getPointerInfo().getAddrSpace());
717     break;
718   }
719   case ISD::STORE: {
720     const StoreSDNode *ST = cast<StoreSDNode>(N);
721     ID.AddInteger(ST->getMemoryVT().getRawBits());
722     ID.AddInteger(ST->getRawSubclassData());
723     ID.AddInteger(ST->getPointerInfo().getAddrSpace());
724     break;
725   }
726   case ISD::VP_LOAD: {
727     const VPLoadSDNode *ELD = cast<VPLoadSDNode>(N);
728     ID.AddInteger(ELD->getMemoryVT().getRawBits());
729     ID.AddInteger(ELD->getRawSubclassData());
730     ID.AddInteger(ELD->getPointerInfo().getAddrSpace());
731     break;
732   }
733   case ISD::VP_STORE: {
734     const VPStoreSDNode *EST = cast<VPStoreSDNode>(N);
735     ID.AddInteger(EST->getMemoryVT().getRawBits());
736     ID.AddInteger(EST->getRawSubclassData());
737     ID.AddInteger(EST->getPointerInfo().getAddrSpace());
738     break;
739   }
740   case ISD::VP_GATHER: {
741     const VPGatherSDNode *EG = cast<VPGatherSDNode>(N);
742     ID.AddInteger(EG->getMemoryVT().getRawBits());
743     ID.AddInteger(EG->getRawSubclassData());
744     ID.AddInteger(EG->getPointerInfo().getAddrSpace());
745     break;
746   }
747   case ISD::VP_SCATTER: {
748     const VPScatterSDNode *ES = cast<VPScatterSDNode>(N);
749     ID.AddInteger(ES->getMemoryVT().getRawBits());
750     ID.AddInteger(ES->getRawSubclassData());
751     ID.AddInteger(ES->getPointerInfo().getAddrSpace());
752     break;
753   }
754   case ISD::MLOAD: {
755     const MaskedLoadSDNode *MLD = cast<MaskedLoadSDNode>(N);
756     ID.AddInteger(MLD->getMemoryVT().getRawBits());
757     ID.AddInteger(MLD->getRawSubclassData());
758     ID.AddInteger(MLD->getPointerInfo().getAddrSpace());
759     break;
760   }
761   case ISD::MSTORE: {
762     const MaskedStoreSDNode *MST = cast<MaskedStoreSDNode>(N);
763     ID.AddInteger(MST->getMemoryVT().getRawBits());
764     ID.AddInteger(MST->getRawSubclassData());
765     ID.AddInteger(MST->getPointerInfo().getAddrSpace());
766     break;
767   }
768   case ISD::MGATHER: {
769     const MaskedGatherSDNode *MG = cast<MaskedGatherSDNode>(N);
770     ID.AddInteger(MG->getMemoryVT().getRawBits());
771     ID.AddInteger(MG->getRawSubclassData());
772     ID.AddInteger(MG->getPointerInfo().getAddrSpace());
773     break;
774   }
775   case ISD::MSCATTER: {
776     const MaskedScatterSDNode *MS = cast<MaskedScatterSDNode>(N);
777     ID.AddInteger(MS->getMemoryVT().getRawBits());
778     ID.AddInteger(MS->getRawSubclassData());
779     ID.AddInteger(MS->getPointerInfo().getAddrSpace());
780     break;
781   }
782   case ISD::ATOMIC_CMP_SWAP:
783   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
784   case ISD::ATOMIC_SWAP:
785   case ISD::ATOMIC_LOAD_ADD:
786   case ISD::ATOMIC_LOAD_SUB:
787   case ISD::ATOMIC_LOAD_AND:
788   case ISD::ATOMIC_LOAD_CLR:
789   case ISD::ATOMIC_LOAD_OR:
790   case ISD::ATOMIC_LOAD_XOR:
791   case ISD::ATOMIC_LOAD_NAND:
792   case ISD::ATOMIC_LOAD_MIN:
793   case ISD::ATOMIC_LOAD_MAX:
794   case ISD::ATOMIC_LOAD_UMIN:
795   case ISD::ATOMIC_LOAD_UMAX:
796   case ISD::ATOMIC_LOAD:
797   case ISD::ATOMIC_STORE: {
798     const AtomicSDNode *AT = cast<AtomicSDNode>(N);
799     ID.AddInteger(AT->getMemoryVT().getRawBits());
800     ID.AddInteger(AT->getRawSubclassData());
801     ID.AddInteger(AT->getPointerInfo().getAddrSpace());
802     break;
803   }
804   case ISD::PREFETCH: {
805     const MemSDNode *PF = cast<MemSDNode>(N);
806     ID.AddInteger(PF->getPointerInfo().getAddrSpace());
807     break;
808   }
809   case ISD::VECTOR_SHUFFLE: {
810     const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
811     for (unsigned i = 0, e = N->getValueType(0).getVectorNumElements();
812          i != e; ++i)
813       ID.AddInteger(SVN->getMaskElt(i));
814     break;
815   }
816   case ISD::TargetBlockAddress:
817   case ISD::BlockAddress: {
818     const BlockAddressSDNode *BA = cast<BlockAddressSDNode>(N);
819     ID.AddPointer(BA->getBlockAddress());
820     ID.AddInteger(BA->getOffset());
821     ID.AddInteger(BA->getTargetFlags());
822     break;
823   }
824   } // end switch (N->getOpcode())
825 
826   // Target specific memory nodes could also have address spaces to check.
827   if (N->isTargetMemoryOpcode())
828     ID.AddInteger(cast<MemSDNode>(N)->getPointerInfo().getAddrSpace());
829 }
830 
831 /// AddNodeIDNode - Generic routine for adding a nodes info to the NodeID
832 /// data.
833 static void AddNodeIDNode(FoldingSetNodeID &ID, const SDNode *N) {
834   AddNodeIDOpcode(ID, N->getOpcode());
835   // Add the return value info.
836   AddNodeIDValueTypes(ID, N->getVTList());
837   // Add the operand info.
838   AddNodeIDOperands(ID, N->ops());
839 
840   // Handle SDNode leafs with special info.
841   AddNodeIDCustom(ID, N);
842 }
843 
844 //===----------------------------------------------------------------------===//
845 //                              SelectionDAG Class
846 //===----------------------------------------------------------------------===//
847 
848 /// doNotCSE - Return true if CSE should not be performed for this node.
849 static bool doNotCSE(SDNode *N) {
850   if (N->getValueType(0) == MVT::Glue)
851     return true; // Never CSE anything that produces a flag.
852 
853   switch (N->getOpcode()) {
854   default: break;
855   case ISD::HANDLENODE:
856   case ISD::EH_LABEL:
857     return true;   // Never CSE these nodes.
858   }
859 
860   // Check that remaining values produced are not flags.
861   for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
862     if (N->getValueType(i) == MVT::Glue)
863       return true; // Never CSE anything that produces a flag.
864 
865   return false;
866 }
867 
868 /// RemoveDeadNodes - This method deletes all unreachable nodes in the
869 /// SelectionDAG.
870 void SelectionDAG::RemoveDeadNodes() {
871   // Create a dummy node (which is not added to allnodes), that adds a reference
872   // to the root node, preventing it from being deleted.
873   HandleSDNode Dummy(getRoot());
874 
875   SmallVector<SDNode*, 128> DeadNodes;
876 
877   // Add all obviously-dead nodes to the DeadNodes worklist.
878   for (SDNode &Node : allnodes())
879     if (Node.use_empty())
880       DeadNodes.push_back(&Node);
881 
882   RemoveDeadNodes(DeadNodes);
883 
884   // If the root changed (e.g. it was a dead load, update the root).
885   setRoot(Dummy.getValue());
886 }
887 
888 /// RemoveDeadNodes - This method deletes the unreachable nodes in the
889 /// given list, and any nodes that become unreachable as a result.
890 void SelectionDAG::RemoveDeadNodes(SmallVectorImpl<SDNode *> &DeadNodes) {
891 
892   // Process the worklist, deleting the nodes and adding their uses to the
893   // worklist.
894   while (!DeadNodes.empty()) {
895     SDNode *N = DeadNodes.pop_back_val();
896     // Skip to next node if we've already managed to delete the node. This could
897     // happen if replacing a node causes a node previously added to the node to
898     // be deleted.
899     if (N->getOpcode() == ISD::DELETED_NODE)
900       continue;
901 
902     for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
903       DUL->NodeDeleted(N, nullptr);
904 
905     // Take the node out of the appropriate CSE map.
906     RemoveNodeFromCSEMaps(N);
907 
908     // Next, brutally remove the operand list.  This is safe to do, as there are
909     // no cycles in the graph.
910     for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) {
911       SDUse &Use = *I++;
912       SDNode *Operand = Use.getNode();
913       Use.set(SDValue());
914 
915       // Now that we removed this operand, see if there are no uses of it left.
916       if (Operand->use_empty())
917         DeadNodes.push_back(Operand);
918     }
919 
920     DeallocateNode(N);
921   }
922 }
923 
924 void SelectionDAG::RemoveDeadNode(SDNode *N){
925   SmallVector<SDNode*, 16> DeadNodes(1, N);
926 
927   // Create a dummy node that adds a reference to the root node, preventing
928   // it from being deleted.  (This matters if the root is an operand of the
929   // dead node.)
930   HandleSDNode Dummy(getRoot());
931 
932   RemoveDeadNodes(DeadNodes);
933 }
934 
935 void SelectionDAG::DeleteNode(SDNode *N) {
936   // First take this out of the appropriate CSE map.
937   RemoveNodeFromCSEMaps(N);
938 
939   // Finally, remove uses due to operands of this node, remove from the
940   // AllNodes list, and delete the node.
941   DeleteNodeNotInCSEMaps(N);
942 }
943 
944 void SelectionDAG::DeleteNodeNotInCSEMaps(SDNode *N) {
945   assert(N->getIterator() != AllNodes.begin() &&
946          "Cannot delete the entry node!");
947   assert(N->use_empty() && "Cannot delete a node that is not dead!");
948 
949   // Drop all of the operands and decrement used node's use counts.
950   N->DropOperands();
951 
952   DeallocateNode(N);
953 }
954 
955 void SDDbgInfo::add(SDDbgValue *V, bool isParameter) {
956   assert(!(V->isVariadic() && isParameter));
957   if (isParameter)
958     ByvalParmDbgValues.push_back(V);
959   else
960     DbgValues.push_back(V);
961   for (const SDNode *Node : V->getSDNodes())
962     if (Node)
963       DbgValMap[Node].push_back(V);
964 }
965 
966 void SDDbgInfo::erase(const SDNode *Node) {
967   DbgValMapType::iterator I = DbgValMap.find(Node);
968   if (I == DbgValMap.end())
969     return;
970   for (auto &Val: I->second)
971     Val->setIsInvalidated();
972   DbgValMap.erase(I);
973 }
974 
975 void SelectionDAG::DeallocateNode(SDNode *N) {
976   // If we have operands, deallocate them.
977   removeOperands(N);
978 
979   NodeAllocator.Deallocate(AllNodes.remove(N));
980 
981   // Set the opcode to DELETED_NODE to help catch bugs when node
982   // memory is reallocated.
983   // FIXME: There are places in SDag that have grown a dependency on the opcode
984   // value in the released node.
985   __asan_unpoison_memory_region(&N->NodeType, sizeof(N->NodeType));
986   N->NodeType = ISD::DELETED_NODE;
987 
988   // If any of the SDDbgValue nodes refer to this SDNode, invalidate
989   // them and forget about that node.
990   DbgInfo->erase(N);
991 }
992 
993 #ifndef NDEBUG
994 /// VerifySDNode - Check the given SDNode.  Aborts if it is invalid.
995 static void VerifySDNode(SDNode *N) {
996   switch (N->getOpcode()) {
997   default:
998     break;
999   case ISD::BUILD_PAIR: {
1000     EVT VT = N->getValueType(0);
1001     assert(N->getNumValues() == 1 && "Too many results!");
1002     assert(!VT.isVector() && (VT.isInteger() || VT.isFloatingPoint()) &&
1003            "Wrong return type!");
1004     assert(N->getNumOperands() == 2 && "Wrong number of operands!");
1005     assert(N->getOperand(0).getValueType() == N->getOperand(1).getValueType() &&
1006            "Mismatched operand types!");
1007     assert(N->getOperand(0).getValueType().isInteger() == VT.isInteger() &&
1008            "Wrong operand type!");
1009     assert(VT.getSizeInBits() == 2 * N->getOperand(0).getValueSizeInBits() &&
1010            "Wrong return type size");
1011     break;
1012   }
1013   case ISD::BUILD_VECTOR: {
1014     assert(N->getNumValues() == 1 && "Too many results!");
1015     assert(N->getValueType(0).isVector() && "Wrong return type!");
1016     assert(N->getNumOperands() == N->getValueType(0).getVectorNumElements() &&
1017            "Wrong number of operands!");
1018     EVT EltVT = N->getValueType(0).getVectorElementType();
1019     for (const SDUse &Op : N->ops()) {
1020       assert((Op.getValueType() == EltVT ||
1021               (EltVT.isInteger() && Op.getValueType().isInteger() &&
1022                EltVT.bitsLE(Op.getValueType()))) &&
1023              "Wrong operand type!");
1024       assert(Op.getValueType() == N->getOperand(0).getValueType() &&
1025              "Operands must all have the same type");
1026     }
1027     break;
1028   }
1029   }
1030 }
1031 #endif // NDEBUG
1032 
1033 /// Insert a newly allocated node into the DAG.
1034 ///
1035 /// Handles insertion into the all nodes list and CSE map, as well as
1036 /// verification and other common operations when a new node is allocated.
1037 void SelectionDAG::InsertNode(SDNode *N) {
1038   AllNodes.push_back(N);
1039 #ifndef NDEBUG
1040   N->PersistentId = NextPersistentId++;
1041   VerifySDNode(N);
1042 #endif
1043   for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
1044     DUL->NodeInserted(N);
1045 }
1046 
1047 /// RemoveNodeFromCSEMaps - Take the specified node out of the CSE map that
1048 /// correspond to it.  This is useful when we're about to delete or repurpose
1049 /// the node.  We don't want future request for structurally identical nodes
1050 /// to return N anymore.
1051 bool SelectionDAG::RemoveNodeFromCSEMaps(SDNode *N) {
1052   bool Erased = false;
1053   switch (N->getOpcode()) {
1054   case ISD::HANDLENODE: return false;  // noop.
1055   case ISD::CONDCODE:
1056     assert(CondCodeNodes[cast<CondCodeSDNode>(N)->get()] &&
1057            "Cond code doesn't exist!");
1058     Erased = CondCodeNodes[cast<CondCodeSDNode>(N)->get()] != nullptr;
1059     CondCodeNodes[cast<CondCodeSDNode>(N)->get()] = nullptr;
1060     break;
1061   case ISD::ExternalSymbol:
1062     Erased = ExternalSymbols.erase(cast<ExternalSymbolSDNode>(N)->getSymbol());
1063     break;
1064   case ISD::TargetExternalSymbol: {
1065     ExternalSymbolSDNode *ESN = cast<ExternalSymbolSDNode>(N);
1066     Erased = TargetExternalSymbols.erase(std::pair<std::string, unsigned>(
1067         ESN->getSymbol(), ESN->getTargetFlags()));
1068     break;
1069   }
1070   case ISD::MCSymbol: {
1071     auto *MCSN = cast<MCSymbolSDNode>(N);
1072     Erased = MCSymbols.erase(MCSN->getMCSymbol());
1073     break;
1074   }
1075   case ISD::VALUETYPE: {
1076     EVT VT = cast<VTSDNode>(N)->getVT();
1077     if (VT.isExtended()) {
1078       Erased = ExtendedValueTypeNodes.erase(VT);
1079     } else {
1080       Erased = ValueTypeNodes[VT.getSimpleVT().SimpleTy] != nullptr;
1081       ValueTypeNodes[VT.getSimpleVT().SimpleTy] = nullptr;
1082     }
1083     break;
1084   }
1085   default:
1086     // Remove it from the CSE Map.
1087     assert(N->getOpcode() != ISD::DELETED_NODE && "DELETED_NODE in CSEMap!");
1088     assert(N->getOpcode() != ISD::EntryToken && "EntryToken in CSEMap!");
1089     Erased = CSEMap.RemoveNode(N);
1090     break;
1091   }
1092 #ifndef NDEBUG
1093   // Verify that the node was actually in one of the CSE maps, unless it has a
1094   // flag result (which cannot be CSE'd) or is one of the special cases that are
1095   // not subject to CSE.
1096   if (!Erased && N->getValueType(N->getNumValues()-1) != MVT::Glue &&
1097       !N->isMachineOpcode() && !doNotCSE(N)) {
1098     N->dump(this);
1099     dbgs() << "\n";
1100     llvm_unreachable("Node is not in map!");
1101   }
1102 #endif
1103   return Erased;
1104 }
1105 
1106 /// AddModifiedNodeToCSEMaps - The specified node has been removed from the CSE
1107 /// maps and modified in place. Add it back to the CSE maps, unless an identical
1108 /// node already exists, in which case transfer all its users to the existing
1109 /// node. This transfer can potentially trigger recursive merging.
1110 void
1111 SelectionDAG::AddModifiedNodeToCSEMaps(SDNode *N) {
1112   // For node types that aren't CSE'd, just act as if no identical node
1113   // already exists.
1114   if (!doNotCSE(N)) {
1115     SDNode *Existing = CSEMap.GetOrInsertNode(N);
1116     if (Existing != N) {
1117       // If there was already an existing matching node, use ReplaceAllUsesWith
1118       // to replace the dead one with the existing one.  This can cause
1119       // recursive merging of other unrelated nodes down the line.
1120       ReplaceAllUsesWith(N, Existing);
1121 
1122       // N is now dead. Inform the listeners and delete it.
1123       for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
1124         DUL->NodeDeleted(N, Existing);
1125       DeleteNodeNotInCSEMaps(N);
1126       return;
1127     }
1128   }
1129 
1130   // If the node doesn't already exist, we updated it.  Inform listeners.
1131   for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
1132     DUL->NodeUpdated(N);
1133 }
1134 
1135 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
1136 /// were replaced with those specified.  If this node is never memoized,
1137 /// return null, otherwise return a pointer to the slot it would take.  If a
1138 /// node already exists with these operands, the slot will be non-null.
1139 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, SDValue Op,
1140                                            void *&InsertPos) {
1141   if (doNotCSE(N))
1142     return nullptr;
1143 
1144   SDValue Ops[] = { Op };
1145   FoldingSetNodeID ID;
1146   AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops);
1147   AddNodeIDCustom(ID, N);
1148   SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos);
1149   if (Node)
1150     Node->intersectFlagsWith(N->getFlags());
1151   return Node;
1152 }
1153 
1154 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
1155 /// were replaced with those specified.  If this node is never memoized,
1156 /// return null, otherwise return a pointer to the slot it would take.  If a
1157 /// node already exists with these operands, the slot will be non-null.
1158 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N,
1159                                            SDValue Op1, SDValue Op2,
1160                                            void *&InsertPos) {
1161   if (doNotCSE(N))
1162     return nullptr;
1163 
1164   SDValue Ops[] = { Op1, Op2 };
1165   FoldingSetNodeID ID;
1166   AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops);
1167   AddNodeIDCustom(ID, N);
1168   SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos);
1169   if (Node)
1170     Node->intersectFlagsWith(N->getFlags());
1171   return Node;
1172 }
1173 
1174 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
1175 /// were replaced with those specified.  If this node is never memoized,
1176 /// return null, otherwise return a pointer to the slot it would take.  If a
1177 /// node already exists with these operands, the slot will be non-null.
1178 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, ArrayRef<SDValue> Ops,
1179                                            void *&InsertPos) {
1180   if (doNotCSE(N))
1181     return nullptr;
1182 
1183   FoldingSetNodeID ID;
1184   AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops);
1185   AddNodeIDCustom(ID, N);
1186   SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos);
1187   if (Node)
1188     Node->intersectFlagsWith(N->getFlags());
1189   return Node;
1190 }
1191 
1192 Align SelectionDAG::getEVTAlign(EVT VT) const {
1193   Type *Ty = VT == MVT::iPTR ?
1194                    PointerType::get(Type::getInt8Ty(*getContext()), 0) :
1195                    VT.getTypeForEVT(*getContext());
1196 
1197   return getDataLayout().getABITypeAlign(Ty);
1198 }
1199 
1200 // EntryNode could meaningfully have debug info if we can find it...
1201 SelectionDAG::SelectionDAG(const TargetMachine &tm, CodeGenOpt::Level OL)
1202     : TM(tm), OptLevel(OL),
1203       EntryNode(ISD::EntryToken, 0, DebugLoc(), getVTList(MVT::Other)),
1204       Root(getEntryNode()) {
1205   InsertNode(&EntryNode);
1206   DbgInfo = new SDDbgInfo();
1207 }
1208 
1209 void SelectionDAG::init(MachineFunction &NewMF,
1210                         OptimizationRemarkEmitter &NewORE,
1211                         Pass *PassPtr, const TargetLibraryInfo *LibraryInfo,
1212                         LegacyDivergenceAnalysis * Divergence,
1213                         ProfileSummaryInfo *PSIin,
1214                         BlockFrequencyInfo *BFIin) {
1215   MF = &NewMF;
1216   SDAGISelPass = PassPtr;
1217   ORE = &NewORE;
1218   TLI = getSubtarget().getTargetLowering();
1219   TSI = getSubtarget().getSelectionDAGInfo();
1220   LibInfo = LibraryInfo;
1221   Context = &MF->getFunction().getContext();
1222   DA = Divergence;
1223   PSI = PSIin;
1224   BFI = BFIin;
1225 }
1226 
1227 SelectionDAG::~SelectionDAG() {
1228   assert(!UpdateListeners && "Dangling registered DAGUpdateListeners");
1229   allnodes_clear();
1230   OperandRecycler.clear(OperandAllocator);
1231   delete DbgInfo;
1232 }
1233 
1234 bool SelectionDAG::shouldOptForSize() const {
1235   return MF->getFunction().hasOptSize() ||
1236       llvm::shouldOptimizeForSize(FLI->MBB->getBasicBlock(), PSI, BFI);
1237 }
1238 
1239 void SelectionDAG::allnodes_clear() {
1240   assert(&*AllNodes.begin() == &EntryNode);
1241   AllNodes.remove(AllNodes.begin());
1242   while (!AllNodes.empty())
1243     DeallocateNode(&AllNodes.front());
1244 #ifndef NDEBUG
1245   NextPersistentId = 0;
1246 #endif
1247 }
1248 
1249 SDNode *SelectionDAG::FindNodeOrInsertPos(const FoldingSetNodeID &ID,
1250                                           void *&InsertPos) {
1251   SDNode *N = CSEMap.FindNodeOrInsertPos(ID, InsertPos);
1252   if (N) {
1253     switch (N->getOpcode()) {
1254     default: break;
1255     case ISD::Constant:
1256     case ISD::ConstantFP:
1257       llvm_unreachable("Querying for Constant and ConstantFP nodes requires "
1258                        "debug location.  Use another overload.");
1259     }
1260   }
1261   return N;
1262 }
1263 
1264 SDNode *SelectionDAG::FindNodeOrInsertPos(const FoldingSetNodeID &ID,
1265                                           const SDLoc &DL, void *&InsertPos) {
1266   SDNode *N = CSEMap.FindNodeOrInsertPos(ID, InsertPos);
1267   if (N) {
1268     switch (N->getOpcode()) {
1269     case ISD::Constant:
1270     case ISD::ConstantFP:
1271       // Erase debug location from the node if the node is used at several
1272       // different places. Do not propagate one location to all uses as it
1273       // will cause a worse single stepping debugging experience.
1274       if (N->getDebugLoc() != DL.getDebugLoc())
1275         N->setDebugLoc(DebugLoc());
1276       break;
1277     default:
1278       // When the node's point of use is located earlier in the instruction
1279       // sequence than its prior point of use, update its debug info to the
1280       // earlier location.
1281       if (DL.getIROrder() && DL.getIROrder() < N->getIROrder())
1282         N->setDebugLoc(DL.getDebugLoc());
1283       break;
1284     }
1285   }
1286   return N;
1287 }
1288 
1289 void SelectionDAG::clear() {
1290   allnodes_clear();
1291   OperandRecycler.clear(OperandAllocator);
1292   OperandAllocator.Reset();
1293   CSEMap.clear();
1294 
1295   ExtendedValueTypeNodes.clear();
1296   ExternalSymbols.clear();
1297   TargetExternalSymbols.clear();
1298   MCSymbols.clear();
1299   SDCallSiteDbgInfo.clear();
1300   std::fill(CondCodeNodes.begin(), CondCodeNodes.end(),
1301             static_cast<CondCodeSDNode*>(nullptr));
1302   std::fill(ValueTypeNodes.begin(), ValueTypeNodes.end(),
1303             static_cast<SDNode*>(nullptr));
1304 
1305   EntryNode.UseList = nullptr;
1306   InsertNode(&EntryNode);
1307   Root = getEntryNode();
1308   DbgInfo->clear();
1309 }
1310 
1311 SDValue SelectionDAG::getFPExtendOrRound(SDValue Op, const SDLoc &DL, EVT VT) {
1312   return VT.bitsGT(Op.getValueType())
1313              ? getNode(ISD::FP_EXTEND, DL, VT, Op)
1314              : getNode(ISD::FP_ROUND, DL, VT, Op, getIntPtrConstant(0, DL));
1315 }
1316 
1317 std::pair<SDValue, SDValue>
1318 SelectionDAG::getStrictFPExtendOrRound(SDValue Op, SDValue Chain,
1319                                        const SDLoc &DL, EVT VT) {
1320   assert(!VT.bitsEq(Op.getValueType()) &&
1321          "Strict no-op FP extend/round not allowed.");
1322   SDValue Res =
1323       VT.bitsGT(Op.getValueType())
1324           ? getNode(ISD::STRICT_FP_EXTEND, DL, {VT, MVT::Other}, {Chain, Op})
1325           : getNode(ISD::STRICT_FP_ROUND, DL, {VT, MVT::Other},
1326                     {Chain, Op, getIntPtrConstant(0, DL)});
1327 
1328   return std::pair<SDValue, SDValue>(Res, SDValue(Res.getNode(), 1));
1329 }
1330 
1331 SDValue SelectionDAG::getAnyExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
1332   return VT.bitsGT(Op.getValueType()) ?
1333     getNode(ISD::ANY_EXTEND, DL, VT, Op) :
1334     getNode(ISD::TRUNCATE, DL, VT, Op);
1335 }
1336 
1337 SDValue SelectionDAG::getSExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
1338   return VT.bitsGT(Op.getValueType()) ?
1339     getNode(ISD::SIGN_EXTEND, DL, VT, Op) :
1340     getNode(ISD::TRUNCATE, DL, VT, Op);
1341 }
1342 
1343 SDValue SelectionDAG::getZExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
1344   return VT.bitsGT(Op.getValueType()) ?
1345     getNode(ISD::ZERO_EXTEND, DL, VT, Op) :
1346     getNode(ISD::TRUNCATE, DL, VT, Op);
1347 }
1348 
1349 SDValue SelectionDAG::getBoolExtOrTrunc(SDValue Op, const SDLoc &SL, EVT VT,
1350                                         EVT OpVT) {
1351   if (VT.bitsLE(Op.getValueType()))
1352     return getNode(ISD::TRUNCATE, SL, VT, Op);
1353 
1354   TargetLowering::BooleanContent BType = TLI->getBooleanContents(OpVT);
1355   return getNode(TLI->getExtendForContent(BType), SL, VT, Op);
1356 }
1357 
1358 SDValue SelectionDAG::getZeroExtendInReg(SDValue Op, const SDLoc &DL, EVT VT) {
1359   EVT OpVT = Op.getValueType();
1360   assert(VT.isInteger() && OpVT.isInteger() &&
1361          "Cannot getZeroExtendInReg FP types");
1362   assert(VT.isVector() == OpVT.isVector() &&
1363          "getZeroExtendInReg type should be vector iff the operand "
1364          "type is vector!");
1365   assert((!VT.isVector() ||
1366           VT.getVectorElementCount() == OpVT.getVectorElementCount()) &&
1367          "Vector element counts must match in getZeroExtendInReg");
1368   assert(VT.bitsLE(OpVT) && "Not extending!");
1369   if (OpVT == VT)
1370     return Op;
1371   APInt Imm = APInt::getLowBitsSet(OpVT.getScalarSizeInBits(),
1372                                    VT.getScalarSizeInBits());
1373   return getNode(ISD::AND, DL, OpVT, Op, getConstant(Imm, DL, OpVT));
1374 }
1375 
1376 SDValue SelectionDAG::getPtrExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
1377   // Only unsigned pointer semantics are supported right now. In the future this
1378   // might delegate to TLI to check pointer signedness.
1379   return getZExtOrTrunc(Op, DL, VT);
1380 }
1381 
1382 SDValue SelectionDAG::getPtrExtendInReg(SDValue Op, const SDLoc &DL, EVT VT) {
1383   // Only unsigned pointer semantics are supported right now. In the future this
1384   // might delegate to TLI to check pointer signedness.
1385   return getZeroExtendInReg(Op, DL, VT);
1386 }
1387 
1388 /// getNOT - Create a bitwise NOT operation as (XOR Val, -1).
1389 SDValue SelectionDAG::getNOT(const SDLoc &DL, SDValue Val, EVT VT) {
1390   return getNode(ISD::XOR, DL, VT, Val, getAllOnesConstant(DL, VT));
1391 }
1392 
1393 SDValue SelectionDAG::getLogicalNOT(const SDLoc &DL, SDValue Val, EVT VT) {
1394   SDValue TrueValue = getBoolConstant(true, DL, VT, VT);
1395   return getNode(ISD::XOR, DL, VT, Val, TrueValue);
1396 }
1397 
1398 SDValue SelectionDAG::getBoolConstant(bool V, const SDLoc &DL, EVT VT,
1399                                       EVT OpVT) {
1400   if (!V)
1401     return getConstant(0, DL, VT);
1402 
1403   switch (TLI->getBooleanContents(OpVT)) {
1404   case TargetLowering::ZeroOrOneBooleanContent:
1405   case TargetLowering::UndefinedBooleanContent:
1406     return getConstant(1, DL, VT);
1407   case TargetLowering::ZeroOrNegativeOneBooleanContent:
1408     return getAllOnesConstant(DL, VT);
1409   }
1410   llvm_unreachable("Unexpected boolean content enum!");
1411 }
1412 
1413 SDValue SelectionDAG::getConstant(uint64_t Val, const SDLoc &DL, EVT VT,
1414                                   bool isT, bool isO) {
1415   EVT EltVT = VT.getScalarType();
1416   assert((EltVT.getSizeInBits() >= 64 ||
1417           (uint64_t)((int64_t)Val >> EltVT.getSizeInBits()) + 1 < 2) &&
1418          "getConstant with a uint64_t value that doesn't fit in the type!");
1419   return getConstant(APInt(EltVT.getSizeInBits(), Val), DL, VT, isT, isO);
1420 }
1421 
1422 SDValue SelectionDAG::getConstant(const APInt &Val, const SDLoc &DL, EVT VT,
1423                                   bool isT, bool isO) {
1424   return getConstant(*ConstantInt::get(*Context, Val), DL, VT, isT, isO);
1425 }
1426 
1427 SDValue SelectionDAG::getConstant(const ConstantInt &Val, const SDLoc &DL,
1428                                   EVT VT, bool isT, bool isO) {
1429   assert(VT.isInteger() && "Cannot create FP integer constant!");
1430 
1431   EVT EltVT = VT.getScalarType();
1432   const ConstantInt *Elt = &Val;
1433 
1434   // In some cases the vector type is legal but the element type is illegal and
1435   // needs to be promoted, for example v8i8 on ARM.  In this case, promote the
1436   // inserted value (the type does not need to match the vector element type).
1437   // Any extra bits introduced will be truncated away.
1438   if (VT.isVector() && TLI->getTypeAction(*getContext(), EltVT) ==
1439                            TargetLowering::TypePromoteInteger) {
1440     EltVT = TLI->getTypeToTransformTo(*getContext(), EltVT);
1441     APInt NewVal = Elt->getValue().zextOrTrunc(EltVT.getSizeInBits());
1442     Elt = ConstantInt::get(*getContext(), NewVal);
1443   }
1444   // In other cases the element type is illegal and needs to be expanded, for
1445   // example v2i64 on MIPS32. In this case, find the nearest legal type, split
1446   // the value into n parts and use a vector type with n-times the elements.
1447   // Then bitcast to the type requested.
1448   // Legalizing constants too early makes the DAGCombiner's job harder so we
1449   // only legalize if the DAG tells us we must produce legal types.
1450   else if (NewNodesMustHaveLegalTypes && VT.isVector() &&
1451            TLI->getTypeAction(*getContext(), EltVT) ==
1452                TargetLowering::TypeExpandInteger) {
1453     const APInt &NewVal = Elt->getValue();
1454     EVT ViaEltVT = TLI->getTypeToTransformTo(*getContext(), EltVT);
1455     unsigned ViaEltSizeInBits = ViaEltVT.getSizeInBits();
1456 
1457     // For scalable vectors, try to use a SPLAT_VECTOR_PARTS node.
1458     if (VT.isScalableVector()) {
1459       assert(EltVT.getSizeInBits() % ViaEltSizeInBits == 0 &&
1460              "Can only handle an even split!");
1461       unsigned Parts = EltVT.getSizeInBits() / ViaEltSizeInBits;
1462 
1463       SmallVector<SDValue, 2> ScalarParts;
1464       for (unsigned i = 0; i != Parts; ++i)
1465         ScalarParts.push_back(getConstant(
1466             NewVal.extractBits(ViaEltSizeInBits, i * ViaEltSizeInBits), DL,
1467             ViaEltVT, isT, isO));
1468 
1469       return getNode(ISD::SPLAT_VECTOR_PARTS, DL, VT, ScalarParts);
1470     }
1471 
1472     unsigned ViaVecNumElts = VT.getSizeInBits() / ViaEltSizeInBits;
1473     EVT ViaVecVT = EVT::getVectorVT(*getContext(), ViaEltVT, ViaVecNumElts);
1474 
1475     // Check the temporary vector is the correct size. If this fails then
1476     // getTypeToTransformTo() probably returned a type whose size (in bits)
1477     // isn't a power-of-2 factor of the requested type size.
1478     assert(ViaVecVT.getSizeInBits() == VT.getSizeInBits());
1479 
1480     SmallVector<SDValue, 2> EltParts;
1481     for (unsigned i = 0; i < ViaVecNumElts / VT.getVectorNumElements(); ++i)
1482       EltParts.push_back(getConstant(
1483           NewVal.extractBits(ViaEltSizeInBits, i * ViaEltSizeInBits), DL,
1484           ViaEltVT, isT, isO));
1485 
1486     // EltParts is currently in little endian order. If we actually want
1487     // big-endian order then reverse it now.
1488     if (getDataLayout().isBigEndian())
1489       std::reverse(EltParts.begin(), EltParts.end());
1490 
1491     // The elements must be reversed when the element order is different
1492     // to the endianness of the elements (because the BITCAST is itself a
1493     // vector shuffle in this situation). However, we do not need any code to
1494     // perform this reversal because getConstant() is producing a vector
1495     // splat.
1496     // This situation occurs in MIPS MSA.
1497 
1498     SmallVector<SDValue, 8> Ops;
1499     for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
1500       llvm::append_range(Ops, EltParts);
1501 
1502     SDValue V =
1503         getNode(ISD::BITCAST, DL, VT, getBuildVector(ViaVecVT, DL, Ops));
1504     return V;
1505   }
1506 
1507   assert(Elt->getBitWidth() == EltVT.getSizeInBits() &&
1508          "APInt size does not match type size!");
1509   unsigned Opc = isT ? ISD::TargetConstant : ISD::Constant;
1510   FoldingSetNodeID ID;
1511   AddNodeIDNode(ID, Opc, getVTList(EltVT), None);
1512   ID.AddPointer(Elt);
1513   ID.AddBoolean(isO);
1514   void *IP = nullptr;
1515   SDNode *N = nullptr;
1516   if ((N = FindNodeOrInsertPos(ID, DL, IP)))
1517     if (!VT.isVector())
1518       return SDValue(N, 0);
1519 
1520   if (!N) {
1521     N = newSDNode<ConstantSDNode>(isT, isO, Elt, EltVT);
1522     CSEMap.InsertNode(N, IP);
1523     InsertNode(N);
1524     NewSDValueDbgMsg(SDValue(N, 0), "Creating constant: ", this);
1525   }
1526 
1527   SDValue Result(N, 0);
1528   if (VT.isScalableVector())
1529     Result = getSplatVector(VT, DL, Result);
1530   else if (VT.isVector())
1531     Result = getSplatBuildVector(VT, DL, Result);
1532 
1533   return Result;
1534 }
1535 
1536 SDValue SelectionDAG::getIntPtrConstant(uint64_t Val, const SDLoc &DL,
1537                                         bool isTarget) {
1538   return getConstant(Val, DL, TLI->getPointerTy(getDataLayout()), isTarget);
1539 }
1540 
1541 SDValue SelectionDAG::getShiftAmountConstant(uint64_t Val, EVT VT,
1542                                              const SDLoc &DL, bool LegalTypes) {
1543   assert(VT.isInteger() && "Shift amount is not an integer type!");
1544   EVT ShiftVT = TLI->getShiftAmountTy(VT, getDataLayout(), LegalTypes);
1545   return getConstant(Val, DL, ShiftVT);
1546 }
1547 
1548 SDValue SelectionDAG::getVectorIdxConstant(uint64_t Val, const SDLoc &DL,
1549                                            bool isTarget) {
1550   return getConstant(Val, DL, TLI->getVectorIdxTy(getDataLayout()), isTarget);
1551 }
1552 
1553 SDValue SelectionDAG::getConstantFP(const APFloat &V, const SDLoc &DL, EVT VT,
1554                                     bool isTarget) {
1555   return getConstantFP(*ConstantFP::get(*getContext(), V), DL, VT, isTarget);
1556 }
1557 
1558 SDValue SelectionDAG::getConstantFP(const ConstantFP &V, const SDLoc &DL,
1559                                     EVT VT, bool isTarget) {
1560   assert(VT.isFloatingPoint() && "Cannot create integer FP constant!");
1561 
1562   EVT EltVT = VT.getScalarType();
1563 
1564   // Do the map lookup using the actual bit pattern for the floating point
1565   // value, so that we don't have problems with 0.0 comparing equal to -0.0, and
1566   // we don't have issues with SNANs.
1567   unsigned Opc = isTarget ? ISD::TargetConstantFP : ISD::ConstantFP;
1568   FoldingSetNodeID ID;
1569   AddNodeIDNode(ID, Opc, getVTList(EltVT), None);
1570   ID.AddPointer(&V);
1571   void *IP = nullptr;
1572   SDNode *N = nullptr;
1573   if ((N = FindNodeOrInsertPos(ID, DL, IP)))
1574     if (!VT.isVector())
1575       return SDValue(N, 0);
1576 
1577   if (!N) {
1578     N = newSDNode<ConstantFPSDNode>(isTarget, &V, EltVT);
1579     CSEMap.InsertNode(N, IP);
1580     InsertNode(N);
1581   }
1582 
1583   SDValue Result(N, 0);
1584   if (VT.isScalableVector())
1585     Result = getSplatVector(VT, DL, Result);
1586   else if (VT.isVector())
1587     Result = getSplatBuildVector(VT, DL, Result);
1588   NewSDValueDbgMsg(Result, "Creating fp constant: ", this);
1589   return Result;
1590 }
1591 
1592 SDValue SelectionDAG::getConstantFP(double Val, const SDLoc &DL, EVT VT,
1593                                     bool isTarget) {
1594   EVT EltVT = VT.getScalarType();
1595   if (EltVT == MVT::f32)
1596     return getConstantFP(APFloat((float)Val), DL, VT, isTarget);
1597   if (EltVT == MVT::f64)
1598     return getConstantFP(APFloat(Val), DL, VT, isTarget);
1599   if (EltVT == MVT::f80 || EltVT == MVT::f128 || EltVT == MVT::ppcf128 ||
1600       EltVT == MVT::f16 || EltVT == MVT::bf16) {
1601     bool Ignored;
1602     APFloat APF = APFloat(Val);
1603     APF.convert(EVTToAPFloatSemantics(EltVT), APFloat::rmNearestTiesToEven,
1604                 &Ignored);
1605     return getConstantFP(APF, DL, VT, isTarget);
1606   }
1607   llvm_unreachable("Unsupported type in getConstantFP");
1608 }
1609 
1610 SDValue SelectionDAG::getGlobalAddress(const GlobalValue *GV, const SDLoc &DL,
1611                                        EVT VT, int64_t Offset, bool isTargetGA,
1612                                        unsigned TargetFlags) {
1613   assert((TargetFlags == 0 || isTargetGA) &&
1614          "Cannot set target flags on target-independent globals");
1615 
1616   // Truncate (with sign-extension) the offset value to the pointer size.
1617   unsigned BitWidth = getDataLayout().getPointerTypeSizeInBits(GV->getType());
1618   if (BitWidth < 64)
1619     Offset = SignExtend64(Offset, BitWidth);
1620 
1621   unsigned Opc;
1622   if (GV->isThreadLocal())
1623     Opc = isTargetGA ? ISD::TargetGlobalTLSAddress : ISD::GlobalTLSAddress;
1624   else
1625     Opc = isTargetGA ? ISD::TargetGlobalAddress : ISD::GlobalAddress;
1626 
1627   FoldingSetNodeID ID;
1628   AddNodeIDNode(ID, Opc, getVTList(VT), None);
1629   ID.AddPointer(GV);
1630   ID.AddInteger(Offset);
1631   ID.AddInteger(TargetFlags);
1632   void *IP = nullptr;
1633   if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
1634     return SDValue(E, 0);
1635 
1636   auto *N = newSDNode<GlobalAddressSDNode>(
1637       Opc, DL.getIROrder(), DL.getDebugLoc(), GV, VT, Offset, TargetFlags);
1638   CSEMap.InsertNode(N, IP);
1639     InsertNode(N);
1640   return SDValue(N, 0);
1641 }
1642 
1643 SDValue SelectionDAG::getFrameIndex(int FI, EVT VT, bool isTarget) {
1644   unsigned Opc = isTarget ? ISD::TargetFrameIndex : ISD::FrameIndex;
1645   FoldingSetNodeID ID;
1646   AddNodeIDNode(ID, Opc, getVTList(VT), None);
1647   ID.AddInteger(FI);
1648   void *IP = nullptr;
1649   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1650     return SDValue(E, 0);
1651 
1652   auto *N = newSDNode<FrameIndexSDNode>(FI, VT, isTarget);
1653   CSEMap.InsertNode(N, IP);
1654   InsertNode(N);
1655   return SDValue(N, 0);
1656 }
1657 
1658 SDValue SelectionDAG::getJumpTable(int JTI, EVT VT, bool isTarget,
1659                                    unsigned TargetFlags) {
1660   assert((TargetFlags == 0 || isTarget) &&
1661          "Cannot set target flags on target-independent jump tables");
1662   unsigned Opc = isTarget ? ISD::TargetJumpTable : ISD::JumpTable;
1663   FoldingSetNodeID ID;
1664   AddNodeIDNode(ID, Opc, getVTList(VT), None);
1665   ID.AddInteger(JTI);
1666   ID.AddInteger(TargetFlags);
1667   void *IP = nullptr;
1668   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1669     return SDValue(E, 0);
1670 
1671   auto *N = newSDNode<JumpTableSDNode>(JTI, VT, isTarget, TargetFlags);
1672   CSEMap.InsertNode(N, IP);
1673   InsertNode(N);
1674   return SDValue(N, 0);
1675 }
1676 
1677 SDValue SelectionDAG::getConstantPool(const Constant *C, EVT VT,
1678                                       MaybeAlign Alignment, int Offset,
1679                                       bool isTarget, unsigned TargetFlags) {
1680   assert((TargetFlags == 0 || isTarget) &&
1681          "Cannot set target flags on target-independent globals");
1682   if (!Alignment)
1683     Alignment = shouldOptForSize()
1684                     ? getDataLayout().getABITypeAlign(C->getType())
1685                     : getDataLayout().getPrefTypeAlign(C->getType());
1686   unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
1687   FoldingSetNodeID ID;
1688   AddNodeIDNode(ID, Opc, getVTList(VT), None);
1689   ID.AddInteger(Alignment->value());
1690   ID.AddInteger(Offset);
1691   ID.AddPointer(C);
1692   ID.AddInteger(TargetFlags);
1693   void *IP = nullptr;
1694   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1695     return SDValue(E, 0);
1696 
1697   auto *N = newSDNode<ConstantPoolSDNode>(isTarget, C, VT, Offset, *Alignment,
1698                                           TargetFlags);
1699   CSEMap.InsertNode(N, IP);
1700   InsertNode(N);
1701   SDValue V = SDValue(N, 0);
1702   NewSDValueDbgMsg(V, "Creating new constant pool: ", this);
1703   return V;
1704 }
1705 
1706 SDValue SelectionDAG::getConstantPool(MachineConstantPoolValue *C, EVT VT,
1707                                       MaybeAlign Alignment, int Offset,
1708                                       bool isTarget, unsigned TargetFlags) {
1709   assert((TargetFlags == 0 || isTarget) &&
1710          "Cannot set target flags on target-independent globals");
1711   if (!Alignment)
1712     Alignment = getDataLayout().getPrefTypeAlign(C->getType());
1713   unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
1714   FoldingSetNodeID ID;
1715   AddNodeIDNode(ID, Opc, getVTList(VT), None);
1716   ID.AddInteger(Alignment->value());
1717   ID.AddInteger(Offset);
1718   C->addSelectionDAGCSEId(ID);
1719   ID.AddInteger(TargetFlags);
1720   void *IP = nullptr;
1721   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1722     return SDValue(E, 0);
1723 
1724   auto *N = newSDNode<ConstantPoolSDNode>(isTarget, C, VT, Offset, *Alignment,
1725                                           TargetFlags);
1726   CSEMap.InsertNode(N, IP);
1727   InsertNode(N);
1728   return SDValue(N, 0);
1729 }
1730 
1731 SDValue SelectionDAG::getTargetIndex(int Index, EVT VT, int64_t Offset,
1732                                      unsigned TargetFlags) {
1733   FoldingSetNodeID ID;
1734   AddNodeIDNode(ID, ISD::TargetIndex, getVTList(VT), None);
1735   ID.AddInteger(Index);
1736   ID.AddInteger(Offset);
1737   ID.AddInteger(TargetFlags);
1738   void *IP = nullptr;
1739   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1740     return SDValue(E, 0);
1741 
1742   auto *N = newSDNode<TargetIndexSDNode>(Index, VT, Offset, TargetFlags);
1743   CSEMap.InsertNode(N, IP);
1744   InsertNode(N);
1745   return SDValue(N, 0);
1746 }
1747 
1748 SDValue SelectionDAG::getBasicBlock(MachineBasicBlock *MBB) {
1749   FoldingSetNodeID ID;
1750   AddNodeIDNode(ID, ISD::BasicBlock, getVTList(MVT::Other), None);
1751   ID.AddPointer(MBB);
1752   void *IP = nullptr;
1753   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1754     return SDValue(E, 0);
1755 
1756   auto *N = newSDNode<BasicBlockSDNode>(MBB);
1757   CSEMap.InsertNode(N, IP);
1758   InsertNode(N);
1759   return SDValue(N, 0);
1760 }
1761 
1762 SDValue SelectionDAG::getValueType(EVT VT) {
1763   if (VT.isSimple() && (unsigned)VT.getSimpleVT().SimpleTy >=
1764       ValueTypeNodes.size())
1765     ValueTypeNodes.resize(VT.getSimpleVT().SimpleTy+1);
1766 
1767   SDNode *&N = VT.isExtended() ?
1768     ExtendedValueTypeNodes[VT] : ValueTypeNodes[VT.getSimpleVT().SimpleTy];
1769 
1770   if (N) return SDValue(N, 0);
1771   N = newSDNode<VTSDNode>(VT);
1772   InsertNode(N);
1773   return SDValue(N, 0);
1774 }
1775 
1776 SDValue SelectionDAG::getExternalSymbol(const char *Sym, EVT VT) {
1777   SDNode *&N = ExternalSymbols[Sym];
1778   if (N) return SDValue(N, 0);
1779   N = newSDNode<ExternalSymbolSDNode>(false, Sym, 0, VT);
1780   InsertNode(N);
1781   return SDValue(N, 0);
1782 }
1783 
1784 SDValue SelectionDAG::getMCSymbol(MCSymbol *Sym, EVT VT) {
1785   SDNode *&N = MCSymbols[Sym];
1786   if (N)
1787     return SDValue(N, 0);
1788   N = newSDNode<MCSymbolSDNode>(Sym, VT);
1789   InsertNode(N);
1790   return SDValue(N, 0);
1791 }
1792 
1793 SDValue SelectionDAG::getTargetExternalSymbol(const char *Sym, EVT VT,
1794                                               unsigned TargetFlags) {
1795   SDNode *&N =
1796       TargetExternalSymbols[std::pair<std::string, unsigned>(Sym, TargetFlags)];
1797   if (N) return SDValue(N, 0);
1798   N = newSDNode<ExternalSymbolSDNode>(true, Sym, TargetFlags, VT);
1799   InsertNode(N);
1800   return SDValue(N, 0);
1801 }
1802 
1803 SDValue SelectionDAG::getCondCode(ISD::CondCode Cond) {
1804   if ((unsigned)Cond >= CondCodeNodes.size())
1805     CondCodeNodes.resize(Cond+1);
1806 
1807   if (!CondCodeNodes[Cond]) {
1808     auto *N = newSDNode<CondCodeSDNode>(Cond);
1809     CondCodeNodes[Cond] = N;
1810     InsertNode(N);
1811   }
1812 
1813   return SDValue(CondCodeNodes[Cond], 0);
1814 }
1815 
1816 SDValue SelectionDAG::getStepVector(const SDLoc &DL, EVT ResVT) {
1817   APInt One(ResVT.getScalarSizeInBits(), 1);
1818   return getStepVector(DL, ResVT, One);
1819 }
1820 
1821 SDValue SelectionDAG::getStepVector(const SDLoc &DL, EVT ResVT, APInt StepVal) {
1822   assert(ResVT.getScalarSizeInBits() == StepVal.getBitWidth());
1823   if (ResVT.isScalableVector())
1824     return getNode(
1825         ISD::STEP_VECTOR, DL, ResVT,
1826         getTargetConstant(StepVal, DL, ResVT.getVectorElementType()));
1827 
1828   SmallVector<SDValue, 16> OpsStepConstants;
1829   for (uint64_t i = 0; i < ResVT.getVectorNumElements(); i++)
1830     OpsStepConstants.push_back(
1831         getConstant(StepVal * i, DL, ResVT.getVectorElementType()));
1832   return getBuildVector(ResVT, DL, OpsStepConstants);
1833 }
1834 
1835 /// Swaps the values of N1 and N2. Swaps all indices in the shuffle mask M that
1836 /// point at N1 to point at N2 and indices that point at N2 to point at N1.
1837 static void commuteShuffle(SDValue &N1, SDValue &N2, MutableArrayRef<int> M) {
1838   std::swap(N1, N2);
1839   ShuffleVectorSDNode::commuteMask(M);
1840 }
1841 
1842 SDValue SelectionDAG::getVectorShuffle(EVT VT, const SDLoc &dl, SDValue N1,
1843                                        SDValue N2, ArrayRef<int> Mask) {
1844   assert(VT.getVectorNumElements() == Mask.size() &&
1845          "Must have the same number of vector elements as mask elements!");
1846   assert(VT == N1.getValueType() && VT == N2.getValueType() &&
1847          "Invalid VECTOR_SHUFFLE");
1848 
1849   // Canonicalize shuffle undef, undef -> undef
1850   if (N1.isUndef() && N2.isUndef())
1851     return getUNDEF(VT);
1852 
1853   // Validate that all indices in Mask are within the range of the elements
1854   // input to the shuffle.
1855   int NElts = Mask.size();
1856   assert(llvm::all_of(Mask,
1857                       [&](int M) { return M < (NElts * 2) && M >= -1; }) &&
1858          "Index out of range");
1859 
1860   // Copy the mask so we can do any needed cleanup.
1861   SmallVector<int, 8> MaskVec(Mask.begin(), Mask.end());
1862 
1863   // Canonicalize shuffle v, v -> v, undef
1864   if (N1 == N2) {
1865     N2 = getUNDEF(VT);
1866     for (int i = 0; i != NElts; ++i)
1867       if (MaskVec[i] >= NElts) MaskVec[i] -= NElts;
1868   }
1869 
1870   // Canonicalize shuffle undef, v -> v, undef.  Commute the shuffle mask.
1871   if (N1.isUndef())
1872     commuteShuffle(N1, N2, MaskVec);
1873 
1874   if (TLI->hasVectorBlend()) {
1875     // If shuffling a splat, try to blend the splat instead. We do this here so
1876     // that even when this arises during lowering we don't have to re-handle it.
1877     auto BlendSplat = [&](BuildVectorSDNode *BV, int Offset) {
1878       BitVector UndefElements;
1879       SDValue Splat = BV->getSplatValue(&UndefElements);
1880       if (!Splat)
1881         return;
1882 
1883       for (int i = 0; i < NElts; ++i) {
1884         if (MaskVec[i] < Offset || MaskVec[i] >= (Offset + NElts))
1885           continue;
1886 
1887         // If this input comes from undef, mark it as such.
1888         if (UndefElements[MaskVec[i] - Offset]) {
1889           MaskVec[i] = -1;
1890           continue;
1891         }
1892 
1893         // If we can blend a non-undef lane, use that instead.
1894         if (!UndefElements[i])
1895           MaskVec[i] = i + Offset;
1896       }
1897     };
1898     if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
1899       BlendSplat(N1BV, 0);
1900     if (auto *N2BV = dyn_cast<BuildVectorSDNode>(N2))
1901       BlendSplat(N2BV, NElts);
1902   }
1903 
1904   // Canonicalize all index into lhs, -> shuffle lhs, undef
1905   // Canonicalize all index into rhs, -> shuffle rhs, undef
1906   bool AllLHS = true, AllRHS = true;
1907   bool N2Undef = N2.isUndef();
1908   for (int i = 0; i != NElts; ++i) {
1909     if (MaskVec[i] >= NElts) {
1910       if (N2Undef)
1911         MaskVec[i] = -1;
1912       else
1913         AllLHS = false;
1914     } else if (MaskVec[i] >= 0) {
1915       AllRHS = false;
1916     }
1917   }
1918   if (AllLHS && AllRHS)
1919     return getUNDEF(VT);
1920   if (AllLHS && !N2Undef)
1921     N2 = getUNDEF(VT);
1922   if (AllRHS) {
1923     N1 = getUNDEF(VT);
1924     commuteShuffle(N1, N2, MaskVec);
1925   }
1926   // Reset our undef status after accounting for the mask.
1927   N2Undef = N2.isUndef();
1928   // Re-check whether both sides ended up undef.
1929   if (N1.isUndef() && N2Undef)
1930     return getUNDEF(VT);
1931 
1932   // If Identity shuffle return that node.
1933   bool Identity = true, AllSame = true;
1934   for (int i = 0; i != NElts; ++i) {
1935     if (MaskVec[i] >= 0 && MaskVec[i] != i) Identity = false;
1936     if (MaskVec[i] != MaskVec[0]) AllSame = false;
1937   }
1938   if (Identity && NElts)
1939     return N1;
1940 
1941   // Shuffling a constant splat doesn't change the result.
1942   if (N2Undef) {
1943     SDValue V = N1;
1944 
1945     // Look through any bitcasts. We check that these don't change the number
1946     // (and size) of elements and just changes their types.
1947     while (V.getOpcode() == ISD::BITCAST)
1948       V = V->getOperand(0);
1949 
1950     // A splat should always show up as a build vector node.
1951     if (auto *BV = dyn_cast<BuildVectorSDNode>(V)) {
1952       BitVector UndefElements;
1953       SDValue Splat = BV->getSplatValue(&UndefElements);
1954       // If this is a splat of an undef, shuffling it is also undef.
1955       if (Splat && Splat.isUndef())
1956         return getUNDEF(VT);
1957 
1958       bool SameNumElts =
1959           V.getValueType().getVectorNumElements() == VT.getVectorNumElements();
1960 
1961       // We only have a splat which can skip shuffles if there is a splatted
1962       // value and no undef lanes rearranged by the shuffle.
1963       if (Splat && UndefElements.none()) {
1964         // Splat of <x, x, ..., x>, return <x, x, ..., x>, provided that the
1965         // number of elements match or the value splatted is a zero constant.
1966         if (SameNumElts)
1967           return N1;
1968         if (auto *C = dyn_cast<ConstantSDNode>(Splat))
1969           if (C->isZero())
1970             return N1;
1971       }
1972 
1973       // If the shuffle itself creates a splat, build the vector directly.
1974       if (AllSame && SameNumElts) {
1975         EVT BuildVT = BV->getValueType(0);
1976         const SDValue &Splatted = BV->getOperand(MaskVec[0]);
1977         SDValue NewBV = getSplatBuildVector(BuildVT, dl, Splatted);
1978 
1979         // We may have jumped through bitcasts, so the type of the
1980         // BUILD_VECTOR may not match the type of the shuffle.
1981         if (BuildVT != VT)
1982           NewBV = getNode(ISD::BITCAST, dl, VT, NewBV);
1983         return NewBV;
1984       }
1985     }
1986   }
1987 
1988   FoldingSetNodeID ID;
1989   SDValue Ops[2] = { N1, N2 };
1990   AddNodeIDNode(ID, ISD::VECTOR_SHUFFLE, getVTList(VT), Ops);
1991   for (int i = 0; i != NElts; ++i)
1992     ID.AddInteger(MaskVec[i]);
1993 
1994   void* IP = nullptr;
1995   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
1996     return SDValue(E, 0);
1997 
1998   // Allocate the mask array for the node out of the BumpPtrAllocator, since
1999   // SDNode doesn't have access to it.  This memory will be "leaked" when
2000   // the node is deallocated, but recovered when the NodeAllocator is released.
2001   int *MaskAlloc = OperandAllocator.Allocate<int>(NElts);
2002   llvm::copy(MaskVec, MaskAlloc);
2003 
2004   auto *N = newSDNode<ShuffleVectorSDNode>(VT, dl.getIROrder(),
2005                                            dl.getDebugLoc(), MaskAlloc);
2006   createOperands(N, Ops);
2007 
2008   CSEMap.InsertNode(N, IP);
2009   InsertNode(N);
2010   SDValue V = SDValue(N, 0);
2011   NewSDValueDbgMsg(V, "Creating new node: ", this);
2012   return V;
2013 }
2014 
2015 SDValue SelectionDAG::getCommutedVectorShuffle(const ShuffleVectorSDNode &SV) {
2016   EVT VT = SV.getValueType(0);
2017   SmallVector<int, 8> MaskVec(SV.getMask().begin(), SV.getMask().end());
2018   ShuffleVectorSDNode::commuteMask(MaskVec);
2019 
2020   SDValue Op0 = SV.getOperand(0);
2021   SDValue Op1 = SV.getOperand(1);
2022   return getVectorShuffle(VT, SDLoc(&SV), Op1, Op0, MaskVec);
2023 }
2024 
2025 SDValue SelectionDAG::getRegister(unsigned RegNo, EVT VT) {
2026   FoldingSetNodeID ID;
2027   AddNodeIDNode(ID, ISD::Register, getVTList(VT), None);
2028   ID.AddInteger(RegNo);
2029   void *IP = nullptr;
2030   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2031     return SDValue(E, 0);
2032 
2033   auto *N = newSDNode<RegisterSDNode>(RegNo, VT);
2034   N->SDNodeBits.IsDivergent = TLI->isSDNodeSourceOfDivergence(N, FLI, DA);
2035   CSEMap.InsertNode(N, IP);
2036   InsertNode(N);
2037   return SDValue(N, 0);
2038 }
2039 
2040 SDValue SelectionDAG::getRegisterMask(const uint32_t *RegMask) {
2041   FoldingSetNodeID ID;
2042   AddNodeIDNode(ID, ISD::RegisterMask, getVTList(MVT::Untyped), None);
2043   ID.AddPointer(RegMask);
2044   void *IP = nullptr;
2045   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2046     return SDValue(E, 0);
2047 
2048   auto *N = newSDNode<RegisterMaskSDNode>(RegMask);
2049   CSEMap.InsertNode(N, IP);
2050   InsertNode(N);
2051   return SDValue(N, 0);
2052 }
2053 
2054 SDValue SelectionDAG::getEHLabel(const SDLoc &dl, SDValue Root,
2055                                  MCSymbol *Label) {
2056   return getLabelNode(ISD::EH_LABEL, dl, Root, Label);
2057 }
2058 
2059 SDValue SelectionDAG::getLabelNode(unsigned Opcode, const SDLoc &dl,
2060                                    SDValue Root, MCSymbol *Label) {
2061   FoldingSetNodeID ID;
2062   SDValue Ops[] = { Root };
2063   AddNodeIDNode(ID, Opcode, getVTList(MVT::Other), Ops);
2064   ID.AddPointer(Label);
2065   void *IP = nullptr;
2066   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2067     return SDValue(E, 0);
2068 
2069   auto *N =
2070       newSDNode<LabelSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(), Label);
2071   createOperands(N, Ops);
2072 
2073   CSEMap.InsertNode(N, IP);
2074   InsertNode(N);
2075   return SDValue(N, 0);
2076 }
2077 
2078 SDValue SelectionDAG::getBlockAddress(const BlockAddress *BA, EVT VT,
2079                                       int64_t Offset, bool isTarget,
2080                                       unsigned TargetFlags) {
2081   unsigned Opc = isTarget ? ISD::TargetBlockAddress : ISD::BlockAddress;
2082 
2083   FoldingSetNodeID ID;
2084   AddNodeIDNode(ID, Opc, getVTList(VT), None);
2085   ID.AddPointer(BA);
2086   ID.AddInteger(Offset);
2087   ID.AddInteger(TargetFlags);
2088   void *IP = nullptr;
2089   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2090     return SDValue(E, 0);
2091 
2092   auto *N = newSDNode<BlockAddressSDNode>(Opc, VT, BA, Offset, TargetFlags);
2093   CSEMap.InsertNode(N, IP);
2094   InsertNode(N);
2095   return SDValue(N, 0);
2096 }
2097 
2098 SDValue SelectionDAG::getSrcValue(const Value *V) {
2099   FoldingSetNodeID ID;
2100   AddNodeIDNode(ID, ISD::SRCVALUE, getVTList(MVT::Other), None);
2101   ID.AddPointer(V);
2102 
2103   void *IP = nullptr;
2104   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2105     return SDValue(E, 0);
2106 
2107   auto *N = newSDNode<SrcValueSDNode>(V);
2108   CSEMap.InsertNode(N, IP);
2109   InsertNode(N);
2110   return SDValue(N, 0);
2111 }
2112 
2113 SDValue SelectionDAG::getMDNode(const MDNode *MD) {
2114   FoldingSetNodeID ID;
2115   AddNodeIDNode(ID, ISD::MDNODE_SDNODE, getVTList(MVT::Other), None);
2116   ID.AddPointer(MD);
2117 
2118   void *IP = nullptr;
2119   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2120     return SDValue(E, 0);
2121 
2122   auto *N = newSDNode<MDNodeSDNode>(MD);
2123   CSEMap.InsertNode(N, IP);
2124   InsertNode(N);
2125   return SDValue(N, 0);
2126 }
2127 
2128 SDValue SelectionDAG::getBitcast(EVT VT, SDValue V) {
2129   if (VT == V.getValueType())
2130     return V;
2131 
2132   return getNode(ISD::BITCAST, SDLoc(V), VT, V);
2133 }
2134 
2135 SDValue SelectionDAG::getAddrSpaceCast(const SDLoc &dl, EVT VT, SDValue Ptr,
2136                                        unsigned SrcAS, unsigned DestAS) {
2137   SDValue Ops[] = {Ptr};
2138   FoldingSetNodeID ID;
2139   AddNodeIDNode(ID, ISD::ADDRSPACECAST, getVTList(VT), Ops);
2140   ID.AddInteger(SrcAS);
2141   ID.AddInteger(DestAS);
2142 
2143   void *IP = nullptr;
2144   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
2145     return SDValue(E, 0);
2146 
2147   auto *N = newSDNode<AddrSpaceCastSDNode>(dl.getIROrder(), dl.getDebugLoc(),
2148                                            VT, SrcAS, DestAS);
2149   createOperands(N, Ops);
2150 
2151   CSEMap.InsertNode(N, IP);
2152   InsertNode(N);
2153   return SDValue(N, 0);
2154 }
2155 
2156 SDValue SelectionDAG::getFreeze(SDValue V) {
2157   return getNode(ISD::FREEZE, SDLoc(V), V.getValueType(), V);
2158 }
2159 
2160 /// getShiftAmountOperand - Return the specified value casted to
2161 /// the target's desired shift amount type.
2162 SDValue SelectionDAG::getShiftAmountOperand(EVT LHSTy, SDValue Op) {
2163   EVT OpTy = Op.getValueType();
2164   EVT ShTy = TLI->getShiftAmountTy(LHSTy, getDataLayout());
2165   if (OpTy == ShTy || OpTy.isVector()) return Op;
2166 
2167   return getZExtOrTrunc(Op, SDLoc(Op), ShTy);
2168 }
2169 
2170 SDValue SelectionDAG::expandVAArg(SDNode *Node) {
2171   SDLoc dl(Node);
2172   const TargetLowering &TLI = getTargetLoweringInfo();
2173   const Value *V = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
2174   EVT VT = Node->getValueType(0);
2175   SDValue Tmp1 = Node->getOperand(0);
2176   SDValue Tmp2 = Node->getOperand(1);
2177   const MaybeAlign MA(Node->getConstantOperandVal(3));
2178 
2179   SDValue VAListLoad = getLoad(TLI.getPointerTy(getDataLayout()), dl, Tmp1,
2180                                Tmp2, MachinePointerInfo(V));
2181   SDValue VAList = VAListLoad;
2182 
2183   if (MA && *MA > TLI.getMinStackArgumentAlignment()) {
2184     VAList = getNode(ISD::ADD, dl, VAList.getValueType(), VAList,
2185                      getConstant(MA->value() - 1, dl, VAList.getValueType()));
2186 
2187     VAList =
2188         getNode(ISD::AND, dl, VAList.getValueType(), VAList,
2189                 getConstant(-(int64_t)MA->value(), dl, VAList.getValueType()));
2190   }
2191 
2192   // Increment the pointer, VAList, to the next vaarg
2193   Tmp1 = getNode(ISD::ADD, dl, VAList.getValueType(), VAList,
2194                  getConstant(getDataLayout().getTypeAllocSize(
2195                                                VT.getTypeForEVT(*getContext())),
2196                              dl, VAList.getValueType()));
2197   // Store the incremented VAList to the legalized pointer
2198   Tmp1 =
2199       getStore(VAListLoad.getValue(1), dl, Tmp1, Tmp2, MachinePointerInfo(V));
2200   // Load the actual argument out of the pointer VAList
2201   return getLoad(VT, dl, Tmp1, VAList, MachinePointerInfo());
2202 }
2203 
2204 SDValue SelectionDAG::expandVACopy(SDNode *Node) {
2205   SDLoc dl(Node);
2206   const TargetLowering &TLI = getTargetLoweringInfo();
2207   // This defaults to loading a pointer from the input and storing it to the
2208   // output, returning the chain.
2209   const Value *VD = cast<SrcValueSDNode>(Node->getOperand(3))->getValue();
2210   const Value *VS = cast<SrcValueSDNode>(Node->getOperand(4))->getValue();
2211   SDValue Tmp1 =
2212       getLoad(TLI.getPointerTy(getDataLayout()), dl, Node->getOperand(0),
2213               Node->getOperand(2), MachinePointerInfo(VS));
2214   return getStore(Tmp1.getValue(1), dl, Tmp1, Node->getOperand(1),
2215                   MachinePointerInfo(VD));
2216 }
2217 
2218 Align SelectionDAG::getReducedAlign(EVT VT, bool UseABI) {
2219   const DataLayout &DL = getDataLayout();
2220   Type *Ty = VT.getTypeForEVT(*getContext());
2221   Align RedAlign = UseABI ? DL.getABITypeAlign(Ty) : DL.getPrefTypeAlign(Ty);
2222 
2223   if (TLI->isTypeLegal(VT) || !VT.isVector())
2224     return RedAlign;
2225 
2226   const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering();
2227   const Align StackAlign = TFI->getStackAlign();
2228 
2229   // See if we can choose a smaller ABI alignment in cases where it's an
2230   // illegal vector type that will get broken down.
2231   if (RedAlign > StackAlign) {
2232     EVT IntermediateVT;
2233     MVT RegisterVT;
2234     unsigned NumIntermediates;
2235     TLI->getVectorTypeBreakdown(*getContext(), VT, IntermediateVT,
2236                                 NumIntermediates, RegisterVT);
2237     Ty = IntermediateVT.getTypeForEVT(*getContext());
2238     Align RedAlign2 = UseABI ? DL.getABITypeAlign(Ty) : DL.getPrefTypeAlign(Ty);
2239     if (RedAlign2 < RedAlign)
2240       RedAlign = RedAlign2;
2241   }
2242 
2243   return RedAlign;
2244 }
2245 
2246 SDValue SelectionDAG::CreateStackTemporary(TypeSize Bytes, Align Alignment) {
2247   MachineFrameInfo &MFI = MF->getFrameInfo();
2248   const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering();
2249   int StackID = 0;
2250   if (Bytes.isScalable())
2251     StackID = TFI->getStackIDForScalableVectors();
2252   // The stack id gives an indication of whether the object is scalable or
2253   // not, so it's safe to pass in the minimum size here.
2254   int FrameIdx = MFI.CreateStackObject(Bytes.getKnownMinSize(), Alignment,
2255                                        false, nullptr, StackID);
2256   return getFrameIndex(FrameIdx, TLI->getFrameIndexTy(getDataLayout()));
2257 }
2258 
2259 SDValue SelectionDAG::CreateStackTemporary(EVT VT, unsigned minAlign) {
2260   Type *Ty = VT.getTypeForEVT(*getContext());
2261   Align StackAlign =
2262       std::max(getDataLayout().getPrefTypeAlign(Ty), Align(minAlign));
2263   return CreateStackTemporary(VT.getStoreSize(), StackAlign);
2264 }
2265 
2266 SDValue SelectionDAG::CreateStackTemporary(EVT VT1, EVT VT2) {
2267   TypeSize VT1Size = VT1.getStoreSize();
2268   TypeSize VT2Size = VT2.getStoreSize();
2269   assert(VT1Size.isScalable() == VT2Size.isScalable() &&
2270          "Don't know how to choose the maximum size when creating a stack "
2271          "temporary");
2272   TypeSize Bytes =
2273       VT1Size.getKnownMinSize() > VT2Size.getKnownMinSize() ? VT1Size : VT2Size;
2274 
2275   Type *Ty1 = VT1.getTypeForEVT(*getContext());
2276   Type *Ty2 = VT2.getTypeForEVT(*getContext());
2277   const DataLayout &DL = getDataLayout();
2278   Align Align = std::max(DL.getPrefTypeAlign(Ty1), DL.getPrefTypeAlign(Ty2));
2279   return CreateStackTemporary(Bytes, Align);
2280 }
2281 
2282 SDValue SelectionDAG::FoldSetCC(EVT VT, SDValue N1, SDValue N2,
2283                                 ISD::CondCode Cond, const SDLoc &dl) {
2284   EVT OpVT = N1.getValueType();
2285 
2286   // These setcc operations always fold.
2287   switch (Cond) {
2288   default: break;
2289   case ISD::SETFALSE:
2290   case ISD::SETFALSE2: return getBoolConstant(false, dl, VT, OpVT);
2291   case ISD::SETTRUE:
2292   case ISD::SETTRUE2: return getBoolConstant(true, dl, VT, OpVT);
2293 
2294   case ISD::SETOEQ:
2295   case ISD::SETOGT:
2296   case ISD::SETOGE:
2297   case ISD::SETOLT:
2298   case ISD::SETOLE:
2299   case ISD::SETONE:
2300   case ISD::SETO:
2301   case ISD::SETUO:
2302   case ISD::SETUEQ:
2303   case ISD::SETUNE:
2304     assert(!OpVT.isInteger() && "Illegal setcc for integer!");
2305     break;
2306   }
2307 
2308   if (OpVT.isInteger()) {
2309     // For EQ and NE, we can always pick a value for the undef to make the
2310     // predicate pass or fail, so we can return undef.
2311     // Matches behavior in llvm::ConstantFoldCompareInstruction.
2312     // icmp eq/ne X, undef -> undef.
2313     if ((N1.isUndef() || N2.isUndef()) &&
2314         (Cond == ISD::SETEQ || Cond == ISD::SETNE))
2315       return getUNDEF(VT);
2316 
2317     // If both operands are undef, we can return undef for int comparison.
2318     // icmp undef, undef -> undef.
2319     if (N1.isUndef() && N2.isUndef())
2320       return getUNDEF(VT);
2321 
2322     // icmp X, X -> true/false
2323     // icmp X, undef -> true/false because undef could be X.
2324     if (N1 == N2)
2325       return getBoolConstant(ISD::isTrueWhenEqual(Cond), dl, VT, OpVT);
2326   }
2327 
2328   if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2)) {
2329     const APInt &C2 = N2C->getAPIntValue();
2330     if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1)) {
2331       const APInt &C1 = N1C->getAPIntValue();
2332 
2333       return getBoolConstant(ICmpInst::compare(C1, C2, getICmpCondCode(Cond)),
2334                              dl, VT, OpVT);
2335     }
2336   }
2337 
2338   auto *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
2339   auto *N2CFP = dyn_cast<ConstantFPSDNode>(N2);
2340 
2341   if (N1CFP && N2CFP) {
2342     APFloat::cmpResult R = N1CFP->getValueAPF().compare(N2CFP->getValueAPF());
2343     switch (Cond) {
2344     default: break;
2345     case ISD::SETEQ:  if (R==APFloat::cmpUnordered)
2346                         return getUNDEF(VT);
2347                       LLVM_FALLTHROUGH;
2348     case ISD::SETOEQ: return getBoolConstant(R==APFloat::cmpEqual, dl, VT,
2349                                              OpVT);
2350     case ISD::SETNE:  if (R==APFloat::cmpUnordered)
2351                         return getUNDEF(VT);
2352                       LLVM_FALLTHROUGH;
2353     case ISD::SETONE: return getBoolConstant(R==APFloat::cmpGreaterThan ||
2354                                              R==APFloat::cmpLessThan, dl, VT,
2355                                              OpVT);
2356     case ISD::SETLT:  if (R==APFloat::cmpUnordered)
2357                         return getUNDEF(VT);
2358                       LLVM_FALLTHROUGH;
2359     case ISD::SETOLT: return getBoolConstant(R==APFloat::cmpLessThan, dl, VT,
2360                                              OpVT);
2361     case ISD::SETGT:  if (R==APFloat::cmpUnordered)
2362                         return getUNDEF(VT);
2363                       LLVM_FALLTHROUGH;
2364     case ISD::SETOGT: return getBoolConstant(R==APFloat::cmpGreaterThan, dl,
2365                                              VT, OpVT);
2366     case ISD::SETLE:  if (R==APFloat::cmpUnordered)
2367                         return getUNDEF(VT);
2368                       LLVM_FALLTHROUGH;
2369     case ISD::SETOLE: return getBoolConstant(R==APFloat::cmpLessThan ||
2370                                              R==APFloat::cmpEqual, dl, VT,
2371                                              OpVT);
2372     case ISD::SETGE:  if (R==APFloat::cmpUnordered)
2373                         return getUNDEF(VT);
2374                       LLVM_FALLTHROUGH;
2375     case ISD::SETOGE: return getBoolConstant(R==APFloat::cmpGreaterThan ||
2376                                          R==APFloat::cmpEqual, dl, VT, OpVT);
2377     case ISD::SETO:   return getBoolConstant(R!=APFloat::cmpUnordered, dl, VT,
2378                                              OpVT);
2379     case ISD::SETUO:  return getBoolConstant(R==APFloat::cmpUnordered, dl, VT,
2380                                              OpVT);
2381     case ISD::SETUEQ: return getBoolConstant(R==APFloat::cmpUnordered ||
2382                                              R==APFloat::cmpEqual, dl, VT,
2383                                              OpVT);
2384     case ISD::SETUNE: return getBoolConstant(R!=APFloat::cmpEqual, dl, VT,
2385                                              OpVT);
2386     case ISD::SETULT: return getBoolConstant(R==APFloat::cmpUnordered ||
2387                                              R==APFloat::cmpLessThan, dl, VT,
2388                                              OpVT);
2389     case ISD::SETUGT: return getBoolConstant(R==APFloat::cmpGreaterThan ||
2390                                              R==APFloat::cmpUnordered, dl, VT,
2391                                              OpVT);
2392     case ISD::SETULE: return getBoolConstant(R!=APFloat::cmpGreaterThan, dl,
2393                                              VT, OpVT);
2394     case ISD::SETUGE: return getBoolConstant(R!=APFloat::cmpLessThan, dl, VT,
2395                                              OpVT);
2396     }
2397   } else if (N1CFP && OpVT.isSimple() && !N2.isUndef()) {
2398     // Ensure that the constant occurs on the RHS.
2399     ISD::CondCode SwappedCond = ISD::getSetCCSwappedOperands(Cond);
2400     if (!TLI->isCondCodeLegal(SwappedCond, OpVT.getSimpleVT()))
2401       return SDValue();
2402     return getSetCC(dl, VT, N2, N1, SwappedCond);
2403   } else if ((N2CFP && N2CFP->getValueAPF().isNaN()) ||
2404              (OpVT.isFloatingPoint() && (N1.isUndef() || N2.isUndef()))) {
2405     // If an operand is known to be a nan (or undef that could be a nan), we can
2406     // fold it.
2407     // Choosing NaN for the undef will always make unordered comparison succeed
2408     // and ordered comparison fails.
2409     // Matches behavior in llvm::ConstantFoldCompareInstruction.
2410     switch (ISD::getUnorderedFlavor(Cond)) {
2411     default:
2412       llvm_unreachable("Unknown flavor!");
2413     case 0: // Known false.
2414       return getBoolConstant(false, dl, VT, OpVT);
2415     case 1: // Known true.
2416       return getBoolConstant(true, dl, VT, OpVT);
2417     case 2: // Undefined.
2418       return getUNDEF(VT);
2419     }
2420   }
2421 
2422   // Could not fold it.
2423   return SDValue();
2424 }
2425 
2426 /// See if the specified operand can be simplified with the knowledge that only
2427 /// the bits specified by DemandedBits are used.
2428 /// TODO: really we should be making this into the DAG equivalent of
2429 /// SimplifyMultipleUseDemandedBits and not generate any new nodes.
2430 SDValue SelectionDAG::GetDemandedBits(SDValue V, const APInt &DemandedBits) {
2431   EVT VT = V.getValueType();
2432 
2433   if (VT.isScalableVector())
2434     return SDValue();
2435 
2436   APInt DemandedElts = VT.isVector()
2437                            ? APInt::getAllOnes(VT.getVectorNumElements())
2438                            : APInt(1, 1);
2439   return GetDemandedBits(V, DemandedBits, DemandedElts);
2440 }
2441 
2442 /// See if the specified operand can be simplified with the knowledge that only
2443 /// the bits specified by DemandedBits are used in the elements specified by
2444 /// DemandedElts.
2445 /// TODO: really we should be making this into the DAG equivalent of
2446 /// SimplifyMultipleUseDemandedBits and not generate any new nodes.
2447 SDValue SelectionDAG::GetDemandedBits(SDValue V, const APInt &DemandedBits,
2448                                       const APInt &DemandedElts) {
2449   switch (V.getOpcode()) {
2450   default:
2451     return TLI->SimplifyMultipleUseDemandedBits(V, DemandedBits, DemandedElts,
2452                                                 *this, 0);
2453   case ISD::Constant: {
2454     const APInt &CVal = cast<ConstantSDNode>(V)->getAPIntValue();
2455     APInt NewVal = CVal & DemandedBits;
2456     if (NewVal != CVal)
2457       return getConstant(NewVal, SDLoc(V), V.getValueType());
2458     break;
2459   }
2460   case ISD::SRL:
2461     // Only look at single-use SRLs.
2462     if (!V.getNode()->hasOneUse())
2463       break;
2464     if (auto *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
2465       // See if we can recursively simplify the LHS.
2466       unsigned Amt = RHSC->getZExtValue();
2467 
2468       // Watch out for shift count overflow though.
2469       if (Amt >= DemandedBits.getBitWidth())
2470         break;
2471       APInt SrcDemandedBits = DemandedBits << Amt;
2472       if (SDValue SimplifyLHS =
2473               GetDemandedBits(V.getOperand(0), SrcDemandedBits))
2474         return getNode(ISD::SRL, SDLoc(V), V.getValueType(), SimplifyLHS,
2475                        V.getOperand(1));
2476     }
2477     break;
2478   }
2479   return SDValue();
2480 }
2481 
2482 /// SignBitIsZero - Return true if the sign bit of Op is known to be zero.  We
2483 /// use this predicate to simplify operations downstream.
2484 bool SelectionDAG::SignBitIsZero(SDValue Op, unsigned Depth) const {
2485   unsigned BitWidth = Op.getScalarValueSizeInBits();
2486   return MaskedValueIsZero(Op, APInt::getSignMask(BitWidth), Depth);
2487 }
2488 
2489 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero.  We use
2490 /// this predicate to simplify operations downstream.  Mask is known to be zero
2491 /// for bits that V cannot have.
2492 bool SelectionDAG::MaskedValueIsZero(SDValue V, const APInt &Mask,
2493                                      unsigned Depth) const {
2494   return Mask.isSubsetOf(computeKnownBits(V, Depth).Zero);
2495 }
2496 
2497 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero in
2498 /// DemandedElts.  We use this predicate to simplify operations downstream.
2499 /// Mask is known to be zero for bits that V cannot have.
2500 bool SelectionDAG::MaskedValueIsZero(SDValue V, const APInt &Mask,
2501                                      const APInt &DemandedElts,
2502                                      unsigned Depth) const {
2503   return Mask.isSubsetOf(computeKnownBits(V, DemandedElts, Depth).Zero);
2504 }
2505 
2506 /// MaskedValueIsAllOnes - Return true if '(Op & Mask) == Mask'.
2507 bool SelectionDAG::MaskedValueIsAllOnes(SDValue V, const APInt &Mask,
2508                                         unsigned Depth) const {
2509   return Mask.isSubsetOf(computeKnownBits(V, Depth).One);
2510 }
2511 
2512 /// isSplatValue - Return true if the vector V has the same value
2513 /// across all DemandedElts. For scalable vectors it does not make
2514 /// sense to specify which elements are demanded or undefined, therefore
2515 /// they are simply ignored.
2516 bool SelectionDAG::isSplatValue(SDValue V, const APInt &DemandedElts,
2517                                 APInt &UndefElts, unsigned Depth) const {
2518   unsigned Opcode = V.getOpcode();
2519   EVT VT = V.getValueType();
2520   assert(VT.isVector() && "Vector type expected");
2521 
2522   if (!VT.isScalableVector() && !DemandedElts)
2523     return false; // No demanded elts, better to assume we don't know anything.
2524 
2525   if (Depth >= MaxRecursionDepth)
2526     return false; // Limit search depth.
2527 
2528   // Deal with some common cases here that work for both fixed and scalable
2529   // vector types.
2530   switch (Opcode) {
2531   case ISD::SPLAT_VECTOR:
2532     UndefElts = V.getOperand(0).isUndef()
2533                     ? APInt::getAllOnes(DemandedElts.getBitWidth())
2534                     : APInt(DemandedElts.getBitWidth(), 0);
2535     return true;
2536   case ISD::ADD:
2537   case ISD::SUB:
2538   case ISD::AND:
2539   case ISD::XOR:
2540   case ISD::OR: {
2541     APInt UndefLHS, UndefRHS;
2542     SDValue LHS = V.getOperand(0);
2543     SDValue RHS = V.getOperand(1);
2544     if (isSplatValue(LHS, DemandedElts, UndefLHS, Depth + 1) &&
2545         isSplatValue(RHS, DemandedElts, UndefRHS, Depth + 1)) {
2546       UndefElts = UndefLHS | UndefRHS;
2547       return true;
2548     }
2549     return false;
2550   }
2551   case ISD::ABS:
2552   case ISD::TRUNCATE:
2553   case ISD::SIGN_EXTEND:
2554   case ISD::ZERO_EXTEND:
2555     return isSplatValue(V.getOperand(0), DemandedElts, UndefElts, Depth + 1);
2556   default:
2557     if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::INTRINSIC_WO_CHAIN ||
2558         Opcode == ISD::INTRINSIC_W_CHAIN || Opcode == ISD::INTRINSIC_VOID)
2559       return TLI->isSplatValueForTargetNode(V, DemandedElts, UndefElts, Depth);
2560     break;
2561 }
2562 
2563   // We don't support other cases than those above for scalable vectors at
2564   // the moment.
2565   if (VT.isScalableVector())
2566     return false;
2567 
2568   unsigned NumElts = VT.getVectorNumElements();
2569   assert(NumElts == DemandedElts.getBitWidth() && "Vector size mismatch");
2570   UndefElts = APInt::getZero(NumElts);
2571 
2572   switch (Opcode) {
2573   case ISD::BUILD_VECTOR: {
2574     SDValue Scl;
2575     for (unsigned i = 0; i != NumElts; ++i) {
2576       SDValue Op = V.getOperand(i);
2577       if (Op.isUndef()) {
2578         UndefElts.setBit(i);
2579         continue;
2580       }
2581       if (!DemandedElts[i])
2582         continue;
2583       if (Scl && Scl != Op)
2584         return false;
2585       Scl = Op;
2586     }
2587     return true;
2588   }
2589   case ISD::VECTOR_SHUFFLE: {
2590     // Check if this is a shuffle node doing a splat.
2591     // TODO: Do we need to handle shuffle(splat, undef, mask)?
2592     int SplatIndex = -1;
2593     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(V)->getMask();
2594     for (int i = 0; i != (int)NumElts; ++i) {
2595       int M = Mask[i];
2596       if (M < 0) {
2597         UndefElts.setBit(i);
2598         continue;
2599       }
2600       if (!DemandedElts[i])
2601         continue;
2602       if (0 <= SplatIndex && SplatIndex != M)
2603         return false;
2604       SplatIndex = M;
2605     }
2606     return true;
2607   }
2608   case ISD::EXTRACT_SUBVECTOR: {
2609     // Offset the demanded elts by the subvector index.
2610     SDValue Src = V.getOperand(0);
2611     // We don't support scalable vectors at the moment.
2612     if (Src.getValueType().isScalableVector())
2613       return false;
2614     uint64_t Idx = V.getConstantOperandVal(1);
2615     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
2616     APInt UndefSrcElts;
2617     APInt DemandedSrcElts = DemandedElts.zextOrSelf(NumSrcElts).shl(Idx);
2618     if (isSplatValue(Src, DemandedSrcElts, UndefSrcElts, Depth + 1)) {
2619       UndefElts = UndefSrcElts.extractBits(NumElts, Idx);
2620       return true;
2621     }
2622     break;
2623   }
2624   case ISD::ANY_EXTEND_VECTOR_INREG:
2625   case ISD::SIGN_EXTEND_VECTOR_INREG:
2626   case ISD::ZERO_EXTEND_VECTOR_INREG: {
2627     // Widen the demanded elts by the src element count.
2628     SDValue Src = V.getOperand(0);
2629     // We don't support scalable vectors at the moment.
2630     if (Src.getValueType().isScalableVector())
2631       return false;
2632     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
2633     APInt UndefSrcElts;
2634     APInt DemandedSrcElts = DemandedElts.zextOrSelf(NumSrcElts);
2635     if (isSplatValue(Src, DemandedSrcElts, UndefSrcElts, Depth + 1)) {
2636       UndefElts = UndefSrcElts.truncOrSelf(NumElts);
2637       return true;
2638     }
2639     break;
2640   }
2641   }
2642 
2643   return false;
2644 }
2645 
2646 /// Helper wrapper to main isSplatValue function.
2647 bool SelectionDAG::isSplatValue(SDValue V, bool AllowUndefs) const {
2648   EVT VT = V.getValueType();
2649   assert(VT.isVector() && "Vector type expected");
2650 
2651   APInt UndefElts;
2652   APInt DemandedElts;
2653 
2654   // For now we don't support this with scalable vectors.
2655   if (!VT.isScalableVector())
2656     DemandedElts = APInt::getAllOnes(VT.getVectorNumElements());
2657   return isSplatValue(V, DemandedElts, UndefElts) &&
2658          (AllowUndefs || !UndefElts);
2659 }
2660 
2661 SDValue SelectionDAG::getSplatSourceVector(SDValue V, int &SplatIdx) {
2662   V = peekThroughExtractSubvectors(V);
2663 
2664   EVT VT = V.getValueType();
2665   unsigned Opcode = V.getOpcode();
2666   switch (Opcode) {
2667   default: {
2668     APInt UndefElts;
2669     APInt DemandedElts;
2670 
2671     if (!VT.isScalableVector())
2672       DemandedElts = APInt::getAllOnes(VT.getVectorNumElements());
2673 
2674     if (isSplatValue(V, DemandedElts, UndefElts)) {
2675       if (VT.isScalableVector()) {
2676         // DemandedElts and UndefElts are ignored for scalable vectors, since
2677         // the only supported cases are SPLAT_VECTOR nodes.
2678         SplatIdx = 0;
2679       } else {
2680         // Handle case where all demanded elements are UNDEF.
2681         if (DemandedElts.isSubsetOf(UndefElts)) {
2682           SplatIdx = 0;
2683           return getUNDEF(VT);
2684         }
2685         SplatIdx = (UndefElts & DemandedElts).countTrailingOnes();
2686       }
2687       return V;
2688     }
2689     break;
2690   }
2691   case ISD::SPLAT_VECTOR:
2692     SplatIdx = 0;
2693     return V;
2694   case ISD::VECTOR_SHUFFLE: {
2695     if (VT.isScalableVector())
2696       return SDValue();
2697 
2698     // Check if this is a shuffle node doing a splat.
2699     // TODO - remove this and rely purely on SelectionDAG::isSplatValue,
2700     // getTargetVShiftNode currently struggles without the splat source.
2701     auto *SVN = cast<ShuffleVectorSDNode>(V);
2702     if (!SVN->isSplat())
2703       break;
2704     int Idx = SVN->getSplatIndex();
2705     int NumElts = V.getValueType().getVectorNumElements();
2706     SplatIdx = Idx % NumElts;
2707     return V.getOperand(Idx / NumElts);
2708   }
2709   }
2710 
2711   return SDValue();
2712 }
2713 
2714 SDValue SelectionDAG::getSplatValue(SDValue V, bool LegalTypes) {
2715   int SplatIdx;
2716   if (SDValue SrcVector = getSplatSourceVector(V, SplatIdx)) {
2717     EVT SVT = SrcVector.getValueType().getScalarType();
2718     EVT LegalSVT = SVT;
2719     if (LegalTypes && !TLI->isTypeLegal(SVT)) {
2720       if (!SVT.isInteger())
2721         return SDValue();
2722       LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT);
2723       if (LegalSVT.bitsLT(SVT))
2724         return SDValue();
2725     }
2726     return getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(V), LegalSVT, SrcVector,
2727                    getVectorIdxConstant(SplatIdx, SDLoc(V)));
2728   }
2729   return SDValue();
2730 }
2731 
2732 const APInt *
2733 SelectionDAG::getValidShiftAmountConstant(SDValue V,
2734                                           const APInt &DemandedElts) const {
2735   assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL ||
2736           V.getOpcode() == ISD::SRA) &&
2737          "Unknown shift node");
2738   unsigned BitWidth = V.getScalarValueSizeInBits();
2739   if (ConstantSDNode *SA = isConstOrConstSplat(V.getOperand(1), DemandedElts)) {
2740     // Shifting more than the bitwidth is not valid.
2741     const APInt &ShAmt = SA->getAPIntValue();
2742     if (ShAmt.ult(BitWidth))
2743       return &ShAmt;
2744   }
2745   return nullptr;
2746 }
2747 
2748 const APInt *SelectionDAG::getValidMinimumShiftAmountConstant(
2749     SDValue V, const APInt &DemandedElts) const {
2750   assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL ||
2751           V.getOpcode() == ISD::SRA) &&
2752          "Unknown shift node");
2753   if (const APInt *ValidAmt = getValidShiftAmountConstant(V, DemandedElts))
2754     return ValidAmt;
2755   unsigned BitWidth = V.getScalarValueSizeInBits();
2756   auto *BV = dyn_cast<BuildVectorSDNode>(V.getOperand(1));
2757   if (!BV)
2758     return nullptr;
2759   const APInt *MinShAmt = nullptr;
2760   for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
2761     if (!DemandedElts[i])
2762       continue;
2763     auto *SA = dyn_cast<ConstantSDNode>(BV->getOperand(i));
2764     if (!SA)
2765       return nullptr;
2766     // Shifting more than the bitwidth is not valid.
2767     const APInt &ShAmt = SA->getAPIntValue();
2768     if (ShAmt.uge(BitWidth))
2769       return nullptr;
2770     if (MinShAmt && MinShAmt->ule(ShAmt))
2771       continue;
2772     MinShAmt = &ShAmt;
2773   }
2774   return MinShAmt;
2775 }
2776 
2777 const APInt *SelectionDAG::getValidMaximumShiftAmountConstant(
2778     SDValue V, const APInt &DemandedElts) const {
2779   assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL ||
2780           V.getOpcode() == ISD::SRA) &&
2781          "Unknown shift node");
2782   if (const APInt *ValidAmt = getValidShiftAmountConstant(V, DemandedElts))
2783     return ValidAmt;
2784   unsigned BitWidth = V.getScalarValueSizeInBits();
2785   auto *BV = dyn_cast<BuildVectorSDNode>(V.getOperand(1));
2786   if (!BV)
2787     return nullptr;
2788   const APInt *MaxShAmt = nullptr;
2789   for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
2790     if (!DemandedElts[i])
2791       continue;
2792     auto *SA = dyn_cast<ConstantSDNode>(BV->getOperand(i));
2793     if (!SA)
2794       return nullptr;
2795     // Shifting more than the bitwidth is not valid.
2796     const APInt &ShAmt = SA->getAPIntValue();
2797     if (ShAmt.uge(BitWidth))
2798       return nullptr;
2799     if (MaxShAmt && MaxShAmt->uge(ShAmt))
2800       continue;
2801     MaxShAmt = &ShAmt;
2802   }
2803   return MaxShAmt;
2804 }
2805 
2806 /// Determine which bits of Op are known to be either zero or one and return
2807 /// them in Known. For vectors, the known bits are those that are shared by
2808 /// every vector element.
2809 KnownBits SelectionDAG::computeKnownBits(SDValue Op, unsigned Depth) const {
2810   EVT VT = Op.getValueType();
2811 
2812   // TOOD: Until we have a plan for how to represent demanded elements for
2813   // scalable vectors, we can just bail out for now.
2814   if (Op.getValueType().isScalableVector()) {
2815     unsigned BitWidth = Op.getScalarValueSizeInBits();
2816     return KnownBits(BitWidth);
2817   }
2818 
2819   APInt DemandedElts = VT.isVector()
2820                            ? APInt::getAllOnes(VT.getVectorNumElements())
2821                            : APInt(1, 1);
2822   return computeKnownBits(Op, DemandedElts, Depth);
2823 }
2824 
2825 /// Determine which bits of Op are known to be either zero or one and return
2826 /// them in Known. The DemandedElts argument allows us to only collect the known
2827 /// bits that are shared by the requested vector elements.
2828 KnownBits SelectionDAG::computeKnownBits(SDValue Op, const APInt &DemandedElts,
2829                                          unsigned Depth) const {
2830   unsigned BitWidth = Op.getScalarValueSizeInBits();
2831 
2832   KnownBits Known(BitWidth);   // Don't know anything.
2833 
2834   // TOOD: Until we have a plan for how to represent demanded elements for
2835   // scalable vectors, we can just bail out for now.
2836   if (Op.getValueType().isScalableVector())
2837     return Known;
2838 
2839   if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
2840     // We know all of the bits for a constant!
2841     return KnownBits::makeConstant(C->getAPIntValue());
2842   }
2843   if (auto *C = dyn_cast<ConstantFPSDNode>(Op)) {
2844     // We know all of the bits for a constant fp!
2845     return KnownBits::makeConstant(C->getValueAPF().bitcastToAPInt());
2846   }
2847 
2848   if (Depth >= MaxRecursionDepth)
2849     return Known;  // Limit search depth.
2850 
2851   KnownBits Known2;
2852   unsigned NumElts = DemandedElts.getBitWidth();
2853   assert((!Op.getValueType().isVector() ||
2854           NumElts == Op.getValueType().getVectorNumElements()) &&
2855          "Unexpected vector size");
2856 
2857   if (!DemandedElts)
2858     return Known;  // No demanded elts, better to assume we don't know anything.
2859 
2860   unsigned Opcode = Op.getOpcode();
2861   switch (Opcode) {
2862   case ISD::BUILD_VECTOR:
2863     // Collect the known bits that are shared by every demanded vector element.
2864     Known.Zero.setAllBits(); Known.One.setAllBits();
2865     for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
2866       if (!DemandedElts[i])
2867         continue;
2868 
2869       SDValue SrcOp = Op.getOperand(i);
2870       Known2 = computeKnownBits(SrcOp, Depth + 1);
2871 
2872       // BUILD_VECTOR can implicitly truncate sources, we must handle this.
2873       if (SrcOp.getValueSizeInBits() != BitWidth) {
2874         assert(SrcOp.getValueSizeInBits() > BitWidth &&
2875                "Expected BUILD_VECTOR implicit truncation");
2876         Known2 = Known2.trunc(BitWidth);
2877       }
2878 
2879       // Known bits are the values that are shared by every demanded element.
2880       Known = KnownBits::commonBits(Known, Known2);
2881 
2882       // If we don't know any bits, early out.
2883       if (Known.isUnknown())
2884         break;
2885     }
2886     break;
2887   case ISD::VECTOR_SHUFFLE: {
2888     // Collect the known bits that are shared by every vector element referenced
2889     // by the shuffle.
2890     APInt DemandedLHS(NumElts, 0), DemandedRHS(NumElts, 0);
2891     Known.Zero.setAllBits(); Known.One.setAllBits();
2892     const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op);
2893     assert(NumElts == SVN->getMask().size() && "Unexpected vector size");
2894     for (unsigned i = 0; i != NumElts; ++i) {
2895       if (!DemandedElts[i])
2896         continue;
2897 
2898       int M = SVN->getMaskElt(i);
2899       if (M < 0) {
2900         // For UNDEF elements, we don't know anything about the common state of
2901         // the shuffle result.
2902         Known.resetAll();
2903         DemandedLHS.clearAllBits();
2904         DemandedRHS.clearAllBits();
2905         break;
2906       }
2907 
2908       if ((unsigned)M < NumElts)
2909         DemandedLHS.setBit((unsigned)M % NumElts);
2910       else
2911         DemandedRHS.setBit((unsigned)M % NumElts);
2912     }
2913     // Known bits are the values that are shared by every demanded element.
2914     if (!!DemandedLHS) {
2915       SDValue LHS = Op.getOperand(0);
2916       Known2 = computeKnownBits(LHS, DemandedLHS, Depth + 1);
2917       Known = KnownBits::commonBits(Known, Known2);
2918     }
2919     // If we don't know any bits, early out.
2920     if (Known.isUnknown())
2921       break;
2922     if (!!DemandedRHS) {
2923       SDValue RHS = Op.getOperand(1);
2924       Known2 = computeKnownBits(RHS, DemandedRHS, Depth + 1);
2925       Known = KnownBits::commonBits(Known, Known2);
2926     }
2927     break;
2928   }
2929   case ISD::CONCAT_VECTORS: {
2930     // Split DemandedElts and test each of the demanded subvectors.
2931     Known.Zero.setAllBits(); Known.One.setAllBits();
2932     EVT SubVectorVT = Op.getOperand(0).getValueType();
2933     unsigned NumSubVectorElts = SubVectorVT.getVectorNumElements();
2934     unsigned NumSubVectors = Op.getNumOperands();
2935     for (unsigned i = 0; i != NumSubVectors; ++i) {
2936       APInt DemandedSub =
2937           DemandedElts.extractBits(NumSubVectorElts, i * NumSubVectorElts);
2938       if (!!DemandedSub) {
2939         SDValue Sub = Op.getOperand(i);
2940         Known2 = computeKnownBits(Sub, DemandedSub, Depth + 1);
2941         Known = KnownBits::commonBits(Known, Known2);
2942       }
2943       // If we don't know any bits, early out.
2944       if (Known.isUnknown())
2945         break;
2946     }
2947     break;
2948   }
2949   case ISD::INSERT_SUBVECTOR: {
2950     // Demand any elements from the subvector and the remainder from the src its
2951     // inserted into.
2952     SDValue Src = Op.getOperand(0);
2953     SDValue Sub = Op.getOperand(1);
2954     uint64_t Idx = Op.getConstantOperandVal(2);
2955     unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
2956     APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
2957     APInt DemandedSrcElts = DemandedElts;
2958     DemandedSrcElts.insertBits(APInt::getZero(NumSubElts), Idx);
2959 
2960     Known.One.setAllBits();
2961     Known.Zero.setAllBits();
2962     if (!!DemandedSubElts) {
2963       Known = computeKnownBits(Sub, DemandedSubElts, Depth + 1);
2964       if (Known.isUnknown())
2965         break; // early-out.
2966     }
2967     if (!!DemandedSrcElts) {
2968       Known2 = computeKnownBits(Src, DemandedSrcElts, Depth + 1);
2969       Known = KnownBits::commonBits(Known, Known2);
2970     }
2971     break;
2972   }
2973   case ISD::EXTRACT_SUBVECTOR: {
2974     // Offset the demanded elts by the subvector index.
2975     SDValue Src = Op.getOperand(0);
2976     // Bail until we can represent demanded elements for scalable vectors.
2977     if (Src.getValueType().isScalableVector())
2978       break;
2979     uint64_t Idx = Op.getConstantOperandVal(1);
2980     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
2981     APInt DemandedSrcElts = DemandedElts.zextOrSelf(NumSrcElts).shl(Idx);
2982     Known = computeKnownBits(Src, DemandedSrcElts, Depth + 1);
2983     break;
2984   }
2985   case ISD::SCALAR_TO_VECTOR: {
2986     // We know about scalar_to_vector as much as we know about it source,
2987     // which becomes the first element of otherwise unknown vector.
2988     if (DemandedElts != 1)
2989       break;
2990 
2991     SDValue N0 = Op.getOperand(0);
2992     Known = computeKnownBits(N0, Depth + 1);
2993     if (N0.getValueSizeInBits() != BitWidth)
2994       Known = Known.trunc(BitWidth);
2995 
2996     break;
2997   }
2998   case ISD::BITCAST: {
2999     SDValue N0 = Op.getOperand(0);
3000     EVT SubVT = N0.getValueType();
3001     unsigned SubBitWidth = SubVT.getScalarSizeInBits();
3002 
3003     // Ignore bitcasts from unsupported types.
3004     if (!(SubVT.isInteger() || SubVT.isFloatingPoint()))
3005       break;
3006 
3007     // Fast handling of 'identity' bitcasts.
3008     if (BitWidth == SubBitWidth) {
3009       Known = computeKnownBits(N0, DemandedElts, Depth + 1);
3010       break;
3011     }
3012 
3013     bool IsLE = getDataLayout().isLittleEndian();
3014 
3015     // Bitcast 'small element' vector to 'large element' scalar/vector.
3016     if ((BitWidth % SubBitWidth) == 0) {
3017       assert(N0.getValueType().isVector() && "Expected bitcast from vector");
3018 
3019       // Collect known bits for the (larger) output by collecting the known
3020       // bits from each set of sub elements and shift these into place.
3021       // We need to separately call computeKnownBits for each set of
3022       // sub elements as the knownbits for each is likely to be different.
3023       unsigned SubScale = BitWidth / SubBitWidth;
3024       APInt SubDemandedElts(NumElts * SubScale, 0);
3025       for (unsigned i = 0; i != NumElts; ++i)
3026         if (DemandedElts[i])
3027           SubDemandedElts.setBit(i * SubScale);
3028 
3029       for (unsigned i = 0; i != SubScale; ++i) {
3030         Known2 = computeKnownBits(N0, SubDemandedElts.shl(i),
3031                          Depth + 1);
3032         unsigned Shifts = IsLE ? i : SubScale - 1 - i;
3033         Known.insertBits(Known2, SubBitWidth * Shifts);
3034       }
3035     }
3036 
3037     // Bitcast 'large element' scalar/vector to 'small element' vector.
3038     if ((SubBitWidth % BitWidth) == 0) {
3039       assert(Op.getValueType().isVector() && "Expected bitcast to vector");
3040 
3041       // Collect known bits for the (smaller) output by collecting the known
3042       // bits from the overlapping larger input elements and extracting the
3043       // sub sections we actually care about.
3044       unsigned SubScale = SubBitWidth / BitWidth;
3045       APInt SubDemandedElts =
3046           APIntOps::ScaleBitMask(DemandedElts, NumElts / SubScale);
3047       Known2 = computeKnownBits(N0, SubDemandedElts, Depth + 1);
3048 
3049       Known.Zero.setAllBits(); Known.One.setAllBits();
3050       for (unsigned i = 0; i != NumElts; ++i)
3051         if (DemandedElts[i]) {
3052           unsigned Shifts = IsLE ? i : NumElts - 1 - i;
3053           unsigned Offset = (Shifts % SubScale) * BitWidth;
3054           Known = KnownBits::commonBits(Known,
3055                                         Known2.extractBits(BitWidth, Offset));
3056           // If we don't know any bits, early out.
3057           if (Known.isUnknown())
3058             break;
3059         }
3060     }
3061     break;
3062   }
3063   case ISD::AND:
3064     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3065     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3066 
3067     Known &= Known2;
3068     break;
3069   case ISD::OR:
3070     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3071     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3072 
3073     Known |= Known2;
3074     break;
3075   case ISD::XOR:
3076     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3077     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3078 
3079     Known ^= Known2;
3080     break;
3081   case ISD::MUL: {
3082     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3083     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3084     bool SelfMultiply = Op.getOperand(0) == Op.getOperand(1);
3085     Known = KnownBits::mul(Known, Known2, SelfMultiply);
3086     break;
3087   }
3088   case ISD::MULHU: {
3089     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3090     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3091     Known = KnownBits::mulhu(Known, Known2);
3092     break;
3093   }
3094   case ISD::MULHS: {
3095     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3096     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3097     Known = KnownBits::mulhs(Known, Known2);
3098     break;
3099   }
3100   case ISD::UMUL_LOHI: {
3101     assert((Op.getResNo() == 0 || Op.getResNo() == 1) && "Unknown result");
3102     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3103     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3104     bool SelfMultiply = Op.getOperand(0) == Op.getOperand(1);
3105     if (Op.getResNo() == 0)
3106       Known = KnownBits::mul(Known, Known2, SelfMultiply);
3107     else
3108       Known = KnownBits::mulhu(Known, Known2);
3109     break;
3110   }
3111   case ISD::SMUL_LOHI: {
3112     assert((Op.getResNo() == 0 || Op.getResNo() == 1) && "Unknown result");
3113     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3114     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3115     bool SelfMultiply = Op.getOperand(0) == Op.getOperand(1);
3116     if (Op.getResNo() == 0)
3117       Known = KnownBits::mul(Known, Known2, SelfMultiply);
3118     else
3119       Known = KnownBits::mulhs(Known, Known2);
3120     break;
3121   }
3122   case ISD::UDIV: {
3123     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3124     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3125     Known = KnownBits::udiv(Known, Known2);
3126     break;
3127   }
3128   case ISD::SELECT:
3129   case ISD::VSELECT:
3130     Known = computeKnownBits(Op.getOperand(2), DemandedElts, Depth+1);
3131     // If we don't know any bits, early out.
3132     if (Known.isUnknown())
3133       break;
3134     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth+1);
3135 
3136     // Only known if known in both the LHS and RHS.
3137     Known = KnownBits::commonBits(Known, Known2);
3138     break;
3139   case ISD::SELECT_CC:
3140     Known = computeKnownBits(Op.getOperand(3), DemandedElts, Depth+1);
3141     // If we don't know any bits, early out.
3142     if (Known.isUnknown())
3143       break;
3144     Known2 = computeKnownBits(Op.getOperand(2), DemandedElts, Depth+1);
3145 
3146     // Only known if known in both the LHS and RHS.
3147     Known = KnownBits::commonBits(Known, Known2);
3148     break;
3149   case ISD::SMULO:
3150   case ISD::UMULO:
3151     if (Op.getResNo() != 1)
3152       break;
3153     // The boolean result conforms to getBooleanContents.
3154     // If we know the result of a setcc has the top bits zero, use this info.
3155     // We know that we have an integer-based boolean since these operations
3156     // are only available for integer.
3157     if (TLI->getBooleanContents(Op.getValueType().isVector(), false) ==
3158             TargetLowering::ZeroOrOneBooleanContent &&
3159         BitWidth > 1)
3160       Known.Zero.setBitsFrom(1);
3161     break;
3162   case ISD::SETCC:
3163   case ISD::STRICT_FSETCC:
3164   case ISD::STRICT_FSETCCS: {
3165     unsigned OpNo = Op->isStrictFPOpcode() ? 1 : 0;
3166     // If we know the result of a setcc has the top bits zero, use this info.
3167     if (TLI->getBooleanContents(Op.getOperand(OpNo).getValueType()) ==
3168             TargetLowering::ZeroOrOneBooleanContent &&
3169         BitWidth > 1)
3170       Known.Zero.setBitsFrom(1);
3171     break;
3172   }
3173   case ISD::SHL:
3174     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3175     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3176     Known = KnownBits::shl(Known, Known2);
3177 
3178     // Minimum shift low bits are known zero.
3179     if (const APInt *ShMinAmt =
3180             getValidMinimumShiftAmountConstant(Op, DemandedElts))
3181       Known.Zero.setLowBits(ShMinAmt->getZExtValue());
3182     break;
3183   case ISD::SRL:
3184     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3185     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3186     Known = KnownBits::lshr(Known, Known2);
3187 
3188     // Minimum shift high bits are known zero.
3189     if (const APInt *ShMinAmt =
3190             getValidMinimumShiftAmountConstant(Op, DemandedElts))
3191       Known.Zero.setHighBits(ShMinAmt->getZExtValue());
3192     break;
3193   case ISD::SRA:
3194     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3195     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3196     Known = KnownBits::ashr(Known, Known2);
3197     // TODO: Add minimum shift high known sign bits.
3198     break;
3199   case ISD::FSHL:
3200   case ISD::FSHR:
3201     if (ConstantSDNode *C = isConstOrConstSplat(Op.getOperand(2), DemandedElts)) {
3202       unsigned Amt = C->getAPIntValue().urem(BitWidth);
3203 
3204       // For fshl, 0-shift returns the 1st arg.
3205       // For fshr, 0-shift returns the 2nd arg.
3206       if (Amt == 0) {
3207         Known = computeKnownBits(Op.getOperand(Opcode == ISD::FSHL ? 0 : 1),
3208                                  DemandedElts, Depth + 1);
3209         break;
3210       }
3211 
3212       // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW)))
3213       // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW))
3214       Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3215       Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3216       if (Opcode == ISD::FSHL) {
3217         Known.One <<= Amt;
3218         Known.Zero <<= Amt;
3219         Known2.One.lshrInPlace(BitWidth - Amt);
3220         Known2.Zero.lshrInPlace(BitWidth - Amt);
3221       } else {
3222         Known.One <<= BitWidth - Amt;
3223         Known.Zero <<= BitWidth - Amt;
3224         Known2.One.lshrInPlace(Amt);
3225         Known2.Zero.lshrInPlace(Amt);
3226       }
3227       Known.One |= Known2.One;
3228       Known.Zero |= Known2.Zero;
3229     }
3230     break;
3231   case ISD::SIGN_EXTEND_INREG: {
3232     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3233     EVT EVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
3234     Known = Known.sextInReg(EVT.getScalarSizeInBits());
3235     break;
3236   }
3237   case ISD::CTTZ:
3238   case ISD::CTTZ_ZERO_UNDEF: {
3239     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3240     // If we have a known 1, its position is our upper bound.
3241     unsigned PossibleTZ = Known2.countMaxTrailingZeros();
3242     unsigned LowBits = Log2_32(PossibleTZ) + 1;
3243     Known.Zero.setBitsFrom(LowBits);
3244     break;
3245   }
3246   case ISD::CTLZ:
3247   case ISD::CTLZ_ZERO_UNDEF: {
3248     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3249     // If we have a known 1, its position is our upper bound.
3250     unsigned PossibleLZ = Known2.countMaxLeadingZeros();
3251     unsigned LowBits = Log2_32(PossibleLZ) + 1;
3252     Known.Zero.setBitsFrom(LowBits);
3253     break;
3254   }
3255   case ISD::CTPOP: {
3256     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3257     // If we know some of the bits are zero, they can't be one.
3258     unsigned PossibleOnes = Known2.countMaxPopulation();
3259     Known.Zero.setBitsFrom(Log2_32(PossibleOnes) + 1);
3260     break;
3261   }
3262   case ISD::PARITY: {
3263     // Parity returns 0 everywhere but the LSB.
3264     Known.Zero.setBitsFrom(1);
3265     break;
3266   }
3267   case ISD::LOAD: {
3268     LoadSDNode *LD = cast<LoadSDNode>(Op);
3269     const Constant *Cst = TLI->getTargetConstantFromLoad(LD);
3270     if (ISD::isNON_EXTLoad(LD) && Cst) {
3271       // Determine any common known bits from the loaded constant pool value.
3272       Type *CstTy = Cst->getType();
3273       if ((NumElts * BitWidth) == CstTy->getPrimitiveSizeInBits()) {
3274         // If its a vector splat, then we can (quickly) reuse the scalar path.
3275         // NOTE: We assume all elements match and none are UNDEF.
3276         if (CstTy->isVectorTy()) {
3277           if (const Constant *Splat = Cst->getSplatValue()) {
3278             Cst = Splat;
3279             CstTy = Cst->getType();
3280           }
3281         }
3282         // TODO - do we need to handle different bitwidths?
3283         if (CstTy->isVectorTy() && BitWidth == CstTy->getScalarSizeInBits()) {
3284           // Iterate across all vector elements finding common known bits.
3285           Known.One.setAllBits();
3286           Known.Zero.setAllBits();
3287           for (unsigned i = 0; i != NumElts; ++i) {
3288             if (!DemandedElts[i])
3289               continue;
3290             if (Constant *Elt = Cst->getAggregateElement(i)) {
3291               if (auto *CInt = dyn_cast<ConstantInt>(Elt)) {
3292                 const APInt &Value = CInt->getValue();
3293                 Known.One &= Value;
3294                 Known.Zero &= ~Value;
3295                 continue;
3296               }
3297               if (auto *CFP = dyn_cast<ConstantFP>(Elt)) {
3298                 APInt Value = CFP->getValueAPF().bitcastToAPInt();
3299                 Known.One &= Value;
3300                 Known.Zero &= ~Value;
3301                 continue;
3302               }
3303             }
3304             Known.One.clearAllBits();
3305             Known.Zero.clearAllBits();
3306             break;
3307           }
3308         } else if (BitWidth == CstTy->getPrimitiveSizeInBits()) {
3309           if (auto *CInt = dyn_cast<ConstantInt>(Cst)) {
3310             Known = KnownBits::makeConstant(CInt->getValue());
3311           } else if (auto *CFP = dyn_cast<ConstantFP>(Cst)) {
3312             Known =
3313                 KnownBits::makeConstant(CFP->getValueAPF().bitcastToAPInt());
3314           }
3315         }
3316       }
3317     } else if (ISD::isZEXTLoad(Op.getNode()) && Op.getResNo() == 0) {
3318       // If this is a ZEXTLoad and we are looking at the loaded value.
3319       EVT VT = LD->getMemoryVT();
3320       unsigned MemBits = VT.getScalarSizeInBits();
3321       Known.Zero.setBitsFrom(MemBits);
3322     } else if (const MDNode *Ranges = LD->getRanges()) {
3323       if (LD->getExtensionType() == ISD::NON_EXTLOAD)
3324         computeKnownBitsFromRangeMetadata(*Ranges, Known);
3325     }
3326     break;
3327   }
3328   case ISD::ZERO_EXTEND_VECTOR_INREG: {
3329     EVT InVT = Op.getOperand(0).getValueType();
3330     APInt InDemandedElts = DemandedElts.zextOrSelf(InVT.getVectorNumElements());
3331     Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1);
3332     Known = Known.zext(BitWidth);
3333     break;
3334   }
3335   case ISD::ZERO_EXTEND: {
3336     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3337     Known = Known.zext(BitWidth);
3338     break;
3339   }
3340   case ISD::SIGN_EXTEND_VECTOR_INREG: {
3341     EVT InVT = Op.getOperand(0).getValueType();
3342     APInt InDemandedElts = DemandedElts.zextOrSelf(InVT.getVectorNumElements());
3343     Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1);
3344     // If the sign bit is known to be zero or one, then sext will extend
3345     // it to the top bits, else it will just zext.
3346     Known = Known.sext(BitWidth);
3347     break;
3348   }
3349   case ISD::SIGN_EXTEND: {
3350     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3351     // If the sign bit is known to be zero or one, then sext will extend
3352     // it to the top bits, else it will just zext.
3353     Known = Known.sext(BitWidth);
3354     break;
3355   }
3356   case ISD::ANY_EXTEND_VECTOR_INREG: {
3357     EVT InVT = Op.getOperand(0).getValueType();
3358     APInt InDemandedElts = DemandedElts.zextOrSelf(InVT.getVectorNumElements());
3359     Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1);
3360     Known = Known.anyext(BitWidth);
3361     break;
3362   }
3363   case ISD::ANY_EXTEND: {
3364     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3365     Known = Known.anyext(BitWidth);
3366     break;
3367   }
3368   case ISD::TRUNCATE: {
3369     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3370     Known = Known.trunc(BitWidth);
3371     break;
3372   }
3373   case ISD::AssertZext: {
3374     EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
3375     APInt InMask = APInt::getLowBitsSet(BitWidth, VT.getSizeInBits());
3376     Known = computeKnownBits(Op.getOperand(0), Depth+1);
3377     Known.Zero |= (~InMask);
3378     Known.One  &= (~Known.Zero);
3379     break;
3380   }
3381   case ISD::AssertAlign: {
3382     unsigned LogOfAlign = Log2(cast<AssertAlignSDNode>(Op)->getAlign());
3383     assert(LogOfAlign != 0);
3384     // If a node is guaranteed to be aligned, set low zero bits accordingly as
3385     // well as clearing one bits.
3386     Known.Zero.setLowBits(LogOfAlign);
3387     Known.One.clearLowBits(LogOfAlign);
3388     break;
3389   }
3390   case ISD::FGETSIGN:
3391     // All bits are zero except the low bit.
3392     Known.Zero.setBitsFrom(1);
3393     break;
3394   case ISD::USUBO:
3395   case ISD::SSUBO:
3396     if (Op.getResNo() == 1) {
3397       // If we know the result of a setcc has the top bits zero, use this info.
3398       if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) ==
3399               TargetLowering::ZeroOrOneBooleanContent &&
3400           BitWidth > 1)
3401         Known.Zero.setBitsFrom(1);
3402       break;
3403     }
3404     LLVM_FALLTHROUGH;
3405   case ISD::SUB:
3406   case ISD::SUBC: {
3407     assert(Op.getResNo() == 0 &&
3408            "We only compute knownbits for the difference here.");
3409 
3410     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3411     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3412     Known = KnownBits::computeForAddSub(/* Add */ false, /* NSW */ false,
3413                                         Known, Known2);
3414     break;
3415   }
3416   case ISD::UADDO:
3417   case ISD::SADDO:
3418   case ISD::ADDCARRY:
3419     if (Op.getResNo() == 1) {
3420       // If we know the result of a setcc has the top bits zero, use this info.
3421       if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) ==
3422               TargetLowering::ZeroOrOneBooleanContent &&
3423           BitWidth > 1)
3424         Known.Zero.setBitsFrom(1);
3425       break;
3426     }
3427     LLVM_FALLTHROUGH;
3428   case ISD::ADD:
3429   case ISD::ADDC:
3430   case ISD::ADDE: {
3431     assert(Op.getResNo() == 0 && "We only compute knownbits for the sum here.");
3432 
3433     // With ADDE and ADDCARRY, a carry bit may be added in.
3434     KnownBits Carry(1);
3435     if (Opcode == ISD::ADDE)
3436       // Can't track carry from glue, set carry to unknown.
3437       Carry.resetAll();
3438     else if (Opcode == ISD::ADDCARRY)
3439       // TODO: Compute known bits for the carry operand. Not sure if it is worth
3440       // the trouble (how often will we find a known carry bit). And I haven't
3441       // tested this very much yet, but something like this might work:
3442       //   Carry = computeKnownBits(Op.getOperand(2), DemandedElts, Depth + 1);
3443       //   Carry = Carry.zextOrTrunc(1, false);
3444       Carry.resetAll();
3445     else
3446       Carry.setAllZero();
3447 
3448     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3449     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3450     Known = KnownBits::computeForAddCarry(Known, Known2, Carry);
3451     break;
3452   }
3453   case ISD::SREM: {
3454     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3455     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3456     Known = KnownBits::srem(Known, Known2);
3457     break;
3458   }
3459   case ISD::UREM: {
3460     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3461     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3462     Known = KnownBits::urem(Known, Known2);
3463     break;
3464   }
3465   case ISD::EXTRACT_ELEMENT: {
3466     Known = computeKnownBits(Op.getOperand(0), Depth+1);
3467     const unsigned Index = Op.getConstantOperandVal(1);
3468     const unsigned EltBitWidth = Op.getValueSizeInBits();
3469 
3470     // Remove low part of known bits mask
3471     Known.Zero = Known.Zero.getHiBits(Known.getBitWidth() - Index * EltBitWidth);
3472     Known.One = Known.One.getHiBits(Known.getBitWidth() - Index * EltBitWidth);
3473 
3474     // Remove high part of known bit mask
3475     Known = Known.trunc(EltBitWidth);
3476     break;
3477   }
3478   case ISD::EXTRACT_VECTOR_ELT: {
3479     SDValue InVec = Op.getOperand(0);
3480     SDValue EltNo = Op.getOperand(1);
3481     EVT VecVT = InVec.getValueType();
3482     // computeKnownBits not yet implemented for scalable vectors.
3483     if (VecVT.isScalableVector())
3484       break;
3485     const unsigned EltBitWidth = VecVT.getScalarSizeInBits();
3486     const unsigned NumSrcElts = VecVT.getVectorNumElements();
3487 
3488     // If BitWidth > EltBitWidth the value is anyext:ed. So we do not know
3489     // anything about the extended bits.
3490     if (BitWidth > EltBitWidth)
3491       Known = Known.trunc(EltBitWidth);
3492 
3493     // If we know the element index, just demand that vector element, else for
3494     // an unknown element index, ignore DemandedElts and demand them all.
3495     APInt DemandedSrcElts = APInt::getAllOnes(NumSrcElts);
3496     auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
3497     if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts))
3498       DemandedSrcElts =
3499           APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue());
3500 
3501     Known = computeKnownBits(InVec, DemandedSrcElts, Depth + 1);
3502     if (BitWidth > EltBitWidth)
3503       Known = Known.anyext(BitWidth);
3504     break;
3505   }
3506   case ISD::INSERT_VECTOR_ELT: {
3507     // If we know the element index, split the demand between the
3508     // source vector and the inserted element, otherwise assume we need
3509     // the original demanded vector elements and the value.
3510     SDValue InVec = Op.getOperand(0);
3511     SDValue InVal = Op.getOperand(1);
3512     SDValue EltNo = Op.getOperand(2);
3513     bool DemandedVal = true;
3514     APInt DemandedVecElts = DemandedElts;
3515     auto *CEltNo = dyn_cast<ConstantSDNode>(EltNo);
3516     if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) {
3517       unsigned EltIdx = CEltNo->getZExtValue();
3518       DemandedVal = !!DemandedElts[EltIdx];
3519       DemandedVecElts.clearBit(EltIdx);
3520     }
3521     Known.One.setAllBits();
3522     Known.Zero.setAllBits();
3523     if (DemandedVal) {
3524       Known2 = computeKnownBits(InVal, Depth + 1);
3525       Known = KnownBits::commonBits(Known, Known2.zextOrTrunc(BitWidth));
3526     }
3527     if (!!DemandedVecElts) {
3528       Known2 = computeKnownBits(InVec, DemandedVecElts, Depth + 1);
3529       Known = KnownBits::commonBits(Known, Known2);
3530     }
3531     break;
3532   }
3533   case ISD::BITREVERSE: {
3534     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3535     Known = Known2.reverseBits();
3536     break;
3537   }
3538   case ISD::BSWAP: {
3539     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3540     Known = Known2.byteSwap();
3541     break;
3542   }
3543   case ISD::ABS: {
3544     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3545     Known = Known2.abs();
3546     break;
3547   }
3548   case ISD::USUBSAT: {
3549     // The result of usubsat will never be larger than the LHS.
3550     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3551     Known.Zero.setHighBits(Known2.countMinLeadingZeros());
3552     break;
3553   }
3554   case ISD::UMIN: {
3555     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3556     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3557     Known = KnownBits::umin(Known, Known2);
3558     break;
3559   }
3560   case ISD::UMAX: {
3561     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3562     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3563     Known = KnownBits::umax(Known, Known2);
3564     break;
3565   }
3566   case ISD::SMIN:
3567   case ISD::SMAX: {
3568     // If we have a clamp pattern, we know that the number of sign bits will be
3569     // the minimum of the clamp min/max range.
3570     bool IsMax = (Opcode == ISD::SMAX);
3571     ConstantSDNode *CstLow = nullptr, *CstHigh = nullptr;
3572     if ((CstLow = isConstOrConstSplat(Op.getOperand(1), DemandedElts)))
3573       if (Op.getOperand(0).getOpcode() == (IsMax ? ISD::SMIN : ISD::SMAX))
3574         CstHigh =
3575             isConstOrConstSplat(Op.getOperand(0).getOperand(1), DemandedElts);
3576     if (CstLow && CstHigh) {
3577       if (!IsMax)
3578         std::swap(CstLow, CstHigh);
3579 
3580       const APInt &ValueLow = CstLow->getAPIntValue();
3581       const APInt &ValueHigh = CstHigh->getAPIntValue();
3582       if (ValueLow.sle(ValueHigh)) {
3583         unsigned LowSignBits = ValueLow.getNumSignBits();
3584         unsigned HighSignBits = ValueHigh.getNumSignBits();
3585         unsigned MinSignBits = std::min(LowSignBits, HighSignBits);
3586         if (ValueLow.isNegative() && ValueHigh.isNegative()) {
3587           Known.One.setHighBits(MinSignBits);
3588           break;
3589         }
3590         if (ValueLow.isNonNegative() && ValueHigh.isNonNegative()) {
3591           Known.Zero.setHighBits(MinSignBits);
3592           break;
3593         }
3594       }
3595     }
3596 
3597     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3598     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3599     if (IsMax)
3600       Known = KnownBits::smax(Known, Known2);
3601     else
3602       Known = KnownBits::smin(Known, Known2);
3603     break;
3604   }
3605   case ISD::FP_TO_UINT_SAT: {
3606     // FP_TO_UINT_SAT produces an unsigned value that fits in the saturating VT.
3607     EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
3608     Known.Zero |= APInt::getBitsSetFrom(BitWidth, VT.getScalarSizeInBits());
3609     break;
3610   }
3611   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
3612     if (Op.getResNo() == 1) {
3613       // The boolean result conforms to getBooleanContents.
3614       // If we know the result of a setcc has the top bits zero, use this info.
3615       // We know that we have an integer-based boolean since these operations
3616       // are only available for integer.
3617       if (TLI->getBooleanContents(Op.getValueType().isVector(), false) ==
3618               TargetLowering::ZeroOrOneBooleanContent &&
3619           BitWidth > 1)
3620         Known.Zero.setBitsFrom(1);
3621       break;
3622     }
3623     LLVM_FALLTHROUGH;
3624   case ISD::ATOMIC_CMP_SWAP:
3625   case ISD::ATOMIC_SWAP:
3626   case ISD::ATOMIC_LOAD_ADD:
3627   case ISD::ATOMIC_LOAD_SUB:
3628   case ISD::ATOMIC_LOAD_AND:
3629   case ISD::ATOMIC_LOAD_CLR:
3630   case ISD::ATOMIC_LOAD_OR:
3631   case ISD::ATOMIC_LOAD_XOR:
3632   case ISD::ATOMIC_LOAD_NAND:
3633   case ISD::ATOMIC_LOAD_MIN:
3634   case ISD::ATOMIC_LOAD_MAX:
3635   case ISD::ATOMIC_LOAD_UMIN:
3636   case ISD::ATOMIC_LOAD_UMAX:
3637   case ISD::ATOMIC_LOAD: {
3638     unsigned MemBits =
3639         cast<AtomicSDNode>(Op)->getMemoryVT().getScalarSizeInBits();
3640     // If we are looking at the loaded value.
3641     if (Op.getResNo() == 0) {
3642       if (TLI->getExtendForAtomicOps() == ISD::ZERO_EXTEND)
3643         Known.Zero.setBitsFrom(MemBits);
3644     }
3645     break;
3646   }
3647   case ISD::FrameIndex:
3648   case ISD::TargetFrameIndex:
3649     TLI->computeKnownBitsForFrameIndex(cast<FrameIndexSDNode>(Op)->getIndex(),
3650                                        Known, getMachineFunction());
3651     break;
3652 
3653   default:
3654     if (Opcode < ISD::BUILTIN_OP_END)
3655       break;
3656     LLVM_FALLTHROUGH;
3657   case ISD::INTRINSIC_WO_CHAIN:
3658   case ISD::INTRINSIC_W_CHAIN:
3659   case ISD::INTRINSIC_VOID:
3660     // Allow the target to implement this method for its nodes.
3661     TLI->computeKnownBitsForTargetNode(Op, Known, DemandedElts, *this, Depth);
3662     break;
3663   }
3664 
3665   assert(!Known.hasConflict() && "Bits known to be one AND zero?");
3666   return Known;
3667 }
3668 
3669 SelectionDAG::OverflowKind SelectionDAG::computeOverflowKind(SDValue N0,
3670                                                              SDValue N1) const {
3671   // X + 0 never overflow
3672   if (isNullConstant(N1))
3673     return OFK_Never;
3674 
3675   KnownBits N1Known = computeKnownBits(N1);
3676   if (N1Known.Zero.getBoolValue()) {
3677     KnownBits N0Known = computeKnownBits(N0);
3678 
3679     bool overflow;
3680     (void)N0Known.getMaxValue().uadd_ov(N1Known.getMaxValue(), overflow);
3681     if (!overflow)
3682       return OFK_Never;
3683   }
3684 
3685   // mulhi + 1 never overflow
3686   if (N0.getOpcode() == ISD::UMUL_LOHI && N0.getResNo() == 1 &&
3687       (N1Known.getMaxValue() & 0x01) == N1Known.getMaxValue())
3688     return OFK_Never;
3689 
3690   if (N1.getOpcode() == ISD::UMUL_LOHI && N1.getResNo() == 1) {
3691     KnownBits N0Known = computeKnownBits(N0);
3692 
3693     if ((N0Known.getMaxValue() & 0x01) == N0Known.getMaxValue())
3694       return OFK_Never;
3695   }
3696 
3697   return OFK_Sometime;
3698 }
3699 
3700 bool SelectionDAG::isKnownToBeAPowerOfTwo(SDValue Val) const {
3701   EVT OpVT = Val.getValueType();
3702   unsigned BitWidth = OpVT.getScalarSizeInBits();
3703 
3704   // Is the constant a known power of 2?
3705   if (ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Val))
3706     return Const->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2();
3707 
3708   // A left-shift of a constant one will have exactly one bit set because
3709   // shifting the bit off the end is undefined.
3710   if (Val.getOpcode() == ISD::SHL) {
3711     auto *C = isConstOrConstSplat(Val.getOperand(0));
3712     if (C && C->getAPIntValue() == 1)
3713       return true;
3714   }
3715 
3716   // Similarly, a logical right-shift of a constant sign-bit will have exactly
3717   // one bit set.
3718   if (Val.getOpcode() == ISD::SRL) {
3719     auto *C = isConstOrConstSplat(Val.getOperand(0));
3720     if (C && C->getAPIntValue().isSignMask())
3721       return true;
3722   }
3723 
3724   // Are all operands of a build vector constant powers of two?
3725   if (Val.getOpcode() == ISD::BUILD_VECTOR)
3726     if (llvm::all_of(Val->ops(), [BitWidth](SDValue E) {
3727           if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(E))
3728             return C->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2();
3729           return false;
3730         }))
3731       return true;
3732 
3733   // Is the operand of a splat vector a constant power of two?
3734   if (Val.getOpcode() == ISD::SPLAT_VECTOR)
3735     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val->getOperand(0)))
3736       if (C->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2())
3737         return true;
3738 
3739   // More could be done here, though the above checks are enough
3740   // to handle some common cases.
3741 
3742   // Fall back to computeKnownBits to catch other known cases.
3743   KnownBits Known = computeKnownBits(Val);
3744   return (Known.countMaxPopulation() == 1) && (Known.countMinPopulation() == 1);
3745 }
3746 
3747 unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, unsigned Depth) const {
3748   EVT VT = Op.getValueType();
3749 
3750   // TODO: Assume we don't know anything for now.
3751   if (VT.isScalableVector())
3752     return 1;
3753 
3754   APInt DemandedElts = VT.isVector()
3755                            ? APInt::getAllOnes(VT.getVectorNumElements())
3756                            : APInt(1, 1);
3757   return ComputeNumSignBits(Op, DemandedElts, Depth);
3758 }
3759 
3760 unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, const APInt &DemandedElts,
3761                                           unsigned Depth) const {
3762   EVT VT = Op.getValueType();
3763   assert((VT.isInteger() || VT.isFloatingPoint()) && "Invalid VT!");
3764   unsigned VTBits = VT.getScalarSizeInBits();
3765   unsigned NumElts = DemandedElts.getBitWidth();
3766   unsigned Tmp, Tmp2;
3767   unsigned FirstAnswer = 1;
3768 
3769   if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
3770     const APInt &Val = C->getAPIntValue();
3771     return Val.getNumSignBits();
3772   }
3773 
3774   if (Depth >= MaxRecursionDepth)
3775     return 1;  // Limit search depth.
3776 
3777   if (!DemandedElts || VT.isScalableVector())
3778     return 1;  // No demanded elts, better to assume we don't know anything.
3779 
3780   unsigned Opcode = Op.getOpcode();
3781   switch (Opcode) {
3782   default: break;
3783   case ISD::AssertSext:
3784     Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
3785     return VTBits-Tmp+1;
3786   case ISD::AssertZext:
3787     Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
3788     return VTBits-Tmp;
3789 
3790   case ISD::BUILD_VECTOR:
3791     Tmp = VTBits;
3792     for (unsigned i = 0, e = Op.getNumOperands(); (i < e) && (Tmp > 1); ++i) {
3793       if (!DemandedElts[i])
3794         continue;
3795 
3796       SDValue SrcOp = Op.getOperand(i);
3797       Tmp2 = ComputeNumSignBits(SrcOp, Depth + 1);
3798 
3799       // BUILD_VECTOR can implicitly truncate sources, we must handle this.
3800       if (SrcOp.getValueSizeInBits() != VTBits) {
3801         assert(SrcOp.getValueSizeInBits() > VTBits &&
3802                "Expected BUILD_VECTOR implicit truncation");
3803         unsigned ExtraBits = SrcOp.getValueSizeInBits() - VTBits;
3804         Tmp2 = (Tmp2 > ExtraBits ? Tmp2 - ExtraBits : 1);
3805       }
3806       Tmp = std::min(Tmp, Tmp2);
3807     }
3808     return Tmp;
3809 
3810   case ISD::VECTOR_SHUFFLE: {
3811     // Collect the minimum number of sign bits that are shared by every vector
3812     // element referenced by the shuffle.
3813     APInt DemandedLHS(NumElts, 0), DemandedRHS(NumElts, 0);
3814     const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op);
3815     assert(NumElts == SVN->getMask().size() && "Unexpected vector size");
3816     for (unsigned i = 0; i != NumElts; ++i) {
3817       int M = SVN->getMaskElt(i);
3818       if (!DemandedElts[i])
3819         continue;
3820       // For UNDEF elements, we don't know anything about the common state of
3821       // the shuffle result.
3822       if (M < 0)
3823         return 1;
3824       if ((unsigned)M < NumElts)
3825         DemandedLHS.setBit((unsigned)M % NumElts);
3826       else
3827         DemandedRHS.setBit((unsigned)M % NumElts);
3828     }
3829     Tmp = std::numeric_limits<unsigned>::max();
3830     if (!!DemandedLHS)
3831       Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedLHS, Depth + 1);
3832     if (!!DemandedRHS) {
3833       Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedRHS, Depth + 1);
3834       Tmp = std::min(Tmp, Tmp2);
3835     }
3836     // If we don't know anything, early out and try computeKnownBits fall-back.
3837     if (Tmp == 1)
3838       break;
3839     assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
3840     return Tmp;
3841   }
3842 
3843   case ISD::BITCAST: {
3844     SDValue N0 = Op.getOperand(0);
3845     EVT SrcVT = N0.getValueType();
3846     unsigned SrcBits = SrcVT.getScalarSizeInBits();
3847 
3848     // Ignore bitcasts from unsupported types..
3849     if (!(SrcVT.isInteger() || SrcVT.isFloatingPoint()))
3850       break;
3851 
3852     // Fast handling of 'identity' bitcasts.
3853     if (VTBits == SrcBits)
3854       return ComputeNumSignBits(N0, DemandedElts, Depth + 1);
3855 
3856     bool IsLE = getDataLayout().isLittleEndian();
3857 
3858     // Bitcast 'large element' scalar/vector to 'small element' vector.
3859     if ((SrcBits % VTBits) == 0) {
3860       assert(VT.isVector() && "Expected bitcast to vector");
3861 
3862       unsigned Scale = SrcBits / VTBits;
3863       APInt SrcDemandedElts =
3864           APIntOps::ScaleBitMask(DemandedElts, NumElts / Scale);
3865 
3866       // Fast case - sign splat can be simply split across the small elements.
3867       Tmp = ComputeNumSignBits(N0, SrcDemandedElts, Depth + 1);
3868       if (Tmp == SrcBits)
3869         return VTBits;
3870 
3871       // Slow case - determine how far the sign extends into each sub-element.
3872       Tmp2 = VTBits;
3873       for (unsigned i = 0; i != NumElts; ++i)
3874         if (DemandedElts[i]) {
3875           unsigned SubOffset = i % Scale;
3876           SubOffset = (IsLE ? ((Scale - 1) - SubOffset) : SubOffset);
3877           SubOffset = SubOffset * VTBits;
3878           if (Tmp <= SubOffset)
3879             return 1;
3880           Tmp2 = std::min(Tmp2, Tmp - SubOffset);
3881         }
3882       return Tmp2;
3883     }
3884     break;
3885   }
3886 
3887   case ISD::FP_TO_SINT_SAT:
3888     // FP_TO_SINT_SAT produces a signed value that fits in the saturating VT.
3889     Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getScalarSizeInBits();
3890     return VTBits - Tmp + 1;
3891   case ISD::SIGN_EXTEND:
3892     Tmp = VTBits - Op.getOperand(0).getScalarValueSizeInBits();
3893     return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1) + Tmp;
3894   case ISD::SIGN_EXTEND_INREG:
3895     // Max of the input and what this extends.
3896     Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getScalarSizeInBits();
3897     Tmp = VTBits-Tmp+1;
3898     Tmp2 = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1);
3899     return std::max(Tmp, Tmp2);
3900   case ISD::SIGN_EXTEND_VECTOR_INREG: {
3901     SDValue Src = Op.getOperand(0);
3902     EVT SrcVT = Src.getValueType();
3903     APInt DemandedSrcElts = DemandedElts.zextOrSelf(SrcVT.getVectorNumElements());
3904     Tmp = VTBits - SrcVT.getScalarSizeInBits();
3905     return ComputeNumSignBits(Src, DemandedSrcElts, Depth+1) + Tmp;
3906   }
3907   case ISD::SRA:
3908     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
3909     // SRA X, C -> adds C sign bits.
3910     if (const APInt *ShAmt =
3911             getValidMinimumShiftAmountConstant(Op, DemandedElts))
3912       Tmp = std::min<uint64_t>(Tmp + ShAmt->getZExtValue(), VTBits);
3913     return Tmp;
3914   case ISD::SHL:
3915     if (const APInt *ShAmt =
3916             getValidMaximumShiftAmountConstant(Op, DemandedElts)) {
3917       // shl destroys sign bits, ensure it doesn't shift out all sign bits.
3918       Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
3919       if (ShAmt->ult(Tmp))
3920         return Tmp - ShAmt->getZExtValue();
3921     }
3922     break;
3923   case ISD::AND:
3924   case ISD::OR:
3925   case ISD::XOR:    // NOT is handled here.
3926     // Logical binary ops preserve the number of sign bits at the worst.
3927     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1);
3928     if (Tmp != 1) {
3929       Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth+1);
3930       FirstAnswer = std::min(Tmp, Tmp2);
3931       // We computed what we know about the sign bits as our first
3932       // answer. Now proceed to the generic code that uses
3933       // computeKnownBits, and pick whichever answer is better.
3934     }
3935     break;
3936 
3937   case ISD::SELECT:
3938   case ISD::VSELECT:
3939     Tmp = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth+1);
3940     if (Tmp == 1) return 1;  // Early out.
3941     Tmp2 = ComputeNumSignBits(Op.getOperand(2), DemandedElts, Depth+1);
3942     return std::min(Tmp, Tmp2);
3943   case ISD::SELECT_CC:
3944     Tmp = ComputeNumSignBits(Op.getOperand(2), DemandedElts, Depth+1);
3945     if (Tmp == 1) return 1;  // Early out.
3946     Tmp2 = ComputeNumSignBits(Op.getOperand(3), DemandedElts, Depth+1);
3947     return std::min(Tmp, Tmp2);
3948 
3949   case ISD::SMIN:
3950   case ISD::SMAX: {
3951     // If we have a clamp pattern, we know that the number of sign bits will be
3952     // the minimum of the clamp min/max range.
3953     bool IsMax = (Opcode == ISD::SMAX);
3954     ConstantSDNode *CstLow = nullptr, *CstHigh = nullptr;
3955     if ((CstLow = isConstOrConstSplat(Op.getOperand(1), DemandedElts)))
3956       if (Op.getOperand(0).getOpcode() == (IsMax ? ISD::SMIN : ISD::SMAX))
3957         CstHigh =
3958             isConstOrConstSplat(Op.getOperand(0).getOperand(1), DemandedElts);
3959     if (CstLow && CstHigh) {
3960       if (!IsMax)
3961         std::swap(CstLow, CstHigh);
3962       if (CstLow->getAPIntValue().sle(CstHigh->getAPIntValue())) {
3963         Tmp = CstLow->getAPIntValue().getNumSignBits();
3964         Tmp2 = CstHigh->getAPIntValue().getNumSignBits();
3965         return std::min(Tmp, Tmp2);
3966       }
3967     }
3968 
3969     // Fallback - just get the minimum number of sign bits of the operands.
3970     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
3971     if (Tmp == 1)
3972       return 1;  // Early out.
3973     Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
3974     return std::min(Tmp, Tmp2);
3975   }
3976   case ISD::UMIN:
3977   case ISD::UMAX:
3978     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
3979     if (Tmp == 1)
3980       return 1;  // Early out.
3981     Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
3982     return std::min(Tmp, Tmp2);
3983   case ISD::SADDO:
3984   case ISD::UADDO:
3985   case ISD::SSUBO:
3986   case ISD::USUBO:
3987   case ISD::SMULO:
3988   case ISD::UMULO:
3989     if (Op.getResNo() != 1)
3990       break;
3991     // The boolean result conforms to getBooleanContents.  Fall through.
3992     // If setcc returns 0/-1, all bits are sign bits.
3993     // We know that we have an integer-based boolean since these operations
3994     // are only available for integer.
3995     if (TLI->getBooleanContents(VT.isVector(), false) ==
3996         TargetLowering::ZeroOrNegativeOneBooleanContent)
3997       return VTBits;
3998     break;
3999   case ISD::SETCC:
4000   case ISD::STRICT_FSETCC:
4001   case ISD::STRICT_FSETCCS: {
4002     unsigned OpNo = Op->isStrictFPOpcode() ? 1 : 0;
4003     // If setcc returns 0/-1, all bits are sign bits.
4004     if (TLI->getBooleanContents(Op.getOperand(OpNo).getValueType()) ==
4005         TargetLowering::ZeroOrNegativeOneBooleanContent)
4006       return VTBits;
4007     break;
4008   }
4009   case ISD::ROTL:
4010   case ISD::ROTR:
4011     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
4012 
4013     // If we're rotating an 0/-1 value, then it stays an 0/-1 value.
4014     if (Tmp == VTBits)
4015       return VTBits;
4016 
4017     if (ConstantSDNode *C =
4018             isConstOrConstSplat(Op.getOperand(1), DemandedElts)) {
4019       unsigned RotAmt = C->getAPIntValue().urem(VTBits);
4020 
4021       // Handle rotate right by N like a rotate left by 32-N.
4022       if (Opcode == ISD::ROTR)
4023         RotAmt = (VTBits - RotAmt) % VTBits;
4024 
4025       // If we aren't rotating out all of the known-in sign bits, return the
4026       // number that are left.  This handles rotl(sext(x), 1) for example.
4027       if (Tmp > (RotAmt + 1)) return (Tmp - RotAmt);
4028     }
4029     break;
4030   case ISD::ADD:
4031   case ISD::ADDC:
4032     // Add can have at most one carry bit.  Thus we know that the output
4033     // is, at worst, one more bit than the inputs.
4034     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
4035     if (Tmp == 1) return 1; // Early out.
4036 
4037     // Special case decrementing a value (ADD X, -1):
4038     if (ConstantSDNode *CRHS =
4039             isConstOrConstSplat(Op.getOperand(1), DemandedElts))
4040       if (CRHS->isAllOnes()) {
4041         KnownBits Known =
4042             computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4043 
4044         // If the input is known to be 0 or 1, the output is 0/-1, which is all
4045         // sign bits set.
4046         if ((Known.Zero | 1).isAllOnes())
4047           return VTBits;
4048 
4049         // If we are subtracting one from a positive number, there is no carry
4050         // out of the result.
4051         if (Known.isNonNegative())
4052           return Tmp;
4053       }
4054 
4055     Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
4056     if (Tmp2 == 1) return 1; // Early out.
4057     return std::min(Tmp, Tmp2) - 1;
4058   case ISD::SUB:
4059     Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
4060     if (Tmp2 == 1) return 1; // Early out.
4061 
4062     // Handle NEG.
4063     if (ConstantSDNode *CLHS =
4064             isConstOrConstSplat(Op.getOperand(0), DemandedElts))
4065       if (CLHS->isZero()) {
4066         KnownBits Known =
4067             computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4068         // If the input is known to be 0 or 1, the output is 0/-1, which is all
4069         // sign bits set.
4070         if ((Known.Zero | 1).isAllOnes())
4071           return VTBits;
4072 
4073         // If the input is known to be positive (the sign bit is known clear),
4074         // the output of the NEG has the same number of sign bits as the input.
4075         if (Known.isNonNegative())
4076           return Tmp2;
4077 
4078         // Otherwise, we treat this like a SUB.
4079       }
4080 
4081     // Sub can have at most one carry bit.  Thus we know that the output
4082     // is, at worst, one more bit than the inputs.
4083     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
4084     if (Tmp == 1) return 1; // Early out.
4085     return std::min(Tmp, Tmp2) - 1;
4086   case ISD::MUL: {
4087     // The output of the Mul can be at most twice the valid bits in the inputs.
4088     unsigned SignBitsOp0 = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
4089     if (SignBitsOp0 == 1)
4090       break;
4091     unsigned SignBitsOp1 = ComputeNumSignBits(Op.getOperand(1), Depth + 1);
4092     if (SignBitsOp1 == 1)
4093       break;
4094     unsigned OutValidBits =
4095         (VTBits - SignBitsOp0 + 1) + (VTBits - SignBitsOp1 + 1);
4096     return OutValidBits > VTBits ? 1 : VTBits - OutValidBits + 1;
4097   }
4098   case ISD::SREM:
4099     // The sign bit is the LHS's sign bit, except when the result of the
4100     // remainder is zero. The magnitude of the result should be less than or
4101     // equal to the magnitude of the LHS. Therefore, the result should have
4102     // at least as many sign bits as the left hand side.
4103     return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
4104   case ISD::TRUNCATE: {
4105     // Check if the sign bits of source go down as far as the truncated value.
4106     unsigned NumSrcBits = Op.getOperand(0).getScalarValueSizeInBits();
4107     unsigned NumSrcSignBits = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
4108     if (NumSrcSignBits > (NumSrcBits - VTBits))
4109       return NumSrcSignBits - (NumSrcBits - VTBits);
4110     break;
4111   }
4112   case ISD::EXTRACT_ELEMENT: {
4113     const int KnownSign = ComputeNumSignBits(Op.getOperand(0), Depth+1);
4114     const int BitWidth = Op.getValueSizeInBits();
4115     const int Items = Op.getOperand(0).getValueSizeInBits() / BitWidth;
4116 
4117     // Get reverse index (starting from 1), Op1 value indexes elements from
4118     // little end. Sign starts at big end.
4119     const int rIndex = Items - 1 - Op.getConstantOperandVal(1);
4120 
4121     // If the sign portion ends in our element the subtraction gives correct
4122     // result. Otherwise it gives either negative or > bitwidth result
4123     return std::max(std::min(KnownSign - rIndex * BitWidth, BitWidth), 0);
4124   }
4125   case ISD::INSERT_VECTOR_ELT: {
4126     // If we know the element index, split the demand between the
4127     // source vector and the inserted element, otherwise assume we need
4128     // the original demanded vector elements and the value.
4129     SDValue InVec = Op.getOperand(0);
4130     SDValue InVal = Op.getOperand(1);
4131     SDValue EltNo = Op.getOperand(2);
4132     bool DemandedVal = true;
4133     APInt DemandedVecElts = DemandedElts;
4134     auto *CEltNo = dyn_cast<ConstantSDNode>(EltNo);
4135     if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) {
4136       unsigned EltIdx = CEltNo->getZExtValue();
4137       DemandedVal = !!DemandedElts[EltIdx];
4138       DemandedVecElts.clearBit(EltIdx);
4139     }
4140     Tmp = std::numeric_limits<unsigned>::max();
4141     if (DemandedVal) {
4142       // TODO - handle implicit truncation of inserted elements.
4143       if (InVal.getScalarValueSizeInBits() != VTBits)
4144         break;
4145       Tmp2 = ComputeNumSignBits(InVal, Depth + 1);
4146       Tmp = std::min(Tmp, Tmp2);
4147     }
4148     if (!!DemandedVecElts) {
4149       Tmp2 = ComputeNumSignBits(InVec, DemandedVecElts, Depth + 1);
4150       Tmp = std::min(Tmp, Tmp2);
4151     }
4152     assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
4153     return Tmp;
4154   }
4155   case ISD::EXTRACT_VECTOR_ELT: {
4156     SDValue InVec = Op.getOperand(0);
4157     SDValue EltNo = Op.getOperand(1);
4158     EVT VecVT = InVec.getValueType();
4159     // ComputeNumSignBits not yet implemented for scalable vectors.
4160     if (VecVT.isScalableVector())
4161       break;
4162     const unsigned BitWidth = Op.getValueSizeInBits();
4163     const unsigned EltBitWidth = Op.getOperand(0).getScalarValueSizeInBits();
4164     const unsigned NumSrcElts = VecVT.getVectorNumElements();
4165 
4166     // If BitWidth > EltBitWidth the value is anyext:ed, and we do not know
4167     // anything about sign bits. But if the sizes match we can derive knowledge
4168     // about sign bits from the vector operand.
4169     if (BitWidth != EltBitWidth)
4170       break;
4171 
4172     // If we know the element index, just demand that vector element, else for
4173     // an unknown element index, ignore DemandedElts and demand them all.
4174     APInt DemandedSrcElts = APInt::getAllOnes(NumSrcElts);
4175     auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
4176     if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts))
4177       DemandedSrcElts =
4178           APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue());
4179 
4180     return ComputeNumSignBits(InVec, DemandedSrcElts, Depth + 1);
4181   }
4182   case ISD::EXTRACT_SUBVECTOR: {
4183     // Offset the demanded elts by the subvector index.
4184     SDValue Src = Op.getOperand(0);
4185     // Bail until we can represent demanded elements for scalable vectors.
4186     if (Src.getValueType().isScalableVector())
4187       break;
4188     uint64_t Idx = Op.getConstantOperandVal(1);
4189     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
4190     APInt DemandedSrcElts = DemandedElts.zextOrSelf(NumSrcElts).shl(Idx);
4191     return ComputeNumSignBits(Src, DemandedSrcElts, Depth + 1);
4192   }
4193   case ISD::CONCAT_VECTORS: {
4194     // Determine the minimum number of sign bits across all demanded
4195     // elts of the input vectors. Early out if the result is already 1.
4196     Tmp = std::numeric_limits<unsigned>::max();
4197     EVT SubVectorVT = Op.getOperand(0).getValueType();
4198     unsigned NumSubVectorElts = SubVectorVT.getVectorNumElements();
4199     unsigned NumSubVectors = Op.getNumOperands();
4200     for (unsigned i = 0; (i < NumSubVectors) && (Tmp > 1); ++i) {
4201       APInt DemandedSub =
4202           DemandedElts.extractBits(NumSubVectorElts, i * NumSubVectorElts);
4203       if (!DemandedSub)
4204         continue;
4205       Tmp2 = ComputeNumSignBits(Op.getOperand(i), DemandedSub, Depth + 1);
4206       Tmp = std::min(Tmp, Tmp2);
4207     }
4208     assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
4209     return Tmp;
4210   }
4211   case ISD::INSERT_SUBVECTOR: {
4212     // Demand any elements from the subvector and the remainder from the src its
4213     // inserted into.
4214     SDValue Src = Op.getOperand(0);
4215     SDValue Sub = Op.getOperand(1);
4216     uint64_t Idx = Op.getConstantOperandVal(2);
4217     unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
4218     APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
4219     APInt DemandedSrcElts = DemandedElts;
4220     DemandedSrcElts.insertBits(APInt::getZero(NumSubElts), Idx);
4221 
4222     Tmp = std::numeric_limits<unsigned>::max();
4223     if (!!DemandedSubElts) {
4224       Tmp = ComputeNumSignBits(Sub, DemandedSubElts, Depth + 1);
4225       if (Tmp == 1)
4226         return 1; // early-out
4227     }
4228     if (!!DemandedSrcElts) {
4229       Tmp2 = ComputeNumSignBits(Src, DemandedSrcElts, Depth + 1);
4230       Tmp = std::min(Tmp, Tmp2);
4231     }
4232     assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
4233     return Tmp;
4234   }
4235   case ISD::ATOMIC_CMP_SWAP:
4236   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
4237   case ISD::ATOMIC_SWAP:
4238   case ISD::ATOMIC_LOAD_ADD:
4239   case ISD::ATOMIC_LOAD_SUB:
4240   case ISD::ATOMIC_LOAD_AND:
4241   case ISD::ATOMIC_LOAD_CLR:
4242   case ISD::ATOMIC_LOAD_OR:
4243   case ISD::ATOMIC_LOAD_XOR:
4244   case ISD::ATOMIC_LOAD_NAND:
4245   case ISD::ATOMIC_LOAD_MIN:
4246   case ISD::ATOMIC_LOAD_MAX:
4247   case ISD::ATOMIC_LOAD_UMIN:
4248   case ISD::ATOMIC_LOAD_UMAX:
4249   case ISD::ATOMIC_LOAD: {
4250     Tmp = cast<AtomicSDNode>(Op)->getMemoryVT().getScalarSizeInBits();
4251     // If we are looking at the loaded value.
4252     if (Op.getResNo() == 0) {
4253       if (Tmp == VTBits)
4254         return 1; // early-out
4255       if (TLI->getExtendForAtomicOps() == ISD::SIGN_EXTEND)
4256         return VTBits - Tmp + 1;
4257       if (TLI->getExtendForAtomicOps() == ISD::ZERO_EXTEND)
4258         return VTBits - Tmp;
4259     }
4260     break;
4261   }
4262   }
4263 
4264   // If we are looking at the loaded value of the SDNode.
4265   if (Op.getResNo() == 0) {
4266     // Handle LOADX separately here. EXTLOAD case will fallthrough.
4267     if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
4268       unsigned ExtType = LD->getExtensionType();
4269       switch (ExtType) {
4270       default: break;
4271       case ISD::SEXTLOAD: // e.g. i16->i32 = '17' bits known.
4272         Tmp = LD->getMemoryVT().getScalarSizeInBits();
4273         return VTBits - Tmp + 1;
4274       case ISD::ZEXTLOAD: // e.g. i16->i32 = '16' bits known.
4275         Tmp = LD->getMemoryVT().getScalarSizeInBits();
4276         return VTBits - Tmp;
4277       case ISD::NON_EXTLOAD:
4278         if (const Constant *Cst = TLI->getTargetConstantFromLoad(LD)) {
4279           // We only need to handle vectors - computeKnownBits should handle
4280           // scalar cases.
4281           Type *CstTy = Cst->getType();
4282           if (CstTy->isVectorTy() &&
4283               (NumElts * VTBits) == CstTy->getPrimitiveSizeInBits()) {
4284             Tmp = VTBits;
4285             for (unsigned i = 0; i != NumElts; ++i) {
4286               if (!DemandedElts[i])
4287                 continue;
4288               if (Constant *Elt = Cst->getAggregateElement(i)) {
4289                 if (auto *CInt = dyn_cast<ConstantInt>(Elt)) {
4290                   const APInt &Value = CInt->getValue();
4291                   Tmp = std::min(Tmp, Value.getNumSignBits());
4292                   continue;
4293                 }
4294                 if (auto *CFP = dyn_cast<ConstantFP>(Elt)) {
4295                   APInt Value = CFP->getValueAPF().bitcastToAPInt();
4296                   Tmp = std::min(Tmp, Value.getNumSignBits());
4297                   continue;
4298                 }
4299               }
4300               // Unknown type. Conservatively assume no bits match sign bit.
4301               return 1;
4302             }
4303             return Tmp;
4304           }
4305         }
4306         break;
4307       }
4308     }
4309   }
4310 
4311   // Allow the target to implement this method for its nodes.
4312   if (Opcode >= ISD::BUILTIN_OP_END ||
4313       Opcode == ISD::INTRINSIC_WO_CHAIN ||
4314       Opcode == ISD::INTRINSIC_W_CHAIN ||
4315       Opcode == ISD::INTRINSIC_VOID) {
4316     unsigned NumBits =
4317         TLI->ComputeNumSignBitsForTargetNode(Op, DemandedElts, *this, Depth);
4318     if (NumBits > 1)
4319       FirstAnswer = std::max(FirstAnswer, NumBits);
4320   }
4321 
4322   // Finally, if we can prove that the top bits of the result are 0's or 1's,
4323   // use this information.
4324   KnownBits Known = computeKnownBits(Op, DemandedElts, Depth);
4325   return std::max(FirstAnswer, Known.countMinSignBits());
4326 }
4327 
4328 unsigned SelectionDAG::ComputeMaxSignificantBits(SDValue Op,
4329                                                  unsigned Depth) const {
4330   unsigned SignBits = ComputeNumSignBits(Op, Depth);
4331   return Op.getScalarValueSizeInBits() - SignBits + 1;
4332 }
4333 
4334 unsigned SelectionDAG::ComputeMaxSignificantBits(SDValue Op,
4335                                                  const APInt &DemandedElts,
4336                                                  unsigned Depth) const {
4337   unsigned SignBits = ComputeNumSignBits(Op, DemandedElts, Depth);
4338   return Op.getScalarValueSizeInBits() - SignBits + 1;
4339 }
4340 
4341 bool SelectionDAG::isGuaranteedNotToBeUndefOrPoison(SDValue Op, bool PoisonOnly,
4342                                                     unsigned Depth) const {
4343   // Early out for FREEZE.
4344   if (Op.getOpcode() == ISD::FREEZE)
4345     return true;
4346 
4347   // TODO: Assume we don't know anything for now.
4348   EVT VT = Op.getValueType();
4349   if (VT.isScalableVector())
4350     return false;
4351 
4352   APInt DemandedElts = VT.isVector()
4353                            ? APInt::getAllOnes(VT.getVectorNumElements())
4354                            : APInt(1, 1);
4355   return isGuaranteedNotToBeUndefOrPoison(Op, DemandedElts, PoisonOnly, Depth);
4356 }
4357 
4358 bool SelectionDAG::isGuaranteedNotToBeUndefOrPoison(SDValue Op,
4359                                                     const APInt &DemandedElts,
4360                                                     bool PoisonOnly,
4361                                                     unsigned Depth) const {
4362   unsigned Opcode = Op.getOpcode();
4363 
4364   // Early out for FREEZE.
4365   if (Opcode == ISD::FREEZE)
4366     return true;
4367 
4368   if (Depth >= MaxRecursionDepth)
4369     return false; // Limit search depth.
4370 
4371   if (isIntOrFPConstant(Op))
4372     return true;
4373 
4374   switch (Opcode) {
4375   case ISD::UNDEF:
4376     return PoisonOnly;
4377 
4378   case ISD::BUILD_VECTOR:
4379     // NOTE: BUILD_VECTOR has implicit truncation of wider scalar elements -
4380     // this shouldn't affect the result.
4381     for (unsigned i = 0, e = Op.getNumOperands(); i < e; ++i) {
4382       if (!DemandedElts[i])
4383         continue;
4384       if (!isGuaranteedNotToBeUndefOrPoison(Op.getOperand(i), PoisonOnly,
4385                                             Depth + 1))
4386         return false;
4387     }
4388     return true;
4389 
4390   // TODO: Search for noundef attributes from library functions.
4391 
4392   // TODO: Pointers dereferenced by ISD::LOAD/STORE ops are noundef.
4393 
4394   default:
4395     // Allow the target to implement this method for its nodes.
4396     if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::INTRINSIC_WO_CHAIN ||
4397         Opcode == ISD::INTRINSIC_W_CHAIN || Opcode == ISD::INTRINSIC_VOID)
4398       return TLI->isGuaranteedNotToBeUndefOrPoisonForTargetNode(
4399           Op, DemandedElts, *this, PoisonOnly, Depth);
4400     break;
4401   }
4402 
4403   return false;
4404 }
4405 
4406 bool SelectionDAG::isBaseWithConstantOffset(SDValue Op) const {
4407   if ((Op.getOpcode() != ISD::ADD && Op.getOpcode() != ISD::OR) ||
4408       !isa<ConstantSDNode>(Op.getOperand(1)))
4409     return false;
4410 
4411   if (Op.getOpcode() == ISD::OR &&
4412       !MaskedValueIsZero(Op.getOperand(0), Op.getConstantOperandAPInt(1)))
4413     return false;
4414 
4415   return true;
4416 }
4417 
4418 bool SelectionDAG::isKnownNeverNaN(SDValue Op, bool SNaN, unsigned Depth) const {
4419   // If we're told that NaNs won't happen, assume they won't.
4420   if (getTarget().Options.NoNaNsFPMath || Op->getFlags().hasNoNaNs())
4421     return true;
4422 
4423   if (Depth >= MaxRecursionDepth)
4424     return false; // Limit search depth.
4425 
4426   // TODO: Handle vectors.
4427   // If the value is a constant, we can obviously see if it is a NaN or not.
4428   if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) {
4429     return !C->getValueAPF().isNaN() ||
4430            (SNaN && !C->getValueAPF().isSignaling());
4431   }
4432 
4433   unsigned Opcode = Op.getOpcode();
4434   switch (Opcode) {
4435   case ISD::FADD:
4436   case ISD::FSUB:
4437   case ISD::FMUL:
4438   case ISD::FDIV:
4439   case ISD::FREM:
4440   case ISD::FSIN:
4441   case ISD::FCOS: {
4442     if (SNaN)
4443       return true;
4444     // TODO: Need isKnownNeverInfinity
4445     return false;
4446   }
4447   case ISD::FCANONICALIZE:
4448   case ISD::FEXP:
4449   case ISD::FEXP2:
4450   case ISD::FTRUNC:
4451   case ISD::FFLOOR:
4452   case ISD::FCEIL:
4453   case ISD::FROUND:
4454   case ISD::FROUNDEVEN:
4455   case ISD::FRINT:
4456   case ISD::FNEARBYINT: {
4457     if (SNaN)
4458       return true;
4459     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
4460   }
4461   case ISD::FABS:
4462   case ISD::FNEG:
4463   case ISD::FCOPYSIGN: {
4464     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
4465   }
4466   case ISD::SELECT:
4467     return isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1) &&
4468            isKnownNeverNaN(Op.getOperand(2), SNaN, Depth + 1);
4469   case ISD::FP_EXTEND:
4470   case ISD::FP_ROUND: {
4471     if (SNaN)
4472       return true;
4473     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
4474   }
4475   case ISD::SINT_TO_FP:
4476   case ISD::UINT_TO_FP:
4477     return true;
4478   case ISD::FMA:
4479   case ISD::FMAD: {
4480     if (SNaN)
4481       return true;
4482     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) &&
4483            isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1) &&
4484            isKnownNeverNaN(Op.getOperand(2), SNaN, Depth + 1);
4485   }
4486   case ISD::FSQRT: // Need is known positive
4487   case ISD::FLOG:
4488   case ISD::FLOG2:
4489   case ISD::FLOG10:
4490   case ISD::FPOWI:
4491   case ISD::FPOW: {
4492     if (SNaN)
4493       return true;
4494     // TODO: Refine on operand
4495     return false;
4496   }
4497   case ISD::FMINNUM:
4498   case ISD::FMAXNUM: {
4499     // Only one needs to be known not-nan, since it will be returned if the
4500     // other ends up being one.
4501     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) ||
4502            isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1);
4503   }
4504   case ISD::FMINNUM_IEEE:
4505   case ISD::FMAXNUM_IEEE: {
4506     if (SNaN)
4507       return true;
4508     // This can return a NaN if either operand is an sNaN, or if both operands
4509     // are NaN.
4510     return (isKnownNeverNaN(Op.getOperand(0), false, Depth + 1) &&
4511             isKnownNeverSNaN(Op.getOperand(1), Depth + 1)) ||
4512            (isKnownNeverNaN(Op.getOperand(1), false, Depth + 1) &&
4513             isKnownNeverSNaN(Op.getOperand(0), Depth + 1));
4514   }
4515   case ISD::FMINIMUM:
4516   case ISD::FMAXIMUM: {
4517     // TODO: Does this quiet or return the origina NaN as-is?
4518     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) &&
4519            isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1);
4520   }
4521   case ISD::EXTRACT_VECTOR_ELT: {
4522     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
4523   }
4524   default:
4525     if (Opcode >= ISD::BUILTIN_OP_END ||
4526         Opcode == ISD::INTRINSIC_WO_CHAIN ||
4527         Opcode == ISD::INTRINSIC_W_CHAIN ||
4528         Opcode == ISD::INTRINSIC_VOID) {
4529       return TLI->isKnownNeverNaNForTargetNode(Op, *this, SNaN, Depth);
4530     }
4531 
4532     return false;
4533   }
4534 }
4535 
4536 bool SelectionDAG::isKnownNeverZeroFloat(SDValue Op) const {
4537   assert(Op.getValueType().isFloatingPoint() &&
4538          "Floating point type expected");
4539 
4540   // If the value is a constant, we can obviously see if it is a zero or not.
4541   // TODO: Add BuildVector support.
4542   if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op))
4543     return !C->isZero();
4544   return false;
4545 }
4546 
4547 bool SelectionDAG::isKnownNeverZero(SDValue Op) const {
4548   assert(!Op.getValueType().isFloatingPoint() &&
4549          "Floating point types unsupported - use isKnownNeverZeroFloat");
4550 
4551   // If the value is a constant, we can obviously see if it is a zero or not.
4552   if (ISD::matchUnaryPredicate(Op,
4553                                [](ConstantSDNode *C) { return !C->isZero(); }))
4554     return true;
4555 
4556   // TODO: Recognize more cases here.
4557   switch (Op.getOpcode()) {
4558   default: break;
4559   case ISD::OR:
4560     if (isKnownNeverZero(Op.getOperand(1)) ||
4561         isKnownNeverZero(Op.getOperand(0)))
4562       return true;
4563     break;
4564   }
4565 
4566   return false;
4567 }
4568 
4569 bool SelectionDAG::isEqualTo(SDValue A, SDValue B) const {
4570   // Check the obvious case.
4571   if (A == B) return true;
4572 
4573   // For for negative and positive zero.
4574   if (const ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A))
4575     if (const ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B))
4576       if (CA->isZero() && CB->isZero()) return true;
4577 
4578   // Otherwise they may not be equal.
4579   return false;
4580 }
4581 
4582 // FIXME: unify with llvm::haveNoCommonBitsSet.
4583 bool SelectionDAG::haveNoCommonBitsSet(SDValue A, SDValue B) const {
4584   assert(A.getValueType() == B.getValueType() &&
4585          "Values must have the same type");
4586   // Match masked merge pattern (X & ~M) op (Y & M)
4587   if (A->getOpcode() == ISD::AND && B->getOpcode() == ISD::AND) {
4588     auto MatchNoCommonBitsPattern = [&](SDValue NotM, SDValue And) {
4589       if (isBitwiseNot(NotM, true)) {
4590         SDValue NotOperand = NotM->getOperand(0);
4591         return NotOperand == And->getOperand(0) ||
4592                NotOperand == And->getOperand(1);
4593       }
4594       return false;
4595     };
4596     if (MatchNoCommonBitsPattern(A->getOperand(0), B) ||
4597         MatchNoCommonBitsPattern(A->getOperand(1), B) ||
4598         MatchNoCommonBitsPattern(B->getOperand(0), A) ||
4599         MatchNoCommonBitsPattern(B->getOperand(1), A))
4600       return true;
4601   }
4602   return KnownBits::haveNoCommonBitsSet(computeKnownBits(A),
4603                                         computeKnownBits(B));
4604 }
4605 
4606 static SDValue FoldSTEP_VECTOR(const SDLoc &DL, EVT VT, SDValue Step,
4607                                SelectionDAG &DAG) {
4608   if (cast<ConstantSDNode>(Step)->isZero())
4609     return DAG.getConstant(0, DL, VT);
4610 
4611   return SDValue();
4612 }
4613 
4614 static SDValue FoldBUILD_VECTOR(const SDLoc &DL, EVT VT,
4615                                 ArrayRef<SDValue> Ops,
4616                                 SelectionDAG &DAG) {
4617   int NumOps = Ops.size();
4618   assert(NumOps != 0 && "Can't build an empty vector!");
4619   assert(!VT.isScalableVector() &&
4620          "BUILD_VECTOR cannot be used with scalable types");
4621   assert(VT.getVectorNumElements() == (unsigned)NumOps &&
4622          "Incorrect element count in BUILD_VECTOR!");
4623 
4624   // BUILD_VECTOR of UNDEFs is UNDEF.
4625   if (llvm::all_of(Ops, [](SDValue Op) { return Op.isUndef(); }))
4626     return DAG.getUNDEF(VT);
4627 
4628   // BUILD_VECTOR of seq extract/insert from the same vector + type is Identity.
4629   SDValue IdentitySrc;
4630   bool IsIdentity = true;
4631   for (int i = 0; i != NumOps; ++i) {
4632     if (Ops[i].getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
4633         Ops[i].getOperand(0).getValueType() != VT ||
4634         (IdentitySrc && Ops[i].getOperand(0) != IdentitySrc) ||
4635         !isa<ConstantSDNode>(Ops[i].getOperand(1)) ||
4636         cast<ConstantSDNode>(Ops[i].getOperand(1))->getAPIntValue() != i) {
4637       IsIdentity = false;
4638       break;
4639     }
4640     IdentitySrc = Ops[i].getOperand(0);
4641   }
4642   if (IsIdentity)
4643     return IdentitySrc;
4644 
4645   return SDValue();
4646 }
4647 
4648 /// Try to simplify vector concatenation to an input value, undef, or build
4649 /// vector.
4650 static SDValue foldCONCAT_VECTORS(const SDLoc &DL, EVT VT,
4651                                   ArrayRef<SDValue> Ops,
4652                                   SelectionDAG &DAG) {
4653   assert(!Ops.empty() && "Can't concatenate an empty list of vectors!");
4654   assert(llvm::all_of(Ops,
4655                       [Ops](SDValue Op) {
4656                         return Ops[0].getValueType() == Op.getValueType();
4657                       }) &&
4658          "Concatenation of vectors with inconsistent value types!");
4659   assert((Ops[0].getValueType().getVectorElementCount() * Ops.size()) ==
4660              VT.getVectorElementCount() &&
4661          "Incorrect element count in vector concatenation!");
4662 
4663   if (Ops.size() == 1)
4664     return Ops[0];
4665 
4666   // Concat of UNDEFs is UNDEF.
4667   if (llvm::all_of(Ops, [](SDValue Op) { return Op.isUndef(); }))
4668     return DAG.getUNDEF(VT);
4669 
4670   // Scan the operands and look for extract operations from a single source
4671   // that correspond to insertion at the same location via this concatenation:
4672   // concat (extract X, 0*subvec_elts), (extract X, 1*subvec_elts), ...
4673   SDValue IdentitySrc;
4674   bool IsIdentity = true;
4675   for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
4676     SDValue Op = Ops[i];
4677     unsigned IdentityIndex = i * Op.getValueType().getVectorMinNumElements();
4678     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
4679         Op.getOperand(0).getValueType() != VT ||
4680         (IdentitySrc && Op.getOperand(0) != IdentitySrc) ||
4681         Op.getConstantOperandVal(1) != IdentityIndex) {
4682       IsIdentity = false;
4683       break;
4684     }
4685     assert((!IdentitySrc || IdentitySrc == Op.getOperand(0)) &&
4686            "Unexpected identity source vector for concat of extracts");
4687     IdentitySrc = Op.getOperand(0);
4688   }
4689   if (IsIdentity) {
4690     assert(IdentitySrc && "Failed to set source vector of extracts");
4691     return IdentitySrc;
4692   }
4693 
4694   // The code below this point is only designed to work for fixed width
4695   // vectors, so we bail out for now.
4696   if (VT.isScalableVector())
4697     return SDValue();
4698 
4699   // A CONCAT_VECTOR with all UNDEF/BUILD_VECTOR operands can be
4700   // simplified to one big BUILD_VECTOR.
4701   // FIXME: Add support for SCALAR_TO_VECTOR as well.
4702   EVT SVT = VT.getScalarType();
4703   SmallVector<SDValue, 16> Elts;
4704   for (SDValue Op : Ops) {
4705     EVT OpVT = Op.getValueType();
4706     if (Op.isUndef())
4707       Elts.append(OpVT.getVectorNumElements(), DAG.getUNDEF(SVT));
4708     else if (Op.getOpcode() == ISD::BUILD_VECTOR)
4709       Elts.append(Op->op_begin(), Op->op_end());
4710     else
4711       return SDValue();
4712   }
4713 
4714   // BUILD_VECTOR requires all inputs to be of the same type, find the
4715   // maximum type and extend them all.
4716   for (SDValue Op : Elts)
4717     SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
4718 
4719   if (SVT.bitsGT(VT.getScalarType())) {
4720     for (SDValue &Op : Elts) {
4721       if (Op.isUndef())
4722         Op = DAG.getUNDEF(SVT);
4723       else
4724         Op = DAG.getTargetLoweringInfo().isZExtFree(Op.getValueType(), SVT)
4725                  ? DAG.getZExtOrTrunc(Op, DL, SVT)
4726                  : DAG.getSExtOrTrunc(Op, DL, SVT);
4727     }
4728   }
4729 
4730   SDValue V = DAG.getBuildVector(VT, DL, Elts);
4731   NewSDValueDbgMsg(V, "New node fold concat vectors: ", &DAG);
4732   return V;
4733 }
4734 
4735 /// Gets or creates the specified node.
4736 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT) {
4737   FoldingSetNodeID ID;
4738   AddNodeIDNode(ID, Opcode, getVTList(VT), None);
4739   void *IP = nullptr;
4740   if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
4741     return SDValue(E, 0);
4742 
4743   auto *N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(),
4744                               getVTList(VT));
4745   CSEMap.InsertNode(N, IP);
4746 
4747   InsertNode(N);
4748   SDValue V = SDValue(N, 0);
4749   NewSDValueDbgMsg(V, "Creating new node: ", this);
4750   return V;
4751 }
4752 
4753 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
4754                               SDValue Operand) {
4755   SDNodeFlags Flags;
4756   if (Inserter)
4757     Flags = Inserter->getFlags();
4758   return getNode(Opcode, DL, VT, Operand, Flags);
4759 }
4760 
4761 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
4762                               SDValue Operand, const SDNodeFlags Flags) {
4763   assert(Operand.getOpcode() != ISD::DELETED_NODE &&
4764          "Operand is DELETED_NODE!");
4765   // Constant fold unary operations with an integer constant operand. Even
4766   // opaque constant will be folded, because the folding of unary operations
4767   // doesn't create new constants with different values. Nevertheless, the
4768   // opaque flag is preserved during folding to prevent future folding with
4769   // other constants.
4770   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Operand)) {
4771     const APInt &Val = C->getAPIntValue();
4772     switch (Opcode) {
4773     default: break;
4774     case ISD::SIGN_EXTEND:
4775       return getConstant(Val.sextOrTrunc(VT.getSizeInBits()), DL, VT,
4776                          C->isTargetOpcode(), C->isOpaque());
4777     case ISD::TRUNCATE:
4778       if (C->isOpaque())
4779         break;
4780       LLVM_FALLTHROUGH;
4781     case ISD::ZERO_EXTEND:
4782       return getConstant(Val.zextOrTrunc(VT.getSizeInBits()), DL, VT,
4783                          C->isTargetOpcode(), C->isOpaque());
4784     case ISD::ANY_EXTEND:
4785       // Some targets like RISCV prefer to sign extend some types.
4786       if (TLI->isSExtCheaperThanZExt(Operand.getValueType(), VT))
4787         return getConstant(Val.sextOrTrunc(VT.getSizeInBits()), DL, VT,
4788                            C->isTargetOpcode(), C->isOpaque());
4789       return getConstant(Val.zextOrTrunc(VT.getSizeInBits()), DL, VT,
4790                          C->isTargetOpcode(), C->isOpaque());
4791     case ISD::UINT_TO_FP:
4792     case ISD::SINT_TO_FP: {
4793       APFloat apf(EVTToAPFloatSemantics(VT),
4794                   APInt::getZero(VT.getSizeInBits()));
4795       (void)apf.convertFromAPInt(Val,
4796                                  Opcode==ISD::SINT_TO_FP,
4797                                  APFloat::rmNearestTiesToEven);
4798       return getConstantFP(apf, DL, VT);
4799     }
4800     case ISD::BITCAST:
4801       if (VT == MVT::f16 && C->getValueType(0) == MVT::i16)
4802         return getConstantFP(APFloat(APFloat::IEEEhalf(), Val), DL, VT);
4803       if (VT == MVT::f32 && C->getValueType(0) == MVT::i32)
4804         return getConstantFP(APFloat(APFloat::IEEEsingle(), Val), DL, VT);
4805       if (VT == MVT::f64 && C->getValueType(0) == MVT::i64)
4806         return getConstantFP(APFloat(APFloat::IEEEdouble(), Val), DL, VT);
4807       if (VT == MVT::f128 && C->getValueType(0) == MVT::i128)
4808         return getConstantFP(APFloat(APFloat::IEEEquad(), Val), DL, VT);
4809       break;
4810     case ISD::ABS:
4811       return getConstant(Val.abs(), DL, VT, C->isTargetOpcode(),
4812                          C->isOpaque());
4813     case ISD::BITREVERSE:
4814       return getConstant(Val.reverseBits(), DL, VT, C->isTargetOpcode(),
4815                          C->isOpaque());
4816     case ISD::BSWAP:
4817       return getConstant(Val.byteSwap(), DL, VT, C->isTargetOpcode(),
4818                          C->isOpaque());
4819     case ISD::CTPOP:
4820       return getConstant(Val.countPopulation(), DL, VT, C->isTargetOpcode(),
4821                          C->isOpaque());
4822     case ISD::CTLZ:
4823     case ISD::CTLZ_ZERO_UNDEF:
4824       return getConstant(Val.countLeadingZeros(), DL, VT, C->isTargetOpcode(),
4825                          C->isOpaque());
4826     case ISD::CTTZ:
4827     case ISD::CTTZ_ZERO_UNDEF:
4828       return getConstant(Val.countTrailingZeros(), DL, VT, C->isTargetOpcode(),
4829                          C->isOpaque());
4830     case ISD::FP16_TO_FP: {
4831       bool Ignored;
4832       APFloat FPV(APFloat::IEEEhalf(),
4833                   (Val.getBitWidth() == 16) ? Val : Val.trunc(16));
4834 
4835       // This can return overflow, underflow, or inexact; we don't care.
4836       // FIXME need to be more flexible about rounding mode.
4837       (void)FPV.convert(EVTToAPFloatSemantics(VT),
4838                         APFloat::rmNearestTiesToEven, &Ignored);
4839       return getConstantFP(FPV, DL, VT);
4840     }
4841     case ISD::STEP_VECTOR: {
4842       if (SDValue V = FoldSTEP_VECTOR(DL, VT, Operand, *this))
4843         return V;
4844       break;
4845     }
4846     }
4847   }
4848 
4849   // Constant fold unary operations with a floating point constant operand.
4850   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Operand)) {
4851     APFloat V = C->getValueAPF();    // make copy
4852     switch (Opcode) {
4853     case ISD::FNEG:
4854       V.changeSign();
4855       return getConstantFP(V, DL, VT);
4856     case ISD::FABS:
4857       V.clearSign();
4858       return getConstantFP(V, DL, VT);
4859     case ISD::FCEIL: {
4860       APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardPositive);
4861       if (fs == APFloat::opOK || fs == APFloat::opInexact)
4862         return getConstantFP(V, DL, VT);
4863       break;
4864     }
4865     case ISD::FTRUNC: {
4866       APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardZero);
4867       if (fs == APFloat::opOK || fs == APFloat::opInexact)
4868         return getConstantFP(V, DL, VT);
4869       break;
4870     }
4871     case ISD::FFLOOR: {
4872       APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardNegative);
4873       if (fs == APFloat::opOK || fs == APFloat::opInexact)
4874         return getConstantFP(V, DL, VT);
4875       break;
4876     }
4877     case ISD::FP_EXTEND: {
4878       bool ignored;
4879       // This can return overflow, underflow, or inexact; we don't care.
4880       // FIXME need to be more flexible about rounding mode.
4881       (void)V.convert(EVTToAPFloatSemantics(VT),
4882                       APFloat::rmNearestTiesToEven, &ignored);
4883       return getConstantFP(V, DL, VT);
4884     }
4885     case ISD::FP_TO_SINT:
4886     case ISD::FP_TO_UINT: {
4887       bool ignored;
4888       APSInt IntVal(VT.getSizeInBits(), Opcode == ISD::FP_TO_UINT);
4889       // FIXME need to be more flexible about rounding mode.
4890       APFloat::opStatus s =
4891           V.convertToInteger(IntVal, APFloat::rmTowardZero, &ignored);
4892       if (s == APFloat::opInvalidOp) // inexact is OK, in fact usual
4893         break;
4894       return getConstant(IntVal, DL, VT);
4895     }
4896     case ISD::BITCAST:
4897       if (VT == MVT::i16 && C->getValueType(0) == MVT::f16)
4898         return getConstant((uint16_t)V.bitcastToAPInt().getZExtValue(), DL, VT);
4899       if (VT == MVT::i16 && C->getValueType(0) == MVT::bf16)
4900         return getConstant((uint16_t)V.bitcastToAPInt().getZExtValue(), DL, VT);
4901       if (VT == MVT::i32 && C->getValueType(0) == MVT::f32)
4902         return getConstant((uint32_t)V.bitcastToAPInt().getZExtValue(), DL, VT);
4903       if (VT == MVT::i64 && C->getValueType(0) == MVT::f64)
4904         return getConstant(V.bitcastToAPInt().getZExtValue(), DL, VT);
4905       break;
4906     case ISD::FP_TO_FP16: {
4907       bool Ignored;
4908       // This can return overflow, underflow, or inexact; we don't care.
4909       // FIXME need to be more flexible about rounding mode.
4910       (void)V.convert(APFloat::IEEEhalf(),
4911                       APFloat::rmNearestTiesToEven, &Ignored);
4912       return getConstant(V.bitcastToAPInt().getZExtValue(), DL, VT);
4913     }
4914     }
4915   }
4916 
4917   // Constant fold unary operations with a vector integer or float operand.
4918   switch (Opcode) {
4919   default:
4920     // FIXME: Entirely reasonable to perform folding of other unary
4921     // operations here as the need arises.
4922     break;
4923   case ISD::FNEG:
4924   case ISD::FABS:
4925   case ISD::FCEIL:
4926   case ISD::FTRUNC:
4927   case ISD::FFLOOR:
4928   case ISD::FP_EXTEND:
4929   case ISD::FP_TO_SINT:
4930   case ISD::FP_TO_UINT:
4931   case ISD::TRUNCATE:
4932   case ISD::ANY_EXTEND:
4933   case ISD::ZERO_EXTEND:
4934   case ISD::SIGN_EXTEND:
4935   case ISD::UINT_TO_FP:
4936   case ISD::SINT_TO_FP:
4937   case ISD::ABS:
4938   case ISD::BITREVERSE:
4939   case ISD::BSWAP:
4940   case ISD::CTLZ:
4941   case ISD::CTLZ_ZERO_UNDEF:
4942   case ISD::CTTZ:
4943   case ISD::CTTZ_ZERO_UNDEF:
4944   case ISD::CTPOP: {
4945     SDValue Ops = {Operand};
4946     if (SDValue Fold = FoldConstantArithmetic(Opcode, DL, VT, Ops))
4947       return Fold;
4948   }
4949   }
4950 
4951   unsigned OpOpcode = Operand.getNode()->getOpcode();
4952   switch (Opcode) {
4953   case ISD::STEP_VECTOR:
4954     assert(VT.isScalableVector() &&
4955            "STEP_VECTOR can only be used with scalable types");
4956     assert(OpOpcode == ISD::TargetConstant &&
4957            VT.getVectorElementType() == Operand.getValueType() &&
4958            "Unexpected step operand");
4959     break;
4960   case ISD::FREEZE:
4961     assert(VT == Operand.getValueType() && "Unexpected VT!");
4962     break;
4963   case ISD::TokenFactor:
4964   case ISD::MERGE_VALUES:
4965   case ISD::CONCAT_VECTORS:
4966     return Operand;         // Factor, merge or concat of one node?  No need.
4967   case ISD::BUILD_VECTOR: {
4968     // Attempt to simplify BUILD_VECTOR.
4969     SDValue Ops[] = {Operand};
4970     if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
4971       return V;
4972     break;
4973   }
4974   case ISD::FP_ROUND: llvm_unreachable("Invalid method to make FP_ROUND node");
4975   case ISD::FP_EXTEND:
4976     assert(VT.isFloatingPoint() &&
4977            Operand.getValueType().isFloatingPoint() && "Invalid FP cast!");
4978     if (Operand.getValueType() == VT) return Operand;  // noop conversion.
4979     assert((!VT.isVector() ||
4980             VT.getVectorElementCount() ==
4981             Operand.getValueType().getVectorElementCount()) &&
4982            "Vector element count mismatch!");
4983     assert(Operand.getValueType().bitsLT(VT) &&
4984            "Invalid fpext node, dst < src!");
4985     if (Operand.isUndef())
4986       return getUNDEF(VT);
4987     break;
4988   case ISD::FP_TO_SINT:
4989   case ISD::FP_TO_UINT:
4990     if (Operand.isUndef())
4991       return getUNDEF(VT);
4992     break;
4993   case ISD::SINT_TO_FP:
4994   case ISD::UINT_TO_FP:
4995     // [us]itofp(undef) = 0, because the result value is bounded.
4996     if (Operand.isUndef())
4997       return getConstantFP(0.0, DL, VT);
4998     break;
4999   case ISD::SIGN_EXTEND:
5000     assert(VT.isInteger() && Operand.getValueType().isInteger() &&
5001            "Invalid SIGN_EXTEND!");
5002     assert(VT.isVector() == Operand.getValueType().isVector() &&
5003            "SIGN_EXTEND result type type should be vector iff the operand "
5004            "type is vector!");
5005     if (Operand.getValueType() == VT) return Operand;   // noop extension
5006     assert((!VT.isVector() ||
5007             VT.getVectorElementCount() ==
5008                 Operand.getValueType().getVectorElementCount()) &&
5009            "Vector element count mismatch!");
5010     assert(Operand.getValueType().bitsLT(VT) &&
5011            "Invalid sext node, dst < src!");
5012     if (OpOpcode == ISD::SIGN_EXTEND || OpOpcode == ISD::ZERO_EXTEND)
5013       return getNode(OpOpcode, DL, VT, Operand.getOperand(0));
5014     if (OpOpcode == ISD::UNDEF)
5015       // sext(undef) = 0, because the top bits will all be the same.
5016       return getConstant(0, DL, VT);
5017     break;
5018   case ISD::ZERO_EXTEND:
5019     assert(VT.isInteger() && Operand.getValueType().isInteger() &&
5020            "Invalid ZERO_EXTEND!");
5021     assert(VT.isVector() == Operand.getValueType().isVector() &&
5022            "ZERO_EXTEND result type type should be vector iff the operand "
5023            "type is vector!");
5024     if (Operand.getValueType() == VT) return Operand;   // noop extension
5025     assert((!VT.isVector() ||
5026             VT.getVectorElementCount() ==
5027                 Operand.getValueType().getVectorElementCount()) &&
5028            "Vector element count mismatch!");
5029     assert(Operand.getValueType().bitsLT(VT) &&
5030            "Invalid zext node, dst < src!");
5031     if (OpOpcode == ISD::ZERO_EXTEND)   // (zext (zext x)) -> (zext x)
5032       return getNode(ISD::ZERO_EXTEND, DL, VT, Operand.getOperand(0));
5033     if (OpOpcode == ISD::UNDEF)
5034       // zext(undef) = 0, because the top bits will be zero.
5035       return getConstant(0, DL, VT);
5036     break;
5037   case ISD::ANY_EXTEND:
5038     assert(VT.isInteger() && Operand.getValueType().isInteger() &&
5039            "Invalid ANY_EXTEND!");
5040     assert(VT.isVector() == Operand.getValueType().isVector() &&
5041            "ANY_EXTEND result type type should be vector iff the operand "
5042            "type is vector!");
5043     if (Operand.getValueType() == VT) return Operand;   // noop extension
5044     assert((!VT.isVector() ||
5045             VT.getVectorElementCount() ==
5046                 Operand.getValueType().getVectorElementCount()) &&
5047            "Vector element count mismatch!");
5048     assert(Operand.getValueType().bitsLT(VT) &&
5049            "Invalid anyext node, dst < src!");
5050 
5051     if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
5052         OpOpcode == ISD::ANY_EXTEND)
5053       // (ext (zext x)) -> (zext x)  and  (ext (sext x)) -> (sext x)
5054       return getNode(OpOpcode, DL, VT, Operand.getOperand(0));
5055     if (OpOpcode == ISD::UNDEF)
5056       return getUNDEF(VT);
5057 
5058     // (ext (trunc x)) -> x
5059     if (OpOpcode == ISD::TRUNCATE) {
5060       SDValue OpOp = Operand.getOperand(0);
5061       if (OpOp.getValueType() == VT) {
5062         transferDbgValues(Operand, OpOp);
5063         return OpOp;
5064       }
5065     }
5066     break;
5067   case ISD::TRUNCATE:
5068     assert(VT.isInteger() && Operand.getValueType().isInteger() &&
5069            "Invalid TRUNCATE!");
5070     assert(VT.isVector() == Operand.getValueType().isVector() &&
5071            "TRUNCATE result type type should be vector iff the operand "
5072            "type is vector!");
5073     if (Operand.getValueType() == VT) return Operand;   // noop truncate
5074     assert((!VT.isVector() ||
5075             VT.getVectorElementCount() ==
5076                 Operand.getValueType().getVectorElementCount()) &&
5077            "Vector element count mismatch!");
5078     assert(Operand.getValueType().bitsGT(VT) &&
5079            "Invalid truncate node, src < dst!");
5080     if (OpOpcode == ISD::TRUNCATE)
5081       return getNode(ISD::TRUNCATE, DL, VT, Operand.getOperand(0));
5082     if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
5083         OpOpcode == ISD::ANY_EXTEND) {
5084       // If the source is smaller than the dest, we still need an extend.
5085       if (Operand.getOperand(0).getValueType().getScalarType()
5086             .bitsLT(VT.getScalarType()))
5087         return getNode(OpOpcode, DL, VT, Operand.getOperand(0));
5088       if (Operand.getOperand(0).getValueType().bitsGT(VT))
5089         return getNode(ISD::TRUNCATE, DL, VT, Operand.getOperand(0));
5090       return Operand.getOperand(0);
5091     }
5092     if (OpOpcode == ISD::UNDEF)
5093       return getUNDEF(VT);
5094     if (OpOpcode == ISD::VSCALE && !NewNodesMustHaveLegalTypes)
5095       return getVScale(DL, VT, Operand.getConstantOperandAPInt(0));
5096     break;
5097   case ISD::ANY_EXTEND_VECTOR_INREG:
5098   case ISD::ZERO_EXTEND_VECTOR_INREG:
5099   case ISD::SIGN_EXTEND_VECTOR_INREG:
5100     assert(VT.isVector() && "This DAG node is restricted to vector types.");
5101     assert(Operand.getValueType().bitsLE(VT) &&
5102            "The input must be the same size or smaller than the result.");
5103     assert(VT.getVectorMinNumElements() <
5104                Operand.getValueType().getVectorMinNumElements() &&
5105            "The destination vector type must have fewer lanes than the input.");
5106     break;
5107   case ISD::ABS:
5108     assert(VT.isInteger() && VT == Operand.getValueType() &&
5109            "Invalid ABS!");
5110     if (OpOpcode == ISD::UNDEF)
5111       return getUNDEF(VT);
5112     break;
5113   case ISD::BSWAP:
5114     assert(VT.isInteger() && VT == Operand.getValueType() &&
5115            "Invalid BSWAP!");
5116     assert((VT.getScalarSizeInBits() % 16 == 0) &&
5117            "BSWAP types must be a multiple of 16 bits!");
5118     if (OpOpcode == ISD::UNDEF)
5119       return getUNDEF(VT);
5120     break;
5121   case ISD::BITREVERSE:
5122     assert(VT.isInteger() && VT == Operand.getValueType() &&
5123            "Invalid BITREVERSE!");
5124     if (OpOpcode == ISD::UNDEF)
5125       return getUNDEF(VT);
5126     break;
5127   case ISD::BITCAST:
5128     assert(VT.getSizeInBits() == Operand.getValueSizeInBits() &&
5129            "Cannot BITCAST between types of different sizes!");
5130     if (VT == Operand.getValueType()) return Operand;  // noop conversion.
5131     if (OpOpcode == ISD::BITCAST)  // bitconv(bitconv(x)) -> bitconv(x)
5132       return getNode(ISD::BITCAST, DL, VT, Operand.getOperand(0));
5133     if (OpOpcode == ISD::UNDEF)
5134       return getUNDEF(VT);
5135     break;
5136   case ISD::SCALAR_TO_VECTOR:
5137     assert(VT.isVector() && !Operand.getValueType().isVector() &&
5138            (VT.getVectorElementType() == Operand.getValueType() ||
5139             (VT.getVectorElementType().isInteger() &&
5140              Operand.getValueType().isInteger() &&
5141              VT.getVectorElementType().bitsLE(Operand.getValueType()))) &&
5142            "Illegal SCALAR_TO_VECTOR node!");
5143     if (OpOpcode == ISD::UNDEF)
5144       return getUNDEF(VT);
5145     // scalar_to_vector(extract_vector_elt V, 0) -> V, top bits are undefined.
5146     if (OpOpcode == ISD::EXTRACT_VECTOR_ELT &&
5147         isa<ConstantSDNode>(Operand.getOperand(1)) &&
5148         Operand.getConstantOperandVal(1) == 0 &&
5149         Operand.getOperand(0).getValueType() == VT)
5150       return Operand.getOperand(0);
5151     break;
5152   case ISD::FNEG:
5153     // Negation of an unknown bag of bits is still completely undefined.
5154     if (OpOpcode == ISD::UNDEF)
5155       return getUNDEF(VT);
5156 
5157     if (OpOpcode == ISD::FNEG)  // --X -> X
5158       return Operand.getOperand(0);
5159     break;
5160   case ISD::FABS:
5161     if (OpOpcode == ISD::FNEG)  // abs(-X) -> abs(X)
5162       return getNode(ISD::FABS, DL, VT, Operand.getOperand(0));
5163     break;
5164   case ISD::VSCALE:
5165     assert(VT == Operand.getValueType() && "Unexpected VT!");
5166     break;
5167   case ISD::CTPOP:
5168     if (Operand.getValueType().getScalarType() == MVT::i1)
5169       return Operand;
5170     break;
5171   case ISD::CTLZ:
5172   case ISD::CTTZ:
5173     if (Operand.getValueType().getScalarType() == MVT::i1)
5174       return getNOT(DL, Operand, Operand.getValueType());
5175     break;
5176   case ISD::VECREDUCE_SMIN:
5177   case ISD::VECREDUCE_UMAX:
5178     if (Operand.getValueType().getScalarType() == MVT::i1)
5179       return getNode(ISD::VECREDUCE_OR, DL, VT, Operand);
5180     break;
5181   case ISD::VECREDUCE_SMAX:
5182   case ISD::VECREDUCE_UMIN:
5183     if (Operand.getValueType().getScalarType() == MVT::i1)
5184       return getNode(ISD::VECREDUCE_AND, DL, VT, Operand);
5185     break;
5186   }
5187 
5188   SDNode *N;
5189   SDVTList VTs = getVTList(VT);
5190   SDValue Ops[] = {Operand};
5191   if (VT != MVT::Glue) { // Don't CSE flag producing nodes
5192     FoldingSetNodeID ID;
5193     AddNodeIDNode(ID, Opcode, VTs, Ops);
5194     void *IP = nullptr;
5195     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
5196       E->intersectFlagsWith(Flags);
5197       return SDValue(E, 0);
5198     }
5199 
5200     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
5201     N->setFlags(Flags);
5202     createOperands(N, Ops);
5203     CSEMap.InsertNode(N, IP);
5204   } else {
5205     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
5206     createOperands(N, Ops);
5207   }
5208 
5209   InsertNode(N);
5210   SDValue V = SDValue(N, 0);
5211   NewSDValueDbgMsg(V, "Creating new node: ", this);
5212   return V;
5213 }
5214 
5215 static llvm::Optional<APInt> FoldValue(unsigned Opcode, const APInt &C1,
5216                                        const APInt &C2) {
5217   switch (Opcode) {
5218   case ISD::ADD:  return C1 + C2;
5219   case ISD::SUB:  return C1 - C2;
5220   case ISD::MUL:  return C1 * C2;
5221   case ISD::AND:  return C1 & C2;
5222   case ISD::OR:   return C1 | C2;
5223   case ISD::XOR:  return C1 ^ C2;
5224   case ISD::SHL:  return C1 << C2;
5225   case ISD::SRL:  return C1.lshr(C2);
5226   case ISD::SRA:  return C1.ashr(C2);
5227   case ISD::ROTL: return C1.rotl(C2);
5228   case ISD::ROTR: return C1.rotr(C2);
5229   case ISD::SMIN: return C1.sle(C2) ? C1 : C2;
5230   case ISD::SMAX: return C1.sge(C2) ? C1 : C2;
5231   case ISD::UMIN: return C1.ule(C2) ? C1 : C2;
5232   case ISD::UMAX: return C1.uge(C2) ? C1 : C2;
5233   case ISD::SADDSAT: return C1.sadd_sat(C2);
5234   case ISD::UADDSAT: return C1.uadd_sat(C2);
5235   case ISD::SSUBSAT: return C1.ssub_sat(C2);
5236   case ISD::USUBSAT: return C1.usub_sat(C2);
5237   case ISD::UDIV:
5238     if (!C2.getBoolValue())
5239       break;
5240     return C1.udiv(C2);
5241   case ISD::UREM:
5242     if (!C2.getBoolValue())
5243       break;
5244     return C1.urem(C2);
5245   case ISD::SDIV:
5246     if (!C2.getBoolValue())
5247       break;
5248     return C1.sdiv(C2);
5249   case ISD::SREM:
5250     if (!C2.getBoolValue())
5251       break;
5252     return C1.srem(C2);
5253   case ISD::MULHS: {
5254     unsigned FullWidth = C1.getBitWidth() * 2;
5255     APInt C1Ext = C1.sext(FullWidth);
5256     APInt C2Ext = C2.sext(FullWidth);
5257     return (C1Ext * C2Ext).extractBits(C1.getBitWidth(), C1.getBitWidth());
5258   }
5259   case ISD::MULHU: {
5260     unsigned FullWidth = C1.getBitWidth() * 2;
5261     APInt C1Ext = C1.zext(FullWidth);
5262     APInt C2Ext = C2.zext(FullWidth);
5263     return (C1Ext * C2Ext).extractBits(C1.getBitWidth(), C1.getBitWidth());
5264   }
5265   }
5266   return llvm::None;
5267 }
5268 
5269 SDValue SelectionDAG::FoldSymbolOffset(unsigned Opcode, EVT VT,
5270                                        const GlobalAddressSDNode *GA,
5271                                        const SDNode *N2) {
5272   if (GA->getOpcode() != ISD::GlobalAddress)
5273     return SDValue();
5274   if (!TLI->isOffsetFoldingLegal(GA))
5275     return SDValue();
5276   auto *C2 = dyn_cast<ConstantSDNode>(N2);
5277   if (!C2)
5278     return SDValue();
5279   int64_t Offset = C2->getSExtValue();
5280   switch (Opcode) {
5281   case ISD::ADD: break;
5282   case ISD::SUB: Offset = -uint64_t(Offset); break;
5283   default: return SDValue();
5284   }
5285   return getGlobalAddress(GA->getGlobal(), SDLoc(C2), VT,
5286                           GA->getOffset() + uint64_t(Offset));
5287 }
5288 
5289 bool SelectionDAG::isUndef(unsigned Opcode, ArrayRef<SDValue> Ops) {
5290   switch (Opcode) {
5291   case ISD::SDIV:
5292   case ISD::UDIV:
5293   case ISD::SREM:
5294   case ISD::UREM: {
5295     // If a divisor is zero/undef or any element of a divisor vector is
5296     // zero/undef, the whole op is undef.
5297     assert(Ops.size() == 2 && "Div/rem should have 2 operands");
5298     SDValue Divisor = Ops[1];
5299     if (Divisor.isUndef() || isNullConstant(Divisor))
5300       return true;
5301 
5302     return ISD::isBuildVectorOfConstantSDNodes(Divisor.getNode()) &&
5303            llvm::any_of(Divisor->op_values(),
5304                         [](SDValue V) { return V.isUndef() ||
5305                                         isNullConstant(V); });
5306     // TODO: Handle signed overflow.
5307   }
5308   // TODO: Handle oversized shifts.
5309   default:
5310     return false;
5311   }
5312 }
5313 
5314 SDValue SelectionDAG::FoldConstantArithmetic(unsigned Opcode, const SDLoc &DL,
5315                                              EVT VT, ArrayRef<SDValue> Ops) {
5316   // If the opcode is a target-specific ISD node, there's nothing we can
5317   // do here and the operand rules may not line up with the below, so
5318   // bail early.
5319   // We can't create a scalar CONCAT_VECTORS so skip it. It will break
5320   // for concats involving SPLAT_VECTOR. Concats of BUILD_VECTORS are handled by
5321   // foldCONCAT_VECTORS in getNode before this is called.
5322   if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::CONCAT_VECTORS)
5323     return SDValue();
5324 
5325   unsigned NumOps = Ops.size();
5326   if (NumOps == 0)
5327     return SDValue();
5328 
5329   if (isUndef(Opcode, Ops))
5330     return getUNDEF(VT);
5331 
5332   // Handle binops special cases.
5333   if (NumOps == 2) {
5334     if (SDValue CFP = foldConstantFPMath(Opcode, DL, VT, Ops[0], Ops[1]))
5335       return CFP;
5336 
5337     if (auto *C1 = dyn_cast<ConstantSDNode>(Ops[0])) {
5338       if (auto *C2 = dyn_cast<ConstantSDNode>(Ops[1])) {
5339         if (C1->isOpaque() || C2->isOpaque())
5340           return SDValue();
5341 
5342         Optional<APInt> FoldAttempt =
5343             FoldValue(Opcode, C1->getAPIntValue(), C2->getAPIntValue());
5344         if (!FoldAttempt)
5345           return SDValue();
5346 
5347         SDValue Folded = getConstant(FoldAttempt.getValue(), DL, VT);
5348         assert((!Folded || !VT.isVector()) &&
5349                "Can't fold vectors ops with scalar operands");
5350         return Folded;
5351       }
5352     }
5353 
5354     // fold (add Sym, c) -> Sym+c
5355     if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Ops[0]))
5356       return FoldSymbolOffset(Opcode, VT, GA, Ops[1].getNode());
5357     if (TLI->isCommutativeBinOp(Opcode))
5358       if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Ops[1]))
5359         return FoldSymbolOffset(Opcode, VT, GA, Ops[0].getNode());
5360   }
5361 
5362   // This is for vector folding only from here on.
5363   if (!VT.isVector())
5364     return SDValue();
5365 
5366   ElementCount NumElts = VT.getVectorElementCount();
5367 
5368   // See if we can fold through bitcasted integer ops.
5369   // TODO: Can we handle undef elements?
5370   if (NumOps == 2 && VT.isFixedLengthVector() && VT.isInteger() &&
5371       Ops[0].getValueType() == VT && Ops[1].getValueType() == VT &&
5372       Ops[0].getOpcode() == ISD::BITCAST &&
5373       Ops[1].getOpcode() == ISD::BITCAST) {
5374     SDValue N1 = peekThroughBitcasts(Ops[0]);
5375     SDValue N2 = peekThroughBitcasts(Ops[1]);
5376     auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
5377     auto *BV2 = dyn_cast<BuildVectorSDNode>(N2);
5378     EVT BVVT = N1.getValueType();
5379     if (BV1 && BV2 && BVVT.isInteger() && BVVT == N2.getValueType()) {
5380       bool IsLE = getDataLayout().isLittleEndian();
5381       unsigned EltBits = VT.getScalarSizeInBits();
5382       SmallVector<APInt> RawBits1, RawBits2;
5383       BitVector UndefElts1, UndefElts2;
5384       if (BV1->getConstantRawBits(IsLE, EltBits, RawBits1, UndefElts1) &&
5385           BV2->getConstantRawBits(IsLE, EltBits, RawBits2, UndefElts2) &&
5386           UndefElts1.none() && UndefElts2.none()) {
5387         SmallVector<APInt> RawBits;
5388         for (unsigned I = 0, E = NumElts.getFixedValue(); I != E; ++I) {
5389           Optional<APInt> Fold = FoldValue(Opcode, RawBits1[I], RawBits2[I]);
5390           if (!Fold)
5391             break;
5392           RawBits.push_back(Fold.getValue());
5393         }
5394         if (RawBits.size() == NumElts.getFixedValue()) {
5395           // We have constant folded, but we need to cast this again back to
5396           // the original (possibly legalized) type.
5397           SmallVector<APInt> DstBits;
5398           BitVector DstUndefs;
5399           BuildVectorSDNode::recastRawBits(IsLE, BVVT.getScalarSizeInBits(),
5400                                            DstBits, RawBits, DstUndefs,
5401                                            BitVector(RawBits.size(), false));
5402           EVT BVEltVT = BV1->getOperand(0).getValueType();
5403           unsigned BVEltBits = BVEltVT.getSizeInBits();
5404           SmallVector<SDValue> Ops(DstBits.size(), getUNDEF(BVEltVT));
5405           for (unsigned I = 0, E = DstBits.size(); I != E; ++I) {
5406             if (DstUndefs[I])
5407               continue;
5408             Ops[I] = getConstant(DstBits[I].sextOrSelf(BVEltBits), DL, BVEltVT);
5409           }
5410           return getBitcast(VT, getBuildVector(BVVT, DL, Ops));
5411         }
5412       }
5413     }
5414   }
5415 
5416   auto IsScalarOrSameVectorSize = [NumElts](const SDValue &Op) {
5417     return !Op.getValueType().isVector() ||
5418            Op.getValueType().getVectorElementCount() == NumElts;
5419   };
5420 
5421   auto IsBuildVectorSplatVectorOrUndef = [](const SDValue &Op) {
5422     return Op.isUndef() || Op.getOpcode() == ISD::CONDCODE ||
5423            Op.getOpcode() == ISD::BUILD_VECTOR ||
5424            Op.getOpcode() == ISD::SPLAT_VECTOR;
5425   };
5426 
5427   // All operands must be vector types with the same number of elements as
5428   // the result type and must be either UNDEF or a build/splat vector
5429   // or UNDEF scalars.
5430   if (!llvm::all_of(Ops, IsBuildVectorSplatVectorOrUndef) ||
5431       !llvm::all_of(Ops, IsScalarOrSameVectorSize))
5432     return SDValue();
5433 
5434   // If we are comparing vectors, then the result needs to be a i1 boolean
5435   // that is then sign-extended back to the legal result type.
5436   EVT SVT = (Opcode == ISD::SETCC ? MVT::i1 : VT.getScalarType());
5437 
5438   // Find legal integer scalar type for constant promotion and
5439   // ensure that its scalar size is at least as large as source.
5440   EVT LegalSVT = VT.getScalarType();
5441   if (NewNodesMustHaveLegalTypes && LegalSVT.isInteger()) {
5442     LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT);
5443     if (LegalSVT.bitsLT(VT.getScalarType()))
5444       return SDValue();
5445   }
5446 
5447   // For scalable vector types we know we're dealing with SPLAT_VECTORs. We
5448   // only have one operand to check. For fixed-length vector types we may have
5449   // a combination of BUILD_VECTOR and SPLAT_VECTOR.
5450   unsigned NumVectorElts = NumElts.isScalable() ? 1 : NumElts.getFixedValue();
5451 
5452   // Constant fold each scalar lane separately.
5453   SmallVector<SDValue, 4> ScalarResults;
5454   for (unsigned I = 0; I != NumVectorElts; I++) {
5455     SmallVector<SDValue, 4> ScalarOps;
5456     for (SDValue Op : Ops) {
5457       EVT InSVT = Op.getValueType().getScalarType();
5458       if (Op.getOpcode() != ISD::BUILD_VECTOR &&
5459           Op.getOpcode() != ISD::SPLAT_VECTOR) {
5460         if (Op.isUndef())
5461           ScalarOps.push_back(getUNDEF(InSVT));
5462         else
5463           ScalarOps.push_back(Op);
5464         continue;
5465       }
5466 
5467       SDValue ScalarOp =
5468           Op.getOperand(Op.getOpcode() == ISD::SPLAT_VECTOR ? 0 : I);
5469       EVT ScalarVT = ScalarOp.getValueType();
5470 
5471       // Build vector (integer) scalar operands may need implicit
5472       // truncation - do this before constant folding.
5473       if (ScalarVT.isInteger() && ScalarVT.bitsGT(InSVT))
5474         ScalarOp = getNode(ISD::TRUNCATE, DL, InSVT, ScalarOp);
5475 
5476       ScalarOps.push_back(ScalarOp);
5477     }
5478 
5479     // Constant fold the scalar operands.
5480     SDValue ScalarResult = getNode(Opcode, DL, SVT, ScalarOps);
5481 
5482     // Legalize the (integer) scalar constant if necessary.
5483     if (LegalSVT != SVT)
5484       ScalarResult = getNode(ISD::SIGN_EXTEND, DL, LegalSVT, ScalarResult);
5485 
5486     // Scalar folding only succeeded if the result is a constant or UNDEF.
5487     if (!ScalarResult.isUndef() && ScalarResult.getOpcode() != ISD::Constant &&
5488         ScalarResult.getOpcode() != ISD::ConstantFP)
5489       return SDValue();
5490     ScalarResults.push_back(ScalarResult);
5491   }
5492 
5493   SDValue V = NumElts.isScalable() ? getSplatVector(VT, DL, ScalarResults[0])
5494                                    : getBuildVector(VT, DL, ScalarResults);
5495   NewSDValueDbgMsg(V, "New node fold constant vector: ", this);
5496   return V;
5497 }
5498 
5499 SDValue SelectionDAG::foldConstantFPMath(unsigned Opcode, const SDLoc &DL,
5500                                          EVT VT, SDValue N1, SDValue N2) {
5501   // TODO: We don't do any constant folding for strict FP opcodes here, but we
5502   //       should. That will require dealing with a potentially non-default
5503   //       rounding mode, checking the "opStatus" return value from the APFloat
5504   //       math calculations, and possibly other variations.
5505   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1, /*AllowUndefs*/ false);
5506   ConstantFPSDNode *N2CFP = isConstOrConstSplatFP(N2, /*AllowUndefs*/ false);
5507   if (N1CFP && N2CFP) {
5508     APFloat C1 = N1CFP->getValueAPF(); // make copy
5509     const APFloat &C2 = N2CFP->getValueAPF();
5510     switch (Opcode) {
5511     case ISD::FADD:
5512       C1.add(C2, APFloat::rmNearestTiesToEven);
5513       return getConstantFP(C1, DL, VT);
5514     case ISD::FSUB:
5515       C1.subtract(C2, APFloat::rmNearestTiesToEven);
5516       return getConstantFP(C1, DL, VT);
5517     case ISD::FMUL:
5518       C1.multiply(C2, APFloat::rmNearestTiesToEven);
5519       return getConstantFP(C1, DL, VT);
5520     case ISD::FDIV:
5521       C1.divide(C2, APFloat::rmNearestTiesToEven);
5522       return getConstantFP(C1, DL, VT);
5523     case ISD::FREM:
5524       C1.mod(C2);
5525       return getConstantFP(C1, DL, VT);
5526     case ISD::FCOPYSIGN:
5527       C1.copySign(C2);
5528       return getConstantFP(C1, DL, VT);
5529     case ISD::FMINNUM:
5530       return getConstantFP(minnum(C1, C2), DL, VT);
5531     case ISD::FMAXNUM:
5532       return getConstantFP(maxnum(C1, C2), DL, VT);
5533     case ISD::FMINIMUM:
5534       return getConstantFP(minimum(C1, C2), DL, VT);
5535     case ISD::FMAXIMUM:
5536       return getConstantFP(maximum(C1, C2), DL, VT);
5537     default: break;
5538     }
5539   }
5540   if (N1CFP && Opcode == ISD::FP_ROUND) {
5541     APFloat C1 = N1CFP->getValueAPF();    // make copy
5542     bool Unused;
5543     // This can return overflow, underflow, or inexact; we don't care.
5544     // FIXME need to be more flexible about rounding mode.
5545     (void) C1.convert(EVTToAPFloatSemantics(VT), APFloat::rmNearestTiesToEven,
5546                       &Unused);
5547     return getConstantFP(C1, DL, VT);
5548   }
5549 
5550   switch (Opcode) {
5551   case ISD::FSUB:
5552     // -0.0 - undef --> undef (consistent with "fneg undef")
5553     if (ConstantFPSDNode *N1C = isConstOrConstSplatFP(N1, /*AllowUndefs*/ true))
5554       if (N1C && N1C->getValueAPF().isNegZero() && N2.isUndef())
5555         return getUNDEF(VT);
5556     LLVM_FALLTHROUGH;
5557 
5558   case ISD::FADD:
5559   case ISD::FMUL:
5560   case ISD::FDIV:
5561   case ISD::FREM:
5562     // If both operands are undef, the result is undef. If 1 operand is undef,
5563     // the result is NaN. This should match the behavior of the IR optimizer.
5564     if (N1.isUndef() && N2.isUndef())
5565       return getUNDEF(VT);
5566     if (N1.isUndef() || N2.isUndef())
5567       return getConstantFP(APFloat::getNaN(EVTToAPFloatSemantics(VT)), DL, VT);
5568   }
5569   return SDValue();
5570 }
5571 
5572 SDValue SelectionDAG::getAssertAlign(const SDLoc &DL, SDValue Val, Align A) {
5573   assert(Val.getValueType().isInteger() && "Invalid AssertAlign!");
5574 
5575   // There's no need to assert on a byte-aligned pointer. All pointers are at
5576   // least byte aligned.
5577   if (A == Align(1))
5578     return Val;
5579 
5580   FoldingSetNodeID ID;
5581   AddNodeIDNode(ID, ISD::AssertAlign, getVTList(Val.getValueType()), {Val});
5582   ID.AddInteger(A.value());
5583 
5584   void *IP = nullptr;
5585   if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
5586     return SDValue(E, 0);
5587 
5588   auto *N = newSDNode<AssertAlignSDNode>(DL.getIROrder(), DL.getDebugLoc(),
5589                                          Val.getValueType(), A);
5590   createOperands(N, {Val});
5591 
5592   CSEMap.InsertNode(N, IP);
5593   InsertNode(N);
5594 
5595   SDValue V(N, 0);
5596   NewSDValueDbgMsg(V, "Creating new node: ", this);
5597   return V;
5598 }
5599 
5600 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
5601                               SDValue N1, SDValue N2) {
5602   SDNodeFlags Flags;
5603   if (Inserter)
5604     Flags = Inserter->getFlags();
5605   return getNode(Opcode, DL, VT, N1, N2, Flags);
5606 }
5607 
5608 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
5609                               SDValue N1, SDValue N2, const SDNodeFlags Flags) {
5610   assert(N1.getOpcode() != ISD::DELETED_NODE &&
5611          N2.getOpcode() != ISD::DELETED_NODE &&
5612          "Operand is DELETED_NODE!");
5613   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
5614   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
5615   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
5616   ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2);
5617 
5618   // Canonicalize constant to RHS if commutative.
5619   if (TLI->isCommutativeBinOp(Opcode)) {
5620     if (N1C && !N2C) {
5621       std::swap(N1C, N2C);
5622       std::swap(N1, N2);
5623     } else if (N1CFP && !N2CFP) {
5624       std::swap(N1CFP, N2CFP);
5625       std::swap(N1, N2);
5626     }
5627   }
5628 
5629   switch (Opcode) {
5630   default: break;
5631   case ISD::TokenFactor:
5632     assert(VT == MVT::Other && N1.getValueType() == MVT::Other &&
5633            N2.getValueType() == MVT::Other && "Invalid token factor!");
5634     // Fold trivial token factors.
5635     if (N1.getOpcode() == ISD::EntryToken) return N2;
5636     if (N2.getOpcode() == ISD::EntryToken) return N1;
5637     if (N1 == N2) return N1;
5638     break;
5639   case ISD::BUILD_VECTOR: {
5640     // Attempt to simplify BUILD_VECTOR.
5641     SDValue Ops[] = {N1, N2};
5642     if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
5643       return V;
5644     break;
5645   }
5646   case ISD::CONCAT_VECTORS: {
5647     SDValue Ops[] = {N1, N2};
5648     if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this))
5649       return V;
5650     break;
5651   }
5652   case ISD::AND:
5653     assert(VT.isInteger() && "This operator does not apply to FP types!");
5654     assert(N1.getValueType() == N2.getValueType() &&
5655            N1.getValueType() == VT && "Binary operator types must match!");
5656     // (X & 0) -> 0.  This commonly occurs when legalizing i64 values, so it's
5657     // worth handling here.
5658     if (N2C && N2C->isZero())
5659       return N2;
5660     if (N2C && N2C->isAllOnes()) // X & -1 -> X
5661       return N1;
5662     break;
5663   case ISD::OR:
5664   case ISD::XOR:
5665   case ISD::ADD:
5666   case ISD::SUB:
5667     assert(VT.isInteger() && "This operator does not apply to FP types!");
5668     assert(N1.getValueType() == N2.getValueType() &&
5669            N1.getValueType() == VT && "Binary operator types must match!");
5670     // (X ^|+- 0) -> X.  This commonly occurs when legalizing i64 values, so
5671     // it's worth handling here.
5672     if (N2C && N2C->isZero())
5673       return N1;
5674     if ((Opcode == ISD::ADD || Opcode == ISD::SUB) && VT.isVector() &&
5675         VT.getVectorElementType() == MVT::i1)
5676       return getNode(ISD::XOR, DL, VT, N1, N2);
5677     break;
5678   case ISD::MUL:
5679     assert(VT.isInteger() && "This operator does not apply to FP types!");
5680     assert(N1.getValueType() == N2.getValueType() &&
5681            N1.getValueType() == VT && "Binary operator types must match!");
5682     if (VT.isVector() && VT.getVectorElementType() == MVT::i1)
5683       return getNode(ISD::AND, DL, VT, N1, N2);
5684     if (N2C && (N1.getOpcode() == ISD::VSCALE) && Flags.hasNoSignedWrap()) {
5685       const APInt &MulImm = N1->getConstantOperandAPInt(0);
5686       const APInt &N2CImm = N2C->getAPIntValue();
5687       return getVScale(DL, VT, MulImm * N2CImm);
5688     }
5689     break;
5690   case ISD::UDIV:
5691   case ISD::UREM:
5692   case ISD::MULHU:
5693   case ISD::MULHS:
5694   case ISD::SDIV:
5695   case ISD::SREM:
5696   case ISD::SADDSAT:
5697   case ISD::SSUBSAT:
5698   case ISD::UADDSAT:
5699   case ISD::USUBSAT:
5700     assert(VT.isInteger() && "This operator does not apply to FP types!");
5701     assert(N1.getValueType() == N2.getValueType() &&
5702            N1.getValueType() == VT && "Binary operator types must match!");
5703     if (VT.isVector() && VT.getVectorElementType() == MVT::i1) {
5704       // fold (add_sat x, y) -> (or x, y) for bool types.
5705       if (Opcode == ISD::SADDSAT || Opcode == ISD::UADDSAT)
5706         return getNode(ISD::OR, DL, VT, N1, N2);
5707       // fold (sub_sat x, y) -> (and x, ~y) for bool types.
5708       if (Opcode == ISD::SSUBSAT || Opcode == ISD::USUBSAT)
5709         return getNode(ISD::AND, DL, VT, N1, getNOT(DL, N2, VT));
5710     }
5711     break;
5712   case ISD::SMIN:
5713   case ISD::UMAX:
5714     assert(VT.isInteger() && "This operator does not apply to FP types!");
5715     assert(N1.getValueType() == N2.getValueType() &&
5716            N1.getValueType() == VT && "Binary operator types must match!");
5717     if (VT.isVector() && VT.getVectorElementType() == MVT::i1)
5718       return getNode(ISD::OR, DL, VT, N1, N2);
5719     break;
5720   case ISD::SMAX:
5721   case ISD::UMIN:
5722     assert(VT.isInteger() && "This operator does not apply to FP types!");
5723     assert(N1.getValueType() == N2.getValueType() &&
5724            N1.getValueType() == VT && "Binary operator types must match!");
5725     if (VT.isVector() && VT.getVectorElementType() == MVT::i1)
5726       return getNode(ISD::AND, DL, VT, N1, N2);
5727     break;
5728   case ISD::FADD:
5729   case ISD::FSUB:
5730   case ISD::FMUL:
5731   case ISD::FDIV:
5732   case ISD::FREM:
5733     assert(VT.isFloatingPoint() && "This operator only applies to FP types!");
5734     assert(N1.getValueType() == N2.getValueType() &&
5735            N1.getValueType() == VT && "Binary operator types must match!");
5736     if (SDValue V = simplifyFPBinop(Opcode, N1, N2, Flags))
5737       return V;
5738     break;
5739   case ISD::FCOPYSIGN:   // N1 and result must match.  N1/N2 need not match.
5740     assert(N1.getValueType() == VT &&
5741            N1.getValueType().isFloatingPoint() &&
5742            N2.getValueType().isFloatingPoint() &&
5743            "Invalid FCOPYSIGN!");
5744     break;
5745   case ISD::SHL:
5746     if (N2C && (N1.getOpcode() == ISD::VSCALE) && Flags.hasNoSignedWrap()) {
5747       const APInt &MulImm = N1->getConstantOperandAPInt(0);
5748       const APInt &ShiftImm = N2C->getAPIntValue();
5749       return getVScale(DL, VT, MulImm << ShiftImm);
5750     }
5751     LLVM_FALLTHROUGH;
5752   case ISD::SRA:
5753   case ISD::SRL:
5754     if (SDValue V = simplifyShift(N1, N2))
5755       return V;
5756     LLVM_FALLTHROUGH;
5757   case ISD::ROTL:
5758   case ISD::ROTR:
5759     assert(VT == N1.getValueType() &&
5760            "Shift operators return type must be the same as their first arg");
5761     assert(VT.isInteger() && N2.getValueType().isInteger() &&
5762            "Shifts only work on integers");
5763     assert((!VT.isVector() || VT == N2.getValueType()) &&
5764            "Vector shift amounts must be in the same as their first arg");
5765     // Verify that the shift amount VT is big enough to hold valid shift
5766     // amounts.  This catches things like trying to shift an i1024 value by an
5767     // i8, which is easy to fall into in generic code that uses
5768     // TLI.getShiftAmount().
5769     assert(N2.getValueType().getScalarSizeInBits() >=
5770                Log2_32_Ceil(VT.getScalarSizeInBits()) &&
5771            "Invalid use of small shift amount with oversized value!");
5772 
5773     // Always fold shifts of i1 values so the code generator doesn't need to
5774     // handle them.  Since we know the size of the shift has to be less than the
5775     // size of the value, the shift/rotate count is guaranteed to be zero.
5776     if (VT == MVT::i1)
5777       return N1;
5778     if (N2C && N2C->isZero())
5779       return N1;
5780     break;
5781   case ISD::FP_ROUND:
5782     assert(VT.isFloatingPoint() &&
5783            N1.getValueType().isFloatingPoint() &&
5784            VT.bitsLE(N1.getValueType()) &&
5785            N2C && (N2C->getZExtValue() == 0 || N2C->getZExtValue() == 1) &&
5786            "Invalid FP_ROUND!");
5787     if (N1.getValueType() == VT) return N1;  // noop conversion.
5788     break;
5789   case ISD::AssertSext:
5790   case ISD::AssertZext: {
5791     EVT EVT = cast<VTSDNode>(N2)->getVT();
5792     assert(VT == N1.getValueType() && "Not an inreg extend!");
5793     assert(VT.isInteger() && EVT.isInteger() &&
5794            "Cannot *_EXTEND_INREG FP types");
5795     assert(!EVT.isVector() &&
5796            "AssertSExt/AssertZExt type should be the vector element type "
5797            "rather than the vector type!");
5798     assert(EVT.bitsLE(VT.getScalarType()) && "Not extending!");
5799     if (VT.getScalarType() == EVT) return N1; // noop assertion.
5800     break;
5801   }
5802   case ISD::SIGN_EXTEND_INREG: {
5803     EVT EVT = cast<VTSDNode>(N2)->getVT();
5804     assert(VT == N1.getValueType() && "Not an inreg extend!");
5805     assert(VT.isInteger() && EVT.isInteger() &&
5806            "Cannot *_EXTEND_INREG FP types");
5807     assert(EVT.isVector() == VT.isVector() &&
5808            "SIGN_EXTEND_INREG type should be vector iff the operand "
5809            "type is vector!");
5810     assert((!EVT.isVector() ||
5811             EVT.getVectorElementCount() == VT.getVectorElementCount()) &&
5812            "Vector element counts must match in SIGN_EXTEND_INREG");
5813     assert(EVT.bitsLE(VT) && "Not extending!");
5814     if (EVT == VT) return N1;  // Not actually extending
5815 
5816     auto SignExtendInReg = [&](APInt Val, llvm::EVT ConstantVT) {
5817       unsigned FromBits = EVT.getScalarSizeInBits();
5818       Val <<= Val.getBitWidth() - FromBits;
5819       Val.ashrInPlace(Val.getBitWidth() - FromBits);
5820       return getConstant(Val, DL, ConstantVT);
5821     };
5822 
5823     if (N1C) {
5824       const APInt &Val = N1C->getAPIntValue();
5825       return SignExtendInReg(Val, VT);
5826     }
5827 
5828     if (ISD::isBuildVectorOfConstantSDNodes(N1.getNode())) {
5829       SmallVector<SDValue, 8> Ops;
5830       llvm::EVT OpVT = N1.getOperand(0).getValueType();
5831       for (int i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
5832         SDValue Op = N1.getOperand(i);
5833         if (Op.isUndef()) {
5834           Ops.push_back(getUNDEF(OpVT));
5835           continue;
5836         }
5837         ConstantSDNode *C = cast<ConstantSDNode>(Op);
5838         APInt Val = C->getAPIntValue();
5839         Ops.push_back(SignExtendInReg(Val, OpVT));
5840       }
5841       return getBuildVector(VT, DL, Ops);
5842     }
5843     break;
5844   }
5845   case ISD::FP_TO_SINT_SAT:
5846   case ISD::FP_TO_UINT_SAT: {
5847     assert(VT.isInteger() && cast<VTSDNode>(N2)->getVT().isInteger() &&
5848            N1.getValueType().isFloatingPoint() && "Invalid FP_TO_*INT_SAT");
5849     assert(N1.getValueType().isVector() == VT.isVector() &&
5850            "FP_TO_*INT_SAT type should be vector iff the operand type is "
5851            "vector!");
5852     assert((!VT.isVector() || VT.getVectorNumElements() ==
5853                                   N1.getValueType().getVectorNumElements()) &&
5854            "Vector element counts must match in FP_TO_*INT_SAT");
5855     assert(!cast<VTSDNode>(N2)->getVT().isVector() &&
5856            "Type to saturate to must be a scalar.");
5857     assert(cast<VTSDNode>(N2)->getVT().bitsLE(VT.getScalarType()) &&
5858            "Not extending!");
5859     break;
5860   }
5861   case ISD::EXTRACT_VECTOR_ELT:
5862     assert(VT.getSizeInBits() >= N1.getValueType().getScalarSizeInBits() &&
5863            "The result of EXTRACT_VECTOR_ELT must be at least as wide as the \
5864              element type of the vector.");
5865 
5866     // Extract from an undefined value or using an undefined index is undefined.
5867     if (N1.isUndef() || N2.isUndef())
5868       return getUNDEF(VT);
5869 
5870     // EXTRACT_VECTOR_ELT of out-of-bounds element is an UNDEF for fixed length
5871     // vectors. For scalable vectors we will provide appropriate support for
5872     // dealing with arbitrary indices.
5873     if (N2C && N1.getValueType().isFixedLengthVector() &&
5874         N2C->getAPIntValue().uge(N1.getValueType().getVectorNumElements()))
5875       return getUNDEF(VT);
5876 
5877     // EXTRACT_VECTOR_ELT of CONCAT_VECTORS is often formed while lowering is
5878     // expanding copies of large vectors from registers. This only works for
5879     // fixed length vectors, since we need to know the exact number of
5880     // elements.
5881     if (N2C && N1.getOperand(0).getValueType().isFixedLengthVector() &&
5882         N1.getOpcode() == ISD::CONCAT_VECTORS && N1.getNumOperands() > 0) {
5883       unsigned Factor =
5884         N1.getOperand(0).getValueType().getVectorNumElements();
5885       return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
5886                      N1.getOperand(N2C->getZExtValue() / Factor),
5887                      getVectorIdxConstant(N2C->getZExtValue() % Factor, DL));
5888     }
5889 
5890     // EXTRACT_VECTOR_ELT of BUILD_VECTOR or SPLAT_VECTOR is often formed while
5891     // lowering is expanding large vector constants.
5892     if (N2C && (N1.getOpcode() == ISD::BUILD_VECTOR ||
5893                 N1.getOpcode() == ISD::SPLAT_VECTOR)) {
5894       assert((N1.getOpcode() != ISD::BUILD_VECTOR ||
5895               N1.getValueType().isFixedLengthVector()) &&
5896              "BUILD_VECTOR used for scalable vectors");
5897       unsigned Index =
5898           N1.getOpcode() == ISD::BUILD_VECTOR ? N2C->getZExtValue() : 0;
5899       SDValue Elt = N1.getOperand(Index);
5900 
5901       if (VT != Elt.getValueType())
5902         // If the vector element type is not legal, the BUILD_VECTOR operands
5903         // are promoted and implicitly truncated, and the result implicitly
5904         // extended. Make that explicit here.
5905         Elt = getAnyExtOrTrunc(Elt, DL, VT);
5906 
5907       return Elt;
5908     }
5909 
5910     // EXTRACT_VECTOR_ELT of INSERT_VECTOR_ELT is often formed when vector
5911     // operations are lowered to scalars.
5912     if (N1.getOpcode() == ISD::INSERT_VECTOR_ELT) {
5913       // If the indices are the same, return the inserted element else
5914       // if the indices are known different, extract the element from
5915       // the original vector.
5916       SDValue N1Op2 = N1.getOperand(2);
5917       ConstantSDNode *N1Op2C = dyn_cast<ConstantSDNode>(N1Op2);
5918 
5919       if (N1Op2C && N2C) {
5920         if (N1Op2C->getZExtValue() == N2C->getZExtValue()) {
5921           if (VT == N1.getOperand(1).getValueType())
5922             return N1.getOperand(1);
5923           return getSExtOrTrunc(N1.getOperand(1), DL, VT);
5924         }
5925         return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0), N2);
5926       }
5927     }
5928 
5929     // EXTRACT_VECTOR_ELT of v1iX EXTRACT_SUBVECTOR could be formed
5930     // when vector types are scalarized and v1iX is legal.
5931     // vextract (v1iX extract_subvector(vNiX, Idx)) -> vextract(vNiX,Idx).
5932     // Here we are completely ignoring the extract element index (N2),
5933     // which is fine for fixed width vectors, since any index other than 0
5934     // is undefined anyway. However, this cannot be ignored for scalable
5935     // vectors - in theory we could support this, but we don't want to do this
5936     // without a profitability check.
5937     if (N1.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
5938         N1.getValueType().isFixedLengthVector() &&
5939         N1.getValueType().getVectorNumElements() == 1) {
5940       return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0),
5941                      N1.getOperand(1));
5942     }
5943     break;
5944   case ISD::EXTRACT_ELEMENT:
5945     assert(N2C && (unsigned)N2C->getZExtValue() < 2 && "Bad EXTRACT_ELEMENT!");
5946     assert(!N1.getValueType().isVector() && !VT.isVector() &&
5947            (N1.getValueType().isInteger() == VT.isInteger()) &&
5948            N1.getValueType() != VT &&
5949            "Wrong types for EXTRACT_ELEMENT!");
5950 
5951     // EXTRACT_ELEMENT of BUILD_PAIR is often formed while legalize is expanding
5952     // 64-bit integers into 32-bit parts.  Instead of building the extract of
5953     // the BUILD_PAIR, only to have legalize rip it apart, just do it now.
5954     if (N1.getOpcode() == ISD::BUILD_PAIR)
5955       return N1.getOperand(N2C->getZExtValue());
5956 
5957     // EXTRACT_ELEMENT of a constant int is also very common.
5958     if (N1C) {
5959       unsigned ElementSize = VT.getSizeInBits();
5960       unsigned Shift = ElementSize * N2C->getZExtValue();
5961       const APInt &Val = N1C->getAPIntValue();
5962       return getConstant(Val.extractBits(ElementSize, Shift), DL, VT);
5963     }
5964     break;
5965   case ISD::EXTRACT_SUBVECTOR: {
5966     EVT N1VT = N1.getValueType();
5967     assert(VT.isVector() && N1VT.isVector() &&
5968            "Extract subvector VTs must be vectors!");
5969     assert(VT.getVectorElementType() == N1VT.getVectorElementType() &&
5970            "Extract subvector VTs must have the same element type!");
5971     assert((VT.isFixedLengthVector() || N1VT.isScalableVector()) &&
5972            "Cannot extract a scalable vector from a fixed length vector!");
5973     assert((VT.isScalableVector() != N1VT.isScalableVector() ||
5974             VT.getVectorMinNumElements() <= N1VT.getVectorMinNumElements()) &&
5975            "Extract subvector must be from larger vector to smaller vector!");
5976     assert(N2C && "Extract subvector index must be a constant");
5977     assert((VT.isScalableVector() != N1VT.isScalableVector() ||
5978             (VT.getVectorMinNumElements() + N2C->getZExtValue()) <=
5979                 N1VT.getVectorMinNumElements()) &&
5980            "Extract subvector overflow!");
5981     assert(N2C->getAPIntValue().getBitWidth() ==
5982                TLI->getVectorIdxTy(getDataLayout()).getFixedSizeInBits() &&
5983            "Constant index for EXTRACT_SUBVECTOR has an invalid size");
5984 
5985     // Trivial extraction.
5986     if (VT == N1VT)
5987       return N1;
5988 
5989     // EXTRACT_SUBVECTOR of an UNDEF is an UNDEF.
5990     if (N1.isUndef())
5991       return getUNDEF(VT);
5992 
5993     // EXTRACT_SUBVECTOR of CONCAT_VECTOR can be simplified if the pieces of
5994     // the concat have the same type as the extract.
5995     if (N1.getOpcode() == ISD::CONCAT_VECTORS && N1.getNumOperands() > 0 &&
5996         VT == N1.getOperand(0).getValueType()) {
5997       unsigned Factor = VT.getVectorMinNumElements();
5998       return N1.getOperand(N2C->getZExtValue() / Factor);
5999     }
6000 
6001     // EXTRACT_SUBVECTOR of INSERT_SUBVECTOR is often created
6002     // during shuffle legalization.
6003     if (N1.getOpcode() == ISD::INSERT_SUBVECTOR && N2 == N1.getOperand(2) &&
6004         VT == N1.getOperand(1).getValueType())
6005       return N1.getOperand(1);
6006     break;
6007   }
6008   }
6009 
6010   // Perform trivial constant folding.
6011   if (SDValue SV = FoldConstantArithmetic(Opcode, DL, VT, {N1, N2}))
6012     return SV;
6013 
6014   // Canonicalize an UNDEF to the RHS, even over a constant.
6015   if (N1.isUndef()) {
6016     if (TLI->isCommutativeBinOp(Opcode)) {
6017       std::swap(N1, N2);
6018     } else {
6019       switch (Opcode) {
6020       case ISD::SIGN_EXTEND_INREG:
6021       case ISD::SUB:
6022         return getUNDEF(VT);     // fold op(undef, arg2) -> undef
6023       case ISD::UDIV:
6024       case ISD::SDIV:
6025       case ISD::UREM:
6026       case ISD::SREM:
6027       case ISD::SSUBSAT:
6028       case ISD::USUBSAT:
6029         return getConstant(0, DL, VT);    // fold op(undef, arg2) -> 0
6030       }
6031     }
6032   }
6033 
6034   // Fold a bunch of operators when the RHS is undef.
6035   if (N2.isUndef()) {
6036     switch (Opcode) {
6037     case ISD::XOR:
6038       if (N1.isUndef())
6039         // Handle undef ^ undef -> 0 special case. This is a common
6040         // idiom (misuse).
6041         return getConstant(0, DL, VT);
6042       LLVM_FALLTHROUGH;
6043     case ISD::ADD:
6044     case ISD::SUB:
6045     case ISD::UDIV:
6046     case ISD::SDIV:
6047     case ISD::UREM:
6048     case ISD::SREM:
6049       return getUNDEF(VT);       // fold op(arg1, undef) -> undef
6050     case ISD::MUL:
6051     case ISD::AND:
6052     case ISD::SSUBSAT:
6053     case ISD::USUBSAT:
6054       return getConstant(0, DL, VT);  // fold op(arg1, undef) -> 0
6055     case ISD::OR:
6056     case ISD::SADDSAT:
6057     case ISD::UADDSAT:
6058       return getAllOnesConstant(DL, VT);
6059     }
6060   }
6061 
6062   // Memoize this node if possible.
6063   SDNode *N;
6064   SDVTList VTs = getVTList(VT);
6065   SDValue Ops[] = {N1, N2};
6066   if (VT != MVT::Glue) {
6067     FoldingSetNodeID ID;
6068     AddNodeIDNode(ID, Opcode, VTs, Ops);
6069     void *IP = nullptr;
6070     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
6071       E->intersectFlagsWith(Flags);
6072       return SDValue(E, 0);
6073     }
6074 
6075     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
6076     N->setFlags(Flags);
6077     createOperands(N, Ops);
6078     CSEMap.InsertNode(N, IP);
6079   } else {
6080     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
6081     createOperands(N, Ops);
6082   }
6083 
6084   InsertNode(N);
6085   SDValue V = SDValue(N, 0);
6086   NewSDValueDbgMsg(V, "Creating new node: ", this);
6087   return V;
6088 }
6089 
6090 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
6091                               SDValue N1, SDValue N2, SDValue N3) {
6092   SDNodeFlags Flags;
6093   if (Inserter)
6094     Flags = Inserter->getFlags();
6095   return getNode(Opcode, DL, VT, N1, N2, N3, Flags);
6096 }
6097 
6098 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
6099                               SDValue N1, SDValue N2, SDValue N3,
6100                               const SDNodeFlags Flags) {
6101   assert(N1.getOpcode() != ISD::DELETED_NODE &&
6102          N2.getOpcode() != ISD::DELETED_NODE &&
6103          N3.getOpcode() != ISD::DELETED_NODE &&
6104          "Operand is DELETED_NODE!");
6105   // Perform various simplifications.
6106   switch (Opcode) {
6107   case ISD::FMA: {
6108     assert(VT.isFloatingPoint() && "This operator only applies to FP types!");
6109     assert(N1.getValueType() == VT && N2.getValueType() == VT &&
6110            N3.getValueType() == VT && "FMA types must match!");
6111     ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6112     ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2);
6113     ConstantFPSDNode *N3CFP = dyn_cast<ConstantFPSDNode>(N3);
6114     if (N1CFP && N2CFP && N3CFP) {
6115       APFloat  V1 = N1CFP->getValueAPF();
6116       const APFloat &V2 = N2CFP->getValueAPF();
6117       const APFloat &V3 = N3CFP->getValueAPF();
6118       V1.fusedMultiplyAdd(V2, V3, APFloat::rmNearestTiesToEven);
6119       return getConstantFP(V1, DL, VT);
6120     }
6121     break;
6122   }
6123   case ISD::BUILD_VECTOR: {
6124     // Attempt to simplify BUILD_VECTOR.
6125     SDValue Ops[] = {N1, N2, N3};
6126     if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
6127       return V;
6128     break;
6129   }
6130   case ISD::CONCAT_VECTORS: {
6131     SDValue Ops[] = {N1, N2, N3};
6132     if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this))
6133       return V;
6134     break;
6135   }
6136   case ISD::SETCC: {
6137     assert(VT.isInteger() && "SETCC result type must be an integer!");
6138     assert(N1.getValueType() == N2.getValueType() &&
6139            "SETCC operands must have the same type!");
6140     assert(VT.isVector() == N1.getValueType().isVector() &&
6141            "SETCC type should be vector iff the operand type is vector!");
6142     assert((!VT.isVector() || VT.getVectorElementCount() ==
6143                                   N1.getValueType().getVectorElementCount()) &&
6144            "SETCC vector element counts must match!");
6145     // Use FoldSetCC to simplify SETCC's.
6146     if (SDValue V = FoldSetCC(VT, N1, N2, cast<CondCodeSDNode>(N3)->get(), DL))
6147       return V;
6148     // Vector constant folding.
6149     SDValue Ops[] = {N1, N2, N3};
6150     if (SDValue V = FoldConstantArithmetic(Opcode, DL, VT, Ops)) {
6151       NewSDValueDbgMsg(V, "New node vector constant folding: ", this);
6152       return V;
6153     }
6154     break;
6155   }
6156   case ISD::SELECT:
6157   case ISD::VSELECT:
6158     if (SDValue V = simplifySelect(N1, N2, N3))
6159       return V;
6160     break;
6161   case ISD::VECTOR_SHUFFLE:
6162     llvm_unreachable("should use getVectorShuffle constructor!");
6163   case ISD::VECTOR_SPLICE: {
6164     if (cast<ConstantSDNode>(N3)->isNullValue())
6165       return N1;
6166     break;
6167   }
6168   case ISD::INSERT_VECTOR_ELT: {
6169     ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3);
6170     // INSERT_VECTOR_ELT into out-of-bounds element is an UNDEF, except
6171     // for scalable vectors where we will generate appropriate code to
6172     // deal with out-of-bounds cases correctly.
6173     if (N3C && N1.getValueType().isFixedLengthVector() &&
6174         N3C->getZExtValue() >= N1.getValueType().getVectorNumElements())
6175       return getUNDEF(VT);
6176 
6177     // Undefined index can be assumed out-of-bounds, so that's UNDEF too.
6178     if (N3.isUndef())
6179       return getUNDEF(VT);
6180 
6181     // If the inserted element is an UNDEF, just use the input vector.
6182     if (N2.isUndef())
6183       return N1;
6184 
6185     break;
6186   }
6187   case ISD::INSERT_SUBVECTOR: {
6188     // Inserting undef into undef is still undef.
6189     if (N1.isUndef() && N2.isUndef())
6190       return getUNDEF(VT);
6191 
6192     EVT N2VT = N2.getValueType();
6193     assert(VT == N1.getValueType() &&
6194            "Dest and insert subvector source types must match!");
6195     assert(VT.isVector() && N2VT.isVector() &&
6196            "Insert subvector VTs must be vectors!");
6197     assert((VT.isScalableVector() || N2VT.isFixedLengthVector()) &&
6198            "Cannot insert a scalable vector into a fixed length vector!");
6199     assert((VT.isScalableVector() != N2VT.isScalableVector() ||
6200             VT.getVectorMinNumElements() >= N2VT.getVectorMinNumElements()) &&
6201            "Insert subvector must be from smaller vector to larger vector!");
6202     assert(isa<ConstantSDNode>(N3) &&
6203            "Insert subvector index must be constant");
6204     assert((VT.isScalableVector() != N2VT.isScalableVector() ||
6205             (N2VT.getVectorMinNumElements() +
6206              cast<ConstantSDNode>(N3)->getZExtValue()) <=
6207                 VT.getVectorMinNumElements()) &&
6208            "Insert subvector overflow!");
6209     assert(cast<ConstantSDNode>(N3)->getAPIntValue().getBitWidth() ==
6210                TLI->getVectorIdxTy(getDataLayout()).getFixedSizeInBits() &&
6211            "Constant index for INSERT_SUBVECTOR has an invalid size");
6212 
6213     // Trivial insertion.
6214     if (VT == N2VT)
6215       return N2;
6216 
6217     // If this is an insert of an extracted vector into an undef vector, we
6218     // can just use the input to the extract.
6219     if (N1.isUndef() && N2.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
6220         N2.getOperand(1) == N3 && N2.getOperand(0).getValueType() == VT)
6221       return N2.getOperand(0);
6222     break;
6223   }
6224   case ISD::BITCAST:
6225     // Fold bit_convert nodes from a type to themselves.
6226     if (N1.getValueType() == VT)
6227       return N1;
6228     break;
6229   }
6230 
6231   // Memoize node if it doesn't produce a flag.
6232   SDNode *N;
6233   SDVTList VTs = getVTList(VT);
6234   SDValue Ops[] = {N1, N2, N3};
6235   if (VT != MVT::Glue) {
6236     FoldingSetNodeID ID;
6237     AddNodeIDNode(ID, Opcode, VTs, Ops);
6238     void *IP = nullptr;
6239     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
6240       E->intersectFlagsWith(Flags);
6241       return SDValue(E, 0);
6242     }
6243 
6244     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
6245     N->setFlags(Flags);
6246     createOperands(N, Ops);
6247     CSEMap.InsertNode(N, IP);
6248   } else {
6249     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
6250     createOperands(N, Ops);
6251   }
6252 
6253   InsertNode(N);
6254   SDValue V = SDValue(N, 0);
6255   NewSDValueDbgMsg(V, "Creating new node: ", this);
6256   return V;
6257 }
6258 
6259 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
6260                               SDValue N1, SDValue N2, SDValue N3, SDValue N4) {
6261   SDValue Ops[] = { N1, N2, N3, N4 };
6262   return getNode(Opcode, DL, VT, Ops);
6263 }
6264 
6265 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
6266                               SDValue N1, SDValue N2, SDValue N3, SDValue N4,
6267                               SDValue N5) {
6268   SDValue Ops[] = { N1, N2, N3, N4, N5 };
6269   return getNode(Opcode, DL, VT, Ops);
6270 }
6271 
6272 /// getStackArgumentTokenFactor - Compute a TokenFactor to force all
6273 /// the incoming stack arguments to be loaded from the stack.
6274 SDValue SelectionDAG::getStackArgumentTokenFactor(SDValue Chain) {
6275   SmallVector<SDValue, 8> ArgChains;
6276 
6277   // Include the original chain at the beginning of the list. When this is
6278   // used by target LowerCall hooks, this helps legalize find the
6279   // CALLSEQ_BEGIN node.
6280   ArgChains.push_back(Chain);
6281 
6282   // Add a chain value for each stack argument.
6283   for (SDNode *U : getEntryNode().getNode()->uses())
6284     if (LoadSDNode *L = dyn_cast<LoadSDNode>(U))
6285       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
6286         if (FI->getIndex() < 0)
6287           ArgChains.push_back(SDValue(L, 1));
6288 
6289   // Build a tokenfactor for all the chains.
6290   return getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains);
6291 }
6292 
6293 /// getMemsetValue - Vectorized representation of the memset value
6294 /// operand.
6295 static SDValue getMemsetValue(SDValue Value, EVT VT, SelectionDAG &DAG,
6296                               const SDLoc &dl) {
6297   assert(!Value.isUndef());
6298 
6299   unsigned NumBits = VT.getScalarSizeInBits();
6300   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
6301     assert(C->getAPIntValue().getBitWidth() == 8);
6302     APInt Val = APInt::getSplat(NumBits, C->getAPIntValue());
6303     if (VT.isInteger()) {
6304       bool IsOpaque = VT.getSizeInBits() > 64 ||
6305           !DAG.getTargetLoweringInfo().isLegalStoreImmediate(C->getSExtValue());
6306       return DAG.getConstant(Val, dl, VT, false, IsOpaque);
6307     }
6308     return DAG.getConstantFP(APFloat(DAG.EVTToAPFloatSemantics(VT), Val), dl,
6309                              VT);
6310   }
6311 
6312   assert(Value.getValueType() == MVT::i8 && "memset with non-byte fill value?");
6313   EVT IntVT = VT.getScalarType();
6314   if (!IntVT.isInteger())
6315     IntVT = EVT::getIntegerVT(*DAG.getContext(), IntVT.getSizeInBits());
6316 
6317   Value = DAG.getNode(ISD::ZERO_EXTEND, dl, IntVT, Value);
6318   if (NumBits > 8) {
6319     // Use a multiplication with 0x010101... to extend the input to the
6320     // required length.
6321     APInt Magic = APInt::getSplat(NumBits, APInt(8, 0x01));
6322     Value = DAG.getNode(ISD::MUL, dl, IntVT, Value,
6323                         DAG.getConstant(Magic, dl, IntVT));
6324   }
6325 
6326   if (VT != Value.getValueType() && !VT.isInteger())
6327     Value = DAG.getBitcast(VT.getScalarType(), Value);
6328   if (VT != Value.getValueType())
6329     Value = DAG.getSplatBuildVector(VT, dl, Value);
6330 
6331   return Value;
6332 }
6333 
6334 /// getMemsetStringVal - Similar to getMemsetValue. Except this is only
6335 /// used when a memcpy is turned into a memset when the source is a constant
6336 /// string ptr.
6337 static SDValue getMemsetStringVal(EVT VT, const SDLoc &dl, SelectionDAG &DAG,
6338                                   const TargetLowering &TLI,
6339                                   const ConstantDataArraySlice &Slice) {
6340   // Handle vector with all elements zero.
6341   if (Slice.Array == nullptr) {
6342     if (VT.isInteger())
6343       return DAG.getConstant(0, dl, VT);
6344     if (VT == MVT::f32 || VT == MVT::f64 || VT == MVT::f128)
6345       return DAG.getConstantFP(0.0, dl, VT);
6346     if (VT.isVector()) {
6347       unsigned NumElts = VT.getVectorNumElements();
6348       MVT EltVT = (VT.getVectorElementType() == MVT::f32) ? MVT::i32 : MVT::i64;
6349       return DAG.getNode(ISD::BITCAST, dl, VT,
6350                          DAG.getConstant(0, dl,
6351                                          EVT::getVectorVT(*DAG.getContext(),
6352                                                           EltVT, NumElts)));
6353     }
6354     llvm_unreachable("Expected type!");
6355   }
6356 
6357   assert(!VT.isVector() && "Can't handle vector type here!");
6358   unsigned NumVTBits = VT.getSizeInBits();
6359   unsigned NumVTBytes = NumVTBits / 8;
6360   unsigned NumBytes = std::min(NumVTBytes, unsigned(Slice.Length));
6361 
6362   APInt Val(NumVTBits, 0);
6363   if (DAG.getDataLayout().isLittleEndian()) {
6364     for (unsigned i = 0; i != NumBytes; ++i)
6365       Val |= (uint64_t)(unsigned char)Slice[i] << i*8;
6366   } else {
6367     for (unsigned i = 0; i != NumBytes; ++i)
6368       Val |= (uint64_t)(unsigned char)Slice[i] << (NumVTBytes-i-1)*8;
6369   }
6370 
6371   // If the "cost" of materializing the integer immediate is less than the cost
6372   // of a load, then it is cost effective to turn the load into the immediate.
6373   Type *Ty = VT.getTypeForEVT(*DAG.getContext());
6374   if (TLI.shouldConvertConstantLoadToIntImm(Val, Ty))
6375     return DAG.getConstant(Val, dl, VT);
6376   return SDValue();
6377 }
6378 
6379 SDValue SelectionDAG::getMemBasePlusOffset(SDValue Base, TypeSize Offset,
6380                                            const SDLoc &DL,
6381                                            const SDNodeFlags Flags) {
6382   EVT VT = Base.getValueType();
6383   SDValue Index;
6384 
6385   if (Offset.isScalable())
6386     Index = getVScale(DL, Base.getValueType(),
6387                       APInt(Base.getValueSizeInBits().getFixedSize(),
6388                             Offset.getKnownMinSize()));
6389   else
6390     Index = getConstant(Offset.getFixedSize(), DL, VT);
6391 
6392   return getMemBasePlusOffset(Base, Index, DL, Flags);
6393 }
6394 
6395 SDValue SelectionDAG::getMemBasePlusOffset(SDValue Ptr, SDValue Offset,
6396                                            const SDLoc &DL,
6397                                            const SDNodeFlags Flags) {
6398   assert(Offset.getValueType().isInteger());
6399   EVT BasePtrVT = Ptr.getValueType();
6400   return getNode(ISD::ADD, DL, BasePtrVT, Ptr, Offset, Flags);
6401 }
6402 
6403 /// Returns true if memcpy source is constant data.
6404 static bool isMemSrcFromConstant(SDValue Src, ConstantDataArraySlice &Slice) {
6405   uint64_t SrcDelta = 0;
6406   GlobalAddressSDNode *G = nullptr;
6407   if (Src.getOpcode() == ISD::GlobalAddress)
6408     G = cast<GlobalAddressSDNode>(Src);
6409   else if (Src.getOpcode() == ISD::ADD &&
6410            Src.getOperand(0).getOpcode() == ISD::GlobalAddress &&
6411            Src.getOperand(1).getOpcode() == ISD::Constant) {
6412     G = cast<GlobalAddressSDNode>(Src.getOperand(0));
6413     SrcDelta = cast<ConstantSDNode>(Src.getOperand(1))->getZExtValue();
6414   }
6415   if (!G)
6416     return false;
6417 
6418   return getConstantDataArrayInfo(G->getGlobal(), Slice, 8,
6419                                   SrcDelta + G->getOffset());
6420 }
6421 
6422 static bool shouldLowerMemFuncForSize(const MachineFunction &MF,
6423                                       SelectionDAG &DAG) {
6424   // On Darwin, -Os means optimize for size without hurting performance, so
6425   // only really optimize for size when -Oz (MinSize) is used.
6426   if (MF.getTarget().getTargetTriple().isOSDarwin())
6427     return MF.getFunction().hasMinSize();
6428   return DAG.shouldOptForSize();
6429 }
6430 
6431 static void chainLoadsAndStoresForMemcpy(SelectionDAG &DAG, const SDLoc &dl,
6432                           SmallVector<SDValue, 32> &OutChains, unsigned From,
6433                           unsigned To, SmallVector<SDValue, 16> &OutLoadChains,
6434                           SmallVector<SDValue, 16> &OutStoreChains) {
6435   assert(OutLoadChains.size() && "Missing loads in memcpy inlining");
6436   assert(OutStoreChains.size() && "Missing stores in memcpy inlining");
6437   SmallVector<SDValue, 16> GluedLoadChains;
6438   for (unsigned i = From; i < To; ++i) {
6439     OutChains.push_back(OutLoadChains[i]);
6440     GluedLoadChains.push_back(OutLoadChains[i]);
6441   }
6442 
6443   // Chain for all loads.
6444   SDValue LoadToken = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
6445                                   GluedLoadChains);
6446 
6447   for (unsigned i = From; i < To; ++i) {
6448     StoreSDNode *ST = dyn_cast<StoreSDNode>(OutStoreChains[i]);
6449     SDValue NewStore = DAG.getTruncStore(LoadToken, dl, ST->getValue(),
6450                                   ST->getBasePtr(), ST->getMemoryVT(),
6451                                   ST->getMemOperand());
6452     OutChains.push_back(NewStore);
6453   }
6454 }
6455 
6456 static SDValue getMemcpyLoadsAndStores(SelectionDAG &DAG, const SDLoc &dl,
6457                                        SDValue Chain, SDValue Dst, SDValue Src,
6458                                        uint64_t Size, Align Alignment,
6459                                        bool isVol, bool AlwaysInline,
6460                                        MachinePointerInfo DstPtrInfo,
6461                                        MachinePointerInfo SrcPtrInfo,
6462                                        const AAMDNodes &AAInfo) {
6463   // Turn a memcpy of undef to nop.
6464   // FIXME: We need to honor volatile even is Src is undef.
6465   if (Src.isUndef())
6466     return Chain;
6467 
6468   // Expand memcpy to a series of load and store ops if the size operand falls
6469   // below a certain threshold.
6470   // TODO: In the AlwaysInline case, if the size is big then generate a loop
6471   // rather than maybe a humongous number of loads and stores.
6472   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6473   const DataLayout &DL = DAG.getDataLayout();
6474   LLVMContext &C = *DAG.getContext();
6475   std::vector<EVT> MemOps;
6476   bool DstAlignCanChange = false;
6477   MachineFunction &MF = DAG.getMachineFunction();
6478   MachineFrameInfo &MFI = MF.getFrameInfo();
6479   bool OptSize = shouldLowerMemFuncForSize(MF, DAG);
6480   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
6481   if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
6482     DstAlignCanChange = true;
6483   MaybeAlign SrcAlign = DAG.InferPtrAlign(Src);
6484   if (!SrcAlign || Alignment > *SrcAlign)
6485     SrcAlign = Alignment;
6486   assert(SrcAlign && "SrcAlign must be set");
6487   ConstantDataArraySlice Slice;
6488   // If marked as volatile, perform a copy even when marked as constant.
6489   bool CopyFromConstant = !isVol && isMemSrcFromConstant(Src, Slice);
6490   bool isZeroConstant = CopyFromConstant && Slice.Array == nullptr;
6491   unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemcpy(OptSize);
6492   const MemOp Op = isZeroConstant
6493                        ? MemOp::Set(Size, DstAlignCanChange, Alignment,
6494                                     /*IsZeroMemset*/ true, isVol)
6495                        : MemOp::Copy(Size, DstAlignCanChange, Alignment,
6496                                      *SrcAlign, isVol, CopyFromConstant);
6497   if (!TLI.findOptimalMemOpLowering(
6498           MemOps, Limit, Op, DstPtrInfo.getAddrSpace(),
6499           SrcPtrInfo.getAddrSpace(), MF.getFunction().getAttributes()))
6500     return SDValue();
6501 
6502   if (DstAlignCanChange) {
6503     Type *Ty = MemOps[0].getTypeForEVT(C);
6504     Align NewAlign = DL.getABITypeAlign(Ty);
6505 
6506     // Don't promote to an alignment that would require dynamic stack
6507     // realignment.
6508     const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
6509     if (!TRI->hasStackRealignment(MF))
6510       while (NewAlign > Alignment && DL.exceedsNaturalStackAlignment(NewAlign))
6511         NewAlign = NewAlign / 2;
6512 
6513     if (NewAlign > Alignment) {
6514       // Give the stack frame object a larger alignment if needed.
6515       if (MFI.getObjectAlign(FI->getIndex()) < NewAlign)
6516         MFI.setObjectAlignment(FI->getIndex(), NewAlign);
6517       Alignment = NewAlign;
6518     }
6519   }
6520 
6521   // Prepare AAInfo for loads/stores after lowering this memcpy.
6522   AAMDNodes NewAAInfo = AAInfo;
6523   NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr;
6524 
6525   MachineMemOperand::Flags MMOFlags =
6526       isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone;
6527   SmallVector<SDValue, 16> OutLoadChains;
6528   SmallVector<SDValue, 16> OutStoreChains;
6529   SmallVector<SDValue, 32> OutChains;
6530   unsigned NumMemOps = MemOps.size();
6531   uint64_t SrcOff = 0, DstOff = 0;
6532   for (unsigned i = 0; i != NumMemOps; ++i) {
6533     EVT VT = MemOps[i];
6534     unsigned VTSize = VT.getSizeInBits() / 8;
6535     SDValue Value, Store;
6536 
6537     if (VTSize > Size) {
6538       // Issuing an unaligned load / store pair  that overlaps with the previous
6539       // pair. Adjust the offset accordingly.
6540       assert(i == NumMemOps-1 && i != 0);
6541       SrcOff -= VTSize - Size;
6542       DstOff -= VTSize - Size;
6543     }
6544 
6545     if (CopyFromConstant &&
6546         (isZeroConstant || (VT.isInteger() && !VT.isVector()))) {
6547       // It's unlikely a store of a vector immediate can be done in a single
6548       // instruction. It would require a load from a constantpool first.
6549       // We only handle zero vectors here.
6550       // FIXME: Handle other cases where store of vector immediate is done in
6551       // a single instruction.
6552       ConstantDataArraySlice SubSlice;
6553       if (SrcOff < Slice.Length) {
6554         SubSlice = Slice;
6555         SubSlice.move(SrcOff);
6556       } else {
6557         // This is an out-of-bounds access and hence UB. Pretend we read zero.
6558         SubSlice.Array = nullptr;
6559         SubSlice.Offset = 0;
6560         SubSlice.Length = VTSize;
6561       }
6562       Value = getMemsetStringVal(VT, dl, DAG, TLI, SubSlice);
6563       if (Value.getNode()) {
6564         Store = DAG.getStore(
6565             Chain, dl, Value,
6566             DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl),
6567             DstPtrInfo.getWithOffset(DstOff), Alignment, MMOFlags, NewAAInfo);
6568         OutChains.push_back(Store);
6569       }
6570     }
6571 
6572     if (!Store.getNode()) {
6573       // The type might not be legal for the target.  This should only happen
6574       // if the type is smaller than a legal type, as on PPC, so the right
6575       // thing to do is generate a LoadExt/StoreTrunc pair.  These simplify
6576       // to Load/Store if NVT==VT.
6577       // FIXME does the case above also need this?
6578       EVT NVT = TLI.getTypeToTransformTo(C, VT);
6579       assert(NVT.bitsGE(VT));
6580 
6581       bool isDereferenceable =
6582         SrcPtrInfo.getWithOffset(SrcOff).isDereferenceable(VTSize, C, DL);
6583       MachineMemOperand::Flags SrcMMOFlags = MMOFlags;
6584       if (isDereferenceable)
6585         SrcMMOFlags |= MachineMemOperand::MODereferenceable;
6586 
6587       Value = DAG.getExtLoad(
6588           ISD::EXTLOAD, dl, NVT, Chain,
6589           DAG.getMemBasePlusOffset(Src, TypeSize::Fixed(SrcOff), dl),
6590           SrcPtrInfo.getWithOffset(SrcOff), VT,
6591           commonAlignment(*SrcAlign, SrcOff), SrcMMOFlags, NewAAInfo);
6592       OutLoadChains.push_back(Value.getValue(1));
6593 
6594       Store = DAG.getTruncStore(
6595           Chain, dl, Value,
6596           DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl),
6597           DstPtrInfo.getWithOffset(DstOff), VT, Alignment, MMOFlags, NewAAInfo);
6598       OutStoreChains.push_back(Store);
6599     }
6600     SrcOff += VTSize;
6601     DstOff += VTSize;
6602     Size -= VTSize;
6603   }
6604 
6605   unsigned GluedLdStLimit = MaxLdStGlue == 0 ?
6606                                 TLI.getMaxGluedStoresPerMemcpy() : MaxLdStGlue;
6607   unsigned NumLdStInMemcpy = OutStoreChains.size();
6608 
6609   if (NumLdStInMemcpy) {
6610     // It may be that memcpy might be converted to memset if it's memcpy
6611     // of constants. In such a case, we won't have loads and stores, but
6612     // just stores. In the absence of loads, there is nothing to gang up.
6613     if ((GluedLdStLimit <= 1) || !EnableMemCpyDAGOpt) {
6614       // If target does not care, just leave as it.
6615       for (unsigned i = 0; i < NumLdStInMemcpy; ++i) {
6616         OutChains.push_back(OutLoadChains[i]);
6617         OutChains.push_back(OutStoreChains[i]);
6618       }
6619     } else {
6620       // Ld/St less than/equal limit set by target.
6621       if (NumLdStInMemcpy <= GluedLdStLimit) {
6622           chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, 0,
6623                                         NumLdStInMemcpy, OutLoadChains,
6624                                         OutStoreChains);
6625       } else {
6626         unsigned NumberLdChain =  NumLdStInMemcpy / GluedLdStLimit;
6627         unsigned RemainingLdStInMemcpy = NumLdStInMemcpy % GluedLdStLimit;
6628         unsigned GlueIter = 0;
6629 
6630         for (unsigned cnt = 0; cnt < NumberLdChain; ++cnt) {
6631           unsigned IndexFrom = NumLdStInMemcpy - GlueIter - GluedLdStLimit;
6632           unsigned IndexTo   = NumLdStInMemcpy - GlueIter;
6633 
6634           chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, IndexFrom, IndexTo,
6635                                        OutLoadChains, OutStoreChains);
6636           GlueIter += GluedLdStLimit;
6637         }
6638 
6639         // Residual ld/st.
6640         if (RemainingLdStInMemcpy) {
6641           chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, 0,
6642                                         RemainingLdStInMemcpy, OutLoadChains,
6643                                         OutStoreChains);
6644         }
6645       }
6646     }
6647   }
6648   return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
6649 }
6650 
6651 static SDValue getMemmoveLoadsAndStores(SelectionDAG &DAG, const SDLoc &dl,
6652                                         SDValue Chain, SDValue Dst, SDValue Src,
6653                                         uint64_t Size, Align Alignment,
6654                                         bool isVol, bool AlwaysInline,
6655                                         MachinePointerInfo DstPtrInfo,
6656                                         MachinePointerInfo SrcPtrInfo,
6657                                         const AAMDNodes &AAInfo) {
6658   // Turn a memmove of undef to nop.
6659   // FIXME: We need to honor volatile even is Src is undef.
6660   if (Src.isUndef())
6661     return Chain;
6662 
6663   // Expand memmove to a series of load and store ops if the size operand falls
6664   // below a certain threshold.
6665   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6666   const DataLayout &DL = DAG.getDataLayout();
6667   LLVMContext &C = *DAG.getContext();
6668   std::vector<EVT> MemOps;
6669   bool DstAlignCanChange = false;
6670   MachineFunction &MF = DAG.getMachineFunction();
6671   MachineFrameInfo &MFI = MF.getFrameInfo();
6672   bool OptSize = shouldLowerMemFuncForSize(MF, DAG);
6673   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
6674   if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
6675     DstAlignCanChange = true;
6676   MaybeAlign SrcAlign = DAG.InferPtrAlign(Src);
6677   if (!SrcAlign || Alignment > *SrcAlign)
6678     SrcAlign = Alignment;
6679   assert(SrcAlign && "SrcAlign must be set");
6680   unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemmove(OptSize);
6681   if (!TLI.findOptimalMemOpLowering(
6682           MemOps, Limit,
6683           MemOp::Copy(Size, DstAlignCanChange, Alignment, *SrcAlign,
6684                       /*IsVolatile*/ true),
6685           DstPtrInfo.getAddrSpace(), SrcPtrInfo.getAddrSpace(),
6686           MF.getFunction().getAttributes()))
6687     return SDValue();
6688 
6689   if (DstAlignCanChange) {
6690     Type *Ty = MemOps[0].getTypeForEVT(C);
6691     Align NewAlign = DL.getABITypeAlign(Ty);
6692     if (NewAlign > Alignment) {
6693       // Give the stack frame object a larger alignment if needed.
6694       if (MFI.getObjectAlign(FI->getIndex()) < NewAlign)
6695         MFI.setObjectAlignment(FI->getIndex(), NewAlign);
6696       Alignment = NewAlign;
6697     }
6698   }
6699 
6700   // Prepare AAInfo for loads/stores after lowering this memmove.
6701   AAMDNodes NewAAInfo = AAInfo;
6702   NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr;
6703 
6704   MachineMemOperand::Flags MMOFlags =
6705       isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone;
6706   uint64_t SrcOff = 0, DstOff = 0;
6707   SmallVector<SDValue, 8> LoadValues;
6708   SmallVector<SDValue, 8> LoadChains;
6709   SmallVector<SDValue, 8> OutChains;
6710   unsigned NumMemOps = MemOps.size();
6711   for (unsigned i = 0; i < NumMemOps; i++) {
6712     EVT VT = MemOps[i];
6713     unsigned VTSize = VT.getSizeInBits() / 8;
6714     SDValue Value;
6715 
6716     bool isDereferenceable =
6717       SrcPtrInfo.getWithOffset(SrcOff).isDereferenceable(VTSize, C, DL);
6718     MachineMemOperand::Flags SrcMMOFlags = MMOFlags;
6719     if (isDereferenceable)
6720       SrcMMOFlags |= MachineMemOperand::MODereferenceable;
6721 
6722     Value = DAG.getLoad(
6723         VT, dl, Chain,
6724         DAG.getMemBasePlusOffset(Src, TypeSize::Fixed(SrcOff), dl),
6725         SrcPtrInfo.getWithOffset(SrcOff), *SrcAlign, SrcMMOFlags, NewAAInfo);
6726     LoadValues.push_back(Value);
6727     LoadChains.push_back(Value.getValue(1));
6728     SrcOff += VTSize;
6729   }
6730   Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
6731   OutChains.clear();
6732   for (unsigned i = 0; i < NumMemOps; i++) {
6733     EVT VT = MemOps[i];
6734     unsigned VTSize = VT.getSizeInBits() / 8;
6735     SDValue Store;
6736 
6737     Store = DAG.getStore(
6738         Chain, dl, LoadValues[i],
6739         DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl),
6740         DstPtrInfo.getWithOffset(DstOff), Alignment, MMOFlags, NewAAInfo);
6741     OutChains.push_back(Store);
6742     DstOff += VTSize;
6743   }
6744 
6745   return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
6746 }
6747 
6748 /// Lower the call to 'memset' intrinsic function into a series of store
6749 /// operations.
6750 ///
6751 /// \param DAG Selection DAG where lowered code is placed.
6752 /// \param dl Link to corresponding IR location.
6753 /// \param Chain Control flow dependency.
6754 /// \param Dst Pointer to destination memory location.
6755 /// \param Src Value of byte to write into the memory.
6756 /// \param Size Number of bytes to write.
6757 /// \param Alignment Alignment of the destination in bytes.
6758 /// \param isVol True if destination is volatile.
6759 /// \param DstPtrInfo IR information on the memory pointer.
6760 /// \returns New head in the control flow, if lowering was successful, empty
6761 /// SDValue otherwise.
6762 ///
6763 /// The function tries to replace 'llvm.memset' intrinsic with several store
6764 /// operations and value calculation code. This is usually profitable for small
6765 /// memory size.
6766 static SDValue getMemsetStores(SelectionDAG &DAG, const SDLoc &dl,
6767                                SDValue Chain, SDValue Dst, SDValue Src,
6768                                uint64_t Size, Align Alignment, bool isVol,
6769                                MachinePointerInfo DstPtrInfo,
6770                                const AAMDNodes &AAInfo) {
6771   // Turn a memset of undef to nop.
6772   // FIXME: We need to honor volatile even is Src is undef.
6773   if (Src.isUndef())
6774     return Chain;
6775 
6776   // Expand memset to a series of load/store ops if the size operand
6777   // falls below a certain threshold.
6778   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6779   std::vector<EVT> MemOps;
6780   bool DstAlignCanChange = false;
6781   MachineFunction &MF = DAG.getMachineFunction();
6782   MachineFrameInfo &MFI = MF.getFrameInfo();
6783   bool OptSize = shouldLowerMemFuncForSize(MF, DAG);
6784   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
6785   if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
6786     DstAlignCanChange = true;
6787   bool IsZeroVal =
6788       isa<ConstantSDNode>(Src) && cast<ConstantSDNode>(Src)->isZero();
6789   if (!TLI.findOptimalMemOpLowering(
6790           MemOps, TLI.getMaxStoresPerMemset(OptSize),
6791           MemOp::Set(Size, DstAlignCanChange, Alignment, IsZeroVal, isVol),
6792           DstPtrInfo.getAddrSpace(), ~0u, MF.getFunction().getAttributes()))
6793     return SDValue();
6794 
6795   if (DstAlignCanChange) {
6796     Type *Ty = MemOps[0].getTypeForEVT(*DAG.getContext());
6797     Align NewAlign = DAG.getDataLayout().getABITypeAlign(Ty);
6798     if (NewAlign > Alignment) {
6799       // Give the stack frame object a larger alignment if needed.
6800       if (MFI.getObjectAlign(FI->getIndex()) < NewAlign)
6801         MFI.setObjectAlignment(FI->getIndex(), NewAlign);
6802       Alignment = NewAlign;
6803     }
6804   }
6805 
6806   SmallVector<SDValue, 8> OutChains;
6807   uint64_t DstOff = 0;
6808   unsigned NumMemOps = MemOps.size();
6809 
6810   // Find the largest store and generate the bit pattern for it.
6811   EVT LargestVT = MemOps[0];
6812   for (unsigned i = 1; i < NumMemOps; i++)
6813     if (MemOps[i].bitsGT(LargestVT))
6814       LargestVT = MemOps[i];
6815   SDValue MemSetValue = getMemsetValue(Src, LargestVT, DAG, dl);
6816 
6817   // Prepare AAInfo for loads/stores after lowering this memset.
6818   AAMDNodes NewAAInfo = AAInfo;
6819   NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr;
6820 
6821   for (unsigned i = 0; i < NumMemOps; i++) {
6822     EVT VT = MemOps[i];
6823     unsigned VTSize = VT.getSizeInBits() / 8;
6824     if (VTSize > Size) {
6825       // Issuing an unaligned load / store pair  that overlaps with the previous
6826       // pair. Adjust the offset accordingly.
6827       assert(i == NumMemOps-1 && i != 0);
6828       DstOff -= VTSize - Size;
6829     }
6830 
6831     // If this store is smaller than the largest store see whether we can get
6832     // the smaller value for free with a truncate.
6833     SDValue Value = MemSetValue;
6834     if (VT.bitsLT(LargestVT)) {
6835       if (!LargestVT.isVector() && !VT.isVector() &&
6836           TLI.isTruncateFree(LargestVT, VT))
6837         Value = DAG.getNode(ISD::TRUNCATE, dl, VT, MemSetValue);
6838       else
6839         Value = getMemsetValue(Src, VT, DAG, dl);
6840     }
6841     assert(Value.getValueType() == VT && "Value with wrong type.");
6842     SDValue Store = DAG.getStore(
6843         Chain, dl, Value,
6844         DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl),
6845         DstPtrInfo.getWithOffset(DstOff), Alignment,
6846         isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone,
6847         NewAAInfo);
6848     OutChains.push_back(Store);
6849     DstOff += VT.getSizeInBits() / 8;
6850     Size -= VTSize;
6851   }
6852 
6853   return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
6854 }
6855 
6856 static void checkAddrSpaceIsValidForLibcall(const TargetLowering *TLI,
6857                                             unsigned AS) {
6858   // Lowering memcpy / memset / memmove intrinsics to calls is only valid if all
6859   // pointer operands can be losslessly bitcasted to pointers of address space 0
6860   if (AS != 0 && !TLI->getTargetMachine().isNoopAddrSpaceCast(AS, 0)) {
6861     report_fatal_error("cannot lower memory intrinsic in address space " +
6862                        Twine(AS));
6863   }
6864 }
6865 
6866 SDValue SelectionDAG::getMemcpy(SDValue Chain, const SDLoc &dl, SDValue Dst,
6867                                 SDValue Src, SDValue Size, Align Alignment,
6868                                 bool isVol, bool AlwaysInline, bool isTailCall,
6869                                 MachinePointerInfo DstPtrInfo,
6870                                 MachinePointerInfo SrcPtrInfo,
6871                                 const AAMDNodes &AAInfo) {
6872   // Check to see if we should lower the memcpy to loads and stores first.
6873   // For cases within the target-specified limits, this is the best choice.
6874   ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
6875   if (ConstantSize) {
6876     // Memcpy with size zero? Just return the original chain.
6877     if (ConstantSize->isZero())
6878       return Chain;
6879 
6880     SDValue Result = getMemcpyLoadsAndStores(
6881         *this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), Alignment,
6882         isVol, false, DstPtrInfo, SrcPtrInfo, AAInfo);
6883     if (Result.getNode())
6884       return Result;
6885   }
6886 
6887   // Then check to see if we should lower the memcpy with target-specific
6888   // code. If the target chooses to do this, this is the next best.
6889   if (TSI) {
6890     SDValue Result = TSI->EmitTargetCodeForMemcpy(
6891         *this, dl, Chain, Dst, Src, Size, Alignment, isVol, AlwaysInline,
6892         DstPtrInfo, SrcPtrInfo);
6893     if (Result.getNode())
6894       return Result;
6895   }
6896 
6897   // If we really need inline code and the target declined to provide it,
6898   // use a (potentially long) sequence of loads and stores.
6899   if (AlwaysInline) {
6900     assert(ConstantSize && "AlwaysInline requires a constant size!");
6901     return getMemcpyLoadsAndStores(*this, dl, Chain, Dst, Src,
6902                                    ConstantSize->getZExtValue(), Alignment,
6903                                    isVol, true, DstPtrInfo, SrcPtrInfo, AAInfo);
6904   }
6905 
6906   checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace());
6907   checkAddrSpaceIsValidForLibcall(TLI, SrcPtrInfo.getAddrSpace());
6908 
6909   // FIXME: If the memcpy is volatile (isVol), lowering it to a plain libc
6910   // memcpy is not guaranteed to be safe. libc memcpys aren't required to
6911   // respect volatile, so they may do things like read or write memory
6912   // beyond the given memory regions. But fixing this isn't easy, and most
6913   // people don't care.
6914 
6915   // Emit a library call.
6916   TargetLowering::ArgListTy Args;
6917   TargetLowering::ArgListEntry Entry;
6918   Entry.Ty = Type::getInt8PtrTy(*getContext());
6919   Entry.Node = Dst; Args.push_back(Entry);
6920   Entry.Node = Src; Args.push_back(Entry);
6921 
6922   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
6923   Entry.Node = Size; Args.push_back(Entry);
6924   // FIXME: pass in SDLoc
6925   TargetLowering::CallLoweringInfo CLI(*this);
6926   CLI.setDebugLoc(dl)
6927       .setChain(Chain)
6928       .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMCPY),
6929                     Dst.getValueType().getTypeForEVT(*getContext()),
6930                     getExternalSymbol(TLI->getLibcallName(RTLIB::MEMCPY),
6931                                       TLI->getPointerTy(getDataLayout())),
6932                     std::move(Args))
6933       .setDiscardResult()
6934       .setTailCall(isTailCall);
6935 
6936   std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
6937   return CallResult.second;
6938 }
6939 
6940 SDValue SelectionDAG::getAtomicMemcpy(SDValue Chain, const SDLoc &dl,
6941                                       SDValue Dst, unsigned DstAlign,
6942                                       SDValue Src, unsigned SrcAlign,
6943                                       SDValue Size, Type *SizeTy,
6944                                       unsigned ElemSz, bool isTailCall,
6945                                       MachinePointerInfo DstPtrInfo,
6946                                       MachinePointerInfo SrcPtrInfo) {
6947   // Emit a library call.
6948   TargetLowering::ArgListTy Args;
6949   TargetLowering::ArgListEntry Entry;
6950   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
6951   Entry.Node = Dst;
6952   Args.push_back(Entry);
6953 
6954   Entry.Node = Src;
6955   Args.push_back(Entry);
6956 
6957   Entry.Ty = SizeTy;
6958   Entry.Node = Size;
6959   Args.push_back(Entry);
6960 
6961   RTLIB::Libcall LibraryCall =
6962       RTLIB::getMEMCPY_ELEMENT_UNORDERED_ATOMIC(ElemSz);
6963   if (LibraryCall == RTLIB::UNKNOWN_LIBCALL)
6964     report_fatal_error("Unsupported element size");
6965 
6966   TargetLowering::CallLoweringInfo CLI(*this);
6967   CLI.setDebugLoc(dl)
6968       .setChain(Chain)
6969       .setLibCallee(TLI->getLibcallCallingConv(LibraryCall),
6970                     Type::getVoidTy(*getContext()),
6971                     getExternalSymbol(TLI->getLibcallName(LibraryCall),
6972                                       TLI->getPointerTy(getDataLayout())),
6973                     std::move(Args))
6974       .setDiscardResult()
6975       .setTailCall(isTailCall);
6976 
6977   std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
6978   return CallResult.second;
6979 }
6980 
6981 SDValue SelectionDAG::getMemmove(SDValue Chain, const SDLoc &dl, SDValue Dst,
6982                                  SDValue Src, SDValue Size, Align Alignment,
6983                                  bool isVol, bool isTailCall,
6984                                  MachinePointerInfo DstPtrInfo,
6985                                  MachinePointerInfo SrcPtrInfo,
6986                                  const AAMDNodes &AAInfo) {
6987   // Check to see if we should lower the memmove to loads and stores first.
6988   // For cases within the target-specified limits, this is the best choice.
6989   ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
6990   if (ConstantSize) {
6991     // Memmove with size zero? Just return the original chain.
6992     if (ConstantSize->isZero())
6993       return Chain;
6994 
6995     SDValue Result = getMemmoveLoadsAndStores(
6996         *this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), Alignment,
6997         isVol, false, DstPtrInfo, SrcPtrInfo, AAInfo);
6998     if (Result.getNode())
6999       return Result;
7000   }
7001 
7002   // Then check to see if we should lower the memmove with target-specific
7003   // code. If the target chooses to do this, this is the next best.
7004   if (TSI) {
7005     SDValue Result =
7006         TSI->EmitTargetCodeForMemmove(*this, dl, Chain, Dst, Src, Size,
7007                                       Alignment, isVol, DstPtrInfo, SrcPtrInfo);
7008     if (Result.getNode())
7009       return Result;
7010   }
7011 
7012   checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace());
7013   checkAddrSpaceIsValidForLibcall(TLI, SrcPtrInfo.getAddrSpace());
7014 
7015   // FIXME: If the memmove is volatile, lowering it to plain libc memmove may
7016   // not be safe.  See memcpy above for more details.
7017 
7018   // Emit a library call.
7019   TargetLowering::ArgListTy Args;
7020   TargetLowering::ArgListEntry Entry;
7021   Entry.Ty = Type::getInt8PtrTy(*getContext());
7022   Entry.Node = Dst; Args.push_back(Entry);
7023   Entry.Node = Src; Args.push_back(Entry);
7024 
7025   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
7026   Entry.Node = Size; Args.push_back(Entry);
7027   // FIXME:  pass in SDLoc
7028   TargetLowering::CallLoweringInfo CLI(*this);
7029   CLI.setDebugLoc(dl)
7030       .setChain(Chain)
7031       .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMMOVE),
7032                     Dst.getValueType().getTypeForEVT(*getContext()),
7033                     getExternalSymbol(TLI->getLibcallName(RTLIB::MEMMOVE),
7034                                       TLI->getPointerTy(getDataLayout())),
7035                     std::move(Args))
7036       .setDiscardResult()
7037       .setTailCall(isTailCall);
7038 
7039   std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
7040   return CallResult.second;
7041 }
7042 
7043 SDValue SelectionDAG::getAtomicMemmove(SDValue Chain, const SDLoc &dl,
7044                                        SDValue Dst, unsigned DstAlign,
7045                                        SDValue Src, unsigned SrcAlign,
7046                                        SDValue Size, Type *SizeTy,
7047                                        unsigned ElemSz, bool isTailCall,
7048                                        MachinePointerInfo DstPtrInfo,
7049                                        MachinePointerInfo SrcPtrInfo) {
7050   // Emit a library call.
7051   TargetLowering::ArgListTy Args;
7052   TargetLowering::ArgListEntry Entry;
7053   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
7054   Entry.Node = Dst;
7055   Args.push_back(Entry);
7056 
7057   Entry.Node = Src;
7058   Args.push_back(Entry);
7059 
7060   Entry.Ty = SizeTy;
7061   Entry.Node = Size;
7062   Args.push_back(Entry);
7063 
7064   RTLIB::Libcall LibraryCall =
7065       RTLIB::getMEMMOVE_ELEMENT_UNORDERED_ATOMIC(ElemSz);
7066   if (LibraryCall == RTLIB::UNKNOWN_LIBCALL)
7067     report_fatal_error("Unsupported element size");
7068 
7069   TargetLowering::CallLoweringInfo CLI(*this);
7070   CLI.setDebugLoc(dl)
7071       .setChain(Chain)
7072       .setLibCallee(TLI->getLibcallCallingConv(LibraryCall),
7073                     Type::getVoidTy(*getContext()),
7074                     getExternalSymbol(TLI->getLibcallName(LibraryCall),
7075                                       TLI->getPointerTy(getDataLayout())),
7076                     std::move(Args))
7077       .setDiscardResult()
7078       .setTailCall(isTailCall);
7079 
7080   std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
7081   return CallResult.second;
7082 }
7083 
7084 SDValue SelectionDAG::getMemset(SDValue Chain, const SDLoc &dl, SDValue Dst,
7085                                 SDValue Src, SDValue Size, Align Alignment,
7086                                 bool isVol, bool isTailCall,
7087                                 MachinePointerInfo DstPtrInfo,
7088                                 const AAMDNodes &AAInfo) {
7089   // Check to see if we should lower the memset to stores first.
7090   // For cases within the target-specified limits, this is the best choice.
7091   ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
7092   if (ConstantSize) {
7093     // Memset with size zero? Just return the original chain.
7094     if (ConstantSize->isZero())
7095       return Chain;
7096 
7097     SDValue Result = getMemsetStores(*this, dl, Chain, Dst, Src,
7098                                      ConstantSize->getZExtValue(), Alignment,
7099                                      isVol, DstPtrInfo, AAInfo);
7100 
7101     if (Result.getNode())
7102       return Result;
7103   }
7104 
7105   // Then check to see if we should lower the memset with target-specific
7106   // code. If the target chooses to do this, this is the next best.
7107   if (TSI) {
7108     SDValue Result = TSI->EmitTargetCodeForMemset(
7109         *this, dl, Chain, Dst, Src, Size, Alignment, isVol, DstPtrInfo);
7110     if (Result.getNode())
7111       return Result;
7112   }
7113 
7114   checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace());
7115 
7116   // Emit a library call.
7117   TargetLowering::ArgListTy Args;
7118   TargetLowering::ArgListEntry Entry;
7119   Entry.Node = Dst; Entry.Ty = Type::getInt8PtrTy(*getContext());
7120   Args.push_back(Entry);
7121   Entry.Node = Src;
7122   Entry.Ty = Src.getValueType().getTypeForEVT(*getContext());
7123   Args.push_back(Entry);
7124   Entry.Node = Size;
7125   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
7126   Args.push_back(Entry);
7127 
7128   // FIXME: pass in SDLoc
7129   TargetLowering::CallLoweringInfo CLI(*this);
7130   CLI.setDebugLoc(dl)
7131       .setChain(Chain)
7132       .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMSET),
7133                     Dst.getValueType().getTypeForEVT(*getContext()),
7134                     getExternalSymbol(TLI->getLibcallName(RTLIB::MEMSET),
7135                                       TLI->getPointerTy(getDataLayout())),
7136                     std::move(Args))
7137       .setDiscardResult()
7138       .setTailCall(isTailCall);
7139 
7140   std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
7141   return CallResult.second;
7142 }
7143 
7144 SDValue SelectionDAG::getAtomicMemset(SDValue Chain, const SDLoc &dl,
7145                                       SDValue Dst, unsigned DstAlign,
7146                                       SDValue Value, SDValue Size, Type *SizeTy,
7147                                       unsigned ElemSz, bool isTailCall,
7148                                       MachinePointerInfo DstPtrInfo) {
7149   // Emit a library call.
7150   TargetLowering::ArgListTy Args;
7151   TargetLowering::ArgListEntry Entry;
7152   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
7153   Entry.Node = Dst;
7154   Args.push_back(Entry);
7155 
7156   Entry.Ty = Type::getInt8Ty(*getContext());
7157   Entry.Node = Value;
7158   Args.push_back(Entry);
7159 
7160   Entry.Ty = SizeTy;
7161   Entry.Node = Size;
7162   Args.push_back(Entry);
7163 
7164   RTLIB::Libcall LibraryCall =
7165       RTLIB::getMEMSET_ELEMENT_UNORDERED_ATOMIC(ElemSz);
7166   if (LibraryCall == RTLIB::UNKNOWN_LIBCALL)
7167     report_fatal_error("Unsupported element size");
7168 
7169   TargetLowering::CallLoweringInfo CLI(*this);
7170   CLI.setDebugLoc(dl)
7171       .setChain(Chain)
7172       .setLibCallee(TLI->getLibcallCallingConv(LibraryCall),
7173                     Type::getVoidTy(*getContext()),
7174                     getExternalSymbol(TLI->getLibcallName(LibraryCall),
7175                                       TLI->getPointerTy(getDataLayout())),
7176                     std::move(Args))
7177       .setDiscardResult()
7178       .setTailCall(isTailCall);
7179 
7180   std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
7181   return CallResult.second;
7182 }
7183 
7184 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
7185                                 SDVTList VTList, ArrayRef<SDValue> Ops,
7186                                 MachineMemOperand *MMO) {
7187   FoldingSetNodeID ID;
7188   ID.AddInteger(MemVT.getRawBits());
7189   AddNodeIDNode(ID, Opcode, VTList, Ops);
7190   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7191   void* IP = nullptr;
7192   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7193     cast<AtomicSDNode>(E)->refineAlignment(MMO);
7194     return SDValue(E, 0);
7195   }
7196 
7197   auto *N = newSDNode<AtomicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
7198                                     VTList, MemVT, MMO);
7199   createOperands(N, Ops);
7200 
7201   CSEMap.InsertNode(N, IP);
7202   InsertNode(N);
7203   return SDValue(N, 0);
7204 }
7205 
7206 SDValue SelectionDAG::getAtomicCmpSwap(unsigned Opcode, const SDLoc &dl,
7207                                        EVT MemVT, SDVTList VTs, SDValue Chain,
7208                                        SDValue Ptr, SDValue Cmp, SDValue Swp,
7209                                        MachineMemOperand *MMO) {
7210   assert(Opcode == ISD::ATOMIC_CMP_SWAP ||
7211          Opcode == ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS);
7212   assert(Cmp.getValueType() == Swp.getValueType() && "Invalid Atomic Op Types");
7213 
7214   SDValue Ops[] = {Chain, Ptr, Cmp, Swp};
7215   return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
7216 }
7217 
7218 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
7219                                 SDValue Chain, SDValue Ptr, SDValue Val,
7220                                 MachineMemOperand *MMO) {
7221   assert((Opcode == ISD::ATOMIC_LOAD_ADD ||
7222           Opcode == ISD::ATOMIC_LOAD_SUB ||
7223           Opcode == ISD::ATOMIC_LOAD_AND ||
7224           Opcode == ISD::ATOMIC_LOAD_CLR ||
7225           Opcode == ISD::ATOMIC_LOAD_OR ||
7226           Opcode == ISD::ATOMIC_LOAD_XOR ||
7227           Opcode == ISD::ATOMIC_LOAD_NAND ||
7228           Opcode == ISD::ATOMIC_LOAD_MIN ||
7229           Opcode == ISD::ATOMIC_LOAD_MAX ||
7230           Opcode == ISD::ATOMIC_LOAD_UMIN ||
7231           Opcode == ISD::ATOMIC_LOAD_UMAX ||
7232           Opcode == ISD::ATOMIC_LOAD_FADD ||
7233           Opcode == ISD::ATOMIC_LOAD_FSUB ||
7234           Opcode == ISD::ATOMIC_SWAP ||
7235           Opcode == ISD::ATOMIC_STORE) &&
7236          "Invalid Atomic Op");
7237 
7238   EVT VT = Val.getValueType();
7239 
7240   SDVTList VTs = Opcode == ISD::ATOMIC_STORE ? getVTList(MVT::Other) :
7241                                                getVTList(VT, MVT::Other);
7242   SDValue Ops[] = {Chain, Ptr, Val};
7243   return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
7244 }
7245 
7246 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
7247                                 EVT VT, SDValue Chain, SDValue Ptr,
7248                                 MachineMemOperand *MMO) {
7249   assert(Opcode == ISD::ATOMIC_LOAD && "Invalid Atomic Op");
7250 
7251   SDVTList VTs = getVTList(VT, MVT::Other);
7252   SDValue Ops[] = {Chain, Ptr};
7253   return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
7254 }
7255 
7256 /// getMergeValues - Create a MERGE_VALUES node from the given operands.
7257 SDValue SelectionDAG::getMergeValues(ArrayRef<SDValue> Ops, const SDLoc &dl) {
7258   if (Ops.size() == 1)
7259     return Ops[0];
7260 
7261   SmallVector<EVT, 4> VTs;
7262   VTs.reserve(Ops.size());
7263   for (const SDValue &Op : Ops)
7264     VTs.push_back(Op.getValueType());
7265   return getNode(ISD::MERGE_VALUES, dl, getVTList(VTs), Ops);
7266 }
7267 
7268 SDValue SelectionDAG::getMemIntrinsicNode(
7269     unsigned Opcode, const SDLoc &dl, SDVTList VTList, ArrayRef<SDValue> Ops,
7270     EVT MemVT, MachinePointerInfo PtrInfo, Align Alignment,
7271     MachineMemOperand::Flags Flags, uint64_t Size, const AAMDNodes &AAInfo) {
7272   if (!Size && MemVT.isScalableVector())
7273     Size = MemoryLocation::UnknownSize;
7274   else if (!Size)
7275     Size = MemVT.getStoreSize();
7276 
7277   MachineFunction &MF = getMachineFunction();
7278   MachineMemOperand *MMO =
7279       MF.getMachineMemOperand(PtrInfo, Flags, Size, Alignment, AAInfo);
7280 
7281   return getMemIntrinsicNode(Opcode, dl, VTList, Ops, MemVT, MMO);
7282 }
7283 
7284 SDValue SelectionDAG::getMemIntrinsicNode(unsigned Opcode, const SDLoc &dl,
7285                                           SDVTList VTList,
7286                                           ArrayRef<SDValue> Ops, EVT MemVT,
7287                                           MachineMemOperand *MMO) {
7288   assert((Opcode == ISD::INTRINSIC_VOID ||
7289           Opcode == ISD::INTRINSIC_W_CHAIN ||
7290           Opcode == ISD::PREFETCH ||
7291           ((int)Opcode <= std::numeric_limits<int>::max() &&
7292            (int)Opcode >= ISD::FIRST_TARGET_MEMORY_OPCODE)) &&
7293          "Opcode is not a memory-accessing opcode!");
7294 
7295   // Memoize the node unless it returns a flag.
7296   MemIntrinsicSDNode *N;
7297   if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) {
7298     FoldingSetNodeID ID;
7299     AddNodeIDNode(ID, Opcode, VTList, Ops);
7300     ID.AddInteger(getSyntheticNodeSubclassData<MemIntrinsicSDNode>(
7301         Opcode, dl.getIROrder(), VTList, MemVT, MMO));
7302     ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7303     void *IP = nullptr;
7304     if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7305       cast<MemIntrinsicSDNode>(E)->refineAlignment(MMO);
7306       return SDValue(E, 0);
7307     }
7308 
7309     N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
7310                                       VTList, MemVT, MMO);
7311     createOperands(N, Ops);
7312 
7313   CSEMap.InsertNode(N, IP);
7314   } else {
7315     N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
7316                                       VTList, MemVT, MMO);
7317     createOperands(N, Ops);
7318   }
7319   InsertNode(N);
7320   SDValue V(N, 0);
7321   NewSDValueDbgMsg(V, "Creating new node: ", this);
7322   return V;
7323 }
7324 
7325 SDValue SelectionDAG::getLifetimeNode(bool IsStart, const SDLoc &dl,
7326                                       SDValue Chain, int FrameIndex,
7327                                       int64_t Size, int64_t Offset) {
7328   const unsigned Opcode = IsStart ? ISD::LIFETIME_START : ISD::LIFETIME_END;
7329   const auto VTs = getVTList(MVT::Other);
7330   SDValue Ops[2] = {
7331       Chain,
7332       getFrameIndex(FrameIndex,
7333                     getTargetLoweringInfo().getFrameIndexTy(getDataLayout()),
7334                     true)};
7335 
7336   FoldingSetNodeID ID;
7337   AddNodeIDNode(ID, Opcode, VTs, Ops);
7338   ID.AddInteger(FrameIndex);
7339   ID.AddInteger(Size);
7340   ID.AddInteger(Offset);
7341   void *IP = nullptr;
7342   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
7343     return SDValue(E, 0);
7344 
7345   LifetimeSDNode *N = newSDNode<LifetimeSDNode>(
7346       Opcode, dl.getIROrder(), dl.getDebugLoc(), VTs, Size, Offset);
7347   createOperands(N, Ops);
7348   CSEMap.InsertNode(N, IP);
7349   InsertNode(N);
7350   SDValue V(N, 0);
7351   NewSDValueDbgMsg(V, "Creating new node: ", this);
7352   return V;
7353 }
7354 
7355 SDValue SelectionDAG::getPseudoProbeNode(const SDLoc &Dl, SDValue Chain,
7356                                          uint64_t Guid, uint64_t Index,
7357                                          uint32_t Attr) {
7358   const unsigned Opcode = ISD::PSEUDO_PROBE;
7359   const auto VTs = getVTList(MVT::Other);
7360   SDValue Ops[] = {Chain};
7361   FoldingSetNodeID ID;
7362   AddNodeIDNode(ID, Opcode, VTs, Ops);
7363   ID.AddInteger(Guid);
7364   ID.AddInteger(Index);
7365   void *IP = nullptr;
7366   if (SDNode *E = FindNodeOrInsertPos(ID, Dl, IP))
7367     return SDValue(E, 0);
7368 
7369   auto *N = newSDNode<PseudoProbeSDNode>(
7370       Opcode, Dl.getIROrder(), Dl.getDebugLoc(), VTs, Guid, Index, Attr);
7371   createOperands(N, Ops);
7372   CSEMap.InsertNode(N, IP);
7373   InsertNode(N);
7374   SDValue V(N, 0);
7375   NewSDValueDbgMsg(V, "Creating new node: ", this);
7376   return V;
7377 }
7378 
7379 /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a
7380 /// MachinePointerInfo record from it.  This is particularly useful because the
7381 /// code generator has many cases where it doesn't bother passing in a
7382 /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst".
7383 static MachinePointerInfo InferPointerInfo(const MachinePointerInfo &Info,
7384                                            SelectionDAG &DAG, SDValue Ptr,
7385                                            int64_t Offset = 0) {
7386   // If this is FI+Offset, we can model it.
7387   if (const FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr))
7388     return MachinePointerInfo::getFixedStack(DAG.getMachineFunction(),
7389                                              FI->getIndex(), Offset);
7390 
7391   // If this is (FI+Offset1)+Offset2, we can model it.
7392   if (Ptr.getOpcode() != ISD::ADD ||
7393       !isa<ConstantSDNode>(Ptr.getOperand(1)) ||
7394       !isa<FrameIndexSDNode>(Ptr.getOperand(0)))
7395     return Info;
7396 
7397   int FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
7398   return MachinePointerInfo::getFixedStack(
7399       DAG.getMachineFunction(), FI,
7400       Offset + cast<ConstantSDNode>(Ptr.getOperand(1))->getSExtValue());
7401 }
7402 
7403 /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a
7404 /// MachinePointerInfo record from it.  This is particularly useful because the
7405 /// code generator has many cases where it doesn't bother passing in a
7406 /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst".
7407 static MachinePointerInfo InferPointerInfo(const MachinePointerInfo &Info,
7408                                            SelectionDAG &DAG, SDValue Ptr,
7409                                            SDValue OffsetOp) {
7410   // If the 'Offset' value isn't a constant, we can't handle this.
7411   if (ConstantSDNode *OffsetNode = dyn_cast<ConstantSDNode>(OffsetOp))
7412     return InferPointerInfo(Info, DAG, Ptr, OffsetNode->getSExtValue());
7413   if (OffsetOp.isUndef())
7414     return InferPointerInfo(Info, DAG, Ptr);
7415   return Info;
7416 }
7417 
7418 SDValue SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType,
7419                               EVT VT, const SDLoc &dl, SDValue Chain,
7420                               SDValue Ptr, SDValue Offset,
7421                               MachinePointerInfo PtrInfo, EVT MemVT,
7422                               Align Alignment,
7423                               MachineMemOperand::Flags MMOFlags,
7424                               const AAMDNodes &AAInfo, const MDNode *Ranges) {
7425   assert(Chain.getValueType() == MVT::Other &&
7426         "Invalid chain type");
7427 
7428   MMOFlags |= MachineMemOperand::MOLoad;
7429   assert((MMOFlags & MachineMemOperand::MOStore) == 0);
7430   // If we don't have a PtrInfo, infer the trivial frame index case to simplify
7431   // clients.
7432   if (PtrInfo.V.isNull())
7433     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr, Offset);
7434 
7435   uint64_t Size = MemoryLocation::getSizeOrUnknown(MemVT.getStoreSize());
7436   MachineFunction &MF = getMachineFunction();
7437   MachineMemOperand *MMO = MF.getMachineMemOperand(PtrInfo, MMOFlags, Size,
7438                                                    Alignment, AAInfo, Ranges);
7439   return getLoad(AM, ExtType, VT, dl, Chain, Ptr, Offset, MemVT, MMO);
7440 }
7441 
7442 SDValue SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType,
7443                               EVT VT, const SDLoc &dl, SDValue Chain,
7444                               SDValue Ptr, SDValue Offset, EVT MemVT,
7445                               MachineMemOperand *MMO) {
7446   if (VT == MemVT) {
7447     ExtType = ISD::NON_EXTLOAD;
7448   } else if (ExtType == ISD::NON_EXTLOAD) {
7449     assert(VT == MemVT && "Non-extending load from different memory type!");
7450   } else {
7451     // Extending load.
7452     assert(MemVT.getScalarType().bitsLT(VT.getScalarType()) &&
7453            "Should only be an extending load, not truncating!");
7454     assert(VT.isInteger() == MemVT.isInteger() &&
7455            "Cannot convert from FP to Int or Int -> FP!");
7456     assert(VT.isVector() == MemVT.isVector() &&
7457            "Cannot use an ext load to convert to or from a vector!");
7458     assert((!VT.isVector() ||
7459             VT.getVectorElementCount() == MemVT.getVectorElementCount()) &&
7460            "Cannot use an ext load to change the number of vector elements!");
7461   }
7462 
7463   bool Indexed = AM != ISD::UNINDEXED;
7464   assert((Indexed || Offset.isUndef()) && "Unindexed load with an offset!");
7465 
7466   SDVTList VTs = Indexed ?
7467     getVTList(VT, Ptr.getValueType(), MVT::Other) : getVTList(VT, MVT::Other);
7468   SDValue Ops[] = { Chain, Ptr, Offset };
7469   FoldingSetNodeID ID;
7470   AddNodeIDNode(ID, ISD::LOAD, VTs, Ops);
7471   ID.AddInteger(MemVT.getRawBits());
7472   ID.AddInteger(getSyntheticNodeSubclassData<LoadSDNode>(
7473       dl.getIROrder(), VTs, AM, ExtType, MemVT, MMO));
7474   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7475   void *IP = nullptr;
7476   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7477     cast<LoadSDNode>(E)->refineAlignment(MMO);
7478     return SDValue(E, 0);
7479   }
7480   auto *N = newSDNode<LoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
7481                                   ExtType, MemVT, MMO);
7482   createOperands(N, Ops);
7483 
7484   CSEMap.InsertNode(N, IP);
7485   InsertNode(N);
7486   SDValue V(N, 0);
7487   NewSDValueDbgMsg(V, "Creating new node: ", this);
7488   return V;
7489 }
7490 
7491 SDValue SelectionDAG::getLoad(EVT VT, const SDLoc &dl, SDValue Chain,
7492                               SDValue Ptr, MachinePointerInfo PtrInfo,
7493                               MaybeAlign Alignment,
7494                               MachineMemOperand::Flags MMOFlags,
7495                               const AAMDNodes &AAInfo, const MDNode *Ranges) {
7496   SDValue Undef = getUNDEF(Ptr.getValueType());
7497   return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
7498                  PtrInfo, VT, Alignment, MMOFlags, AAInfo, Ranges);
7499 }
7500 
7501 SDValue SelectionDAG::getLoad(EVT VT, const SDLoc &dl, SDValue Chain,
7502                               SDValue Ptr, MachineMemOperand *MMO) {
7503   SDValue Undef = getUNDEF(Ptr.getValueType());
7504   return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
7505                  VT, MMO);
7506 }
7507 
7508 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl,
7509                                  EVT VT, SDValue Chain, SDValue Ptr,
7510                                  MachinePointerInfo PtrInfo, EVT MemVT,
7511                                  MaybeAlign Alignment,
7512                                  MachineMemOperand::Flags MMOFlags,
7513                                  const AAMDNodes &AAInfo) {
7514   SDValue Undef = getUNDEF(Ptr.getValueType());
7515   return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, PtrInfo,
7516                  MemVT, Alignment, MMOFlags, AAInfo);
7517 }
7518 
7519 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl,
7520                                  EVT VT, SDValue Chain, SDValue Ptr, EVT MemVT,
7521                                  MachineMemOperand *MMO) {
7522   SDValue Undef = getUNDEF(Ptr.getValueType());
7523   return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef,
7524                  MemVT, MMO);
7525 }
7526 
7527 SDValue SelectionDAG::getIndexedLoad(SDValue OrigLoad, const SDLoc &dl,
7528                                      SDValue Base, SDValue Offset,
7529                                      ISD::MemIndexedMode AM) {
7530   LoadSDNode *LD = cast<LoadSDNode>(OrigLoad);
7531   assert(LD->getOffset().isUndef() && "Load is already a indexed load!");
7532   // Don't propagate the invariant or dereferenceable flags.
7533   auto MMOFlags =
7534       LD->getMemOperand()->getFlags() &
7535       ~(MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable);
7536   return getLoad(AM, LD->getExtensionType(), OrigLoad.getValueType(), dl,
7537                  LD->getChain(), Base, Offset, LD->getPointerInfo(),
7538                  LD->getMemoryVT(), LD->getAlign(), MMOFlags, LD->getAAInfo());
7539 }
7540 
7541 SDValue SelectionDAG::getStore(SDValue Chain, const SDLoc &dl, SDValue Val,
7542                                SDValue Ptr, MachinePointerInfo PtrInfo,
7543                                Align Alignment,
7544                                MachineMemOperand::Flags MMOFlags,
7545                                const AAMDNodes &AAInfo) {
7546   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
7547 
7548   MMOFlags |= MachineMemOperand::MOStore;
7549   assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
7550 
7551   if (PtrInfo.V.isNull())
7552     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
7553 
7554   MachineFunction &MF = getMachineFunction();
7555   uint64_t Size =
7556       MemoryLocation::getSizeOrUnknown(Val.getValueType().getStoreSize());
7557   MachineMemOperand *MMO =
7558       MF.getMachineMemOperand(PtrInfo, MMOFlags, Size, Alignment, AAInfo);
7559   return getStore(Chain, dl, Val, Ptr, MMO);
7560 }
7561 
7562 SDValue SelectionDAG::getStore(SDValue Chain, const SDLoc &dl, SDValue Val,
7563                                SDValue Ptr, MachineMemOperand *MMO) {
7564   assert(Chain.getValueType() == MVT::Other &&
7565         "Invalid chain type");
7566   EVT VT = Val.getValueType();
7567   SDVTList VTs = getVTList(MVT::Other);
7568   SDValue Undef = getUNDEF(Ptr.getValueType());
7569   SDValue Ops[] = { Chain, Val, Ptr, Undef };
7570   FoldingSetNodeID ID;
7571   AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
7572   ID.AddInteger(VT.getRawBits());
7573   ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>(
7574       dl.getIROrder(), VTs, ISD::UNINDEXED, false, VT, MMO));
7575   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7576   void *IP = nullptr;
7577   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7578     cast<StoreSDNode>(E)->refineAlignment(MMO);
7579     return SDValue(E, 0);
7580   }
7581   auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
7582                                    ISD::UNINDEXED, false, VT, MMO);
7583   createOperands(N, Ops);
7584 
7585   CSEMap.InsertNode(N, IP);
7586   InsertNode(N);
7587   SDValue V(N, 0);
7588   NewSDValueDbgMsg(V, "Creating new node: ", this);
7589   return V;
7590 }
7591 
7592 SDValue SelectionDAG::getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val,
7593                                     SDValue Ptr, MachinePointerInfo PtrInfo,
7594                                     EVT SVT, Align Alignment,
7595                                     MachineMemOperand::Flags MMOFlags,
7596                                     const AAMDNodes &AAInfo) {
7597   assert(Chain.getValueType() == MVT::Other &&
7598         "Invalid chain type");
7599 
7600   MMOFlags |= MachineMemOperand::MOStore;
7601   assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
7602 
7603   if (PtrInfo.V.isNull())
7604     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
7605 
7606   MachineFunction &MF = getMachineFunction();
7607   MachineMemOperand *MMO = MF.getMachineMemOperand(
7608       PtrInfo, MMOFlags, MemoryLocation::getSizeOrUnknown(SVT.getStoreSize()),
7609       Alignment, AAInfo);
7610   return getTruncStore(Chain, dl, Val, Ptr, SVT, MMO);
7611 }
7612 
7613 SDValue SelectionDAG::getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val,
7614                                     SDValue Ptr, EVT SVT,
7615                                     MachineMemOperand *MMO) {
7616   EVT VT = Val.getValueType();
7617 
7618   assert(Chain.getValueType() == MVT::Other &&
7619         "Invalid chain type");
7620   if (VT == SVT)
7621     return getStore(Chain, dl, Val, Ptr, MMO);
7622 
7623   assert(SVT.getScalarType().bitsLT(VT.getScalarType()) &&
7624          "Should only be a truncating store, not extending!");
7625   assert(VT.isInteger() == SVT.isInteger() &&
7626          "Can't do FP-INT conversion!");
7627   assert(VT.isVector() == SVT.isVector() &&
7628          "Cannot use trunc store to convert to or from a vector!");
7629   assert((!VT.isVector() ||
7630           VT.getVectorElementCount() == SVT.getVectorElementCount()) &&
7631          "Cannot use trunc store to change the number of vector elements!");
7632 
7633   SDVTList VTs = getVTList(MVT::Other);
7634   SDValue Undef = getUNDEF(Ptr.getValueType());
7635   SDValue Ops[] = { Chain, Val, Ptr, Undef };
7636   FoldingSetNodeID ID;
7637   AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
7638   ID.AddInteger(SVT.getRawBits());
7639   ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>(
7640       dl.getIROrder(), VTs, ISD::UNINDEXED, true, SVT, MMO));
7641   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7642   void *IP = nullptr;
7643   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7644     cast<StoreSDNode>(E)->refineAlignment(MMO);
7645     return SDValue(E, 0);
7646   }
7647   auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
7648                                    ISD::UNINDEXED, true, SVT, MMO);
7649   createOperands(N, Ops);
7650 
7651   CSEMap.InsertNode(N, IP);
7652   InsertNode(N);
7653   SDValue V(N, 0);
7654   NewSDValueDbgMsg(V, "Creating new node: ", this);
7655   return V;
7656 }
7657 
7658 SDValue SelectionDAG::getIndexedStore(SDValue OrigStore, const SDLoc &dl,
7659                                       SDValue Base, SDValue Offset,
7660                                       ISD::MemIndexedMode AM) {
7661   StoreSDNode *ST = cast<StoreSDNode>(OrigStore);
7662   assert(ST->getOffset().isUndef() && "Store is already a indexed store!");
7663   SDVTList VTs = getVTList(Base.getValueType(), MVT::Other);
7664   SDValue Ops[] = { ST->getChain(), ST->getValue(), Base, Offset };
7665   FoldingSetNodeID ID;
7666   AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
7667   ID.AddInteger(ST->getMemoryVT().getRawBits());
7668   ID.AddInteger(ST->getRawSubclassData());
7669   ID.AddInteger(ST->getPointerInfo().getAddrSpace());
7670   void *IP = nullptr;
7671   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
7672     return SDValue(E, 0);
7673 
7674   auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
7675                                    ST->isTruncatingStore(), ST->getMemoryVT(),
7676                                    ST->getMemOperand());
7677   createOperands(N, Ops);
7678 
7679   CSEMap.InsertNode(N, IP);
7680   InsertNode(N);
7681   SDValue V(N, 0);
7682   NewSDValueDbgMsg(V, "Creating new node: ", this);
7683   return V;
7684 }
7685 
7686 SDValue SelectionDAG::getLoadVP(
7687     ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, EVT VT, const SDLoc &dl,
7688     SDValue Chain, SDValue Ptr, SDValue Offset, SDValue Mask, SDValue EVL,
7689     MachinePointerInfo PtrInfo, EVT MemVT, Align Alignment,
7690     MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo,
7691     const MDNode *Ranges, bool IsExpanding) {
7692   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
7693 
7694   MMOFlags |= MachineMemOperand::MOLoad;
7695   assert((MMOFlags & MachineMemOperand::MOStore) == 0);
7696   // If we don't have a PtrInfo, infer the trivial frame index case to simplify
7697   // clients.
7698   if (PtrInfo.V.isNull())
7699     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr, Offset);
7700 
7701   uint64_t Size = MemoryLocation::getSizeOrUnknown(MemVT.getStoreSize());
7702   MachineFunction &MF = getMachineFunction();
7703   MachineMemOperand *MMO = MF.getMachineMemOperand(PtrInfo, MMOFlags, Size,
7704                                                    Alignment, AAInfo, Ranges);
7705   return getLoadVP(AM, ExtType, VT, dl, Chain, Ptr, Offset, Mask, EVL, MemVT,
7706                    MMO, IsExpanding);
7707 }
7708 
7709 SDValue SelectionDAG::getLoadVP(ISD::MemIndexedMode AM,
7710                                 ISD::LoadExtType ExtType, EVT VT,
7711                                 const SDLoc &dl, SDValue Chain, SDValue Ptr,
7712                                 SDValue Offset, SDValue Mask, SDValue EVL,
7713                                 EVT MemVT, MachineMemOperand *MMO,
7714                                 bool IsExpanding) {
7715   bool Indexed = AM != ISD::UNINDEXED;
7716   assert((Indexed || Offset.isUndef()) && "Unindexed load with an offset!");
7717 
7718   SDVTList VTs = Indexed ? getVTList(VT, Ptr.getValueType(), MVT::Other)
7719                          : getVTList(VT, MVT::Other);
7720   SDValue Ops[] = {Chain, Ptr, Offset, Mask, EVL};
7721   FoldingSetNodeID ID;
7722   AddNodeIDNode(ID, ISD::VP_LOAD, VTs, Ops);
7723   ID.AddInteger(VT.getRawBits());
7724   ID.AddInteger(getSyntheticNodeSubclassData<VPLoadSDNode>(
7725       dl.getIROrder(), VTs, AM, ExtType, IsExpanding, MemVT, MMO));
7726   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7727   void *IP = nullptr;
7728   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7729     cast<VPLoadSDNode>(E)->refineAlignment(MMO);
7730     return SDValue(E, 0);
7731   }
7732   auto *N = newSDNode<VPLoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
7733                                     ExtType, IsExpanding, MemVT, MMO);
7734   createOperands(N, Ops);
7735 
7736   CSEMap.InsertNode(N, IP);
7737   InsertNode(N);
7738   SDValue V(N, 0);
7739   NewSDValueDbgMsg(V, "Creating new node: ", this);
7740   return V;
7741 }
7742 
7743 SDValue SelectionDAG::getLoadVP(EVT VT, const SDLoc &dl, SDValue Chain,
7744                                 SDValue Ptr, SDValue Mask, SDValue EVL,
7745                                 MachinePointerInfo PtrInfo,
7746                                 MaybeAlign Alignment,
7747                                 MachineMemOperand::Flags MMOFlags,
7748                                 const AAMDNodes &AAInfo, const MDNode *Ranges,
7749                                 bool IsExpanding) {
7750   SDValue Undef = getUNDEF(Ptr.getValueType());
7751   return getLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
7752                    Mask, EVL, PtrInfo, VT, Alignment, MMOFlags, AAInfo, Ranges,
7753                    IsExpanding);
7754 }
7755 
7756 SDValue SelectionDAG::getLoadVP(EVT VT, const SDLoc &dl, SDValue Chain,
7757                                 SDValue Ptr, SDValue Mask, SDValue EVL,
7758                                 MachineMemOperand *MMO, bool IsExpanding) {
7759   SDValue Undef = getUNDEF(Ptr.getValueType());
7760   return getLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
7761                    Mask, EVL, VT, MMO, IsExpanding);
7762 }
7763 
7764 SDValue SelectionDAG::getExtLoadVP(ISD::LoadExtType ExtType, const SDLoc &dl,
7765                                    EVT VT, SDValue Chain, SDValue Ptr,
7766                                    SDValue Mask, SDValue EVL,
7767                                    MachinePointerInfo PtrInfo, EVT MemVT,
7768                                    MaybeAlign Alignment,
7769                                    MachineMemOperand::Flags MMOFlags,
7770                                    const AAMDNodes &AAInfo, bool IsExpanding) {
7771   SDValue Undef = getUNDEF(Ptr.getValueType());
7772   return getLoadVP(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, Mask,
7773                    EVL, PtrInfo, MemVT, Alignment, MMOFlags, AAInfo, nullptr,
7774                    IsExpanding);
7775 }
7776 
7777 SDValue SelectionDAG::getExtLoadVP(ISD::LoadExtType ExtType, const SDLoc &dl,
7778                                    EVT VT, SDValue Chain, SDValue Ptr,
7779                                    SDValue Mask, SDValue EVL, EVT MemVT,
7780                                    MachineMemOperand *MMO, bool IsExpanding) {
7781   SDValue Undef = getUNDEF(Ptr.getValueType());
7782   return getLoadVP(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, Mask,
7783                    EVL, MemVT, MMO, IsExpanding);
7784 }
7785 
7786 SDValue SelectionDAG::getIndexedLoadVP(SDValue OrigLoad, const SDLoc &dl,
7787                                        SDValue Base, SDValue Offset,
7788                                        ISD::MemIndexedMode AM) {
7789   auto *LD = cast<VPLoadSDNode>(OrigLoad);
7790   assert(LD->getOffset().isUndef() && "Load is already a indexed load!");
7791   // Don't propagate the invariant or dereferenceable flags.
7792   auto MMOFlags =
7793       LD->getMemOperand()->getFlags() &
7794       ~(MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable);
7795   return getLoadVP(AM, LD->getExtensionType(), OrigLoad.getValueType(), dl,
7796                    LD->getChain(), Base, Offset, LD->getMask(),
7797                    LD->getVectorLength(), LD->getPointerInfo(),
7798                    LD->getMemoryVT(), LD->getAlign(), MMOFlags, LD->getAAInfo(),
7799                    nullptr, LD->isExpandingLoad());
7800 }
7801 
7802 SDValue SelectionDAG::getStoreVP(SDValue Chain, const SDLoc &dl, SDValue Val,
7803                                  SDValue Ptr, SDValue Offset, SDValue Mask,
7804                                  SDValue EVL, EVT MemVT, MachineMemOperand *MMO,
7805                                  ISD::MemIndexedMode AM, bool IsTruncating,
7806                                  bool IsCompressing) {
7807   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
7808   bool Indexed = AM != ISD::UNINDEXED;
7809   assert((Indexed || Offset.isUndef()) && "Unindexed vp_store with an offset!");
7810   SDVTList VTs = Indexed ? getVTList(Ptr.getValueType(), MVT::Other)
7811                          : getVTList(MVT::Other);
7812   SDValue Ops[] = {Chain, Val, Ptr, Offset, Mask, EVL};
7813   FoldingSetNodeID ID;
7814   AddNodeIDNode(ID, ISD::VP_STORE, VTs, Ops);
7815   ID.AddInteger(MemVT.getRawBits());
7816   ID.AddInteger(getSyntheticNodeSubclassData<VPStoreSDNode>(
7817       dl.getIROrder(), VTs, AM, IsTruncating, IsCompressing, MemVT, MMO));
7818   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7819   void *IP = nullptr;
7820   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7821     cast<VPStoreSDNode>(E)->refineAlignment(MMO);
7822     return SDValue(E, 0);
7823   }
7824   auto *N = newSDNode<VPStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
7825                                      IsTruncating, IsCompressing, MemVT, MMO);
7826   createOperands(N, Ops);
7827 
7828   CSEMap.InsertNode(N, IP);
7829   InsertNode(N);
7830   SDValue V(N, 0);
7831   NewSDValueDbgMsg(V, "Creating new node: ", this);
7832   return V;
7833 }
7834 
7835 SDValue SelectionDAG::getTruncStoreVP(SDValue Chain, const SDLoc &dl,
7836                                       SDValue Val, SDValue Ptr, SDValue Mask,
7837                                       SDValue EVL, MachinePointerInfo PtrInfo,
7838                                       EVT SVT, Align Alignment,
7839                                       MachineMemOperand::Flags MMOFlags,
7840                                       const AAMDNodes &AAInfo,
7841                                       bool IsCompressing) {
7842   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
7843 
7844   MMOFlags |= MachineMemOperand::MOStore;
7845   assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
7846 
7847   if (PtrInfo.V.isNull())
7848     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
7849 
7850   MachineFunction &MF = getMachineFunction();
7851   MachineMemOperand *MMO = MF.getMachineMemOperand(
7852       PtrInfo, MMOFlags, MemoryLocation::getSizeOrUnknown(SVT.getStoreSize()),
7853       Alignment, AAInfo);
7854   return getTruncStoreVP(Chain, dl, Val, Ptr, Mask, EVL, SVT, MMO,
7855                          IsCompressing);
7856 }
7857 
7858 SDValue SelectionDAG::getTruncStoreVP(SDValue Chain, const SDLoc &dl,
7859                                       SDValue Val, SDValue Ptr, SDValue Mask,
7860                                       SDValue EVL, EVT SVT,
7861                                       MachineMemOperand *MMO,
7862                                       bool IsCompressing) {
7863   EVT VT = Val.getValueType();
7864 
7865   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
7866   if (VT == SVT)
7867     return getStoreVP(Chain, dl, Val, Ptr, getUNDEF(Ptr.getValueType()), Mask,
7868                       EVL, VT, MMO, ISD::UNINDEXED,
7869                       /*IsTruncating*/ false, IsCompressing);
7870 
7871   assert(SVT.getScalarType().bitsLT(VT.getScalarType()) &&
7872          "Should only be a truncating store, not extending!");
7873   assert(VT.isInteger() == SVT.isInteger() && "Can't do FP-INT conversion!");
7874   assert(VT.isVector() == SVT.isVector() &&
7875          "Cannot use trunc store to convert to or from a vector!");
7876   assert((!VT.isVector() ||
7877           VT.getVectorElementCount() == SVT.getVectorElementCount()) &&
7878          "Cannot use trunc store to change the number of vector elements!");
7879 
7880   SDVTList VTs = getVTList(MVT::Other);
7881   SDValue Undef = getUNDEF(Ptr.getValueType());
7882   SDValue Ops[] = {Chain, Val, Ptr, Undef, Mask, EVL};
7883   FoldingSetNodeID ID;
7884   AddNodeIDNode(ID, ISD::VP_STORE, VTs, Ops);
7885   ID.AddInteger(SVT.getRawBits());
7886   ID.AddInteger(getSyntheticNodeSubclassData<VPStoreSDNode>(
7887       dl.getIROrder(), VTs, ISD::UNINDEXED, true, IsCompressing, SVT, MMO));
7888   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7889   void *IP = nullptr;
7890   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7891     cast<VPStoreSDNode>(E)->refineAlignment(MMO);
7892     return SDValue(E, 0);
7893   }
7894   auto *N =
7895       newSDNode<VPStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
7896                                ISD::UNINDEXED, true, IsCompressing, SVT, MMO);
7897   createOperands(N, Ops);
7898 
7899   CSEMap.InsertNode(N, IP);
7900   InsertNode(N);
7901   SDValue V(N, 0);
7902   NewSDValueDbgMsg(V, "Creating new node: ", this);
7903   return V;
7904 }
7905 
7906 SDValue SelectionDAG::getIndexedStoreVP(SDValue OrigStore, const SDLoc &dl,
7907                                         SDValue Base, SDValue Offset,
7908                                         ISD::MemIndexedMode AM) {
7909   auto *ST = cast<VPStoreSDNode>(OrigStore);
7910   assert(ST->getOffset().isUndef() && "Store is already an indexed store!");
7911   SDVTList VTs = getVTList(Base.getValueType(), MVT::Other);
7912   SDValue Ops[] = {ST->getChain(), ST->getValue(), Base,
7913                    Offset,         ST->getMask(),  ST->getVectorLength()};
7914   FoldingSetNodeID ID;
7915   AddNodeIDNode(ID, ISD::VP_STORE, VTs, Ops);
7916   ID.AddInteger(ST->getMemoryVT().getRawBits());
7917   ID.AddInteger(ST->getRawSubclassData());
7918   ID.AddInteger(ST->getPointerInfo().getAddrSpace());
7919   void *IP = nullptr;
7920   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
7921     return SDValue(E, 0);
7922 
7923   auto *N = newSDNode<VPStoreSDNode>(
7924       dl.getIROrder(), dl.getDebugLoc(), VTs, AM, ST->isTruncatingStore(),
7925       ST->isCompressingStore(), ST->getMemoryVT(), ST->getMemOperand());
7926   createOperands(N, Ops);
7927 
7928   CSEMap.InsertNode(N, IP);
7929   InsertNode(N);
7930   SDValue V(N, 0);
7931   NewSDValueDbgMsg(V, "Creating new node: ", this);
7932   return V;
7933 }
7934 
7935 SDValue SelectionDAG::getGatherVP(SDVTList VTs, EVT VT, const SDLoc &dl,
7936                                   ArrayRef<SDValue> Ops, MachineMemOperand *MMO,
7937                                   ISD::MemIndexType IndexType) {
7938   assert(Ops.size() == 6 && "Incompatible number of operands");
7939 
7940   FoldingSetNodeID ID;
7941   AddNodeIDNode(ID, ISD::VP_GATHER, VTs, Ops);
7942   ID.AddInteger(VT.getRawBits());
7943   ID.AddInteger(getSyntheticNodeSubclassData<VPGatherSDNode>(
7944       dl.getIROrder(), VTs, VT, MMO, IndexType));
7945   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7946   void *IP = nullptr;
7947   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7948     cast<VPGatherSDNode>(E)->refineAlignment(MMO);
7949     return SDValue(E, 0);
7950   }
7951 
7952   auto *N = newSDNode<VPGatherSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
7953                                       VT, MMO, IndexType);
7954   createOperands(N, Ops);
7955 
7956   assert(N->getMask().getValueType().getVectorElementCount() ==
7957              N->getValueType(0).getVectorElementCount() &&
7958          "Vector width mismatch between mask and data");
7959   assert(N->getIndex().getValueType().getVectorElementCount().isScalable() ==
7960              N->getValueType(0).getVectorElementCount().isScalable() &&
7961          "Scalable flags of index and data do not match");
7962   assert(ElementCount::isKnownGE(
7963              N->getIndex().getValueType().getVectorElementCount(),
7964              N->getValueType(0).getVectorElementCount()) &&
7965          "Vector width mismatch between index and data");
7966   assert(isa<ConstantSDNode>(N->getScale()) &&
7967          cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() &&
7968          "Scale should be a constant power of 2");
7969 
7970   CSEMap.InsertNode(N, IP);
7971   InsertNode(N);
7972   SDValue V(N, 0);
7973   NewSDValueDbgMsg(V, "Creating new node: ", this);
7974   return V;
7975 }
7976 
7977 SDValue SelectionDAG::getScatterVP(SDVTList VTs, EVT VT, const SDLoc &dl,
7978                                    ArrayRef<SDValue> Ops,
7979                                    MachineMemOperand *MMO,
7980                                    ISD::MemIndexType IndexType) {
7981   assert(Ops.size() == 7 && "Incompatible number of operands");
7982 
7983   FoldingSetNodeID ID;
7984   AddNodeIDNode(ID, ISD::VP_SCATTER, VTs, Ops);
7985   ID.AddInteger(VT.getRawBits());
7986   ID.AddInteger(getSyntheticNodeSubclassData<VPScatterSDNode>(
7987       dl.getIROrder(), VTs, VT, MMO, IndexType));
7988   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7989   void *IP = nullptr;
7990   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7991     cast<VPScatterSDNode>(E)->refineAlignment(MMO);
7992     return SDValue(E, 0);
7993   }
7994   auto *N = newSDNode<VPScatterSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
7995                                        VT, MMO, IndexType);
7996   createOperands(N, Ops);
7997 
7998   assert(N->getMask().getValueType().getVectorElementCount() ==
7999              N->getValue().getValueType().getVectorElementCount() &&
8000          "Vector width mismatch between mask and data");
8001   assert(
8002       N->getIndex().getValueType().getVectorElementCount().isScalable() ==
8003           N->getValue().getValueType().getVectorElementCount().isScalable() &&
8004       "Scalable flags of index and data do not match");
8005   assert(ElementCount::isKnownGE(
8006              N->getIndex().getValueType().getVectorElementCount(),
8007              N->getValue().getValueType().getVectorElementCount()) &&
8008          "Vector width mismatch between index and data");
8009   assert(isa<ConstantSDNode>(N->getScale()) &&
8010          cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() &&
8011          "Scale should be a constant power of 2");
8012 
8013   CSEMap.InsertNode(N, IP);
8014   InsertNode(N);
8015   SDValue V(N, 0);
8016   NewSDValueDbgMsg(V, "Creating new node: ", this);
8017   return V;
8018 }
8019 
8020 SDValue SelectionDAG::getMaskedLoad(EVT VT, const SDLoc &dl, SDValue Chain,
8021                                     SDValue Base, SDValue Offset, SDValue Mask,
8022                                     SDValue PassThru, EVT MemVT,
8023                                     MachineMemOperand *MMO,
8024                                     ISD::MemIndexedMode AM,
8025                                     ISD::LoadExtType ExtTy, bool isExpanding) {
8026   bool Indexed = AM != ISD::UNINDEXED;
8027   assert((Indexed || Offset.isUndef()) &&
8028          "Unindexed masked load with an offset!");
8029   SDVTList VTs = Indexed ? getVTList(VT, Base.getValueType(), MVT::Other)
8030                          : getVTList(VT, MVT::Other);
8031   SDValue Ops[] = {Chain, Base, Offset, Mask, PassThru};
8032   FoldingSetNodeID ID;
8033   AddNodeIDNode(ID, ISD::MLOAD, VTs, Ops);
8034   ID.AddInteger(MemVT.getRawBits());
8035   ID.AddInteger(getSyntheticNodeSubclassData<MaskedLoadSDNode>(
8036       dl.getIROrder(), VTs, AM, ExtTy, isExpanding, MemVT, MMO));
8037   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8038   void *IP = nullptr;
8039   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
8040     cast<MaskedLoadSDNode>(E)->refineAlignment(MMO);
8041     return SDValue(E, 0);
8042   }
8043   auto *N = newSDNode<MaskedLoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
8044                                         AM, ExtTy, isExpanding, MemVT, MMO);
8045   createOperands(N, Ops);
8046 
8047   CSEMap.InsertNode(N, IP);
8048   InsertNode(N);
8049   SDValue V(N, 0);
8050   NewSDValueDbgMsg(V, "Creating new node: ", this);
8051   return V;
8052 }
8053 
8054 SDValue SelectionDAG::getIndexedMaskedLoad(SDValue OrigLoad, const SDLoc &dl,
8055                                            SDValue Base, SDValue Offset,
8056                                            ISD::MemIndexedMode AM) {
8057   MaskedLoadSDNode *LD = cast<MaskedLoadSDNode>(OrigLoad);
8058   assert(LD->getOffset().isUndef() && "Masked load is already a indexed load!");
8059   return getMaskedLoad(OrigLoad.getValueType(), dl, LD->getChain(), Base,
8060                        Offset, LD->getMask(), LD->getPassThru(),
8061                        LD->getMemoryVT(), LD->getMemOperand(), AM,
8062                        LD->getExtensionType(), LD->isExpandingLoad());
8063 }
8064 
8065 SDValue SelectionDAG::getMaskedStore(SDValue Chain, const SDLoc &dl,
8066                                      SDValue Val, SDValue Base, SDValue Offset,
8067                                      SDValue Mask, EVT MemVT,
8068                                      MachineMemOperand *MMO,
8069                                      ISD::MemIndexedMode AM, bool IsTruncating,
8070                                      bool IsCompressing) {
8071   assert(Chain.getValueType() == MVT::Other &&
8072         "Invalid chain type");
8073   bool Indexed = AM != ISD::UNINDEXED;
8074   assert((Indexed || Offset.isUndef()) &&
8075          "Unindexed masked store with an offset!");
8076   SDVTList VTs = Indexed ? getVTList(Base.getValueType(), MVT::Other)
8077                          : getVTList(MVT::Other);
8078   SDValue Ops[] = {Chain, Val, Base, Offset, Mask};
8079   FoldingSetNodeID ID;
8080   AddNodeIDNode(ID, ISD::MSTORE, VTs, Ops);
8081   ID.AddInteger(MemVT.getRawBits());
8082   ID.AddInteger(getSyntheticNodeSubclassData<MaskedStoreSDNode>(
8083       dl.getIROrder(), VTs, AM, IsTruncating, IsCompressing, MemVT, MMO));
8084   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8085   void *IP = nullptr;
8086   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
8087     cast<MaskedStoreSDNode>(E)->refineAlignment(MMO);
8088     return SDValue(E, 0);
8089   }
8090   auto *N =
8091       newSDNode<MaskedStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
8092                                    IsTruncating, IsCompressing, MemVT, MMO);
8093   createOperands(N, Ops);
8094 
8095   CSEMap.InsertNode(N, IP);
8096   InsertNode(N);
8097   SDValue V(N, 0);
8098   NewSDValueDbgMsg(V, "Creating new node: ", this);
8099   return V;
8100 }
8101 
8102 SDValue SelectionDAG::getIndexedMaskedStore(SDValue OrigStore, const SDLoc &dl,
8103                                             SDValue Base, SDValue Offset,
8104                                             ISD::MemIndexedMode AM) {
8105   MaskedStoreSDNode *ST = cast<MaskedStoreSDNode>(OrigStore);
8106   assert(ST->getOffset().isUndef() &&
8107          "Masked store is already a indexed store!");
8108   return getMaskedStore(ST->getChain(), dl, ST->getValue(), Base, Offset,
8109                         ST->getMask(), ST->getMemoryVT(), ST->getMemOperand(),
8110                         AM, ST->isTruncatingStore(), ST->isCompressingStore());
8111 }
8112 
8113 SDValue SelectionDAG::getMaskedGather(SDVTList VTs, EVT MemVT, const SDLoc &dl,
8114                                       ArrayRef<SDValue> Ops,
8115                                       MachineMemOperand *MMO,
8116                                       ISD::MemIndexType IndexType,
8117                                       ISD::LoadExtType ExtTy) {
8118   assert(Ops.size() == 6 && "Incompatible number of operands");
8119 
8120   FoldingSetNodeID ID;
8121   AddNodeIDNode(ID, ISD::MGATHER, VTs, Ops);
8122   ID.AddInteger(MemVT.getRawBits());
8123   ID.AddInteger(getSyntheticNodeSubclassData<MaskedGatherSDNode>(
8124       dl.getIROrder(), VTs, MemVT, MMO, IndexType, ExtTy));
8125   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8126   void *IP = nullptr;
8127   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
8128     cast<MaskedGatherSDNode>(E)->refineAlignment(MMO);
8129     return SDValue(E, 0);
8130   }
8131 
8132   IndexType = TLI->getCanonicalIndexType(IndexType, MemVT, Ops[4]);
8133   auto *N = newSDNode<MaskedGatherSDNode>(dl.getIROrder(), dl.getDebugLoc(),
8134                                           VTs, MemVT, MMO, IndexType, ExtTy);
8135   createOperands(N, Ops);
8136 
8137   assert(N->getPassThru().getValueType() == N->getValueType(0) &&
8138          "Incompatible type of the PassThru value in MaskedGatherSDNode");
8139   assert(N->getMask().getValueType().getVectorElementCount() ==
8140              N->getValueType(0).getVectorElementCount() &&
8141          "Vector width mismatch between mask and data");
8142   assert(N->getIndex().getValueType().getVectorElementCount().isScalable() ==
8143              N->getValueType(0).getVectorElementCount().isScalable() &&
8144          "Scalable flags of index and data do not match");
8145   assert(ElementCount::isKnownGE(
8146              N->getIndex().getValueType().getVectorElementCount(),
8147              N->getValueType(0).getVectorElementCount()) &&
8148          "Vector width mismatch between index and data");
8149   assert(isa<ConstantSDNode>(N->getScale()) &&
8150          cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() &&
8151          "Scale should be a constant power of 2");
8152 
8153   CSEMap.InsertNode(N, IP);
8154   InsertNode(N);
8155   SDValue V(N, 0);
8156   NewSDValueDbgMsg(V, "Creating new node: ", this);
8157   return V;
8158 }
8159 
8160 SDValue SelectionDAG::getMaskedScatter(SDVTList VTs, EVT MemVT, const SDLoc &dl,
8161                                        ArrayRef<SDValue> Ops,
8162                                        MachineMemOperand *MMO,
8163                                        ISD::MemIndexType IndexType,
8164                                        bool IsTrunc) {
8165   assert(Ops.size() == 6 && "Incompatible number of operands");
8166 
8167   FoldingSetNodeID ID;
8168   AddNodeIDNode(ID, ISD::MSCATTER, VTs, Ops);
8169   ID.AddInteger(MemVT.getRawBits());
8170   ID.AddInteger(getSyntheticNodeSubclassData<MaskedScatterSDNode>(
8171       dl.getIROrder(), VTs, MemVT, MMO, IndexType, IsTrunc));
8172   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8173   void *IP = nullptr;
8174   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
8175     cast<MaskedScatterSDNode>(E)->refineAlignment(MMO);
8176     return SDValue(E, 0);
8177   }
8178 
8179   IndexType = TLI->getCanonicalIndexType(IndexType, MemVT, Ops[4]);
8180   auto *N = newSDNode<MaskedScatterSDNode>(dl.getIROrder(), dl.getDebugLoc(),
8181                                            VTs, MemVT, MMO, IndexType, IsTrunc);
8182   createOperands(N, Ops);
8183 
8184   assert(N->getMask().getValueType().getVectorElementCount() ==
8185              N->getValue().getValueType().getVectorElementCount() &&
8186          "Vector width mismatch between mask and data");
8187   assert(
8188       N->getIndex().getValueType().getVectorElementCount().isScalable() ==
8189           N->getValue().getValueType().getVectorElementCount().isScalable() &&
8190       "Scalable flags of index and data do not match");
8191   assert(ElementCount::isKnownGE(
8192              N->getIndex().getValueType().getVectorElementCount(),
8193              N->getValue().getValueType().getVectorElementCount()) &&
8194          "Vector width mismatch between index and data");
8195   assert(isa<ConstantSDNode>(N->getScale()) &&
8196          cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() &&
8197          "Scale should be a constant power of 2");
8198 
8199   CSEMap.InsertNode(N, IP);
8200   InsertNode(N);
8201   SDValue V(N, 0);
8202   NewSDValueDbgMsg(V, "Creating new node: ", this);
8203   return V;
8204 }
8205 
8206 SDValue SelectionDAG::simplifySelect(SDValue Cond, SDValue T, SDValue F) {
8207   // select undef, T, F --> T (if T is a constant), otherwise F
8208   // select, ?, undef, F --> F
8209   // select, ?, T, undef --> T
8210   if (Cond.isUndef())
8211     return isConstantValueOfAnyType(T) ? T : F;
8212   if (T.isUndef())
8213     return F;
8214   if (F.isUndef())
8215     return T;
8216 
8217   // select true, T, F --> T
8218   // select false, T, F --> F
8219   if (auto *CondC = dyn_cast<ConstantSDNode>(Cond))
8220     return CondC->isZero() ? F : T;
8221 
8222   // TODO: This should simplify VSELECT with constant condition using something
8223   // like this (but check boolean contents to be complete?):
8224   //  if (ISD::isBuildVectorAllOnes(Cond.getNode()))
8225   //    return T;
8226   //  if (ISD::isBuildVectorAllZeros(Cond.getNode()))
8227   //    return F;
8228 
8229   // select ?, T, T --> T
8230   if (T == F)
8231     return T;
8232 
8233   return SDValue();
8234 }
8235 
8236 SDValue SelectionDAG::simplifyShift(SDValue X, SDValue Y) {
8237   // shift undef, Y --> 0 (can always assume that the undef value is 0)
8238   if (X.isUndef())
8239     return getConstant(0, SDLoc(X.getNode()), X.getValueType());
8240   // shift X, undef --> undef (because it may shift by the bitwidth)
8241   if (Y.isUndef())
8242     return getUNDEF(X.getValueType());
8243 
8244   // shift 0, Y --> 0
8245   // shift X, 0 --> X
8246   if (isNullOrNullSplat(X) || isNullOrNullSplat(Y))
8247     return X;
8248 
8249   // shift X, C >= bitwidth(X) --> undef
8250   // All vector elements must be too big (or undef) to avoid partial undefs.
8251   auto isShiftTooBig = [X](ConstantSDNode *Val) {
8252     return !Val || Val->getAPIntValue().uge(X.getScalarValueSizeInBits());
8253   };
8254   if (ISD::matchUnaryPredicate(Y, isShiftTooBig, true))
8255     return getUNDEF(X.getValueType());
8256 
8257   return SDValue();
8258 }
8259 
8260 SDValue SelectionDAG::simplifyFPBinop(unsigned Opcode, SDValue X, SDValue Y,
8261                                       SDNodeFlags Flags) {
8262   // If this operation has 'nnan' or 'ninf' and at least 1 disallowed operand
8263   // (an undef operand can be chosen to be Nan/Inf), then the result of this
8264   // operation is poison. That result can be relaxed to undef.
8265   ConstantFPSDNode *XC = isConstOrConstSplatFP(X, /* AllowUndefs */ true);
8266   ConstantFPSDNode *YC = isConstOrConstSplatFP(Y, /* AllowUndefs */ true);
8267   bool HasNan = (XC && XC->getValueAPF().isNaN()) ||
8268                 (YC && YC->getValueAPF().isNaN());
8269   bool HasInf = (XC && XC->getValueAPF().isInfinity()) ||
8270                 (YC && YC->getValueAPF().isInfinity());
8271 
8272   if (Flags.hasNoNaNs() && (HasNan || X.isUndef() || Y.isUndef()))
8273     return getUNDEF(X.getValueType());
8274 
8275   if (Flags.hasNoInfs() && (HasInf || X.isUndef() || Y.isUndef()))
8276     return getUNDEF(X.getValueType());
8277 
8278   if (!YC)
8279     return SDValue();
8280 
8281   // X + -0.0 --> X
8282   if (Opcode == ISD::FADD)
8283     if (YC->getValueAPF().isNegZero())
8284       return X;
8285 
8286   // X - +0.0 --> X
8287   if (Opcode == ISD::FSUB)
8288     if (YC->getValueAPF().isPosZero())
8289       return X;
8290 
8291   // X * 1.0 --> X
8292   // X / 1.0 --> X
8293   if (Opcode == ISD::FMUL || Opcode == ISD::FDIV)
8294     if (YC->getValueAPF().isExactlyValue(1.0))
8295       return X;
8296 
8297   // X * 0.0 --> 0.0
8298   if (Opcode == ISD::FMUL && Flags.hasNoNaNs() && Flags.hasNoSignedZeros())
8299     if (YC->getValueAPF().isZero())
8300       return getConstantFP(0.0, SDLoc(Y), Y.getValueType());
8301 
8302   return SDValue();
8303 }
8304 
8305 SDValue SelectionDAG::getVAArg(EVT VT, const SDLoc &dl, SDValue Chain,
8306                                SDValue Ptr, SDValue SV, unsigned Align) {
8307   SDValue Ops[] = { Chain, Ptr, SV, getTargetConstant(Align, dl, MVT::i32) };
8308   return getNode(ISD::VAARG, dl, getVTList(VT, MVT::Other), Ops);
8309 }
8310 
8311 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
8312                               ArrayRef<SDUse> Ops) {
8313   switch (Ops.size()) {
8314   case 0: return getNode(Opcode, DL, VT);
8315   case 1: return getNode(Opcode, DL, VT, static_cast<const SDValue>(Ops[0]));
8316   case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1]);
8317   case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2]);
8318   default: break;
8319   }
8320 
8321   // Copy from an SDUse array into an SDValue array for use with
8322   // the regular getNode logic.
8323   SmallVector<SDValue, 8> NewOps(Ops.begin(), Ops.end());
8324   return getNode(Opcode, DL, VT, NewOps);
8325 }
8326 
8327 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
8328                               ArrayRef<SDValue> Ops) {
8329   SDNodeFlags Flags;
8330   if (Inserter)
8331     Flags = Inserter->getFlags();
8332   return getNode(Opcode, DL, VT, Ops, Flags);
8333 }
8334 
8335 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
8336                               ArrayRef<SDValue> Ops, const SDNodeFlags Flags) {
8337   unsigned NumOps = Ops.size();
8338   switch (NumOps) {
8339   case 0: return getNode(Opcode, DL, VT);
8340   case 1: return getNode(Opcode, DL, VT, Ops[0], Flags);
8341   case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Flags);
8342   case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2], Flags);
8343   default: break;
8344   }
8345 
8346 #ifndef NDEBUG
8347   for (auto &Op : Ops)
8348     assert(Op.getOpcode() != ISD::DELETED_NODE &&
8349            "Operand is DELETED_NODE!");
8350 #endif
8351 
8352   switch (Opcode) {
8353   default: break;
8354   case ISD::BUILD_VECTOR:
8355     // Attempt to simplify BUILD_VECTOR.
8356     if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
8357       return V;
8358     break;
8359   case ISD::CONCAT_VECTORS:
8360     if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this))
8361       return V;
8362     break;
8363   case ISD::SELECT_CC:
8364     assert(NumOps == 5 && "SELECT_CC takes 5 operands!");
8365     assert(Ops[0].getValueType() == Ops[1].getValueType() &&
8366            "LHS and RHS of condition must have same type!");
8367     assert(Ops[2].getValueType() == Ops[3].getValueType() &&
8368            "True and False arms of SelectCC must have same type!");
8369     assert(Ops[2].getValueType() == VT &&
8370            "select_cc node must be of same type as true and false value!");
8371     break;
8372   case ISD::BR_CC:
8373     assert(NumOps == 5 && "BR_CC takes 5 operands!");
8374     assert(Ops[2].getValueType() == Ops[3].getValueType() &&
8375            "LHS/RHS of comparison should match types!");
8376     break;
8377   }
8378 
8379   // Memoize nodes.
8380   SDNode *N;
8381   SDVTList VTs = getVTList(VT);
8382 
8383   if (VT != MVT::Glue) {
8384     FoldingSetNodeID ID;
8385     AddNodeIDNode(ID, Opcode, VTs, Ops);
8386     void *IP = nullptr;
8387 
8388     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
8389       return SDValue(E, 0);
8390 
8391     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
8392     createOperands(N, Ops);
8393 
8394     CSEMap.InsertNode(N, IP);
8395   } else {
8396     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
8397     createOperands(N, Ops);
8398   }
8399 
8400   N->setFlags(Flags);
8401   InsertNode(N);
8402   SDValue V(N, 0);
8403   NewSDValueDbgMsg(V, "Creating new node: ", this);
8404   return V;
8405 }
8406 
8407 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL,
8408                               ArrayRef<EVT> ResultTys, ArrayRef<SDValue> Ops) {
8409   return getNode(Opcode, DL, getVTList(ResultTys), Ops);
8410 }
8411 
8412 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
8413                               ArrayRef<SDValue> Ops) {
8414   SDNodeFlags Flags;
8415   if (Inserter)
8416     Flags = Inserter->getFlags();
8417   return getNode(Opcode, DL, VTList, Ops, Flags);
8418 }
8419 
8420 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
8421                               ArrayRef<SDValue> Ops, const SDNodeFlags Flags) {
8422   if (VTList.NumVTs == 1)
8423     return getNode(Opcode, DL, VTList.VTs[0], Ops);
8424 
8425 #ifndef NDEBUG
8426   for (auto &Op : Ops)
8427     assert(Op.getOpcode() != ISD::DELETED_NODE &&
8428            "Operand is DELETED_NODE!");
8429 #endif
8430 
8431   switch (Opcode) {
8432   case ISD::STRICT_FP_EXTEND:
8433     assert(VTList.NumVTs == 2 && Ops.size() == 2 &&
8434            "Invalid STRICT_FP_EXTEND!");
8435     assert(VTList.VTs[0].isFloatingPoint() &&
8436            Ops[1].getValueType().isFloatingPoint() && "Invalid FP cast!");
8437     assert(VTList.VTs[0].isVector() == Ops[1].getValueType().isVector() &&
8438            "STRICT_FP_EXTEND result type should be vector iff the operand "
8439            "type is vector!");
8440     assert((!VTList.VTs[0].isVector() ||
8441             VTList.VTs[0].getVectorNumElements() ==
8442             Ops[1].getValueType().getVectorNumElements()) &&
8443            "Vector element count mismatch!");
8444     assert(Ops[1].getValueType().bitsLT(VTList.VTs[0]) &&
8445            "Invalid fpext node, dst <= src!");
8446     break;
8447   case ISD::STRICT_FP_ROUND:
8448     assert(VTList.NumVTs == 2 && Ops.size() == 3 && "Invalid STRICT_FP_ROUND!");
8449     assert(VTList.VTs[0].isVector() == Ops[1].getValueType().isVector() &&
8450            "STRICT_FP_ROUND result type should be vector iff the operand "
8451            "type is vector!");
8452     assert((!VTList.VTs[0].isVector() ||
8453             VTList.VTs[0].getVectorNumElements() ==
8454             Ops[1].getValueType().getVectorNumElements()) &&
8455            "Vector element count mismatch!");
8456     assert(VTList.VTs[0].isFloatingPoint() &&
8457            Ops[1].getValueType().isFloatingPoint() &&
8458            VTList.VTs[0].bitsLT(Ops[1].getValueType()) &&
8459            isa<ConstantSDNode>(Ops[2]) &&
8460            (cast<ConstantSDNode>(Ops[2])->getZExtValue() == 0 ||
8461             cast<ConstantSDNode>(Ops[2])->getZExtValue() == 1) &&
8462            "Invalid STRICT_FP_ROUND!");
8463     break;
8464 #if 0
8465   // FIXME: figure out how to safely handle things like
8466   // int foo(int x) { return 1 << (x & 255); }
8467   // int bar() { return foo(256); }
8468   case ISD::SRA_PARTS:
8469   case ISD::SRL_PARTS:
8470   case ISD::SHL_PARTS:
8471     if (N3.getOpcode() == ISD::SIGN_EXTEND_INREG &&
8472         cast<VTSDNode>(N3.getOperand(1))->getVT() != MVT::i1)
8473       return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0));
8474     else if (N3.getOpcode() == ISD::AND)
8475       if (ConstantSDNode *AndRHS = dyn_cast<ConstantSDNode>(N3.getOperand(1))) {
8476         // If the and is only masking out bits that cannot effect the shift,
8477         // eliminate the and.
8478         unsigned NumBits = VT.getScalarSizeInBits()*2;
8479         if ((AndRHS->getValue() & (NumBits-1)) == NumBits-1)
8480           return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0));
8481       }
8482     break;
8483 #endif
8484   }
8485 
8486   // Memoize the node unless it returns a flag.
8487   SDNode *N;
8488   if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) {
8489     FoldingSetNodeID ID;
8490     AddNodeIDNode(ID, Opcode, VTList, Ops);
8491     void *IP = nullptr;
8492     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
8493       return SDValue(E, 0);
8494 
8495     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList);
8496     createOperands(N, Ops);
8497     CSEMap.InsertNode(N, IP);
8498   } else {
8499     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList);
8500     createOperands(N, Ops);
8501   }
8502 
8503   N->setFlags(Flags);
8504   InsertNode(N);
8505   SDValue V(N, 0);
8506   NewSDValueDbgMsg(V, "Creating new node: ", this);
8507   return V;
8508 }
8509 
8510 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL,
8511                               SDVTList VTList) {
8512   return getNode(Opcode, DL, VTList, None);
8513 }
8514 
8515 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
8516                               SDValue N1) {
8517   SDValue Ops[] = { N1 };
8518   return getNode(Opcode, DL, VTList, Ops);
8519 }
8520 
8521 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
8522                               SDValue N1, SDValue N2) {
8523   SDValue Ops[] = { N1, N2 };
8524   return getNode(Opcode, DL, VTList, Ops);
8525 }
8526 
8527 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
8528                               SDValue N1, SDValue N2, SDValue N3) {
8529   SDValue Ops[] = { N1, N2, N3 };
8530   return getNode(Opcode, DL, VTList, Ops);
8531 }
8532 
8533 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
8534                               SDValue N1, SDValue N2, SDValue N3, SDValue N4) {
8535   SDValue Ops[] = { N1, N2, N3, N4 };
8536   return getNode(Opcode, DL, VTList, Ops);
8537 }
8538 
8539 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
8540                               SDValue N1, SDValue N2, SDValue N3, SDValue N4,
8541                               SDValue N5) {
8542   SDValue Ops[] = { N1, N2, N3, N4, N5 };
8543   return getNode(Opcode, DL, VTList, Ops);
8544 }
8545 
8546 SDVTList SelectionDAG::getVTList(EVT VT) {
8547   return makeVTList(SDNode::getValueTypeList(VT), 1);
8548 }
8549 
8550 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2) {
8551   FoldingSetNodeID ID;
8552   ID.AddInteger(2U);
8553   ID.AddInteger(VT1.getRawBits());
8554   ID.AddInteger(VT2.getRawBits());
8555 
8556   void *IP = nullptr;
8557   SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
8558   if (!Result) {
8559     EVT *Array = Allocator.Allocate<EVT>(2);
8560     Array[0] = VT1;
8561     Array[1] = VT2;
8562     Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 2);
8563     VTListMap.InsertNode(Result, IP);
8564   }
8565   return Result->getSDVTList();
8566 }
8567 
8568 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3) {
8569   FoldingSetNodeID ID;
8570   ID.AddInteger(3U);
8571   ID.AddInteger(VT1.getRawBits());
8572   ID.AddInteger(VT2.getRawBits());
8573   ID.AddInteger(VT3.getRawBits());
8574 
8575   void *IP = nullptr;
8576   SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
8577   if (!Result) {
8578     EVT *Array = Allocator.Allocate<EVT>(3);
8579     Array[0] = VT1;
8580     Array[1] = VT2;
8581     Array[2] = VT3;
8582     Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 3);
8583     VTListMap.InsertNode(Result, IP);
8584   }
8585   return Result->getSDVTList();
8586 }
8587 
8588 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3, EVT VT4) {
8589   FoldingSetNodeID ID;
8590   ID.AddInteger(4U);
8591   ID.AddInteger(VT1.getRawBits());
8592   ID.AddInteger(VT2.getRawBits());
8593   ID.AddInteger(VT3.getRawBits());
8594   ID.AddInteger(VT4.getRawBits());
8595 
8596   void *IP = nullptr;
8597   SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
8598   if (!Result) {
8599     EVT *Array = Allocator.Allocate<EVT>(4);
8600     Array[0] = VT1;
8601     Array[1] = VT2;
8602     Array[2] = VT3;
8603     Array[3] = VT4;
8604     Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 4);
8605     VTListMap.InsertNode(Result, IP);
8606   }
8607   return Result->getSDVTList();
8608 }
8609 
8610 SDVTList SelectionDAG::getVTList(ArrayRef<EVT> VTs) {
8611   unsigned NumVTs = VTs.size();
8612   FoldingSetNodeID ID;
8613   ID.AddInteger(NumVTs);
8614   for (unsigned index = 0; index < NumVTs; index++) {
8615     ID.AddInteger(VTs[index].getRawBits());
8616   }
8617 
8618   void *IP = nullptr;
8619   SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
8620   if (!Result) {
8621     EVT *Array = Allocator.Allocate<EVT>(NumVTs);
8622     llvm::copy(VTs, Array);
8623     Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, NumVTs);
8624     VTListMap.InsertNode(Result, IP);
8625   }
8626   return Result->getSDVTList();
8627 }
8628 
8629 
8630 /// UpdateNodeOperands - *Mutate* the specified node in-place to have the
8631 /// specified operands.  If the resultant node already exists in the DAG,
8632 /// this does not modify the specified node, instead it returns the node that
8633 /// already exists.  If the resultant node does not exist in the DAG, the
8634 /// input node is returned.  As a degenerate case, if you specify the same
8635 /// input operands as the node already has, the input node is returned.
8636 SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op) {
8637   assert(N->getNumOperands() == 1 && "Update with wrong number of operands");
8638 
8639   // Check to see if there is no change.
8640   if (Op == N->getOperand(0)) return N;
8641 
8642   // See if the modified node already exists.
8643   void *InsertPos = nullptr;
8644   if (SDNode *Existing = FindModifiedNodeSlot(N, Op, InsertPos))
8645     return Existing;
8646 
8647   // Nope it doesn't.  Remove the node from its current place in the maps.
8648   if (InsertPos)
8649     if (!RemoveNodeFromCSEMaps(N))
8650       InsertPos = nullptr;
8651 
8652   // Now we update the operands.
8653   N->OperandList[0].set(Op);
8654 
8655   updateDivergence(N);
8656   // If this gets put into a CSE map, add it.
8657   if (InsertPos) CSEMap.InsertNode(N, InsertPos);
8658   return N;
8659 }
8660 
8661 SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2) {
8662   assert(N->getNumOperands() == 2 && "Update with wrong number of operands");
8663 
8664   // Check to see if there is no change.
8665   if (Op1 == N->getOperand(0) && Op2 == N->getOperand(1))
8666     return N;   // No operands changed, just return the input node.
8667 
8668   // See if the modified node already exists.
8669   void *InsertPos = nullptr;
8670   if (SDNode *Existing = FindModifiedNodeSlot(N, Op1, Op2, InsertPos))
8671     return Existing;
8672 
8673   // Nope it doesn't.  Remove the node from its current place in the maps.
8674   if (InsertPos)
8675     if (!RemoveNodeFromCSEMaps(N))
8676       InsertPos = nullptr;
8677 
8678   // Now we update the operands.
8679   if (N->OperandList[0] != Op1)
8680     N->OperandList[0].set(Op1);
8681   if (N->OperandList[1] != Op2)
8682     N->OperandList[1].set(Op2);
8683 
8684   updateDivergence(N);
8685   // If this gets put into a CSE map, add it.
8686   if (InsertPos) CSEMap.InsertNode(N, InsertPos);
8687   return N;
8688 }
8689 
8690 SDNode *SelectionDAG::
8691 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2, SDValue Op3) {
8692   SDValue Ops[] = { Op1, Op2, Op3 };
8693   return UpdateNodeOperands(N, Ops);
8694 }
8695 
8696 SDNode *SelectionDAG::
8697 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2,
8698                    SDValue Op3, SDValue Op4) {
8699   SDValue Ops[] = { Op1, Op2, Op3, Op4 };
8700   return UpdateNodeOperands(N, Ops);
8701 }
8702 
8703 SDNode *SelectionDAG::
8704 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2,
8705                    SDValue Op3, SDValue Op4, SDValue Op5) {
8706   SDValue Ops[] = { Op1, Op2, Op3, Op4, Op5 };
8707   return UpdateNodeOperands(N, Ops);
8708 }
8709 
8710 SDNode *SelectionDAG::
8711 UpdateNodeOperands(SDNode *N, ArrayRef<SDValue> Ops) {
8712   unsigned NumOps = Ops.size();
8713   assert(N->getNumOperands() == NumOps &&
8714          "Update with wrong number of operands");
8715 
8716   // If no operands changed just return the input node.
8717   if (std::equal(Ops.begin(), Ops.end(), N->op_begin()))
8718     return N;
8719 
8720   // See if the modified node already exists.
8721   void *InsertPos = nullptr;
8722   if (SDNode *Existing = FindModifiedNodeSlot(N, Ops, InsertPos))
8723     return Existing;
8724 
8725   // Nope it doesn't.  Remove the node from its current place in the maps.
8726   if (InsertPos)
8727     if (!RemoveNodeFromCSEMaps(N))
8728       InsertPos = nullptr;
8729 
8730   // Now we update the operands.
8731   for (unsigned i = 0; i != NumOps; ++i)
8732     if (N->OperandList[i] != Ops[i])
8733       N->OperandList[i].set(Ops[i]);
8734 
8735   updateDivergence(N);
8736   // If this gets put into a CSE map, add it.
8737   if (InsertPos) CSEMap.InsertNode(N, InsertPos);
8738   return N;
8739 }
8740 
8741 /// DropOperands - Release the operands and set this node to have
8742 /// zero operands.
8743 void SDNode::DropOperands() {
8744   // Unlike the code in MorphNodeTo that does this, we don't need to
8745   // watch for dead nodes here.
8746   for (op_iterator I = op_begin(), E = op_end(); I != E; ) {
8747     SDUse &Use = *I++;
8748     Use.set(SDValue());
8749   }
8750 }
8751 
8752 void SelectionDAG::setNodeMemRefs(MachineSDNode *N,
8753                                   ArrayRef<MachineMemOperand *> NewMemRefs) {
8754   if (NewMemRefs.empty()) {
8755     N->clearMemRefs();
8756     return;
8757   }
8758 
8759   // Check if we can avoid allocating by storing a single reference directly.
8760   if (NewMemRefs.size() == 1) {
8761     N->MemRefs = NewMemRefs[0];
8762     N->NumMemRefs = 1;
8763     return;
8764   }
8765 
8766   MachineMemOperand **MemRefsBuffer =
8767       Allocator.template Allocate<MachineMemOperand *>(NewMemRefs.size());
8768   llvm::copy(NewMemRefs, MemRefsBuffer);
8769   N->MemRefs = MemRefsBuffer;
8770   N->NumMemRefs = static_cast<int>(NewMemRefs.size());
8771 }
8772 
8773 /// SelectNodeTo - These are wrappers around MorphNodeTo that accept a
8774 /// machine opcode.
8775 ///
8776 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8777                                    EVT VT) {
8778   SDVTList VTs = getVTList(VT);
8779   return SelectNodeTo(N, MachineOpc, VTs, None);
8780 }
8781 
8782 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8783                                    EVT VT, SDValue Op1) {
8784   SDVTList VTs = getVTList(VT);
8785   SDValue Ops[] = { Op1 };
8786   return SelectNodeTo(N, MachineOpc, VTs, Ops);
8787 }
8788 
8789 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8790                                    EVT VT, SDValue Op1,
8791                                    SDValue Op2) {
8792   SDVTList VTs = getVTList(VT);
8793   SDValue Ops[] = { Op1, Op2 };
8794   return SelectNodeTo(N, MachineOpc, VTs, Ops);
8795 }
8796 
8797 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8798                                    EVT VT, SDValue Op1,
8799                                    SDValue Op2, SDValue Op3) {
8800   SDVTList VTs = getVTList(VT);
8801   SDValue Ops[] = { Op1, Op2, Op3 };
8802   return SelectNodeTo(N, MachineOpc, VTs, Ops);
8803 }
8804 
8805 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8806                                    EVT VT, ArrayRef<SDValue> Ops) {
8807   SDVTList VTs = getVTList(VT);
8808   return SelectNodeTo(N, MachineOpc, VTs, Ops);
8809 }
8810 
8811 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8812                                    EVT VT1, EVT VT2, ArrayRef<SDValue> Ops) {
8813   SDVTList VTs = getVTList(VT1, VT2);
8814   return SelectNodeTo(N, MachineOpc, VTs, Ops);
8815 }
8816 
8817 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8818                                    EVT VT1, EVT VT2) {
8819   SDVTList VTs = getVTList(VT1, VT2);
8820   return SelectNodeTo(N, MachineOpc, VTs, None);
8821 }
8822 
8823 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8824                                    EVT VT1, EVT VT2, EVT VT3,
8825                                    ArrayRef<SDValue> Ops) {
8826   SDVTList VTs = getVTList(VT1, VT2, VT3);
8827   return SelectNodeTo(N, MachineOpc, VTs, Ops);
8828 }
8829 
8830 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8831                                    EVT VT1, EVT VT2,
8832                                    SDValue Op1, SDValue Op2) {
8833   SDVTList VTs = getVTList(VT1, VT2);
8834   SDValue Ops[] = { Op1, Op2 };
8835   return SelectNodeTo(N, MachineOpc, VTs, Ops);
8836 }
8837 
8838 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8839                                    SDVTList VTs,ArrayRef<SDValue> Ops) {
8840   SDNode *New = MorphNodeTo(N, ~MachineOpc, VTs, Ops);
8841   // Reset the NodeID to -1.
8842   New->setNodeId(-1);
8843   if (New != N) {
8844     ReplaceAllUsesWith(N, New);
8845     RemoveDeadNode(N);
8846   }
8847   return New;
8848 }
8849 
8850 /// UpdateSDLocOnMergeSDNode - If the opt level is -O0 then it throws away
8851 /// the line number information on the merged node since it is not possible to
8852 /// preserve the information that operation is associated with multiple lines.
8853 /// This will make the debugger working better at -O0, were there is a higher
8854 /// probability having other instructions associated with that line.
8855 ///
8856 /// For IROrder, we keep the smaller of the two
8857 SDNode *SelectionDAG::UpdateSDLocOnMergeSDNode(SDNode *N, const SDLoc &OLoc) {
8858   DebugLoc NLoc = N->getDebugLoc();
8859   if (NLoc && OptLevel == CodeGenOpt::None && OLoc.getDebugLoc() != NLoc) {
8860     N->setDebugLoc(DebugLoc());
8861   }
8862   unsigned Order = std::min(N->getIROrder(), OLoc.getIROrder());
8863   N->setIROrder(Order);
8864   return N;
8865 }
8866 
8867 /// MorphNodeTo - This *mutates* the specified node to have the specified
8868 /// return type, opcode, and operands.
8869 ///
8870 /// Note that MorphNodeTo returns the resultant node.  If there is already a
8871 /// node of the specified opcode and operands, it returns that node instead of
8872 /// the current one.  Note that the SDLoc need not be the same.
8873 ///
8874 /// Using MorphNodeTo is faster than creating a new node and swapping it in
8875 /// with ReplaceAllUsesWith both because it often avoids allocating a new
8876 /// node, and because it doesn't require CSE recalculation for any of
8877 /// the node's users.
8878 ///
8879 /// However, note that MorphNodeTo recursively deletes dead nodes from the DAG.
8880 /// As a consequence it isn't appropriate to use from within the DAG combiner or
8881 /// the legalizer which maintain worklists that would need to be updated when
8882 /// deleting things.
8883 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
8884                                   SDVTList VTs, ArrayRef<SDValue> Ops) {
8885   // If an identical node already exists, use it.
8886   void *IP = nullptr;
8887   if (VTs.VTs[VTs.NumVTs-1] != MVT::Glue) {
8888     FoldingSetNodeID ID;
8889     AddNodeIDNode(ID, Opc, VTs, Ops);
8890     if (SDNode *ON = FindNodeOrInsertPos(ID, SDLoc(N), IP))
8891       return UpdateSDLocOnMergeSDNode(ON, SDLoc(N));
8892   }
8893 
8894   if (!RemoveNodeFromCSEMaps(N))
8895     IP = nullptr;
8896 
8897   // Start the morphing.
8898   N->NodeType = Opc;
8899   N->ValueList = VTs.VTs;
8900   N->NumValues = VTs.NumVTs;
8901 
8902   // Clear the operands list, updating used nodes to remove this from their
8903   // use list.  Keep track of any operands that become dead as a result.
8904   SmallPtrSet<SDNode*, 16> DeadNodeSet;
8905   for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) {
8906     SDUse &Use = *I++;
8907     SDNode *Used = Use.getNode();
8908     Use.set(SDValue());
8909     if (Used->use_empty())
8910       DeadNodeSet.insert(Used);
8911   }
8912 
8913   // For MachineNode, initialize the memory references information.
8914   if (MachineSDNode *MN = dyn_cast<MachineSDNode>(N))
8915     MN->clearMemRefs();
8916 
8917   // Swap for an appropriately sized array from the recycler.
8918   removeOperands(N);
8919   createOperands(N, Ops);
8920 
8921   // Delete any nodes that are still dead after adding the uses for the
8922   // new operands.
8923   if (!DeadNodeSet.empty()) {
8924     SmallVector<SDNode *, 16> DeadNodes;
8925     for (SDNode *N : DeadNodeSet)
8926       if (N->use_empty())
8927         DeadNodes.push_back(N);
8928     RemoveDeadNodes(DeadNodes);
8929   }
8930 
8931   if (IP)
8932     CSEMap.InsertNode(N, IP);   // Memoize the new node.
8933   return N;
8934 }
8935 
8936 SDNode* SelectionDAG::mutateStrictFPToFP(SDNode *Node) {
8937   unsigned OrigOpc = Node->getOpcode();
8938   unsigned NewOpc;
8939   switch (OrigOpc) {
8940   default:
8941     llvm_unreachable("mutateStrictFPToFP called with unexpected opcode!");
8942 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN)               \
8943   case ISD::STRICT_##DAGN: NewOpc = ISD::DAGN; break;
8944 #define CMP_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN)               \
8945   case ISD::STRICT_##DAGN: NewOpc = ISD::SETCC; break;
8946 #include "llvm/IR/ConstrainedOps.def"
8947   }
8948 
8949   assert(Node->getNumValues() == 2 && "Unexpected number of results!");
8950 
8951   // We're taking this node out of the chain, so we need to re-link things.
8952   SDValue InputChain = Node->getOperand(0);
8953   SDValue OutputChain = SDValue(Node, 1);
8954   ReplaceAllUsesOfValueWith(OutputChain, InputChain);
8955 
8956   SmallVector<SDValue, 3> Ops;
8957   for (unsigned i = 1, e = Node->getNumOperands(); i != e; ++i)
8958     Ops.push_back(Node->getOperand(i));
8959 
8960   SDVTList VTs = getVTList(Node->getValueType(0));
8961   SDNode *Res = MorphNodeTo(Node, NewOpc, VTs, Ops);
8962 
8963   // MorphNodeTo can operate in two ways: if an existing node with the
8964   // specified operands exists, it can just return it.  Otherwise, it
8965   // updates the node in place to have the requested operands.
8966   if (Res == Node) {
8967     // If we updated the node in place, reset the node ID.  To the isel,
8968     // this should be just like a newly allocated machine node.
8969     Res->setNodeId(-1);
8970   } else {
8971     ReplaceAllUsesWith(Node, Res);
8972     RemoveDeadNode(Node);
8973   }
8974 
8975   return Res;
8976 }
8977 
8978 /// getMachineNode - These are used for target selectors to create a new node
8979 /// with specified return type(s), MachineInstr opcode, and operands.
8980 ///
8981 /// Note that getMachineNode returns the resultant node.  If there is already a
8982 /// node of the specified opcode and operands, it returns that node instead of
8983 /// the current one.
8984 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
8985                                             EVT VT) {
8986   SDVTList VTs = getVTList(VT);
8987   return getMachineNode(Opcode, dl, VTs, None);
8988 }
8989 
8990 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
8991                                             EVT VT, SDValue Op1) {
8992   SDVTList VTs = getVTList(VT);
8993   SDValue Ops[] = { Op1 };
8994   return getMachineNode(Opcode, dl, VTs, Ops);
8995 }
8996 
8997 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
8998                                             EVT VT, SDValue Op1, SDValue Op2) {
8999   SDVTList VTs = getVTList(VT);
9000   SDValue Ops[] = { Op1, Op2 };
9001   return getMachineNode(Opcode, dl, VTs, Ops);
9002 }
9003 
9004 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9005                                             EVT VT, SDValue Op1, SDValue Op2,
9006                                             SDValue Op3) {
9007   SDVTList VTs = getVTList(VT);
9008   SDValue Ops[] = { Op1, Op2, Op3 };
9009   return getMachineNode(Opcode, dl, VTs, Ops);
9010 }
9011 
9012 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9013                                             EVT VT, ArrayRef<SDValue> Ops) {
9014   SDVTList VTs = getVTList(VT);
9015   return getMachineNode(Opcode, dl, VTs, Ops);
9016 }
9017 
9018 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9019                                             EVT VT1, EVT VT2, SDValue Op1,
9020                                             SDValue Op2) {
9021   SDVTList VTs = getVTList(VT1, VT2);
9022   SDValue Ops[] = { Op1, Op2 };
9023   return getMachineNode(Opcode, dl, VTs, Ops);
9024 }
9025 
9026 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9027                                             EVT VT1, EVT VT2, SDValue Op1,
9028                                             SDValue Op2, SDValue Op3) {
9029   SDVTList VTs = getVTList(VT1, VT2);
9030   SDValue Ops[] = { Op1, Op2, Op3 };
9031   return getMachineNode(Opcode, dl, VTs, Ops);
9032 }
9033 
9034 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9035                                             EVT VT1, EVT VT2,
9036                                             ArrayRef<SDValue> Ops) {
9037   SDVTList VTs = getVTList(VT1, VT2);
9038   return getMachineNode(Opcode, dl, VTs, Ops);
9039 }
9040 
9041 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9042                                             EVT VT1, EVT VT2, EVT VT3,
9043                                             SDValue Op1, SDValue Op2) {
9044   SDVTList VTs = getVTList(VT1, VT2, VT3);
9045   SDValue Ops[] = { Op1, Op2 };
9046   return getMachineNode(Opcode, dl, VTs, Ops);
9047 }
9048 
9049 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9050                                             EVT VT1, EVT VT2, EVT VT3,
9051                                             SDValue Op1, SDValue Op2,
9052                                             SDValue Op3) {
9053   SDVTList VTs = getVTList(VT1, VT2, VT3);
9054   SDValue Ops[] = { Op1, Op2, Op3 };
9055   return getMachineNode(Opcode, dl, VTs, Ops);
9056 }
9057 
9058 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9059                                             EVT VT1, EVT VT2, EVT VT3,
9060                                             ArrayRef<SDValue> Ops) {
9061   SDVTList VTs = getVTList(VT1, VT2, VT3);
9062   return getMachineNode(Opcode, dl, VTs, Ops);
9063 }
9064 
9065 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9066                                             ArrayRef<EVT> ResultTys,
9067                                             ArrayRef<SDValue> Ops) {
9068   SDVTList VTs = getVTList(ResultTys);
9069   return getMachineNode(Opcode, dl, VTs, Ops);
9070 }
9071 
9072 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &DL,
9073                                             SDVTList VTs,
9074                                             ArrayRef<SDValue> Ops) {
9075   bool DoCSE = VTs.VTs[VTs.NumVTs-1] != MVT::Glue;
9076   MachineSDNode *N;
9077   void *IP = nullptr;
9078 
9079   if (DoCSE) {
9080     FoldingSetNodeID ID;
9081     AddNodeIDNode(ID, ~Opcode, VTs, Ops);
9082     IP = nullptr;
9083     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
9084       return cast<MachineSDNode>(UpdateSDLocOnMergeSDNode(E, DL));
9085     }
9086   }
9087 
9088   // Allocate a new MachineSDNode.
9089   N = newSDNode<MachineSDNode>(~Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
9090   createOperands(N, Ops);
9091 
9092   if (DoCSE)
9093     CSEMap.InsertNode(N, IP);
9094 
9095   InsertNode(N);
9096   NewSDValueDbgMsg(SDValue(N, 0), "Creating new machine node: ", this);
9097   return N;
9098 }
9099 
9100 /// getTargetExtractSubreg - A convenience function for creating
9101 /// TargetOpcode::EXTRACT_SUBREG nodes.
9102 SDValue SelectionDAG::getTargetExtractSubreg(int SRIdx, const SDLoc &DL, EVT VT,
9103                                              SDValue Operand) {
9104   SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32);
9105   SDNode *Subreg = getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL,
9106                                   VT, Operand, SRIdxVal);
9107   return SDValue(Subreg, 0);
9108 }
9109 
9110 /// getTargetInsertSubreg - A convenience function for creating
9111 /// TargetOpcode::INSERT_SUBREG nodes.
9112 SDValue SelectionDAG::getTargetInsertSubreg(int SRIdx, const SDLoc &DL, EVT VT,
9113                                             SDValue Operand, SDValue Subreg) {
9114   SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32);
9115   SDNode *Result = getMachineNode(TargetOpcode::INSERT_SUBREG, DL,
9116                                   VT, Operand, Subreg, SRIdxVal);
9117   return SDValue(Result, 0);
9118 }
9119 
9120 /// getNodeIfExists - Get the specified node if it's already available, or
9121 /// else return NULL.
9122 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList,
9123                                       ArrayRef<SDValue> Ops) {
9124   SDNodeFlags Flags;
9125   if (Inserter)
9126     Flags = Inserter->getFlags();
9127   return getNodeIfExists(Opcode, VTList, Ops, Flags);
9128 }
9129 
9130 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList,
9131                                       ArrayRef<SDValue> Ops,
9132                                       const SDNodeFlags Flags) {
9133   if (VTList.VTs[VTList.NumVTs - 1] != MVT::Glue) {
9134     FoldingSetNodeID ID;
9135     AddNodeIDNode(ID, Opcode, VTList, Ops);
9136     void *IP = nullptr;
9137     if (SDNode *E = FindNodeOrInsertPos(ID, SDLoc(), IP)) {
9138       E->intersectFlagsWith(Flags);
9139       return E;
9140     }
9141   }
9142   return nullptr;
9143 }
9144 
9145 /// doesNodeExist - Check if a node exists without modifying its flags.
9146 bool SelectionDAG::doesNodeExist(unsigned Opcode, SDVTList VTList,
9147                                  ArrayRef<SDValue> Ops) {
9148   if (VTList.VTs[VTList.NumVTs - 1] != MVT::Glue) {
9149     FoldingSetNodeID ID;
9150     AddNodeIDNode(ID, Opcode, VTList, Ops);
9151     void *IP = nullptr;
9152     if (FindNodeOrInsertPos(ID, SDLoc(), IP))
9153       return true;
9154   }
9155   return false;
9156 }
9157 
9158 /// getDbgValue - Creates a SDDbgValue node.
9159 ///
9160 /// SDNode
9161 SDDbgValue *SelectionDAG::getDbgValue(DIVariable *Var, DIExpression *Expr,
9162                                       SDNode *N, unsigned R, bool IsIndirect,
9163                                       const DebugLoc &DL, unsigned O) {
9164   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
9165          "Expected inlined-at fields to agree");
9166   return new (DbgInfo->getAlloc())
9167       SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromNode(N, R),
9168                  {}, IsIndirect, DL, O,
9169                  /*IsVariadic=*/false);
9170 }
9171 
9172 /// Constant
9173 SDDbgValue *SelectionDAG::getConstantDbgValue(DIVariable *Var,
9174                                               DIExpression *Expr,
9175                                               const Value *C,
9176                                               const DebugLoc &DL, unsigned O) {
9177   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
9178          "Expected inlined-at fields to agree");
9179   return new (DbgInfo->getAlloc())
9180       SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromConst(C), {},
9181                  /*IsIndirect=*/false, DL, O,
9182                  /*IsVariadic=*/false);
9183 }
9184 
9185 /// FrameIndex
9186 SDDbgValue *SelectionDAG::getFrameIndexDbgValue(DIVariable *Var,
9187                                                 DIExpression *Expr, unsigned FI,
9188                                                 bool IsIndirect,
9189                                                 const DebugLoc &DL,
9190                                                 unsigned O) {
9191   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
9192          "Expected inlined-at fields to agree");
9193   return getFrameIndexDbgValue(Var, Expr, FI, {}, IsIndirect, DL, O);
9194 }
9195 
9196 /// FrameIndex with dependencies
9197 SDDbgValue *SelectionDAG::getFrameIndexDbgValue(DIVariable *Var,
9198                                                 DIExpression *Expr, unsigned FI,
9199                                                 ArrayRef<SDNode *> Dependencies,
9200                                                 bool IsIndirect,
9201                                                 const DebugLoc &DL,
9202                                                 unsigned O) {
9203   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
9204          "Expected inlined-at fields to agree");
9205   return new (DbgInfo->getAlloc())
9206       SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromFrameIdx(FI),
9207                  Dependencies, IsIndirect, DL, O,
9208                  /*IsVariadic=*/false);
9209 }
9210 
9211 /// VReg
9212 SDDbgValue *SelectionDAG::getVRegDbgValue(DIVariable *Var, DIExpression *Expr,
9213                                           unsigned VReg, bool IsIndirect,
9214                                           const DebugLoc &DL, unsigned O) {
9215   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
9216          "Expected inlined-at fields to agree");
9217   return new (DbgInfo->getAlloc())
9218       SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromVReg(VReg),
9219                  {}, IsIndirect, DL, O,
9220                  /*IsVariadic=*/false);
9221 }
9222 
9223 SDDbgValue *SelectionDAG::getDbgValueList(DIVariable *Var, DIExpression *Expr,
9224                                           ArrayRef<SDDbgOperand> Locs,
9225                                           ArrayRef<SDNode *> Dependencies,
9226                                           bool IsIndirect, const DebugLoc &DL,
9227                                           unsigned O, bool IsVariadic) {
9228   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
9229          "Expected inlined-at fields to agree");
9230   return new (DbgInfo->getAlloc())
9231       SDDbgValue(DbgInfo->getAlloc(), Var, Expr, Locs, Dependencies, IsIndirect,
9232                  DL, O, IsVariadic);
9233 }
9234 
9235 void SelectionDAG::transferDbgValues(SDValue From, SDValue To,
9236                                      unsigned OffsetInBits, unsigned SizeInBits,
9237                                      bool InvalidateDbg) {
9238   SDNode *FromNode = From.getNode();
9239   SDNode *ToNode = To.getNode();
9240   assert(FromNode && ToNode && "Can't modify dbg values");
9241 
9242   // PR35338
9243   // TODO: assert(From != To && "Redundant dbg value transfer");
9244   // TODO: assert(FromNode != ToNode && "Intranode dbg value transfer");
9245   if (From == To || FromNode == ToNode)
9246     return;
9247 
9248   if (!FromNode->getHasDebugValue())
9249     return;
9250 
9251   SDDbgOperand FromLocOp =
9252       SDDbgOperand::fromNode(From.getNode(), From.getResNo());
9253   SDDbgOperand ToLocOp = SDDbgOperand::fromNode(To.getNode(), To.getResNo());
9254 
9255   SmallVector<SDDbgValue *, 2> ClonedDVs;
9256   for (SDDbgValue *Dbg : GetDbgValues(FromNode)) {
9257     if (Dbg->isInvalidated())
9258       continue;
9259 
9260     // TODO: assert(!Dbg->isInvalidated() && "Transfer of invalid dbg value");
9261 
9262     // Create a new location ops vector that is equal to the old vector, but
9263     // with each instance of FromLocOp replaced with ToLocOp.
9264     bool Changed = false;
9265     auto NewLocOps = Dbg->copyLocationOps();
9266     std::replace_if(
9267         NewLocOps.begin(), NewLocOps.end(),
9268         [&Changed, FromLocOp](const SDDbgOperand &Op) {
9269           bool Match = Op == FromLocOp;
9270           Changed |= Match;
9271           return Match;
9272         },
9273         ToLocOp);
9274     // Ignore this SDDbgValue if we didn't find a matching location.
9275     if (!Changed)
9276       continue;
9277 
9278     DIVariable *Var = Dbg->getVariable();
9279     auto *Expr = Dbg->getExpression();
9280     // If a fragment is requested, update the expression.
9281     if (SizeInBits) {
9282       // When splitting a larger (e.g., sign-extended) value whose
9283       // lower bits are described with an SDDbgValue, do not attempt
9284       // to transfer the SDDbgValue to the upper bits.
9285       if (auto FI = Expr->getFragmentInfo())
9286         if (OffsetInBits + SizeInBits > FI->SizeInBits)
9287           continue;
9288       auto Fragment = DIExpression::createFragmentExpression(Expr, OffsetInBits,
9289                                                              SizeInBits);
9290       if (!Fragment)
9291         continue;
9292       Expr = *Fragment;
9293     }
9294 
9295     auto AdditionalDependencies = Dbg->getAdditionalDependencies();
9296     // Clone the SDDbgValue and move it to To.
9297     SDDbgValue *Clone = getDbgValueList(
9298         Var, Expr, NewLocOps, AdditionalDependencies, Dbg->isIndirect(),
9299         Dbg->getDebugLoc(), std::max(ToNode->getIROrder(), Dbg->getOrder()),
9300         Dbg->isVariadic());
9301     ClonedDVs.push_back(Clone);
9302 
9303     if (InvalidateDbg) {
9304       // Invalidate value and indicate the SDDbgValue should not be emitted.
9305       Dbg->setIsInvalidated();
9306       Dbg->setIsEmitted();
9307     }
9308   }
9309 
9310   for (SDDbgValue *Dbg : ClonedDVs) {
9311     assert(is_contained(Dbg->getSDNodes(), ToNode) &&
9312            "Transferred DbgValues should depend on the new SDNode");
9313     AddDbgValue(Dbg, false);
9314   }
9315 }
9316 
9317 void SelectionDAG::salvageDebugInfo(SDNode &N) {
9318   if (!N.getHasDebugValue())
9319     return;
9320 
9321   SmallVector<SDDbgValue *, 2> ClonedDVs;
9322   for (auto DV : GetDbgValues(&N)) {
9323     if (DV->isInvalidated())
9324       continue;
9325     switch (N.getOpcode()) {
9326     default:
9327       break;
9328     case ISD::ADD:
9329       SDValue N0 = N.getOperand(0);
9330       SDValue N1 = N.getOperand(1);
9331       if (!isConstantIntBuildVectorOrConstantInt(N0) &&
9332           isConstantIntBuildVectorOrConstantInt(N1)) {
9333         uint64_t Offset = N.getConstantOperandVal(1);
9334 
9335         // Rewrite an ADD constant node into a DIExpression. Since we are
9336         // performing arithmetic to compute the variable's *value* in the
9337         // DIExpression, we need to mark the expression with a
9338         // DW_OP_stack_value.
9339         auto *DIExpr = DV->getExpression();
9340         auto NewLocOps = DV->copyLocationOps();
9341         bool Changed = false;
9342         for (size_t i = 0; i < NewLocOps.size(); ++i) {
9343           // We're not given a ResNo to compare against because the whole
9344           // node is going away. We know that any ISD::ADD only has one
9345           // result, so we can assume any node match is using the result.
9346           if (NewLocOps[i].getKind() != SDDbgOperand::SDNODE ||
9347               NewLocOps[i].getSDNode() != &N)
9348             continue;
9349           NewLocOps[i] = SDDbgOperand::fromNode(N0.getNode(), N0.getResNo());
9350           SmallVector<uint64_t, 3> ExprOps;
9351           DIExpression::appendOffset(ExprOps, Offset);
9352           DIExpr = DIExpression::appendOpsToArg(DIExpr, ExprOps, i, true);
9353           Changed = true;
9354         }
9355         (void)Changed;
9356         assert(Changed && "Salvage target doesn't use N");
9357 
9358         auto AdditionalDependencies = DV->getAdditionalDependencies();
9359         SDDbgValue *Clone = getDbgValueList(DV->getVariable(), DIExpr,
9360                                             NewLocOps, AdditionalDependencies,
9361                                             DV->isIndirect(), DV->getDebugLoc(),
9362                                             DV->getOrder(), DV->isVariadic());
9363         ClonedDVs.push_back(Clone);
9364         DV->setIsInvalidated();
9365         DV->setIsEmitted();
9366         LLVM_DEBUG(dbgs() << "SALVAGE: Rewriting";
9367                    N0.getNode()->dumprFull(this);
9368                    dbgs() << " into " << *DIExpr << '\n');
9369       }
9370     }
9371   }
9372 
9373   for (SDDbgValue *Dbg : ClonedDVs) {
9374     assert(!Dbg->getSDNodes().empty() &&
9375            "Salvaged DbgValue should depend on a new SDNode");
9376     AddDbgValue(Dbg, false);
9377   }
9378 }
9379 
9380 /// Creates a SDDbgLabel node.
9381 SDDbgLabel *SelectionDAG::getDbgLabel(DILabel *Label,
9382                                       const DebugLoc &DL, unsigned O) {
9383   assert(cast<DILabel>(Label)->isValidLocationForIntrinsic(DL) &&
9384          "Expected inlined-at fields to agree");
9385   return new (DbgInfo->getAlloc()) SDDbgLabel(Label, DL, O);
9386 }
9387 
9388 namespace {
9389 
9390 /// RAUWUpdateListener - Helper for ReplaceAllUsesWith - When the node
9391 /// pointed to by a use iterator is deleted, increment the use iterator
9392 /// so that it doesn't dangle.
9393 ///
9394 class RAUWUpdateListener : public SelectionDAG::DAGUpdateListener {
9395   SDNode::use_iterator &UI;
9396   SDNode::use_iterator &UE;
9397 
9398   void NodeDeleted(SDNode *N, SDNode *E) override {
9399     // Increment the iterator as needed.
9400     while (UI != UE && N == *UI)
9401       ++UI;
9402   }
9403 
9404 public:
9405   RAUWUpdateListener(SelectionDAG &d,
9406                      SDNode::use_iterator &ui,
9407                      SDNode::use_iterator &ue)
9408     : SelectionDAG::DAGUpdateListener(d), UI(ui), UE(ue) {}
9409 };
9410 
9411 } // end anonymous namespace
9412 
9413 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
9414 /// This can cause recursive merging of nodes in the DAG.
9415 ///
9416 /// This version assumes From has a single result value.
9417 ///
9418 void SelectionDAG::ReplaceAllUsesWith(SDValue FromN, SDValue To) {
9419   SDNode *From = FromN.getNode();
9420   assert(From->getNumValues() == 1 && FromN.getResNo() == 0 &&
9421          "Cannot replace with this method!");
9422   assert(From != To.getNode() && "Cannot replace uses of with self");
9423 
9424   // Preserve Debug Values
9425   transferDbgValues(FromN, To);
9426 
9427   // Iterate over all the existing uses of From. New uses will be added
9428   // to the beginning of the use list, which we avoid visiting.
9429   // This specifically avoids visiting uses of From that arise while the
9430   // replacement is happening, because any such uses would be the result
9431   // of CSE: If an existing node looks like From after one of its operands
9432   // is replaced by To, we don't want to replace of all its users with To
9433   // too. See PR3018 for more info.
9434   SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
9435   RAUWUpdateListener Listener(*this, UI, UE);
9436   while (UI != UE) {
9437     SDNode *User = *UI;
9438 
9439     // This node is about to morph, remove its old self from the CSE maps.
9440     RemoveNodeFromCSEMaps(User);
9441 
9442     // A user can appear in a use list multiple times, and when this
9443     // happens the uses are usually next to each other in the list.
9444     // To help reduce the number of CSE recomputations, process all
9445     // the uses of this user that we can find this way.
9446     do {
9447       SDUse &Use = UI.getUse();
9448       ++UI;
9449       Use.set(To);
9450       if (To->isDivergent() != From->isDivergent())
9451         updateDivergence(User);
9452     } while (UI != UE && *UI == User);
9453     // Now that we have modified User, add it back to the CSE maps.  If it
9454     // already exists there, recursively merge the results together.
9455     AddModifiedNodeToCSEMaps(User);
9456   }
9457 
9458   // If we just RAUW'd the root, take note.
9459   if (FromN == getRoot())
9460     setRoot(To);
9461 }
9462 
9463 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
9464 /// This can cause recursive merging of nodes in the DAG.
9465 ///
9466 /// This version assumes that for each value of From, there is a
9467 /// corresponding value in To in the same position with the same type.
9468 ///
9469 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, SDNode *To) {
9470 #ifndef NDEBUG
9471   for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
9472     assert((!From->hasAnyUseOfValue(i) ||
9473             From->getValueType(i) == To->getValueType(i)) &&
9474            "Cannot use this version of ReplaceAllUsesWith!");
9475 #endif
9476 
9477   // Handle the trivial case.
9478   if (From == To)
9479     return;
9480 
9481   // Preserve Debug Info. Only do this if there's a use.
9482   for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
9483     if (From->hasAnyUseOfValue(i)) {
9484       assert((i < To->getNumValues()) && "Invalid To location");
9485       transferDbgValues(SDValue(From, i), SDValue(To, i));
9486     }
9487 
9488   // Iterate over just the existing users of From. See the comments in
9489   // the ReplaceAllUsesWith above.
9490   SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
9491   RAUWUpdateListener Listener(*this, UI, UE);
9492   while (UI != UE) {
9493     SDNode *User = *UI;
9494 
9495     // This node is about to morph, remove its old self from the CSE maps.
9496     RemoveNodeFromCSEMaps(User);
9497 
9498     // A user can appear in a use list multiple times, and when this
9499     // happens the uses are usually next to each other in the list.
9500     // To help reduce the number of CSE recomputations, process all
9501     // the uses of this user that we can find this way.
9502     do {
9503       SDUse &Use = UI.getUse();
9504       ++UI;
9505       Use.setNode(To);
9506       if (To->isDivergent() != From->isDivergent())
9507         updateDivergence(User);
9508     } while (UI != UE && *UI == User);
9509 
9510     // Now that we have modified User, add it back to the CSE maps.  If it
9511     // already exists there, recursively merge the results together.
9512     AddModifiedNodeToCSEMaps(User);
9513   }
9514 
9515   // If we just RAUW'd the root, take note.
9516   if (From == getRoot().getNode())
9517     setRoot(SDValue(To, getRoot().getResNo()));
9518 }
9519 
9520 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
9521 /// This can cause recursive merging of nodes in the DAG.
9522 ///
9523 /// This version can replace From with any result values.  To must match the
9524 /// number and types of values returned by From.
9525 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, const SDValue *To) {
9526   if (From->getNumValues() == 1)  // Handle the simple case efficiently.
9527     return ReplaceAllUsesWith(SDValue(From, 0), To[0]);
9528 
9529   // Preserve Debug Info.
9530   for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
9531     transferDbgValues(SDValue(From, i), To[i]);
9532 
9533   // Iterate over just the existing users of From. See the comments in
9534   // the ReplaceAllUsesWith above.
9535   SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
9536   RAUWUpdateListener Listener(*this, UI, UE);
9537   while (UI != UE) {
9538     SDNode *User = *UI;
9539 
9540     // This node is about to morph, remove its old self from the CSE maps.
9541     RemoveNodeFromCSEMaps(User);
9542 
9543     // A user can appear in a use list multiple times, and when this happens the
9544     // uses are usually next to each other in the list.  To help reduce the
9545     // number of CSE and divergence recomputations, process all the uses of this
9546     // user that we can find this way.
9547     bool To_IsDivergent = false;
9548     do {
9549       SDUse &Use = UI.getUse();
9550       const SDValue &ToOp = To[Use.getResNo()];
9551       ++UI;
9552       Use.set(ToOp);
9553       To_IsDivergent |= ToOp->isDivergent();
9554     } while (UI != UE && *UI == User);
9555 
9556     if (To_IsDivergent != From->isDivergent())
9557       updateDivergence(User);
9558 
9559     // Now that we have modified User, add it back to the CSE maps.  If it
9560     // already exists there, recursively merge the results together.
9561     AddModifiedNodeToCSEMaps(User);
9562   }
9563 
9564   // If we just RAUW'd the root, take note.
9565   if (From == getRoot().getNode())
9566     setRoot(SDValue(To[getRoot().getResNo()]));
9567 }
9568 
9569 /// ReplaceAllUsesOfValueWith - Replace any uses of From with To, leaving
9570 /// uses of other values produced by From.getNode() alone.  The Deleted
9571 /// vector is handled the same way as for ReplaceAllUsesWith.
9572 void SelectionDAG::ReplaceAllUsesOfValueWith(SDValue From, SDValue To){
9573   // Handle the really simple, really trivial case efficiently.
9574   if (From == To) return;
9575 
9576   // Handle the simple, trivial, case efficiently.
9577   if (From.getNode()->getNumValues() == 1) {
9578     ReplaceAllUsesWith(From, To);
9579     return;
9580   }
9581 
9582   // Preserve Debug Info.
9583   transferDbgValues(From, To);
9584 
9585   // Iterate over just the existing users of From. See the comments in
9586   // the ReplaceAllUsesWith above.
9587   SDNode::use_iterator UI = From.getNode()->use_begin(),
9588                        UE = From.getNode()->use_end();
9589   RAUWUpdateListener Listener(*this, UI, UE);
9590   while (UI != UE) {
9591     SDNode *User = *UI;
9592     bool UserRemovedFromCSEMaps = false;
9593 
9594     // A user can appear in a use list multiple times, and when this
9595     // happens the uses are usually next to each other in the list.
9596     // To help reduce the number of CSE recomputations, process all
9597     // the uses of this user that we can find this way.
9598     do {
9599       SDUse &Use = UI.getUse();
9600 
9601       // Skip uses of different values from the same node.
9602       if (Use.getResNo() != From.getResNo()) {
9603         ++UI;
9604         continue;
9605       }
9606 
9607       // If this node hasn't been modified yet, it's still in the CSE maps,
9608       // so remove its old self from the CSE maps.
9609       if (!UserRemovedFromCSEMaps) {
9610         RemoveNodeFromCSEMaps(User);
9611         UserRemovedFromCSEMaps = true;
9612       }
9613 
9614       ++UI;
9615       Use.set(To);
9616       if (To->isDivergent() != From->isDivergent())
9617         updateDivergence(User);
9618     } while (UI != UE && *UI == User);
9619     // We are iterating over all uses of the From node, so if a use
9620     // doesn't use the specific value, no changes are made.
9621     if (!UserRemovedFromCSEMaps)
9622       continue;
9623 
9624     // Now that we have modified User, add it back to the CSE maps.  If it
9625     // already exists there, recursively merge the results together.
9626     AddModifiedNodeToCSEMaps(User);
9627   }
9628 
9629   // If we just RAUW'd the root, take note.
9630   if (From == getRoot())
9631     setRoot(To);
9632 }
9633 
9634 namespace {
9635 
9636   /// UseMemo - This class is used by SelectionDAG::ReplaceAllUsesOfValuesWith
9637   /// to record information about a use.
9638   struct UseMemo {
9639     SDNode *User;
9640     unsigned Index;
9641     SDUse *Use;
9642   };
9643 
9644   /// operator< - Sort Memos by User.
9645   bool operator<(const UseMemo &L, const UseMemo &R) {
9646     return (intptr_t)L.User < (intptr_t)R.User;
9647   }
9648 
9649 } // end anonymous namespace
9650 
9651 bool SelectionDAG::calculateDivergence(SDNode *N) {
9652   if (TLI->isSDNodeAlwaysUniform(N)) {
9653     assert(!TLI->isSDNodeSourceOfDivergence(N, FLI, DA) &&
9654            "Conflicting divergence information!");
9655     return false;
9656   }
9657   if (TLI->isSDNodeSourceOfDivergence(N, FLI, DA))
9658     return true;
9659   for (auto &Op : N->ops()) {
9660     if (Op.Val.getValueType() != MVT::Other && Op.getNode()->isDivergent())
9661       return true;
9662   }
9663   return false;
9664 }
9665 
9666 void SelectionDAG::updateDivergence(SDNode *N) {
9667   SmallVector<SDNode *, 16> Worklist(1, N);
9668   do {
9669     N = Worklist.pop_back_val();
9670     bool IsDivergent = calculateDivergence(N);
9671     if (N->SDNodeBits.IsDivergent != IsDivergent) {
9672       N->SDNodeBits.IsDivergent = IsDivergent;
9673       llvm::append_range(Worklist, N->uses());
9674     }
9675   } while (!Worklist.empty());
9676 }
9677 
9678 void SelectionDAG::CreateTopologicalOrder(std::vector<SDNode *> &Order) {
9679   DenseMap<SDNode *, unsigned> Degree;
9680   Order.reserve(AllNodes.size());
9681   for (auto &N : allnodes()) {
9682     unsigned NOps = N.getNumOperands();
9683     Degree[&N] = NOps;
9684     if (0 == NOps)
9685       Order.push_back(&N);
9686   }
9687   for (size_t I = 0; I != Order.size(); ++I) {
9688     SDNode *N = Order[I];
9689     for (auto U : N->uses()) {
9690       unsigned &UnsortedOps = Degree[U];
9691       if (0 == --UnsortedOps)
9692         Order.push_back(U);
9693     }
9694   }
9695 }
9696 
9697 #ifndef NDEBUG
9698 void SelectionDAG::VerifyDAGDivergence() {
9699   std::vector<SDNode *> TopoOrder;
9700   CreateTopologicalOrder(TopoOrder);
9701   for (auto *N : TopoOrder) {
9702     assert(calculateDivergence(N) == N->isDivergent() &&
9703            "Divergence bit inconsistency detected");
9704   }
9705 }
9706 #endif
9707 
9708 /// ReplaceAllUsesOfValuesWith - Replace any uses of From with To, leaving
9709 /// uses of other values produced by From.getNode() alone.  The same value
9710 /// may appear in both the From and To list.  The Deleted vector is
9711 /// handled the same way as for ReplaceAllUsesWith.
9712 void SelectionDAG::ReplaceAllUsesOfValuesWith(const SDValue *From,
9713                                               const SDValue *To,
9714                                               unsigned Num){
9715   // Handle the simple, trivial case efficiently.
9716   if (Num == 1)
9717     return ReplaceAllUsesOfValueWith(*From, *To);
9718 
9719   transferDbgValues(*From, *To);
9720 
9721   // Read up all the uses and make records of them. This helps
9722   // processing new uses that are introduced during the
9723   // replacement process.
9724   SmallVector<UseMemo, 4> Uses;
9725   for (unsigned i = 0; i != Num; ++i) {
9726     unsigned FromResNo = From[i].getResNo();
9727     SDNode *FromNode = From[i].getNode();
9728     for (SDNode::use_iterator UI = FromNode->use_begin(),
9729          E = FromNode->use_end(); UI != E; ++UI) {
9730       SDUse &Use = UI.getUse();
9731       if (Use.getResNo() == FromResNo) {
9732         UseMemo Memo = { *UI, i, &Use };
9733         Uses.push_back(Memo);
9734       }
9735     }
9736   }
9737 
9738   // Sort the uses, so that all the uses from a given User are together.
9739   llvm::sort(Uses);
9740 
9741   for (unsigned UseIndex = 0, UseIndexEnd = Uses.size();
9742        UseIndex != UseIndexEnd; ) {
9743     // We know that this user uses some value of From.  If it is the right
9744     // value, update it.
9745     SDNode *User = Uses[UseIndex].User;
9746 
9747     // This node is about to morph, remove its old self from the CSE maps.
9748     RemoveNodeFromCSEMaps(User);
9749 
9750     // The Uses array is sorted, so all the uses for a given User
9751     // are next to each other in the list.
9752     // To help reduce the number of CSE recomputations, process all
9753     // the uses of this user that we can find this way.
9754     do {
9755       unsigned i = Uses[UseIndex].Index;
9756       SDUse &Use = *Uses[UseIndex].Use;
9757       ++UseIndex;
9758 
9759       Use.set(To[i]);
9760     } while (UseIndex != UseIndexEnd && Uses[UseIndex].User == User);
9761 
9762     // Now that we have modified User, add it back to the CSE maps.  If it
9763     // already exists there, recursively merge the results together.
9764     AddModifiedNodeToCSEMaps(User);
9765   }
9766 }
9767 
9768 /// AssignTopologicalOrder - Assign a unique node id for each node in the DAG
9769 /// based on their topological order. It returns the maximum id and a vector
9770 /// of the SDNodes* in assigned order by reference.
9771 unsigned SelectionDAG::AssignTopologicalOrder() {
9772   unsigned DAGSize = 0;
9773 
9774   // SortedPos tracks the progress of the algorithm. Nodes before it are
9775   // sorted, nodes after it are unsorted. When the algorithm completes
9776   // it is at the end of the list.
9777   allnodes_iterator SortedPos = allnodes_begin();
9778 
9779   // Visit all the nodes. Move nodes with no operands to the front of
9780   // the list immediately. Annotate nodes that do have operands with their
9781   // operand count. Before we do this, the Node Id fields of the nodes
9782   // may contain arbitrary values. After, the Node Id fields for nodes
9783   // before SortedPos will contain the topological sort index, and the
9784   // Node Id fields for nodes At SortedPos and after will contain the
9785   // count of outstanding operands.
9786   for (SDNode &N : llvm::make_early_inc_range(allnodes())) {
9787     checkForCycles(&N, this);
9788     unsigned Degree = N.getNumOperands();
9789     if (Degree == 0) {
9790       // A node with no uses, add it to the result array immediately.
9791       N.setNodeId(DAGSize++);
9792       allnodes_iterator Q(&N);
9793       if (Q != SortedPos)
9794         SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(Q));
9795       assert(SortedPos != AllNodes.end() && "Overran node list");
9796       ++SortedPos;
9797     } else {
9798       // Temporarily use the Node Id as scratch space for the degree count.
9799       N.setNodeId(Degree);
9800     }
9801   }
9802 
9803   // Visit all the nodes. As we iterate, move nodes into sorted order,
9804   // such that by the time the end is reached all nodes will be sorted.
9805   for (SDNode &Node : allnodes()) {
9806     SDNode *N = &Node;
9807     checkForCycles(N, this);
9808     // N is in sorted position, so all its uses have one less operand
9809     // that needs to be sorted.
9810     for (SDNode *P : N->uses()) {
9811       unsigned Degree = P->getNodeId();
9812       assert(Degree != 0 && "Invalid node degree");
9813       --Degree;
9814       if (Degree == 0) {
9815         // All of P's operands are sorted, so P may sorted now.
9816         P->setNodeId(DAGSize++);
9817         if (P->getIterator() != SortedPos)
9818           SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(P));
9819         assert(SortedPos != AllNodes.end() && "Overran node list");
9820         ++SortedPos;
9821       } else {
9822         // Update P's outstanding operand count.
9823         P->setNodeId(Degree);
9824       }
9825     }
9826     if (Node.getIterator() == SortedPos) {
9827 #ifndef NDEBUG
9828       allnodes_iterator I(N);
9829       SDNode *S = &*++I;
9830       dbgs() << "Overran sorted position:\n";
9831       S->dumprFull(this); dbgs() << "\n";
9832       dbgs() << "Checking if this is due to cycles\n";
9833       checkForCycles(this, true);
9834 #endif
9835       llvm_unreachable(nullptr);
9836     }
9837   }
9838 
9839   assert(SortedPos == AllNodes.end() &&
9840          "Topological sort incomplete!");
9841   assert(AllNodes.front().getOpcode() == ISD::EntryToken &&
9842          "First node in topological sort is not the entry token!");
9843   assert(AllNodes.front().getNodeId() == 0 &&
9844          "First node in topological sort has non-zero id!");
9845   assert(AllNodes.front().getNumOperands() == 0 &&
9846          "First node in topological sort has operands!");
9847   assert(AllNodes.back().getNodeId() == (int)DAGSize-1 &&
9848          "Last node in topologic sort has unexpected id!");
9849   assert(AllNodes.back().use_empty() &&
9850          "Last node in topologic sort has users!");
9851   assert(DAGSize == allnodes_size() && "Node count mismatch!");
9852   return DAGSize;
9853 }
9854 
9855 /// AddDbgValue - Add a dbg_value SDNode. If SD is non-null that means the
9856 /// value is produced by SD.
9857 void SelectionDAG::AddDbgValue(SDDbgValue *DB, bool isParameter) {
9858   for (SDNode *SD : DB->getSDNodes()) {
9859     if (!SD)
9860       continue;
9861     assert(DbgInfo->getSDDbgValues(SD).empty() || SD->getHasDebugValue());
9862     SD->setHasDebugValue(true);
9863   }
9864   DbgInfo->add(DB, isParameter);
9865 }
9866 
9867 void SelectionDAG::AddDbgLabel(SDDbgLabel *DB) { DbgInfo->add(DB); }
9868 
9869 SDValue SelectionDAG::makeEquivalentMemoryOrdering(SDValue OldChain,
9870                                                    SDValue NewMemOpChain) {
9871   assert(isa<MemSDNode>(NewMemOpChain) && "Expected a memop node");
9872   assert(NewMemOpChain.getValueType() == MVT::Other && "Expected a token VT");
9873   // The new memory operation must have the same position as the old load in
9874   // terms of memory dependency. Create a TokenFactor for the old load and new
9875   // memory operation and update uses of the old load's output chain to use that
9876   // TokenFactor.
9877   if (OldChain == NewMemOpChain || OldChain.use_empty())
9878     return NewMemOpChain;
9879 
9880   SDValue TokenFactor = getNode(ISD::TokenFactor, SDLoc(OldChain), MVT::Other,
9881                                 OldChain, NewMemOpChain);
9882   ReplaceAllUsesOfValueWith(OldChain, TokenFactor);
9883   UpdateNodeOperands(TokenFactor.getNode(), OldChain, NewMemOpChain);
9884   return TokenFactor;
9885 }
9886 
9887 SDValue SelectionDAG::makeEquivalentMemoryOrdering(LoadSDNode *OldLoad,
9888                                                    SDValue NewMemOp) {
9889   assert(isa<MemSDNode>(NewMemOp.getNode()) && "Expected a memop node");
9890   SDValue OldChain = SDValue(OldLoad, 1);
9891   SDValue NewMemOpChain = NewMemOp.getValue(1);
9892   return makeEquivalentMemoryOrdering(OldChain, NewMemOpChain);
9893 }
9894 
9895 SDValue SelectionDAG::getSymbolFunctionGlobalAddress(SDValue Op,
9896                                                      Function **OutFunction) {
9897   assert(isa<ExternalSymbolSDNode>(Op) && "Node should be an ExternalSymbol");
9898 
9899   auto *Symbol = cast<ExternalSymbolSDNode>(Op)->getSymbol();
9900   auto *Module = MF->getFunction().getParent();
9901   auto *Function = Module->getFunction(Symbol);
9902 
9903   if (OutFunction != nullptr)
9904       *OutFunction = Function;
9905 
9906   if (Function != nullptr) {
9907     auto PtrTy = TLI->getPointerTy(getDataLayout(), Function->getAddressSpace());
9908     return getGlobalAddress(Function, SDLoc(Op), PtrTy);
9909   }
9910 
9911   std::string ErrorStr;
9912   raw_string_ostream ErrorFormatter(ErrorStr);
9913   ErrorFormatter << "Undefined external symbol ";
9914   ErrorFormatter << '"' << Symbol << '"';
9915   report_fatal_error(Twine(ErrorFormatter.str()));
9916 }
9917 
9918 //===----------------------------------------------------------------------===//
9919 //                              SDNode Class
9920 //===----------------------------------------------------------------------===//
9921 
9922 bool llvm::isNullConstant(SDValue V) {
9923   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
9924   return Const != nullptr && Const->isZero();
9925 }
9926 
9927 bool llvm::isNullFPConstant(SDValue V) {
9928   ConstantFPSDNode *Const = dyn_cast<ConstantFPSDNode>(V);
9929   return Const != nullptr && Const->isZero() && !Const->isNegative();
9930 }
9931 
9932 bool llvm::isAllOnesConstant(SDValue V) {
9933   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
9934   return Const != nullptr && Const->isAllOnes();
9935 }
9936 
9937 bool llvm::isOneConstant(SDValue V) {
9938   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
9939   return Const != nullptr && Const->isOne();
9940 }
9941 
9942 SDValue llvm::peekThroughBitcasts(SDValue V) {
9943   while (V.getOpcode() == ISD::BITCAST)
9944     V = V.getOperand(0);
9945   return V;
9946 }
9947 
9948 SDValue llvm::peekThroughOneUseBitcasts(SDValue V) {
9949   while (V.getOpcode() == ISD::BITCAST && V.getOperand(0).hasOneUse())
9950     V = V.getOperand(0);
9951   return V;
9952 }
9953 
9954 SDValue llvm::peekThroughExtractSubvectors(SDValue V) {
9955   while (V.getOpcode() == ISD::EXTRACT_SUBVECTOR)
9956     V = V.getOperand(0);
9957   return V;
9958 }
9959 
9960 bool llvm::isBitwiseNot(SDValue V, bool AllowUndefs) {
9961   if (V.getOpcode() != ISD::XOR)
9962     return false;
9963   V = peekThroughBitcasts(V.getOperand(1));
9964   unsigned NumBits = V.getScalarValueSizeInBits();
9965   ConstantSDNode *C =
9966       isConstOrConstSplat(V, AllowUndefs, /*AllowTruncation*/ true);
9967   return C && (C->getAPIntValue().countTrailingOnes() >= NumBits);
9968 }
9969 
9970 ConstantSDNode *llvm::isConstOrConstSplat(SDValue N, bool AllowUndefs,
9971                                           bool AllowTruncation) {
9972   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
9973     return CN;
9974 
9975   // SplatVectors can truncate their operands. Ignore that case here unless
9976   // AllowTruncation is set.
9977   if (N->getOpcode() == ISD::SPLAT_VECTOR) {
9978     EVT VecEltVT = N->getValueType(0).getVectorElementType();
9979     if (auto *CN = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
9980       EVT CVT = CN->getValueType(0);
9981       assert(CVT.bitsGE(VecEltVT) && "Illegal splat_vector element extension");
9982       if (AllowTruncation || CVT == VecEltVT)
9983         return CN;
9984     }
9985   }
9986 
9987   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
9988     BitVector UndefElements;
9989     ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
9990 
9991     // BuildVectors can truncate their operands. Ignore that case here unless
9992     // AllowTruncation is set.
9993     if (CN && (UndefElements.none() || AllowUndefs)) {
9994       EVT CVT = CN->getValueType(0);
9995       EVT NSVT = N.getValueType().getScalarType();
9996       assert(CVT.bitsGE(NSVT) && "Illegal build vector element extension");
9997       if (AllowTruncation || (CVT == NSVT))
9998         return CN;
9999     }
10000   }
10001 
10002   return nullptr;
10003 }
10004 
10005 ConstantSDNode *llvm::isConstOrConstSplat(SDValue N, const APInt &DemandedElts,
10006                                           bool AllowUndefs,
10007                                           bool AllowTruncation) {
10008   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
10009     return CN;
10010 
10011   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
10012     BitVector UndefElements;
10013     ConstantSDNode *CN = BV->getConstantSplatNode(DemandedElts, &UndefElements);
10014 
10015     // BuildVectors can truncate their operands. Ignore that case here unless
10016     // AllowTruncation is set.
10017     if (CN && (UndefElements.none() || AllowUndefs)) {
10018       EVT CVT = CN->getValueType(0);
10019       EVT NSVT = N.getValueType().getScalarType();
10020       assert(CVT.bitsGE(NSVT) && "Illegal build vector element extension");
10021       if (AllowTruncation || (CVT == NSVT))
10022         return CN;
10023     }
10024   }
10025 
10026   return nullptr;
10027 }
10028 
10029 ConstantFPSDNode *llvm::isConstOrConstSplatFP(SDValue N, bool AllowUndefs) {
10030   if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
10031     return CN;
10032 
10033   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
10034     BitVector UndefElements;
10035     ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements);
10036     if (CN && (UndefElements.none() || AllowUndefs))
10037       return CN;
10038   }
10039 
10040   if (N.getOpcode() == ISD::SPLAT_VECTOR)
10041     if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N.getOperand(0)))
10042       return CN;
10043 
10044   return nullptr;
10045 }
10046 
10047 ConstantFPSDNode *llvm::isConstOrConstSplatFP(SDValue N,
10048                                               const APInt &DemandedElts,
10049                                               bool AllowUndefs) {
10050   if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
10051     return CN;
10052 
10053   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
10054     BitVector UndefElements;
10055     ConstantFPSDNode *CN =
10056         BV->getConstantFPSplatNode(DemandedElts, &UndefElements);
10057     if (CN && (UndefElements.none() || AllowUndefs))
10058       return CN;
10059   }
10060 
10061   return nullptr;
10062 }
10063 
10064 bool llvm::isNullOrNullSplat(SDValue N, bool AllowUndefs) {
10065   // TODO: may want to use peekThroughBitcast() here.
10066   ConstantSDNode *C =
10067       isConstOrConstSplat(N, AllowUndefs, /*AllowTruncation=*/true);
10068   return C && C->isZero();
10069 }
10070 
10071 bool llvm::isOneOrOneSplat(SDValue N, bool AllowUndefs) {
10072   // TODO: may want to use peekThroughBitcast() here.
10073   unsigned BitWidth = N.getScalarValueSizeInBits();
10074   ConstantSDNode *C = isConstOrConstSplat(N, AllowUndefs);
10075   return C && C->isOne() && C->getValueSizeInBits(0) == BitWidth;
10076 }
10077 
10078 bool llvm::isAllOnesOrAllOnesSplat(SDValue N, bool AllowUndefs) {
10079   N = peekThroughBitcasts(N);
10080   unsigned BitWidth = N.getScalarValueSizeInBits();
10081   ConstantSDNode *C = isConstOrConstSplat(N, AllowUndefs);
10082   return C && C->isAllOnes() && C->getValueSizeInBits(0) == BitWidth;
10083 }
10084 
10085 HandleSDNode::~HandleSDNode() {
10086   DropOperands();
10087 }
10088 
10089 GlobalAddressSDNode::GlobalAddressSDNode(unsigned Opc, unsigned Order,
10090                                          const DebugLoc &DL,
10091                                          const GlobalValue *GA, EVT VT,
10092                                          int64_t o, unsigned TF)
10093     : SDNode(Opc, Order, DL, getSDVTList(VT)), Offset(o), TargetFlags(TF) {
10094   TheGlobal = GA;
10095 }
10096 
10097 AddrSpaceCastSDNode::AddrSpaceCastSDNode(unsigned Order, const DebugLoc &dl,
10098                                          EVT VT, unsigned SrcAS,
10099                                          unsigned DestAS)
10100     : SDNode(ISD::ADDRSPACECAST, Order, dl, getSDVTList(VT)),
10101       SrcAddrSpace(SrcAS), DestAddrSpace(DestAS) {}
10102 
10103 MemSDNode::MemSDNode(unsigned Opc, unsigned Order, const DebugLoc &dl,
10104                      SDVTList VTs, EVT memvt, MachineMemOperand *mmo)
10105     : SDNode(Opc, Order, dl, VTs), MemoryVT(memvt), MMO(mmo) {
10106   MemSDNodeBits.IsVolatile = MMO->isVolatile();
10107   MemSDNodeBits.IsNonTemporal = MMO->isNonTemporal();
10108   MemSDNodeBits.IsDereferenceable = MMO->isDereferenceable();
10109   MemSDNodeBits.IsInvariant = MMO->isInvariant();
10110 
10111   // We check here that the size of the memory operand fits within the size of
10112   // the MMO. This is because the MMO might indicate only a possible address
10113   // range instead of specifying the affected memory addresses precisely.
10114   // TODO: Make MachineMemOperands aware of scalable vectors.
10115   assert(memvt.getStoreSize().getKnownMinSize() <= MMO->getSize() &&
10116          "Size mismatch!");
10117 }
10118 
10119 /// Profile - Gather unique data for the node.
10120 ///
10121 void SDNode::Profile(FoldingSetNodeID &ID) const {
10122   AddNodeIDNode(ID, this);
10123 }
10124 
10125 namespace {
10126 
10127   struct EVTArray {
10128     std::vector<EVT> VTs;
10129 
10130     EVTArray() {
10131       VTs.reserve(MVT::VALUETYPE_SIZE);
10132       for (unsigned i = 0; i < MVT::VALUETYPE_SIZE; ++i)
10133         VTs.push_back(MVT((MVT::SimpleValueType)i));
10134     }
10135   };
10136 
10137 } // end anonymous namespace
10138 
10139 static ManagedStatic<std::set<EVT, EVT::compareRawBits>> EVTs;
10140 static ManagedStatic<EVTArray> SimpleVTArray;
10141 static ManagedStatic<sys::SmartMutex<true>> VTMutex;
10142 
10143 /// getValueTypeList - Return a pointer to the specified value type.
10144 ///
10145 const EVT *SDNode::getValueTypeList(EVT VT) {
10146   if (VT.isExtended()) {
10147     sys::SmartScopedLock<true> Lock(*VTMutex);
10148     return &(*EVTs->insert(VT).first);
10149   }
10150   assert(VT.getSimpleVT() < MVT::VALUETYPE_SIZE && "Value type out of range!");
10151   return &SimpleVTArray->VTs[VT.getSimpleVT().SimpleTy];
10152 }
10153 
10154 /// hasNUsesOfValue - Return true if there are exactly NUSES uses of the
10155 /// indicated value.  This method ignores uses of other values defined by this
10156 /// operation.
10157 bool SDNode::hasNUsesOfValue(unsigned NUses, unsigned Value) const {
10158   assert(Value < getNumValues() && "Bad value!");
10159 
10160   // TODO: Only iterate over uses of a given value of the node
10161   for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) {
10162     if (UI.getUse().getResNo() == Value) {
10163       if (NUses == 0)
10164         return false;
10165       --NUses;
10166     }
10167   }
10168 
10169   // Found exactly the right number of uses?
10170   return NUses == 0;
10171 }
10172 
10173 /// hasAnyUseOfValue - Return true if there are any use of the indicated
10174 /// value. This method ignores uses of other values defined by this operation.
10175 bool SDNode::hasAnyUseOfValue(unsigned Value) const {
10176   assert(Value < getNumValues() && "Bad value!");
10177 
10178   for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI)
10179     if (UI.getUse().getResNo() == Value)
10180       return true;
10181 
10182   return false;
10183 }
10184 
10185 /// isOnlyUserOf - Return true if this node is the only use of N.
10186 bool SDNode::isOnlyUserOf(const SDNode *N) const {
10187   bool Seen = false;
10188   for (const SDNode *User : N->uses()) {
10189     if (User == this)
10190       Seen = true;
10191     else
10192       return false;
10193   }
10194 
10195   return Seen;
10196 }
10197 
10198 /// Return true if the only users of N are contained in Nodes.
10199 bool SDNode::areOnlyUsersOf(ArrayRef<const SDNode *> Nodes, const SDNode *N) {
10200   bool Seen = false;
10201   for (const SDNode *User : N->uses()) {
10202     if (llvm::is_contained(Nodes, User))
10203       Seen = true;
10204     else
10205       return false;
10206   }
10207 
10208   return Seen;
10209 }
10210 
10211 /// isOperand - Return true if this node is an operand of N.
10212 bool SDValue::isOperandOf(const SDNode *N) const {
10213   return is_contained(N->op_values(), *this);
10214 }
10215 
10216 bool SDNode::isOperandOf(const SDNode *N) const {
10217   return any_of(N->op_values(),
10218                 [this](SDValue Op) { return this == Op.getNode(); });
10219 }
10220 
10221 /// reachesChainWithoutSideEffects - Return true if this operand (which must
10222 /// be a chain) reaches the specified operand without crossing any
10223 /// side-effecting instructions on any chain path.  In practice, this looks
10224 /// through token factors and non-volatile loads.  In order to remain efficient,
10225 /// this only looks a couple of nodes in, it does not do an exhaustive search.
10226 ///
10227 /// Note that we only need to examine chains when we're searching for
10228 /// side-effects; SelectionDAG requires that all side-effects are represented
10229 /// by chains, even if another operand would force a specific ordering. This
10230 /// constraint is necessary to allow transformations like splitting loads.
10231 bool SDValue::reachesChainWithoutSideEffects(SDValue Dest,
10232                                              unsigned Depth) const {
10233   if (*this == Dest) return true;
10234 
10235   // Don't search too deeply, we just want to be able to see through
10236   // TokenFactor's etc.
10237   if (Depth == 0) return false;
10238 
10239   // If this is a token factor, all inputs to the TF happen in parallel.
10240   if (getOpcode() == ISD::TokenFactor) {
10241     // First, try a shallow search.
10242     if (is_contained((*this)->ops(), Dest)) {
10243       // We found the chain we want as an operand of this TokenFactor.
10244       // Essentially, we reach the chain without side-effects if we could
10245       // serialize the TokenFactor into a simple chain of operations with
10246       // Dest as the last operation. This is automatically true if the
10247       // chain has one use: there are no other ordering constraints.
10248       // If the chain has more than one use, we give up: some other
10249       // use of Dest might force a side-effect between Dest and the current
10250       // node.
10251       if (Dest.hasOneUse())
10252         return true;
10253     }
10254     // Next, try a deep search: check whether every operand of the TokenFactor
10255     // reaches Dest.
10256     return llvm::all_of((*this)->ops(), [=](SDValue Op) {
10257       return Op.reachesChainWithoutSideEffects(Dest, Depth - 1);
10258     });
10259   }
10260 
10261   // Loads don't have side effects, look through them.
10262   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(*this)) {
10263     if (Ld->isUnordered())
10264       return Ld->getChain().reachesChainWithoutSideEffects(Dest, Depth-1);
10265   }
10266   return false;
10267 }
10268 
10269 bool SDNode::hasPredecessor(const SDNode *N) const {
10270   SmallPtrSet<const SDNode *, 32> Visited;
10271   SmallVector<const SDNode *, 16> Worklist;
10272   Worklist.push_back(this);
10273   return hasPredecessorHelper(N, Visited, Worklist);
10274 }
10275 
10276 void SDNode::intersectFlagsWith(const SDNodeFlags Flags) {
10277   this->Flags.intersectWith(Flags);
10278 }
10279 
10280 SDValue
10281 SelectionDAG::matchBinOpReduction(SDNode *Extract, ISD::NodeType &BinOp,
10282                                   ArrayRef<ISD::NodeType> CandidateBinOps,
10283                                   bool AllowPartials) {
10284   // The pattern must end in an extract from index 0.
10285   if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10286       !isNullConstant(Extract->getOperand(1)))
10287     return SDValue();
10288 
10289   // Match against one of the candidate binary ops.
10290   SDValue Op = Extract->getOperand(0);
10291   if (llvm::none_of(CandidateBinOps, [Op](ISD::NodeType BinOp) {
10292         return Op.getOpcode() == unsigned(BinOp);
10293       }))
10294     return SDValue();
10295 
10296   // Floating-point reductions may require relaxed constraints on the final step
10297   // of the reduction because they may reorder intermediate operations.
10298   unsigned CandidateBinOp = Op.getOpcode();
10299   if (Op.getValueType().isFloatingPoint()) {
10300     SDNodeFlags Flags = Op->getFlags();
10301     switch (CandidateBinOp) {
10302     case ISD::FADD:
10303       if (!Flags.hasNoSignedZeros() || !Flags.hasAllowReassociation())
10304         return SDValue();
10305       break;
10306     default:
10307       llvm_unreachable("Unhandled FP opcode for binop reduction");
10308     }
10309   }
10310 
10311   // Matching failed - attempt to see if we did enough stages that a partial
10312   // reduction from a subvector is possible.
10313   auto PartialReduction = [&](SDValue Op, unsigned NumSubElts) {
10314     if (!AllowPartials || !Op)
10315       return SDValue();
10316     EVT OpVT = Op.getValueType();
10317     EVT OpSVT = OpVT.getScalarType();
10318     EVT SubVT = EVT::getVectorVT(*getContext(), OpSVT, NumSubElts);
10319     if (!TLI->isExtractSubvectorCheap(SubVT, OpVT, 0))
10320       return SDValue();
10321     BinOp = (ISD::NodeType)CandidateBinOp;
10322     return getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(Op), SubVT, Op,
10323                    getVectorIdxConstant(0, SDLoc(Op)));
10324   };
10325 
10326   // At each stage, we're looking for something that looks like:
10327   // %s = shufflevector <8 x i32> %op, <8 x i32> undef,
10328   //                    <8 x i32> <i32 2, i32 3, i32 undef, i32 undef,
10329   //                               i32 undef, i32 undef, i32 undef, i32 undef>
10330   // %a = binop <8 x i32> %op, %s
10331   // Where the mask changes according to the stage. E.g. for a 3-stage pyramid,
10332   // we expect something like:
10333   // <4,5,6,7,u,u,u,u>
10334   // <2,3,u,u,u,u,u,u>
10335   // <1,u,u,u,u,u,u,u>
10336   // While a partial reduction match would be:
10337   // <2,3,u,u,u,u,u,u>
10338   // <1,u,u,u,u,u,u,u>
10339   unsigned Stages = Log2_32(Op.getValueType().getVectorNumElements());
10340   SDValue PrevOp;
10341   for (unsigned i = 0; i < Stages; ++i) {
10342     unsigned MaskEnd = (1 << i);
10343 
10344     if (Op.getOpcode() != CandidateBinOp)
10345       return PartialReduction(PrevOp, MaskEnd);
10346 
10347     SDValue Op0 = Op.getOperand(0);
10348     SDValue Op1 = Op.getOperand(1);
10349 
10350     ShuffleVectorSDNode *Shuffle = dyn_cast<ShuffleVectorSDNode>(Op0);
10351     if (Shuffle) {
10352       Op = Op1;
10353     } else {
10354       Shuffle = dyn_cast<ShuffleVectorSDNode>(Op1);
10355       Op = Op0;
10356     }
10357 
10358     // The first operand of the shuffle should be the same as the other operand
10359     // of the binop.
10360     if (!Shuffle || Shuffle->getOperand(0) != Op)
10361       return PartialReduction(PrevOp, MaskEnd);
10362 
10363     // Verify the shuffle has the expected (at this stage of the pyramid) mask.
10364     for (int Index = 0; Index < (int)MaskEnd; ++Index)
10365       if (Shuffle->getMaskElt(Index) != (int)(MaskEnd + Index))
10366         return PartialReduction(PrevOp, MaskEnd);
10367 
10368     PrevOp = Op;
10369   }
10370 
10371   // Handle subvector reductions, which tend to appear after the shuffle
10372   // reduction stages.
10373   while (Op.getOpcode() == CandidateBinOp) {
10374     unsigned NumElts = Op.getValueType().getVectorNumElements();
10375     SDValue Op0 = Op.getOperand(0);
10376     SDValue Op1 = Op.getOperand(1);
10377     if (Op0.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
10378         Op1.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
10379         Op0.getOperand(0) != Op1.getOperand(0))
10380       break;
10381     SDValue Src = Op0.getOperand(0);
10382     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
10383     if (NumSrcElts != (2 * NumElts))
10384       break;
10385     if (!(Op0.getConstantOperandAPInt(1) == 0 &&
10386           Op1.getConstantOperandAPInt(1) == NumElts) &&
10387         !(Op1.getConstantOperandAPInt(1) == 0 &&
10388           Op0.getConstantOperandAPInt(1) == NumElts))
10389       break;
10390     Op = Src;
10391   }
10392 
10393   BinOp = (ISD::NodeType)CandidateBinOp;
10394   return Op;
10395 }
10396 
10397 SDValue SelectionDAG::UnrollVectorOp(SDNode *N, unsigned ResNE) {
10398   assert(N->getNumValues() == 1 &&
10399          "Can't unroll a vector with multiple results!");
10400 
10401   EVT VT = N->getValueType(0);
10402   unsigned NE = VT.getVectorNumElements();
10403   EVT EltVT = VT.getVectorElementType();
10404   SDLoc dl(N);
10405 
10406   SmallVector<SDValue, 8> Scalars;
10407   SmallVector<SDValue, 4> Operands(N->getNumOperands());
10408 
10409   // If ResNE is 0, fully unroll the vector op.
10410   if (ResNE == 0)
10411     ResNE = NE;
10412   else if (NE > ResNE)
10413     NE = ResNE;
10414 
10415   unsigned i;
10416   for (i= 0; i != NE; ++i) {
10417     for (unsigned j = 0, e = N->getNumOperands(); j != e; ++j) {
10418       SDValue Operand = N->getOperand(j);
10419       EVT OperandVT = Operand.getValueType();
10420       if (OperandVT.isVector()) {
10421         // A vector operand; extract a single element.
10422         EVT OperandEltVT = OperandVT.getVectorElementType();
10423         Operands[j] = getNode(ISD::EXTRACT_VECTOR_ELT, dl, OperandEltVT,
10424                               Operand, getVectorIdxConstant(i, dl));
10425       } else {
10426         // A scalar operand; just use it as is.
10427         Operands[j] = Operand;
10428       }
10429     }
10430 
10431     switch (N->getOpcode()) {
10432     default: {
10433       Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands,
10434                                 N->getFlags()));
10435       break;
10436     }
10437     case ISD::VSELECT:
10438       Scalars.push_back(getNode(ISD::SELECT, dl, EltVT, Operands));
10439       break;
10440     case ISD::SHL:
10441     case ISD::SRA:
10442     case ISD::SRL:
10443     case ISD::ROTL:
10444     case ISD::ROTR:
10445       Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands[0],
10446                                getShiftAmountOperand(Operands[0].getValueType(),
10447                                                      Operands[1])));
10448       break;
10449     case ISD::SIGN_EXTEND_INREG: {
10450       EVT ExtVT = cast<VTSDNode>(Operands[1])->getVT().getVectorElementType();
10451       Scalars.push_back(getNode(N->getOpcode(), dl, EltVT,
10452                                 Operands[0],
10453                                 getValueType(ExtVT)));
10454     }
10455     }
10456   }
10457 
10458   for (; i < ResNE; ++i)
10459     Scalars.push_back(getUNDEF(EltVT));
10460 
10461   EVT VecVT = EVT::getVectorVT(*getContext(), EltVT, ResNE);
10462   return getBuildVector(VecVT, dl, Scalars);
10463 }
10464 
10465 std::pair<SDValue, SDValue> SelectionDAG::UnrollVectorOverflowOp(
10466     SDNode *N, unsigned ResNE) {
10467   unsigned Opcode = N->getOpcode();
10468   assert((Opcode == ISD::UADDO || Opcode == ISD::SADDO ||
10469           Opcode == ISD::USUBO || Opcode == ISD::SSUBO ||
10470           Opcode == ISD::UMULO || Opcode == ISD::SMULO) &&
10471          "Expected an overflow opcode");
10472 
10473   EVT ResVT = N->getValueType(0);
10474   EVT OvVT = N->getValueType(1);
10475   EVT ResEltVT = ResVT.getVectorElementType();
10476   EVT OvEltVT = OvVT.getVectorElementType();
10477   SDLoc dl(N);
10478 
10479   // If ResNE is 0, fully unroll the vector op.
10480   unsigned NE = ResVT.getVectorNumElements();
10481   if (ResNE == 0)
10482     ResNE = NE;
10483   else if (NE > ResNE)
10484     NE = ResNE;
10485 
10486   SmallVector<SDValue, 8> LHSScalars;
10487   SmallVector<SDValue, 8> RHSScalars;
10488   ExtractVectorElements(N->getOperand(0), LHSScalars, 0, NE);
10489   ExtractVectorElements(N->getOperand(1), RHSScalars, 0, NE);
10490 
10491   EVT SVT = TLI->getSetCCResultType(getDataLayout(), *getContext(), ResEltVT);
10492   SDVTList VTs = getVTList(ResEltVT, SVT);
10493   SmallVector<SDValue, 8> ResScalars;
10494   SmallVector<SDValue, 8> OvScalars;
10495   for (unsigned i = 0; i < NE; ++i) {
10496     SDValue Res = getNode(Opcode, dl, VTs, LHSScalars[i], RHSScalars[i]);
10497     SDValue Ov =
10498         getSelect(dl, OvEltVT, Res.getValue(1),
10499                   getBoolConstant(true, dl, OvEltVT, ResVT),
10500                   getConstant(0, dl, OvEltVT));
10501 
10502     ResScalars.push_back(Res);
10503     OvScalars.push_back(Ov);
10504   }
10505 
10506   ResScalars.append(ResNE - NE, getUNDEF(ResEltVT));
10507   OvScalars.append(ResNE - NE, getUNDEF(OvEltVT));
10508 
10509   EVT NewResVT = EVT::getVectorVT(*getContext(), ResEltVT, ResNE);
10510   EVT NewOvVT = EVT::getVectorVT(*getContext(), OvEltVT, ResNE);
10511   return std::make_pair(getBuildVector(NewResVT, dl, ResScalars),
10512                         getBuildVector(NewOvVT, dl, OvScalars));
10513 }
10514 
10515 bool SelectionDAG::areNonVolatileConsecutiveLoads(LoadSDNode *LD,
10516                                                   LoadSDNode *Base,
10517                                                   unsigned Bytes,
10518                                                   int Dist) const {
10519   if (LD->isVolatile() || Base->isVolatile())
10520     return false;
10521   // TODO: probably too restrictive for atomics, revisit
10522   if (!LD->isSimple())
10523     return false;
10524   if (LD->isIndexed() || Base->isIndexed())
10525     return false;
10526   if (LD->getChain() != Base->getChain())
10527     return false;
10528   EVT VT = LD->getValueType(0);
10529   if (VT.getSizeInBits() / 8 != Bytes)
10530     return false;
10531 
10532   auto BaseLocDecomp = BaseIndexOffset::match(Base, *this);
10533   auto LocDecomp = BaseIndexOffset::match(LD, *this);
10534 
10535   int64_t Offset = 0;
10536   if (BaseLocDecomp.equalBaseIndex(LocDecomp, *this, Offset))
10537     return (Dist * Bytes == Offset);
10538   return false;
10539 }
10540 
10541 /// InferPtrAlignment - Infer alignment of a load / store address. Return None
10542 /// if it cannot be inferred.
10543 MaybeAlign SelectionDAG::InferPtrAlign(SDValue Ptr) const {
10544   // If this is a GlobalAddress + cst, return the alignment.
10545   const GlobalValue *GV = nullptr;
10546   int64_t GVOffset = 0;
10547   if (TLI->isGAPlusOffset(Ptr.getNode(), GV, GVOffset)) {
10548     unsigned PtrWidth = getDataLayout().getPointerTypeSizeInBits(GV->getType());
10549     KnownBits Known(PtrWidth);
10550     llvm::computeKnownBits(GV, Known, getDataLayout());
10551     unsigned AlignBits = Known.countMinTrailingZeros();
10552     if (AlignBits)
10553       return commonAlignment(Align(1ull << std::min(31U, AlignBits)), GVOffset);
10554   }
10555 
10556   // If this is a direct reference to a stack slot, use information about the
10557   // stack slot's alignment.
10558   int FrameIdx = INT_MIN;
10559   int64_t FrameOffset = 0;
10560   if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr)) {
10561     FrameIdx = FI->getIndex();
10562   } else if (isBaseWithConstantOffset(Ptr) &&
10563              isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
10564     // Handle FI+Cst
10565     FrameIdx = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
10566     FrameOffset = Ptr.getConstantOperandVal(1);
10567   }
10568 
10569   if (FrameIdx != INT_MIN) {
10570     const MachineFrameInfo &MFI = getMachineFunction().getFrameInfo();
10571     return commonAlignment(MFI.getObjectAlign(FrameIdx), FrameOffset);
10572   }
10573 
10574   return None;
10575 }
10576 
10577 /// GetSplitDestVTs - Compute the VTs needed for the low/hi parts of a type
10578 /// which is split (or expanded) into two not necessarily identical pieces.
10579 std::pair<EVT, EVT> SelectionDAG::GetSplitDestVTs(const EVT &VT) const {
10580   // Currently all types are split in half.
10581   EVT LoVT, HiVT;
10582   if (!VT.isVector())
10583     LoVT = HiVT = TLI->getTypeToTransformTo(*getContext(), VT);
10584   else
10585     LoVT = HiVT = VT.getHalfNumVectorElementsVT(*getContext());
10586 
10587   return std::make_pair(LoVT, HiVT);
10588 }
10589 
10590 /// GetDependentSplitDestVTs - Compute the VTs needed for the low/hi parts of a
10591 /// type, dependent on an enveloping VT that has been split into two identical
10592 /// pieces. Sets the HiIsEmpty flag when hi type has zero storage size.
10593 std::pair<EVT, EVT>
10594 SelectionDAG::GetDependentSplitDestVTs(const EVT &VT, const EVT &EnvVT,
10595                                        bool *HiIsEmpty) const {
10596   EVT EltTp = VT.getVectorElementType();
10597   // Examples:
10598   //   custom VL=8  with enveloping VL=8/8 yields 8/0 (hi empty)
10599   //   custom VL=9  with enveloping VL=8/8 yields 8/1
10600   //   custom VL=10 with enveloping VL=8/8 yields 8/2
10601   //   etc.
10602   ElementCount VTNumElts = VT.getVectorElementCount();
10603   ElementCount EnvNumElts = EnvVT.getVectorElementCount();
10604   assert(VTNumElts.isScalable() == EnvNumElts.isScalable() &&
10605          "Mixing fixed width and scalable vectors when enveloping a type");
10606   EVT LoVT, HiVT;
10607   if (VTNumElts.getKnownMinValue() > EnvNumElts.getKnownMinValue()) {
10608     LoVT = EVT::getVectorVT(*getContext(), EltTp, EnvNumElts);
10609     HiVT = EVT::getVectorVT(*getContext(), EltTp, VTNumElts - EnvNumElts);
10610     *HiIsEmpty = false;
10611   } else {
10612     // Flag that hi type has zero storage size, but return split envelop type
10613     // (this would be easier if vector types with zero elements were allowed).
10614     LoVT = EVT::getVectorVT(*getContext(), EltTp, VTNumElts);
10615     HiVT = EVT::getVectorVT(*getContext(), EltTp, EnvNumElts);
10616     *HiIsEmpty = true;
10617   }
10618   return std::make_pair(LoVT, HiVT);
10619 }
10620 
10621 /// SplitVector - Split the vector with EXTRACT_SUBVECTOR and return the
10622 /// low/high part.
10623 std::pair<SDValue, SDValue>
10624 SelectionDAG::SplitVector(const SDValue &N, const SDLoc &DL, const EVT &LoVT,
10625                           const EVT &HiVT) {
10626   assert(LoVT.isScalableVector() == HiVT.isScalableVector() &&
10627          LoVT.isScalableVector() == N.getValueType().isScalableVector() &&
10628          "Splitting vector with an invalid mixture of fixed and scalable "
10629          "vector types");
10630   assert(LoVT.getVectorMinNumElements() + HiVT.getVectorMinNumElements() <=
10631              N.getValueType().getVectorMinNumElements() &&
10632          "More vector elements requested than available!");
10633   SDValue Lo, Hi;
10634   Lo =
10635       getNode(ISD::EXTRACT_SUBVECTOR, DL, LoVT, N, getVectorIdxConstant(0, DL));
10636   // For scalable vectors it is safe to use LoVT.getVectorMinNumElements()
10637   // (rather than having to use ElementCount), because EXTRACT_SUBVECTOR scales
10638   // IDX with the runtime scaling factor of the result vector type. For
10639   // fixed-width result vectors, that runtime scaling factor is 1.
10640   Hi = getNode(ISD::EXTRACT_SUBVECTOR, DL, HiVT, N,
10641                getVectorIdxConstant(LoVT.getVectorMinNumElements(), DL));
10642   return std::make_pair(Lo, Hi);
10643 }
10644 
10645 std::pair<SDValue, SDValue> SelectionDAG::SplitEVL(SDValue N, EVT VecVT,
10646                                                    const SDLoc &DL) {
10647   // Split the vector length parameter.
10648   // %evl -> umin(%evl, %halfnumelts) and usubsat(%evl - %halfnumelts).
10649   EVT VT = N.getValueType();
10650   assert(VecVT.getVectorElementCount().isKnownEven() &&
10651          "Expecting the mask to be an evenly-sized vector");
10652   unsigned HalfMinNumElts = VecVT.getVectorMinNumElements() / 2;
10653   SDValue HalfNumElts =
10654       VecVT.isFixedLengthVector()
10655           ? getConstant(HalfMinNumElts, DL, VT)
10656           : getVScale(DL, VT, APInt(VT.getScalarSizeInBits(), HalfMinNumElts));
10657   SDValue Lo = getNode(ISD::UMIN, DL, VT, N, HalfNumElts);
10658   SDValue Hi = getNode(ISD::USUBSAT, DL, VT, N, HalfNumElts);
10659   return std::make_pair(Lo, Hi);
10660 }
10661 
10662 /// Widen the vector up to the next power of two using INSERT_SUBVECTOR.
10663 SDValue SelectionDAG::WidenVector(const SDValue &N, const SDLoc &DL) {
10664   EVT VT = N.getValueType();
10665   EVT WideVT = EVT::getVectorVT(*getContext(), VT.getVectorElementType(),
10666                                 NextPowerOf2(VT.getVectorNumElements()));
10667   return getNode(ISD::INSERT_SUBVECTOR, DL, WideVT, getUNDEF(WideVT), N,
10668                  getVectorIdxConstant(0, DL));
10669 }
10670 
10671 void SelectionDAG::ExtractVectorElements(SDValue Op,
10672                                          SmallVectorImpl<SDValue> &Args,
10673                                          unsigned Start, unsigned Count,
10674                                          EVT EltVT) {
10675   EVT VT = Op.getValueType();
10676   if (Count == 0)
10677     Count = VT.getVectorNumElements();
10678   if (EltVT == EVT())
10679     EltVT = VT.getVectorElementType();
10680   SDLoc SL(Op);
10681   for (unsigned i = Start, e = Start + Count; i != e; ++i) {
10682     Args.push_back(getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Op,
10683                            getVectorIdxConstant(i, SL)));
10684   }
10685 }
10686 
10687 // getAddressSpace - Return the address space this GlobalAddress belongs to.
10688 unsigned GlobalAddressSDNode::getAddressSpace() const {
10689   return getGlobal()->getType()->getAddressSpace();
10690 }
10691 
10692 Type *ConstantPoolSDNode::getType() const {
10693   if (isMachineConstantPoolEntry())
10694     return Val.MachineCPVal->getType();
10695   return Val.ConstVal->getType();
10696 }
10697 
10698 bool BuildVectorSDNode::isConstantSplat(APInt &SplatValue, APInt &SplatUndef,
10699                                         unsigned &SplatBitSize,
10700                                         bool &HasAnyUndefs,
10701                                         unsigned MinSplatBits,
10702                                         bool IsBigEndian) const {
10703   EVT VT = getValueType(0);
10704   assert(VT.isVector() && "Expected a vector type");
10705   unsigned VecWidth = VT.getSizeInBits();
10706   if (MinSplatBits > VecWidth)
10707     return false;
10708 
10709   // FIXME: The widths are based on this node's type, but build vectors can
10710   // truncate their operands.
10711   SplatValue = APInt(VecWidth, 0);
10712   SplatUndef = APInt(VecWidth, 0);
10713 
10714   // Get the bits. Bits with undefined values (when the corresponding element
10715   // of the vector is an ISD::UNDEF value) are set in SplatUndef and cleared
10716   // in SplatValue. If any of the values are not constant, give up and return
10717   // false.
10718   unsigned int NumOps = getNumOperands();
10719   assert(NumOps > 0 && "isConstantSplat has 0-size build vector");
10720   unsigned EltWidth = VT.getScalarSizeInBits();
10721 
10722   for (unsigned j = 0; j < NumOps; ++j) {
10723     unsigned i = IsBigEndian ? NumOps - 1 - j : j;
10724     SDValue OpVal = getOperand(i);
10725     unsigned BitPos = j * EltWidth;
10726 
10727     if (OpVal.isUndef())
10728       SplatUndef.setBits(BitPos, BitPos + EltWidth);
10729     else if (auto *CN = dyn_cast<ConstantSDNode>(OpVal))
10730       SplatValue.insertBits(CN->getAPIntValue().zextOrTrunc(EltWidth), BitPos);
10731     else if (auto *CN = dyn_cast<ConstantFPSDNode>(OpVal))
10732       SplatValue.insertBits(CN->getValueAPF().bitcastToAPInt(), BitPos);
10733     else
10734       return false;
10735   }
10736 
10737   // The build_vector is all constants or undefs. Find the smallest element
10738   // size that splats the vector.
10739   HasAnyUndefs = (SplatUndef != 0);
10740 
10741   // FIXME: This does not work for vectors with elements less than 8 bits.
10742   while (VecWidth > 8) {
10743     unsigned HalfSize = VecWidth / 2;
10744     APInt HighValue = SplatValue.extractBits(HalfSize, HalfSize);
10745     APInt LowValue = SplatValue.extractBits(HalfSize, 0);
10746     APInt HighUndef = SplatUndef.extractBits(HalfSize, HalfSize);
10747     APInt LowUndef = SplatUndef.extractBits(HalfSize, 0);
10748 
10749     // If the two halves do not match (ignoring undef bits), stop here.
10750     if ((HighValue & ~LowUndef) != (LowValue & ~HighUndef) ||
10751         MinSplatBits > HalfSize)
10752       break;
10753 
10754     SplatValue = HighValue | LowValue;
10755     SplatUndef = HighUndef & LowUndef;
10756 
10757     VecWidth = HalfSize;
10758   }
10759 
10760   SplatBitSize = VecWidth;
10761   return true;
10762 }
10763 
10764 SDValue BuildVectorSDNode::getSplatValue(const APInt &DemandedElts,
10765                                          BitVector *UndefElements) const {
10766   unsigned NumOps = getNumOperands();
10767   if (UndefElements) {
10768     UndefElements->clear();
10769     UndefElements->resize(NumOps);
10770   }
10771   assert(NumOps == DemandedElts.getBitWidth() && "Unexpected vector size");
10772   if (!DemandedElts)
10773     return SDValue();
10774   SDValue Splatted;
10775   for (unsigned i = 0; i != NumOps; ++i) {
10776     if (!DemandedElts[i])
10777       continue;
10778     SDValue Op = getOperand(i);
10779     if (Op.isUndef()) {
10780       if (UndefElements)
10781         (*UndefElements)[i] = true;
10782     } else if (!Splatted) {
10783       Splatted = Op;
10784     } else if (Splatted != Op) {
10785       return SDValue();
10786     }
10787   }
10788 
10789   if (!Splatted) {
10790     unsigned FirstDemandedIdx = DemandedElts.countTrailingZeros();
10791     assert(getOperand(FirstDemandedIdx).isUndef() &&
10792            "Can only have a splat without a constant for all undefs.");
10793     return getOperand(FirstDemandedIdx);
10794   }
10795 
10796   return Splatted;
10797 }
10798 
10799 SDValue BuildVectorSDNode::getSplatValue(BitVector *UndefElements) const {
10800   APInt DemandedElts = APInt::getAllOnes(getNumOperands());
10801   return getSplatValue(DemandedElts, UndefElements);
10802 }
10803 
10804 bool BuildVectorSDNode::getRepeatedSequence(const APInt &DemandedElts,
10805                                             SmallVectorImpl<SDValue> &Sequence,
10806                                             BitVector *UndefElements) const {
10807   unsigned NumOps = getNumOperands();
10808   Sequence.clear();
10809   if (UndefElements) {
10810     UndefElements->clear();
10811     UndefElements->resize(NumOps);
10812   }
10813   assert(NumOps == DemandedElts.getBitWidth() && "Unexpected vector size");
10814   if (!DemandedElts || NumOps < 2 || !isPowerOf2_32(NumOps))
10815     return false;
10816 
10817   // Set the undefs even if we don't find a sequence (like getSplatValue).
10818   if (UndefElements)
10819     for (unsigned I = 0; I != NumOps; ++I)
10820       if (DemandedElts[I] && getOperand(I).isUndef())
10821         (*UndefElements)[I] = true;
10822 
10823   // Iteratively widen the sequence length looking for repetitions.
10824   for (unsigned SeqLen = 1; SeqLen < NumOps; SeqLen *= 2) {
10825     Sequence.append(SeqLen, SDValue());
10826     for (unsigned I = 0; I != NumOps; ++I) {
10827       if (!DemandedElts[I])
10828         continue;
10829       SDValue &SeqOp = Sequence[I % SeqLen];
10830       SDValue Op = getOperand(I);
10831       if (Op.isUndef()) {
10832         if (!SeqOp)
10833           SeqOp = Op;
10834         continue;
10835       }
10836       if (SeqOp && !SeqOp.isUndef() && SeqOp != Op) {
10837         Sequence.clear();
10838         break;
10839       }
10840       SeqOp = Op;
10841     }
10842     if (!Sequence.empty())
10843       return true;
10844   }
10845 
10846   assert(Sequence.empty() && "Failed to empty non-repeating sequence pattern");
10847   return false;
10848 }
10849 
10850 bool BuildVectorSDNode::getRepeatedSequence(SmallVectorImpl<SDValue> &Sequence,
10851                                             BitVector *UndefElements) const {
10852   APInt DemandedElts = APInt::getAllOnes(getNumOperands());
10853   return getRepeatedSequence(DemandedElts, Sequence, UndefElements);
10854 }
10855 
10856 ConstantSDNode *
10857 BuildVectorSDNode::getConstantSplatNode(const APInt &DemandedElts,
10858                                         BitVector *UndefElements) const {
10859   return dyn_cast_or_null<ConstantSDNode>(
10860       getSplatValue(DemandedElts, UndefElements));
10861 }
10862 
10863 ConstantSDNode *
10864 BuildVectorSDNode::getConstantSplatNode(BitVector *UndefElements) const {
10865   return dyn_cast_or_null<ConstantSDNode>(getSplatValue(UndefElements));
10866 }
10867 
10868 ConstantFPSDNode *
10869 BuildVectorSDNode::getConstantFPSplatNode(const APInt &DemandedElts,
10870                                           BitVector *UndefElements) const {
10871   return dyn_cast_or_null<ConstantFPSDNode>(
10872       getSplatValue(DemandedElts, UndefElements));
10873 }
10874 
10875 ConstantFPSDNode *
10876 BuildVectorSDNode::getConstantFPSplatNode(BitVector *UndefElements) const {
10877   return dyn_cast_or_null<ConstantFPSDNode>(getSplatValue(UndefElements));
10878 }
10879 
10880 int32_t
10881 BuildVectorSDNode::getConstantFPSplatPow2ToLog2Int(BitVector *UndefElements,
10882                                                    uint32_t BitWidth) const {
10883   if (ConstantFPSDNode *CN =
10884           dyn_cast_or_null<ConstantFPSDNode>(getSplatValue(UndefElements))) {
10885     bool IsExact;
10886     APSInt IntVal(BitWidth);
10887     const APFloat &APF = CN->getValueAPF();
10888     if (APF.convertToInteger(IntVal, APFloat::rmTowardZero, &IsExact) !=
10889             APFloat::opOK ||
10890         !IsExact)
10891       return -1;
10892 
10893     return IntVal.exactLogBase2();
10894   }
10895   return -1;
10896 }
10897 
10898 bool BuildVectorSDNode::getConstantRawBits(
10899     bool IsLittleEndian, unsigned DstEltSizeInBits,
10900     SmallVectorImpl<APInt> &RawBitElements, BitVector &UndefElements) const {
10901   // Early-out if this contains anything but Undef/Constant/ConstantFP.
10902   if (!isConstant())
10903     return false;
10904 
10905   unsigned NumSrcOps = getNumOperands();
10906   unsigned SrcEltSizeInBits = getValueType(0).getScalarSizeInBits();
10907   assert(((NumSrcOps * SrcEltSizeInBits) % DstEltSizeInBits) == 0 &&
10908          "Invalid bitcast scale");
10909 
10910   // Extract raw src bits.
10911   SmallVector<APInt> SrcBitElements(NumSrcOps,
10912                                     APInt::getNullValue(SrcEltSizeInBits));
10913   BitVector SrcUndeElements(NumSrcOps, false);
10914 
10915   for (unsigned I = 0; I != NumSrcOps; ++I) {
10916     SDValue Op = getOperand(I);
10917     if (Op.isUndef()) {
10918       SrcUndeElements.set(I);
10919       continue;
10920     }
10921     auto *CInt = dyn_cast<ConstantSDNode>(Op);
10922     auto *CFP = dyn_cast<ConstantFPSDNode>(Op);
10923     assert((CInt || CFP) && "Unknown constant");
10924     SrcBitElements[I] =
10925         CInt ? CInt->getAPIntValue().truncOrSelf(SrcEltSizeInBits)
10926              : CFP->getValueAPF().bitcastToAPInt();
10927   }
10928 
10929   // Recast to dst width.
10930   recastRawBits(IsLittleEndian, DstEltSizeInBits, RawBitElements,
10931                 SrcBitElements, UndefElements, SrcUndeElements);
10932   return true;
10933 }
10934 
10935 void BuildVectorSDNode::recastRawBits(bool IsLittleEndian,
10936                                       unsigned DstEltSizeInBits,
10937                                       SmallVectorImpl<APInt> &DstBitElements,
10938                                       ArrayRef<APInt> SrcBitElements,
10939                                       BitVector &DstUndefElements,
10940                                       const BitVector &SrcUndefElements) {
10941   unsigned NumSrcOps = SrcBitElements.size();
10942   unsigned SrcEltSizeInBits = SrcBitElements[0].getBitWidth();
10943   assert(((NumSrcOps * SrcEltSizeInBits) % DstEltSizeInBits) == 0 &&
10944          "Invalid bitcast scale");
10945   assert(NumSrcOps == SrcUndefElements.size() &&
10946          "Vector size mismatch");
10947 
10948   unsigned NumDstOps = (NumSrcOps * SrcEltSizeInBits) / DstEltSizeInBits;
10949   DstUndefElements.clear();
10950   DstUndefElements.resize(NumDstOps, false);
10951   DstBitElements.assign(NumDstOps, APInt::getNullValue(DstEltSizeInBits));
10952 
10953   // Concatenate src elements constant bits together into dst element.
10954   if (SrcEltSizeInBits <= DstEltSizeInBits) {
10955     unsigned Scale = DstEltSizeInBits / SrcEltSizeInBits;
10956     for (unsigned I = 0; I != NumDstOps; ++I) {
10957       DstUndefElements.set(I);
10958       APInt &DstBits = DstBitElements[I];
10959       for (unsigned J = 0; J != Scale; ++J) {
10960         unsigned Idx = (I * Scale) + (IsLittleEndian ? J : (Scale - J - 1));
10961         if (SrcUndefElements[Idx])
10962           continue;
10963         DstUndefElements.reset(I);
10964         const APInt &SrcBits = SrcBitElements[Idx];
10965         assert(SrcBits.getBitWidth() == SrcEltSizeInBits &&
10966                "Illegal constant bitwidths");
10967         DstBits.insertBits(SrcBits, J * SrcEltSizeInBits);
10968       }
10969     }
10970     return;
10971   }
10972 
10973   // Split src element constant bits into dst elements.
10974   unsigned Scale = SrcEltSizeInBits / DstEltSizeInBits;
10975   for (unsigned I = 0; I != NumSrcOps; ++I) {
10976     if (SrcUndefElements[I]) {
10977       DstUndefElements.set(I * Scale, (I + 1) * Scale);
10978       continue;
10979     }
10980     const APInt &SrcBits = SrcBitElements[I];
10981     for (unsigned J = 0; J != Scale; ++J) {
10982       unsigned Idx = (I * Scale) + (IsLittleEndian ? J : (Scale - J - 1));
10983       APInt &DstBits = DstBitElements[Idx];
10984       DstBits = SrcBits.extractBits(DstEltSizeInBits, J * DstEltSizeInBits);
10985     }
10986   }
10987 }
10988 
10989 bool BuildVectorSDNode::isConstant() const {
10990   for (const SDValue &Op : op_values()) {
10991     unsigned Opc = Op.getOpcode();
10992     if (Opc != ISD::UNDEF && Opc != ISD::Constant && Opc != ISD::ConstantFP)
10993       return false;
10994   }
10995   return true;
10996 }
10997 
10998 bool ShuffleVectorSDNode::isSplatMask(const int *Mask, EVT VT) {
10999   // Find the first non-undef value in the shuffle mask.
11000   unsigned i, e;
11001   for (i = 0, e = VT.getVectorNumElements(); i != e && Mask[i] < 0; ++i)
11002     /* search */;
11003 
11004   // If all elements are undefined, this shuffle can be considered a splat
11005   // (although it should eventually get simplified away completely).
11006   if (i == e)
11007     return true;
11008 
11009   // Make sure all remaining elements are either undef or the same as the first
11010   // non-undef value.
11011   for (int Idx = Mask[i]; i != e; ++i)
11012     if (Mask[i] >= 0 && Mask[i] != Idx)
11013       return false;
11014   return true;
11015 }
11016 
11017 // Returns the SDNode if it is a constant integer BuildVector
11018 // or constant integer.
11019 SDNode *SelectionDAG::isConstantIntBuildVectorOrConstantInt(SDValue N) const {
11020   if (isa<ConstantSDNode>(N))
11021     return N.getNode();
11022   if (ISD::isBuildVectorOfConstantSDNodes(N.getNode()))
11023     return N.getNode();
11024   // Treat a GlobalAddress supporting constant offset folding as a
11025   // constant integer.
11026   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N))
11027     if (GA->getOpcode() == ISD::GlobalAddress &&
11028         TLI->isOffsetFoldingLegal(GA))
11029       return GA;
11030   if ((N.getOpcode() == ISD::SPLAT_VECTOR) &&
11031       isa<ConstantSDNode>(N.getOperand(0)))
11032     return N.getNode();
11033   return nullptr;
11034 }
11035 
11036 // Returns the SDNode if it is a constant float BuildVector
11037 // or constant float.
11038 SDNode *SelectionDAG::isConstantFPBuildVectorOrConstantFP(SDValue N) const {
11039   if (isa<ConstantFPSDNode>(N))
11040     return N.getNode();
11041 
11042   if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode()))
11043     return N.getNode();
11044 
11045   return nullptr;
11046 }
11047 
11048 void SelectionDAG::createOperands(SDNode *Node, ArrayRef<SDValue> Vals) {
11049   assert(!Node->OperandList && "Node already has operands");
11050   assert(SDNode::getMaxNumOperands() >= Vals.size() &&
11051          "too many operands to fit into SDNode");
11052   SDUse *Ops = OperandRecycler.allocate(
11053       ArrayRecycler<SDUse>::Capacity::get(Vals.size()), OperandAllocator);
11054 
11055   bool IsDivergent = false;
11056   for (unsigned I = 0; I != Vals.size(); ++I) {
11057     Ops[I].setUser(Node);
11058     Ops[I].setInitial(Vals[I]);
11059     if (Ops[I].Val.getValueType() != MVT::Other) // Skip Chain. It does not carry divergence.
11060       IsDivergent |= Ops[I].getNode()->isDivergent();
11061   }
11062   Node->NumOperands = Vals.size();
11063   Node->OperandList = Ops;
11064   if (!TLI->isSDNodeAlwaysUniform(Node)) {
11065     IsDivergent |= TLI->isSDNodeSourceOfDivergence(Node, FLI, DA);
11066     Node->SDNodeBits.IsDivergent = IsDivergent;
11067   }
11068   checkForCycles(Node);
11069 }
11070 
11071 SDValue SelectionDAG::getTokenFactor(const SDLoc &DL,
11072                                      SmallVectorImpl<SDValue> &Vals) {
11073   size_t Limit = SDNode::getMaxNumOperands();
11074   while (Vals.size() > Limit) {
11075     unsigned SliceIdx = Vals.size() - Limit;
11076     auto ExtractedTFs = ArrayRef<SDValue>(Vals).slice(SliceIdx, Limit);
11077     SDValue NewTF = getNode(ISD::TokenFactor, DL, MVT::Other, ExtractedTFs);
11078     Vals.erase(Vals.begin() + SliceIdx, Vals.end());
11079     Vals.emplace_back(NewTF);
11080   }
11081   return getNode(ISD::TokenFactor, DL, MVT::Other, Vals);
11082 }
11083 
11084 SDValue SelectionDAG::getNeutralElement(unsigned Opcode, const SDLoc &DL,
11085                                         EVT VT, SDNodeFlags Flags) {
11086   switch (Opcode) {
11087   default:
11088     return SDValue();
11089   case ISD::ADD:
11090   case ISD::OR:
11091   case ISD::XOR:
11092   case ISD::UMAX:
11093     return getConstant(0, DL, VT);
11094   case ISD::MUL:
11095     return getConstant(1, DL, VT);
11096   case ISD::AND:
11097   case ISD::UMIN:
11098     return getAllOnesConstant(DL, VT);
11099   case ISD::SMAX:
11100     return getConstant(APInt::getSignedMinValue(VT.getSizeInBits()), DL, VT);
11101   case ISD::SMIN:
11102     return getConstant(APInt::getSignedMaxValue(VT.getSizeInBits()), DL, VT);
11103   case ISD::FADD:
11104     return getConstantFP(-0.0, DL, VT);
11105   case ISD::FMUL:
11106     return getConstantFP(1.0, DL, VT);
11107   case ISD::FMINNUM:
11108   case ISD::FMAXNUM: {
11109     // Neutral element for fminnum is NaN, Inf or FLT_MAX, depending on FMF.
11110     const fltSemantics &Semantics = EVTToAPFloatSemantics(VT);
11111     APFloat NeutralAF = !Flags.hasNoNaNs() ? APFloat::getQNaN(Semantics) :
11112                         !Flags.hasNoInfs() ? APFloat::getInf(Semantics) :
11113                         APFloat::getLargest(Semantics);
11114     if (Opcode == ISD::FMAXNUM)
11115       NeutralAF.changeSign();
11116 
11117     return getConstantFP(NeutralAF, DL, VT);
11118   }
11119   }
11120 }
11121 
11122 #ifndef NDEBUG
11123 static void checkForCyclesHelper(const SDNode *N,
11124                                  SmallPtrSetImpl<const SDNode*> &Visited,
11125                                  SmallPtrSetImpl<const SDNode*> &Checked,
11126                                  const llvm::SelectionDAG *DAG) {
11127   // If this node has already been checked, don't check it again.
11128   if (Checked.count(N))
11129     return;
11130 
11131   // If a node has already been visited on this depth-first walk, reject it as
11132   // a cycle.
11133   if (!Visited.insert(N).second) {
11134     errs() << "Detected cycle in SelectionDAG\n";
11135     dbgs() << "Offending node:\n";
11136     N->dumprFull(DAG); dbgs() << "\n";
11137     abort();
11138   }
11139 
11140   for (const SDValue &Op : N->op_values())
11141     checkForCyclesHelper(Op.getNode(), Visited, Checked, DAG);
11142 
11143   Checked.insert(N);
11144   Visited.erase(N);
11145 }
11146 #endif
11147 
11148 void llvm::checkForCycles(const llvm::SDNode *N,
11149                           const llvm::SelectionDAG *DAG,
11150                           bool force) {
11151 #ifndef NDEBUG
11152   bool check = force;
11153 #ifdef EXPENSIVE_CHECKS
11154   check = true;
11155 #endif  // EXPENSIVE_CHECKS
11156   if (check) {
11157     assert(N && "Checking nonexistent SDNode");
11158     SmallPtrSet<const SDNode*, 32> visited;
11159     SmallPtrSet<const SDNode*, 32> checked;
11160     checkForCyclesHelper(N, visited, checked, DAG);
11161   }
11162 #endif  // !NDEBUG
11163 }
11164 
11165 void llvm::checkForCycles(const llvm::SelectionDAG *DAG, bool force) {
11166   checkForCycles(DAG->getRoot().getNode(), DAG, force);
11167 }
11168