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