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