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