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