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