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