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