1 //===- SelectionDAG.cpp - Implement the SelectionDAG data structures ------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This implements the SelectionDAG class.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "llvm/CodeGen/SelectionDAG.h"
14 #include "SDNodeDbgValue.h"
15 #include "llvm/ADT/APFloat.h"
16 #include "llvm/ADT/APInt.h"
17 #include "llvm/ADT/APSInt.h"
18 #include "llvm/ADT/ArrayRef.h"
19 #include "llvm/ADT/BitVector.h"
20 #include "llvm/ADT/FoldingSet.h"
21 #include "llvm/ADT/None.h"
22 #include "llvm/ADT/STLExtras.h"
23 #include "llvm/ADT/SmallPtrSet.h"
24 #include "llvm/ADT/SmallVector.h"
25 #include "llvm/ADT/Triple.h"
26 #include "llvm/ADT/Twine.h"
27 #include "llvm/Analysis/BlockFrequencyInfo.h"
28 #include "llvm/Analysis/MemoryLocation.h"
29 #include "llvm/Analysis/ProfileSummaryInfo.h"
30 #include "llvm/Analysis/ValueTracking.h"
31 #include "llvm/CodeGen/FunctionLoweringInfo.h"
32 #include "llvm/CodeGen/ISDOpcodes.h"
33 #include "llvm/CodeGen/MachineBasicBlock.h"
34 #include "llvm/CodeGen/MachineConstantPool.h"
35 #include "llvm/CodeGen/MachineFrameInfo.h"
36 #include "llvm/CodeGen/MachineFunction.h"
37 #include "llvm/CodeGen/MachineMemOperand.h"
38 #include "llvm/CodeGen/RuntimeLibcalls.h"
39 #include "llvm/CodeGen/SelectionDAGAddressAnalysis.h"
40 #include "llvm/CodeGen/SelectionDAGNodes.h"
41 #include "llvm/CodeGen/SelectionDAGTargetInfo.h"
42 #include "llvm/CodeGen/TargetFrameLowering.h"
43 #include "llvm/CodeGen/TargetLowering.h"
44 #include "llvm/CodeGen/TargetRegisterInfo.h"
45 #include "llvm/CodeGen/TargetSubtargetInfo.h"
46 #include "llvm/CodeGen/ValueTypes.h"
47 #include "llvm/IR/Constant.h"
48 #include "llvm/IR/Constants.h"
49 #include "llvm/IR/DataLayout.h"
50 #include "llvm/IR/DebugInfoMetadata.h"
51 #include "llvm/IR/DebugLoc.h"
52 #include "llvm/IR/DerivedTypes.h"
53 #include "llvm/IR/Function.h"
54 #include "llvm/IR/GlobalValue.h"
55 #include "llvm/IR/Metadata.h"
56 #include "llvm/IR/Type.h"
57 #include "llvm/IR/Value.h"
58 #include "llvm/Support/Casting.h"
59 #include "llvm/Support/CodeGen.h"
60 #include "llvm/Support/Compiler.h"
61 #include "llvm/Support/Debug.h"
62 #include "llvm/Support/ErrorHandling.h"
63 #include "llvm/Support/KnownBits.h"
64 #include "llvm/Support/MachineValueType.h"
65 #include "llvm/Support/ManagedStatic.h"
66 #include "llvm/Support/MathExtras.h"
67 #include "llvm/Support/Mutex.h"
68 #include "llvm/Support/raw_ostream.h"
69 #include "llvm/Target/TargetMachine.h"
70 #include "llvm/Target/TargetOptions.h"
71 #include "llvm/Transforms/Utils/SizeOpts.h"
72 #include <algorithm>
73 #include <cassert>
74 #include <cstdint>
75 #include <cstdlib>
76 #include <limits>
77 #include <set>
78 #include <string>
79 #include <utility>
80 #include <vector>
81 
82 using namespace llvm;
83 
84 /// makeVTList - Return an instance of the SDVTList struct initialized with the
85 /// specified members.
86 static SDVTList makeVTList(const EVT *VTs, unsigned NumVTs) {
87   SDVTList Res = {VTs, NumVTs};
88   return Res;
89 }
90 
91 // Default null implementations of the callbacks.
92 void SelectionDAG::DAGUpdateListener::NodeDeleted(SDNode*, SDNode*) {}
93 void SelectionDAG::DAGUpdateListener::NodeUpdated(SDNode*) {}
94 void SelectionDAG::DAGUpdateListener::NodeInserted(SDNode *) {}
95 
96 void SelectionDAG::DAGNodeDeletedListener::anchor() {}
97 
98 #define DEBUG_TYPE "selectiondag"
99 
100 static cl::opt<bool> EnableMemCpyDAGOpt("enable-memcpy-dag-opt",
101        cl::Hidden, cl::init(true),
102        cl::desc("Gang up loads and stores generated by inlining of memcpy"));
103 
104 static cl::opt<int> MaxLdStGlue("ldstmemcpy-glue-max",
105        cl::desc("Number limit for gluing ld/st of memcpy."),
106        cl::Hidden, cl::init(0));
107 
108 static void NewSDValueDbgMsg(SDValue V, StringRef Msg, SelectionDAG *G) {
109   LLVM_DEBUG(dbgs() << Msg; V.getNode()->dump(G););
110 }
111 
112 //===----------------------------------------------------------------------===//
113 //                              ConstantFPSDNode Class
114 //===----------------------------------------------------------------------===//
115 
116 /// isExactlyValue - We don't rely on operator== working on double values, as
117 /// it returns true for things that are clearly not equal, like -0.0 and 0.0.
118 /// As such, this method can be used to do an exact bit-for-bit comparison of
119 /// two floating point values.
120 bool ConstantFPSDNode::isExactlyValue(const APFloat& V) const {
121   return getValueAPF().bitwiseIsEqual(V);
122 }
123 
124 bool ConstantFPSDNode::isValueValidForType(EVT VT,
125                                            const APFloat& Val) {
126   assert(VT.isFloatingPoint() && "Can only convert between FP types");
127 
128   // convert modifies in place, so make a copy.
129   APFloat Val2 = APFloat(Val);
130   bool losesInfo;
131   (void) Val2.convert(SelectionDAG::EVTToAPFloatSemantics(VT),
132                       APFloat::rmNearestTiesToEven,
133                       &losesInfo);
134   return !losesInfo;
135 }
136 
137 //===----------------------------------------------------------------------===//
138 //                              ISD Namespace
139 //===----------------------------------------------------------------------===//
140 
141 bool ISD::isConstantSplatVector(const SDNode *N, APInt &SplatVal) {
142   if (N->getOpcode() == ISD::SPLAT_VECTOR) {
143     unsigned EltSize =
144         N->getValueType(0).getVectorElementType().getSizeInBits();
145     if (auto *Op0 = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
146       SplatVal = Op0->getAPIntValue().truncOrSelf(EltSize);
147       return true;
148     }
149   }
150 
151   auto *BV = dyn_cast<BuildVectorSDNode>(N);
152   if (!BV)
153     return false;
154 
155   APInt SplatUndef;
156   unsigned SplatBitSize;
157   bool HasUndefs;
158   unsigned EltSize = N->getValueType(0).getVectorElementType().getSizeInBits();
159   return BV->isConstantSplat(SplatVal, SplatUndef, SplatBitSize, HasUndefs,
160                              EltSize) &&
161          EltSize == SplatBitSize;
162 }
163 
164 // FIXME: AllOnes and AllZeros duplicate a lot of code. Could these be
165 // specializations of the more general isConstantSplatVector()?
166 
167 bool ISD::isConstantSplatVectorAllOnes(const SDNode *N, bool BuildVectorOnly) {
168   // Look through a bit convert.
169   while (N->getOpcode() == ISD::BITCAST)
170     N = N->getOperand(0).getNode();
171 
172   if (!BuildVectorOnly && N->getOpcode() == ISD::SPLAT_VECTOR) {
173     APInt SplatVal;
174     return isConstantSplatVector(N, SplatVal) && SplatVal.isAllOnesValue();
175   }
176 
177   if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
178 
179   unsigned i = 0, e = N->getNumOperands();
180 
181   // Skip over all of the undef values.
182   while (i != e && N->getOperand(i).isUndef())
183     ++i;
184 
185   // Do not accept an all-undef vector.
186   if (i == e) return false;
187 
188   // Do not accept build_vectors that aren't all constants or which have non-~0
189   // elements. We have to be a bit careful here, as the type of the constant
190   // may not be the same as the type of the vector elements due to type
191   // legalization (the elements are promoted to a legal type for the target and
192   // a vector of a type may be legal when the base element type is not).
193   // We only want to check enough bits to cover the vector elements, because
194   // we care if the resultant vector is all ones, not whether the individual
195   // constants are.
196   SDValue NotZero = N->getOperand(i);
197   unsigned EltSize = N->getValueType(0).getScalarSizeInBits();
198   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(NotZero)) {
199     if (CN->getAPIntValue().countTrailingOnes() < EltSize)
200       return false;
201   } else if (ConstantFPSDNode *CFPN = dyn_cast<ConstantFPSDNode>(NotZero)) {
202     if (CFPN->getValueAPF().bitcastToAPInt().countTrailingOnes() < EltSize)
203       return false;
204   } else
205     return false;
206 
207   // Okay, we have at least one ~0 value, check to see if the rest match or are
208   // undefs. Even with the above element type twiddling, this should be OK, as
209   // the same type legalization should have applied to all the elements.
210   for (++i; i != e; ++i)
211     if (N->getOperand(i) != NotZero && !N->getOperand(i).isUndef())
212       return false;
213   return true;
214 }
215 
216 bool ISD::isConstantSplatVectorAllZeros(const SDNode *N, bool BuildVectorOnly) {
217   // Look through a bit convert.
218   while (N->getOpcode() == ISD::BITCAST)
219     N = N->getOperand(0).getNode();
220 
221   if (!BuildVectorOnly && N->getOpcode() == ISD::SPLAT_VECTOR) {
222     APInt SplatVal;
223     return isConstantSplatVector(N, SplatVal) && SplatVal.isNullValue();
224   }
225 
226   if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
227 
228   bool IsAllUndef = true;
229   for (const SDValue &Op : N->op_values()) {
230     if (Op.isUndef())
231       continue;
232     IsAllUndef = false;
233     // Do not accept build_vectors that aren't all constants or which have non-0
234     // elements. We have to be a bit careful here, as the type of the constant
235     // may not be the same as the type of the vector elements due to type
236     // legalization (the elements are promoted to a legal type for the target
237     // and a vector of a type may be legal when the base element type is not).
238     // We only want to check enough bits to cover the vector elements, because
239     // we care if the resultant vector is all zeros, not whether the individual
240     // constants are.
241     unsigned EltSize = N->getValueType(0).getScalarSizeInBits();
242     if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Op)) {
243       if (CN->getAPIntValue().countTrailingZeros() < EltSize)
244         return false;
245     } else if (ConstantFPSDNode *CFPN = dyn_cast<ConstantFPSDNode>(Op)) {
246       if (CFPN->getValueAPF().bitcastToAPInt().countTrailingZeros() < EltSize)
247         return false;
248     } else
249       return false;
250   }
251 
252   // Do not accept an all-undef vector.
253   if (IsAllUndef)
254     return false;
255   return true;
256 }
257 
258 bool ISD::isBuildVectorAllOnes(const SDNode *N) {
259   return isConstantSplatVectorAllOnes(N, /*BuildVectorOnly*/ true);
260 }
261 
262 bool ISD::isBuildVectorAllZeros(const SDNode *N) {
263   return isConstantSplatVectorAllZeros(N, /*BuildVectorOnly*/ true);
264 }
265 
266 bool ISD::isBuildVectorOfConstantSDNodes(const SDNode *N) {
267   if (N->getOpcode() != ISD::BUILD_VECTOR)
268     return false;
269 
270   for (const SDValue &Op : N->op_values()) {
271     if (Op.isUndef())
272       continue;
273     if (!isa<ConstantSDNode>(Op))
274       return false;
275   }
276   return true;
277 }
278 
279 bool ISD::isBuildVectorOfConstantFPSDNodes(const SDNode *N) {
280   if (N->getOpcode() != ISD::BUILD_VECTOR)
281     return false;
282 
283   for (const SDValue &Op : N->op_values()) {
284     if (Op.isUndef())
285       continue;
286     if (!isa<ConstantFPSDNode>(Op))
287       return false;
288   }
289   return true;
290 }
291 
292 bool ISD::allOperandsUndef(const SDNode *N) {
293   // Return false if the node has no operands.
294   // This is "logically inconsistent" with the definition of "all" but
295   // is probably the desired behavior.
296   if (N->getNumOperands() == 0)
297     return false;
298   return all_of(N->op_values(), [](SDValue Op) { return Op.isUndef(); });
299 }
300 
301 bool ISD::matchUnaryPredicate(SDValue Op,
302                               std::function<bool(ConstantSDNode *)> Match,
303                               bool AllowUndefs) {
304   // FIXME: Add support for scalar UNDEF cases?
305   if (auto *Cst = dyn_cast<ConstantSDNode>(Op))
306     return Match(Cst);
307 
308   // FIXME: Add support for vector UNDEF cases?
309   if (ISD::BUILD_VECTOR != Op.getOpcode() &&
310       ISD::SPLAT_VECTOR != Op.getOpcode())
311     return false;
312 
313   EVT SVT = Op.getValueType().getScalarType();
314   for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
315     if (AllowUndefs && Op.getOperand(i).isUndef()) {
316       if (!Match(nullptr))
317         return false;
318       continue;
319     }
320 
321     auto *Cst = dyn_cast<ConstantSDNode>(Op.getOperand(i));
322     if (!Cst || Cst->getValueType(0) != SVT || !Match(Cst))
323       return false;
324   }
325   return true;
326 }
327 
328 bool ISD::matchBinaryPredicate(
329     SDValue LHS, SDValue RHS,
330     std::function<bool(ConstantSDNode *, ConstantSDNode *)> Match,
331     bool AllowUndefs, bool AllowTypeMismatch) {
332   if (!AllowTypeMismatch && LHS.getValueType() != RHS.getValueType())
333     return false;
334 
335   // TODO: Add support for scalar UNDEF cases?
336   if (auto *LHSCst = dyn_cast<ConstantSDNode>(LHS))
337     if (auto *RHSCst = dyn_cast<ConstantSDNode>(RHS))
338       return Match(LHSCst, RHSCst);
339 
340   // TODO: Add support for vector UNDEF cases?
341   if (ISD::BUILD_VECTOR != LHS.getOpcode() ||
342       ISD::BUILD_VECTOR != RHS.getOpcode())
343     return false;
344 
345   EVT SVT = LHS.getValueType().getScalarType();
346   for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
347     SDValue LHSOp = LHS.getOperand(i);
348     SDValue RHSOp = RHS.getOperand(i);
349     bool LHSUndef = AllowUndefs && LHSOp.isUndef();
350     bool RHSUndef = AllowUndefs && RHSOp.isUndef();
351     auto *LHSCst = dyn_cast<ConstantSDNode>(LHSOp);
352     auto *RHSCst = dyn_cast<ConstantSDNode>(RHSOp);
353     if ((!LHSCst && !LHSUndef) || (!RHSCst && !RHSUndef))
354       return false;
355     if (!AllowTypeMismatch && (LHSOp.getValueType() != SVT ||
356                                LHSOp.getValueType() != RHSOp.getValueType()))
357       return false;
358     if (!Match(LHSCst, RHSCst))
359       return false;
360   }
361   return true;
362 }
363 
364 ISD::NodeType ISD::getVecReduceBaseOpcode(unsigned VecReduceOpcode) {
365   switch (VecReduceOpcode) {
366   default:
367     llvm_unreachable("Expected VECREDUCE opcode");
368   case ISD::VECREDUCE_FADD:
369   case ISD::VECREDUCE_SEQ_FADD:
370     return ISD::FADD;
371   case ISD::VECREDUCE_FMUL:
372   case ISD::VECREDUCE_SEQ_FMUL:
373     return ISD::FMUL;
374   case ISD::VECREDUCE_ADD:
375     return ISD::ADD;
376   case ISD::VECREDUCE_MUL:
377     return ISD::MUL;
378   case ISD::VECREDUCE_AND:
379     return ISD::AND;
380   case ISD::VECREDUCE_OR:
381     return ISD::OR;
382   case ISD::VECREDUCE_XOR:
383     return ISD::XOR;
384   case ISD::VECREDUCE_SMAX:
385     return ISD::SMAX;
386   case ISD::VECREDUCE_SMIN:
387     return ISD::SMIN;
388   case ISD::VECREDUCE_UMAX:
389     return ISD::UMAX;
390   case ISD::VECREDUCE_UMIN:
391     return ISD::UMIN;
392   case ISD::VECREDUCE_FMAX:
393     return ISD::FMAXNUM;
394   case ISD::VECREDUCE_FMIN:
395     return ISD::FMINNUM;
396   }
397 }
398 
399 bool ISD::isVPOpcode(unsigned Opcode) {
400   switch (Opcode) {
401   default:
402     return false;
403 #define BEGIN_REGISTER_VP_SDNODE(SDOPC, ...)                                   \
404   case ISD::SDOPC:                                                             \
405     return true;
406 #include "llvm/IR/VPIntrinsics.def"
407   }
408 }
409 
410 /// The operand position of the vector mask.
411 Optional<unsigned> ISD::getVPMaskIdx(unsigned Opcode) {
412   switch (Opcode) {
413   default:
414     return None;
415 #define BEGIN_REGISTER_VP_SDNODE(SDOPC, LEGALPOS, TDNAME, MASKPOS, ...)        \
416   case ISD::SDOPC:                                                             \
417     return MASKPOS;
418 #include "llvm/IR/VPIntrinsics.def"
419   }
420 }
421 
422 /// The operand position of the explicit vector length parameter.
423 Optional<unsigned> ISD::getVPExplicitVectorLengthIdx(unsigned Opcode) {
424   switch (Opcode) {
425   default:
426     return None;
427 #define BEGIN_REGISTER_VP_SDNODE(SDOPC, LEGALPOS, TDNAME, MASKPOS, EVLPOS)     \
428   case ISD::SDOPC:                                                             \
429     return EVLPOS;
430 #include "llvm/IR/VPIntrinsics.def"
431   }
432 }
433 
434 ISD::NodeType ISD::getExtForLoadExtType(bool IsFP, ISD::LoadExtType ExtType) {
435   switch (ExtType) {
436   case ISD::EXTLOAD:
437     return IsFP ? ISD::FP_EXTEND : ISD::ANY_EXTEND;
438   case ISD::SEXTLOAD:
439     return ISD::SIGN_EXTEND;
440   case ISD::ZEXTLOAD:
441     return ISD::ZERO_EXTEND;
442   default:
443     break;
444   }
445 
446   llvm_unreachable("Invalid LoadExtType");
447 }
448 
449 ISD::CondCode ISD::getSetCCSwappedOperands(ISD::CondCode Operation) {
450   // To perform this operation, we just need to swap the L and G bits of the
451   // operation.
452   unsigned OldL = (Operation >> 2) & 1;
453   unsigned OldG = (Operation >> 1) & 1;
454   return ISD::CondCode((Operation & ~6) |  // Keep the N, U, E bits
455                        (OldL << 1) |       // New G bit
456                        (OldG << 2));       // New L bit.
457 }
458 
459 static ISD::CondCode getSetCCInverseImpl(ISD::CondCode Op, bool isIntegerLike) {
460   unsigned Operation = Op;
461   if (isIntegerLike)
462     Operation ^= 7;   // Flip L, G, E bits, but not U.
463   else
464     Operation ^= 15;  // Flip all of the condition bits.
465 
466   if (Operation > ISD::SETTRUE2)
467     Operation &= ~8;  // Don't let N and U bits get set.
468 
469   return ISD::CondCode(Operation);
470 }
471 
472 ISD::CondCode ISD::getSetCCInverse(ISD::CondCode Op, EVT Type) {
473   return getSetCCInverseImpl(Op, Type.isInteger());
474 }
475 
476 ISD::CondCode ISD::GlobalISel::getSetCCInverse(ISD::CondCode Op,
477                                                bool isIntegerLike) {
478   return getSetCCInverseImpl(Op, isIntegerLike);
479 }
480 
481 /// For an integer comparison, return 1 if the comparison is a signed operation
482 /// and 2 if the result is an unsigned comparison. Return zero if the operation
483 /// does not depend on the sign of the input (setne and seteq).
484 static int isSignedOp(ISD::CondCode Opcode) {
485   switch (Opcode) {
486   default: llvm_unreachable("Illegal integer setcc operation!");
487   case ISD::SETEQ:
488   case ISD::SETNE: return 0;
489   case ISD::SETLT:
490   case ISD::SETLE:
491   case ISD::SETGT:
492   case ISD::SETGE: return 1;
493   case ISD::SETULT:
494   case ISD::SETULE:
495   case ISD::SETUGT:
496   case ISD::SETUGE: return 2;
497   }
498 }
499 
500 ISD::CondCode ISD::getSetCCOrOperation(ISD::CondCode Op1, ISD::CondCode Op2,
501                                        EVT Type) {
502   bool IsInteger = Type.isInteger();
503   if (IsInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
504     // Cannot fold a signed integer setcc with an unsigned integer setcc.
505     return ISD::SETCC_INVALID;
506 
507   unsigned Op = Op1 | Op2;  // Combine all of the condition bits.
508 
509   // If the N and U bits get set, then the resultant comparison DOES suddenly
510   // care about orderedness, and it is true when ordered.
511   if (Op > ISD::SETTRUE2)
512     Op &= ~16;     // Clear the U bit if the N bit is set.
513 
514   // Canonicalize illegal integer setcc's.
515   if (IsInteger && Op == ISD::SETUNE)  // e.g. SETUGT | SETULT
516     Op = ISD::SETNE;
517 
518   return ISD::CondCode(Op);
519 }
520 
521 ISD::CondCode ISD::getSetCCAndOperation(ISD::CondCode Op1, ISD::CondCode Op2,
522                                         EVT Type) {
523   bool IsInteger = Type.isInteger();
524   if (IsInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
525     // Cannot fold a signed setcc with an unsigned setcc.
526     return ISD::SETCC_INVALID;
527 
528   // Combine all of the condition bits.
529   ISD::CondCode Result = ISD::CondCode(Op1 & Op2);
530 
531   // Canonicalize illegal integer setcc's.
532   if (IsInteger) {
533     switch (Result) {
534     default: break;
535     case ISD::SETUO : Result = ISD::SETFALSE; break;  // SETUGT & SETULT
536     case ISD::SETOEQ:                                 // SETEQ  & SETU[LG]E
537     case ISD::SETUEQ: Result = ISD::SETEQ   ; break;  // SETUGE & SETULE
538     case ISD::SETOLT: Result = ISD::SETULT  ; break;  // SETULT & SETNE
539     case ISD::SETOGT: Result = ISD::SETUGT  ; break;  // SETUGT & SETNE
540     }
541   }
542 
543   return Result;
544 }
545 
546 //===----------------------------------------------------------------------===//
547 //                           SDNode Profile Support
548 //===----------------------------------------------------------------------===//
549 
550 /// AddNodeIDOpcode - Add the node opcode to the NodeID data.
551 static void AddNodeIDOpcode(FoldingSetNodeID &ID, unsigned OpC)  {
552   ID.AddInteger(OpC);
553 }
554 
555 /// AddNodeIDValueTypes - Value type lists are intern'd so we can represent them
556 /// solely with their pointer.
557 static void AddNodeIDValueTypes(FoldingSetNodeID &ID, SDVTList VTList) {
558   ID.AddPointer(VTList.VTs);
559 }
560 
561 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data.
562 static void AddNodeIDOperands(FoldingSetNodeID &ID,
563                               ArrayRef<SDValue> Ops) {
564   for (auto& Op : Ops) {
565     ID.AddPointer(Op.getNode());
566     ID.AddInteger(Op.getResNo());
567   }
568 }
569 
570 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data.
571 static void AddNodeIDOperands(FoldingSetNodeID &ID,
572                               ArrayRef<SDUse> Ops) {
573   for (auto& Op : Ops) {
574     ID.AddPointer(Op.getNode());
575     ID.AddInteger(Op.getResNo());
576   }
577 }
578 
579 static void AddNodeIDNode(FoldingSetNodeID &ID, unsigned short OpC,
580                           SDVTList VTList, ArrayRef<SDValue> OpList) {
581   AddNodeIDOpcode(ID, OpC);
582   AddNodeIDValueTypes(ID, VTList);
583   AddNodeIDOperands(ID, OpList);
584 }
585 
586 /// If this is an SDNode with special info, add this info to the NodeID data.
587 static void AddNodeIDCustom(FoldingSetNodeID &ID, const SDNode *N) {
588   switch (N->getOpcode()) {
589   case ISD::TargetExternalSymbol:
590   case ISD::ExternalSymbol:
591   case ISD::MCSymbol:
592     llvm_unreachable("Should only be used on nodes with operands");
593   default: break;  // Normal nodes don't need extra info.
594   case ISD::TargetConstant:
595   case ISD::Constant: {
596     const ConstantSDNode *C = cast<ConstantSDNode>(N);
597     ID.AddPointer(C->getConstantIntValue());
598     ID.AddBoolean(C->isOpaque());
599     break;
600   }
601   case ISD::TargetConstantFP:
602   case ISD::ConstantFP:
603     ID.AddPointer(cast<ConstantFPSDNode>(N)->getConstantFPValue());
604     break;
605   case ISD::TargetGlobalAddress:
606   case ISD::GlobalAddress:
607   case ISD::TargetGlobalTLSAddress:
608   case ISD::GlobalTLSAddress: {
609     const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(N);
610     ID.AddPointer(GA->getGlobal());
611     ID.AddInteger(GA->getOffset());
612     ID.AddInteger(GA->getTargetFlags());
613     break;
614   }
615   case ISD::BasicBlock:
616     ID.AddPointer(cast<BasicBlockSDNode>(N)->getBasicBlock());
617     break;
618   case ISD::Register:
619     ID.AddInteger(cast<RegisterSDNode>(N)->getReg());
620     break;
621   case ISD::RegisterMask:
622     ID.AddPointer(cast<RegisterMaskSDNode>(N)->getRegMask());
623     break;
624   case ISD::SRCVALUE:
625     ID.AddPointer(cast<SrcValueSDNode>(N)->getValue());
626     break;
627   case ISD::FrameIndex:
628   case ISD::TargetFrameIndex:
629     ID.AddInteger(cast<FrameIndexSDNode>(N)->getIndex());
630     break;
631   case ISD::LIFETIME_START:
632   case ISD::LIFETIME_END:
633     if (cast<LifetimeSDNode>(N)->hasOffset()) {
634       ID.AddInteger(cast<LifetimeSDNode>(N)->getSize());
635       ID.AddInteger(cast<LifetimeSDNode>(N)->getOffset());
636     }
637     break;
638   case ISD::PSEUDO_PROBE:
639     ID.AddInteger(cast<PseudoProbeSDNode>(N)->getGuid());
640     ID.AddInteger(cast<PseudoProbeSDNode>(N)->getIndex());
641     ID.AddInteger(cast<PseudoProbeSDNode>(N)->getAttributes());
642     break;
643   case ISD::JumpTable:
644   case ISD::TargetJumpTable:
645     ID.AddInteger(cast<JumpTableSDNode>(N)->getIndex());
646     ID.AddInteger(cast<JumpTableSDNode>(N)->getTargetFlags());
647     break;
648   case ISD::ConstantPool:
649   case ISD::TargetConstantPool: {
650     const ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(N);
651     ID.AddInteger(CP->getAlign().value());
652     ID.AddInteger(CP->getOffset());
653     if (CP->isMachineConstantPoolEntry())
654       CP->getMachineCPVal()->addSelectionDAGCSEId(ID);
655     else
656       ID.AddPointer(CP->getConstVal());
657     ID.AddInteger(CP->getTargetFlags());
658     break;
659   }
660   case ISD::TargetIndex: {
661     const TargetIndexSDNode *TI = cast<TargetIndexSDNode>(N);
662     ID.AddInteger(TI->getIndex());
663     ID.AddInteger(TI->getOffset());
664     ID.AddInteger(TI->getTargetFlags());
665     break;
666   }
667   case ISD::LOAD: {
668     const LoadSDNode *LD = cast<LoadSDNode>(N);
669     ID.AddInteger(LD->getMemoryVT().getRawBits());
670     ID.AddInteger(LD->getRawSubclassData());
671     ID.AddInteger(LD->getPointerInfo().getAddrSpace());
672     break;
673   }
674   case ISD::STORE: {
675     const StoreSDNode *ST = cast<StoreSDNode>(N);
676     ID.AddInteger(ST->getMemoryVT().getRawBits());
677     ID.AddInteger(ST->getRawSubclassData());
678     ID.AddInteger(ST->getPointerInfo().getAddrSpace());
679     break;
680   }
681   case ISD::MLOAD: {
682     const MaskedLoadSDNode *MLD = cast<MaskedLoadSDNode>(N);
683     ID.AddInteger(MLD->getMemoryVT().getRawBits());
684     ID.AddInteger(MLD->getRawSubclassData());
685     ID.AddInteger(MLD->getPointerInfo().getAddrSpace());
686     break;
687   }
688   case ISD::MSTORE: {
689     const MaskedStoreSDNode *MST = cast<MaskedStoreSDNode>(N);
690     ID.AddInteger(MST->getMemoryVT().getRawBits());
691     ID.AddInteger(MST->getRawSubclassData());
692     ID.AddInteger(MST->getPointerInfo().getAddrSpace());
693     break;
694   }
695   case ISD::MGATHER: {
696     const MaskedGatherSDNode *MG = cast<MaskedGatherSDNode>(N);
697     ID.AddInteger(MG->getMemoryVT().getRawBits());
698     ID.AddInteger(MG->getRawSubclassData());
699     ID.AddInteger(MG->getPointerInfo().getAddrSpace());
700     break;
701   }
702   case ISD::MSCATTER: {
703     const MaskedScatterSDNode *MS = cast<MaskedScatterSDNode>(N);
704     ID.AddInteger(MS->getMemoryVT().getRawBits());
705     ID.AddInteger(MS->getRawSubclassData());
706     ID.AddInteger(MS->getPointerInfo().getAddrSpace());
707     break;
708   }
709   case ISD::ATOMIC_CMP_SWAP:
710   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
711   case ISD::ATOMIC_SWAP:
712   case ISD::ATOMIC_LOAD_ADD:
713   case ISD::ATOMIC_LOAD_SUB:
714   case ISD::ATOMIC_LOAD_AND:
715   case ISD::ATOMIC_LOAD_CLR:
716   case ISD::ATOMIC_LOAD_OR:
717   case ISD::ATOMIC_LOAD_XOR:
718   case ISD::ATOMIC_LOAD_NAND:
719   case ISD::ATOMIC_LOAD_MIN:
720   case ISD::ATOMIC_LOAD_MAX:
721   case ISD::ATOMIC_LOAD_UMIN:
722   case ISD::ATOMIC_LOAD_UMAX:
723   case ISD::ATOMIC_LOAD:
724   case ISD::ATOMIC_STORE: {
725     const AtomicSDNode *AT = cast<AtomicSDNode>(N);
726     ID.AddInteger(AT->getMemoryVT().getRawBits());
727     ID.AddInteger(AT->getRawSubclassData());
728     ID.AddInteger(AT->getPointerInfo().getAddrSpace());
729     break;
730   }
731   case ISD::PREFETCH: {
732     const MemSDNode *PF = cast<MemSDNode>(N);
733     ID.AddInteger(PF->getPointerInfo().getAddrSpace());
734     break;
735   }
736   case ISD::VECTOR_SHUFFLE: {
737     const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
738     for (unsigned i = 0, e = N->getValueType(0).getVectorNumElements();
739          i != e; ++i)
740       ID.AddInteger(SVN->getMaskElt(i));
741     break;
742   }
743   case ISD::TargetBlockAddress:
744   case ISD::BlockAddress: {
745     const BlockAddressSDNode *BA = cast<BlockAddressSDNode>(N);
746     ID.AddPointer(BA->getBlockAddress());
747     ID.AddInteger(BA->getOffset());
748     ID.AddInteger(BA->getTargetFlags());
749     break;
750   }
751   } // end switch (N->getOpcode())
752 
753   // Target specific memory nodes could also have address spaces to check.
754   if (N->isTargetMemoryOpcode())
755     ID.AddInteger(cast<MemSDNode>(N)->getPointerInfo().getAddrSpace());
756 }
757 
758 /// AddNodeIDNode - Generic routine for adding a nodes info to the NodeID
759 /// data.
760 static void AddNodeIDNode(FoldingSetNodeID &ID, const SDNode *N) {
761   AddNodeIDOpcode(ID, N->getOpcode());
762   // Add the return value info.
763   AddNodeIDValueTypes(ID, N->getVTList());
764   // Add the operand info.
765   AddNodeIDOperands(ID, N->ops());
766 
767   // Handle SDNode leafs with special info.
768   AddNodeIDCustom(ID, N);
769 }
770 
771 //===----------------------------------------------------------------------===//
772 //                              SelectionDAG Class
773 //===----------------------------------------------------------------------===//
774 
775 /// doNotCSE - Return true if CSE should not be performed for this node.
776 static bool doNotCSE(SDNode *N) {
777   if (N->getValueType(0) == MVT::Glue)
778     return true; // Never CSE anything that produces a flag.
779 
780   switch (N->getOpcode()) {
781   default: break;
782   case ISD::HANDLENODE:
783   case ISD::EH_LABEL:
784     return true;   // Never CSE these nodes.
785   }
786 
787   // Check that remaining values produced are not flags.
788   for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
789     if (N->getValueType(i) == MVT::Glue)
790       return true; // Never CSE anything that produces a flag.
791 
792   return false;
793 }
794 
795 /// RemoveDeadNodes - This method deletes all unreachable nodes in the
796 /// SelectionDAG.
797 void SelectionDAG::RemoveDeadNodes() {
798   // Create a dummy node (which is not added to allnodes), that adds a reference
799   // to the root node, preventing it from being deleted.
800   HandleSDNode Dummy(getRoot());
801 
802   SmallVector<SDNode*, 128> DeadNodes;
803 
804   // Add all obviously-dead nodes to the DeadNodes worklist.
805   for (SDNode &Node : allnodes())
806     if (Node.use_empty())
807       DeadNodes.push_back(&Node);
808 
809   RemoveDeadNodes(DeadNodes);
810 
811   // If the root changed (e.g. it was a dead load, update the root).
812   setRoot(Dummy.getValue());
813 }
814 
815 /// RemoveDeadNodes - This method deletes the unreachable nodes in the
816 /// given list, and any nodes that become unreachable as a result.
817 void SelectionDAG::RemoveDeadNodes(SmallVectorImpl<SDNode *> &DeadNodes) {
818 
819   // Process the worklist, deleting the nodes and adding their uses to the
820   // worklist.
821   while (!DeadNodes.empty()) {
822     SDNode *N = DeadNodes.pop_back_val();
823     // Skip to next node if we've already managed to delete the node. This could
824     // happen if replacing a node causes a node previously added to the node to
825     // be deleted.
826     if (N->getOpcode() == ISD::DELETED_NODE)
827       continue;
828 
829     for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
830       DUL->NodeDeleted(N, nullptr);
831 
832     // Take the node out of the appropriate CSE map.
833     RemoveNodeFromCSEMaps(N);
834 
835     // Next, brutally remove the operand list.  This is safe to do, as there are
836     // no cycles in the graph.
837     for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) {
838       SDUse &Use = *I++;
839       SDNode *Operand = Use.getNode();
840       Use.set(SDValue());
841 
842       // Now that we removed this operand, see if there are no uses of it left.
843       if (Operand->use_empty())
844         DeadNodes.push_back(Operand);
845     }
846 
847     DeallocateNode(N);
848   }
849 }
850 
851 void SelectionDAG::RemoveDeadNode(SDNode *N){
852   SmallVector<SDNode*, 16> DeadNodes(1, N);
853 
854   // Create a dummy node that adds a reference to the root node, preventing
855   // it from being deleted.  (This matters if the root is an operand of the
856   // dead node.)
857   HandleSDNode Dummy(getRoot());
858 
859   RemoveDeadNodes(DeadNodes);
860 }
861 
862 void SelectionDAG::DeleteNode(SDNode *N) {
863   // First take this out of the appropriate CSE map.
864   RemoveNodeFromCSEMaps(N);
865 
866   // Finally, remove uses due to operands of this node, remove from the
867   // AllNodes list, and delete the node.
868   DeleteNodeNotInCSEMaps(N);
869 }
870 
871 void SelectionDAG::DeleteNodeNotInCSEMaps(SDNode *N) {
872   assert(N->getIterator() != AllNodes.begin() &&
873          "Cannot delete the entry node!");
874   assert(N->use_empty() && "Cannot delete a node that is not dead!");
875 
876   // Drop all of the operands and decrement used node's use counts.
877   N->DropOperands();
878 
879   DeallocateNode(N);
880 }
881 
882 void SDDbgInfo::add(SDDbgValue *V, bool isParameter) {
883   assert(!(V->isVariadic() && isParameter));
884   if (isParameter)
885     ByvalParmDbgValues.push_back(V);
886   else
887     DbgValues.push_back(V);
888   for (const SDNode *Node : V->getSDNodes())
889     if (Node)
890       DbgValMap[Node].push_back(V);
891 }
892 
893 void SDDbgInfo::erase(const SDNode *Node) {
894   DbgValMapType::iterator I = DbgValMap.find(Node);
895   if (I == DbgValMap.end())
896     return;
897   for (auto &Val: I->second)
898     Val->setIsInvalidated();
899   DbgValMap.erase(I);
900 }
901 
902 void SelectionDAG::DeallocateNode(SDNode *N) {
903   // If we have operands, deallocate them.
904   removeOperands(N);
905 
906   NodeAllocator.Deallocate(AllNodes.remove(N));
907 
908   // Set the opcode to DELETED_NODE to help catch bugs when node
909   // memory is reallocated.
910   // FIXME: There are places in SDag that have grown a dependency on the opcode
911   // value in the released node.
912   __asan_unpoison_memory_region(&N->NodeType, sizeof(N->NodeType));
913   N->NodeType = ISD::DELETED_NODE;
914 
915   // If any of the SDDbgValue nodes refer to this SDNode, invalidate
916   // them and forget about that node.
917   DbgInfo->erase(N);
918 }
919 
920 #ifndef NDEBUG
921 /// VerifySDNode - Sanity check the given SDNode.  Aborts if it is invalid.
922 static void VerifySDNode(SDNode *N) {
923   switch (N->getOpcode()) {
924   default:
925     break;
926   case ISD::BUILD_PAIR: {
927     EVT VT = N->getValueType(0);
928     assert(N->getNumValues() == 1 && "Too many results!");
929     assert(!VT.isVector() && (VT.isInteger() || VT.isFloatingPoint()) &&
930            "Wrong return type!");
931     assert(N->getNumOperands() == 2 && "Wrong number of operands!");
932     assert(N->getOperand(0).getValueType() == N->getOperand(1).getValueType() &&
933            "Mismatched operand types!");
934     assert(N->getOperand(0).getValueType().isInteger() == VT.isInteger() &&
935            "Wrong operand type!");
936     assert(VT.getSizeInBits() == 2 * N->getOperand(0).getValueSizeInBits() &&
937            "Wrong return type size");
938     break;
939   }
940   case ISD::BUILD_VECTOR: {
941     assert(N->getNumValues() == 1 && "Too many results!");
942     assert(N->getValueType(0).isVector() && "Wrong return type!");
943     assert(N->getNumOperands() == N->getValueType(0).getVectorNumElements() &&
944            "Wrong number of operands!");
945     EVT EltVT = N->getValueType(0).getVectorElementType();
946     for (const SDUse &Op : N->ops()) {
947       assert((Op.getValueType() == EltVT ||
948               (EltVT.isInteger() && Op.getValueType().isInteger() &&
949                EltVT.bitsLE(Op.getValueType()))) &&
950              "Wrong operand type!");
951       assert(Op.getValueType() == N->getOperand(0).getValueType() &&
952              "Operands must all have the same type");
953     }
954     break;
955   }
956   }
957 }
958 #endif // NDEBUG
959 
960 /// Insert a newly allocated node into the DAG.
961 ///
962 /// Handles insertion into the all nodes list and CSE map, as well as
963 /// verification and other common operations when a new node is allocated.
964 void SelectionDAG::InsertNode(SDNode *N) {
965   AllNodes.push_back(N);
966 #ifndef NDEBUG
967   N->PersistentId = NextPersistentId++;
968   VerifySDNode(N);
969 #endif
970   for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
971     DUL->NodeInserted(N);
972 }
973 
974 /// RemoveNodeFromCSEMaps - Take the specified node out of the CSE map that
975 /// correspond to it.  This is useful when we're about to delete or repurpose
976 /// the node.  We don't want future request for structurally identical nodes
977 /// to return N anymore.
978 bool SelectionDAG::RemoveNodeFromCSEMaps(SDNode *N) {
979   bool Erased = false;
980   switch (N->getOpcode()) {
981   case ISD::HANDLENODE: return false;  // noop.
982   case ISD::CONDCODE:
983     assert(CondCodeNodes[cast<CondCodeSDNode>(N)->get()] &&
984            "Cond code doesn't exist!");
985     Erased = CondCodeNodes[cast<CondCodeSDNode>(N)->get()] != nullptr;
986     CondCodeNodes[cast<CondCodeSDNode>(N)->get()] = nullptr;
987     break;
988   case ISD::ExternalSymbol:
989     Erased = ExternalSymbols.erase(cast<ExternalSymbolSDNode>(N)->getSymbol());
990     break;
991   case ISD::TargetExternalSymbol: {
992     ExternalSymbolSDNode *ESN = cast<ExternalSymbolSDNode>(N);
993     Erased = TargetExternalSymbols.erase(std::pair<std::string, unsigned>(
994         ESN->getSymbol(), ESN->getTargetFlags()));
995     break;
996   }
997   case ISD::MCSymbol: {
998     auto *MCSN = cast<MCSymbolSDNode>(N);
999     Erased = MCSymbols.erase(MCSN->getMCSymbol());
1000     break;
1001   }
1002   case ISD::VALUETYPE: {
1003     EVT VT = cast<VTSDNode>(N)->getVT();
1004     if (VT.isExtended()) {
1005       Erased = ExtendedValueTypeNodes.erase(VT);
1006     } else {
1007       Erased = ValueTypeNodes[VT.getSimpleVT().SimpleTy] != nullptr;
1008       ValueTypeNodes[VT.getSimpleVT().SimpleTy] = nullptr;
1009     }
1010     break;
1011   }
1012   default:
1013     // Remove it from the CSE Map.
1014     assert(N->getOpcode() != ISD::DELETED_NODE && "DELETED_NODE in CSEMap!");
1015     assert(N->getOpcode() != ISD::EntryToken && "EntryToken in CSEMap!");
1016     Erased = CSEMap.RemoveNode(N);
1017     break;
1018   }
1019 #ifndef NDEBUG
1020   // Verify that the node was actually in one of the CSE maps, unless it has a
1021   // flag result (which cannot be CSE'd) or is one of the special cases that are
1022   // not subject to CSE.
1023   if (!Erased && N->getValueType(N->getNumValues()-1) != MVT::Glue &&
1024       !N->isMachineOpcode() && !doNotCSE(N)) {
1025     N->dump(this);
1026     dbgs() << "\n";
1027     llvm_unreachable("Node is not in map!");
1028   }
1029 #endif
1030   return Erased;
1031 }
1032 
1033 /// AddModifiedNodeToCSEMaps - The specified node has been removed from the CSE
1034 /// maps and modified in place. Add it back to the CSE maps, unless an identical
1035 /// node already exists, in which case transfer all its users to the existing
1036 /// node. This transfer can potentially trigger recursive merging.
1037 void
1038 SelectionDAG::AddModifiedNodeToCSEMaps(SDNode *N) {
1039   // For node types that aren't CSE'd, just act as if no identical node
1040   // already exists.
1041   if (!doNotCSE(N)) {
1042     SDNode *Existing = CSEMap.GetOrInsertNode(N);
1043     if (Existing != N) {
1044       // If there was already an existing matching node, use ReplaceAllUsesWith
1045       // to replace the dead one with the existing one.  This can cause
1046       // recursive merging of other unrelated nodes down the line.
1047       ReplaceAllUsesWith(N, Existing);
1048 
1049       // N is now dead. Inform the listeners and delete it.
1050       for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
1051         DUL->NodeDeleted(N, Existing);
1052       DeleteNodeNotInCSEMaps(N);
1053       return;
1054     }
1055   }
1056 
1057   // If the node doesn't already exist, we updated it.  Inform listeners.
1058   for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
1059     DUL->NodeUpdated(N);
1060 }
1061 
1062 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
1063 /// were replaced with those specified.  If this node is never memoized,
1064 /// return null, otherwise return a pointer to the slot it would take.  If a
1065 /// node already exists with these operands, the slot will be non-null.
1066 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, SDValue Op,
1067                                            void *&InsertPos) {
1068   if (doNotCSE(N))
1069     return nullptr;
1070 
1071   SDValue Ops[] = { Op };
1072   FoldingSetNodeID ID;
1073   AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops);
1074   AddNodeIDCustom(ID, N);
1075   SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos);
1076   if (Node)
1077     Node->intersectFlagsWith(N->getFlags());
1078   return Node;
1079 }
1080 
1081 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
1082 /// were replaced with those specified.  If this node is never memoized,
1083 /// return null, otherwise return a pointer to the slot it would take.  If a
1084 /// node already exists with these operands, the slot will be non-null.
1085 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N,
1086                                            SDValue Op1, SDValue Op2,
1087                                            void *&InsertPos) {
1088   if (doNotCSE(N))
1089     return nullptr;
1090 
1091   SDValue Ops[] = { Op1, Op2 };
1092   FoldingSetNodeID ID;
1093   AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops);
1094   AddNodeIDCustom(ID, N);
1095   SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos);
1096   if (Node)
1097     Node->intersectFlagsWith(N->getFlags());
1098   return Node;
1099 }
1100 
1101 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
1102 /// were replaced with those specified.  If this node is never memoized,
1103 /// return null, otherwise return a pointer to the slot it would take.  If a
1104 /// node already exists with these operands, the slot will be non-null.
1105 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, ArrayRef<SDValue> Ops,
1106                                            void *&InsertPos) {
1107   if (doNotCSE(N))
1108     return nullptr;
1109 
1110   FoldingSetNodeID ID;
1111   AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops);
1112   AddNodeIDCustom(ID, N);
1113   SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos);
1114   if (Node)
1115     Node->intersectFlagsWith(N->getFlags());
1116   return Node;
1117 }
1118 
1119 Align SelectionDAG::getEVTAlign(EVT VT) const {
1120   Type *Ty = VT == MVT::iPTR ?
1121                    PointerType::get(Type::getInt8Ty(*getContext()), 0) :
1122                    VT.getTypeForEVT(*getContext());
1123 
1124   return getDataLayout().getABITypeAlign(Ty);
1125 }
1126 
1127 // EntryNode could meaningfully have debug info if we can find it...
1128 SelectionDAG::SelectionDAG(const TargetMachine &tm, CodeGenOpt::Level OL)
1129     : TM(tm), OptLevel(OL),
1130       EntryNode(ISD::EntryToken, 0, DebugLoc(), getVTList(MVT::Other)),
1131       Root(getEntryNode()) {
1132   InsertNode(&EntryNode);
1133   DbgInfo = new SDDbgInfo();
1134 }
1135 
1136 void SelectionDAG::init(MachineFunction &NewMF,
1137                         OptimizationRemarkEmitter &NewORE,
1138                         Pass *PassPtr, const TargetLibraryInfo *LibraryInfo,
1139                         LegacyDivergenceAnalysis * Divergence,
1140                         ProfileSummaryInfo *PSIin,
1141                         BlockFrequencyInfo *BFIin) {
1142   MF = &NewMF;
1143   SDAGISelPass = PassPtr;
1144   ORE = &NewORE;
1145   TLI = getSubtarget().getTargetLowering();
1146   TSI = getSubtarget().getSelectionDAGInfo();
1147   LibInfo = LibraryInfo;
1148   Context = &MF->getFunction().getContext();
1149   DA = Divergence;
1150   PSI = PSIin;
1151   BFI = BFIin;
1152 }
1153 
1154 SelectionDAG::~SelectionDAG() {
1155   assert(!UpdateListeners && "Dangling registered DAGUpdateListeners");
1156   allnodes_clear();
1157   OperandRecycler.clear(OperandAllocator);
1158   delete DbgInfo;
1159 }
1160 
1161 bool SelectionDAG::shouldOptForSize() const {
1162   return MF->getFunction().hasOptSize() ||
1163       llvm::shouldOptimizeForSize(FLI->MBB->getBasicBlock(), PSI, BFI);
1164 }
1165 
1166 void SelectionDAG::allnodes_clear() {
1167   assert(&*AllNodes.begin() == &EntryNode);
1168   AllNodes.remove(AllNodes.begin());
1169   while (!AllNodes.empty())
1170     DeallocateNode(&AllNodes.front());
1171 #ifndef NDEBUG
1172   NextPersistentId = 0;
1173 #endif
1174 }
1175 
1176 SDNode *SelectionDAG::FindNodeOrInsertPos(const FoldingSetNodeID &ID,
1177                                           void *&InsertPos) {
1178   SDNode *N = CSEMap.FindNodeOrInsertPos(ID, InsertPos);
1179   if (N) {
1180     switch (N->getOpcode()) {
1181     default: break;
1182     case ISD::Constant:
1183     case ISD::ConstantFP:
1184       llvm_unreachable("Querying for Constant and ConstantFP nodes requires "
1185                        "debug location.  Use another overload.");
1186     }
1187   }
1188   return N;
1189 }
1190 
1191 SDNode *SelectionDAG::FindNodeOrInsertPos(const FoldingSetNodeID &ID,
1192                                           const SDLoc &DL, void *&InsertPos) {
1193   SDNode *N = CSEMap.FindNodeOrInsertPos(ID, InsertPos);
1194   if (N) {
1195     switch (N->getOpcode()) {
1196     case ISD::Constant:
1197     case ISD::ConstantFP:
1198       // Erase debug location from the node if the node is used at several
1199       // different places. Do not propagate one location to all uses as it
1200       // will cause a worse single stepping debugging experience.
1201       if (N->getDebugLoc() != DL.getDebugLoc())
1202         N->setDebugLoc(DebugLoc());
1203       break;
1204     default:
1205       // When the node's point of use is located earlier in the instruction
1206       // sequence than its prior point of use, update its debug info to the
1207       // earlier location.
1208       if (DL.getIROrder() && DL.getIROrder() < N->getIROrder())
1209         N->setDebugLoc(DL.getDebugLoc());
1210       break;
1211     }
1212   }
1213   return N;
1214 }
1215 
1216 void SelectionDAG::clear() {
1217   allnodes_clear();
1218   OperandRecycler.clear(OperandAllocator);
1219   OperandAllocator.Reset();
1220   CSEMap.clear();
1221 
1222   ExtendedValueTypeNodes.clear();
1223   ExternalSymbols.clear();
1224   TargetExternalSymbols.clear();
1225   MCSymbols.clear();
1226   SDCallSiteDbgInfo.clear();
1227   std::fill(CondCodeNodes.begin(), CondCodeNodes.end(),
1228             static_cast<CondCodeSDNode*>(nullptr));
1229   std::fill(ValueTypeNodes.begin(), ValueTypeNodes.end(),
1230             static_cast<SDNode*>(nullptr));
1231 
1232   EntryNode.UseList = nullptr;
1233   InsertNode(&EntryNode);
1234   Root = getEntryNode();
1235   DbgInfo->clear();
1236 }
1237 
1238 SDValue SelectionDAG::getFPExtendOrRound(SDValue Op, const SDLoc &DL, EVT VT) {
1239   return VT.bitsGT(Op.getValueType())
1240              ? getNode(ISD::FP_EXTEND, DL, VT, Op)
1241              : getNode(ISD::FP_ROUND, DL, VT, Op, getIntPtrConstant(0, DL));
1242 }
1243 
1244 std::pair<SDValue, SDValue>
1245 SelectionDAG::getStrictFPExtendOrRound(SDValue Op, SDValue Chain,
1246                                        const SDLoc &DL, EVT VT) {
1247   assert(!VT.bitsEq(Op.getValueType()) &&
1248          "Strict no-op FP extend/round not allowed.");
1249   SDValue Res =
1250       VT.bitsGT(Op.getValueType())
1251           ? getNode(ISD::STRICT_FP_EXTEND, DL, {VT, MVT::Other}, {Chain, Op})
1252           : getNode(ISD::STRICT_FP_ROUND, DL, {VT, MVT::Other},
1253                     {Chain, Op, getIntPtrConstant(0, DL)});
1254 
1255   return std::pair<SDValue, SDValue>(Res, SDValue(Res.getNode(), 1));
1256 }
1257 
1258 SDValue SelectionDAG::getAnyExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
1259   return VT.bitsGT(Op.getValueType()) ?
1260     getNode(ISD::ANY_EXTEND, DL, VT, Op) :
1261     getNode(ISD::TRUNCATE, DL, VT, Op);
1262 }
1263 
1264 SDValue SelectionDAG::getSExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
1265   return VT.bitsGT(Op.getValueType()) ?
1266     getNode(ISD::SIGN_EXTEND, DL, VT, Op) :
1267     getNode(ISD::TRUNCATE, DL, VT, Op);
1268 }
1269 
1270 SDValue SelectionDAG::getZExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
1271   return VT.bitsGT(Op.getValueType()) ?
1272     getNode(ISD::ZERO_EXTEND, DL, VT, Op) :
1273     getNode(ISD::TRUNCATE, DL, VT, Op);
1274 }
1275 
1276 SDValue SelectionDAG::getBoolExtOrTrunc(SDValue Op, const SDLoc &SL, EVT VT,
1277                                         EVT OpVT) {
1278   if (VT.bitsLE(Op.getValueType()))
1279     return getNode(ISD::TRUNCATE, SL, VT, Op);
1280 
1281   TargetLowering::BooleanContent BType = TLI->getBooleanContents(OpVT);
1282   return getNode(TLI->getExtendForContent(BType), SL, VT, Op);
1283 }
1284 
1285 SDValue SelectionDAG::getZeroExtendInReg(SDValue Op, const SDLoc &DL, EVT VT) {
1286   EVT OpVT = Op.getValueType();
1287   assert(VT.isInteger() && OpVT.isInteger() &&
1288          "Cannot getZeroExtendInReg FP types");
1289   assert(VT.isVector() == OpVT.isVector() &&
1290          "getZeroExtendInReg type should be vector iff the operand "
1291          "type is vector!");
1292   assert((!VT.isVector() ||
1293           VT.getVectorElementCount() == OpVT.getVectorElementCount()) &&
1294          "Vector element counts must match in getZeroExtendInReg");
1295   assert(VT.bitsLE(OpVT) && "Not extending!");
1296   if (OpVT == VT)
1297     return Op;
1298   APInt Imm = APInt::getLowBitsSet(OpVT.getScalarSizeInBits(),
1299                                    VT.getScalarSizeInBits());
1300   return getNode(ISD::AND, DL, OpVT, Op, getConstant(Imm, DL, OpVT));
1301 }
1302 
1303 SDValue SelectionDAG::getPtrExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
1304   // Only unsigned pointer semantics are supported right now. In the future this
1305   // might delegate to TLI to check pointer signedness.
1306   return getZExtOrTrunc(Op, DL, VT);
1307 }
1308 
1309 SDValue SelectionDAG::getPtrExtendInReg(SDValue Op, const SDLoc &DL, EVT VT) {
1310   // Only unsigned pointer semantics are supported right now. In the future this
1311   // might delegate to TLI to check pointer signedness.
1312   return getZeroExtendInReg(Op, DL, VT);
1313 }
1314 
1315 /// getNOT - Create a bitwise NOT operation as (XOR Val, -1).
1316 SDValue SelectionDAG::getNOT(const SDLoc &DL, SDValue Val, EVT VT) {
1317   EVT EltVT = VT.getScalarType();
1318   SDValue NegOne =
1319     getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), DL, VT);
1320   return getNode(ISD::XOR, DL, VT, Val, NegOne);
1321 }
1322 
1323 SDValue SelectionDAG::getLogicalNOT(const SDLoc &DL, SDValue Val, EVT VT) {
1324   SDValue TrueValue = getBoolConstant(true, DL, VT, VT);
1325   return getNode(ISD::XOR, DL, VT, Val, TrueValue);
1326 }
1327 
1328 SDValue SelectionDAG::getBoolConstant(bool V, const SDLoc &DL, EVT VT,
1329                                       EVT OpVT) {
1330   if (!V)
1331     return getConstant(0, DL, VT);
1332 
1333   switch (TLI->getBooleanContents(OpVT)) {
1334   case TargetLowering::ZeroOrOneBooleanContent:
1335   case TargetLowering::UndefinedBooleanContent:
1336     return getConstant(1, DL, VT);
1337   case TargetLowering::ZeroOrNegativeOneBooleanContent:
1338     return getAllOnesConstant(DL, VT);
1339   }
1340   llvm_unreachable("Unexpected boolean content enum!");
1341 }
1342 
1343 SDValue SelectionDAG::getConstant(uint64_t Val, const SDLoc &DL, EVT VT,
1344                                   bool isT, bool isO) {
1345   EVT EltVT = VT.getScalarType();
1346   assert((EltVT.getSizeInBits() >= 64 ||
1347           (uint64_t)((int64_t)Val >> EltVT.getSizeInBits()) + 1 < 2) &&
1348          "getConstant with a uint64_t value that doesn't fit in the type!");
1349   return getConstant(APInt(EltVT.getSizeInBits(), Val), DL, VT, isT, isO);
1350 }
1351 
1352 SDValue SelectionDAG::getConstant(const APInt &Val, const SDLoc &DL, EVT VT,
1353                                   bool isT, bool isO) {
1354   return getConstant(*ConstantInt::get(*Context, Val), DL, VT, isT, isO);
1355 }
1356 
1357 SDValue SelectionDAG::getConstant(const ConstantInt &Val, const SDLoc &DL,
1358                                   EVT VT, bool isT, bool isO) {
1359   assert(VT.isInteger() && "Cannot create FP integer constant!");
1360 
1361   EVT EltVT = VT.getScalarType();
1362   const ConstantInt *Elt = &Val;
1363 
1364   // In some cases the vector type is legal but the element type is illegal and
1365   // needs to be promoted, for example v8i8 on ARM.  In this case, promote the
1366   // inserted value (the type does not need to match the vector element type).
1367   // Any extra bits introduced will be truncated away.
1368   if (VT.isVector() && TLI->getTypeAction(*getContext(), EltVT) ==
1369                            TargetLowering::TypePromoteInteger) {
1370     EltVT = TLI->getTypeToTransformTo(*getContext(), EltVT);
1371     APInt NewVal = Elt->getValue().zextOrTrunc(EltVT.getSizeInBits());
1372     Elt = ConstantInt::get(*getContext(), NewVal);
1373   }
1374   // In other cases the element type is illegal and needs to be expanded, for
1375   // example v2i64 on MIPS32. In this case, find the nearest legal type, split
1376   // the value into n parts and use a vector type with n-times the elements.
1377   // Then bitcast to the type requested.
1378   // Legalizing constants too early makes the DAGCombiner's job harder so we
1379   // only legalize if the DAG tells us we must produce legal types.
1380   else if (NewNodesMustHaveLegalTypes && VT.isVector() &&
1381            TLI->getTypeAction(*getContext(), EltVT) ==
1382                TargetLowering::TypeExpandInteger) {
1383     const APInt &NewVal = Elt->getValue();
1384     EVT ViaEltVT = TLI->getTypeToTransformTo(*getContext(), EltVT);
1385     unsigned ViaEltSizeInBits = ViaEltVT.getSizeInBits();
1386 
1387     // For scalable vectors, try to use a SPLAT_VECTOR_PARTS node.
1388     if (VT.isScalableVector()) {
1389       assert(EltVT.getSizeInBits() % ViaEltSizeInBits == 0 &&
1390              "Can only handle an even split!");
1391       unsigned Parts = EltVT.getSizeInBits() / ViaEltSizeInBits;
1392 
1393       SmallVector<SDValue, 2> ScalarParts;
1394       for (unsigned i = 0; i != Parts; ++i)
1395         ScalarParts.push_back(getConstant(
1396             NewVal.lshr(i * ViaEltSizeInBits).trunc(ViaEltSizeInBits), DL,
1397             ViaEltVT, isT, isO));
1398 
1399       return getNode(ISD::SPLAT_VECTOR_PARTS, DL, VT, ScalarParts);
1400     }
1401 
1402     unsigned ViaVecNumElts = VT.getSizeInBits() / ViaEltSizeInBits;
1403     EVT ViaVecVT = EVT::getVectorVT(*getContext(), ViaEltVT, ViaVecNumElts);
1404 
1405     // Check the temporary vector is the correct size. If this fails then
1406     // getTypeToTransformTo() probably returned a type whose size (in bits)
1407     // isn't a power-of-2 factor of the requested type size.
1408     assert(ViaVecVT.getSizeInBits() == VT.getSizeInBits());
1409 
1410     SmallVector<SDValue, 2> EltParts;
1411     for (unsigned i = 0; i < ViaVecNumElts / VT.getVectorNumElements(); ++i) {
1412       EltParts.push_back(getConstant(
1413           NewVal.lshr(i * ViaEltSizeInBits).zextOrTrunc(ViaEltSizeInBits), DL,
1414           ViaEltVT, isT, isO));
1415     }
1416 
1417     // EltParts is currently in little endian order. If we actually want
1418     // big-endian order then reverse it now.
1419     if (getDataLayout().isBigEndian())
1420       std::reverse(EltParts.begin(), EltParts.end());
1421 
1422     // The elements must be reversed when the element order is different
1423     // to the endianness of the elements (because the BITCAST is itself a
1424     // vector shuffle in this situation). However, we do not need any code to
1425     // perform this reversal because getConstant() is producing a vector
1426     // splat.
1427     // This situation occurs in MIPS MSA.
1428 
1429     SmallVector<SDValue, 8> Ops;
1430     for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
1431       llvm::append_range(Ops, EltParts);
1432 
1433     SDValue V =
1434         getNode(ISD::BITCAST, DL, VT, getBuildVector(ViaVecVT, DL, Ops));
1435     return V;
1436   }
1437 
1438   assert(Elt->getBitWidth() == EltVT.getSizeInBits() &&
1439          "APInt size does not match type size!");
1440   unsigned Opc = isT ? ISD::TargetConstant : ISD::Constant;
1441   FoldingSetNodeID ID;
1442   AddNodeIDNode(ID, Opc, getVTList(EltVT), None);
1443   ID.AddPointer(Elt);
1444   ID.AddBoolean(isO);
1445   void *IP = nullptr;
1446   SDNode *N = nullptr;
1447   if ((N = FindNodeOrInsertPos(ID, DL, IP)))
1448     if (!VT.isVector())
1449       return SDValue(N, 0);
1450 
1451   if (!N) {
1452     N = newSDNode<ConstantSDNode>(isT, isO, Elt, EltVT);
1453     CSEMap.InsertNode(N, IP);
1454     InsertNode(N);
1455     NewSDValueDbgMsg(SDValue(N, 0), "Creating constant: ", this);
1456   }
1457 
1458   SDValue Result(N, 0);
1459   if (VT.isScalableVector())
1460     Result = getSplatVector(VT, DL, Result);
1461   else if (VT.isVector())
1462     Result = getSplatBuildVector(VT, DL, Result);
1463 
1464   return Result;
1465 }
1466 
1467 SDValue SelectionDAG::getIntPtrConstant(uint64_t Val, const SDLoc &DL,
1468                                         bool isTarget) {
1469   return getConstant(Val, DL, TLI->getPointerTy(getDataLayout()), isTarget);
1470 }
1471 
1472 SDValue SelectionDAG::getShiftAmountConstant(uint64_t Val, EVT VT,
1473                                              const SDLoc &DL, bool LegalTypes) {
1474   assert(VT.isInteger() && "Shift amount is not an integer type!");
1475   EVT ShiftVT = TLI->getShiftAmountTy(VT, getDataLayout(), LegalTypes);
1476   return getConstant(Val, DL, ShiftVT);
1477 }
1478 
1479 SDValue SelectionDAG::getVectorIdxConstant(uint64_t Val, const SDLoc &DL,
1480                                            bool isTarget) {
1481   return getConstant(Val, DL, TLI->getVectorIdxTy(getDataLayout()), isTarget);
1482 }
1483 
1484 SDValue SelectionDAG::getConstantFP(const APFloat &V, const SDLoc &DL, EVT VT,
1485                                     bool isTarget) {
1486   return getConstantFP(*ConstantFP::get(*getContext(), V), DL, VT, isTarget);
1487 }
1488 
1489 SDValue SelectionDAG::getConstantFP(const ConstantFP &V, const SDLoc &DL,
1490                                     EVT VT, bool isTarget) {
1491   assert(VT.isFloatingPoint() && "Cannot create integer FP constant!");
1492 
1493   EVT EltVT = VT.getScalarType();
1494 
1495   // Do the map lookup using the actual bit pattern for the floating point
1496   // value, so that we don't have problems with 0.0 comparing equal to -0.0, and
1497   // we don't have issues with SNANs.
1498   unsigned Opc = isTarget ? ISD::TargetConstantFP : ISD::ConstantFP;
1499   FoldingSetNodeID ID;
1500   AddNodeIDNode(ID, Opc, getVTList(EltVT), None);
1501   ID.AddPointer(&V);
1502   void *IP = nullptr;
1503   SDNode *N = nullptr;
1504   if ((N = FindNodeOrInsertPos(ID, DL, IP)))
1505     if (!VT.isVector())
1506       return SDValue(N, 0);
1507 
1508   if (!N) {
1509     N = newSDNode<ConstantFPSDNode>(isTarget, &V, EltVT);
1510     CSEMap.InsertNode(N, IP);
1511     InsertNode(N);
1512   }
1513 
1514   SDValue Result(N, 0);
1515   if (VT.isScalableVector())
1516     Result = getSplatVector(VT, DL, Result);
1517   else if (VT.isVector())
1518     Result = getSplatBuildVector(VT, DL, Result);
1519   NewSDValueDbgMsg(Result, "Creating fp constant: ", this);
1520   return Result;
1521 }
1522 
1523 SDValue SelectionDAG::getConstantFP(double Val, const SDLoc &DL, EVT VT,
1524                                     bool isTarget) {
1525   EVT EltVT = VT.getScalarType();
1526   if (EltVT == MVT::f32)
1527     return getConstantFP(APFloat((float)Val), DL, VT, isTarget);
1528   else if (EltVT == MVT::f64)
1529     return getConstantFP(APFloat(Val), DL, VT, isTarget);
1530   else if (EltVT == MVT::f80 || EltVT == MVT::f128 || EltVT == MVT::ppcf128 ||
1531            EltVT == MVT::f16 || EltVT == MVT::bf16) {
1532     bool Ignored;
1533     APFloat APF = APFloat(Val);
1534     APF.convert(EVTToAPFloatSemantics(EltVT), APFloat::rmNearestTiesToEven,
1535                 &Ignored);
1536     return getConstantFP(APF, DL, VT, isTarget);
1537   } else
1538     llvm_unreachable("Unsupported type in getConstantFP");
1539 }
1540 
1541 SDValue SelectionDAG::getGlobalAddress(const GlobalValue *GV, const SDLoc &DL,
1542                                        EVT VT, int64_t Offset, bool isTargetGA,
1543                                        unsigned TargetFlags) {
1544   assert((TargetFlags == 0 || isTargetGA) &&
1545          "Cannot set target flags on target-independent globals");
1546 
1547   // Truncate (with sign-extension) the offset value to the pointer size.
1548   unsigned BitWidth = getDataLayout().getPointerTypeSizeInBits(GV->getType());
1549   if (BitWidth < 64)
1550     Offset = SignExtend64(Offset, BitWidth);
1551 
1552   unsigned Opc;
1553   if (GV->isThreadLocal())
1554     Opc = isTargetGA ? ISD::TargetGlobalTLSAddress : ISD::GlobalTLSAddress;
1555   else
1556     Opc = isTargetGA ? ISD::TargetGlobalAddress : ISD::GlobalAddress;
1557 
1558   FoldingSetNodeID ID;
1559   AddNodeIDNode(ID, Opc, getVTList(VT), None);
1560   ID.AddPointer(GV);
1561   ID.AddInteger(Offset);
1562   ID.AddInteger(TargetFlags);
1563   void *IP = nullptr;
1564   if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
1565     return SDValue(E, 0);
1566 
1567   auto *N = newSDNode<GlobalAddressSDNode>(
1568       Opc, DL.getIROrder(), DL.getDebugLoc(), GV, VT, Offset, TargetFlags);
1569   CSEMap.InsertNode(N, IP);
1570     InsertNode(N);
1571   return SDValue(N, 0);
1572 }
1573 
1574 SDValue SelectionDAG::getFrameIndex(int FI, EVT VT, bool isTarget) {
1575   unsigned Opc = isTarget ? ISD::TargetFrameIndex : ISD::FrameIndex;
1576   FoldingSetNodeID ID;
1577   AddNodeIDNode(ID, Opc, getVTList(VT), None);
1578   ID.AddInteger(FI);
1579   void *IP = nullptr;
1580   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1581     return SDValue(E, 0);
1582 
1583   auto *N = newSDNode<FrameIndexSDNode>(FI, VT, isTarget);
1584   CSEMap.InsertNode(N, IP);
1585   InsertNode(N);
1586   return SDValue(N, 0);
1587 }
1588 
1589 SDValue SelectionDAG::getJumpTable(int JTI, EVT VT, bool isTarget,
1590                                    unsigned TargetFlags) {
1591   assert((TargetFlags == 0 || isTarget) &&
1592          "Cannot set target flags on target-independent jump tables");
1593   unsigned Opc = isTarget ? ISD::TargetJumpTable : ISD::JumpTable;
1594   FoldingSetNodeID ID;
1595   AddNodeIDNode(ID, Opc, getVTList(VT), None);
1596   ID.AddInteger(JTI);
1597   ID.AddInteger(TargetFlags);
1598   void *IP = nullptr;
1599   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1600     return SDValue(E, 0);
1601 
1602   auto *N = newSDNode<JumpTableSDNode>(JTI, VT, isTarget, TargetFlags);
1603   CSEMap.InsertNode(N, IP);
1604   InsertNode(N);
1605   return SDValue(N, 0);
1606 }
1607 
1608 SDValue SelectionDAG::getConstantPool(const Constant *C, EVT VT,
1609                                       MaybeAlign Alignment, int Offset,
1610                                       bool isTarget, unsigned TargetFlags) {
1611   assert((TargetFlags == 0 || isTarget) &&
1612          "Cannot set target flags on target-independent globals");
1613   if (!Alignment)
1614     Alignment = shouldOptForSize()
1615                     ? getDataLayout().getABITypeAlign(C->getType())
1616                     : getDataLayout().getPrefTypeAlign(C->getType());
1617   unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
1618   FoldingSetNodeID ID;
1619   AddNodeIDNode(ID, Opc, getVTList(VT), None);
1620   ID.AddInteger(Alignment->value());
1621   ID.AddInteger(Offset);
1622   ID.AddPointer(C);
1623   ID.AddInteger(TargetFlags);
1624   void *IP = nullptr;
1625   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1626     return SDValue(E, 0);
1627 
1628   auto *N = newSDNode<ConstantPoolSDNode>(isTarget, C, VT, Offset, *Alignment,
1629                                           TargetFlags);
1630   CSEMap.InsertNode(N, IP);
1631   InsertNode(N);
1632   SDValue V = SDValue(N, 0);
1633   NewSDValueDbgMsg(V, "Creating new constant pool: ", this);
1634   return V;
1635 }
1636 
1637 SDValue SelectionDAG::getConstantPool(MachineConstantPoolValue *C, EVT VT,
1638                                       MaybeAlign Alignment, int Offset,
1639                                       bool isTarget, unsigned TargetFlags) {
1640   assert((TargetFlags == 0 || isTarget) &&
1641          "Cannot set target flags on target-independent globals");
1642   if (!Alignment)
1643     Alignment = getDataLayout().getPrefTypeAlign(C->getType());
1644   unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
1645   FoldingSetNodeID ID;
1646   AddNodeIDNode(ID, Opc, getVTList(VT), None);
1647   ID.AddInteger(Alignment->value());
1648   ID.AddInteger(Offset);
1649   C->addSelectionDAGCSEId(ID);
1650   ID.AddInteger(TargetFlags);
1651   void *IP = nullptr;
1652   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1653     return SDValue(E, 0);
1654 
1655   auto *N = newSDNode<ConstantPoolSDNode>(isTarget, C, VT, Offset, *Alignment,
1656                                           TargetFlags);
1657   CSEMap.InsertNode(N, IP);
1658   InsertNode(N);
1659   return SDValue(N, 0);
1660 }
1661 
1662 SDValue SelectionDAG::getTargetIndex(int Index, EVT VT, int64_t Offset,
1663                                      unsigned TargetFlags) {
1664   FoldingSetNodeID ID;
1665   AddNodeIDNode(ID, ISD::TargetIndex, getVTList(VT), None);
1666   ID.AddInteger(Index);
1667   ID.AddInteger(Offset);
1668   ID.AddInteger(TargetFlags);
1669   void *IP = nullptr;
1670   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1671     return SDValue(E, 0);
1672 
1673   auto *N = newSDNode<TargetIndexSDNode>(Index, VT, Offset, TargetFlags);
1674   CSEMap.InsertNode(N, IP);
1675   InsertNode(N);
1676   return SDValue(N, 0);
1677 }
1678 
1679 SDValue SelectionDAG::getBasicBlock(MachineBasicBlock *MBB) {
1680   FoldingSetNodeID ID;
1681   AddNodeIDNode(ID, ISD::BasicBlock, getVTList(MVT::Other), None);
1682   ID.AddPointer(MBB);
1683   void *IP = nullptr;
1684   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1685     return SDValue(E, 0);
1686 
1687   auto *N = newSDNode<BasicBlockSDNode>(MBB);
1688   CSEMap.InsertNode(N, IP);
1689   InsertNode(N);
1690   return SDValue(N, 0);
1691 }
1692 
1693 SDValue SelectionDAG::getValueType(EVT VT) {
1694   if (VT.isSimple() && (unsigned)VT.getSimpleVT().SimpleTy >=
1695       ValueTypeNodes.size())
1696     ValueTypeNodes.resize(VT.getSimpleVT().SimpleTy+1);
1697 
1698   SDNode *&N = VT.isExtended() ?
1699     ExtendedValueTypeNodes[VT] : ValueTypeNodes[VT.getSimpleVT().SimpleTy];
1700 
1701   if (N) return SDValue(N, 0);
1702   N = newSDNode<VTSDNode>(VT);
1703   InsertNode(N);
1704   return SDValue(N, 0);
1705 }
1706 
1707 SDValue SelectionDAG::getExternalSymbol(const char *Sym, EVT VT) {
1708   SDNode *&N = ExternalSymbols[Sym];
1709   if (N) return SDValue(N, 0);
1710   N = newSDNode<ExternalSymbolSDNode>(false, Sym, 0, VT);
1711   InsertNode(N);
1712   return SDValue(N, 0);
1713 }
1714 
1715 SDValue SelectionDAG::getMCSymbol(MCSymbol *Sym, EVT VT) {
1716   SDNode *&N = MCSymbols[Sym];
1717   if (N)
1718     return SDValue(N, 0);
1719   N = newSDNode<MCSymbolSDNode>(Sym, VT);
1720   InsertNode(N);
1721   return SDValue(N, 0);
1722 }
1723 
1724 SDValue SelectionDAG::getTargetExternalSymbol(const char *Sym, EVT VT,
1725                                               unsigned TargetFlags) {
1726   SDNode *&N =
1727       TargetExternalSymbols[std::pair<std::string, unsigned>(Sym, TargetFlags)];
1728   if (N) return SDValue(N, 0);
1729   N = newSDNode<ExternalSymbolSDNode>(true, Sym, TargetFlags, VT);
1730   InsertNode(N);
1731   return SDValue(N, 0);
1732 }
1733 
1734 SDValue SelectionDAG::getCondCode(ISD::CondCode Cond) {
1735   if ((unsigned)Cond >= CondCodeNodes.size())
1736     CondCodeNodes.resize(Cond+1);
1737 
1738   if (!CondCodeNodes[Cond]) {
1739     auto *N = newSDNode<CondCodeSDNode>(Cond);
1740     CondCodeNodes[Cond] = N;
1741     InsertNode(N);
1742   }
1743 
1744   return SDValue(CondCodeNodes[Cond], 0);
1745 }
1746 
1747 /// Swaps the values of N1 and N2. Swaps all indices in the shuffle mask M that
1748 /// point at N1 to point at N2 and indices that point at N2 to point at N1.
1749 static void commuteShuffle(SDValue &N1, SDValue &N2, MutableArrayRef<int> M) {
1750   std::swap(N1, N2);
1751   ShuffleVectorSDNode::commuteMask(M);
1752 }
1753 
1754 SDValue SelectionDAG::getVectorShuffle(EVT VT, const SDLoc &dl, SDValue N1,
1755                                        SDValue N2, ArrayRef<int> Mask) {
1756   assert(VT.getVectorNumElements() == Mask.size() &&
1757            "Must have the same number of vector elements as mask elements!");
1758   assert(VT == N1.getValueType() && VT == N2.getValueType() &&
1759          "Invalid VECTOR_SHUFFLE");
1760 
1761   // Canonicalize shuffle undef, undef -> undef
1762   if (N1.isUndef() && N2.isUndef())
1763     return getUNDEF(VT);
1764 
1765   // Validate that all indices in Mask are within the range of the elements
1766   // input to the shuffle.
1767   int NElts = Mask.size();
1768   assert(llvm::all_of(Mask,
1769                       [&](int M) { return M < (NElts * 2) && M >= -1; }) &&
1770          "Index out of range");
1771 
1772   // Copy the mask so we can do any needed cleanup.
1773   SmallVector<int, 8> MaskVec(Mask.begin(), Mask.end());
1774 
1775   // Canonicalize shuffle v, v -> v, undef
1776   if (N1 == N2) {
1777     N2 = getUNDEF(VT);
1778     for (int i = 0; i != NElts; ++i)
1779       if (MaskVec[i] >= NElts) MaskVec[i] -= NElts;
1780   }
1781 
1782   // Canonicalize shuffle undef, v -> v, undef.  Commute the shuffle mask.
1783   if (N1.isUndef())
1784     commuteShuffle(N1, N2, MaskVec);
1785 
1786   if (TLI->hasVectorBlend()) {
1787     // If shuffling a splat, try to blend the splat instead. We do this here so
1788     // that even when this arises during lowering we don't have to re-handle it.
1789     auto BlendSplat = [&](BuildVectorSDNode *BV, int Offset) {
1790       BitVector UndefElements;
1791       SDValue Splat = BV->getSplatValue(&UndefElements);
1792       if (!Splat)
1793         return;
1794 
1795       for (int i = 0; i < NElts; ++i) {
1796         if (MaskVec[i] < Offset || MaskVec[i] >= (Offset + NElts))
1797           continue;
1798 
1799         // If this input comes from undef, mark it as such.
1800         if (UndefElements[MaskVec[i] - Offset]) {
1801           MaskVec[i] = -1;
1802           continue;
1803         }
1804 
1805         // If we can blend a non-undef lane, use that instead.
1806         if (!UndefElements[i])
1807           MaskVec[i] = i + Offset;
1808       }
1809     };
1810     if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
1811       BlendSplat(N1BV, 0);
1812     if (auto *N2BV = dyn_cast<BuildVectorSDNode>(N2))
1813       BlendSplat(N2BV, NElts);
1814   }
1815 
1816   // Canonicalize all index into lhs, -> shuffle lhs, undef
1817   // Canonicalize all index into rhs, -> shuffle rhs, undef
1818   bool AllLHS = true, AllRHS = true;
1819   bool N2Undef = N2.isUndef();
1820   for (int i = 0; i != NElts; ++i) {
1821     if (MaskVec[i] >= NElts) {
1822       if (N2Undef)
1823         MaskVec[i] = -1;
1824       else
1825         AllLHS = false;
1826     } else if (MaskVec[i] >= 0) {
1827       AllRHS = false;
1828     }
1829   }
1830   if (AllLHS && AllRHS)
1831     return getUNDEF(VT);
1832   if (AllLHS && !N2Undef)
1833     N2 = getUNDEF(VT);
1834   if (AllRHS) {
1835     N1 = getUNDEF(VT);
1836     commuteShuffle(N1, N2, MaskVec);
1837   }
1838   // Reset our undef status after accounting for the mask.
1839   N2Undef = N2.isUndef();
1840   // Re-check whether both sides ended up undef.
1841   if (N1.isUndef() && N2Undef)
1842     return getUNDEF(VT);
1843 
1844   // If Identity shuffle return that node.
1845   bool Identity = true, AllSame = true;
1846   for (int i = 0; i != NElts; ++i) {
1847     if (MaskVec[i] >= 0 && MaskVec[i] != i) Identity = false;
1848     if (MaskVec[i] != MaskVec[0]) AllSame = false;
1849   }
1850   if (Identity && NElts)
1851     return N1;
1852 
1853   // Shuffling a constant splat doesn't change the result.
1854   if (N2Undef) {
1855     SDValue V = N1;
1856 
1857     // Look through any bitcasts. We check that these don't change the number
1858     // (and size) of elements and just changes their types.
1859     while (V.getOpcode() == ISD::BITCAST)
1860       V = V->getOperand(0);
1861 
1862     // A splat should always show up as a build vector node.
1863     if (auto *BV = dyn_cast<BuildVectorSDNode>(V)) {
1864       BitVector UndefElements;
1865       SDValue Splat = BV->getSplatValue(&UndefElements);
1866       // If this is a splat of an undef, shuffling it is also undef.
1867       if (Splat && Splat.isUndef())
1868         return getUNDEF(VT);
1869 
1870       bool SameNumElts =
1871           V.getValueType().getVectorNumElements() == VT.getVectorNumElements();
1872 
1873       // We only have a splat which can skip shuffles if there is a splatted
1874       // value and no undef lanes rearranged by the shuffle.
1875       if (Splat && UndefElements.none()) {
1876         // Splat of <x, x, ..., x>, return <x, x, ..., x>, provided that the
1877         // number of elements match or the value splatted is a zero constant.
1878         if (SameNumElts)
1879           return N1;
1880         if (auto *C = dyn_cast<ConstantSDNode>(Splat))
1881           if (C->isNullValue())
1882             return N1;
1883       }
1884 
1885       // If the shuffle itself creates a splat, build the vector directly.
1886       if (AllSame && SameNumElts) {
1887         EVT BuildVT = BV->getValueType(0);
1888         const SDValue &Splatted = BV->getOperand(MaskVec[0]);
1889         SDValue NewBV = getSplatBuildVector(BuildVT, dl, Splatted);
1890 
1891         // We may have jumped through bitcasts, so the type of the
1892         // BUILD_VECTOR may not match the type of the shuffle.
1893         if (BuildVT != VT)
1894           NewBV = getNode(ISD::BITCAST, dl, VT, NewBV);
1895         return NewBV;
1896       }
1897     }
1898   }
1899 
1900   FoldingSetNodeID ID;
1901   SDValue Ops[2] = { N1, N2 };
1902   AddNodeIDNode(ID, ISD::VECTOR_SHUFFLE, getVTList(VT), Ops);
1903   for (int i = 0; i != NElts; ++i)
1904     ID.AddInteger(MaskVec[i]);
1905 
1906   void* IP = nullptr;
1907   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
1908     return SDValue(E, 0);
1909 
1910   // Allocate the mask array for the node out of the BumpPtrAllocator, since
1911   // SDNode doesn't have access to it.  This memory will be "leaked" when
1912   // the node is deallocated, but recovered when the NodeAllocator is released.
1913   int *MaskAlloc = OperandAllocator.Allocate<int>(NElts);
1914   llvm::copy(MaskVec, MaskAlloc);
1915 
1916   auto *N = newSDNode<ShuffleVectorSDNode>(VT, dl.getIROrder(),
1917                                            dl.getDebugLoc(), MaskAlloc);
1918   createOperands(N, Ops);
1919 
1920   CSEMap.InsertNode(N, IP);
1921   InsertNode(N);
1922   SDValue V = SDValue(N, 0);
1923   NewSDValueDbgMsg(V, "Creating new node: ", this);
1924   return V;
1925 }
1926 
1927 SDValue SelectionDAG::getCommutedVectorShuffle(const ShuffleVectorSDNode &SV) {
1928   EVT VT = SV.getValueType(0);
1929   SmallVector<int, 8> MaskVec(SV.getMask().begin(), SV.getMask().end());
1930   ShuffleVectorSDNode::commuteMask(MaskVec);
1931 
1932   SDValue Op0 = SV.getOperand(0);
1933   SDValue Op1 = SV.getOperand(1);
1934   return getVectorShuffle(VT, SDLoc(&SV), Op1, Op0, MaskVec);
1935 }
1936 
1937 SDValue SelectionDAG::getRegister(unsigned RegNo, EVT VT) {
1938   FoldingSetNodeID ID;
1939   AddNodeIDNode(ID, ISD::Register, getVTList(VT), None);
1940   ID.AddInteger(RegNo);
1941   void *IP = nullptr;
1942   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1943     return SDValue(E, 0);
1944 
1945   auto *N = newSDNode<RegisterSDNode>(RegNo, VT);
1946   N->SDNodeBits.IsDivergent = TLI->isSDNodeSourceOfDivergence(N, FLI, DA);
1947   CSEMap.InsertNode(N, IP);
1948   InsertNode(N);
1949   return SDValue(N, 0);
1950 }
1951 
1952 SDValue SelectionDAG::getRegisterMask(const uint32_t *RegMask) {
1953   FoldingSetNodeID ID;
1954   AddNodeIDNode(ID, ISD::RegisterMask, getVTList(MVT::Untyped), None);
1955   ID.AddPointer(RegMask);
1956   void *IP = nullptr;
1957   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1958     return SDValue(E, 0);
1959 
1960   auto *N = newSDNode<RegisterMaskSDNode>(RegMask);
1961   CSEMap.InsertNode(N, IP);
1962   InsertNode(N);
1963   return SDValue(N, 0);
1964 }
1965 
1966 SDValue SelectionDAG::getEHLabel(const SDLoc &dl, SDValue Root,
1967                                  MCSymbol *Label) {
1968   return getLabelNode(ISD::EH_LABEL, dl, Root, Label);
1969 }
1970 
1971 SDValue SelectionDAG::getLabelNode(unsigned Opcode, const SDLoc &dl,
1972                                    SDValue Root, MCSymbol *Label) {
1973   FoldingSetNodeID ID;
1974   SDValue Ops[] = { Root };
1975   AddNodeIDNode(ID, Opcode, getVTList(MVT::Other), Ops);
1976   ID.AddPointer(Label);
1977   void *IP = nullptr;
1978   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1979     return SDValue(E, 0);
1980 
1981   auto *N =
1982       newSDNode<LabelSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(), Label);
1983   createOperands(N, Ops);
1984 
1985   CSEMap.InsertNode(N, IP);
1986   InsertNode(N);
1987   return SDValue(N, 0);
1988 }
1989 
1990 SDValue SelectionDAG::getBlockAddress(const BlockAddress *BA, EVT VT,
1991                                       int64_t Offset, bool isTarget,
1992                                       unsigned TargetFlags) {
1993   unsigned Opc = isTarget ? ISD::TargetBlockAddress : ISD::BlockAddress;
1994 
1995   FoldingSetNodeID ID;
1996   AddNodeIDNode(ID, Opc, getVTList(VT), None);
1997   ID.AddPointer(BA);
1998   ID.AddInteger(Offset);
1999   ID.AddInteger(TargetFlags);
2000   void *IP = nullptr;
2001   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2002     return SDValue(E, 0);
2003 
2004   auto *N = newSDNode<BlockAddressSDNode>(Opc, VT, BA, Offset, TargetFlags);
2005   CSEMap.InsertNode(N, IP);
2006   InsertNode(N);
2007   return SDValue(N, 0);
2008 }
2009 
2010 SDValue SelectionDAG::getSrcValue(const Value *V) {
2011   FoldingSetNodeID ID;
2012   AddNodeIDNode(ID, ISD::SRCVALUE, getVTList(MVT::Other), None);
2013   ID.AddPointer(V);
2014 
2015   void *IP = nullptr;
2016   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2017     return SDValue(E, 0);
2018 
2019   auto *N = newSDNode<SrcValueSDNode>(V);
2020   CSEMap.InsertNode(N, IP);
2021   InsertNode(N);
2022   return SDValue(N, 0);
2023 }
2024 
2025 SDValue SelectionDAG::getMDNode(const MDNode *MD) {
2026   FoldingSetNodeID ID;
2027   AddNodeIDNode(ID, ISD::MDNODE_SDNODE, getVTList(MVT::Other), None);
2028   ID.AddPointer(MD);
2029 
2030   void *IP = nullptr;
2031   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2032     return SDValue(E, 0);
2033 
2034   auto *N = newSDNode<MDNodeSDNode>(MD);
2035   CSEMap.InsertNode(N, IP);
2036   InsertNode(N);
2037   return SDValue(N, 0);
2038 }
2039 
2040 SDValue SelectionDAG::getBitcast(EVT VT, SDValue V) {
2041   if (VT == V.getValueType())
2042     return V;
2043 
2044   return getNode(ISD::BITCAST, SDLoc(V), VT, V);
2045 }
2046 
2047 SDValue SelectionDAG::getAddrSpaceCast(const SDLoc &dl, EVT VT, SDValue Ptr,
2048                                        unsigned SrcAS, unsigned DestAS) {
2049   SDValue Ops[] = {Ptr};
2050   FoldingSetNodeID ID;
2051   AddNodeIDNode(ID, ISD::ADDRSPACECAST, getVTList(VT), Ops);
2052   ID.AddInteger(SrcAS);
2053   ID.AddInteger(DestAS);
2054 
2055   void *IP = nullptr;
2056   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
2057     return SDValue(E, 0);
2058 
2059   auto *N = newSDNode<AddrSpaceCastSDNode>(dl.getIROrder(), dl.getDebugLoc(),
2060                                            VT, SrcAS, DestAS);
2061   createOperands(N, Ops);
2062 
2063   CSEMap.InsertNode(N, IP);
2064   InsertNode(N);
2065   return SDValue(N, 0);
2066 }
2067 
2068 SDValue SelectionDAG::getFreeze(SDValue V) {
2069   return getNode(ISD::FREEZE, SDLoc(V), V.getValueType(), V);
2070 }
2071 
2072 /// getShiftAmountOperand - Return the specified value casted to
2073 /// the target's desired shift amount type.
2074 SDValue SelectionDAG::getShiftAmountOperand(EVT LHSTy, SDValue Op) {
2075   EVT OpTy = Op.getValueType();
2076   EVT ShTy = TLI->getShiftAmountTy(LHSTy, getDataLayout());
2077   if (OpTy == ShTy || OpTy.isVector()) return Op;
2078 
2079   return getZExtOrTrunc(Op, SDLoc(Op), ShTy);
2080 }
2081 
2082 SDValue SelectionDAG::expandVAArg(SDNode *Node) {
2083   SDLoc dl(Node);
2084   const TargetLowering &TLI = getTargetLoweringInfo();
2085   const Value *V = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
2086   EVT VT = Node->getValueType(0);
2087   SDValue Tmp1 = Node->getOperand(0);
2088   SDValue Tmp2 = Node->getOperand(1);
2089   const MaybeAlign MA(Node->getConstantOperandVal(3));
2090 
2091   SDValue VAListLoad = getLoad(TLI.getPointerTy(getDataLayout()), dl, Tmp1,
2092                                Tmp2, MachinePointerInfo(V));
2093   SDValue VAList = VAListLoad;
2094 
2095   if (MA && *MA > TLI.getMinStackArgumentAlignment()) {
2096     VAList = getNode(ISD::ADD, dl, VAList.getValueType(), VAList,
2097                      getConstant(MA->value() - 1, dl, VAList.getValueType()));
2098 
2099     VAList =
2100         getNode(ISD::AND, dl, VAList.getValueType(), VAList,
2101                 getConstant(-(int64_t)MA->value(), dl, VAList.getValueType()));
2102   }
2103 
2104   // Increment the pointer, VAList, to the next vaarg
2105   Tmp1 = getNode(ISD::ADD, dl, VAList.getValueType(), VAList,
2106                  getConstant(getDataLayout().getTypeAllocSize(
2107                                                VT.getTypeForEVT(*getContext())),
2108                              dl, VAList.getValueType()));
2109   // Store the incremented VAList to the legalized pointer
2110   Tmp1 =
2111       getStore(VAListLoad.getValue(1), dl, Tmp1, Tmp2, MachinePointerInfo(V));
2112   // Load the actual argument out of the pointer VAList
2113   return getLoad(VT, dl, Tmp1, VAList, MachinePointerInfo());
2114 }
2115 
2116 SDValue SelectionDAG::expandVACopy(SDNode *Node) {
2117   SDLoc dl(Node);
2118   const TargetLowering &TLI = getTargetLoweringInfo();
2119   // This defaults to loading a pointer from the input and storing it to the
2120   // output, returning the chain.
2121   const Value *VD = cast<SrcValueSDNode>(Node->getOperand(3))->getValue();
2122   const Value *VS = cast<SrcValueSDNode>(Node->getOperand(4))->getValue();
2123   SDValue Tmp1 =
2124       getLoad(TLI.getPointerTy(getDataLayout()), dl, Node->getOperand(0),
2125               Node->getOperand(2), MachinePointerInfo(VS));
2126   return getStore(Tmp1.getValue(1), dl, Tmp1, Node->getOperand(1),
2127                   MachinePointerInfo(VD));
2128 }
2129 
2130 Align SelectionDAG::getReducedAlign(EVT VT, bool UseABI) {
2131   const DataLayout &DL = getDataLayout();
2132   Type *Ty = VT.getTypeForEVT(*getContext());
2133   Align RedAlign = UseABI ? DL.getABITypeAlign(Ty) : DL.getPrefTypeAlign(Ty);
2134 
2135   if (TLI->isTypeLegal(VT) || !VT.isVector())
2136     return RedAlign;
2137 
2138   const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering();
2139   const Align StackAlign = TFI->getStackAlign();
2140 
2141   // See if we can choose a smaller ABI alignment in cases where it's an
2142   // illegal vector type that will get broken down.
2143   if (RedAlign > StackAlign) {
2144     EVT IntermediateVT;
2145     MVT RegisterVT;
2146     unsigned NumIntermediates;
2147     TLI->getVectorTypeBreakdown(*getContext(), VT, IntermediateVT,
2148                                 NumIntermediates, RegisterVT);
2149     Ty = IntermediateVT.getTypeForEVT(*getContext());
2150     Align RedAlign2 = UseABI ? DL.getABITypeAlign(Ty) : DL.getPrefTypeAlign(Ty);
2151     if (RedAlign2 < RedAlign)
2152       RedAlign = RedAlign2;
2153   }
2154 
2155   return RedAlign;
2156 }
2157 
2158 SDValue SelectionDAG::CreateStackTemporary(TypeSize Bytes, Align Alignment) {
2159   MachineFrameInfo &MFI = MF->getFrameInfo();
2160   const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering();
2161   int StackID = 0;
2162   if (Bytes.isScalable())
2163     StackID = TFI->getStackIDForScalableVectors();
2164   // The stack id gives an indication of whether the object is scalable or
2165   // not, so it's safe to pass in the minimum size here.
2166   int FrameIdx = MFI.CreateStackObject(Bytes.getKnownMinSize(), Alignment,
2167                                        false, nullptr, StackID);
2168   return getFrameIndex(FrameIdx, TLI->getFrameIndexTy(getDataLayout()));
2169 }
2170 
2171 SDValue SelectionDAG::CreateStackTemporary(EVT VT, unsigned minAlign) {
2172   Type *Ty = VT.getTypeForEVT(*getContext());
2173   Align StackAlign =
2174       std::max(getDataLayout().getPrefTypeAlign(Ty), Align(minAlign));
2175   return CreateStackTemporary(VT.getStoreSize(), StackAlign);
2176 }
2177 
2178 SDValue SelectionDAG::CreateStackTemporary(EVT VT1, EVT VT2) {
2179   TypeSize VT1Size = VT1.getStoreSize();
2180   TypeSize VT2Size = VT2.getStoreSize();
2181   assert(VT1Size.isScalable() == VT2Size.isScalable() &&
2182          "Don't know how to choose the maximum size when creating a stack "
2183          "temporary");
2184   TypeSize Bytes =
2185       VT1Size.getKnownMinSize() > VT2Size.getKnownMinSize() ? VT1Size : VT2Size;
2186 
2187   Type *Ty1 = VT1.getTypeForEVT(*getContext());
2188   Type *Ty2 = VT2.getTypeForEVT(*getContext());
2189   const DataLayout &DL = getDataLayout();
2190   Align Align = std::max(DL.getPrefTypeAlign(Ty1), DL.getPrefTypeAlign(Ty2));
2191   return CreateStackTemporary(Bytes, Align);
2192 }
2193 
2194 SDValue SelectionDAG::FoldSetCC(EVT VT, SDValue N1, SDValue N2,
2195                                 ISD::CondCode Cond, const SDLoc &dl) {
2196   EVT OpVT = N1.getValueType();
2197 
2198   // These setcc operations always fold.
2199   switch (Cond) {
2200   default: break;
2201   case ISD::SETFALSE:
2202   case ISD::SETFALSE2: return getBoolConstant(false, dl, VT, OpVT);
2203   case ISD::SETTRUE:
2204   case ISD::SETTRUE2: return getBoolConstant(true, dl, VT, OpVT);
2205 
2206   case ISD::SETOEQ:
2207   case ISD::SETOGT:
2208   case ISD::SETOGE:
2209   case ISD::SETOLT:
2210   case ISD::SETOLE:
2211   case ISD::SETONE:
2212   case ISD::SETO:
2213   case ISD::SETUO:
2214   case ISD::SETUEQ:
2215   case ISD::SETUNE:
2216     assert(!OpVT.isInteger() && "Illegal setcc for integer!");
2217     break;
2218   }
2219 
2220   if (OpVT.isInteger()) {
2221     // For EQ and NE, we can always pick a value for the undef to make the
2222     // predicate pass or fail, so we can return undef.
2223     // Matches behavior in llvm::ConstantFoldCompareInstruction.
2224     // icmp eq/ne X, undef -> undef.
2225     if ((N1.isUndef() || N2.isUndef()) &&
2226         (Cond == ISD::SETEQ || Cond == ISD::SETNE))
2227       return getUNDEF(VT);
2228 
2229     // If both operands are undef, we can return undef for int comparison.
2230     // icmp undef, undef -> undef.
2231     if (N1.isUndef() && N2.isUndef())
2232       return getUNDEF(VT);
2233 
2234     // icmp X, X -> true/false
2235     // icmp X, undef -> true/false because undef could be X.
2236     if (N1 == N2)
2237       return getBoolConstant(ISD::isTrueWhenEqual(Cond), dl, VT, OpVT);
2238   }
2239 
2240   if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2)) {
2241     const APInt &C2 = N2C->getAPIntValue();
2242     if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1)) {
2243       const APInt &C1 = N1C->getAPIntValue();
2244 
2245       switch (Cond) {
2246       default: llvm_unreachable("Unknown integer setcc!");
2247       case ISD::SETEQ:  return getBoolConstant(C1 == C2, dl, VT, OpVT);
2248       case ISD::SETNE:  return getBoolConstant(C1 != C2, dl, VT, OpVT);
2249       case ISD::SETULT: return getBoolConstant(C1.ult(C2), dl, VT, OpVT);
2250       case ISD::SETUGT: return getBoolConstant(C1.ugt(C2), dl, VT, OpVT);
2251       case ISD::SETULE: return getBoolConstant(C1.ule(C2), dl, VT, OpVT);
2252       case ISD::SETUGE: return getBoolConstant(C1.uge(C2), dl, VT, OpVT);
2253       case ISD::SETLT:  return getBoolConstant(C1.slt(C2), dl, VT, OpVT);
2254       case ISD::SETGT:  return getBoolConstant(C1.sgt(C2), dl, VT, OpVT);
2255       case ISD::SETLE:  return getBoolConstant(C1.sle(C2), dl, VT, OpVT);
2256       case ISD::SETGE:  return getBoolConstant(C1.sge(C2), dl, VT, OpVT);
2257       }
2258     }
2259   }
2260 
2261   auto *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
2262   auto *N2CFP = dyn_cast<ConstantFPSDNode>(N2);
2263 
2264   if (N1CFP && N2CFP) {
2265     APFloat::cmpResult R = N1CFP->getValueAPF().compare(N2CFP->getValueAPF());
2266     switch (Cond) {
2267     default: break;
2268     case ISD::SETEQ:  if (R==APFloat::cmpUnordered)
2269                         return getUNDEF(VT);
2270                       LLVM_FALLTHROUGH;
2271     case ISD::SETOEQ: return getBoolConstant(R==APFloat::cmpEqual, dl, VT,
2272                                              OpVT);
2273     case ISD::SETNE:  if (R==APFloat::cmpUnordered)
2274                         return getUNDEF(VT);
2275                       LLVM_FALLTHROUGH;
2276     case ISD::SETONE: return getBoolConstant(R==APFloat::cmpGreaterThan ||
2277                                              R==APFloat::cmpLessThan, dl, VT,
2278                                              OpVT);
2279     case ISD::SETLT:  if (R==APFloat::cmpUnordered)
2280                         return getUNDEF(VT);
2281                       LLVM_FALLTHROUGH;
2282     case ISD::SETOLT: return getBoolConstant(R==APFloat::cmpLessThan, dl, VT,
2283                                              OpVT);
2284     case ISD::SETGT:  if (R==APFloat::cmpUnordered)
2285                         return getUNDEF(VT);
2286                       LLVM_FALLTHROUGH;
2287     case ISD::SETOGT: return getBoolConstant(R==APFloat::cmpGreaterThan, dl,
2288                                              VT, OpVT);
2289     case ISD::SETLE:  if (R==APFloat::cmpUnordered)
2290                         return getUNDEF(VT);
2291                       LLVM_FALLTHROUGH;
2292     case ISD::SETOLE: return getBoolConstant(R==APFloat::cmpLessThan ||
2293                                              R==APFloat::cmpEqual, dl, VT,
2294                                              OpVT);
2295     case ISD::SETGE:  if (R==APFloat::cmpUnordered)
2296                         return getUNDEF(VT);
2297                       LLVM_FALLTHROUGH;
2298     case ISD::SETOGE: return getBoolConstant(R==APFloat::cmpGreaterThan ||
2299                                          R==APFloat::cmpEqual, dl, VT, OpVT);
2300     case ISD::SETO:   return getBoolConstant(R!=APFloat::cmpUnordered, dl, VT,
2301                                              OpVT);
2302     case ISD::SETUO:  return getBoolConstant(R==APFloat::cmpUnordered, dl, VT,
2303                                              OpVT);
2304     case ISD::SETUEQ: return getBoolConstant(R==APFloat::cmpUnordered ||
2305                                              R==APFloat::cmpEqual, dl, VT,
2306                                              OpVT);
2307     case ISD::SETUNE: return getBoolConstant(R!=APFloat::cmpEqual, dl, VT,
2308                                              OpVT);
2309     case ISD::SETULT: return getBoolConstant(R==APFloat::cmpUnordered ||
2310                                              R==APFloat::cmpLessThan, dl, VT,
2311                                              OpVT);
2312     case ISD::SETUGT: return getBoolConstant(R==APFloat::cmpGreaterThan ||
2313                                              R==APFloat::cmpUnordered, dl, VT,
2314                                              OpVT);
2315     case ISD::SETULE: return getBoolConstant(R!=APFloat::cmpGreaterThan, dl,
2316                                              VT, OpVT);
2317     case ISD::SETUGE: return getBoolConstant(R!=APFloat::cmpLessThan, dl, VT,
2318                                              OpVT);
2319     }
2320   } else if (N1CFP && OpVT.isSimple() && !N2.isUndef()) {
2321     // Ensure that the constant occurs on the RHS.
2322     ISD::CondCode SwappedCond = ISD::getSetCCSwappedOperands(Cond);
2323     if (!TLI->isCondCodeLegal(SwappedCond, OpVT.getSimpleVT()))
2324       return SDValue();
2325     return getSetCC(dl, VT, N2, N1, SwappedCond);
2326   } else if ((N2CFP && N2CFP->getValueAPF().isNaN()) ||
2327              (OpVT.isFloatingPoint() && (N1.isUndef() || N2.isUndef()))) {
2328     // If an operand is known to be a nan (or undef that could be a nan), we can
2329     // fold it.
2330     // Choosing NaN for the undef will always make unordered comparison succeed
2331     // and ordered comparison fails.
2332     // Matches behavior in llvm::ConstantFoldCompareInstruction.
2333     switch (ISD::getUnorderedFlavor(Cond)) {
2334     default:
2335       llvm_unreachable("Unknown flavor!");
2336     case 0: // Known false.
2337       return getBoolConstant(false, dl, VT, OpVT);
2338     case 1: // Known true.
2339       return getBoolConstant(true, dl, VT, OpVT);
2340     case 2: // Undefined.
2341       return getUNDEF(VT);
2342     }
2343   }
2344 
2345   // Could not fold it.
2346   return SDValue();
2347 }
2348 
2349 /// See if the specified operand can be simplified with the knowledge that only
2350 /// the bits specified by DemandedBits are used.
2351 /// TODO: really we should be making this into the DAG equivalent of
2352 /// SimplifyMultipleUseDemandedBits and not generate any new nodes.
2353 SDValue SelectionDAG::GetDemandedBits(SDValue V, const APInt &DemandedBits) {
2354   EVT VT = V.getValueType();
2355 
2356   if (VT.isScalableVector())
2357     return SDValue();
2358 
2359   APInt DemandedElts = VT.isVector()
2360                            ? APInt::getAllOnesValue(VT.getVectorNumElements())
2361                            : APInt(1, 1);
2362   return GetDemandedBits(V, DemandedBits, DemandedElts);
2363 }
2364 
2365 /// See if the specified operand can be simplified with the knowledge that only
2366 /// the bits specified by DemandedBits are used in the elements specified by
2367 /// DemandedElts.
2368 /// TODO: really we should be making this into the DAG equivalent of
2369 /// SimplifyMultipleUseDemandedBits and not generate any new nodes.
2370 SDValue SelectionDAG::GetDemandedBits(SDValue V, const APInt &DemandedBits,
2371                                       const APInt &DemandedElts) {
2372   switch (V.getOpcode()) {
2373   default:
2374     return TLI->SimplifyMultipleUseDemandedBits(V, DemandedBits, DemandedElts,
2375                                                 *this, 0);
2376   case ISD::Constant: {
2377     const APInt &CVal = cast<ConstantSDNode>(V)->getAPIntValue();
2378     APInt NewVal = CVal & DemandedBits;
2379     if (NewVal != CVal)
2380       return getConstant(NewVal, SDLoc(V), V.getValueType());
2381     break;
2382   }
2383   case ISD::SRL:
2384     // Only look at single-use SRLs.
2385     if (!V.getNode()->hasOneUse())
2386       break;
2387     if (auto *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
2388       // See if we can recursively simplify the LHS.
2389       unsigned Amt = RHSC->getZExtValue();
2390 
2391       // Watch out for shift count overflow though.
2392       if (Amt >= DemandedBits.getBitWidth())
2393         break;
2394       APInt SrcDemandedBits = DemandedBits << Amt;
2395       if (SDValue SimplifyLHS =
2396               GetDemandedBits(V.getOperand(0), SrcDemandedBits))
2397         return getNode(ISD::SRL, SDLoc(V), V.getValueType(), SimplifyLHS,
2398                        V.getOperand(1));
2399     }
2400     break;
2401   }
2402   return SDValue();
2403 }
2404 
2405 /// SignBitIsZero - Return true if the sign bit of Op is known to be zero.  We
2406 /// use this predicate to simplify operations downstream.
2407 bool SelectionDAG::SignBitIsZero(SDValue Op, unsigned Depth) const {
2408   unsigned BitWidth = Op.getScalarValueSizeInBits();
2409   return MaskedValueIsZero(Op, APInt::getSignMask(BitWidth), Depth);
2410 }
2411 
2412 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero.  We use
2413 /// this predicate to simplify operations downstream.  Mask is known to be zero
2414 /// for bits that V cannot have.
2415 bool SelectionDAG::MaskedValueIsZero(SDValue V, const APInt &Mask,
2416                                      unsigned Depth) const {
2417   return Mask.isSubsetOf(computeKnownBits(V, Depth).Zero);
2418 }
2419 
2420 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero in
2421 /// DemandedElts.  We use this predicate to simplify operations downstream.
2422 /// Mask is known to be zero for bits that V cannot have.
2423 bool SelectionDAG::MaskedValueIsZero(SDValue V, const APInt &Mask,
2424                                      const APInt &DemandedElts,
2425                                      unsigned Depth) const {
2426   return Mask.isSubsetOf(computeKnownBits(V, DemandedElts, Depth).Zero);
2427 }
2428 
2429 /// MaskedValueIsAllOnes - Return true if '(Op & Mask) == Mask'.
2430 bool SelectionDAG::MaskedValueIsAllOnes(SDValue V, const APInt &Mask,
2431                                         unsigned Depth) const {
2432   return Mask.isSubsetOf(computeKnownBits(V, Depth).One);
2433 }
2434 
2435 /// isSplatValue - Return true if the vector V has the same value
2436 /// across all DemandedElts. For scalable vectors it does not make
2437 /// sense to specify which elements are demanded or undefined, therefore
2438 /// they are simply ignored.
2439 bool SelectionDAG::isSplatValue(SDValue V, const APInt &DemandedElts,
2440                                 APInt &UndefElts, unsigned Depth) {
2441   EVT VT = V.getValueType();
2442   assert(VT.isVector() && "Vector type expected");
2443 
2444   if (!VT.isScalableVector() && !DemandedElts)
2445     return false; // No demanded elts, better to assume we don't know anything.
2446 
2447   if (Depth >= MaxRecursionDepth)
2448     return false; // Limit search depth.
2449 
2450   // Deal with some common cases here that work for both fixed and scalable
2451   // vector types.
2452   switch (V.getOpcode()) {
2453   case ISD::SPLAT_VECTOR:
2454     UndefElts = V.getOperand(0).isUndef()
2455                     ? APInt::getAllOnesValue(DemandedElts.getBitWidth())
2456                     : APInt(DemandedElts.getBitWidth(), 0);
2457     return true;
2458   case ISD::ADD:
2459   case ISD::SUB:
2460   case ISD::AND:
2461   case ISD::XOR:
2462   case ISD::OR: {
2463     APInt UndefLHS, UndefRHS;
2464     SDValue LHS = V.getOperand(0);
2465     SDValue RHS = V.getOperand(1);
2466     if (isSplatValue(LHS, DemandedElts, UndefLHS, Depth + 1) &&
2467         isSplatValue(RHS, DemandedElts, UndefRHS, Depth + 1)) {
2468       UndefElts = UndefLHS | UndefRHS;
2469       return true;
2470     }
2471     break;
2472   }
2473   case ISD::ABS:
2474   case ISD::TRUNCATE:
2475   case ISD::SIGN_EXTEND:
2476   case ISD::ZERO_EXTEND:
2477     return isSplatValue(V.getOperand(0), DemandedElts, UndefElts, Depth + 1);
2478   }
2479 
2480   // We don't support other cases than those above for scalable vectors at
2481   // the moment.
2482   if (VT.isScalableVector())
2483     return false;
2484 
2485   unsigned NumElts = VT.getVectorNumElements();
2486   assert(NumElts == DemandedElts.getBitWidth() && "Vector size mismatch");
2487   UndefElts = APInt::getNullValue(NumElts);
2488 
2489   switch (V.getOpcode()) {
2490   case ISD::BUILD_VECTOR: {
2491     SDValue Scl;
2492     for (unsigned i = 0; i != NumElts; ++i) {
2493       SDValue Op = V.getOperand(i);
2494       if (Op.isUndef()) {
2495         UndefElts.setBit(i);
2496         continue;
2497       }
2498       if (!DemandedElts[i])
2499         continue;
2500       if (Scl && Scl != Op)
2501         return false;
2502       Scl = Op;
2503     }
2504     return true;
2505   }
2506   case ISD::VECTOR_SHUFFLE: {
2507     // Check if this is a shuffle node doing a splat.
2508     // TODO: Do we need to handle shuffle(splat, undef, mask)?
2509     int SplatIndex = -1;
2510     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(V)->getMask();
2511     for (int i = 0; i != (int)NumElts; ++i) {
2512       int M = Mask[i];
2513       if (M < 0) {
2514         UndefElts.setBit(i);
2515         continue;
2516       }
2517       if (!DemandedElts[i])
2518         continue;
2519       if (0 <= SplatIndex && SplatIndex != M)
2520         return false;
2521       SplatIndex = M;
2522     }
2523     return true;
2524   }
2525   case ISD::EXTRACT_SUBVECTOR: {
2526     // Offset the demanded elts by the subvector index.
2527     SDValue Src = V.getOperand(0);
2528     // We don't support scalable vectors at the moment.
2529     if (Src.getValueType().isScalableVector())
2530       return false;
2531     uint64_t Idx = V.getConstantOperandVal(1);
2532     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
2533     APInt UndefSrcElts;
2534     APInt DemandedSrcElts = DemandedElts.zextOrSelf(NumSrcElts).shl(Idx);
2535     if (isSplatValue(Src, DemandedSrcElts, UndefSrcElts, Depth + 1)) {
2536       UndefElts = UndefSrcElts.extractBits(NumElts, Idx);
2537       return true;
2538     }
2539     break;
2540   }
2541   }
2542 
2543   return false;
2544 }
2545 
2546 /// Helper wrapper to main isSplatValue function.
2547 bool SelectionDAG::isSplatValue(SDValue V, bool AllowUndefs) {
2548   EVT VT = V.getValueType();
2549   assert(VT.isVector() && "Vector type expected");
2550 
2551   APInt UndefElts;
2552   APInt DemandedElts;
2553 
2554   // For now we don't support this with scalable vectors.
2555   if (!VT.isScalableVector())
2556     DemandedElts = APInt::getAllOnesValue(VT.getVectorNumElements());
2557   return isSplatValue(V, DemandedElts, UndefElts) &&
2558          (AllowUndefs || !UndefElts);
2559 }
2560 
2561 SDValue SelectionDAG::getSplatSourceVector(SDValue V, int &SplatIdx) {
2562   V = peekThroughExtractSubvectors(V);
2563 
2564   EVT VT = V.getValueType();
2565   unsigned Opcode = V.getOpcode();
2566   switch (Opcode) {
2567   default: {
2568     APInt UndefElts;
2569     APInt DemandedElts;
2570 
2571     if (!VT.isScalableVector())
2572       DemandedElts = APInt::getAllOnesValue(VT.getVectorNumElements());
2573 
2574     if (isSplatValue(V, DemandedElts, UndefElts)) {
2575       if (VT.isScalableVector()) {
2576         // DemandedElts and UndefElts are ignored for scalable vectors, since
2577         // the only supported cases are SPLAT_VECTOR nodes.
2578         SplatIdx = 0;
2579       } else {
2580         // Handle case where all demanded elements are UNDEF.
2581         if (DemandedElts.isSubsetOf(UndefElts)) {
2582           SplatIdx = 0;
2583           return getUNDEF(VT);
2584         }
2585         SplatIdx = (UndefElts & DemandedElts).countTrailingOnes();
2586       }
2587       return V;
2588     }
2589     break;
2590   }
2591   case ISD::SPLAT_VECTOR:
2592     SplatIdx = 0;
2593     return V;
2594   case ISD::VECTOR_SHUFFLE: {
2595     if (VT.isScalableVector())
2596       return SDValue();
2597 
2598     // Check if this is a shuffle node doing a splat.
2599     // TODO - remove this and rely purely on SelectionDAG::isSplatValue,
2600     // getTargetVShiftNode currently struggles without the splat source.
2601     auto *SVN = cast<ShuffleVectorSDNode>(V);
2602     if (!SVN->isSplat())
2603       break;
2604     int Idx = SVN->getSplatIndex();
2605     int NumElts = V.getValueType().getVectorNumElements();
2606     SplatIdx = Idx % NumElts;
2607     return V.getOperand(Idx / NumElts);
2608   }
2609   }
2610 
2611   return SDValue();
2612 }
2613 
2614 SDValue SelectionDAG::getSplatValue(SDValue V) {
2615   int SplatIdx;
2616   if (SDValue SrcVector = getSplatSourceVector(V, SplatIdx))
2617     return getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(V),
2618                    SrcVector.getValueType().getScalarType(), SrcVector,
2619                    getVectorIdxConstant(SplatIdx, SDLoc(V)));
2620   return SDValue();
2621 }
2622 
2623 const APInt *
2624 SelectionDAG::getValidShiftAmountConstant(SDValue V,
2625                                           const APInt &DemandedElts) const {
2626   assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL ||
2627           V.getOpcode() == ISD::SRA) &&
2628          "Unknown shift node");
2629   unsigned BitWidth = V.getScalarValueSizeInBits();
2630   if (ConstantSDNode *SA = isConstOrConstSplat(V.getOperand(1), DemandedElts)) {
2631     // Shifting more than the bitwidth is not valid.
2632     const APInt &ShAmt = SA->getAPIntValue();
2633     if (ShAmt.ult(BitWidth))
2634       return &ShAmt;
2635   }
2636   return nullptr;
2637 }
2638 
2639 const APInt *SelectionDAG::getValidMinimumShiftAmountConstant(
2640     SDValue V, const APInt &DemandedElts) const {
2641   assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL ||
2642           V.getOpcode() == ISD::SRA) &&
2643          "Unknown shift node");
2644   if (const APInt *ValidAmt = getValidShiftAmountConstant(V, DemandedElts))
2645     return ValidAmt;
2646   unsigned BitWidth = V.getScalarValueSizeInBits();
2647   auto *BV = dyn_cast<BuildVectorSDNode>(V.getOperand(1));
2648   if (!BV)
2649     return nullptr;
2650   const APInt *MinShAmt = nullptr;
2651   for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
2652     if (!DemandedElts[i])
2653       continue;
2654     auto *SA = dyn_cast<ConstantSDNode>(BV->getOperand(i));
2655     if (!SA)
2656       return nullptr;
2657     // Shifting more than the bitwidth is not valid.
2658     const APInt &ShAmt = SA->getAPIntValue();
2659     if (ShAmt.uge(BitWidth))
2660       return nullptr;
2661     if (MinShAmt && MinShAmt->ule(ShAmt))
2662       continue;
2663     MinShAmt = &ShAmt;
2664   }
2665   return MinShAmt;
2666 }
2667 
2668 const APInt *SelectionDAG::getValidMaximumShiftAmountConstant(
2669     SDValue V, const APInt &DemandedElts) const {
2670   assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL ||
2671           V.getOpcode() == ISD::SRA) &&
2672          "Unknown shift node");
2673   if (const APInt *ValidAmt = getValidShiftAmountConstant(V, DemandedElts))
2674     return ValidAmt;
2675   unsigned BitWidth = V.getScalarValueSizeInBits();
2676   auto *BV = dyn_cast<BuildVectorSDNode>(V.getOperand(1));
2677   if (!BV)
2678     return nullptr;
2679   const APInt *MaxShAmt = nullptr;
2680   for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
2681     if (!DemandedElts[i])
2682       continue;
2683     auto *SA = dyn_cast<ConstantSDNode>(BV->getOperand(i));
2684     if (!SA)
2685       return nullptr;
2686     // Shifting more than the bitwidth is not valid.
2687     const APInt &ShAmt = SA->getAPIntValue();
2688     if (ShAmt.uge(BitWidth))
2689       return nullptr;
2690     if (MaxShAmt && MaxShAmt->uge(ShAmt))
2691       continue;
2692     MaxShAmt = &ShAmt;
2693   }
2694   return MaxShAmt;
2695 }
2696 
2697 /// Determine which bits of Op are known to be either zero or one and return
2698 /// them in Known. For vectors, the known bits are those that are shared by
2699 /// every vector element.
2700 KnownBits SelectionDAG::computeKnownBits(SDValue Op, unsigned Depth) const {
2701   EVT VT = Op.getValueType();
2702 
2703   // TOOD: Until we have a plan for how to represent demanded elements for
2704   // scalable vectors, we can just bail out for now.
2705   if (Op.getValueType().isScalableVector()) {
2706     unsigned BitWidth = Op.getScalarValueSizeInBits();
2707     return KnownBits(BitWidth);
2708   }
2709 
2710   APInt DemandedElts = VT.isVector()
2711                            ? APInt::getAllOnesValue(VT.getVectorNumElements())
2712                            : APInt(1, 1);
2713   return computeKnownBits(Op, DemandedElts, Depth);
2714 }
2715 
2716 /// Determine which bits of Op are known to be either zero or one and return
2717 /// them in Known. The DemandedElts argument allows us to only collect the known
2718 /// bits that are shared by the requested vector elements.
2719 KnownBits SelectionDAG::computeKnownBits(SDValue Op, const APInt &DemandedElts,
2720                                          unsigned Depth) const {
2721   unsigned BitWidth = Op.getScalarValueSizeInBits();
2722 
2723   KnownBits Known(BitWidth);   // Don't know anything.
2724 
2725   // TOOD: Until we have a plan for how to represent demanded elements for
2726   // scalable vectors, we can just bail out for now.
2727   if (Op.getValueType().isScalableVector())
2728     return Known;
2729 
2730   if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
2731     // We know all of the bits for a constant!
2732     return KnownBits::makeConstant(C->getAPIntValue());
2733   }
2734   if (auto *C = dyn_cast<ConstantFPSDNode>(Op)) {
2735     // We know all of the bits for a constant fp!
2736     return KnownBits::makeConstant(C->getValueAPF().bitcastToAPInt());
2737   }
2738 
2739   if (Depth >= MaxRecursionDepth)
2740     return Known;  // Limit search depth.
2741 
2742   KnownBits Known2;
2743   unsigned NumElts = DemandedElts.getBitWidth();
2744   assert((!Op.getValueType().isVector() ||
2745           NumElts == Op.getValueType().getVectorNumElements()) &&
2746          "Unexpected vector size");
2747 
2748   if (!DemandedElts)
2749     return Known;  // No demanded elts, better to assume we don't know anything.
2750 
2751   unsigned Opcode = Op.getOpcode();
2752   switch (Opcode) {
2753   case ISD::BUILD_VECTOR:
2754     // Collect the known bits that are shared by every demanded vector element.
2755     Known.Zero.setAllBits(); Known.One.setAllBits();
2756     for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
2757       if (!DemandedElts[i])
2758         continue;
2759 
2760       SDValue SrcOp = Op.getOperand(i);
2761       Known2 = computeKnownBits(SrcOp, Depth + 1);
2762 
2763       // BUILD_VECTOR can implicitly truncate sources, we must handle this.
2764       if (SrcOp.getValueSizeInBits() != BitWidth) {
2765         assert(SrcOp.getValueSizeInBits() > BitWidth &&
2766                "Expected BUILD_VECTOR implicit truncation");
2767         Known2 = Known2.trunc(BitWidth);
2768       }
2769 
2770       // Known bits are the values that are shared by every demanded element.
2771       Known = KnownBits::commonBits(Known, Known2);
2772 
2773       // If we don't know any bits, early out.
2774       if (Known.isUnknown())
2775         break;
2776     }
2777     break;
2778   case ISD::VECTOR_SHUFFLE: {
2779     // Collect the known bits that are shared by every vector element referenced
2780     // by the shuffle.
2781     APInt DemandedLHS(NumElts, 0), DemandedRHS(NumElts, 0);
2782     Known.Zero.setAllBits(); Known.One.setAllBits();
2783     const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op);
2784     assert(NumElts == SVN->getMask().size() && "Unexpected vector size");
2785     for (unsigned i = 0; i != NumElts; ++i) {
2786       if (!DemandedElts[i])
2787         continue;
2788 
2789       int M = SVN->getMaskElt(i);
2790       if (M < 0) {
2791         // For UNDEF elements, we don't know anything about the common state of
2792         // the shuffle result.
2793         Known.resetAll();
2794         DemandedLHS.clearAllBits();
2795         DemandedRHS.clearAllBits();
2796         break;
2797       }
2798 
2799       if ((unsigned)M < NumElts)
2800         DemandedLHS.setBit((unsigned)M % NumElts);
2801       else
2802         DemandedRHS.setBit((unsigned)M % NumElts);
2803     }
2804     // Known bits are the values that are shared by every demanded element.
2805     if (!!DemandedLHS) {
2806       SDValue LHS = Op.getOperand(0);
2807       Known2 = computeKnownBits(LHS, DemandedLHS, Depth + 1);
2808       Known = KnownBits::commonBits(Known, Known2);
2809     }
2810     // If we don't know any bits, early out.
2811     if (Known.isUnknown())
2812       break;
2813     if (!!DemandedRHS) {
2814       SDValue RHS = Op.getOperand(1);
2815       Known2 = computeKnownBits(RHS, DemandedRHS, Depth + 1);
2816       Known = KnownBits::commonBits(Known, Known2);
2817     }
2818     break;
2819   }
2820   case ISD::CONCAT_VECTORS: {
2821     // Split DemandedElts and test each of the demanded subvectors.
2822     Known.Zero.setAllBits(); Known.One.setAllBits();
2823     EVT SubVectorVT = Op.getOperand(0).getValueType();
2824     unsigned NumSubVectorElts = SubVectorVT.getVectorNumElements();
2825     unsigned NumSubVectors = Op.getNumOperands();
2826     for (unsigned i = 0; i != NumSubVectors; ++i) {
2827       APInt DemandedSub = DemandedElts.lshr(i * NumSubVectorElts);
2828       DemandedSub = DemandedSub.trunc(NumSubVectorElts);
2829       if (!!DemandedSub) {
2830         SDValue Sub = Op.getOperand(i);
2831         Known2 = computeKnownBits(Sub, DemandedSub, Depth + 1);
2832         Known = KnownBits::commonBits(Known, Known2);
2833       }
2834       // If we don't know any bits, early out.
2835       if (Known.isUnknown())
2836         break;
2837     }
2838     break;
2839   }
2840   case ISD::INSERT_SUBVECTOR: {
2841     // Demand any elements from the subvector and the remainder from the src its
2842     // inserted into.
2843     SDValue Src = Op.getOperand(0);
2844     SDValue Sub = Op.getOperand(1);
2845     uint64_t Idx = Op.getConstantOperandVal(2);
2846     unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
2847     APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
2848     APInt DemandedSrcElts = DemandedElts;
2849     DemandedSrcElts.insertBits(APInt::getNullValue(NumSubElts), Idx);
2850 
2851     Known.One.setAllBits();
2852     Known.Zero.setAllBits();
2853     if (!!DemandedSubElts) {
2854       Known = computeKnownBits(Sub, DemandedSubElts, Depth + 1);
2855       if (Known.isUnknown())
2856         break; // early-out.
2857     }
2858     if (!!DemandedSrcElts) {
2859       Known2 = computeKnownBits(Src, DemandedSrcElts, Depth + 1);
2860       Known = KnownBits::commonBits(Known, Known2);
2861     }
2862     break;
2863   }
2864   case ISD::EXTRACT_SUBVECTOR: {
2865     // Offset the demanded elts by the subvector index.
2866     SDValue Src = Op.getOperand(0);
2867     // Bail until we can represent demanded elements for scalable vectors.
2868     if (Src.getValueType().isScalableVector())
2869       break;
2870     uint64_t Idx = Op.getConstantOperandVal(1);
2871     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
2872     APInt DemandedSrcElts = DemandedElts.zextOrSelf(NumSrcElts).shl(Idx);
2873     Known = computeKnownBits(Src, DemandedSrcElts, Depth + 1);
2874     break;
2875   }
2876   case ISD::SCALAR_TO_VECTOR: {
2877     // We know about scalar_to_vector as much as we know about it source,
2878     // which becomes the first element of otherwise unknown vector.
2879     if (DemandedElts != 1)
2880       break;
2881 
2882     SDValue N0 = Op.getOperand(0);
2883     Known = computeKnownBits(N0, Depth + 1);
2884     if (N0.getValueSizeInBits() != BitWidth)
2885       Known = Known.trunc(BitWidth);
2886 
2887     break;
2888   }
2889   case ISD::BITCAST: {
2890     SDValue N0 = Op.getOperand(0);
2891     EVT SubVT = N0.getValueType();
2892     unsigned SubBitWidth = SubVT.getScalarSizeInBits();
2893 
2894     // Ignore bitcasts from unsupported types.
2895     if (!(SubVT.isInteger() || SubVT.isFloatingPoint()))
2896       break;
2897 
2898     // Fast handling of 'identity' bitcasts.
2899     if (BitWidth == SubBitWidth) {
2900       Known = computeKnownBits(N0, DemandedElts, Depth + 1);
2901       break;
2902     }
2903 
2904     bool IsLE = getDataLayout().isLittleEndian();
2905 
2906     // Bitcast 'small element' vector to 'large element' scalar/vector.
2907     if ((BitWidth % SubBitWidth) == 0) {
2908       assert(N0.getValueType().isVector() && "Expected bitcast from vector");
2909 
2910       // Collect known bits for the (larger) output by collecting the known
2911       // bits from each set of sub elements and shift these into place.
2912       // We need to separately call computeKnownBits for each set of
2913       // sub elements as the knownbits for each is likely to be different.
2914       unsigned SubScale = BitWidth / SubBitWidth;
2915       APInt SubDemandedElts(NumElts * SubScale, 0);
2916       for (unsigned i = 0; i != NumElts; ++i)
2917         if (DemandedElts[i])
2918           SubDemandedElts.setBit(i * SubScale);
2919 
2920       for (unsigned i = 0; i != SubScale; ++i) {
2921         Known2 = computeKnownBits(N0, SubDemandedElts.shl(i),
2922                          Depth + 1);
2923         unsigned Shifts = IsLE ? i : SubScale - 1 - i;
2924         Known.One |= Known2.One.zext(BitWidth).shl(SubBitWidth * Shifts);
2925         Known.Zero |= Known2.Zero.zext(BitWidth).shl(SubBitWidth * Shifts);
2926       }
2927     }
2928 
2929     // Bitcast 'large element' scalar/vector to 'small element' vector.
2930     if ((SubBitWidth % BitWidth) == 0) {
2931       assert(Op.getValueType().isVector() && "Expected bitcast to vector");
2932 
2933       // Collect known bits for the (smaller) output by collecting the known
2934       // bits from the overlapping larger input elements and extracting the
2935       // sub sections we actually care about.
2936       unsigned SubScale = SubBitWidth / BitWidth;
2937       APInt SubDemandedElts(NumElts / SubScale, 0);
2938       for (unsigned i = 0; i != NumElts; ++i)
2939         if (DemandedElts[i])
2940           SubDemandedElts.setBit(i / SubScale);
2941 
2942       Known2 = computeKnownBits(N0, SubDemandedElts, Depth + 1);
2943 
2944       Known.Zero.setAllBits(); Known.One.setAllBits();
2945       for (unsigned i = 0; i != NumElts; ++i)
2946         if (DemandedElts[i]) {
2947           unsigned Shifts = IsLE ? i : NumElts - 1 - i;
2948           unsigned Offset = (Shifts % SubScale) * BitWidth;
2949           Known.One &= Known2.One.lshr(Offset).trunc(BitWidth);
2950           Known.Zero &= Known2.Zero.lshr(Offset).trunc(BitWidth);
2951           // If we don't know any bits, early out.
2952           if (Known.isUnknown())
2953             break;
2954         }
2955     }
2956     break;
2957   }
2958   case ISD::AND:
2959     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
2960     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
2961 
2962     Known &= Known2;
2963     break;
2964   case ISD::OR:
2965     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
2966     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
2967 
2968     Known |= Known2;
2969     break;
2970   case ISD::XOR:
2971     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
2972     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
2973 
2974     Known ^= Known2;
2975     break;
2976   case ISD::MUL: {
2977     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
2978     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
2979     Known = KnownBits::computeForMul(Known, Known2);
2980     break;
2981   }
2982   case ISD::MULHU: {
2983     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
2984     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
2985     Known = KnownBits::mulhu(Known, Known2);
2986     break;
2987   }
2988   case ISD::MULHS: {
2989     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
2990     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
2991     Known = KnownBits::mulhs(Known, Known2);
2992     break;
2993   }
2994   case ISD::UMUL_LOHI: {
2995     assert((Op.getResNo() == 0 || Op.getResNo() == 1) && "Unknown result");
2996     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
2997     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
2998     if (Op.getResNo() == 0)
2999       Known = KnownBits::computeForMul(Known, Known2);
3000     else
3001       Known = KnownBits::mulhu(Known, Known2);
3002     break;
3003   }
3004   case ISD::SMUL_LOHI: {
3005     assert((Op.getResNo() == 0 || Op.getResNo() == 1) && "Unknown result");
3006     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3007     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3008     if (Op.getResNo() == 0)
3009       Known = KnownBits::computeForMul(Known, Known2);
3010     else
3011       Known = KnownBits::mulhs(Known, Known2);
3012     break;
3013   }
3014   case ISD::UDIV: {
3015     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3016     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3017     Known = KnownBits::udiv(Known, Known2);
3018     break;
3019   }
3020   case ISD::SELECT:
3021   case ISD::VSELECT:
3022     Known = computeKnownBits(Op.getOperand(2), DemandedElts, Depth+1);
3023     // If we don't know any bits, early out.
3024     if (Known.isUnknown())
3025       break;
3026     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth+1);
3027 
3028     // Only known if known in both the LHS and RHS.
3029     Known = KnownBits::commonBits(Known, Known2);
3030     break;
3031   case ISD::SELECT_CC:
3032     Known = computeKnownBits(Op.getOperand(3), DemandedElts, Depth+1);
3033     // If we don't know any bits, early out.
3034     if (Known.isUnknown())
3035       break;
3036     Known2 = computeKnownBits(Op.getOperand(2), DemandedElts, Depth+1);
3037 
3038     // Only known if known in both the LHS and RHS.
3039     Known = KnownBits::commonBits(Known, Known2);
3040     break;
3041   case ISD::SMULO:
3042   case ISD::UMULO:
3043   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
3044     if (Op.getResNo() != 1)
3045       break;
3046     // The boolean result conforms to getBooleanContents.
3047     // If we know the result of a setcc has the top bits zero, use this info.
3048     // We know that we have an integer-based boolean since these operations
3049     // are only available for integer.
3050     if (TLI->getBooleanContents(Op.getValueType().isVector(), false) ==
3051             TargetLowering::ZeroOrOneBooleanContent &&
3052         BitWidth > 1)
3053       Known.Zero.setBitsFrom(1);
3054     break;
3055   case ISD::SETCC:
3056   case ISD::STRICT_FSETCC:
3057   case ISD::STRICT_FSETCCS: {
3058     unsigned OpNo = Op->isStrictFPOpcode() ? 1 : 0;
3059     // If we know the result of a setcc has the top bits zero, use this info.
3060     if (TLI->getBooleanContents(Op.getOperand(OpNo).getValueType()) ==
3061             TargetLowering::ZeroOrOneBooleanContent &&
3062         BitWidth > 1)
3063       Known.Zero.setBitsFrom(1);
3064     break;
3065   }
3066   case ISD::SHL:
3067     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3068     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3069     Known = KnownBits::shl(Known, Known2);
3070 
3071     // Minimum shift low bits are known zero.
3072     if (const APInt *ShMinAmt =
3073             getValidMinimumShiftAmountConstant(Op, DemandedElts))
3074       Known.Zero.setLowBits(ShMinAmt->getZExtValue());
3075     break;
3076   case ISD::SRL:
3077     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3078     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3079     Known = KnownBits::lshr(Known, Known2);
3080 
3081     // Minimum shift high bits are known zero.
3082     if (const APInt *ShMinAmt =
3083             getValidMinimumShiftAmountConstant(Op, DemandedElts))
3084       Known.Zero.setHighBits(ShMinAmt->getZExtValue());
3085     break;
3086   case ISD::SRA:
3087     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3088     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3089     Known = KnownBits::ashr(Known, Known2);
3090     // TODO: Add minimum shift high known sign bits.
3091     break;
3092   case ISD::FSHL:
3093   case ISD::FSHR:
3094     if (ConstantSDNode *C = isConstOrConstSplat(Op.getOperand(2), DemandedElts)) {
3095       unsigned Amt = C->getAPIntValue().urem(BitWidth);
3096 
3097       // For fshl, 0-shift returns the 1st arg.
3098       // For fshr, 0-shift returns the 2nd arg.
3099       if (Amt == 0) {
3100         Known = computeKnownBits(Op.getOperand(Opcode == ISD::FSHL ? 0 : 1),
3101                                  DemandedElts, Depth + 1);
3102         break;
3103       }
3104 
3105       // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW)))
3106       // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW))
3107       Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3108       Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3109       if (Opcode == ISD::FSHL) {
3110         Known.One <<= Amt;
3111         Known.Zero <<= Amt;
3112         Known2.One.lshrInPlace(BitWidth - Amt);
3113         Known2.Zero.lshrInPlace(BitWidth - Amt);
3114       } else {
3115         Known.One <<= BitWidth - Amt;
3116         Known.Zero <<= BitWidth - Amt;
3117         Known2.One.lshrInPlace(Amt);
3118         Known2.Zero.lshrInPlace(Amt);
3119       }
3120       Known.One |= Known2.One;
3121       Known.Zero |= Known2.Zero;
3122     }
3123     break;
3124   case ISD::SIGN_EXTEND_INREG: {
3125     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3126     EVT EVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
3127     Known = Known.sextInReg(EVT.getScalarSizeInBits());
3128     break;
3129   }
3130   case ISD::CTTZ:
3131   case ISD::CTTZ_ZERO_UNDEF: {
3132     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3133     // If we have a known 1, its position is our upper bound.
3134     unsigned PossibleTZ = Known2.countMaxTrailingZeros();
3135     unsigned LowBits = Log2_32(PossibleTZ) + 1;
3136     Known.Zero.setBitsFrom(LowBits);
3137     break;
3138   }
3139   case ISD::CTLZ:
3140   case ISD::CTLZ_ZERO_UNDEF: {
3141     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3142     // If we have a known 1, its position is our upper bound.
3143     unsigned PossibleLZ = Known2.countMaxLeadingZeros();
3144     unsigned LowBits = Log2_32(PossibleLZ) + 1;
3145     Known.Zero.setBitsFrom(LowBits);
3146     break;
3147   }
3148   case ISD::CTPOP: {
3149     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3150     // If we know some of the bits are zero, they can't be one.
3151     unsigned PossibleOnes = Known2.countMaxPopulation();
3152     Known.Zero.setBitsFrom(Log2_32(PossibleOnes) + 1);
3153     break;
3154   }
3155   case ISD::PARITY: {
3156     // Parity returns 0 everywhere but the LSB.
3157     Known.Zero.setBitsFrom(1);
3158     break;
3159   }
3160   case ISD::LOAD: {
3161     LoadSDNode *LD = cast<LoadSDNode>(Op);
3162     const Constant *Cst = TLI->getTargetConstantFromLoad(LD);
3163     if (ISD::isNON_EXTLoad(LD) && Cst) {
3164       // Determine any common known bits from the loaded constant pool value.
3165       Type *CstTy = Cst->getType();
3166       if ((NumElts * BitWidth) == CstTy->getPrimitiveSizeInBits()) {
3167         // If its a vector splat, then we can (quickly) reuse the scalar path.
3168         // NOTE: We assume all elements match and none are UNDEF.
3169         if (CstTy->isVectorTy()) {
3170           if (const Constant *Splat = Cst->getSplatValue()) {
3171             Cst = Splat;
3172             CstTy = Cst->getType();
3173           }
3174         }
3175         // TODO - do we need to handle different bitwidths?
3176         if (CstTy->isVectorTy() && BitWidth == CstTy->getScalarSizeInBits()) {
3177           // Iterate across all vector elements finding common known bits.
3178           Known.One.setAllBits();
3179           Known.Zero.setAllBits();
3180           for (unsigned i = 0; i != NumElts; ++i) {
3181             if (!DemandedElts[i])
3182               continue;
3183             if (Constant *Elt = Cst->getAggregateElement(i)) {
3184               if (auto *CInt = dyn_cast<ConstantInt>(Elt)) {
3185                 const APInt &Value = CInt->getValue();
3186                 Known.One &= Value;
3187                 Known.Zero &= ~Value;
3188                 continue;
3189               }
3190               if (auto *CFP = dyn_cast<ConstantFP>(Elt)) {
3191                 APInt Value = CFP->getValueAPF().bitcastToAPInt();
3192                 Known.One &= Value;
3193                 Known.Zero &= ~Value;
3194                 continue;
3195               }
3196             }
3197             Known.One.clearAllBits();
3198             Known.Zero.clearAllBits();
3199             break;
3200           }
3201         } else if (BitWidth == CstTy->getPrimitiveSizeInBits()) {
3202           if (auto *CInt = dyn_cast<ConstantInt>(Cst)) {
3203             Known = KnownBits::makeConstant(CInt->getValue());
3204           } else if (auto *CFP = dyn_cast<ConstantFP>(Cst)) {
3205             Known =
3206                 KnownBits::makeConstant(CFP->getValueAPF().bitcastToAPInt());
3207           }
3208         }
3209       }
3210     } else if (ISD::isZEXTLoad(Op.getNode()) && Op.getResNo() == 0) {
3211       // If this is a ZEXTLoad and we are looking at the loaded value.
3212       EVT VT = LD->getMemoryVT();
3213       unsigned MemBits = VT.getScalarSizeInBits();
3214       Known.Zero.setBitsFrom(MemBits);
3215     } else if (const MDNode *Ranges = LD->getRanges()) {
3216       if (LD->getExtensionType() == ISD::NON_EXTLOAD)
3217         computeKnownBitsFromRangeMetadata(*Ranges, Known);
3218     }
3219     break;
3220   }
3221   case ISD::ZERO_EXTEND_VECTOR_INREG: {
3222     EVT InVT = Op.getOperand(0).getValueType();
3223     APInt InDemandedElts = DemandedElts.zextOrSelf(InVT.getVectorNumElements());
3224     Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1);
3225     Known = Known.zext(BitWidth);
3226     break;
3227   }
3228   case ISD::ZERO_EXTEND: {
3229     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3230     Known = Known.zext(BitWidth);
3231     break;
3232   }
3233   case ISD::SIGN_EXTEND_VECTOR_INREG: {
3234     EVT InVT = Op.getOperand(0).getValueType();
3235     APInt InDemandedElts = DemandedElts.zextOrSelf(InVT.getVectorNumElements());
3236     Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1);
3237     // If the sign bit is known to be zero or one, then sext will extend
3238     // it to the top bits, else it will just zext.
3239     Known = Known.sext(BitWidth);
3240     break;
3241   }
3242   case ISD::SIGN_EXTEND: {
3243     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3244     // If the sign bit is known to be zero or one, then sext will extend
3245     // it to the top bits, else it will just zext.
3246     Known = Known.sext(BitWidth);
3247     break;
3248   }
3249   case ISD::ANY_EXTEND_VECTOR_INREG: {
3250     EVT InVT = Op.getOperand(0).getValueType();
3251     APInt InDemandedElts = DemandedElts.zextOrSelf(InVT.getVectorNumElements());
3252     Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1);
3253     Known = Known.anyext(BitWidth);
3254     break;
3255   }
3256   case ISD::ANY_EXTEND: {
3257     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3258     Known = Known.anyext(BitWidth);
3259     break;
3260   }
3261   case ISD::TRUNCATE: {
3262     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3263     Known = Known.trunc(BitWidth);
3264     break;
3265   }
3266   case ISD::AssertZext: {
3267     EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
3268     APInt InMask = APInt::getLowBitsSet(BitWidth, VT.getSizeInBits());
3269     Known = computeKnownBits(Op.getOperand(0), Depth+1);
3270     Known.Zero |= (~InMask);
3271     Known.One  &= (~Known.Zero);
3272     break;
3273   }
3274   case ISD::AssertAlign: {
3275     unsigned LogOfAlign = Log2(cast<AssertAlignSDNode>(Op)->getAlign());
3276     assert(LogOfAlign != 0);
3277     // If a node is guaranteed to be aligned, set low zero bits accordingly as
3278     // well as clearing one bits.
3279     Known.Zero.setLowBits(LogOfAlign);
3280     Known.One.clearLowBits(LogOfAlign);
3281     break;
3282   }
3283   case ISD::FGETSIGN:
3284     // All bits are zero except the low bit.
3285     Known.Zero.setBitsFrom(1);
3286     break;
3287   case ISD::USUBO:
3288   case ISD::SSUBO:
3289     if (Op.getResNo() == 1) {
3290       // If we know the result of a setcc has the top bits zero, use this info.
3291       if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) ==
3292               TargetLowering::ZeroOrOneBooleanContent &&
3293           BitWidth > 1)
3294         Known.Zero.setBitsFrom(1);
3295       break;
3296     }
3297     LLVM_FALLTHROUGH;
3298   case ISD::SUB:
3299   case ISD::SUBC: {
3300     assert(Op.getResNo() == 0 &&
3301            "We only compute knownbits for the difference here.");
3302 
3303     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3304     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3305     Known = KnownBits::computeForAddSub(/* Add */ false, /* NSW */ false,
3306                                         Known, Known2);
3307     break;
3308   }
3309   case ISD::UADDO:
3310   case ISD::SADDO:
3311   case ISD::ADDCARRY:
3312     if (Op.getResNo() == 1) {
3313       // If we know the result of a setcc has the top bits zero, use this info.
3314       if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) ==
3315               TargetLowering::ZeroOrOneBooleanContent &&
3316           BitWidth > 1)
3317         Known.Zero.setBitsFrom(1);
3318       break;
3319     }
3320     LLVM_FALLTHROUGH;
3321   case ISD::ADD:
3322   case ISD::ADDC:
3323   case ISD::ADDE: {
3324     assert(Op.getResNo() == 0 && "We only compute knownbits for the sum here.");
3325 
3326     // With ADDE and ADDCARRY, a carry bit may be added in.
3327     KnownBits Carry(1);
3328     if (Opcode == ISD::ADDE)
3329       // Can't track carry from glue, set carry to unknown.
3330       Carry.resetAll();
3331     else if (Opcode == ISD::ADDCARRY)
3332       // TODO: Compute known bits for the carry operand. Not sure if it is worth
3333       // the trouble (how often will we find a known carry bit). And I haven't
3334       // tested this very much yet, but something like this might work:
3335       //   Carry = computeKnownBits(Op.getOperand(2), DemandedElts, Depth + 1);
3336       //   Carry = Carry.zextOrTrunc(1, false);
3337       Carry.resetAll();
3338     else
3339       Carry.setAllZero();
3340 
3341     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3342     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3343     Known = KnownBits::computeForAddCarry(Known, Known2, Carry);
3344     break;
3345   }
3346   case ISD::SREM: {
3347     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3348     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3349     Known = KnownBits::srem(Known, Known2);
3350     break;
3351   }
3352   case ISD::UREM: {
3353     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3354     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3355     Known = KnownBits::urem(Known, Known2);
3356     break;
3357   }
3358   case ISD::EXTRACT_ELEMENT: {
3359     Known = computeKnownBits(Op.getOperand(0), Depth+1);
3360     const unsigned Index = Op.getConstantOperandVal(1);
3361     const unsigned EltBitWidth = Op.getValueSizeInBits();
3362 
3363     // Remove low part of known bits mask
3364     Known.Zero = Known.Zero.getHiBits(Known.getBitWidth() - Index * EltBitWidth);
3365     Known.One = Known.One.getHiBits(Known.getBitWidth() - Index * EltBitWidth);
3366 
3367     // Remove high part of known bit mask
3368     Known = Known.trunc(EltBitWidth);
3369     break;
3370   }
3371   case ISD::EXTRACT_VECTOR_ELT: {
3372     SDValue InVec = Op.getOperand(0);
3373     SDValue EltNo = Op.getOperand(1);
3374     EVT VecVT = InVec.getValueType();
3375     // computeKnownBits not yet implemented for scalable vectors.
3376     if (VecVT.isScalableVector())
3377       break;
3378     const unsigned EltBitWidth = VecVT.getScalarSizeInBits();
3379     const unsigned NumSrcElts = VecVT.getVectorNumElements();
3380 
3381     // If BitWidth > EltBitWidth the value is anyext:ed. So we do not know
3382     // anything about the extended bits.
3383     if (BitWidth > EltBitWidth)
3384       Known = Known.trunc(EltBitWidth);
3385 
3386     // If we know the element index, just demand that vector element, else for
3387     // an unknown element index, ignore DemandedElts and demand them all.
3388     APInt DemandedSrcElts = APInt::getAllOnesValue(NumSrcElts);
3389     auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
3390     if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts))
3391       DemandedSrcElts =
3392           APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue());
3393 
3394     Known = computeKnownBits(InVec, DemandedSrcElts, Depth + 1);
3395     if (BitWidth > EltBitWidth)
3396       Known = Known.anyext(BitWidth);
3397     break;
3398   }
3399   case ISD::INSERT_VECTOR_ELT: {
3400     // If we know the element index, split the demand between the
3401     // source vector and the inserted element, otherwise assume we need
3402     // the original demanded vector elements and the value.
3403     SDValue InVec = Op.getOperand(0);
3404     SDValue InVal = Op.getOperand(1);
3405     SDValue EltNo = Op.getOperand(2);
3406     bool DemandedVal = true;
3407     APInt DemandedVecElts = DemandedElts;
3408     auto *CEltNo = dyn_cast<ConstantSDNode>(EltNo);
3409     if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) {
3410       unsigned EltIdx = CEltNo->getZExtValue();
3411       DemandedVal = !!DemandedElts[EltIdx];
3412       DemandedVecElts.clearBit(EltIdx);
3413     }
3414     Known.One.setAllBits();
3415     Known.Zero.setAllBits();
3416     if (DemandedVal) {
3417       Known2 = computeKnownBits(InVal, Depth + 1);
3418       Known = KnownBits::commonBits(Known, Known2.zextOrTrunc(BitWidth));
3419     }
3420     if (!!DemandedVecElts) {
3421       Known2 = computeKnownBits(InVec, DemandedVecElts, Depth + 1);
3422       Known = KnownBits::commonBits(Known, Known2);
3423     }
3424     break;
3425   }
3426   case ISD::BITREVERSE: {
3427     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3428     Known = Known2.reverseBits();
3429     break;
3430   }
3431   case ISD::BSWAP: {
3432     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3433     Known = Known2.byteSwap();
3434     break;
3435   }
3436   case ISD::ABS: {
3437     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3438     Known = Known2.abs();
3439     break;
3440   }
3441   case ISD::USUBSAT: {
3442     // The result of usubsat will never be larger than the LHS.
3443     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3444     Known.Zero.setHighBits(Known2.countMinLeadingZeros());
3445     break;
3446   }
3447   case ISD::UMIN: {
3448     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3449     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3450     Known = KnownBits::umin(Known, Known2);
3451     break;
3452   }
3453   case ISD::UMAX: {
3454     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3455     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3456     Known = KnownBits::umax(Known, Known2);
3457     break;
3458   }
3459   case ISD::SMIN:
3460   case ISD::SMAX: {
3461     // If we have a clamp pattern, we know that the number of sign bits will be
3462     // the minimum of the clamp min/max range.
3463     bool IsMax = (Opcode == ISD::SMAX);
3464     ConstantSDNode *CstLow = nullptr, *CstHigh = nullptr;
3465     if ((CstLow = isConstOrConstSplat(Op.getOperand(1), DemandedElts)))
3466       if (Op.getOperand(0).getOpcode() == (IsMax ? ISD::SMIN : ISD::SMAX))
3467         CstHigh =
3468             isConstOrConstSplat(Op.getOperand(0).getOperand(1), DemandedElts);
3469     if (CstLow && CstHigh) {
3470       if (!IsMax)
3471         std::swap(CstLow, CstHigh);
3472 
3473       const APInt &ValueLow = CstLow->getAPIntValue();
3474       const APInt &ValueHigh = CstHigh->getAPIntValue();
3475       if (ValueLow.sle(ValueHigh)) {
3476         unsigned LowSignBits = ValueLow.getNumSignBits();
3477         unsigned HighSignBits = ValueHigh.getNumSignBits();
3478         unsigned MinSignBits = std::min(LowSignBits, HighSignBits);
3479         if (ValueLow.isNegative() && ValueHigh.isNegative()) {
3480           Known.One.setHighBits(MinSignBits);
3481           break;
3482         }
3483         if (ValueLow.isNonNegative() && ValueHigh.isNonNegative()) {
3484           Known.Zero.setHighBits(MinSignBits);
3485           break;
3486         }
3487       }
3488     }
3489 
3490     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3491     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3492     if (IsMax)
3493       Known = KnownBits::smax(Known, Known2);
3494     else
3495       Known = KnownBits::smin(Known, Known2);
3496     break;
3497   }
3498   case ISD::FrameIndex:
3499   case ISD::TargetFrameIndex:
3500     TLI->computeKnownBitsForFrameIndex(cast<FrameIndexSDNode>(Op)->getIndex(),
3501                                        Known, getMachineFunction());
3502     break;
3503 
3504   default:
3505     if (Opcode < ISD::BUILTIN_OP_END)
3506       break;
3507     LLVM_FALLTHROUGH;
3508   case ISD::INTRINSIC_WO_CHAIN:
3509   case ISD::INTRINSIC_W_CHAIN:
3510   case ISD::INTRINSIC_VOID:
3511     // Allow the target to implement this method for its nodes.
3512     TLI->computeKnownBitsForTargetNode(Op, Known, DemandedElts, *this, Depth);
3513     break;
3514   }
3515 
3516   assert(!Known.hasConflict() && "Bits known to be one AND zero?");
3517   return Known;
3518 }
3519 
3520 SelectionDAG::OverflowKind SelectionDAG::computeOverflowKind(SDValue N0,
3521                                                              SDValue N1) const {
3522   // X + 0 never overflow
3523   if (isNullConstant(N1))
3524     return OFK_Never;
3525 
3526   KnownBits N1Known = computeKnownBits(N1);
3527   if (N1Known.Zero.getBoolValue()) {
3528     KnownBits N0Known = computeKnownBits(N0);
3529 
3530     bool overflow;
3531     (void)N0Known.getMaxValue().uadd_ov(N1Known.getMaxValue(), overflow);
3532     if (!overflow)
3533       return OFK_Never;
3534   }
3535 
3536   // mulhi + 1 never overflow
3537   if (N0.getOpcode() == ISD::UMUL_LOHI && N0.getResNo() == 1 &&
3538       (N1Known.getMaxValue() & 0x01) == N1Known.getMaxValue())
3539     return OFK_Never;
3540 
3541   if (N1.getOpcode() == ISD::UMUL_LOHI && N1.getResNo() == 1) {
3542     KnownBits N0Known = computeKnownBits(N0);
3543 
3544     if ((N0Known.getMaxValue() & 0x01) == N0Known.getMaxValue())
3545       return OFK_Never;
3546   }
3547 
3548   return OFK_Sometime;
3549 }
3550 
3551 bool SelectionDAG::isKnownToBeAPowerOfTwo(SDValue Val) const {
3552   EVT OpVT = Val.getValueType();
3553   unsigned BitWidth = OpVT.getScalarSizeInBits();
3554 
3555   // Is the constant a known power of 2?
3556   if (ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Val))
3557     return Const->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2();
3558 
3559   // A left-shift of a constant one will have exactly one bit set because
3560   // shifting the bit off the end is undefined.
3561   if (Val.getOpcode() == ISD::SHL) {
3562     auto *C = isConstOrConstSplat(Val.getOperand(0));
3563     if (C && C->getAPIntValue() == 1)
3564       return true;
3565   }
3566 
3567   // Similarly, a logical right-shift of a constant sign-bit will have exactly
3568   // one bit set.
3569   if (Val.getOpcode() == ISD::SRL) {
3570     auto *C = isConstOrConstSplat(Val.getOperand(0));
3571     if (C && C->getAPIntValue().isSignMask())
3572       return true;
3573   }
3574 
3575   // Are all operands of a build vector constant powers of two?
3576   if (Val.getOpcode() == ISD::BUILD_VECTOR)
3577     if (llvm::all_of(Val->ops(), [BitWidth](SDValue E) {
3578           if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(E))
3579             return C->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2();
3580           return false;
3581         }))
3582       return true;
3583 
3584   // More could be done here, though the above checks are enough
3585   // to handle some common cases.
3586 
3587   // Fall back to computeKnownBits to catch other known cases.
3588   KnownBits Known = computeKnownBits(Val);
3589   return (Known.countMaxPopulation() == 1) && (Known.countMinPopulation() == 1);
3590 }
3591 
3592 unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, unsigned Depth) const {
3593   EVT VT = Op.getValueType();
3594 
3595   // TODO: Assume we don't know anything for now.
3596   if (VT.isScalableVector())
3597     return 1;
3598 
3599   APInt DemandedElts = VT.isVector()
3600                            ? APInt::getAllOnesValue(VT.getVectorNumElements())
3601                            : APInt(1, 1);
3602   return ComputeNumSignBits(Op, DemandedElts, Depth);
3603 }
3604 
3605 unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, const APInt &DemandedElts,
3606                                           unsigned Depth) const {
3607   EVT VT = Op.getValueType();
3608   assert((VT.isInteger() || VT.isFloatingPoint()) && "Invalid VT!");
3609   unsigned VTBits = VT.getScalarSizeInBits();
3610   unsigned NumElts = DemandedElts.getBitWidth();
3611   unsigned Tmp, Tmp2;
3612   unsigned FirstAnswer = 1;
3613 
3614   if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
3615     const APInt &Val = C->getAPIntValue();
3616     return Val.getNumSignBits();
3617   }
3618 
3619   if (Depth >= MaxRecursionDepth)
3620     return 1;  // Limit search depth.
3621 
3622   if (!DemandedElts || VT.isScalableVector())
3623     return 1;  // No demanded elts, better to assume we don't know anything.
3624 
3625   unsigned Opcode = Op.getOpcode();
3626   switch (Opcode) {
3627   default: break;
3628   case ISD::AssertSext:
3629     Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
3630     return VTBits-Tmp+1;
3631   case ISD::AssertZext:
3632     Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
3633     return VTBits-Tmp;
3634 
3635   case ISD::BUILD_VECTOR:
3636     Tmp = VTBits;
3637     for (unsigned i = 0, e = Op.getNumOperands(); (i < e) && (Tmp > 1); ++i) {
3638       if (!DemandedElts[i])
3639         continue;
3640 
3641       SDValue SrcOp = Op.getOperand(i);
3642       Tmp2 = ComputeNumSignBits(SrcOp, Depth + 1);
3643 
3644       // BUILD_VECTOR can implicitly truncate sources, we must handle this.
3645       if (SrcOp.getValueSizeInBits() != VTBits) {
3646         assert(SrcOp.getValueSizeInBits() > VTBits &&
3647                "Expected BUILD_VECTOR implicit truncation");
3648         unsigned ExtraBits = SrcOp.getValueSizeInBits() - VTBits;
3649         Tmp2 = (Tmp2 > ExtraBits ? Tmp2 - ExtraBits : 1);
3650       }
3651       Tmp = std::min(Tmp, Tmp2);
3652     }
3653     return Tmp;
3654 
3655   case ISD::VECTOR_SHUFFLE: {
3656     // Collect the minimum number of sign bits that are shared by every vector
3657     // element referenced by the shuffle.
3658     APInt DemandedLHS(NumElts, 0), DemandedRHS(NumElts, 0);
3659     const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op);
3660     assert(NumElts == SVN->getMask().size() && "Unexpected vector size");
3661     for (unsigned i = 0; i != NumElts; ++i) {
3662       int M = SVN->getMaskElt(i);
3663       if (!DemandedElts[i])
3664         continue;
3665       // For UNDEF elements, we don't know anything about the common state of
3666       // the shuffle result.
3667       if (M < 0)
3668         return 1;
3669       if ((unsigned)M < NumElts)
3670         DemandedLHS.setBit((unsigned)M % NumElts);
3671       else
3672         DemandedRHS.setBit((unsigned)M % NumElts);
3673     }
3674     Tmp = std::numeric_limits<unsigned>::max();
3675     if (!!DemandedLHS)
3676       Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedLHS, Depth + 1);
3677     if (!!DemandedRHS) {
3678       Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedRHS, Depth + 1);
3679       Tmp = std::min(Tmp, Tmp2);
3680     }
3681     // If we don't know anything, early out and try computeKnownBits fall-back.
3682     if (Tmp == 1)
3683       break;
3684     assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
3685     return Tmp;
3686   }
3687 
3688   case ISD::BITCAST: {
3689     SDValue N0 = Op.getOperand(0);
3690     EVT SrcVT = N0.getValueType();
3691     unsigned SrcBits = SrcVT.getScalarSizeInBits();
3692 
3693     // Ignore bitcasts from unsupported types..
3694     if (!(SrcVT.isInteger() || SrcVT.isFloatingPoint()))
3695       break;
3696 
3697     // Fast handling of 'identity' bitcasts.
3698     if (VTBits == SrcBits)
3699       return ComputeNumSignBits(N0, DemandedElts, Depth + 1);
3700 
3701     bool IsLE = getDataLayout().isLittleEndian();
3702 
3703     // Bitcast 'large element' scalar/vector to 'small element' vector.
3704     if ((SrcBits % VTBits) == 0) {
3705       assert(VT.isVector() && "Expected bitcast to vector");
3706 
3707       unsigned Scale = SrcBits / VTBits;
3708       APInt SrcDemandedElts(NumElts / Scale, 0);
3709       for (unsigned i = 0; i != NumElts; ++i)
3710         if (DemandedElts[i])
3711           SrcDemandedElts.setBit(i / Scale);
3712 
3713       // Fast case - sign splat can be simply split across the small elements.
3714       Tmp = ComputeNumSignBits(N0, SrcDemandedElts, Depth + 1);
3715       if (Tmp == SrcBits)
3716         return VTBits;
3717 
3718       // Slow case - determine how far the sign extends into each sub-element.
3719       Tmp2 = VTBits;
3720       for (unsigned i = 0; i != NumElts; ++i)
3721         if (DemandedElts[i]) {
3722           unsigned SubOffset = i % Scale;
3723           SubOffset = (IsLE ? ((Scale - 1) - SubOffset) : SubOffset);
3724           SubOffset = SubOffset * VTBits;
3725           if (Tmp <= SubOffset)
3726             return 1;
3727           Tmp2 = std::min(Tmp2, Tmp - SubOffset);
3728         }
3729       return Tmp2;
3730     }
3731     break;
3732   }
3733 
3734   case ISD::SIGN_EXTEND:
3735     Tmp = VTBits - Op.getOperand(0).getScalarValueSizeInBits();
3736     return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1) + Tmp;
3737   case ISD::SIGN_EXTEND_INREG:
3738     // Max of the input and what this extends.
3739     Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getScalarSizeInBits();
3740     Tmp = VTBits-Tmp+1;
3741     Tmp2 = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1);
3742     return std::max(Tmp, Tmp2);
3743   case ISD::SIGN_EXTEND_VECTOR_INREG: {
3744     SDValue Src = Op.getOperand(0);
3745     EVT SrcVT = Src.getValueType();
3746     APInt DemandedSrcElts = DemandedElts.zextOrSelf(SrcVT.getVectorNumElements());
3747     Tmp = VTBits - SrcVT.getScalarSizeInBits();
3748     return ComputeNumSignBits(Src, DemandedSrcElts, Depth+1) + Tmp;
3749   }
3750   case ISD::SRA:
3751     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
3752     // SRA X, C -> adds C sign bits.
3753     if (const APInt *ShAmt =
3754             getValidMinimumShiftAmountConstant(Op, DemandedElts))
3755       Tmp = std::min<uint64_t>(Tmp + ShAmt->getZExtValue(), VTBits);
3756     return Tmp;
3757   case ISD::SHL:
3758     if (const APInt *ShAmt =
3759             getValidMaximumShiftAmountConstant(Op, DemandedElts)) {
3760       // shl destroys sign bits, ensure it doesn't shift out all sign bits.
3761       Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
3762       if (ShAmt->ult(Tmp))
3763         return Tmp - ShAmt->getZExtValue();
3764     }
3765     break;
3766   case ISD::AND:
3767   case ISD::OR:
3768   case ISD::XOR:    // NOT is handled here.
3769     // Logical binary ops preserve the number of sign bits at the worst.
3770     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1);
3771     if (Tmp != 1) {
3772       Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth+1);
3773       FirstAnswer = std::min(Tmp, Tmp2);
3774       // We computed what we know about the sign bits as our first
3775       // answer. Now proceed to the generic code that uses
3776       // computeKnownBits, and pick whichever answer is better.
3777     }
3778     break;
3779 
3780   case ISD::SELECT:
3781   case ISD::VSELECT:
3782     Tmp = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth+1);
3783     if (Tmp == 1) return 1;  // Early out.
3784     Tmp2 = ComputeNumSignBits(Op.getOperand(2), DemandedElts, Depth+1);
3785     return std::min(Tmp, Tmp2);
3786   case ISD::SELECT_CC:
3787     Tmp = ComputeNumSignBits(Op.getOperand(2), DemandedElts, Depth+1);
3788     if (Tmp == 1) return 1;  // Early out.
3789     Tmp2 = ComputeNumSignBits(Op.getOperand(3), DemandedElts, Depth+1);
3790     return std::min(Tmp, Tmp2);
3791 
3792   case ISD::SMIN:
3793   case ISD::SMAX: {
3794     // If we have a clamp pattern, we know that the number of sign bits will be
3795     // the minimum of the clamp min/max range.
3796     bool IsMax = (Opcode == ISD::SMAX);
3797     ConstantSDNode *CstLow = nullptr, *CstHigh = nullptr;
3798     if ((CstLow = isConstOrConstSplat(Op.getOperand(1), DemandedElts)))
3799       if (Op.getOperand(0).getOpcode() == (IsMax ? ISD::SMIN : ISD::SMAX))
3800         CstHigh =
3801             isConstOrConstSplat(Op.getOperand(0).getOperand(1), DemandedElts);
3802     if (CstLow && CstHigh) {
3803       if (!IsMax)
3804         std::swap(CstLow, CstHigh);
3805       if (CstLow->getAPIntValue().sle(CstHigh->getAPIntValue())) {
3806         Tmp = CstLow->getAPIntValue().getNumSignBits();
3807         Tmp2 = CstHigh->getAPIntValue().getNumSignBits();
3808         return std::min(Tmp, Tmp2);
3809       }
3810     }
3811 
3812     // Fallback - just get the minimum number of sign bits of the operands.
3813     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
3814     if (Tmp == 1)
3815       return 1;  // Early out.
3816     Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
3817     return std::min(Tmp, Tmp2);
3818   }
3819   case ISD::UMIN:
3820   case ISD::UMAX:
3821     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
3822     if (Tmp == 1)
3823       return 1;  // Early out.
3824     Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
3825     return std::min(Tmp, Tmp2);
3826   case ISD::SADDO:
3827   case ISD::UADDO:
3828   case ISD::SSUBO:
3829   case ISD::USUBO:
3830   case ISD::SMULO:
3831   case ISD::UMULO:
3832     if (Op.getResNo() != 1)
3833       break;
3834     // The boolean result conforms to getBooleanContents.  Fall through.
3835     // If setcc returns 0/-1, all bits are sign bits.
3836     // We know that we have an integer-based boolean since these operations
3837     // are only available for integer.
3838     if (TLI->getBooleanContents(VT.isVector(), false) ==
3839         TargetLowering::ZeroOrNegativeOneBooleanContent)
3840       return VTBits;
3841     break;
3842   case ISD::SETCC:
3843   case ISD::STRICT_FSETCC:
3844   case ISD::STRICT_FSETCCS: {
3845     unsigned OpNo = Op->isStrictFPOpcode() ? 1 : 0;
3846     // If setcc returns 0/-1, all bits are sign bits.
3847     if (TLI->getBooleanContents(Op.getOperand(OpNo).getValueType()) ==
3848         TargetLowering::ZeroOrNegativeOneBooleanContent)
3849       return VTBits;
3850     break;
3851   }
3852   case ISD::ROTL:
3853   case ISD::ROTR:
3854     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
3855 
3856     // If we're rotating an 0/-1 value, then it stays an 0/-1 value.
3857     if (Tmp == VTBits)
3858       return VTBits;
3859 
3860     if (ConstantSDNode *C =
3861             isConstOrConstSplat(Op.getOperand(1), DemandedElts)) {
3862       unsigned RotAmt = C->getAPIntValue().urem(VTBits);
3863 
3864       // Handle rotate right by N like a rotate left by 32-N.
3865       if (Opcode == ISD::ROTR)
3866         RotAmt = (VTBits - RotAmt) % VTBits;
3867 
3868       // If we aren't rotating out all of the known-in sign bits, return the
3869       // number that are left.  This handles rotl(sext(x), 1) for example.
3870       if (Tmp > (RotAmt + 1)) return (Tmp - RotAmt);
3871     }
3872     break;
3873   case ISD::ADD:
3874   case ISD::ADDC:
3875     // Add can have at most one carry bit.  Thus we know that the output
3876     // is, at worst, one more bit than the inputs.
3877     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
3878     if (Tmp == 1) return 1; // Early out.
3879 
3880     // Special case decrementing a value (ADD X, -1):
3881     if (ConstantSDNode *CRHS =
3882             isConstOrConstSplat(Op.getOperand(1), DemandedElts))
3883       if (CRHS->isAllOnesValue()) {
3884         KnownBits Known =
3885             computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3886 
3887         // If the input is known to be 0 or 1, the output is 0/-1, which is all
3888         // sign bits set.
3889         if ((Known.Zero | 1).isAllOnesValue())
3890           return VTBits;
3891 
3892         // If we are subtracting one from a positive number, there is no carry
3893         // out of the result.
3894         if (Known.isNonNegative())
3895           return Tmp;
3896       }
3897 
3898     Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
3899     if (Tmp2 == 1) return 1; // Early out.
3900     return std::min(Tmp, Tmp2) - 1;
3901   case ISD::SUB:
3902     Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
3903     if (Tmp2 == 1) return 1; // Early out.
3904 
3905     // Handle NEG.
3906     if (ConstantSDNode *CLHS =
3907             isConstOrConstSplat(Op.getOperand(0), DemandedElts))
3908       if (CLHS->isNullValue()) {
3909         KnownBits Known =
3910             computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3911         // If the input is known to be 0 or 1, the output is 0/-1, which is all
3912         // sign bits set.
3913         if ((Known.Zero | 1).isAllOnesValue())
3914           return VTBits;
3915 
3916         // If the input is known to be positive (the sign bit is known clear),
3917         // the output of the NEG has the same number of sign bits as the input.
3918         if (Known.isNonNegative())
3919           return Tmp2;
3920 
3921         // Otherwise, we treat this like a SUB.
3922       }
3923 
3924     // Sub can have at most one carry bit.  Thus we know that the output
3925     // is, at worst, one more bit than the inputs.
3926     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
3927     if (Tmp == 1) return 1; // Early out.
3928     return std::min(Tmp, Tmp2) - 1;
3929   case ISD::MUL: {
3930     // The output of the Mul can be at most twice the valid bits in the inputs.
3931     unsigned SignBitsOp0 = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
3932     if (SignBitsOp0 == 1)
3933       break;
3934     unsigned SignBitsOp1 = ComputeNumSignBits(Op.getOperand(1), Depth + 1);
3935     if (SignBitsOp1 == 1)
3936       break;
3937     unsigned OutValidBits =
3938         (VTBits - SignBitsOp0 + 1) + (VTBits - SignBitsOp1 + 1);
3939     return OutValidBits > VTBits ? 1 : VTBits - OutValidBits + 1;
3940   }
3941   case ISD::SREM:
3942     // The sign bit is the LHS's sign bit, except when the result of the
3943     // remainder is zero. The magnitude of the result should be less than or
3944     // equal to the magnitude of the LHS. Therefore, the result should have
3945     // at least as many sign bits as the left hand side.
3946     return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
3947   case ISD::TRUNCATE: {
3948     // Check if the sign bits of source go down as far as the truncated value.
3949     unsigned NumSrcBits = Op.getOperand(0).getScalarValueSizeInBits();
3950     unsigned NumSrcSignBits = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
3951     if (NumSrcSignBits > (NumSrcBits - VTBits))
3952       return NumSrcSignBits - (NumSrcBits - VTBits);
3953     break;
3954   }
3955   case ISD::EXTRACT_ELEMENT: {
3956     const int KnownSign = ComputeNumSignBits(Op.getOperand(0), Depth+1);
3957     const int BitWidth = Op.getValueSizeInBits();
3958     const int Items = Op.getOperand(0).getValueSizeInBits() / BitWidth;
3959 
3960     // Get reverse index (starting from 1), Op1 value indexes elements from
3961     // little end. Sign starts at big end.
3962     const int rIndex = Items - 1 - Op.getConstantOperandVal(1);
3963 
3964     // If the sign portion ends in our element the subtraction gives correct
3965     // result. Otherwise it gives either negative or > bitwidth result
3966     return std::max(std::min(KnownSign - rIndex * BitWidth, BitWidth), 0);
3967   }
3968   case ISD::INSERT_VECTOR_ELT: {
3969     // If we know the element index, split the demand between the
3970     // source vector and the inserted element, otherwise assume we need
3971     // the original demanded vector elements and the value.
3972     SDValue InVec = Op.getOperand(0);
3973     SDValue InVal = Op.getOperand(1);
3974     SDValue EltNo = Op.getOperand(2);
3975     bool DemandedVal = true;
3976     APInt DemandedVecElts = DemandedElts;
3977     auto *CEltNo = dyn_cast<ConstantSDNode>(EltNo);
3978     if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) {
3979       unsigned EltIdx = CEltNo->getZExtValue();
3980       DemandedVal = !!DemandedElts[EltIdx];
3981       DemandedVecElts.clearBit(EltIdx);
3982     }
3983     Tmp = std::numeric_limits<unsigned>::max();
3984     if (DemandedVal) {
3985       // TODO - handle implicit truncation of inserted elements.
3986       if (InVal.getScalarValueSizeInBits() != VTBits)
3987         break;
3988       Tmp2 = ComputeNumSignBits(InVal, Depth + 1);
3989       Tmp = std::min(Tmp, Tmp2);
3990     }
3991     if (!!DemandedVecElts) {
3992       Tmp2 = ComputeNumSignBits(InVec, DemandedVecElts, Depth + 1);
3993       Tmp = std::min(Tmp, Tmp2);
3994     }
3995     assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
3996     return Tmp;
3997   }
3998   case ISD::EXTRACT_VECTOR_ELT: {
3999     SDValue InVec = Op.getOperand(0);
4000     SDValue EltNo = Op.getOperand(1);
4001     EVT VecVT = InVec.getValueType();
4002     // ComputeNumSignBits not yet implemented for scalable vectors.
4003     if (VecVT.isScalableVector())
4004       break;
4005     const unsigned BitWidth = Op.getValueSizeInBits();
4006     const unsigned EltBitWidth = Op.getOperand(0).getScalarValueSizeInBits();
4007     const unsigned NumSrcElts = VecVT.getVectorNumElements();
4008 
4009     // If BitWidth > EltBitWidth the value is anyext:ed, and we do not know
4010     // anything about sign bits. But if the sizes match we can derive knowledge
4011     // about sign bits from the vector operand.
4012     if (BitWidth != EltBitWidth)
4013       break;
4014 
4015     // If we know the element index, just demand that vector element, else for
4016     // an unknown element index, ignore DemandedElts and demand them all.
4017     APInt DemandedSrcElts = APInt::getAllOnesValue(NumSrcElts);
4018     auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
4019     if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts))
4020       DemandedSrcElts =
4021           APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue());
4022 
4023     return ComputeNumSignBits(InVec, DemandedSrcElts, Depth + 1);
4024   }
4025   case ISD::EXTRACT_SUBVECTOR: {
4026     // Offset the demanded elts by the subvector index.
4027     SDValue Src = Op.getOperand(0);
4028     // Bail until we can represent demanded elements for scalable vectors.
4029     if (Src.getValueType().isScalableVector())
4030       break;
4031     uint64_t Idx = Op.getConstantOperandVal(1);
4032     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
4033     APInt DemandedSrcElts = DemandedElts.zextOrSelf(NumSrcElts).shl(Idx);
4034     return ComputeNumSignBits(Src, DemandedSrcElts, Depth + 1);
4035   }
4036   case ISD::CONCAT_VECTORS: {
4037     // Determine the minimum number of sign bits across all demanded
4038     // elts of the input vectors. Early out if the result is already 1.
4039     Tmp = std::numeric_limits<unsigned>::max();
4040     EVT SubVectorVT = Op.getOperand(0).getValueType();
4041     unsigned NumSubVectorElts = SubVectorVT.getVectorNumElements();
4042     unsigned NumSubVectors = Op.getNumOperands();
4043     for (unsigned i = 0; (i < NumSubVectors) && (Tmp > 1); ++i) {
4044       APInt DemandedSub = DemandedElts.lshr(i * NumSubVectorElts);
4045       DemandedSub = DemandedSub.trunc(NumSubVectorElts);
4046       if (!DemandedSub)
4047         continue;
4048       Tmp2 = ComputeNumSignBits(Op.getOperand(i), DemandedSub, Depth + 1);
4049       Tmp = std::min(Tmp, Tmp2);
4050     }
4051     assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
4052     return Tmp;
4053   }
4054   case ISD::INSERT_SUBVECTOR: {
4055     // Demand any elements from the subvector and the remainder from the src its
4056     // inserted into.
4057     SDValue Src = Op.getOperand(0);
4058     SDValue Sub = Op.getOperand(1);
4059     uint64_t Idx = Op.getConstantOperandVal(2);
4060     unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
4061     APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
4062     APInt DemandedSrcElts = DemandedElts;
4063     DemandedSrcElts.insertBits(APInt::getNullValue(NumSubElts), Idx);
4064 
4065     Tmp = std::numeric_limits<unsigned>::max();
4066     if (!!DemandedSubElts) {
4067       Tmp = ComputeNumSignBits(Sub, DemandedSubElts, Depth + 1);
4068       if (Tmp == 1)
4069         return 1; // early-out
4070     }
4071     if (!!DemandedSrcElts) {
4072       Tmp2 = ComputeNumSignBits(Src, DemandedSrcElts, Depth + 1);
4073       Tmp = std::min(Tmp, Tmp2);
4074     }
4075     assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
4076     return Tmp;
4077   }
4078   }
4079 
4080   // If we are looking at the loaded value of the SDNode.
4081   if (Op.getResNo() == 0) {
4082     // Handle LOADX separately here. EXTLOAD case will fallthrough.
4083     if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
4084       unsigned ExtType = LD->getExtensionType();
4085       switch (ExtType) {
4086       default: break;
4087       case ISD::SEXTLOAD: // e.g. i16->i32 = '17' bits known.
4088         Tmp = LD->getMemoryVT().getScalarSizeInBits();
4089         return VTBits - Tmp + 1;
4090       case ISD::ZEXTLOAD: // e.g. i16->i32 = '16' bits known.
4091         Tmp = LD->getMemoryVT().getScalarSizeInBits();
4092         return VTBits - Tmp;
4093       case ISD::NON_EXTLOAD:
4094         if (const Constant *Cst = TLI->getTargetConstantFromLoad(LD)) {
4095           // We only need to handle vectors - computeKnownBits should handle
4096           // scalar cases.
4097           Type *CstTy = Cst->getType();
4098           if (CstTy->isVectorTy() &&
4099               (NumElts * VTBits) == CstTy->getPrimitiveSizeInBits()) {
4100             Tmp = VTBits;
4101             for (unsigned i = 0; i != NumElts; ++i) {
4102               if (!DemandedElts[i])
4103                 continue;
4104               if (Constant *Elt = Cst->getAggregateElement(i)) {
4105                 if (auto *CInt = dyn_cast<ConstantInt>(Elt)) {
4106                   const APInt &Value = CInt->getValue();
4107                   Tmp = std::min(Tmp, Value.getNumSignBits());
4108                   continue;
4109                 }
4110                 if (auto *CFP = dyn_cast<ConstantFP>(Elt)) {
4111                   APInt Value = CFP->getValueAPF().bitcastToAPInt();
4112                   Tmp = std::min(Tmp, Value.getNumSignBits());
4113                   continue;
4114                 }
4115               }
4116               // Unknown type. Conservatively assume no bits match sign bit.
4117               return 1;
4118             }
4119             return Tmp;
4120           }
4121         }
4122         break;
4123       }
4124     }
4125   }
4126 
4127   // Allow the target to implement this method for its nodes.
4128   if (Opcode >= ISD::BUILTIN_OP_END ||
4129       Opcode == ISD::INTRINSIC_WO_CHAIN ||
4130       Opcode == ISD::INTRINSIC_W_CHAIN ||
4131       Opcode == ISD::INTRINSIC_VOID) {
4132     unsigned NumBits =
4133         TLI->ComputeNumSignBitsForTargetNode(Op, DemandedElts, *this, Depth);
4134     if (NumBits > 1)
4135       FirstAnswer = std::max(FirstAnswer, NumBits);
4136   }
4137 
4138   // Finally, if we can prove that the top bits of the result are 0's or 1's,
4139   // use this information.
4140   KnownBits Known = computeKnownBits(Op, DemandedElts, Depth);
4141 
4142   APInt Mask;
4143   if (Known.isNonNegative()) {        // sign bit is 0
4144     Mask = Known.Zero;
4145   } else if (Known.isNegative()) {  // sign bit is 1;
4146     Mask = Known.One;
4147   } else {
4148     // Nothing known.
4149     return FirstAnswer;
4150   }
4151 
4152   // Okay, we know that the sign bit in Mask is set.  Use CLO to determine
4153   // the number of identical bits in the top of the input value.
4154   Mask <<= Mask.getBitWidth()-VTBits;
4155   return std::max(FirstAnswer, Mask.countLeadingOnes());
4156 }
4157 
4158 bool SelectionDAG::isBaseWithConstantOffset(SDValue Op) const {
4159   if ((Op.getOpcode() != ISD::ADD && Op.getOpcode() != ISD::OR) ||
4160       !isa<ConstantSDNode>(Op.getOperand(1)))
4161     return false;
4162 
4163   if (Op.getOpcode() == ISD::OR &&
4164       !MaskedValueIsZero(Op.getOperand(0), Op.getConstantOperandAPInt(1)))
4165     return false;
4166 
4167   return true;
4168 }
4169 
4170 bool SelectionDAG::isKnownNeverNaN(SDValue Op, bool SNaN, unsigned Depth) const {
4171   // If we're told that NaNs won't happen, assume they won't.
4172   if (getTarget().Options.NoNaNsFPMath || Op->getFlags().hasNoNaNs())
4173     return true;
4174 
4175   if (Depth >= MaxRecursionDepth)
4176     return false; // Limit search depth.
4177 
4178   // TODO: Handle vectors.
4179   // If the value is a constant, we can obviously see if it is a NaN or not.
4180   if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) {
4181     return !C->getValueAPF().isNaN() ||
4182            (SNaN && !C->getValueAPF().isSignaling());
4183   }
4184 
4185   unsigned Opcode = Op.getOpcode();
4186   switch (Opcode) {
4187   case ISD::FADD:
4188   case ISD::FSUB:
4189   case ISD::FMUL:
4190   case ISD::FDIV:
4191   case ISD::FREM:
4192   case ISD::FSIN:
4193   case ISD::FCOS: {
4194     if (SNaN)
4195       return true;
4196     // TODO: Need isKnownNeverInfinity
4197     return false;
4198   }
4199   case ISD::FCANONICALIZE:
4200   case ISD::FEXP:
4201   case ISD::FEXP2:
4202   case ISD::FTRUNC:
4203   case ISD::FFLOOR:
4204   case ISD::FCEIL:
4205   case ISD::FROUND:
4206   case ISD::FROUNDEVEN:
4207   case ISD::FRINT:
4208   case ISD::FNEARBYINT: {
4209     if (SNaN)
4210       return true;
4211     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
4212   }
4213   case ISD::FABS:
4214   case ISD::FNEG:
4215   case ISD::FCOPYSIGN: {
4216     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
4217   }
4218   case ISD::SELECT:
4219     return isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1) &&
4220            isKnownNeverNaN(Op.getOperand(2), SNaN, Depth + 1);
4221   case ISD::FP_EXTEND:
4222   case ISD::FP_ROUND: {
4223     if (SNaN)
4224       return true;
4225     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
4226   }
4227   case ISD::SINT_TO_FP:
4228   case ISD::UINT_TO_FP:
4229     return true;
4230   case ISD::FMA:
4231   case ISD::FMAD: {
4232     if (SNaN)
4233       return true;
4234     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) &&
4235            isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1) &&
4236            isKnownNeverNaN(Op.getOperand(2), SNaN, Depth + 1);
4237   }
4238   case ISD::FSQRT: // Need is known positive
4239   case ISD::FLOG:
4240   case ISD::FLOG2:
4241   case ISD::FLOG10:
4242   case ISD::FPOWI:
4243   case ISD::FPOW: {
4244     if (SNaN)
4245       return true;
4246     // TODO: Refine on operand
4247     return false;
4248   }
4249   case ISD::FMINNUM:
4250   case ISD::FMAXNUM: {
4251     // Only one needs to be known not-nan, since it will be returned if the
4252     // other ends up being one.
4253     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) ||
4254            isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1);
4255   }
4256   case ISD::FMINNUM_IEEE:
4257   case ISD::FMAXNUM_IEEE: {
4258     if (SNaN)
4259       return true;
4260     // This can return a NaN if either operand is an sNaN, or if both operands
4261     // are NaN.
4262     return (isKnownNeverNaN(Op.getOperand(0), false, Depth + 1) &&
4263             isKnownNeverSNaN(Op.getOperand(1), Depth + 1)) ||
4264            (isKnownNeverNaN(Op.getOperand(1), false, Depth + 1) &&
4265             isKnownNeverSNaN(Op.getOperand(0), Depth + 1));
4266   }
4267   case ISD::FMINIMUM:
4268   case ISD::FMAXIMUM: {
4269     // TODO: Does this quiet or return the origina NaN as-is?
4270     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) &&
4271            isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1);
4272   }
4273   case ISD::EXTRACT_VECTOR_ELT: {
4274     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
4275   }
4276   default:
4277     if (Opcode >= ISD::BUILTIN_OP_END ||
4278         Opcode == ISD::INTRINSIC_WO_CHAIN ||
4279         Opcode == ISD::INTRINSIC_W_CHAIN ||
4280         Opcode == ISD::INTRINSIC_VOID) {
4281       return TLI->isKnownNeverNaNForTargetNode(Op, *this, SNaN, Depth);
4282     }
4283 
4284     return false;
4285   }
4286 }
4287 
4288 bool SelectionDAG::isKnownNeverZeroFloat(SDValue Op) const {
4289   assert(Op.getValueType().isFloatingPoint() &&
4290          "Floating point type expected");
4291 
4292   // If the value is a constant, we can obviously see if it is a zero or not.
4293   // TODO: Add BuildVector support.
4294   if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op))
4295     return !C->isZero();
4296   return false;
4297 }
4298 
4299 bool SelectionDAG::isKnownNeverZero(SDValue Op) const {
4300   assert(!Op.getValueType().isFloatingPoint() &&
4301          "Floating point types unsupported - use isKnownNeverZeroFloat");
4302 
4303   // If the value is a constant, we can obviously see if it is a zero or not.
4304   if (ISD::matchUnaryPredicate(
4305           Op, [](ConstantSDNode *C) { return !C->isNullValue(); }))
4306     return true;
4307 
4308   // TODO: Recognize more cases here.
4309   switch (Op.getOpcode()) {
4310   default: break;
4311   case ISD::OR:
4312     if (isKnownNeverZero(Op.getOperand(1)) ||
4313         isKnownNeverZero(Op.getOperand(0)))
4314       return true;
4315     break;
4316   }
4317 
4318   return false;
4319 }
4320 
4321 bool SelectionDAG::isEqualTo(SDValue A, SDValue B) const {
4322   // Check the obvious case.
4323   if (A == B) return true;
4324 
4325   // For for negative and positive zero.
4326   if (const ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A))
4327     if (const ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B))
4328       if (CA->isZero() && CB->isZero()) return true;
4329 
4330   // Otherwise they may not be equal.
4331   return false;
4332 }
4333 
4334 // FIXME: unify with llvm::haveNoCommonBitsSet.
4335 // FIXME: could also handle masked merge pattern (X & ~M) op (Y & M)
4336 bool SelectionDAG::haveNoCommonBitsSet(SDValue A, SDValue B) const {
4337   assert(A.getValueType() == B.getValueType() &&
4338          "Values must have the same type");
4339   return (computeKnownBits(A).Zero | computeKnownBits(B).Zero).isAllOnesValue();
4340 }
4341 
4342 static SDValue FoldBUILD_VECTOR(const SDLoc &DL, EVT VT,
4343                                 ArrayRef<SDValue> Ops,
4344                                 SelectionDAG &DAG) {
4345   int NumOps = Ops.size();
4346   assert(NumOps != 0 && "Can't build an empty vector!");
4347   assert(!VT.isScalableVector() &&
4348          "BUILD_VECTOR cannot be used with scalable types");
4349   assert(VT.getVectorNumElements() == (unsigned)NumOps &&
4350          "Incorrect element count in BUILD_VECTOR!");
4351 
4352   // BUILD_VECTOR of UNDEFs is UNDEF.
4353   if (llvm::all_of(Ops, [](SDValue Op) { return Op.isUndef(); }))
4354     return DAG.getUNDEF(VT);
4355 
4356   // BUILD_VECTOR of seq extract/insert from the same vector + type is Identity.
4357   SDValue IdentitySrc;
4358   bool IsIdentity = true;
4359   for (int i = 0; i != NumOps; ++i) {
4360     if (Ops[i].getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
4361         Ops[i].getOperand(0).getValueType() != VT ||
4362         (IdentitySrc && Ops[i].getOperand(0) != IdentitySrc) ||
4363         !isa<ConstantSDNode>(Ops[i].getOperand(1)) ||
4364         cast<ConstantSDNode>(Ops[i].getOperand(1))->getAPIntValue() != i) {
4365       IsIdentity = false;
4366       break;
4367     }
4368     IdentitySrc = Ops[i].getOperand(0);
4369   }
4370   if (IsIdentity)
4371     return IdentitySrc;
4372 
4373   return SDValue();
4374 }
4375 
4376 /// Try to simplify vector concatenation to an input value, undef, or build
4377 /// vector.
4378 static SDValue foldCONCAT_VECTORS(const SDLoc &DL, EVT VT,
4379                                   ArrayRef<SDValue> Ops,
4380                                   SelectionDAG &DAG) {
4381   assert(!Ops.empty() && "Can't concatenate an empty list of vectors!");
4382   assert(llvm::all_of(Ops,
4383                       [Ops](SDValue Op) {
4384                         return Ops[0].getValueType() == Op.getValueType();
4385                       }) &&
4386          "Concatenation of vectors with inconsistent value types!");
4387   assert((Ops[0].getValueType().getVectorElementCount() * Ops.size()) ==
4388              VT.getVectorElementCount() &&
4389          "Incorrect element count in vector concatenation!");
4390 
4391   if (Ops.size() == 1)
4392     return Ops[0];
4393 
4394   // Concat of UNDEFs is UNDEF.
4395   if (llvm::all_of(Ops, [](SDValue Op) { return Op.isUndef(); }))
4396     return DAG.getUNDEF(VT);
4397 
4398   // Scan the operands and look for extract operations from a single source
4399   // that correspond to insertion at the same location via this concatenation:
4400   // concat (extract X, 0*subvec_elts), (extract X, 1*subvec_elts), ...
4401   SDValue IdentitySrc;
4402   bool IsIdentity = true;
4403   for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
4404     SDValue Op = Ops[i];
4405     unsigned IdentityIndex = i * Op.getValueType().getVectorMinNumElements();
4406     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
4407         Op.getOperand(0).getValueType() != VT ||
4408         (IdentitySrc && Op.getOperand(0) != IdentitySrc) ||
4409         Op.getConstantOperandVal(1) != IdentityIndex) {
4410       IsIdentity = false;
4411       break;
4412     }
4413     assert((!IdentitySrc || IdentitySrc == Op.getOperand(0)) &&
4414            "Unexpected identity source vector for concat of extracts");
4415     IdentitySrc = Op.getOperand(0);
4416   }
4417   if (IsIdentity) {
4418     assert(IdentitySrc && "Failed to set source vector of extracts");
4419     return IdentitySrc;
4420   }
4421 
4422   // The code below this point is only designed to work for fixed width
4423   // vectors, so we bail out for now.
4424   if (VT.isScalableVector())
4425     return SDValue();
4426 
4427   // A CONCAT_VECTOR with all UNDEF/BUILD_VECTOR operands can be
4428   // simplified to one big BUILD_VECTOR.
4429   // FIXME: Add support for SCALAR_TO_VECTOR as well.
4430   EVT SVT = VT.getScalarType();
4431   SmallVector<SDValue, 16> Elts;
4432   for (SDValue Op : Ops) {
4433     EVT OpVT = Op.getValueType();
4434     if (Op.isUndef())
4435       Elts.append(OpVT.getVectorNumElements(), DAG.getUNDEF(SVT));
4436     else if (Op.getOpcode() == ISD::BUILD_VECTOR)
4437       Elts.append(Op->op_begin(), Op->op_end());
4438     else
4439       return SDValue();
4440   }
4441 
4442   // BUILD_VECTOR requires all inputs to be of the same type, find the
4443   // maximum type and extend them all.
4444   for (SDValue Op : Elts)
4445     SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
4446 
4447   if (SVT.bitsGT(VT.getScalarType())) {
4448     for (SDValue &Op : Elts) {
4449       if (Op.isUndef())
4450         Op = DAG.getUNDEF(SVT);
4451       else
4452         Op = DAG.getTargetLoweringInfo().isZExtFree(Op.getValueType(), SVT)
4453                  ? DAG.getZExtOrTrunc(Op, DL, SVT)
4454                  : DAG.getSExtOrTrunc(Op, DL, SVT);
4455     }
4456   }
4457 
4458   SDValue V = DAG.getBuildVector(VT, DL, Elts);
4459   NewSDValueDbgMsg(V, "New node fold concat vectors: ", &DAG);
4460   return V;
4461 }
4462 
4463 /// Gets or creates the specified node.
4464 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT) {
4465   FoldingSetNodeID ID;
4466   AddNodeIDNode(ID, Opcode, getVTList(VT), None);
4467   void *IP = nullptr;
4468   if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
4469     return SDValue(E, 0);
4470 
4471   auto *N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(),
4472                               getVTList(VT));
4473   CSEMap.InsertNode(N, IP);
4474 
4475   InsertNode(N);
4476   SDValue V = SDValue(N, 0);
4477   NewSDValueDbgMsg(V, "Creating new node: ", this);
4478   return V;
4479 }
4480 
4481 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
4482                               SDValue Operand) {
4483   SDNodeFlags Flags;
4484   if (Inserter)
4485     Flags = Inserter->getFlags();
4486   return getNode(Opcode, DL, VT, Operand, Flags);
4487 }
4488 
4489 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
4490                               SDValue Operand, const SDNodeFlags Flags) {
4491   assert(Operand.getOpcode() != ISD::DELETED_NODE &&
4492          "Operand is DELETED_NODE!");
4493   // Constant fold unary operations with an integer constant operand. Even
4494   // opaque constant will be folded, because the folding of unary operations
4495   // doesn't create new constants with different values. Nevertheless, the
4496   // opaque flag is preserved during folding to prevent future folding with
4497   // other constants.
4498   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Operand)) {
4499     const APInt &Val = C->getAPIntValue();
4500     switch (Opcode) {
4501     default: break;
4502     case ISD::SIGN_EXTEND:
4503       return getConstant(Val.sextOrTrunc(VT.getSizeInBits()), DL, VT,
4504                          C->isTargetOpcode(), C->isOpaque());
4505     case ISD::TRUNCATE:
4506       if (C->isOpaque())
4507         break;
4508       LLVM_FALLTHROUGH;
4509     case ISD::ANY_EXTEND:
4510     case ISD::ZERO_EXTEND:
4511       return getConstant(Val.zextOrTrunc(VT.getSizeInBits()), DL, VT,
4512                          C->isTargetOpcode(), C->isOpaque());
4513     case ISD::UINT_TO_FP:
4514     case ISD::SINT_TO_FP: {
4515       APFloat apf(EVTToAPFloatSemantics(VT),
4516                   APInt::getNullValue(VT.getSizeInBits()));
4517       (void)apf.convertFromAPInt(Val,
4518                                  Opcode==ISD::SINT_TO_FP,
4519                                  APFloat::rmNearestTiesToEven);
4520       return getConstantFP(apf, DL, VT);
4521     }
4522     case ISD::BITCAST:
4523       if (VT == MVT::f16 && C->getValueType(0) == MVT::i16)
4524         return getConstantFP(APFloat(APFloat::IEEEhalf(), Val), DL, VT);
4525       if (VT == MVT::f32 && C->getValueType(0) == MVT::i32)
4526         return getConstantFP(APFloat(APFloat::IEEEsingle(), Val), DL, VT);
4527       if (VT == MVT::f64 && C->getValueType(0) == MVT::i64)
4528         return getConstantFP(APFloat(APFloat::IEEEdouble(), Val), DL, VT);
4529       if (VT == MVT::f128 && C->getValueType(0) == MVT::i128)
4530         return getConstantFP(APFloat(APFloat::IEEEquad(), Val), DL, VT);
4531       break;
4532     case ISD::ABS:
4533       return getConstant(Val.abs(), DL, VT, C->isTargetOpcode(),
4534                          C->isOpaque());
4535     case ISD::BITREVERSE:
4536       return getConstant(Val.reverseBits(), DL, VT, C->isTargetOpcode(),
4537                          C->isOpaque());
4538     case ISD::BSWAP:
4539       return getConstant(Val.byteSwap(), DL, VT, C->isTargetOpcode(),
4540                          C->isOpaque());
4541     case ISD::CTPOP:
4542       return getConstant(Val.countPopulation(), DL, VT, C->isTargetOpcode(),
4543                          C->isOpaque());
4544     case ISD::CTLZ:
4545     case ISD::CTLZ_ZERO_UNDEF:
4546       return getConstant(Val.countLeadingZeros(), DL, VT, C->isTargetOpcode(),
4547                          C->isOpaque());
4548     case ISD::CTTZ:
4549     case ISD::CTTZ_ZERO_UNDEF:
4550       return getConstant(Val.countTrailingZeros(), DL, VT, C->isTargetOpcode(),
4551                          C->isOpaque());
4552     case ISD::FP16_TO_FP: {
4553       bool Ignored;
4554       APFloat FPV(APFloat::IEEEhalf(),
4555                   (Val.getBitWidth() == 16) ? Val : Val.trunc(16));
4556 
4557       // This can return overflow, underflow, or inexact; we don't care.
4558       // FIXME need to be more flexible about rounding mode.
4559       (void)FPV.convert(EVTToAPFloatSemantics(VT),
4560                         APFloat::rmNearestTiesToEven, &Ignored);
4561       return getConstantFP(FPV, DL, VT);
4562     }
4563     }
4564   }
4565 
4566   // Constant fold unary operations with a floating point constant operand.
4567   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Operand)) {
4568     APFloat V = C->getValueAPF();    // make copy
4569     switch (Opcode) {
4570     case ISD::FNEG:
4571       V.changeSign();
4572       return getConstantFP(V, DL, VT);
4573     case ISD::FABS:
4574       V.clearSign();
4575       return getConstantFP(V, DL, VT);
4576     case ISD::FCEIL: {
4577       APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardPositive);
4578       if (fs == APFloat::opOK || fs == APFloat::opInexact)
4579         return getConstantFP(V, DL, VT);
4580       break;
4581     }
4582     case ISD::FTRUNC: {
4583       APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardZero);
4584       if (fs == APFloat::opOK || fs == APFloat::opInexact)
4585         return getConstantFP(V, DL, VT);
4586       break;
4587     }
4588     case ISD::FFLOOR: {
4589       APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardNegative);
4590       if (fs == APFloat::opOK || fs == APFloat::opInexact)
4591         return getConstantFP(V, DL, VT);
4592       break;
4593     }
4594     case ISD::FP_EXTEND: {
4595       bool ignored;
4596       // This can return overflow, underflow, or inexact; we don't care.
4597       // FIXME need to be more flexible about rounding mode.
4598       (void)V.convert(EVTToAPFloatSemantics(VT),
4599                       APFloat::rmNearestTiesToEven, &ignored);
4600       return getConstantFP(V, DL, VT);
4601     }
4602     case ISD::FP_TO_SINT:
4603     case ISD::FP_TO_UINT: {
4604       bool ignored;
4605       APSInt IntVal(VT.getSizeInBits(), Opcode == ISD::FP_TO_UINT);
4606       // FIXME need to be more flexible about rounding mode.
4607       APFloat::opStatus s =
4608           V.convertToInteger(IntVal, APFloat::rmTowardZero, &ignored);
4609       if (s == APFloat::opInvalidOp) // inexact is OK, in fact usual
4610         break;
4611       return getConstant(IntVal, DL, VT);
4612     }
4613     case ISD::BITCAST:
4614       if (VT == MVT::i16 && C->getValueType(0) == MVT::f16)
4615         return getConstant((uint16_t)V.bitcastToAPInt().getZExtValue(), DL, VT);
4616       else if (VT == MVT::i32 && C->getValueType(0) == MVT::f32)
4617         return getConstant((uint32_t)V.bitcastToAPInt().getZExtValue(), DL, VT);
4618       else if (VT == MVT::i64 && C->getValueType(0) == MVT::f64)
4619         return getConstant(V.bitcastToAPInt().getZExtValue(), DL, VT);
4620       break;
4621     case ISD::FP_TO_FP16: {
4622       bool Ignored;
4623       // This can return overflow, underflow, or inexact; we don't care.
4624       // FIXME need to be more flexible about rounding mode.
4625       (void)V.convert(APFloat::IEEEhalf(),
4626                       APFloat::rmNearestTiesToEven, &Ignored);
4627       return getConstant(V.bitcastToAPInt().getZExtValue(), DL, VT);
4628     }
4629     }
4630   }
4631 
4632   // Constant fold unary operations with a vector integer or float operand.
4633   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Operand)) {
4634     if (BV->isConstant()) {
4635       switch (Opcode) {
4636       default:
4637         // FIXME: Entirely reasonable to perform folding of other unary
4638         // operations here as the need arises.
4639         break;
4640       case ISD::FNEG:
4641       case ISD::FABS:
4642       case ISD::FCEIL:
4643       case ISD::FTRUNC:
4644       case ISD::FFLOOR:
4645       case ISD::FP_EXTEND:
4646       case ISD::FP_TO_SINT:
4647       case ISD::FP_TO_UINT:
4648       case ISD::TRUNCATE:
4649       case ISD::ANY_EXTEND:
4650       case ISD::ZERO_EXTEND:
4651       case ISD::SIGN_EXTEND:
4652       case ISD::UINT_TO_FP:
4653       case ISD::SINT_TO_FP:
4654       case ISD::ABS:
4655       case ISD::BITREVERSE:
4656       case ISD::BSWAP:
4657       case ISD::CTLZ:
4658       case ISD::CTLZ_ZERO_UNDEF:
4659       case ISD::CTTZ:
4660       case ISD::CTTZ_ZERO_UNDEF:
4661       case ISD::CTPOP: {
4662         SDValue Ops = { Operand };
4663         if (SDValue Fold = FoldConstantVectorArithmetic(Opcode, DL, VT, Ops))
4664           return Fold;
4665       }
4666       }
4667     }
4668   }
4669 
4670   unsigned OpOpcode = Operand.getNode()->getOpcode();
4671   switch (Opcode) {
4672   case ISD::FREEZE:
4673     assert(VT == Operand.getValueType() && "Unexpected VT!");
4674     break;
4675   case ISD::TokenFactor:
4676   case ISD::MERGE_VALUES:
4677   case ISD::CONCAT_VECTORS:
4678     return Operand;         // Factor, merge or concat of one node?  No need.
4679   case ISD::BUILD_VECTOR: {
4680     // Attempt to simplify BUILD_VECTOR.
4681     SDValue Ops[] = {Operand};
4682     if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
4683       return V;
4684     break;
4685   }
4686   case ISD::FP_ROUND: llvm_unreachable("Invalid method to make FP_ROUND node");
4687   case ISD::FP_EXTEND:
4688     assert(VT.isFloatingPoint() &&
4689            Operand.getValueType().isFloatingPoint() && "Invalid FP cast!");
4690     if (Operand.getValueType() == VT) return Operand;  // noop conversion.
4691     assert((!VT.isVector() ||
4692             VT.getVectorElementCount() ==
4693             Operand.getValueType().getVectorElementCount()) &&
4694            "Vector element count mismatch!");
4695     assert(Operand.getValueType().bitsLT(VT) &&
4696            "Invalid fpext node, dst < src!");
4697     if (Operand.isUndef())
4698       return getUNDEF(VT);
4699     break;
4700   case ISD::FP_TO_SINT:
4701   case ISD::FP_TO_UINT:
4702     if (Operand.isUndef())
4703       return getUNDEF(VT);
4704     break;
4705   case ISD::SINT_TO_FP:
4706   case ISD::UINT_TO_FP:
4707     // [us]itofp(undef) = 0, because the result value is bounded.
4708     if (Operand.isUndef())
4709       return getConstantFP(0.0, DL, VT);
4710     break;
4711   case ISD::SIGN_EXTEND:
4712     assert(VT.isInteger() && Operand.getValueType().isInteger() &&
4713            "Invalid SIGN_EXTEND!");
4714     assert(VT.isVector() == Operand.getValueType().isVector() &&
4715            "SIGN_EXTEND result type type should be vector iff the operand "
4716            "type is vector!");
4717     if (Operand.getValueType() == VT) return Operand;   // noop extension
4718     assert((!VT.isVector() ||
4719             VT.getVectorElementCount() ==
4720                 Operand.getValueType().getVectorElementCount()) &&
4721            "Vector element count mismatch!");
4722     assert(Operand.getValueType().bitsLT(VT) &&
4723            "Invalid sext node, dst < src!");
4724     if (OpOpcode == ISD::SIGN_EXTEND || OpOpcode == ISD::ZERO_EXTEND)
4725       return getNode(OpOpcode, DL, VT, Operand.getOperand(0));
4726     else if (OpOpcode == ISD::UNDEF)
4727       // sext(undef) = 0, because the top bits will all be the same.
4728       return getConstant(0, DL, VT);
4729     break;
4730   case ISD::ZERO_EXTEND:
4731     assert(VT.isInteger() && Operand.getValueType().isInteger() &&
4732            "Invalid ZERO_EXTEND!");
4733     assert(VT.isVector() == Operand.getValueType().isVector() &&
4734            "ZERO_EXTEND result type type should be vector iff the operand "
4735            "type is vector!");
4736     if (Operand.getValueType() == VT) return Operand;   // noop extension
4737     assert((!VT.isVector() ||
4738             VT.getVectorElementCount() ==
4739                 Operand.getValueType().getVectorElementCount()) &&
4740            "Vector element count mismatch!");
4741     assert(Operand.getValueType().bitsLT(VT) &&
4742            "Invalid zext node, dst < src!");
4743     if (OpOpcode == ISD::ZERO_EXTEND)   // (zext (zext x)) -> (zext x)
4744       return getNode(ISD::ZERO_EXTEND, DL, VT, Operand.getOperand(0));
4745     else if (OpOpcode == ISD::UNDEF)
4746       // zext(undef) = 0, because the top bits will be zero.
4747       return getConstant(0, DL, VT);
4748     break;
4749   case ISD::ANY_EXTEND:
4750     assert(VT.isInteger() && Operand.getValueType().isInteger() &&
4751            "Invalid ANY_EXTEND!");
4752     assert(VT.isVector() == Operand.getValueType().isVector() &&
4753            "ANY_EXTEND result type type should be vector iff the operand "
4754            "type is vector!");
4755     if (Operand.getValueType() == VT) return Operand;   // noop extension
4756     assert((!VT.isVector() ||
4757             VT.getVectorElementCount() ==
4758                 Operand.getValueType().getVectorElementCount()) &&
4759            "Vector element count mismatch!");
4760     assert(Operand.getValueType().bitsLT(VT) &&
4761            "Invalid anyext node, dst < src!");
4762 
4763     if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
4764         OpOpcode == ISD::ANY_EXTEND)
4765       // (ext (zext x)) -> (zext x)  and  (ext (sext x)) -> (sext x)
4766       return getNode(OpOpcode, DL, VT, Operand.getOperand(0));
4767     else if (OpOpcode == ISD::UNDEF)
4768       return getUNDEF(VT);
4769 
4770     // (ext (trunc x)) -> x
4771     if (OpOpcode == ISD::TRUNCATE) {
4772       SDValue OpOp = Operand.getOperand(0);
4773       if (OpOp.getValueType() == VT) {
4774         transferDbgValues(Operand, OpOp);
4775         return OpOp;
4776       }
4777     }
4778     break;
4779   case ISD::TRUNCATE:
4780     assert(VT.isInteger() && Operand.getValueType().isInteger() &&
4781            "Invalid TRUNCATE!");
4782     assert(VT.isVector() == Operand.getValueType().isVector() &&
4783            "TRUNCATE result type type should be vector iff the operand "
4784            "type is vector!");
4785     if (Operand.getValueType() == VT) return Operand;   // noop truncate
4786     assert((!VT.isVector() ||
4787             VT.getVectorElementCount() ==
4788                 Operand.getValueType().getVectorElementCount()) &&
4789            "Vector element count mismatch!");
4790     assert(Operand.getValueType().bitsGT(VT) &&
4791            "Invalid truncate node, src < dst!");
4792     if (OpOpcode == ISD::TRUNCATE)
4793       return getNode(ISD::TRUNCATE, DL, VT, Operand.getOperand(0));
4794     if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
4795         OpOpcode == ISD::ANY_EXTEND) {
4796       // If the source is smaller than the dest, we still need an extend.
4797       if (Operand.getOperand(0).getValueType().getScalarType()
4798             .bitsLT(VT.getScalarType()))
4799         return getNode(OpOpcode, DL, VT, Operand.getOperand(0));
4800       if (Operand.getOperand(0).getValueType().bitsGT(VT))
4801         return getNode(ISD::TRUNCATE, DL, VT, Operand.getOperand(0));
4802       return Operand.getOperand(0);
4803     }
4804     if (OpOpcode == ISD::UNDEF)
4805       return getUNDEF(VT);
4806     break;
4807   case ISD::ANY_EXTEND_VECTOR_INREG:
4808   case ISD::ZERO_EXTEND_VECTOR_INREG:
4809   case ISD::SIGN_EXTEND_VECTOR_INREG:
4810     assert(VT.isVector() && "This DAG node is restricted to vector types.");
4811     assert(Operand.getValueType().bitsLE(VT) &&
4812            "The input must be the same size or smaller than the result.");
4813     assert(VT.getVectorNumElements() <
4814              Operand.getValueType().getVectorNumElements() &&
4815            "The destination vector type must have fewer lanes than the input.");
4816     break;
4817   case ISD::ABS:
4818     assert(VT.isInteger() && VT == Operand.getValueType() &&
4819            "Invalid ABS!");
4820     if (OpOpcode == ISD::UNDEF)
4821       return getUNDEF(VT);
4822     break;
4823   case ISD::BSWAP:
4824     assert(VT.isInteger() && VT == Operand.getValueType() &&
4825            "Invalid BSWAP!");
4826     assert((VT.getScalarSizeInBits() % 16 == 0) &&
4827            "BSWAP types must be a multiple of 16 bits!");
4828     if (OpOpcode == ISD::UNDEF)
4829       return getUNDEF(VT);
4830     break;
4831   case ISD::BITREVERSE:
4832     assert(VT.isInteger() && VT == Operand.getValueType() &&
4833            "Invalid BITREVERSE!");
4834     if (OpOpcode == ISD::UNDEF)
4835       return getUNDEF(VT);
4836     break;
4837   case ISD::BITCAST:
4838     // Basic sanity checking.
4839     assert(VT.getSizeInBits() == Operand.getValueSizeInBits() &&
4840            "Cannot BITCAST between types of different sizes!");
4841     if (VT == Operand.getValueType()) return Operand;  // noop conversion.
4842     if (OpOpcode == ISD::BITCAST)  // bitconv(bitconv(x)) -> bitconv(x)
4843       return getNode(ISD::BITCAST, DL, VT, Operand.getOperand(0));
4844     if (OpOpcode == ISD::UNDEF)
4845       return getUNDEF(VT);
4846     break;
4847   case ISD::SCALAR_TO_VECTOR:
4848     assert(VT.isVector() && !Operand.getValueType().isVector() &&
4849            (VT.getVectorElementType() == Operand.getValueType() ||
4850             (VT.getVectorElementType().isInteger() &&
4851              Operand.getValueType().isInteger() &&
4852              VT.getVectorElementType().bitsLE(Operand.getValueType()))) &&
4853            "Illegal SCALAR_TO_VECTOR node!");
4854     if (OpOpcode == ISD::UNDEF)
4855       return getUNDEF(VT);
4856     // scalar_to_vector(extract_vector_elt V, 0) -> V, top bits are undefined.
4857     if (OpOpcode == ISD::EXTRACT_VECTOR_ELT &&
4858         isa<ConstantSDNode>(Operand.getOperand(1)) &&
4859         Operand.getConstantOperandVal(1) == 0 &&
4860         Operand.getOperand(0).getValueType() == VT)
4861       return Operand.getOperand(0);
4862     break;
4863   case ISD::FNEG:
4864     // Negation of an unknown bag of bits is still completely undefined.
4865     if (OpOpcode == ISD::UNDEF)
4866       return getUNDEF(VT);
4867 
4868     if (OpOpcode == ISD::FNEG)  // --X -> X
4869       return Operand.getOperand(0);
4870     break;
4871   case ISD::FABS:
4872     if (OpOpcode == ISD::FNEG)  // abs(-X) -> abs(X)
4873       return getNode(ISD::FABS, DL, VT, Operand.getOperand(0));
4874     break;
4875   case ISD::VSCALE:
4876     assert(VT == Operand.getValueType() && "Unexpected VT!");
4877     break;
4878   case ISD::CTPOP:
4879     if (Operand.getValueType().getScalarType() == MVT::i1)
4880       return Operand;
4881     break;
4882   case ISD::CTLZ:
4883   case ISD::CTTZ:
4884     if (Operand.getValueType().getScalarType() == MVT::i1)
4885       return getNOT(DL, Operand, Operand.getValueType());
4886     break;
4887   case ISD::VECREDUCE_SMIN:
4888   case ISD::VECREDUCE_UMAX:
4889     if (Operand.getValueType().getScalarType() == MVT::i1)
4890       return getNode(ISD::VECREDUCE_OR, DL, VT, Operand);
4891     break;
4892   case ISD::VECREDUCE_SMAX:
4893   case ISD::VECREDUCE_UMIN:
4894     if (Operand.getValueType().getScalarType() == MVT::i1)
4895       return getNode(ISD::VECREDUCE_AND, DL, VT, Operand);
4896     break;
4897   }
4898 
4899   SDNode *N;
4900   SDVTList VTs = getVTList(VT);
4901   SDValue Ops[] = {Operand};
4902   if (VT != MVT::Glue) { // Don't CSE flag producing nodes
4903     FoldingSetNodeID ID;
4904     AddNodeIDNode(ID, Opcode, VTs, Ops);
4905     void *IP = nullptr;
4906     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
4907       E->intersectFlagsWith(Flags);
4908       return SDValue(E, 0);
4909     }
4910 
4911     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
4912     N->setFlags(Flags);
4913     createOperands(N, Ops);
4914     CSEMap.InsertNode(N, IP);
4915   } else {
4916     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
4917     createOperands(N, Ops);
4918   }
4919 
4920   InsertNode(N);
4921   SDValue V = SDValue(N, 0);
4922   NewSDValueDbgMsg(V, "Creating new node: ", this);
4923   return V;
4924 }
4925 
4926 static llvm::Optional<APInt> FoldValue(unsigned Opcode, const APInt &C1,
4927                                        const APInt &C2) {
4928   switch (Opcode) {
4929   case ISD::ADD:  return C1 + C2;
4930   case ISD::SUB:  return C1 - C2;
4931   case ISD::MUL:  return C1 * C2;
4932   case ISD::AND:  return C1 & C2;
4933   case ISD::OR:   return C1 | C2;
4934   case ISD::XOR:  return C1 ^ C2;
4935   case ISD::SHL:  return C1 << C2;
4936   case ISD::SRL:  return C1.lshr(C2);
4937   case ISD::SRA:  return C1.ashr(C2);
4938   case ISD::ROTL: return C1.rotl(C2);
4939   case ISD::ROTR: return C1.rotr(C2);
4940   case ISD::SMIN: return C1.sle(C2) ? C1 : C2;
4941   case ISD::SMAX: return C1.sge(C2) ? C1 : C2;
4942   case ISD::UMIN: return C1.ule(C2) ? C1 : C2;
4943   case ISD::UMAX: return C1.uge(C2) ? C1 : C2;
4944   case ISD::SADDSAT: return C1.sadd_sat(C2);
4945   case ISD::UADDSAT: return C1.uadd_sat(C2);
4946   case ISD::SSUBSAT: return C1.ssub_sat(C2);
4947   case ISD::USUBSAT: return C1.usub_sat(C2);
4948   case ISD::UDIV:
4949     if (!C2.getBoolValue())
4950       break;
4951     return C1.udiv(C2);
4952   case ISD::UREM:
4953     if (!C2.getBoolValue())
4954       break;
4955     return C1.urem(C2);
4956   case ISD::SDIV:
4957     if (!C2.getBoolValue())
4958       break;
4959     return C1.sdiv(C2);
4960   case ISD::SREM:
4961     if (!C2.getBoolValue())
4962       break;
4963     return C1.srem(C2);
4964   }
4965   return llvm::None;
4966 }
4967 
4968 SDValue SelectionDAG::FoldSymbolOffset(unsigned Opcode, EVT VT,
4969                                        const GlobalAddressSDNode *GA,
4970                                        const SDNode *N2) {
4971   if (GA->getOpcode() != ISD::GlobalAddress)
4972     return SDValue();
4973   if (!TLI->isOffsetFoldingLegal(GA))
4974     return SDValue();
4975   auto *C2 = dyn_cast<ConstantSDNode>(N2);
4976   if (!C2)
4977     return SDValue();
4978   int64_t Offset = C2->getSExtValue();
4979   switch (Opcode) {
4980   case ISD::ADD: break;
4981   case ISD::SUB: Offset = -uint64_t(Offset); break;
4982   default: return SDValue();
4983   }
4984   return getGlobalAddress(GA->getGlobal(), SDLoc(C2), VT,
4985                           GA->getOffset() + uint64_t(Offset));
4986 }
4987 
4988 bool SelectionDAG::isUndef(unsigned Opcode, ArrayRef<SDValue> Ops) {
4989   switch (Opcode) {
4990   case ISD::SDIV:
4991   case ISD::UDIV:
4992   case ISD::SREM:
4993   case ISD::UREM: {
4994     // If a divisor is zero/undef or any element of a divisor vector is
4995     // zero/undef, the whole op is undef.
4996     assert(Ops.size() == 2 && "Div/rem should have 2 operands");
4997     SDValue Divisor = Ops[1];
4998     if (Divisor.isUndef() || isNullConstant(Divisor))
4999       return true;
5000 
5001     return ISD::isBuildVectorOfConstantSDNodes(Divisor.getNode()) &&
5002            llvm::any_of(Divisor->op_values(),
5003                         [](SDValue V) { return V.isUndef() ||
5004                                         isNullConstant(V); });
5005     // TODO: Handle signed overflow.
5006   }
5007   // TODO: Handle oversized shifts.
5008   default:
5009     return false;
5010   }
5011 }
5012 
5013 SDValue SelectionDAG::FoldConstantArithmetic(unsigned Opcode, const SDLoc &DL,
5014                                              EVT VT, ArrayRef<SDValue> Ops) {
5015   // If the opcode is a target-specific ISD node, there's nothing we can
5016   // do here and the operand rules may not line up with the below, so
5017   // bail early.
5018   if (Opcode >= ISD::BUILTIN_OP_END)
5019     return SDValue();
5020 
5021   // For now, the array Ops should only contain two values.
5022   // This enforcement will be removed once this function is merged with
5023   // FoldConstantVectorArithmetic
5024   if (Ops.size() != 2)
5025     return SDValue();
5026 
5027   if (isUndef(Opcode, Ops))
5028     return getUNDEF(VT);
5029 
5030   SDNode *N1 = Ops[0].getNode();
5031   SDNode *N2 = Ops[1].getNode();
5032 
5033   // Handle the case of two scalars.
5034   if (auto *C1 = dyn_cast<ConstantSDNode>(N1)) {
5035     if (auto *C2 = dyn_cast<ConstantSDNode>(N2)) {
5036       if (C1->isOpaque() || C2->isOpaque())
5037         return SDValue();
5038 
5039       Optional<APInt> FoldAttempt =
5040           FoldValue(Opcode, C1->getAPIntValue(), C2->getAPIntValue());
5041       if (!FoldAttempt)
5042         return SDValue();
5043 
5044       SDValue Folded = getConstant(FoldAttempt.getValue(), DL, VT);
5045       assert((!Folded || !VT.isVector()) &&
5046              "Can't fold vectors ops with scalar operands");
5047       return Folded;
5048     }
5049   }
5050 
5051   // fold (add Sym, c) -> Sym+c
5052   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N1))
5053     return FoldSymbolOffset(Opcode, VT, GA, N2);
5054   if (TLI->isCommutativeBinOp(Opcode))
5055     if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N2))
5056       return FoldSymbolOffset(Opcode, VT, GA, N1);
5057 
5058   // TODO: All the folds below are performed lane-by-lane and assume a fixed
5059   // vector width, however we should be able to do constant folds involving
5060   // splat vector nodes too.
5061   if (VT.isScalableVector())
5062     return SDValue();
5063 
5064   // For fixed width vectors, extract each constant element and fold them
5065   // individually. Either input may be an undef value.
5066   auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
5067   if (!BV1 && !N1->isUndef())
5068     return SDValue();
5069   auto *BV2 = dyn_cast<BuildVectorSDNode>(N2);
5070   if (!BV2 && !N2->isUndef())
5071     return SDValue();
5072   // If both operands are undef, that's handled the same way as scalars.
5073   if (!BV1 && !BV2)
5074     return SDValue();
5075 
5076   assert((!BV1 || !BV2 || BV1->getNumOperands() == BV2->getNumOperands()) &&
5077          "Vector binop with different number of elements in operands?");
5078 
5079   EVT SVT = VT.getScalarType();
5080   EVT LegalSVT = SVT;
5081   if (NewNodesMustHaveLegalTypes && LegalSVT.isInteger()) {
5082     LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT);
5083     if (LegalSVT.bitsLT(SVT))
5084       return SDValue();
5085   }
5086   SmallVector<SDValue, 4> Outputs;
5087   unsigned NumOps = BV1 ? BV1->getNumOperands() : BV2->getNumOperands();
5088   for (unsigned I = 0; I != NumOps; ++I) {
5089     SDValue V1 = BV1 ? BV1->getOperand(I) : getUNDEF(SVT);
5090     SDValue V2 = BV2 ? BV2->getOperand(I) : getUNDEF(SVT);
5091     if (SVT.isInteger()) {
5092       if (V1->getValueType(0).bitsGT(SVT))
5093         V1 = getNode(ISD::TRUNCATE, DL, SVT, V1);
5094       if (V2->getValueType(0).bitsGT(SVT))
5095         V2 = getNode(ISD::TRUNCATE, DL, SVT, V2);
5096     }
5097 
5098     if (V1->getValueType(0) != SVT || V2->getValueType(0) != SVT)
5099       return SDValue();
5100 
5101     // Fold one vector element.
5102     SDValue ScalarResult = getNode(Opcode, DL, SVT, V1, V2);
5103     if (LegalSVT != SVT)
5104       ScalarResult = getNode(ISD::SIGN_EXTEND, DL, LegalSVT, ScalarResult);
5105 
5106     // Scalar folding only succeeded if the result is a constant or UNDEF.
5107     if (!ScalarResult.isUndef() && ScalarResult.getOpcode() != ISD::Constant &&
5108         ScalarResult.getOpcode() != ISD::ConstantFP)
5109       return SDValue();
5110     Outputs.push_back(ScalarResult);
5111   }
5112 
5113   assert(VT.getVectorNumElements() == Outputs.size() &&
5114          "Vector size mismatch!");
5115 
5116   // We may have a vector type but a scalar result. Create a splat.
5117   Outputs.resize(VT.getVectorNumElements(), Outputs.back());
5118 
5119   // Build a big vector out of the scalar elements we generated.
5120   return getBuildVector(VT, SDLoc(), Outputs);
5121 }
5122 
5123 // TODO: Merge with FoldConstantArithmetic
5124 SDValue SelectionDAG::FoldConstantVectorArithmetic(unsigned Opcode,
5125                                                    const SDLoc &DL, EVT VT,
5126                                                    ArrayRef<SDValue> Ops,
5127                                                    const SDNodeFlags Flags) {
5128   // If the opcode is a target-specific ISD node, there's nothing we can
5129   // do here and the operand rules may not line up with the below, so
5130   // bail early.
5131   if (Opcode >= ISD::BUILTIN_OP_END)
5132     return SDValue();
5133 
5134   if (isUndef(Opcode, Ops))
5135     return getUNDEF(VT);
5136 
5137   // We can only fold vectors - maybe merge with FoldConstantArithmetic someday?
5138   if (!VT.isVector())
5139     return SDValue();
5140 
5141   // TODO: All the folds below are performed lane-by-lane and assume a fixed
5142   // vector width, however we should be able to do constant folds involving
5143   // splat vector nodes too.
5144   if (VT.isScalableVector())
5145     return SDValue();
5146 
5147   // From this point onwards all vectors are assumed to be fixed width.
5148   unsigned NumElts = VT.getVectorNumElements();
5149 
5150   auto IsScalarOrSameVectorSize = [&](const SDValue &Op) {
5151     return !Op.getValueType().isVector() ||
5152            Op.getValueType().getVectorNumElements() == NumElts;
5153   };
5154 
5155   auto IsConstantBuildVectorOrUndef = [&](const SDValue &Op) {
5156     BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op);
5157     return (Op.isUndef()) || (Op.getOpcode() == ISD::CONDCODE) ||
5158            (BV && BV->isConstant());
5159   };
5160 
5161   // All operands must be vector types with the same number of elements as
5162   // the result type and must be either UNDEF or a build vector of constant
5163   // or UNDEF scalars.
5164   if (!llvm::all_of(Ops, IsConstantBuildVectorOrUndef) ||
5165       !llvm::all_of(Ops, IsScalarOrSameVectorSize))
5166     return SDValue();
5167 
5168   // If we are comparing vectors, then the result needs to be a i1 boolean
5169   // that is then sign-extended back to the legal result type.
5170   EVT SVT = (Opcode == ISD::SETCC ? MVT::i1 : VT.getScalarType());
5171 
5172   // Find legal integer scalar type for constant promotion and
5173   // ensure that its scalar size is at least as large as source.
5174   EVT LegalSVT = VT.getScalarType();
5175   if (NewNodesMustHaveLegalTypes && LegalSVT.isInteger()) {
5176     LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT);
5177     if (LegalSVT.bitsLT(VT.getScalarType()))
5178       return SDValue();
5179   }
5180 
5181   // Constant fold each scalar lane separately.
5182   SmallVector<SDValue, 4> ScalarResults;
5183   for (unsigned i = 0; i != NumElts; i++) {
5184     SmallVector<SDValue, 4> ScalarOps;
5185     for (SDValue Op : Ops) {
5186       EVT InSVT = Op.getValueType().getScalarType();
5187       BuildVectorSDNode *InBV = dyn_cast<BuildVectorSDNode>(Op);
5188       if (!InBV) {
5189         // We've checked that this is UNDEF or a constant of some kind.
5190         if (Op.isUndef())
5191           ScalarOps.push_back(getUNDEF(InSVT));
5192         else
5193           ScalarOps.push_back(Op);
5194         continue;
5195       }
5196 
5197       SDValue ScalarOp = InBV->getOperand(i);
5198       EVT ScalarVT = ScalarOp.getValueType();
5199 
5200       // Build vector (integer) scalar operands may need implicit
5201       // truncation - do this before constant folding.
5202       if (ScalarVT.isInteger() && ScalarVT.bitsGT(InSVT))
5203         ScalarOp = getNode(ISD::TRUNCATE, DL, InSVT, ScalarOp);
5204 
5205       ScalarOps.push_back(ScalarOp);
5206     }
5207 
5208     // Constant fold the scalar operands.
5209     SDValue ScalarResult = getNode(Opcode, DL, SVT, ScalarOps, Flags);
5210 
5211     // Legalize the (integer) scalar constant if necessary.
5212     if (LegalSVT != SVT)
5213       ScalarResult = getNode(ISD::SIGN_EXTEND, DL, LegalSVT, ScalarResult);
5214 
5215     // Scalar folding only succeeded if the result is a constant or UNDEF.
5216     if (!ScalarResult.isUndef() && ScalarResult.getOpcode() != ISD::Constant &&
5217         ScalarResult.getOpcode() != ISD::ConstantFP)
5218       return SDValue();
5219     ScalarResults.push_back(ScalarResult);
5220   }
5221 
5222   SDValue V = getBuildVector(VT, DL, ScalarResults);
5223   NewSDValueDbgMsg(V, "New node fold constant vector: ", this);
5224   return V;
5225 }
5226 
5227 SDValue SelectionDAG::foldConstantFPMath(unsigned Opcode, const SDLoc &DL,
5228                                          EVT VT, SDValue N1, SDValue N2) {
5229   // TODO: We don't do any constant folding for strict FP opcodes here, but we
5230   //       should. That will require dealing with a potentially non-default
5231   //       rounding mode, checking the "opStatus" return value from the APFloat
5232   //       math calculations, and possibly other variations.
5233   auto *N1CFP = dyn_cast<ConstantFPSDNode>(N1.getNode());
5234   auto *N2CFP = dyn_cast<ConstantFPSDNode>(N2.getNode());
5235   if (N1CFP && N2CFP) {
5236     APFloat C1 = N1CFP->getValueAPF(), C2 = N2CFP->getValueAPF();
5237     switch (Opcode) {
5238     case ISD::FADD:
5239       C1.add(C2, APFloat::rmNearestTiesToEven);
5240       return getConstantFP(C1, DL, VT);
5241     case ISD::FSUB:
5242       C1.subtract(C2, APFloat::rmNearestTiesToEven);
5243       return getConstantFP(C1, DL, VT);
5244     case ISD::FMUL:
5245       C1.multiply(C2, APFloat::rmNearestTiesToEven);
5246       return getConstantFP(C1, DL, VT);
5247     case ISD::FDIV:
5248       C1.divide(C2, APFloat::rmNearestTiesToEven);
5249       return getConstantFP(C1, DL, VT);
5250     case ISD::FREM:
5251       C1.mod(C2);
5252       return getConstantFP(C1, DL, VT);
5253     case ISD::FCOPYSIGN:
5254       C1.copySign(C2);
5255       return getConstantFP(C1, DL, VT);
5256     default: break;
5257     }
5258   }
5259   if (N1CFP && Opcode == ISD::FP_ROUND) {
5260     APFloat C1 = N1CFP->getValueAPF();    // make copy
5261     bool Unused;
5262     // This can return overflow, underflow, or inexact; we don't care.
5263     // FIXME need to be more flexible about rounding mode.
5264     (void) C1.convert(EVTToAPFloatSemantics(VT), APFloat::rmNearestTiesToEven,
5265                       &Unused);
5266     return getConstantFP(C1, DL, VT);
5267   }
5268 
5269   switch (Opcode) {
5270   case ISD::FSUB:
5271     // -0.0 - undef --> undef (consistent with "fneg undef")
5272     if (N1CFP && N1CFP->getValueAPF().isNegZero() && N2.isUndef())
5273       return getUNDEF(VT);
5274     LLVM_FALLTHROUGH;
5275 
5276   case ISD::FADD:
5277   case ISD::FMUL:
5278   case ISD::FDIV:
5279   case ISD::FREM:
5280     // If both operands are undef, the result is undef. If 1 operand is undef,
5281     // the result is NaN. This should match the behavior of the IR optimizer.
5282     if (N1.isUndef() && N2.isUndef())
5283       return getUNDEF(VT);
5284     if (N1.isUndef() || N2.isUndef())
5285       return getConstantFP(APFloat::getNaN(EVTToAPFloatSemantics(VT)), DL, VT);
5286   }
5287   return SDValue();
5288 }
5289 
5290 SDValue SelectionDAG::getAssertAlign(const SDLoc &DL, SDValue Val, Align A) {
5291   assert(Val.getValueType().isInteger() && "Invalid AssertAlign!");
5292 
5293   // There's no need to assert on a byte-aligned pointer. All pointers are at
5294   // least byte aligned.
5295   if (A == Align(1))
5296     return Val;
5297 
5298   FoldingSetNodeID ID;
5299   AddNodeIDNode(ID, ISD::AssertAlign, getVTList(Val.getValueType()), {Val});
5300   ID.AddInteger(A.value());
5301 
5302   void *IP = nullptr;
5303   if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
5304     return SDValue(E, 0);
5305 
5306   auto *N = newSDNode<AssertAlignSDNode>(DL.getIROrder(), DL.getDebugLoc(),
5307                                          Val.getValueType(), A);
5308   createOperands(N, {Val});
5309 
5310   CSEMap.InsertNode(N, IP);
5311   InsertNode(N);
5312 
5313   SDValue V(N, 0);
5314   NewSDValueDbgMsg(V, "Creating new node: ", this);
5315   return V;
5316 }
5317 
5318 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
5319                               SDValue N1, SDValue N2) {
5320   SDNodeFlags Flags;
5321   if (Inserter)
5322     Flags = Inserter->getFlags();
5323   return getNode(Opcode, DL, VT, N1, N2, Flags);
5324 }
5325 
5326 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
5327                               SDValue N1, SDValue N2, const SDNodeFlags Flags) {
5328   assert(N1.getOpcode() != ISD::DELETED_NODE &&
5329          N2.getOpcode() != ISD::DELETED_NODE &&
5330          "Operand is DELETED_NODE!");
5331   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
5332   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
5333   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
5334   ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2);
5335 
5336   // Canonicalize constant to RHS if commutative.
5337   if (TLI->isCommutativeBinOp(Opcode)) {
5338     if (N1C && !N2C) {
5339       std::swap(N1C, N2C);
5340       std::swap(N1, N2);
5341     } else if (N1CFP && !N2CFP) {
5342       std::swap(N1CFP, N2CFP);
5343       std::swap(N1, N2);
5344     }
5345   }
5346 
5347   switch (Opcode) {
5348   default: break;
5349   case ISD::TokenFactor:
5350     assert(VT == MVT::Other && N1.getValueType() == MVT::Other &&
5351            N2.getValueType() == MVT::Other && "Invalid token factor!");
5352     // Fold trivial token factors.
5353     if (N1.getOpcode() == ISD::EntryToken) return N2;
5354     if (N2.getOpcode() == ISD::EntryToken) return N1;
5355     if (N1 == N2) return N1;
5356     break;
5357   case ISD::BUILD_VECTOR: {
5358     // Attempt to simplify BUILD_VECTOR.
5359     SDValue Ops[] = {N1, N2};
5360     if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
5361       return V;
5362     break;
5363   }
5364   case ISD::CONCAT_VECTORS: {
5365     SDValue Ops[] = {N1, N2};
5366     if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this))
5367       return V;
5368     break;
5369   }
5370   case ISD::AND:
5371     assert(VT.isInteger() && "This operator does not apply to FP types!");
5372     assert(N1.getValueType() == N2.getValueType() &&
5373            N1.getValueType() == VT && "Binary operator types must match!");
5374     // (X & 0) -> 0.  This commonly occurs when legalizing i64 values, so it's
5375     // worth handling here.
5376     if (N2C && N2C->isNullValue())
5377       return N2;
5378     if (N2C && N2C->isAllOnesValue())  // X & -1 -> X
5379       return N1;
5380     break;
5381   case ISD::OR:
5382   case ISD::XOR:
5383   case ISD::ADD:
5384   case ISD::SUB:
5385     assert(VT.isInteger() && "This operator does not apply to FP types!");
5386     assert(N1.getValueType() == N2.getValueType() &&
5387            N1.getValueType() == VT && "Binary operator types must match!");
5388     // (X ^|+- 0) -> X.  This commonly occurs when legalizing i64 values, so
5389     // it's worth handling here.
5390     if (N2C && N2C->isNullValue())
5391       return N1;
5392     if ((Opcode == ISD::ADD || Opcode == ISD::SUB) && VT.isVector() &&
5393         VT.getVectorElementType() == MVT::i1)
5394       return getNode(ISD::XOR, DL, VT, N1, N2);
5395     break;
5396   case ISD::MUL:
5397     assert(VT.isInteger() && "This operator does not apply to FP types!");
5398     assert(N1.getValueType() == N2.getValueType() &&
5399            N1.getValueType() == VT && "Binary operator types must match!");
5400     if (VT.isVector() && VT.getVectorElementType() == MVT::i1)
5401       return getNode(ISD::AND, DL, VT, N1, N2);
5402     if (N2C && (N1.getOpcode() == ISD::VSCALE) && Flags.hasNoSignedWrap()) {
5403       const APInt &MulImm = N1->getConstantOperandAPInt(0);
5404       const APInt &N2CImm = N2C->getAPIntValue();
5405       return getVScale(DL, VT, MulImm * N2CImm);
5406     }
5407     break;
5408   case ISD::UDIV:
5409   case ISD::UREM:
5410   case ISD::MULHU:
5411   case ISD::MULHS:
5412   case ISD::SDIV:
5413   case ISD::SREM:
5414   case ISD::SADDSAT:
5415   case ISD::SSUBSAT:
5416   case ISD::UADDSAT:
5417   case ISD::USUBSAT:
5418     assert(VT.isInteger() && "This operator does not apply to FP types!");
5419     assert(N1.getValueType() == N2.getValueType() &&
5420            N1.getValueType() == VT && "Binary operator types must match!");
5421     if (VT.isVector() && VT.getVectorElementType() == MVT::i1) {
5422       // fold (add_sat x, y) -> (or x, y) for bool types.
5423       if (Opcode == ISD::SADDSAT || Opcode == ISD::UADDSAT)
5424         return getNode(ISD::OR, DL, VT, N1, N2);
5425       // fold (sub_sat x, y) -> (and x, ~y) for bool types.
5426       if (Opcode == ISD::SSUBSAT || Opcode == ISD::USUBSAT)
5427         return getNode(ISD::AND, DL, VT, N1, getNOT(DL, N2, VT));
5428     }
5429     break;
5430   case ISD::SMIN:
5431   case ISD::UMAX:
5432     assert(VT.isInteger() && "This operator does not apply to FP types!");
5433     assert(N1.getValueType() == N2.getValueType() &&
5434            N1.getValueType() == VT && "Binary operator types must match!");
5435     if (VT.isVector() && VT.getVectorElementType() == MVT::i1)
5436       return getNode(ISD::OR, DL, VT, N1, N2);
5437     break;
5438   case ISD::SMAX:
5439   case ISD::UMIN:
5440     assert(VT.isInteger() && "This operator does not apply to FP types!");
5441     assert(N1.getValueType() == N2.getValueType() &&
5442            N1.getValueType() == VT && "Binary operator types must match!");
5443     if (VT.isVector() && VT.getVectorElementType() == MVT::i1)
5444       return getNode(ISD::AND, DL, VT, N1, N2);
5445     break;
5446   case ISD::FADD:
5447   case ISD::FSUB:
5448   case ISD::FMUL:
5449   case ISD::FDIV:
5450   case ISD::FREM:
5451     assert(VT.isFloatingPoint() && "This operator only applies to FP types!");
5452     assert(N1.getValueType() == N2.getValueType() &&
5453            N1.getValueType() == VT && "Binary operator types must match!");
5454     if (SDValue V = simplifyFPBinop(Opcode, N1, N2, Flags))
5455       return V;
5456     break;
5457   case ISD::FCOPYSIGN:   // N1 and result must match.  N1/N2 need not match.
5458     assert(N1.getValueType() == VT &&
5459            N1.getValueType().isFloatingPoint() &&
5460            N2.getValueType().isFloatingPoint() &&
5461            "Invalid FCOPYSIGN!");
5462     break;
5463   case ISD::SHL:
5464     if (N2C && (N1.getOpcode() == ISD::VSCALE) && Flags.hasNoSignedWrap()) {
5465       const APInt &MulImm = N1->getConstantOperandAPInt(0);
5466       const APInt &ShiftImm = N2C->getAPIntValue();
5467       return getVScale(DL, VT, MulImm << ShiftImm);
5468     }
5469     LLVM_FALLTHROUGH;
5470   case ISD::SRA:
5471   case ISD::SRL:
5472     if (SDValue V = simplifyShift(N1, N2))
5473       return V;
5474     LLVM_FALLTHROUGH;
5475   case ISD::ROTL:
5476   case ISD::ROTR:
5477     assert(VT == N1.getValueType() &&
5478            "Shift operators return type must be the same as their first arg");
5479     assert(VT.isInteger() && N2.getValueType().isInteger() &&
5480            "Shifts only work on integers");
5481     assert((!VT.isVector() || VT == N2.getValueType()) &&
5482            "Vector shift amounts must be in the same as their first arg");
5483     // Verify that the shift amount VT is big enough to hold valid shift
5484     // amounts.  This catches things like trying to shift an i1024 value by an
5485     // i8, which is easy to fall into in generic code that uses
5486     // TLI.getShiftAmount().
5487     assert(N2.getValueType().getScalarSizeInBits() >=
5488                Log2_32_Ceil(VT.getScalarSizeInBits()) &&
5489            "Invalid use of small shift amount with oversized value!");
5490 
5491     // Always fold shifts of i1 values so the code generator doesn't need to
5492     // handle them.  Since we know the size of the shift has to be less than the
5493     // size of the value, the shift/rotate count is guaranteed to be zero.
5494     if (VT == MVT::i1)
5495       return N1;
5496     if (N2C && N2C->isNullValue())
5497       return N1;
5498     break;
5499   case ISD::FP_ROUND:
5500     assert(VT.isFloatingPoint() &&
5501            N1.getValueType().isFloatingPoint() &&
5502            VT.bitsLE(N1.getValueType()) &&
5503            N2C && (N2C->getZExtValue() == 0 || N2C->getZExtValue() == 1) &&
5504            "Invalid FP_ROUND!");
5505     if (N1.getValueType() == VT) return N1;  // noop conversion.
5506     break;
5507   case ISD::AssertSext:
5508   case ISD::AssertZext: {
5509     EVT EVT = cast<VTSDNode>(N2)->getVT();
5510     assert(VT == N1.getValueType() && "Not an inreg extend!");
5511     assert(VT.isInteger() && EVT.isInteger() &&
5512            "Cannot *_EXTEND_INREG FP types");
5513     assert(!EVT.isVector() &&
5514            "AssertSExt/AssertZExt type should be the vector element type "
5515            "rather than the vector type!");
5516     assert(EVT.bitsLE(VT.getScalarType()) && "Not extending!");
5517     if (VT.getScalarType() == EVT) return N1; // noop assertion.
5518     break;
5519   }
5520   case ISD::SIGN_EXTEND_INREG: {
5521     EVT EVT = cast<VTSDNode>(N2)->getVT();
5522     assert(VT == N1.getValueType() && "Not an inreg extend!");
5523     assert(VT.isInteger() && EVT.isInteger() &&
5524            "Cannot *_EXTEND_INREG FP types");
5525     assert(EVT.isVector() == VT.isVector() &&
5526            "SIGN_EXTEND_INREG type should be vector iff the operand "
5527            "type is vector!");
5528     assert((!EVT.isVector() ||
5529             EVT.getVectorElementCount() == VT.getVectorElementCount()) &&
5530            "Vector element counts must match in SIGN_EXTEND_INREG");
5531     assert(EVT.bitsLE(VT) && "Not extending!");
5532     if (EVT == VT) return N1;  // Not actually extending
5533 
5534     auto SignExtendInReg = [&](APInt Val, llvm::EVT ConstantVT) {
5535       unsigned FromBits = EVT.getScalarSizeInBits();
5536       Val <<= Val.getBitWidth() - FromBits;
5537       Val.ashrInPlace(Val.getBitWidth() - FromBits);
5538       return getConstant(Val, DL, ConstantVT);
5539     };
5540 
5541     if (N1C) {
5542       const APInt &Val = N1C->getAPIntValue();
5543       return SignExtendInReg(Val, VT);
5544     }
5545     if (ISD::isBuildVectorOfConstantSDNodes(N1.getNode())) {
5546       SmallVector<SDValue, 8> Ops;
5547       llvm::EVT OpVT = N1.getOperand(0).getValueType();
5548       for (int i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
5549         SDValue Op = N1.getOperand(i);
5550         if (Op.isUndef()) {
5551           Ops.push_back(getUNDEF(OpVT));
5552           continue;
5553         }
5554         ConstantSDNode *C = cast<ConstantSDNode>(Op);
5555         APInt Val = C->getAPIntValue();
5556         Ops.push_back(SignExtendInReg(Val, OpVT));
5557       }
5558       return getBuildVector(VT, DL, Ops);
5559     }
5560     break;
5561   }
5562   case ISD::EXTRACT_VECTOR_ELT:
5563     assert(VT.getSizeInBits() >= N1.getValueType().getScalarSizeInBits() &&
5564            "The result of EXTRACT_VECTOR_ELT must be at least as wide as the \
5565              element type of the vector.");
5566 
5567     // Extract from an undefined value or using an undefined index is undefined.
5568     if (N1.isUndef() || N2.isUndef())
5569       return getUNDEF(VT);
5570 
5571     // EXTRACT_VECTOR_ELT of out-of-bounds element is an UNDEF for fixed length
5572     // vectors. For scalable vectors we will provide appropriate support for
5573     // dealing with arbitrary indices.
5574     if (N2C && N1.getValueType().isFixedLengthVector() &&
5575         N2C->getAPIntValue().uge(N1.getValueType().getVectorNumElements()))
5576       return getUNDEF(VT);
5577 
5578     // EXTRACT_VECTOR_ELT of CONCAT_VECTORS is often formed while lowering is
5579     // expanding copies of large vectors from registers. This only works for
5580     // fixed length vectors, since we need to know the exact number of
5581     // elements.
5582     if (N2C && N1.getOperand(0).getValueType().isFixedLengthVector() &&
5583         N1.getOpcode() == ISD::CONCAT_VECTORS && N1.getNumOperands() > 0) {
5584       unsigned Factor =
5585         N1.getOperand(0).getValueType().getVectorNumElements();
5586       return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
5587                      N1.getOperand(N2C->getZExtValue() / Factor),
5588                      getVectorIdxConstant(N2C->getZExtValue() % Factor, DL));
5589     }
5590 
5591     // EXTRACT_VECTOR_ELT of BUILD_VECTOR or SPLAT_VECTOR is often formed while
5592     // lowering is expanding large vector constants.
5593     if (N2C && (N1.getOpcode() == ISD::BUILD_VECTOR ||
5594                 N1.getOpcode() == ISD::SPLAT_VECTOR)) {
5595       assert((N1.getOpcode() != ISD::BUILD_VECTOR ||
5596               N1.getValueType().isFixedLengthVector()) &&
5597              "BUILD_VECTOR used for scalable vectors");
5598       unsigned Index =
5599           N1.getOpcode() == ISD::BUILD_VECTOR ? N2C->getZExtValue() : 0;
5600       SDValue Elt = N1.getOperand(Index);
5601 
5602       if (VT != Elt.getValueType())
5603         // If the vector element type is not legal, the BUILD_VECTOR operands
5604         // are promoted and implicitly truncated, and the result implicitly
5605         // extended. Make that explicit here.
5606         Elt = getAnyExtOrTrunc(Elt, DL, VT);
5607 
5608       return Elt;
5609     }
5610 
5611     // EXTRACT_VECTOR_ELT of INSERT_VECTOR_ELT is often formed when vector
5612     // operations are lowered to scalars.
5613     if (N1.getOpcode() == ISD::INSERT_VECTOR_ELT) {
5614       // If the indices are the same, return the inserted element else
5615       // if the indices are known different, extract the element from
5616       // the original vector.
5617       SDValue N1Op2 = N1.getOperand(2);
5618       ConstantSDNode *N1Op2C = dyn_cast<ConstantSDNode>(N1Op2);
5619 
5620       if (N1Op2C && N2C) {
5621         if (N1Op2C->getZExtValue() == N2C->getZExtValue()) {
5622           if (VT == N1.getOperand(1).getValueType())
5623             return N1.getOperand(1);
5624           else
5625             return getSExtOrTrunc(N1.getOperand(1), DL, VT);
5626         }
5627 
5628         return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0), N2);
5629       }
5630     }
5631 
5632     // EXTRACT_VECTOR_ELT of v1iX EXTRACT_SUBVECTOR could be formed
5633     // when vector types are scalarized and v1iX is legal.
5634     // vextract (v1iX extract_subvector(vNiX, Idx)) -> vextract(vNiX,Idx).
5635     // Here we are completely ignoring the extract element index (N2),
5636     // which is fine for fixed width vectors, since any index other than 0
5637     // is undefined anyway. However, this cannot be ignored for scalable
5638     // vectors - in theory we could support this, but we don't want to do this
5639     // without a profitability check.
5640     if (N1.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
5641         N1.getValueType().isFixedLengthVector() &&
5642         N1.getValueType().getVectorNumElements() == 1) {
5643       return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0),
5644                      N1.getOperand(1));
5645     }
5646     break;
5647   case ISD::EXTRACT_ELEMENT:
5648     assert(N2C && (unsigned)N2C->getZExtValue() < 2 && "Bad EXTRACT_ELEMENT!");
5649     assert(!N1.getValueType().isVector() && !VT.isVector() &&
5650            (N1.getValueType().isInteger() == VT.isInteger()) &&
5651            N1.getValueType() != VT &&
5652            "Wrong types for EXTRACT_ELEMENT!");
5653 
5654     // EXTRACT_ELEMENT of BUILD_PAIR is often formed while legalize is expanding
5655     // 64-bit integers into 32-bit parts.  Instead of building the extract of
5656     // the BUILD_PAIR, only to have legalize rip it apart, just do it now.
5657     if (N1.getOpcode() == ISD::BUILD_PAIR)
5658       return N1.getOperand(N2C->getZExtValue());
5659 
5660     // EXTRACT_ELEMENT of a constant int is also very common.
5661     if (N1C) {
5662       unsigned ElementSize = VT.getSizeInBits();
5663       unsigned Shift = ElementSize * N2C->getZExtValue();
5664       const APInt &Val = N1C->getAPIntValue();
5665       return getConstant(Val.extractBits(ElementSize, Shift), DL, VT);
5666     }
5667     break;
5668   case ISD::EXTRACT_SUBVECTOR:
5669     EVT N1VT = N1.getValueType();
5670     assert(VT.isVector() && N1VT.isVector() &&
5671            "Extract subvector VTs must be vectors!");
5672     assert(VT.getVectorElementType() == N1VT.getVectorElementType() &&
5673            "Extract subvector VTs must have the same element type!");
5674     assert((VT.isFixedLengthVector() || N1VT.isScalableVector()) &&
5675            "Cannot extract a scalable vector from a fixed length vector!");
5676     assert((VT.isScalableVector() != N1VT.isScalableVector() ||
5677             VT.getVectorMinNumElements() <= N1VT.getVectorMinNumElements()) &&
5678            "Extract subvector must be from larger vector to smaller vector!");
5679     assert(N2C && "Extract subvector index must be a constant");
5680     assert((VT.isScalableVector() != N1VT.isScalableVector() ||
5681             (VT.getVectorMinNumElements() + N2C->getZExtValue()) <=
5682                 N1VT.getVectorMinNumElements()) &&
5683            "Extract subvector overflow!");
5684     assert(N2C->getAPIntValue().getBitWidth() ==
5685                TLI->getVectorIdxTy(getDataLayout()).getFixedSizeInBits() &&
5686            "Constant index for EXTRACT_SUBVECTOR has an invalid size");
5687 
5688     // Trivial extraction.
5689     if (VT == N1VT)
5690       return N1;
5691 
5692     // EXTRACT_SUBVECTOR of an UNDEF is an UNDEF.
5693     if (N1.isUndef())
5694       return getUNDEF(VT);
5695 
5696     // EXTRACT_SUBVECTOR of CONCAT_VECTOR can be simplified if the pieces of
5697     // the concat have the same type as the extract.
5698     if (N1.getOpcode() == ISD::CONCAT_VECTORS && N1.getNumOperands() > 0 &&
5699         VT == N1.getOperand(0).getValueType()) {
5700       unsigned Factor = VT.getVectorMinNumElements();
5701       return N1.getOperand(N2C->getZExtValue() / Factor);
5702     }
5703 
5704     // EXTRACT_SUBVECTOR of INSERT_SUBVECTOR is often created
5705     // during shuffle legalization.
5706     if (N1.getOpcode() == ISD::INSERT_SUBVECTOR && N2 == N1.getOperand(2) &&
5707         VT == N1.getOperand(1).getValueType())
5708       return N1.getOperand(1);
5709     break;
5710   }
5711 
5712   // Perform trivial constant folding.
5713   if (SDValue SV = FoldConstantArithmetic(Opcode, DL, VT, {N1, N2}))
5714     return SV;
5715 
5716   if (SDValue V = foldConstantFPMath(Opcode, DL, VT, N1, N2))
5717     return V;
5718 
5719   // Canonicalize an UNDEF to the RHS, even over a constant.
5720   if (N1.isUndef()) {
5721     if (TLI->isCommutativeBinOp(Opcode)) {
5722       std::swap(N1, N2);
5723     } else {
5724       switch (Opcode) {
5725       case ISD::SIGN_EXTEND_INREG:
5726       case ISD::SUB:
5727         return getUNDEF(VT);     // fold op(undef, arg2) -> undef
5728       case ISD::UDIV:
5729       case ISD::SDIV:
5730       case ISD::UREM:
5731       case ISD::SREM:
5732       case ISD::SSUBSAT:
5733       case ISD::USUBSAT:
5734         return getConstant(0, DL, VT);    // fold op(undef, arg2) -> 0
5735       }
5736     }
5737   }
5738 
5739   // Fold a bunch of operators when the RHS is undef.
5740   if (N2.isUndef()) {
5741     switch (Opcode) {
5742     case ISD::XOR:
5743       if (N1.isUndef())
5744         // Handle undef ^ undef -> 0 special case. This is a common
5745         // idiom (misuse).
5746         return getConstant(0, DL, VT);
5747       LLVM_FALLTHROUGH;
5748     case ISD::ADD:
5749     case ISD::SUB:
5750     case ISD::UDIV:
5751     case ISD::SDIV:
5752     case ISD::UREM:
5753     case ISD::SREM:
5754       return getUNDEF(VT);       // fold op(arg1, undef) -> undef
5755     case ISD::MUL:
5756     case ISD::AND:
5757     case ISD::SSUBSAT:
5758     case ISD::USUBSAT:
5759       return getConstant(0, DL, VT);  // fold op(arg1, undef) -> 0
5760     case ISD::OR:
5761     case ISD::SADDSAT:
5762     case ISD::UADDSAT:
5763       return getAllOnesConstant(DL, VT);
5764     }
5765   }
5766 
5767   // Memoize this node if possible.
5768   SDNode *N;
5769   SDVTList VTs = getVTList(VT);
5770   SDValue Ops[] = {N1, N2};
5771   if (VT != MVT::Glue) {
5772     FoldingSetNodeID ID;
5773     AddNodeIDNode(ID, Opcode, VTs, Ops);
5774     void *IP = nullptr;
5775     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
5776       E->intersectFlagsWith(Flags);
5777       return SDValue(E, 0);
5778     }
5779 
5780     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
5781     N->setFlags(Flags);
5782     createOperands(N, Ops);
5783     CSEMap.InsertNode(N, IP);
5784   } else {
5785     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
5786     createOperands(N, Ops);
5787   }
5788 
5789   InsertNode(N);
5790   SDValue V = SDValue(N, 0);
5791   NewSDValueDbgMsg(V, "Creating new node: ", this);
5792   return V;
5793 }
5794 
5795 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
5796                               SDValue N1, SDValue N2, SDValue N3) {
5797   SDNodeFlags Flags;
5798   if (Inserter)
5799     Flags = Inserter->getFlags();
5800   return getNode(Opcode, DL, VT, N1, N2, N3, Flags);
5801 }
5802 
5803 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
5804                               SDValue N1, SDValue N2, SDValue N3,
5805                               const SDNodeFlags Flags) {
5806   assert(N1.getOpcode() != ISD::DELETED_NODE &&
5807          N2.getOpcode() != ISD::DELETED_NODE &&
5808          N3.getOpcode() != ISD::DELETED_NODE &&
5809          "Operand is DELETED_NODE!");
5810   // Perform various simplifications.
5811   switch (Opcode) {
5812   case ISD::FMA: {
5813     assert(VT.isFloatingPoint() && "This operator only applies to FP types!");
5814     assert(N1.getValueType() == VT && N2.getValueType() == VT &&
5815            N3.getValueType() == VT && "FMA types must match!");
5816     ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
5817     ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2);
5818     ConstantFPSDNode *N3CFP = dyn_cast<ConstantFPSDNode>(N3);
5819     if (N1CFP && N2CFP && N3CFP) {
5820       APFloat  V1 = N1CFP->getValueAPF();
5821       const APFloat &V2 = N2CFP->getValueAPF();
5822       const APFloat &V3 = N3CFP->getValueAPF();
5823       V1.fusedMultiplyAdd(V2, V3, APFloat::rmNearestTiesToEven);
5824       return getConstantFP(V1, DL, VT);
5825     }
5826     break;
5827   }
5828   case ISD::BUILD_VECTOR: {
5829     // Attempt to simplify BUILD_VECTOR.
5830     SDValue Ops[] = {N1, N2, N3};
5831     if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
5832       return V;
5833     break;
5834   }
5835   case ISD::CONCAT_VECTORS: {
5836     SDValue Ops[] = {N1, N2, N3};
5837     if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this))
5838       return V;
5839     break;
5840   }
5841   case ISD::SETCC: {
5842     assert(VT.isInteger() && "SETCC result type must be an integer!");
5843     assert(N1.getValueType() == N2.getValueType() &&
5844            "SETCC operands must have the same type!");
5845     assert(VT.isVector() == N1.getValueType().isVector() &&
5846            "SETCC type should be vector iff the operand type is vector!");
5847     assert((!VT.isVector() || VT.getVectorElementCount() ==
5848                                   N1.getValueType().getVectorElementCount()) &&
5849            "SETCC vector element counts must match!");
5850     // Use FoldSetCC to simplify SETCC's.
5851     if (SDValue V = FoldSetCC(VT, N1, N2, cast<CondCodeSDNode>(N3)->get(), DL))
5852       return V;
5853     // Vector constant folding.
5854     SDValue Ops[] = {N1, N2, N3};
5855     if (SDValue V = FoldConstantVectorArithmetic(Opcode, DL, VT, Ops)) {
5856       NewSDValueDbgMsg(V, "New node vector constant folding: ", this);
5857       return V;
5858     }
5859     break;
5860   }
5861   case ISD::SELECT:
5862   case ISD::VSELECT:
5863     if (SDValue V = simplifySelect(N1, N2, N3))
5864       return V;
5865     break;
5866   case ISD::VECTOR_SHUFFLE:
5867     llvm_unreachable("should use getVectorShuffle constructor!");
5868   case ISD::INSERT_VECTOR_ELT: {
5869     ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3);
5870     // INSERT_VECTOR_ELT into out-of-bounds element is an UNDEF, except
5871     // for scalable vectors where we will generate appropriate code to
5872     // deal with out-of-bounds cases correctly.
5873     if (N3C && N1.getValueType().isFixedLengthVector() &&
5874         N3C->getZExtValue() >= N1.getValueType().getVectorNumElements())
5875       return getUNDEF(VT);
5876 
5877     // Undefined index can be assumed out-of-bounds, so that's UNDEF too.
5878     if (N3.isUndef())
5879       return getUNDEF(VT);
5880 
5881     // If the inserted element is an UNDEF, just use the input vector.
5882     if (N2.isUndef())
5883       return N1;
5884 
5885     break;
5886   }
5887   case ISD::INSERT_SUBVECTOR: {
5888     // Inserting undef into undef is still undef.
5889     if (N1.isUndef() && N2.isUndef())
5890       return getUNDEF(VT);
5891 
5892     EVT N2VT = N2.getValueType();
5893     assert(VT == N1.getValueType() &&
5894            "Dest and insert subvector source types must match!");
5895     assert(VT.isVector() && N2VT.isVector() &&
5896            "Insert subvector VTs must be vectors!");
5897     assert((VT.isScalableVector() || N2VT.isFixedLengthVector()) &&
5898            "Cannot insert a scalable vector into a fixed length vector!");
5899     assert((VT.isScalableVector() != N2VT.isScalableVector() ||
5900             VT.getVectorMinNumElements() >= N2VT.getVectorMinNumElements()) &&
5901            "Insert subvector must be from smaller vector to larger vector!");
5902     assert(isa<ConstantSDNode>(N3) &&
5903            "Insert subvector index must be constant");
5904     assert((VT.isScalableVector() != N2VT.isScalableVector() ||
5905             (N2VT.getVectorMinNumElements() +
5906              cast<ConstantSDNode>(N3)->getZExtValue()) <=
5907                 VT.getVectorMinNumElements()) &&
5908            "Insert subvector overflow!");
5909     assert(cast<ConstantSDNode>(N3)->getAPIntValue().getBitWidth() ==
5910                TLI->getVectorIdxTy(getDataLayout()).getFixedSizeInBits() &&
5911            "Constant index for INSERT_SUBVECTOR has an invalid size");
5912 
5913     // Trivial insertion.
5914     if (VT == N2VT)
5915       return N2;
5916 
5917     // If this is an insert of an extracted vector into an undef vector, we
5918     // can just use the input to the extract.
5919     if (N1.isUndef() && N2.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
5920         N2.getOperand(1) == N3 && N2.getOperand(0).getValueType() == VT)
5921       return N2.getOperand(0);
5922     break;
5923   }
5924   case ISD::BITCAST:
5925     // Fold bit_convert nodes from a type to themselves.
5926     if (N1.getValueType() == VT)
5927       return N1;
5928     break;
5929   }
5930 
5931   // Memoize node if it doesn't produce a flag.
5932   SDNode *N;
5933   SDVTList VTs = getVTList(VT);
5934   SDValue Ops[] = {N1, N2, N3};
5935   if (VT != MVT::Glue) {
5936     FoldingSetNodeID ID;
5937     AddNodeIDNode(ID, Opcode, VTs, Ops);
5938     void *IP = nullptr;
5939     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
5940       E->intersectFlagsWith(Flags);
5941       return SDValue(E, 0);
5942     }
5943 
5944     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
5945     N->setFlags(Flags);
5946     createOperands(N, Ops);
5947     CSEMap.InsertNode(N, IP);
5948   } else {
5949     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
5950     createOperands(N, Ops);
5951   }
5952 
5953   InsertNode(N);
5954   SDValue V = SDValue(N, 0);
5955   NewSDValueDbgMsg(V, "Creating new node: ", this);
5956   return V;
5957 }
5958 
5959 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
5960                               SDValue N1, SDValue N2, SDValue N3, SDValue N4) {
5961   SDValue Ops[] = { N1, N2, N3, N4 };
5962   return getNode(Opcode, DL, VT, Ops);
5963 }
5964 
5965 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
5966                               SDValue N1, SDValue N2, SDValue N3, SDValue N4,
5967                               SDValue N5) {
5968   SDValue Ops[] = { N1, N2, N3, N4, N5 };
5969   return getNode(Opcode, DL, VT, Ops);
5970 }
5971 
5972 /// getStackArgumentTokenFactor - Compute a TokenFactor to force all
5973 /// the incoming stack arguments to be loaded from the stack.
5974 SDValue SelectionDAG::getStackArgumentTokenFactor(SDValue Chain) {
5975   SmallVector<SDValue, 8> ArgChains;
5976 
5977   // Include the original chain at the beginning of the list. When this is
5978   // used by target LowerCall hooks, this helps legalize find the
5979   // CALLSEQ_BEGIN node.
5980   ArgChains.push_back(Chain);
5981 
5982   // Add a chain value for each stack argument.
5983   for (SDNode::use_iterator U = getEntryNode().getNode()->use_begin(),
5984        UE = getEntryNode().getNode()->use_end(); U != UE; ++U)
5985     if (LoadSDNode *L = dyn_cast<LoadSDNode>(*U))
5986       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
5987         if (FI->getIndex() < 0)
5988           ArgChains.push_back(SDValue(L, 1));
5989 
5990   // Build a tokenfactor for all the chains.
5991   return getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains);
5992 }
5993 
5994 /// getMemsetValue - Vectorized representation of the memset value
5995 /// operand.
5996 static SDValue getMemsetValue(SDValue Value, EVT VT, SelectionDAG &DAG,
5997                               const SDLoc &dl) {
5998   assert(!Value.isUndef());
5999 
6000   unsigned NumBits = VT.getScalarSizeInBits();
6001   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
6002     assert(C->getAPIntValue().getBitWidth() == 8);
6003     APInt Val = APInt::getSplat(NumBits, C->getAPIntValue());
6004     if (VT.isInteger()) {
6005       bool IsOpaque = VT.getSizeInBits() > 64 ||
6006           !DAG.getTargetLoweringInfo().isLegalStoreImmediate(C->getSExtValue());
6007       return DAG.getConstant(Val, dl, VT, false, IsOpaque);
6008     }
6009     return DAG.getConstantFP(APFloat(DAG.EVTToAPFloatSemantics(VT), Val), dl,
6010                              VT);
6011   }
6012 
6013   assert(Value.getValueType() == MVT::i8 && "memset with non-byte fill value?");
6014   EVT IntVT = VT.getScalarType();
6015   if (!IntVT.isInteger())
6016     IntVT = EVT::getIntegerVT(*DAG.getContext(), IntVT.getSizeInBits());
6017 
6018   Value = DAG.getNode(ISD::ZERO_EXTEND, dl, IntVT, Value);
6019   if (NumBits > 8) {
6020     // Use a multiplication with 0x010101... to extend the input to the
6021     // required length.
6022     APInt Magic = APInt::getSplat(NumBits, APInt(8, 0x01));
6023     Value = DAG.getNode(ISD::MUL, dl, IntVT, Value,
6024                         DAG.getConstant(Magic, dl, IntVT));
6025   }
6026 
6027   if (VT != Value.getValueType() && !VT.isInteger())
6028     Value = DAG.getBitcast(VT.getScalarType(), Value);
6029   if (VT != Value.getValueType())
6030     Value = DAG.getSplatBuildVector(VT, dl, Value);
6031 
6032   return Value;
6033 }
6034 
6035 /// getMemsetStringVal - Similar to getMemsetValue. Except this is only
6036 /// used when a memcpy is turned into a memset when the source is a constant
6037 /// string ptr.
6038 static SDValue getMemsetStringVal(EVT VT, const SDLoc &dl, SelectionDAG &DAG,
6039                                   const TargetLowering &TLI,
6040                                   const ConstantDataArraySlice &Slice) {
6041   // Handle vector with all elements zero.
6042   if (Slice.Array == nullptr) {
6043     if (VT.isInteger())
6044       return DAG.getConstant(0, dl, VT);
6045     else if (VT == MVT::f32 || VT == MVT::f64 || VT == MVT::f128)
6046       return DAG.getConstantFP(0.0, dl, VT);
6047     else if (VT.isVector()) {
6048       unsigned NumElts = VT.getVectorNumElements();
6049       MVT EltVT = (VT.getVectorElementType() == MVT::f32) ? MVT::i32 : MVT::i64;
6050       return DAG.getNode(ISD::BITCAST, dl, VT,
6051                          DAG.getConstant(0, dl,
6052                                          EVT::getVectorVT(*DAG.getContext(),
6053                                                           EltVT, NumElts)));
6054     } else
6055       llvm_unreachable("Expected type!");
6056   }
6057 
6058   assert(!VT.isVector() && "Can't handle vector type here!");
6059   unsigned NumVTBits = VT.getSizeInBits();
6060   unsigned NumVTBytes = NumVTBits / 8;
6061   unsigned NumBytes = std::min(NumVTBytes, unsigned(Slice.Length));
6062 
6063   APInt Val(NumVTBits, 0);
6064   if (DAG.getDataLayout().isLittleEndian()) {
6065     for (unsigned i = 0; i != NumBytes; ++i)
6066       Val |= (uint64_t)(unsigned char)Slice[i] << i*8;
6067   } else {
6068     for (unsigned i = 0; i != NumBytes; ++i)
6069       Val |= (uint64_t)(unsigned char)Slice[i] << (NumVTBytes-i-1)*8;
6070   }
6071 
6072   // If the "cost" of materializing the integer immediate is less than the cost
6073   // of a load, then it is cost effective to turn the load into the immediate.
6074   Type *Ty = VT.getTypeForEVT(*DAG.getContext());
6075   if (TLI.shouldConvertConstantLoadToIntImm(Val, Ty))
6076     return DAG.getConstant(Val, dl, VT);
6077   return SDValue(nullptr, 0);
6078 }
6079 
6080 SDValue SelectionDAG::getMemBasePlusOffset(SDValue Base, TypeSize Offset,
6081                                            const SDLoc &DL,
6082                                            const SDNodeFlags Flags) {
6083   EVT VT = Base.getValueType();
6084   SDValue Index;
6085 
6086   if (Offset.isScalable())
6087     Index = getVScale(DL, Base.getValueType(),
6088                       APInt(Base.getValueSizeInBits().getFixedSize(),
6089                             Offset.getKnownMinSize()));
6090   else
6091     Index = getConstant(Offset.getFixedSize(), DL, VT);
6092 
6093   return getMemBasePlusOffset(Base, Index, DL, Flags);
6094 }
6095 
6096 SDValue SelectionDAG::getMemBasePlusOffset(SDValue Ptr, SDValue Offset,
6097                                            const SDLoc &DL,
6098                                            const SDNodeFlags Flags) {
6099   assert(Offset.getValueType().isInteger());
6100   EVT BasePtrVT = Ptr.getValueType();
6101   return getNode(ISD::ADD, DL, BasePtrVT, Ptr, Offset, Flags);
6102 }
6103 
6104 /// Returns true if memcpy source is constant data.
6105 static bool isMemSrcFromConstant(SDValue Src, ConstantDataArraySlice &Slice) {
6106   uint64_t SrcDelta = 0;
6107   GlobalAddressSDNode *G = nullptr;
6108   if (Src.getOpcode() == ISD::GlobalAddress)
6109     G = cast<GlobalAddressSDNode>(Src);
6110   else if (Src.getOpcode() == ISD::ADD &&
6111            Src.getOperand(0).getOpcode() == ISD::GlobalAddress &&
6112            Src.getOperand(1).getOpcode() == ISD::Constant) {
6113     G = cast<GlobalAddressSDNode>(Src.getOperand(0));
6114     SrcDelta = cast<ConstantSDNode>(Src.getOperand(1))->getZExtValue();
6115   }
6116   if (!G)
6117     return false;
6118 
6119   return getConstantDataArrayInfo(G->getGlobal(), Slice, 8,
6120                                   SrcDelta + G->getOffset());
6121 }
6122 
6123 static bool shouldLowerMemFuncForSize(const MachineFunction &MF,
6124                                       SelectionDAG &DAG) {
6125   // On Darwin, -Os means optimize for size without hurting performance, so
6126   // only really optimize for size when -Oz (MinSize) is used.
6127   if (MF.getTarget().getTargetTriple().isOSDarwin())
6128     return MF.getFunction().hasMinSize();
6129   return DAG.shouldOptForSize();
6130 }
6131 
6132 static void chainLoadsAndStoresForMemcpy(SelectionDAG &DAG, const SDLoc &dl,
6133                           SmallVector<SDValue, 32> &OutChains, unsigned From,
6134                           unsigned To, SmallVector<SDValue, 16> &OutLoadChains,
6135                           SmallVector<SDValue, 16> &OutStoreChains) {
6136   assert(OutLoadChains.size() && "Missing loads in memcpy inlining");
6137   assert(OutStoreChains.size() && "Missing stores in memcpy inlining");
6138   SmallVector<SDValue, 16> GluedLoadChains;
6139   for (unsigned i = From; i < To; ++i) {
6140     OutChains.push_back(OutLoadChains[i]);
6141     GluedLoadChains.push_back(OutLoadChains[i]);
6142   }
6143 
6144   // Chain for all loads.
6145   SDValue LoadToken = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
6146                                   GluedLoadChains);
6147 
6148   for (unsigned i = From; i < To; ++i) {
6149     StoreSDNode *ST = dyn_cast<StoreSDNode>(OutStoreChains[i]);
6150     SDValue NewStore = DAG.getTruncStore(LoadToken, dl, ST->getValue(),
6151                                   ST->getBasePtr(), ST->getMemoryVT(),
6152                                   ST->getMemOperand());
6153     OutChains.push_back(NewStore);
6154   }
6155 }
6156 
6157 static SDValue getMemcpyLoadsAndStores(SelectionDAG &DAG, const SDLoc &dl,
6158                                        SDValue Chain, SDValue Dst, SDValue Src,
6159                                        uint64_t Size, Align Alignment,
6160                                        bool isVol, bool AlwaysInline,
6161                                        MachinePointerInfo DstPtrInfo,
6162                                        MachinePointerInfo SrcPtrInfo) {
6163   // Turn a memcpy of undef to nop.
6164   // FIXME: We need to honor volatile even is Src is undef.
6165   if (Src.isUndef())
6166     return Chain;
6167 
6168   // Expand memcpy to a series of load and store ops if the size operand falls
6169   // below a certain threshold.
6170   // TODO: In the AlwaysInline case, if the size is big then generate a loop
6171   // rather than maybe a humongous number of loads and stores.
6172   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6173   const DataLayout &DL = DAG.getDataLayout();
6174   LLVMContext &C = *DAG.getContext();
6175   std::vector<EVT> MemOps;
6176   bool DstAlignCanChange = false;
6177   MachineFunction &MF = DAG.getMachineFunction();
6178   MachineFrameInfo &MFI = MF.getFrameInfo();
6179   bool OptSize = shouldLowerMemFuncForSize(MF, DAG);
6180   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
6181   if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
6182     DstAlignCanChange = true;
6183   MaybeAlign SrcAlign = DAG.InferPtrAlign(Src);
6184   if (!SrcAlign || Alignment > *SrcAlign)
6185     SrcAlign = Alignment;
6186   assert(SrcAlign && "SrcAlign must be set");
6187   ConstantDataArraySlice Slice;
6188   // If marked as volatile, perform a copy even when marked as constant.
6189   bool CopyFromConstant = !isVol && isMemSrcFromConstant(Src, Slice);
6190   bool isZeroConstant = CopyFromConstant && Slice.Array == nullptr;
6191   unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemcpy(OptSize);
6192   const MemOp Op = isZeroConstant
6193                        ? MemOp::Set(Size, DstAlignCanChange, Alignment,
6194                                     /*IsZeroMemset*/ true, isVol)
6195                        : MemOp::Copy(Size, DstAlignCanChange, Alignment,
6196                                      *SrcAlign, isVol, CopyFromConstant);
6197   if (!TLI.findOptimalMemOpLowering(
6198           MemOps, Limit, Op, DstPtrInfo.getAddrSpace(),
6199           SrcPtrInfo.getAddrSpace(), MF.getFunction().getAttributes()))
6200     return SDValue();
6201 
6202   if (DstAlignCanChange) {
6203     Type *Ty = MemOps[0].getTypeForEVT(C);
6204     Align NewAlign = DL.getABITypeAlign(Ty);
6205 
6206     // Don't promote to an alignment that would require dynamic stack
6207     // realignment.
6208     const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
6209     if (!TRI->needsStackRealignment(MF))
6210       while (NewAlign > Alignment && DL.exceedsNaturalStackAlignment(NewAlign))
6211         NewAlign = NewAlign / 2;
6212 
6213     if (NewAlign > Alignment) {
6214       // Give the stack frame object a larger alignment if needed.
6215       if (MFI.getObjectAlign(FI->getIndex()) < NewAlign)
6216         MFI.setObjectAlignment(FI->getIndex(), NewAlign);
6217       Alignment = NewAlign;
6218     }
6219   }
6220 
6221   MachineMemOperand::Flags MMOFlags =
6222       isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone;
6223   SmallVector<SDValue, 16> OutLoadChains;
6224   SmallVector<SDValue, 16> OutStoreChains;
6225   SmallVector<SDValue, 32> OutChains;
6226   unsigned NumMemOps = MemOps.size();
6227   uint64_t SrcOff = 0, DstOff = 0;
6228   for (unsigned i = 0; i != NumMemOps; ++i) {
6229     EVT VT = MemOps[i];
6230     unsigned VTSize = VT.getSizeInBits() / 8;
6231     SDValue Value, Store;
6232 
6233     if (VTSize > Size) {
6234       // Issuing an unaligned load / store pair  that overlaps with the previous
6235       // pair. Adjust the offset accordingly.
6236       assert(i == NumMemOps-1 && i != 0);
6237       SrcOff -= VTSize - Size;
6238       DstOff -= VTSize - Size;
6239     }
6240 
6241     if (CopyFromConstant &&
6242         (isZeroConstant || (VT.isInteger() && !VT.isVector()))) {
6243       // It's unlikely a store of a vector immediate can be done in a single
6244       // instruction. It would require a load from a constantpool first.
6245       // We only handle zero vectors here.
6246       // FIXME: Handle other cases where store of vector immediate is done in
6247       // a single instruction.
6248       ConstantDataArraySlice SubSlice;
6249       if (SrcOff < Slice.Length) {
6250         SubSlice = Slice;
6251         SubSlice.move(SrcOff);
6252       } else {
6253         // This is an out-of-bounds access and hence UB. Pretend we read zero.
6254         SubSlice.Array = nullptr;
6255         SubSlice.Offset = 0;
6256         SubSlice.Length = VTSize;
6257       }
6258       Value = getMemsetStringVal(VT, dl, DAG, TLI, SubSlice);
6259       if (Value.getNode()) {
6260         Store = DAG.getStore(
6261             Chain, dl, Value,
6262             DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl),
6263             DstPtrInfo.getWithOffset(DstOff), Alignment, MMOFlags);
6264         OutChains.push_back(Store);
6265       }
6266     }
6267 
6268     if (!Store.getNode()) {
6269       // The type might not be legal for the target.  This should only happen
6270       // if the type is smaller than a legal type, as on PPC, so the right
6271       // thing to do is generate a LoadExt/StoreTrunc pair.  These simplify
6272       // to Load/Store if NVT==VT.
6273       // FIXME does the case above also need this?
6274       EVT NVT = TLI.getTypeToTransformTo(C, VT);
6275       assert(NVT.bitsGE(VT));
6276 
6277       bool isDereferenceable =
6278         SrcPtrInfo.getWithOffset(SrcOff).isDereferenceable(VTSize, C, DL);
6279       MachineMemOperand::Flags SrcMMOFlags = MMOFlags;
6280       if (isDereferenceable)
6281         SrcMMOFlags |= MachineMemOperand::MODereferenceable;
6282 
6283       Value = DAG.getExtLoad(
6284           ISD::EXTLOAD, dl, NVT, Chain,
6285           DAG.getMemBasePlusOffset(Src, TypeSize::Fixed(SrcOff), dl),
6286           SrcPtrInfo.getWithOffset(SrcOff), VT,
6287           commonAlignment(*SrcAlign, SrcOff), SrcMMOFlags);
6288       OutLoadChains.push_back(Value.getValue(1));
6289 
6290       Store = DAG.getTruncStore(
6291           Chain, dl, Value,
6292           DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl),
6293           DstPtrInfo.getWithOffset(DstOff), VT, Alignment, MMOFlags);
6294       OutStoreChains.push_back(Store);
6295     }
6296     SrcOff += VTSize;
6297     DstOff += VTSize;
6298     Size -= VTSize;
6299   }
6300 
6301   unsigned GluedLdStLimit = MaxLdStGlue == 0 ?
6302                                 TLI.getMaxGluedStoresPerMemcpy() : MaxLdStGlue;
6303   unsigned NumLdStInMemcpy = OutStoreChains.size();
6304 
6305   if (NumLdStInMemcpy) {
6306     // It may be that memcpy might be converted to memset if it's memcpy
6307     // of constants. In such a case, we won't have loads and stores, but
6308     // just stores. In the absence of loads, there is nothing to gang up.
6309     if ((GluedLdStLimit <= 1) || !EnableMemCpyDAGOpt) {
6310       // If target does not care, just leave as it.
6311       for (unsigned i = 0; i < NumLdStInMemcpy; ++i) {
6312         OutChains.push_back(OutLoadChains[i]);
6313         OutChains.push_back(OutStoreChains[i]);
6314       }
6315     } else {
6316       // Ld/St less than/equal limit set by target.
6317       if (NumLdStInMemcpy <= GluedLdStLimit) {
6318           chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, 0,
6319                                         NumLdStInMemcpy, OutLoadChains,
6320                                         OutStoreChains);
6321       } else {
6322         unsigned NumberLdChain =  NumLdStInMemcpy / GluedLdStLimit;
6323         unsigned RemainingLdStInMemcpy = NumLdStInMemcpy % GluedLdStLimit;
6324         unsigned GlueIter = 0;
6325 
6326         for (unsigned cnt = 0; cnt < NumberLdChain; ++cnt) {
6327           unsigned IndexFrom = NumLdStInMemcpy - GlueIter - GluedLdStLimit;
6328           unsigned IndexTo   = NumLdStInMemcpy - GlueIter;
6329 
6330           chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, IndexFrom, IndexTo,
6331                                        OutLoadChains, OutStoreChains);
6332           GlueIter += GluedLdStLimit;
6333         }
6334 
6335         // Residual ld/st.
6336         if (RemainingLdStInMemcpy) {
6337           chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, 0,
6338                                         RemainingLdStInMemcpy, OutLoadChains,
6339                                         OutStoreChains);
6340         }
6341       }
6342     }
6343   }
6344   return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
6345 }
6346 
6347 static SDValue getMemmoveLoadsAndStores(SelectionDAG &DAG, const SDLoc &dl,
6348                                         SDValue Chain, SDValue Dst, SDValue Src,
6349                                         uint64_t Size, Align Alignment,
6350                                         bool isVol, bool AlwaysInline,
6351                                         MachinePointerInfo DstPtrInfo,
6352                                         MachinePointerInfo SrcPtrInfo) {
6353   // Turn a memmove of undef to nop.
6354   // FIXME: We need to honor volatile even is Src is undef.
6355   if (Src.isUndef())
6356     return Chain;
6357 
6358   // Expand memmove to a series of load and store ops if the size operand falls
6359   // below a certain threshold.
6360   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6361   const DataLayout &DL = DAG.getDataLayout();
6362   LLVMContext &C = *DAG.getContext();
6363   std::vector<EVT> MemOps;
6364   bool DstAlignCanChange = false;
6365   MachineFunction &MF = DAG.getMachineFunction();
6366   MachineFrameInfo &MFI = MF.getFrameInfo();
6367   bool OptSize = shouldLowerMemFuncForSize(MF, DAG);
6368   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
6369   if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
6370     DstAlignCanChange = true;
6371   MaybeAlign SrcAlign = DAG.InferPtrAlign(Src);
6372   if (!SrcAlign || Alignment > *SrcAlign)
6373     SrcAlign = Alignment;
6374   assert(SrcAlign && "SrcAlign must be set");
6375   unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemmove(OptSize);
6376   if (!TLI.findOptimalMemOpLowering(
6377           MemOps, Limit,
6378           MemOp::Copy(Size, DstAlignCanChange, Alignment, *SrcAlign,
6379                       /*IsVolatile*/ true),
6380           DstPtrInfo.getAddrSpace(), SrcPtrInfo.getAddrSpace(),
6381           MF.getFunction().getAttributes()))
6382     return SDValue();
6383 
6384   if (DstAlignCanChange) {
6385     Type *Ty = MemOps[0].getTypeForEVT(C);
6386     Align NewAlign = DL.getABITypeAlign(Ty);
6387     if (NewAlign > Alignment) {
6388       // Give the stack frame object a larger alignment if needed.
6389       if (MFI.getObjectAlign(FI->getIndex()) < NewAlign)
6390         MFI.setObjectAlignment(FI->getIndex(), NewAlign);
6391       Alignment = NewAlign;
6392     }
6393   }
6394 
6395   MachineMemOperand::Flags MMOFlags =
6396       isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone;
6397   uint64_t SrcOff = 0, DstOff = 0;
6398   SmallVector<SDValue, 8> LoadValues;
6399   SmallVector<SDValue, 8> LoadChains;
6400   SmallVector<SDValue, 8> OutChains;
6401   unsigned NumMemOps = MemOps.size();
6402   for (unsigned i = 0; i < NumMemOps; i++) {
6403     EVT VT = MemOps[i];
6404     unsigned VTSize = VT.getSizeInBits() / 8;
6405     SDValue Value;
6406 
6407     bool isDereferenceable =
6408       SrcPtrInfo.getWithOffset(SrcOff).isDereferenceable(VTSize, C, DL);
6409     MachineMemOperand::Flags SrcMMOFlags = MMOFlags;
6410     if (isDereferenceable)
6411       SrcMMOFlags |= MachineMemOperand::MODereferenceable;
6412 
6413     Value =
6414         DAG.getLoad(VT, dl, Chain,
6415                     DAG.getMemBasePlusOffset(Src, TypeSize::Fixed(SrcOff), dl),
6416                     SrcPtrInfo.getWithOffset(SrcOff), *SrcAlign, SrcMMOFlags);
6417     LoadValues.push_back(Value);
6418     LoadChains.push_back(Value.getValue(1));
6419     SrcOff += VTSize;
6420   }
6421   Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
6422   OutChains.clear();
6423   for (unsigned i = 0; i < NumMemOps; i++) {
6424     EVT VT = MemOps[i];
6425     unsigned VTSize = VT.getSizeInBits() / 8;
6426     SDValue Store;
6427 
6428     Store =
6429         DAG.getStore(Chain, dl, LoadValues[i],
6430                      DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl),
6431                      DstPtrInfo.getWithOffset(DstOff), Alignment, MMOFlags);
6432     OutChains.push_back(Store);
6433     DstOff += VTSize;
6434   }
6435 
6436   return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
6437 }
6438 
6439 /// Lower the call to 'memset' intrinsic function into a series of store
6440 /// operations.
6441 ///
6442 /// \param DAG Selection DAG where lowered code is placed.
6443 /// \param dl Link to corresponding IR location.
6444 /// \param Chain Control flow dependency.
6445 /// \param Dst Pointer to destination memory location.
6446 /// \param Src Value of byte to write into the memory.
6447 /// \param Size Number of bytes to write.
6448 /// \param Alignment Alignment of the destination in bytes.
6449 /// \param isVol True if destination is volatile.
6450 /// \param DstPtrInfo IR information on the memory pointer.
6451 /// \returns New head in the control flow, if lowering was successful, empty
6452 /// SDValue otherwise.
6453 ///
6454 /// The function tries to replace 'llvm.memset' intrinsic with several store
6455 /// operations and value calculation code. This is usually profitable for small
6456 /// memory size.
6457 static SDValue getMemsetStores(SelectionDAG &DAG, const SDLoc &dl,
6458                                SDValue Chain, SDValue Dst, SDValue Src,
6459                                uint64_t Size, Align Alignment, bool isVol,
6460                                MachinePointerInfo DstPtrInfo) {
6461   // Turn a memset of undef to nop.
6462   // FIXME: We need to honor volatile even is Src is undef.
6463   if (Src.isUndef())
6464     return Chain;
6465 
6466   // Expand memset to a series of load/store ops if the size operand
6467   // falls below a certain threshold.
6468   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6469   std::vector<EVT> MemOps;
6470   bool DstAlignCanChange = false;
6471   MachineFunction &MF = DAG.getMachineFunction();
6472   MachineFrameInfo &MFI = MF.getFrameInfo();
6473   bool OptSize = shouldLowerMemFuncForSize(MF, DAG);
6474   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
6475   if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
6476     DstAlignCanChange = true;
6477   bool IsZeroVal =
6478     isa<ConstantSDNode>(Src) && cast<ConstantSDNode>(Src)->isNullValue();
6479   if (!TLI.findOptimalMemOpLowering(
6480           MemOps, TLI.getMaxStoresPerMemset(OptSize),
6481           MemOp::Set(Size, DstAlignCanChange, Alignment, IsZeroVal, isVol),
6482           DstPtrInfo.getAddrSpace(), ~0u, MF.getFunction().getAttributes()))
6483     return SDValue();
6484 
6485   if (DstAlignCanChange) {
6486     Type *Ty = MemOps[0].getTypeForEVT(*DAG.getContext());
6487     Align NewAlign = DAG.getDataLayout().getABITypeAlign(Ty);
6488     if (NewAlign > Alignment) {
6489       // Give the stack frame object a larger alignment if needed.
6490       if (MFI.getObjectAlign(FI->getIndex()) < NewAlign)
6491         MFI.setObjectAlignment(FI->getIndex(), NewAlign);
6492       Alignment = NewAlign;
6493     }
6494   }
6495 
6496   SmallVector<SDValue, 8> OutChains;
6497   uint64_t DstOff = 0;
6498   unsigned NumMemOps = MemOps.size();
6499 
6500   // Find the largest store and generate the bit pattern for it.
6501   EVT LargestVT = MemOps[0];
6502   for (unsigned i = 1; i < NumMemOps; i++)
6503     if (MemOps[i].bitsGT(LargestVT))
6504       LargestVT = MemOps[i];
6505   SDValue MemSetValue = getMemsetValue(Src, LargestVT, DAG, dl);
6506 
6507   for (unsigned i = 0; i < NumMemOps; i++) {
6508     EVT VT = MemOps[i];
6509     unsigned VTSize = VT.getSizeInBits() / 8;
6510     if (VTSize > Size) {
6511       // Issuing an unaligned load / store pair  that overlaps with the previous
6512       // pair. Adjust the offset accordingly.
6513       assert(i == NumMemOps-1 && i != 0);
6514       DstOff -= VTSize - Size;
6515     }
6516 
6517     // If this store is smaller than the largest store see whether we can get
6518     // the smaller value for free with a truncate.
6519     SDValue Value = MemSetValue;
6520     if (VT.bitsLT(LargestVT)) {
6521       if (!LargestVT.isVector() && !VT.isVector() &&
6522           TLI.isTruncateFree(LargestVT, VT))
6523         Value = DAG.getNode(ISD::TRUNCATE, dl, VT, MemSetValue);
6524       else
6525         Value = getMemsetValue(Src, VT, DAG, dl);
6526     }
6527     assert(Value.getValueType() == VT && "Value with wrong type.");
6528     SDValue Store = DAG.getStore(
6529         Chain, dl, Value,
6530         DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl),
6531         DstPtrInfo.getWithOffset(DstOff), Alignment,
6532         isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone);
6533     OutChains.push_back(Store);
6534     DstOff += VT.getSizeInBits() / 8;
6535     Size -= VTSize;
6536   }
6537 
6538   return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
6539 }
6540 
6541 static void checkAddrSpaceIsValidForLibcall(const TargetLowering *TLI,
6542                                             unsigned AS) {
6543   // Lowering memcpy / memset / memmove intrinsics to calls is only valid if all
6544   // pointer operands can be losslessly bitcasted to pointers of address space 0
6545   if (AS != 0 && !TLI->getTargetMachine().isNoopAddrSpaceCast(AS, 0)) {
6546     report_fatal_error("cannot lower memory intrinsic in address space " +
6547                        Twine(AS));
6548   }
6549 }
6550 
6551 SDValue SelectionDAG::getMemcpy(SDValue Chain, const SDLoc &dl, SDValue Dst,
6552                                 SDValue Src, SDValue Size, Align Alignment,
6553                                 bool isVol, bool AlwaysInline, bool isTailCall,
6554                                 MachinePointerInfo DstPtrInfo,
6555                                 MachinePointerInfo SrcPtrInfo) {
6556   // Check to see if we should lower the memcpy to loads and stores first.
6557   // For cases within the target-specified limits, this is the best choice.
6558   ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
6559   if (ConstantSize) {
6560     // Memcpy with size zero? Just return the original chain.
6561     if (ConstantSize->isNullValue())
6562       return Chain;
6563 
6564     SDValue Result = getMemcpyLoadsAndStores(
6565         *this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), Alignment,
6566         isVol, false, DstPtrInfo, SrcPtrInfo);
6567     if (Result.getNode())
6568       return Result;
6569   }
6570 
6571   // Then check to see if we should lower the memcpy with target-specific
6572   // code. If the target chooses to do this, this is the next best.
6573   if (TSI) {
6574     SDValue Result = TSI->EmitTargetCodeForMemcpy(
6575         *this, dl, Chain, Dst, Src, Size, Alignment, isVol, AlwaysInline,
6576         DstPtrInfo, SrcPtrInfo);
6577     if (Result.getNode())
6578       return Result;
6579   }
6580 
6581   // If we really need inline code and the target declined to provide it,
6582   // use a (potentially long) sequence of loads and stores.
6583   if (AlwaysInline) {
6584     assert(ConstantSize && "AlwaysInline requires a constant size!");
6585     return getMemcpyLoadsAndStores(*this, dl, Chain, Dst, Src,
6586                                    ConstantSize->getZExtValue(), Alignment,
6587                                    isVol, true, DstPtrInfo, SrcPtrInfo);
6588   }
6589 
6590   checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace());
6591   checkAddrSpaceIsValidForLibcall(TLI, SrcPtrInfo.getAddrSpace());
6592 
6593   // FIXME: If the memcpy is volatile (isVol), lowering it to a plain libc
6594   // memcpy is not guaranteed to be safe. libc memcpys aren't required to
6595   // respect volatile, so they may do things like read or write memory
6596   // beyond the given memory regions. But fixing this isn't easy, and most
6597   // people don't care.
6598 
6599   // Emit a library call.
6600   TargetLowering::ArgListTy Args;
6601   TargetLowering::ArgListEntry Entry;
6602   Entry.Ty = Type::getInt8PtrTy(*getContext());
6603   Entry.Node = Dst; Args.push_back(Entry);
6604   Entry.Node = Src; Args.push_back(Entry);
6605 
6606   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
6607   Entry.Node = Size; Args.push_back(Entry);
6608   // FIXME: pass in SDLoc
6609   TargetLowering::CallLoweringInfo CLI(*this);
6610   CLI.setDebugLoc(dl)
6611       .setChain(Chain)
6612       .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMCPY),
6613                     Dst.getValueType().getTypeForEVT(*getContext()),
6614                     getExternalSymbol(TLI->getLibcallName(RTLIB::MEMCPY),
6615                                       TLI->getPointerTy(getDataLayout())),
6616                     std::move(Args))
6617       .setDiscardResult()
6618       .setTailCall(isTailCall);
6619 
6620   std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
6621   return CallResult.second;
6622 }
6623 
6624 SDValue SelectionDAG::getAtomicMemcpy(SDValue Chain, const SDLoc &dl,
6625                                       SDValue Dst, unsigned DstAlign,
6626                                       SDValue Src, unsigned SrcAlign,
6627                                       SDValue Size, Type *SizeTy,
6628                                       unsigned ElemSz, bool isTailCall,
6629                                       MachinePointerInfo DstPtrInfo,
6630                                       MachinePointerInfo SrcPtrInfo) {
6631   // Emit a library call.
6632   TargetLowering::ArgListTy Args;
6633   TargetLowering::ArgListEntry Entry;
6634   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
6635   Entry.Node = Dst;
6636   Args.push_back(Entry);
6637 
6638   Entry.Node = Src;
6639   Args.push_back(Entry);
6640 
6641   Entry.Ty = SizeTy;
6642   Entry.Node = Size;
6643   Args.push_back(Entry);
6644 
6645   RTLIB::Libcall LibraryCall =
6646       RTLIB::getMEMCPY_ELEMENT_UNORDERED_ATOMIC(ElemSz);
6647   if (LibraryCall == RTLIB::UNKNOWN_LIBCALL)
6648     report_fatal_error("Unsupported element size");
6649 
6650   TargetLowering::CallLoweringInfo CLI(*this);
6651   CLI.setDebugLoc(dl)
6652       .setChain(Chain)
6653       .setLibCallee(TLI->getLibcallCallingConv(LibraryCall),
6654                     Type::getVoidTy(*getContext()),
6655                     getExternalSymbol(TLI->getLibcallName(LibraryCall),
6656                                       TLI->getPointerTy(getDataLayout())),
6657                     std::move(Args))
6658       .setDiscardResult()
6659       .setTailCall(isTailCall);
6660 
6661   std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
6662   return CallResult.second;
6663 }
6664 
6665 SDValue SelectionDAG::getMemmove(SDValue Chain, const SDLoc &dl, SDValue Dst,
6666                                  SDValue Src, SDValue Size, Align Alignment,
6667                                  bool isVol, bool isTailCall,
6668                                  MachinePointerInfo DstPtrInfo,
6669                                  MachinePointerInfo SrcPtrInfo) {
6670   // Check to see if we should lower the memmove to loads and stores first.
6671   // For cases within the target-specified limits, this is the best choice.
6672   ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
6673   if (ConstantSize) {
6674     // Memmove with size zero? Just return the original chain.
6675     if (ConstantSize->isNullValue())
6676       return Chain;
6677 
6678     SDValue Result = getMemmoveLoadsAndStores(
6679         *this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), Alignment,
6680         isVol, false, DstPtrInfo, SrcPtrInfo);
6681     if (Result.getNode())
6682       return Result;
6683   }
6684 
6685   // Then check to see if we should lower the memmove with target-specific
6686   // code. If the target chooses to do this, this is the next best.
6687   if (TSI) {
6688     SDValue Result =
6689         TSI->EmitTargetCodeForMemmove(*this, dl, Chain, Dst, Src, Size,
6690                                       Alignment, isVol, DstPtrInfo, SrcPtrInfo);
6691     if (Result.getNode())
6692       return Result;
6693   }
6694 
6695   checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace());
6696   checkAddrSpaceIsValidForLibcall(TLI, SrcPtrInfo.getAddrSpace());
6697 
6698   // FIXME: If the memmove is volatile, lowering it to plain libc memmove may
6699   // not be safe.  See memcpy above for more details.
6700 
6701   // Emit a library call.
6702   TargetLowering::ArgListTy Args;
6703   TargetLowering::ArgListEntry Entry;
6704   Entry.Ty = Type::getInt8PtrTy(*getContext());
6705   Entry.Node = Dst; Args.push_back(Entry);
6706   Entry.Node = Src; Args.push_back(Entry);
6707 
6708   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
6709   Entry.Node = Size; Args.push_back(Entry);
6710   // FIXME:  pass in SDLoc
6711   TargetLowering::CallLoweringInfo CLI(*this);
6712   CLI.setDebugLoc(dl)
6713       .setChain(Chain)
6714       .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMMOVE),
6715                     Dst.getValueType().getTypeForEVT(*getContext()),
6716                     getExternalSymbol(TLI->getLibcallName(RTLIB::MEMMOVE),
6717                                       TLI->getPointerTy(getDataLayout())),
6718                     std::move(Args))
6719       .setDiscardResult()
6720       .setTailCall(isTailCall);
6721 
6722   std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
6723   return CallResult.second;
6724 }
6725 
6726 SDValue SelectionDAG::getAtomicMemmove(SDValue Chain, const SDLoc &dl,
6727                                        SDValue Dst, unsigned DstAlign,
6728                                        SDValue Src, unsigned SrcAlign,
6729                                        SDValue Size, Type *SizeTy,
6730                                        unsigned ElemSz, bool isTailCall,
6731                                        MachinePointerInfo DstPtrInfo,
6732                                        MachinePointerInfo SrcPtrInfo) {
6733   // Emit a library call.
6734   TargetLowering::ArgListTy Args;
6735   TargetLowering::ArgListEntry Entry;
6736   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
6737   Entry.Node = Dst;
6738   Args.push_back(Entry);
6739 
6740   Entry.Node = Src;
6741   Args.push_back(Entry);
6742 
6743   Entry.Ty = SizeTy;
6744   Entry.Node = Size;
6745   Args.push_back(Entry);
6746 
6747   RTLIB::Libcall LibraryCall =
6748       RTLIB::getMEMMOVE_ELEMENT_UNORDERED_ATOMIC(ElemSz);
6749   if (LibraryCall == RTLIB::UNKNOWN_LIBCALL)
6750     report_fatal_error("Unsupported element size");
6751 
6752   TargetLowering::CallLoweringInfo CLI(*this);
6753   CLI.setDebugLoc(dl)
6754       .setChain(Chain)
6755       .setLibCallee(TLI->getLibcallCallingConv(LibraryCall),
6756                     Type::getVoidTy(*getContext()),
6757                     getExternalSymbol(TLI->getLibcallName(LibraryCall),
6758                                       TLI->getPointerTy(getDataLayout())),
6759                     std::move(Args))
6760       .setDiscardResult()
6761       .setTailCall(isTailCall);
6762 
6763   std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
6764   return CallResult.second;
6765 }
6766 
6767 SDValue SelectionDAG::getMemset(SDValue Chain, const SDLoc &dl, SDValue Dst,
6768                                 SDValue Src, SDValue Size, Align Alignment,
6769                                 bool isVol, bool isTailCall,
6770                                 MachinePointerInfo DstPtrInfo) {
6771   // Check to see if we should lower the memset to stores first.
6772   // For cases within the target-specified limits, this is the best choice.
6773   ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
6774   if (ConstantSize) {
6775     // Memset with size zero? Just return the original chain.
6776     if (ConstantSize->isNullValue())
6777       return Chain;
6778 
6779     SDValue Result = getMemsetStores(*this, dl, Chain, Dst, Src,
6780                                      ConstantSize->getZExtValue(), Alignment,
6781                                      isVol, DstPtrInfo);
6782 
6783     if (Result.getNode())
6784       return Result;
6785   }
6786 
6787   // Then check to see if we should lower the memset with target-specific
6788   // code. If the target chooses to do this, this is the next best.
6789   if (TSI) {
6790     SDValue Result = TSI->EmitTargetCodeForMemset(
6791         *this, dl, Chain, Dst, Src, Size, Alignment, isVol, DstPtrInfo);
6792     if (Result.getNode())
6793       return Result;
6794   }
6795 
6796   checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace());
6797 
6798   // Emit a library call.
6799   TargetLowering::ArgListTy Args;
6800   TargetLowering::ArgListEntry Entry;
6801   Entry.Node = Dst; Entry.Ty = Type::getInt8PtrTy(*getContext());
6802   Args.push_back(Entry);
6803   Entry.Node = Src;
6804   Entry.Ty = Src.getValueType().getTypeForEVT(*getContext());
6805   Args.push_back(Entry);
6806   Entry.Node = Size;
6807   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
6808   Args.push_back(Entry);
6809 
6810   // FIXME: pass in SDLoc
6811   TargetLowering::CallLoweringInfo CLI(*this);
6812   CLI.setDebugLoc(dl)
6813       .setChain(Chain)
6814       .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMSET),
6815                     Dst.getValueType().getTypeForEVT(*getContext()),
6816                     getExternalSymbol(TLI->getLibcallName(RTLIB::MEMSET),
6817                                       TLI->getPointerTy(getDataLayout())),
6818                     std::move(Args))
6819       .setDiscardResult()
6820       .setTailCall(isTailCall);
6821 
6822   std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
6823   return CallResult.second;
6824 }
6825 
6826 SDValue SelectionDAG::getAtomicMemset(SDValue Chain, const SDLoc &dl,
6827                                       SDValue Dst, unsigned DstAlign,
6828                                       SDValue Value, SDValue Size, Type *SizeTy,
6829                                       unsigned ElemSz, bool isTailCall,
6830                                       MachinePointerInfo DstPtrInfo) {
6831   // Emit a library call.
6832   TargetLowering::ArgListTy Args;
6833   TargetLowering::ArgListEntry Entry;
6834   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
6835   Entry.Node = Dst;
6836   Args.push_back(Entry);
6837 
6838   Entry.Ty = Type::getInt8Ty(*getContext());
6839   Entry.Node = Value;
6840   Args.push_back(Entry);
6841 
6842   Entry.Ty = SizeTy;
6843   Entry.Node = Size;
6844   Args.push_back(Entry);
6845 
6846   RTLIB::Libcall LibraryCall =
6847       RTLIB::getMEMSET_ELEMENT_UNORDERED_ATOMIC(ElemSz);
6848   if (LibraryCall == RTLIB::UNKNOWN_LIBCALL)
6849     report_fatal_error("Unsupported element size");
6850 
6851   TargetLowering::CallLoweringInfo CLI(*this);
6852   CLI.setDebugLoc(dl)
6853       .setChain(Chain)
6854       .setLibCallee(TLI->getLibcallCallingConv(LibraryCall),
6855                     Type::getVoidTy(*getContext()),
6856                     getExternalSymbol(TLI->getLibcallName(LibraryCall),
6857                                       TLI->getPointerTy(getDataLayout())),
6858                     std::move(Args))
6859       .setDiscardResult()
6860       .setTailCall(isTailCall);
6861 
6862   std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
6863   return CallResult.second;
6864 }
6865 
6866 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
6867                                 SDVTList VTList, ArrayRef<SDValue> Ops,
6868                                 MachineMemOperand *MMO) {
6869   FoldingSetNodeID ID;
6870   ID.AddInteger(MemVT.getRawBits());
6871   AddNodeIDNode(ID, Opcode, VTList, Ops);
6872   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
6873   void* IP = nullptr;
6874   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
6875     cast<AtomicSDNode>(E)->refineAlignment(MMO);
6876     return SDValue(E, 0);
6877   }
6878 
6879   auto *N = newSDNode<AtomicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
6880                                     VTList, MemVT, MMO);
6881   createOperands(N, Ops);
6882 
6883   CSEMap.InsertNode(N, IP);
6884   InsertNode(N);
6885   return SDValue(N, 0);
6886 }
6887 
6888 SDValue SelectionDAG::getAtomicCmpSwap(unsigned Opcode, const SDLoc &dl,
6889                                        EVT MemVT, SDVTList VTs, SDValue Chain,
6890                                        SDValue Ptr, SDValue Cmp, SDValue Swp,
6891                                        MachineMemOperand *MMO) {
6892   assert(Opcode == ISD::ATOMIC_CMP_SWAP ||
6893          Opcode == ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS);
6894   assert(Cmp.getValueType() == Swp.getValueType() && "Invalid Atomic Op Types");
6895 
6896   SDValue Ops[] = {Chain, Ptr, Cmp, Swp};
6897   return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
6898 }
6899 
6900 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
6901                                 SDValue Chain, SDValue Ptr, SDValue Val,
6902                                 MachineMemOperand *MMO) {
6903   assert((Opcode == ISD::ATOMIC_LOAD_ADD ||
6904           Opcode == ISD::ATOMIC_LOAD_SUB ||
6905           Opcode == ISD::ATOMIC_LOAD_AND ||
6906           Opcode == ISD::ATOMIC_LOAD_CLR ||
6907           Opcode == ISD::ATOMIC_LOAD_OR ||
6908           Opcode == ISD::ATOMIC_LOAD_XOR ||
6909           Opcode == ISD::ATOMIC_LOAD_NAND ||
6910           Opcode == ISD::ATOMIC_LOAD_MIN ||
6911           Opcode == ISD::ATOMIC_LOAD_MAX ||
6912           Opcode == ISD::ATOMIC_LOAD_UMIN ||
6913           Opcode == ISD::ATOMIC_LOAD_UMAX ||
6914           Opcode == ISD::ATOMIC_LOAD_FADD ||
6915           Opcode == ISD::ATOMIC_LOAD_FSUB ||
6916           Opcode == ISD::ATOMIC_SWAP ||
6917           Opcode == ISD::ATOMIC_STORE) &&
6918          "Invalid Atomic Op");
6919 
6920   EVT VT = Val.getValueType();
6921 
6922   SDVTList VTs = Opcode == ISD::ATOMIC_STORE ? getVTList(MVT::Other) :
6923                                                getVTList(VT, MVT::Other);
6924   SDValue Ops[] = {Chain, Ptr, Val};
6925   return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
6926 }
6927 
6928 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
6929                                 EVT VT, SDValue Chain, SDValue Ptr,
6930                                 MachineMemOperand *MMO) {
6931   assert(Opcode == ISD::ATOMIC_LOAD && "Invalid Atomic Op");
6932 
6933   SDVTList VTs = getVTList(VT, MVT::Other);
6934   SDValue Ops[] = {Chain, Ptr};
6935   return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
6936 }
6937 
6938 /// getMergeValues - Create a MERGE_VALUES node from the given operands.
6939 SDValue SelectionDAG::getMergeValues(ArrayRef<SDValue> Ops, const SDLoc &dl) {
6940   if (Ops.size() == 1)
6941     return Ops[0];
6942 
6943   SmallVector<EVT, 4> VTs;
6944   VTs.reserve(Ops.size());
6945   for (const SDValue &Op : Ops)
6946     VTs.push_back(Op.getValueType());
6947   return getNode(ISD::MERGE_VALUES, dl, getVTList(VTs), Ops);
6948 }
6949 
6950 SDValue SelectionDAG::getMemIntrinsicNode(
6951     unsigned Opcode, const SDLoc &dl, SDVTList VTList, ArrayRef<SDValue> Ops,
6952     EVT MemVT, MachinePointerInfo PtrInfo, Align Alignment,
6953     MachineMemOperand::Flags Flags, uint64_t Size, const AAMDNodes &AAInfo) {
6954   if (!Size && MemVT.isScalableVector())
6955     Size = MemoryLocation::UnknownSize;
6956   else if (!Size)
6957     Size = MemVT.getStoreSize();
6958 
6959   MachineFunction &MF = getMachineFunction();
6960   MachineMemOperand *MMO =
6961       MF.getMachineMemOperand(PtrInfo, Flags, Size, Alignment, AAInfo);
6962 
6963   return getMemIntrinsicNode(Opcode, dl, VTList, Ops, MemVT, MMO);
6964 }
6965 
6966 SDValue SelectionDAG::getMemIntrinsicNode(unsigned Opcode, const SDLoc &dl,
6967                                           SDVTList VTList,
6968                                           ArrayRef<SDValue> Ops, EVT MemVT,
6969                                           MachineMemOperand *MMO) {
6970   assert((Opcode == ISD::INTRINSIC_VOID ||
6971           Opcode == ISD::INTRINSIC_W_CHAIN ||
6972           Opcode == ISD::PREFETCH ||
6973           ((int)Opcode <= std::numeric_limits<int>::max() &&
6974            (int)Opcode >= ISD::FIRST_TARGET_MEMORY_OPCODE)) &&
6975          "Opcode is not a memory-accessing opcode!");
6976 
6977   // Memoize the node unless it returns a flag.
6978   MemIntrinsicSDNode *N;
6979   if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) {
6980     FoldingSetNodeID ID;
6981     AddNodeIDNode(ID, Opcode, VTList, Ops);
6982     ID.AddInteger(getSyntheticNodeSubclassData<MemIntrinsicSDNode>(
6983         Opcode, dl.getIROrder(), VTList, MemVT, MMO));
6984     ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
6985     void *IP = nullptr;
6986     if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
6987       cast<MemIntrinsicSDNode>(E)->refineAlignment(MMO);
6988       return SDValue(E, 0);
6989     }
6990 
6991     N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
6992                                       VTList, MemVT, MMO);
6993     createOperands(N, Ops);
6994 
6995   CSEMap.InsertNode(N, IP);
6996   } else {
6997     N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
6998                                       VTList, MemVT, MMO);
6999     createOperands(N, Ops);
7000   }
7001   InsertNode(N);
7002   SDValue V(N, 0);
7003   NewSDValueDbgMsg(V, "Creating new node: ", this);
7004   return V;
7005 }
7006 
7007 SDValue SelectionDAG::getLifetimeNode(bool IsStart, const SDLoc &dl,
7008                                       SDValue Chain, int FrameIndex,
7009                                       int64_t Size, int64_t Offset) {
7010   const unsigned Opcode = IsStart ? ISD::LIFETIME_START : ISD::LIFETIME_END;
7011   const auto VTs = getVTList(MVT::Other);
7012   SDValue Ops[2] = {
7013       Chain,
7014       getFrameIndex(FrameIndex,
7015                     getTargetLoweringInfo().getFrameIndexTy(getDataLayout()),
7016                     true)};
7017 
7018   FoldingSetNodeID ID;
7019   AddNodeIDNode(ID, Opcode, VTs, Ops);
7020   ID.AddInteger(FrameIndex);
7021   ID.AddInteger(Size);
7022   ID.AddInteger(Offset);
7023   void *IP = nullptr;
7024   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
7025     return SDValue(E, 0);
7026 
7027   LifetimeSDNode *N = newSDNode<LifetimeSDNode>(
7028       Opcode, dl.getIROrder(), dl.getDebugLoc(), VTs, Size, Offset);
7029   createOperands(N, Ops);
7030   CSEMap.InsertNode(N, IP);
7031   InsertNode(N);
7032   SDValue V(N, 0);
7033   NewSDValueDbgMsg(V, "Creating new node: ", this);
7034   return V;
7035 }
7036 
7037 SDValue SelectionDAG::getPseudoProbeNode(const SDLoc &Dl, SDValue Chain,
7038                                          uint64_t Guid, uint64_t Index,
7039                                          uint32_t Attr) {
7040   const unsigned Opcode = ISD::PSEUDO_PROBE;
7041   const auto VTs = getVTList(MVT::Other);
7042   SDValue Ops[] = {Chain};
7043   FoldingSetNodeID ID;
7044   AddNodeIDNode(ID, Opcode, VTs, Ops);
7045   ID.AddInteger(Guid);
7046   ID.AddInteger(Index);
7047   void *IP = nullptr;
7048   if (SDNode *E = FindNodeOrInsertPos(ID, Dl, IP))
7049     return SDValue(E, 0);
7050 
7051   auto *N = newSDNode<PseudoProbeSDNode>(
7052       Opcode, Dl.getIROrder(), Dl.getDebugLoc(), VTs, Guid, Index, Attr);
7053   createOperands(N, Ops);
7054   CSEMap.InsertNode(N, IP);
7055   InsertNode(N);
7056   SDValue V(N, 0);
7057   NewSDValueDbgMsg(V, "Creating new node: ", this);
7058   return V;
7059 }
7060 
7061 /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a
7062 /// MachinePointerInfo record from it.  This is particularly useful because the
7063 /// code generator has many cases where it doesn't bother passing in a
7064 /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst".
7065 static MachinePointerInfo InferPointerInfo(const MachinePointerInfo &Info,
7066                                            SelectionDAG &DAG, SDValue Ptr,
7067                                            int64_t Offset = 0) {
7068   // If this is FI+Offset, we can model it.
7069   if (const FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr))
7070     return MachinePointerInfo::getFixedStack(DAG.getMachineFunction(),
7071                                              FI->getIndex(), Offset);
7072 
7073   // If this is (FI+Offset1)+Offset2, we can model it.
7074   if (Ptr.getOpcode() != ISD::ADD ||
7075       !isa<ConstantSDNode>(Ptr.getOperand(1)) ||
7076       !isa<FrameIndexSDNode>(Ptr.getOperand(0)))
7077     return Info;
7078 
7079   int FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
7080   return MachinePointerInfo::getFixedStack(
7081       DAG.getMachineFunction(), FI,
7082       Offset + cast<ConstantSDNode>(Ptr.getOperand(1))->getSExtValue());
7083 }
7084 
7085 /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a
7086 /// MachinePointerInfo record from it.  This is particularly useful because the
7087 /// code generator has many cases where it doesn't bother passing in a
7088 /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst".
7089 static MachinePointerInfo InferPointerInfo(const MachinePointerInfo &Info,
7090                                            SelectionDAG &DAG, SDValue Ptr,
7091                                            SDValue OffsetOp) {
7092   // If the 'Offset' value isn't a constant, we can't handle this.
7093   if (ConstantSDNode *OffsetNode = dyn_cast<ConstantSDNode>(OffsetOp))
7094     return InferPointerInfo(Info, DAG, Ptr, OffsetNode->getSExtValue());
7095   if (OffsetOp.isUndef())
7096     return InferPointerInfo(Info, DAG, Ptr);
7097   return Info;
7098 }
7099 
7100 SDValue SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType,
7101                               EVT VT, const SDLoc &dl, SDValue Chain,
7102                               SDValue Ptr, SDValue Offset,
7103                               MachinePointerInfo PtrInfo, EVT MemVT,
7104                               Align Alignment,
7105                               MachineMemOperand::Flags MMOFlags,
7106                               const AAMDNodes &AAInfo, const MDNode *Ranges) {
7107   assert(Chain.getValueType() == MVT::Other &&
7108         "Invalid chain type");
7109 
7110   MMOFlags |= MachineMemOperand::MOLoad;
7111   assert((MMOFlags & MachineMemOperand::MOStore) == 0);
7112   // If we don't have a PtrInfo, infer the trivial frame index case to simplify
7113   // clients.
7114   if (PtrInfo.V.isNull())
7115     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr, Offset);
7116 
7117   uint64_t Size = MemoryLocation::getSizeOrUnknown(MemVT.getStoreSize());
7118   MachineFunction &MF = getMachineFunction();
7119   MachineMemOperand *MMO = MF.getMachineMemOperand(PtrInfo, MMOFlags, Size,
7120                                                    Alignment, AAInfo, Ranges);
7121   return getLoad(AM, ExtType, VT, dl, Chain, Ptr, Offset, MemVT, MMO);
7122 }
7123 
7124 SDValue SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType,
7125                               EVT VT, const SDLoc &dl, SDValue Chain,
7126                               SDValue Ptr, SDValue Offset, EVT MemVT,
7127                               MachineMemOperand *MMO) {
7128   if (VT == MemVT) {
7129     ExtType = ISD::NON_EXTLOAD;
7130   } else if (ExtType == ISD::NON_EXTLOAD) {
7131     assert(VT == MemVT && "Non-extending load from different memory type!");
7132   } else {
7133     // Extending load.
7134     assert(MemVT.getScalarType().bitsLT(VT.getScalarType()) &&
7135            "Should only be an extending load, not truncating!");
7136     assert(VT.isInteger() == MemVT.isInteger() &&
7137            "Cannot convert from FP to Int or Int -> FP!");
7138     assert(VT.isVector() == MemVT.isVector() &&
7139            "Cannot use an ext load to convert to or from a vector!");
7140     assert((!VT.isVector() ||
7141             VT.getVectorElementCount() == MemVT.getVectorElementCount()) &&
7142            "Cannot use an ext load to change the number of vector elements!");
7143   }
7144 
7145   bool Indexed = AM != ISD::UNINDEXED;
7146   assert((Indexed || Offset.isUndef()) && "Unindexed load with an offset!");
7147 
7148   SDVTList VTs = Indexed ?
7149     getVTList(VT, Ptr.getValueType(), MVT::Other) : getVTList(VT, MVT::Other);
7150   SDValue Ops[] = { Chain, Ptr, Offset };
7151   FoldingSetNodeID ID;
7152   AddNodeIDNode(ID, ISD::LOAD, VTs, Ops);
7153   ID.AddInteger(MemVT.getRawBits());
7154   ID.AddInteger(getSyntheticNodeSubclassData<LoadSDNode>(
7155       dl.getIROrder(), VTs, AM, ExtType, MemVT, MMO));
7156   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7157   void *IP = nullptr;
7158   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7159     cast<LoadSDNode>(E)->refineAlignment(MMO);
7160     return SDValue(E, 0);
7161   }
7162   auto *N = newSDNode<LoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
7163                                   ExtType, MemVT, MMO);
7164   createOperands(N, Ops);
7165 
7166   CSEMap.InsertNode(N, IP);
7167   InsertNode(N);
7168   SDValue V(N, 0);
7169   NewSDValueDbgMsg(V, "Creating new node: ", this);
7170   return V;
7171 }
7172 
7173 SDValue SelectionDAG::getLoad(EVT VT, const SDLoc &dl, SDValue Chain,
7174                               SDValue Ptr, MachinePointerInfo PtrInfo,
7175                               MaybeAlign Alignment,
7176                               MachineMemOperand::Flags MMOFlags,
7177                               const AAMDNodes &AAInfo, const MDNode *Ranges) {
7178   SDValue Undef = getUNDEF(Ptr.getValueType());
7179   return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
7180                  PtrInfo, VT, Alignment, MMOFlags, AAInfo, Ranges);
7181 }
7182 
7183 SDValue SelectionDAG::getLoad(EVT VT, const SDLoc &dl, SDValue Chain,
7184                               SDValue Ptr, MachineMemOperand *MMO) {
7185   SDValue Undef = getUNDEF(Ptr.getValueType());
7186   return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
7187                  VT, MMO);
7188 }
7189 
7190 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl,
7191                                  EVT VT, SDValue Chain, SDValue Ptr,
7192                                  MachinePointerInfo PtrInfo, EVT MemVT,
7193                                  MaybeAlign Alignment,
7194                                  MachineMemOperand::Flags MMOFlags,
7195                                  const AAMDNodes &AAInfo) {
7196   SDValue Undef = getUNDEF(Ptr.getValueType());
7197   return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, PtrInfo,
7198                  MemVT, Alignment, MMOFlags, AAInfo);
7199 }
7200 
7201 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl,
7202                                  EVT VT, SDValue Chain, SDValue Ptr, EVT MemVT,
7203                                  MachineMemOperand *MMO) {
7204   SDValue Undef = getUNDEF(Ptr.getValueType());
7205   return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef,
7206                  MemVT, MMO);
7207 }
7208 
7209 SDValue SelectionDAG::getIndexedLoad(SDValue OrigLoad, const SDLoc &dl,
7210                                      SDValue Base, SDValue Offset,
7211                                      ISD::MemIndexedMode AM) {
7212   LoadSDNode *LD = cast<LoadSDNode>(OrigLoad);
7213   assert(LD->getOffset().isUndef() && "Load is already a indexed load!");
7214   // Don't propagate the invariant or dereferenceable flags.
7215   auto MMOFlags =
7216       LD->getMemOperand()->getFlags() &
7217       ~(MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable);
7218   return getLoad(AM, LD->getExtensionType(), OrigLoad.getValueType(), dl,
7219                  LD->getChain(), Base, Offset, LD->getPointerInfo(),
7220                  LD->getMemoryVT(), LD->getAlign(), MMOFlags, LD->getAAInfo());
7221 }
7222 
7223 SDValue SelectionDAG::getStore(SDValue Chain, const SDLoc &dl, SDValue Val,
7224                                SDValue Ptr, MachinePointerInfo PtrInfo,
7225                                Align Alignment,
7226                                MachineMemOperand::Flags MMOFlags,
7227                                const AAMDNodes &AAInfo) {
7228   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
7229 
7230   MMOFlags |= MachineMemOperand::MOStore;
7231   assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
7232 
7233   if (PtrInfo.V.isNull())
7234     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
7235 
7236   MachineFunction &MF = getMachineFunction();
7237   uint64_t Size =
7238       MemoryLocation::getSizeOrUnknown(Val.getValueType().getStoreSize());
7239   MachineMemOperand *MMO =
7240       MF.getMachineMemOperand(PtrInfo, MMOFlags, Size, Alignment, AAInfo);
7241   return getStore(Chain, dl, Val, Ptr, MMO);
7242 }
7243 
7244 SDValue SelectionDAG::getStore(SDValue Chain, const SDLoc &dl, SDValue Val,
7245                                SDValue Ptr, MachineMemOperand *MMO) {
7246   assert(Chain.getValueType() == MVT::Other &&
7247         "Invalid chain type");
7248   EVT VT = Val.getValueType();
7249   SDVTList VTs = getVTList(MVT::Other);
7250   SDValue Undef = getUNDEF(Ptr.getValueType());
7251   SDValue Ops[] = { Chain, Val, Ptr, Undef };
7252   FoldingSetNodeID ID;
7253   AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
7254   ID.AddInteger(VT.getRawBits());
7255   ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>(
7256       dl.getIROrder(), VTs, ISD::UNINDEXED, false, VT, MMO));
7257   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7258   void *IP = nullptr;
7259   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7260     cast<StoreSDNode>(E)->refineAlignment(MMO);
7261     return SDValue(E, 0);
7262   }
7263   auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
7264                                    ISD::UNINDEXED, false, VT, MMO);
7265   createOperands(N, Ops);
7266 
7267   CSEMap.InsertNode(N, IP);
7268   InsertNode(N);
7269   SDValue V(N, 0);
7270   NewSDValueDbgMsg(V, "Creating new node: ", this);
7271   return V;
7272 }
7273 
7274 SDValue SelectionDAG::getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val,
7275                                     SDValue Ptr, MachinePointerInfo PtrInfo,
7276                                     EVT SVT, Align Alignment,
7277                                     MachineMemOperand::Flags MMOFlags,
7278                                     const AAMDNodes &AAInfo) {
7279   assert(Chain.getValueType() == MVT::Other &&
7280         "Invalid chain type");
7281 
7282   MMOFlags |= MachineMemOperand::MOStore;
7283   assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
7284 
7285   if (PtrInfo.V.isNull())
7286     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
7287 
7288   MachineFunction &MF = getMachineFunction();
7289   MachineMemOperand *MMO = MF.getMachineMemOperand(
7290       PtrInfo, MMOFlags, MemoryLocation::getSizeOrUnknown(SVT.getStoreSize()),
7291       Alignment, AAInfo);
7292   return getTruncStore(Chain, dl, Val, Ptr, SVT, MMO);
7293 }
7294 
7295 SDValue SelectionDAG::getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val,
7296                                     SDValue Ptr, EVT SVT,
7297                                     MachineMemOperand *MMO) {
7298   EVT VT = Val.getValueType();
7299 
7300   assert(Chain.getValueType() == MVT::Other &&
7301         "Invalid chain type");
7302   if (VT == SVT)
7303     return getStore(Chain, dl, Val, Ptr, MMO);
7304 
7305   assert(SVT.getScalarType().bitsLT(VT.getScalarType()) &&
7306          "Should only be a truncating store, not extending!");
7307   assert(VT.isInteger() == SVT.isInteger() &&
7308          "Can't do FP-INT conversion!");
7309   assert(VT.isVector() == SVT.isVector() &&
7310          "Cannot use trunc store to convert to or from a vector!");
7311   assert((!VT.isVector() ||
7312           VT.getVectorElementCount() == SVT.getVectorElementCount()) &&
7313          "Cannot use trunc store to change the number of vector elements!");
7314 
7315   SDVTList VTs = getVTList(MVT::Other);
7316   SDValue Undef = getUNDEF(Ptr.getValueType());
7317   SDValue Ops[] = { Chain, Val, Ptr, Undef };
7318   FoldingSetNodeID ID;
7319   AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
7320   ID.AddInteger(SVT.getRawBits());
7321   ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>(
7322       dl.getIROrder(), VTs, ISD::UNINDEXED, true, SVT, MMO));
7323   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7324   void *IP = nullptr;
7325   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7326     cast<StoreSDNode>(E)->refineAlignment(MMO);
7327     return SDValue(E, 0);
7328   }
7329   auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
7330                                    ISD::UNINDEXED, true, SVT, MMO);
7331   createOperands(N, Ops);
7332 
7333   CSEMap.InsertNode(N, IP);
7334   InsertNode(N);
7335   SDValue V(N, 0);
7336   NewSDValueDbgMsg(V, "Creating new node: ", this);
7337   return V;
7338 }
7339 
7340 SDValue SelectionDAG::getIndexedStore(SDValue OrigStore, const SDLoc &dl,
7341                                       SDValue Base, SDValue Offset,
7342                                       ISD::MemIndexedMode AM) {
7343   StoreSDNode *ST = cast<StoreSDNode>(OrigStore);
7344   assert(ST->getOffset().isUndef() && "Store is already a indexed store!");
7345   SDVTList VTs = getVTList(Base.getValueType(), MVT::Other);
7346   SDValue Ops[] = { ST->getChain(), ST->getValue(), Base, Offset };
7347   FoldingSetNodeID ID;
7348   AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
7349   ID.AddInteger(ST->getMemoryVT().getRawBits());
7350   ID.AddInteger(ST->getRawSubclassData());
7351   ID.AddInteger(ST->getPointerInfo().getAddrSpace());
7352   void *IP = nullptr;
7353   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
7354     return SDValue(E, 0);
7355 
7356   auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
7357                                    ST->isTruncatingStore(), ST->getMemoryVT(),
7358                                    ST->getMemOperand());
7359   createOperands(N, Ops);
7360 
7361   CSEMap.InsertNode(N, IP);
7362   InsertNode(N);
7363   SDValue V(N, 0);
7364   NewSDValueDbgMsg(V, "Creating new node: ", this);
7365   return V;
7366 }
7367 
7368 SDValue SelectionDAG::getMaskedLoad(EVT VT, const SDLoc &dl, SDValue Chain,
7369                                     SDValue Base, SDValue Offset, SDValue Mask,
7370                                     SDValue PassThru, EVT MemVT,
7371                                     MachineMemOperand *MMO,
7372                                     ISD::MemIndexedMode AM,
7373                                     ISD::LoadExtType ExtTy, bool isExpanding) {
7374   bool Indexed = AM != ISD::UNINDEXED;
7375   assert((Indexed || Offset.isUndef()) &&
7376          "Unindexed masked load with an offset!");
7377   SDVTList VTs = Indexed ? getVTList(VT, Base.getValueType(), MVT::Other)
7378                          : getVTList(VT, MVT::Other);
7379   SDValue Ops[] = {Chain, Base, Offset, Mask, PassThru};
7380   FoldingSetNodeID ID;
7381   AddNodeIDNode(ID, ISD::MLOAD, VTs, Ops);
7382   ID.AddInteger(MemVT.getRawBits());
7383   ID.AddInteger(getSyntheticNodeSubclassData<MaskedLoadSDNode>(
7384       dl.getIROrder(), VTs, AM, ExtTy, isExpanding, MemVT, MMO));
7385   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7386   void *IP = nullptr;
7387   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7388     cast<MaskedLoadSDNode>(E)->refineAlignment(MMO);
7389     return SDValue(E, 0);
7390   }
7391   auto *N = newSDNode<MaskedLoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
7392                                         AM, ExtTy, isExpanding, MemVT, MMO);
7393   createOperands(N, Ops);
7394 
7395   CSEMap.InsertNode(N, IP);
7396   InsertNode(N);
7397   SDValue V(N, 0);
7398   NewSDValueDbgMsg(V, "Creating new node: ", this);
7399   return V;
7400 }
7401 
7402 SDValue SelectionDAG::getIndexedMaskedLoad(SDValue OrigLoad, const SDLoc &dl,
7403                                            SDValue Base, SDValue Offset,
7404                                            ISD::MemIndexedMode AM) {
7405   MaskedLoadSDNode *LD = cast<MaskedLoadSDNode>(OrigLoad);
7406   assert(LD->getOffset().isUndef() && "Masked load is already a indexed load!");
7407   return getMaskedLoad(OrigLoad.getValueType(), dl, LD->getChain(), Base,
7408                        Offset, LD->getMask(), LD->getPassThru(),
7409                        LD->getMemoryVT(), LD->getMemOperand(), AM,
7410                        LD->getExtensionType(), LD->isExpandingLoad());
7411 }
7412 
7413 SDValue SelectionDAG::getMaskedStore(SDValue Chain, const SDLoc &dl,
7414                                      SDValue Val, SDValue Base, SDValue Offset,
7415                                      SDValue Mask, EVT MemVT,
7416                                      MachineMemOperand *MMO,
7417                                      ISD::MemIndexedMode AM, bool IsTruncating,
7418                                      bool IsCompressing) {
7419   assert(Chain.getValueType() == MVT::Other &&
7420         "Invalid chain type");
7421   bool Indexed = AM != ISD::UNINDEXED;
7422   assert((Indexed || Offset.isUndef()) &&
7423          "Unindexed masked store with an offset!");
7424   SDVTList VTs = Indexed ? getVTList(Base.getValueType(), MVT::Other)
7425                          : getVTList(MVT::Other);
7426   SDValue Ops[] = {Chain, Val, Base, Offset, Mask};
7427   FoldingSetNodeID ID;
7428   AddNodeIDNode(ID, ISD::MSTORE, VTs, Ops);
7429   ID.AddInteger(MemVT.getRawBits());
7430   ID.AddInteger(getSyntheticNodeSubclassData<MaskedStoreSDNode>(
7431       dl.getIROrder(), VTs, AM, IsTruncating, IsCompressing, MemVT, MMO));
7432   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7433   void *IP = nullptr;
7434   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7435     cast<MaskedStoreSDNode>(E)->refineAlignment(MMO);
7436     return SDValue(E, 0);
7437   }
7438   auto *N =
7439       newSDNode<MaskedStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
7440                                    IsTruncating, IsCompressing, MemVT, MMO);
7441   createOperands(N, Ops);
7442 
7443   CSEMap.InsertNode(N, IP);
7444   InsertNode(N);
7445   SDValue V(N, 0);
7446   NewSDValueDbgMsg(V, "Creating new node: ", this);
7447   return V;
7448 }
7449 
7450 SDValue SelectionDAG::getIndexedMaskedStore(SDValue OrigStore, const SDLoc &dl,
7451                                             SDValue Base, SDValue Offset,
7452                                             ISD::MemIndexedMode AM) {
7453   MaskedStoreSDNode *ST = cast<MaskedStoreSDNode>(OrigStore);
7454   assert(ST->getOffset().isUndef() &&
7455          "Masked store is already a indexed store!");
7456   return getMaskedStore(ST->getChain(), dl, ST->getValue(), Base, Offset,
7457                         ST->getMask(), ST->getMemoryVT(), ST->getMemOperand(),
7458                         AM, ST->isTruncatingStore(), ST->isCompressingStore());
7459 }
7460 
7461 SDValue SelectionDAG::getMaskedGather(SDVTList VTs, EVT VT, const SDLoc &dl,
7462                                       ArrayRef<SDValue> Ops,
7463                                       MachineMemOperand *MMO,
7464                                       ISD::MemIndexType IndexType,
7465                                       ISD::LoadExtType ExtTy) {
7466   assert(Ops.size() == 6 && "Incompatible number of operands");
7467 
7468   FoldingSetNodeID ID;
7469   AddNodeIDNode(ID, ISD::MGATHER, VTs, Ops);
7470   ID.AddInteger(VT.getRawBits());
7471   ID.AddInteger(getSyntheticNodeSubclassData<MaskedGatherSDNode>(
7472       dl.getIROrder(), VTs, VT, MMO, IndexType, ExtTy));
7473   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7474   void *IP = nullptr;
7475   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7476     cast<MaskedGatherSDNode>(E)->refineAlignment(MMO);
7477     return SDValue(E, 0);
7478   }
7479 
7480   IndexType = TLI->getCanonicalIndexType(IndexType, VT, Ops[4]);
7481   auto *N = newSDNode<MaskedGatherSDNode>(dl.getIROrder(), dl.getDebugLoc(),
7482                                           VTs, VT, MMO, IndexType, ExtTy);
7483   createOperands(N, Ops);
7484 
7485   assert(N->getPassThru().getValueType() == N->getValueType(0) &&
7486          "Incompatible type of the PassThru value in MaskedGatherSDNode");
7487   assert(N->getMask().getValueType().getVectorElementCount() ==
7488              N->getValueType(0).getVectorElementCount() &&
7489          "Vector width mismatch between mask and data");
7490   assert(N->getIndex().getValueType().getVectorElementCount().isScalable() ==
7491              N->getValueType(0).getVectorElementCount().isScalable() &&
7492          "Scalable flags of index and data do not match");
7493   assert(ElementCount::isKnownGE(
7494              N->getIndex().getValueType().getVectorElementCount(),
7495              N->getValueType(0).getVectorElementCount()) &&
7496          "Vector width mismatch between index and data");
7497   assert(isa<ConstantSDNode>(N->getScale()) &&
7498          cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() &&
7499          "Scale should be a constant power of 2");
7500 
7501   CSEMap.InsertNode(N, IP);
7502   InsertNode(N);
7503   SDValue V(N, 0);
7504   NewSDValueDbgMsg(V, "Creating new node: ", this);
7505   return V;
7506 }
7507 
7508 SDValue SelectionDAG::getMaskedScatter(SDVTList VTs, EVT VT, const SDLoc &dl,
7509                                        ArrayRef<SDValue> Ops,
7510                                        MachineMemOperand *MMO,
7511                                        ISD::MemIndexType IndexType,
7512                                        bool IsTrunc) {
7513   assert(Ops.size() == 6 && "Incompatible number of operands");
7514 
7515   FoldingSetNodeID ID;
7516   AddNodeIDNode(ID, ISD::MSCATTER, VTs, Ops);
7517   ID.AddInteger(VT.getRawBits());
7518   ID.AddInteger(getSyntheticNodeSubclassData<MaskedScatterSDNode>(
7519       dl.getIROrder(), VTs, VT, MMO, IndexType, IsTrunc));
7520   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7521   void *IP = nullptr;
7522   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7523     cast<MaskedScatterSDNode>(E)->refineAlignment(MMO);
7524     return SDValue(E, 0);
7525   }
7526 
7527   IndexType = TLI->getCanonicalIndexType(IndexType, VT, Ops[4]);
7528   auto *N = newSDNode<MaskedScatterSDNode>(dl.getIROrder(), dl.getDebugLoc(),
7529                                            VTs, VT, MMO, IndexType, IsTrunc);
7530   createOperands(N, Ops);
7531 
7532   assert(N->getMask().getValueType().getVectorElementCount() ==
7533              N->getValue().getValueType().getVectorElementCount() &&
7534          "Vector width mismatch between mask and data");
7535   assert(
7536       N->getIndex().getValueType().getVectorElementCount().isScalable() ==
7537           N->getValue().getValueType().getVectorElementCount().isScalable() &&
7538       "Scalable flags of index and data do not match");
7539   assert(ElementCount::isKnownGE(
7540              N->getIndex().getValueType().getVectorElementCount(),
7541              N->getValue().getValueType().getVectorElementCount()) &&
7542          "Vector width mismatch between index and data");
7543   assert(isa<ConstantSDNode>(N->getScale()) &&
7544          cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() &&
7545          "Scale should be a constant power of 2");
7546 
7547   CSEMap.InsertNode(N, IP);
7548   InsertNode(N);
7549   SDValue V(N, 0);
7550   NewSDValueDbgMsg(V, "Creating new node: ", this);
7551   return V;
7552 }
7553 
7554 SDValue SelectionDAG::simplifySelect(SDValue Cond, SDValue T, SDValue F) {
7555   // select undef, T, F --> T (if T is a constant), otherwise F
7556   // select, ?, undef, F --> F
7557   // select, ?, T, undef --> T
7558   if (Cond.isUndef())
7559     return isConstantValueOfAnyType(T) ? T : F;
7560   if (T.isUndef())
7561     return F;
7562   if (F.isUndef())
7563     return T;
7564 
7565   // select true, T, F --> T
7566   // select false, T, F --> F
7567   if (auto *CondC = dyn_cast<ConstantSDNode>(Cond))
7568     return CondC->isNullValue() ? F : T;
7569 
7570   // TODO: This should simplify VSELECT with constant condition using something
7571   // like this (but check boolean contents to be complete?):
7572   //  if (ISD::isBuildVectorAllOnes(Cond.getNode()))
7573   //    return T;
7574   //  if (ISD::isBuildVectorAllZeros(Cond.getNode()))
7575   //    return F;
7576 
7577   // select ?, T, T --> T
7578   if (T == F)
7579     return T;
7580 
7581   return SDValue();
7582 }
7583 
7584 SDValue SelectionDAG::simplifyShift(SDValue X, SDValue Y) {
7585   // shift undef, Y --> 0 (can always assume that the undef value is 0)
7586   if (X.isUndef())
7587     return getConstant(0, SDLoc(X.getNode()), X.getValueType());
7588   // shift X, undef --> undef (because it may shift by the bitwidth)
7589   if (Y.isUndef())
7590     return getUNDEF(X.getValueType());
7591 
7592   // shift 0, Y --> 0
7593   // shift X, 0 --> X
7594   if (isNullOrNullSplat(X) || isNullOrNullSplat(Y))
7595     return X;
7596 
7597   // shift X, C >= bitwidth(X) --> undef
7598   // All vector elements must be too big (or undef) to avoid partial undefs.
7599   auto isShiftTooBig = [X](ConstantSDNode *Val) {
7600     return !Val || Val->getAPIntValue().uge(X.getScalarValueSizeInBits());
7601   };
7602   if (ISD::matchUnaryPredicate(Y, isShiftTooBig, true))
7603     return getUNDEF(X.getValueType());
7604 
7605   return SDValue();
7606 }
7607 
7608 SDValue SelectionDAG::simplifyFPBinop(unsigned Opcode, SDValue X, SDValue Y,
7609                                       SDNodeFlags Flags) {
7610   // If this operation has 'nnan' or 'ninf' and at least 1 disallowed operand
7611   // (an undef operand can be chosen to be Nan/Inf), then the result of this
7612   // operation is poison. That result can be relaxed to undef.
7613   ConstantFPSDNode *XC = isConstOrConstSplatFP(X, /* AllowUndefs */ true);
7614   ConstantFPSDNode *YC = isConstOrConstSplatFP(Y, /* AllowUndefs */ true);
7615   bool HasNan = (XC && XC->getValueAPF().isNaN()) ||
7616                 (YC && YC->getValueAPF().isNaN());
7617   bool HasInf = (XC && XC->getValueAPF().isInfinity()) ||
7618                 (YC && YC->getValueAPF().isInfinity());
7619 
7620   if (Flags.hasNoNaNs() && (HasNan || X.isUndef() || Y.isUndef()))
7621     return getUNDEF(X.getValueType());
7622 
7623   if (Flags.hasNoInfs() && (HasInf || X.isUndef() || Y.isUndef()))
7624     return getUNDEF(X.getValueType());
7625 
7626   if (!YC)
7627     return SDValue();
7628 
7629   // X + -0.0 --> X
7630   if (Opcode == ISD::FADD)
7631     if (YC->getValueAPF().isNegZero())
7632       return X;
7633 
7634   // X - +0.0 --> X
7635   if (Opcode == ISD::FSUB)
7636     if (YC->getValueAPF().isPosZero())
7637       return X;
7638 
7639   // X * 1.0 --> X
7640   // X / 1.0 --> X
7641   if (Opcode == ISD::FMUL || Opcode == ISD::FDIV)
7642     if (YC->getValueAPF().isExactlyValue(1.0))
7643       return X;
7644 
7645   // X * 0.0 --> 0.0
7646   if (Opcode == ISD::FMUL && Flags.hasNoNaNs() && Flags.hasNoSignedZeros())
7647     if (YC->getValueAPF().isZero())
7648       return getConstantFP(0.0, SDLoc(Y), Y.getValueType());
7649 
7650   return SDValue();
7651 }
7652 
7653 SDValue SelectionDAG::getVAArg(EVT VT, const SDLoc &dl, SDValue Chain,
7654                                SDValue Ptr, SDValue SV, unsigned Align) {
7655   SDValue Ops[] = { Chain, Ptr, SV, getTargetConstant(Align, dl, MVT::i32) };
7656   return getNode(ISD::VAARG, dl, getVTList(VT, MVT::Other), Ops);
7657 }
7658 
7659 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
7660                               ArrayRef<SDUse> Ops) {
7661   switch (Ops.size()) {
7662   case 0: return getNode(Opcode, DL, VT);
7663   case 1: return getNode(Opcode, DL, VT, static_cast<const SDValue>(Ops[0]));
7664   case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1]);
7665   case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2]);
7666   default: break;
7667   }
7668 
7669   // Copy from an SDUse array into an SDValue array for use with
7670   // the regular getNode logic.
7671   SmallVector<SDValue, 8> NewOps(Ops.begin(), Ops.end());
7672   return getNode(Opcode, DL, VT, NewOps);
7673 }
7674 
7675 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
7676                               ArrayRef<SDValue> Ops) {
7677   SDNodeFlags Flags;
7678   if (Inserter)
7679     Flags = Inserter->getFlags();
7680   return getNode(Opcode, DL, VT, Ops, Flags);
7681 }
7682 
7683 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
7684                               ArrayRef<SDValue> Ops, const SDNodeFlags Flags) {
7685   unsigned NumOps = Ops.size();
7686   switch (NumOps) {
7687   case 0: return getNode(Opcode, DL, VT);
7688   case 1: return getNode(Opcode, DL, VT, Ops[0], Flags);
7689   case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Flags);
7690   case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2], Flags);
7691   default: break;
7692   }
7693 
7694 #ifndef NDEBUG
7695   for (auto &Op : Ops)
7696     assert(Op.getOpcode() != ISD::DELETED_NODE &&
7697            "Operand is DELETED_NODE!");
7698 #endif
7699 
7700   switch (Opcode) {
7701   default: break;
7702   case ISD::BUILD_VECTOR:
7703     // Attempt to simplify BUILD_VECTOR.
7704     if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
7705       return V;
7706     break;
7707   case ISD::CONCAT_VECTORS:
7708     if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this))
7709       return V;
7710     break;
7711   case ISD::SELECT_CC:
7712     assert(NumOps == 5 && "SELECT_CC takes 5 operands!");
7713     assert(Ops[0].getValueType() == Ops[1].getValueType() &&
7714            "LHS and RHS of condition must have same type!");
7715     assert(Ops[2].getValueType() == Ops[3].getValueType() &&
7716            "True and False arms of SelectCC must have same type!");
7717     assert(Ops[2].getValueType() == VT &&
7718            "select_cc node must be of same type as true and false value!");
7719     break;
7720   case ISD::BR_CC:
7721     assert(NumOps == 5 && "BR_CC takes 5 operands!");
7722     assert(Ops[2].getValueType() == Ops[3].getValueType() &&
7723            "LHS/RHS of comparison should match types!");
7724     break;
7725   }
7726 
7727   // Memoize nodes.
7728   SDNode *N;
7729   SDVTList VTs = getVTList(VT);
7730 
7731   if (VT != MVT::Glue) {
7732     FoldingSetNodeID ID;
7733     AddNodeIDNode(ID, Opcode, VTs, Ops);
7734     void *IP = nullptr;
7735 
7736     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
7737       return SDValue(E, 0);
7738 
7739     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
7740     createOperands(N, Ops);
7741 
7742     CSEMap.InsertNode(N, IP);
7743   } else {
7744     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
7745     createOperands(N, Ops);
7746   }
7747 
7748   N->setFlags(Flags);
7749   InsertNode(N);
7750   SDValue V(N, 0);
7751   NewSDValueDbgMsg(V, "Creating new node: ", this);
7752   return V;
7753 }
7754 
7755 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL,
7756                               ArrayRef<EVT> ResultTys, ArrayRef<SDValue> Ops) {
7757   return getNode(Opcode, DL, getVTList(ResultTys), Ops);
7758 }
7759 
7760 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
7761                               ArrayRef<SDValue> Ops) {
7762   SDNodeFlags Flags;
7763   if (Inserter)
7764     Flags = Inserter->getFlags();
7765   return getNode(Opcode, DL, VTList, Ops, Flags);
7766 }
7767 
7768 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
7769                               ArrayRef<SDValue> Ops, const SDNodeFlags Flags) {
7770   if (VTList.NumVTs == 1)
7771     return getNode(Opcode, DL, VTList.VTs[0], Ops);
7772 
7773 #ifndef NDEBUG
7774   for (auto &Op : Ops)
7775     assert(Op.getOpcode() != ISD::DELETED_NODE &&
7776            "Operand is DELETED_NODE!");
7777 #endif
7778 
7779   switch (Opcode) {
7780   case ISD::STRICT_FP_EXTEND:
7781     assert(VTList.NumVTs == 2 && Ops.size() == 2 &&
7782            "Invalid STRICT_FP_EXTEND!");
7783     assert(VTList.VTs[0].isFloatingPoint() &&
7784            Ops[1].getValueType().isFloatingPoint() && "Invalid FP cast!");
7785     assert(VTList.VTs[0].isVector() == Ops[1].getValueType().isVector() &&
7786            "STRICT_FP_EXTEND result type should be vector iff the operand "
7787            "type is vector!");
7788     assert((!VTList.VTs[0].isVector() ||
7789             VTList.VTs[0].getVectorNumElements() ==
7790             Ops[1].getValueType().getVectorNumElements()) &&
7791            "Vector element count mismatch!");
7792     assert(Ops[1].getValueType().bitsLT(VTList.VTs[0]) &&
7793            "Invalid fpext node, dst <= src!");
7794     break;
7795   case ISD::STRICT_FP_ROUND:
7796     assert(VTList.NumVTs == 2 && Ops.size() == 3 && "Invalid STRICT_FP_ROUND!");
7797     assert(VTList.VTs[0].isVector() == Ops[1].getValueType().isVector() &&
7798            "STRICT_FP_ROUND result type should be vector iff the operand "
7799            "type is vector!");
7800     assert((!VTList.VTs[0].isVector() ||
7801             VTList.VTs[0].getVectorNumElements() ==
7802             Ops[1].getValueType().getVectorNumElements()) &&
7803            "Vector element count mismatch!");
7804     assert(VTList.VTs[0].isFloatingPoint() &&
7805            Ops[1].getValueType().isFloatingPoint() &&
7806            VTList.VTs[0].bitsLT(Ops[1].getValueType()) &&
7807            isa<ConstantSDNode>(Ops[2]) &&
7808            (cast<ConstantSDNode>(Ops[2])->getZExtValue() == 0 ||
7809             cast<ConstantSDNode>(Ops[2])->getZExtValue() == 1) &&
7810            "Invalid STRICT_FP_ROUND!");
7811     break;
7812 #if 0
7813   // FIXME: figure out how to safely handle things like
7814   // int foo(int x) { return 1 << (x & 255); }
7815   // int bar() { return foo(256); }
7816   case ISD::SRA_PARTS:
7817   case ISD::SRL_PARTS:
7818   case ISD::SHL_PARTS:
7819     if (N3.getOpcode() == ISD::SIGN_EXTEND_INREG &&
7820         cast<VTSDNode>(N3.getOperand(1))->getVT() != MVT::i1)
7821       return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0));
7822     else if (N3.getOpcode() == ISD::AND)
7823       if (ConstantSDNode *AndRHS = dyn_cast<ConstantSDNode>(N3.getOperand(1))) {
7824         // If the and is only masking out bits that cannot effect the shift,
7825         // eliminate the and.
7826         unsigned NumBits = VT.getScalarSizeInBits()*2;
7827         if ((AndRHS->getValue() & (NumBits-1)) == NumBits-1)
7828           return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0));
7829       }
7830     break;
7831 #endif
7832   }
7833 
7834   // Memoize the node unless it returns a flag.
7835   SDNode *N;
7836   if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) {
7837     FoldingSetNodeID ID;
7838     AddNodeIDNode(ID, Opcode, VTList, Ops);
7839     void *IP = nullptr;
7840     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
7841       return SDValue(E, 0);
7842 
7843     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList);
7844     createOperands(N, Ops);
7845     CSEMap.InsertNode(N, IP);
7846   } else {
7847     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList);
7848     createOperands(N, Ops);
7849   }
7850 
7851   N->setFlags(Flags);
7852   InsertNode(N);
7853   SDValue V(N, 0);
7854   NewSDValueDbgMsg(V, "Creating new node: ", this);
7855   return V;
7856 }
7857 
7858 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL,
7859                               SDVTList VTList) {
7860   return getNode(Opcode, DL, VTList, None);
7861 }
7862 
7863 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
7864                               SDValue N1) {
7865   SDValue Ops[] = { N1 };
7866   return getNode(Opcode, DL, VTList, Ops);
7867 }
7868 
7869 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
7870                               SDValue N1, SDValue N2) {
7871   SDValue Ops[] = { N1, N2 };
7872   return getNode(Opcode, DL, VTList, Ops);
7873 }
7874 
7875 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
7876                               SDValue N1, SDValue N2, SDValue N3) {
7877   SDValue Ops[] = { N1, N2, N3 };
7878   return getNode(Opcode, DL, VTList, Ops);
7879 }
7880 
7881 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
7882                               SDValue N1, SDValue N2, SDValue N3, SDValue N4) {
7883   SDValue Ops[] = { N1, N2, N3, N4 };
7884   return getNode(Opcode, DL, VTList, Ops);
7885 }
7886 
7887 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
7888                               SDValue N1, SDValue N2, SDValue N3, SDValue N4,
7889                               SDValue N5) {
7890   SDValue Ops[] = { N1, N2, N3, N4, N5 };
7891   return getNode(Opcode, DL, VTList, Ops);
7892 }
7893 
7894 SDVTList SelectionDAG::getVTList(EVT VT) {
7895   return makeVTList(SDNode::getValueTypeList(VT), 1);
7896 }
7897 
7898 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2) {
7899   FoldingSetNodeID ID;
7900   ID.AddInteger(2U);
7901   ID.AddInteger(VT1.getRawBits());
7902   ID.AddInteger(VT2.getRawBits());
7903 
7904   void *IP = nullptr;
7905   SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
7906   if (!Result) {
7907     EVT *Array = Allocator.Allocate<EVT>(2);
7908     Array[0] = VT1;
7909     Array[1] = VT2;
7910     Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 2);
7911     VTListMap.InsertNode(Result, IP);
7912   }
7913   return Result->getSDVTList();
7914 }
7915 
7916 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3) {
7917   FoldingSetNodeID ID;
7918   ID.AddInteger(3U);
7919   ID.AddInteger(VT1.getRawBits());
7920   ID.AddInteger(VT2.getRawBits());
7921   ID.AddInteger(VT3.getRawBits());
7922 
7923   void *IP = nullptr;
7924   SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
7925   if (!Result) {
7926     EVT *Array = Allocator.Allocate<EVT>(3);
7927     Array[0] = VT1;
7928     Array[1] = VT2;
7929     Array[2] = VT3;
7930     Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 3);
7931     VTListMap.InsertNode(Result, IP);
7932   }
7933   return Result->getSDVTList();
7934 }
7935 
7936 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3, EVT VT4) {
7937   FoldingSetNodeID ID;
7938   ID.AddInteger(4U);
7939   ID.AddInteger(VT1.getRawBits());
7940   ID.AddInteger(VT2.getRawBits());
7941   ID.AddInteger(VT3.getRawBits());
7942   ID.AddInteger(VT4.getRawBits());
7943 
7944   void *IP = nullptr;
7945   SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
7946   if (!Result) {
7947     EVT *Array = Allocator.Allocate<EVT>(4);
7948     Array[0] = VT1;
7949     Array[1] = VT2;
7950     Array[2] = VT3;
7951     Array[3] = VT4;
7952     Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 4);
7953     VTListMap.InsertNode(Result, IP);
7954   }
7955   return Result->getSDVTList();
7956 }
7957 
7958 SDVTList SelectionDAG::getVTList(ArrayRef<EVT> VTs) {
7959   unsigned NumVTs = VTs.size();
7960   FoldingSetNodeID ID;
7961   ID.AddInteger(NumVTs);
7962   for (unsigned index = 0; index < NumVTs; index++) {
7963     ID.AddInteger(VTs[index].getRawBits());
7964   }
7965 
7966   void *IP = nullptr;
7967   SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
7968   if (!Result) {
7969     EVT *Array = Allocator.Allocate<EVT>(NumVTs);
7970     llvm::copy(VTs, Array);
7971     Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, NumVTs);
7972     VTListMap.InsertNode(Result, IP);
7973   }
7974   return Result->getSDVTList();
7975 }
7976 
7977 
7978 /// UpdateNodeOperands - *Mutate* the specified node in-place to have the
7979 /// specified operands.  If the resultant node already exists in the DAG,
7980 /// this does not modify the specified node, instead it returns the node that
7981 /// already exists.  If the resultant node does not exist in the DAG, the
7982 /// input node is returned.  As a degenerate case, if you specify the same
7983 /// input operands as the node already has, the input node is returned.
7984 SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op) {
7985   assert(N->getNumOperands() == 1 && "Update with wrong number of operands");
7986 
7987   // Check to see if there is no change.
7988   if (Op == N->getOperand(0)) return N;
7989 
7990   // See if the modified node already exists.
7991   void *InsertPos = nullptr;
7992   if (SDNode *Existing = FindModifiedNodeSlot(N, Op, InsertPos))
7993     return Existing;
7994 
7995   // Nope it doesn't.  Remove the node from its current place in the maps.
7996   if (InsertPos)
7997     if (!RemoveNodeFromCSEMaps(N))
7998       InsertPos = nullptr;
7999 
8000   // Now we update the operands.
8001   N->OperandList[0].set(Op);
8002 
8003   updateDivergence(N);
8004   // If this gets put into a CSE map, add it.
8005   if (InsertPos) CSEMap.InsertNode(N, InsertPos);
8006   return N;
8007 }
8008 
8009 SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2) {
8010   assert(N->getNumOperands() == 2 && "Update with wrong number of operands");
8011 
8012   // Check to see if there is no change.
8013   if (Op1 == N->getOperand(0) && Op2 == N->getOperand(1))
8014     return N;   // No operands changed, just return the input node.
8015 
8016   // See if the modified node already exists.
8017   void *InsertPos = nullptr;
8018   if (SDNode *Existing = FindModifiedNodeSlot(N, Op1, Op2, InsertPos))
8019     return Existing;
8020 
8021   // Nope it doesn't.  Remove the node from its current place in the maps.
8022   if (InsertPos)
8023     if (!RemoveNodeFromCSEMaps(N))
8024       InsertPos = nullptr;
8025 
8026   // Now we update the operands.
8027   if (N->OperandList[0] != Op1)
8028     N->OperandList[0].set(Op1);
8029   if (N->OperandList[1] != Op2)
8030     N->OperandList[1].set(Op2);
8031 
8032   updateDivergence(N);
8033   // If this gets put into a CSE map, add it.
8034   if (InsertPos) CSEMap.InsertNode(N, InsertPos);
8035   return N;
8036 }
8037 
8038 SDNode *SelectionDAG::
8039 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2, SDValue Op3) {
8040   SDValue Ops[] = { Op1, Op2, Op3 };
8041   return UpdateNodeOperands(N, Ops);
8042 }
8043 
8044 SDNode *SelectionDAG::
8045 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2,
8046                    SDValue Op3, SDValue Op4) {
8047   SDValue Ops[] = { Op1, Op2, Op3, Op4 };
8048   return UpdateNodeOperands(N, Ops);
8049 }
8050 
8051 SDNode *SelectionDAG::
8052 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2,
8053                    SDValue Op3, SDValue Op4, SDValue Op5) {
8054   SDValue Ops[] = { Op1, Op2, Op3, Op4, Op5 };
8055   return UpdateNodeOperands(N, Ops);
8056 }
8057 
8058 SDNode *SelectionDAG::
8059 UpdateNodeOperands(SDNode *N, ArrayRef<SDValue> Ops) {
8060   unsigned NumOps = Ops.size();
8061   assert(N->getNumOperands() == NumOps &&
8062          "Update with wrong number of operands");
8063 
8064   // If no operands changed just return the input node.
8065   if (std::equal(Ops.begin(), Ops.end(), N->op_begin()))
8066     return N;
8067 
8068   // See if the modified node already exists.
8069   void *InsertPos = nullptr;
8070   if (SDNode *Existing = FindModifiedNodeSlot(N, Ops, InsertPos))
8071     return Existing;
8072 
8073   // Nope it doesn't.  Remove the node from its current place in the maps.
8074   if (InsertPos)
8075     if (!RemoveNodeFromCSEMaps(N))
8076       InsertPos = nullptr;
8077 
8078   // Now we update the operands.
8079   for (unsigned i = 0; i != NumOps; ++i)
8080     if (N->OperandList[i] != Ops[i])
8081       N->OperandList[i].set(Ops[i]);
8082 
8083   updateDivergence(N);
8084   // If this gets put into a CSE map, add it.
8085   if (InsertPos) CSEMap.InsertNode(N, InsertPos);
8086   return N;
8087 }
8088 
8089 /// DropOperands - Release the operands and set this node to have
8090 /// zero operands.
8091 void SDNode::DropOperands() {
8092   // Unlike the code in MorphNodeTo that does this, we don't need to
8093   // watch for dead nodes here.
8094   for (op_iterator I = op_begin(), E = op_end(); I != E; ) {
8095     SDUse &Use = *I++;
8096     Use.set(SDValue());
8097   }
8098 }
8099 
8100 void SelectionDAG::setNodeMemRefs(MachineSDNode *N,
8101                                   ArrayRef<MachineMemOperand *> NewMemRefs) {
8102   if (NewMemRefs.empty()) {
8103     N->clearMemRefs();
8104     return;
8105   }
8106 
8107   // Check if we can avoid allocating by storing a single reference directly.
8108   if (NewMemRefs.size() == 1) {
8109     N->MemRefs = NewMemRefs[0];
8110     N->NumMemRefs = 1;
8111     return;
8112   }
8113 
8114   MachineMemOperand **MemRefsBuffer =
8115       Allocator.template Allocate<MachineMemOperand *>(NewMemRefs.size());
8116   llvm::copy(NewMemRefs, MemRefsBuffer);
8117   N->MemRefs = MemRefsBuffer;
8118   N->NumMemRefs = static_cast<int>(NewMemRefs.size());
8119 }
8120 
8121 /// SelectNodeTo - These are wrappers around MorphNodeTo that accept a
8122 /// machine opcode.
8123 ///
8124 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8125                                    EVT VT) {
8126   SDVTList VTs = getVTList(VT);
8127   return SelectNodeTo(N, MachineOpc, VTs, None);
8128 }
8129 
8130 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8131                                    EVT VT, SDValue Op1) {
8132   SDVTList VTs = getVTList(VT);
8133   SDValue Ops[] = { Op1 };
8134   return SelectNodeTo(N, MachineOpc, VTs, Ops);
8135 }
8136 
8137 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8138                                    EVT VT, SDValue Op1,
8139                                    SDValue Op2) {
8140   SDVTList VTs = getVTList(VT);
8141   SDValue Ops[] = { Op1, Op2 };
8142   return SelectNodeTo(N, MachineOpc, VTs, Ops);
8143 }
8144 
8145 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8146                                    EVT VT, SDValue Op1,
8147                                    SDValue Op2, SDValue Op3) {
8148   SDVTList VTs = getVTList(VT);
8149   SDValue Ops[] = { Op1, Op2, Op3 };
8150   return SelectNodeTo(N, MachineOpc, VTs, Ops);
8151 }
8152 
8153 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8154                                    EVT VT, ArrayRef<SDValue> Ops) {
8155   SDVTList VTs = getVTList(VT);
8156   return SelectNodeTo(N, MachineOpc, VTs, Ops);
8157 }
8158 
8159 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8160                                    EVT VT1, EVT VT2, ArrayRef<SDValue> Ops) {
8161   SDVTList VTs = getVTList(VT1, VT2);
8162   return SelectNodeTo(N, MachineOpc, VTs, Ops);
8163 }
8164 
8165 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8166                                    EVT VT1, EVT VT2) {
8167   SDVTList VTs = getVTList(VT1, VT2);
8168   return SelectNodeTo(N, MachineOpc, VTs, None);
8169 }
8170 
8171 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8172                                    EVT VT1, EVT VT2, EVT VT3,
8173                                    ArrayRef<SDValue> Ops) {
8174   SDVTList VTs = getVTList(VT1, VT2, VT3);
8175   return SelectNodeTo(N, MachineOpc, VTs, Ops);
8176 }
8177 
8178 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8179                                    EVT VT1, EVT VT2,
8180                                    SDValue Op1, SDValue Op2) {
8181   SDVTList VTs = getVTList(VT1, VT2);
8182   SDValue Ops[] = { Op1, Op2 };
8183   return SelectNodeTo(N, MachineOpc, VTs, Ops);
8184 }
8185 
8186 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8187                                    SDVTList VTs,ArrayRef<SDValue> Ops) {
8188   SDNode *New = MorphNodeTo(N, ~MachineOpc, VTs, Ops);
8189   // Reset the NodeID to -1.
8190   New->setNodeId(-1);
8191   if (New != N) {
8192     ReplaceAllUsesWith(N, New);
8193     RemoveDeadNode(N);
8194   }
8195   return New;
8196 }
8197 
8198 /// UpdateSDLocOnMergeSDNode - If the opt level is -O0 then it throws away
8199 /// the line number information on the merged node since it is not possible to
8200 /// preserve the information that operation is associated with multiple lines.
8201 /// This will make the debugger working better at -O0, were there is a higher
8202 /// probability having other instructions associated with that line.
8203 ///
8204 /// For IROrder, we keep the smaller of the two
8205 SDNode *SelectionDAG::UpdateSDLocOnMergeSDNode(SDNode *N, const SDLoc &OLoc) {
8206   DebugLoc NLoc = N->getDebugLoc();
8207   if (NLoc && OptLevel == CodeGenOpt::None && OLoc.getDebugLoc() != NLoc) {
8208     N->setDebugLoc(DebugLoc());
8209   }
8210   unsigned Order = std::min(N->getIROrder(), OLoc.getIROrder());
8211   N->setIROrder(Order);
8212   return N;
8213 }
8214 
8215 /// MorphNodeTo - This *mutates* the specified node to have the specified
8216 /// return type, opcode, and operands.
8217 ///
8218 /// Note that MorphNodeTo returns the resultant node.  If there is already a
8219 /// node of the specified opcode and operands, it returns that node instead of
8220 /// the current one.  Note that the SDLoc need not be the same.
8221 ///
8222 /// Using MorphNodeTo is faster than creating a new node and swapping it in
8223 /// with ReplaceAllUsesWith both because it often avoids allocating a new
8224 /// node, and because it doesn't require CSE recalculation for any of
8225 /// the node's users.
8226 ///
8227 /// However, note that MorphNodeTo recursively deletes dead nodes from the DAG.
8228 /// As a consequence it isn't appropriate to use from within the DAG combiner or
8229 /// the legalizer which maintain worklists that would need to be updated when
8230 /// deleting things.
8231 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
8232                                   SDVTList VTs, ArrayRef<SDValue> Ops) {
8233   // If an identical node already exists, use it.
8234   void *IP = nullptr;
8235   if (VTs.VTs[VTs.NumVTs-1] != MVT::Glue) {
8236     FoldingSetNodeID ID;
8237     AddNodeIDNode(ID, Opc, VTs, Ops);
8238     if (SDNode *ON = FindNodeOrInsertPos(ID, SDLoc(N), IP))
8239       return UpdateSDLocOnMergeSDNode(ON, SDLoc(N));
8240   }
8241 
8242   if (!RemoveNodeFromCSEMaps(N))
8243     IP = nullptr;
8244 
8245   // Start the morphing.
8246   N->NodeType = Opc;
8247   N->ValueList = VTs.VTs;
8248   N->NumValues = VTs.NumVTs;
8249 
8250   // Clear the operands list, updating used nodes to remove this from their
8251   // use list.  Keep track of any operands that become dead as a result.
8252   SmallPtrSet<SDNode*, 16> DeadNodeSet;
8253   for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) {
8254     SDUse &Use = *I++;
8255     SDNode *Used = Use.getNode();
8256     Use.set(SDValue());
8257     if (Used->use_empty())
8258       DeadNodeSet.insert(Used);
8259   }
8260 
8261   // For MachineNode, initialize the memory references information.
8262   if (MachineSDNode *MN = dyn_cast<MachineSDNode>(N))
8263     MN->clearMemRefs();
8264 
8265   // Swap for an appropriately sized array from the recycler.
8266   removeOperands(N);
8267   createOperands(N, Ops);
8268 
8269   // Delete any nodes that are still dead after adding the uses for the
8270   // new operands.
8271   if (!DeadNodeSet.empty()) {
8272     SmallVector<SDNode *, 16> DeadNodes;
8273     for (SDNode *N : DeadNodeSet)
8274       if (N->use_empty())
8275         DeadNodes.push_back(N);
8276     RemoveDeadNodes(DeadNodes);
8277   }
8278 
8279   if (IP)
8280     CSEMap.InsertNode(N, IP);   // Memoize the new node.
8281   return N;
8282 }
8283 
8284 SDNode* SelectionDAG::mutateStrictFPToFP(SDNode *Node) {
8285   unsigned OrigOpc = Node->getOpcode();
8286   unsigned NewOpc;
8287   switch (OrigOpc) {
8288   default:
8289     llvm_unreachable("mutateStrictFPToFP called with unexpected opcode!");
8290 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN)               \
8291   case ISD::STRICT_##DAGN: NewOpc = ISD::DAGN; break;
8292 #define CMP_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN)               \
8293   case ISD::STRICT_##DAGN: NewOpc = ISD::SETCC; break;
8294 #include "llvm/IR/ConstrainedOps.def"
8295   }
8296 
8297   assert(Node->getNumValues() == 2 && "Unexpected number of results!");
8298 
8299   // We're taking this node out of the chain, so we need to re-link things.
8300   SDValue InputChain = Node->getOperand(0);
8301   SDValue OutputChain = SDValue(Node, 1);
8302   ReplaceAllUsesOfValueWith(OutputChain, InputChain);
8303 
8304   SmallVector<SDValue, 3> Ops;
8305   for (unsigned i = 1, e = Node->getNumOperands(); i != e; ++i)
8306     Ops.push_back(Node->getOperand(i));
8307 
8308   SDVTList VTs = getVTList(Node->getValueType(0));
8309   SDNode *Res = MorphNodeTo(Node, NewOpc, VTs, Ops);
8310 
8311   // MorphNodeTo can operate in two ways: if an existing node with the
8312   // specified operands exists, it can just return it.  Otherwise, it
8313   // updates the node in place to have the requested operands.
8314   if (Res == Node) {
8315     // If we updated the node in place, reset the node ID.  To the isel,
8316     // this should be just like a newly allocated machine node.
8317     Res->setNodeId(-1);
8318   } else {
8319     ReplaceAllUsesWith(Node, Res);
8320     RemoveDeadNode(Node);
8321   }
8322 
8323   return Res;
8324 }
8325 
8326 /// getMachineNode - These are used for target selectors to create a new node
8327 /// with specified return type(s), MachineInstr opcode, and operands.
8328 ///
8329 /// Note that getMachineNode returns the resultant node.  If there is already a
8330 /// node of the specified opcode and operands, it returns that node instead of
8331 /// the current one.
8332 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
8333                                             EVT VT) {
8334   SDVTList VTs = getVTList(VT);
8335   return getMachineNode(Opcode, dl, VTs, None);
8336 }
8337 
8338 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
8339                                             EVT VT, SDValue Op1) {
8340   SDVTList VTs = getVTList(VT);
8341   SDValue Ops[] = { Op1 };
8342   return getMachineNode(Opcode, dl, VTs, Ops);
8343 }
8344 
8345 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
8346                                             EVT VT, SDValue Op1, SDValue Op2) {
8347   SDVTList VTs = getVTList(VT);
8348   SDValue Ops[] = { Op1, Op2 };
8349   return getMachineNode(Opcode, dl, VTs, Ops);
8350 }
8351 
8352 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
8353                                             EVT VT, SDValue Op1, SDValue Op2,
8354                                             SDValue Op3) {
8355   SDVTList VTs = getVTList(VT);
8356   SDValue Ops[] = { Op1, Op2, Op3 };
8357   return getMachineNode(Opcode, dl, VTs, Ops);
8358 }
8359 
8360 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
8361                                             EVT VT, ArrayRef<SDValue> Ops) {
8362   SDVTList VTs = getVTList(VT);
8363   return getMachineNode(Opcode, dl, VTs, Ops);
8364 }
8365 
8366 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
8367                                             EVT VT1, EVT VT2, SDValue Op1,
8368                                             SDValue Op2) {
8369   SDVTList VTs = getVTList(VT1, VT2);
8370   SDValue Ops[] = { Op1, Op2 };
8371   return getMachineNode(Opcode, dl, VTs, Ops);
8372 }
8373 
8374 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
8375                                             EVT VT1, EVT VT2, SDValue Op1,
8376                                             SDValue Op2, SDValue Op3) {
8377   SDVTList VTs = getVTList(VT1, VT2);
8378   SDValue Ops[] = { Op1, Op2, Op3 };
8379   return getMachineNode(Opcode, dl, VTs, Ops);
8380 }
8381 
8382 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
8383                                             EVT VT1, EVT VT2,
8384                                             ArrayRef<SDValue> Ops) {
8385   SDVTList VTs = getVTList(VT1, VT2);
8386   return getMachineNode(Opcode, dl, VTs, Ops);
8387 }
8388 
8389 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
8390                                             EVT VT1, EVT VT2, EVT VT3,
8391                                             SDValue Op1, SDValue Op2) {
8392   SDVTList VTs = getVTList(VT1, VT2, VT3);
8393   SDValue Ops[] = { Op1, Op2 };
8394   return getMachineNode(Opcode, dl, VTs, Ops);
8395 }
8396 
8397 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
8398                                             EVT VT1, EVT VT2, EVT VT3,
8399                                             SDValue Op1, SDValue Op2,
8400                                             SDValue Op3) {
8401   SDVTList VTs = getVTList(VT1, VT2, VT3);
8402   SDValue Ops[] = { Op1, Op2, Op3 };
8403   return getMachineNode(Opcode, dl, VTs, Ops);
8404 }
8405 
8406 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
8407                                             EVT VT1, EVT VT2, EVT VT3,
8408                                             ArrayRef<SDValue> Ops) {
8409   SDVTList VTs = getVTList(VT1, VT2, VT3);
8410   return getMachineNode(Opcode, dl, VTs, Ops);
8411 }
8412 
8413 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
8414                                             ArrayRef<EVT> ResultTys,
8415                                             ArrayRef<SDValue> Ops) {
8416   SDVTList VTs = getVTList(ResultTys);
8417   return getMachineNode(Opcode, dl, VTs, Ops);
8418 }
8419 
8420 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &DL,
8421                                             SDVTList VTs,
8422                                             ArrayRef<SDValue> Ops) {
8423   bool DoCSE = VTs.VTs[VTs.NumVTs-1] != MVT::Glue;
8424   MachineSDNode *N;
8425   void *IP = nullptr;
8426 
8427   if (DoCSE) {
8428     FoldingSetNodeID ID;
8429     AddNodeIDNode(ID, ~Opcode, VTs, Ops);
8430     IP = nullptr;
8431     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
8432       return cast<MachineSDNode>(UpdateSDLocOnMergeSDNode(E, DL));
8433     }
8434   }
8435 
8436   // Allocate a new MachineSDNode.
8437   N = newSDNode<MachineSDNode>(~Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
8438   createOperands(N, Ops);
8439 
8440   if (DoCSE)
8441     CSEMap.InsertNode(N, IP);
8442 
8443   InsertNode(N);
8444   NewSDValueDbgMsg(SDValue(N, 0), "Creating new machine node: ", this);
8445   return N;
8446 }
8447 
8448 /// getTargetExtractSubreg - A convenience function for creating
8449 /// TargetOpcode::EXTRACT_SUBREG nodes.
8450 SDValue SelectionDAG::getTargetExtractSubreg(int SRIdx, const SDLoc &DL, EVT VT,
8451                                              SDValue Operand) {
8452   SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32);
8453   SDNode *Subreg = getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL,
8454                                   VT, Operand, SRIdxVal);
8455   return SDValue(Subreg, 0);
8456 }
8457 
8458 /// getTargetInsertSubreg - A convenience function for creating
8459 /// TargetOpcode::INSERT_SUBREG nodes.
8460 SDValue SelectionDAG::getTargetInsertSubreg(int SRIdx, const SDLoc &DL, EVT VT,
8461                                             SDValue Operand, SDValue Subreg) {
8462   SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32);
8463   SDNode *Result = getMachineNode(TargetOpcode::INSERT_SUBREG, DL,
8464                                   VT, Operand, Subreg, SRIdxVal);
8465   return SDValue(Result, 0);
8466 }
8467 
8468 /// getNodeIfExists - Get the specified node if it's already available, or
8469 /// else return NULL.
8470 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList,
8471                                       ArrayRef<SDValue> Ops) {
8472   SDNodeFlags Flags;
8473   if (Inserter)
8474     Flags = Inserter->getFlags();
8475   return getNodeIfExists(Opcode, VTList, Ops, Flags);
8476 }
8477 
8478 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList,
8479                                       ArrayRef<SDValue> Ops,
8480                                       const SDNodeFlags Flags) {
8481   if (VTList.VTs[VTList.NumVTs - 1] != MVT::Glue) {
8482     FoldingSetNodeID ID;
8483     AddNodeIDNode(ID, Opcode, VTList, Ops);
8484     void *IP = nullptr;
8485     if (SDNode *E = FindNodeOrInsertPos(ID, SDLoc(), IP)) {
8486       E->intersectFlagsWith(Flags);
8487       return E;
8488     }
8489   }
8490   return nullptr;
8491 }
8492 
8493 /// doesNodeExist - Check if a node exists without modifying its flags.
8494 bool SelectionDAG::doesNodeExist(unsigned Opcode, SDVTList VTList,
8495                                  ArrayRef<SDValue> Ops) {
8496   if (VTList.VTs[VTList.NumVTs - 1] != MVT::Glue) {
8497     FoldingSetNodeID ID;
8498     AddNodeIDNode(ID, Opcode, VTList, Ops);
8499     void *IP = nullptr;
8500     if (FindNodeOrInsertPos(ID, SDLoc(), IP))
8501       return true;
8502   }
8503   return false;
8504 }
8505 
8506 /// getDbgValue - Creates a SDDbgValue node.
8507 ///
8508 /// SDNode
8509 SDDbgValue *SelectionDAG::getDbgValue(DIVariable *Var, DIExpression *Expr,
8510                                       SDNode *N, unsigned R, bool IsIndirect,
8511                                       const DebugLoc &DL, unsigned O) {
8512   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
8513          "Expected inlined-at fields to agree");
8514   return new (DbgInfo->getAlloc())
8515       SDDbgValue(Var, Expr, SDDbgOperand::fromNode(N, R), N, IsIndirect, DL, O,
8516                  /*IsVariadic=*/false);
8517 }
8518 
8519 /// Constant
8520 SDDbgValue *SelectionDAG::getConstantDbgValue(DIVariable *Var,
8521                                               DIExpression *Expr,
8522                                               const Value *C,
8523                                               const DebugLoc &DL, unsigned O) {
8524   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
8525          "Expected inlined-at fields to agree");
8526   return new (DbgInfo->getAlloc()) SDDbgValue(
8527       Var, Expr, SDDbgOperand::fromConst(C), {}, /*IsIndirect=*/false, DL, O,
8528       /*IsVariadic=*/false);
8529 }
8530 
8531 /// FrameIndex
8532 SDDbgValue *SelectionDAG::getFrameIndexDbgValue(DIVariable *Var,
8533                                                 DIExpression *Expr, unsigned FI,
8534                                                 bool IsIndirect,
8535                                                 const DebugLoc &DL,
8536                                                 unsigned O) {
8537   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
8538          "Expected inlined-at fields to agree");
8539   return getFrameIndexDbgValue(Var, Expr, FI, {}, IsIndirect, DL, O);
8540 }
8541 
8542 /// FrameIndex with dependencies
8543 SDDbgValue *SelectionDAG::getFrameIndexDbgValue(DIVariable *Var,
8544                                                 DIExpression *Expr, unsigned FI,
8545                                                 ArrayRef<SDNode *> Dependencies,
8546                                                 bool IsIndirect,
8547                                                 const DebugLoc &DL,
8548                                                 unsigned O) {
8549   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
8550          "Expected inlined-at fields to agree");
8551   return new (DbgInfo->getAlloc())
8552       SDDbgValue(Var, Expr, SDDbgOperand::fromFrameIdx(FI), Dependencies,
8553                  IsIndirect, DL, O,
8554                  /*IsVariadic=*/false);
8555 }
8556 
8557 /// VReg
8558 SDDbgValue *SelectionDAG::getVRegDbgValue(DIVariable *Var, DIExpression *Expr,
8559                                           unsigned VReg, bool IsIndirect,
8560                                           const DebugLoc &DL, unsigned O) {
8561   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
8562          "Expected inlined-at fields to agree");
8563   return new (DbgInfo->getAlloc())
8564       SDDbgValue(Var, Expr, SDDbgOperand::fromVReg(VReg), {}, IsIndirect, DL, O,
8565                  /*IsVariadic=*/false);
8566 }
8567 
8568 SDDbgValue *SelectionDAG::getDbgValueList(DIVariable *Var, DIExpression *Expr,
8569                                           ArrayRef<SDDbgOperand> Locs,
8570                                           ArrayRef<SDNode *> Dependencies,
8571                                           bool IsIndirect, const DebugLoc &DL,
8572                                           unsigned O, bool IsVariadic) {
8573   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
8574          "Expected inlined-at fields to agree");
8575   return new (DbgInfo->getAlloc())
8576       SDDbgValue(Var, Expr, Locs, Dependencies, IsIndirect, DL, O, IsVariadic);
8577 }
8578 
8579 void SelectionDAG::transferDbgValues(SDValue From, SDValue To,
8580                                      unsigned OffsetInBits, unsigned SizeInBits,
8581                                      bool InvalidateDbg) {
8582   SDNode *FromNode = From.getNode();
8583   SDNode *ToNode = To.getNode();
8584   assert(FromNode && ToNode && "Can't modify dbg values");
8585 
8586   // PR35338
8587   // TODO: assert(From != To && "Redundant dbg value transfer");
8588   // TODO: assert(FromNode != ToNode && "Intranode dbg value transfer");
8589   if (From == To || FromNode == ToNode)
8590     return;
8591 
8592   if (!FromNode->getHasDebugValue())
8593     return;
8594 
8595   SDDbgOperand FromLocOp =
8596       SDDbgOperand::fromNode(From.getNode(), From.getResNo());
8597   SDDbgOperand ToLocOp = SDDbgOperand::fromNode(To.getNode(), To.getResNo());
8598 
8599   SmallVector<SDDbgValue *, 2> ClonedDVs;
8600   for (SDDbgValue *Dbg : GetDbgValues(FromNode)) {
8601     if (Dbg->isInvalidated())
8602       continue;
8603 
8604     // TODO: assert(!Dbg->isInvalidated() && "Transfer of invalid dbg value");
8605 
8606     // Create a new location ops vector that is equal to the old vector, but
8607     // with each instance of FromLocOp replaced with ToLocOp.
8608     bool Changed = false;
8609     auto NewLocOps = Dbg->copyLocationOps();
8610     std::replace_if(
8611         NewLocOps.begin(), NewLocOps.end(),
8612         [&Changed, FromLocOp](const SDDbgOperand &Op) {
8613           bool Match = Op == FromLocOp;
8614           Changed |= Match;
8615           return Match;
8616         },
8617         ToLocOp);
8618     // Ignore this SDDbgValue if we didn't find a matching location.
8619     if (!Changed)
8620       continue;
8621 
8622     DIVariable *Var = Dbg->getVariable();
8623     auto *Expr = Dbg->getExpression();
8624     // If a fragment is requested, update the expression.
8625     if (SizeInBits) {
8626       // When splitting a larger (e.g., sign-extended) value whose
8627       // lower bits are described with an SDDbgValue, do not attempt
8628       // to transfer the SDDbgValue to the upper bits.
8629       if (auto FI = Expr->getFragmentInfo())
8630         if (OffsetInBits + SizeInBits > FI->SizeInBits)
8631           continue;
8632       auto Fragment = DIExpression::createFragmentExpression(Expr, OffsetInBits,
8633                                                              SizeInBits);
8634       if (!Fragment)
8635         continue;
8636       Expr = *Fragment;
8637     }
8638 
8639     auto NewDependencies = Dbg->copySDNodes();
8640     std::replace(NewDependencies.begin(), NewDependencies.end(), FromNode,
8641                  ToNode);
8642     // Clone the SDDbgValue and move it to To.
8643     SDDbgValue *Clone = getDbgValueList(
8644         Var, Expr, NewLocOps, NewDependencies, Dbg->isIndirect(),
8645         Dbg->getDebugLoc(), std::max(ToNode->getIROrder(), Dbg->getOrder()),
8646         Dbg->isVariadic());
8647     ClonedDVs.push_back(Clone);
8648 
8649     if (InvalidateDbg) {
8650       // Invalidate value and indicate the SDDbgValue should not be emitted.
8651       Dbg->setIsInvalidated();
8652       Dbg->setIsEmitted();
8653     }
8654   }
8655 
8656   for (SDDbgValue *Dbg : ClonedDVs) {
8657     assert(is_contained(Dbg->getSDNodes(), ToNode) &&
8658            "Transferred DbgValues should depend on the new SDNode");
8659     AddDbgValue(Dbg, false);
8660   }
8661 }
8662 
8663 void SelectionDAG::salvageDebugInfo(SDNode &N) {
8664   if (!N.getHasDebugValue())
8665     return;
8666 
8667   SmallVector<SDDbgValue *, 2> ClonedDVs;
8668   for (auto DV : GetDbgValues(&N)) {
8669     if (DV->isInvalidated())
8670       continue;
8671     switch (N.getOpcode()) {
8672     default:
8673       break;
8674     case ISD::ADD:
8675       SDValue N0 = N.getOperand(0);
8676       SDValue N1 = N.getOperand(1);
8677       if (!isConstantIntBuildVectorOrConstantInt(N0) &&
8678           isConstantIntBuildVectorOrConstantInt(N1)) {
8679         uint64_t Offset = N.getConstantOperandVal(1);
8680 
8681         // Rewrite an ADD constant node into a DIExpression. Since we are
8682         // performing arithmetic to compute the variable's *value* in the
8683         // DIExpression, we need to mark the expression with a
8684         // DW_OP_stack_value.
8685         auto *DIExpr = DV->getExpression();
8686         auto NewLocOps = DV->copyLocationOps();
8687         bool Changed = false;
8688         for (size_t i = 0; i < NewLocOps.size(); ++i) {
8689           // We're not given a ResNo to compare against because the whole
8690           // node is going away. We know that any ISD::ADD only has one
8691           // result, so we can assume any node match is using the result.
8692           if (NewLocOps[i].getKind() != SDDbgOperand::SDNODE ||
8693               NewLocOps[i].getSDNode() != &N)
8694             continue;
8695           NewLocOps[i] = SDDbgOperand::fromNode(N0.getNode(), N0.getResNo());
8696           SmallVector<uint64_t, 3> ExprOps;
8697           DIExpression::appendOffset(ExprOps, Offset);
8698           DIExpr = DIExpression::appendOpsToArg(DIExpr, ExprOps, i, true);
8699           Changed = true;
8700         }
8701         (void)Changed;
8702         assert(Changed && "Salvage target doesn't use N");
8703 
8704         auto NewDependencies = DV->copySDNodes();
8705         std::replace(NewDependencies.begin(), NewDependencies.end(), &N,
8706                      N0.getNode());
8707         SDDbgValue *Clone = getDbgValueList(DV->getVariable(), DIExpr,
8708                                             NewLocOps, NewDependencies,
8709                                             DV->isIndirect(), DV->getDebugLoc(),
8710                                             DV->getOrder(), DV->isVariadic());
8711         ClonedDVs.push_back(Clone);
8712         DV->setIsInvalidated();
8713         DV->setIsEmitted();
8714         LLVM_DEBUG(dbgs() << "SALVAGE: Rewriting";
8715                    N0.getNode()->dumprFull(this);
8716                    dbgs() << " into " << *DIExpr << '\n');
8717       }
8718     }
8719   }
8720 
8721   for (SDDbgValue *Dbg : ClonedDVs) {
8722     assert(!Dbg->getSDNodes().empty() &&
8723            "Salvaged DbgValue should depend on a new SDNode");
8724     AddDbgValue(Dbg, false);
8725   }
8726 }
8727 
8728 /// Creates a SDDbgLabel node.
8729 SDDbgLabel *SelectionDAG::getDbgLabel(DILabel *Label,
8730                                       const DebugLoc &DL, unsigned O) {
8731   assert(cast<DILabel>(Label)->isValidLocationForIntrinsic(DL) &&
8732          "Expected inlined-at fields to agree");
8733   return new (DbgInfo->getAlloc()) SDDbgLabel(Label, DL, O);
8734 }
8735 
8736 namespace {
8737 
8738 /// RAUWUpdateListener - Helper for ReplaceAllUsesWith - When the node
8739 /// pointed to by a use iterator is deleted, increment the use iterator
8740 /// so that it doesn't dangle.
8741 ///
8742 class RAUWUpdateListener : public SelectionDAG::DAGUpdateListener {
8743   SDNode::use_iterator &UI;
8744   SDNode::use_iterator &UE;
8745 
8746   void NodeDeleted(SDNode *N, SDNode *E) override {
8747     // Increment the iterator as needed.
8748     while (UI != UE && N == *UI)
8749       ++UI;
8750   }
8751 
8752 public:
8753   RAUWUpdateListener(SelectionDAG &d,
8754                      SDNode::use_iterator &ui,
8755                      SDNode::use_iterator &ue)
8756     : SelectionDAG::DAGUpdateListener(d), UI(ui), UE(ue) {}
8757 };
8758 
8759 } // end anonymous namespace
8760 
8761 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
8762 /// This can cause recursive merging of nodes in the DAG.
8763 ///
8764 /// This version assumes From has a single result value.
8765 ///
8766 void SelectionDAG::ReplaceAllUsesWith(SDValue FromN, SDValue To) {
8767   SDNode *From = FromN.getNode();
8768   assert(From->getNumValues() == 1 && FromN.getResNo() == 0 &&
8769          "Cannot replace with this method!");
8770   assert(From != To.getNode() && "Cannot replace uses of with self");
8771 
8772   // Preserve Debug Values
8773   transferDbgValues(FromN, To);
8774 
8775   // Iterate over all the existing uses of From. New uses will be added
8776   // to the beginning of the use list, which we avoid visiting.
8777   // This specifically avoids visiting uses of From that arise while the
8778   // replacement is happening, because any such uses would be the result
8779   // of CSE: If an existing node looks like From after one of its operands
8780   // is replaced by To, we don't want to replace of all its users with To
8781   // too. See PR3018 for more info.
8782   SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
8783   RAUWUpdateListener Listener(*this, UI, UE);
8784   while (UI != UE) {
8785     SDNode *User = *UI;
8786 
8787     // This node is about to morph, remove its old self from the CSE maps.
8788     RemoveNodeFromCSEMaps(User);
8789 
8790     // A user can appear in a use list multiple times, and when this
8791     // happens the uses are usually next to each other in the list.
8792     // To help reduce the number of CSE recomputations, process all
8793     // the uses of this user that we can find this way.
8794     do {
8795       SDUse &Use = UI.getUse();
8796       ++UI;
8797       Use.set(To);
8798       if (To->isDivergent() != From->isDivergent())
8799         updateDivergence(User);
8800     } while (UI != UE && *UI == User);
8801     // Now that we have modified User, add it back to the CSE maps.  If it
8802     // already exists there, recursively merge the results together.
8803     AddModifiedNodeToCSEMaps(User);
8804   }
8805 
8806   // If we just RAUW'd the root, take note.
8807   if (FromN == getRoot())
8808     setRoot(To);
8809 }
8810 
8811 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
8812 /// This can cause recursive merging of nodes in the DAG.
8813 ///
8814 /// This version assumes that for each value of From, there is a
8815 /// corresponding value in To in the same position with the same type.
8816 ///
8817 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, SDNode *To) {
8818 #ifndef NDEBUG
8819   for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
8820     assert((!From->hasAnyUseOfValue(i) ||
8821             From->getValueType(i) == To->getValueType(i)) &&
8822            "Cannot use this version of ReplaceAllUsesWith!");
8823 #endif
8824 
8825   // Handle the trivial case.
8826   if (From == To)
8827     return;
8828 
8829   // Preserve Debug Info. Only do this if there's a use.
8830   for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
8831     if (From->hasAnyUseOfValue(i)) {
8832       assert((i < To->getNumValues()) && "Invalid To location");
8833       transferDbgValues(SDValue(From, i), SDValue(To, i));
8834     }
8835 
8836   // Iterate over just the existing users of From. See the comments in
8837   // the ReplaceAllUsesWith above.
8838   SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
8839   RAUWUpdateListener Listener(*this, UI, UE);
8840   while (UI != UE) {
8841     SDNode *User = *UI;
8842 
8843     // This node is about to morph, remove its old self from the CSE maps.
8844     RemoveNodeFromCSEMaps(User);
8845 
8846     // A user can appear in a use list multiple times, and when this
8847     // happens the uses are usually next to each other in the list.
8848     // To help reduce the number of CSE recomputations, process all
8849     // the uses of this user that we can find this way.
8850     do {
8851       SDUse &Use = UI.getUse();
8852       ++UI;
8853       Use.setNode(To);
8854       if (To->isDivergent() != From->isDivergent())
8855         updateDivergence(User);
8856     } while (UI != UE && *UI == User);
8857 
8858     // Now that we have modified User, add it back to the CSE maps.  If it
8859     // already exists there, recursively merge the results together.
8860     AddModifiedNodeToCSEMaps(User);
8861   }
8862 
8863   // If we just RAUW'd the root, take note.
8864   if (From == getRoot().getNode())
8865     setRoot(SDValue(To, getRoot().getResNo()));
8866 }
8867 
8868 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
8869 /// This can cause recursive merging of nodes in the DAG.
8870 ///
8871 /// This version can replace From with any result values.  To must match the
8872 /// number and types of values returned by From.
8873 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, const SDValue *To) {
8874   if (From->getNumValues() == 1)  // Handle the simple case efficiently.
8875     return ReplaceAllUsesWith(SDValue(From, 0), To[0]);
8876 
8877   // Preserve Debug Info.
8878   for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
8879     transferDbgValues(SDValue(From, i), To[i]);
8880 
8881   // Iterate over just the existing users of From. See the comments in
8882   // the ReplaceAllUsesWith above.
8883   SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
8884   RAUWUpdateListener Listener(*this, UI, UE);
8885   while (UI != UE) {
8886     SDNode *User = *UI;
8887 
8888     // This node is about to morph, remove its old self from the CSE maps.
8889     RemoveNodeFromCSEMaps(User);
8890 
8891     // A user can appear in a use list multiple times, and when this happens the
8892     // uses are usually next to each other in the list.  To help reduce the
8893     // number of CSE and divergence recomputations, process all the uses of this
8894     // user that we can find this way.
8895     bool To_IsDivergent = false;
8896     do {
8897       SDUse &Use = UI.getUse();
8898       const SDValue &ToOp = To[Use.getResNo()];
8899       ++UI;
8900       Use.set(ToOp);
8901       To_IsDivergent |= ToOp->isDivergent();
8902     } while (UI != UE && *UI == User);
8903 
8904     if (To_IsDivergent != From->isDivergent())
8905       updateDivergence(User);
8906 
8907     // Now that we have modified User, add it back to the CSE maps.  If it
8908     // already exists there, recursively merge the results together.
8909     AddModifiedNodeToCSEMaps(User);
8910   }
8911 
8912   // If we just RAUW'd the root, take note.
8913   if (From == getRoot().getNode())
8914     setRoot(SDValue(To[getRoot().getResNo()]));
8915 }
8916 
8917 /// ReplaceAllUsesOfValueWith - Replace any uses of From with To, leaving
8918 /// uses of other values produced by From.getNode() alone.  The Deleted
8919 /// vector is handled the same way as for ReplaceAllUsesWith.
8920 void SelectionDAG::ReplaceAllUsesOfValueWith(SDValue From, SDValue To){
8921   // Handle the really simple, really trivial case efficiently.
8922   if (From == To) return;
8923 
8924   // Handle the simple, trivial, case efficiently.
8925   if (From.getNode()->getNumValues() == 1) {
8926     ReplaceAllUsesWith(From, To);
8927     return;
8928   }
8929 
8930   // Preserve Debug Info.
8931   transferDbgValues(From, To);
8932 
8933   // Iterate over just the existing users of From. See the comments in
8934   // the ReplaceAllUsesWith above.
8935   SDNode::use_iterator UI = From.getNode()->use_begin(),
8936                        UE = From.getNode()->use_end();
8937   RAUWUpdateListener Listener(*this, UI, UE);
8938   while (UI != UE) {
8939     SDNode *User = *UI;
8940     bool UserRemovedFromCSEMaps = false;
8941 
8942     // A user can appear in a use list multiple times, and when this
8943     // happens the uses are usually next to each other in the list.
8944     // To help reduce the number of CSE recomputations, process all
8945     // the uses of this user that we can find this way.
8946     do {
8947       SDUse &Use = UI.getUse();
8948 
8949       // Skip uses of different values from the same node.
8950       if (Use.getResNo() != From.getResNo()) {
8951         ++UI;
8952         continue;
8953       }
8954 
8955       // If this node hasn't been modified yet, it's still in the CSE maps,
8956       // so remove its old self from the CSE maps.
8957       if (!UserRemovedFromCSEMaps) {
8958         RemoveNodeFromCSEMaps(User);
8959         UserRemovedFromCSEMaps = true;
8960       }
8961 
8962       ++UI;
8963       Use.set(To);
8964       if (To->isDivergent() != From->isDivergent())
8965         updateDivergence(User);
8966     } while (UI != UE && *UI == User);
8967     // We are iterating over all uses of the From node, so if a use
8968     // doesn't use the specific value, no changes are made.
8969     if (!UserRemovedFromCSEMaps)
8970       continue;
8971 
8972     // Now that we have modified User, add it back to the CSE maps.  If it
8973     // already exists there, recursively merge the results together.
8974     AddModifiedNodeToCSEMaps(User);
8975   }
8976 
8977   // If we just RAUW'd the root, take note.
8978   if (From == getRoot())
8979     setRoot(To);
8980 }
8981 
8982 namespace {
8983 
8984   /// UseMemo - This class is used by SelectionDAG::ReplaceAllUsesOfValuesWith
8985   /// to record information about a use.
8986   struct UseMemo {
8987     SDNode *User;
8988     unsigned Index;
8989     SDUse *Use;
8990   };
8991 
8992   /// operator< - Sort Memos by User.
8993   bool operator<(const UseMemo &L, const UseMemo &R) {
8994     return (intptr_t)L.User < (intptr_t)R.User;
8995   }
8996 
8997 } // end anonymous namespace
8998 
8999 bool SelectionDAG::calculateDivergence(SDNode *N) {
9000   if (TLI->isSDNodeAlwaysUniform(N)) {
9001     assert(!TLI->isSDNodeSourceOfDivergence(N, FLI, DA) &&
9002            "Conflicting divergence information!");
9003     return false;
9004   }
9005   if (TLI->isSDNodeSourceOfDivergence(N, FLI, DA))
9006     return true;
9007   for (auto &Op : N->ops()) {
9008     if (Op.Val.getValueType() != MVT::Other && Op.getNode()->isDivergent())
9009       return true;
9010   }
9011   return false;
9012 }
9013 
9014 void SelectionDAG::updateDivergence(SDNode *N) {
9015   SmallVector<SDNode *, 16> Worklist(1, N);
9016   do {
9017     N = Worklist.pop_back_val();
9018     bool IsDivergent = calculateDivergence(N);
9019     if (N->SDNodeBits.IsDivergent != IsDivergent) {
9020       N->SDNodeBits.IsDivergent = IsDivergent;
9021       llvm::append_range(Worklist, N->uses());
9022     }
9023   } while (!Worklist.empty());
9024 }
9025 
9026 void SelectionDAG::CreateTopologicalOrder(std::vector<SDNode *> &Order) {
9027   DenseMap<SDNode *, unsigned> Degree;
9028   Order.reserve(AllNodes.size());
9029   for (auto &N : allnodes()) {
9030     unsigned NOps = N.getNumOperands();
9031     Degree[&N] = NOps;
9032     if (0 == NOps)
9033       Order.push_back(&N);
9034   }
9035   for (size_t I = 0; I != Order.size(); ++I) {
9036     SDNode *N = Order[I];
9037     for (auto U : N->uses()) {
9038       unsigned &UnsortedOps = Degree[U];
9039       if (0 == --UnsortedOps)
9040         Order.push_back(U);
9041     }
9042   }
9043 }
9044 
9045 #ifndef NDEBUG
9046 void SelectionDAG::VerifyDAGDiverence() {
9047   std::vector<SDNode *> TopoOrder;
9048   CreateTopologicalOrder(TopoOrder);
9049   for (auto *N : TopoOrder) {
9050     assert(calculateDivergence(N) == N->isDivergent() &&
9051            "Divergence bit inconsistency detected");
9052   }
9053 }
9054 #endif
9055 
9056 /// ReplaceAllUsesOfValuesWith - Replace any uses of From with To, leaving
9057 /// uses of other values produced by From.getNode() alone.  The same value
9058 /// may appear in both the From and To list.  The Deleted vector is
9059 /// handled the same way as for ReplaceAllUsesWith.
9060 void SelectionDAG::ReplaceAllUsesOfValuesWith(const SDValue *From,
9061                                               const SDValue *To,
9062                                               unsigned Num){
9063   // Handle the simple, trivial case efficiently.
9064   if (Num == 1)
9065     return ReplaceAllUsesOfValueWith(*From, *To);
9066 
9067   transferDbgValues(*From, *To);
9068 
9069   // Read up all the uses and make records of them. This helps
9070   // processing new uses that are introduced during the
9071   // replacement process.
9072   SmallVector<UseMemo, 4> Uses;
9073   for (unsigned i = 0; i != Num; ++i) {
9074     unsigned FromResNo = From[i].getResNo();
9075     SDNode *FromNode = From[i].getNode();
9076     for (SDNode::use_iterator UI = FromNode->use_begin(),
9077          E = FromNode->use_end(); UI != E; ++UI) {
9078       SDUse &Use = UI.getUse();
9079       if (Use.getResNo() == FromResNo) {
9080         UseMemo Memo = { *UI, i, &Use };
9081         Uses.push_back(Memo);
9082       }
9083     }
9084   }
9085 
9086   // Sort the uses, so that all the uses from a given User are together.
9087   llvm::sort(Uses);
9088 
9089   for (unsigned UseIndex = 0, UseIndexEnd = Uses.size();
9090        UseIndex != UseIndexEnd; ) {
9091     // We know that this user uses some value of From.  If it is the right
9092     // value, update it.
9093     SDNode *User = Uses[UseIndex].User;
9094 
9095     // This node is about to morph, remove its old self from the CSE maps.
9096     RemoveNodeFromCSEMaps(User);
9097 
9098     // The Uses array is sorted, so all the uses for a given User
9099     // are next to each other in the list.
9100     // To help reduce the number of CSE recomputations, process all
9101     // the uses of this user that we can find this way.
9102     do {
9103       unsigned i = Uses[UseIndex].Index;
9104       SDUse &Use = *Uses[UseIndex].Use;
9105       ++UseIndex;
9106 
9107       Use.set(To[i]);
9108     } while (UseIndex != UseIndexEnd && Uses[UseIndex].User == User);
9109 
9110     // Now that we have modified User, add it back to the CSE maps.  If it
9111     // already exists there, recursively merge the results together.
9112     AddModifiedNodeToCSEMaps(User);
9113   }
9114 }
9115 
9116 /// AssignTopologicalOrder - Assign a unique node id for each node in the DAG
9117 /// based on their topological order. It returns the maximum id and a vector
9118 /// of the SDNodes* in assigned order by reference.
9119 unsigned SelectionDAG::AssignTopologicalOrder() {
9120   unsigned DAGSize = 0;
9121 
9122   // SortedPos tracks the progress of the algorithm. Nodes before it are
9123   // sorted, nodes after it are unsorted. When the algorithm completes
9124   // it is at the end of the list.
9125   allnodes_iterator SortedPos = allnodes_begin();
9126 
9127   // Visit all the nodes. Move nodes with no operands to the front of
9128   // the list immediately. Annotate nodes that do have operands with their
9129   // operand count. Before we do this, the Node Id fields of the nodes
9130   // may contain arbitrary values. After, the Node Id fields for nodes
9131   // before SortedPos will contain the topological sort index, and the
9132   // Node Id fields for nodes At SortedPos and after will contain the
9133   // count of outstanding operands.
9134   for (allnodes_iterator I = allnodes_begin(),E = allnodes_end(); I != E; ) {
9135     SDNode *N = &*I++;
9136     checkForCycles(N, this);
9137     unsigned Degree = N->getNumOperands();
9138     if (Degree == 0) {
9139       // A node with no uses, add it to the result array immediately.
9140       N->setNodeId(DAGSize++);
9141       allnodes_iterator Q(N);
9142       if (Q != SortedPos)
9143         SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(Q));
9144       assert(SortedPos != AllNodes.end() && "Overran node list");
9145       ++SortedPos;
9146     } else {
9147       // Temporarily use the Node Id as scratch space for the degree count.
9148       N->setNodeId(Degree);
9149     }
9150   }
9151 
9152   // Visit all the nodes. As we iterate, move nodes into sorted order,
9153   // such that by the time the end is reached all nodes will be sorted.
9154   for (SDNode &Node : allnodes()) {
9155     SDNode *N = &Node;
9156     checkForCycles(N, this);
9157     // N is in sorted position, so all its uses have one less operand
9158     // that needs to be sorted.
9159     for (SDNode *P : N->uses()) {
9160       unsigned Degree = P->getNodeId();
9161       assert(Degree != 0 && "Invalid node degree");
9162       --Degree;
9163       if (Degree == 0) {
9164         // All of P's operands are sorted, so P may sorted now.
9165         P->setNodeId(DAGSize++);
9166         if (P->getIterator() != SortedPos)
9167           SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(P));
9168         assert(SortedPos != AllNodes.end() && "Overran node list");
9169         ++SortedPos;
9170       } else {
9171         // Update P's outstanding operand count.
9172         P->setNodeId(Degree);
9173       }
9174     }
9175     if (Node.getIterator() == SortedPos) {
9176 #ifndef NDEBUG
9177       allnodes_iterator I(N);
9178       SDNode *S = &*++I;
9179       dbgs() << "Overran sorted position:\n";
9180       S->dumprFull(this); dbgs() << "\n";
9181       dbgs() << "Checking if this is due to cycles\n";
9182       checkForCycles(this, true);
9183 #endif
9184       llvm_unreachable(nullptr);
9185     }
9186   }
9187 
9188   assert(SortedPos == AllNodes.end() &&
9189          "Topological sort incomplete!");
9190   assert(AllNodes.front().getOpcode() == ISD::EntryToken &&
9191          "First node in topological sort is not the entry token!");
9192   assert(AllNodes.front().getNodeId() == 0 &&
9193          "First node in topological sort has non-zero id!");
9194   assert(AllNodes.front().getNumOperands() == 0 &&
9195          "First node in topological sort has operands!");
9196   assert(AllNodes.back().getNodeId() == (int)DAGSize-1 &&
9197          "Last node in topologic sort has unexpected id!");
9198   assert(AllNodes.back().use_empty() &&
9199          "Last node in topologic sort has users!");
9200   assert(DAGSize == allnodes_size() && "Node count mismatch!");
9201   return DAGSize;
9202 }
9203 
9204 /// AddDbgValue - Add a dbg_value SDNode. If SD is non-null that means the
9205 /// value is produced by SD.
9206 void SelectionDAG::AddDbgValue(SDDbgValue *DB, bool isParameter) {
9207   for (SDNode *SD : DB->getSDNodes()) {
9208     if (!SD)
9209       continue;
9210     assert(DbgInfo->getSDDbgValues(SD).empty() || SD->getHasDebugValue());
9211     SD->setHasDebugValue(true);
9212   }
9213   DbgInfo->add(DB, isParameter);
9214 }
9215 
9216 void SelectionDAG::AddDbgLabel(SDDbgLabel *DB) { DbgInfo->add(DB); }
9217 
9218 SDValue SelectionDAG::makeEquivalentMemoryOrdering(SDValue OldChain,
9219                                                    SDValue NewMemOpChain) {
9220   assert(isa<MemSDNode>(NewMemOpChain) && "Expected a memop node");
9221   assert(NewMemOpChain.getValueType() == MVT::Other && "Expected a token VT");
9222   // The new memory operation must have the same position as the old load in
9223   // terms of memory dependency. Create a TokenFactor for the old load and new
9224   // memory operation and update uses of the old load's output chain to use that
9225   // TokenFactor.
9226   if (OldChain == NewMemOpChain || OldChain.use_empty())
9227     return NewMemOpChain;
9228 
9229   SDValue TokenFactor = getNode(ISD::TokenFactor, SDLoc(OldChain), MVT::Other,
9230                                 OldChain, NewMemOpChain);
9231   ReplaceAllUsesOfValueWith(OldChain, TokenFactor);
9232   UpdateNodeOperands(TokenFactor.getNode(), OldChain, NewMemOpChain);
9233   return TokenFactor;
9234 }
9235 
9236 SDValue SelectionDAG::makeEquivalentMemoryOrdering(LoadSDNode *OldLoad,
9237                                                    SDValue NewMemOp) {
9238   assert(isa<MemSDNode>(NewMemOp.getNode()) && "Expected a memop node");
9239   SDValue OldChain = SDValue(OldLoad, 1);
9240   SDValue NewMemOpChain = NewMemOp.getValue(1);
9241   return makeEquivalentMemoryOrdering(OldChain, NewMemOpChain);
9242 }
9243 
9244 SDValue SelectionDAG::getSymbolFunctionGlobalAddress(SDValue Op,
9245                                                      Function **OutFunction) {
9246   assert(isa<ExternalSymbolSDNode>(Op) && "Node should be an ExternalSymbol");
9247 
9248   auto *Symbol = cast<ExternalSymbolSDNode>(Op)->getSymbol();
9249   auto *Module = MF->getFunction().getParent();
9250   auto *Function = Module->getFunction(Symbol);
9251 
9252   if (OutFunction != nullptr)
9253       *OutFunction = Function;
9254 
9255   if (Function != nullptr) {
9256     auto PtrTy = TLI->getPointerTy(getDataLayout(), Function->getAddressSpace());
9257     return getGlobalAddress(Function, SDLoc(Op), PtrTy);
9258   }
9259 
9260   std::string ErrorStr;
9261   raw_string_ostream ErrorFormatter(ErrorStr);
9262 
9263   ErrorFormatter << "Undefined external symbol ";
9264   ErrorFormatter << '"' << Symbol << '"';
9265   ErrorFormatter.flush();
9266 
9267   report_fatal_error(ErrorStr);
9268 }
9269 
9270 //===----------------------------------------------------------------------===//
9271 //                              SDNode Class
9272 //===----------------------------------------------------------------------===//
9273 
9274 bool llvm::isNullConstant(SDValue V) {
9275   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
9276   return Const != nullptr && Const->isNullValue();
9277 }
9278 
9279 bool llvm::isNullFPConstant(SDValue V) {
9280   ConstantFPSDNode *Const = dyn_cast<ConstantFPSDNode>(V);
9281   return Const != nullptr && Const->isZero() && !Const->isNegative();
9282 }
9283 
9284 bool llvm::isAllOnesConstant(SDValue V) {
9285   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
9286   return Const != nullptr && Const->isAllOnesValue();
9287 }
9288 
9289 bool llvm::isOneConstant(SDValue V) {
9290   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
9291   return Const != nullptr && Const->isOne();
9292 }
9293 
9294 SDValue llvm::peekThroughBitcasts(SDValue V) {
9295   while (V.getOpcode() == ISD::BITCAST)
9296     V = V.getOperand(0);
9297   return V;
9298 }
9299 
9300 SDValue llvm::peekThroughOneUseBitcasts(SDValue V) {
9301   while (V.getOpcode() == ISD::BITCAST && V.getOperand(0).hasOneUse())
9302     V = V.getOperand(0);
9303   return V;
9304 }
9305 
9306 SDValue llvm::peekThroughExtractSubvectors(SDValue V) {
9307   while (V.getOpcode() == ISD::EXTRACT_SUBVECTOR)
9308     V = V.getOperand(0);
9309   return V;
9310 }
9311 
9312 bool llvm::isBitwiseNot(SDValue V, bool AllowUndefs) {
9313   if (V.getOpcode() != ISD::XOR)
9314     return false;
9315   V = peekThroughBitcasts(V.getOperand(1));
9316   unsigned NumBits = V.getScalarValueSizeInBits();
9317   ConstantSDNode *C =
9318       isConstOrConstSplat(V, AllowUndefs, /*AllowTruncation*/ true);
9319   return C && (C->getAPIntValue().countTrailingOnes() >= NumBits);
9320 }
9321 
9322 ConstantSDNode *llvm::isConstOrConstSplat(SDValue N, bool AllowUndefs,
9323                                           bool AllowTruncation) {
9324   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
9325     return CN;
9326 
9327   // SplatVectors can truncate their operands. Ignore that case here unless
9328   // AllowTruncation is set.
9329   if (N->getOpcode() == ISD::SPLAT_VECTOR) {
9330     EVT VecEltVT = N->getValueType(0).getVectorElementType();
9331     if (auto *CN = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
9332       EVT CVT = CN->getValueType(0);
9333       assert(CVT.bitsGE(VecEltVT) && "Illegal splat_vector element extension");
9334       if (AllowTruncation || CVT == VecEltVT)
9335         return CN;
9336     }
9337   }
9338 
9339   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
9340     BitVector UndefElements;
9341     ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
9342 
9343     // BuildVectors can truncate their operands. Ignore that case here unless
9344     // AllowTruncation is set.
9345     if (CN && (UndefElements.none() || AllowUndefs)) {
9346       EVT CVT = CN->getValueType(0);
9347       EVT NSVT = N.getValueType().getScalarType();
9348       assert(CVT.bitsGE(NSVT) && "Illegal build vector element extension");
9349       if (AllowTruncation || (CVT == NSVT))
9350         return CN;
9351     }
9352   }
9353 
9354   return nullptr;
9355 }
9356 
9357 ConstantSDNode *llvm::isConstOrConstSplat(SDValue N, const APInt &DemandedElts,
9358                                           bool AllowUndefs,
9359                                           bool AllowTruncation) {
9360   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
9361     return CN;
9362 
9363   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
9364     BitVector UndefElements;
9365     ConstantSDNode *CN = BV->getConstantSplatNode(DemandedElts, &UndefElements);
9366 
9367     // BuildVectors can truncate their operands. Ignore that case here unless
9368     // AllowTruncation is set.
9369     if (CN && (UndefElements.none() || AllowUndefs)) {
9370       EVT CVT = CN->getValueType(0);
9371       EVT NSVT = N.getValueType().getScalarType();
9372       assert(CVT.bitsGE(NSVT) && "Illegal build vector element extension");
9373       if (AllowTruncation || (CVT == NSVT))
9374         return CN;
9375     }
9376   }
9377 
9378   return nullptr;
9379 }
9380 
9381 ConstantFPSDNode *llvm::isConstOrConstSplatFP(SDValue N, bool AllowUndefs) {
9382   if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
9383     return CN;
9384 
9385   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
9386     BitVector UndefElements;
9387     ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements);
9388     if (CN && (UndefElements.none() || AllowUndefs))
9389       return CN;
9390   }
9391 
9392   if (N.getOpcode() == ISD::SPLAT_VECTOR)
9393     if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N.getOperand(0)))
9394       return CN;
9395 
9396   return nullptr;
9397 }
9398 
9399 ConstantFPSDNode *llvm::isConstOrConstSplatFP(SDValue N,
9400                                               const APInt &DemandedElts,
9401                                               bool AllowUndefs) {
9402   if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
9403     return CN;
9404 
9405   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
9406     BitVector UndefElements;
9407     ConstantFPSDNode *CN =
9408         BV->getConstantFPSplatNode(DemandedElts, &UndefElements);
9409     if (CN && (UndefElements.none() || AllowUndefs))
9410       return CN;
9411   }
9412 
9413   return nullptr;
9414 }
9415 
9416 bool llvm::isNullOrNullSplat(SDValue N, bool AllowUndefs) {
9417   // TODO: may want to use peekThroughBitcast() here.
9418   ConstantSDNode *C = isConstOrConstSplat(N, AllowUndefs);
9419   return C && C->isNullValue();
9420 }
9421 
9422 bool llvm::isOneOrOneSplat(SDValue N, bool AllowUndefs) {
9423   // TODO: may want to use peekThroughBitcast() here.
9424   unsigned BitWidth = N.getScalarValueSizeInBits();
9425   ConstantSDNode *C = isConstOrConstSplat(N, AllowUndefs);
9426   return C && C->isOne() && C->getValueSizeInBits(0) == BitWidth;
9427 }
9428 
9429 bool llvm::isAllOnesOrAllOnesSplat(SDValue N, bool AllowUndefs) {
9430   N = peekThroughBitcasts(N);
9431   unsigned BitWidth = N.getScalarValueSizeInBits();
9432   ConstantSDNode *C = isConstOrConstSplat(N, AllowUndefs);
9433   return C && C->isAllOnesValue() && C->getValueSizeInBits(0) == BitWidth;
9434 }
9435 
9436 HandleSDNode::~HandleSDNode() {
9437   DropOperands();
9438 }
9439 
9440 GlobalAddressSDNode::GlobalAddressSDNode(unsigned Opc, unsigned Order,
9441                                          const DebugLoc &DL,
9442                                          const GlobalValue *GA, EVT VT,
9443                                          int64_t o, unsigned TF)
9444     : SDNode(Opc, Order, DL, getSDVTList(VT)), Offset(o), TargetFlags(TF) {
9445   TheGlobal = GA;
9446 }
9447 
9448 AddrSpaceCastSDNode::AddrSpaceCastSDNode(unsigned Order, const DebugLoc &dl,
9449                                          EVT VT, unsigned SrcAS,
9450                                          unsigned DestAS)
9451     : SDNode(ISD::ADDRSPACECAST, Order, dl, getSDVTList(VT)),
9452       SrcAddrSpace(SrcAS), DestAddrSpace(DestAS) {}
9453 
9454 MemSDNode::MemSDNode(unsigned Opc, unsigned Order, const DebugLoc &dl,
9455                      SDVTList VTs, EVT memvt, MachineMemOperand *mmo)
9456     : SDNode(Opc, Order, dl, VTs), MemoryVT(memvt), MMO(mmo) {
9457   MemSDNodeBits.IsVolatile = MMO->isVolatile();
9458   MemSDNodeBits.IsNonTemporal = MMO->isNonTemporal();
9459   MemSDNodeBits.IsDereferenceable = MMO->isDereferenceable();
9460   MemSDNodeBits.IsInvariant = MMO->isInvariant();
9461 
9462   // We check here that the size of the memory operand fits within the size of
9463   // the MMO. This is because the MMO might indicate only a possible address
9464   // range instead of specifying the affected memory addresses precisely.
9465   // TODO: Make MachineMemOperands aware of scalable vectors.
9466   assert(memvt.getStoreSize().getKnownMinSize() <= MMO->getSize() &&
9467          "Size mismatch!");
9468 }
9469 
9470 /// Profile - Gather unique data for the node.
9471 ///
9472 void SDNode::Profile(FoldingSetNodeID &ID) const {
9473   AddNodeIDNode(ID, this);
9474 }
9475 
9476 namespace {
9477 
9478   struct EVTArray {
9479     std::vector<EVT> VTs;
9480 
9481     EVTArray() {
9482       VTs.reserve(MVT::LAST_VALUETYPE);
9483       for (unsigned i = 0; i < MVT::LAST_VALUETYPE; ++i)
9484         VTs.push_back(MVT((MVT::SimpleValueType)i));
9485     }
9486   };
9487 
9488 } // end anonymous namespace
9489 
9490 static ManagedStatic<std::set<EVT, EVT::compareRawBits>> EVTs;
9491 static ManagedStatic<EVTArray> SimpleVTArray;
9492 static ManagedStatic<sys::SmartMutex<true>> VTMutex;
9493 
9494 /// getValueTypeList - Return a pointer to the specified value type.
9495 ///
9496 const EVT *SDNode::getValueTypeList(EVT VT) {
9497   if (VT.isExtended()) {
9498     sys::SmartScopedLock<true> Lock(*VTMutex);
9499     return &(*EVTs->insert(VT).first);
9500   } else {
9501     assert(VT.getSimpleVT() < MVT::LAST_VALUETYPE &&
9502            "Value type out of range!");
9503     return &SimpleVTArray->VTs[VT.getSimpleVT().SimpleTy];
9504   }
9505 }
9506 
9507 /// hasNUsesOfValue - Return true if there are exactly NUSES uses of the
9508 /// indicated value.  This method ignores uses of other values defined by this
9509 /// operation.
9510 bool SDNode::hasNUsesOfValue(unsigned NUses, unsigned Value) const {
9511   assert(Value < getNumValues() && "Bad value!");
9512 
9513   // TODO: Only iterate over uses of a given value of the node
9514   for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) {
9515     if (UI.getUse().getResNo() == Value) {
9516       if (NUses == 0)
9517         return false;
9518       --NUses;
9519     }
9520   }
9521 
9522   // Found exactly the right number of uses?
9523   return NUses == 0;
9524 }
9525 
9526 /// hasAnyUseOfValue - Return true if there are any use of the indicated
9527 /// value. This method ignores uses of other values defined by this operation.
9528 bool SDNode::hasAnyUseOfValue(unsigned Value) const {
9529   assert(Value < getNumValues() && "Bad value!");
9530 
9531   for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI)
9532     if (UI.getUse().getResNo() == Value)
9533       return true;
9534 
9535   return false;
9536 }
9537 
9538 /// isOnlyUserOf - Return true if this node is the only use of N.
9539 bool SDNode::isOnlyUserOf(const SDNode *N) const {
9540   bool Seen = false;
9541   for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) {
9542     SDNode *User = *I;
9543     if (User == this)
9544       Seen = true;
9545     else
9546       return false;
9547   }
9548 
9549   return Seen;
9550 }
9551 
9552 /// Return true if the only users of N are contained in Nodes.
9553 bool SDNode::areOnlyUsersOf(ArrayRef<const SDNode *> Nodes, const SDNode *N) {
9554   bool Seen = false;
9555   for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) {
9556     SDNode *User = *I;
9557     if (llvm::is_contained(Nodes, User))
9558       Seen = true;
9559     else
9560       return false;
9561   }
9562 
9563   return Seen;
9564 }
9565 
9566 /// isOperand - Return true if this node is an operand of N.
9567 bool SDValue::isOperandOf(const SDNode *N) const {
9568   return is_contained(N->op_values(), *this);
9569 }
9570 
9571 bool SDNode::isOperandOf(const SDNode *N) const {
9572   return any_of(N->op_values(),
9573                 [this](SDValue Op) { return this == Op.getNode(); });
9574 }
9575 
9576 /// reachesChainWithoutSideEffects - Return true if this operand (which must
9577 /// be a chain) reaches the specified operand without crossing any
9578 /// side-effecting instructions on any chain path.  In practice, this looks
9579 /// through token factors and non-volatile loads.  In order to remain efficient,
9580 /// this only looks a couple of nodes in, it does not do an exhaustive search.
9581 ///
9582 /// Note that we only need to examine chains when we're searching for
9583 /// side-effects; SelectionDAG requires that all side-effects are represented
9584 /// by chains, even if another operand would force a specific ordering. This
9585 /// constraint is necessary to allow transformations like splitting loads.
9586 bool SDValue::reachesChainWithoutSideEffects(SDValue Dest,
9587                                              unsigned Depth) const {
9588   if (*this == Dest) return true;
9589 
9590   // Don't search too deeply, we just want to be able to see through
9591   // TokenFactor's etc.
9592   if (Depth == 0) return false;
9593 
9594   // If this is a token factor, all inputs to the TF happen in parallel.
9595   if (getOpcode() == ISD::TokenFactor) {
9596     // First, try a shallow search.
9597     if (is_contained((*this)->ops(), Dest)) {
9598       // We found the chain we want as an operand of this TokenFactor.
9599       // Essentially, we reach the chain without side-effects if we could
9600       // serialize the TokenFactor into a simple chain of operations with
9601       // Dest as the last operation. This is automatically true if the
9602       // chain has one use: there are no other ordering constraints.
9603       // If the chain has more than one use, we give up: some other
9604       // use of Dest might force a side-effect between Dest and the current
9605       // node.
9606       if (Dest.hasOneUse())
9607         return true;
9608     }
9609     // Next, try a deep search: check whether every operand of the TokenFactor
9610     // reaches Dest.
9611     return llvm::all_of((*this)->ops(), [=](SDValue Op) {
9612       return Op.reachesChainWithoutSideEffects(Dest, Depth - 1);
9613     });
9614   }
9615 
9616   // Loads don't have side effects, look through them.
9617   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(*this)) {
9618     if (Ld->isUnordered())
9619       return Ld->getChain().reachesChainWithoutSideEffects(Dest, Depth-1);
9620   }
9621   return false;
9622 }
9623 
9624 bool SDNode::hasPredecessor(const SDNode *N) const {
9625   SmallPtrSet<const SDNode *, 32> Visited;
9626   SmallVector<const SDNode *, 16> Worklist;
9627   Worklist.push_back(this);
9628   return hasPredecessorHelper(N, Visited, Worklist);
9629 }
9630 
9631 void SDNode::intersectFlagsWith(const SDNodeFlags Flags) {
9632   this->Flags.intersectWith(Flags);
9633 }
9634 
9635 SDValue
9636 SelectionDAG::matchBinOpReduction(SDNode *Extract, ISD::NodeType &BinOp,
9637                                   ArrayRef<ISD::NodeType> CandidateBinOps,
9638                                   bool AllowPartials) {
9639   // The pattern must end in an extract from index 0.
9640   if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
9641       !isNullConstant(Extract->getOperand(1)))
9642     return SDValue();
9643 
9644   // Match against one of the candidate binary ops.
9645   SDValue Op = Extract->getOperand(0);
9646   if (llvm::none_of(CandidateBinOps, [Op](ISD::NodeType BinOp) {
9647         return Op.getOpcode() == unsigned(BinOp);
9648       }))
9649     return SDValue();
9650 
9651   // Floating-point reductions may require relaxed constraints on the final step
9652   // of the reduction because they may reorder intermediate operations.
9653   unsigned CandidateBinOp = Op.getOpcode();
9654   if (Op.getValueType().isFloatingPoint()) {
9655     SDNodeFlags Flags = Op->getFlags();
9656     switch (CandidateBinOp) {
9657     case ISD::FADD:
9658       if (!Flags.hasNoSignedZeros() || !Flags.hasAllowReassociation())
9659         return SDValue();
9660       break;
9661     default:
9662       llvm_unreachable("Unhandled FP opcode for binop reduction");
9663     }
9664   }
9665 
9666   // Matching failed - attempt to see if we did enough stages that a partial
9667   // reduction from a subvector is possible.
9668   auto PartialReduction = [&](SDValue Op, unsigned NumSubElts) {
9669     if (!AllowPartials || !Op)
9670       return SDValue();
9671     EVT OpVT = Op.getValueType();
9672     EVT OpSVT = OpVT.getScalarType();
9673     EVT SubVT = EVT::getVectorVT(*getContext(), OpSVT, NumSubElts);
9674     if (!TLI->isExtractSubvectorCheap(SubVT, OpVT, 0))
9675       return SDValue();
9676     BinOp = (ISD::NodeType)CandidateBinOp;
9677     return getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(Op), SubVT, Op,
9678                    getVectorIdxConstant(0, SDLoc(Op)));
9679   };
9680 
9681   // At each stage, we're looking for something that looks like:
9682   // %s = shufflevector <8 x i32> %op, <8 x i32> undef,
9683   //                    <8 x i32> <i32 2, i32 3, i32 undef, i32 undef,
9684   //                               i32 undef, i32 undef, i32 undef, i32 undef>
9685   // %a = binop <8 x i32> %op, %s
9686   // Where the mask changes according to the stage. E.g. for a 3-stage pyramid,
9687   // we expect something like:
9688   // <4,5,6,7,u,u,u,u>
9689   // <2,3,u,u,u,u,u,u>
9690   // <1,u,u,u,u,u,u,u>
9691   // While a partial reduction match would be:
9692   // <2,3,u,u,u,u,u,u>
9693   // <1,u,u,u,u,u,u,u>
9694   unsigned Stages = Log2_32(Op.getValueType().getVectorNumElements());
9695   SDValue PrevOp;
9696   for (unsigned i = 0; i < Stages; ++i) {
9697     unsigned MaskEnd = (1 << i);
9698 
9699     if (Op.getOpcode() != CandidateBinOp)
9700       return PartialReduction(PrevOp, MaskEnd);
9701 
9702     SDValue Op0 = Op.getOperand(0);
9703     SDValue Op1 = Op.getOperand(1);
9704 
9705     ShuffleVectorSDNode *Shuffle = dyn_cast<ShuffleVectorSDNode>(Op0);
9706     if (Shuffle) {
9707       Op = Op1;
9708     } else {
9709       Shuffle = dyn_cast<ShuffleVectorSDNode>(Op1);
9710       Op = Op0;
9711     }
9712 
9713     // The first operand of the shuffle should be the same as the other operand
9714     // of the binop.
9715     if (!Shuffle || Shuffle->getOperand(0) != Op)
9716       return PartialReduction(PrevOp, MaskEnd);
9717 
9718     // Verify the shuffle has the expected (at this stage of the pyramid) mask.
9719     for (int Index = 0; Index < (int)MaskEnd; ++Index)
9720       if (Shuffle->getMaskElt(Index) != (int)(MaskEnd + Index))
9721         return PartialReduction(PrevOp, MaskEnd);
9722 
9723     PrevOp = Op;
9724   }
9725 
9726   // Handle subvector reductions, which tend to appear after the shuffle
9727   // reduction stages.
9728   while (Op.getOpcode() == CandidateBinOp) {
9729     unsigned NumElts = Op.getValueType().getVectorNumElements();
9730     SDValue Op0 = Op.getOperand(0);
9731     SDValue Op1 = Op.getOperand(1);
9732     if (Op0.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
9733         Op1.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
9734         Op0.getOperand(0) != Op1.getOperand(0))
9735       break;
9736     SDValue Src = Op0.getOperand(0);
9737     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
9738     if (NumSrcElts != (2 * NumElts))
9739       break;
9740     if (!(Op0.getConstantOperandAPInt(1) == 0 &&
9741           Op1.getConstantOperandAPInt(1) == NumElts) &&
9742         !(Op1.getConstantOperandAPInt(1) == 0 &&
9743           Op0.getConstantOperandAPInt(1) == NumElts))
9744       break;
9745     Op = Src;
9746   }
9747 
9748   BinOp = (ISD::NodeType)CandidateBinOp;
9749   return Op;
9750 }
9751 
9752 SDValue SelectionDAG::UnrollVectorOp(SDNode *N, unsigned ResNE) {
9753   assert(N->getNumValues() == 1 &&
9754          "Can't unroll a vector with multiple results!");
9755 
9756   EVT VT = N->getValueType(0);
9757   unsigned NE = VT.getVectorNumElements();
9758   EVT EltVT = VT.getVectorElementType();
9759   SDLoc dl(N);
9760 
9761   SmallVector<SDValue, 8> Scalars;
9762   SmallVector<SDValue, 4> Operands(N->getNumOperands());
9763 
9764   // If ResNE is 0, fully unroll the vector op.
9765   if (ResNE == 0)
9766     ResNE = NE;
9767   else if (NE > ResNE)
9768     NE = ResNE;
9769 
9770   unsigned i;
9771   for (i= 0; i != NE; ++i) {
9772     for (unsigned j = 0, e = N->getNumOperands(); j != e; ++j) {
9773       SDValue Operand = N->getOperand(j);
9774       EVT OperandVT = Operand.getValueType();
9775       if (OperandVT.isVector()) {
9776         // A vector operand; extract a single element.
9777         EVT OperandEltVT = OperandVT.getVectorElementType();
9778         Operands[j] = getNode(ISD::EXTRACT_VECTOR_ELT, dl, OperandEltVT,
9779                               Operand, getVectorIdxConstant(i, dl));
9780       } else {
9781         // A scalar operand; just use it as is.
9782         Operands[j] = Operand;
9783       }
9784     }
9785 
9786     switch (N->getOpcode()) {
9787     default: {
9788       Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands,
9789                                 N->getFlags()));
9790       break;
9791     }
9792     case ISD::VSELECT:
9793       Scalars.push_back(getNode(ISD::SELECT, dl, EltVT, Operands));
9794       break;
9795     case ISD::SHL:
9796     case ISD::SRA:
9797     case ISD::SRL:
9798     case ISD::ROTL:
9799     case ISD::ROTR:
9800       Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands[0],
9801                                getShiftAmountOperand(Operands[0].getValueType(),
9802                                                      Operands[1])));
9803       break;
9804     case ISD::SIGN_EXTEND_INREG: {
9805       EVT ExtVT = cast<VTSDNode>(Operands[1])->getVT().getVectorElementType();
9806       Scalars.push_back(getNode(N->getOpcode(), dl, EltVT,
9807                                 Operands[0],
9808                                 getValueType(ExtVT)));
9809     }
9810     }
9811   }
9812 
9813   for (; i < ResNE; ++i)
9814     Scalars.push_back(getUNDEF(EltVT));
9815 
9816   EVT VecVT = EVT::getVectorVT(*getContext(), EltVT, ResNE);
9817   return getBuildVector(VecVT, dl, Scalars);
9818 }
9819 
9820 std::pair<SDValue, SDValue> SelectionDAG::UnrollVectorOverflowOp(
9821     SDNode *N, unsigned ResNE) {
9822   unsigned Opcode = N->getOpcode();
9823   assert((Opcode == ISD::UADDO || Opcode == ISD::SADDO ||
9824           Opcode == ISD::USUBO || Opcode == ISD::SSUBO ||
9825           Opcode == ISD::UMULO || Opcode == ISD::SMULO) &&
9826          "Expected an overflow opcode");
9827 
9828   EVT ResVT = N->getValueType(0);
9829   EVT OvVT = N->getValueType(1);
9830   EVT ResEltVT = ResVT.getVectorElementType();
9831   EVT OvEltVT = OvVT.getVectorElementType();
9832   SDLoc dl(N);
9833 
9834   // If ResNE is 0, fully unroll the vector op.
9835   unsigned NE = ResVT.getVectorNumElements();
9836   if (ResNE == 0)
9837     ResNE = NE;
9838   else if (NE > ResNE)
9839     NE = ResNE;
9840 
9841   SmallVector<SDValue, 8> LHSScalars;
9842   SmallVector<SDValue, 8> RHSScalars;
9843   ExtractVectorElements(N->getOperand(0), LHSScalars, 0, NE);
9844   ExtractVectorElements(N->getOperand(1), RHSScalars, 0, NE);
9845 
9846   EVT SVT = TLI->getSetCCResultType(getDataLayout(), *getContext(), ResEltVT);
9847   SDVTList VTs = getVTList(ResEltVT, SVT);
9848   SmallVector<SDValue, 8> ResScalars;
9849   SmallVector<SDValue, 8> OvScalars;
9850   for (unsigned i = 0; i < NE; ++i) {
9851     SDValue Res = getNode(Opcode, dl, VTs, LHSScalars[i], RHSScalars[i]);
9852     SDValue Ov =
9853         getSelect(dl, OvEltVT, Res.getValue(1),
9854                   getBoolConstant(true, dl, OvEltVT, ResVT),
9855                   getConstant(0, dl, OvEltVT));
9856 
9857     ResScalars.push_back(Res);
9858     OvScalars.push_back(Ov);
9859   }
9860 
9861   ResScalars.append(ResNE - NE, getUNDEF(ResEltVT));
9862   OvScalars.append(ResNE - NE, getUNDEF(OvEltVT));
9863 
9864   EVT NewResVT = EVT::getVectorVT(*getContext(), ResEltVT, ResNE);
9865   EVT NewOvVT = EVT::getVectorVT(*getContext(), OvEltVT, ResNE);
9866   return std::make_pair(getBuildVector(NewResVT, dl, ResScalars),
9867                         getBuildVector(NewOvVT, dl, OvScalars));
9868 }
9869 
9870 bool SelectionDAG::areNonVolatileConsecutiveLoads(LoadSDNode *LD,
9871                                                   LoadSDNode *Base,
9872                                                   unsigned Bytes,
9873                                                   int Dist) const {
9874   if (LD->isVolatile() || Base->isVolatile())
9875     return false;
9876   // TODO: probably too restrictive for atomics, revisit
9877   if (!LD->isSimple())
9878     return false;
9879   if (LD->isIndexed() || Base->isIndexed())
9880     return false;
9881   if (LD->getChain() != Base->getChain())
9882     return false;
9883   EVT VT = LD->getValueType(0);
9884   if (VT.getSizeInBits() / 8 != Bytes)
9885     return false;
9886 
9887   auto BaseLocDecomp = BaseIndexOffset::match(Base, *this);
9888   auto LocDecomp = BaseIndexOffset::match(LD, *this);
9889 
9890   int64_t Offset = 0;
9891   if (BaseLocDecomp.equalBaseIndex(LocDecomp, *this, Offset))
9892     return (Dist * Bytes == Offset);
9893   return false;
9894 }
9895 
9896 /// InferPtrAlignment - Infer alignment of a load / store address. Return None
9897 /// if it cannot be inferred.
9898 MaybeAlign SelectionDAG::InferPtrAlign(SDValue Ptr) const {
9899   // If this is a GlobalAddress + cst, return the alignment.
9900   const GlobalValue *GV = nullptr;
9901   int64_t GVOffset = 0;
9902   if (TLI->isGAPlusOffset(Ptr.getNode(), GV, GVOffset)) {
9903     unsigned PtrWidth = getDataLayout().getPointerTypeSizeInBits(GV->getType());
9904     KnownBits Known(PtrWidth);
9905     llvm::computeKnownBits(GV, Known, getDataLayout());
9906     unsigned AlignBits = Known.countMinTrailingZeros();
9907     if (AlignBits)
9908       return commonAlignment(Align(1ull << std::min(31U, AlignBits)), GVOffset);
9909   }
9910 
9911   // If this is a direct reference to a stack slot, use information about the
9912   // stack slot's alignment.
9913   int FrameIdx = INT_MIN;
9914   int64_t FrameOffset = 0;
9915   if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr)) {
9916     FrameIdx = FI->getIndex();
9917   } else if (isBaseWithConstantOffset(Ptr) &&
9918              isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
9919     // Handle FI+Cst
9920     FrameIdx = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
9921     FrameOffset = Ptr.getConstantOperandVal(1);
9922   }
9923 
9924   if (FrameIdx != INT_MIN) {
9925     const MachineFrameInfo &MFI = getMachineFunction().getFrameInfo();
9926     return commonAlignment(MFI.getObjectAlign(FrameIdx), FrameOffset);
9927   }
9928 
9929   return None;
9930 }
9931 
9932 /// GetSplitDestVTs - Compute the VTs needed for the low/hi parts of a type
9933 /// which is split (or expanded) into two not necessarily identical pieces.
9934 std::pair<EVT, EVT> SelectionDAG::GetSplitDestVTs(const EVT &VT) const {
9935   // Currently all types are split in half.
9936   EVT LoVT, HiVT;
9937   if (!VT.isVector())
9938     LoVT = HiVT = TLI->getTypeToTransformTo(*getContext(), VT);
9939   else
9940     LoVT = HiVT = VT.getHalfNumVectorElementsVT(*getContext());
9941 
9942   return std::make_pair(LoVT, HiVT);
9943 }
9944 
9945 /// GetDependentSplitDestVTs - Compute the VTs needed for the low/hi parts of a
9946 /// type, dependent on an enveloping VT that has been split into two identical
9947 /// pieces. Sets the HiIsEmpty flag when hi type has zero storage size.
9948 std::pair<EVT, EVT>
9949 SelectionDAG::GetDependentSplitDestVTs(const EVT &VT, const EVT &EnvVT,
9950                                        bool *HiIsEmpty) const {
9951   EVT EltTp = VT.getVectorElementType();
9952   // Examples:
9953   //   custom VL=8  with enveloping VL=8/8 yields 8/0 (hi empty)
9954   //   custom VL=9  with enveloping VL=8/8 yields 8/1
9955   //   custom VL=10 with enveloping VL=8/8 yields 8/2
9956   //   etc.
9957   ElementCount VTNumElts = VT.getVectorElementCount();
9958   ElementCount EnvNumElts = EnvVT.getVectorElementCount();
9959   assert(VTNumElts.isScalable() == EnvNumElts.isScalable() &&
9960          "Mixing fixed width and scalable vectors when enveloping a type");
9961   EVT LoVT, HiVT;
9962   if (VTNumElts.getKnownMinValue() > EnvNumElts.getKnownMinValue()) {
9963     LoVT = EnvVT;
9964     HiVT = EVT::getVectorVT(*getContext(), EltTp, VTNumElts - EnvNumElts);
9965     *HiIsEmpty = false;
9966   } else {
9967     // Flag that hi type has zero storage size, but return split envelop type
9968     // (this would be easier if vector types with zero elements were allowed).
9969     LoVT = EVT::getVectorVT(*getContext(), EltTp, VTNumElts);
9970     HiVT = EnvVT;
9971     *HiIsEmpty = true;
9972   }
9973   return std::make_pair(LoVT, HiVT);
9974 }
9975 
9976 /// SplitVector - Split the vector with EXTRACT_SUBVECTOR and return the
9977 /// low/high part.
9978 std::pair<SDValue, SDValue>
9979 SelectionDAG::SplitVector(const SDValue &N, const SDLoc &DL, const EVT &LoVT,
9980                           const EVT &HiVT) {
9981   assert(LoVT.isScalableVector() == HiVT.isScalableVector() &&
9982          LoVT.isScalableVector() == N.getValueType().isScalableVector() &&
9983          "Splitting vector with an invalid mixture of fixed and scalable "
9984          "vector types");
9985   assert(LoVT.getVectorMinNumElements() + HiVT.getVectorMinNumElements() <=
9986              N.getValueType().getVectorMinNumElements() &&
9987          "More vector elements requested than available!");
9988   SDValue Lo, Hi;
9989   Lo =
9990       getNode(ISD::EXTRACT_SUBVECTOR, DL, LoVT, N, getVectorIdxConstant(0, DL));
9991   // For scalable vectors it is safe to use LoVT.getVectorMinNumElements()
9992   // (rather than having to use ElementCount), because EXTRACT_SUBVECTOR scales
9993   // IDX with the runtime scaling factor of the result vector type. For
9994   // fixed-width result vectors, that runtime scaling factor is 1.
9995   Hi = getNode(ISD::EXTRACT_SUBVECTOR, DL, HiVT, N,
9996                getVectorIdxConstant(LoVT.getVectorMinNumElements(), DL));
9997   return std::make_pair(Lo, Hi);
9998 }
9999 
10000 /// Widen the vector up to the next power of two using INSERT_SUBVECTOR.
10001 SDValue SelectionDAG::WidenVector(const SDValue &N, const SDLoc &DL) {
10002   EVT VT = N.getValueType();
10003   EVT WideVT = EVT::getVectorVT(*getContext(), VT.getVectorElementType(),
10004                                 NextPowerOf2(VT.getVectorNumElements()));
10005   return getNode(ISD::INSERT_SUBVECTOR, DL, WideVT, getUNDEF(WideVT), N,
10006                  getVectorIdxConstant(0, DL));
10007 }
10008 
10009 void SelectionDAG::ExtractVectorElements(SDValue Op,
10010                                          SmallVectorImpl<SDValue> &Args,
10011                                          unsigned Start, unsigned Count,
10012                                          EVT EltVT) {
10013   EVT VT = Op.getValueType();
10014   if (Count == 0)
10015     Count = VT.getVectorNumElements();
10016   if (EltVT == EVT())
10017     EltVT = VT.getVectorElementType();
10018   SDLoc SL(Op);
10019   for (unsigned i = Start, e = Start + Count; i != e; ++i) {
10020     Args.push_back(getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Op,
10021                            getVectorIdxConstant(i, SL)));
10022   }
10023 }
10024 
10025 // getAddressSpace - Return the address space this GlobalAddress belongs to.
10026 unsigned GlobalAddressSDNode::getAddressSpace() const {
10027   return getGlobal()->getType()->getAddressSpace();
10028 }
10029 
10030 Type *ConstantPoolSDNode::getType() const {
10031   if (isMachineConstantPoolEntry())
10032     return Val.MachineCPVal->getType();
10033   return Val.ConstVal->getType();
10034 }
10035 
10036 bool BuildVectorSDNode::isConstantSplat(APInt &SplatValue, APInt &SplatUndef,
10037                                         unsigned &SplatBitSize,
10038                                         bool &HasAnyUndefs,
10039                                         unsigned MinSplatBits,
10040                                         bool IsBigEndian) const {
10041   EVT VT = getValueType(0);
10042   assert(VT.isVector() && "Expected a vector type");
10043   unsigned VecWidth = VT.getSizeInBits();
10044   if (MinSplatBits > VecWidth)
10045     return false;
10046 
10047   // FIXME: The widths are based on this node's type, but build vectors can
10048   // truncate their operands.
10049   SplatValue = APInt(VecWidth, 0);
10050   SplatUndef = APInt(VecWidth, 0);
10051 
10052   // Get the bits. Bits with undefined values (when the corresponding element
10053   // of the vector is an ISD::UNDEF value) are set in SplatUndef and cleared
10054   // in SplatValue. If any of the values are not constant, give up and return
10055   // false.
10056   unsigned int NumOps = getNumOperands();
10057   assert(NumOps > 0 && "isConstantSplat has 0-size build vector");
10058   unsigned EltWidth = VT.getScalarSizeInBits();
10059 
10060   for (unsigned j = 0; j < NumOps; ++j) {
10061     unsigned i = IsBigEndian ? NumOps - 1 - j : j;
10062     SDValue OpVal = getOperand(i);
10063     unsigned BitPos = j * EltWidth;
10064 
10065     if (OpVal.isUndef())
10066       SplatUndef.setBits(BitPos, BitPos + EltWidth);
10067     else if (auto *CN = dyn_cast<ConstantSDNode>(OpVal))
10068       SplatValue.insertBits(CN->getAPIntValue().zextOrTrunc(EltWidth), BitPos);
10069     else if (auto *CN = dyn_cast<ConstantFPSDNode>(OpVal))
10070       SplatValue.insertBits(CN->getValueAPF().bitcastToAPInt(), BitPos);
10071     else
10072       return false;
10073   }
10074 
10075   // The build_vector is all constants or undefs. Find the smallest element
10076   // size that splats the vector.
10077   HasAnyUndefs = (SplatUndef != 0);
10078 
10079   // FIXME: This does not work for vectors with elements less than 8 bits.
10080   while (VecWidth > 8) {
10081     unsigned HalfSize = VecWidth / 2;
10082     APInt HighValue = SplatValue.lshr(HalfSize).trunc(HalfSize);
10083     APInt LowValue = SplatValue.trunc(HalfSize);
10084     APInt HighUndef = SplatUndef.lshr(HalfSize).trunc(HalfSize);
10085     APInt LowUndef = SplatUndef.trunc(HalfSize);
10086 
10087     // If the two halves do not match (ignoring undef bits), stop here.
10088     if ((HighValue & ~LowUndef) != (LowValue & ~HighUndef) ||
10089         MinSplatBits > HalfSize)
10090       break;
10091 
10092     SplatValue = HighValue | LowValue;
10093     SplatUndef = HighUndef & LowUndef;
10094 
10095     VecWidth = HalfSize;
10096   }
10097 
10098   SplatBitSize = VecWidth;
10099   return true;
10100 }
10101 
10102 SDValue BuildVectorSDNode::getSplatValue(const APInt &DemandedElts,
10103                                          BitVector *UndefElements) const {
10104   unsigned NumOps = getNumOperands();
10105   if (UndefElements) {
10106     UndefElements->clear();
10107     UndefElements->resize(NumOps);
10108   }
10109   assert(NumOps == DemandedElts.getBitWidth() && "Unexpected vector size");
10110   if (!DemandedElts)
10111     return SDValue();
10112   SDValue Splatted;
10113   for (unsigned i = 0; i != NumOps; ++i) {
10114     if (!DemandedElts[i])
10115       continue;
10116     SDValue Op = getOperand(i);
10117     if (Op.isUndef()) {
10118       if (UndefElements)
10119         (*UndefElements)[i] = true;
10120     } else if (!Splatted) {
10121       Splatted = Op;
10122     } else if (Splatted != Op) {
10123       return SDValue();
10124     }
10125   }
10126 
10127   if (!Splatted) {
10128     unsigned FirstDemandedIdx = DemandedElts.countTrailingZeros();
10129     assert(getOperand(FirstDemandedIdx).isUndef() &&
10130            "Can only have a splat without a constant for all undefs.");
10131     return getOperand(FirstDemandedIdx);
10132   }
10133 
10134   return Splatted;
10135 }
10136 
10137 SDValue BuildVectorSDNode::getSplatValue(BitVector *UndefElements) const {
10138   APInt DemandedElts = APInt::getAllOnesValue(getNumOperands());
10139   return getSplatValue(DemandedElts, UndefElements);
10140 }
10141 
10142 bool BuildVectorSDNode::getRepeatedSequence(const APInt &DemandedElts,
10143                                             SmallVectorImpl<SDValue> &Sequence,
10144                                             BitVector *UndefElements) const {
10145   unsigned NumOps = getNumOperands();
10146   Sequence.clear();
10147   if (UndefElements) {
10148     UndefElements->clear();
10149     UndefElements->resize(NumOps);
10150   }
10151   assert(NumOps == DemandedElts.getBitWidth() && "Unexpected vector size");
10152   if (!DemandedElts || NumOps < 2 || !isPowerOf2_32(NumOps))
10153     return false;
10154 
10155   // Set the undefs even if we don't find a sequence (like getSplatValue).
10156   if (UndefElements)
10157     for (unsigned I = 0; I != NumOps; ++I)
10158       if (DemandedElts[I] && getOperand(I).isUndef())
10159         (*UndefElements)[I] = true;
10160 
10161   // Iteratively widen the sequence length looking for repetitions.
10162   for (unsigned SeqLen = 1; SeqLen < NumOps; SeqLen *= 2) {
10163     Sequence.append(SeqLen, SDValue());
10164     for (unsigned I = 0; I != NumOps; ++I) {
10165       if (!DemandedElts[I])
10166         continue;
10167       SDValue &SeqOp = Sequence[I % SeqLen];
10168       SDValue Op = getOperand(I);
10169       if (Op.isUndef()) {
10170         if (!SeqOp)
10171           SeqOp = Op;
10172         continue;
10173       }
10174       if (SeqOp && !SeqOp.isUndef() && SeqOp != Op) {
10175         Sequence.clear();
10176         break;
10177       }
10178       SeqOp = Op;
10179     }
10180     if (!Sequence.empty())
10181       return true;
10182   }
10183 
10184   assert(Sequence.empty() && "Failed to empty non-repeating sequence pattern");
10185   return false;
10186 }
10187 
10188 bool BuildVectorSDNode::getRepeatedSequence(SmallVectorImpl<SDValue> &Sequence,
10189                                             BitVector *UndefElements) const {
10190   APInt DemandedElts = APInt::getAllOnesValue(getNumOperands());
10191   return getRepeatedSequence(DemandedElts, Sequence, UndefElements);
10192 }
10193 
10194 ConstantSDNode *
10195 BuildVectorSDNode::getConstantSplatNode(const APInt &DemandedElts,
10196                                         BitVector *UndefElements) const {
10197   return dyn_cast_or_null<ConstantSDNode>(
10198       getSplatValue(DemandedElts, UndefElements));
10199 }
10200 
10201 ConstantSDNode *
10202 BuildVectorSDNode::getConstantSplatNode(BitVector *UndefElements) const {
10203   return dyn_cast_or_null<ConstantSDNode>(getSplatValue(UndefElements));
10204 }
10205 
10206 ConstantFPSDNode *
10207 BuildVectorSDNode::getConstantFPSplatNode(const APInt &DemandedElts,
10208                                           BitVector *UndefElements) const {
10209   return dyn_cast_or_null<ConstantFPSDNode>(
10210       getSplatValue(DemandedElts, UndefElements));
10211 }
10212 
10213 ConstantFPSDNode *
10214 BuildVectorSDNode::getConstantFPSplatNode(BitVector *UndefElements) const {
10215   return dyn_cast_or_null<ConstantFPSDNode>(getSplatValue(UndefElements));
10216 }
10217 
10218 int32_t
10219 BuildVectorSDNode::getConstantFPSplatPow2ToLog2Int(BitVector *UndefElements,
10220                                                    uint32_t BitWidth) const {
10221   if (ConstantFPSDNode *CN =
10222           dyn_cast_or_null<ConstantFPSDNode>(getSplatValue(UndefElements))) {
10223     bool IsExact;
10224     APSInt IntVal(BitWidth);
10225     const APFloat &APF = CN->getValueAPF();
10226     if (APF.convertToInteger(IntVal, APFloat::rmTowardZero, &IsExact) !=
10227             APFloat::opOK ||
10228         !IsExact)
10229       return -1;
10230 
10231     return IntVal.exactLogBase2();
10232   }
10233   return -1;
10234 }
10235 
10236 bool BuildVectorSDNode::isConstant() const {
10237   for (const SDValue &Op : op_values()) {
10238     unsigned Opc = Op.getOpcode();
10239     if (Opc != ISD::UNDEF && Opc != ISD::Constant && Opc != ISD::ConstantFP)
10240       return false;
10241   }
10242   return true;
10243 }
10244 
10245 bool ShuffleVectorSDNode::isSplatMask(const int *Mask, EVT VT) {
10246   // Find the first non-undef value in the shuffle mask.
10247   unsigned i, e;
10248   for (i = 0, e = VT.getVectorNumElements(); i != e && Mask[i] < 0; ++i)
10249     /* search */;
10250 
10251   // If all elements are undefined, this shuffle can be considered a splat
10252   // (although it should eventually get simplified away completely).
10253   if (i == e)
10254     return true;
10255 
10256   // Make sure all remaining elements are either undef or the same as the first
10257   // non-undef value.
10258   for (int Idx = Mask[i]; i != e; ++i)
10259     if (Mask[i] >= 0 && Mask[i] != Idx)
10260       return false;
10261   return true;
10262 }
10263 
10264 // Returns the SDNode if it is a constant integer BuildVector
10265 // or constant integer.
10266 SDNode *SelectionDAG::isConstantIntBuildVectorOrConstantInt(SDValue N) const {
10267   if (isa<ConstantSDNode>(N))
10268     return N.getNode();
10269   if (ISD::isBuildVectorOfConstantSDNodes(N.getNode()))
10270     return N.getNode();
10271   // Treat a GlobalAddress supporting constant offset folding as a
10272   // constant integer.
10273   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N))
10274     if (GA->getOpcode() == ISD::GlobalAddress &&
10275         TLI->isOffsetFoldingLegal(GA))
10276       return GA;
10277   if ((N.getOpcode() == ISD::SPLAT_VECTOR) &&
10278       isa<ConstantSDNode>(N.getOperand(0)))
10279     return N.getNode();
10280   return nullptr;
10281 }
10282 
10283 // Returns the SDNode if it is a constant float BuildVector
10284 // or constant float.
10285 SDNode *SelectionDAG::isConstantFPBuildVectorOrConstantFP(SDValue N) const {
10286   if (isa<ConstantFPSDNode>(N))
10287     return N.getNode();
10288 
10289   if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode()))
10290     return N.getNode();
10291 
10292   return nullptr;
10293 }
10294 
10295 void SelectionDAG::createOperands(SDNode *Node, ArrayRef<SDValue> Vals) {
10296   assert(!Node->OperandList && "Node already has operands");
10297   assert(SDNode::getMaxNumOperands() >= Vals.size() &&
10298          "too many operands to fit into SDNode");
10299   SDUse *Ops = OperandRecycler.allocate(
10300       ArrayRecycler<SDUse>::Capacity::get(Vals.size()), OperandAllocator);
10301 
10302   bool IsDivergent = false;
10303   for (unsigned I = 0; I != Vals.size(); ++I) {
10304     Ops[I].setUser(Node);
10305     Ops[I].setInitial(Vals[I]);
10306     if (Ops[I].Val.getValueType() != MVT::Other) // Skip Chain. It does not carry divergence.
10307       IsDivergent |= Ops[I].getNode()->isDivergent();
10308   }
10309   Node->NumOperands = Vals.size();
10310   Node->OperandList = Ops;
10311   if (!TLI->isSDNodeAlwaysUniform(Node)) {
10312     IsDivergent |= TLI->isSDNodeSourceOfDivergence(Node, FLI, DA);
10313     Node->SDNodeBits.IsDivergent = IsDivergent;
10314   }
10315   checkForCycles(Node);
10316 }
10317 
10318 SDValue SelectionDAG::getTokenFactor(const SDLoc &DL,
10319                                      SmallVectorImpl<SDValue> &Vals) {
10320   size_t Limit = SDNode::getMaxNumOperands();
10321   while (Vals.size() > Limit) {
10322     unsigned SliceIdx = Vals.size() - Limit;
10323     auto ExtractedTFs = ArrayRef<SDValue>(Vals).slice(SliceIdx, Limit);
10324     SDValue NewTF = getNode(ISD::TokenFactor, DL, MVT::Other, ExtractedTFs);
10325     Vals.erase(Vals.begin() + SliceIdx, Vals.end());
10326     Vals.emplace_back(NewTF);
10327   }
10328   return getNode(ISD::TokenFactor, DL, MVT::Other, Vals);
10329 }
10330 
10331 SDValue SelectionDAG::getNeutralElement(unsigned Opcode, const SDLoc &DL,
10332                                         EVT VT, SDNodeFlags Flags) {
10333   switch (Opcode) {
10334   default:
10335     return SDValue();
10336   case ISD::ADD:
10337   case ISD::OR:
10338   case ISD::XOR:
10339   case ISD::UMAX:
10340     return getConstant(0, DL, VT);
10341   case ISD::MUL:
10342     return getConstant(1, DL, VT);
10343   case ISD::AND:
10344   case ISD::UMIN:
10345     return getAllOnesConstant(DL, VT);
10346   case ISD::SMAX:
10347     return getConstant(APInt::getSignedMinValue(VT.getSizeInBits()), DL, VT);
10348   case ISD::SMIN:
10349     return getConstant(APInt::getSignedMaxValue(VT.getSizeInBits()), DL, VT);
10350   case ISD::FADD:
10351     return getConstantFP(-0.0, DL, VT);
10352   case ISD::FMUL:
10353     return getConstantFP(1.0, DL, VT);
10354   case ISD::FMINNUM:
10355   case ISD::FMAXNUM: {
10356     // Neutral element for fminnum is NaN, Inf or FLT_MAX, depending on FMF.
10357     const fltSemantics &Semantics = EVTToAPFloatSemantics(VT);
10358     APFloat NeutralAF = !Flags.hasNoNaNs() ? APFloat::getQNaN(Semantics) :
10359                         !Flags.hasNoInfs() ? APFloat::getInf(Semantics) :
10360                         APFloat::getLargest(Semantics);
10361     if (Opcode == ISD::FMAXNUM)
10362       NeutralAF.changeSign();
10363 
10364     return getConstantFP(NeutralAF, DL, VT);
10365   }
10366   }
10367 }
10368 
10369 #ifndef NDEBUG
10370 static void checkForCyclesHelper(const SDNode *N,
10371                                  SmallPtrSetImpl<const SDNode*> &Visited,
10372                                  SmallPtrSetImpl<const SDNode*> &Checked,
10373                                  const llvm::SelectionDAG *DAG) {
10374   // If this node has already been checked, don't check it again.
10375   if (Checked.count(N))
10376     return;
10377 
10378   // If a node has already been visited on this depth-first walk, reject it as
10379   // a cycle.
10380   if (!Visited.insert(N).second) {
10381     errs() << "Detected cycle in SelectionDAG\n";
10382     dbgs() << "Offending node:\n";
10383     N->dumprFull(DAG); dbgs() << "\n";
10384     abort();
10385   }
10386 
10387   for (const SDValue &Op : N->op_values())
10388     checkForCyclesHelper(Op.getNode(), Visited, Checked, DAG);
10389 
10390   Checked.insert(N);
10391   Visited.erase(N);
10392 }
10393 #endif
10394 
10395 void llvm::checkForCycles(const llvm::SDNode *N,
10396                           const llvm::SelectionDAG *DAG,
10397                           bool force) {
10398 #ifndef NDEBUG
10399   bool check = force;
10400 #ifdef EXPENSIVE_CHECKS
10401   check = true;
10402 #endif  // EXPENSIVE_CHECKS
10403   if (check) {
10404     assert(N && "Checking nonexistent SDNode");
10405     SmallPtrSet<const SDNode*, 32> visited;
10406     SmallPtrSet<const SDNode*, 32> checked;
10407     checkForCyclesHelper(N, visited, checked, DAG);
10408   }
10409 #endif  // !NDEBUG
10410 }
10411 
10412 void llvm::checkForCycles(const llvm::SelectionDAG *DAG, bool force) {
10413   checkForCycles(DAG->getRoot().getNode(), DAG, force);
10414 }
10415