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.zext(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     // Bitcast 'large element' scalar/vector to 'small element' vector.
3244     // TODO: Handle cases other than 'sign splat' when we have a use case.
3245     // Requires handling of DemandedElts and Endianness.
3246     if ((SrcBits % VTBits) == 0) {
3247       assert(Op.getValueType().isVector() && "Expected bitcast to vector");
3248       Tmp = ComputeNumSignBits(N0, Depth + 1);
3249       if (Tmp == SrcBits)
3250         return VTBits;
3251     }
3252     break;
3253   }
3254 
3255   case ISD::SIGN_EXTEND:
3256     Tmp = VTBits - Op.getOperand(0).getScalarValueSizeInBits();
3257     return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1) + Tmp;
3258   case ISD::SIGN_EXTEND_INREG:
3259     // Max of the input and what this extends.
3260     Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getScalarSizeInBits();
3261     Tmp = VTBits-Tmp+1;
3262     Tmp2 = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1);
3263     return std::max(Tmp, Tmp2);
3264   case ISD::SIGN_EXTEND_VECTOR_INREG: {
3265     SDValue Src = Op.getOperand(0);
3266     EVT SrcVT = Src.getValueType();
3267     APInt DemandedSrcElts = DemandedElts.zext(SrcVT.getVectorNumElements());
3268     Tmp = VTBits - SrcVT.getScalarSizeInBits();
3269     return ComputeNumSignBits(Src, DemandedSrcElts, Depth+1) + Tmp;
3270   }
3271 
3272   case ISD::SRA:
3273     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1);
3274     // SRA X, C   -> adds C sign bits.
3275     if (ConstantSDNode *C =
3276             isConstOrDemandedConstSplat(Op.getOperand(1), DemandedElts)) {
3277       APInt ShiftVal = C->getAPIntValue();
3278       ShiftVal += Tmp;
3279       Tmp = ShiftVal.uge(VTBits) ? VTBits : ShiftVal.getZExtValue();
3280     }
3281     return Tmp;
3282   case ISD::SHL:
3283     if (ConstantSDNode *C =
3284             isConstOrDemandedConstSplat(Op.getOperand(1), DemandedElts)) {
3285       // shl destroys sign bits.
3286       Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1);
3287       if (C->getAPIntValue().uge(VTBits) ||      // Bad shift.
3288           C->getAPIntValue().uge(Tmp)) break;    // Shifted all sign bits out.
3289       return Tmp - C->getZExtValue();
3290     }
3291     break;
3292   case ISD::AND:
3293   case ISD::OR:
3294   case ISD::XOR:    // NOT is handled here.
3295     // Logical binary ops preserve the number of sign bits at the worst.
3296     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1);
3297     if (Tmp != 1) {
3298       Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth+1);
3299       FirstAnswer = std::min(Tmp, Tmp2);
3300       // We computed what we know about the sign bits as our first
3301       // answer. Now proceed to the generic code that uses
3302       // computeKnownBits, and pick whichever answer is better.
3303     }
3304     break;
3305 
3306   case ISD::SELECT:
3307   case ISD::VSELECT:
3308     Tmp = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth+1);
3309     if (Tmp == 1) return 1;  // Early out.
3310     Tmp2 = ComputeNumSignBits(Op.getOperand(2), DemandedElts, Depth+1);
3311     return std::min(Tmp, Tmp2);
3312   case ISD::SELECT_CC:
3313     Tmp = ComputeNumSignBits(Op.getOperand(2), DemandedElts, Depth+1);
3314     if (Tmp == 1) return 1;  // Early out.
3315     Tmp2 = ComputeNumSignBits(Op.getOperand(3), DemandedElts, Depth+1);
3316     return std::min(Tmp, Tmp2);
3317 
3318   case ISD::SMIN:
3319   case ISD::SMAX: {
3320     // If we have a clamp pattern, we know that the number of sign bits will be
3321     // the minimum of the clamp min/max range.
3322     bool IsMax = (Opcode == ISD::SMAX);
3323     ConstantSDNode *CstLow = nullptr, *CstHigh = nullptr;
3324     if ((CstLow = isConstOrDemandedConstSplat(Op.getOperand(1), DemandedElts)))
3325       if (Op.getOperand(0).getOpcode() == (IsMax ? ISD::SMIN : ISD::SMAX))
3326         CstHigh = isConstOrDemandedConstSplat(Op.getOperand(0).getOperand(1),
3327                                               DemandedElts);
3328     if (CstLow && CstHigh) {
3329       if (!IsMax)
3330         std::swap(CstLow, CstHigh);
3331       if (CstLow->getAPIntValue().sle(CstHigh->getAPIntValue())) {
3332         Tmp = CstLow->getAPIntValue().getNumSignBits();
3333         Tmp2 = CstHigh->getAPIntValue().getNumSignBits();
3334         return std::min(Tmp, Tmp2);
3335       }
3336     }
3337 
3338     // Fallback - just get the minimum number of sign bits of the operands.
3339     Tmp = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
3340     if (Tmp == 1)
3341       return 1;  // Early out.
3342     Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth + 1);
3343     return std::min(Tmp, Tmp2);
3344   }
3345   case ISD::UMIN:
3346   case ISD::UMAX:
3347     Tmp = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
3348     if (Tmp == 1)
3349       return 1;  // Early out.
3350     Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth + 1);
3351     return std::min(Tmp, Tmp2);
3352   case ISD::SADDO:
3353   case ISD::UADDO:
3354   case ISD::SSUBO:
3355   case ISD::USUBO:
3356   case ISD::SMULO:
3357   case ISD::UMULO:
3358     if (Op.getResNo() != 1)
3359       break;
3360     // The boolean result conforms to getBooleanContents.  Fall through.
3361     // If setcc returns 0/-1, all bits are sign bits.
3362     // We know that we have an integer-based boolean since these operations
3363     // are only available for integer.
3364     if (TLI->getBooleanContents(Op.getValueType().isVector(), false) ==
3365         TargetLowering::ZeroOrNegativeOneBooleanContent)
3366       return VTBits;
3367     break;
3368   case ISD::SETCC:
3369     // If setcc returns 0/-1, all bits are sign bits.
3370     if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) ==
3371         TargetLowering::ZeroOrNegativeOneBooleanContent)
3372       return VTBits;
3373     break;
3374   case ISD::ROTL:
3375   case ISD::ROTR:
3376     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
3377       unsigned RotAmt = C->getAPIntValue().urem(VTBits);
3378 
3379       // Handle rotate right by N like a rotate left by 32-N.
3380       if (Opcode == ISD::ROTR)
3381         RotAmt = (VTBits - RotAmt) % VTBits;
3382 
3383       // If we aren't rotating out all of the known-in sign bits, return the
3384       // number that are left.  This handles rotl(sext(x), 1) for example.
3385       Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
3386       if (Tmp > (RotAmt + 1)) return (Tmp - RotAmt);
3387     }
3388     break;
3389   case ISD::ADD:
3390   case ISD::ADDC:
3391     // Add can have at most one carry bit.  Thus we know that the output
3392     // is, at worst, one more bit than the inputs.
3393     Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
3394     if (Tmp == 1) return 1;  // Early out.
3395 
3396     // Special case decrementing a value (ADD X, -1):
3397     if (ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
3398       if (CRHS->isAllOnesValue()) {
3399         KnownBits Known;
3400         computeKnownBits(Op.getOperand(0), Known, Depth+1);
3401 
3402         // If the input is known to be 0 or 1, the output is 0/-1, which is all
3403         // sign bits set.
3404         if ((Known.Zero | 1).isAllOnesValue())
3405           return VTBits;
3406 
3407         // If we are subtracting one from a positive number, there is no carry
3408         // out of the result.
3409         if (Known.isNonNegative())
3410           return Tmp;
3411       }
3412 
3413     Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
3414     if (Tmp2 == 1) return 1;
3415     return std::min(Tmp, Tmp2)-1;
3416 
3417   case ISD::SUB:
3418     Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
3419     if (Tmp2 == 1) return 1;
3420 
3421     // Handle NEG.
3422     if (ConstantSDNode *CLHS = isConstOrConstSplat(Op.getOperand(0)))
3423       if (CLHS->isNullValue()) {
3424         KnownBits Known;
3425         computeKnownBits(Op.getOperand(1), Known, Depth+1);
3426         // If the input is known to be 0 or 1, the output is 0/-1, which is all
3427         // sign bits set.
3428         if ((Known.Zero | 1).isAllOnesValue())
3429           return VTBits;
3430 
3431         // If the input is known to be positive (the sign bit is known clear),
3432         // the output of the NEG has the same number of sign bits as the input.
3433         if (Known.isNonNegative())
3434           return Tmp2;
3435 
3436         // Otherwise, we treat this like a SUB.
3437       }
3438 
3439     // Sub can have at most one carry bit.  Thus we know that the output
3440     // is, at worst, one more bit than the inputs.
3441     Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
3442     if (Tmp == 1) return 1;  // Early out.
3443     return std::min(Tmp, Tmp2)-1;
3444   case ISD::TRUNCATE: {
3445     // Check if the sign bits of source go down as far as the truncated value.
3446     unsigned NumSrcBits = Op.getOperand(0).getScalarValueSizeInBits();
3447     unsigned NumSrcSignBits = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
3448     if (NumSrcSignBits > (NumSrcBits - VTBits))
3449       return NumSrcSignBits - (NumSrcBits - VTBits);
3450     break;
3451   }
3452   case ISD::EXTRACT_ELEMENT: {
3453     const int KnownSign = ComputeNumSignBits(Op.getOperand(0), Depth+1);
3454     const int BitWidth = Op.getValueSizeInBits();
3455     const int Items = Op.getOperand(0).getValueSizeInBits() / BitWidth;
3456 
3457     // Get reverse index (starting from 1), Op1 value indexes elements from
3458     // little end. Sign starts at big end.
3459     const int rIndex = Items - 1 - Op.getConstantOperandVal(1);
3460 
3461     // If the sign portion ends in our element the subtraction gives correct
3462     // result. Otherwise it gives either negative or > bitwidth result
3463     return std::max(std::min(KnownSign - rIndex * BitWidth, BitWidth), 0);
3464   }
3465   case ISD::INSERT_VECTOR_ELT: {
3466     SDValue InVec = Op.getOperand(0);
3467     SDValue InVal = Op.getOperand(1);
3468     SDValue EltNo = Op.getOperand(2);
3469     unsigned NumElts = InVec.getValueType().getVectorNumElements();
3470 
3471     ConstantSDNode *CEltNo = dyn_cast<ConstantSDNode>(EltNo);
3472     if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) {
3473       // If we know the element index, split the demand between the
3474       // source vector and the inserted element.
3475       unsigned EltIdx = CEltNo->getZExtValue();
3476 
3477       // If we demand the inserted element then get its sign bits.
3478       Tmp = std::numeric_limits<unsigned>::max();
3479       if (DemandedElts[EltIdx]) {
3480         // TODO - handle implicit truncation of inserted elements.
3481         if (InVal.getScalarValueSizeInBits() != VTBits)
3482           break;
3483         Tmp = ComputeNumSignBits(InVal, Depth + 1);
3484       }
3485 
3486       // If we demand the source vector then get its sign bits, and determine
3487       // the minimum.
3488       APInt VectorElts = DemandedElts;
3489       VectorElts.clearBit(EltIdx);
3490       if (!!VectorElts) {
3491         Tmp2 = ComputeNumSignBits(InVec, VectorElts, Depth + 1);
3492         Tmp = std::min(Tmp, Tmp2);
3493       }
3494     } else {
3495       // Unknown element index, so ignore DemandedElts and demand them all.
3496       Tmp = ComputeNumSignBits(InVec, Depth + 1);
3497       Tmp2 = ComputeNumSignBits(InVal, Depth + 1);
3498       Tmp = std::min(Tmp, Tmp2);
3499     }
3500     assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
3501     return Tmp;
3502   }
3503   case ISD::EXTRACT_VECTOR_ELT: {
3504     SDValue InVec = Op.getOperand(0);
3505     SDValue EltNo = Op.getOperand(1);
3506     EVT VecVT = InVec.getValueType();
3507     const unsigned BitWidth = Op.getValueSizeInBits();
3508     const unsigned EltBitWidth = Op.getOperand(0).getScalarValueSizeInBits();
3509     const unsigned NumSrcElts = VecVT.getVectorNumElements();
3510 
3511     // If BitWidth > EltBitWidth the value is anyext:ed, and we do not know
3512     // anything about sign bits. But if the sizes match we can derive knowledge
3513     // about sign bits from the vector operand.
3514     if (BitWidth != EltBitWidth)
3515       break;
3516 
3517     // If we know the element index, just demand that vector element, else for
3518     // an unknown element index, ignore DemandedElts and demand them all.
3519     APInt DemandedSrcElts = APInt::getAllOnesValue(NumSrcElts);
3520     ConstantSDNode *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
3521     if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts))
3522       DemandedSrcElts =
3523           APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue());
3524 
3525     return ComputeNumSignBits(InVec, DemandedSrcElts, Depth + 1);
3526   }
3527   case ISD::EXTRACT_SUBVECTOR: {
3528     // If we know the element index, just demand that subvector elements,
3529     // otherwise demand them all.
3530     SDValue Src = Op.getOperand(0);
3531     ConstantSDNode *SubIdx = dyn_cast<ConstantSDNode>(Op.getOperand(1));
3532     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
3533     if (SubIdx && SubIdx->getAPIntValue().ule(NumSrcElts - NumElts)) {
3534       // Offset the demanded elts by the subvector index.
3535       uint64_t Idx = SubIdx->getZExtValue();
3536       APInt DemandedSrc = DemandedElts.zext(NumSrcElts).shl(Idx);
3537       return ComputeNumSignBits(Src, DemandedSrc, Depth + 1);
3538     }
3539     return ComputeNumSignBits(Src, Depth + 1);
3540   }
3541   case ISD::CONCAT_VECTORS:
3542     // Determine the minimum number of sign bits across all demanded
3543     // elts of the input vectors. Early out if the result is already 1.
3544     Tmp = std::numeric_limits<unsigned>::max();
3545     EVT SubVectorVT = Op.getOperand(0).getValueType();
3546     unsigned NumSubVectorElts = SubVectorVT.getVectorNumElements();
3547     unsigned NumSubVectors = Op.getNumOperands();
3548     for (unsigned i = 0; (i < NumSubVectors) && (Tmp > 1); ++i) {
3549       APInt DemandedSub = DemandedElts.lshr(i * NumSubVectorElts);
3550       DemandedSub = DemandedSub.trunc(NumSubVectorElts);
3551       if (!DemandedSub)
3552         continue;
3553       Tmp2 = ComputeNumSignBits(Op.getOperand(i), DemandedSub, Depth + 1);
3554       Tmp = std::min(Tmp, Tmp2);
3555     }
3556     assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
3557     return Tmp;
3558   }
3559 
3560   // If we are looking at the loaded value of the SDNode.
3561   if (Op.getResNo() == 0) {
3562     // Handle LOADX separately here. EXTLOAD case will fallthrough.
3563     if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
3564       unsigned ExtType = LD->getExtensionType();
3565       switch (ExtType) {
3566         default: break;
3567         case ISD::SEXTLOAD:    // '17' bits known
3568           Tmp = LD->getMemoryVT().getScalarSizeInBits();
3569           return VTBits-Tmp+1;
3570         case ISD::ZEXTLOAD:    // '16' bits known
3571           Tmp = LD->getMemoryVT().getScalarSizeInBits();
3572           return VTBits-Tmp;
3573       }
3574     }
3575   }
3576 
3577   // Allow the target to implement this method for its nodes.
3578   if (Opcode >= ISD::BUILTIN_OP_END ||
3579       Opcode == ISD::INTRINSIC_WO_CHAIN ||
3580       Opcode == ISD::INTRINSIC_W_CHAIN ||
3581       Opcode == ISD::INTRINSIC_VOID) {
3582     unsigned NumBits =
3583         TLI->ComputeNumSignBitsForTargetNode(Op, DemandedElts, *this, Depth);
3584     if (NumBits > 1)
3585       FirstAnswer = std::max(FirstAnswer, NumBits);
3586   }
3587 
3588   // Finally, if we can prove that the top bits of the result are 0's or 1's,
3589   // use this information.
3590   KnownBits Known;
3591   computeKnownBits(Op, Known, DemandedElts, Depth);
3592 
3593   APInt Mask;
3594   if (Known.isNonNegative()) {        // sign bit is 0
3595     Mask = Known.Zero;
3596   } else if (Known.isNegative()) {  // sign bit is 1;
3597     Mask = Known.One;
3598   } else {
3599     // Nothing known.
3600     return FirstAnswer;
3601   }
3602 
3603   // Okay, we know that the sign bit in Mask is set.  Use CLZ to determine
3604   // the number of identical bits in the top of the input value.
3605   Mask = ~Mask;
3606   Mask <<= Mask.getBitWidth()-VTBits;
3607   // Return # leading zeros.  We use 'min' here in case Val was zero before
3608   // shifting.  We don't want to return '64' as for an i32 "0".
3609   return std::max(FirstAnswer, std::min(VTBits, Mask.countLeadingZeros()));
3610 }
3611 
3612 bool SelectionDAG::isBaseWithConstantOffset(SDValue Op) const {
3613   if ((Op.getOpcode() != ISD::ADD && Op.getOpcode() != ISD::OR) ||
3614       !isa<ConstantSDNode>(Op.getOperand(1)))
3615     return false;
3616 
3617   if (Op.getOpcode() == ISD::OR &&
3618       !MaskedValueIsZero(Op.getOperand(0),
3619                      cast<ConstantSDNode>(Op.getOperand(1))->getAPIntValue()))
3620     return false;
3621 
3622   return true;
3623 }
3624 
3625 bool SelectionDAG::isKnownNeverNaN(SDValue Op, bool SNaN, unsigned Depth) const {
3626   // If we're told that NaNs won't happen, assume they won't.
3627   if (getTarget().Options.NoNaNsFPMath || Op->getFlags().hasNoNaNs())
3628     return true;
3629 
3630   if (Depth == 6)
3631     return false; // Limit search depth.
3632 
3633   // TODO: Handle vectors.
3634   // If the value is a constant, we can obviously see if it is a NaN or not.
3635   if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) {
3636     return !C->getValueAPF().isNaN() ||
3637            (SNaN && !C->getValueAPF().isSignaling());
3638   }
3639 
3640   unsigned Opcode = Op.getOpcode();
3641   switch (Opcode) {
3642   case ISD::FADD:
3643   case ISD::FSUB:
3644   case ISD::FMUL: {
3645     if (SNaN)
3646       return true;
3647     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) &&
3648            isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1);
3649   }
3650   case ISD::FCANONICALIZE:
3651   case ISD::FEXP:
3652   case ISD::FEXP2:
3653   case ISD::FTRUNC:
3654   case ISD::FFLOOR:
3655   case ISD::FCEIL:
3656   case ISD::FROUND:
3657   case ISD::FRINT:
3658   case ISD::FNEARBYINT: {
3659     if (SNaN)
3660       return true;
3661     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
3662   }
3663   case ISD::FABS:
3664   case ISD::FNEG:
3665   case ISD::FCOPYSIGN: {
3666     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
3667   }
3668   case ISD::SELECT:
3669     return isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1) &&
3670            isKnownNeverNaN(Op.getOperand(2), SNaN, Depth + 1);
3671   case ISD::FDIV:
3672   case ISD::FREM:
3673   case ISD::FSIN:
3674   case ISD::FCOS: {
3675     if (SNaN)
3676       return true;
3677     // TODO: Need isKnownNeverInfinity
3678     return false;
3679   }
3680   case ISD::FP_EXTEND:
3681   case ISD::FP_ROUND: {
3682     if (SNaN)
3683       return true;
3684     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
3685   }
3686   case ISD::SINT_TO_FP:
3687   case ISD::UINT_TO_FP:
3688     return true;
3689   case ISD::FMA:
3690   case ISD::FMAD: {
3691     if (SNaN)
3692       return true;
3693     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) &&
3694            isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1) &&
3695            isKnownNeverNaN(Op.getOperand(2), SNaN, Depth + 1);
3696   }
3697   case ISD::FSQRT: // Need is known positive
3698   case ISD::FLOG:
3699   case ISD::FLOG2:
3700   case ISD::FLOG10:
3701   case ISD::FPOWI:
3702   case ISD::FPOW: {
3703     if (SNaN)
3704       return true;
3705     // TODO: Refine on operand
3706     return false;
3707   }
3708 
3709   // TODO: Handle FMINNUM/FMAXNUM/FMINNAN/FMAXNAN when there is an agreement on
3710   // what they should do.
3711   default:
3712     if (Opcode >= ISD::BUILTIN_OP_END ||
3713         Opcode == ISD::INTRINSIC_WO_CHAIN ||
3714         Opcode == ISD::INTRINSIC_W_CHAIN ||
3715         Opcode == ISD::INTRINSIC_VOID) {
3716       return TLI->isKnownNeverNaNForTargetNode(Op, *this, SNaN, Depth);
3717     }
3718 
3719     return false;
3720   }
3721 }
3722 
3723 bool SelectionDAG::isKnownNeverZeroFloat(SDValue Op) const {
3724   assert(Op.getValueType().isFloatingPoint() &&
3725          "Floating point type expected");
3726 
3727   // If the value is a constant, we can obviously see if it is a zero or not.
3728   // TODO: Add BuildVector support.
3729   if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op))
3730     return !C->isZero();
3731   return false;
3732 }
3733 
3734 bool SelectionDAG::isKnownNeverZero(SDValue Op) const {
3735   assert(!Op.getValueType().isFloatingPoint() &&
3736          "Floating point types unsupported - use isKnownNeverZeroFloat");
3737 
3738   // If the value is a constant, we can obviously see if it is a zero or not.
3739   if (ISD::matchUnaryPredicate(
3740           Op, [](ConstantSDNode *C) { return !C->isNullValue(); }))
3741     return true;
3742 
3743   // TODO: Recognize more cases here.
3744   switch (Op.getOpcode()) {
3745   default: break;
3746   case ISD::OR:
3747     if (isKnownNeverZero(Op.getOperand(1)) ||
3748         isKnownNeverZero(Op.getOperand(0)))
3749       return true;
3750     break;
3751   }
3752 
3753   return false;
3754 }
3755 
3756 bool SelectionDAG::isEqualTo(SDValue A, SDValue B) const {
3757   // Check the obvious case.
3758   if (A == B) return true;
3759 
3760   // For for negative and positive zero.
3761   if (const ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A))
3762     if (const ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B))
3763       if (CA->isZero() && CB->isZero()) return true;
3764 
3765   // Otherwise they may not be equal.
3766   return false;
3767 }
3768 
3769 // FIXME: unify with llvm::haveNoCommonBitsSet.
3770 // FIXME: could also handle masked merge pattern (X & ~M) op (Y & M)
3771 bool SelectionDAG::haveNoCommonBitsSet(SDValue A, SDValue B) const {
3772   assert(A.getValueType() == B.getValueType() &&
3773          "Values must have the same type");
3774   KnownBits AKnown, BKnown;
3775   computeKnownBits(A, AKnown);
3776   computeKnownBits(B, BKnown);
3777   return (AKnown.Zero | BKnown.Zero).isAllOnesValue();
3778 }
3779 
3780 static SDValue FoldCONCAT_VECTORS(const SDLoc &DL, EVT VT,
3781                                   ArrayRef<SDValue> Ops,
3782                                   SelectionDAG &DAG) {
3783   assert(!Ops.empty() && "Can't concatenate an empty list of vectors!");
3784   assert(llvm::all_of(Ops,
3785                       [Ops](SDValue Op) {
3786                         return Ops[0].getValueType() == Op.getValueType();
3787                       }) &&
3788          "Concatenation of vectors with inconsistent value types!");
3789   assert((Ops.size() * Ops[0].getValueType().getVectorNumElements()) ==
3790              VT.getVectorNumElements() &&
3791          "Incorrect element count in vector concatenation!");
3792 
3793   if (Ops.size() == 1)
3794     return Ops[0];
3795 
3796   // Concat of UNDEFs is UNDEF.
3797   if (llvm::all_of(Ops, [](SDValue Op) { return Op.isUndef(); }))
3798     return DAG.getUNDEF(VT);
3799 
3800   // A CONCAT_VECTOR with all UNDEF/BUILD_VECTOR operands can be
3801   // simplified to one big BUILD_VECTOR.
3802   // FIXME: Add support for SCALAR_TO_VECTOR as well.
3803   EVT SVT = VT.getScalarType();
3804   SmallVector<SDValue, 16> Elts;
3805   for (SDValue Op : Ops) {
3806     EVT OpVT = Op.getValueType();
3807     if (Op.isUndef())
3808       Elts.append(OpVT.getVectorNumElements(), DAG.getUNDEF(SVT));
3809     else if (Op.getOpcode() == ISD::BUILD_VECTOR)
3810       Elts.append(Op->op_begin(), Op->op_end());
3811     else
3812       return SDValue();
3813   }
3814 
3815   // BUILD_VECTOR requires all inputs to be of the same type, find the
3816   // maximum type and extend them all.
3817   for (SDValue Op : Elts)
3818     SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
3819 
3820   if (SVT.bitsGT(VT.getScalarType()))
3821     for (SDValue &Op : Elts)
3822       Op = DAG.getTargetLoweringInfo().isZExtFree(Op.getValueType(), SVT)
3823                ? DAG.getZExtOrTrunc(Op, DL, SVT)
3824                : DAG.getSExtOrTrunc(Op, DL, SVT);
3825 
3826   SDValue V = DAG.getBuildVector(VT, DL, Elts);
3827   NewSDValueDbgMsg(V, "New node fold concat vectors: ", &DAG);
3828   return V;
3829 }
3830 
3831 /// Gets or creates the specified node.
3832 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT) {
3833   FoldingSetNodeID ID;
3834   AddNodeIDNode(ID, Opcode, getVTList(VT), None);
3835   void *IP = nullptr;
3836   if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
3837     return SDValue(E, 0);
3838 
3839   auto *N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(),
3840                               getVTList(VT));
3841   CSEMap.InsertNode(N, IP);
3842 
3843   InsertNode(N);
3844   SDValue V = SDValue(N, 0);
3845   NewSDValueDbgMsg(V, "Creating new node: ", this);
3846   return V;
3847 }
3848 
3849 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
3850                               SDValue Operand, const SDNodeFlags Flags) {
3851   // Constant fold unary operations with an integer constant operand. Even
3852   // opaque constant will be folded, because the folding of unary operations
3853   // doesn't create new constants with different values. Nevertheless, the
3854   // opaque flag is preserved during folding to prevent future folding with
3855   // other constants.
3856   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Operand)) {
3857     const APInt &Val = C->getAPIntValue();
3858     switch (Opcode) {
3859     default: break;
3860     case ISD::SIGN_EXTEND:
3861       return getConstant(Val.sextOrTrunc(VT.getSizeInBits()), DL, VT,
3862                          C->isTargetOpcode(), C->isOpaque());
3863     case ISD::ANY_EXTEND:
3864     case ISD::ZERO_EXTEND:
3865     case ISD::TRUNCATE:
3866       return getConstant(Val.zextOrTrunc(VT.getSizeInBits()), DL, VT,
3867                          C->isTargetOpcode(), C->isOpaque());
3868     case ISD::UINT_TO_FP:
3869     case ISD::SINT_TO_FP: {
3870       APFloat apf(EVTToAPFloatSemantics(VT),
3871                   APInt::getNullValue(VT.getSizeInBits()));
3872       (void)apf.convertFromAPInt(Val,
3873                                  Opcode==ISD::SINT_TO_FP,
3874                                  APFloat::rmNearestTiesToEven);
3875       return getConstantFP(apf, DL, VT);
3876     }
3877     case ISD::BITCAST:
3878       if (VT == MVT::f16 && C->getValueType(0) == MVT::i16)
3879         return getConstantFP(APFloat(APFloat::IEEEhalf(), Val), DL, VT);
3880       if (VT == MVT::f32 && C->getValueType(0) == MVT::i32)
3881         return getConstantFP(APFloat(APFloat::IEEEsingle(), Val), DL, VT);
3882       if (VT == MVT::f64 && C->getValueType(0) == MVT::i64)
3883         return getConstantFP(APFloat(APFloat::IEEEdouble(), Val), DL, VT);
3884       if (VT == MVT::f128 && C->getValueType(0) == MVT::i128)
3885         return getConstantFP(APFloat(APFloat::IEEEquad(), Val), DL, VT);
3886       break;
3887     case ISD::ABS:
3888       return getConstant(Val.abs(), DL, VT, C->isTargetOpcode(),
3889                          C->isOpaque());
3890     case ISD::BITREVERSE:
3891       return getConstant(Val.reverseBits(), DL, VT, C->isTargetOpcode(),
3892                          C->isOpaque());
3893     case ISD::BSWAP:
3894       return getConstant(Val.byteSwap(), DL, VT, C->isTargetOpcode(),
3895                          C->isOpaque());
3896     case ISD::CTPOP:
3897       return getConstant(Val.countPopulation(), DL, VT, C->isTargetOpcode(),
3898                          C->isOpaque());
3899     case ISD::CTLZ:
3900     case ISD::CTLZ_ZERO_UNDEF:
3901       return getConstant(Val.countLeadingZeros(), DL, VT, C->isTargetOpcode(),
3902                          C->isOpaque());
3903     case ISD::CTTZ:
3904     case ISD::CTTZ_ZERO_UNDEF:
3905       return getConstant(Val.countTrailingZeros(), DL, VT, C->isTargetOpcode(),
3906                          C->isOpaque());
3907     case ISD::FP16_TO_FP: {
3908       bool Ignored;
3909       APFloat FPV(APFloat::IEEEhalf(),
3910                   (Val.getBitWidth() == 16) ? Val : Val.trunc(16));
3911 
3912       // This can return overflow, underflow, or inexact; we don't care.
3913       // FIXME need to be more flexible about rounding mode.
3914       (void)FPV.convert(EVTToAPFloatSemantics(VT),
3915                         APFloat::rmNearestTiesToEven, &Ignored);
3916       return getConstantFP(FPV, DL, VT);
3917     }
3918     }
3919   }
3920 
3921   // Constant fold unary operations with a floating point constant operand.
3922   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Operand)) {
3923     APFloat V = C->getValueAPF();    // make copy
3924     switch (Opcode) {
3925     case ISD::FNEG:
3926       V.changeSign();
3927       return getConstantFP(V, DL, VT);
3928     case ISD::FABS:
3929       V.clearSign();
3930       return getConstantFP(V, DL, VT);
3931     case ISD::FCEIL: {
3932       APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardPositive);
3933       if (fs == APFloat::opOK || fs == APFloat::opInexact)
3934         return getConstantFP(V, DL, VT);
3935       break;
3936     }
3937     case ISD::FTRUNC: {
3938       APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardZero);
3939       if (fs == APFloat::opOK || fs == APFloat::opInexact)
3940         return getConstantFP(V, DL, VT);
3941       break;
3942     }
3943     case ISD::FFLOOR: {
3944       APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardNegative);
3945       if (fs == APFloat::opOK || fs == APFloat::opInexact)
3946         return getConstantFP(V, DL, VT);
3947       break;
3948     }
3949     case ISD::FP_EXTEND: {
3950       bool ignored;
3951       // This can return overflow, underflow, or inexact; we don't care.
3952       // FIXME need to be more flexible about rounding mode.
3953       (void)V.convert(EVTToAPFloatSemantics(VT),
3954                       APFloat::rmNearestTiesToEven, &ignored);
3955       return getConstantFP(V, DL, VT);
3956     }
3957     case ISD::FP_TO_SINT:
3958     case ISD::FP_TO_UINT: {
3959       bool ignored;
3960       APSInt IntVal(VT.getSizeInBits(), Opcode == ISD::FP_TO_UINT);
3961       // FIXME need to be more flexible about rounding mode.
3962       APFloat::opStatus s =
3963           V.convertToInteger(IntVal, APFloat::rmTowardZero, &ignored);
3964       if (s == APFloat::opInvalidOp) // inexact is OK, in fact usual
3965         break;
3966       return getConstant(IntVal, DL, VT);
3967     }
3968     case ISD::BITCAST:
3969       if (VT == MVT::i16 && C->getValueType(0) == MVT::f16)
3970         return getConstant((uint16_t)V.bitcastToAPInt().getZExtValue(), DL, VT);
3971       else if (VT == MVT::i32 && C->getValueType(0) == MVT::f32)
3972         return getConstant((uint32_t)V.bitcastToAPInt().getZExtValue(), DL, VT);
3973       else if (VT == MVT::i64 && C->getValueType(0) == MVT::f64)
3974         return getConstant(V.bitcastToAPInt().getZExtValue(), DL, VT);
3975       break;
3976     case ISD::FP_TO_FP16: {
3977       bool Ignored;
3978       // This can return overflow, underflow, or inexact; we don't care.
3979       // FIXME need to be more flexible about rounding mode.
3980       (void)V.convert(APFloat::IEEEhalf(),
3981                       APFloat::rmNearestTiesToEven, &Ignored);
3982       return getConstant(V.bitcastToAPInt(), DL, VT);
3983     }
3984     }
3985   }
3986 
3987   // Constant fold unary operations with a vector integer or float operand.
3988   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Operand)) {
3989     if (BV->isConstant()) {
3990       switch (Opcode) {
3991       default:
3992         // FIXME: Entirely reasonable to perform folding of other unary
3993         // operations here as the need arises.
3994         break;
3995       case ISD::FNEG:
3996       case ISD::FABS:
3997       case ISD::FCEIL:
3998       case ISD::FTRUNC:
3999       case ISD::FFLOOR:
4000       case ISD::FP_EXTEND:
4001       case ISD::FP_TO_SINT:
4002       case ISD::FP_TO_UINT:
4003       case ISD::TRUNCATE:
4004       case ISD::ANY_EXTEND:
4005       case ISD::ZERO_EXTEND:
4006       case ISD::SIGN_EXTEND:
4007       case ISD::UINT_TO_FP:
4008       case ISD::SINT_TO_FP:
4009       case ISD::ABS:
4010       case ISD::BITREVERSE:
4011       case ISD::BSWAP:
4012       case ISD::CTLZ:
4013       case ISD::CTLZ_ZERO_UNDEF:
4014       case ISD::CTTZ:
4015       case ISD::CTTZ_ZERO_UNDEF:
4016       case ISD::CTPOP: {
4017         SDValue Ops = { Operand };
4018         if (SDValue Fold = FoldConstantVectorArithmetic(Opcode, DL, VT, Ops))
4019           return Fold;
4020       }
4021       }
4022     }
4023   }
4024 
4025   unsigned OpOpcode = Operand.getNode()->getOpcode();
4026   switch (Opcode) {
4027   case ISD::TokenFactor:
4028   case ISD::MERGE_VALUES:
4029   case ISD::CONCAT_VECTORS:
4030     return Operand;         // Factor, merge or concat of one node?  No need.
4031   case ISD::FP_ROUND: llvm_unreachable("Invalid method to make FP_ROUND node");
4032   case ISD::FP_EXTEND:
4033     assert(VT.isFloatingPoint() &&
4034            Operand.getValueType().isFloatingPoint() && "Invalid FP cast!");
4035     if (Operand.getValueType() == VT) return Operand;  // noop conversion.
4036     assert((!VT.isVector() ||
4037             VT.getVectorNumElements() ==
4038             Operand.getValueType().getVectorNumElements()) &&
4039            "Vector element count mismatch!");
4040     assert(Operand.getValueType().bitsLT(VT) &&
4041            "Invalid fpext node, dst < src!");
4042     if (Operand.isUndef())
4043       return getUNDEF(VT);
4044     break;
4045   case ISD::SIGN_EXTEND:
4046     assert(VT.isInteger() && Operand.getValueType().isInteger() &&
4047            "Invalid SIGN_EXTEND!");
4048     if (Operand.getValueType() == VT) return Operand;   // noop extension
4049     assert((!VT.isVector() ||
4050             VT.getVectorNumElements() ==
4051             Operand.getValueType().getVectorNumElements()) &&
4052            "Vector element count mismatch!");
4053     assert(Operand.getValueType().bitsLT(VT) &&
4054            "Invalid sext node, dst < src!");
4055     if (OpOpcode == ISD::SIGN_EXTEND || OpOpcode == ISD::ZERO_EXTEND)
4056       return getNode(OpOpcode, DL, VT, Operand.getOperand(0));
4057     else if (OpOpcode == ISD::UNDEF)
4058       // sext(undef) = 0, because the top bits will all be the same.
4059       return getConstant(0, DL, VT);
4060     break;
4061   case ISD::ZERO_EXTEND:
4062     assert(VT.isInteger() && Operand.getValueType().isInteger() &&
4063            "Invalid ZERO_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 zext node, dst < src!");
4071     if (OpOpcode == ISD::ZERO_EXTEND)   // (zext (zext x)) -> (zext x)
4072       return getNode(ISD::ZERO_EXTEND, DL, VT, Operand.getOperand(0));
4073     else if (OpOpcode == ISD::UNDEF)
4074       // zext(undef) = 0, because the top bits will be zero.
4075       return getConstant(0, DL, VT);
4076     break;
4077   case ISD::ANY_EXTEND:
4078     assert(VT.isInteger() && Operand.getValueType().isInteger() &&
4079            "Invalid ANY_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 anyext node, dst < src!");
4087 
4088     if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
4089         OpOpcode == ISD::ANY_EXTEND)
4090       // (ext (zext x)) -> (zext x)  and  (ext (sext x)) -> (sext x)
4091       return getNode(OpOpcode, DL, VT, Operand.getOperand(0));
4092     else if (OpOpcode == ISD::UNDEF)
4093       return getUNDEF(VT);
4094 
4095     // (ext (trunc x)) -> x
4096     if (OpOpcode == ISD::TRUNCATE) {
4097       SDValue OpOp = Operand.getOperand(0);
4098       if (OpOp.getValueType() == VT) {
4099         transferDbgValues(Operand, OpOp);
4100         return OpOp;
4101       }
4102     }
4103     break;
4104   case ISD::TRUNCATE:
4105     assert(VT.isInteger() && Operand.getValueType().isInteger() &&
4106            "Invalid TRUNCATE!");
4107     if (Operand.getValueType() == VT) return Operand;   // noop truncate
4108     assert((!VT.isVector() ||
4109             VT.getVectorNumElements() ==
4110             Operand.getValueType().getVectorNumElements()) &&
4111            "Vector element count mismatch!");
4112     assert(Operand.getValueType().bitsGT(VT) &&
4113            "Invalid truncate node, src < dst!");
4114     if (OpOpcode == ISD::TRUNCATE)
4115       return getNode(ISD::TRUNCATE, DL, VT, Operand.getOperand(0));
4116     if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
4117         OpOpcode == ISD::ANY_EXTEND) {
4118       // If the source is smaller than the dest, we still need an extend.
4119       if (Operand.getOperand(0).getValueType().getScalarType()
4120             .bitsLT(VT.getScalarType()))
4121         return getNode(OpOpcode, DL, VT, Operand.getOperand(0));
4122       if (Operand.getOperand(0).getValueType().bitsGT(VT))
4123         return getNode(ISD::TRUNCATE, DL, VT, Operand.getOperand(0));
4124       return Operand.getOperand(0);
4125     }
4126     if (OpOpcode == ISD::UNDEF)
4127       return getUNDEF(VT);
4128     break;
4129   case ISD::ABS:
4130     assert(VT.isInteger() && VT == Operand.getValueType() &&
4131            "Invalid ABS!");
4132     if (OpOpcode == ISD::UNDEF)
4133       return getUNDEF(VT);
4134     break;
4135   case ISD::BSWAP:
4136     assert(VT.isInteger() && VT == Operand.getValueType() &&
4137            "Invalid BSWAP!");
4138     assert((VT.getScalarSizeInBits() % 16 == 0) &&
4139            "BSWAP types must be a multiple of 16 bits!");
4140     if (OpOpcode == ISD::UNDEF)
4141       return getUNDEF(VT);
4142     break;
4143   case ISD::BITREVERSE:
4144     assert(VT.isInteger() && VT == Operand.getValueType() &&
4145            "Invalid BITREVERSE!");
4146     if (OpOpcode == ISD::UNDEF)
4147       return getUNDEF(VT);
4148     break;
4149   case ISD::BITCAST:
4150     // Basic sanity checking.
4151     assert(VT.getSizeInBits() == Operand.getValueSizeInBits() &&
4152            "Cannot BITCAST between types of different sizes!");
4153     if (VT == Operand.getValueType()) return Operand;  // noop conversion.
4154     if (OpOpcode == ISD::BITCAST)  // bitconv(bitconv(x)) -> bitconv(x)
4155       return getNode(ISD::BITCAST, DL, VT, Operand.getOperand(0));
4156     if (OpOpcode == ISD::UNDEF)
4157       return getUNDEF(VT);
4158     break;
4159   case ISD::SCALAR_TO_VECTOR:
4160     assert(VT.isVector() && !Operand.getValueType().isVector() &&
4161            (VT.getVectorElementType() == Operand.getValueType() ||
4162             (VT.getVectorElementType().isInteger() &&
4163              Operand.getValueType().isInteger() &&
4164              VT.getVectorElementType().bitsLE(Operand.getValueType()))) &&
4165            "Illegal SCALAR_TO_VECTOR node!");
4166     if (OpOpcode == ISD::UNDEF)
4167       return getUNDEF(VT);
4168     // scalar_to_vector(extract_vector_elt V, 0) -> V, top bits are undefined.
4169     if (OpOpcode == ISD::EXTRACT_VECTOR_ELT &&
4170         isa<ConstantSDNode>(Operand.getOperand(1)) &&
4171         Operand.getConstantOperandVal(1) == 0 &&
4172         Operand.getOperand(0).getValueType() == VT)
4173       return Operand.getOperand(0);
4174     break;
4175   case ISD::FNEG:
4176     // -(X-Y) -> (Y-X) is unsafe because when X==Y, -0.0 != +0.0
4177     if ((getTarget().Options.UnsafeFPMath || Flags.hasNoSignedZeros()) &&
4178         OpOpcode == ISD::FSUB)
4179       return getNode(ISD::FSUB, DL, VT, Operand.getOperand(1),
4180                      Operand.getOperand(0), Flags);
4181     if (OpOpcode == ISD::FNEG)  // --X -> X
4182       return Operand.getOperand(0);
4183     break;
4184   case ISD::FABS:
4185     if (OpOpcode == ISD::FNEG)  // abs(-X) -> abs(X)
4186       return getNode(ISD::FABS, DL, VT, Operand.getOperand(0));
4187     break;
4188   }
4189 
4190   SDNode *N;
4191   SDVTList VTs = getVTList(VT);
4192   SDValue Ops[] = {Operand};
4193   if (VT != MVT::Glue) { // Don't CSE flag producing nodes
4194     FoldingSetNodeID ID;
4195     AddNodeIDNode(ID, Opcode, VTs, Ops);
4196     void *IP = nullptr;
4197     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
4198       E->intersectFlagsWith(Flags);
4199       return SDValue(E, 0);
4200     }
4201 
4202     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
4203     N->setFlags(Flags);
4204     createOperands(N, Ops);
4205     CSEMap.InsertNode(N, IP);
4206   } else {
4207     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
4208     createOperands(N, Ops);
4209   }
4210 
4211   InsertNode(N);
4212   SDValue V = SDValue(N, 0);
4213   NewSDValueDbgMsg(V, "Creating new node: ", this);
4214   return V;
4215 }
4216 
4217 static std::pair<APInt, bool> FoldValue(unsigned Opcode, const APInt &C1,
4218                                         const APInt &C2) {
4219   switch (Opcode) {
4220   case ISD::ADD:  return std::make_pair(C1 + C2, true);
4221   case ISD::SUB:  return std::make_pair(C1 - C2, true);
4222   case ISD::MUL:  return std::make_pair(C1 * C2, true);
4223   case ISD::AND:  return std::make_pair(C1 & C2, true);
4224   case ISD::OR:   return std::make_pair(C1 | C2, true);
4225   case ISD::XOR:  return std::make_pair(C1 ^ C2, true);
4226   case ISD::SHL:  return std::make_pair(C1 << C2, true);
4227   case ISD::SRL:  return std::make_pair(C1.lshr(C2), true);
4228   case ISD::SRA:  return std::make_pair(C1.ashr(C2), true);
4229   case ISD::ROTL: return std::make_pair(C1.rotl(C2), true);
4230   case ISD::ROTR: return std::make_pair(C1.rotr(C2), true);
4231   case ISD::SMIN: return std::make_pair(C1.sle(C2) ? C1 : C2, true);
4232   case ISD::SMAX: return std::make_pair(C1.sge(C2) ? C1 : C2, true);
4233   case ISD::UMIN: return std::make_pair(C1.ule(C2) ? C1 : C2, true);
4234   case ISD::UMAX: return std::make_pair(C1.uge(C2) ? C1 : C2, true);
4235   case ISD::UDIV:
4236     if (!C2.getBoolValue())
4237       break;
4238     return std::make_pair(C1.udiv(C2), true);
4239   case ISD::UREM:
4240     if (!C2.getBoolValue())
4241       break;
4242     return std::make_pair(C1.urem(C2), true);
4243   case ISD::SDIV:
4244     if (!C2.getBoolValue())
4245       break;
4246     return std::make_pair(C1.sdiv(C2), true);
4247   case ISD::SREM:
4248     if (!C2.getBoolValue())
4249       break;
4250     return std::make_pair(C1.srem(C2), true);
4251   }
4252   return std::make_pair(APInt(1, 0), false);
4253 }
4254 
4255 SDValue SelectionDAG::FoldConstantArithmetic(unsigned Opcode, const SDLoc &DL,
4256                                              EVT VT, const ConstantSDNode *Cst1,
4257                                              const ConstantSDNode *Cst2) {
4258   if (Cst1->isOpaque() || Cst2->isOpaque())
4259     return SDValue();
4260 
4261   std::pair<APInt, bool> Folded = FoldValue(Opcode, Cst1->getAPIntValue(),
4262                                             Cst2->getAPIntValue());
4263   if (!Folded.second)
4264     return SDValue();
4265   return getConstant(Folded.first, DL, VT);
4266 }
4267 
4268 SDValue SelectionDAG::FoldSymbolOffset(unsigned Opcode, EVT VT,
4269                                        const GlobalAddressSDNode *GA,
4270                                        const SDNode *N2) {
4271   if (GA->getOpcode() != ISD::GlobalAddress)
4272     return SDValue();
4273   if (!TLI->isOffsetFoldingLegal(GA))
4274     return SDValue();
4275   const ConstantSDNode *Cst2 = dyn_cast<ConstantSDNode>(N2);
4276   if (!Cst2)
4277     return SDValue();
4278   int64_t Offset = Cst2->getSExtValue();
4279   switch (Opcode) {
4280   case ISD::ADD: break;
4281   case ISD::SUB: Offset = -uint64_t(Offset); break;
4282   default: return SDValue();
4283   }
4284   return getGlobalAddress(GA->getGlobal(), SDLoc(Cst2), VT,
4285                           GA->getOffset() + uint64_t(Offset));
4286 }
4287 
4288 bool SelectionDAG::isUndef(unsigned Opcode, ArrayRef<SDValue> Ops) {
4289   switch (Opcode) {
4290   case ISD::SDIV:
4291   case ISD::UDIV:
4292   case ISD::SREM:
4293   case ISD::UREM: {
4294     // If a divisor is zero/undef or any element of a divisor vector is
4295     // zero/undef, the whole op is undef.
4296     assert(Ops.size() == 2 && "Div/rem should have 2 operands");
4297     SDValue Divisor = Ops[1];
4298     if (Divisor.isUndef() || isNullConstant(Divisor))
4299       return true;
4300 
4301     return ISD::isBuildVectorOfConstantSDNodes(Divisor.getNode()) &&
4302            llvm::any_of(Divisor->op_values(),
4303                         [](SDValue V) { return V.isUndef() ||
4304                                         isNullConstant(V); });
4305     // TODO: Handle signed overflow.
4306   }
4307   // TODO: Handle oversized shifts.
4308   default:
4309     return false;
4310   }
4311 }
4312 
4313 SDValue SelectionDAG::FoldConstantArithmetic(unsigned Opcode, const SDLoc &DL,
4314                                              EVT VT, SDNode *Cst1,
4315                                              SDNode *Cst2) {
4316   // If the opcode is a target-specific ISD node, there's nothing we can
4317   // do here and the operand rules may not line up with the below, so
4318   // bail early.
4319   if (Opcode >= ISD::BUILTIN_OP_END)
4320     return SDValue();
4321 
4322   if (isUndef(Opcode, {SDValue(Cst1, 0), SDValue(Cst2, 0)}))
4323     return getUNDEF(VT);
4324 
4325   // Handle the case of two scalars.
4326   if (const ConstantSDNode *Scalar1 = dyn_cast<ConstantSDNode>(Cst1)) {
4327     if (const ConstantSDNode *Scalar2 = dyn_cast<ConstantSDNode>(Cst2)) {
4328       SDValue Folded = FoldConstantArithmetic(Opcode, DL, VT, Scalar1, Scalar2);
4329       assert((!Folded || !VT.isVector()) &&
4330              "Can't fold vectors ops with scalar operands");
4331       return Folded;
4332     }
4333   }
4334 
4335   // fold (add Sym, c) -> Sym+c
4336   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Cst1))
4337     return FoldSymbolOffset(Opcode, VT, GA, Cst2);
4338   if (TLI->isCommutativeBinOp(Opcode))
4339     if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Cst2))
4340       return FoldSymbolOffset(Opcode, VT, GA, Cst1);
4341 
4342   // For vectors extract each constant element into Inputs so we can constant
4343   // fold them individually.
4344   BuildVectorSDNode *BV1 = dyn_cast<BuildVectorSDNode>(Cst1);
4345   BuildVectorSDNode *BV2 = dyn_cast<BuildVectorSDNode>(Cst2);
4346   if (!BV1 || !BV2)
4347     return SDValue();
4348 
4349   assert(BV1->getNumOperands() == BV2->getNumOperands() && "Out of sync!");
4350 
4351   EVT SVT = VT.getScalarType();
4352   EVT LegalSVT = SVT;
4353   if (NewNodesMustHaveLegalTypes && LegalSVT.isInteger()) {
4354     LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT);
4355     if (LegalSVT.bitsLT(SVT))
4356       return SDValue();
4357   }
4358   SmallVector<SDValue, 4> Outputs;
4359   for (unsigned I = 0, E = BV1->getNumOperands(); I != E; ++I) {
4360     SDValue V1 = BV1->getOperand(I);
4361     SDValue V2 = BV2->getOperand(I);
4362 
4363     if (SVT.isInteger()) {
4364         if (V1->getValueType(0).bitsGT(SVT))
4365           V1 = getNode(ISD::TRUNCATE, DL, SVT, V1);
4366         if (V2->getValueType(0).bitsGT(SVT))
4367           V2 = getNode(ISD::TRUNCATE, DL, SVT, V2);
4368     }
4369 
4370     if (V1->getValueType(0) != SVT || V2->getValueType(0) != SVT)
4371       return SDValue();
4372 
4373     // Fold one vector element.
4374     SDValue ScalarResult = getNode(Opcode, DL, SVT, V1, V2);
4375     if (LegalSVT != SVT)
4376       ScalarResult = getNode(ISD::SIGN_EXTEND, DL, LegalSVT, ScalarResult);
4377 
4378     // Scalar folding only succeeded if the result is a constant or UNDEF.
4379     if (!ScalarResult.isUndef() && ScalarResult.getOpcode() != ISD::Constant &&
4380         ScalarResult.getOpcode() != ISD::ConstantFP)
4381       return SDValue();
4382     Outputs.push_back(ScalarResult);
4383   }
4384 
4385   assert(VT.getVectorNumElements() == Outputs.size() &&
4386          "Vector size mismatch!");
4387 
4388   // We may have a vector type but a scalar result. Create a splat.
4389   Outputs.resize(VT.getVectorNumElements(), Outputs.back());
4390 
4391   // Build a big vector out of the scalar elements we generated.
4392   return getBuildVector(VT, SDLoc(), Outputs);
4393 }
4394 
4395 // TODO: Merge with FoldConstantArithmetic
4396 SDValue SelectionDAG::FoldConstantVectorArithmetic(unsigned Opcode,
4397                                                    const SDLoc &DL, EVT VT,
4398                                                    ArrayRef<SDValue> Ops,
4399                                                    const SDNodeFlags Flags) {
4400   // If the opcode is a target-specific ISD node, there's nothing we can
4401   // do here and the operand rules may not line up with the below, so
4402   // bail early.
4403   if (Opcode >= ISD::BUILTIN_OP_END)
4404     return SDValue();
4405 
4406   if (isUndef(Opcode, Ops))
4407     return getUNDEF(VT);
4408 
4409   // We can only fold vectors - maybe merge with FoldConstantArithmetic someday?
4410   if (!VT.isVector())
4411     return SDValue();
4412 
4413   unsigned NumElts = VT.getVectorNumElements();
4414 
4415   auto IsScalarOrSameVectorSize = [&](const SDValue &Op) {
4416     return !Op.getValueType().isVector() ||
4417            Op.getValueType().getVectorNumElements() == NumElts;
4418   };
4419 
4420   auto IsConstantBuildVectorOrUndef = [&](const SDValue &Op) {
4421     BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op);
4422     return (Op.isUndef()) || (Op.getOpcode() == ISD::CONDCODE) ||
4423            (BV && BV->isConstant());
4424   };
4425 
4426   // All operands must be vector types with the same number of elements as
4427   // the result type and must be either UNDEF or a build vector of constant
4428   // or UNDEF scalars.
4429   if (!llvm::all_of(Ops, IsConstantBuildVectorOrUndef) ||
4430       !llvm::all_of(Ops, IsScalarOrSameVectorSize))
4431     return SDValue();
4432 
4433   // If we are comparing vectors, then the result needs to be a i1 boolean
4434   // that is then sign-extended back to the legal result type.
4435   EVT SVT = (Opcode == ISD::SETCC ? MVT::i1 : VT.getScalarType());
4436 
4437   // Find legal integer scalar type for constant promotion and
4438   // ensure that its scalar size is at least as large as source.
4439   EVT LegalSVT = VT.getScalarType();
4440   if (NewNodesMustHaveLegalTypes && LegalSVT.isInteger()) {
4441     LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT);
4442     if (LegalSVT.bitsLT(VT.getScalarType()))
4443       return SDValue();
4444   }
4445 
4446   // Constant fold each scalar lane separately.
4447   SmallVector<SDValue, 4> ScalarResults;
4448   for (unsigned i = 0; i != NumElts; i++) {
4449     SmallVector<SDValue, 4> ScalarOps;
4450     for (SDValue Op : Ops) {
4451       EVT InSVT = Op.getValueType().getScalarType();
4452       BuildVectorSDNode *InBV = dyn_cast<BuildVectorSDNode>(Op);
4453       if (!InBV) {
4454         // We've checked that this is UNDEF or a constant of some kind.
4455         if (Op.isUndef())
4456           ScalarOps.push_back(getUNDEF(InSVT));
4457         else
4458           ScalarOps.push_back(Op);
4459         continue;
4460       }
4461 
4462       SDValue ScalarOp = InBV->getOperand(i);
4463       EVT ScalarVT = ScalarOp.getValueType();
4464 
4465       // Build vector (integer) scalar operands may need implicit
4466       // truncation - do this before constant folding.
4467       if (ScalarVT.isInteger() && ScalarVT.bitsGT(InSVT))
4468         ScalarOp = getNode(ISD::TRUNCATE, DL, InSVT, ScalarOp);
4469 
4470       ScalarOps.push_back(ScalarOp);
4471     }
4472 
4473     // Constant fold the scalar operands.
4474     SDValue ScalarResult = getNode(Opcode, DL, SVT, ScalarOps, Flags);
4475 
4476     // Legalize the (integer) scalar constant if necessary.
4477     if (LegalSVT != SVT)
4478       ScalarResult = getNode(ISD::SIGN_EXTEND, DL, LegalSVT, ScalarResult);
4479 
4480     // Scalar folding only succeeded if the result is a constant or UNDEF.
4481     if (!ScalarResult.isUndef() && ScalarResult.getOpcode() != ISD::Constant &&
4482         ScalarResult.getOpcode() != ISD::ConstantFP)
4483       return SDValue();
4484     ScalarResults.push_back(ScalarResult);
4485   }
4486 
4487   SDValue V = getBuildVector(VT, DL, ScalarResults);
4488   NewSDValueDbgMsg(V, "New node fold constant vector: ", this);
4489   return V;
4490 }
4491 
4492 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
4493                               SDValue N1, SDValue N2, const SDNodeFlags Flags) {
4494   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4495   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
4496   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
4497   ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2);
4498 
4499   // Canonicalize constant to RHS if commutative.
4500   if (TLI->isCommutativeBinOp(Opcode)) {
4501     if (N1C && !N2C) {
4502       std::swap(N1C, N2C);
4503       std::swap(N1, N2);
4504     } else if (N1CFP && !N2CFP) {
4505       std::swap(N1CFP, N2CFP);
4506       std::swap(N1, N2);
4507     }
4508   }
4509 
4510   switch (Opcode) {
4511   default: break;
4512   case ISD::TokenFactor:
4513     assert(VT == MVT::Other && N1.getValueType() == MVT::Other &&
4514            N2.getValueType() == MVT::Other && "Invalid token factor!");
4515     // Fold trivial token factors.
4516     if (N1.getOpcode() == ISD::EntryToken) return N2;
4517     if (N2.getOpcode() == ISD::EntryToken) return N1;
4518     if (N1 == N2) return N1;
4519     break;
4520   case ISD::CONCAT_VECTORS: {
4521     // Attempt to fold CONCAT_VECTORS into BUILD_VECTOR or UNDEF.
4522     SDValue Ops[] = {N1, N2};
4523     if (SDValue V = FoldCONCAT_VECTORS(DL, VT, Ops, *this))
4524       return V;
4525     break;
4526   }
4527   case ISD::AND:
4528     assert(VT.isInteger() && "This operator does not apply to FP types!");
4529     assert(N1.getValueType() == N2.getValueType() &&
4530            N1.getValueType() == VT && "Binary operator types must match!");
4531     // (X & 0) -> 0.  This commonly occurs when legalizing i64 values, so it's
4532     // worth handling here.
4533     if (N2C && N2C->isNullValue())
4534       return N2;
4535     if (N2C && N2C->isAllOnesValue())  // X & -1 -> X
4536       return N1;
4537     break;
4538   case ISD::OR:
4539   case ISD::XOR:
4540   case ISD::ADD:
4541   case ISD::SUB:
4542     assert(VT.isInteger() && "This operator does not apply to FP types!");
4543     assert(N1.getValueType() == N2.getValueType() &&
4544            N1.getValueType() == VT && "Binary operator types must match!");
4545     // (X ^|+- 0) -> X.  This commonly occurs when legalizing i64 values, so
4546     // it's worth handling here.
4547     if (N2C && N2C->isNullValue())
4548       return N1;
4549     break;
4550   case ISD::UDIV:
4551   case ISD::UREM:
4552   case ISD::MULHU:
4553   case ISD::MULHS:
4554   case ISD::MUL:
4555   case ISD::SDIV:
4556   case ISD::SREM:
4557   case ISD::SMIN:
4558   case ISD::SMAX:
4559   case ISD::UMIN:
4560   case ISD::UMAX:
4561     assert(VT.isInteger() && "This operator does not apply to FP types!");
4562     assert(N1.getValueType() == N2.getValueType() &&
4563            N1.getValueType() == VT && "Binary operator types must match!");
4564     break;
4565   case ISD::FADD:
4566   case ISD::FSUB:
4567   case ISD::FMUL:
4568   case ISD::FDIV:
4569   case ISD::FREM:
4570     assert(VT.isFloatingPoint() && "This operator only applies to FP types!");
4571     assert(N1.getValueType() == N2.getValueType() &&
4572            N1.getValueType() == VT && "Binary operator types must match!");
4573     break;
4574   case ISD::FCOPYSIGN:   // N1 and result must match.  N1/N2 need not match.
4575     assert(N1.getValueType() == VT &&
4576            N1.getValueType().isFloatingPoint() &&
4577            N2.getValueType().isFloatingPoint() &&
4578            "Invalid FCOPYSIGN!");
4579     break;
4580   case ISD::SHL:
4581   case ISD::SRA:
4582   case ISD::SRL:
4583   case ISD::ROTL:
4584   case ISD::ROTR:
4585     assert(VT == N1.getValueType() &&
4586            "Shift operators return type must be the same as their first arg");
4587     assert(VT.isInteger() && N2.getValueType().isInteger() &&
4588            "Shifts only work on integers");
4589     assert((!VT.isVector() || VT == N2.getValueType()) &&
4590            "Vector shift amounts must be in the same as their first arg");
4591     // Verify that the shift amount VT is bit enough to hold valid shift
4592     // amounts.  This catches things like trying to shift an i1024 value by an
4593     // i8, which is easy to fall into in generic code that uses
4594     // TLI.getShiftAmount().
4595     assert(N2.getValueSizeInBits() >= Log2_32_Ceil(N1.getValueSizeInBits()) &&
4596            "Invalid use of small shift amount with oversized value!");
4597 
4598     // Always fold shifts of i1 values so the code generator doesn't need to
4599     // handle them.  Since we know the size of the shift has to be less than the
4600     // size of the value, the shift/rotate count is guaranteed to be zero.
4601     if (VT == MVT::i1)
4602       return N1;
4603     if (N2C && N2C->isNullValue())
4604       return N1;
4605     break;
4606   case ISD::FP_ROUND_INREG: {
4607     EVT EVT = cast<VTSDNode>(N2)->getVT();
4608     assert(VT == N1.getValueType() && "Not an inreg round!");
4609     assert(VT.isFloatingPoint() && EVT.isFloatingPoint() &&
4610            "Cannot FP_ROUND_INREG integer types");
4611     assert(EVT.isVector() == VT.isVector() &&
4612            "FP_ROUND_INREG type should be vector iff the operand "
4613            "type is vector!");
4614     assert((!EVT.isVector() ||
4615             EVT.getVectorNumElements() == VT.getVectorNumElements()) &&
4616            "Vector element counts must match in FP_ROUND_INREG");
4617     assert(EVT.bitsLE(VT) && "Not rounding down!");
4618     (void)EVT;
4619     if (cast<VTSDNode>(N2)->getVT() == VT) return N1;  // Not actually rounding.
4620     break;
4621   }
4622   case ISD::FP_ROUND:
4623     assert(VT.isFloatingPoint() &&
4624            N1.getValueType().isFloatingPoint() &&
4625            VT.bitsLE(N1.getValueType()) &&
4626            N2C && (N2C->getZExtValue() == 0 || N2C->getZExtValue() == 1) &&
4627            "Invalid FP_ROUND!");
4628     if (N1.getValueType() == VT) return N1;  // noop conversion.
4629     break;
4630   case ISD::AssertSext:
4631   case ISD::AssertZext: {
4632     EVT EVT = cast<VTSDNode>(N2)->getVT();
4633     assert(VT == N1.getValueType() && "Not an inreg extend!");
4634     assert(VT.isInteger() && EVT.isInteger() &&
4635            "Cannot *_EXTEND_INREG FP types");
4636     assert(!EVT.isVector() &&
4637            "AssertSExt/AssertZExt type should be the vector element type "
4638            "rather than the vector type!");
4639     assert(EVT.bitsLE(VT) && "Not extending!");
4640     if (VT == EVT) return N1; // noop assertion.
4641     break;
4642   }
4643   case ISD::SIGN_EXTEND_INREG: {
4644     EVT EVT = cast<VTSDNode>(N2)->getVT();
4645     assert(VT == N1.getValueType() && "Not an inreg extend!");
4646     assert(VT.isInteger() && EVT.isInteger() &&
4647            "Cannot *_EXTEND_INREG FP types");
4648     assert(EVT.isVector() == VT.isVector() &&
4649            "SIGN_EXTEND_INREG type should be vector iff the operand "
4650            "type is vector!");
4651     assert((!EVT.isVector() ||
4652             EVT.getVectorNumElements() == VT.getVectorNumElements()) &&
4653            "Vector element counts must match in SIGN_EXTEND_INREG");
4654     assert(EVT.bitsLE(VT) && "Not extending!");
4655     if (EVT == VT) return N1;  // Not actually extending
4656 
4657     auto SignExtendInReg = [&](APInt Val, llvm::EVT ConstantVT) {
4658       unsigned FromBits = EVT.getScalarSizeInBits();
4659       Val <<= Val.getBitWidth() - FromBits;
4660       Val.ashrInPlace(Val.getBitWidth() - FromBits);
4661       return getConstant(Val, DL, ConstantVT);
4662     };
4663 
4664     if (N1C) {
4665       const APInt &Val = N1C->getAPIntValue();
4666       return SignExtendInReg(Val, VT);
4667     }
4668     if (ISD::isBuildVectorOfConstantSDNodes(N1.getNode())) {
4669       SmallVector<SDValue, 8> Ops;
4670       llvm::EVT OpVT = N1.getOperand(0).getValueType();
4671       for (int i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
4672         SDValue Op = N1.getOperand(i);
4673         if (Op.isUndef()) {
4674           Ops.push_back(getUNDEF(OpVT));
4675           continue;
4676         }
4677         ConstantSDNode *C = cast<ConstantSDNode>(Op);
4678         APInt Val = C->getAPIntValue();
4679         Ops.push_back(SignExtendInReg(Val, OpVT));
4680       }
4681       return getBuildVector(VT, DL, Ops);
4682     }
4683     break;
4684   }
4685   case ISD::EXTRACT_VECTOR_ELT:
4686     assert(VT.getSizeInBits() >= N1.getValueType().getScalarSizeInBits() &&
4687            "The result of EXTRACT_VECTOR_ELT must be at least as wide as the \
4688              element type of the vector.");
4689 
4690     // EXTRACT_VECTOR_ELT of an UNDEF is an UNDEF.
4691     if (N1.isUndef())
4692       return getUNDEF(VT);
4693 
4694     // EXTRACT_VECTOR_ELT of out-of-bounds element is an UNDEF
4695     if (N2C && N2C->getAPIntValue().uge(N1.getValueType().getVectorNumElements()))
4696       return getUNDEF(VT);
4697 
4698     // EXTRACT_VECTOR_ELT of CONCAT_VECTORS is often formed while lowering is
4699     // expanding copies of large vectors from registers.
4700     if (N2C &&
4701         N1.getOpcode() == ISD::CONCAT_VECTORS &&
4702         N1.getNumOperands() > 0) {
4703       unsigned Factor =
4704         N1.getOperand(0).getValueType().getVectorNumElements();
4705       return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
4706                      N1.getOperand(N2C->getZExtValue() / Factor),
4707                      getConstant(N2C->getZExtValue() % Factor, DL,
4708                                  N2.getValueType()));
4709     }
4710 
4711     // EXTRACT_VECTOR_ELT of BUILD_VECTOR is often formed while lowering is
4712     // expanding large vector constants.
4713     if (N2C && N1.getOpcode() == ISD::BUILD_VECTOR) {
4714       SDValue Elt = N1.getOperand(N2C->getZExtValue());
4715 
4716       if (VT != Elt.getValueType())
4717         // If the vector element type is not legal, the BUILD_VECTOR operands
4718         // are promoted and implicitly truncated, and the result implicitly
4719         // extended. Make that explicit here.
4720         Elt = getAnyExtOrTrunc(Elt, DL, VT);
4721 
4722       return Elt;
4723     }
4724 
4725     // EXTRACT_VECTOR_ELT of INSERT_VECTOR_ELT is often formed when vector
4726     // operations are lowered to scalars.
4727     if (N1.getOpcode() == ISD::INSERT_VECTOR_ELT) {
4728       // If the indices are the same, return the inserted element else
4729       // if the indices are known different, extract the element from
4730       // the original vector.
4731       SDValue N1Op2 = N1.getOperand(2);
4732       ConstantSDNode *N1Op2C = dyn_cast<ConstantSDNode>(N1Op2);
4733 
4734       if (N1Op2C && N2C) {
4735         if (N1Op2C->getZExtValue() == N2C->getZExtValue()) {
4736           if (VT == N1.getOperand(1).getValueType())
4737             return N1.getOperand(1);
4738           else
4739             return getSExtOrTrunc(N1.getOperand(1), DL, VT);
4740         }
4741 
4742         return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0), N2);
4743       }
4744     }
4745 
4746     // EXTRACT_VECTOR_ELT of v1iX EXTRACT_SUBVECTOR could be formed
4747     // when vector types are scalarized and v1iX is legal.
4748     // vextract (v1iX extract_subvector(vNiX, Idx)) -> vextract(vNiX,Idx)
4749     if (N1.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
4750         N1.getValueType().getVectorNumElements() == 1) {
4751       return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0),
4752                      N1.getOperand(1));
4753     }
4754     break;
4755   case ISD::EXTRACT_ELEMENT:
4756     assert(N2C && (unsigned)N2C->getZExtValue() < 2 && "Bad EXTRACT_ELEMENT!");
4757     assert(!N1.getValueType().isVector() && !VT.isVector() &&
4758            (N1.getValueType().isInteger() == VT.isInteger()) &&
4759            N1.getValueType() != VT &&
4760            "Wrong types for EXTRACT_ELEMENT!");
4761 
4762     // EXTRACT_ELEMENT of BUILD_PAIR is often formed while legalize is expanding
4763     // 64-bit integers into 32-bit parts.  Instead of building the extract of
4764     // the BUILD_PAIR, only to have legalize rip it apart, just do it now.
4765     if (N1.getOpcode() == ISD::BUILD_PAIR)
4766       return N1.getOperand(N2C->getZExtValue());
4767 
4768     // EXTRACT_ELEMENT of a constant int is also very common.
4769     if (N1C) {
4770       unsigned ElementSize = VT.getSizeInBits();
4771       unsigned Shift = ElementSize * N2C->getZExtValue();
4772       APInt ShiftedVal = N1C->getAPIntValue().lshr(Shift);
4773       return getConstant(ShiftedVal.trunc(ElementSize), DL, VT);
4774     }
4775     break;
4776   case ISD::EXTRACT_SUBVECTOR:
4777     if (VT.isSimple() && N1.getValueType().isSimple()) {
4778       assert(VT.isVector() && N1.getValueType().isVector() &&
4779              "Extract subvector VTs must be a vectors!");
4780       assert(VT.getVectorElementType() ==
4781              N1.getValueType().getVectorElementType() &&
4782              "Extract subvector VTs must have the same element type!");
4783       assert(VT.getSimpleVT() <= N1.getSimpleValueType() &&
4784              "Extract subvector must be from larger vector to smaller vector!");
4785 
4786       if (N2C) {
4787         assert((VT.getVectorNumElements() + N2C->getZExtValue()
4788                 <= N1.getValueType().getVectorNumElements())
4789                && "Extract subvector overflow!");
4790       }
4791 
4792       // Trivial extraction.
4793       if (VT.getSimpleVT() == N1.getSimpleValueType())
4794         return N1;
4795 
4796       // EXTRACT_SUBVECTOR of an UNDEF is an UNDEF.
4797       if (N1.isUndef())
4798         return getUNDEF(VT);
4799 
4800       // EXTRACT_SUBVECTOR of CONCAT_VECTOR can be simplified if the pieces of
4801       // the concat have the same type as the extract.
4802       if (N2C && N1.getOpcode() == ISD::CONCAT_VECTORS &&
4803           N1.getNumOperands() > 0 &&
4804           VT == N1.getOperand(0).getValueType()) {
4805         unsigned Factor = VT.getVectorNumElements();
4806         return N1.getOperand(N2C->getZExtValue() / Factor);
4807       }
4808 
4809       // EXTRACT_SUBVECTOR of INSERT_SUBVECTOR is often created
4810       // during shuffle legalization.
4811       if (N1.getOpcode() == ISD::INSERT_SUBVECTOR && N2 == N1.getOperand(2) &&
4812           VT == N1.getOperand(1).getValueType())
4813         return N1.getOperand(1);
4814     }
4815     break;
4816   }
4817 
4818   // Perform trivial constant folding.
4819   if (SDValue SV =
4820           FoldConstantArithmetic(Opcode, DL, VT, N1.getNode(), N2.getNode()))
4821     return SV;
4822 
4823   // Constant fold FP operations.
4824   bool HasFPExceptions = TLI->hasFloatingPointExceptions();
4825   if (N1CFP) {
4826     if (N2CFP) {
4827       APFloat V1 = N1CFP->getValueAPF(), V2 = N2CFP->getValueAPF();
4828       APFloat::opStatus s;
4829       switch (Opcode) {
4830       case ISD::FADD:
4831         s = V1.add(V2, APFloat::rmNearestTiesToEven);
4832         if (!HasFPExceptions || s != APFloat::opInvalidOp)
4833           return getConstantFP(V1, DL, VT);
4834         break;
4835       case ISD::FSUB:
4836         s = V1.subtract(V2, APFloat::rmNearestTiesToEven);
4837         if (!HasFPExceptions || s!=APFloat::opInvalidOp)
4838           return getConstantFP(V1, DL, VT);
4839         break;
4840       case ISD::FMUL:
4841         s = V1.multiply(V2, APFloat::rmNearestTiesToEven);
4842         if (!HasFPExceptions || s!=APFloat::opInvalidOp)
4843           return getConstantFP(V1, DL, VT);
4844         break;
4845       case ISD::FDIV:
4846         s = V1.divide(V2, APFloat::rmNearestTiesToEven);
4847         if (!HasFPExceptions || (s!=APFloat::opInvalidOp &&
4848                                  s!=APFloat::opDivByZero)) {
4849           return getConstantFP(V1, DL, VT);
4850         }
4851         break;
4852       case ISD::FREM :
4853         s = V1.mod(V2);
4854         if (!HasFPExceptions || (s!=APFloat::opInvalidOp &&
4855                                  s!=APFloat::opDivByZero)) {
4856           return getConstantFP(V1, DL, VT);
4857         }
4858         break;
4859       case ISD::FCOPYSIGN:
4860         V1.copySign(V2);
4861         return getConstantFP(V1, DL, VT);
4862       default: break;
4863       }
4864     }
4865 
4866     if (Opcode == ISD::FP_ROUND) {
4867       APFloat V = N1CFP->getValueAPF();    // make copy
4868       bool ignored;
4869       // This can return overflow, underflow, or inexact; we don't care.
4870       // FIXME need to be more flexible about rounding mode.
4871       (void)V.convert(EVTToAPFloatSemantics(VT),
4872                       APFloat::rmNearestTiesToEven, &ignored);
4873       return getConstantFP(V, DL, VT);
4874     }
4875   }
4876 
4877   // Any FP binop with an undef operand is folded to NaN. This matches the
4878   // behavior of the IR optimizer.
4879   switch (Opcode) {
4880   case ISD::FADD:
4881   case ISD::FSUB:
4882   case ISD::FMUL:
4883   case ISD::FDIV:
4884   case ISD::FREM:
4885     if (N1.isUndef() || N2.isUndef())
4886       return getConstantFP(APFloat::getNaN(EVTToAPFloatSemantics(VT)), DL, VT);
4887   }
4888 
4889   // Canonicalize an UNDEF to the RHS, even over a constant.
4890   if (N1.isUndef()) {
4891     if (TLI->isCommutativeBinOp(Opcode)) {
4892       std::swap(N1, N2);
4893     } else {
4894       switch (Opcode) {
4895       case ISD::FP_ROUND_INREG:
4896       case ISD::SIGN_EXTEND_INREG:
4897       case ISD::SUB:
4898         return getUNDEF(VT);     // fold op(undef, arg2) -> undef
4899       case ISD::UDIV:
4900       case ISD::SDIV:
4901       case ISD::UREM:
4902       case ISD::SREM:
4903       case ISD::SRA:
4904       case ISD::SRL:
4905       case ISD::SHL:
4906         return getConstant(0, DL, VT);    // fold op(undef, arg2) -> 0
4907       }
4908     }
4909   }
4910 
4911   // Fold a bunch of operators when the RHS is undef.
4912   if (N2.isUndef()) {
4913     switch (Opcode) {
4914     case ISD::XOR:
4915       if (N1.isUndef())
4916         // Handle undef ^ undef -> 0 special case. This is a common
4917         // idiom (misuse).
4918         return getConstant(0, DL, VT);
4919       LLVM_FALLTHROUGH;
4920     case ISD::ADD:
4921     case ISD::ADDC:
4922     case ISD::ADDE:
4923     case ISD::SUB:
4924     case ISD::UDIV:
4925     case ISD::SDIV:
4926     case ISD::UREM:
4927     case ISD::SREM:
4928     case ISD::SRA:
4929     case ISD::SRL:
4930     case ISD::SHL:
4931       return getUNDEF(VT);       // fold op(arg1, undef) -> undef
4932     case ISD::MUL:
4933     case ISD::AND:
4934       return getConstant(0, DL, VT);  // fold op(arg1, undef) -> 0
4935     case ISD::OR:
4936       return getAllOnesConstant(DL, VT);
4937     }
4938   }
4939 
4940   // Memoize this node if possible.
4941   SDNode *N;
4942   SDVTList VTs = getVTList(VT);
4943   SDValue Ops[] = {N1, N2};
4944   if (VT != MVT::Glue) {
4945     FoldingSetNodeID ID;
4946     AddNodeIDNode(ID, Opcode, VTs, Ops);
4947     void *IP = nullptr;
4948     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
4949       E->intersectFlagsWith(Flags);
4950       return SDValue(E, 0);
4951     }
4952 
4953     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
4954     N->setFlags(Flags);
4955     createOperands(N, Ops);
4956     CSEMap.InsertNode(N, IP);
4957   } else {
4958     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
4959     createOperands(N, Ops);
4960   }
4961 
4962   InsertNode(N);
4963   SDValue V = SDValue(N, 0);
4964   NewSDValueDbgMsg(V, "Creating new node: ", this);
4965   return V;
4966 }
4967 
4968 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
4969                               SDValue N1, SDValue N2, SDValue N3,
4970                               const SDNodeFlags Flags) {
4971   // Perform various simplifications.
4972   switch (Opcode) {
4973   case ISD::FMA: {
4974     assert(VT.isFloatingPoint() && "This operator only applies to FP types!");
4975     assert(N1.getValueType() == VT && N2.getValueType() == VT &&
4976            N3.getValueType() == VT && "FMA types must match!");
4977     ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
4978     ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2);
4979     ConstantFPSDNode *N3CFP = dyn_cast<ConstantFPSDNode>(N3);
4980     if (N1CFP && N2CFP && N3CFP) {
4981       APFloat  V1 = N1CFP->getValueAPF();
4982       const APFloat &V2 = N2CFP->getValueAPF();
4983       const APFloat &V3 = N3CFP->getValueAPF();
4984       APFloat::opStatus s =
4985         V1.fusedMultiplyAdd(V2, V3, APFloat::rmNearestTiesToEven);
4986       if (!TLI->hasFloatingPointExceptions() || s != APFloat::opInvalidOp)
4987         return getConstantFP(V1, DL, VT);
4988     }
4989     break;
4990   }
4991   case ISD::CONCAT_VECTORS: {
4992     // Attempt to fold CONCAT_VECTORS into BUILD_VECTOR or UNDEF.
4993     SDValue Ops[] = {N1, N2, N3};
4994     if (SDValue V = FoldCONCAT_VECTORS(DL, VT, Ops, *this))
4995       return V;
4996     break;
4997   }
4998   case ISD::SETCC: {
4999     // Use FoldSetCC to simplify SETCC's.
5000     if (SDValue V = FoldSetCC(VT, N1, N2, cast<CondCodeSDNode>(N3)->get(), DL))
5001       return V;
5002     // Vector constant folding.
5003     SDValue Ops[] = {N1, N2, N3};
5004     if (SDValue V = FoldConstantVectorArithmetic(Opcode, DL, VT, Ops)) {
5005       NewSDValueDbgMsg(V, "New node vector constant folding: ", this);
5006       return V;
5007     }
5008     break;
5009   }
5010   case ISD::SELECT:
5011     if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1)) {
5012      if (N1C->getZExtValue())
5013        return N2;             // select true, X, Y -> X
5014      return N3;             // select false, X, Y -> Y
5015     }
5016 
5017     if (N2 == N3) return N2;   // select C, X, X -> X
5018     break;
5019   case ISD::VECTOR_SHUFFLE:
5020     llvm_unreachable("should use getVectorShuffle constructor!");
5021   case ISD::INSERT_VECTOR_ELT: {
5022     ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3);
5023     // INSERT_VECTOR_ELT into out-of-bounds element is an UNDEF
5024     if (N3C && N3C->getZExtValue() >= N1.getValueType().getVectorNumElements())
5025       return getUNDEF(VT);
5026     break;
5027   }
5028   case ISD::INSERT_SUBVECTOR: {
5029     SDValue Index = N3;
5030     if (VT.isSimple() && N1.getValueType().isSimple()
5031         && N2.getValueType().isSimple()) {
5032       assert(VT.isVector() && N1.getValueType().isVector() &&
5033              N2.getValueType().isVector() &&
5034              "Insert subvector VTs must be a vectors");
5035       assert(VT == N1.getValueType() &&
5036              "Dest and insert subvector source types must match!");
5037       assert(N2.getSimpleValueType() <= N1.getSimpleValueType() &&
5038              "Insert subvector must be from smaller vector to larger vector!");
5039       if (isa<ConstantSDNode>(Index)) {
5040         assert((N2.getValueType().getVectorNumElements() +
5041                 cast<ConstantSDNode>(Index)->getZExtValue()
5042                 <= VT.getVectorNumElements())
5043                && "Insert subvector overflow!");
5044       }
5045 
5046       // Trivial insertion.
5047       if (VT.getSimpleVT() == N2.getSimpleValueType())
5048         return N2;
5049     }
5050     break;
5051   }
5052   case ISD::BITCAST:
5053     // Fold bit_convert nodes from a type to themselves.
5054     if (N1.getValueType() == VT)
5055       return N1;
5056     break;
5057   }
5058 
5059   // Memoize node if it doesn't produce a flag.
5060   SDNode *N;
5061   SDVTList VTs = getVTList(VT);
5062   SDValue Ops[] = {N1, N2, N3};
5063   if (VT != MVT::Glue) {
5064     FoldingSetNodeID ID;
5065     AddNodeIDNode(ID, Opcode, VTs, Ops);
5066     void *IP = nullptr;
5067     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
5068       E->intersectFlagsWith(Flags);
5069       return SDValue(E, 0);
5070     }
5071 
5072     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
5073     N->setFlags(Flags);
5074     createOperands(N, Ops);
5075     CSEMap.InsertNode(N, IP);
5076   } else {
5077     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
5078     createOperands(N, Ops);
5079   }
5080 
5081   InsertNode(N);
5082   SDValue V = SDValue(N, 0);
5083   NewSDValueDbgMsg(V, "Creating new node: ", this);
5084   return V;
5085 }
5086 
5087 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
5088                               SDValue N1, SDValue N2, SDValue N3, SDValue N4) {
5089   SDValue Ops[] = { N1, N2, N3, N4 };
5090   return getNode(Opcode, DL, VT, Ops);
5091 }
5092 
5093 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
5094                               SDValue N1, SDValue N2, SDValue N3, SDValue N4,
5095                               SDValue N5) {
5096   SDValue Ops[] = { N1, N2, N3, N4, N5 };
5097   return getNode(Opcode, DL, VT, Ops);
5098 }
5099 
5100 /// getStackArgumentTokenFactor - Compute a TokenFactor to force all
5101 /// the incoming stack arguments to be loaded from the stack.
5102 SDValue SelectionDAG::getStackArgumentTokenFactor(SDValue Chain) {
5103   SmallVector<SDValue, 8> ArgChains;
5104 
5105   // Include the original chain at the beginning of the list. When this is
5106   // used by target LowerCall hooks, this helps legalize find the
5107   // CALLSEQ_BEGIN node.
5108   ArgChains.push_back(Chain);
5109 
5110   // Add a chain value for each stack argument.
5111   for (SDNode::use_iterator U = getEntryNode().getNode()->use_begin(),
5112        UE = getEntryNode().getNode()->use_end(); U != UE; ++U)
5113     if (LoadSDNode *L = dyn_cast<LoadSDNode>(*U))
5114       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
5115         if (FI->getIndex() < 0)
5116           ArgChains.push_back(SDValue(L, 1));
5117 
5118   // Build a tokenfactor for all the chains.
5119   return getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains);
5120 }
5121 
5122 /// getMemsetValue - Vectorized representation of the memset value
5123 /// operand.
5124 static SDValue getMemsetValue(SDValue Value, EVT VT, SelectionDAG &DAG,
5125                               const SDLoc &dl) {
5126   assert(!Value.isUndef());
5127 
5128   unsigned NumBits = VT.getScalarSizeInBits();
5129   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
5130     assert(C->getAPIntValue().getBitWidth() == 8);
5131     APInt Val = APInt::getSplat(NumBits, C->getAPIntValue());
5132     if (VT.isInteger())
5133       return DAG.getConstant(Val, dl, VT);
5134     return DAG.getConstantFP(APFloat(DAG.EVTToAPFloatSemantics(VT), Val), dl,
5135                              VT);
5136   }
5137 
5138   assert(Value.getValueType() == MVT::i8 && "memset with non-byte fill value?");
5139   EVT IntVT = VT.getScalarType();
5140   if (!IntVT.isInteger())
5141     IntVT = EVT::getIntegerVT(*DAG.getContext(), IntVT.getSizeInBits());
5142 
5143   Value = DAG.getNode(ISD::ZERO_EXTEND, dl, IntVT, Value);
5144   if (NumBits > 8) {
5145     // Use a multiplication with 0x010101... to extend the input to the
5146     // required length.
5147     APInt Magic = APInt::getSplat(NumBits, APInt(8, 0x01));
5148     Value = DAG.getNode(ISD::MUL, dl, IntVT, Value,
5149                         DAG.getConstant(Magic, dl, IntVT));
5150   }
5151 
5152   if (VT != Value.getValueType() && !VT.isInteger())
5153     Value = DAG.getBitcast(VT.getScalarType(), Value);
5154   if (VT != Value.getValueType())
5155     Value = DAG.getSplatBuildVector(VT, dl, Value);
5156 
5157   return Value;
5158 }
5159 
5160 /// getMemsetStringVal - Similar to getMemsetValue. Except this is only
5161 /// used when a memcpy is turned into a memset when the source is a constant
5162 /// string ptr.
5163 static SDValue getMemsetStringVal(EVT VT, const SDLoc &dl, SelectionDAG &DAG,
5164                                   const TargetLowering &TLI,
5165                                   const ConstantDataArraySlice &Slice) {
5166   // Handle vector with all elements zero.
5167   if (Slice.Array == nullptr) {
5168     if (VT.isInteger())
5169       return DAG.getConstant(0, dl, VT);
5170     else if (VT == MVT::f32 || VT == MVT::f64 || VT == MVT::f128)
5171       return DAG.getConstantFP(0.0, dl, VT);
5172     else if (VT.isVector()) {
5173       unsigned NumElts = VT.getVectorNumElements();
5174       MVT EltVT = (VT.getVectorElementType() == MVT::f32) ? MVT::i32 : MVT::i64;
5175       return DAG.getNode(ISD::BITCAST, dl, VT,
5176                          DAG.getConstant(0, dl,
5177                                          EVT::getVectorVT(*DAG.getContext(),
5178                                                           EltVT, NumElts)));
5179     } else
5180       llvm_unreachable("Expected type!");
5181   }
5182 
5183   assert(!VT.isVector() && "Can't handle vector type here!");
5184   unsigned NumVTBits = VT.getSizeInBits();
5185   unsigned NumVTBytes = NumVTBits / 8;
5186   unsigned NumBytes = std::min(NumVTBytes, unsigned(Slice.Length));
5187 
5188   APInt Val(NumVTBits, 0);
5189   if (DAG.getDataLayout().isLittleEndian()) {
5190     for (unsigned i = 0; i != NumBytes; ++i)
5191       Val |= (uint64_t)(unsigned char)Slice[i] << i*8;
5192   } else {
5193     for (unsigned i = 0; i != NumBytes; ++i)
5194       Val |= (uint64_t)(unsigned char)Slice[i] << (NumVTBytes-i-1)*8;
5195   }
5196 
5197   // If the "cost" of materializing the integer immediate is less than the cost
5198   // of a load, then it is cost effective to turn the load into the immediate.
5199   Type *Ty = VT.getTypeForEVT(*DAG.getContext());
5200   if (TLI.shouldConvertConstantLoadToIntImm(Val, Ty))
5201     return DAG.getConstant(Val, dl, VT);
5202   return SDValue(nullptr, 0);
5203 }
5204 
5205 SDValue SelectionDAG::getMemBasePlusOffset(SDValue Base, unsigned Offset,
5206                                            const SDLoc &DL) {
5207   EVT VT = Base.getValueType();
5208   return getNode(ISD::ADD, DL, VT, Base, getConstant(Offset, DL, VT));
5209 }
5210 
5211 /// Returns true if memcpy source is constant data.
5212 static bool isMemSrcFromConstant(SDValue Src, ConstantDataArraySlice &Slice) {
5213   uint64_t SrcDelta = 0;
5214   GlobalAddressSDNode *G = nullptr;
5215   if (Src.getOpcode() == ISD::GlobalAddress)
5216     G = cast<GlobalAddressSDNode>(Src);
5217   else if (Src.getOpcode() == ISD::ADD &&
5218            Src.getOperand(0).getOpcode() == ISD::GlobalAddress &&
5219            Src.getOperand(1).getOpcode() == ISD::Constant) {
5220     G = cast<GlobalAddressSDNode>(Src.getOperand(0));
5221     SrcDelta = cast<ConstantSDNode>(Src.getOperand(1))->getZExtValue();
5222   }
5223   if (!G)
5224     return false;
5225 
5226   return getConstantDataArrayInfo(G->getGlobal(), Slice, 8,
5227                                   SrcDelta + G->getOffset());
5228 }
5229 
5230 /// Determines the optimal series of memory ops to replace the memset / memcpy.
5231 /// Return true if the number of memory ops is below the threshold (Limit).
5232 /// It returns the types of the sequence of memory ops to perform
5233 /// memset / memcpy by reference.
5234 static bool FindOptimalMemOpLowering(std::vector<EVT> &MemOps,
5235                                      unsigned Limit, uint64_t Size,
5236                                      unsigned DstAlign, unsigned SrcAlign,
5237                                      bool IsMemset,
5238                                      bool ZeroMemset,
5239                                      bool MemcpyStrSrc,
5240                                      bool AllowOverlap,
5241                                      unsigned DstAS, unsigned SrcAS,
5242                                      SelectionDAG &DAG,
5243                                      const TargetLowering &TLI) {
5244   assert((SrcAlign == 0 || SrcAlign >= DstAlign) &&
5245          "Expecting memcpy / memset source to meet alignment requirement!");
5246   // If 'SrcAlign' is zero, that means the memory operation does not need to
5247   // load the value, i.e. memset or memcpy from constant string. Otherwise,
5248   // it's the inferred alignment of the source. 'DstAlign', on the other hand,
5249   // is the specified alignment of the memory operation. If it is zero, that
5250   // means it's possible to change the alignment of the destination.
5251   // 'MemcpyStrSrc' indicates whether the memcpy source is constant so it does
5252   // not need to be loaded.
5253   EVT VT = TLI.getOptimalMemOpType(Size, DstAlign, SrcAlign,
5254                                    IsMemset, ZeroMemset, MemcpyStrSrc,
5255                                    DAG.getMachineFunction());
5256 
5257   if (VT == MVT::Other) {
5258     // Use the largest integer type whose alignment constraints are satisfied.
5259     // We only need to check DstAlign here as SrcAlign is always greater or
5260     // equal to DstAlign (or zero).
5261     VT = MVT::i64;
5262     while (DstAlign && DstAlign < VT.getSizeInBits() / 8 &&
5263            !TLI.allowsMisalignedMemoryAccesses(VT, DstAS, DstAlign))
5264       VT = (MVT::SimpleValueType)(VT.getSimpleVT().SimpleTy - 1);
5265     assert(VT.isInteger());
5266 
5267     // Find the largest legal integer type.
5268     MVT LVT = MVT::i64;
5269     while (!TLI.isTypeLegal(LVT))
5270       LVT = (MVT::SimpleValueType)(LVT.SimpleTy - 1);
5271     assert(LVT.isInteger());
5272 
5273     // If the type we've chosen is larger than the largest legal integer type
5274     // then use that instead.
5275     if (VT.bitsGT(LVT))
5276       VT = LVT;
5277   }
5278 
5279   unsigned NumMemOps = 0;
5280   while (Size != 0) {
5281     unsigned VTSize = VT.getSizeInBits() / 8;
5282     while (VTSize > Size) {
5283       // For now, only use non-vector load / store's for the left-over pieces.
5284       EVT NewVT = VT;
5285       unsigned NewVTSize;
5286 
5287       bool Found = false;
5288       if (VT.isVector() || VT.isFloatingPoint()) {
5289         NewVT = (VT.getSizeInBits() > 64) ? MVT::i64 : MVT::i32;
5290         if (TLI.isOperationLegalOrCustom(ISD::STORE, NewVT) &&
5291             TLI.isSafeMemOpType(NewVT.getSimpleVT()))
5292           Found = true;
5293         else if (NewVT == MVT::i64 &&
5294                  TLI.isOperationLegalOrCustom(ISD::STORE, MVT::f64) &&
5295                  TLI.isSafeMemOpType(MVT::f64)) {
5296           // i64 is usually not legal on 32-bit targets, but f64 may be.
5297           NewVT = MVT::f64;
5298           Found = true;
5299         }
5300       }
5301 
5302       if (!Found) {
5303         do {
5304           NewVT = (MVT::SimpleValueType)(NewVT.getSimpleVT().SimpleTy - 1);
5305           if (NewVT == MVT::i8)
5306             break;
5307         } while (!TLI.isSafeMemOpType(NewVT.getSimpleVT()));
5308       }
5309       NewVTSize = NewVT.getSizeInBits() / 8;
5310 
5311       // If the new VT cannot cover all of the remaining bits, then consider
5312       // issuing a (or a pair of) unaligned and overlapping load / store.
5313       // FIXME: Only does this for 64-bit or more since we don't have proper
5314       // cost model for unaligned load / store.
5315       bool Fast;
5316       if (NumMemOps && AllowOverlap &&
5317           VTSize >= 8 && NewVTSize < Size &&
5318           TLI.allowsMisalignedMemoryAccesses(VT, DstAS, DstAlign, &Fast) && Fast)
5319         VTSize = Size;
5320       else {
5321         VT = NewVT;
5322         VTSize = NewVTSize;
5323       }
5324     }
5325 
5326     if (++NumMemOps > Limit)
5327       return false;
5328 
5329     MemOps.push_back(VT);
5330     Size -= VTSize;
5331   }
5332 
5333   return true;
5334 }
5335 
5336 static bool shouldLowerMemFuncForSize(const MachineFunction &MF) {
5337   // On Darwin, -Os means optimize for size without hurting performance, so
5338   // only really optimize for size when -Oz (MinSize) is used.
5339   if (MF.getTarget().getTargetTriple().isOSDarwin())
5340     return MF.getFunction().optForMinSize();
5341   return MF.getFunction().optForSize();
5342 }
5343 
5344 static void chainLoadsAndStoresForMemcpy(SelectionDAG &DAG, const SDLoc &dl,
5345                           SmallVector<SDValue, 32> &OutChains, unsigned From,
5346                           unsigned To, SmallVector<SDValue, 16> &OutLoadChains,
5347                           SmallVector<SDValue, 16> &OutStoreChains) {
5348   assert(OutLoadChains.size() && "Missing loads in memcpy inlining");
5349   assert(OutStoreChains.size() && "Missing stores in memcpy inlining");
5350   SmallVector<SDValue, 16> GluedLoadChains;
5351   for (unsigned i = From; i < To; ++i) {
5352     OutChains.push_back(OutLoadChains[i]);
5353     GluedLoadChains.push_back(OutLoadChains[i]);
5354   }
5355 
5356   // Chain for all loads.
5357   SDValue LoadToken = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
5358                                   GluedLoadChains);
5359 
5360   for (unsigned i = From; i < To; ++i) {
5361     StoreSDNode *ST = dyn_cast<StoreSDNode>(OutStoreChains[i]);
5362     SDValue NewStore = DAG.getTruncStore(LoadToken, dl, ST->getValue(),
5363                                   ST->getBasePtr(), ST->getMemoryVT(),
5364                                   ST->getMemOperand());
5365     OutChains.push_back(NewStore);
5366   }
5367 }
5368 
5369 static SDValue getMemcpyLoadsAndStores(SelectionDAG &DAG, const SDLoc &dl,
5370                                        SDValue Chain, SDValue Dst, SDValue Src,
5371                                        uint64_t Size, unsigned Align,
5372                                        bool isVol, bool AlwaysInline,
5373                                        MachinePointerInfo DstPtrInfo,
5374                                        MachinePointerInfo SrcPtrInfo) {
5375   // Turn a memcpy of undef to nop.
5376   if (Src.isUndef())
5377     return Chain;
5378 
5379   // Expand memcpy to a series of load and store ops if the size operand falls
5380   // below a certain threshold.
5381   // TODO: In the AlwaysInline case, if the size is big then generate a loop
5382   // rather than maybe a humongous number of loads and stores.
5383   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5384   const DataLayout &DL = DAG.getDataLayout();
5385   LLVMContext &C = *DAG.getContext();
5386   std::vector<EVT> MemOps;
5387   bool DstAlignCanChange = false;
5388   MachineFunction &MF = DAG.getMachineFunction();
5389   MachineFrameInfo &MFI = MF.getFrameInfo();
5390   bool OptSize = shouldLowerMemFuncForSize(MF);
5391   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
5392   if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
5393     DstAlignCanChange = true;
5394   unsigned SrcAlign = DAG.InferPtrAlignment(Src);
5395   if (Align > SrcAlign)
5396     SrcAlign = Align;
5397   ConstantDataArraySlice Slice;
5398   bool CopyFromConstant = isMemSrcFromConstant(Src, Slice);
5399   bool isZeroConstant = CopyFromConstant && Slice.Array == nullptr;
5400   unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemcpy(OptSize);
5401 
5402   if (!FindOptimalMemOpLowering(MemOps, Limit, Size,
5403                                 (DstAlignCanChange ? 0 : Align),
5404                                 (isZeroConstant ? 0 : SrcAlign),
5405                                 false, false, CopyFromConstant, true,
5406                                 DstPtrInfo.getAddrSpace(),
5407                                 SrcPtrInfo.getAddrSpace(),
5408                                 DAG, TLI))
5409     return SDValue();
5410 
5411   if (DstAlignCanChange) {
5412     Type *Ty = MemOps[0].getTypeForEVT(C);
5413     unsigned NewAlign = (unsigned)DL.getABITypeAlignment(Ty);
5414 
5415     // Don't promote to an alignment that would require dynamic stack
5416     // realignment.
5417     const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
5418     if (!TRI->needsStackRealignment(MF))
5419       while (NewAlign > Align &&
5420              DL.exceedsNaturalStackAlignment(NewAlign))
5421           NewAlign /= 2;
5422 
5423     if (NewAlign > Align) {
5424       // Give the stack frame object a larger alignment if needed.
5425       if (MFI.getObjectAlignment(FI->getIndex()) < NewAlign)
5426         MFI.setObjectAlignment(FI->getIndex(), NewAlign);
5427       Align = NewAlign;
5428     }
5429   }
5430 
5431   MachineMemOperand::Flags MMOFlags =
5432       isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone;
5433   SmallVector<SDValue, 16> OutLoadChains;
5434   SmallVector<SDValue, 16> OutStoreChains;
5435   SmallVector<SDValue, 32> OutChains;
5436   unsigned NumMemOps = MemOps.size();
5437   uint64_t SrcOff = 0, DstOff = 0;
5438   for (unsigned i = 0; i != NumMemOps; ++i) {
5439     EVT VT = MemOps[i];
5440     unsigned VTSize = VT.getSizeInBits() / 8;
5441     SDValue Value, Store;
5442 
5443     if (VTSize > Size) {
5444       // Issuing an unaligned load / store pair  that overlaps with the previous
5445       // pair. Adjust the offset accordingly.
5446       assert(i == NumMemOps-1 && i != 0);
5447       SrcOff -= VTSize - Size;
5448       DstOff -= VTSize - Size;
5449     }
5450 
5451     if (CopyFromConstant &&
5452         (isZeroConstant || (VT.isInteger() && !VT.isVector()))) {
5453       // It's unlikely a store of a vector immediate can be done in a single
5454       // instruction. It would require a load from a constantpool first.
5455       // We only handle zero vectors here.
5456       // FIXME: Handle other cases where store of vector immediate is done in
5457       // a single instruction.
5458       ConstantDataArraySlice SubSlice;
5459       if (SrcOff < Slice.Length) {
5460         SubSlice = Slice;
5461         SubSlice.move(SrcOff);
5462       } else {
5463         // This is an out-of-bounds access and hence UB. Pretend we read zero.
5464         SubSlice.Array = nullptr;
5465         SubSlice.Offset = 0;
5466         SubSlice.Length = VTSize;
5467       }
5468       Value = getMemsetStringVal(VT, dl, DAG, TLI, SubSlice);
5469       if (Value.getNode()) {
5470         Store = DAG.getStore(Chain, dl, Value,
5471                              DAG.getMemBasePlusOffset(Dst, DstOff, dl),
5472                              DstPtrInfo.getWithOffset(DstOff), Align,
5473                              MMOFlags);
5474         OutChains.push_back(Store);
5475       }
5476     }
5477 
5478     if (!Store.getNode()) {
5479       // The type might not be legal for the target.  This should only happen
5480       // if the type is smaller than a legal type, as on PPC, so the right
5481       // thing to do is generate a LoadExt/StoreTrunc pair.  These simplify
5482       // to Load/Store if NVT==VT.
5483       // FIXME does the case above also need this?
5484       EVT NVT = TLI.getTypeToTransformTo(C, VT);
5485       assert(NVT.bitsGE(VT));
5486 
5487       bool isDereferenceable =
5488         SrcPtrInfo.getWithOffset(SrcOff).isDereferenceable(VTSize, C, DL);
5489       MachineMemOperand::Flags SrcMMOFlags = MMOFlags;
5490       if (isDereferenceable)
5491         SrcMMOFlags |= MachineMemOperand::MODereferenceable;
5492 
5493       Value = DAG.getExtLoad(ISD::EXTLOAD, dl, NVT, Chain,
5494                              DAG.getMemBasePlusOffset(Src, SrcOff, dl),
5495                              SrcPtrInfo.getWithOffset(SrcOff), VT,
5496                              MinAlign(SrcAlign, SrcOff), SrcMMOFlags);
5497       OutLoadChains.push_back(Value.getValue(1));
5498 
5499       Store = DAG.getTruncStore(
5500           Chain, dl, Value, DAG.getMemBasePlusOffset(Dst, DstOff, dl),
5501           DstPtrInfo.getWithOffset(DstOff), VT, Align, MMOFlags);
5502       OutStoreChains.push_back(Store);
5503     }
5504     SrcOff += VTSize;
5505     DstOff += VTSize;
5506     Size -= VTSize;
5507   }
5508 
5509   unsigned GluedLdStLimit = MaxLdStGlue == 0 ?
5510                                 TLI.getMaxGluedStoresPerMemcpy() : MaxLdStGlue;
5511   unsigned NumLdStInMemcpy = OutStoreChains.size();
5512 
5513   if (NumLdStInMemcpy) {
5514     // It may be that memcpy might be converted to memset if it's memcpy
5515     // of constants. In such a case, we won't have loads and stores, but
5516     // just stores. In the absence of loads, there is nothing to gang up.
5517     if ((GluedLdStLimit <= 1) || !EnableMemCpyDAGOpt) {
5518       // If target does not care, just leave as it.
5519       for (unsigned i = 0; i < NumLdStInMemcpy; ++i) {
5520         OutChains.push_back(OutLoadChains[i]);
5521         OutChains.push_back(OutStoreChains[i]);
5522       }
5523     } else {
5524       // Ld/St less than/equal limit set by target.
5525       if (NumLdStInMemcpy <= GluedLdStLimit) {
5526           chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, 0,
5527                                         NumLdStInMemcpy, OutLoadChains,
5528                                         OutStoreChains);
5529       } else {
5530         unsigned NumberLdChain =  NumLdStInMemcpy / GluedLdStLimit;
5531         unsigned RemainingLdStInMemcpy = NumLdStInMemcpy % GluedLdStLimit;
5532         unsigned GlueIter = 0;
5533 
5534         for (unsigned cnt = 0; cnt < NumberLdChain; ++cnt) {
5535           unsigned IndexFrom = NumLdStInMemcpy - GlueIter - GluedLdStLimit;
5536           unsigned IndexTo   = NumLdStInMemcpy - GlueIter;
5537 
5538           chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, IndexFrom, IndexTo,
5539                                        OutLoadChains, OutStoreChains);
5540           GlueIter += GluedLdStLimit;
5541         }
5542 
5543         // Residual ld/st.
5544         if (RemainingLdStInMemcpy) {
5545           chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, 0,
5546                                         RemainingLdStInMemcpy, OutLoadChains,
5547                                         OutStoreChains);
5548         }
5549       }
5550     }
5551   }
5552   return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
5553 }
5554 
5555 static SDValue getMemmoveLoadsAndStores(SelectionDAG &DAG, const SDLoc &dl,
5556                                         SDValue Chain, SDValue Dst, SDValue Src,
5557                                         uint64_t Size, unsigned Align,
5558                                         bool isVol, bool AlwaysInline,
5559                                         MachinePointerInfo DstPtrInfo,
5560                                         MachinePointerInfo SrcPtrInfo) {
5561   // Turn a memmove of undef to nop.
5562   if (Src.isUndef())
5563     return Chain;
5564 
5565   // Expand memmove to a series of load and store ops if the size operand falls
5566   // below a certain threshold.
5567   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5568   const DataLayout &DL = DAG.getDataLayout();
5569   LLVMContext &C = *DAG.getContext();
5570   std::vector<EVT> MemOps;
5571   bool DstAlignCanChange = false;
5572   MachineFunction &MF = DAG.getMachineFunction();
5573   MachineFrameInfo &MFI = MF.getFrameInfo();
5574   bool OptSize = shouldLowerMemFuncForSize(MF);
5575   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
5576   if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
5577     DstAlignCanChange = true;
5578   unsigned SrcAlign = DAG.InferPtrAlignment(Src);
5579   if (Align > SrcAlign)
5580     SrcAlign = Align;
5581   unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemmove(OptSize);
5582 
5583   if (!FindOptimalMemOpLowering(MemOps, Limit, Size,
5584                                 (DstAlignCanChange ? 0 : Align), SrcAlign,
5585                                 false, false, false, false,
5586                                 DstPtrInfo.getAddrSpace(),
5587                                 SrcPtrInfo.getAddrSpace(),
5588                                 DAG, TLI))
5589     return SDValue();
5590 
5591   if (DstAlignCanChange) {
5592     Type *Ty = MemOps[0].getTypeForEVT(C);
5593     unsigned NewAlign = (unsigned)DL.getABITypeAlignment(Ty);
5594     if (NewAlign > Align) {
5595       // Give the stack frame object a larger alignment if needed.
5596       if (MFI.getObjectAlignment(FI->getIndex()) < NewAlign)
5597         MFI.setObjectAlignment(FI->getIndex(), NewAlign);
5598       Align = NewAlign;
5599     }
5600   }
5601 
5602   MachineMemOperand::Flags MMOFlags =
5603       isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone;
5604   uint64_t SrcOff = 0, DstOff = 0;
5605   SmallVector<SDValue, 8> LoadValues;
5606   SmallVector<SDValue, 8> LoadChains;
5607   SmallVector<SDValue, 8> OutChains;
5608   unsigned NumMemOps = MemOps.size();
5609   for (unsigned i = 0; i < NumMemOps; i++) {
5610     EVT VT = MemOps[i];
5611     unsigned VTSize = VT.getSizeInBits() / 8;
5612     SDValue Value;
5613 
5614     bool isDereferenceable =
5615       SrcPtrInfo.getWithOffset(SrcOff).isDereferenceable(VTSize, C, DL);
5616     MachineMemOperand::Flags SrcMMOFlags = MMOFlags;
5617     if (isDereferenceable)
5618       SrcMMOFlags |= MachineMemOperand::MODereferenceable;
5619 
5620     Value =
5621         DAG.getLoad(VT, dl, Chain, DAG.getMemBasePlusOffset(Src, SrcOff, dl),
5622                     SrcPtrInfo.getWithOffset(SrcOff), SrcAlign, SrcMMOFlags);
5623     LoadValues.push_back(Value);
5624     LoadChains.push_back(Value.getValue(1));
5625     SrcOff += VTSize;
5626   }
5627   Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
5628   OutChains.clear();
5629   for (unsigned i = 0; i < NumMemOps; i++) {
5630     EVT VT = MemOps[i];
5631     unsigned VTSize = VT.getSizeInBits() / 8;
5632     SDValue Store;
5633 
5634     Store = DAG.getStore(Chain, dl, LoadValues[i],
5635                          DAG.getMemBasePlusOffset(Dst, DstOff, dl),
5636                          DstPtrInfo.getWithOffset(DstOff), Align, MMOFlags);
5637     OutChains.push_back(Store);
5638     DstOff += VTSize;
5639   }
5640 
5641   return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
5642 }
5643 
5644 /// Lower the call to 'memset' intrinsic function into a series of store
5645 /// operations.
5646 ///
5647 /// \param DAG Selection DAG where lowered code is placed.
5648 /// \param dl Link to corresponding IR location.
5649 /// \param Chain Control flow dependency.
5650 /// \param Dst Pointer to destination memory location.
5651 /// \param Src Value of byte to write into the memory.
5652 /// \param Size Number of bytes to write.
5653 /// \param Align Alignment of the destination in bytes.
5654 /// \param isVol True if destination is volatile.
5655 /// \param DstPtrInfo IR information on the memory pointer.
5656 /// \returns New head in the control flow, if lowering was successful, empty
5657 /// SDValue otherwise.
5658 ///
5659 /// The function tries to replace 'llvm.memset' intrinsic with several store
5660 /// operations and value calculation code. This is usually profitable for small
5661 /// memory size.
5662 static SDValue getMemsetStores(SelectionDAG &DAG, const SDLoc &dl,
5663                                SDValue Chain, SDValue Dst, SDValue Src,
5664                                uint64_t Size, unsigned Align, bool isVol,
5665                                MachinePointerInfo DstPtrInfo) {
5666   // Turn a memset of undef to nop.
5667   if (Src.isUndef())
5668     return Chain;
5669 
5670   // Expand memset to a series of load/store ops if the size operand
5671   // falls below a certain threshold.
5672   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5673   std::vector<EVT> MemOps;
5674   bool DstAlignCanChange = false;
5675   MachineFunction &MF = DAG.getMachineFunction();
5676   MachineFrameInfo &MFI = MF.getFrameInfo();
5677   bool OptSize = shouldLowerMemFuncForSize(MF);
5678   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
5679   if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
5680     DstAlignCanChange = true;
5681   bool IsZeroVal =
5682     isa<ConstantSDNode>(Src) && cast<ConstantSDNode>(Src)->isNullValue();
5683   if (!FindOptimalMemOpLowering(MemOps, TLI.getMaxStoresPerMemset(OptSize),
5684                                 Size, (DstAlignCanChange ? 0 : Align), 0,
5685                                 true, IsZeroVal, false, true,
5686                                 DstPtrInfo.getAddrSpace(), ~0u,
5687                                 DAG, TLI))
5688     return SDValue();
5689 
5690   if (DstAlignCanChange) {
5691     Type *Ty = MemOps[0].getTypeForEVT(*DAG.getContext());
5692     unsigned NewAlign = (unsigned)DAG.getDataLayout().getABITypeAlignment(Ty);
5693     if (NewAlign > Align) {
5694       // Give the stack frame object a larger alignment if needed.
5695       if (MFI.getObjectAlignment(FI->getIndex()) < NewAlign)
5696         MFI.setObjectAlignment(FI->getIndex(), NewAlign);
5697       Align = NewAlign;
5698     }
5699   }
5700 
5701   SmallVector<SDValue, 8> OutChains;
5702   uint64_t DstOff = 0;
5703   unsigned NumMemOps = MemOps.size();
5704 
5705   // Find the largest store and generate the bit pattern for it.
5706   EVT LargestVT = MemOps[0];
5707   for (unsigned i = 1; i < NumMemOps; i++)
5708     if (MemOps[i].bitsGT(LargestVT))
5709       LargestVT = MemOps[i];
5710   SDValue MemSetValue = getMemsetValue(Src, LargestVT, DAG, dl);
5711 
5712   for (unsigned i = 0; i < NumMemOps; i++) {
5713     EVT VT = MemOps[i];
5714     unsigned VTSize = VT.getSizeInBits() / 8;
5715     if (VTSize > Size) {
5716       // Issuing an unaligned load / store pair  that overlaps with the previous
5717       // pair. Adjust the offset accordingly.
5718       assert(i == NumMemOps-1 && i != 0);
5719       DstOff -= VTSize - Size;
5720     }
5721 
5722     // If this store is smaller than the largest store see whether we can get
5723     // the smaller value for free with a truncate.
5724     SDValue Value = MemSetValue;
5725     if (VT.bitsLT(LargestVT)) {
5726       if (!LargestVT.isVector() && !VT.isVector() &&
5727           TLI.isTruncateFree(LargestVT, VT))
5728         Value = DAG.getNode(ISD::TRUNCATE, dl, VT, MemSetValue);
5729       else
5730         Value = getMemsetValue(Src, VT, DAG, dl);
5731     }
5732     assert(Value.getValueType() == VT && "Value with wrong type.");
5733     SDValue Store = DAG.getStore(
5734         Chain, dl, Value, DAG.getMemBasePlusOffset(Dst, DstOff, dl),
5735         DstPtrInfo.getWithOffset(DstOff), Align,
5736         isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone);
5737     OutChains.push_back(Store);
5738     DstOff += VT.getSizeInBits() / 8;
5739     Size -= VTSize;
5740   }
5741 
5742   return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
5743 }
5744 
5745 static void checkAddrSpaceIsValidForLibcall(const TargetLowering *TLI,
5746                                             unsigned AS) {
5747   // Lowering memcpy / memset / memmove intrinsics to calls is only valid if all
5748   // pointer operands can be losslessly bitcasted to pointers of address space 0
5749   if (AS != 0 && !TLI->isNoopAddrSpaceCast(AS, 0)) {
5750     report_fatal_error("cannot lower memory intrinsic in address space " +
5751                        Twine(AS));
5752   }
5753 }
5754 
5755 SDValue SelectionDAG::getMemcpy(SDValue Chain, const SDLoc &dl, SDValue Dst,
5756                                 SDValue Src, SDValue Size, unsigned Align,
5757                                 bool isVol, bool AlwaysInline, bool isTailCall,
5758                                 MachinePointerInfo DstPtrInfo,
5759                                 MachinePointerInfo SrcPtrInfo) {
5760   assert(Align && "The SDAG layer expects explicit alignment and reserves 0");
5761 
5762   // Check to see if we should lower the memcpy to loads and stores first.
5763   // For cases within the target-specified limits, this is the best choice.
5764   ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
5765   if (ConstantSize) {
5766     // Memcpy with size zero? Just return the original chain.
5767     if (ConstantSize->isNullValue())
5768       return Chain;
5769 
5770     SDValue Result = getMemcpyLoadsAndStores(*this, dl, Chain, Dst, Src,
5771                                              ConstantSize->getZExtValue(),Align,
5772                                 isVol, false, DstPtrInfo, SrcPtrInfo);
5773     if (Result.getNode())
5774       return Result;
5775   }
5776 
5777   // Then check to see if we should lower the memcpy with target-specific
5778   // code. If the target chooses to do this, this is the next best.
5779   if (TSI) {
5780     SDValue Result = TSI->EmitTargetCodeForMemcpy(
5781         *this, dl, Chain, Dst, Src, Size, Align, isVol, AlwaysInline,
5782         DstPtrInfo, SrcPtrInfo);
5783     if (Result.getNode())
5784       return Result;
5785   }
5786 
5787   // If we really need inline code and the target declined to provide it,
5788   // use a (potentially long) sequence of loads and stores.
5789   if (AlwaysInline) {
5790     assert(ConstantSize && "AlwaysInline requires a constant size!");
5791     return getMemcpyLoadsAndStores(*this, dl, Chain, Dst, Src,
5792                                    ConstantSize->getZExtValue(), Align, isVol,
5793                                    true, DstPtrInfo, SrcPtrInfo);
5794   }
5795 
5796   checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace());
5797   checkAddrSpaceIsValidForLibcall(TLI, SrcPtrInfo.getAddrSpace());
5798 
5799   // FIXME: If the memcpy is volatile (isVol), lowering it to a plain libc
5800   // memcpy is not guaranteed to be safe. libc memcpys aren't required to
5801   // respect volatile, so they may do things like read or write memory
5802   // beyond the given memory regions. But fixing this isn't easy, and most
5803   // people don't care.
5804 
5805   // Emit a library call.
5806   TargetLowering::ArgListTy Args;
5807   TargetLowering::ArgListEntry Entry;
5808   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
5809   Entry.Node = Dst; Args.push_back(Entry);
5810   Entry.Node = Src; Args.push_back(Entry);
5811   Entry.Node = Size; Args.push_back(Entry);
5812   // FIXME: pass in SDLoc
5813   TargetLowering::CallLoweringInfo CLI(*this);
5814   CLI.setDebugLoc(dl)
5815       .setChain(Chain)
5816       .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMCPY),
5817                     Dst.getValueType().getTypeForEVT(*getContext()),
5818                     getExternalSymbol(TLI->getLibcallName(RTLIB::MEMCPY),
5819                                       TLI->getPointerTy(getDataLayout())),
5820                     std::move(Args))
5821       .setDiscardResult()
5822       .setTailCall(isTailCall);
5823 
5824   std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
5825   return CallResult.second;
5826 }
5827 
5828 SDValue SelectionDAG::getAtomicMemcpy(SDValue Chain, const SDLoc &dl,
5829                                       SDValue Dst, unsigned DstAlign,
5830                                       SDValue Src, unsigned SrcAlign,
5831                                       SDValue Size, Type *SizeTy,
5832                                       unsigned ElemSz, bool isTailCall,
5833                                       MachinePointerInfo DstPtrInfo,
5834                                       MachinePointerInfo SrcPtrInfo) {
5835   // Emit a library call.
5836   TargetLowering::ArgListTy Args;
5837   TargetLowering::ArgListEntry Entry;
5838   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
5839   Entry.Node = Dst;
5840   Args.push_back(Entry);
5841 
5842   Entry.Node = Src;
5843   Args.push_back(Entry);
5844 
5845   Entry.Ty = SizeTy;
5846   Entry.Node = Size;
5847   Args.push_back(Entry);
5848 
5849   RTLIB::Libcall LibraryCall =
5850       RTLIB::getMEMCPY_ELEMENT_UNORDERED_ATOMIC(ElemSz);
5851   if (LibraryCall == RTLIB::UNKNOWN_LIBCALL)
5852     report_fatal_error("Unsupported element size");
5853 
5854   TargetLowering::CallLoweringInfo CLI(*this);
5855   CLI.setDebugLoc(dl)
5856       .setChain(Chain)
5857       .setLibCallee(TLI->getLibcallCallingConv(LibraryCall),
5858                     Type::getVoidTy(*getContext()),
5859                     getExternalSymbol(TLI->getLibcallName(LibraryCall),
5860                                       TLI->getPointerTy(getDataLayout())),
5861                     std::move(Args))
5862       .setDiscardResult()
5863       .setTailCall(isTailCall);
5864 
5865   std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
5866   return CallResult.second;
5867 }
5868 
5869 SDValue SelectionDAG::getMemmove(SDValue Chain, const SDLoc &dl, SDValue Dst,
5870                                  SDValue Src, SDValue Size, unsigned Align,
5871                                  bool isVol, bool isTailCall,
5872                                  MachinePointerInfo DstPtrInfo,
5873                                  MachinePointerInfo SrcPtrInfo) {
5874   assert(Align && "The SDAG layer expects explicit alignment and reserves 0");
5875 
5876   // Check to see if we should lower the memmove to loads and stores first.
5877   // For cases within the target-specified limits, this is the best choice.
5878   ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
5879   if (ConstantSize) {
5880     // Memmove with size zero? Just return the original chain.
5881     if (ConstantSize->isNullValue())
5882       return Chain;
5883 
5884     SDValue Result =
5885       getMemmoveLoadsAndStores(*this, dl, Chain, Dst, Src,
5886                                ConstantSize->getZExtValue(), Align, isVol,
5887                                false, DstPtrInfo, SrcPtrInfo);
5888     if (Result.getNode())
5889       return Result;
5890   }
5891 
5892   // Then check to see if we should lower the memmove with target-specific
5893   // code. If the target chooses to do this, this is the next best.
5894   if (TSI) {
5895     SDValue Result = TSI->EmitTargetCodeForMemmove(
5896         *this, dl, Chain, Dst, Src, Size, Align, isVol, DstPtrInfo, SrcPtrInfo);
5897     if (Result.getNode())
5898       return Result;
5899   }
5900 
5901   checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace());
5902   checkAddrSpaceIsValidForLibcall(TLI, SrcPtrInfo.getAddrSpace());
5903 
5904   // FIXME: If the memmove is volatile, lowering it to plain libc memmove may
5905   // not be safe.  See memcpy above for more details.
5906 
5907   // Emit a library call.
5908   TargetLowering::ArgListTy Args;
5909   TargetLowering::ArgListEntry Entry;
5910   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
5911   Entry.Node = Dst; Args.push_back(Entry);
5912   Entry.Node = Src; Args.push_back(Entry);
5913   Entry.Node = Size; Args.push_back(Entry);
5914   // FIXME:  pass in SDLoc
5915   TargetLowering::CallLoweringInfo CLI(*this);
5916   CLI.setDebugLoc(dl)
5917       .setChain(Chain)
5918       .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMMOVE),
5919                     Dst.getValueType().getTypeForEVT(*getContext()),
5920                     getExternalSymbol(TLI->getLibcallName(RTLIB::MEMMOVE),
5921                                       TLI->getPointerTy(getDataLayout())),
5922                     std::move(Args))
5923       .setDiscardResult()
5924       .setTailCall(isTailCall);
5925 
5926   std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
5927   return CallResult.second;
5928 }
5929 
5930 SDValue SelectionDAG::getAtomicMemmove(SDValue Chain, const SDLoc &dl,
5931                                        SDValue Dst, unsigned DstAlign,
5932                                        SDValue Src, unsigned SrcAlign,
5933                                        SDValue Size, Type *SizeTy,
5934                                        unsigned ElemSz, bool isTailCall,
5935                                        MachinePointerInfo DstPtrInfo,
5936                                        MachinePointerInfo SrcPtrInfo) {
5937   // Emit a library call.
5938   TargetLowering::ArgListTy Args;
5939   TargetLowering::ArgListEntry Entry;
5940   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
5941   Entry.Node = Dst;
5942   Args.push_back(Entry);
5943 
5944   Entry.Node = Src;
5945   Args.push_back(Entry);
5946 
5947   Entry.Ty = SizeTy;
5948   Entry.Node = Size;
5949   Args.push_back(Entry);
5950 
5951   RTLIB::Libcall LibraryCall =
5952       RTLIB::getMEMMOVE_ELEMENT_UNORDERED_ATOMIC(ElemSz);
5953   if (LibraryCall == RTLIB::UNKNOWN_LIBCALL)
5954     report_fatal_error("Unsupported element size");
5955 
5956   TargetLowering::CallLoweringInfo CLI(*this);
5957   CLI.setDebugLoc(dl)
5958       .setChain(Chain)
5959       .setLibCallee(TLI->getLibcallCallingConv(LibraryCall),
5960                     Type::getVoidTy(*getContext()),
5961                     getExternalSymbol(TLI->getLibcallName(LibraryCall),
5962                                       TLI->getPointerTy(getDataLayout())),
5963                     std::move(Args))
5964       .setDiscardResult()
5965       .setTailCall(isTailCall);
5966 
5967   std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
5968   return CallResult.second;
5969 }
5970 
5971 SDValue SelectionDAG::getMemset(SDValue Chain, const SDLoc &dl, SDValue Dst,
5972                                 SDValue Src, SDValue Size, unsigned Align,
5973                                 bool isVol, bool isTailCall,
5974                                 MachinePointerInfo DstPtrInfo) {
5975   assert(Align && "The SDAG layer expects explicit alignment and reserves 0");
5976 
5977   // Check to see if we should lower the memset to stores first.
5978   // For cases within the target-specified limits, this is the best choice.
5979   ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
5980   if (ConstantSize) {
5981     // Memset with size zero? Just return the original chain.
5982     if (ConstantSize->isNullValue())
5983       return Chain;
5984 
5985     SDValue Result =
5986       getMemsetStores(*this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(),
5987                       Align, isVol, DstPtrInfo);
5988 
5989     if (Result.getNode())
5990       return Result;
5991   }
5992 
5993   // Then check to see if we should lower the memset with target-specific
5994   // code. If the target chooses to do this, this is the next best.
5995   if (TSI) {
5996     SDValue Result = TSI->EmitTargetCodeForMemset(
5997         *this, dl, Chain, Dst, Src, Size, Align, isVol, DstPtrInfo);
5998     if (Result.getNode())
5999       return Result;
6000   }
6001 
6002   checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace());
6003 
6004   // Emit a library call.
6005   Type *IntPtrTy = getDataLayout().getIntPtrType(*getContext());
6006   TargetLowering::ArgListTy Args;
6007   TargetLowering::ArgListEntry Entry;
6008   Entry.Node = Dst; Entry.Ty = IntPtrTy;
6009   Args.push_back(Entry);
6010   Entry.Node = Src;
6011   Entry.Ty = Src.getValueType().getTypeForEVT(*getContext());
6012   Args.push_back(Entry);
6013   Entry.Node = Size;
6014   Entry.Ty = IntPtrTy;
6015   Args.push_back(Entry);
6016 
6017   // FIXME: pass in SDLoc
6018   TargetLowering::CallLoweringInfo CLI(*this);
6019   CLI.setDebugLoc(dl)
6020       .setChain(Chain)
6021       .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMSET),
6022                     Dst.getValueType().getTypeForEVT(*getContext()),
6023                     getExternalSymbol(TLI->getLibcallName(RTLIB::MEMSET),
6024                                       TLI->getPointerTy(getDataLayout())),
6025                     std::move(Args))
6026       .setDiscardResult()
6027       .setTailCall(isTailCall);
6028 
6029   std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
6030   return CallResult.second;
6031 }
6032 
6033 SDValue SelectionDAG::getAtomicMemset(SDValue Chain, const SDLoc &dl,
6034                                       SDValue Dst, unsigned DstAlign,
6035                                       SDValue Value, SDValue Size, Type *SizeTy,
6036                                       unsigned ElemSz, bool isTailCall,
6037                                       MachinePointerInfo DstPtrInfo) {
6038   // Emit a library call.
6039   TargetLowering::ArgListTy Args;
6040   TargetLowering::ArgListEntry Entry;
6041   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
6042   Entry.Node = Dst;
6043   Args.push_back(Entry);
6044 
6045   Entry.Ty = Type::getInt8Ty(*getContext());
6046   Entry.Node = Value;
6047   Args.push_back(Entry);
6048 
6049   Entry.Ty = SizeTy;
6050   Entry.Node = Size;
6051   Args.push_back(Entry);
6052 
6053   RTLIB::Libcall LibraryCall =
6054       RTLIB::getMEMSET_ELEMENT_UNORDERED_ATOMIC(ElemSz);
6055   if (LibraryCall == RTLIB::UNKNOWN_LIBCALL)
6056     report_fatal_error("Unsupported element size");
6057 
6058   TargetLowering::CallLoweringInfo CLI(*this);
6059   CLI.setDebugLoc(dl)
6060       .setChain(Chain)
6061       .setLibCallee(TLI->getLibcallCallingConv(LibraryCall),
6062                     Type::getVoidTy(*getContext()),
6063                     getExternalSymbol(TLI->getLibcallName(LibraryCall),
6064                                       TLI->getPointerTy(getDataLayout())),
6065                     std::move(Args))
6066       .setDiscardResult()
6067       .setTailCall(isTailCall);
6068 
6069   std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
6070   return CallResult.second;
6071 }
6072 
6073 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
6074                                 SDVTList VTList, ArrayRef<SDValue> Ops,
6075                                 MachineMemOperand *MMO) {
6076   FoldingSetNodeID ID;
6077   ID.AddInteger(MemVT.getRawBits());
6078   AddNodeIDNode(ID, Opcode, VTList, Ops);
6079   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
6080   void* IP = nullptr;
6081   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
6082     cast<AtomicSDNode>(E)->refineAlignment(MMO);
6083     return SDValue(E, 0);
6084   }
6085 
6086   auto *N = newSDNode<AtomicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
6087                                     VTList, MemVT, MMO);
6088   createOperands(N, Ops);
6089 
6090   CSEMap.InsertNode(N, IP);
6091   InsertNode(N);
6092   return SDValue(N, 0);
6093 }
6094 
6095 SDValue SelectionDAG::getAtomicCmpSwap(
6096     unsigned Opcode, const SDLoc &dl, EVT MemVT, SDVTList VTs, SDValue Chain,
6097     SDValue Ptr, SDValue Cmp, SDValue Swp, MachinePointerInfo PtrInfo,
6098     unsigned Alignment, AtomicOrdering SuccessOrdering,
6099     AtomicOrdering FailureOrdering, SyncScope::ID SSID) {
6100   assert(Opcode == ISD::ATOMIC_CMP_SWAP ||
6101          Opcode == ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS);
6102   assert(Cmp.getValueType() == Swp.getValueType() && "Invalid Atomic Op Types");
6103 
6104   if (Alignment == 0)  // Ensure that codegen never sees alignment 0
6105     Alignment = getEVTAlignment(MemVT);
6106 
6107   MachineFunction &MF = getMachineFunction();
6108 
6109   // FIXME: Volatile isn't really correct; we should keep track of atomic
6110   // orderings in the memoperand.
6111   auto Flags = MachineMemOperand::MOVolatile | MachineMemOperand::MOLoad |
6112                MachineMemOperand::MOStore;
6113   MachineMemOperand *MMO =
6114     MF.getMachineMemOperand(PtrInfo, Flags, MemVT.getStoreSize(), Alignment,
6115                             AAMDNodes(), nullptr, SSID, SuccessOrdering,
6116                             FailureOrdering);
6117 
6118   return getAtomicCmpSwap(Opcode, dl, MemVT, VTs, Chain, Ptr, Cmp, Swp, MMO);
6119 }
6120 
6121 SDValue SelectionDAG::getAtomicCmpSwap(unsigned Opcode, const SDLoc &dl,
6122                                        EVT MemVT, SDVTList VTs, SDValue Chain,
6123                                        SDValue Ptr, SDValue Cmp, SDValue Swp,
6124                                        MachineMemOperand *MMO) {
6125   assert(Opcode == ISD::ATOMIC_CMP_SWAP ||
6126          Opcode == ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS);
6127   assert(Cmp.getValueType() == Swp.getValueType() && "Invalid Atomic Op Types");
6128 
6129   SDValue Ops[] = {Chain, Ptr, Cmp, Swp};
6130   return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
6131 }
6132 
6133 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
6134                                 SDValue Chain, SDValue Ptr, SDValue Val,
6135                                 const Value *PtrVal, unsigned Alignment,
6136                                 AtomicOrdering Ordering,
6137                                 SyncScope::ID SSID) {
6138   if (Alignment == 0)  // Ensure that codegen never sees alignment 0
6139     Alignment = getEVTAlignment(MemVT);
6140 
6141   MachineFunction &MF = getMachineFunction();
6142   // An atomic store does not load. An atomic load does not store.
6143   // (An atomicrmw obviously both loads and stores.)
6144   // For now, atomics are considered to be volatile always, and they are
6145   // chained as such.
6146   // FIXME: Volatile isn't really correct; we should keep track of atomic
6147   // orderings in the memoperand.
6148   auto Flags = MachineMemOperand::MOVolatile;
6149   if (Opcode != ISD::ATOMIC_STORE)
6150     Flags |= MachineMemOperand::MOLoad;
6151   if (Opcode != ISD::ATOMIC_LOAD)
6152     Flags |= MachineMemOperand::MOStore;
6153 
6154   MachineMemOperand *MMO =
6155     MF.getMachineMemOperand(MachinePointerInfo(PtrVal), Flags,
6156                             MemVT.getStoreSize(), Alignment, AAMDNodes(),
6157                             nullptr, SSID, Ordering);
6158 
6159   return getAtomic(Opcode, dl, MemVT, Chain, Ptr, Val, MMO);
6160 }
6161 
6162 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
6163                                 SDValue Chain, SDValue Ptr, SDValue Val,
6164                                 MachineMemOperand *MMO) {
6165   assert((Opcode == ISD::ATOMIC_LOAD_ADD ||
6166           Opcode == ISD::ATOMIC_LOAD_SUB ||
6167           Opcode == ISD::ATOMIC_LOAD_AND ||
6168           Opcode == ISD::ATOMIC_LOAD_CLR ||
6169           Opcode == ISD::ATOMIC_LOAD_OR ||
6170           Opcode == ISD::ATOMIC_LOAD_XOR ||
6171           Opcode == ISD::ATOMIC_LOAD_NAND ||
6172           Opcode == ISD::ATOMIC_LOAD_MIN ||
6173           Opcode == ISD::ATOMIC_LOAD_MAX ||
6174           Opcode == ISD::ATOMIC_LOAD_UMIN ||
6175           Opcode == ISD::ATOMIC_LOAD_UMAX ||
6176           Opcode == ISD::ATOMIC_SWAP ||
6177           Opcode == ISD::ATOMIC_STORE) &&
6178          "Invalid Atomic Op");
6179 
6180   EVT VT = Val.getValueType();
6181 
6182   SDVTList VTs = Opcode == ISD::ATOMIC_STORE ? getVTList(MVT::Other) :
6183                                                getVTList(VT, MVT::Other);
6184   SDValue Ops[] = {Chain, Ptr, Val};
6185   return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
6186 }
6187 
6188 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
6189                                 EVT VT, SDValue Chain, SDValue Ptr,
6190                                 MachineMemOperand *MMO) {
6191   assert(Opcode == ISD::ATOMIC_LOAD && "Invalid Atomic Op");
6192 
6193   SDVTList VTs = getVTList(VT, MVT::Other);
6194   SDValue Ops[] = {Chain, Ptr};
6195   return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
6196 }
6197 
6198 /// getMergeValues - Create a MERGE_VALUES node from the given operands.
6199 SDValue SelectionDAG::getMergeValues(ArrayRef<SDValue> Ops, const SDLoc &dl) {
6200   if (Ops.size() == 1)
6201     return Ops[0];
6202 
6203   SmallVector<EVT, 4> VTs;
6204   VTs.reserve(Ops.size());
6205   for (unsigned i = 0; i < Ops.size(); ++i)
6206     VTs.push_back(Ops[i].getValueType());
6207   return getNode(ISD::MERGE_VALUES, dl, getVTList(VTs), Ops);
6208 }
6209 
6210 SDValue SelectionDAG::getMemIntrinsicNode(
6211     unsigned Opcode, const SDLoc &dl, SDVTList VTList, ArrayRef<SDValue> Ops,
6212     EVT MemVT, MachinePointerInfo PtrInfo, unsigned Align,
6213     MachineMemOperand::Flags Flags, unsigned Size) {
6214   if (Align == 0)  // Ensure that codegen never sees alignment 0
6215     Align = getEVTAlignment(MemVT);
6216 
6217   if (!Size)
6218     Size = MemVT.getStoreSize();
6219 
6220   MachineFunction &MF = getMachineFunction();
6221   MachineMemOperand *MMO =
6222     MF.getMachineMemOperand(PtrInfo, Flags, Size, Align);
6223 
6224   return getMemIntrinsicNode(Opcode, dl, VTList, Ops, MemVT, MMO);
6225 }
6226 
6227 SDValue SelectionDAG::getMemIntrinsicNode(unsigned Opcode, const SDLoc &dl,
6228                                           SDVTList VTList,
6229                                           ArrayRef<SDValue> Ops, EVT MemVT,
6230                                           MachineMemOperand *MMO) {
6231   assert((Opcode == ISD::INTRINSIC_VOID ||
6232           Opcode == ISD::INTRINSIC_W_CHAIN ||
6233           Opcode == ISD::PREFETCH ||
6234           Opcode == ISD::LIFETIME_START ||
6235           Opcode == ISD::LIFETIME_END ||
6236           ((int)Opcode <= std::numeric_limits<int>::max() &&
6237            (int)Opcode >= ISD::FIRST_TARGET_MEMORY_OPCODE)) &&
6238          "Opcode is not a memory-accessing opcode!");
6239 
6240   // Memoize the node unless it returns a flag.
6241   MemIntrinsicSDNode *N;
6242   if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) {
6243     FoldingSetNodeID ID;
6244     AddNodeIDNode(ID, Opcode, VTList, Ops);
6245     ID.AddInteger(getSyntheticNodeSubclassData<MemIntrinsicSDNode>(
6246         Opcode, dl.getIROrder(), VTList, MemVT, MMO));
6247     ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
6248     void *IP = nullptr;
6249     if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
6250       cast<MemIntrinsicSDNode>(E)->refineAlignment(MMO);
6251       return SDValue(E, 0);
6252     }
6253 
6254     N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
6255                                       VTList, MemVT, MMO);
6256     createOperands(N, Ops);
6257 
6258   CSEMap.InsertNode(N, IP);
6259   } else {
6260     N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
6261                                       VTList, MemVT, MMO);
6262     createOperands(N, Ops);
6263   }
6264   InsertNode(N);
6265   return SDValue(N, 0);
6266 }
6267 
6268 /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a
6269 /// MachinePointerInfo record from it.  This is particularly useful because the
6270 /// code generator has many cases where it doesn't bother passing in a
6271 /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst".
6272 static MachinePointerInfo InferPointerInfo(const MachinePointerInfo &Info,
6273                                            SelectionDAG &DAG, SDValue Ptr,
6274                                            int64_t Offset = 0) {
6275   // If this is FI+Offset, we can model it.
6276   if (const FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr))
6277     return MachinePointerInfo::getFixedStack(DAG.getMachineFunction(),
6278                                              FI->getIndex(), Offset);
6279 
6280   // If this is (FI+Offset1)+Offset2, we can model it.
6281   if (Ptr.getOpcode() != ISD::ADD ||
6282       !isa<ConstantSDNode>(Ptr.getOperand(1)) ||
6283       !isa<FrameIndexSDNode>(Ptr.getOperand(0)))
6284     return Info;
6285 
6286   int FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
6287   return MachinePointerInfo::getFixedStack(
6288       DAG.getMachineFunction(), FI,
6289       Offset + cast<ConstantSDNode>(Ptr.getOperand(1))->getSExtValue());
6290 }
6291 
6292 /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a
6293 /// MachinePointerInfo record from it.  This is particularly useful because the
6294 /// code generator has many cases where it doesn't bother passing in a
6295 /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst".
6296 static MachinePointerInfo InferPointerInfo(const MachinePointerInfo &Info,
6297                                            SelectionDAG &DAG, SDValue Ptr,
6298                                            SDValue OffsetOp) {
6299   // If the 'Offset' value isn't a constant, we can't handle this.
6300   if (ConstantSDNode *OffsetNode = dyn_cast<ConstantSDNode>(OffsetOp))
6301     return InferPointerInfo(Info, DAG, Ptr, OffsetNode->getSExtValue());
6302   if (OffsetOp.isUndef())
6303     return InferPointerInfo(Info, DAG, Ptr);
6304   return Info;
6305 }
6306 
6307 SDValue SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType,
6308                               EVT VT, const SDLoc &dl, SDValue Chain,
6309                               SDValue Ptr, SDValue Offset,
6310                               MachinePointerInfo PtrInfo, EVT MemVT,
6311                               unsigned Alignment,
6312                               MachineMemOperand::Flags MMOFlags,
6313                               const AAMDNodes &AAInfo, const MDNode *Ranges) {
6314   assert(Chain.getValueType() == MVT::Other &&
6315         "Invalid chain type");
6316   if (Alignment == 0)  // Ensure that codegen never sees alignment 0
6317     Alignment = getEVTAlignment(MemVT);
6318 
6319   MMOFlags |= MachineMemOperand::MOLoad;
6320   assert((MMOFlags & MachineMemOperand::MOStore) == 0);
6321   // If we don't have a PtrInfo, infer the trivial frame index case to simplify
6322   // clients.
6323   if (PtrInfo.V.isNull())
6324     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr, Offset);
6325 
6326   MachineFunction &MF = getMachineFunction();
6327   MachineMemOperand *MMO = MF.getMachineMemOperand(
6328       PtrInfo, MMOFlags, MemVT.getStoreSize(), Alignment, AAInfo, Ranges);
6329   return getLoad(AM, ExtType, VT, dl, Chain, Ptr, Offset, MemVT, MMO);
6330 }
6331 
6332 SDValue SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType,
6333                               EVT VT, const SDLoc &dl, SDValue Chain,
6334                               SDValue Ptr, SDValue Offset, EVT MemVT,
6335                               MachineMemOperand *MMO) {
6336   if (VT == MemVT) {
6337     ExtType = ISD::NON_EXTLOAD;
6338   } else if (ExtType == ISD::NON_EXTLOAD) {
6339     assert(VT == MemVT && "Non-extending load from different memory type!");
6340   } else {
6341     // Extending load.
6342     assert(MemVT.getScalarType().bitsLT(VT.getScalarType()) &&
6343            "Should only be an extending load, not truncating!");
6344     assert(VT.isInteger() == MemVT.isInteger() &&
6345            "Cannot convert from FP to Int or Int -> FP!");
6346     assert(VT.isVector() == MemVT.isVector() &&
6347            "Cannot use an ext load to convert to or from a vector!");
6348     assert((!VT.isVector() ||
6349             VT.getVectorNumElements() == MemVT.getVectorNumElements()) &&
6350            "Cannot use an ext load to change the number of vector elements!");
6351   }
6352 
6353   bool Indexed = AM != ISD::UNINDEXED;
6354   assert((Indexed || Offset.isUndef()) && "Unindexed load with an offset!");
6355 
6356   SDVTList VTs = Indexed ?
6357     getVTList(VT, Ptr.getValueType(), MVT::Other) : getVTList(VT, MVT::Other);
6358   SDValue Ops[] = { Chain, Ptr, Offset };
6359   FoldingSetNodeID ID;
6360   AddNodeIDNode(ID, ISD::LOAD, VTs, Ops);
6361   ID.AddInteger(MemVT.getRawBits());
6362   ID.AddInteger(getSyntheticNodeSubclassData<LoadSDNode>(
6363       dl.getIROrder(), VTs, AM, ExtType, MemVT, MMO));
6364   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
6365   void *IP = nullptr;
6366   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
6367     cast<LoadSDNode>(E)->refineAlignment(MMO);
6368     return SDValue(E, 0);
6369   }
6370   auto *N = newSDNode<LoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
6371                                   ExtType, MemVT, MMO);
6372   createOperands(N, Ops);
6373 
6374   CSEMap.InsertNode(N, IP);
6375   InsertNode(N);
6376   SDValue V(N, 0);
6377   NewSDValueDbgMsg(V, "Creating new node: ", this);
6378   return V;
6379 }
6380 
6381 SDValue SelectionDAG::getLoad(EVT VT, const SDLoc &dl, SDValue Chain,
6382                               SDValue Ptr, MachinePointerInfo PtrInfo,
6383                               unsigned Alignment,
6384                               MachineMemOperand::Flags MMOFlags,
6385                               const AAMDNodes &AAInfo, const MDNode *Ranges) {
6386   SDValue Undef = getUNDEF(Ptr.getValueType());
6387   return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
6388                  PtrInfo, VT, Alignment, MMOFlags, AAInfo, Ranges);
6389 }
6390 
6391 SDValue SelectionDAG::getLoad(EVT VT, const SDLoc &dl, SDValue Chain,
6392                               SDValue Ptr, MachineMemOperand *MMO) {
6393   SDValue Undef = getUNDEF(Ptr.getValueType());
6394   return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
6395                  VT, MMO);
6396 }
6397 
6398 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl,
6399                                  EVT VT, SDValue Chain, SDValue Ptr,
6400                                  MachinePointerInfo PtrInfo, EVT MemVT,
6401                                  unsigned Alignment,
6402                                  MachineMemOperand::Flags MMOFlags,
6403                                  const AAMDNodes &AAInfo) {
6404   SDValue Undef = getUNDEF(Ptr.getValueType());
6405   return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, PtrInfo,
6406                  MemVT, Alignment, MMOFlags, AAInfo);
6407 }
6408 
6409 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl,
6410                                  EVT VT, SDValue Chain, SDValue Ptr, EVT MemVT,
6411                                  MachineMemOperand *MMO) {
6412   SDValue Undef = getUNDEF(Ptr.getValueType());
6413   return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef,
6414                  MemVT, MMO);
6415 }
6416 
6417 SDValue SelectionDAG::getIndexedLoad(SDValue OrigLoad, const SDLoc &dl,
6418                                      SDValue Base, SDValue Offset,
6419                                      ISD::MemIndexedMode AM) {
6420   LoadSDNode *LD = cast<LoadSDNode>(OrigLoad);
6421   assert(LD->getOffset().isUndef() && "Load is already a indexed load!");
6422   // Don't propagate the invariant or dereferenceable flags.
6423   auto MMOFlags =
6424       LD->getMemOperand()->getFlags() &
6425       ~(MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable);
6426   return getLoad(AM, LD->getExtensionType(), OrigLoad.getValueType(), dl,
6427                  LD->getChain(), Base, Offset, LD->getPointerInfo(),
6428                  LD->getMemoryVT(), LD->getAlignment(), MMOFlags,
6429                  LD->getAAInfo());
6430 }
6431 
6432 SDValue SelectionDAG::getStore(SDValue Chain, const SDLoc &dl, SDValue Val,
6433                                SDValue Ptr, MachinePointerInfo PtrInfo,
6434                                unsigned Alignment,
6435                                MachineMemOperand::Flags MMOFlags,
6436                                const AAMDNodes &AAInfo) {
6437   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
6438   if (Alignment == 0)  // Ensure that codegen never sees alignment 0
6439     Alignment = getEVTAlignment(Val.getValueType());
6440 
6441   MMOFlags |= MachineMemOperand::MOStore;
6442   assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
6443 
6444   if (PtrInfo.V.isNull())
6445     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
6446 
6447   MachineFunction &MF = getMachineFunction();
6448   MachineMemOperand *MMO = MF.getMachineMemOperand(
6449       PtrInfo, MMOFlags, Val.getValueType().getStoreSize(), Alignment, AAInfo);
6450   return getStore(Chain, dl, Val, Ptr, MMO);
6451 }
6452 
6453 SDValue SelectionDAG::getStore(SDValue Chain, const SDLoc &dl, SDValue Val,
6454                                SDValue Ptr, MachineMemOperand *MMO) {
6455   assert(Chain.getValueType() == MVT::Other &&
6456         "Invalid chain type");
6457   EVT VT = Val.getValueType();
6458   SDVTList VTs = getVTList(MVT::Other);
6459   SDValue Undef = getUNDEF(Ptr.getValueType());
6460   SDValue Ops[] = { Chain, Val, Ptr, Undef };
6461   FoldingSetNodeID ID;
6462   AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
6463   ID.AddInteger(VT.getRawBits());
6464   ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>(
6465       dl.getIROrder(), VTs, ISD::UNINDEXED, false, VT, MMO));
6466   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
6467   void *IP = nullptr;
6468   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
6469     cast<StoreSDNode>(E)->refineAlignment(MMO);
6470     return SDValue(E, 0);
6471   }
6472   auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
6473                                    ISD::UNINDEXED, false, VT, MMO);
6474   createOperands(N, Ops);
6475 
6476   CSEMap.InsertNode(N, IP);
6477   InsertNode(N);
6478   SDValue V(N, 0);
6479   NewSDValueDbgMsg(V, "Creating new node: ", this);
6480   return V;
6481 }
6482 
6483 SDValue SelectionDAG::getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val,
6484                                     SDValue Ptr, MachinePointerInfo PtrInfo,
6485                                     EVT SVT, unsigned Alignment,
6486                                     MachineMemOperand::Flags MMOFlags,
6487                                     const AAMDNodes &AAInfo) {
6488   assert(Chain.getValueType() == MVT::Other &&
6489         "Invalid chain type");
6490   if (Alignment == 0)  // Ensure that codegen never sees alignment 0
6491     Alignment = getEVTAlignment(SVT);
6492 
6493   MMOFlags |= MachineMemOperand::MOStore;
6494   assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
6495 
6496   if (PtrInfo.V.isNull())
6497     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
6498 
6499   MachineFunction &MF = getMachineFunction();
6500   MachineMemOperand *MMO = MF.getMachineMemOperand(
6501       PtrInfo, MMOFlags, SVT.getStoreSize(), Alignment, AAInfo);
6502   return getTruncStore(Chain, dl, Val, Ptr, SVT, MMO);
6503 }
6504 
6505 SDValue SelectionDAG::getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val,
6506                                     SDValue Ptr, EVT SVT,
6507                                     MachineMemOperand *MMO) {
6508   EVT VT = Val.getValueType();
6509 
6510   assert(Chain.getValueType() == MVT::Other &&
6511         "Invalid chain type");
6512   if (VT == SVT)
6513     return getStore(Chain, dl, Val, Ptr, MMO);
6514 
6515   assert(SVT.getScalarType().bitsLT(VT.getScalarType()) &&
6516          "Should only be a truncating store, not extending!");
6517   assert(VT.isInteger() == SVT.isInteger() &&
6518          "Can't do FP-INT conversion!");
6519   assert(VT.isVector() == SVT.isVector() &&
6520          "Cannot use trunc store to convert to or from a vector!");
6521   assert((!VT.isVector() ||
6522           VT.getVectorNumElements() == SVT.getVectorNumElements()) &&
6523          "Cannot use trunc store to change the number of vector elements!");
6524 
6525   SDVTList VTs = getVTList(MVT::Other);
6526   SDValue Undef = getUNDEF(Ptr.getValueType());
6527   SDValue Ops[] = { Chain, Val, Ptr, Undef };
6528   FoldingSetNodeID ID;
6529   AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
6530   ID.AddInteger(SVT.getRawBits());
6531   ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>(
6532       dl.getIROrder(), VTs, ISD::UNINDEXED, true, SVT, MMO));
6533   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
6534   void *IP = nullptr;
6535   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
6536     cast<StoreSDNode>(E)->refineAlignment(MMO);
6537     return SDValue(E, 0);
6538   }
6539   auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
6540                                    ISD::UNINDEXED, true, SVT, MMO);
6541   createOperands(N, Ops);
6542 
6543   CSEMap.InsertNode(N, IP);
6544   InsertNode(N);
6545   SDValue V(N, 0);
6546   NewSDValueDbgMsg(V, "Creating new node: ", this);
6547   return V;
6548 }
6549 
6550 SDValue SelectionDAG::getIndexedStore(SDValue OrigStore, const SDLoc &dl,
6551                                       SDValue Base, SDValue Offset,
6552                                       ISD::MemIndexedMode AM) {
6553   StoreSDNode *ST = cast<StoreSDNode>(OrigStore);
6554   assert(ST->getOffset().isUndef() && "Store is already a indexed store!");
6555   SDVTList VTs = getVTList(Base.getValueType(), MVT::Other);
6556   SDValue Ops[] = { ST->getChain(), ST->getValue(), Base, Offset };
6557   FoldingSetNodeID ID;
6558   AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
6559   ID.AddInteger(ST->getMemoryVT().getRawBits());
6560   ID.AddInteger(ST->getRawSubclassData());
6561   ID.AddInteger(ST->getPointerInfo().getAddrSpace());
6562   void *IP = nullptr;
6563   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
6564     return SDValue(E, 0);
6565 
6566   auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
6567                                    ST->isTruncatingStore(), ST->getMemoryVT(),
6568                                    ST->getMemOperand());
6569   createOperands(N, Ops);
6570 
6571   CSEMap.InsertNode(N, IP);
6572   InsertNode(N);
6573   SDValue V(N, 0);
6574   NewSDValueDbgMsg(V, "Creating new node: ", this);
6575   return V;
6576 }
6577 
6578 SDValue SelectionDAG::getMaskedLoad(EVT VT, const SDLoc &dl, SDValue Chain,
6579                                     SDValue Ptr, SDValue Mask, SDValue Src0,
6580                                     EVT MemVT, MachineMemOperand *MMO,
6581                                     ISD::LoadExtType ExtTy, bool isExpanding) {
6582   SDVTList VTs = getVTList(VT, MVT::Other);
6583   SDValue Ops[] = { Chain, Ptr, Mask, Src0 };
6584   FoldingSetNodeID ID;
6585   AddNodeIDNode(ID, ISD::MLOAD, VTs, Ops);
6586   ID.AddInteger(VT.getRawBits());
6587   ID.AddInteger(getSyntheticNodeSubclassData<MaskedLoadSDNode>(
6588       dl.getIROrder(), VTs, ExtTy, isExpanding, MemVT, MMO));
6589   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
6590   void *IP = nullptr;
6591   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
6592     cast<MaskedLoadSDNode>(E)->refineAlignment(MMO);
6593     return SDValue(E, 0);
6594   }
6595   auto *N = newSDNode<MaskedLoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
6596                                         ExtTy, isExpanding, MemVT, MMO);
6597   createOperands(N, Ops);
6598 
6599   CSEMap.InsertNode(N, IP);
6600   InsertNode(N);
6601   SDValue V(N, 0);
6602   NewSDValueDbgMsg(V, "Creating new node: ", this);
6603   return V;
6604 }
6605 
6606 SDValue SelectionDAG::getMaskedStore(SDValue Chain, const SDLoc &dl,
6607                                      SDValue Val, SDValue Ptr, SDValue Mask,
6608                                      EVT MemVT, MachineMemOperand *MMO,
6609                                      bool IsTruncating, bool IsCompressing) {
6610   assert(Chain.getValueType() == MVT::Other &&
6611         "Invalid chain type");
6612   EVT VT = Val.getValueType();
6613   SDVTList VTs = getVTList(MVT::Other);
6614   SDValue Ops[] = { Chain, Ptr, Mask, Val };
6615   FoldingSetNodeID ID;
6616   AddNodeIDNode(ID, ISD::MSTORE, VTs, Ops);
6617   ID.AddInteger(VT.getRawBits());
6618   ID.AddInteger(getSyntheticNodeSubclassData<MaskedStoreSDNode>(
6619       dl.getIROrder(), VTs, IsTruncating, IsCompressing, MemVT, MMO));
6620   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
6621   void *IP = nullptr;
6622   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
6623     cast<MaskedStoreSDNode>(E)->refineAlignment(MMO);
6624     return SDValue(E, 0);
6625   }
6626   auto *N = newSDNode<MaskedStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
6627                                          IsTruncating, IsCompressing, MemVT, MMO);
6628   createOperands(N, Ops);
6629 
6630   CSEMap.InsertNode(N, IP);
6631   InsertNode(N);
6632   SDValue V(N, 0);
6633   NewSDValueDbgMsg(V, "Creating new node: ", this);
6634   return V;
6635 }
6636 
6637 SDValue SelectionDAG::getMaskedGather(SDVTList VTs, EVT VT, const SDLoc &dl,
6638                                       ArrayRef<SDValue> Ops,
6639                                       MachineMemOperand *MMO) {
6640   assert(Ops.size() == 6 && "Incompatible number of operands");
6641 
6642   FoldingSetNodeID ID;
6643   AddNodeIDNode(ID, ISD::MGATHER, VTs, Ops);
6644   ID.AddInteger(VT.getRawBits());
6645   ID.AddInteger(getSyntheticNodeSubclassData<MaskedGatherSDNode>(
6646       dl.getIROrder(), VTs, VT, MMO));
6647   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
6648   void *IP = nullptr;
6649   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
6650     cast<MaskedGatherSDNode>(E)->refineAlignment(MMO);
6651     return SDValue(E, 0);
6652   }
6653 
6654   auto *N = newSDNode<MaskedGatherSDNode>(dl.getIROrder(), dl.getDebugLoc(),
6655                                           VTs, VT, MMO);
6656   createOperands(N, Ops);
6657 
6658   assert(N->getPassThru().getValueType() == N->getValueType(0) &&
6659          "Incompatible type of the PassThru value in MaskedGatherSDNode");
6660   assert(N->getMask().getValueType().getVectorNumElements() ==
6661              N->getValueType(0).getVectorNumElements() &&
6662          "Vector width mismatch between mask and data");
6663   assert(N->getIndex().getValueType().getVectorNumElements() ==
6664              N->getValueType(0).getVectorNumElements() &&
6665          "Vector width mismatch between index and data");
6666   assert(isa<ConstantSDNode>(N->getScale()) &&
6667          cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() &&
6668          "Scale should be a constant power of 2");
6669 
6670   CSEMap.InsertNode(N, IP);
6671   InsertNode(N);
6672   SDValue V(N, 0);
6673   NewSDValueDbgMsg(V, "Creating new node: ", this);
6674   return V;
6675 }
6676 
6677 SDValue SelectionDAG::getMaskedScatter(SDVTList VTs, EVT VT, const SDLoc &dl,
6678                                        ArrayRef<SDValue> Ops,
6679                                        MachineMemOperand *MMO) {
6680   assert(Ops.size() == 6 && "Incompatible number of operands");
6681 
6682   FoldingSetNodeID ID;
6683   AddNodeIDNode(ID, ISD::MSCATTER, VTs, Ops);
6684   ID.AddInteger(VT.getRawBits());
6685   ID.AddInteger(getSyntheticNodeSubclassData<MaskedScatterSDNode>(
6686       dl.getIROrder(), VTs, VT, MMO));
6687   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
6688   void *IP = nullptr;
6689   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
6690     cast<MaskedScatterSDNode>(E)->refineAlignment(MMO);
6691     return SDValue(E, 0);
6692   }
6693   auto *N = newSDNode<MaskedScatterSDNode>(dl.getIROrder(), dl.getDebugLoc(),
6694                                            VTs, VT, MMO);
6695   createOperands(N, Ops);
6696 
6697   assert(N->getMask().getValueType().getVectorNumElements() ==
6698              N->getValue().getValueType().getVectorNumElements() &&
6699          "Vector width mismatch between mask and data");
6700   assert(N->getIndex().getValueType().getVectorNumElements() ==
6701              N->getValue().getValueType().getVectorNumElements() &&
6702          "Vector width mismatch between index and data");
6703   assert(isa<ConstantSDNode>(N->getScale()) &&
6704          cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() &&
6705          "Scale should be a constant power of 2");
6706 
6707   CSEMap.InsertNode(N, IP);
6708   InsertNode(N);
6709   SDValue V(N, 0);
6710   NewSDValueDbgMsg(V, "Creating new node: ", this);
6711   return V;
6712 }
6713 
6714 SDValue SelectionDAG::getVAArg(EVT VT, const SDLoc &dl, SDValue Chain,
6715                                SDValue Ptr, SDValue SV, unsigned Align) {
6716   SDValue Ops[] = { Chain, Ptr, SV, getTargetConstant(Align, dl, MVT::i32) };
6717   return getNode(ISD::VAARG, dl, getVTList(VT, MVT::Other), Ops);
6718 }
6719 
6720 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
6721                               ArrayRef<SDUse> Ops) {
6722   switch (Ops.size()) {
6723   case 0: return getNode(Opcode, DL, VT);
6724   case 1: return getNode(Opcode, DL, VT, static_cast<const SDValue>(Ops[0]));
6725   case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1]);
6726   case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2]);
6727   default: break;
6728   }
6729 
6730   // Copy from an SDUse array into an SDValue array for use with
6731   // the regular getNode logic.
6732   SmallVector<SDValue, 8> NewOps(Ops.begin(), Ops.end());
6733   return getNode(Opcode, DL, VT, NewOps);
6734 }
6735 
6736 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
6737                               ArrayRef<SDValue> Ops, const SDNodeFlags Flags) {
6738   unsigned NumOps = Ops.size();
6739   switch (NumOps) {
6740   case 0: return getNode(Opcode, DL, VT);
6741   case 1: return getNode(Opcode, DL, VT, Ops[0], Flags);
6742   case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Flags);
6743   case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2], Flags);
6744   default: break;
6745   }
6746 
6747   switch (Opcode) {
6748   default: break;
6749   case ISD::CONCAT_VECTORS:
6750     // Attempt to fold CONCAT_VECTORS into BUILD_VECTOR or UNDEF.
6751     if (SDValue V = FoldCONCAT_VECTORS(DL, VT, Ops, *this))
6752       return V;
6753     break;
6754   case ISD::SELECT_CC:
6755     assert(NumOps == 5 && "SELECT_CC takes 5 operands!");
6756     assert(Ops[0].getValueType() == Ops[1].getValueType() &&
6757            "LHS and RHS of condition must have same type!");
6758     assert(Ops[2].getValueType() == Ops[3].getValueType() &&
6759            "True and False arms of SelectCC must have same type!");
6760     assert(Ops[2].getValueType() == VT &&
6761            "select_cc node must be of same type as true and false value!");
6762     break;
6763   case ISD::BR_CC:
6764     assert(NumOps == 5 && "BR_CC takes 5 operands!");
6765     assert(Ops[2].getValueType() == Ops[3].getValueType() &&
6766            "LHS/RHS of comparison should match types!");
6767     break;
6768   }
6769 
6770   // Memoize nodes.
6771   SDNode *N;
6772   SDVTList VTs = getVTList(VT);
6773 
6774   if (VT != MVT::Glue) {
6775     FoldingSetNodeID ID;
6776     AddNodeIDNode(ID, Opcode, VTs, Ops);
6777     void *IP = nullptr;
6778 
6779     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
6780       return SDValue(E, 0);
6781 
6782     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
6783     createOperands(N, Ops);
6784 
6785     CSEMap.InsertNode(N, IP);
6786   } else {
6787     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
6788     createOperands(N, Ops);
6789   }
6790 
6791   InsertNode(N);
6792   SDValue V(N, 0);
6793   NewSDValueDbgMsg(V, "Creating new node: ", this);
6794   return V;
6795 }
6796 
6797 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL,
6798                               ArrayRef<EVT> ResultTys, ArrayRef<SDValue> Ops) {
6799   return getNode(Opcode, DL, getVTList(ResultTys), Ops);
6800 }
6801 
6802 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
6803                               ArrayRef<SDValue> Ops) {
6804   if (VTList.NumVTs == 1)
6805     return getNode(Opcode, DL, VTList.VTs[0], Ops);
6806 
6807 #if 0
6808   switch (Opcode) {
6809   // FIXME: figure out how to safely handle things like
6810   // int foo(int x) { return 1 << (x & 255); }
6811   // int bar() { return foo(256); }
6812   case ISD::SRA_PARTS:
6813   case ISD::SRL_PARTS:
6814   case ISD::SHL_PARTS:
6815     if (N3.getOpcode() == ISD::SIGN_EXTEND_INREG &&
6816         cast<VTSDNode>(N3.getOperand(1))->getVT() != MVT::i1)
6817       return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0));
6818     else if (N3.getOpcode() == ISD::AND)
6819       if (ConstantSDNode *AndRHS = dyn_cast<ConstantSDNode>(N3.getOperand(1))) {
6820         // If the and is only masking out bits that cannot effect the shift,
6821         // eliminate the and.
6822         unsigned NumBits = VT.getScalarSizeInBits()*2;
6823         if ((AndRHS->getValue() & (NumBits-1)) == NumBits-1)
6824           return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0));
6825       }
6826     break;
6827   }
6828 #endif
6829 
6830   // Memoize the node unless it returns a flag.
6831   SDNode *N;
6832   if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) {
6833     FoldingSetNodeID ID;
6834     AddNodeIDNode(ID, Opcode, VTList, Ops);
6835     void *IP = nullptr;
6836     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
6837       return SDValue(E, 0);
6838 
6839     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList);
6840     createOperands(N, Ops);
6841     CSEMap.InsertNode(N, IP);
6842   } else {
6843     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList);
6844     createOperands(N, Ops);
6845   }
6846   InsertNode(N);
6847   SDValue V(N, 0);
6848   NewSDValueDbgMsg(V, "Creating new node: ", this);
6849   return V;
6850 }
6851 
6852 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL,
6853                               SDVTList VTList) {
6854   return getNode(Opcode, DL, VTList, None);
6855 }
6856 
6857 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
6858                               SDValue N1) {
6859   SDValue Ops[] = { N1 };
6860   return getNode(Opcode, DL, VTList, Ops);
6861 }
6862 
6863 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
6864                               SDValue N1, SDValue N2) {
6865   SDValue Ops[] = { N1, N2 };
6866   return getNode(Opcode, DL, VTList, Ops);
6867 }
6868 
6869 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
6870                               SDValue N1, SDValue N2, SDValue N3) {
6871   SDValue Ops[] = { N1, N2, N3 };
6872   return getNode(Opcode, DL, VTList, Ops);
6873 }
6874 
6875 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
6876                               SDValue N1, SDValue N2, SDValue N3, SDValue N4) {
6877   SDValue Ops[] = { N1, N2, N3, N4 };
6878   return getNode(Opcode, DL, VTList, Ops);
6879 }
6880 
6881 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
6882                               SDValue N1, SDValue N2, SDValue N3, SDValue N4,
6883                               SDValue N5) {
6884   SDValue Ops[] = { N1, N2, N3, N4, N5 };
6885   return getNode(Opcode, DL, VTList, Ops);
6886 }
6887 
6888 SDVTList SelectionDAG::getVTList(EVT VT) {
6889   return makeVTList(SDNode::getValueTypeList(VT), 1);
6890 }
6891 
6892 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2) {
6893   FoldingSetNodeID ID;
6894   ID.AddInteger(2U);
6895   ID.AddInteger(VT1.getRawBits());
6896   ID.AddInteger(VT2.getRawBits());
6897 
6898   void *IP = nullptr;
6899   SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
6900   if (!Result) {
6901     EVT *Array = Allocator.Allocate<EVT>(2);
6902     Array[0] = VT1;
6903     Array[1] = VT2;
6904     Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 2);
6905     VTListMap.InsertNode(Result, IP);
6906   }
6907   return Result->getSDVTList();
6908 }
6909 
6910 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3) {
6911   FoldingSetNodeID ID;
6912   ID.AddInteger(3U);
6913   ID.AddInteger(VT1.getRawBits());
6914   ID.AddInteger(VT2.getRawBits());
6915   ID.AddInteger(VT3.getRawBits());
6916 
6917   void *IP = nullptr;
6918   SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
6919   if (!Result) {
6920     EVT *Array = Allocator.Allocate<EVT>(3);
6921     Array[0] = VT1;
6922     Array[1] = VT2;
6923     Array[2] = VT3;
6924     Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 3);
6925     VTListMap.InsertNode(Result, IP);
6926   }
6927   return Result->getSDVTList();
6928 }
6929 
6930 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3, EVT VT4) {
6931   FoldingSetNodeID ID;
6932   ID.AddInteger(4U);
6933   ID.AddInteger(VT1.getRawBits());
6934   ID.AddInteger(VT2.getRawBits());
6935   ID.AddInteger(VT3.getRawBits());
6936   ID.AddInteger(VT4.getRawBits());
6937 
6938   void *IP = nullptr;
6939   SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
6940   if (!Result) {
6941     EVT *Array = Allocator.Allocate<EVT>(4);
6942     Array[0] = VT1;
6943     Array[1] = VT2;
6944     Array[2] = VT3;
6945     Array[3] = VT4;
6946     Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 4);
6947     VTListMap.InsertNode(Result, IP);
6948   }
6949   return Result->getSDVTList();
6950 }
6951 
6952 SDVTList SelectionDAG::getVTList(ArrayRef<EVT> VTs) {
6953   unsigned NumVTs = VTs.size();
6954   FoldingSetNodeID ID;
6955   ID.AddInteger(NumVTs);
6956   for (unsigned index = 0; index < NumVTs; index++) {
6957     ID.AddInteger(VTs[index].getRawBits());
6958   }
6959 
6960   void *IP = nullptr;
6961   SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
6962   if (!Result) {
6963     EVT *Array = Allocator.Allocate<EVT>(NumVTs);
6964     std::copy(VTs.begin(), VTs.end(), Array);
6965     Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, NumVTs);
6966     VTListMap.InsertNode(Result, IP);
6967   }
6968   return Result->getSDVTList();
6969 }
6970 
6971 
6972 /// UpdateNodeOperands - *Mutate* the specified node in-place to have the
6973 /// specified operands.  If the resultant node already exists in the DAG,
6974 /// this does not modify the specified node, instead it returns the node that
6975 /// already exists.  If the resultant node does not exist in the DAG, the
6976 /// input node is returned.  As a degenerate case, if you specify the same
6977 /// input operands as the node already has, the input node is returned.
6978 SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op) {
6979   assert(N->getNumOperands() == 1 && "Update with wrong number of operands");
6980 
6981   // Check to see if there is no change.
6982   if (Op == N->getOperand(0)) return N;
6983 
6984   // See if the modified node already exists.
6985   void *InsertPos = nullptr;
6986   if (SDNode *Existing = FindModifiedNodeSlot(N, Op, InsertPos))
6987     return Existing;
6988 
6989   // Nope it doesn't.  Remove the node from its current place in the maps.
6990   if (InsertPos)
6991     if (!RemoveNodeFromCSEMaps(N))
6992       InsertPos = nullptr;
6993 
6994   // Now we update the operands.
6995   N->OperandList[0].set(Op);
6996 
6997   updateDivergence(N);
6998   // If this gets put into a CSE map, add it.
6999   if (InsertPos) CSEMap.InsertNode(N, InsertPos);
7000   return N;
7001 }
7002 
7003 SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2) {
7004   assert(N->getNumOperands() == 2 && "Update with wrong number of operands");
7005 
7006   // Check to see if there is no change.
7007   if (Op1 == N->getOperand(0) && Op2 == N->getOperand(1))
7008     return N;   // No operands changed, just return the input node.
7009 
7010   // See if the modified node already exists.
7011   void *InsertPos = nullptr;
7012   if (SDNode *Existing = FindModifiedNodeSlot(N, Op1, Op2, InsertPos))
7013     return Existing;
7014 
7015   // Nope it doesn't.  Remove the node from its current place in the maps.
7016   if (InsertPos)
7017     if (!RemoveNodeFromCSEMaps(N))
7018       InsertPos = nullptr;
7019 
7020   // Now we update the operands.
7021   if (N->OperandList[0] != Op1)
7022     N->OperandList[0].set(Op1);
7023   if (N->OperandList[1] != Op2)
7024     N->OperandList[1].set(Op2);
7025 
7026   updateDivergence(N);
7027   // If this gets put into a CSE map, add it.
7028   if (InsertPos) CSEMap.InsertNode(N, InsertPos);
7029   return N;
7030 }
7031 
7032 SDNode *SelectionDAG::
7033 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2, SDValue Op3) {
7034   SDValue Ops[] = { Op1, Op2, Op3 };
7035   return UpdateNodeOperands(N, Ops);
7036 }
7037 
7038 SDNode *SelectionDAG::
7039 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2,
7040                    SDValue Op3, SDValue Op4) {
7041   SDValue Ops[] = { Op1, Op2, Op3, Op4 };
7042   return UpdateNodeOperands(N, Ops);
7043 }
7044 
7045 SDNode *SelectionDAG::
7046 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2,
7047                    SDValue Op3, SDValue Op4, SDValue Op5) {
7048   SDValue Ops[] = { Op1, Op2, Op3, Op4, Op5 };
7049   return UpdateNodeOperands(N, Ops);
7050 }
7051 
7052 SDNode *SelectionDAG::
7053 UpdateNodeOperands(SDNode *N, ArrayRef<SDValue> Ops) {
7054   unsigned NumOps = Ops.size();
7055   assert(N->getNumOperands() == NumOps &&
7056          "Update with wrong number of operands");
7057 
7058   // If no operands changed just return the input node.
7059   if (std::equal(Ops.begin(), Ops.end(), N->op_begin()))
7060     return N;
7061 
7062   // See if the modified node already exists.
7063   void *InsertPos = nullptr;
7064   if (SDNode *Existing = FindModifiedNodeSlot(N, Ops, InsertPos))
7065     return Existing;
7066 
7067   // Nope it doesn't.  Remove the node from its current place in the maps.
7068   if (InsertPos)
7069     if (!RemoveNodeFromCSEMaps(N))
7070       InsertPos = nullptr;
7071 
7072   // Now we update the operands.
7073   for (unsigned i = 0; i != NumOps; ++i)
7074     if (N->OperandList[i] != Ops[i])
7075       N->OperandList[i].set(Ops[i]);
7076 
7077   updateDivergence(N);
7078   // If this gets put into a CSE map, add it.
7079   if (InsertPos) CSEMap.InsertNode(N, InsertPos);
7080   return N;
7081 }
7082 
7083 /// DropOperands - Release the operands and set this node to have
7084 /// zero operands.
7085 void SDNode::DropOperands() {
7086   // Unlike the code in MorphNodeTo that does this, we don't need to
7087   // watch for dead nodes here.
7088   for (op_iterator I = op_begin(), E = op_end(); I != E; ) {
7089     SDUse &Use = *I++;
7090     Use.set(SDValue());
7091   }
7092 }
7093 
7094 /// SelectNodeTo - These are wrappers around MorphNodeTo that accept a
7095 /// machine opcode.
7096 ///
7097 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
7098                                    EVT VT) {
7099   SDVTList VTs = getVTList(VT);
7100   return SelectNodeTo(N, MachineOpc, VTs, None);
7101 }
7102 
7103 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
7104                                    EVT VT, SDValue Op1) {
7105   SDVTList VTs = getVTList(VT);
7106   SDValue Ops[] = { Op1 };
7107   return SelectNodeTo(N, MachineOpc, VTs, Ops);
7108 }
7109 
7110 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
7111                                    EVT VT, SDValue Op1,
7112                                    SDValue Op2) {
7113   SDVTList VTs = getVTList(VT);
7114   SDValue Ops[] = { Op1, Op2 };
7115   return SelectNodeTo(N, MachineOpc, VTs, Ops);
7116 }
7117 
7118 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
7119                                    EVT VT, SDValue Op1,
7120                                    SDValue Op2, SDValue Op3) {
7121   SDVTList VTs = getVTList(VT);
7122   SDValue Ops[] = { Op1, Op2, Op3 };
7123   return SelectNodeTo(N, MachineOpc, VTs, Ops);
7124 }
7125 
7126 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
7127                                    EVT VT, ArrayRef<SDValue> Ops) {
7128   SDVTList VTs = getVTList(VT);
7129   return SelectNodeTo(N, MachineOpc, VTs, Ops);
7130 }
7131 
7132 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
7133                                    EVT VT1, EVT VT2, ArrayRef<SDValue> Ops) {
7134   SDVTList VTs = getVTList(VT1, VT2);
7135   return SelectNodeTo(N, MachineOpc, VTs, Ops);
7136 }
7137 
7138 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
7139                                    EVT VT1, EVT VT2) {
7140   SDVTList VTs = getVTList(VT1, VT2);
7141   return SelectNodeTo(N, MachineOpc, VTs, None);
7142 }
7143 
7144 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
7145                                    EVT VT1, EVT VT2, EVT VT3,
7146                                    ArrayRef<SDValue> Ops) {
7147   SDVTList VTs = getVTList(VT1, VT2, VT3);
7148   return SelectNodeTo(N, MachineOpc, VTs, Ops);
7149 }
7150 
7151 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
7152                                    EVT VT1, EVT VT2,
7153                                    SDValue Op1, SDValue Op2) {
7154   SDVTList VTs = getVTList(VT1, VT2);
7155   SDValue Ops[] = { Op1, Op2 };
7156   return SelectNodeTo(N, MachineOpc, VTs, Ops);
7157 }
7158 
7159 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
7160                                    SDVTList VTs,ArrayRef<SDValue> Ops) {
7161   SDNode *New = MorphNodeTo(N, ~MachineOpc, VTs, Ops);
7162   // Reset the NodeID to -1.
7163   New->setNodeId(-1);
7164   if (New != N) {
7165     ReplaceAllUsesWith(N, New);
7166     RemoveDeadNode(N);
7167   }
7168   return New;
7169 }
7170 
7171 /// UpdateSDLocOnMergeSDNode - If the opt level is -O0 then it throws away
7172 /// the line number information on the merged node since it is not possible to
7173 /// preserve the information that operation is associated with multiple lines.
7174 /// This will make the debugger working better at -O0, were there is a higher
7175 /// probability having other instructions associated with that line.
7176 ///
7177 /// For IROrder, we keep the smaller of the two
7178 SDNode *SelectionDAG::UpdateSDLocOnMergeSDNode(SDNode *N, const SDLoc &OLoc) {
7179   DebugLoc NLoc = N->getDebugLoc();
7180   if (NLoc && OptLevel == CodeGenOpt::None && OLoc.getDebugLoc() != NLoc) {
7181     N->setDebugLoc(DebugLoc());
7182   }
7183   unsigned Order = std::min(N->getIROrder(), OLoc.getIROrder());
7184   N->setIROrder(Order);
7185   return N;
7186 }
7187 
7188 /// MorphNodeTo - This *mutates* the specified node to have the specified
7189 /// return type, opcode, and operands.
7190 ///
7191 /// Note that MorphNodeTo returns the resultant node.  If there is already a
7192 /// node of the specified opcode and operands, it returns that node instead of
7193 /// the current one.  Note that the SDLoc need not be the same.
7194 ///
7195 /// Using MorphNodeTo is faster than creating a new node and swapping it in
7196 /// with ReplaceAllUsesWith both because it often avoids allocating a new
7197 /// node, and because it doesn't require CSE recalculation for any of
7198 /// the node's users.
7199 ///
7200 /// However, note that MorphNodeTo recursively deletes dead nodes from the DAG.
7201 /// As a consequence it isn't appropriate to use from within the DAG combiner or
7202 /// the legalizer which maintain worklists that would need to be updated when
7203 /// deleting things.
7204 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
7205                                   SDVTList VTs, ArrayRef<SDValue> Ops) {
7206   // If an identical node already exists, use it.
7207   void *IP = nullptr;
7208   if (VTs.VTs[VTs.NumVTs-1] != MVT::Glue) {
7209     FoldingSetNodeID ID;
7210     AddNodeIDNode(ID, Opc, VTs, Ops);
7211     if (SDNode *ON = FindNodeOrInsertPos(ID, SDLoc(N), IP))
7212       return UpdateSDLocOnMergeSDNode(ON, SDLoc(N));
7213   }
7214 
7215   if (!RemoveNodeFromCSEMaps(N))
7216     IP = nullptr;
7217 
7218   // Start the morphing.
7219   N->NodeType = Opc;
7220   N->ValueList = VTs.VTs;
7221   N->NumValues = VTs.NumVTs;
7222 
7223   // Clear the operands list, updating used nodes to remove this from their
7224   // use list.  Keep track of any operands that become dead as a result.
7225   SmallPtrSet<SDNode*, 16> DeadNodeSet;
7226   for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) {
7227     SDUse &Use = *I++;
7228     SDNode *Used = Use.getNode();
7229     Use.set(SDValue());
7230     if (Used->use_empty())
7231       DeadNodeSet.insert(Used);
7232   }
7233 
7234   // For MachineNode, initialize the memory references information.
7235   if (MachineSDNode *MN = dyn_cast<MachineSDNode>(N))
7236     MN->setMemRefs(nullptr, nullptr);
7237 
7238   // Swap for an appropriately sized array from the recycler.
7239   removeOperands(N);
7240   createOperands(N, Ops);
7241 
7242   // Delete any nodes that are still dead after adding the uses for the
7243   // new operands.
7244   if (!DeadNodeSet.empty()) {
7245     SmallVector<SDNode *, 16> DeadNodes;
7246     for (SDNode *N : DeadNodeSet)
7247       if (N->use_empty())
7248         DeadNodes.push_back(N);
7249     RemoveDeadNodes(DeadNodes);
7250   }
7251 
7252   if (IP)
7253     CSEMap.InsertNode(N, IP);   // Memoize the new node.
7254   return N;
7255 }
7256 
7257 SDNode* SelectionDAG::mutateStrictFPToFP(SDNode *Node) {
7258   unsigned OrigOpc = Node->getOpcode();
7259   unsigned NewOpc;
7260   bool IsUnary = false;
7261   bool IsTernary = false;
7262   switch (OrigOpc) {
7263   default:
7264     llvm_unreachable("mutateStrictFPToFP called with unexpected opcode!");
7265   case ISD::STRICT_FADD: NewOpc = ISD::FADD; break;
7266   case ISD::STRICT_FSUB: NewOpc = ISD::FSUB; break;
7267   case ISD::STRICT_FMUL: NewOpc = ISD::FMUL; break;
7268   case ISD::STRICT_FDIV: NewOpc = ISD::FDIV; break;
7269   case ISD::STRICT_FREM: NewOpc = ISD::FREM; break;
7270   case ISD::STRICT_FMA: NewOpc = ISD::FMA; IsTernary = true; break;
7271   case ISD::STRICT_FSQRT: NewOpc = ISD::FSQRT; IsUnary = true; break;
7272   case ISD::STRICT_FPOW: NewOpc = ISD::FPOW; break;
7273   case ISD::STRICT_FPOWI: NewOpc = ISD::FPOWI; break;
7274   case ISD::STRICT_FSIN: NewOpc = ISD::FSIN; IsUnary = true; break;
7275   case ISD::STRICT_FCOS: NewOpc = ISD::FCOS; IsUnary = true; break;
7276   case ISD::STRICT_FEXP: NewOpc = ISD::FEXP; IsUnary = true; break;
7277   case ISD::STRICT_FEXP2: NewOpc = ISD::FEXP2; IsUnary = true; break;
7278   case ISD::STRICT_FLOG: NewOpc = ISD::FLOG; IsUnary = true; break;
7279   case ISD::STRICT_FLOG10: NewOpc = ISD::FLOG10; IsUnary = true; break;
7280   case ISD::STRICT_FLOG2: NewOpc = ISD::FLOG2; IsUnary = true; break;
7281   case ISD::STRICT_FRINT: NewOpc = ISD::FRINT; IsUnary = true; break;
7282   case ISD::STRICT_FNEARBYINT:
7283     NewOpc = ISD::FNEARBYINT;
7284     IsUnary = true;
7285     break;
7286   }
7287 
7288   // We're taking this node out of the chain, so we need to re-link things.
7289   SDValue InputChain = Node->getOperand(0);
7290   SDValue OutputChain = SDValue(Node, 1);
7291   ReplaceAllUsesOfValueWith(OutputChain, InputChain);
7292 
7293   SDVTList VTs = getVTList(Node->getOperand(1).getValueType());
7294   SDNode *Res = nullptr;
7295   if (IsUnary)
7296     Res = MorphNodeTo(Node, NewOpc, VTs, { Node->getOperand(1) });
7297   else if (IsTernary)
7298     Res = MorphNodeTo(Node, NewOpc, VTs, { Node->getOperand(1),
7299                                            Node->getOperand(2),
7300                                            Node->getOperand(3)});
7301   else
7302     Res = MorphNodeTo(Node, NewOpc, VTs, { Node->getOperand(1),
7303                                            Node->getOperand(2) });
7304 
7305   // MorphNodeTo can operate in two ways: if an existing node with the
7306   // specified operands exists, it can just return it.  Otherwise, it
7307   // updates the node in place to have the requested operands.
7308   if (Res == Node) {
7309     // If we updated the node in place, reset the node ID.  To the isel,
7310     // this should be just like a newly allocated machine node.
7311     Res->setNodeId(-1);
7312   } else {
7313     ReplaceAllUsesWith(Node, Res);
7314     RemoveDeadNode(Node);
7315   }
7316 
7317   return Res;
7318 }
7319 
7320 /// getMachineNode - These are used for target selectors to create a new node
7321 /// with specified return type(s), MachineInstr opcode, and operands.
7322 ///
7323 /// Note that getMachineNode returns the resultant node.  If there is already a
7324 /// node of the specified opcode and operands, it returns that node instead of
7325 /// the current one.
7326 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
7327                                             EVT VT) {
7328   SDVTList VTs = getVTList(VT);
7329   return getMachineNode(Opcode, dl, VTs, None);
7330 }
7331 
7332 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
7333                                             EVT VT, SDValue Op1) {
7334   SDVTList VTs = getVTList(VT);
7335   SDValue Ops[] = { Op1 };
7336   return getMachineNode(Opcode, dl, VTs, Ops);
7337 }
7338 
7339 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
7340                                             EVT VT, SDValue Op1, SDValue Op2) {
7341   SDVTList VTs = getVTList(VT);
7342   SDValue Ops[] = { Op1, Op2 };
7343   return getMachineNode(Opcode, dl, VTs, Ops);
7344 }
7345 
7346 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
7347                                             EVT VT, SDValue Op1, SDValue Op2,
7348                                             SDValue Op3) {
7349   SDVTList VTs = getVTList(VT);
7350   SDValue Ops[] = { Op1, Op2, Op3 };
7351   return getMachineNode(Opcode, dl, VTs, Ops);
7352 }
7353 
7354 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
7355                                             EVT VT, ArrayRef<SDValue> Ops) {
7356   SDVTList VTs = getVTList(VT);
7357   return getMachineNode(Opcode, dl, VTs, Ops);
7358 }
7359 
7360 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
7361                                             EVT VT1, EVT VT2, SDValue Op1,
7362                                             SDValue Op2) {
7363   SDVTList VTs = getVTList(VT1, VT2);
7364   SDValue Ops[] = { Op1, Op2 };
7365   return getMachineNode(Opcode, dl, VTs, Ops);
7366 }
7367 
7368 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
7369                                             EVT VT1, EVT VT2, SDValue Op1,
7370                                             SDValue Op2, SDValue Op3) {
7371   SDVTList VTs = getVTList(VT1, VT2);
7372   SDValue Ops[] = { Op1, Op2, Op3 };
7373   return getMachineNode(Opcode, dl, VTs, Ops);
7374 }
7375 
7376 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
7377                                             EVT VT1, EVT VT2,
7378                                             ArrayRef<SDValue> Ops) {
7379   SDVTList VTs = getVTList(VT1, VT2);
7380   return getMachineNode(Opcode, dl, VTs, Ops);
7381 }
7382 
7383 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
7384                                             EVT VT1, EVT VT2, EVT VT3,
7385                                             SDValue Op1, SDValue Op2) {
7386   SDVTList VTs = getVTList(VT1, VT2, VT3);
7387   SDValue Ops[] = { Op1, Op2 };
7388   return getMachineNode(Opcode, dl, VTs, Ops);
7389 }
7390 
7391 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
7392                                             EVT VT1, EVT VT2, EVT VT3,
7393                                             SDValue Op1, SDValue Op2,
7394                                             SDValue Op3) {
7395   SDVTList VTs = getVTList(VT1, VT2, VT3);
7396   SDValue Ops[] = { Op1, Op2, Op3 };
7397   return getMachineNode(Opcode, dl, VTs, Ops);
7398 }
7399 
7400 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
7401                                             EVT VT1, EVT VT2, EVT VT3,
7402                                             ArrayRef<SDValue> Ops) {
7403   SDVTList VTs = getVTList(VT1, VT2, VT3);
7404   return getMachineNode(Opcode, dl, VTs, Ops);
7405 }
7406 
7407 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
7408                                             ArrayRef<EVT> ResultTys,
7409                                             ArrayRef<SDValue> Ops) {
7410   SDVTList VTs = getVTList(ResultTys);
7411   return getMachineNode(Opcode, dl, VTs, Ops);
7412 }
7413 
7414 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &DL,
7415                                             SDVTList VTs,
7416                                             ArrayRef<SDValue> Ops) {
7417   bool DoCSE = VTs.VTs[VTs.NumVTs-1] != MVT::Glue;
7418   MachineSDNode *N;
7419   void *IP = nullptr;
7420 
7421   if (DoCSE) {
7422     FoldingSetNodeID ID;
7423     AddNodeIDNode(ID, ~Opcode, VTs, Ops);
7424     IP = nullptr;
7425     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
7426       return cast<MachineSDNode>(UpdateSDLocOnMergeSDNode(E, DL));
7427     }
7428   }
7429 
7430   // Allocate a new MachineSDNode.
7431   N = newSDNode<MachineSDNode>(~Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
7432   createOperands(N, Ops);
7433 
7434   if (DoCSE)
7435     CSEMap.InsertNode(N, IP);
7436 
7437   InsertNode(N);
7438   return N;
7439 }
7440 
7441 /// getTargetExtractSubreg - A convenience function for creating
7442 /// TargetOpcode::EXTRACT_SUBREG nodes.
7443 SDValue SelectionDAG::getTargetExtractSubreg(int SRIdx, const SDLoc &DL, EVT VT,
7444                                              SDValue Operand) {
7445   SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32);
7446   SDNode *Subreg = getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL,
7447                                   VT, Operand, SRIdxVal);
7448   return SDValue(Subreg, 0);
7449 }
7450 
7451 /// getTargetInsertSubreg - A convenience function for creating
7452 /// TargetOpcode::INSERT_SUBREG nodes.
7453 SDValue SelectionDAG::getTargetInsertSubreg(int SRIdx, const SDLoc &DL, EVT VT,
7454                                             SDValue Operand, SDValue Subreg) {
7455   SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32);
7456   SDNode *Result = getMachineNode(TargetOpcode::INSERT_SUBREG, DL,
7457                                   VT, Operand, Subreg, SRIdxVal);
7458   return SDValue(Result, 0);
7459 }
7460 
7461 /// getNodeIfExists - Get the specified node if it's already available, or
7462 /// else return NULL.
7463 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList,
7464                                       ArrayRef<SDValue> Ops,
7465                                       const SDNodeFlags Flags) {
7466   if (VTList.VTs[VTList.NumVTs - 1] != MVT::Glue) {
7467     FoldingSetNodeID ID;
7468     AddNodeIDNode(ID, Opcode, VTList, Ops);
7469     void *IP = nullptr;
7470     if (SDNode *E = FindNodeOrInsertPos(ID, SDLoc(), IP)) {
7471       E->intersectFlagsWith(Flags);
7472       return E;
7473     }
7474   }
7475   return nullptr;
7476 }
7477 
7478 /// getDbgValue - Creates a SDDbgValue node.
7479 ///
7480 /// SDNode
7481 SDDbgValue *SelectionDAG::getDbgValue(DIVariable *Var, DIExpression *Expr,
7482                                       SDNode *N, unsigned R, bool IsIndirect,
7483                                       const DebugLoc &DL, unsigned O) {
7484   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
7485          "Expected inlined-at fields to agree");
7486   return new (DbgInfo->getAlloc())
7487       SDDbgValue(Var, Expr, N, R, IsIndirect, DL, O);
7488 }
7489 
7490 /// Constant
7491 SDDbgValue *SelectionDAG::getConstantDbgValue(DIVariable *Var,
7492                                               DIExpression *Expr,
7493                                               const Value *C,
7494                                               const DebugLoc &DL, unsigned O) {
7495   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
7496          "Expected inlined-at fields to agree");
7497   return new (DbgInfo->getAlloc()) SDDbgValue(Var, Expr, C, DL, O);
7498 }
7499 
7500 /// FrameIndex
7501 SDDbgValue *SelectionDAG::getFrameIndexDbgValue(DIVariable *Var,
7502                                                 DIExpression *Expr, unsigned FI,
7503                                                 bool IsIndirect,
7504                                                 const DebugLoc &DL,
7505                                                 unsigned O) {
7506   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
7507          "Expected inlined-at fields to agree");
7508   return new (DbgInfo->getAlloc())
7509       SDDbgValue(Var, Expr, FI, IsIndirect, DL, O, SDDbgValue::FRAMEIX);
7510 }
7511 
7512 /// VReg
7513 SDDbgValue *SelectionDAG::getVRegDbgValue(DIVariable *Var,
7514                                           DIExpression *Expr,
7515                                           unsigned VReg, bool IsIndirect,
7516                                           const DebugLoc &DL, unsigned O) {
7517   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
7518          "Expected inlined-at fields to agree");
7519   return new (DbgInfo->getAlloc())
7520       SDDbgValue(Var, Expr, VReg, IsIndirect, DL, O, SDDbgValue::VREG);
7521 }
7522 
7523 void SelectionDAG::transferDbgValues(SDValue From, SDValue To,
7524                                      unsigned OffsetInBits, unsigned SizeInBits,
7525                                      bool InvalidateDbg) {
7526   SDNode *FromNode = From.getNode();
7527   SDNode *ToNode = To.getNode();
7528   assert(FromNode && ToNode && "Can't modify dbg values");
7529 
7530   // PR35338
7531   // TODO: assert(From != To && "Redundant dbg value transfer");
7532   // TODO: assert(FromNode != ToNode && "Intranode dbg value transfer");
7533   if (From == To || FromNode == ToNode)
7534     return;
7535 
7536   if (!FromNode->getHasDebugValue())
7537     return;
7538 
7539   SmallVector<SDDbgValue *, 2> ClonedDVs;
7540   for (SDDbgValue *Dbg : GetDbgValues(FromNode)) {
7541     if (Dbg->getKind() != SDDbgValue::SDNODE || Dbg->isInvalidated())
7542       continue;
7543 
7544     // TODO: assert(!Dbg->isInvalidated() && "Transfer of invalid dbg value");
7545 
7546     // Just transfer the dbg value attached to From.
7547     if (Dbg->getResNo() != From.getResNo())
7548       continue;
7549 
7550     DIVariable *Var = Dbg->getVariable();
7551     auto *Expr = Dbg->getExpression();
7552     // If a fragment is requested, update the expression.
7553     if (SizeInBits) {
7554       // When splitting a larger (e.g., sign-extended) value whose
7555       // lower bits are described with an SDDbgValue, do not attempt
7556       // to transfer the SDDbgValue to the upper bits.
7557       if (auto FI = Expr->getFragmentInfo())
7558         if (OffsetInBits + SizeInBits > FI->SizeInBits)
7559           continue;
7560       auto Fragment = DIExpression::createFragmentExpression(Expr, OffsetInBits,
7561                                                              SizeInBits);
7562       if (!Fragment)
7563         continue;
7564       Expr = *Fragment;
7565     }
7566     // Clone the SDDbgValue and move it to To.
7567     SDDbgValue *Clone =
7568         getDbgValue(Var, Expr, ToNode, To.getResNo(), Dbg->isIndirect(),
7569                     Dbg->getDebugLoc(), Dbg->getOrder());
7570     ClonedDVs.push_back(Clone);
7571 
7572     if (InvalidateDbg)
7573       Dbg->setIsInvalidated();
7574   }
7575 
7576   for (SDDbgValue *Dbg : ClonedDVs)
7577     AddDbgValue(Dbg, ToNode, false);
7578 }
7579 
7580 void SelectionDAG::salvageDebugInfo(SDNode &N) {
7581   if (!N.getHasDebugValue())
7582     return;
7583 
7584   SmallVector<SDDbgValue *, 2> ClonedDVs;
7585   for (auto DV : GetDbgValues(&N)) {
7586     if (DV->isInvalidated())
7587       continue;
7588     switch (N.getOpcode()) {
7589     default:
7590       break;
7591     case ISD::ADD:
7592       SDValue N0 = N.getOperand(0);
7593       SDValue N1 = N.getOperand(1);
7594       if (!isConstantIntBuildVectorOrConstantInt(N0) &&
7595           isConstantIntBuildVectorOrConstantInt(N1)) {
7596         uint64_t Offset = N.getConstantOperandVal(1);
7597         // Rewrite an ADD constant node into a DIExpression. Since we are
7598         // performing arithmetic to compute the variable's *value* in the
7599         // DIExpression, we need to mark the expression with a
7600         // DW_OP_stack_value.
7601         auto *DIExpr = DV->getExpression();
7602         DIExpr = DIExpression::prepend(DIExpr, DIExpression::NoDeref, Offset,
7603                                        DIExpression::NoDeref,
7604                                        DIExpression::WithStackValue);
7605         SDDbgValue *Clone =
7606             getDbgValue(DV->getVariable(), DIExpr, N0.getNode(), N0.getResNo(),
7607                         DV->isIndirect(), DV->getDebugLoc(), DV->getOrder());
7608         ClonedDVs.push_back(Clone);
7609         DV->setIsInvalidated();
7610         LLVM_DEBUG(dbgs() << "SALVAGE: Rewriting";
7611                    N0.getNode()->dumprFull(this);
7612                    dbgs() << " into " << *DIExpr << '\n');
7613       }
7614     }
7615   }
7616 
7617   for (SDDbgValue *Dbg : ClonedDVs)
7618     AddDbgValue(Dbg, Dbg->getSDNode(), false);
7619 }
7620 
7621 /// Creates a SDDbgLabel node.
7622 SDDbgLabel *SelectionDAG::getDbgLabel(DILabel *Label,
7623                                       const DebugLoc &DL, unsigned O) {
7624   assert(cast<DILabel>(Label)->isValidLocationForIntrinsic(DL) &&
7625          "Expected inlined-at fields to agree");
7626   return new (DbgInfo->getAlloc()) SDDbgLabel(Label, DL, O);
7627 }
7628 
7629 namespace {
7630 
7631 /// RAUWUpdateListener - Helper for ReplaceAllUsesWith - When the node
7632 /// pointed to by a use iterator is deleted, increment the use iterator
7633 /// so that it doesn't dangle.
7634 ///
7635 class RAUWUpdateListener : public SelectionDAG::DAGUpdateListener {
7636   SDNode::use_iterator &UI;
7637   SDNode::use_iterator &UE;
7638 
7639   void NodeDeleted(SDNode *N, SDNode *E) override {
7640     // Increment the iterator as needed.
7641     while (UI != UE && N == *UI)
7642       ++UI;
7643   }
7644 
7645 public:
7646   RAUWUpdateListener(SelectionDAG &d,
7647                      SDNode::use_iterator &ui,
7648                      SDNode::use_iterator &ue)
7649     : SelectionDAG::DAGUpdateListener(d), UI(ui), UE(ue) {}
7650 };
7651 
7652 } // end anonymous namespace
7653 
7654 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
7655 /// This can cause recursive merging of nodes in the DAG.
7656 ///
7657 /// This version assumes From has a single result value.
7658 ///
7659 void SelectionDAG::ReplaceAllUsesWith(SDValue FromN, SDValue To) {
7660   SDNode *From = FromN.getNode();
7661   assert(From->getNumValues() == 1 && FromN.getResNo() == 0 &&
7662          "Cannot replace with this method!");
7663   assert(From != To.getNode() && "Cannot replace uses of with self");
7664 
7665   // Preserve Debug Values
7666   transferDbgValues(FromN, To);
7667 
7668   // Iterate over all the existing uses of From. New uses will be added
7669   // to the beginning of the use list, which we avoid visiting.
7670   // This specifically avoids visiting uses of From that arise while the
7671   // replacement is happening, because any such uses would be the result
7672   // of CSE: If an existing node looks like From after one of its operands
7673   // is replaced by To, we don't want to replace of all its users with To
7674   // too. See PR3018 for more info.
7675   SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
7676   RAUWUpdateListener Listener(*this, UI, UE);
7677   while (UI != UE) {
7678     SDNode *User = *UI;
7679 
7680     // This node is about to morph, remove its old self from the CSE maps.
7681     RemoveNodeFromCSEMaps(User);
7682 
7683     // A user can appear in a use list multiple times, and when this
7684     // happens the uses are usually next to each other in the list.
7685     // To help reduce the number of CSE recomputations, process all
7686     // the uses of this user that we can find this way.
7687     do {
7688       SDUse &Use = UI.getUse();
7689       ++UI;
7690       Use.set(To);
7691       if (To->isDivergent() != From->isDivergent())
7692         updateDivergence(User);
7693     } while (UI != UE && *UI == User);
7694     // Now that we have modified User, add it back to the CSE maps.  If it
7695     // already exists there, recursively merge the results together.
7696     AddModifiedNodeToCSEMaps(User);
7697   }
7698 
7699   // If we just RAUW'd the root, take note.
7700   if (FromN == getRoot())
7701     setRoot(To);
7702 }
7703 
7704 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
7705 /// This can cause recursive merging of nodes in the DAG.
7706 ///
7707 /// This version assumes that for each value of From, there is a
7708 /// corresponding value in To in the same position with the same type.
7709 ///
7710 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, SDNode *To) {
7711 #ifndef NDEBUG
7712   for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
7713     assert((!From->hasAnyUseOfValue(i) ||
7714             From->getValueType(i) == To->getValueType(i)) &&
7715            "Cannot use this version of ReplaceAllUsesWith!");
7716 #endif
7717 
7718   // Handle the trivial case.
7719   if (From == To)
7720     return;
7721 
7722   // Preserve Debug Info. Only do this if there's a use.
7723   for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
7724     if (From->hasAnyUseOfValue(i)) {
7725       assert((i < To->getNumValues()) && "Invalid To location");
7726       transferDbgValues(SDValue(From, i), SDValue(To, i));
7727     }
7728 
7729   // Iterate over just the existing users of From. See the comments in
7730   // the ReplaceAllUsesWith above.
7731   SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
7732   RAUWUpdateListener Listener(*this, UI, UE);
7733   while (UI != UE) {
7734     SDNode *User = *UI;
7735 
7736     // This node is about to morph, remove its old self from the CSE maps.
7737     RemoveNodeFromCSEMaps(User);
7738 
7739     // A user can appear in a use list multiple times, and when this
7740     // happens the uses are usually next to each other in the list.
7741     // To help reduce the number of CSE recomputations, process all
7742     // the uses of this user that we can find this way.
7743     do {
7744       SDUse &Use = UI.getUse();
7745       ++UI;
7746       Use.setNode(To);
7747       if (To->isDivergent() != From->isDivergent())
7748         updateDivergence(User);
7749     } while (UI != UE && *UI == User);
7750 
7751     // Now that we have modified User, add it back to the CSE maps.  If it
7752     // already exists there, recursively merge the results together.
7753     AddModifiedNodeToCSEMaps(User);
7754   }
7755 
7756   // If we just RAUW'd the root, take note.
7757   if (From == getRoot().getNode())
7758     setRoot(SDValue(To, getRoot().getResNo()));
7759 }
7760 
7761 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
7762 /// This can cause recursive merging of nodes in the DAG.
7763 ///
7764 /// This version can replace From with any result values.  To must match the
7765 /// number and types of values returned by From.
7766 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, const SDValue *To) {
7767   if (From->getNumValues() == 1)  // Handle the simple case efficiently.
7768     return ReplaceAllUsesWith(SDValue(From, 0), To[0]);
7769 
7770   // Preserve Debug Info.
7771   for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
7772     transferDbgValues(SDValue(From, i), *To);
7773 
7774   // Iterate over just the existing users of From. See the comments in
7775   // the ReplaceAllUsesWith above.
7776   SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
7777   RAUWUpdateListener Listener(*this, UI, UE);
7778   while (UI != UE) {
7779     SDNode *User = *UI;
7780 
7781     // This node is about to morph, remove its old self from the CSE maps.
7782     RemoveNodeFromCSEMaps(User);
7783 
7784     // A user can appear in a use list multiple times, and when this
7785     // happens the uses are usually next to each other in the list.
7786     // To help reduce the number of CSE recomputations, process all
7787     // the uses of this user that we can find this way.
7788     do {
7789       SDUse &Use = UI.getUse();
7790       const SDValue &ToOp = To[Use.getResNo()];
7791       ++UI;
7792       Use.set(ToOp);
7793       if (To->getNode()->isDivergent() != From->isDivergent())
7794         updateDivergence(User);
7795     } while (UI != UE && *UI == User);
7796     // Now that we have modified User, add it back to the CSE maps.  If it
7797     // already exists there, recursively merge the results together.
7798     AddModifiedNodeToCSEMaps(User);
7799   }
7800 
7801   // If we just RAUW'd the root, take note.
7802   if (From == getRoot().getNode())
7803     setRoot(SDValue(To[getRoot().getResNo()]));
7804 }
7805 
7806 /// ReplaceAllUsesOfValueWith - Replace any uses of From with To, leaving
7807 /// uses of other values produced by From.getNode() alone.  The Deleted
7808 /// vector is handled the same way as for ReplaceAllUsesWith.
7809 void SelectionDAG::ReplaceAllUsesOfValueWith(SDValue From, SDValue To){
7810   // Handle the really simple, really trivial case efficiently.
7811   if (From == To) return;
7812 
7813   // Handle the simple, trivial, case efficiently.
7814   if (From.getNode()->getNumValues() == 1) {
7815     ReplaceAllUsesWith(From, To);
7816     return;
7817   }
7818 
7819   // Preserve Debug Info.
7820   transferDbgValues(From, To);
7821 
7822   // Iterate over just the existing users of From. See the comments in
7823   // the ReplaceAllUsesWith above.
7824   SDNode::use_iterator UI = From.getNode()->use_begin(),
7825                        UE = From.getNode()->use_end();
7826   RAUWUpdateListener Listener(*this, UI, UE);
7827   while (UI != UE) {
7828     SDNode *User = *UI;
7829     bool UserRemovedFromCSEMaps = false;
7830 
7831     // A user can appear in a use list multiple times, and when this
7832     // happens the uses are usually next to each other in the list.
7833     // To help reduce the number of CSE recomputations, process all
7834     // the uses of this user that we can find this way.
7835     do {
7836       SDUse &Use = UI.getUse();
7837 
7838       // Skip uses of different values from the same node.
7839       if (Use.getResNo() != From.getResNo()) {
7840         ++UI;
7841         continue;
7842       }
7843 
7844       // If this node hasn't been modified yet, it's still in the CSE maps,
7845       // so remove its old self from the CSE maps.
7846       if (!UserRemovedFromCSEMaps) {
7847         RemoveNodeFromCSEMaps(User);
7848         UserRemovedFromCSEMaps = true;
7849       }
7850 
7851       ++UI;
7852       Use.set(To);
7853       if (To->isDivergent() != From->isDivergent())
7854         updateDivergence(User);
7855     } while (UI != UE && *UI == User);
7856     // We are iterating over all uses of the From node, so if a use
7857     // doesn't use the specific value, no changes are made.
7858     if (!UserRemovedFromCSEMaps)
7859       continue;
7860 
7861     // Now that we have modified User, add it back to the CSE maps.  If it
7862     // already exists there, recursively merge the results together.
7863     AddModifiedNodeToCSEMaps(User);
7864   }
7865 
7866   // If we just RAUW'd the root, take note.
7867   if (From == getRoot())
7868     setRoot(To);
7869 }
7870 
7871 namespace {
7872 
7873   /// UseMemo - This class is used by SelectionDAG::ReplaceAllUsesOfValuesWith
7874   /// to record information about a use.
7875   struct UseMemo {
7876     SDNode *User;
7877     unsigned Index;
7878     SDUse *Use;
7879   };
7880 
7881   /// operator< - Sort Memos by User.
7882   bool operator<(const UseMemo &L, const UseMemo &R) {
7883     return (intptr_t)L.User < (intptr_t)R.User;
7884   }
7885 
7886 } // end anonymous namespace
7887 
7888 void SelectionDAG::updateDivergence(SDNode * N)
7889 {
7890   if (TLI->isSDNodeAlwaysUniform(N))
7891     return;
7892   bool IsDivergent = TLI->isSDNodeSourceOfDivergence(N, FLI, DA);
7893   for (auto &Op : N->ops()) {
7894     if (Op.Val.getValueType() != MVT::Other)
7895       IsDivergent |= Op.getNode()->isDivergent();
7896   }
7897   if (N->SDNodeBits.IsDivergent != IsDivergent) {
7898     N->SDNodeBits.IsDivergent = IsDivergent;
7899     for (auto U : N->uses()) {
7900       updateDivergence(U);
7901     }
7902   }
7903 }
7904 
7905 
7906 void SelectionDAG::CreateTopologicalOrder(std::vector<SDNode*>& Order) {
7907   DenseMap<SDNode *, unsigned> Degree;
7908   Order.reserve(AllNodes.size());
7909   for (auto & N : allnodes()) {
7910     unsigned NOps = N.getNumOperands();
7911     Degree[&N] = NOps;
7912     if (0 == NOps)
7913       Order.push_back(&N);
7914   }
7915   for (std::vector<SDNode *>::iterator I = Order.begin();
7916   I!=Order.end();++I) {
7917     SDNode * N = *I;
7918     for (auto U : N->uses()) {
7919       unsigned &UnsortedOps = Degree[U];
7920       if (0 == --UnsortedOps)
7921         Order.push_back(U);
7922     }
7923   }
7924 }
7925 
7926 void SelectionDAG::VerifyDAGDiverence()
7927 {
7928   std::vector<SDNode*> TopoOrder;
7929   CreateTopologicalOrder(TopoOrder);
7930   const TargetLowering &TLI = getTargetLoweringInfo();
7931   DenseMap<const SDNode *, bool> DivergenceMap;
7932   for (auto &N : allnodes()) {
7933     DivergenceMap[&N] = false;
7934   }
7935   for (auto N : TopoOrder) {
7936     bool IsDivergent = DivergenceMap[N];
7937     bool IsSDNodeDivergent = TLI.isSDNodeSourceOfDivergence(N, FLI, DA);
7938     for (auto &Op : N->ops()) {
7939       if (Op.Val.getValueType() != MVT::Other)
7940         IsSDNodeDivergent |= DivergenceMap[Op.getNode()];
7941     }
7942     if (!IsDivergent && IsSDNodeDivergent && !TLI.isSDNodeAlwaysUniform(N)) {
7943       DivergenceMap[N] = true;
7944     }
7945   }
7946   for (auto &N : allnodes()) {
7947     (void)N;
7948     assert(DivergenceMap[&N] == N.isDivergent() &&
7949            "Divergence bit inconsistency detected\n");
7950   }
7951 }
7952 
7953 
7954 /// ReplaceAllUsesOfValuesWith - Replace any uses of From with To, leaving
7955 /// uses of other values produced by From.getNode() alone.  The same value
7956 /// may appear in both the From and To list.  The Deleted vector is
7957 /// handled the same way as for ReplaceAllUsesWith.
7958 void SelectionDAG::ReplaceAllUsesOfValuesWith(const SDValue *From,
7959                                               const SDValue *To,
7960                                               unsigned Num){
7961   // Handle the simple, trivial case efficiently.
7962   if (Num == 1)
7963     return ReplaceAllUsesOfValueWith(*From, *To);
7964 
7965   transferDbgValues(*From, *To);
7966 
7967   // Read up all the uses and make records of them. This helps
7968   // processing new uses that are introduced during the
7969   // replacement process.
7970   SmallVector<UseMemo, 4> Uses;
7971   for (unsigned i = 0; i != Num; ++i) {
7972     unsigned FromResNo = From[i].getResNo();
7973     SDNode *FromNode = From[i].getNode();
7974     for (SDNode::use_iterator UI = FromNode->use_begin(),
7975          E = FromNode->use_end(); UI != E; ++UI) {
7976       SDUse &Use = UI.getUse();
7977       if (Use.getResNo() == FromResNo) {
7978         UseMemo Memo = { *UI, i, &Use };
7979         Uses.push_back(Memo);
7980       }
7981     }
7982   }
7983 
7984   // Sort the uses, so that all the uses from a given User are together.
7985   llvm::sort(Uses.begin(), Uses.end());
7986 
7987   for (unsigned UseIndex = 0, UseIndexEnd = Uses.size();
7988        UseIndex != UseIndexEnd; ) {
7989     // We know that this user uses some value of From.  If it is the right
7990     // value, update it.
7991     SDNode *User = Uses[UseIndex].User;
7992 
7993     // This node is about to morph, remove its old self from the CSE maps.
7994     RemoveNodeFromCSEMaps(User);
7995 
7996     // The Uses array is sorted, so all the uses for a given User
7997     // are next to each other in the list.
7998     // To help reduce the number of CSE recomputations, process all
7999     // the uses of this user that we can find this way.
8000     do {
8001       unsigned i = Uses[UseIndex].Index;
8002       SDUse &Use = *Uses[UseIndex].Use;
8003       ++UseIndex;
8004 
8005       Use.set(To[i]);
8006     } while (UseIndex != UseIndexEnd && Uses[UseIndex].User == User);
8007 
8008     // Now that we have modified User, add it back to the CSE maps.  If it
8009     // already exists there, recursively merge the results together.
8010     AddModifiedNodeToCSEMaps(User);
8011   }
8012 }
8013 
8014 /// AssignTopologicalOrder - Assign a unique node id for each node in the DAG
8015 /// based on their topological order. It returns the maximum id and a vector
8016 /// of the SDNodes* in assigned order by reference.
8017 unsigned SelectionDAG::AssignTopologicalOrder() {
8018   unsigned DAGSize = 0;
8019 
8020   // SortedPos tracks the progress of the algorithm. Nodes before it are
8021   // sorted, nodes after it are unsorted. When the algorithm completes
8022   // it is at the end of the list.
8023   allnodes_iterator SortedPos = allnodes_begin();
8024 
8025   // Visit all the nodes. Move nodes with no operands to the front of
8026   // the list immediately. Annotate nodes that do have operands with their
8027   // operand count. Before we do this, the Node Id fields of the nodes
8028   // may contain arbitrary values. After, the Node Id fields for nodes
8029   // before SortedPos will contain the topological sort index, and the
8030   // Node Id fields for nodes At SortedPos and after will contain the
8031   // count of outstanding operands.
8032   for (allnodes_iterator I = allnodes_begin(),E = allnodes_end(); I != E; ) {
8033     SDNode *N = &*I++;
8034     checkForCycles(N, this);
8035     unsigned Degree = N->getNumOperands();
8036     if (Degree == 0) {
8037       // A node with no uses, add it to the result array immediately.
8038       N->setNodeId(DAGSize++);
8039       allnodes_iterator Q(N);
8040       if (Q != SortedPos)
8041         SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(Q));
8042       assert(SortedPos != AllNodes.end() && "Overran node list");
8043       ++SortedPos;
8044     } else {
8045       // Temporarily use the Node Id as scratch space for the degree count.
8046       N->setNodeId(Degree);
8047     }
8048   }
8049 
8050   // Visit all the nodes. As we iterate, move nodes into sorted order,
8051   // such that by the time the end is reached all nodes will be sorted.
8052   for (SDNode &Node : allnodes()) {
8053     SDNode *N = &Node;
8054     checkForCycles(N, this);
8055     // N is in sorted position, so all its uses have one less operand
8056     // that needs to be sorted.
8057     for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
8058          UI != UE; ++UI) {
8059       SDNode *P = *UI;
8060       unsigned Degree = P->getNodeId();
8061       assert(Degree != 0 && "Invalid node degree");
8062       --Degree;
8063       if (Degree == 0) {
8064         // All of P's operands are sorted, so P may sorted now.
8065         P->setNodeId(DAGSize++);
8066         if (P->getIterator() != SortedPos)
8067           SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(P));
8068         assert(SortedPos != AllNodes.end() && "Overran node list");
8069         ++SortedPos;
8070       } else {
8071         // Update P's outstanding operand count.
8072         P->setNodeId(Degree);
8073       }
8074     }
8075     if (Node.getIterator() == SortedPos) {
8076 #ifndef NDEBUG
8077       allnodes_iterator I(N);
8078       SDNode *S = &*++I;
8079       dbgs() << "Overran sorted position:\n";
8080       S->dumprFull(this); dbgs() << "\n";
8081       dbgs() << "Checking if this is due to cycles\n";
8082       checkForCycles(this, true);
8083 #endif
8084       llvm_unreachable(nullptr);
8085     }
8086   }
8087 
8088   assert(SortedPos == AllNodes.end() &&
8089          "Topological sort incomplete!");
8090   assert(AllNodes.front().getOpcode() == ISD::EntryToken &&
8091          "First node in topological sort is not the entry token!");
8092   assert(AllNodes.front().getNodeId() == 0 &&
8093          "First node in topological sort has non-zero id!");
8094   assert(AllNodes.front().getNumOperands() == 0 &&
8095          "First node in topological sort has operands!");
8096   assert(AllNodes.back().getNodeId() == (int)DAGSize-1 &&
8097          "Last node in topologic sort has unexpected id!");
8098   assert(AllNodes.back().use_empty() &&
8099          "Last node in topologic sort has users!");
8100   assert(DAGSize == allnodes_size() && "Node count mismatch!");
8101   return DAGSize;
8102 }
8103 
8104 /// AddDbgValue - Add a dbg_value SDNode. If SD is non-null that means the
8105 /// value is produced by SD.
8106 void SelectionDAG::AddDbgValue(SDDbgValue *DB, SDNode *SD, bool isParameter) {
8107   if (SD) {
8108     assert(DbgInfo->getSDDbgValues(SD).empty() || SD->getHasDebugValue());
8109     SD->setHasDebugValue(true);
8110   }
8111   DbgInfo->add(DB, SD, isParameter);
8112 }
8113 
8114 void SelectionDAG::AddDbgLabel(SDDbgLabel *DB) {
8115   DbgInfo->add(DB);
8116 }
8117 
8118 SDValue SelectionDAG::makeEquivalentMemoryOrdering(LoadSDNode *OldLoad,
8119                                                    SDValue NewMemOp) {
8120   assert(isa<MemSDNode>(NewMemOp.getNode()) && "Expected a memop node");
8121   // The new memory operation must have the same position as the old load in
8122   // terms of memory dependency. Create a TokenFactor for the old load and new
8123   // memory operation and update uses of the old load's output chain to use that
8124   // TokenFactor.
8125   SDValue OldChain = SDValue(OldLoad, 1);
8126   SDValue NewChain = SDValue(NewMemOp.getNode(), 1);
8127   if (!OldLoad->hasAnyUseOfValue(1))
8128     return NewChain;
8129 
8130   SDValue TokenFactor =
8131       getNode(ISD::TokenFactor, SDLoc(OldLoad), MVT::Other, OldChain, NewChain);
8132   ReplaceAllUsesOfValueWith(OldChain, TokenFactor);
8133   UpdateNodeOperands(TokenFactor.getNode(), OldChain, NewChain);
8134   return TokenFactor;
8135 }
8136 
8137 //===----------------------------------------------------------------------===//
8138 //                              SDNode Class
8139 //===----------------------------------------------------------------------===//
8140 
8141 bool llvm::isNullConstant(SDValue V) {
8142   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
8143   return Const != nullptr && Const->isNullValue();
8144 }
8145 
8146 bool llvm::isNullFPConstant(SDValue V) {
8147   ConstantFPSDNode *Const = dyn_cast<ConstantFPSDNode>(V);
8148   return Const != nullptr && Const->isZero() && !Const->isNegative();
8149 }
8150 
8151 bool llvm::isAllOnesConstant(SDValue V) {
8152   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
8153   return Const != nullptr && Const->isAllOnesValue();
8154 }
8155 
8156 bool llvm::isOneConstant(SDValue V) {
8157   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
8158   return Const != nullptr && Const->isOne();
8159 }
8160 
8161 bool llvm::isBitwiseNot(SDValue V) {
8162   return V.getOpcode() == ISD::XOR && isAllOnesConstant(V.getOperand(1));
8163 }
8164 
8165 ConstantSDNode *llvm::isConstOrConstSplat(SDValue N) {
8166   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
8167     return CN;
8168 
8169   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
8170     BitVector UndefElements;
8171     ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
8172 
8173     // BuildVectors can truncate their operands. Ignore that case here.
8174     // FIXME: We blindly ignore splats which include undef which is overly
8175     // pessimistic.
8176     if (CN && UndefElements.none() &&
8177         CN->getValueType(0) == N.getValueType().getScalarType())
8178       return CN;
8179   }
8180 
8181   return nullptr;
8182 }
8183 
8184 ConstantFPSDNode *llvm::isConstOrConstSplatFP(SDValue N) {
8185   if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
8186     return CN;
8187 
8188   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
8189     BitVector UndefElements;
8190     ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements);
8191 
8192     if (CN && UndefElements.none())
8193       return CN;
8194   }
8195 
8196   return nullptr;
8197 }
8198 
8199 HandleSDNode::~HandleSDNode() {
8200   DropOperands();
8201 }
8202 
8203 GlobalAddressSDNode::GlobalAddressSDNode(unsigned Opc, unsigned Order,
8204                                          const DebugLoc &DL,
8205                                          const GlobalValue *GA, EVT VT,
8206                                          int64_t o, unsigned char TF)
8207     : SDNode(Opc, Order, DL, getSDVTList(VT)), Offset(o), TargetFlags(TF) {
8208   TheGlobal = GA;
8209 }
8210 
8211 AddrSpaceCastSDNode::AddrSpaceCastSDNode(unsigned Order, const DebugLoc &dl,
8212                                          EVT VT, unsigned SrcAS,
8213                                          unsigned DestAS)
8214     : SDNode(ISD::ADDRSPACECAST, Order, dl, getSDVTList(VT)),
8215       SrcAddrSpace(SrcAS), DestAddrSpace(DestAS) {}
8216 
8217 MemSDNode::MemSDNode(unsigned Opc, unsigned Order, const DebugLoc &dl,
8218                      SDVTList VTs, EVT memvt, MachineMemOperand *mmo)
8219     : SDNode(Opc, Order, dl, VTs), MemoryVT(memvt), MMO(mmo) {
8220   MemSDNodeBits.IsVolatile = MMO->isVolatile();
8221   MemSDNodeBits.IsNonTemporal = MMO->isNonTemporal();
8222   MemSDNodeBits.IsDereferenceable = MMO->isDereferenceable();
8223   MemSDNodeBits.IsInvariant = MMO->isInvariant();
8224 
8225   // We check here that the size of the memory operand fits within the size of
8226   // the MMO. This is because the MMO might indicate only a possible address
8227   // range instead of specifying the affected memory addresses precisely.
8228   assert(memvt.getStoreSize() <= MMO->getSize() && "Size mismatch!");
8229 }
8230 
8231 /// Profile - Gather unique data for the node.
8232 ///
8233 void SDNode::Profile(FoldingSetNodeID &ID) const {
8234   AddNodeIDNode(ID, this);
8235 }
8236 
8237 namespace {
8238 
8239   struct EVTArray {
8240     std::vector<EVT> VTs;
8241 
8242     EVTArray() {
8243       VTs.reserve(MVT::LAST_VALUETYPE);
8244       for (unsigned i = 0; i < MVT::LAST_VALUETYPE; ++i)
8245         VTs.push_back(MVT((MVT::SimpleValueType)i));
8246     }
8247   };
8248 
8249 } // end anonymous namespace
8250 
8251 static ManagedStatic<std::set<EVT, EVT::compareRawBits>> EVTs;
8252 static ManagedStatic<EVTArray> SimpleVTArray;
8253 static ManagedStatic<sys::SmartMutex<true>> VTMutex;
8254 
8255 /// getValueTypeList - Return a pointer to the specified value type.
8256 ///
8257 const EVT *SDNode::getValueTypeList(EVT VT) {
8258   if (VT.isExtended()) {
8259     sys::SmartScopedLock<true> Lock(*VTMutex);
8260     return &(*EVTs->insert(VT).first);
8261   } else {
8262     assert(VT.getSimpleVT() < MVT::LAST_VALUETYPE &&
8263            "Value type out of range!");
8264     return &SimpleVTArray->VTs[VT.getSimpleVT().SimpleTy];
8265   }
8266 }
8267 
8268 /// hasNUsesOfValue - Return true if there are exactly NUSES uses of the
8269 /// indicated value.  This method ignores uses of other values defined by this
8270 /// operation.
8271 bool SDNode::hasNUsesOfValue(unsigned NUses, unsigned Value) const {
8272   assert(Value < getNumValues() && "Bad value!");
8273 
8274   // TODO: Only iterate over uses of a given value of the node
8275   for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) {
8276     if (UI.getUse().getResNo() == Value) {
8277       if (NUses == 0)
8278         return false;
8279       --NUses;
8280     }
8281   }
8282 
8283   // Found exactly the right number of uses?
8284   return NUses == 0;
8285 }
8286 
8287 /// hasAnyUseOfValue - Return true if there are any use of the indicated
8288 /// value. This method ignores uses of other values defined by this operation.
8289 bool SDNode::hasAnyUseOfValue(unsigned Value) const {
8290   assert(Value < getNumValues() && "Bad value!");
8291 
8292   for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI)
8293     if (UI.getUse().getResNo() == Value)
8294       return true;
8295 
8296   return false;
8297 }
8298 
8299 /// isOnlyUserOf - Return true if this node is the only use of N.
8300 bool SDNode::isOnlyUserOf(const SDNode *N) const {
8301   bool Seen = false;
8302   for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) {
8303     SDNode *User = *I;
8304     if (User == this)
8305       Seen = true;
8306     else
8307       return false;
8308   }
8309 
8310   return Seen;
8311 }
8312 
8313 /// Return true if the only users of N are contained in Nodes.
8314 bool SDNode::areOnlyUsersOf(ArrayRef<const SDNode *> Nodes, const SDNode *N) {
8315   bool Seen = false;
8316   for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) {
8317     SDNode *User = *I;
8318     if (llvm::any_of(Nodes,
8319                      [&User](const SDNode *Node) { return User == Node; }))
8320       Seen = true;
8321     else
8322       return false;
8323   }
8324 
8325   return Seen;
8326 }
8327 
8328 /// isOperand - Return true if this node is an operand of N.
8329 bool SDValue::isOperandOf(const SDNode *N) const {
8330   for (const SDValue &Op : N->op_values())
8331     if (*this == Op)
8332       return true;
8333   return false;
8334 }
8335 
8336 bool SDNode::isOperandOf(const SDNode *N) const {
8337   for (const SDValue &Op : N->op_values())
8338     if (this == Op.getNode())
8339       return true;
8340   return false;
8341 }
8342 
8343 /// reachesChainWithoutSideEffects - Return true if this operand (which must
8344 /// be a chain) reaches the specified operand without crossing any
8345 /// side-effecting instructions on any chain path.  In practice, this looks
8346 /// through token factors and non-volatile loads.  In order to remain efficient,
8347 /// this only looks a couple of nodes in, it does not do an exhaustive search.
8348 ///
8349 /// Note that we only need to examine chains when we're searching for
8350 /// side-effects; SelectionDAG requires that all side-effects are represented
8351 /// by chains, even if another operand would force a specific ordering. This
8352 /// constraint is necessary to allow transformations like splitting loads.
8353 bool SDValue::reachesChainWithoutSideEffects(SDValue Dest,
8354                                              unsigned Depth) const {
8355   if (*this == Dest) return true;
8356 
8357   // Don't search too deeply, we just want to be able to see through
8358   // TokenFactor's etc.
8359   if (Depth == 0) return false;
8360 
8361   // If this is a token factor, all inputs to the TF happen in parallel.
8362   if (getOpcode() == ISD::TokenFactor) {
8363     // First, try a shallow search.
8364     if (is_contained((*this)->ops(), Dest)) {
8365       // We found the chain we want as an operand of this TokenFactor.
8366       // Essentially, we reach the chain without side-effects if we could
8367       // serialize the TokenFactor into a simple chain of operations with
8368       // Dest as the last operation. This is automatically true if the
8369       // chain has one use: there are no other ordering constraints.
8370       // If the chain has more than one use, we give up: some other
8371       // use of Dest might force a side-effect between Dest and the current
8372       // node.
8373       if (Dest.hasOneUse())
8374         return true;
8375     }
8376     // Next, try a deep search: check whether every operand of the TokenFactor
8377     // reaches Dest.
8378     return llvm::all_of((*this)->ops(), [=](SDValue Op) {
8379       return Op.reachesChainWithoutSideEffects(Dest, Depth - 1);
8380     });
8381   }
8382 
8383   // Loads don't have side effects, look through them.
8384   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(*this)) {
8385     if (!Ld->isVolatile())
8386       return Ld->getChain().reachesChainWithoutSideEffects(Dest, Depth-1);
8387   }
8388   return false;
8389 }
8390 
8391 bool SDNode::hasPredecessor(const SDNode *N) const {
8392   SmallPtrSet<const SDNode *, 32> Visited;
8393   SmallVector<const SDNode *, 16> Worklist;
8394   Worklist.push_back(this);
8395   return hasPredecessorHelper(N, Visited, Worklist);
8396 }
8397 
8398 void SDNode::intersectFlagsWith(const SDNodeFlags Flags) {
8399   this->Flags.intersectWith(Flags);
8400 }
8401 
8402 SDValue
8403 SelectionDAG::matchBinOpReduction(SDNode *Extract, ISD::NodeType &BinOp,
8404                                   ArrayRef<ISD::NodeType> CandidateBinOps) {
8405   // The pattern must end in an extract from index 0.
8406   if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
8407       !isNullConstant(Extract->getOperand(1)))
8408     return SDValue();
8409 
8410   SDValue Op = Extract->getOperand(0);
8411   unsigned Stages = Log2_32(Op.getValueType().getVectorNumElements());
8412 
8413   // Match against one of the candidate binary ops.
8414   if (llvm::none_of(CandidateBinOps, [Op](ISD::NodeType BinOp) {
8415         return Op.getOpcode() == unsigned(BinOp);
8416       }))
8417     return SDValue();
8418 
8419   // At each stage, we're looking for something that looks like:
8420   // %s = shufflevector <8 x i32> %op, <8 x i32> undef,
8421   //                    <8 x i32> <i32 2, i32 3, i32 undef, i32 undef,
8422   //                               i32 undef, i32 undef, i32 undef, i32 undef>
8423   // %a = binop <8 x i32> %op, %s
8424   // Where the mask changes according to the stage. E.g. for a 3-stage pyramid,
8425   // we expect something like:
8426   // <4,5,6,7,u,u,u,u>
8427   // <2,3,u,u,u,u,u,u>
8428   // <1,u,u,u,u,u,u,u>
8429   unsigned CandidateBinOp = Op.getOpcode();
8430   for (unsigned i = 0; i < Stages; ++i) {
8431     if (Op.getOpcode() != CandidateBinOp)
8432       return SDValue();
8433 
8434     SDValue Op0 = Op.getOperand(0);
8435     SDValue Op1 = Op.getOperand(1);
8436 
8437     ShuffleVectorSDNode *Shuffle = dyn_cast<ShuffleVectorSDNode>(Op0);
8438     if (Shuffle) {
8439       Op = Op1;
8440     } else {
8441       Shuffle = dyn_cast<ShuffleVectorSDNode>(Op1);
8442       Op = Op0;
8443     }
8444 
8445     // The first operand of the shuffle should be the same as the other operand
8446     // of the binop.
8447     if (!Shuffle || Shuffle->getOperand(0) != Op)
8448       return SDValue();
8449 
8450     // Verify the shuffle has the expected (at this stage of the pyramid) mask.
8451     for (int Index = 0, MaskEnd = 1 << i; Index < MaskEnd; ++Index)
8452       if (Shuffle->getMaskElt(Index) != MaskEnd + Index)
8453         return SDValue();
8454   }
8455 
8456   BinOp = (ISD::NodeType)CandidateBinOp;
8457   return Op;
8458 }
8459 
8460 SDValue SelectionDAG::UnrollVectorOp(SDNode *N, unsigned ResNE) {
8461   assert(N->getNumValues() == 1 &&
8462          "Can't unroll a vector with multiple results!");
8463 
8464   EVT VT = N->getValueType(0);
8465   unsigned NE = VT.getVectorNumElements();
8466   EVT EltVT = VT.getVectorElementType();
8467   SDLoc dl(N);
8468 
8469   SmallVector<SDValue, 8> Scalars;
8470   SmallVector<SDValue, 4> Operands(N->getNumOperands());
8471 
8472   // If ResNE is 0, fully unroll the vector op.
8473   if (ResNE == 0)
8474     ResNE = NE;
8475   else if (NE > ResNE)
8476     NE = ResNE;
8477 
8478   unsigned i;
8479   for (i= 0; i != NE; ++i) {
8480     for (unsigned j = 0, e = N->getNumOperands(); j != e; ++j) {
8481       SDValue Operand = N->getOperand(j);
8482       EVT OperandVT = Operand.getValueType();
8483       if (OperandVT.isVector()) {
8484         // A vector operand; extract a single element.
8485         EVT OperandEltVT = OperandVT.getVectorElementType();
8486         Operands[j] =
8487             getNode(ISD::EXTRACT_VECTOR_ELT, dl, OperandEltVT, Operand,
8488                     getConstant(i, dl, TLI->getVectorIdxTy(getDataLayout())));
8489       } else {
8490         // A scalar operand; just use it as is.
8491         Operands[j] = Operand;
8492       }
8493     }
8494 
8495     switch (N->getOpcode()) {
8496     default: {
8497       Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands,
8498                                 N->getFlags()));
8499       break;
8500     }
8501     case ISD::VSELECT:
8502       Scalars.push_back(getNode(ISD::SELECT, dl, EltVT, Operands));
8503       break;
8504     case ISD::SHL:
8505     case ISD::SRA:
8506     case ISD::SRL:
8507     case ISD::ROTL:
8508     case ISD::ROTR:
8509       Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands[0],
8510                                getShiftAmountOperand(Operands[0].getValueType(),
8511                                                      Operands[1])));
8512       break;
8513     case ISD::SIGN_EXTEND_INREG:
8514     case ISD::FP_ROUND_INREG: {
8515       EVT ExtVT = cast<VTSDNode>(Operands[1])->getVT().getVectorElementType();
8516       Scalars.push_back(getNode(N->getOpcode(), dl, EltVT,
8517                                 Operands[0],
8518                                 getValueType(ExtVT)));
8519     }
8520     }
8521   }
8522 
8523   for (; i < ResNE; ++i)
8524     Scalars.push_back(getUNDEF(EltVT));
8525 
8526   EVT VecVT = EVT::getVectorVT(*getContext(), EltVT, ResNE);
8527   return getBuildVector(VecVT, dl, Scalars);
8528 }
8529 
8530 bool SelectionDAG::areNonVolatileConsecutiveLoads(LoadSDNode *LD,
8531                                                   LoadSDNode *Base,
8532                                                   unsigned Bytes,
8533                                                   int Dist) const {
8534   if (LD->isVolatile() || Base->isVolatile())
8535     return false;
8536   if (LD->isIndexed() || Base->isIndexed())
8537     return false;
8538   if (LD->getChain() != Base->getChain())
8539     return false;
8540   EVT VT = LD->getValueType(0);
8541   if (VT.getSizeInBits() / 8 != Bytes)
8542     return false;
8543 
8544   auto BaseLocDecomp = BaseIndexOffset::match(Base, *this);
8545   auto LocDecomp = BaseIndexOffset::match(LD, *this);
8546 
8547   int64_t Offset = 0;
8548   if (BaseLocDecomp.equalBaseIndex(LocDecomp, *this, Offset))
8549     return (Dist * Bytes == Offset);
8550   return false;
8551 }
8552 
8553 /// InferPtrAlignment - Infer alignment of a load / store address. Return 0 if
8554 /// it cannot be inferred.
8555 unsigned SelectionDAG::InferPtrAlignment(SDValue Ptr) const {
8556   // If this is a GlobalAddress + cst, return the alignment.
8557   const GlobalValue *GV;
8558   int64_t GVOffset = 0;
8559   if (TLI->isGAPlusOffset(Ptr.getNode(), GV, GVOffset)) {
8560     unsigned IdxWidth = getDataLayout().getIndexTypeSizeInBits(GV->getType());
8561     KnownBits Known(IdxWidth);
8562     llvm::computeKnownBits(GV, Known, getDataLayout());
8563     unsigned AlignBits = Known.countMinTrailingZeros();
8564     unsigned Align = AlignBits ? 1 << std::min(31U, AlignBits) : 0;
8565     if (Align)
8566       return MinAlign(Align, GVOffset);
8567   }
8568 
8569   // If this is a direct reference to a stack slot, use information about the
8570   // stack slot's alignment.
8571   int FrameIdx = 1 << 31;
8572   int64_t FrameOffset = 0;
8573   if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr)) {
8574     FrameIdx = FI->getIndex();
8575   } else if (isBaseWithConstantOffset(Ptr) &&
8576              isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
8577     // Handle FI+Cst
8578     FrameIdx = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
8579     FrameOffset = Ptr.getConstantOperandVal(1);
8580   }
8581 
8582   if (FrameIdx != (1 << 31)) {
8583     const MachineFrameInfo &MFI = getMachineFunction().getFrameInfo();
8584     unsigned FIInfoAlign = MinAlign(MFI.getObjectAlignment(FrameIdx),
8585                                     FrameOffset);
8586     return FIInfoAlign;
8587   }
8588 
8589   return 0;
8590 }
8591 
8592 /// GetSplitDestVTs - Compute the VTs needed for the low/hi parts of a type
8593 /// which is split (or expanded) into two not necessarily identical pieces.
8594 std::pair<EVT, EVT> SelectionDAG::GetSplitDestVTs(const EVT &VT) const {
8595   // Currently all types are split in half.
8596   EVT LoVT, HiVT;
8597   if (!VT.isVector())
8598     LoVT = HiVT = TLI->getTypeToTransformTo(*getContext(), VT);
8599   else
8600     LoVT = HiVT = VT.getHalfNumVectorElementsVT(*getContext());
8601 
8602   return std::make_pair(LoVT, HiVT);
8603 }
8604 
8605 /// SplitVector - Split the vector with EXTRACT_SUBVECTOR and return the
8606 /// low/high part.
8607 std::pair<SDValue, SDValue>
8608 SelectionDAG::SplitVector(const SDValue &N, const SDLoc &DL, const EVT &LoVT,
8609                           const EVT &HiVT) {
8610   assert(LoVT.getVectorNumElements() + HiVT.getVectorNumElements() <=
8611          N.getValueType().getVectorNumElements() &&
8612          "More vector elements requested than available!");
8613   SDValue Lo, Hi;
8614   Lo = getNode(ISD::EXTRACT_SUBVECTOR, DL, LoVT, N,
8615                getConstant(0, DL, TLI->getVectorIdxTy(getDataLayout())));
8616   Hi = getNode(ISD::EXTRACT_SUBVECTOR, DL, HiVT, N,
8617                getConstant(LoVT.getVectorNumElements(), DL,
8618                            TLI->getVectorIdxTy(getDataLayout())));
8619   return std::make_pair(Lo, Hi);
8620 }
8621 
8622 void SelectionDAG::ExtractVectorElements(SDValue Op,
8623                                          SmallVectorImpl<SDValue> &Args,
8624                                          unsigned Start, unsigned Count) {
8625   EVT VT = Op.getValueType();
8626   if (Count == 0)
8627     Count = VT.getVectorNumElements();
8628 
8629   EVT EltVT = VT.getVectorElementType();
8630   EVT IdxTy = TLI->getVectorIdxTy(getDataLayout());
8631   SDLoc SL(Op);
8632   for (unsigned i = Start, e = Start + Count; i != e; ++i) {
8633     Args.push_back(getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
8634                            Op, getConstant(i, SL, IdxTy)));
8635   }
8636 }
8637 
8638 // getAddressSpace - Return the address space this GlobalAddress belongs to.
8639 unsigned GlobalAddressSDNode::getAddressSpace() const {
8640   return getGlobal()->getType()->getAddressSpace();
8641 }
8642 
8643 Type *ConstantPoolSDNode::getType() const {
8644   if (isMachineConstantPoolEntry())
8645     return Val.MachineCPVal->getType();
8646   return Val.ConstVal->getType();
8647 }
8648 
8649 bool BuildVectorSDNode::isConstantSplat(APInt &SplatValue, APInt &SplatUndef,
8650                                         unsigned &SplatBitSize,
8651                                         bool &HasAnyUndefs,
8652                                         unsigned MinSplatBits,
8653                                         bool IsBigEndian) const {
8654   EVT VT = getValueType(0);
8655   assert(VT.isVector() && "Expected a vector type");
8656   unsigned VecWidth = VT.getSizeInBits();
8657   if (MinSplatBits > VecWidth)
8658     return false;
8659 
8660   // FIXME: The widths are based on this node's type, but build vectors can
8661   // truncate their operands.
8662   SplatValue = APInt(VecWidth, 0);
8663   SplatUndef = APInt(VecWidth, 0);
8664 
8665   // Get the bits. Bits with undefined values (when the corresponding element
8666   // of the vector is an ISD::UNDEF value) are set in SplatUndef and cleared
8667   // in SplatValue. If any of the values are not constant, give up and return
8668   // false.
8669   unsigned int NumOps = getNumOperands();
8670   assert(NumOps > 0 && "isConstantSplat has 0-size build vector");
8671   unsigned EltWidth = VT.getScalarSizeInBits();
8672 
8673   for (unsigned j = 0; j < NumOps; ++j) {
8674     unsigned i = IsBigEndian ? NumOps - 1 - j : j;
8675     SDValue OpVal = getOperand(i);
8676     unsigned BitPos = j * EltWidth;
8677 
8678     if (OpVal.isUndef())
8679       SplatUndef.setBits(BitPos, BitPos + EltWidth);
8680     else if (auto *CN = dyn_cast<ConstantSDNode>(OpVal))
8681       SplatValue.insertBits(CN->getAPIntValue().zextOrTrunc(EltWidth), BitPos);
8682     else if (auto *CN = dyn_cast<ConstantFPSDNode>(OpVal))
8683       SplatValue.insertBits(CN->getValueAPF().bitcastToAPInt(), BitPos);
8684     else
8685       return false;
8686   }
8687 
8688   // The build_vector is all constants or undefs. Find the smallest element
8689   // size that splats the vector.
8690   HasAnyUndefs = (SplatUndef != 0);
8691 
8692   // FIXME: This does not work for vectors with elements less than 8 bits.
8693   while (VecWidth > 8) {
8694     unsigned HalfSize = VecWidth / 2;
8695     APInt HighValue = SplatValue.lshr(HalfSize).trunc(HalfSize);
8696     APInt LowValue = SplatValue.trunc(HalfSize);
8697     APInt HighUndef = SplatUndef.lshr(HalfSize).trunc(HalfSize);
8698     APInt LowUndef = SplatUndef.trunc(HalfSize);
8699 
8700     // If the two halves do not match (ignoring undef bits), stop here.
8701     if ((HighValue & ~LowUndef) != (LowValue & ~HighUndef) ||
8702         MinSplatBits > HalfSize)
8703       break;
8704 
8705     SplatValue = HighValue | LowValue;
8706     SplatUndef = HighUndef & LowUndef;
8707 
8708     VecWidth = HalfSize;
8709   }
8710 
8711   SplatBitSize = VecWidth;
8712   return true;
8713 }
8714 
8715 SDValue BuildVectorSDNode::getSplatValue(BitVector *UndefElements) const {
8716   if (UndefElements) {
8717     UndefElements->clear();
8718     UndefElements->resize(getNumOperands());
8719   }
8720   SDValue Splatted;
8721   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
8722     SDValue Op = getOperand(i);
8723     if (Op.isUndef()) {
8724       if (UndefElements)
8725         (*UndefElements)[i] = true;
8726     } else if (!Splatted) {
8727       Splatted = Op;
8728     } else if (Splatted != Op) {
8729       return SDValue();
8730     }
8731   }
8732 
8733   if (!Splatted) {
8734     assert(getOperand(0).isUndef() &&
8735            "Can only have a splat without a constant for all undefs.");
8736     return getOperand(0);
8737   }
8738 
8739   return Splatted;
8740 }
8741 
8742 ConstantSDNode *
8743 BuildVectorSDNode::getConstantSplatNode(BitVector *UndefElements) const {
8744   return dyn_cast_or_null<ConstantSDNode>(getSplatValue(UndefElements));
8745 }
8746 
8747 ConstantFPSDNode *
8748 BuildVectorSDNode::getConstantFPSplatNode(BitVector *UndefElements) const {
8749   return dyn_cast_or_null<ConstantFPSDNode>(getSplatValue(UndefElements));
8750 }
8751 
8752 int32_t
8753 BuildVectorSDNode::getConstantFPSplatPow2ToLog2Int(BitVector *UndefElements,
8754                                                    uint32_t BitWidth) const {
8755   if (ConstantFPSDNode *CN =
8756           dyn_cast_or_null<ConstantFPSDNode>(getSplatValue(UndefElements))) {
8757     bool IsExact;
8758     APSInt IntVal(BitWidth);
8759     const APFloat &APF = CN->getValueAPF();
8760     if (APF.convertToInteger(IntVal, APFloat::rmTowardZero, &IsExact) !=
8761             APFloat::opOK ||
8762         !IsExact)
8763       return -1;
8764 
8765     return IntVal.exactLogBase2();
8766   }
8767   return -1;
8768 }
8769 
8770 bool BuildVectorSDNode::isConstant() const {
8771   for (const SDValue &Op : op_values()) {
8772     unsigned Opc = Op.getOpcode();
8773     if (Opc != ISD::UNDEF && Opc != ISD::Constant && Opc != ISD::ConstantFP)
8774       return false;
8775   }
8776   return true;
8777 }
8778 
8779 bool ShuffleVectorSDNode::isSplatMask(const int *Mask, EVT VT) {
8780   // Find the first non-undef value in the shuffle mask.
8781   unsigned i, e;
8782   for (i = 0, e = VT.getVectorNumElements(); i != e && Mask[i] < 0; ++i)
8783     /* search */;
8784 
8785   assert(i != e && "VECTOR_SHUFFLE node with all undef indices!");
8786 
8787   // Make sure all remaining elements are either undef or the same as the first
8788   // non-undef value.
8789   for (int Idx = Mask[i]; i != e; ++i)
8790     if (Mask[i] >= 0 && Mask[i] != Idx)
8791       return false;
8792   return true;
8793 }
8794 
8795 // Returns the SDNode if it is a constant integer BuildVector
8796 // or constant integer.
8797 SDNode *SelectionDAG::isConstantIntBuildVectorOrConstantInt(SDValue N) {
8798   if (isa<ConstantSDNode>(N))
8799     return N.getNode();
8800   if (ISD::isBuildVectorOfConstantSDNodes(N.getNode()))
8801     return N.getNode();
8802   // Treat a GlobalAddress supporting constant offset folding as a
8803   // constant integer.
8804   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N))
8805     if (GA->getOpcode() == ISD::GlobalAddress &&
8806         TLI->isOffsetFoldingLegal(GA))
8807       return GA;
8808   return nullptr;
8809 }
8810 
8811 SDNode *SelectionDAG::isConstantFPBuildVectorOrConstantFP(SDValue N) {
8812   if (isa<ConstantFPSDNode>(N))
8813     return N.getNode();
8814 
8815   if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode()))
8816     return N.getNode();
8817 
8818   return nullptr;
8819 }
8820 
8821 void SelectionDAG::createOperands(SDNode *Node, ArrayRef<SDValue> Vals) {
8822   assert(!Node->OperandList && "Node already has operands");
8823   SDUse *Ops = OperandRecycler.allocate(
8824     ArrayRecycler<SDUse>::Capacity::get(Vals.size()), OperandAllocator);
8825 
8826   bool IsDivergent = false;
8827   for (unsigned I = 0; I != Vals.size(); ++I) {
8828     Ops[I].setUser(Node);
8829     Ops[I].setInitial(Vals[I]);
8830     if (Ops[I].Val.getValueType() != MVT::Other) // Skip Chain. It does not carry divergence.
8831       IsDivergent = IsDivergent || Ops[I].getNode()->isDivergent();
8832   }
8833   Node->NumOperands = Vals.size();
8834   Node->OperandList = Ops;
8835   IsDivergent |= TLI->isSDNodeSourceOfDivergence(Node, FLI, DA);
8836   if (!TLI->isSDNodeAlwaysUniform(Node))
8837     Node->SDNodeBits.IsDivergent = IsDivergent;
8838   checkForCycles(Node);
8839 }
8840 
8841 #ifndef NDEBUG
8842 static void checkForCyclesHelper(const SDNode *N,
8843                                  SmallPtrSetImpl<const SDNode*> &Visited,
8844                                  SmallPtrSetImpl<const SDNode*> &Checked,
8845                                  const llvm::SelectionDAG *DAG) {
8846   // If this node has already been checked, don't check it again.
8847   if (Checked.count(N))
8848     return;
8849 
8850   // If a node has already been visited on this depth-first walk, reject it as
8851   // a cycle.
8852   if (!Visited.insert(N).second) {
8853     errs() << "Detected cycle in SelectionDAG\n";
8854     dbgs() << "Offending node:\n";
8855     N->dumprFull(DAG); dbgs() << "\n";
8856     abort();
8857   }
8858 
8859   for (const SDValue &Op : N->op_values())
8860     checkForCyclesHelper(Op.getNode(), Visited, Checked, DAG);
8861 
8862   Checked.insert(N);
8863   Visited.erase(N);
8864 }
8865 #endif
8866 
8867 void llvm::checkForCycles(const llvm::SDNode *N,
8868                           const llvm::SelectionDAG *DAG,
8869                           bool force) {
8870 #ifndef NDEBUG
8871   bool check = force;
8872 #ifdef EXPENSIVE_CHECKS
8873   check = true;
8874 #endif  // EXPENSIVE_CHECKS
8875   if (check) {
8876     assert(N && "Checking nonexistent SDNode");
8877     SmallPtrSet<const SDNode*, 32> visited;
8878     SmallPtrSet<const SDNode*, 32> checked;
8879     checkForCyclesHelper(N, visited, checked, DAG);
8880   }
8881 #endif  // !NDEBUG
8882 }
8883 
8884 void llvm::checkForCycles(const llvm::SelectionDAG *DAG, bool force) {
8885   checkForCycles(DAG->getRoot().getNode(), DAG, force);
8886 }
8887