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