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