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