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