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