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