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