1//===-- llvm/CodeGen/SelectionDAGNodes.h - SelectionDAG Nodes ---*- C++ -*-===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file declares the SDNode class and derived classes, which are used to
11// represent the nodes and operations present in a SelectionDAG.  These nodes
12// and operations are machine code level operations, with some similarities to
13// the GCC RTL representation.
14//
15// Clients should include the SelectionDAG.h file instead of this file directly.
16//
17//===----------------------------------------------------------------------===//
18
19#ifndef LLVM_CODEGEN_SELECTIONDAGNODES_H
20#define LLVM_CODEGEN_SELECTIONDAGNODES_H
21
22#include "llvm/ADT/BitVector.h"
23#include "llvm/ADT/FoldingSet.h"
24#include "llvm/ADT/GraphTraits.h"
25#include "llvm/ADT/STLExtras.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_range.h"
30#include "llvm/CodeGen/ISDOpcodes.h"
31#include "llvm/CodeGen/MachineMemOperand.h"
32#include "llvm/CodeGen/ValueTypes.h"
33#include "llvm/IR/Constants.h"
34#include "llvm/IR/DebugLoc.h"
35#include "llvm/IR/Instructions.h"
36#include "llvm/Support/DataTypes.h"
37#include "llvm/Support/MathExtras.h"
38#include <cassert>
39
40namespace llvm {
41
42class SelectionDAG;
43class GlobalValue;
44class MachineBasicBlock;
45class MachineConstantPoolValue;
46class SDNode;
47class BinaryWithFlagsSDNode;
48class Value;
49class MCSymbol;
50template <typename T> struct DenseMapInfo;
51template <typename T> struct simplify_type;
52template <typename T> struct ilist_traits;
53
54void checkForCycles(const SDNode *N, const SelectionDAG *DAG = nullptr,
55                    bool force = false);
56
57/// This represents a list of ValueType's that has been intern'd by
58/// a SelectionDAG.  Instances of this simple value class are returned by
59/// SelectionDAG::getVTList(...).
60///
61struct SDVTList {
62  const EVT *VTs;
63  unsigned int NumVTs;
64};
65
66namespace ISD {
67  /// Node predicates
68
69  /// Return true if the specified node is a
70  /// BUILD_VECTOR where all of the elements are ~0 or undef.
71  bool isBuildVectorAllOnes(const SDNode *N);
72
73  /// Return true if the specified node is a
74  /// BUILD_VECTOR where all of the elements are 0 or undef.
75  bool isBuildVectorAllZeros(const SDNode *N);
76
77  /// \brief Return true if the specified node is a BUILD_VECTOR node of
78  /// all ConstantSDNode or undef.
79  bool isBuildVectorOfConstantSDNodes(const SDNode *N);
80
81  /// \brief Return true if the specified node is a BUILD_VECTOR node of
82  /// all ConstantFPSDNode or undef.
83  bool isBuildVectorOfConstantFPSDNodes(const SDNode *N);
84
85  /// Return true if the node has at least one operand
86  /// and all operands of the specified node are ISD::UNDEF.
87  bool allOperandsUndef(const SDNode *N);
88}  // end llvm:ISD namespace
89
90//===----------------------------------------------------------------------===//
91/// Unlike LLVM values, Selection DAG nodes may return multiple
92/// values as the result of a computation.  Many nodes return multiple values,
93/// from loads (which define a token and a return value) to ADDC (which returns
94/// a result and a carry value), to calls (which may return an arbitrary number
95/// of values).
96///
97/// As such, each use of a SelectionDAG computation must indicate the node that
98/// computes it as well as which return value to use from that node.  This pair
99/// of information is represented with the SDValue value type.
100///
101class SDValue {
102  friend struct DenseMapInfo<SDValue>;
103
104  SDNode *Node;       // The node defining the value we are using.
105  unsigned ResNo;     // Which return value of the node we are using.
106public:
107  SDValue() : Node(nullptr), ResNo(0) {}
108  SDValue(SDNode *node, unsigned resno);
109
110  /// get the index which selects a specific result in the SDNode
111  unsigned getResNo() const { return ResNo; }
112
113  /// get the SDNode which holds the desired result
114  SDNode *getNode() const { return Node; }
115
116  /// set the SDNode
117  void setNode(SDNode *N) { Node = N; }
118
119  inline SDNode *operator->() const { return Node; }
120
121  bool operator==(const SDValue &O) const {
122    return Node == O.Node && ResNo == O.ResNo;
123  }
124  bool operator!=(const SDValue &O) const {
125    return !operator==(O);
126  }
127  bool operator<(const SDValue &O) const {
128    return std::tie(Node, ResNo) < std::tie(O.Node, O.ResNo);
129  }
130  explicit operator bool() const {
131    return Node != nullptr;
132  }
133
134  SDValue getValue(unsigned R) const {
135    return SDValue(Node, R);
136  }
137
138  /// Return true if this node is an operand of N.
139  bool isOperandOf(const SDNode *N) const;
140
141  /// Return the ValueType of the referenced return value.
142  inline EVT getValueType() const;
143
144  /// Return the simple ValueType of the referenced return value.
145  MVT getSimpleValueType() const {
146    return getValueType().getSimpleVT();
147  }
148
149  /// Returns the size of the value in bits.
150  unsigned getValueSizeInBits() const {
151    return getValueType().getSizeInBits();
152  }
153
154  unsigned getScalarValueSizeInBits() const {
155    return getValueType().getScalarType().getSizeInBits();
156  }
157
158  // Forwarding methods - These forward to the corresponding methods in SDNode.
159  inline unsigned getOpcode() const;
160  inline unsigned getNumOperands() const;
161  inline const SDValue &getOperand(unsigned i) const;
162  inline uint64_t getConstantOperandVal(unsigned i) const;
163  inline bool isTargetMemoryOpcode() const;
164  inline bool isTargetOpcode() const;
165  inline bool isMachineOpcode() const;
166  inline bool isUndef() const;
167  inline unsigned getMachineOpcode() const;
168  inline const DebugLoc &getDebugLoc() const;
169  inline void dump() const;
170  inline void dumpr() const;
171
172  /// Return true if this operand (which must be a chain) reaches the
173  /// specified operand without crossing any side-effecting instructions.
174  /// In practice, this looks through token factors and non-volatile loads.
175  /// In order to remain efficient, this only
176  /// looks a couple of nodes in, it does not do an exhaustive search.
177  bool reachesChainWithoutSideEffects(SDValue Dest,
178                                      unsigned Depth = 2) const;
179
180  /// Return true if there are no nodes using value ResNo of Node.
181  inline bool use_empty() const;
182
183  /// Return true if there is exactly one node using value ResNo of Node.
184  inline bool hasOneUse() const;
185};
186
187
188template<> struct DenseMapInfo<SDValue> {
189  static inline SDValue getEmptyKey() {
190    SDValue V;
191    V.ResNo = -1U;
192    return V;
193  }
194  static inline SDValue getTombstoneKey() {
195    SDValue V;
196    V.ResNo = -2U;
197    return V;
198  }
199  static unsigned getHashValue(const SDValue &Val) {
200    return ((unsigned)((uintptr_t)Val.getNode() >> 4) ^
201            (unsigned)((uintptr_t)Val.getNode() >> 9)) + Val.getResNo();
202  }
203  static bool isEqual(const SDValue &LHS, const SDValue &RHS) {
204    return LHS == RHS;
205  }
206};
207template <> struct isPodLike<SDValue> { static const bool value = true; };
208
209
210/// Allow casting operators to work directly on
211/// SDValues as if they were SDNode*'s.
212template<> struct simplify_type<SDValue> {
213  typedef SDNode* SimpleType;
214  static SimpleType getSimplifiedValue(SDValue &Val) {
215    return Val.getNode();
216  }
217};
218template<> struct simplify_type<const SDValue> {
219  typedef /*const*/ SDNode* SimpleType;
220  static SimpleType getSimplifiedValue(const SDValue &Val) {
221    return Val.getNode();
222  }
223};
224
225/// Represents a use of a SDNode. This class holds an SDValue,
226/// which records the SDNode being used and the result number, a
227/// pointer to the SDNode using the value, and Next and Prev pointers,
228/// which link together all the uses of an SDNode.
229///
230class SDUse {
231  /// Val - The value being used.
232  SDValue Val;
233  /// User - The user of this value.
234  SDNode *User;
235  /// Prev, Next - Pointers to the uses list of the SDNode referred by
236  /// this operand.
237  SDUse **Prev, *Next;
238
239  SDUse(const SDUse &U) = delete;
240  void operator=(const SDUse &U) = delete;
241
242public:
243  SDUse() : Val(), User(nullptr), Prev(nullptr), Next(nullptr) {}
244
245  /// Normally SDUse will just implicitly convert to an SDValue that it holds.
246  operator const SDValue&() const { return Val; }
247
248  /// If implicit conversion to SDValue doesn't work, the get() method returns
249  /// the SDValue.
250  const SDValue &get() const { return Val; }
251
252  /// This returns the SDNode that contains this Use.
253  SDNode *getUser() { return User; }
254
255  /// Get the next SDUse in the use list.
256  SDUse *getNext() const { return Next; }
257
258  /// Convenience function for get().getNode().
259  SDNode *getNode() const { return Val.getNode(); }
260  /// Convenience function for get().getResNo().
261  unsigned getResNo() const { return Val.getResNo(); }
262  /// Convenience function for get().getValueType().
263  EVT getValueType() const { return Val.getValueType(); }
264
265  /// Convenience function for get().operator==
266  bool operator==(const SDValue &V) const {
267    return Val == V;
268  }
269
270  /// Convenience function for get().operator!=
271  bool operator!=(const SDValue &V) const {
272    return Val != V;
273  }
274
275  /// Convenience function for get().operator<
276  bool operator<(const SDValue &V) const {
277    return Val < V;
278  }
279
280private:
281  friend class SelectionDAG;
282  friend class SDNode;
283
284  void setUser(SDNode *p) { User = p; }
285
286  /// Remove this use from its existing use list, assign it the
287  /// given value, and add it to the new value's node's use list.
288  inline void set(const SDValue &V);
289  /// Like set, but only supports initializing a newly-allocated
290  /// SDUse with a non-null value.
291  inline void setInitial(const SDValue &V);
292  /// Like set, but only sets the Node portion of the value,
293  /// leaving the ResNo portion unmodified.
294  inline void setNode(SDNode *N);
295
296  void addToList(SDUse **List) {
297    Next = *List;
298    if (Next) Next->Prev = &Next;
299    Prev = List;
300    *List = this;
301  }
302
303  void removeFromList() {
304    *Prev = Next;
305    if (Next) Next->Prev = Prev;
306  }
307};
308
309/// simplify_type specializations - Allow casting operators to work directly on
310/// SDValues as if they were SDNode*'s.
311template<> struct simplify_type<SDUse> {
312  typedef SDNode* SimpleType;
313  static SimpleType getSimplifiedValue(SDUse &Val) {
314    return Val.getNode();
315  }
316};
317
318/// These are IR-level optimization flags that may be propagated to SDNodes.
319/// TODO: This data structure should be shared by the IR optimizer and the
320/// the backend.
321struct SDNodeFlags {
322private:
323  bool NoUnsignedWrap : 1;
324  bool NoSignedWrap : 1;
325  bool Exact : 1;
326  bool UnsafeAlgebra : 1;
327  bool NoNaNs : 1;
328  bool NoInfs : 1;
329  bool NoSignedZeros : 1;
330  bool AllowReciprocal : 1;
331
332public:
333  /// Default constructor turns off all optimization flags.
334  SDNodeFlags() {
335    NoUnsignedWrap = false;
336    NoSignedWrap = false;
337    Exact = false;
338    UnsafeAlgebra = false;
339    NoNaNs = false;
340    NoInfs = false;
341    NoSignedZeros = false;
342    AllowReciprocal = false;
343  }
344
345  // These are mutators for each flag.
346  void setNoUnsignedWrap(bool b) { NoUnsignedWrap = b; }
347  void setNoSignedWrap(bool b) { NoSignedWrap = b; }
348  void setExact(bool b) { Exact = b; }
349  void setUnsafeAlgebra(bool b) { UnsafeAlgebra = b; }
350  void setNoNaNs(bool b) { NoNaNs = b; }
351  void setNoInfs(bool b) { NoInfs = b; }
352  void setNoSignedZeros(bool b) { NoSignedZeros = b; }
353  void setAllowReciprocal(bool b) { AllowReciprocal = b; }
354
355  // These are accessors for each flag.
356  bool hasNoUnsignedWrap() const { return NoUnsignedWrap; }
357  bool hasNoSignedWrap() const { return NoSignedWrap; }
358  bool hasExact() const { return Exact; }
359  bool hasUnsafeAlgebra() const { return UnsafeAlgebra; }
360  bool hasNoNaNs() const { return NoNaNs; }
361  bool hasNoInfs() const { return NoInfs; }
362  bool hasNoSignedZeros() const { return NoSignedZeros; }
363  bool hasAllowReciprocal() const { return AllowReciprocal; }
364
365  /// Return a raw encoding of the flags.
366  /// This function should only be used to add data to the NodeID value.
367  unsigned getRawFlags() const {
368    return (NoUnsignedWrap << 0) | (NoSignedWrap << 1) | (Exact << 2) |
369    (UnsafeAlgebra << 3) | (NoNaNs << 4) | (NoInfs << 5) |
370    (NoSignedZeros << 6) | (AllowReciprocal << 7);
371  }
372};
373
374/// Represents one node in the SelectionDAG.
375///
376class SDNode : public FoldingSetNode, public ilist_node<SDNode> {
377private:
378  /// The operation that this node performs.
379  int16_t NodeType;
380
381  /// This is true if OperandList was new[]'d.  If true,
382  /// then they will be delete[]'d when the node is destroyed.
383  uint16_t OperandsNeedDelete : 1;
384
385  /// This tracks whether this node has one or more dbg_value
386  /// nodes corresponding to it.
387  uint16_t HasDebugValue : 1;
388
389protected:
390  /// This member is defined by this class, but is not used for
391  /// anything.  Subclasses can use it to hold whatever state they find useful.
392  /// This field is initialized to zero by the ctor.
393  uint16_t SubclassData : 14;
394
395private:
396  /// Unique id per SDNode in the DAG.
397  int NodeId;
398
399  /// The values that are used by this operation.
400  SDUse *OperandList;
401
402  /// The types of the values this node defines.  SDNode's may
403  /// define multiple values simultaneously.
404  const EVT *ValueList;
405
406  /// List of uses for this SDNode.
407  SDUse *UseList;
408
409  /// The number of entries in the Operand/Value list.
410  unsigned short NumOperands, NumValues;
411
412  // The ordering of the SDNodes. It roughly corresponds to the ordering of the
413  // original LLVM instructions.
414  // This is used for turning off scheduling, because we'll forgo
415  // the normal scheduling algorithms and output the instructions according to
416  // this ordering.
417  unsigned IROrder;
418
419  /// Source line information.
420  DebugLoc debugLoc;
421
422  /// Return a pointer to the specified value type.
423  static const EVT *getValueTypeList(EVT VT);
424
425  friend class SelectionDAG;
426  friend struct ilist_traits<SDNode>;
427
428public:
429  /// Unique and persistent id per SDNode in the DAG.
430  /// Used for debug printing.
431  uint16_t PersistentId;
432
433  //===--------------------------------------------------------------------===//
434  //  Accessors
435  //
436
437  /// Return the SelectionDAG opcode value for this node. For
438  /// pre-isel nodes (those for which isMachineOpcode returns false), these
439  /// are the opcode values in the ISD and <target>ISD namespaces. For
440  /// post-isel opcodes, see getMachineOpcode.
441  unsigned getOpcode()  const { return (unsigned short)NodeType; }
442
443  /// Test if this node has a target-specific opcode (in the
444  /// \<target\>ISD namespace).
445  bool isTargetOpcode() const { return NodeType >= ISD::BUILTIN_OP_END; }
446
447  /// Test if this node has a target-specific
448  /// memory-referencing opcode (in the \<target\>ISD namespace and
449  /// greater than FIRST_TARGET_MEMORY_OPCODE).
450  bool isTargetMemoryOpcode() const {
451    return NodeType >= ISD::FIRST_TARGET_MEMORY_OPCODE;
452  }
453
454  /// Return true if the type of the node type undefined.
455  bool isUndef() const { return NodeType == ISD::UNDEF; }
456
457  /// Test if this node is a memory intrinsic (with valid pointer information).
458  /// INTRINSIC_W_CHAIN and INTRINSIC_VOID nodes are sometimes created for
459  /// non-memory intrinsics (with chains) that are not really instances of
460  /// MemSDNode. For such nodes, we need some extra state to determine the
461  /// proper classof relationship.
462  bool isMemIntrinsic() const {
463    return (NodeType == ISD::INTRINSIC_W_CHAIN ||
464            NodeType == ISD::INTRINSIC_VOID) && ((SubclassData >> 13) & 1);
465  }
466
467  /// Test if this node has a post-isel opcode, directly
468  /// corresponding to a MachineInstr opcode.
469  bool isMachineOpcode() const { return NodeType < 0; }
470
471  /// This may only be called if isMachineOpcode returns
472  /// true. It returns the MachineInstr opcode value that the node's opcode
473  /// corresponds to.
474  unsigned getMachineOpcode() const {
475    assert(isMachineOpcode() && "Not a MachineInstr opcode!");
476    return ~NodeType;
477  }
478
479  /// Get this bit.
480  bool getHasDebugValue() const { return HasDebugValue; }
481
482  /// Set this bit.
483  void setHasDebugValue(bool b) { HasDebugValue = b; }
484
485  /// Return true if there are no uses of this node.
486  bool use_empty() const { return UseList == nullptr; }
487
488  /// Return true if there is exactly one use of this node.
489  bool hasOneUse() const {
490    return !use_empty() && std::next(use_begin()) == use_end();
491  }
492
493  /// Return the number of uses of this node. This method takes
494  /// time proportional to the number of uses.
495  size_t use_size() const { return std::distance(use_begin(), use_end()); }
496
497  /// Return the unique node id.
498  int getNodeId() const { return NodeId; }
499
500  /// Set unique node id.
501  void setNodeId(int Id) { NodeId = Id; }
502
503  /// Return the node ordering.
504  unsigned getIROrder() const { return IROrder; }
505
506  /// Set the node ordering.
507  void setIROrder(unsigned Order) { IROrder = Order; }
508
509  /// Return the source location info.
510  const DebugLoc &getDebugLoc() const { return debugLoc; }
511
512  /// Set source location info.  Try to avoid this, putting
513  /// it in the constructor is preferable.
514  void setDebugLoc(DebugLoc dl) { debugLoc = std::move(dl); }
515
516  /// This class provides iterator support for SDUse
517  /// operands that use a specific SDNode.
518  class use_iterator
519    : public std::iterator<std::forward_iterator_tag, SDUse, ptrdiff_t> {
520    SDUse *Op;
521    explicit use_iterator(SDUse *op) : Op(op) {
522    }
523    friend class SDNode;
524  public:
525    typedef std::iterator<std::forward_iterator_tag,
526                          SDUse, ptrdiff_t>::reference reference;
527    typedef std::iterator<std::forward_iterator_tag,
528                          SDUse, ptrdiff_t>::pointer pointer;
529
530    use_iterator(const use_iterator &I) : Op(I.Op) {}
531    use_iterator() : Op(nullptr) {}
532
533    bool operator==(const use_iterator &x) const {
534      return Op == x.Op;
535    }
536    bool operator!=(const use_iterator &x) const {
537      return !operator==(x);
538    }
539
540    /// Return true if this iterator is at the end of uses list.
541    bool atEnd() const { return Op == nullptr; }
542
543    // Iterator traversal: forward iteration only.
544    use_iterator &operator++() {          // Preincrement
545      assert(Op && "Cannot increment end iterator!");
546      Op = Op->getNext();
547      return *this;
548    }
549
550    use_iterator operator++(int) {        // Postincrement
551      use_iterator tmp = *this; ++*this; return tmp;
552    }
553
554    /// Retrieve a pointer to the current user node.
555    SDNode *operator*() const {
556      assert(Op && "Cannot dereference end iterator!");
557      return Op->getUser();
558    }
559
560    SDNode *operator->() const { return operator*(); }
561
562    SDUse &getUse() const { return *Op; }
563
564    /// Retrieve the operand # of this use in its user.
565    unsigned getOperandNo() const {
566      assert(Op && "Cannot dereference end iterator!");
567      return (unsigned)(Op - Op->getUser()->OperandList);
568    }
569  };
570
571  /// Provide iteration support to walk over all uses of an SDNode.
572  use_iterator use_begin() const {
573    return use_iterator(UseList);
574  }
575
576  static use_iterator use_end() { return use_iterator(nullptr); }
577
578  inline iterator_range<use_iterator> uses() {
579    return make_range(use_begin(), use_end());
580  }
581  inline iterator_range<use_iterator> uses() const {
582    return make_range(use_begin(), use_end());
583  }
584
585  /// Return true if there are exactly NUSES uses of the indicated value.
586  /// This method ignores uses of other values defined by this operation.
587  bool hasNUsesOfValue(unsigned NUses, unsigned Value) const;
588
589  /// Return true if there are any use of the indicated value.
590  /// This method ignores uses of other values defined by this operation.
591  bool hasAnyUseOfValue(unsigned Value) const;
592
593  /// Return true if this node is the only use of N.
594  bool isOnlyUserOf(const SDNode *N) const;
595
596  /// Return true if this node is an operand of N.
597  bool isOperandOf(const SDNode *N) const;
598
599  /// Return true if this node is a predecessor of N.
600  /// NOTE: Implemented on top of hasPredecessor and every bit as
601  /// expensive. Use carefully.
602  bool isPredecessorOf(const SDNode *N) const {
603    return N->hasPredecessor(this);
604  }
605
606  /// Return true if N is a predecessor of this node.
607  /// N is either an operand of this node, or can be reached by recursively
608  /// traversing up the operands.
609  /// NOTE: This is an expensive method. Use it carefully.
610  bool hasPredecessor(const SDNode *N) const;
611
612  /// Return true if N is a predecessor of this node.
613  /// N is either an operand of this node, or can be reached by recursively
614  /// traversing up the operands.
615  /// In this helper the Visited and worklist sets are held externally to
616  /// cache predecessors over multiple invocations. If you want to test for
617  /// multiple predecessors this method is preferable to multiple calls to
618  /// hasPredecessor. Be sure to clear Visited and Worklist if the DAG
619  /// changes.
620  /// NOTE: This is still very expensive. Use carefully.
621  bool hasPredecessorHelper(const SDNode *N,
622                            SmallPtrSetImpl<const SDNode *> &Visited,
623                            SmallVectorImpl<const SDNode *> &Worklist) const;
624
625  /// Return the number of values used by this operation.
626  unsigned getNumOperands() const { return NumOperands; }
627
628  /// Helper method returns the integer value of a ConstantSDNode operand.
629  uint64_t getConstantOperandVal(unsigned Num) const;
630
631  const SDValue &getOperand(unsigned Num) const {
632    assert(Num < NumOperands && "Invalid child # of SDNode!");
633    return OperandList[Num];
634  }
635
636  typedef SDUse* op_iterator;
637  op_iterator op_begin() const { return OperandList; }
638  op_iterator op_end() const { return OperandList+NumOperands; }
639  ArrayRef<SDUse> ops() const { return makeArrayRef(op_begin(), op_end()); }
640
641  /// Iterator for directly iterating over the operand SDValue's.
642  struct value_op_iterator
643      : iterator_adaptor_base<value_op_iterator, op_iterator,
644                              std::random_access_iterator_tag, SDValue,
645                              ptrdiff_t, value_op_iterator *,
646                              value_op_iterator *> {
647    explicit value_op_iterator(SDUse *U = nullptr)
648      : iterator_adaptor_base(U) {}
649
650    const SDValue &operator*() const { return I->get(); }
651  };
652
653  iterator_range<value_op_iterator> op_values() const {
654    return make_range(value_op_iterator(op_begin()),
655                      value_op_iterator(op_end()));
656  }
657
658  SDVTList getVTList() const {
659    SDVTList X = { ValueList, NumValues };
660    return X;
661  }
662
663  /// If this node has a glue operand, return the node
664  /// to which the glue operand points. Otherwise return NULL.
665  SDNode *getGluedNode() const {
666    if (getNumOperands() != 0 &&
667        getOperand(getNumOperands()-1).getValueType() == MVT::Glue)
668      return getOperand(getNumOperands()-1).getNode();
669    return nullptr;
670  }
671
672  /// If this node has a glue value with a user, return
673  /// the user (there is at most one). Otherwise return NULL.
674  SDNode *getGluedUser() const {
675    for (use_iterator UI = use_begin(), UE = use_end(); UI != UE; ++UI)
676      if (UI.getUse().get().getValueType() == MVT::Glue)
677        return *UI;
678    return nullptr;
679  }
680
681  /// This could be defined as a virtual function and implemented more simply
682  /// and directly, but it is not to avoid creating a vtable for this class.
683  const SDNodeFlags *getFlags() const;
684
685  /// Return the number of values defined/returned by this operator.
686  unsigned getNumValues() const { return NumValues; }
687
688  /// Return the type of a specified result.
689  EVT getValueType(unsigned ResNo) const {
690    assert(ResNo < NumValues && "Illegal result number!");
691    return ValueList[ResNo];
692  }
693
694  /// Return the type of a specified result as a simple type.
695  MVT getSimpleValueType(unsigned ResNo) const {
696    return getValueType(ResNo).getSimpleVT();
697  }
698
699  /// Returns MVT::getSizeInBits(getValueType(ResNo)).
700  unsigned getValueSizeInBits(unsigned ResNo) const {
701    return getValueType(ResNo).getSizeInBits();
702  }
703
704  typedef const EVT* value_iterator;
705  value_iterator value_begin() const { return ValueList; }
706  value_iterator value_end() const { return ValueList+NumValues; }
707
708  /// Return the opcode of this operation for printing.
709  std::string getOperationName(const SelectionDAG *G = nullptr) const;
710  static const char* getIndexedModeName(ISD::MemIndexedMode AM);
711  void print_types(raw_ostream &OS, const SelectionDAG *G) const;
712  void print_details(raw_ostream &OS, const SelectionDAG *G) const;
713  void print(raw_ostream &OS, const SelectionDAG *G = nullptr) const;
714  void printr(raw_ostream &OS, const SelectionDAG *G = nullptr) const;
715
716  /// Print a SelectionDAG node and all children down to
717  /// the leaves.  The given SelectionDAG allows target-specific nodes
718  /// to be printed in human-readable form.  Unlike printr, this will
719  /// print the whole DAG, including children that appear multiple
720  /// times.
721  ///
722  void printrFull(raw_ostream &O, const SelectionDAG *G = nullptr) const;
723
724  /// Print a SelectionDAG node and children up to
725  /// depth "depth."  The given SelectionDAG allows target-specific
726  /// nodes to be printed in human-readable form.  Unlike printr, this
727  /// will print children that appear multiple times wherever they are
728  /// used.
729  ///
730  void printrWithDepth(raw_ostream &O, const SelectionDAG *G = nullptr,
731                       unsigned depth = 100) const;
732
733
734  /// Dump this node, for debugging.
735  void dump() const;
736
737  /// Dump (recursively) this node and its use-def subgraph.
738  void dumpr() const;
739
740  /// Dump this node, for debugging.
741  /// The given SelectionDAG allows target-specific nodes to be printed
742  /// in human-readable form.
743  void dump(const SelectionDAG *G) const;
744
745  /// Dump (recursively) this node and its use-def subgraph.
746  /// The given SelectionDAG allows target-specific nodes to be printed
747  /// in human-readable form.
748  void dumpr(const SelectionDAG *G) const;
749
750  /// printrFull to dbgs().  The given SelectionDAG allows
751  /// target-specific nodes to be printed in human-readable form.
752  /// Unlike dumpr, this will print the whole DAG, including children
753  /// that appear multiple times.
754  void dumprFull(const SelectionDAG *G = nullptr) const;
755
756  /// printrWithDepth to dbgs().  The given
757  /// SelectionDAG allows target-specific nodes to be printed in
758  /// human-readable form.  Unlike dumpr, this will print children
759  /// that appear multiple times wherever they are used.
760  ///
761  void dumprWithDepth(const SelectionDAG *G = nullptr,
762                      unsigned depth = 100) const;
763
764  /// Gather unique data for the node.
765  void Profile(FoldingSetNodeID &ID) const;
766
767  /// This method should only be used by the SDUse class.
768  void addUse(SDUse &U) { U.addToList(&UseList); }
769
770protected:
771  static SDVTList getSDVTList(EVT VT) {
772    SDVTList Ret = { getValueTypeList(VT), 1 };
773    return Ret;
774  }
775
776  SDNode(unsigned Opc, unsigned Order, DebugLoc dl, SDVTList VTs,
777         ArrayRef<SDValue> Ops)
778      : NodeType(Opc), OperandsNeedDelete(true), HasDebugValue(false),
779        SubclassData(0), NodeId(-1),
780        OperandList(Ops.size() ? new SDUse[Ops.size()] : nullptr),
781        ValueList(VTs.VTs), UseList(nullptr), NumOperands(Ops.size()),
782        NumValues(VTs.NumVTs), IROrder(Order), debugLoc(std::move(dl)) {
783    assert(debugLoc.hasTrivialDestructor() && "Expected trivial destructor");
784    assert(NumOperands == Ops.size() &&
785           "NumOperands wasn't wide enough for its operands!");
786    assert(NumValues == VTs.NumVTs &&
787           "NumValues wasn't wide enough for its operands!");
788    for (unsigned i = 0; i != Ops.size(); ++i) {
789      assert(OperandList && "no operands available");
790      OperandList[i].setUser(this);
791      OperandList[i].setInitial(Ops[i]);
792    }
793    checkForCycles(this);
794  }
795
796  /// This constructor adds no operands itself; operands can be
797  /// set later with InitOperands.
798  SDNode(unsigned Opc, unsigned Order, DebugLoc dl, SDVTList VTs)
799      : NodeType(Opc), OperandsNeedDelete(false), HasDebugValue(false),
800        SubclassData(0), NodeId(-1), OperandList(nullptr), ValueList(VTs.VTs),
801        UseList(nullptr), NumOperands(0), NumValues(VTs.NumVTs),
802        IROrder(Order), debugLoc(std::move(dl)) {
803    assert(debugLoc.hasTrivialDestructor() && "Expected trivial destructor");
804    assert(NumValues == VTs.NumVTs &&
805           "NumValues wasn't wide enough for its operands!");
806  }
807
808  /// Initialize the operands list of this with 1 operand.
809  void InitOperands(SDUse *Ops, const SDValue &Op0) {
810    Ops[0].setUser(this);
811    Ops[0].setInitial(Op0);
812    NumOperands = 1;
813    OperandList = Ops;
814    checkForCycles(this);
815  }
816
817  /// Initialize the operands list of this with 2 operands.
818  void InitOperands(SDUse *Ops, const SDValue &Op0, const SDValue &Op1) {
819    Ops[0].setUser(this);
820    Ops[0].setInitial(Op0);
821    Ops[1].setUser(this);
822    Ops[1].setInitial(Op1);
823    NumOperands = 2;
824    OperandList = Ops;
825    checkForCycles(this);
826  }
827
828  /// Initialize the operands list of this with 3 operands.
829  void InitOperands(SDUse *Ops, const SDValue &Op0, const SDValue &Op1,
830                    const SDValue &Op2) {
831    Ops[0].setUser(this);
832    Ops[0].setInitial(Op0);
833    Ops[1].setUser(this);
834    Ops[1].setInitial(Op1);
835    Ops[2].setUser(this);
836    Ops[2].setInitial(Op2);
837    NumOperands = 3;
838    OperandList = Ops;
839    checkForCycles(this);
840  }
841
842  /// Initialize the operands list of this with 4 operands.
843  void InitOperands(SDUse *Ops, const SDValue &Op0, const SDValue &Op1,
844                    const SDValue &Op2, const SDValue &Op3) {
845    Ops[0].setUser(this);
846    Ops[0].setInitial(Op0);
847    Ops[1].setUser(this);
848    Ops[1].setInitial(Op1);
849    Ops[2].setUser(this);
850    Ops[2].setInitial(Op2);
851    Ops[3].setUser(this);
852    Ops[3].setInitial(Op3);
853    NumOperands = 4;
854    OperandList = Ops;
855    checkForCycles(this);
856  }
857
858  /// Initialize the operands list of this with N operands.
859  void InitOperands(SDUse *Ops, const SDValue *Vals, unsigned N) {
860    for (unsigned i = 0; i != N; ++i) {
861      Ops[i].setUser(this);
862      Ops[i].setInitial(Vals[i]);
863    }
864    NumOperands = N;
865    assert(NumOperands == N &&
866           "NumOperands wasn't wide enough for its operands!");
867    OperandList = Ops;
868    checkForCycles(this);
869  }
870
871  /// Release the operands and set this node to have zero operands.
872  void DropOperands();
873};
874
875/// Wrapper class for IR location info (IR ordering and DebugLoc) to be passed
876/// into SDNode creation functions.
877/// When an SDNode is created from the DAGBuilder, the DebugLoc is extracted
878/// from the original Instruction, and IROrder is the ordinal position of
879/// the instruction.
880/// When an SDNode is created after the DAG is being built, both DebugLoc and
881/// the IROrder are propagated from the original SDNode.
882/// So SDLoc class provides two constructors besides the default one, one to
883/// be used by the DAGBuilder, the other to be used by others.
884class SDLoc {
885private:
886  // Ptr could be used for either Instruction* or SDNode*. It is used for
887  // Instruction* if IROrder is not -1.
888  const void *Ptr;
889  int IROrder;
890
891public:
892  SDLoc() : Ptr(nullptr), IROrder(0) {}
893  SDLoc(const SDNode *N) : Ptr(N), IROrder(-1) {
894    assert(N && "null SDNode");
895  }
896  SDLoc(const SDValue V) : Ptr(V.getNode()), IROrder(-1) {
897    assert(Ptr && "null SDNode");
898  }
899  SDLoc(const Instruction *I, int Order) : Ptr(I), IROrder(Order) {
900    assert(Order >= 0 && "bad IROrder");
901  }
902  unsigned getIROrder() {
903    if (IROrder >= 0 || Ptr == nullptr) {
904      return (unsigned)IROrder;
905    }
906    const SDNode *N = (const SDNode*)(Ptr);
907    return N->getIROrder();
908  }
909  DebugLoc getDebugLoc() {
910    if (!Ptr) {
911      return DebugLoc();
912    }
913    if (IROrder >= 0) {
914      const Instruction *I = (const Instruction*)(Ptr);
915      return I->getDebugLoc();
916    }
917    const SDNode *N = (const SDNode*)(Ptr);
918    return N->getDebugLoc();
919  }
920};
921
922
923// Define inline functions from the SDValue class.
924
925inline SDValue::SDValue(SDNode *node, unsigned resno)
926    : Node(node), ResNo(resno) {
927  assert((!Node || ResNo < Node->getNumValues()) &&
928         "Invalid result number for the given node!");
929  assert(ResNo < -2U && "Cannot use result numbers reserved for DenseMaps.");
930}
931
932inline unsigned SDValue::getOpcode() const {
933  return Node->getOpcode();
934}
935inline EVT SDValue::getValueType() const {
936  return Node->getValueType(ResNo);
937}
938inline unsigned SDValue::getNumOperands() const {
939  return Node->getNumOperands();
940}
941inline const SDValue &SDValue::getOperand(unsigned i) const {
942  return Node->getOperand(i);
943}
944inline uint64_t SDValue::getConstantOperandVal(unsigned i) const {
945  return Node->getConstantOperandVal(i);
946}
947inline bool SDValue::isTargetOpcode() const {
948  return Node->isTargetOpcode();
949}
950inline bool SDValue::isTargetMemoryOpcode() const {
951  return Node->isTargetMemoryOpcode();
952}
953inline bool SDValue::isMachineOpcode() const {
954  return Node->isMachineOpcode();
955}
956inline unsigned SDValue::getMachineOpcode() const {
957  return Node->getMachineOpcode();
958}
959inline bool SDValue::isUndef() const {
960  return Node->isUndef();
961}
962inline bool SDValue::use_empty() const {
963  return !Node->hasAnyUseOfValue(ResNo);
964}
965inline bool SDValue::hasOneUse() const {
966  return Node->hasNUsesOfValue(1, ResNo);
967}
968inline const DebugLoc &SDValue::getDebugLoc() const {
969  return Node->getDebugLoc();
970}
971inline void SDValue::dump() const {
972  return Node->dump();
973}
974inline void SDValue::dumpr() const {
975  return Node->dumpr();
976}
977// Define inline functions from the SDUse class.
978
979inline void SDUse::set(const SDValue &V) {
980  if (Val.getNode()) removeFromList();
981  Val = V;
982  if (V.getNode()) V.getNode()->addUse(*this);
983}
984
985inline void SDUse::setInitial(const SDValue &V) {
986  Val = V;
987  V.getNode()->addUse(*this);
988}
989
990inline void SDUse::setNode(SDNode *N) {
991  if (Val.getNode()) removeFromList();
992  Val.setNode(N);
993  if (N) N->addUse(*this);
994}
995
996/// This class is used for single-operand SDNodes.  This is solely
997/// to allow co-allocation of node operands with the node itself.
998class UnarySDNode : public SDNode {
999  SDUse Op;
1000public:
1001  UnarySDNode(unsigned Opc, unsigned Order, DebugLoc dl, SDVTList VTs,
1002              SDValue X)
1003    : SDNode(Opc, Order, dl, VTs) {
1004    InitOperands(&Op, X);
1005  }
1006};
1007
1008/// This class is used for two-operand SDNodes.  This is solely
1009/// to allow co-allocation of node operands with the node itself.
1010class BinarySDNode : public SDNode {
1011  SDUse Ops[2];
1012public:
1013  BinarySDNode(unsigned Opc, unsigned Order, DebugLoc dl, SDVTList VTs,
1014               SDValue X, SDValue Y)
1015    : SDNode(Opc, Order, dl, VTs) {
1016    InitOperands(Ops, X, Y);
1017  }
1018};
1019
1020/// Returns true if the opcode is a binary operation with flags.
1021static bool isBinOpWithFlags(unsigned Opcode) {
1022  switch (Opcode) {
1023  case ISD::SDIV:
1024  case ISD::UDIV:
1025  case ISD::SRA:
1026  case ISD::SRL:
1027  case ISD::MUL:
1028  case ISD::ADD:
1029  case ISD::SUB:
1030  case ISD::SHL:
1031  case ISD::FADD:
1032  case ISD::FDIV:
1033  case ISD::FMUL:
1034  case ISD::FREM:
1035  case ISD::FSUB:
1036    return true;
1037  default:
1038    return false;
1039  }
1040}
1041
1042/// This class is an extension of BinarySDNode
1043/// used from those opcodes that have associated extra flags.
1044class BinaryWithFlagsSDNode : public BinarySDNode {
1045public:
1046  SDNodeFlags Flags;
1047  BinaryWithFlagsSDNode(unsigned Opc, unsigned Order, DebugLoc dl, SDVTList VTs,
1048                        SDValue X, SDValue Y, const SDNodeFlags &NodeFlags)
1049      : BinarySDNode(Opc, Order, dl, VTs, X, Y), Flags(NodeFlags) {}
1050  static bool classof(const SDNode *N) {
1051    return isBinOpWithFlags(N->getOpcode());
1052  }
1053};
1054
1055/// This class is used for three-operand SDNodes. This is solely
1056/// to allow co-allocation of node operands with the node itself.
1057class TernarySDNode : public SDNode {
1058  SDUse Ops[3];
1059public:
1060  TernarySDNode(unsigned Opc, unsigned Order, DebugLoc dl, SDVTList VTs,
1061                SDValue X, SDValue Y, SDValue Z)
1062    : SDNode(Opc, Order, dl, VTs) {
1063    InitOperands(Ops, X, Y, Z);
1064  }
1065};
1066
1067
1068/// This class is used to form a handle around another node that
1069/// is persistent and is updated across invocations of replaceAllUsesWith on its
1070/// operand.  This node should be directly created by end-users and not added to
1071/// the AllNodes list.
1072class HandleSDNode : public SDNode {
1073  SDUse Op;
1074public:
1075  explicit HandleSDNode(SDValue X)
1076    : SDNode(ISD::HANDLENODE, 0, DebugLoc(), getSDVTList(MVT::Other)) {
1077    // HandleSDNodes are never inserted into the DAG, so they won't be
1078    // auto-numbered. Use ID 65535 as a sentinel.
1079    PersistentId = 0xffff;
1080    InitOperands(&Op, X);
1081  }
1082  ~HandleSDNode();
1083  const SDValue &getValue() const { return Op; }
1084};
1085
1086class AddrSpaceCastSDNode : public UnarySDNode {
1087private:
1088  unsigned SrcAddrSpace;
1089  unsigned DestAddrSpace;
1090
1091public:
1092  AddrSpaceCastSDNode(unsigned Order, DebugLoc dl, EVT VT, SDValue X,
1093                      unsigned SrcAS, unsigned DestAS);
1094
1095  unsigned getSrcAddressSpace() const { return SrcAddrSpace; }
1096  unsigned getDestAddressSpace() const { return DestAddrSpace; }
1097
1098  static bool classof(const SDNode *N) {
1099    return N->getOpcode() == ISD::ADDRSPACECAST;
1100  }
1101};
1102
1103/// This is an abstract virtual class for memory operations.
1104class MemSDNode : public SDNode {
1105private:
1106  // VT of in-memory value.
1107  EVT MemoryVT;
1108
1109protected:
1110  /// Memory reference information.
1111  MachineMemOperand *MMO;
1112
1113public:
1114  MemSDNode(unsigned Opc, unsigned Order, DebugLoc dl, SDVTList VTs,
1115            EVT MemoryVT, MachineMemOperand *MMO);
1116
1117  MemSDNode(unsigned Opc, unsigned Order, DebugLoc dl, SDVTList VTs,
1118            ArrayRef<SDValue> Ops, EVT MemoryVT, MachineMemOperand *MMO);
1119
1120  bool readMem() const { return MMO->isLoad(); }
1121  bool writeMem() const { return MMO->isStore(); }
1122
1123  /// Returns alignment and volatility of the memory access
1124  unsigned getOriginalAlignment() const {
1125    return MMO->getBaseAlignment();
1126  }
1127  unsigned getAlignment() const {
1128    return MMO->getAlignment();
1129  }
1130
1131  /// Return the SubclassData value, which contains an
1132  /// encoding of the volatile flag, as well as bits used by subclasses. This
1133  /// function should only be used to compute a FoldingSetNodeID value.
1134  unsigned getRawSubclassData() const {
1135    return SubclassData;
1136  }
1137
1138  // We access subclass data here so that we can check consistency
1139  // with MachineMemOperand information.
1140  bool isVolatile() const { return (SubclassData >> 5) & 1; }
1141  bool isNonTemporal() const { return (SubclassData >> 6) & 1; }
1142  bool isInvariant() const { return (SubclassData >> 7) & 1; }
1143
1144  AtomicOrdering getOrdering() const {
1145    return AtomicOrdering((SubclassData >> 8) & 15);
1146  }
1147  SynchronizationScope getSynchScope() const {
1148    return SynchronizationScope((SubclassData >> 12) & 1);
1149  }
1150
1151  // Returns the offset from the location of the access.
1152  int64_t getSrcValueOffset() const { return MMO->getOffset(); }
1153
1154  /// Returns the AA info that describes the dereference.
1155  AAMDNodes getAAInfo() const { return MMO->getAAInfo(); }
1156
1157  /// Returns the Ranges that describes the dereference.
1158  const MDNode *getRanges() const { return MMO->getRanges(); }
1159
1160  /// Return the type of the in-memory value.
1161  EVT getMemoryVT() const { return MemoryVT; }
1162
1163  /// Return a MachineMemOperand object describing the memory
1164  /// reference performed by operation.
1165  MachineMemOperand *getMemOperand() const { return MMO; }
1166
1167  const MachinePointerInfo &getPointerInfo() const {
1168    return MMO->getPointerInfo();
1169  }
1170
1171  /// Return the address space for the associated pointer
1172  unsigned getAddressSpace() const {
1173    return getPointerInfo().getAddrSpace();
1174  }
1175
1176  /// Update this MemSDNode's MachineMemOperand information
1177  /// to reflect the alignment of NewMMO, if it has a greater alignment.
1178  /// This must only be used when the new alignment applies to all users of
1179  /// this MachineMemOperand.
1180  void refineAlignment(const MachineMemOperand *NewMMO) {
1181    MMO->refineAlignment(NewMMO);
1182  }
1183
1184  const SDValue &getChain() const { return getOperand(0); }
1185  const SDValue &getBasePtr() const {
1186    return getOperand(getOpcode() == ISD::STORE ? 2 : 1);
1187  }
1188
1189  // Methods to support isa and dyn_cast
1190  static bool classof(const SDNode *N) {
1191    // For some targets, we lower some target intrinsics to a MemIntrinsicNode
1192    // with either an intrinsic or a target opcode.
1193    return N->getOpcode() == ISD::LOAD                ||
1194           N->getOpcode() == ISD::STORE               ||
1195           N->getOpcode() == ISD::PREFETCH            ||
1196           N->getOpcode() == ISD::ATOMIC_CMP_SWAP     ||
1197           N->getOpcode() == ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS ||
1198           N->getOpcode() == ISD::ATOMIC_SWAP         ||
1199           N->getOpcode() == ISD::ATOMIC_LOAD_ADD     ||
1200           N->getOpcode() == ISD::ATOMIC_LOAD_SUB     ||
1201           N->getOpcode() == ISD::ATOMIC_LOAD_AND     ||
1202           N->getOpcode() == ISD::ATOMIC_LOAD_OR      ||
1203           N->getOpcode() == ISD::ATOMIC_LOAD_XOR     ||
1204           N->getOpcode() == ISD::ATOMIC_LOAD_NAND    ||
1205           N->getOpcode() == ISD::ATOMIC_LOAD_MIN     ||
1206           N->getOpcode() == ISD::ATOMIC_LOAD_MAX     ||
1207           N->getOpcode() == ISD::ATOMIC_LOAD_UMIN    ||
1208           N->getOpcode() == ISD::ATOMIC_LOAD_UMAX    ||
1209           N->getOpcode() == ISD::ATOMIC_LOAD         ||
1210           N->getOpcode() == ISD::ATOMIC_STORE        ||
1211           N->getOpcode() == ISD::MLOAD               ||
1212           N->getOpcode() == ISD::MSTORE              ||
1213           N->getOpcode() == ISD::MGATHER             ||
1214           N->getOpcode() == ISD::MSCATTER            ||
1215           N->isMemIntrinsic()                        ||
1216           N->isTargetMemoryOpcode();
1217  }
1218};
1219
1220/// This is an SDNode representing atomic operations.
1221class AtomicSDNode : public MemSDNode {
1222  SDUse Ops[4];
1223
1224  /// For cmpxchg instructions, the ordering requirements when a store does not
1225  /// occur.
1226  AtomicOrdering FailureOrdering;
1227
1228  void InitAtomic(AtomicOrdering SuccessOrdering,
1229                  AtomicOrdering FailureOrdering,
1230                  SynchronizationScope SynchScope) {
1231    // This must match encodeMemSDNodeFlags() in SelectionDAG.cpp.
1232    assert((SuccessOrdering & 15) == SuccessOrdering &&
1233           "Ordering may not require more than 4 bits!");
1234    assert((FailureOrdering & 15) == FailureOrdering &&
1235           "Ordering may not require more than 4 bits!");
1236    assert((SynchScope & 1) == SynchScope &&
1237           "SynchScope may not require more than 1 bit!");
1238    SubclassData |= SuccessOrdering << 8;
1239    SubclassData |= SynchScope << 12;
1240    this->FailureOrdering = FailureOrdering;
1241    assert(getSuccessOrdering() == SuccessOrdering &&
1242           "Ordering encoding error!");
1243    assert(getFailureOrdering() == FailureOrdering &&
1244           "Ordering encoding error!");
1245    assert(getSynchScope() == SynchScope && "Synch-scope encoding error!");
1246  }
1247
1248public:
1249  // Opc:   opcode for atomic
1250  // VTL:    value type list
1251  // Chain:  memory chain for operaand
1252  // Ptr:    address to update as a SDValue
1253  // Cmp:    compare value
1254  // Swp:    swap value
1255  // SrcVal: address to update as a Value (used for MemOperand)
1256  // Align:  alignment of memory
1257  AtomicSDNode(unsigned Opc, unsigned Order, DebugLoc dl, SDVTList VTL,
1258               EVT MemVT, SDValue Chain, SDValue Ptr, SDValue Cmp, SDValue Swp,
1259               MachineMemOperand *MMO, AtomicOrdering Ordering,
1260               SynchronizationScope SynchScope)
1261      : MemSDNode(Opc, Order, dl, VTL, MemVT, MMO) {
1262    InitAtomic(Ordering, Ordering, SynchScope);
1263    InitOperands(Ops, Chain, Ptr, Cmp, Swp);
1264  }
1265  AtomicSDNode(unsigned Opc, unsigned Order, DebugLoc dl, SDVTList VTL,
1266               EVT MemVT,
1267               SDValue Chain, SDValue Ptr,
1268               SDValue Val, MachineMemOperand *MMO,
1269               AtomicOrdering Ordering, SynchronizationScope SynchScope)
1270    : MemSDNode(Opc, Order, dl, VTL, MemVT, MMO) {
1271    InitAtomic(Ordering, Ordering, SynchScope);
1272    InitOperands(Ops, Chain, Ptr, Val);
1273  }
1274  AtomicSDNode(unsigned Opc, unsigned Order, DebugLoc dl, SDVTList VTL,
1275               EVT MemVT,
1276               SDValue Chain, SDValue Ptr,
1277               MachineMemOperand *MMO,
1278               AtomicOrdering Ordering, SynchronizationScope SynchScope)
1279    : MemSDNode(Opc, Order, dl, VTL, MemVT, MMO) {
1280    InitAtomic(Ordering, Ordering, SynchScope);
1281    InitOperands(Ops, Chain, Ptr);
1282  }
1283  AtomicSDNode(unsigned Opc, unsigned Order, DebugLoc dl, SDVTList VTL, EVT MemVT,
1284               const SDValue* AllOps, SDUse *DynOps, unsigned NumOps,
1285               MachineMemOperand *MMO,
1286               AtomicOrdering SuccessOrdering, AtomicOrdering FailureOrdering,
1287               SynchronizationScope SynchScope)
1288    : MemSDNode(Opc, Order, dl, VTL, MemVT, MMO) {
1289    InitAtomic(SuccessOrdering, FailureOrdering, SynchScope);
1290    assert((DynOps || NumOps <= array_lengthof(Ops)) &&
1291           "Too many ops for internal storage!");
1292    InitOperands(DynOps ? DynOps : Ops, AllOps, NumOps);
1293  }
1294
1295  const SDValue &getBasePtr() const { return getOperand(1); }
1296  const SDValue &getVal() const { return getOperand(2); }
1297
1298  AtomicOrdering getSuccessOrdering() const {
1299    return getOrdering();
1300  }
1301
1302  // Not quite enough room in SubclassData for everything, so failure gets its
1303  // own field.
1304  AtomicOrdering getFailureOrdering() const {
1305    return FailureOrdering;
1306  }
1307
1308  bool isCompareAndSwap() const {
1309    unsigned Op = getOpcode();
1310    return Op == ISD::ATOMIC_CMP_SWAP || Op == ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS;
1311  }
1312
1313  // Methods to support isa and dyn_cast
1314  static bool classof(const SDNode *N) {
1315    return N->getOpcode() == ISD::ATOMIC_CMP_SWAP     ||
1316           N->getOpcode() == ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS ||
1317           N->getOpcode() == ISD::ATOMIC_SWAP         ||
1318           N->getOpcode() == ISD::ATOMIC_LOAD_ADD     ||
1319           N->getOpcode() == ISD::ATOMIC_LOAD_SUB     ||
1320           N->getOpcode() == ISD::ATOMIC_LOAD_AND     ||
1321           N->getOpcode() == ISD::ATOMIC_LOAD_OR      ||
1322           N->getOpcode() == ISD::ATOMIC_LOAD_XOR     ||
1323           N->getOpcode() == ISD::ATOMIC_LOAD_NAND    ||
1324           N->getOpcode() == ISD::ATOMIC_LOAD_MIN     ||
1325           N->getOpcode() == ISD::ATOMIC_LOAD_MAX     ||
1326           N->getOpcode() == ISD::ATOMIC_LOAD_UMIN    ||
1327           N->getOpcode() == ISD::ATOMIC_LOAD_UMAX    ||
1328           N->getOpcode() == ISD::ATOMIC_LOAD         ||
1329           N->getOpcode() == ISD::ATOMIC_STORE;
1330  }
1331};
1332
1333/// This SDNode is used for target intrinsics that touch
1334/// memory and need an associated MachineMemOperand. Its opcode may be
1335/// INTRINSIC_VOID, INTRINSIC_W_CHAIN, PREFETCH, or a target-specific opcode
1336/// with a value not less than FIRST_TARGET_MEMORY_OPCODE.
1337class MemIntrinsicSDNode : public MemSDNode {
1338public:
1339  MemIntrinsicSDNode(unsigned Opc, unsigned Order, DebugLoc dl, SDVTList VTs,
1340                     ArrayRef<SDValue> Ops, EVT MemoryVT,
1341                     MachineMemOperand *MMO)
1342    : MemSDNode(Opc, Order, dl, VTs, Ops, MemoryVT, MMO) {
1343    SubclassData |= 1u << 13;
1344  }
1345
1346  // Methods to support isa and dyn_cast
1347  static bool classof(const SDNode *N) {
1348    // We lower some target intrinsics to their target opcode
1349    // early a node with a target opcode can be of this class
1350    return N->isMemIntrinsic()             ||
1351           N->getOpcode() == ISD::PREFETCH ||
1352           N->isTargetMemoryOpcode();
1353  }
1354};
1355
1356/// This SDNode is used to implement the code generator
1357/// support for the llvm IR shufflevector instruction.  It combines elements
1358/// from two input vectors into a new input vector, with the selection and
1359/// ordering of elements determined by an array of integers, referred to as
1360/// the shuffle mask.  For input vectors of width N, mask indices of 0..N-1
1361/// refer to elements from the LHS input, and indices from N to 2N-1 the RHS.
1362/// An index of -1 is treated as undef, such that the code generator may put
1363/// any value in the corresponding element of the result.
1364class ShuffleVectorSDNode : public SDNode {
1365  SDUse Ops[2];
1366
1367  // The memory for Mask is owned by the SelectionDAG's OperandAllocator, and
1368  // is freed when the SelectionDAG object is destroyed.
1369  const int *Mask;
1370protected:
1371  friend class SelectionDAG;
1372  ShuffleVectorSDNode(EVT VT, unsigned Order, DebugLoc dl, SDValue N1,
1373                      SDValue N2, const int *M)
1374    : SDNode(ISD::VECTOR_SHUFFLE, Order, dl, getSDVTList(VT)), Mask(M) {
1375    InitOperands(Ops, N1, N2);
1376  }
1377public:
1378
1379  ArrayRef<int> getMask() const {
1380    EVT VT = getValueType(0);
1381    return makeArrayRef(Mask, VT.getVectorNumElements());
1382  }
1383  int getMaskElt(unsigned Idx) const {
1384    assert(Idx < getValueType(0).getVectorNumElements() && "Idx out of range!");
1385    return Mask[Idx];
1386  }
1387
1388  bool isSplat() const { return isSplatMask(Mask, getValueType(0)); }
1389  int  getSplatIndex() const {
1390    assert(isSplat() && "Cannot get splat index for non-splat!");
1391    EVT VT = getValueType(0);
1392    for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
1393      if (Mask[i] >= 0)
1394        return Mask[i];
1395    }
1396    llvm_unreachable("Splat with all undef indices?");
1397  }
1398  static bool isSplatMask(const int *Mask, EVT VT);
1399
1400  /// Change values in a shuffle permute mask assuming
1401  /// the two vector operands have swapped position.
1402  static void commuteMask(SmallVectorImpl<int> &Mask) {
1403    unsigned NumElems = Mask.size();
1404    for (unsigned i = 0; i != NumElems; ++i) {
1405      int idx = Mask[i];
1406      if (idx < 0)
1407        continue;
1408      else if (idx < (int)NumElems)
1409        Mask[i] = idx + NumElems;
1410      else
1411        Mask[i] = idx - NumElems;
1412    }
1413  }
1414
1415  static bool classof(const SDNode *N) {
1416    return N->getOpcode() == ISD::VECTOR_SHUFFLE;
1417  }
1418};
1419
1420class ConstantSDNode : public SDNode {
1421  const ConstantInt *Value;
1422  friend class SelectionDAG;
1423  ConstantSDNode(bool isTarget, bool isOpaque, const ConstantInt *val,
1424                 DebugLoc DL, EVT VT)
1425    : SDNode(isTarget ? ISD::TargetConstant : ISD::Constant,
1426             0, DL, getSDVTList(VT)), Value(val) {
1427    SubclassData |= (uint16_t)isOpaque;
1428  }
1429public:
1430
1431  const ConstantInt *getConstantIntValue() const { return Value; }
1432  const APInt &getAPIntValue() const { return Value->getValue(); }
1433  uint64_t getZExtValue() const { return Value->getZExtValue(); }
1434  int64_t getSExtValue() const { return Value->getSExtValue(); }
1435
1436  bool isOne() const { return Value->isOne(); }
1437  bool isNullValue() const { return Value->isNullValue(); }
1438  bool isAllOnesValue() const { return Value->isAllOnesValue(); }
1439
1440  bool isOpaque() const { return SubclassData & 1; }
1441
1442  static bool classof(const SDNode *N) {
1443    return N->getOpcode() == ISD::Constant ||
1444           N->getOpcode() == ISD::TargetConstant;
1445  }
1446};
1447
1448class ConstantFPSDNode : public SDNode {
1449  const ConstantFP *Value;
1450  friend class SelectionDAG;
1451  ConstantFPSDNode(bool isTarget, const ConstantFP *val, DebugLoc DL, EVT VT)
1452    : SDNode(isTarget ? ISD::TargetConstantFP : ISD::ConstantFP,
1453             0, DL, getSDVTList(VT)), Value(val) {
1454  }
1455public:
1456
1457  const APFloat& getValueAPF() const { return Value->getValueAPF(); }
1458  const ConstantFP *getConstantFPValue() const { return Value; }
1459
1460  /// Return true if the value is positive or negative zero.
1461  bool isZero() const { return Value->isZero(); }
1462
1463  /// Return true if the value is a NaN.
1464  bool isNaN() const { return Value->isNaN(); }
1465
1466  /// Return true if the value is an infinity
1467  bool isInfinity() const { return Value->isInfinity(); }
1468
1469  /// Return true if the value is negative.
1470  bool isNegative() const { return Value->isNegative(); }
1471
1472  /// We don't rely on operator== working on double values, as
1473  /// it returns true for things that are clearly not equal, like -0.0 and 0.0.
1474  /// As such, this method can be used to do an exact bit-for-bit comparison of
1475  /// two floating point values.
1476
1477  /// We leave the version with the double argument here because it's just so
1478  /// convenient to write "2.0" and the like.  Without this function we'd
1479  /// have to duplicate its logic everywhere it's called.
1480  bool isExactlyValue(double V) const {
1481    bool ignored;
1482    APFloat Tmp(V);
1483    Tmp.convert(Value->getValueAPF().getSemantics(),
1484                APFloat::rmNearestTiesToEven, &ignored);
1485    return isExactlyValue(Tmp);
1486  }
1487  bool isExactlyValue(const APFloat& V) const;
1488
1489  static bool isValueValidForType(EVT VT, const APFloat& Val);
1490
1491  static bool classof(const SDNode *N) {
1492    return N->getOpcode() == ISD::ConstantFP ||
1493           N->getOpcode() == ISD::TargetConstantFP;
1494  }
1495};
1496
1497/// Returns true if \p V is a constant integer zero.
1498bool isNullConstant(SDValue V);
1499/// Returns true if \p V is an FP constant with a value of positive zero.
1500bool isNullFPConstant(SDValue V);
1501/// Returns true if \p V is an integer constant with all bits set.
1502bool isAllOnesConstant(SDValue V);
1503/// Returns true if \p V is a constant integer one.
1504bool isOneConstant(SDValue V);
1505
1506class GlobalAddressSDNode : public SDNode {
1507  const GlobalValue *TheGlobal;
1508  int64_t Offset;
1509  unsigned char TargetFlags;
1510  friend class SelectionDAG;
1511  GlobalAddressSDNode(unsigned Opc, unsigned Order, DebugLoc DL,
1512                      const GlobalValue *GA, EVT VT, int64_t o,
1513                      unsigned char TargetFlags);
1514public:
1515
1516  const GlobalValue *getGlobal() const { return TheGlobal; }
1517  int64_t getOffset() const { return Offset; }
1518  unsigned char getTargetFlags() const { return TargetFlags; }
1519  // Return the address space this GlobalAddress belongs to.
1520  unsigned getAddressSpace() const;
1521
1522  static bool classof(const SDNode *N) {
1523    return N->getOpcode() == ISD::GlobalAddress ||
1524           N->getOpcode() == ISD::TargetGlobalAddress ||
1525           N->getOpcode() == ISD::GlobalTLSAddress ||
1526           N->getOpcode() == ISD::TargetGlobalTLSAddress;
1527  }
1528};
1529
1530class FrameIndexSDNode : public SDNode {
1531  int FI;
1532  friend class SelectionDAG;
1533  FrameIndexSDNode(int fi, EVT VT, bool isTarg)
1534    : SDNode(isTarg ? ISD::TargetFrameIndex : ISD::FrameIndex,
1535      0, DebugLoc(), getSDVTList(VT)), FI(fi) {
1536  }
1537public:
1538
1539  int getIndex() const { return FI; }
1540
1541  static bool classof(const SDNode *N) {
1542    return N->getOpcode() == ISD::FrameIndex ||
1543           N->getOpcode() == ISD::TargetFrameIndex;
1544  }
1545};
1546
1547class JumpTableSDNode : public SDNode {
1548  int JTI;
1549  unsigned char TargetFlags;
1550  friend class SelectionDAG;
1551  JumpTableSDNode(int jti, EVT VT, bool isTarg, unsigned char TF)
1552    : SDNode(isTarg ? ISD::TargetJumpTable : ISD::JumpTable,
1553      0, DebugLoc(), getSDVTList(VT)), JTI(jti), TargetFlags(TF) {
1554  }
1555public:
1556
1557  int getIndex() const { return JTI; }
1558  unsigned char getTargetFlags() const { return TargetFlags; }
1559
1560  static bool classof(const SDNode *N) {
1561    return N->getOpcode() == ISD::JumpTable ||
1562           N->getOpcode() == ISD::TargetJumpTable;
1563  }
1564};
1565
1566class ConstantPoolSDNode : public SDNode {
1567  union {
1568    const Constant *ConstVal;
1569    MachineConstantPoolValue *MachineCPVal;
1570  } Val;
1571  int Offset;  // It's a MachineConstantPoolValue if top bit is set.
1572  unsigned Alignment;  // Minimum alignment requirement of CP (not log2 value).
1573  unsigned char TargetFlags;
1574  friend class SelectionDAG;
1575  ConstantPoolSDNode(bool isTarget, const Constant *c, EVT VT, int o,
1576                     unsigned Align, unsigned char TF)
1577    : SDNode(isTarget ? ISD::TargetConstantPool : ISD::ConstantPool, 0,
1578             DebugLoc(), getSDVTList(VT)), Offset(o), Alignment(Align),
1579             TargetFlags(TF) {
1580    assert(Offset >= 0 && "Offset is too large");
1581    Val.ConstVal = c;
1582  }
1583  ConstantPoolSDNode(bool isTarget, MachineConstantPoolValue *v,
1584                     EVT VT, int o, unsigned Align, unsigned char TF)
1585    : SDNode(isTarget ? ISD::TargetConstantPool : ISD::ConstantPool, 0,
1586             DebugLoc(), getSDVTList(VT)), Offset(o), Alignment(Align),
1587             TargetFlags(TF) {
1588    assert(Offset >= 0 && "Offset is too large");
1589    Val.MachineCPVal = v;
1590    Offset |= 1 << (sizeof(unsigned)*CHAR_BIT-1);
1591  }
1592public:
1593
1594  bool isMachineConstantPoolEntry() const {
1595    return Offset < 0;
1596  }
1597
1598  const Constant *getConstVal() const {
1599    assert(!isMachineConstantPoolEntry() && "Wrong constantpool type");
1600    return Val.ConstVal;
1601  }
1602
1603  MachineConstantPoolValue *getMachineCPVal() const {
1604    assert(isMachineConstantPoolEntry() && "Wrong constantpool type");
1605    return Val.MachineCPVal;
1606  }
1607
1608  int getOffset() const {
1609    return Offset & ~(1 << (sizeof(unsigned)*CHAR_BIT-1));
1610  }
1611
1612  // Return the alignment of this constant pool object, which is either 0 (for
1613  // default alignment) or the desired value.
1614  unsigned getAlignment() const { return Alignment; }
1615  unsigned char getTargetFlags() const { return TargetFlags; }
1616
1617  Type *getType() const;
1618
1619  static bool classof(const SDNode *N) {
1620    return N->getOpcode() == ISD::ConstantPool ||
1621           N->getOpcode() == ISD::TargetConstantPool;
1622  }
1623};
1624
1625/// Completely target-dependent object reference.
1626class TargetIndexSDNode : public SDNode {
1627  unsigned char TargetFlags;
1628  int Index;
1629  int64_t Offset;
1630  friend class SelectionDAG;
1631public:
1632
1633  TargetIndexSDNode(int Idx, EVT VT, int64_t Ofs, unsigned char TF)
1634    : SDNode(ISD::TargetIndex, 0, DebugLoc(), getSDVTList(VT)),
1635      TargetFlags(TF), Index(Idx), Offset(Ofs) {}
1636public:
1637
1638  unsigned char getTargetFlags() const { return TargetFlags; }
1639  int getIndex() const { return Index; }
1640  int64_t getOffset() const { return Offset; }
1641
1642  static bool classof(const SDNode *N) {
1643    return N->getOpcode() == ISD::TargetIndex;
1644  }
1645};
1646
1647class BasicBlockSDNode : public SDNode {
1648  MachineBasicBlock *MBB;
1649  friend class SelectionDAG;
1650  /// Debug info is meaningful and potentially useful here, but we create
1651  /// blocks out of order when they're jumped to, which makes it a bit
1652  /// harder.  Let's see if we need it first.
1653  explicit BasicBlockSDNode(MachineBasicBlock *mbb)
1654    : SDNode(ISD::BasicBlock, 0, DebugLoc(), getSDVTList(MVT::Other)), MBB(mbb)
1655  {}
1656public:
1657
1658  MachineBasicBlock *getBasicBlock() const { return MBB; }
1659
1660  static bool classof(const SDNode *N) {
1661    return N->getOpcode() == ISD::BasicBlock;
1662  }
1663};
1664
1665/// A "pseudo-class" with methods for operating on BUILD_VECTORs.
1666class BuildVectorSDNode : public SDNode {
1667  // These are constructed as SDNodes and then cast to BuildVectorSDNodes.
1668  explicit BuildVectorSDNode() = delete;
1669public:
1670  /// Check if this is a constant splat, and if so, find the
1671  /// smallest element size that splats the vector.  If MinSplatBits is
1672  /// nonzero, the element size must be at least that large.  Note that the
1673  /// splat element may be the entire vector (i.e., a one element vector).
1674  /// Returns the splat element value in SplatValue.  Any undefined bits in
1675  /// that value are zero, and the corresponding bits in the SplatUndef mask
1676  /// are set.  The SplatBitSize value is set to the splat element size in
1677  /// bits.  HasAnyUndefs is set to true if any bits in the vector are
1678  /// undefined.  isBigEndian describes the endianness of the target.
1679  bool isConstantSplat(APInt &SplatValue, APInt &SplatUndef,
1680                       unsigned &SplatBitSize, bool &HasAnyUndefs,
1681                       unsigned MinSplatBits = 0,
1682                       bool isBigEndian = false) const;
1683
1684  /// \brief Returns the splatted value or a null value if this is not a splat.
1685  ///
1686  /// If passed a non-null UndefElements bitvector, it will resize it to match
1687  /// the vector width and set the bits where elements are undef.
1688  SDValue getSplatValue(BitVector *UndefElements = nullptr) const;
1689
1690  /// \brief Returns the splatted constant or null if this is not a constant
1691  /// splat.
1692  ///
1693  /// If passed a non-null UndefElements bitvector, it will resize it to match
1694  /// the vector width and set the bits where elements are undef.
1695  ConstantSDNode *
1696  getConstantSplatNode(BitVector *UndefElements = nullptr) const;
1697
1698  /// \brief Returns the splatted constant FP or null if this is not a constant
1699  /// FP splat.
1700  ///
1701  /// If passed a non-null UndefElements bitvector, it will resize it to match
1702  /// the vector width and set the bits where elements are undef.
1703  ConstantFPSDNode *
1704  getConstantFPSplatNode(BitVector *UndefElements = nullptr) const;
1705
1706  /// \brief If this is a constant FP splat and the splatted constant FP is an
1707  /// exact power or 2, return the log base 2 integer value.  Otherwise,
1708  /// return -1.
1709  ///
1710  /// The BitWidth specifies the necessary bit precision.
1711  int32_t getConstantFPSplatPow2ToLog2Int(BitVector *UndefElements,
1712                                          uint32_t BitWidth) const;
1713
1714  bool isConstant() const;
1715
1716  static inline bool classof(const SDNode *N) {
1717    return N->getOpcode() == ISD::BUILD_VECTOR;
1718  }
1719};
1720
1721/// An SDNode that holds an arbitrary LLVM IR Value. This is
1722/// used when the SelectionDAG needs to make a simple reference to something
1723/// in the LLVM IR representation.
1724///
1725class SrcValueSDNode : public SDNode {
1726  const Value *V;
1727  friend class SelectionDAG;
1728  /// Create a SrcValue for a general value.
1729  explicit SrcValueSDNode(const Value *v)
1730    : SDNode(ISD::SRCVALUE, 0, DebugLoc(), getSDVTList(MVT::Other)), V(v) {}
1731
1732public:
1733  /// Return the contained Value.
1734  const Value *getValue() const { return V; }
1735
1736  static bool classof(const SDNode *N) {
1737    return N->getOpcode() == ISD::SRCVALUE;
1738  }
1739};
1740
1741class MDNodeSDNode : public SDNode {
1742  const MDNode *MD;
1743  friend class SelectionDAG;
1744  explicit MDNodeSDNode(const MDNode *md)
1745  : SDNode(ISD::MDNODE_SDNODE, 0, DebugLoc(), getSDVTList(MVT::Other)), MD(md)
1746  {}
1747public:
1748
1749  const MDNode *getMD() const { return MD; }
1750
1751  static bool classof(const SDNode *N) {
1752    return N->getOpcode() == ISD::MDNODE_SDNODE;
1753  }
1754};
1755
1756class RegisterSDNode : public SDNode {
1757  unsigned Reg;
1758  friend class SelectionDAG;
1759  RegisterSDNode(unsigned reg, EVT VT)
1760    : SDNode(ISD::Register, 0, DebugLoc(), getSDVTList(VT)), Reg(reg) {
1761  }
1762public:
1763
1764  unsigned getReg() const { return Reg; }
1765
1766  static bool classof(const SDNode *N) {
1767    return N->getOpcode() == ISD::Register;
1768  }
1769};
1770
1771class RegisterMaskSDNode : public SDNode {
1772  // The memory for RegMask is not owned by the node.
1773  const uint32_t *RegMask;
1774  friend class SelectionDAG;
1775  RegisterMaskSDNode(const uint32_t *mask)
1776    : SDNode(ISD::RegisterMask, 0, DebugLoc(), getSDVTList(MVT::Untyped)),
1777      RegMask(mask) {}
1778public:
1779
1780  const uint32_t *getRegMask() const { return RegMask; }
1781
1782  static bool classof(const SDNode *N) {
1783    return N->getOpcode() == ISD::RegisterMask;
1784  }
1785};
1786
1787class BlockAddressSDNode : public SDNode {
1788  const BlockAddress *BA;
1789  int64_t Offset;
1790  unsigned char TargetFlags;
1791  friend class SelectionDAG;
1792  BlockAddressSDNode(unsigned NodeTy, EVT VT, const BlockAddress *ba,
1793                     int64_t o, unsigned char Flags)
1794    : SDNode(NodeTy, 0, DebugLoc(), getSDVTList(VT)),
1795             BA(ba), Offset(o), TargetFlags(Flags) {
1796  }
1797public:
1798  const BlockAddress *getBlockAddress() const { return BA; }
1799  int64_t getOffset() const { return Offset; }
1800  unsigned char getTargetFlags() const { return TargetFlags; }
1801
1802  static bool classof(const SDNode *N) {
1803    return N->getOpcode() == ISD::BlockAddress ||
1804           N->getOpcode() == ISD::TargetBlockAddress;
1805  }
1806};
1807
1808class EHLabelSDNode : public SDNode {
1809  SDUse Chain;
1810  MCSymbol *Label;
1811  friend class SelectionDAG;
1812  EHLabelSDNode(unsigned Order, DebugLoc dl, SDValue ch, MCSymbol *L)
1813    : SDNode(ISD::EH_LABEL, Order, dl, getSDVTList(MVT::Other)), Label(L) {
1814    InitOperands(&Chain, ch);
1815  }
1816public:
1817  MCSymbol *getLabel() const { return Label; }
1818
1819  static bool classof(const SDNode *N) {
1820    return N->getOpcode() == ISD::EH_LABEL;
1821  }
1822};
1823
1824class ExternalSymbolSDNode : public SDNode {
1825  const char *Symbol;
1826  unsigned char TargetFlags;
1827
1828  friend class SelectionDAG;
1829  ExternalSymbolSDNode(bool isTarget, const char *Sym, unsigned char TF, EVT VT)
1830    : SDNode(isTarget ? ISD::TargetExternalSymbol : ISD::ExternalSymbol,
1831             0, DebugLoc(), getSDVTList(VT)), Symbol(Sym), TargetFlags(TF) {
1832  }
1833public:
1834
1835  const char *getSymbol() const { return Symbol; }
1836  unsigned char getTargetFlags() const { return TargetFlags; }
1837
1838  static bool classof(const SDNode *N) {
1839    return N->getOpcode() == ISD::ExternalSymbol ||
1840           N->getOpcode() == ISD::TargetExternalSymbol;
1841  }
1842};
1843
1844class MCSymbolSDNode : public SDNode {
1845  MCSymbol *Symbol;
1846
1847  friend class SelectionDAG;
1848  MCSymbolSDNode(MCSymbol *Symbol, EVT VT)
1849      : SDNode(ISD::MCSymbol, 0, DebugLoc(), getSDVTList(VT)), Symbol(Symbol) {}
1850
1851public:
1852  MCSymbol *getMCSymbol() const { return Symbol; }
1853
1854  static bool classof(const SDNode *N) {
1855    return N->getOpcode() == ISD::MCSymbol;
1856  }
1857};
1858
1859class CondCodeSDNode : public SDNode {
1860  ISD::CondCode Condition;
1861  friend class SelectionDAG;
1862  explicit CondCodeSDNode(ISD::CondCode Cond)
1863    : SDNode(ISD::CONDCODE, 0, DebugLoc(), getSDVTList(MVT::Other)),
1864      Condition(Cond) {
1865  }
1866public:
1867
1868  ISD::CondCode get() const { return Condition; }
1869
1870  static bool classof(const SDNode *N) {
1871    return N->getOpcode() == ISD::CONDCODE;
1872  }
1873};
1874
1875/// NOTE: avoid using this node as this may disappear in the
1876/// future and most targets don't support it.
1877class CvtRndSatSDNode : public SDNode {
1878  ISD::CvtCode CvtCode;
1879  friend class SelectionDAG;
1880  explicit CvtRndSatSDNode(EVT VT, unsigned Order, DebugLoc dl,
1881                           ArrayRef<SDValue> Ops, ISD::CvtCode Code)
1882    : SDNode(ISD::CONVERT_RNDSAT, Order, dl, getSDVTList(VT), Ops),
1883      CvtCode(Code) {
1884    assert(Ops.size() == 5 && "wrong number of operations");
1885  }
1886public:
1887  ISD::CvtCode getCvtCode() const { return CvtCode; }
1888
1889  static bool classof(const SDNode *N) {
1890    return N->getOpcode() == ISD::CONVERT_RNDSAT;
1891  }
1892};
1893
1894/// This class is used to represent EVT's, which are used
1895/// to parameterize some operations.
1896class VTSDNode : public SDNode {
1897  EVT ValueType;
1898  friend class SelectionDAG;
1899  explicit VTSDNode(EVT VT)
1900    : SDNode(ISD::VALUETYPE, 0, DebugLoc(), getSDVTList(MVT::Other)),
1901      ValueType(VT) {
1902  }
1903public:
1904
1905  EVT getVT() const { return ValueType; }
1906
1907  static bool classof(const SDNode *N) {
1908    return N->getOpcode() == ISD::VALUETYPE;
1909  }
1910};
1911
1912/// Base class for LoadSDNode and StoreSDNode
1913class LSBaseSDNode : public MemSDNode {
1914  //! Operand array for load and store
1915  /*!
1916    \note Moving this array to the base class captures more
1917    common functionality shared between LoadSDNode and
1918    StoreSDNode
1919   */
1920  SDUse Ops[4];
1921public:
1922  LSBaseSDNode(ISD::NodeType NodeTy, unsigned Order, DebugLoc dl,
1923               SDValue *Operands, unsigned numOperands,
1924               SDVTList VTs, ISD::MemIndexedMode AM, EVT MemVT,
1925               MachineMemOperand *MMO)
1926    : MemSDNode(NodeTy, Order, dl, VTs, MemVT, MMO) {
1927    SubclassData |= AM << 2;
1928    assert(getAddressingMode() == AM && "MemIndexedMode encoding error!");
1929    InitOperands(Ops, Operands, numOperands);
1930    assert((getOffset().getOpcode() == ISD::UNDEF || isIndexed()) &&
1931           "Only indexed loads and stores have a non-undef offset operand");
1932  }
1933
1934  const SDValue &getOffset() const {
1935    return getOperand(getOpcode() == ISD::LOAD ? 2 : 3);
1936  }
1937
1938  /// Return the addressing mode for this load or store:
1939  /// unindexed, pre-inc, pre-dec, post-inc, or post-dec.
1940  ISD::MemIndexedMode getAddressingMode() const {
1941    return ISD::MemIndexedMode((SubclassData >> 2) & 7);
1942  }
1943
1944  /// Return true if this is a pre/post inc/dec load/store.
1945  bool isIndexed() const { return getAddressingMode() != ISD::UNINDEXED; }
1946
1947  /// Return true if this is NOT a pre/post inc/dec load/store.
1948  bool isUnindexed() const { return getAddressingMode() == ISD::UNINDEXED; }
1949
1950  static bool classof(const SDNode *N) {
1951    return N->getOpcode() == ISD::LOAD ||
1952           N->getOpcode() == ISD::STORE;
1953  }
1954};
1955
1956/// This class is used to represent ISD::LOAD nodes.
1957class LoadSDNode : public LSBaseSDNode {
1958  friend class SelectionDAG;
1959  LoadSDNode(SDValue *ChainPtrOff, unsigned Order, DebugLoc dl, SDVTList VTs,
1960             ISD::MemIndexedMode AM, ISD::LoadExtType ETy, EVT MemVT,
1961             MachineMemOperand *MMO)
1962    : LSBaseSDNode(ISD::LOAD, Order, dl, ChainPtrOff, 3, VTs, AM, MemVT, MMO) {
1963    SubclassData |= (unsigned short)ETy;
1964    assert(getExtensionType() == ETy && "LoadExtType encoding error!");
1965    assert(readMem() && "Load MachineMemOperand is not a load!");
1966    assert(!writeMem() && "Load MachineMemOperand is a store!");
1967  }
1968public:
1969
1970  /// Return whether this is a plain node,
1971  /// or one of the varieties of value-extending loads.
1972  ISD::LoadExtType getExtensionType() const {
1973    return ISD::LoadExtType(SubclassData & 3);
1974  }
1975
1976  const SDValue &getBasePtr() const { return getOperand(1); }
1977  const SDValue &getOffset() const { return getOperand(2); }
1978
1979  static bool classof(const SDNode *N) {
1980    return N->getOpcode() == ISD::LOAD;
1981  }
1982};
1983
1984/// This class is used to represent ISD::STORE nodes.
1985class StoreSDNode : public LSBaseSDNode {
1986  friend class SelectionDAG;
1987  StoreSDNode(SDValue *ChainValuePtrOff, unsigned Order, DebugLoc dl,
1988              SDVTList VTs, ISD::MemIndexedMode AM, bool isTrunc, EVT MemVT,
1989              MachineMemOperand *MMO)
1990    : LSBaseSDNode(ISD::STORE, Order, dl, ChainValuePtrOff, 4,
1991                   VTs, AM, MemVT, MMO) {
1992    SubclassData |= (unsigned short)isTrunc;
1993    assert(isTruncatingStore() == isTrunc && "isTrunc encoding error!");
1994    assert(!readMem() && "Store MachineMemOperand is a load!");
1995    assert(writeMem() && "Store MachineMemOperand is not a store!");
1996  }
1997public:
1998
1999  /// Return true if the op does a truncation before store.
2000  /// For integers this is the same as doing a TRUNCATE and storing the result.
2001  /// For floats, it is the same as doing an FP_ROUND and storing the result.
2002  bool isTruncatingStore() const { return SubclassData & 1; }
2003
2004  const SDValue &getValue() const { return getOperand(1); }
2005  const SDValue &getBasePtr() const { return getOperand(2); }
2006  const SDValue &getOffset() const { return getOperand(3); }
2007
2008  static bool classof(const SDNode *N) {
2009    return N->getOpcode() == ISD::STORE;
2010  }
2011};
2012
2013/// This base class is used to represent MLOAD and MSTORE nodes
2014class MaskedLoadStoreSDNode : public MemSDNode {
2015  // Operands
2016  SDUse Ops[4];
2017public:
2018  friend class SelectionDAG;
2019  MaskedLoadStoreSDNode(ISD::NodeType NodeTy, unsigned Order, DebugLoc dl,
2020                        SDValue *Operands, unsigned numOperands, SDVTList VTs,
2021                        EVT MemVT, MachineMemOperand *MMO)
2022      : MemSDNode(NodeTy, Order, dl, VTs, MemVT, MMO) {
2023    InitOperands(Ops, Operands, numOperands);
2024  }
2025
2026  // In the both nodes address is Op1, mask is Op2:
2027  // MaskedLoadSDNode (Chain, ptr, mask, src0), src0 is a passthru value
2028  // MaskedStoreSDNode (Chain, ptr, mask, data)
2029  // Mask is a vector of i1 elements
2030  const SDValue &getBasePtr() const { return getOperand(1); }
2031  const SDValue &getMask() const    { return getOperand(2); }
2032
2033  static bool classof(const SDNode *N) {
2034    return N->getOpcode() == ISD::MLOAD ||
2035           N->getOpcode() == ISD::MSTORE;
2036  }
2037};
2038
2039/// This class is used to represent an MLOAD node
2040class MaskedLoadSDNode : public MaskedLoadStoreSDNode {
2041public:
2042  friend class SelectionDAG;
2043  MaskedLoadSDNode(unsigned Order, DebugLoc dl, SDValue *Operands,
2044                   unsigned numOperands, SDVTList VTs, ISD::LoadExtType ETy,
2045                   EVT MemVT, MachineMemOperand *MMO)
2046    : MaskedLoadStoreSDNode(ISD::MLOAD, Order, dl, Operands, numOperands,
2047                            VTs, MemVT, MMO) {
2048    SubclassData |= (unsigned short)ETy;
2049  }
2050
2051  ISD::LoadExtType getExtensionType() const {
2052    return ISD::LoadExtType(SubclassData & 3);
2053  }
2054  const SDValue &getSrc0() const { return getOperand(3); }
2055  static bool classof(const SDNode *N) {
2056    return N->getOpcode() == ISD::MLOAD;
2057  }
2058};
2059
2060/// This class is used to represent an MSTORE node
2061class MaskedStoreSDNode : public MaskedLoadStoreSDNode {
2062
2063public:
2064  friend class SelectionDAG;
2065  MaskedStoreSDNode(unsigned Order, DebugLoc dl, SDValue *Operands,
2066                    unsigned numOperands, SDVTList VTs, bool isTrunc, EVT MemVT,
2067                    MachineMemOperand *MMO)
2068    : MaskedLoadStoreSDNode(ISD::MSTORE, Order, dl, Operands, numOperands,
2069                            VTs, MemVT, MMO) {
2070      SubclassData |= (unsigned short)isTrunc;
2071  }
2072  /// Return true if the op does a truncation before store.
2073  /// For integers this is the same as doing a TRUNCATE and storing the result.
2074  /// For floats, it is the same as doing an FP_ROUND and storing the result.
2075  bool isTruncatingStore() const { return SubclassData & 1; }
2076
2077  const SDValue &getValue() const { return getOperand(3); }
2078
2079  static bool classof(const SDNode *N) {
2080    return N->getOpcode() == ISD::MSTORE;
2081  }
2082};
2083
2084/// This is a base class used to represent
2085/// MGATHER and MSCATTER nodes
2086///
2087class MaskedGatherScatterSDNode : public MemSDNode {
2088  // Operands
2089  SDUse Ops[5];
2090public:
2091  friend class SelectionDAG;
2092  MaskedGatherScatterSDNode(ISD::NodeType NodeTy, unsigned Order, DebugLoc dl,
2093                            ArrayRef<SDValue> Operands, SDVTList VTs, EVT MemVT,
2094                            MachineMemOperand *MMO)
2095    : MemSDNode(NodeTy, Order, dl, VTs, MemVT, MMO) {
2096    assert(Operands.size() == 5 && "Incompatible number of operands");
2097    InitOperands(Ops, Operands.data(), Operands.size());
2098  }
2099
2100  // In the both nodes address is Op1, mask is Op2:
2101  // MaskedGatherSDNode  (Chain, src0, mask, base, index), src0 is a passthru value
2102  // MaskedScatterSDNode (Chain, value, mask, base, index)
2103  // Mask is a vector of i1 elements
2104  const SDValue &getBasePtr() const { return getOperand(3); }
2105  const SDValue &getIndex()   const { return getOperand(4); }
2106  const SDValue &getMask()    const { return getOperand(2); }
2107  const SDValue &getValue()   const { return getOperand(1); }
2108
2109  static bool classof(const SDNode *N) {
2110    return N->getOpcode() == ISD::MGATHER ||
2111           N->getOpcode() == ISD::MSCATTER;
2112  }
2113};
2114
2115/// This class is used to represent an MGATHER node
2116///
2117class MaskedGatherSDNode : public MaskedGatherScatterSDNode {
2118public:
2119  friend class SelectionDAG;
2120  MaskedGatherSDNode(unsigned Order, DebugLoc dl, ArrayRef<SDValue> Operands,
2121                     SDVTList VTs, EVT MemVT, MachineMemOperand *MMO)
2122    : MaskedGatherScatterSDNode(ISD::MGATHER, Order, dl, Operands, VTs, MemVT,
2123                                MMO) {
2124    assert(getValue().getValueType() == getValueType(0) &&
2125           "Incompatible type of the PassThru value in MaskedGatherSDNode");
2126    assert(getMask().getValueType().getVectorNumElements() ==
2127           getValueType(0).getVectorNumElements() &&
2128           "Vector width mismatch between mask and data");
2129    assert(getIndex().getValueType().getVectorNumElements() ==
2130           getValueType(0).getVectorNumElements() &&
2131           "Vector width mismatch between index and data");
2132  }
2133
2134  static bool classof(const SDNode *N) {
2135    return N->getOpcode() == ISD::MGATHER;
2136  }
2137};
2138
2139/// This class is used to represent an MSCATTER node
2140///
2141class MaskedScatterSDNode : public MaskedGatherScatterSDNode {
2142
2143public:
2144  friend class SelectionDAG;
2145  MaskedScatterSDNode(unsigned Order, DebugLoc dl,ArrayRef<SDValue> Operands,
2146                      SDVTList VTs, EVT MemVT, MachineMemOperand *MMO)
2147    : MaskedGatherScatterSDNode(ISD::MSCATTER, Order, dl, Operands, VTs, MemVT,
2148                                MMO) {
2149    assert(getMask().getValueType().getVectorNumElements() ==
2150           getValue().getValueType().getVectorNumElements() &&
2151           "Vector width mismatch between mask and data");
2152    assert(getIndex().getValueType().getVectorNumElements() ==
2153           getValue().getValueType().getVectorNumElements() &&
2154           "Vector width mismatch between index and data");
2155  }
2156
2157  static bool classof(const SDNode *N) {
2158    return N->getOpcode() == ISD::MSCATTER;
2159  }
2160};
2161
2162/// An SDNode that represents everything that will be needed
2163/// to construct a MachineInstr. These nodes are created during the
2164/// instruction selection proper phase.
2165class MachineSDNode : public SDNode {
2166public:
2167  typedef MachineMemOperand **mmo_iterator;
2168
2169private:
2170  friend class SelectionDAG;
2171  MachineSDNode(unsigned Opc, unsigned Order, const DebugLoc DL, SDVTList VTs)
2172    : SDNode(Opc, Order, DL, VTs), MemRefs(nullptr), MemRefsEnd(nullptr) {}
2173
2174  /// Operands for this instruction, if they fit here. If
2175  /// they don't, this field is unused.
2176  SDUse LocalOperands[4];
2177
2178  /// Memory reference descriptions for this instruction.
2179  mmo_iterator MemRefs;
2180  mmo_iterator MemRefsEnd;
2181
2182public:
2183  mmo_iterator memoperands_begin() const { return MemRefs; }
2184  mmo_iterator memoperands_end() const { return MemRefsEnd; }
2185  bool memoperands_empty() const { return MemRefsEnd == MemRefs; }
2186
2187  /// Assign this MachineSDNodes's memory reference descriptor
2188  /// list. This does not transfer ownership.
2189  void setMemRefs(mmo_iterator NewMemRefs, mmo_iterator NewMemRefsEnd) {
2190    for (mmo_iterator MMI = NewMemRefs, MME = NewMemRefsEnd; MMI != MME; ++MMI)
2191      assert(*MMI && "Null mem ref detected!");
2192    MemRefs = NewMemRefs;
2193    MemRefsEnd = NewMemRefsEnd;
2194  }
2195
2196  static bool classof(const SDNode *N) {
2197    return N->isMachineOpcode();
2198  }
2199};
2200
2201class SDNodeIterator : public std::iterator<std::forward_iterator_tag,
2202                                            SDNode, ptrdiff_t> {
2203  const SDNode *Node;
2204  unsigned Operand;
2205
2206  SDNodeIterator(const SDNode *N, unsigned Op) : Node(N), Operand(Op) {}
2207public:
2208  bool operator==(const SDNodeIterator& x) const {
2209    return Operand == x.Operand;
2210  }
2211  bool operator!=(const SDNodeIterator& x) const { return !operator==(x); }
2212
2213  pointer operator*() const {
2214    return Node->getOperand(Operand).getNode();
2215  }
2216  pointer operator->() const { return operator*(); }
2217
2218  SDNodeIterator& operator++() {                // Preincrement
2219    ++Operand;
2220    return *this;
2221  }
2222  SDNodeIterator operator++(int) { // Postincrement
2223    SDNodeIterator tmp = *this; ++*this; return tmp;
2224  }
2225  size_t operator-(SDNodeIterator Other) const {
2226    assert(Node == Other.Node &&
2227           "Cannot compare iterators of two different nodes!");
2228    return Operand - Other.Operand;
2229  }
2230
2231  static SDNodeIterator begin(const SDNode *N) { return SDNodeIterator(N, 0); }
2232  static SDNodeIterator end  (const SDNode *N) {
2233    return SDNodeIterator(N, N->getNumOperands());
2234  }
2235
2236  unsigned getOperand() const { return Operand; }
2237  const SDNode *getNode() const { return Node; }
2238};
2239
2240template <> struct GraphTraits<SDNode*> {
2241  typedef SDNode NodeType;
2242  typedef SDNodeIterator ChildIteratorType;
2243  static inline NodeType *getEntryNode(SDNode *N) { return N; }
2244  static inline ChildIteratorType child_begin(NodeType *N) {
2245    return SDNodeIterator::begin(N);
2246  }
2247  static inline ChildIteratorType child_end(NodeType *N) {
2248    return SDNodeIterator::end(N);
2249  }
2250};
2251
2252/// The largest SDNode class.
2253typedef MaskedGatherScatterSDNode LargestSDNode;
2254
2255/// The SDNode class with the greatest alignment requirement.
2256typedef GlobalAddressSDNode MostAlignedSDNode;
2257
2258namespace ISD {
2259  /// Returns true if the specified node is a non-extending and unindexed load.
2260  inline bool isNormalLoad(const SDNode *N) {
2261    const LoadSDNode *Ld = dyn_cast<LoadSDNode>(N);
2262    return Ld && Ld->getExtensionType() == ISD::NON_EXTLOAD &&
2263      Ld->getAddressingMode() == ISD::UNINDEXED;
2264  }
2265
2266  /// Returns true if the specified node is a non-extending load.
2267  inline bool isNON_EXTLoad(const SDNode *N) {
2268    return isa<LoadSDNode>(N) &&
2269      cast<LoadSDNode>(N)->getExtensionType() == ISD::NON_EXTLOAD;
2270  }
2271
2272  /// Returns true if the specified node is a EXTLOAD.
2273  inline bool isEXTLoad(const SDNode *N) {
2274    return isa<LoadSDNode>(N) &&
2275      cast<LoadSDNode>(N)->getExtensionType() == ISD::EXTLOAD;
2276  }
2277
2278  /// Returns true if the specified node is a SEXTLOAD.
2279  inline bool isSEXTLoad(const SDNode *N) {
2280    return isa<LoadSDNode>(N) &&
2281      cast<LoadSDNode>(N)->getExtensionType() == ISD::SEXTLOAD;
2282  }
2283
2284  /// Returns true if the specified node is a ZEXTLOAD.
2285  inline bool isZEXTLoad(const SDNode *N) {
2286    return isa<LoadSDNode>(N) &&
2287      cast<LoadSDNode>(N)->getExtensionType() == ISD::ZEXTLOAD;
2288  }
2289
2290  /// Returns true if the specified node is an unindexed load.
2291  inline bool isUNINDEXEDLoad(const SDNode *N) {
2292    return isa<LoadSDNode>(N) &&
2293      cast<LoadSDNode>(N)->getAddressingMode() == ISD::UNINDEXED;
2294  }
2295
2296  /// Returns true if the specified node is a non-truncating
2297  /// and unindexed store.
2298  inline bool isNormalStore(const SDNode *N) {
2299    const StoreSDNode *St = dyn_cast<StoreSDNode>(N);
2300    return St && !St->isTruncatingStore() &&
2301      St->getAddressingMode() == ISD::UNINDEXED;
2302  }
2303
2304  /// Returns true if the specified node is a non-truncating store.
2305  inline bool isNON_TRUNCStore(const SDNode *N) {
2306    return isa<StoreSDNode>(N) && !cast<StoreSDNode>(N)->isTruncatingStore();
2307  }
2308
2309  /// Returns true if the specified node is a truncating store.
2310  inline bool isTRUNCStore(const SDNode *N) {
2311    return isa<StoreSDNode>(N) && cast<StoreSDNode>(N)->isTruncatingStore();
2312  }
2313
2314  /// Returns true if the specified node is an unindexed store.
2315  inline bool isUNINDEXEDStore(const SDNode *N) {
2316    return isa<StoreSDNode>(N) &&
2317      cast<StoreSDNode>(N)->getAddressingMode() == ISD::UNINDEXED;
2318  }
2319}
2320
2321} // end llvm namespace
2322
2323#endif
2324