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