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