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