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