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