1 //===- llvm/CodeGen/SelectionDAGNodes.h - SelectionDAG Nodes ----*- C++ -*-===//
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 file declares the SDNode class and derived classes, which are used to
10 // represent the nodes and operations present in a SelectionDAG.  These nodes
11 // and operations are machine code level operations, with some similarities to
12 // the GCC RTL representation.
13 //
14 // Clients should include the SelectionDAG.h file instead of this file directly.
15 //
16 //===----------------------------------------------------------------------===//
17 
18 #ifndef LLVM_CODEGEN_SELECTIONDAGNODES_H
19 #define LLVM_CODEGEN_SELECTIONDAGNODES_H
20 
21 #include "llvm/ADT/APFloat.h"
22 #include "llvm/ADT/ArrayRef.h"
23 #include "llvm/ADT/BitVector.h"
24 #include "llvm/ADT/FoldingSet.h"
25 #include "llvm/ADT/GraphTraits.h"
26 #include "llvm/ADT/SmallPtrSet.h"
27 #include "llvm/ADT/SmallVector.h"
28 #include "llvm/ADT/ilist_node.h"
29 #include "llvm/ADT/iterator.h"
30 #include "llvm/ADT/iterator_range.h"
31 #include "llvm/CodeGen/ISDOpcodes.h"
32 #include "llvm/CodeGen/MachineMemOperand.h"
33 #include "llvm/CodeGen/Register.h"
34 #include "llvm/CodeGen/ValueTypes.h"
35 #include "llvm/IR/Constants.h"
36 #include "llvm/IR/DebugLoc.h"
37 #include "llvm/IR/Instruction.h"
38 #include "llvm/IR/Instructions.h"
39 #include "llvm/IR/Metadata.h"
40 #include "llvm/IR/Operator.h"
41 #include "llvm/Support/AlignOf.h"
42 #include "llvm/Support/AtomicOrdering.h"
43 #include "llvm/Support/Casting.h"
44 #include "llvm/Support/ErrorHandling.h"
45 #include "llvm/Support/MachineValueType.h"
46 #include "llvm/Support/TypeSize.h"
47 #include <algorithm>
48 #include <cassert>
49 #include <climits>
50 #include <cstddef>
51 #include <cstdint>
52 #include <cstring>
53 #include <iterator>
54 #include <string>
55 #include <tuple>
56 #include <utility>
57 
58 namespace llvm {
59 
60 class APInt;
61 class Constant;
62 class GlobalValue;
63 class MachineBasicBlock;
64 class MachineConstantPoolValue;
65 class MCSymbol;
66 class raw_ostream;
67 class SDNode;
68 class SelectionDAG;
69 class Type;
70 class Value;
71 
72 void checkForCycles(const SDNode *N, const SelectionDAG *DAG = nullptr,
73                     bool force = false);
74 
75 /// This represents a list of ValueType's that has been intern'd by
76 /// a SelectionDAG.  Instances of this simple value class are returned by
77 /// SelectionDAG::getVTList(...).
78 ///
79 struct SDVTList {
80   const EVT *VTs;
81   unsigned int NumVTs;
82 };
83 
84 namespace ISD {
85 
86   /// Node predicates
87 
88 /// If N is a BUILD_VECTOR or SPLAT_VECTOR node whose elements are all the
89 /// same constant or undefined, return true and return the constant value in
90 /// \p SplatValue.
91 bool isConstantSplatVector(const SDNode *N, APInt &SplatValue);
92 
93 /// Return true if the specified node is a BUILD_VECTOR or SPLAT_VECTOR where
94 /// all of the elements are ~0 or undef. If \p BuildVectorOnly is set to
95 /// true, it only checks BUILD_VECTOR.
96 bool isConstantSplatVectorAllOnes(const SDNode *N,
97                                   bool BuildVectorOnly = false);
98 
99 /// Return true if the specified node is a BUILD_VECTOR or SPLAT_VECTOR where
100 /// all of the elements are 0 or undef. If \p BuildVectorOnly is set to true, it
101 /// only checks BUILD_VECTOR.
102 bool isConstantSplatVectorAllZeros(const SDNode *N,
103                                    bool BuildVectorOnly = false);
104 
105 /// Return true if the specified node is a BUILD_VECTOR where all of the
106 /// elements are ~0 or undef.
107 bool isBuildVectorAllOnes(const SDNode *N);
108 
109 /// Return true if the specified node is a BUILD_VECTOR where all of the
110 /// elements are 0 or undef.
111 bool isBuildVectorAllZeros(const SDNode *N);
112 
113 /// Return true if the specified node is a BUILD_VECTOR node of all
114 /// ConstantSDNode or undef.
115 bool isBuildVectorOfConstantSDNodes(const SDNode *N);
116 
117 /// Return true if the specified node is a BUILD_VECTOR node of all
118 /// ConstantFPSDNode or undef.
119 bool isBuildVectorOfConstantFPSDNodes(const SDNode *N);
120 
121 /// Return true if the node has at least one operand and all operands of the
122 /// specified node are ISD::UNDEF.
123 bool allOperandsUndef(const SDNode *N);
124 
125 } // end namespace ISD
126 
127 //===----------------------------------------------------------------------===//
128 /// Unlike LLVM values, Selection DAG nodes may return multiple
129 /// values as the result of a computation.  Many nodes return multiple values,
130 /// from loads (which define a token and a return value) to ADDC (which returns
131 /// a result and a carry value), to calls (which may return an arbitrary number
132 /// of values).
133 ///
134 /// As such, each use of a SelectionDAG computation must indicate the node that
135 /// computes it as well as which return value to use from that node.  This pair
136 /// of information is represented with the SDValue value type.
137 ///
138 class SDValue {
139   friend struct DenseMapInfo<SDValue>;
140 
141   SDNode *Node = nullptr; // The node defining the value we are using.
142   unsigned ResNo = 0;     // Which return value of the node we are using.
143 
144 public:
145   SDValue() = default;
146   SDValue(SDNode *node, unsigned resno);
147 
148   /// get the index which selects a specific result in the SDNode
149   unsigned getResNo() const { return ResNo; }
150 
151   /// get the SDNode which holds the desired result
152   SDNode *getNode() const { return Node; }
153 
154   /// set the SDNode
155   void setNode(SDNode *N) { Node = N; }
156 
157   inline SDNode *operator->() const { return Node; }
158 
159   bool operator==(const SDValue &O) const {
160     return Node == O.Node && ResNo == O.ResNo;
161   }
162   bool operator!=(const SDValue &O) const {
163     return !operator==(O);
164   }
165   bool operator<(const SDValue &O) const {
166     return std::tie(Node, ResNo) < std::tie(O.Node, O.ResNo);
167   }
168   explicit operator bool() const {
169     return Node != nullptr;
170   }
171 
172   SDValue getValue(unsigned R) const {
173     return SDValue(Node, R);
174   }
175 
176   /// Return true if this node is an operand of N.
177   bool isOperandOf(const SDNode *N) const;
178 
179   /// Return the ValueType of the referenced return value.
180   inline EVT getValueType() const;
181 
182   /// Return the simple ValueType of the referenced return value.
183   MVT getSimpleValueType() const {
184     return getValueType().getSimpleVT();
185   }
186 
187   /// Returns the size of the value in bits.
188   ///
189   /// If the value type is a scalable vector type, the scalable property will
190   /// be set and the runtime size will be a positive integer multiple of the
191   /// base size.
192   TypeSize getValueSizeInBits() const {
193     return getValueType().getSizeInBits();
194   }
195 
196   uint64_t getScalarValueSizeInBits() const {
197     return getValueType().getScalarType().getFixedSizeInBits();
198   }
199 
200   // Forwarding methods - These forward to the corresponding methods in SDNode.
201   inline unsigned getOpcode() const;
202   inline unsigned getNumOperands() const;
203   inline const SDValue &getOperand(unsigned i) const;
204   inline uint64_t getConstantOperandVal(unsigned i) const;
205   inline const APInt &getConstantOperandAPInt(unsigned i) const;
206   inline bool isTargetMemoryOpcode() const;
207   inline bool isTargetOpcode() const;
208   inline bool isMachineOpcode() const;
209   inline bool isUndef() const;
210   inline unsigned getMachineOpcode() const;
211   inline const DebugLoc &getDebugLoc() const;
212   inline void dump() const;
213   inline void dump(const SelectionDAG *G) const;
214   inline void dumpr() const;
215   inline void dumpr(const SelectionDAG *G) const;
216 
217   /// Return true if this operand (which must be a chain) reaches the
218   /// specified operand without crossing any side-effecting instructions.
219   /// In practice, this looks through token factors and non-volatile loads.
220   /// In order to remain efficient, this only
221   /// looks a couple of nodes in, it does not do an exhaustive search.
222   bool reachesChainWithoutSideEffects(SDValue Dest,
223                                       unsigned Depth = 2) const;
224 
225   /// Return true if there are no nodes using value ResNo of Node.
226   inline bool use_empty() const;
227 
228   /// Return true if there is exactly one node using value ResNo of Node.
229   inline bool hasOneUse() const;
230 };
231 
232 template<> struct DenseMapInfo<SDValue> {
233   static inline SDValue getEmptyKey() {
234     SDValue V;
235     V.ResNo = -1U;
236     return V;
237   }
238 
239   static inline SDValue getTombstoneKey() {
240     SDValue V;
241     V.ResNo = -2U;
242     return V;
243   }
244 
245   static unsigned getHashValue(const SDValue &Val) {
246     return ((unsigned)((uintptr_t)Val.getNode() >> 4) ^
247             (unsigned)((uintptr_t)Val.getNode() >> 9)) + Val.getResNo();
248   }
249 
250   static bool isEqual(const SDValue &LHS, const SDValue &RHS) {
251     return LHS == RHS;
252   }
253 };
254 
255 /// Allow casting operators to work directly on
256 /// SDValues as if they were SDNode*'s.
257 template<> struct simplify_type<SDValue> {
258   using SimpleType = SDNode *;
259 
260   static SimpleType getSimplifiedValue(SDValue &Val) {
261     return Val.getNode();
262   }
263 };
264 template<> struct simplify_type<const SDValue> {
265   using SimpleType = /*const*/ SDNode *;
266 
267   static SimpleType getSimplifiedValue(const SDValue &Val) {
268     return Val.getNode();
269   }
270 };
271 
272 /// Represents a use of a SDNode. This class holds an SDValue,
273 /// which records the SDNode being used and the result number, a
274 /// pointer to the SDNode using the value, and Next and Prev pointers,
275 /// which link together all the uses of an SDNode.
276 ///
277 class SDUse {
278   /// Val - The value being used.
279   SDValue Val;
280   /// User - The user of this value.
281   SDNode *User = nullptr;
282   /// Prev, Next - Pointers to the uses list of the SDNode referred by
283   /// this operand.
284   SDUse **Prev = nullptr;
285   SDUse *Next = nullptr;
286 
287 public:
288   SDUse() = default;
289   SDUse(const SDUse &U) = delete;
290   SDUse &operator=(const SDUse &) = delete;
291 
292   /// Normally SDUse will just implicitly convert to an SDValue that it holds.
293   operator const SDValue&() const { return Val; }
294 
295   /// If implicit conversion to SDValue doesn't work, the get() method returns
296   /// the SDValue.
297   const SDValue &get() const { return Val; }
298 
299   /// This returns the SDNode that contains this Use.
300   SDNode *getUser() { return User; }
301 
302   /// Get the next SDUse in the use list.
303   SDUse *getNext() const { return Next; }
304 
305   /// Convenience function for get().getNode().
306   SDNode *getNode() const { return Val.getNode(); }
307   /// Convenience function for get().getResNo().
308   unsigned getResNo() const { return Val.getResNo(); }
309   /// Convenience function for get().getValueType().
310   EVT getValueType() const { return Val.getValueType(); }
311 
312   /// Convenience function for get().operator==
313   bool operator==(const SDValue &V) const {
314     return Val == V;
315   }
316 
317   /// Convenience function for get().operator!=
318   bool operator!=(const SDValue &V) const {
319     return Val != V;
320   }
321 
322   /// Convenience function for get().operator<
323   bool operator<(const SDValue &V) const {
324     return Val < V;
325   }
326 
327 private:
328   friend class SelectionDAG;
329   friend class SDNode;
330   // TODO: unfriend HandleSDNode once we fix its operand handling.
331   friend class HandleSDNode;
332 
333   void setUser(SDNode *p) { User = p; }
334 
335   /// Remove this use from its existing use list, assign it the
336   /// given value, and add it to the new value's node's use list.
337   inline void set(const SDValue &V);
338   /// Like set, but only supports initializing a newly-allocated
339   /// SDUse with a non-null value.
340   inline void setInitial(const SDValue &V);
341   /// Like set, but only sets the Node portion of the value,
342   /// leaving the ResNo portion unmodified.
343   inline void setNode(SDNode *N);
344 
345   void addToList(SDUse **List) {
346     Next = *List;
347     if (Next) Next->Prev = &Next;
348     Prev = List;
349     *List = this;
350   }
351 
352   void removeFromList() {
353     *Prev = Next;
354     if (Next) Next->Prev = Prev;
355   }
356 };
357 
358 /// simplify_type specializations - Allow casting operators to work directly on
359 /// SDValues as if they were SDNode*'s.
360 template<> struct simplify_type<SDUse> {
361   using SimpleType = SDNode *;
362 
363   static SimpleType getSimplifiedValue(SDUse &Val) {
364     return Val.getNode();
365   }
366 };
367 
368 /// These are IR-level optimization flags that may be propagated to SDNodes.
369 /// TODO: This data structure should be shared by the IR optimizer and the
370 /// the backend.
371 struct SDNodeFlags {
372 private:
373   bool NoUnsignedWrap : 1;
374   bool NoSignedWrap : 1;
375   bool Exact : 1;
376   bool NoNaNs : 1;
377   bool NoInfs : 1;
378   bool NoSignedZeros : 1;
379   bool AllowReciprocal : 1;
380   bool AllowContract : 1;
381   bool ApproximateFuncs : 1;
382   bool AllowReassociation : 1;
383 
384   // We assume instructions do not raise floating-point exceptions by default,
385   // and only those marked explicitly may do so.  We could choose to represent
386   // this via a positive "FPExcept" flags like on the MI level, but having a
387   // negative "NoFPExcept" flag here (that defaults to true) makes the flag
388   // intersection logic more straightforward.
389   bool NoFPExcept : 1;
390 
391 public:
392   /// Default constructor turns off all optimization flags.
393   SDNodeFlags()
394       : NoUnsignedWrap(false), NoSignedWrap(false), Exact(false), NoNaNs(false),
395         NoInfs(false), NoSignedZeros(false), AllowReciprocal(false),
396         AllowContract(false), ApproximateFuncs(false),
397         AllowReassociation(false), NoFPExcept(false) {}
398 
399   /// Propagate the fast-math-flags from an IR FPMathOperator.
400   void copyFMF(const FPMathOperator &FPMO) {
401     setNoNaNs(FPMO.hasNoNaNs());
402     setNoInfs(FPMO.hasNoInfs());
403     setNoSignedZeros(FPMO.hasNoSignedZeros());
404     setAllowReciprocal(FPMO.hasAllowReciprocal());
405     setAllowContract(FPMO.hasAllowContract());
406     setApproximateFuncs(FPMO.hasApproxFunc());
407     setAllowReassociation(FPMO.hasAllowReassoc());
408   }
409 
410   // These are mutators for each flag.
411   void setNoUnsignedWrap(bool b) { NoUnsignedWrap = b; }
412   void setNoSignedWrap(bool b) { NoSignedWrap = b; }
413   void setExact(bool b) { Exact = b; }
414   void setNoNaNs(bool b) { NoNaNs = b; }
415   void setNoInfs(bool b) { NoInfs = b; }
416   void setNoSignedZeros(bool b) { NoSignedZeros = b; }
417   void setAllowReciprocal(bool b) { AllowReciprocal = b; }
418   void setAllowContract(bool b) { AllowContract = b; }
419   void setApproximateFuncs(bool b) { ApproximateFuncs = b; }
420   void setAllowReassociation(bool b) { AllowReassociation = b; }
421   void setNoFPExcept(bool b) { NoFPExcept = b; }
422 
423   // These are accessors for each flag.
424   bool hasNoUnsignedWrap() const { return NoUnsignedWrap; }
425   bool hasNoSignedWrap() const { return NoSignedWrap; }
426   bool hasExact() const { return Exact; }
427   bool hasNoNaNs() const { return NoNaNs; }
428   bool hasNoInfs() const { return NoInfs; }
429   bool hasNoSignedZeros() const { return NoSignedZeros; }
430   bool hasAllowReciprocal() const { return AllowReciprocal; }
431   bool hasAllowContract() const { return AllowContract; }
432   bool hasApproximateFuncs() const { return ApproximateFuncs; }
433   bool hasAllowReassociation() const { return AllowReassociation; }
434   bool hasNoFPExcept() const { return NoFPExcept; }
435 
436   /// Clear any flags in this flag set that aren't also set in Flags. All
437   /// flags will be cleared if Flags are undefined.
438   void intersectWith(const SDNodeFlags Flags) {
439     NoUnsignedWrap &= Flags.NoUnsignedWrap;
440     NoSignedWrap &= Flags.NoSignedWrap;
441     Exact &= Flags.Exact;
442     NoNaNs &= Flags.NoNaNs;
443     NoInfs &= Flags.NoInfs;
444     NoSignedZeros &= Flags.NoSignedZeros;
445     AllowReciprocal &= Flags.AllowReciprocal;
446     AllowContract &= Flags.AllowContract;
447     ApproximateFuncs &= Flags.ApproximateFuncs;
448     AllowReassociation &= Flags.AllowReassociation;
449     NoFPExcept &= Flags.NoFPExcept;
450   }
451 };
452 
453 /// Represents one node in the SelectionDAG.
454 ///
455 class SDNode : public FoldingSetNode, public ilist_node<SDNode> {
456 private:
457   /// The operation that this node performs.
458   int16_t NodeType;
459 
460 protected:
461   // We define a set of mini-helper classes to help us interpret the bits in our
462   // SubclassData.  These are designed to fit within a uint16_t so they pack
463   // with NodeType.
464 
465 #if defined(_AIX) && (!defined(__GNUC__) || defined(__clang__))
466 // Except for GCC; by default, AIX compilers store bit-fields in 4-byte words
467 // and give the `pack` pragma push semantics.
468 #define BEGIN_TWO_BYTE_PACK() _Pragma("pack(2)")
469 #define END_TWO_BYTE_PACK() _Pragma("pack(pop)")
470 #else
471 #define BEGIN_TWO_BYTE_PACK()
472 #define END_TWO_BYTE_PACK()
473 #endif
474 
475 BEGIN_TWO_BYTE_PACK()
476   class SDNodeBitfields {
477     friend class SDNode;
478     friend class MemIntrinsicSDNode;
479     friend class MemSDNode;
480     friend class SelectionDAG;
481 
482     uint16_t HasDebugValue : 1;
483     uint16_t IsMemIntrinsic : 1;
484     uint16_t IsDivergent : 1;
485   };
486   enum { NumSDNodeBits = 3 };
487 
488   class ConstantSDNodeBitfields {
489     friend class ConstantSDNode;
490 
491     uint16_t : NumSDNodeBits;
492 
493     uint16_t IsOpaque : 1;
494   };
495 
496   class MemSDNodeBitfields {
497     friend class MemSDNode;
498     friend class MemIntrinsicSDNode;
499     friend class AtomicSDNode;
500 
501     uint16_t : NumSDNodeBits;
502 
503     uint16_t IsVolatile : 1;
504     uint16_t IsNonTemporal : 1;
505     uint16_t IsDereferenceable : 1;
506     uint16_t IsInvariant : 1;
507   };
508   enum { NumMemSDNodeBits = NumSDNodeBits + 4 };
509 
510   class LSBaseSDNodeBitfields {
511     friend class LSBaseSDNode;
512     friend class VPBaseLoadStoreSDNode;
513     friend class MaskedLoadStoreSDNode;
514     friend class MaskedGatherScatterSDNode;
515     friend class VPGatherScatterSDNode;
516 
517     uint16_t : NumMemSDNodeBits;
518 
519     // This storage is shared between disparate class hierarchies to hold an
520     // enumeration specific to the class hierarchy in use.
521     //   LSBaseSDNode => enum ISD::MemIndexedMode
522     //   VPLoadStoreBaseSDNode => enum ISD::MemIndexedMode
523     //   MaskedLoadStoreBaseSDNode => enum ISD::MemIndexedMode
524     //   VPGatherScatterSDNode => enum ISD::MemIndexType
525     //   MaskedGatherScatterSDNode => enum ISD::MemIndexType
526     uint16_t AddressingMode : 3;
527   };
528   enum { NumLSBaseSDNodeBits = NumMemSDNodeBits + 3 };
529 
530   class LoadSDNodeBitfields {
531     friend class LoadSDNode;
532     friend class VPLoadSDNode;
533     friend class VPStridedLoadSDNode;
534     friend class MaskedLoadSDNode;
535     friend class MaskedGatherSDNode;
536     friend class VPGatherSDNode;
537 
538     uint16_t : NumLSBaseSDNodeBits;
539 
540     uint16_t ExtTy : 2; // enum ISD::LoadExtType
541     uint16_t IsExpanding : 1;
542   };
543 
544   class StoreSDNodeBitfields {
545     friend class StoreSDNode;
546     friend class VPStoreSDNode;
547     friend class VPStridedStoreSDNode;
548     friend class MaskedStoreSDNode;
549     friend class MaskedScatterSDNode;
550     friend class VPScatterSDNode;
551 
552     uint16_t : NumLSBaseSDNodeBits;
553 
554     uint16_t IsTruncating : 1;
555     uint16_t IsCompressing : 1;
556   };
557 
558   union {
559     char RawSDNodeBits[sizeof(uint16_t)];
560     SDNodeBitfields SDNodeBits;
561     ConstantSDNodeBitfields ConstantSDNodeBits;
562     MemSDNodeBitfields MemSDNodeBits;
563     LSBaseSDNodeBitfields LSBaseSDNodeBits;
564     LoadSDNodeBitfields LoadSDNodeBits;
565     StoreSDNodeBitfields StoreSDNodeBits;
566   };
567 END_TWO_BYTE_PACK()
568 #undef BEGIN_TWO_BYTE_PACK
569 #undef END_TWO_BYTE_PACK
570 
571   // RawSDNodeBits must cover the entirety of the union.  This means that all of
572   // the union's members must have size <= RawSDNodeBits.  We write the RHS as
573   // "2" instead of sizeof(RawSDNodeBits) because MSVC can't handle the latter.
574   static_assert(sizeof(SDNodeBitfields) <= 2, "field too wide");
575   static_assert(sizeof(ConstantSDNodeBitfields) <= 2, "field too wide");
576   static_assert(sizeof(MemSDNodeBitfields) <= 2, "field too wide");
577   static_assert(sizeof(LSBaseSDNodeBitfields) <= 2, "field too wide");
578   static_assert(sizeof(LoadSDNodeBitfields) <= 2, "field too wide");
579   static_assert(sizeof(StoreSDNodeBitfields) <= 2, "field too wide");
580 
581 private:
582   friend class SelectionDAG;
583   // TODO: unfriend HandleSDNode once we fix its operand handling.
584   friend class HandleSDNode;
585 
586   /// Unique id per SDNode in the DAG.
587   int NodeId = -1;
588 
589   /// The values that are used by this operation.
590   SDUse *OperandList = nullptr;
591 
592   /// The types of the values this node defines.  SDNode's may
593   /// define multiple values simultaneously.
594   const EVT *ValueList;
595 
596   /// List of uses for this SDNode.
597   SDUse *UseList = nullptr;
598 
599   /// The number of entries in the Operand/Value list.
600   unsigned short NumOperands = 0;
601   unsigned short NumValues;
602 
603   // The ordering of the SDNodes. It roughly corresponds to the ordering of the
604   // original LLVM instructions.
605   // This is used for turning off scheduling, because we'll forgo
606   // the normal scheduling algorithms and output the instructions according to
607   // this ordering.
608   unsigned IROrder;
609 
610   /// Source line information.
611   DebugLoc debugLoc;
612 
613   /// Return a pointer to the specified value type.
614   static const EVT *getValueTypeList(EVT VT);
615 
616   SDNodeFlags Flags;
617 
618 public:
619   /// Unique and persistent id per SDNode in the DAG. Used for debug printing.
620   /// We do not place that under `#if LLVM_ENABLE_ABI_BREAKING_CHECKS`
621   /// intentionally because it adds unneeded complexity without noticeable
622   /// benefits (see discussion with @thakis in D120714).
623   uint16_t PersistentId;
624 
625   //===--------------------------------------------------------------------===//
626   //  Accessors
627   //
628 
629   /// Return the SelectionDAG opcode value for this node. For
630   /// pre-isel nodes (those for which isMachineOpcode returns false), these
631   /// are the opcode values in the ISD and <target>ISD namespaces. For
632   /// post-isel opcodes, see getMachineOpcode.
633   unsigned getOpcode()  const { return (unsigned short)NodeType; }
634 
635   /// Test if this node has a target-specific opcode (in the
636   /// \<target\>ISD namespace).
637   bool isTargetOpcode() const { return NodeType >= ISD::BUILTIN_OP_END; }
638 
639   /// Test if this node has a target-specific opcode that may raise
640   /// FP exceptions (in the \<target\>ISD namespace and greater than
641   /// FIRST_TARGET_STRICTFP_OPCODE).  Note that all target memory
642   /// opcode are currently automatically considered to possibly raise
643   /// FP exceptions as well.
644   bool isTargetStrictFPOpcode() const {
645     return NodeType >= ISD::FIRST_TARGET_STRICTFP_OPCODE;
646   }
647 
648   /// Test if this node has a target-specific
649   /// memory-referencing opcode (in the \<target\>ISD namespace and
650   /// greater than FIRST_TARGET_MEMORY_OPCODE).
651   bool isTargetMemoryOpcode() const {
652     return NodeType >= ISD::FIRST_TARGET_MEMORY_OPCODE;
653   }
654 
655   /// Return true if the type of the node type undefined.
656   bool isUndef() const { return NodeType == ISD::UNDEF; }
657 
658   /// Test if this node is a memory intrinsic (with valid pointer information).
659   /// INTRINSIC_W_CHAIN and INTRINSIC_VOID nodes are sometimes created for
660   /// non-memory intrinsics (with chains) that are not really instances of
661   /// MemSDNode. For such nodes, we need some extra state to determine the
662   /// proper classof relationship.
663   bool isMemIntrinsic() const {
664     return (NodeType == ISD::INTRINSIC_W_CHAIN ||
665             NodeType == ISD::INTRINSIC_VOID) &&
666            SDNodeBits.IsMemIntrinsic;
667   }
668 
669   /// Test if this node is a strict floating point pseudo-op.
670   bool isStrictFPOpcode() {
671     switch (NodeType) {
672       default:
673         return false;
674       case ISD::STRICT_FP16_TO_FP:
675       case ISD::STRICT_FP_TO_FP16:
676 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN)               \
677       case ISD::STRICT_##DAGN:
678 #include "llvm/IR/ConstrainedOps.def"
679         return true;
680     }
681   }
682 
683   /// Test if this node is a vector predication operation.
684   bool isVPOpcode() const { return ISD::isVPOpcode(getOpcode()); }
685 
686   /// Test if this node has a post-isel opcode, directly
687   /// corresponding to a MachineInstr opcode.
688   bool isMachineOpcode() const { return NodeType < 0; }
689 
690   /// This may only be called if isMachineOpcode returns
691   /// true. It returns the MachineInstr opcode value that the node's opcode
692   /// corresponds to.
693   unsigned getMachineOpcode() const {
694     assert(isMachineOpcode() && "Not a MachineInstr opcode!");
695     return ~NodeType;
696   }
697 
698   bool getHasDebugValue() const { return SDNodeBits.HasDebugValue; }
699   void setHasDebugValue(bool b) { SDNodeBits.HasDebugValue = b; }
700 
701   bool isDivergent() const { return SDNodeBits.IsDivergent; }
702 
703   /// Return true if there are no uses of this node.
704   bool use_empty() const { return UseList == nullptr; }
705 
706   /// Return true if there is exactly one use of this node.
707   bool hasOneUse() const { return hasSingleElement(uses()); }
708 
709   /// Return the number of uses of this node. This method takes
710   /// time proportional to the number of uses.
711   size_t use_size() const { return std::distance(use_begin(), use_end()); }
712 
713   /// Return the unique node id.
714   int getNodeId() const { return NodeId; }
715 
716   /// Set unique node id.
717   void setNodeId(int Id) { NodeId = Id; }
718 
719   /// Return the node ordering.
720   unsigned getIROrder() const { return IROrder; }
721 
722   /// Set the node ordering.
723   void setIROrder(unsigned Order) { IROrder = Order; }
724 
725   /// Return the source location info.
726   const DebugLoc &getDebugLoc() const { return debugLoc; }
727 
728   /// Set source location info.  Try to avoid this, putting
729   /// it in the constructor is preferable.
730   void setDebugLoc(DebugLoc dl) { debugLoc = std::move(dl); }
731 
732   /// This class provides iterator support for SDUse
733   /// operands that use a specific SDNode.
734   class use_iterator {
735     friend class SDNode;
736 
737     SDUse *Op = nullptr;
738 
739     explicit use_iterator(SDUse *op) : Op(op) {}
740 
741   public:
742     using iterator_category = std::forward_iterator_tag;
743     using value_type = SDUse;
744     using difference_type = std::ptrdiff_t;
745     using pointer = value_type *;
746     using reference = value_type &;
747 
748     use_iterator() = default;
749     use_iterator(const use_iterator &I) = default;
750 
751     bool operator==(const use_iterator &x) const { return Op == x.Op; }
752     bool operator!=(const use_iterator &x) const {
753       return !operator==(x);
754     }
755 
756     /// Return true if this iterator is at the end of uses list.
757     bool atEnd() const { return Op == nullptr; }
758 
759     // Iterator traversal: forward iteration only.
760     use_iterator &operator++() {          // Preincrement
761       assert(Op && "Cannot increment end iterator!");
762       Op = Op->getNext();
763       return *this;
764     }
765 
766     use_iterator operator++(int) {        // Postincrement
767       use_iterator tmp = *this; ++*this; return tmp;
768     }
769 
770     /// Retrieve a pointer to the current user node.
771     SDNode *operator*() const {
772       assert(Op && "Cannot dereference end iterator!");
773       return Op->getUser();
774     }
775 
776     SDNode *operator->() const { return operator*(); }
777 
778     SDUse &getUse() const { return *Op; }
779 
780     /// Retrieve the operand # of this use in its user.
781     unsigned getOperandNo() const {
782       assert(Op && "Cannot dereference end iterator!");
783       return (unsigned)(Op - Op->getUser()->OperandList);
784     }
785   };
786 
787   /// Provide iteration support to walk over all uses of an SDNode.
788   use_iterator use_begin() const {
789     return use_iterator(UseList);
790   }
791 
792   static use_iterator use_end() { return use_iterator(nullptr); }
793 
794   inline iterator_range<use_iterator> uses() {
795     return make_range(use_begin(), use_end());
796   }
797   inline iterator_range<use_iterator> uses() const {
798     return make_range(use_begin(), use_end());
799   }
800 
801   /// Return true if there are exactly NUSES uses of the indicated value.
802   /// This method ignores uses of other values defined by this operation.
803   bool hasNUsesOfValue(unsigned NUses, unsigned Value) const;
804 
805   /// Return true if there are any use of the indicated value.
806   /// This method ignores uses of other values defined by this operation.
807   bool hasAnyUseOfValue(unsigned Value) const;
808 
809   /// Return true if this node is the only use of N.
810   bool isOnlyUserOf(const SDNode *N) const;
811 
812   /// Return true if this node is an operand of N.
813   bool isOperandOf(const SDNode *N) const;
814 
815   /// Return true if this node is a predecessor of N.
816   /// NOTE: Implemented on top of hasPredecessor and every bit as
817   /// expensive. Use carefully.
818   bool isPredecessorOf(const SDNode *N) const {
819     return N->hasPredecessor(this);
820   }
821 
822   /// Return true if N is a predecessor of this node.
823   /// N is either an operand of this node, or can be reached by recursively
824   /// traversing up the operands.
825   /// NOTE: This is an expensive method. Use it carefully.
826   bool hasPredecessor(const SDNode *N) const;
827 
828   /// Returns true if N is a predecessor of any node in Worklist. This
829   /// helper keeps Visited and Worklist sets externally to allow unions
830   /// searches to be performed in parallel, caching of results across
831   /// queries and incremental addition to Worklist. Stops early if N is
832   /// found but will resume. Remember to clear Visited and Worklists
833   /// if DAG changes. MaxSteps gives a maximum number of nodes to visit before
834   /// giving up. The TopologicalPrune flag signals that positive NodeIds are
835   /// topologically ordered (Operands have strictly smaller node id) and search
836   /// can be pruned leveraging this.
837   static bool hasPredecessorHelper(const SDNode *N,
838                                    SmallPtrSetImpl<const SDNode *> &Visited,
839                                    SmallVectorImpl<const SDNode *> &Worklist,
840                                    unsigned int MaxSteps = 0,
841                                    bool TopologicalPrune = false) {
842     SmallVector<const SDNode *, 8> DeferredNodes;
843     if (Visited.count(N))
844       return true;
845 
846     // Node Id's are assigned in three places: As a topological
847     // ordering (> 0), during legalization (results in values set to
848     // 0), new nodes (set to -1). If N has a topolgical id then we
849     // know that all nodes with ids smaller than it cannot be
850     // successors and we need not check them. Filter out all node
851     // that can't be matches. We add them to the worklist before exit
852     // in case of multiple calls. Note that during selection the topological id
853     // may be violated if a node's predecessor is selected before it. We mark
854     // this at selection negating the id of unselected successors and
855     // restricting topological pruning to positive ids.
856 
857     int NId = N->getNodeId();
858     // If we Invalidated the Id, reconstruct original NId.
859     if (NId < -1)
860       NId = -(NId + 1);
861 
862     bool Found = false;
863     while (!Worklist.empty()) {
864       const SDNode *M = Worklist.pop_back_val();
865       int MId = M->getNodeId();
866       if (TopologicalPrune && M->getOpcode() != ISD::TokenFactor && (NId > 0) &&
867           (MId > 0) && (MId < NId)) {
868         DeferredNodes.push_back(M);
869         continue;
870       }
871       for (const SDValue &OpV : M->op_values()) {
872         SDNode *Op = OpV.getNode();
873         if (Visited.insert(Op).second)
874           Worklist.push_back(Op);
875         if (Op == N)
876           Found = true;
877       }
878       if (Found)
879         break;
880       if (MaxSteps != 0 && Visited.size() >= MaxSteps)
881         break;
882     }
883     // Push deferred nodes back on worklist.
884     Worklist.append(DeferredNodes.begin(), DeferredNodes.end());
885     // If we bailed early, conservatively return found.
886     if (MaxSteps != 0 && Visited.size() >= MaxSteps)
887       return true;
888     return Found;
889   }
890 
891   /// Return true if all the users of N are contained in Nodes.
892   /// NOTE: Requires at least one match, but doesn't require them all.
893   static bool areOnlyUsersOf(ArrayRef<const SDNode *> Nodes, const SDNode *N);
894 
895   /// Return the number of values used by this operation.
896   unsigned getNumOperands() const { return NumOperands; }
897 
898   /// Return the maximum number of operands that a SDNode can hold.
899   static constexpr size_t getMaxNumOperands() {
900     return std::numeric_limits<decltype(SDNode::NumOperands)>::max();
901   }
902 
903   /// Helper method returns the integer value of a ConstantSDNode operand.
904   inline uint64_t getConstantOperandVal(unsigned Num) const;
905 
906   /// Helper method returns the APInt of a ConstantSDNode operand.
907   inline const APInt &getConstantOperandAPInt(unsigned Num) const;
908 
909   const SDValue &getOperand(unsigned Num) const {
910     assert(Num < NumOperands && "Invalid child # of SDNode!");
911     return OperandList[Num];
912   }
913 
914   using op_iterator = SDUse *;
915 
916   op_iterator op_begin() const { return OperandList; }
917   op_iterator op_end() const { return OperandList+NumOperands; }
918   ArrayRef<SDUse> ops() const { return makeArrayRef(op_begin(), op_end()); }
919 
920   /// Iterator for directly iterating over the operand SDValue's.
921   struct value_op_iterator
922       : iterator_adaptor_base<value_op_iterator, op_iterator,
923                               std::random_access_iterator_tag, SDValue,
924                               ptrdiff_t, value_op_iterator *,
925                               value_op_iterator *> {
926     explicit value_op_iterator(SDUse *U = nullptr)
927       : iterator_adaptor_base(U) {}
928 
929     const SDValue &operator*() const { return I->get(); }
930   };
931 
932   iterator_range<value_op_iterator> op_values() const {
933     return make_range(value_op_iterator(op_begin()),
934                       value_op_iterator(op_end()));
935   }
936 
937   SDVTList getVTList() const {
938     SDVTList X = { ValueList, NumValues };
939     return X;
940   }
941 
942   /// If this node has a glue operand, return the node
943   /// to which the glue operand points. Otherwise return NULL.
944   SDNode *getGluedNode() const {
945     if (getNumOperands() != 0 &&
946         getOperand(getNumOperands()-1).getValueType() == MVT::Glue)
947       return getOperand(getNumOperands()-1).getNode();
948     return nullptr;
949   }
950 
951   /// If this node has a glue value with a user, return
952   /// the user (there is at most one). Otherwise return NULL.
953   SDNode *getGluedUser() const {
954     for (use_iterator UI = use_begin(), UE = use_end(); UI != UE; ++UI)
955       if (UI.getUse().get().getValueType() == MVT::Glue)
956         return *UI;
957     return nullptr;
958   }
959 
960   SDNodeFlags getFlags() const { return Flags; }
961   void setFlags(SDNodeFlags NewFlags) { Flags = NewFlags; }
962 
963   /// Clear any flags in this node that aren't also set in Flags.
964   /// If Flags is not in a defined state then this has no effect.
965   void intersectFlagsWith(const SDNodeFlags Flags);
966 
967   /// Return the number of values defined/returned by this operator.
968   unsigned getNumValues() const { return NumValues; }
969 
970   /// Return the type of a specified result.
971   EVT getValueType(unsigned ResNo) const {
972     assert(ResNo < NumValues && "Illegal result number!");
973     return ValueList[ResNo];
974   }
975 
976   /// Return the type of a specified result as a simple type.
977   MVT getSimpleValueType(unsigned ResNo) const {
978     return getValueType(ResNo).getSimpleVT();
979   }
980 
981   /// Returns MVT::getSizeInBits(getValueType(ResNo)).
982   ///
983   /// If the value type is a scalable vector type, the scalable property will
984   /// be set and the runtime size will be a positive integer multiple of the
985   /// base size.
986   TypeSize getValueSizeInBits(unsigned ResNo) const {
987     return getValueType(ResNo).getSizeInBits();
988   }
989 
990   using value_iterator = const EVT *;
991 
992   value_iterator value_begin() const { return ValueList; }
993   value_iterator value_end() const { return ValueList+NumValues; }
994   iterator_range<value_iterator> values() const {
995     return llvm::make_range(value_begin(), value_end());
996   }
997 
998   /// Return the opcode of this operation for printing.
999   std::string getOperationName(const SelectionDAG *G = nullptr) const;
1000   static const char* getIndexedModeName(ISD::MemIndexedMode AM);
1001   void print_types(raw_ostream &OS, const SelectionDAG *G) const;
1002   void print_details(raw_ostream &OS, const SelectionDAG *G) const;
1003   void print(raw_ostream &OS, const SelectionDAG *G = nullptr) const;
1004   void printr(raw_ostream &OS, const SelectionDAG *G = nullptr) const;
1005 
1006   /// Print a SelectionDAG node and all children down to
1007   /// the leaves.  The given SelectionDAG allows target-specific nodes
1008   /// to be printed in human-readable form.  Unlike printr, this will
1009   /// print the whole DAG, including children that appear multiple
1010   /// times.
1011   ///
1012   void printrFull(raw_ostream &O, const SelectionDAG *G = nullptr) const;
1013 
1014   /// Print a SelectionDAG node and children up to
1015   /// depth "depth."  The given SelectionDAG allows target-specific
1016   /// nodes to be printed in human-readable form.  Unlike printr, this
1017   /// will print children that appear multiple times wherever they are
1018   /// used.
1019   ///
1020   void printrWithDepth(raw_ostream &O, const SelectionDAG *G = nullptr,
1021                        unsigned depth = 100) const;
1022 
1023   /// Dump this node, for debugging.
1024   void dump() const;
1025 
1026   /// Dump (recursively) this node and its use-def subgraph.
1027   void dumpr() const;
1028 
1029   /// Dump this node, for debugging.
1030   /// The given SelectionDAG allows target-specific nodes to be printed
1031   /// in human-readable form.
1032   void dump(const SelectionDAG *G) const;
1033 
1034   /// Dump (recursively) this node and its use-def subgraph.
1035   /// The given SelectionDAG allows target-specific nodes to be printed
1036   /// in human-readable form.
1037   void dumpr(const SelectionDAG *G) const;
1038 
1039   /// printrFull to dbgs().  The given SelectionDAG allows
1040   /// target-specific nodes to be printed in human-readable form.
1041   /// Unlike dumpr, this will print the whole DAG, including children
1042   /// that appear multiple times.
1043   void dumprFull(const SelectionDAG *G = nullptr) const;
1044 
1045   /// printrWithDepth to dbgs().  The given
1046   /// SelectionDAG allows target-specific nodes to be printed in
1047   /// human-readable form.  Unlike dumpr, this will print children
1048   /// that appear multiple times wherever they are used.
1049   ///
1050   void dumprWithDepth(const SelectionDAG *G = nullptr,
1051                       unsigned depth = 100) const;
1052 
1053   /// Gather unique data for the node.
1054   void Profile(FoldingSetNodeID &ID) const;
1055 
1056   /// This method should only be used by the SDUse class.
1057   void addUse(SDUse &U) { U.addToList(&UseList); }
1058 
1059 protected:
1060   static SDVTList getSDVTList(EVT VT) {
1061     SDVTList Ret = { getValueTypeList(VT), 1 };
1062     return Ret;
1063   }
1064 
1065   /// Create an SDNode.
1066   ///
1067   /// SDNodes are created without any operands, and never own the operand
1068   /// storage. To add operands, see SelectionDAG::createOperands.
1069   SDNode(unsigned Opc, unsigned Order, DebugLoc dl, SDVTList VTs)
1070       : NodeType(Opc), ValueList(VTs.VTs), NumValues(VTs.NumVTs),
1071         IROrder(Order), debugLoc(std::move(dl)) {
1072     memset(&RawSDNodeBits, 0, sizeof(RawSDNodeBits));
1073     assert(debugLoc.hasTrivialDestructor() && "Expected trivial destructor");
1074     assert(NumValues == VTs.NumVTs &&
1075            "NumValues wasn't wide enough for its operands!");
1076   }
1077 
1078   /// Release the operands and set this node to have zero operands.
1079   void DropOperands();
1080 };
1081 
1082 /// Wrapper class for IR location info (IR ordering and DebugLoc) to be passed
1083 /// into SDNode creation functions.
1084 /// When an SDNode is created from the DAGBuilder, the DebugLoc is extracted
1085 /// from the original Instruction, and IROrder is the ordinal position of
1086 /// the instruction.
1087 /// When an SDNode is created after the DAG is being built, both DebugLoc and
1088 /// the IROrder are propagated from the original SDNode.
1089 /// So SDLoc class provides two constructors besides the default one, one to
1090 /// be used by the DAGBuilder, the other to be used by others.
1091 class SDLoc {
1092 private:
1093   DebugLoc DL;
1094   int IROrder = 0;
1095 
1096 public:
1097   SDLoc() = default;
1098   SDLoc(const SDNode *N) : DL(N->getDebugLoc()), IROrder(N->getIROrder()) {}
1099   SDLoc(const SDValue V) : SDLoc(V.getNode()) {}
1100   SDLoc(const Instruction *I, int Order) : IROrder(Order) {
1101     assert(Order >= 0 && "bad IROrder");
1102     if (I)
1103       DL = I->getDebugLoc();
1104   }
1105 
1106   unsigned getIROrder() const { return IROrder; }
1107   const DebugLoc &getDebugLoc() const { return DL; }
1108 };
1109 
1110 // Define inline functions from the SDValue class.
1111 
1112 inline SDValue::SDValue(SDNode *node, unsigned resno)
1113     : Node(node), ResNo(resno) {
1114   // Explicitly check for !ResNo to avoid use-after-free, because there are
1115   // callers that use SDValue(N, 0) with a deleted N to indicate successful
1116   // combines.
1117   assert((!Node || !ResNo || ResNo < Node->getNumValues()) &&
1118          "Invalid result number for the given node!");
1119   assert(ResNo < -2U && "Cannot use result numbers reserved for DenseMaps.");
1120 }
1121 
1122 inline unsigned SDValue::getOpcode() const {
1123   return Node->getOpcode();
1124 }
1125 
1126 inline EVT SDValue::getValueType() const {
1127   return Node->getValueType(ResNo);
1128 }
1129 
1130 inline unsigned SDValue::getNumOperands() const {
1131   return Node->getNumOperands();
1132 }
1133 
1134 inline const SDValue &SDValue::getOperand(unsigned i) const {
1135   return Node->getOperand(i);
1136 }
1137 
1138 inline uint64_t SDValue::getConstantOperandVal(unsigned i) const {
1139   return Node->getConstantOperandVal(i);
1140 }
1141 
1142 inline const APInt &SDValue::getConstantOperandAPInt(unsigned i) const {
1143   return Node->getConstantOperandAPInt(i);
1144 }
1145 
1146 inline bool SDValue::isTargetOpcode() const {
1147   return Node->isTargetOpcode();
1148 }
1149 
1150 inline bool SDValue::isTargetMemoryOpcode() const {
1151   return Node->isTargetMemoryOpcode();
1152 }
1153 
1154 inline bool SDValue::isMachineOpcode() const {
1155   return Node->isMachineOpcode();
1156 }
1157 
1158 inline unsigned SDValue::getMachineOpcode() const {
1159   return Node->getMachineOpcode();
1160 }
1161 
1162 inline bool SDValue::isUndef() const {
1163   return Node->isUndef();
1164 }
1165 
1166 inline bool SDValue::use_empty() const {
1167   return !Node->hasAnyUseOfValue(ResNo);
1168 }
1169 
1170 inline bool SDValue::hasOneUse() const {
1171   return Node->hasNUsesOfValue(1, ResNo);
1172 }
1173 
1174 inline const DebugLoc &SDValue::getDebugLoc() const {
1175   return Node->getDebugLoc();
1176 }
1177 
1178 inline void SDValue::dump() const {
1179   return Node->dump();
1180 }
1181 
1182 inline void SDValue::dump(const SelectionDAG *G) const {
1183   return Node->dump(G);
1184 }
1185 
1186 inline void SDValue::dumpr() const {
1187   return Node->dumpr();
1188 }
1189 
1190 inline void SDValue::dumpr(const SelectionDAG *G) const {
1191   return Node->dumpr(G);
1192 }
1193 
1194 // Define inline functions from the SDUse class.
1195 
1196 inline void SDUse::set(const SDValue &V) {
1197   if (Val.getNode()) removeFromList();
1198   Val = V;
1199   if (V.getNode())
1200     V->addUse(*this);
1201 }
1202 
1203 inline void SDUse::setInitial(const SDValue &V) {
1204   Val = V;
1205   V->addUse(*this);
1206 }
1207 
1208 inline void SDUse::setNode(SDNode *N) {
1209   if (Val.getNode()) removeFromList();
1210   Val.setNode(N);
1211   if (N) N->addUse(*this);
1212 }
1213 
1214 /// This class is used to form a handle around another node that
1215 /// is persistent and is updated across invocations of replaceAllUsesWith on its
1216 /// operand.  This node should be directly created by end-users and not added to
1217 /// the AllNodes list.
1218 class HandleSDNode : public SDNode {
1219   SDUse Op;
1220 
1221 public:
1222   explicit HandleSDNode(SDValue X)
1223     : SDNode(ISD::HANDLENODE, 0, DebugLoc(), getSDVTList(MVT::Other)) {
1224     // HandleSDNodes are never inserted into the DAG, so they won't be
1225     // auto-numbered. Use ID 65535 as a sentinel.
1226     PersistentId = 0xffff;
1227 
1228     // Manually set up the operand list. This node type is special in that it's
1229     // always stack allocated and SelectionDAG does not manage its operands.
1230     // TODO: This should either (a) not be in the SDNode hierarchy, or (b) not
1231     // be so special.
1232     Op.setUser(this);
1233     Op.setInitial(X);
1234     NumOperands = 1;
1235     OperandList = &Op;
1236   }
1237   ~HandleSDNode();
1238 
1239   const SDValue &getValue() const { return Op; }
1240 };
1241 
1242 class AddrSpaceCastSDNode : public SDNode {
1243 private:
1244   unsigned SrcAddrSpace;
1245   unsigned DestAddrSpace;
1246 
1247 public:
1248   AddrSpaceCastSDNode(unsigned Order, const DebugLoc &dl, EVT VT,
1249                       unsigned SrcAS, unsigned DestAS);
1250 
1251   unsigned getSrcAddressSpace() const { return SrcAddrSpace; }
1252   unsigned getDestAddressSpace() const { return DestAddrSpace; }
1253 
1254   static bool classof(const SDNode *N) {
1255     return N->getOpcode() == ISD::ADDRSPACECAST;
1256   }
1257 };
1258 
1259 /// This is an abstract virtual class for memory operations.
1260 class MemSDNode : public SDNode {
1261 private:
1262   // VT of in-memory value.
1263   EVT MemoryVT;
1264 
1265 protected:
1266   /// Memory reference information.
1267   MachineMemOperand *MMO;
1268 
1269 public:
1270   MemSDNode(unsigned Opc, unsigned Order, const DebugLoc &dl, SDVTList VTs,
1271             EVT memvt, MachineMemOperand *MMO);
1272 
1273   bool readMem() const { return MMO->isLoad(); }
1274   bool writeMem() const { return MMO->isStore(); }
1275 
1276   /// Returns alignment and volatility of the memory access
1277   Align getOriginalAlign() const { return MMO->getBaseAlign(); }
1278   Align getAlign() const { return MMO->getAlign(); }
1279   // FIXME: Remove once transition to getAlign is over.
1280   unsigned getAlignment() const { return MMO->getAlign().value(); }
1281 
1282   /// Return the SubclassData value, without HasDebugValue. This contains an
1283   /// encoding of the volatile flag, as well as bits used by subclasses. This
1284   /// function should only be used to compute a FoldingSetNodeID value.
1285   /// The HasDebugValue bit is masked out because CSE map needs to match
1286   /// nodes with debug info with nodes without debug info. Same is about
1287   /// isDivergent bit.
1288   unsigned getRawSubclassData() const {
1289     uint16_t Data;
1290     union {
1291       char RawSDNodeBits[sizeof(uint16_t)];
1292       SDNodeBitfields SDNodeBits;
1293     };
1294     memcpy(&RawSDNodeBits, &this->RawSDNodeBits, sizeof(this->RawSDNodeBits));
1295     SDNodeBits.HasDebugValue = 0;
1296     SDNodeBits.IsDivergent = false;
1297     memcpy(&Data, &RawSDNodeBits, sizeof(RawSDNodeBits));
1298     return Data;
1299   }
1300 
1301   bool isVolatile() const { return MemSDNodeBits.IsVolatile; }
1302   bool isNonTemporal() const { return MemSDNodeBits.IsNonTemporal; }
1303   bool isDereferenceable() const { return MemSDNodeBits.IsDereferenceable; }
1304   bool isInvariant() const { return MemSDNodeBits.IsInvariant; }
1305 
1306   // Returns the offset from the location of the access.
1307   int64_t getSrcValueOffset() const { return MMO->getOffset(); }
1308 
1309   /// Returns the AA info that describes the dereference.
1310   AAMDNodes getAAInfo() const { return MMO->getAAInfo(); }
1311 
1312   /// Returns the Ranges that describes the dereference.
1313   const MDNode *getRanges() const { return MMO->getRanges(); }
1314 
1315   /// Returns the synchronization scope ID for this memory operation.
1316   SyncScope::ID getSyncScopeID() const { return MMO->getSyncScopeID(); }
1317 
1318   /// Return the atomic ordering requirements for this memory operation. For
1319   /// cmpxchg atomic operations, return the atomic ordering requirements when
1320   /// store occurs.
1321   AtomicOrdering getSuccessOrdering() const {
1322     return MMO->getSuccessOrdering();
1323   }
1324 
1325   /// Return a single atomic ordering that is at least as strong as both the
1326   /// success and failure orderings for an atomic operation.  (For operations
1327   /// other than cmpxchg, this is equivalent to getSuccessOrdering().)
1328   AtomicOrdering getMergedOrdering() const { return MMO->getMergedOrdering(); }
1329 
1330   /// Return true if the memory operation ordering is Unordered or higher.
1331   bool isAtomic() const { return MMO->isAtomic(); }
1332 
1333   /// Returns true if the memory operation doesn't imply any ordering
1334   /// constraints on surrounding memory operations beyond the normal memory
1335   /// aliasing rules.
1336   bool isUnordered() const { return MMO->isUnordered(); }
1337 
1338   /// Returns true if the memory operation is neither atomic or volatile.
1339   bool isSimple() const { return !isAtomic() && !isVolatile(); }
1340 
1341   /// Return the type of the in-memory value.
1342   EVT getMemoryVT() const { return MemoryVT; }
1343 
1344   /// Return a MachineMemOperand object describing the memory
1345   /// reference performed by operation.
1346   MachineMemOperand *getMemOperand() const { return MMO; }
1347 
1348   const MachinePointerInfo &getPointerInfo() const {
1349     return MMO->getPointerInfo();
1350   }
1351 
1352   /// Return the address space for the associated pointer
1353   unsigned getAddressSpace() const {
1354     return getPointerInfo().getAddrSpace();
1355   }
1356 
1357   /// Update this MemSDNode's MachineMemOperand information
1358   /// to reflect the alignment of NewMMO, if it has a greater alignment.
1359   /// This must only be used when the new alignment applies to all users of
1360   /// this MachineMemOperand.
1361   void refineAlignment(const MachineMemOperand *NewMMO) {
1362     MMO->refineAlignment(NewMMO);
1363   }
1364 
1365   const SDValue &getChain() const { return getOperand(0); }
1366 
1367   const SDValue &getBasePtr() const {
1368     switch (getOpcode()) {
1369     case ISD::STORE:
1370     case ISD::VP_STORE:
1371     case ISD::MSTORE:
1372     case ISD::VP_SCATTER:
1373     case ISD::EXPERIMENTAL_VP_STRIDED_STORE:
1374       return getOperand(2);
1375     case ISD::MGATHER:
1376     case ISD::MSCATTER:
1377       return getOperand(3);
1378     default:
1379       return getOperand(1);
1380     }
1381   }
1382 
1383   // Methods to support isa and dyn_cast
1384   static bool classof(const SDNode *N) {
1385     // For some targets, we lower some target intrinsics to a MemIntrinsicNode
1386     // with either an intrinsic or a target opcode.
1387     switch (N->getOpcode()) {
1388     case ISD::LOAD:
1389     case ISD::STORE:
1390     case ISD::PREFETCH:
1391     case ISD::ATOMIC_CMP_SWAP:
1392     case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
1393     case ISD::ATOMIC_SWAP:
1394     case ISD::ATOMIC_LOAD_ADD:
1395     case ISD::ATOMIC_LOAD_SUB:
1396     case ISD::ATOMIC_LOAD_AND:
1397     case ISD::ATOMIC_LOAD_CLR:
1398     case ISD::ATOMIC_LOAD_OR:
1399     case ISD::ATOMIC_LOAD_XOR:
1400     case ISD::ATOMIC_LOAD_NAND:
1401     case ISD::ATOMIC_LOAD_MIN:
1402     case ISD::ATOMIC_LOAD_MAX:
1403     case ISD::ATOMIC_LOAD_UMIN:
1404     case ISD::ATOMIC_LOAD_UMAX:
1405     case ISD::ATOMIC_LOAD_FADD:
1406     case ISD::ATOMIC_LOAD_FSUB:
1407     case ISD::ATOMIC_LOAD_FMAX:
1408     case ISD::ATOMIC_LOAD_FMIN:
1409     case ISD::ATOMIC_LOAD:
1410     case ISD::ATOMIC_STORE:
1411     case ISD::MLOAD:
1412     case ISD::MSTORE:
1413     case ISD::MGATHER:
1414     case ISD::MSCATTER:
1415     case ISD::VP_LOAD:
1416     case ISD::VP_STORE:
1417     case ISD::VP_GATHER:
1418     case ISD::VP_SCATTER:
1419     case ISD::EXPERIMENTAL_VP_STRIDED_LOAD:
1420     case ISD::EXPERIMENTAL_VP_STRIDED_STORE:
1421       return true;
1422     default:
1423       return N->isMemIntrinsic() || N->isTargetMemoryOpcode();
1424     }
1425   }
1426 };
1427 
1428 /// This is an SDNode representing atomic operations.
1429 class AtomicSDNode : public MemSDNode {
1430 public:
1431   AtomicSDNode(unsigned Opc, unsigned Order, const DebugLoc &dl, SDVTList VTL,
1432                EVT MemVT, MachineMemOperand *MMO)
1433     : MemSDNode(Opc, Order, dl, VTL, MemVT, MMO) {
1434     assert(((Opc != ISD::ATOMIC_LOAD && Opc != ISD::ATOMIC_STORE) ||
1435             MMO->isAtomic()) && "then why are we using an AtomicSDNode?");
1436   }
1437 
1438   const SDValue &getBasePtr() const { return getOperand(1); }
1439   const SDValue &getVal() const { return getOperand(2); }
1440 
1441   /// Returns true if this SDNode represents cmpxchg atomic operation, false
1442   /// otherwise.
1443   bool isCompareAndSwap() const {
1444     unsigned Op = getOpcode();
1445     return Op == ISD::ATOMIC_CMP_SWAP ||
1446            Op == ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS;
1447   }
1448 
1449   /// For cmpxchg atomic operations, return the atomic ordering requirements
1450   /// when store does not occur.
1451   AtomicOrdering getFailureOrdering() const {
1452     assert(isCompareAndSwap() && "Must be cmpxchg operation");
1453     return MMO->getFailureOrdering();
1454   }
1455 
1456   // Methods to support isa and dyn_cast
1457   static bool classof(const SDNode *N) {
1458     return N->getOpcode() == ISD::ATOMIC_CMP_SWAP     ||
1459            N->getOpcode() == ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS ||
1460            N->getOpcode() == ISD::ATOMIC_SWAP         ||
1461            N->getOpcode() == ISD::ATOMIC_LOAD_ADD     ||
1462            N->getOpcode() == ISD::ATOMIC_LOAD_SUB     ||
1463            N->getOpcode() == ISD::ATOMIC_LOAD_AND     ||
1464            N->getOpcode() == ISD::ATOMIC_LOAD_CLR     ||
1465            N->getOpcode() == ISD::ATOMIC_LOAD_OR      ||
1466            N->getOpcode() == ISD::ATOMIC_LOAD_XOR     ||
1467            N->getOpcode() == ISD::ATOMIC_LOAD_NAND    ||
1468            N->getOpcode() == ISD::ATOMIC_LOAD_MIN     ||
1469            N->getOpcode() == ISD::ATOMIC_LOAD_MAX     ||
1470            N->getOpcode() == ISD::ATOMIC_LOAD_UMIN    ||
1471            N->getOpcode() == ISD::ATOMIC_LOAD_UMAX    ||
1472            N->getOpcode() == ISD::ATOMIC_LOAD_FADD    ||
1473            N->getOpcode() == ISD::ATOMIC_LOAD_FSUB    ||
1474            N->getOpcode() == ISD::ATOMIC_LOAD_FMAX    ||
1475            N->getOpcode() == ISD::ATOMIC_LOAD_FMIN    ||
1476            N->getOpcode() == ISD::ATOMIC_LOAD         ||
1477            N->getOpcode() == ISD::ATOMIC_STORE;
1478   }
1479 };
1480 
1481 /// This SDNode is used for target intrinsics that touch
1482 /// memory and need an associated MachineMemOperand. Its opcode may be
1483 /// INTRINSIC_VOID, INTRINSIC_W_CHAIN, PREFETCH, or a target-specific opcode
1484 /// with a value not less than FIRST_TARGET_MEMORY_OPCODE.
1485 class MemIntrinsicSDNode : public MemSDNode {
1486 public:
1487   MemIntrinsicSDNode(unsigned Opc, unsigned Order, const DebugLoc &dl,
1488                      SDVTList VTs, EVT MemoryVT, MachineMemOperand *MMO)
1489       : MemSDNode(Opc, Order, dl, VTs, MemoryVT, MMO) {
1490     SDNodeBits.IsMemIntrinsic = true;
1491   }
1492 
1493   // Methods to support isa and dyn_cast
1494   static bool classof(const SDNode *N) {
1495     // We lower some target intrinsics to their target opcode
1496     // early a node with a target opcode can be of this class
1497     return N->isMemIntrinsic()             ||
1498            N->getOpcode() == ISD::PREFETCH ||
1499            N->isTargetMemoryOpcode();
1500   }
1501 };
1502 
1503 /// This SDNode is used to implement the code generator
1504 /// support for the llvm IR shufflevector instruction.  It combines elements
1505 /// from two input vectors into a new input vector, with the selection and
1506 /// ordering of elements determined by an array of integers, referred to as
1507 /// the shuffle mask.  For input vectors of width N, mask indices of 0..N-1
1508 /// refer to elements from the LHS input, and indices from N to 2N-1 the RHS.
1509 /// An index of -1 is treated as undef, such that the code generator may put
1510 /// any value in the corresponding element of the result.
1511 class ShuffleVectorSDNode : public SDNode {
1512   // The memory for Mask is owned by the SelectionDAG's OperandAllocator, and
1513   // is freed when the SelectionDAG object is destroyed.
1514   const int *Mask;
1515 
1516 protected:
1517   friend class SelectionDAG;
1518 
1519   ShuffleVectorSDNode(EVT VT, unsigned Order, const DebugLoc &dl, const int *M)
1520       : SDNode(ISD::VECTOR_SHUFFLE, Order, dl, getSDVTList(VT)), Mask(M) {}
1521 
1522 public:
1523   ArrayRef<int> getMask() const {
1524     EVT VT = getValueType(0);
1525     return makeArrayRef(Mask, VT.getVectorNumElements());
1526   }
1527 
1528   int getMaskElt(unsigned Idx) const {
1529     assert(Idx < getValueType(0).getVectorNumElements() && "Idx out of range!");
1530     return Mask[Idx];
1531   }
1532 
1533   bool isSplat() const { return isSplatMask(Mask, getValueType(0)); }
1534 
1535   int getSplatIndex() const {
1536     assert(isSplat() && "Cannot get splat index for non-splat!");
1537     EVT VT = getValueType(0);
1538     for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
1539       if (Mask[i] >= 0)
1540         return Mask[i];
1541 
1542     // We can choose any index value here and be correct because all elements
1543     // are undefined. Return 0 for better potential for callers to simplify.
1544     return 0;
1545   }
1546 
1547   static bool isSplatMask(const int *Mask, EVT VT);
1548 
1549   /// Change values in a shuffle permute mask assuming
1550   /// the two vector operands have swapped position.
1551   static void commuteMask(MutableArrayRef<int> Mask) {
1552     unsigned NumElems = Mask.size();
1553     for (unsigned i = 0; i != NumElems; ++i) {
1554       int idx = Mask[i];
1555       if (idx < 0)
1556         continue;
1557       else if (idx < (int)NumElems)
1558         Mask[i] = idx + NumElems;
1559       else
1560         Mask[i] = idx - NumElems;
1561     }
1562   }
1563 
1564   static bool classof(const SDNode *N) {
1565     return N->getOpcode() == ISD::VECTOR_SHUFFLE;
1566   }
1567 };
1568 
1569 class ConstantSDNode : public SDNode {
1570   friend class SelectionDAG;
1571 
1572   const ConstantInt *Value;
1573 
1574   ConstantSDNode(bool isTarget, bool isOpaque, const ConstantInt *val, EVT VT)
1575       : SDNode(isTarget ? ISD::TargetConstant : ISD::Constant, 0, DebugLoc(),
1576                getSDVTList(VT)),
1577         Value(val) {
1578     ConstantSDNodeBits.IsOpaque = isOpaque;
1579   }
1580 
1581 public:
1582   const ConstantInt *getConstantIntValue() const { return Value; }
1583   const APInt &getAPIntValue() const { return Value->getValue(); }
1584   uint64_t getZExtValue() const { return Value->getZExtValue(); }
1585   int64_t getSExtValue() const { return Value->getSExtValue(); }
1586   uint64_t getLimitedValue(uint64_t Limit = UINT64_MAX) {
1587     return Value->getLimitedValue(Limit);
1588   }
1589   MaybeAlign getMaybeAlignValue() const { return Value->getMaybeAlignValue(); }
1590   Align getAlignValue() const { return Value->getAlignValue(); }
1591 
1592   bool isOne() const { return Value->isOne(); }
1593   bool isZero() const { return Value->isZero(); }
1594   // NOTE: This is soft-deprecated.  Please use `isZero()` instead.
1595   bool isNullValue() const { return isZero(); }
1596   bool isAllOnes() const { return Value->isMinusOne(); }
1597   // NOTE: This is soft-deprecated.  Please use `isAllOnes()` instead.
1598   bool isAllOnesValue() const { return isAllOnes(); }
1599   bool isMaxSignedValue() const { return Value->isMaxValue(true); }
1600   bool isMinSignedValue() const { return Value->isMinValue(true); }
1601 
1602   bool isOpaque() const { return ConstantSDNodeBits.IsOpaque; }
1603 
1604   static bool classof(const SDNode *N) {
1605     return N->getOpcode() == ISD::Constant ||
1606            N->getOpcode() == ISD::TargetConstant;
1607   }
1608 };
1609 
1610 uint64_t SDNode::getConstantOperandVal(unsigned Num) const {
1611   return cast<ConstantSDNode>(getOperand(Num))->getZExtValue();
1612 }
1613 
1614 const APInt &SDNode::getConstantOperandAPInt(unsigned Num) const {
1615   return cast<ConstantSDNode>(getOperand(Num))->getAPIntValue();
1616 }
1617 
1618 class ConstantFPSDNode : public SDNode {
1619   friend class SelectionDAG;
1620 
1621   const ConstantFP *Value;
1622 
1623   ConstantFPSDNode(bool isTarget, const ConstantFP *val, EVT VT)
1624       : SDNode(isTarget ? ISD::TargetConstantFP : ISD::ConstantFP, 0,
1625                DebugLoc(), getSDVTList(VT)),
1626         Value(val) {}
1627 
1628 public:
1629   const APFloat& getValueAPF() const { return Value->getValueAPF(); }
1630   const ConstantFP *getConstantFPValue() const { return Value; }
1631 
1632   /// Return true if the value is positive or negative zero.
1633   bool isZero() const { return Value->isZero(); }
1634 
1635   /// Return true if the value is a NaN.
1636   bool isNaN() const { return Value->isNaN(); }
1637 
1638   /// Return true if the value is an infinity
1639   bool isInfinity() const { return Value->isInfinity(); }
1640 
1641   /// Return true if the value is negative.
1642   bool isNegative() const { return Value->isNegative(); }
1643 
1644   /// We don't rely on operator== working on double values, as
1645   /// it returns true for things that are clearly not equal, like -0.0 and 0.0.
1646   /// As such, this method can be used to do an exact bit-for-bit comparison of
1647   /// two floating point values.
1648 
1649   /// We leave the version with the double argument here because it's just so
1650   /// convenient to write "2.0" and the like.  Without this function we'd
1651   /// have to duplicate its logic everywhere it's called.
1652   bool isExactlyValue(double V) const {
1653     return Value->getValueAPF().isExactlyValue(V);
1654   }
1655   bool isExactlyValue(const APFloat& V) const;
1656 
1657   static bool isValueValidForType(EVT VT, const APFloat& Val);
1658 
1659   static bool classof(const SDNode *N) {
1660     return N->getOpcode() == ISD::ConstantFP ||
1661            N->getOpcode() == ISD::TargetConstantFP;
1662   }
1663 };
1664 
1665 /// Returns true if \p V is a constant integer zero.
1666 bool isNullConstant(SDValue V);
1667 
1668 /// Returns true if \p V is an FP constant with a value of positive zero.
1669 bool isNullFPConstant(SDValue V);
1670 
1671 /// Returns true if \p V is an integer constant with all bits set.
1672 bool isAllOnesConstant(SDValue V);
1673 
1674 /// Returns true if \p V is a constant integer one.
1675 bool isOneConstant(SDValue V);
1676 
1677 /// Returns true if \p V is a constant min signed integer value.
1678 bool isMinSignedConstant(SDValue V);
1679 
1680 /// Return the non-bitcasted source operand of \p V if it exists.
1681 /// If \p V is not a bitcasted value, it is returned as-is.
1682 SDValue peekThroughBitcasts(SDValue V);
1683 
1684 /// Return the non-bitcasted and one-use source operand of \p V if it exists.
1685 /// If \p V is not a bitcasted one-use value, it is returned as-is.
1686 SDValue peekThroughOneUseBitcasts(SDValue V);
1687 
1688 /// Return the non-extracted vector source operand of \p V if it exists.
1689 /// If \p V is not an extracted subvector, it is returned as-is.
1690 SDValue peekThroughExtractSubvectors(SDValue V);
1691 
1692 /// Returns true if \p V is a bitwise not operation. Assumes that an all ones
1693 /// constant is canonicalized to be operand 1.
1694 bool isBitwiseNot(SDValue V, bool AllowUndefs = false);
1695 
1696 /// If \p V is a bitwise not, returns the inverted operand. Otherwise returns
1697 /// an empty SDValue. Only bits set in \p Mask are required to be inverted,
1698 /// other bits may be arbitrary.
1699 SDValue getBitwiseNotOperand(SDValue V, SDValue Mask, bool AllowUndefs);
1700 
1701 /// Returns the SDNode if it is a constant splat BuildVector or constant int.
1702 ConstantSDNode *isConstOrConstSplat(SDValue N, bool AllowUndefs = false,
1703                                     bool AllowTruncation = false);
1704 
1705 /// Returns the SDNode if it is a demanded constant splat BuildVector or
1706 /// constant int.
1707 ConstantSDNode *isConstOrConstSplat(SDValue N, const APInt &DemandedElts,
1708                                     bool AllowUndefs = false,
1709                                     bool AllowTruncation = false);
1710 
1711 /// Returns the SDNode if it is a constant splat BuildVector or constant float.
1712 ConstantFPSDNode *isConstOrConstSplatFP(SDValue N, bool AllowUndefs = false);
1713 
1714 /// Returns the SDNode if it is a demanded constant splat BuildVector or
1715 /// constant float.
1716 ConstantFPSDNode *isConstOrConstSplatFP(SDValue N, const APInt &DemandedElts,
1717                                         bool AllowUndefs = false);
1718 
1719 /// Return true if the value is a constant 0 integer or a splatted vector of
1720 /// a constant 0 integer (with no undefs by default).
1721 /// Build vector implicit truncation is not an issue for null values.
1722 bool isNullOrNullSplat(SDValue V, bool AllowUndefs = false);
1723 
1724 /// Return true if the value is a constant 1 integer or a splatted vector of a
1725 /// constant 1 integer (with no undefs).
1726 /// Does not permit build vector implicit truncation.
1727 bool isOneOrOneSplat(SDValue V, bool AllowUndefs = false);
1728 
1729 /// Return true if the value is a constant -1 integer or a splatted vector of a
1730 /// constant -1 integer (with no undefs).
1731 /// Does not permit build vector implicit truncation.
1732 bool isAllOnesOrAllOnesSplat(SDValue V, bool AllowUndefs = false);
1733 
1734 /// Return true if \p V is either a integer or FP constant.
1735 inline bool isIntOrFPConstant(SDValue V) {
1736   return isa<ConstantSDNode>(V) || isa<ConstantFPSDNode>(V);
1737 }
1738 
1739 class GlobalAddressSDNode : public SDNode {
1740   friend class SelectionDAG;
1741 
1742   const GlobalValue *TheGlobal;
1743   int64_t Offset;
1744   unsigned TargetFlags;
1745 
1746   GlobalAddressSDNode(unsigned Opc, unsigned Order, const DebugLoc &DL,
1747                       const GlobalValue *GA, EVT VT, int64_t o,
1748                       unsigned TF);
1749 
1750 public:
1751   const GlobalValue *getGlobal() const { return TheGlobal; }
1752   int64_t getOffset() const { return Offset; }
1753   unsigned getTargetFlags() const { return TargetFlags; }
1754   // Return the address space this GlobalAddress belongs to.
1755   unsigned getAddressSpace() const;
1756 
1757   static bool classof(const SDNode *N) {
1758     return N->getOpcode() == ISD::GlobalAddress ||
1759            N->getOpcode() == ISD::TargetGlobalAddress ||
1760            N->getOpcode() == ISD::GlobalTLSAddress ||
1761            N->getOpcode() == ISD::TargetGlobalTLSAddress;
1762   }
1763 };
1764 
1765 class FrameIndexSDNode : public SDNode {
1766   friend class SelectionDAG;
1767 
1768   int FI;
1769 
1770   FrameIndexSDNode(int fi, EVT VT, bool isTarg)
1771     : SDNode(isTarg ? ISD::TargetFrameIndex : ISD::FrameIndex,
1772       0, DebugLoc(), getSDVTList(VT)), FI(fi) {
1773   }
1774 
1775 public:
1776   int getIndex() const { return FI; }
1777 
1778   static bool classof(const SDNode *N) {
1779     return N->getOpcode() == ISD::FrameIndex ||
1780            N->getOpcode() == ISD::TargetFrameIndex;
1781   }
1782 };
1783 
1784 /// This SDNode is used for LIFETIME_START/LIFETIME_END values, which indicate
1785 /// the offet and size that are started/ended in the underlying FrameIndex.
1786 class LifetimeSDNode : public SDNode {
1787   friend class SelectionDAG;
1788   int64_t Size;
1789   int64_t Offset; // -1 if offset is unknown.
1790 
1791   LifetimeSDNode(unsigned Opcode, unsigned Order, const DebugLoc &dl,
1792                  SDVTList VTs, int64_t Size, int64_t Offset)
1793       : SDNode(Opcode, Order, dl, VTs), Size(Size), Offset(Offset) {}
1794 public:
1795   int64_t getFrameIndex() const {
1796     return cast<FrameIndexSDNode>(getOperand(1))->getIndex();
1797   }
1798 
1799   bool hasOffset() const { return Offset >= 0; }
1800   int64_t getOffset() const {
1801     assert(hasOffset() && "offset is unknown");
1802     return Offset;
1803   }
1804   int64_t getSize() const {
1805     assert(hasOffset() && "offset is unknown");
1806     return Size;
1807   }
1808 
1809   // Methods to support isa and dyn_cast
1810   static bool classof(const SDNode *N) {
1811     return N->getOpcode() == ISD::LIFETIME_START ||
1812            N->getOpcode() == ISD::LIFETIME_END;
1813   }
1814 };
1815 
1816 /// This SDNode is used for PSEUDO_PROBE values, which are the function guid and
1817 /// the index of the basic block being probed. A pseudo probe serves as a place
1818 /// holder and will be removed at the end of compilation. It does not have any
1819 /// operand because we do not want the instruction selection to deal with any.
1820 class PseudoProbeSDNode : public SDNode {
1821   friend class SelectionDAG;
1822   uint64_t Guid;
1823   uint64_t Index;
1824   uint32_t Attributes;
1825 
1826   PseudoProbeSDNode(unsigned Opcode, unsigned Order, const DebugLoc &Dl,
1827                     SDVTList VTs, uint64_t Guid, uint64_t Index, uint32_t Attr)
1828       : SDNode(Opcode, Order, Dl, VTs), Guid(Guid), Index(Index),
1829         Attributes(Attr) {}
1830 
1831 public:
1832   uint64_t getGuid() const { return Guid; }
1833   uint64_t getIndex() const { return Index; }
1834   uint32_t getAttributes() const { return Attributes; }
1835 
1836   // Methods to support isa and dyn_cast
1837   static bool classof(const SDNode *N) {
1838     return N->getOpcode() == ISD::PSEUDO_PROBE;
1839   }
1840 };
1841 
1842 class JumpTableSDNode : public SDNode {
1843   friend class SelectionDAG;
1844 
1845   int JTI;
1846   unsigned TargetFlags;
1847 
1848   JumpTableSDNode(int jti, EVT VT, bool isTarg, unsigned TF)
1849     : SDNode(isTarg ? ISD::TargetJumpTable : ISD::JumpTable,
1850       0, DebugLoc(), getSDVTList(VT)), JTI(jti), TargetFlags(TF) {
1851   }
1852 
1853 public:
1854   int getIndex() const { return JTI; }
1855   unsigned getTargetFlags() const { return TargetFlags; }
1856 
1857   static bool classof(const SDNode *N) {
1858     return N->getOpcode() == ISD::JumpTable ||
1859            N->getOpcode() == ISD::TargetJumpTable;
1860   }
1861 };
1862 
1863 class ConstantPoolSDNode : public SDNode {
1864   friend class SelectionDAG;
1865 
1866   union {
1867     const Constant *ConstVal;
1868     MachineConstantPoolValue *MachineCPVal;
1869   } Val;
1870   int Offset;  // It's a MachineConstantPoolValue if top bit is set.
1871   Align Alignment; // Minimum alignment requirement of CP.
1872   unsigned TargetFlags;
1873 
1874   ConstantPoolSDNode(bool isTarget, const Constant *c, EVT VT, int o,
1875                      Align Alignment, unsigned TF)
1876       : SDNode(isTarget ? ISD::TargetConstantPool : ISD::ConstantPool, 0,
1877                DebugLoc(), getSDVTList(VT)),
1878         Offset(o), Alignment(Alignment), TargetFlags(TF) {
1879     assert(Offset >= 0 && "Offset is too large");
1880     Val.ConstVal = c;
1881   }
1882 
1883   ConstantPoolSDNode(bool isTarget, MachineConstantPoolValue *v, EVT VT, int o,
1884                      Align Alignment, unsigned TF)
1885       : SDNode(isTarget ? ISD::TargetConstantPool : ISD::ConstantPool, 0,
1886                DebugLoc(), getSDVTList(VT)),
1887         Offset(o), Alignment(Alignment), TargetFlags(TF) {
1888     assert(Offset >= 0 && "Offset is too large");
1889     Val.MachineCPVal = v;
1890     Offset |= 1 << (sizeof(unsigned)*CHAR_BIT-1);
1891   }
1892 
1893 public:
1894   bool isMachineConstantPoolEntry() const {
1895     return Offset < 0;
1896   }
1897 
1898   const Constant *getConstVal() const {
1899     assert(!isMachineConstantPoolEntry() && "Wrong constantpool type");
1900     return Val.ConstVal;
1901   }
1902 
1903   MachineConstantPoolValue *getMachineCPVal() const {
1904     assert(isMachineConstantPoolEntry() && "Wrong constantpool type");
1905     return Val.MachineCPVal;
1906   }
1907 
1908   int getOffset() const {
1909     return Offset & ~(1 << (sizeof(unsigned)*CHAR_BIT-1));
1910   }
1911 
1912   // Return the alignment of this constant pool object, which is either 0 (for
1913   // default alignment) or the desired value.
1914   Align getAlign() const { return Alignment; }
1915   unsigned getTargetFlags() const { return TargetFlags; }
1916 
1917   Type *getType() const;
1918 
1919   static bool classof(const SDNode *N) {
1920     return N->getOpcode() == ISD::ConstantPool ||
1921            N->getOpcode() == ISD::TargetConstantPool;
1922   }
1923 };
1924 
1925 /// Completely target-dependent object reference.
1926 class TargetIndexSDNode : public SDNode {
1927   friend class SelectionDAG;
1928 
1929   unsigned TargetFlags;
1930   int Index;
1931   int64_t Offset;
1932 
1933 public:
1934   TargetIndexSDNode(int Idx, EVT VT, int64_t Ofs, unsigned TF)
1935       : SDNode(ISD::TargetIndex, 0, DebugLoc(), getSDVTList(VT)),
1936         TargetFlags(TF), Index(Idx), Offset(Ofs) {}
1937 
1938   unsigned getTargetFlags() const { return TargetFlags; }
1939   int getIndex() const { return Index; }
1940   int64_t getOffset() const { return Offset; }
1941 
1942   static bool classof(const SDNode *N) {
1943     return N->getOpcode() == ISD::TargetIndex;
1944   }
1945 };
1946 
1947 class BasicBlockSDNode : public SDNode {
1948   friend class SelectionDAG;
1949 
1950   MachineBasicBlock *MBB;
1951 
1952   /// Debug info is meaningful and potentially useful here, but we create
1953   /// blocks out of order when they're jumped to, which makes it a bit
1954   /// harder.  Let's see if we need it first.
1955   explicit BasicBlockSDNode(MachineBasicBlock *mbb)
1956     : SDNode(ISD::BasicBlock, 0, DebugLoc(), getSDVTList(MVT::Other)), MBB(mbb)
1957   {}
1958 
1959 public:
1960   MachineBasicBlock *getBasicBlock() const { return MBB; }
1961 
1962   static bool classof(const SDNode *N) {
1963     return N->getOpcode() == ISD::BasicBlock;
1964   }
1965 };
1966 
1967 /// A "pseudo-class" with methods for operating on BUILD_VECTORs.
1968 class BuildVectorSDNode : public SDNode {
1969 public:
1970   // These are constructed as SDNodes and then cast to BuildVectorSDNodes.
1971   explicit BuildVectorSDNode() = delete;
1972 
1973   /// Check if this is a constant splat, and if so, find the
1974   /// smallest element size that splats the vector.  If MinSplatBits is
1975   /// nonzero, the element size must be at least that large.  Note that the
1976   /// splat element may be the entire vector (i.e., a one element vector).
1977   /// Returns the splat element value in SplatValue.  Any undefined bits in
1978   /// that value are zero, and the corresponding bits in the SplatUndef mask
1979   /// are set.  The SplatBitSize value is set to the splat element size in
1980   /// bits.  HasAnyUndefs is set to true if any bits in the vector are
1981   /// undefined.  isBigEndian describes the endianness of the target.
1982   bool isConstantSplat(APInt &SplatValue, APInt &SplatUndef,
1983                        unsigned &SplatBitSize, bool &HasAnyUndefs,
1984                        unsigned MinSplatBits = 0,
1985                        bool isBigEndian = false) const;
1986 
1987   /// Returns the demanded splatted value or a null value if this is not a
1988   /// splat.
1989   ///
1990   /// The DemandedElts mask indicates the elements that must be in the splat.
1991   /// If passed a non-null UndefElements bitvector, it will resize it to match
1992   /// the vector width and set the bits where elements are undef.
1993   SDValue getSplatValue(const APInt &DemandedElts,
1994                         BitVector *UndefElements = nullptr) const;
1995 
1996   /// Returns the splatted value or a null value if this is not a splat.
1997   ///
1998   /// If passed a non-null UndefElements bitvector, it will resize it to match
1999   /// the vector width and set the bits where elements are undef.
2000   SDValue getSplatValue(BitVector *UndefElements = nullptr) const;
2001 
2002   /// Find the shortest repeating sequence of values in the build vector.
2003   ///
2004   /// e.g. { u, X, u, X, u, u, X, u } -> { X }
2005   ///      { X, Y, u, Y, u, u, X, u } -> { X, Y }
2006   ///
2007   /// Currently this must be a power-of-2 build vector.
2008   /// The DemandedElts mask indicates the elements that must be present,
2009   /// undemanded elements in Sequence may be null (SDValue()). If passed a
2010   /// non-null UndefElements bitvector, it will resize it to match the original
2011   /// vector width and set the bits where elements are undef. If result is
2012   /// false, Sequence will be empty.
2013   bool getRepeatedSequence(const APInt &DemandedElts,
2014                            SmallVectorImpl<SDValue> &Sequence,
2015                            BitVector *UndefElements = nullptr) const;
2016 
2017   /// Find the shortest repeating sequence of values in the build vector.
2018   ///
2019   /// e.g. { u, X, u, X, u, u, X, u } -> { X }
2020   ///      { X, Y, u, Y, u, u, X, u } -> { X, Y }
2021   ///
2022   /// Currently this must be a power-of-2 build vector.
2023   /// If passed a non-null UndefElements bitvector, it will resize it to match
2024   /// the original vector width and set the bits where elements are undef.
2025   /// If result is false, Sequence will be empty.
2026   bool getRepeatedSequence(SmallVectorImpl<SDValue> &Sequence,
2027                            BitVector *UndefElements = nullptr) const;
2028 
2029   /// Returns the demanded splatted constant or null if this is not a constant
2030   /// splat.
2031   ///
2032   /// The DemandedElts mask indicates the elements that must be in the splat.
2033   /// If passed a non-null UndefElements bitvector, it will resize it to match
2034   /// the vector width and set the bits where elements are undef.
2035   ConstantSDNode *
2036   getConstantSplatNode(const APInt &DemandedElts,
2037                        BitVector *UndefElements = nullptr) const;
2038 
2039   /// Returns the splatted constant or null if this is not a constant
2040   /// splat.
2041   ///
2042   /// If passed a non-null UndefElements bitvector, it will resize it to match
2043   /// the vector width and set the bits where elements are undef.
2044   ConstantSDNode *
2045   getConstantSplatNode(BitVector *UndefElements = nullptr) const;
2046 
2047   /// Returns the demanded splatted constant FP or null if this is not a
2048   /// constant FP splat.
2049   ///
2050   /// The DemandedElts mask indicates the elements that must be in the splat.
2051   /// If passed a non-null UndefElements bitvector, it will resize it to match
2052   /// the vector width and set the bits where elements are undef.
2053   ConstantFPSDNode *
2054   getConstantFPSplatNode(const APInt &DemandedElts,
2055                          BitVector *UndefElements = nullptr) const;
2056 
2057   /// Returns the splatted constant FP or null if this is not a constant
2058   /// FP splat.
2059   ///
2060   /// If passed a non-null UndefElements bitvector, it will resize it to match
2061   /// the vector width and set the bits where elements are undef.
2062   ConstantFPSDNode *
2063   getConstantFPSplatNode(BitVector *UndefElements = nullptr) const;
2064 
2065   /// If this is a constant FP splat and the splatted constant FP is an
2066   /// exact power or 2, return the log base 2 integer value.  Otherwise,
2067   /// return -1.
2068   ///
2069   /// The BitWidth specifies the necessary bit precision.
2070   int32_t getConstantFPSplatPow2ToLog2Int(BitVector *UndefElements,
2071                                           uint32_t BitWidth) const;
2072 
2073   /// Extract the raw bit data from a build vector of Undef, Constant or
2074   /// ConstantFP node elements. Each raw bit element will be \p
2075   /// DstEltSizeInBits wide, undef elements are treated as zero, and entirely
2076   /// undefined elements are flagged in \p UndefElements.
2077   bool getConstantRawBits(bool IsLittleEndian, unsigned DstEltSizeInBits,
2078                           SmallVectorImpl<APInt> &RawBitElements,
2079                           BitVector &UndefElements) const;
2080 
2081   bool isConstant() const;
2082 
2083   /// If this BuildVector is constant and represents the numerical series
2084   /// <a, a+n, a+2n, a+3n, ...> where a is integer and n is a non-zero integer,
2085   /// the value <a,n> is returned.
2086   Optional<std::pair<APInt, APInt>> isConstantSequence() const;
2087 
2088   /// Recast bit data \p SrcBitElements to \p DstEltSizeInBits wide elements.
2089   /// Undef elements are treated as zero, and entirely undefined elements are
2090   /// flagged in \p DstUndefElements.
2091   static void recastRawBits(bool IsLittleEndian, unsigned DstEltSizeInBits,
2092                             SmallVectorImpl<APInt> &DstBitElements,
2093                             ArrayRef<APInt> SrcBitElements,
2094                             BitVector &DstUndefElements,
2095                             const BitVector &SrcUndefElements);
2096 
2097   static bool classof(const SDNode *N) {
2098     return N->getOpcode() == ISD::BUILD_VECTOR;
2099   }
2100 };
2101 
2102 /// An SDNode that holds an arbitrary LLVM IR Value. This is
2103 /// used when the SelectionDAG needs to make a simple reference to something
2104 /// in the LLVM IR representation.
2105 ///
2106 class SrcValueSDNode : public SDNode {
2107   friend class SelectionDAG;
2108 
2109   const Value *V;
2110 
2111   /// Create a SrcValue for a general value.
2112   explicit SrcValueSDNode(const Value *v)
2113     : SDNode(ISD::SRCVALUE, 0, DebugLoc(), getSDVTList(MVT::Other)), V(v) {}
2114 
2115 public:
2116   /// Return the contained Value.
2117   const Value *getValue() const { return V; }
2118 
2119   static bool classof(const SDNode *N) {
2120     return N->getOpcode() == ISD::SRCVALUE;
2121   }
2122 };
2123 
2124 class MDNodeSDNode : public SDNode {
2125   friend class SelectionDAG;
2126 
2127   const MDNode *MD;
2128 
2129   explicit MDNodeSDNode(const MDNode *md)
2130   : SDNode(ISD::MDNODE_SDNODE, 0, DebugLoc(), getSDVTList(MVT::Other)), MD(md)
2131   {}
2132 
2133 public:
2134   const MDNode *getMD() const { return MD; }
2135 
2136   static bool classof(const SDNode *N) {
2137     return N->getOpcode() == ISD::MDNODE_SDNODE;
2138   }
2139 };
2140 
2141 class RegisterSDNode : public SDNode {
2142   friend class SelectionDAG;
2143 
2144   Register Reg;
2145 
2146   RegisterSDNode(Register reg, EVT VT)
2147     : SDNode(ISD::Register, 0, DebugLoc(), getSDVTList(VT)), Reg(reg) {}
2148 
2149 public:
2150   Register getReg() const { return Reg; }
2151 
2152   static bool classof(const SDNode *N) {
2153     return N->getOpcode() == ISD::Register;
2154   }
2155 };
2156 
2157 class RegisterMaskSDNode : public SDNode {
2158   friend class SelectionDAG;
2159 
2160   // The memory for RegMask is not owned by the node.
2161   const uint32_t *RegMask;
2162 
2163   RegisterMaskSDNode(const uint32_t *mask)
2164     : SDNode(ISD::RegisterMask, 0, DebugLoc(), getSDVTList(MVT::Untyped)),
2165       RegMask(mask) {}
2166 
2167 public:
2168   const uint32_t *getRegMask() const { return RegMask; }
2169 
2170   static bool classof(const SDNode *N) {
2171     return N->getOpcode() == ISD::RegisterMask;
2172   }
2173 };
2174 
2175 class BlockAddressSDNode : public SDNode {
2176   friend class SelectionDAG;
2177 
2178   const BlockAddress *BA;
2179   int64_t Offset;
2180   unsigned TargetFlags;
2181 
2182   BlockAddressSDNode(unsigned NodeTy, EVT VT, const BlockAddress *ba,
2183                      int64_t o, unsigned Flags)
2184     : SDNode(NodeTy, 0, DebugLoc(), getSDVTList(VT)),
2185              BA(ba), Offset(o), TargetFlags(Flags) {}
2186 
2187 public:
2188   const BlockAddress *getBlockAddress() const { return BA; }
2189   int64_t getOffset() const { return Offset; }
2190   unsigned getTargetFlags() const { return TargetFlags; }
2191 
2192   static bool classof(const SDNode *N) {
2193     return N->getOpcode() == ISD::BlockAddress ||
2194            N->getOpcode() == ISD::TargetBlockAddress;
2195   }
2196 };
2197 
2198 class LabelSDNode : public SDNode {
2199   friend class SelectionDAG;
2200 
2201   MCSymbol *Label;
2202 
2203   LabelSDNode(unsigned Opcode, unsigned Order, const DebugLoc &dl, MCSymbol *L)
2204       : SDNode(Opcode, Order, dl, getSDVTList(MVT::Other)), Label(L) {
2205     assert(LabelSDNode::classof(this) && "not a label opcode");
2206   }
2207 
2208 public:
2209   MCSymbol *getLabel() const { return Label; }
2210 
2211   static bool classof(const SDNode *N) {
2212     return N->getOpcode() == ISD::EH_LABEL ||
2213            N->getOpcode() == ISD::ANNOTATION_LABEL;
2214   }
2215 };
2216 
2217 class ExternalSymbolSDNode : public SDNode {
2218   friend class SelectionDAG;
2219 
2220   const char *Symbol;
2221   unsigned TargetFlags;
2222 
2223   ExternalSymbolSDNode(bool isTarget, const char *Sym, unsigned TF, EVT VT)
2224       : SDNode(isTarget ? ISD::TargetExternalSymbol : ISD::ExternalSymbol, 0,
2225                DebugLoc(), getSDVTList(VT)),
2226         Symbol(Sym), TargetFlags(TF) {}
2227 
2228 public:
2229   const char *getSymbol() const { return Symbol; }
2230   unsigned getTargetFlags() const { return TargetFlags; }
2231 
2232   static bool classof(const SDNode *N) {
2233     return N->getOpcode() == ISD::ExternalSymbol ||
2234            N->getOpcode() == ISD::TargetExternalSymbol;
2235   }
2236 };
2237 
2238 class MCSymbolSDNode : public SDNode {
2239   friend class SelectionDAG;
2240 
2241   MCSymbol *Symbol;
2242 
2243   MCSymbolSDNode(MCSymbol *Symbol, EVT VT)
2244       : SDNode(ISD::MCSymbol, 0, DebugLoc(), getSDVTList(VT)), Symbol(Symbol) {}
2245 
2246 public:
2247   MCSymbol *getMCSymbol() const { return Symbol; }
2248 
2249   static bool classof(const SDNode *N) {
2250     return N->getOpcode() == ISD::MCSymbol;
2251   }
2252 };
2253 
2254 class CondCodeSDNode : public SDNode {
2255   friend class SelectionDAG;
2256 
2257   ISD::CondCode Condition;
2258 
2259   explicit CondCodeSDNode(ISD::CondCode Cond)
2260     : SDNode(ISD::CONDCODE, 0, DebugLoc(), getSDVTList(MVT::Other)),
2261       Condition(Cond) {}
2262 
2263 public:
2264   ISD::CondCode get() const { return Condition; }
2265 
2266   static bool classof(const SDNode *N) {
2267     return N->getOpcode() == ISD::CONDCODE;
2268   }
2269 };
2270 
2271 /// This class is used to represent EVT's, which are used
2272 /// to parameterize some operations.
2273 class VTSDNode : public SDNode {
2274   friend class SelectionDAG;
2275 
2276   EVT ValueType;
2277 
2278   explicit VTSDNode(EVT VT)
2279     : SDNode(ISD::VALUETYPE, 0, DebugLoc(), getSDVTList(MVT::Other)),
2280       ValueType(VT) {}
2281 
2282 public:
2283   EVT getVT() const { return ValueType; }
2284 
2285   static bool classof(const SDNode *N) {
2286     return N->getOpcode() == ISD::VALUETYPE;
2287   }
2288 };
2289 
2290 /// Base class for LoadSDNode and StoreSDNode
2291 class LSBaseSDNode : public MemSDNode {
2292 public:
2293   LSBaseSDNode(ISD::NodeType NodeTy, unsigned Order, const DebugLoc &dl,
2294                SDVTList VTs, ISD::MemIndexedMode AM, EVT MemVT,
2295                MachineMemOperand *MMO)
2296       : MemSDNode(NodeTy, Order, dl, VTs, MemVT, MMO) {
2297     LSBaseSDNodeBits.AddressingMode = AM;
2298     assert(getAddressingMode() == AM && "Value truncated");
2299   }
2300 
2301   const SDValue &getOffset() const {
2302     return getOperand(getOpcode() == ISD::LOAD ? 2 : 3);
2303   }
2304 
2305   /// Return the addressing mode for this load or store:
2306   /// unindexed, pre-inc, pre-dec, post-inc, or post-dec.
2307   ISD::MemIndexedMode getAddressingMode() const {
2308     return static_cast<ISD::MemIndexedMode>(LSBaseSDNodeBits.AddressingMode);
2309   }
2310 
2311   /// Return true if this is a pre/post inc/dec load/store.
2312   bool isIndexed() const { return getAddressingMode() != ISD::UNINDEXED; }
2313 
2314   /// Return true if this is NOT a pre/post inc/dec load/store.
2315   bool isUnindexed() const { return getAddressingMode() == ISD::UNINDEXED; }
2316 
2317   static bool classof(const SDNode *N) {
2318     return N->getOpcode() == ISD::LOAD ||
2319            N->getOpcode() == ISD::STORE;
2320   }
2321 };
2322 
2323 /// This class is used to represent ISD::LOAD nodes.
2324 class LoadSDNode : public LSBaseSDNode {
2325   friend class SelectionDAG;
2326 
2327   LoadSDNode(unsigned Order, const DebugLoc &dl, SDVTList VTs,
2328              ISD::MemIndexedMode AM, ISD::LoadExtType ETy, EVT MemVT,
2329              MachineMemOperand *MMO)
2330       : LSBaseSDNode(ISD::LOAD, Order, dl, VTs, AM, MemVT, MMO) {
2331     LoadSDNodeBits.ExtTy = ETy;
2332     assert(readMem() && "Load MachineMemOperand is not a load!");
2333     assert(!writeMem() && "Load MachineMemOperand is a store!");
2334   }
2335 
2336 public:
2337   /// Return whether this is a plain node,
2338   /// or one of the varieties of value-extending loads.
2339   ISD::LoadExtType getExtensionType() const {
2340     return static_cast<ISD::LoadExtType>(LoadSDNodeBits.ExtTy);
2341   }
2342 
2343   const SDValue &getBasePtr() const { return getOperand(1); }
2344   const SDValue &getOffset() const { return getOperand(2); }
2345 
2346   static bool classof(const SDNode *N) {
2347     return N->getOpcode() == ISD::LOAD;
2348   }
2349 };
2350 
2351 /// This class is used to represent ISD::STORE nodes.
2352 class StoreSDNode : public LSBaseSDNode {
2353   friend class SelectionDAG;
2354 
2355   StoreSDNode(unsigned Order, const DebugLoc &dl, SDVTList VTs,
2356               ISD::MemIndexedMode AM, bool isTrunc, EVT MemVT,
2357               MachineMemOperand *MMO)
2358       : LSBaseSDNode(ISD::STORE, Order, dl, VTs, AM, MemVT, MMO) {
2359     StoreSDNodeBits.IsTruncating = isTrunc;
2360     assert(!readMem() && "Store MachineMemOperand is a load!");
2361     assert(writeMem() && "Store MachineMemOperand is not a store!");
2362   }
2363 
2364 public:
2365   /// Return true if the op does a truncation before store.
2366   /// For integers this is the same as doing a TRUNCATE and storing the result.
2367   /// For floats, it is the same as doing an FP_ROUND and storing the result.
2368   bool isTruncatingStore() const { return StoreSDNodeBits.IsTruncating; }
2369   void setTruncatingStore(bool Truncating) {
2370     StoreSDNodeBits.IsTruncating = Truncating;
2371   }
2372 
2373   const SDValue &getValue() const { return getOperand(1); }
2374   const SDValue &getBasePtr() const { return getOperand(2); }
2375   const SDValue &getOffset() const { return getOperand(3); }
2376 
2377   static bool classof(const SDNode *N) {
2378     return N->getOpcode() == ISD::STORE;
2379   }
2380 };
2381 
2382 /// This base class is used to represent VP_LOAD, VP_STORE,
2383 /// EXPERIMENTAL_VP_STRIDED_LOAD and EXPERIMENTAL_VP_STRIDED_STORE nodes
2384 class VPBaseLoadStoreSDNode : public MemSDNode {
2385 public:
2386   friend class SelectionDAG;
2387 
2388   VPBaseLoadStoreSDNode(ISD::NodeType NodeTy, unsigned Order,
2389                         const DebugLoc &DL, SDVTList VTs,
2390                         ISD::MemIndexedMode AM, EVT MemVT,
2391                         MachineMemOperand *MMO)
2392       : MemSDNode(NodeTy, Order, DL, VTs, MemVT, MMO) {
2393     LSBaseSDNodeBits.AddressingMode = AM;
2394     assert(getAddressingMode() == AM && "Value truncated");
2395   }
2396 
2397   // VPStridedStoreSDNode (Chain, Data, Ptr,    Offset, Stride, Mask, EVL)
2398   // VPStoreSDNode        (Chain, Data, Ptr,    Offset, Mask,   EVL)
2399   // VPStridedLoadSDNode  (Chain, Ptr,  Offset, Stride, Mask,   EVL)
2400   // VPLoadSDNode         (Chain, Ptr,  Offset, Mask,   EVL)
2401   // Mask is a vector of i1 elements;
2402   // the type of EVL is TLI.getVPExplicitVectorLengthTy().
2403   const SDValue &getOffset() const {
2404     return getOperand((getOpcode() == ISD::EXPERIMENTAL_VP_STRIDED_LOAD ||
2405                        getOpcode() == ISD::VP_LOAD)
2406                           ? 2
2407                           : 3);
2408   }
2409   const SDValue &getBasePtr() const {
2410     return getOperand((getOpcode() == ISD::EXPERIMENTAL_VP_STRIDED_LOAD ||
2411                        getOpcode() == ISD::VP_LOAD)
2412                           ? 1
2413                           : 2);
2414   }
2415   const SDValue &getMask() const {
2416     switch (getOpcode()) {
2417     default:
2418       llvm_unreachable("Invalid opcode");
2419     case ISD::VP_LOAD:
2420       return getOperand(3);
2421     case ISD::VP_STORE:
2422     case ISD::EXPERIMENTAL_VP_STRIDED_LOAD:
2423       return getOperand(4);
2424     case ISD::EXPERIMENTAL_VP_STRIDED_STORE:
2425       return getOperand(5);
2426     }
2427   }
2428   const SDValue &getVectorLength() const {
2429     switch (getOpcode()) {
2430     default:
2431       llvm_unreachable("Invalid opcode");
2432     case ISD::VP_LOAD:
2433       return getOperand(4);
2434     case ISD::VP_STORE:
2435     case ISD::EXPERIMENTAL_VP_STRIDED_LOAD:
2436       return getOperand(5);
2437     case ISD::EXPERIMENTAL_VP_STRIDED_STORE:
2438       return getOperand(6);
2439     }
2440   }
2441 
2442   /// Return the addressing mode for this load or store:
2443   /// unindexed, pre-inc, pre-dec, post-inc, or post-dec.
2444   ISD::MemIndexedMode getAddressingMode() const {
2445     return static_cast<ISD::MemIndexedMode>(LSBaseSDNodeBits.AddressingMode);
2446   }
2447 
2448   /// Return true if this is a pre/post inc/dec load/store.
2449   bool isIndexed() const { return getAddressingMode() != ISD::UNINDEXED; }
2450 
2451   /// Return true if this is NOT a pre/post inc/dec load/store.
2452   bool isUnindexed() const { return getAddressingMode() == ISD::UNINDEXED; }
2453 
2454   static bool classof(const SDNode *N) {
2455     return N->getOpcode() == ISD::EXPERIMENTAL_VP_STRIDED_LOAD ||
2456            N->getOpcode() == ISD::EXPERIMENTAL_VP_STRIDED_STORE ||
2457            N->getOpcode() == ISD::VP_LOAD || N->getOpcode() == ISD::VP_STORE;
2458   }
2459 };
2460 
2461 /// This class is used to represent a VP_LOAD node
2462 class VPLoadSDNode : public VPBaseLoadStoreSDNode {
2463 public:
2464   friend class SelectionDAG;
2465 
2466   VPLoadSDNode(unsigned Order, const DebugLoc &dl, SDVTList VTs,
2467                ISD::MemIndexedMode AM, ISD::LoadExtType ETy, bool isExpanding,
2468                EVT MemVT, MachineMemOperand *MMO)
2469       : VPBaseLoadStoreSDNode(ISD::VP_LOAD, Order, dl, VTs, AM, MemVT, MMO) {
2470     LoadSDNodeBits.ExtTy = ETy;
2471     LoadSDNodeBits.IsExpanding = isExpanding;
2472   }
2473 
2474   ISD::LoadExtType getExtensionType() const {
2475     return static_cast<ISD::LoadExtType>(LoadSDNodeBits.ExtTy);
2476   }
2477 
2478   const SDValue &getBasePtr() const { return getOperand(1); }
2479   const SDValue &getOffset() const { return getOperand(2); }
2480   const SDValue &getMask() const { return getOperand(3); }
2481   const SDValue &getVectorLength() const { return getOperand(4); }
2482 
2483   static bool classof(const SDNode *N) {
2484     return N->getOpcode() == ISD::VP_LOAD;
2485   }
2486   bool isExpandingLoad() const { return LoadSDNodeBits.IsExpanding; }
2487 };
2488 
2489 /// This class is used to represent an EXPERIMENTAL_VP_STRIDED_LOAD node.
2490 class VPStridedLoadSDNode : public VPBaseLoadStoreSDNode {
2491 public:
2492   friend class SelectionDAG;
2493 
2494   VPStridedLoadSDNode(unsigned Order, const DebugLoc &DL, SDVTList VTs,
2495                       ISD::MemIndexedMode AM, ISD::LoadExtType ETy,
2496                       bool IsExpanding, EVT MemVT, MachineMemOperand *MMO)
2497       : VPBaseLoadStoreSDNode(ISD::EXPERIMENTAL_VP_STRIDED_LOAD, Order, DL, VTs,
2498                               AM, MemVT, MMO) {
2499     LoadSDNodeBits.ExtTy = ETy;
2500     LoadSDNodeBits.IsExpanding = IsExpanding;
2501   }
2502 
2503   ISD::LoadExtType getExtensionType() const {
2504     return static_cast<ISD::LoadExtType>(LoadSDNodeBits.ExtTy);
2505   }
2506 
2507   const SDValue &getBasePtr() const { return getOperand(1); }
2508   const SDValue &getOffset() const { return getOperand(2); }
2509   const SDValue &getStride() const { return getOperand(3); }
2510   const SDValue &getMask() const { return getOperand(4); }
2511   const SDValue &getVectorLength() const { return getOperand(5); }
2512 
2513   static bool classof(const SDNode *N) {
2514     return N->getOpcode() == ISD::EXPERIMENTAL_VP_STRIDED_LOAD;
2515   }
2516   bool isExpandingLoad() const { return LoadSDNodeBits.IsExpanding; }
2517 };
2518 
2519 /// This class is used to represent a VP_STORE node
2520 class VPStoreSDNode : public VPBaseLoadStoreSDNode {
2521 public:
2522   friend class SelectionDAG;
2523 
2524   VPStoreSDNode(unsigned Order, const DebugLoc &dl, SDVTList VTs,
2525                 ISD::MemIndexedMode AM, bool isTrunc, bool isCompressing,
2526                 EVT MemVT, MachineMemOperand *MMO)
2527       : VPBaseLoadStoreSDNode(ISD::VP_STORE, Order, dl, VTs, AM, MemVT, MMO) {
2528     StoreSDNodeBits.IsTruncating = isTrunc;
2529     StoreSDNodeBits.IsCompressing = isCompressing;
2530   }
2531 
2532   /// Return true if this is a truncating store.
2533   /// For integers this is the same as doing a TRUNCATE and storing the result.
2534   /// For floats, it is the same as doing an FP_ROUND and storing the result.
2535   bool isTruncatingStore() const { return StoreSDNodeBits.IsTruncating; }
2536 
2537   /// Returns true if the op does a compression to the vector before storing.
2538   /// The node contiguously stores the active elements (integers or floats)
2539   /// in src (those with their respective bit set in writemask k) to unaligned
2540   /// memory at base_addr.
2541   bool isCompressingStore() const { return StoreSDNodeBits.IsCompressing; }
2542 
2543   const SDValue &getValue() const { return getOperand(1); }
2544   const SDValue &getBasePtr() const { return getOperand(2); }
2545   const SDValue &getOffset() const { return getOperand(3); }
2546   const SDValue &getMask() const { return getOperand(4); }
2547   const SDValue &getVectorLength() const { return getOperand(5); }
2548 
2549   static bool classof(const SDNode *N) {
2550     return N->getOpcode() == ISD::VP_STORE;
2551   }
2552 };
2553 
2554 /// This class is used to represent an EXPERIMENTAL_VP_STRIDED_STORE node.
2555 class VPStridedStoreSDNode : public VPBaseLoadStoreSDNode {
2556 public:
2557   friend class SelectionDAG;
2558 
2559   VPStridedStoreSDNode(unsigned Order, const DebugLoc &DL, SDVTList VTs,
2560                        ISD::MemIndexedMode AM, bool IsTrunc, bool IsCompressing,
2561                        EVT MemVT, MachineMemOperand *MMO)
2562       : VPBaseLoadStoreSDNode(ISD::EXPERIMENTAL_VP_STRIDED_STORE, Order, DL,
2563                               VTs, AM, MemVT, MMO) {
2564     StoreSDNodeBits.IsTruncating = IsTrunc;
2565     StoreSDNodeBits.IsCompressing = IsCompressing;
2566   }
2567 
2568   /// Return true if this is a truncating store.
2569   /// For integers this is the same as doing a TRUNCATE and storing the result.
2570   /// For floats, it is the same as doing an FP_ROUND and storing the result.
2571   bool isTruncatingStore() const { return StoreSDNodeBits.IsTruncating; }
2572 
2573   /// Returns true if the op does a compression to the vector before storing.
2574   /// The node contiguously stores the active elements (integers or floats)
2575   /// in src (those with their respective bit set in writemask k) to unaligned
2576   /// memory at base_addr.
2577   bool isCompressingStore() const { return StoreSDNodeBits.IsCompressing; }
2578 
2579   const SDValue &getValue() const { return getOperand(1); }
2580   const SDValue &getBasePtr() const { return getOperand(2); }
2581   const SDValue &getOffset() const { return getOperand(3); }
2582   const SDValue &getStride() const { return getOperand(4); }
2583   const SDValue &getMask() const { return getOperand(5); }
2584   const SDValue &getVectorLength() const { return getOperand(6); }
2585 
2586   static bool classof(const SDNode *N) {
2587     return N->getOpcode() == ISD::EXPERIMENTAL_VP_STRIDED_STORE;
2588   }
2589 };
2590 
2591 /// This base class is used to represent MLOAD and MSTORE nodes
2592 class MaskedLoadStoreSDNode : public MemSDNode {
2593 public:
2594   friend class SelectionDAG;
2595 
2596   MaskedLoadStoreSDNode(ISD::NodeType NodeTy, unsigned Order,
2597                         const DebugLoc &dl, SDVTList VTs,
2598                         ISD::MemIndexedMode AM, EVT MemVT,
2599                         MachineMemOperand *MMO)
2600       : MemSDNode(NodeTy, Order, dl, VTs, MemVT, MMO) {
2601     LSBaseSDNodeBits.AddressingMode = AM;
2602     assert(getAddressingMode() == AM && "Value truncated");
2603   }
2604 
2605   // MaskedLoadSDNode (Chain, ptr, offset, mask, passthru)
2606   // MaskedStoreSDNode (Chain, data, ptr, offset, mask)
2607   // Mask is a vector of i1 elements
2608   const SDValue &getOffset() const {
2609     return getOperand(getOpcode() == ISD::MLOAD ? 2 : 3);
2610   }
2611   const SDValue &getMask() const {
2612     return getOperand(getOpcode() == ISD::MLOAD ? 3 : 4);
2613   }
2614 
2615   /// Return the addressing mode for this load or store:
2616   /// unindexed, pre-inc, pre-dec, post-inc, or post-dec.
2617   ISD::MemIndexedMode getAddressingMode() const {
2618     return static_cast<ISD::MemIndexedMode>(LSBaseSDNodeBits.AddressingMode);
2619   }
2620 
2621   /// Return true if this is a pre/post inc/dec load/store.
2622   bool isIndexed() const { return getAddressingMode() != ISD::UNINDEXED; }
2623 
2624   /// Return true if this is NOT a pre/post inc/dec load/store.
2625   bool isUnindexed() const { return getAddressingMode() == ISD::UNINDEXED; }
2626 
2627   static bool classof(const SDNode *N) {
2628     return N->getOpcode() == ISD::MLOAD ||
2629            N->getOpcode() == ISD::MSTORE;
2630   }
2631 };
2632 
2633 /// This class is used to represent an MLOAD node
2634 class MaskedLoadSDNode : public MaskedLoadStoreSDNode {
2635 public:
2636   friend class SelectionDAG;
2637 
2638   MaskedLoadSDNode(unsigned Order, const DebugLoc &dl, SDVTList VTs,
2639                    ISD::MemIndexedMode AM, ISD::LoadExtType ETy,
2640                    bool IsExpanding, EVT MemVT, MachineMemOperand *MMO)
2641       : MaskedLoadStoreSDNode(ISD::MLOAD, Order, dl, VTs, AM, MemVT, MMO) {
2642     LoadSDNodeBits.ExtTy = ETy;
2643     LoadSDNodeBits.IsExpanding = IsExpanding;
2644   }
2645 
2646   ISD::LoadExtType getExtensionType() const {
2647     return static_cast<ISD::LoadExtType>(LoadSDNodeBits.ExtTy);
2648   }
2649 
2650   const SDValue &getBasePtr() const { return getOperand(1); }
2651   const SDValue &getOffset() const { return getOperand(2); }
2652   const SDValue &getMask() const { return getOperand(3); }
2653   const SDValue &getPassThru() const { return getOperand(4); }
2654 
2655   static bool classof(const SDNode *N) {
2656     return N->getOpcode() == ISD::MLOAD;
2657   }
2658 
2659   bool isExpandingLoad() const { return LoadSDNodeBits.IsExpanding; }
2660 };
2661 
2662 /// This class is used to represent an MSTORE node
2663 class MaskedStoreSDNode : public MaskedLoadStoreSDNode {
2664 public:
2665   friend class SelectionDAG;
2666 
2667   MaskedStoreSDNode(unsigned Order, const DebugLoc &dl, SDVTList VTs,
2668                     ISD::MemIndexedMode AM, bool isTrunc, bool isCompressing,
2669                     EVT MemVT, MachineMemOperand *MMO)
2670       : MaskedLoadStoreSDNode(ISD::MSTORE, Order, dl, VTs, AM, MemVT, MMO) {
2671     StoreSDNodeBits.IsTruncating = isTrunc;
2672     StoreSDNodeBits.IsCompressing = isCompressing;
2673   }
2674 
2675   /// Return true if the op does a truncation before store.
2676   /// For integers this is the same as doing a TRUNCATE and storing the result.
2677   /// For floats, it is the same as doing an FP_ROUND and storing the result.
2678   bool isTruncatingStore() const { return StoreSDNodeBits.IsTruncating; }
2679 
2680   /// Returns true if the op does a compression to the vector before storing.
2681   /// The node contiguously stores the active elements (integers or floats)
2682   /// in src (those with their respective bit set in writemask k) to unaligned
2683   /// memory at base_addr.
2684   bool isCompressingStore() const { return StoreSDNodeBits.IsCompressing; }
2685 
2686   const SDValue &getValue() const { return getOperand(1); }
2687   const SDValue &getBasePtr() const { return getOperand(2); }
2688   const SDValue &getOffset() const { return getOperand(3); }
2689   const SDValue &getMask() const { return getOperand(4); }
2690 
2691   static bool classof(const SDNode *N) {
2692     return N->getOpcode() == ISD::MSTORE;
2693   }
2694 };
2695 
2696 /// This is a base class used to represent
2697 /// VP_GATHER and VP_SCATTER nodes
2698 ///
2699 class VPGatherScatterSDNode : public MemSDNode {
2700 public:
2701   friend class SelectionDAG;
2702 
2703   VPGatherScatterSDNode(ISD::NodeType NodeTy, unsigned Order,
2704                         const DebugLoc &dl, SDVTList VTs, EVT MemVT,
2705                         MachineMemOperand *MMO, ISD::MemIndexType IndexType)
2706       : MemSDNode(NodeTy, Order, dl, VTs, MemVT, MMO) {
2707     LSBaseSDNodeBits.AddressingMode = IndexType;
2708     assert(getIndexType() == IndexType && "Value truncated");
2709   }
2710 
2711   /// How is Index applied to BasePtr when computing addresses.
2712   ISD::MemIndexType getIndexType() const {
2713     return static_cast<ISD::MemIndexType>(LSBaseSDNodeBits.AddressingMode);
2714   }
2715   bool isIndexScaled() const {
2716     return !cast<ConstantSDNode>(getScale())->isOne();
2717   }
2718   bool isIndexSigned() const { return isIndexTypeSigned(getIndexType()); }
2719 
2720   // In the both nodes address is Op1, mask is Op2:
2721   // VPGatherSDNode  (Chain, base, index, scale, mask, vlen)
2722   // VPScatterSDNode (Chain, value, base, index, scale, mask, vlen)
2723   // Mask is a vector of i1 elements
2724   const SDValue &getBasePtr() const {
2725     return getOperand((getOpcode() == ISD::VP_GATHER) ? 1 : 2);
2726   }
2727   const SDValue &getIndex() const {
2728     return getOperand((getOpcode() == ISD::VP_GATHER) ? 2 : 3);
2729   }
2730   const SDValue &getScale() const {
2731     return getOperand((getOpcode() == ISD::VP_GATHER) ? 3 : 4);
2732   }
2733   const SDValue &getMask() const {
2734     return getOperand((getOpcode() == ISD::VP_GATHER) ? 4 : 5);
2735   }
2736   const SDValue &getVectorLength() const {
2737     return getOperand((getOpcode() == ISD::VP_GATHER) ? 5 : 6);
2738   }
2739 
2740   static bool classof(const SDNode *N) {
2741     return N->getOpcode() == ISD::VP_GATHER ||
2742            N->getOpcode() == ISD::VP_SCATTER;
2743   }
2744 };
2745 
2746 /// This class is used to represent an VP_GATHER node
2747 ///
2748 class VPGatherSDNode : public VPGatherScatterSDNode {
2749 public:
2750   friend class SelectionDAG;
2751 
2752   VPGatherSDNode(unsigned Order, const DebugLoc &dl, SDVTList VTs, EVT MemVT,
2753                  MachineMemOperand *MMO, ISD::MemIndexType IndexType)
2754       : VPGatherScatterSDNode(ISD::VP_GATHER, Order, dl, VTs, MemVT, MMO,
2755                               IndexType) {}
2756 
2757   static bool classof(const SDNode *N) {
2758     return N->getOpcode() == ISD::VP_GATHER;
2759   }
2760 };
2761 
2762 /// This class is used to represent an VP_SCATTER node
2763 ///
2764 class VPScatterSDNode : public VPGatherScatterSDNode {
2765 public:
2766   friend class SelectionDAG;
2767 
2768   VPScatterSDNode(unsigned Order, const DebugLoc &dl, SDVTList VTs, EVT MemVT,
2769                   MachineMemOperand *MMO, ISD::MemIndexType IndexType)
2770       : VPGatherScatterSDNode(ISD::VP_SCATTER, Order, dl, VTs, MemVT, MMO,
2771                               IndexType) {}
2772 
2773   const SDValue &getValue() const { return getOperand(1); }
2774 
2775   static bool classof(const SDNode *N) {
2776     return N->getOpcode() == ISD::VP_SCATTER;
2777   }
2778 };
2779 
2780 /// This is a base class used to represent
2781 /// MGATHER and MSCATTER nodes
2782 ///
2783 class MaskedGatherScatterSDNode : public MemSDNode {
2784 public:
2785   friend class SelectionDAG;
2786 
2787   MaskedGatherScatterSDNode(ISD::NodeType NodeTy, unsigned Order,
2788                             const DebugLoc &dl, SDVTList VTs, EVT MemVT,
2789                             MachineMemOperand *MMO, ISD::MemIndexType IndexType)
2790       : MemSDNode(NodeTy, Order, dl, VTs, MemVT, MMO) {
2791     LSBaseSDNodeBits.AddressingMode = IndexType;
2792     assert(getIndexType() == IndexType && "Value truncated");
2793   }
2794 
2795   /// How is Index applied to BasePtr when computing addresses.
2796   ISD::MemIndexType getIndexType() const {
2797     return static_cast<ISD::MemIndexType>(LSBaseSDNodeBits.AddressingMode);
2798   }
2799   bool isIndexScaled() const {
2800     return !cast<ConstantSDNode>(getScale())->isOne();
2801   }
2802   bool isIndexSigned() const { return isIndexTypeSigned(getIndexType()); }
2803 
2804   // In the both nodes address is Op1, mask is Op2:
2805   // MaskedGatherSDNode  (Chain, passthru, mask, base, index, scale)
2806   // MaskedScatterSDNode (Chain, value, mask, base, index, scale)
2807   // Mask is a vector of i1 elements
2808   const SDValue &getBasePtr() const { return getOperand(3); }
2809   const SDValue &getIndex()   const { return getOperand(4); }
2810   const SDValue &getMask()    const { return getOperand(2); }
2811   const SDValue &getScale()   const { return getOperand(5); }
2812 
2813   static bool classof(const SDNode *N) {
2814     return N->getOpcode() == ISD::MGATHER ||
2815            N->getOpcode() == ISD::MSCATTER;
2816   }
2817 };
2818 
2819 /// This class is used to represent an MGATHER node
2820 ///
2821 class MaskedGatherSDNode : public MaskedGatherScatterSDNode {
2822 public:
2823   friend class SelectionDAG;
2824 
2825   MaskedGatherSDNode(unsigned Order, const DebugLoc &dl, SDVTList VTs,
2826                      EVT MemVT, MachineMemOperand *MMO,
2827                      ISD::MemIndexType IndexType, ISD::LoadExtType ETy)
2828       : MaskedGatherScatterSDNode(ISD::MGATHER, Order, dl, VTs, MemVT, MMO,
2829                                   IndexType) {
2830     LoadSDNodeBits.ExtTy = ETy;
2831   }
2832 
2833   const SDValue &getPassThru() const { return getOperand(1); }
2834 
2835   ISD::LoadExtType getExtensionType() const {
2836     return ISD::LoadExtType(LoadSDNodeBits.ExtTy);
2837   }
2838 
2839   static bool classof(const SDNode *N) {
2840     return N->getOpcode() == ISD::MGATHER;
2841   }
2842 };
2843 
2844 /// This class is used to represent an MSCATTER node
2845 ///
2846 class MaskedScatterSDNode : public MaskedGatherScatterSDNode {
2847 public:
2848   friend class SelectionDAG;
2849 
2850   MaskedScatterSDNode(unsigned Order, const DebugLoc &dl, SDVTList VTs,
2851                       EVT MemVT, MachineMemOperand *MMO,
2852                       ISD::MemIndexType IndexType, bool IsTrunc)
2853       : MaskedGatherScatterSDNode(ISD::MSCATTER, Order, dl, VTs, MemVT, MMO,
2854                                   IndexType) {
2855     StoreSDNodeBits.IsTruncating = IsTrunc;
2856   }
2857 
2858   /// Return true if the op does a truncation before store.
2859   /// For integers this is the same as doing a TRUNCATE and storing the result.
2860   /// For floats, it is the same as doing an FP_ROUND and storing the result.
2861   bool isTruncatingStore() const { return StoreSDNodeBits.IsTruncating; }
2862 
2863   const SDValue &getValue() const { return getOperand(1); }
2864 
2865   static bool classof(const SDNode *N) {
2866     return N->getOpcode() == ISD::MSCATTER;
2867   }
2868 };
2869 
2870 /// An SDNode that represents everything that will be needed
2871 /// to construct a MachineInstr. These nodes are created during the
2872 /// instruction selection proper phase.
2873 ///
2874 /// Note that the only supported way to set the `memoperands` is by calling the
2875 /// `SelectionDAG::setNodeMemRefs` function as the memory management happens
2876 /// inside the DAG rather than in the node.
2877 class MachineSDNode : public SDNode {
2878 private:
2879   friend class SelectionDAG;
2880 
2881   MachineSDNode(unsigned Opc, unsigned Order, const DebugLoc &DL, SDVTList VTs)
2882       : SDNode(Opc, Order, DL, VTs) {}
2883 
2884   // We use a pointer union between a single `MachineMemOperand` pointer and
2885   // a pointer to an array of `MachineMemOperand` pointers. This is null when
2886   // the number of these is zero, the single pointer variant used when the
2887   // number is one, and the array is used for larger numbers.
2888   //
2889   // The array is allocated via the `SelectionDAG`'s allocator and so will
2890   // always live until the DAG is cleaned up and doesn't require ownership here.
2891   //
2892   // We can't use something simpler like `TinyPtrVector` here because `SDNode`
2893   // subclasses aren't managed in a conforming C++ manner. See the comments on
2894   // `SelectionDAG::MorphNodeTo` which details what all goes on, but the
2895   // constraint here is that these don't manage memory with their constructor or
2896   // destructor and can be initialized to a good state even if they start off
2897   // uninitialized.
2898   PointerUnion<MachineMemOperand *, MachineMemOperand **> MemRefs = {};
2899 
2900   // Note that this could be folded into the above `MemRefs` member if doing so
2901   // is advantageous at some point. We don't need to store this in most cases.
2902   // However, at the moment this doesn't appear to make the allocation any
2903   // smaller and makes the code somewhat simpler to read.
2904   int NumMemRefs = 0;
2905 
2906 public:
2907   using mmo_iterator = ArrayRef<MachineMemOperand *>::const_iterator;
2908 
2909   ArrayRef<MachineMemOperand *> memoperands() const {
2910     // Special case the common cases.
2911     if (NumMemRefs == 0)
2912       return {};
2913     if (NumMemRefs == 1)
2914       return makeArrayRef(MemRefs.getAddrOfPtr1(), 1);
2915 
2916     // Otherwise we have an actual array.
2917     return makeArrayRef(MemRefs.get<MachineMemOperand **>(), NumMemRefs);
2918   }
2919   mmo_iterator memoperands_begin() const { return memoperands().begin(); }
2920   mmo_iterator memoperands_end() const { return memoperands().end(); }
2921   bool memoperands_empty() const { return memoperands().empty(); }
2922 
2923   /// Clear out the memory reference descriptor list.
2924   void clearMemRefs() {
2925     MemRefs = nullptr;
2926     NumMemRefs = 0;
2927   }
2928 
2929   static bool classof(const SDNode *N) {
2930     return N->isMachineOpcode();
2931   }
2932 };
2933 
2934 /// An SDNode that records if a register contains a value that is guaranteed to
2935 /// be aligned accordingly.
2936 class AssertAlignSDNode : public SDNode {
2937   Align Alignment;
2938 
2939 public:
2940   AssertAlignSDNode(unsigned Order, const DebugLoc &DL, EVT VT, Align A)
2941       : SDNode(ISD::AssertAlign, Order, DL, getSDVTList(VT)), Alignment(A) {}
2942 
2943   Align getAlign() const { return Alignment; }
2944 
2945   static bool classof(const SDNode *N) {
2946     return N->getOpcode() == ISD::AssertAlign;
2947   }
2948 };
2949 
2950 class SDNodeIterator {
2951   const SDNode *Node;
2952   unsigned Operand;
2953 
2954   SDNodeIterator(const SDNode *N, unsigned Op) : Node(N), Operand(Op) {}
2955 
2956 public:
2957   using iterator_category = std::forward_iterator_tag;
2958   using value_type = SDNode;
2959   using difference_type = std::ptrdiff_t;
2960   using pointer = value_type *;
2961   using reference = value_type &;
2962 
2963   bool operator==(const SDNodeIterator& x) const {
2964     return Operand == x.Operand;
2965   }
2966   bool operator!=(const SDNodeIterator& x) const { return !operator==(x); }
2967 
2968   pointer operator*() const {
2969     return Node->getOperand(Operand).getNode();
2970   }
2971   pointer operator->() const { return operator*(); }
2972 
2973   SDNodeIterator& operator++() {                // Preincrement
2974     ++Operand;
2975     return *this;
2976   }
2977   SDNodeIterator operator++(int) { // Postincrement
2978     SDNodeIterator tmp = *this; ++*this; return tmp;
2979   }
2980   size_t operator-(SDNodeIterator Other) const {
2981     assert(Node == Other.Node &&
2982            "Cannot compare iterators of two different nodes!");
2983     return Operand - Other.Operand;
2984   }
2985 
2986   static SDNodeIterator begin(const SDNode *N) { return SDNodeIterator(N, 0); }
2987   static SDNodeIterator end  (const SDNode *N) {
2988     return SDNodeIterator(N, N->getNumOperands());
2989   }
2990 
2991   unsigned getOperand() const { return Operand; }
2992   const SDNode *getNode() const { return Node; }
2993 };
2994 
2995 template <> struct GraphTraits<SDNode*> {
2996   using NodeRef = SDNode *;
2997   using ChildIteratorType = SDNodeIterator;
2998 
2999   static NodeRef getEntryNode(SDNode *N) { return N; }
3000 
3001   static ChildIteratorType child_begin(NodeRef N) {
3002     return SDNodeIterator::begin(N);
3003   }
3004 
3005   static ChildIteratorType child_end(NodeRef N) {
3006     return SDNodeIterator::end(N);
3007   }
3008 };
3009 
3010 /// A representation of the largest SDNode, for use in sizeof().
3011 ///
3012 /// This needs to be a union because the largest node differs on 32 bit systems
3013 /// with 4 and 8 byte pointer alignment, respectively.
3014 using LargestSDNode = AlignedCharArrayUnion<AtomicSDNode, TargetIndexSDNode,
3015                                             BlockAddressSDNode,
3016                                             GlobalAddressSDNode,
3017                                             PseudoProbeSDNode>;
3018 
3019 /// The SDNode class with the greatest alignment requirement.
3020 using MostAlignedSDNode = GlobalAddressSDNode;
3021 
3022 namespace ISD {
3023 
3024   /// Returns true if the specified node is a non-extending and unindexed load.
3025   inline bool isNormalLoad(const SDNode *N) {
3026     const LoadSDNode *Ld = dyn_cast<LoadSDNode>(N);
3027     return Ld && Ld->getExtensionType() == ISD::NON_EXTLOAD &&
3028       Ld->getAddressingMode() == ISD::UNINDEXED;
3029   }
3030 
3031   /// Returns true if the specified node is a non-extending load.
3032   inline bool isNON_EXTLoad(const SDNode *N) {
3033     return isa<LoadSDNode>(N) &&
3034       cast<LoadSDNode>(N)->getExtensionType() == ISD::NON_EXTLOAD;
3035   }
3036 
3037   /// Returns true if the specified node is a EXTLOAD.
3038   inline bool isEXTLoad(const SDNode *N) {
3039     return isa<LoadSDNode>(N) &&
3040       cast<LoadSDNode>(N)->getExtensionType() == ISD::EXTLOAD;
3041   }
3042 
3043   /// Returns true if the specified node is a SEXTLOAD.
3044   inline bool isSEXTLoad(const SDNode *N) {
3045     return isa<LoadSDNode>(N) &&
3046       cast<LoadSDNode>(N)->getExtensionType() == ISD::SEXTLOAD;
3047   }
3048 
3049   /// Returns true if the specified node is a ZEXTLOAD.
3050   inline bool isZEXTLoad(const SDNode *N) {
3051     return isa<LoadSDNode>(N) &&
3052       cast<LoadSDNode>(N)->getExtensionType() == ISD::ZEXTLOAD;
3053   }
3054 
3055   /// Returns true if the specified node is an unindexed load.
3056   inline bool isUNINDEXEDLoad(const SDNode *N) {
3057     return isa<LoadSDNode>(N) &&
3058       cast<LoadSDNode>(N)->getAddressingMode() == ISD::UNINDEXED;
3059   }
3060 
3061   /// Returns true if the specified node is a non-truncating
3062   /// and unindexed store.
3063   inline bool isNormalStore(const SDNode *N) {
3064     const StoreSDNode *St = dyn_cast<StoreSDNode>(N);
3065     return St && !St->isTruncatingStore() &&
3066       St->getAddressingMode() == ISD::UNINDEXED;
3067   }
3068 
3069   /// Returns true if the specified node is an unindexed store.
3070   inline bool isUNINDEXEDStore(const SDNode *N) {
3071     return isa<StoreSDNode>(N) &&
3072       cast<StoreSDNode>(N)->getAddressingMode() == ISD::UNINDEXED;
3073   }
3074 
3075   /// Attempt to match a unary predicate against a scalar/splat constant or
3076   /// every element of a constant BUILD_VECTOR.
3077   /// If AllowUndef is true, then UNDEF elements will pass nullptr to Match.
3078   bool matchUnaryPredicate(SDValue Op,
3079                            std::function<bool(ConstantSDNode *)> Match,
3080                            bool AllowUndefs = false);
3081 
3082   /// Attempt to match a binary predicate against a pair of scalar/splat
3083   /// constants or every element of a pair of constant BUILD_VECTORs.
3084   /// If AllowUndef is true, then UNDEF elements will pass nullptr to Match.
3085   /// If AllowTypeMismatch is true then RetType + ArgTypes don't need to match.
3086   bool matchBinaryPredicate(
3087       SDValue LHS, SDValue RHS,
3088       std::function<bool(ConstantSDNode *, ConstantSDNode *)> Match,
3089       bool AllowUndefs = false, bool AllowTypeMismatch = false);
3090 
3091   /// Returns true if the specified value is the overflow result from one
3092   /// of the overflow intrinsic nodes.
3093   inline bool isOverflowIntrOpRes(SDValue Op) {
3094     unsigned Opc = Op.getOpcode();
3095     return (Op.getResNo() == 1 &&
3096             (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
3097              Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO));
3098   }
3099 
3100 } // end namespace ISD
3101 
3102 } // end namespace llvm
3103 
3104 #endif // LLVM_CODEGEN_SELECTIONDAGNODES_H
3105