Revert r243347 "Add TargetTransformInfo::isZExtFree."
[oota-llvm.git] / include / llvm / CodeGen / SelectionDAGNodes.h
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
40 namespace llvm {
41
42 class SelectionDAG;
43 class GlobalValue;
44 class MachineBasicBlock;
45 class MachineConstantPoolValue;
46 class SDNode;
47 class BinaryWithFlagsSDNode;
48 class Value;
49 class MCSymbol;
50 template <typename T> struct DenseMapInfo;
51 template <typename T> struct simplify_type;
52 template <typename T> struct ilist_traits;
53
54 void 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 ///
61 struct SDVTList {
62   const EVT *VTs;
63   unsigned int NumVTs;
64 };
65
66 namespace 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 ///
101 class 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.
106 public:
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
188 template<> 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 };
207 template <> 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.
212 template<> struct simplify_type<SDValue> {
213   typedef SDNode* SimpleType;
214   static SimpleType getSimplifiedValue(SDValue &Val) {
215     return Val.getNode();
216   }
217 };
218 template<> 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 ///
230 class 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
242 public:
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
280 private:
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.
311 template<> 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.
321 struct SDNodeFlags {
322 private:
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
332 public:
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 ///
376 class SDNode : public FoldingSetNode, public ilist_node<SDNode> {
377 private:
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
389 protected:
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
395 private:
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
428 public:
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 iterator_range<use_iterator>(use_begin(), use_end());
580   }
581   inline iterator_range<use_iterator> uses() const {
582     return iterator_range<use_iterator>(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 iterator_range<value_op_iterator>(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
770 protected:
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.
884 class SDLoc {
885 private:
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
891 public:
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
925 inline 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
932 inline unsigned SDValue::getOpcode() const {
933   return Node->getOpcode();
934 }
935 inline EVT SDValue::getValueType() const {
936   return Node->getValueType(ResNo);
937 }
938 inline unsigned SDValue::getNumOperands() const {
939   return Node->getNumOperands();
940 }
941 inline const SDValue &SDValue::getOperand(unsigned i) const {
942   return Node->getOperand(i);
943 }
944 inline uint64_t SDValue::getConstantOperandVal(unsigned i) const {
945   return Node->getConstantOperandVal(i);
946 }
947 inline bool SDValue::isTargetOpcode() const {
948   return Node->isTargetOpcode();
949 }
950 inline bool SDValue::isTargetMemoryOpcode() const {
951   return Node->isTargetMemoryOpcode();
952 }
953 inline bool SDValue::isMachineOpcode() const {
954   return Node->isMachineOpcode();
955 }
956 inline unsigned SDValue::getMachineOpcode() const {
957   return Node->getMachineOpcode();
958 }
959 inline bool SDValue::isUndef() const {
960   return Node->isUndef();
961 }
962 inline bool SDValue::use_empty() const {
963   return !Node->hasAnyUseOfValue(ResNo);
964 }
965 inline bool SDValue::hasOneUse() const {
966   return Node->hasNUsesOfValue(1, ResNo);
967 }
968 inline const DebugLoc &SDValue::getDebugLoc() const {
969   return Node->getDebugLoc();
970 }
971 inline void SDValue::dump() const {
972   return Node->dump();
973 }
974 inline void SDValue::dumpr() const {
975   return Node->dumpr();
976 }
977 // Define inline functions from the SDUse class.
978
979 inline void SDUse::set(const SDValue &V) {
980   if (Val.getNode()) removeFromList();
981   Val = V;
982   if (V.getNode()) V.getNode()->addUse(*this);
983 }
984
985 inline void SDUse::setInitial(const SDValue &V) {
986   Val = V;
987   V.getNode()->addUse(*this);
988 }
989
990 inline 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.
998 class UnarySDNode : public SDNode {
999   SDUse Op;
1000 public:
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.
1010 class BinarySDNode : public SDNode {
1011   SDUse Ops[2];
1012 public:
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.
1021 static 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.
1044 class BinaryWithFlagsSDNode : public BinarySDNode {
1045 public:
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.
1057 class TernarySDNode : public SDNode {
1058   SDUse Ops[3];
1059 public:
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.
1072 class HandleSDNode : public SDNode {
1073   SDUse Op;
1074 public:
1075   explicit HandleSDNode(SDValue X)
1076     : SDNode(ISD::HANDLENODE, 0, DebugLoc(), getSDVTList(MVT::Other)) {
1077     InitOperands(&Op, X);
1078   }
1079   ~HandleSDNode();
1080   const SDValue &getValue() const { return Op; }
1081 };
1082
1083 class AddrSpaceCastSDNode : public UnarySDNode {
1084 private:
1085   unsigned SrcAddrSpace;
1086   unsigned DestAddrSpace;
1087
1088 public:
1089   AddrSpaceCastSDNode(unsigned Order, DebugLoc dl, EVT VT, SDValue X,
1090                       unsigned SrcAS, unsigned DestAS);
1091
1092   unsigned getSrcAddressSpace() const { return SrcAddrSpace; }
1093   unsigned getDestAddressSpace() const { return DestAddrSpace; }
1094
1095   static bool classof(const SDNode *N) {
1096     return N->getOpcode() == ISD::ADDRSPACECAST;
1097   }
1098 };
1099
1100 /// This is an abstract virtual class for memory operations.
1101 class MemSDNode : public SDNode {
1102 private:
1103   // VT of in-memory value.
1104   EVT MemoryVT;
1105
1106 protected:
1107   /// Memory reference information.
1108   MachineMemOperand *MMO;
1109
1110 public:
1111   MemSDNode(unsigned Opc, unsigned Order, DebugLoc dl, SDVTList VTs,
1112             EVT MemoryVT, MachineMemOperand *MMO);
1113
1114   MemSDNode(unsigned Opc, unsigned Order, DebugLoc dl, SDVTList VTs,
1115             ArrayRef<SDValue> Ops, EVT MemoryVT, MachineMemOperand *MMO);
1116
1117   bool readMem() const { return MMO->isLoad(); }
1118   bool writeMem() const { return MMO->isStore(); }
1119
1120   /// Returns alignment and volatility of the memory access
1121   unsigned getOriginalAlignment() const {
1122     return MMO->getBaseAlignment();
1123   }
1124   unsigned getAlignment() const {
1125     return MMO->getAlignment();
1126   }
1127
1128   /// Return the SubclassData value, which contains an
1129   /// encoding of the volatile flag, as well as bits used by subclasses. This
1130   /// function should only be used to compute a FoldingSetNodeID value.
1131   unsigned getRawSubclassData() const {
1132     return SubclassData;
1133   }
1134
1135   // We access subclass data here so that we can check consistency
1136   // with MachineMemOperand information.
1137   bool isVolatile() const { return (SubclassData >> 5) & 1; }
1138   bool isNonTemporal() const { return (SubclassData >> 6) & 1; }
1139   bool isInvariant() const { return (SubclassData >> 7) & 1; }
1140
1141   AtomicOrdering getOrdering() const {
1142     return AtomicOrdering((SubclassData >> 8) & 15);
1143   }
1144   SynchronizationScope getSynchScope() const {
1145     return SynchronizationScope((SubclassData >> 12) & 1);
1146   }
1147
1148   // Returns the offset from the location of the access.
1149   int64_t getSrcValueOffset() const { return MMO->getOffset(); }
1150
1151   /// Returns the AA info that describes the dereference.
1152   AAMDNodes getAAInfo() const { return MMO->getAAInfo(); }
1153
1154   /// Returns the Ranges that describes the dereference.
1155   const MDNode *getRanges() const { return MMO->getRanges(); }
1156
1157   /// Return the type of the in-memory value.
1158   EVT getMemoryVT() const { return MemoryVT; }
1159
1160   /// Return a MachineMemOperand object describing the memory
1161   /// reference performed by operation.
1162   MachineMemOperand *getMemOperand() const { return MMO; }
1163
1164   const MachinePointerInfo &getPointerInfo() const {
1165     return MMO->getPointerInfo();
1166   }
1167
1168   /// Return the address space for the associated pointer
1169   unsigned getAddressSpace() const {
1170     return getPointerInfo().getAddrSpace();
1171   }
1172
1173   /// Update this MemSDNode's MachineMemOperand information
1174   /// to reflect the alignment of NewMMO, if it has a greater alignment.
1175   /// This must only be used when the new alignment applies to all users of
1176   /// this MachineMemOperand.
1177   void refineAlignment(const MachineMemOperand *NewMMO) {
1178     MMO->refineAlignment(NewMMO);
1179   }
1180
1181   const SDValue &getChain() const { return getOperand(0); }
1182   const SDValue &getBasePtr() const {
1183     return getOperand(getOpcode() == ISD::STORE ? 2 : 1);
1184   }
1185
1186   // Methods to support isa and dyn_cast
1187   static bool classof(const SDNode *N) {
1188     // For some targets, we lower some target intrinsics to a MemIntrinsicNode
1189     // with either an intrinsic or a target opcode.
1190     return N->getOpcode() == ISD::LOAD                ||
1191            N->getOpcode() == ISD::STORE               ||
1192            N->getOpcode() == ISD::PREFETCH            ||
1193            N->getOpcode() == ISD::ATOMIC_CMP_SWAP     ||
1194            N->getOpcode() == ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS ||
1195            N->getOpcode() == ISD::ATOMIC_SWAP         ||
1196            N->getOpcode() == ISD::ATOMIC_LOAD_ADD     ||
1197            N->getOpcode() == ISD::ATOMIC_LOAD_SUB     ||
1198            N->getOpcode() == ISD::ATOMIC_LOAD_AND     ||
1199            N->getOpcode() == ISD::ATOMIC_LOAD_OR      ||
1200            N->getOpcode() == ISD::ATOMIC_LOAD_XOR     ||
1201            N->getOpcode() == ISD::ATOMIC_LOAD_NAND    ||
1202            N->getOpcode() == ISD::ATOMIC_LOAD_MIN     ||
1203            N->getOpcode() == ISD::ATOMIC_LOAD_MAX     ||
1204            N->getOpcode() == ISD::ATOMIC_LOAD_UMIN    ||
1205            N->getOpcode() == ISD::ATOMIC_LOAD_UMAX    ||
1206            N->getOpcode() == ISD::ATOMIC_LOAD         ||
1207            N->getOpcode() == ISD::ATOMIC_STORE        ||
1208            N->getOpcode() == ISD::MLOAD               ||
1209            N->getOpcode() == ISD::MSTORE              ||
1210            N->getOpcode() == ISD::MGATHER             ||
1211            N->getOpcode() == ISD::MSCATTER            ||
1212            N->isMemIntrinsic()                        ||
1213            N->isTargetMemoryOpcode();
1214   }
1215 };
1216
1217 /// This is an SDNode representing atomic operations.
1218 class AtomicSDNode : public MemSDNode {
1219   SDUse Ops[4];
1220
1221   /// For cmpxchg instructions, the ordering requirements when a store does not
1222   /// occur.
1223   AtomicOrdering FailureOrdering;
1224
1225   void InitAtomic(AtomicOrdering SuccessOrdering,
1226                   AtomicOrdering FailureOrdering,
1227                   SynchronizationScope SynchScope) {
1228     // This must match encodeMemSDNodeFlags() in SelectionDAG.cpp.
1229     assert((SuccessOrdering & 15) == SuccessOrdering &&
1230            "Ordering may not require more than 4 bits!");
1231     assert((FailureOrdering & 15) == FailureOrdering &&
1232            "Ordering may not require more than 4 bits!");
1233     assert((SynchScope & 1) == SynchScope &&
1234            "SynchScope may not require more than 1 bit!");
1235     SubclassData |= SuccessOrdering << 8;
1236     SubclassData |= SynchScope << 12;
1237     this->FailureOrdering = FailureOrdering;
1238     assert(getSuccessOrdering() == SuccessOrdering &&
1239            "Ordering encoding error!");
1240     assert(getFailureOrdering() == FailureOrdering &&
1241            "Ordering encoding error!");
1242     assert(getSynchScope() == SynchScope && "Synch-scope encoding error!");
1243   }
1244
1245 public:
1246   // Opc:   opcode for atomic
1247   // VTL:    value type list
1248   // Chain:  memory chain for operaand
1249   // Ptr:    address to update as a SDValue
1250   // Cmp:    compare value
1251   // Swp:    swap value
1252   // SrcVal: address to update as a Value (used for MemOperand)
1253   // Align:  alignment of memory
1254   AtomicSDNode(unsigned Opc, unsigned Order, DebugLoc dl, SDVTList VTL,
1255                EVT MemVT, SDValue Chain, SDValue Ptr, SDValue Cmp, SDValue Swp,
1256                MachineMemOperand *MMO, AtomicOrdering Ordering,
1257                SynchronizationScope SynchScope)
1258       : MemSDNode(Opc, Order, dl, VTL, MemVT, MMO) {
1259     InitAtomic(Ordering, Ordering, SynchScope);
1260     InitOperands(Ops, Chain, Ptr, Cmp, Swp);
1261   }
1262   AtomicSDNode(unsigned Opc, unsigned Order, DebugLoc dl, SDVTList VTL,
1263                EVT MemVT,
1264                SDValue Chain, SDValue Ptr,
1265                SDValue Val, MachineMemOperand *MMO,
1266                AtomicOrdering Ordering, SynchronizationScope SynchScope)
1267     : MemSDNode(Opc, Order, dl, VTL, MemVT, MMO) {
1268     InitAtomic(Ordering, Ordering, SynchScope);
1269     InitOperands(Ops, Chain, Ptr, Val);
1270   }
1271   AtomicSDNode(unsigned Opc, unsigned Order, DebugLoc dl, SDVTList VTL,
1272                EVT MemVT,
1273                SDValue Chain, SDValue Ptr,
1274                MachineMemOperand *MMO,
1275                AtomicOrdering Ordering, SynchronizationScope SynchScope)
1276     : MemSDNode(Opc, Order, dl, VTL, MemVT, MMO) {
1277     InitAtomic(Ordering, Ordering, SynchScope);
1278     InitOperands(Ops, Chain, Ptr);
1279   }
1280   AtomicSDNode(unsigned Opc, unsigned Order, DebugLoc dl, SDVTList VTL, EVT MemVT,
1281                const SDValue* AllOps, SDUse *DynOps, unsigned NumOps,
1282                MachineMemOperand *MMO,
1283                AtomicOrdering SuccessOrdering, AtomicOrdering FailureOrdering,
1284                SynchronizationScope SynchScope)
1285     : MemSDNode(Opc, Order, dl, VTL, MemVT, MMO) {
1286     InitAtomic(SuccessOrdering, FailureOrdering, SynchScope);
1287     assert((DynOps || NumOps <= array_lengthof(Ops)) &&
1288            "Too many ops for internal storage!");
1289     InitOperands(DynOps ? DynOps : Ops, AllOps, NumOps);
1290   }
1291
1292   const SDValue &getBasePtr() const { return getOperand(1); }
1293   const SDValue &getVal() const { return getOperand(2); }
1294
1295   AtomicOrdering getSuccessOrdering() const {
1296     return getOrdering();
1297   }
1298
1299   // Not quite enough room in SubclassData for everything, so failure gets its
1300   // own field.
1301   AtomicOrdering getFailureOrdering() const {
1302     return FailureOrdering;
1303   }
1304
1305   bool isCompareAndSwap() const {
1306     unsigned Op = getOpcode();
1307     return Op == ISD::ATOMIC_CMP_SWAP || Op == ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS;
1308   }
1309
1310   // Methods to support isa and dyn_cast
1311   static bool classof(const SDNode *N) {
1312     return N->getOpcode() == ISD::ATOMIC_CMP_SWAP     ||
1313            N->getOpcode() == ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS ||
1314            N->getOpcode() == ISD::ATOMIC_SWAP         ||
1315            N->getOpcode() == ISD::ATOMIC_LOAD_ADD     ||
1316            N->getOpcode() == ISD::ATOMIC_LOAD_SUB     ||
1317            N->getOpcode() == ISD::ATOMIC_LOAD_AND     ||
1318            N->getOpcode() == ISD::ATOMIC_LOAD_OR      ||
1319            N->getOpcode() == ISD::ATOMIC_LOAD_XOR     ||
1320            N->getOpcode() == ISD::ATOMIC_LOAD_NAND    ||
1321            N->getOpcode() == ISD::ATOMIC_LOAD_MIN     ||
1322            N->getOpcode() == ISD::ATOMIC_LOAD_MAX     ||
1323            N->getOpcode() == ISD::ATOMIC_LOAD_UMIN    ||
1324            N->getOpcode() == ISD::ATOMIC_LOAD_UMAX    ||
1325            N->getOpcode() == ISD::ATOMIC_LOAD         ||
1326            N->getOpcode() == ISD::ATOMIC_STORE;
1327   }
1328 };
1329
1330 /// This SDNode is used for target intrinsics that touch
1331 /// memory and need an associated MachineMemOperand. Its opcode may be
1332 /// INTRINSIC_VOID, INTRINSIC_W_CHAIN, PREFETCH, or a target-specific opcode
1333 /// with a value not less than FIRST_TARGET_MEMORY_OPCODE.
1334 class MemIntrinsicSDNode : public MemSDNode {
1335 public:
1336   MemIntrinsicSDNode(unsigned Opc, unsigned Order, DebugLoc dl, SDVTList VTs,
1337                      ArrayRef<SDValue> Ops, EVT MemoryVT,
1338                      MachineMemOperand *MMO)
1339     : MemSDNode(Opc, Order, dl, VTs, Ops, MemoryVT, MMO) {
1340     SubclassData |= 1u << 13;
1341   }
1342
1343   // Methods to support isa and dyn_cast
1344   static bool classof(const SDNode *N) {
1345     // We lower some target intrinsics to their target opcode
1346     // early a node with a target opcode can be of this class
1347     return N->isMemIntrinsic()             ||
1348            N->getOpcode() == ISD::PREFETCH ||
1349            N->isTargetMemoryOpcode();
1350   }
1351 };
1352
1353 /// This SDNode is used to implement the code generator
1354 /// support for the llvm IR shufflevector instruction.  It combines elements
1355 /// from two input vectors into a new input vector, with the selection and
1356 /// ordering of elements determined by an array of integers, referred to as
1357 /// the shuffle mask.  For input vectors of width N, mask indices of 0..N-1
1358 /// refer to elements from the LHS input, and indices from N to 2N-1 the RHS.
1359 /// An index of -1 is treated as undef, such that the code generator may put
1360 /// any value in the corresponding element of the result.
1361 class ShuffleVectorSDNode : public SDNode {
1362   SDUse Ops[2];
1363
1364   // The memory for Mask is owned by the SelectionDAG's OperandAllocator, and
1365   // is freed when the SelectionDAG object is destroyed.
1366   const int *Mask;
1367 protected:
1368   friend class SelectionDAG;
1369   ShuffleVectorSDNode(EVT VT, unsigned Order, DebugLoc dl, SDValue N1,
1370                       SDValue N2, const int *M)
1371     : SDNode(ISD::VECTOR_SHUFFLE, Order, dl, getSDVTList(VT)), Mask(M) {
1372     InitOperands(Ops, N1, N2);
1373   }
1374 public:
1375
1376   ArrayRef<int> getMask() const {
1377     EVT VT = getValueType(0);
1378     return makeArrayRef(Mask, VT.getVectorNumElements());
1379   }
1380   int getMaskElt(unsigned Idx) const {
1381     assert(Idx < getValueType(0).getVectorNumElements() && "Idx out of range!");
1382     return Mask[Idx];
1383   }
1384
1385   bool isSplat() const { return isSplatMask(Mask, getValueType(0)); }
1386   int  getSplatIndex() const {
1387     assert(isSplat() && "Cannot get splat index for non-splat!");
1388     EVT VT = getValueType(0);
1389     for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
1390       if (Mask[i] >= 0)
1391         return Mask[i];
1392     }
1393     llvm_unreachable("Splat with all undef indices?");
1394   }
1395   static bool isSplatMask(const int *Mask, EVT VT);
1396
1397   /// Change values in a shuffle permute mask assuming
1398   /// the two vector operands have swapped position.
1399   static void commuteMask(SmallVectorImpl<int> &Mask) {
1400     unsigned NumElems = Mask.size();
1401     for (unsigned i = 0; i != NumElems; ++i) {
1402       int idx = Mask[i];
1403       if (idx < 0)
1404         continue;
1405       else if (idx < (int)NumElems)
1406         Mask[i] = idx + NumElems;
1407       else
1408         Mask[i] = idx - NumElems;
1409     }
1410   }
1411
1412   static bool classof(const SDNode *N) {
1413     return N->getOpcode() == ISD::VECTOR_SHUFFLE;
1414   }
1415 };
1416
1417 class ConstantSDNode : public SDNode {
1418   const ConstantInt *Value;
1419   friend class SelectionDAG;
1420   ConstantSDNode(bool isTarget, bool isOpaque, const ConstantInt *val,
1421                  DebugLoc DL, EVT VT)
1422     : SDNode(isTarget ? ISD::TargetConstant : ISD::Constant,
1423              0, DL, getSDVTList(VT)), Value(val) {
1424     SubclassData |= (uint16_t)isOpaque;
1425   }
1426 public:
1427
1428   const ConstantInt *getConstantIntValue() const { return Value; }
1429   const APInt &getAPIntValue() const { return Value->getValue(); }
1430   uint64_t getZExtValue() const { return Value->getZExtValue(); }
1431   int64_t getSExtValue() const { return Value->getSExtValue(); }
1432
1433   bool isOne() const { return Value->isOne(); }
1434   bool isNullValue() const { return Value->isNullValue(); }
1435   bool isAllOnesValue() const { return Value->isAllOnesValue(); }
1436
1437   bool isOpaque() const { return SubclassData & 1; }
1438
1439   static bool classof(const SDNode *N) {
1440     return N->getOpcode() == ISD::Constant ||
1441            N->getOpcode() == ISD::TargetConstant;
1442   }
1443 };
1444
1445 class ConstantFPSDNode : public SDNode {
1446   const ConstantFP *Value;
1447   friend class SelectionDAG;
1448   ConstantFPSDNode(bool isTarget, const ConstantFP *val, DebugLoc DL, EVT VT)
1449     : SDNode(isTarget ? ISD::TargetConstantFP : ISD::ConstantFP,
1450              0, DL, getSDVTList(VT)), Value(val) {
1451   }
1452 public:
1453
1454   const APFloat& getValueAPF() const { return Value->getValueAPF(); }
1455   const ConstantFP *getConstantFPValue() const { return Value; }
1456
1457   /// Return true if the value is positive or negative zero.
1458   bool isZero() const { return Value->isZero(); }
1459
1460   /// Return true if the value is a NaN.
1461   bool isNaN() const { return Value->isNaN(); }
1462
1463   /// Return true if the value is an infinity
1464   bool isInfinity() const { return Value->isInfinity(); }
1465
1466   /// Return true if the value is negative.
1467   bool isNegative() const { return Value->isNegative(); }
1468
1469   /// We don't rely on operator== working on double values, as
1470   /// it returns true for things that are clearly not equal, like -0.0 and 0.0.
1471   /// As such, this method can be used to do an exact bit-for-bit comparison of
1472   /// two floating point values.
1473
1474   /// We leave the version with the double argument here because it's just so
1475   /// convenient to write "2.0" and the like.  Without this function we'd
1476   /// have to duplicate its logic everywhere it's called.
1477   bool isExactlyValue(double V) const {
1478     bool ignored;
1479     APFloat Tmp(V);
1480     Tmp.convert(Value->getValueAPF().getSemantics(),
1481                 APFloat::rmNearestTiesToEven, &ignored);
1482     return isExactlyValue(Tmp);
1483   }
1484   bool isExactlyValue(const APFloat& V) const;
1485
1486   static bool isValueValidForType(EVT VT, const APFloat& Val);
1487
1488   static bool classof(const SDNode *N) {
1489     return N->getOpcode() == ISD::ConstantFP ||
1490            N->getOpcode() == ISD::TargetConstantFP;
1491   }
1492 };
1493
1494 class GlobalAddressSDNode : public SDNode {
1495   const GlobalValue *TheGlobal;
1496   int64_t Offset;
1497   unsigned char TargetFlags;
1498   friend class SelectionDAG;
1499   GlobalAddressSDNode(unsigned Opc, unsigned Order, DebugLoc DL,
1500                       const GlobalValue *GA, EVT VT, int64_t o,
1501                       unsigned char TargetFlags);
1502 public:
1503
1504   const GlobalValue *getGlobal() const { return TheGlobal; }
1505   int64_t getOffset() const { return Offset; }
1506   unsigned char getTargetFlags() const { return TargetFlags; }
1507   // Return the address space this GlobalAddress belongs to.
1508   unsigned getAddressSpace() const;
1509
1510   static bool classof(const SDNode *N) {
1511     return N->getOpcode() == ISD::GlobalAddress ||
1512            N->getOpcode() == ISD::TargetGlobalAddress ||
1513            N->getOpcode() == ISD::GlobalTLSAddress ||
1514            N->getOpcode() == ISD::TargetGlobalTLSAddress;
1515   }
1516 };
1517
1518 class FrameIndexSDNode : public SDNode {
1519   int FI;
1520   friend class SelectionDAG;
1521   FrameIndexSDNode(int fi, EVT VT, bool isTarg)
1522     : SDNode(isTarg ? ISD::TargetFrameIndex : ISD::FrameIndex,
1523       0, DebugLoc(), getSDVTList(VT)), FI(fi) {
1524   }
1525 public:
1526
1527   int getIndex() const { return FI; }
1528
1529   static bool classof(const SDNode *N) {
1530     return N->getOpcode() == ISD::FrameIndex ||
1531            N->getOpcode() == ISD::TargetFrameIndex;
1532   }
1533 };
1534
1535 class JumpTableSDNode : public SDNode {
1536   int JTI;
1537   unsigned char TargetFlags;
1538   friend class SelectionDAG;
1539   JumpTableSDNode(int jti, EVT VT, bool isTarg, unsigned char TF)
1540     : SDNode(isTarg ? ISD::TargetJumpTable : ISD::JumpTable,
1541       0, DebugLoc(), getSDVTList(VT)), JTI(jti), TargetFlags(TF) {
1542   }
1543 public:
1544
1545   int getIndex() const { return JTI; }
1546   unsigned char getTargetFlags() const { return TargetFlags; }
1547
1548   static bool classof(const SDNode *N) {
1549     return N->getOpcode() == ISD::JumpTable ||
1550            N->getOpcode() == ISD::TargetJumpTable;
1551   }
1552 };
1553
1554 class ConstantPoolSDNode : public SDNode {
1555   union {
1556     const Constant *ConstVal;
1557     MachineConstantPoolValue *MachineCPVal;
1558   } Val;
1559   int Offset;  // It's a MachineConstantPoolValue if top bit is set.
1560   unsigned Alignment;  // Minimum alignment requirement of CP (not log2 value).
1561   unsigned char TargetFlags;
1562   friend class SelectionDAG;
1563   ConstantPoolSDNode(bool isTarget, const Constant *c, EVT VT, int o,
1564                      unsigned Align, unsigned char TF)
1565     : SDNode(isTarget ? ISD::TargetConstantPool : ISD::ConstantPool, 0,
1566              DebugLoc(), getSDVTList(VT)), Offset(o), Alignment(Align),
1567              TargetFlags(TF) {
1568     assert(Offset >= 0 && "Offset is too large");
1569     Val.ConstVal = c;
1570   }
1571   ConstantPoolSDNode(bool isTarget, MachineConstantPoolValue *v,
1572                      EVT VT, int o, unsigned Align, unsigned char TF)
1573     : SDNode(isTarget ? ISD::TargetConstantPool : ISD::ConstantPool, 0,
1574              DebugLoc(), getSDVTList(VT)), Offset(o), Alignment(Align),
1575              TargetFlags(TF) {
1576     assert(Offset >= 0 && "Offset is too large");
1577     Val.MachineCPVal = v;
1578     Offset |= 1 << (sizeof(unsigned)*CHAR_BIT-1);
1579   }
1580 public:
1581
1582   bool isMachineConstantPoolEntry() const {
1583     return Offset < 0;
1584   }
1585
1586   const Constant *getConstVal() const {
1587     assert(!isMachineConstantPoolEntry() && "Wrong constantpool type");
1588     return Val.ConstVal;
1589   }
1590
1591   MachineConstantPoolValue *getMachineCPVal() const {
1592     assert(isMachineConstantPoolEntry() && "Wrong constantpool type");
1593     return Val.MachineCPVal;
1594   }
1595
1596   int getOffset() const {
1597     return Offset & ~(1 << (sizeof(unsigned)*CHAR_BIT-1));
1598   }
1599
1600   // Return the alignment of this constant pool object, which is either 0 (for
1601   // default alignment) or the desired value.
1602   unsigned getAlignment() const { return Alignment; }
1603   unsigned char getTargetFlags() const { return TargetFlags; }
1604
1605   Type *getType() const;
1606
1607   static bool classof(const SDNode *N) {
1608     return N->getOpcode() == ISD::ConstantPool ||
1609            N->getOpcode() == ISD::TargetConstantPool;
1610   }
1611 };
1612
1613 /// Completely target-dependent object reference.
1614 class TargetIndexSDNode : public SDNode {
1615   unsigned char TargetFlags;
1616   int Index;
1617   int64_t Offset;
1618   friend class SelectionDAG;
1619 public:
1620
1621   TargetIndexSDNode(int Idx, EVT VT, int64_t Ofs, unsigned char TF)
1622     : SDNode(ISD::TargetIndex, 0, DebugLoc(), getSDVTList(VT)),
1623       TargetFlags(TF), Index(Idx), Offset(Ofs) {}
1624 public:
1625
1626   unsigned char getTargetFlags() const { return TargetFlags; }
1627   int getIndex() const { return Index; }
1628   int64_t getOffset() const { return Offset; }
1629
1630   static bool classof(const SDNode *N) {
1631     return N->getOpcode() == ISD::TargetIndex;
1632   }
1633 };
1634
1635 class BasicBlockSDNode : public SDNode {
1636   MachineBasicBlock *MBB;
1637   friend class SelectionDAG;
1638   /// Debug info is meaningful and potentially useful here, but we create
1639   /// blocks out of order when they're jumped to, which makes it a bit
1640   /// harder.  Let's see if we need it first.
1641   explicit BasicBlockSDNode(MachineBasicBlock *mbb)
1642     : SDNode(ISD::BasicBlock, 0, DebugLoc(), getSDVTList(MVT::Other)), MBB(mbb)
1643   {}
1644 public:
1645
1646   MachineBasicBlock *getBasicBlock() const { return MBB; }
1647
1648   static bool classof(const SDNode *N) {
1649     return N->getOpcode() == ISD::BasicBlock;
1650   }
1651 };
1652
1653 /// A "pseudo-class" with methods for operating on BUILD_VECTORs.
1654 class BuildVectorSDNode : public SDNode {
1655   // These are constructed as SDNodes and then cast to BuildVectorSDNodes.
1656   explicit BuildVectorSDNode() = delete;
1657 public:
1658   /// Check if this is a constant splat, and if so, find the
1659   /// smallest element size that splats the vector.  If MinSplatBits is
1660   /// nonzero, the element size must be at least that large.  Note that the
1661   /// splat element may be the entire vector (i.e., a one element vector).
1662   /// Returns the splat element value in SplatValue.  Any undefined bits in
1663   /// that value are zero, and the corresponding bits in the SplatUndef mask
1664   /// are set.  The SplatBitSize value is set to the splat element size in
1665   /// bits.  HasAnyUndefs is set to true if any bits in the vector are
1666   /// undefined.  isBigEndian describes the endianness of the target.
1667   bool isConstantSplat(APInt &SplatValue, APInt &SplatUndef,
1668                        unsigned &SplatBitSize, bool &HasAnyUndefs,
1669                        unsigned MinSplatBits = 0,
1670                        bool isBigEndian = false) const;
1671
1672   /// \brief Returns the splatted value or a null value if this is not a splat.
1673   ///
1674   /// If passed a non-null UndefElements bitvector, it will resize it to match
1675   /// the vector width and set the bits where elements are undef.
1676   SDValue getSplatValue(BitVector *UndefElements = nullptr) const;
1677
1678   /// \brief Returns the splatted constant or null if this is not a constant
1679   /// splat.
1680   ///
1681   /// If passed a non-null UndefElements bitvector, it will resize it to match
1682   /// the vector width and set the bits where elements are undef.
1683   ConstantSDNode *
1684   getConstantSplatNode(BitVector *UndefElements = nullptr) const;
1685
1686   /// \brief Returns the splatted constant FP or null if this is not a constant
1687   /// FP splat.
1688   ///
1689   /// If passed a non-null UndefElements bitvector, it will resize it to match
1690   /// the vector width and set the bits where elements are undef.
1691   ConstantFPSDNode *
1692   getConstantFPSplatNode(BitVector *UndefElements = nullptr) const;
1693
1694   /// \brief If this is a constant FP splat and the splatted constant FP is an
1695   /// exact power or 2, return the log base 2 integer value.  Otherwise,
1696   /// return -1.
1697   ///
1698   /// The BitWidth specifies the necessary bit precision.
1699   int32_t getConstantFPSplatPow2ToLog2Int(BitVector *UndefElements,
1700                                           uint32_t BitWidth) const;
1701
1702   bool isConstant() const;
1703
1704   static inline bool classof(const SDNode *N) {
1705     return N->getOpcode() == ISD::BUILD_VECTOR;
1706   }
1707 };
1708
1709 /// An SDNode that holds an arbitrary LLVM IR Value. This is
1710 /// used when the SelectionDAG needs to make a simple reference to something
1711 /// in the LLVM IR representation.
1712 ///
1713 class SrcValueSDNode : public SDNode {
1714   const Value *V;
1715   friend class SelectionDAG;
1716   /// Create a SrcValue for a general value.
1717   explicit SrcValueSDNode(const Value *v)
1718     : SDNode(ISD::SRCVALUE, 0, DebugLoc(), getSDVTList(MVT::Other)), V(v) {}
1719
1720 public:
1721   /// Return the contained Value.
1722   const Value *getValue() const { return V; }
1723
1724   static bool classof(const SDNode *N) {
1725     return N->getOpcode() == ISD::SRCVALUE;
1726   }
1727 };
1728
1729 class MDNodeSDNode : public SDNode {
1730   const MDNode *MD;
1731   friend class SelectionDAG;
1732   explicit MDNodeSDNode(const MDNode *md)
1733   : SDNode(ISD::MDNODE_SDNODE, 0, DebugLoc(), getSDVTList(MVT::Other)), MD(md)
1734   {}
1735 public:
1736
1737   const MDNode *getMD() const { return MD; }
1738
1739   static bool classof(const SDNode *N) {
1740     return N->getOpcode() == ISD::MDNODE_SDNODE;
1741   }
1742 };
1743
1744 class RegisterSDNode : public SDNode {
1745   unsigned Reg;
1746   friend class SelectionDAG;
1747   RegisterSDNode(unsigned reg, EVT VT)
1748     : SDNode(ISD::Register, 0, DebugLoc(), getSDVTList(VT)), Reg(reg) {
1749   }
1750 public:
1751
1752   unsigned getReg() const { return Reg; }
1753
1754   static bool classof(const SDNode *N) {
1755     return N->getOpcode() == ISD::Register;
1756   }
1757 };
1758
1759 class RegisterMaskSDNode : public SDNode {
1760   // The memory for RegMask is not owned by the node.
1761   const uint32_t *RegMask;
1762   friend class SelectionDAG;
1763   RegisterMaskSDNode(const uint32_t *mask)
1764     : SDNode(ISD::RegisterMask, 0, DebugLoc(), getSDVTList(MVT::Untyped)),
1765       RegMask(mask) {}
1766 public:
1767
1768   const uint32_t *getRegMask() const { return RegMask; }
1769
1770   static bool classof(const SDNode *N) {
1771     return N->getOpcode() == ISD::RegisterMask;
1772   }
1773 };
1774
1775 class BlockAddressSDNode : public SDNode {
1776   const BlockAddress *BA;
1777   int64_t Offset;
1778   unsigned char TargetFlags;
1779   friend class SelectionDAG;
1780   BlockAddressSDNode(unsigned NodeTy, EVT VT, const BlockAddress *ba,
1781                      int64_t o, unsigned char Flags)
1782     : SDNode(NodeTy, 0, DebugLoc(), getSDVTList(VT)),
1783              BA(ba), Offset(o), TargetFlags(Flags) {
1784   }
1785 public:
1786   const BlockAddress *getBlockAddress() const { return BA; }
1787   int64_t getOffset() const { return Offset; }
1788   unsigned char getTargetFlags() const { return TargetFlags; }
1789
1790   static bool classof(const SDNode *N) {
1791     return N->getOpcode() == ISD::BlockAddress ||
1792            N->getOpcode() == ISD::TargetBlockAddress;
1793   }
1794 };
1795
1796 class EHLabelSDNode : public SDNode {
1797   SDUse Chain;
1798   MCSymbol *Label;
1799   friend class SelectionDAG;
1800   EHLabelSDNode(unsigned Order, DebugLoc dl, SDValue ch, MCSymbol *L)
1801     : SDNode(ISD::EH_LABEL, Order, dl, getSDVTList(MVT::Other)), Label(L) {
1802     InitOperands(&Chain, ch);
1803   }
1804 public:
1805   MCSymbol *getLabel() const { return Label; }
1806
1807   static bool classof(const SDNode *N) {
1808     return N->getOpcode() == ISD::EH_LABEL;
1809   }
1810 };
1811
1812 class ExternalSymbolSDNode : public SDNode {
1813   const char *Symbol;
1814   unsigned char TargetFlags;
1815
1816   friend class SelectionDAG;
1817   ExternalSymbolSDNode(bool isTarget, const char *Sym, unsigned char TF, EVT VT)
1818     : SDNode(isTarget ? ISD::TargetExternalSymbol : ISD::ExternalSymbol,
1819              0, DebugLoc(), getSDVTList(VT)), Symbol(Sym), TargetFlags(TF) {
1820   }
1821 public:
1822
1823   const char *getSymbol() const { return Symbol; }
1824   unsigned char getTargetFlags() const { return TargetFlags; }
1825
1826   static bool classof(const SDNode *N) {
1827     return N->getOpcode() == ISD::ExternalSymbol ||
1828            N->getOpcode() == ISD::TargetExternalSymbol;
1829   }
1830 };
1831
1832 class MCSymbolSDNode : public SDNode {
1833   MCSymbol *Symbol;
1834
1835   friend class SelectionDAG;
1836   MCSymbolSDNode(MCSymbol *Symbol, EVT VT)
1837       : SDNode(ISD::MCSymbol, 0, DebugLoc(), getSDVTList(VT)), Symbol(Symbol) {}
1838
1839 public:
1840   MCSymbol *getMCSymbol() const { return Symbol; }
1841
1842   static bool classof(const SDNode *N) {
1843     return N->getOpcode() == ISD::MCSymbol;
1844   }
1845 };
1846
1847 class CondCodeSDNode : public SDNode {
1848   ISD::CondCode Condition;
1849   friend class SelectionDAG;
1850   explicit CondCodeSDNode(ISD::CondCode Cond)
1851     : SDNode(ISD::CONDCODE, 0, DebugLoc(), getSDVTList(MVT::Other)),
1852       Condition(Cond) {
1853   }
1854 public:
1855
1856   ISD::CondCode get() const { return Condition; }
1857
1858   static bool classof(const SDNode *N) {
1859     return N->getOpcode() == ISD::CONDCODE;
1860   }
1861 };
1862
1863 /// NOTE: avoid using this node as this may disappear in the
1864 /// future and most targets don't support it.
1865 class CvtRndSatSDNode : public SDNode {
1866   ISD::CvtCode CvtCode;
1867   friend class SelectionDAG;
1868   explicit CvtRndSatSDNode(EVT VT, unsigned Order, DebugLoc dl,
1869                            ArrayRef<SDValue> Ops, ISD::CvtCode Code)
1870     : SDNode(ISD::CONVERT_RNDSAT, Order, dl, getSDVTList(VT), Ops),
1871       CvtCode(Code) {
1872     assert(Ops.size() == 5 && "wrong number of operations");
1873   }
1874 public:
1875   ISD::CvtCode getCvtCode() const { return CvtCode; }
1876
1877   static bool classof(const SDNode *N) {
1878     return N->getOpcode() == ISD::CONVERT_RNDSAT;
1879   }
1880 };
1881
1882 /// This class is used to represent EVT's, which are used
1883 /// to parameterize some operations.
1884 class VTSDNode : public SDNode {
1885   EVT ValueType;
1886   friend class SelectionDAG;
1887   explicit VTSDNode(EVT VT)
1888     : SDNode(ISD::VALUETYPE, 0, DebugLoc(), getSDVTList(MVT::Other)),
1889       ValueType(VT) {
1890   }
1891 public:
1892
1893   EVT getVT() const { return ValueType; }
1894
1895   static bool classof(const SDNode *N) {
1896     return N->getOpcode() == ISD::VALUETYPE;
1897   }
1898 };
1899
1900 /// Base class for LoadSDNode and StoreSDNode
1901 class LSBaseSDNode : public MemSDNode {
1902   //! Operand array for load and store
1903   /*!
1904     \note Moving this array to the base class captures more
1905     common functionality shared between LoadSDNode and
1906     StoreSDNode
1907    */
1908   SDUse Ops[4];
1909 public:
1910   LSBaseSDNode(ISD::NodeType NodeTy, unsigned Order, DebugLoc dl,
1911                SDValue *Operands, unsigned numOperands,
1912                SDVTList VTs, ISD::MemIndexedMode AM, EVT MemVT,
1913                MachineMemOperand *MMO)
1914     : MemSDNode(NodeTy, Order, dl, VTs, MemVT, MMO) {
1915     SubclassData |= AM << 2;
1916     assert(getAddressingMode() == AM && "MemIndexedMode encoding error!");
1917     InitOperands(Ops, Operands, numOperands);
1918     assert((getOffset().getOpcode() == ISD::UNDEF || isIndexed()) &&
1919            "Only indexed loads and stores have a non-undef offset operand");
1920   }
1921
1922   const SDValue &getOffset() const {
1923     return getOperand(getOpcode() == ISD::LOAD ? 2 : 3);
1924   }
1925
1926   /// Return the addressing mode for this load or store:
1927   /// unindexed, pre-inc, pre-dec, post-inc, or post-dec.
1928   ISD::MemIndexedMode getAddressingMode() const {
1929     return ISD::MemIndexedMode((SubclassData >> 2) & 7);
1930   }
1931
1932   /// Return true if this is a pre/post inc/dec load/store.
1933   bool isIndexed() const { return getAddressingMode() != ISD::UNINDEXED; }
1934
1935   /// Return true if this is NOT a pre/post inc/dec load/store.
1936   bool isUnindexed() const { return getAddressingMode() == ISD::UNINDEXED; }
1937
1938   static bool classof(const SDNode *N) {
1939     return N->getOpcode() == ISD::LOAD ||
1940            N->getOpcode() == ISD::STORE;
1941   }
1942 };
1943
1944 /// This class is used to represent ISD::LOAD nodes.
1945 class LoadSDNode : public LSBaseSDNode {
1946   friend class SelectionDAG;
1947   LoadSDNode(SDValue *ChainPtrOff, unsigned Order, DebugLoc dl, SDVTList VTs,
1948              ISD::MemIndexedMode AM, ISD::LoadExtType ETy, EVT MemVT,
1949              MachineMemOperand *MMO)
1950     : LSBaseSDNode(ISD::LOAD, Order, dl, ChainPtrOff, 3, VTs, AM, MemVT, MMO) {
1951     SubclassData |= (unsigned short)ETy;
1952     assert(getExtensionType() == ETy && "LoadExtType encoding error!");
1953     assert(readMem() && "Load MachineMemOperand is not a load!");
1954     assert(!writeMem() && "Load MachineMemOperand is a store!");
1955   }
1956 public:
1957
1958   /// Return whether this is a plain node,
1959   /// or one of the varieties of value-extending loads.
1960   ISD::LoadExtType getExtensionType() const {
1961     return ISD::LoadExtType(SubclassData & 3);
1962   }
1963
1964   const SDValue &getBasePtr() const { return getOperand(1); }
1965   const SDValue &getOffset() const { return getOperand(2); }
1966
1967   static bool classof(const SDNode *N) {
1968     return N->getOpcode() == ISD::LOAD;
1969   }
1970 };
1971
1972 /// This class is used to represent ISD::STORE nodes.
1973 class StoreSDNode : public LSBaseSDNode {
1974   friend class SelectionDAG;
1975   StoreSDNode(SDValue *ChainValuePtrOff, unsigned Order, DebugLoc dl,
1976               SDVTList VTs, ISD::MemIndexedMode AM, bool isTrunc, EVT MemVT,
1977               MachineMemOperand *MMO)
1978     : LSBaseSDNode(ISD::STORE, Order, dl, ChainValuePtrOff, 4,
1979                    VTs, AM, MemVT, MMO) {
1980     SubclassData |= (unsigned short)isTrunc;
1981     assert(isTruncatingStore() == isTrunc && "isTrunc encoding error!");
1982     assert(!readMem() && "Store MachineMemOperand is a load!");
1983     assert(writeMem() && "Store MachineMemOperand is not a store!");
1984   }
1985 public:
1986
1987   /// Return true if the op does a truncation before store.
1988   /// For integers this is the same as doing a TRUNCATE and storing the result.
1989   /// For floats, it is the same as doing an FP_ROUND and storing the result.
1990   bool isTruncatingStore() const { return SubclassData & 1; }
1991
1992   const SDValue &getValue() const { return getOperand(1); }
1993   const SDValue &getBasePtr() const { return getOperand(2); }
1994   const SDValue &getOffset() const { return getOperand(3); }
1995
1996   static bool classof(const SDNode *N) {
1997     return N->getOpcode() == ISD::STORE;
1998   }
1999 };
2000
2001 /// This base class is used to represent MLOAD and MSTORE nodes
2002 class MaskedLoadStoreSDNode : public MemSDNode {
2003   // Operands
2004   SDUse Ops[4];
2005 public:
2006   friend class SelectionDAG;
2007   MaskedLoadStoreSDNode(ISD::NodeType NodeTy, unsigned Order, DebugLoc dl,
2008                         SDValue *Operands, unsigned numOperands, SDVTList VTs,
2009                         EVT MemVT, MachineMemOperand *MMO)
2010       : MemSDNode(NodeTy, Order, dl, VTs, MemVT, MMO) {
2011     InitOperands(Ops, Operands, numOperands);
2012   }
2013
2014   // In the both nodes address is Op1, mask is Op2:
2015   // MaskedLoadSDNode (Chain, ptr, mask, src0), src0 is a passthru value
2016   // MaskedStoreSDNode (Chain, ptr, mask, data)
2017   // Mask is a vector of i1 elements
2018   const SDValue &getBasePtr() const { return getOperand(1); }
2019   const SDValue &getMask() const    { return getOperand(2); }
2020
2021   static bool classof(const SDNode *N) {
2022     return N->getOpcode() == ISD::MLOAD ||
2023            N->getOpcode() == ISD::MSTORE;
2024   }
2025 };
2026
2027 /// This class is used to represent an MLOAD node
2028 class MaskedLoadSDNode : public MaskedLoadStoreSDNode {
2029 public:
2030   friend class SelectionDAG;
2031   MaskedLoadSDNode(unsigned Order, DebugLoc dl, SDValue *Operands,
2032                    unsigned numOperands, SDVTList VTs, ISD::LoadExtType ETy,
2033                    EVT MemVT, MachineMemOperand *MMO)
2034     : MaskedLoadStoreSDNode(ISD::MLOAD, Order, dl, Operands, numOperands,
2035                             VTs, MemVT, MMO) {
2036     SubclassData |= (unsigned short)ETy;
2037   }
2038
2039   ISD::LoadExtType getExtensionType() const {
2040     return ISD::LoadExtType(SubclassData & 3);
2041   }
2042   const SDValue &getSrc0() const { return getOperand(3); }
2043   static bool classof(const SDNode *N) {
2044     return N->getOpcode() == ISD::MLOAD;
2045   }
2046 };
2047
2048 /// This class is used to represent an MSTORE node
2049 class MaskedStoreSDNode : public MaskedLoadStoreSDNode {
2050
2051 public:
2052   friend class SelectionDAG;
2053   MaskedStoreSDNode(unsigned Order, DebugLoc dl, SDValue *Operands,
2054                     unsigned numOperands, SDVTList VTs, bool isTrunc, EVT MemVT,
2055                     MachineMemOperand *MMO)
2056     : MaskedLoadStoreSDNode(ISD::MSTORE, Order, dl, Operands, numOperands,
2057                             VTs, MemVT, MMO) {
2058       SubclassData |= (unsigned short)isTrunc;
2059   }
2060   /// Return true if the op does a truncation before store.
2061   /// For integers this is the same as doing a TRUNCATE and storing the result.
2062   /// For floats, it is the same as doing an FP_ROUND and storing the result.
2063   bool isTruncatingStore() const { return SubclassData & 1; }
2064
2065   const SDValue &getValue() const { return getOperand(3); }
2066
2067   static bool classof(const SDNode *N) {
2068     return N->getOpcode() == ISD::MSTORE;
2069   }
2070 };
2071
2072 /// This is a base class used to represent
2073 /// MGATHER and MSCATTER nodes
2074 ///
2075 class MaskedGatherScatterSDNode : public MemSDNode {
2076   // Operands
2077   SDUse Ops[5];
2078 public:
2079   friend class SelectionDAG;
2080   MaskedGatherScatterSDNode(ISD::NodeType NodeTy, unsigned Order, DebugLoc dl,
2081                             ArrayRef<SDValue> Operands, SDVTList VTs, EVT MemVT,
2082                             MachineMemOperand *MMO)
2083     : MemSDNode(NodeTy, Order, dl, VTs, MemVT, MMO) {
2084     assert(Operands.size() == 5 && "Incompatible number of operands");
2085     InitOperands(Ops, Operands.data(), Operands.size());
2086   }
2087
2088   // In the both nodes address is Op1, mask is Op2:
2089   // MaskedGatherSDNode  (Chain, src0, mask, base, index), src0 is a passthru value
2090   // MaskedScatterSDNode (Chain, value, mask, base, index)
2091   // Mask is a vector of i1 elements
2092   const SDValue &getBasePtr() const { return getOperand(3); }
2093   const SDValue &getIndex()   const { return getOperand(4); }
2094   const SDValue &getMask()    const { return getOperand(2); }
2095   const SDValue &getValue()   const { return getOperand(1); }
2096
2097   static bool classof(const SDNode *N) {
2098     return N->getOpcode() == ISD::MGATHER ||
2099            N->getOpcode() == ISD::MSCATTER;
2100   }
2101 };
2102
2103 /// This class is used to represent an MGATHER node
2104 ///
2105 class MaskedGatherSDNode : public MaskedGatherScatterSDNode {
2106 public:
2107   friend class SelectionDAG;
2108   MaskedGatherSDNode(unsigned Order, DebugLoc dl, ArrayRef<SDValue> Operands,
2109                      SDVTList VTs, EVT MemVT, MachineMemOperand *MMO)
2110     : MaskedGatherScatterSDNode(ISD::MGATHER, Order, dl, Operands, VTs, MemVT,
2111                                 MMO) {
2112     assert(getValue().getValueType() == getValueType(0) &&
2113            "Incompatible type of the PathThru value in MaskedGatherSDNode");
2114     assert(getMask().getValueType().getVectorNumElements() ==
2115                getValueType(0).getVectorNumElements() &&
2116            "Vector width mismatch between mask and data");
2117     assert(getMask().getValueType().getScalarType() == MVT::i1 &&
2118            "Vector width mismatch between mask and data");
2119   }
2120
2121   static bool classof(const SDNode *N) {
2122     return N->getOpcode() == ISD::MGATHER;
2123   }
2124 };
2125
2126 /// This class is used to represent an MSCATTER node
2127 ///
2128 class MaskedScatterSDNode : public MaskedGatherScatterSDNode {
2129
2130 public:
2131   friend class SelectionDAG;
2132   MaskedScatterSDNode(unsigned Order, DebugLoc dl,ArrayRef<SDValue> Operands,
2133                       SDVTList VTs, EVT MemVT, MachineMemOperand *MMO)
2134       : MaskedGatherScatterSDNode(ISD::MSCATTER, Order, dl, Operands, VTs,
2135                                   MemVT, MMO) {
2136     assert(getMask().getValueType().getVectorNumElements() ==
2137                getValue().getValueType().getVectorNumElements() &&
2138            "Vector width mismatch between mask and data");
2139     assert(getMask().getValueType().getScalarType() == MVT::i1 &&
2140            "Vector width mismatch between mask and data");
2141   }
2142
2143   static bool classof(const SDNode *N) {
2144     return N->getOpcode() == ISD::MSCATTER;
2145   }
2146 };
2147
2148 /// An SDNode that represents everything that will be needed
2149 /// to construct a MachineInstr. These nodes are created during the
2150 /// instruction selection proper phase.
2151 class MachineSDNode : public SDNode {
2152 public:
2153   typedef MachineMemOperand **mmo_iterator;
2154
2155 private:
2156   friend class SelectionDAG;
2157   MachineSDNode(unsigned Opc, unsigned Order, const DebugLoc DL, SDVTList VTs)
2158     : SDNode(Opc, Order, DL, VTs), MemRefs(nullptr), MemRefsEnd(nullptr) {}
2159
2160   /// Operands for this instruction, if they fit here. If
2161   /// they don't, this field is unused.
2162   SDUse LocalOperands[4];
2163
2164   /// Memory reference descriptions for this instruction.
2165   mmo_iterator MemRefs;
2166   mmo_iterator MemRefsEnd;
2167
2168 public:
2169   mmo_iterator memoperands_begin() const { return MemRefs; }
2170   mmo_iterator memoperands_end() const { return MemRefsEnd; }
2171   bool memoperands_empty() const { return MemRefsEnd == MemRefs; }
2172
2173   /// Assign this MachineSDNodes's memory reference descriptor
2174   /// list. This does not transfer ownership.
2175   void setMemRefs(mmo_iterator NewMemRefs, mmo_iterator NewMemRefsEnd) {
2176     for (mmo_iterator MMI = NewMemRefs, MME = NewMemRefsEnd; MMI != MME; ++MMI)
2177       assert(*MMI && "Null mem ref detected!");
2178     MemRefs = NewMemRefs;
2179     MemRefsEnd = NewMemRefsEnd;
2180   }
2181
2182   static bool classof(const SDNode *N) {
2183     return N->isMachineOpcode();
2184   }
2185 };
2186
2187 class SDNodeIterator : public std::iterator<std::forward_iterator_tag,
2188                                             SDNode, ptrdiff_t> {
2189   const SDNode *Node;
2190   unsigned Operand;
2191
2192   SDNodeIterator(const SDNode *N, unsigned Op) : Node(N), Operand(Op) {}
2193 public:
2194   bool operator==(const SDNodeIterator& x) const {
2195     return Operand == x.Operand;
2196   }
2197   bool operator!=(const SDNodeIterator& x) const { return !operator==(x); }
2198
2199   pointer operator*() const {
2200     return Node->getOperand(Operand).getNode();
2201   }
2202   pointer operator->() const { return operator*(); }
2203
2204   SDNodeIterator& operator++() {                // Preincrement
2205     ++Operand;
2206     return *this;
2207   }
2208   SDNodeIterator operator++(int) { // Postincrement
2209     SDNodeIterator tmp = *this; ++*this; return tmp;
2210   }
2211   size_t operator-(SDNodeIterator Other) const {
2212     assert(Node == Other.Node &&
2213            "Cannot compare iterators of two different nodes!");
2214     return Operand - Other.Operand;
2215   }
2216
2217   static SDNodeIterator begin(const SDNode *N) { return SDNodeIterator(N, 0); }
2218   static SDNodeIterator end  (const SDNode *N) {
2219     return SDNodeIterator(N, N->getNumOperands());
2220   }
2221
2222   unsigned getOperand() const { return Operand; }
2223   const SDNode *getNode() const { return Node; }
2224 };
2225
2226 template <> struct GraphTraits<SDNode*> {
2227   typedef SDNode NodeType;
2228   typedef SDNodeIterator ChildIteratorType;
2229   static inline NodeType *getEntryNode(SDNode *N) { return N; }
2230   static inline ChildIteratorType child_begin(NodeType *N) {
2231     return SDNodeIterator::begin(N);
2232   }
2233   static inline ChildIteratorType child_end(NodeType *N) {
2234     return SDNodeIterator::end(N);
2235   }
2236 };
2237
2238 /// The largest SDNode class.
2239 typedef MaskedGatherScatterSDNode LargestSDNode;
2240
2241 /// The SDNode class with the greatest alignment requirement.
2242 typedef GlobalAddressSDNode MostAlignedSDNode;
2243
2244 namespace ISD {
2245   /// Returns true if the specified node is a non-extending and unindexed load.
2246   inline bool isNormalLoad(const SDNode *N) {
2247     const LoadSDNode *Ld = dyn_cast<LoadSDNode>(N);
2248     return Ld && Ld->getExtensionType() == ISD::NON_EXTLOAD &&
2249       Ld->getAddressingMode() == ISD::UNINDEXED;
2250   }
2251
2252   /// Returns true if the specified node is a non-extending load.
2253   inline bool isNON_EXTLoad(const SDNode *N) {
2254     return isa<LoadSDNode>(N) &&
2255       cast<LoadSDNode>(N)->getExtensionType() == ISD::NON_EXTLOAD;
2256   }
2257
2258   /// Returns true if the specified node is a EXTLOAD.
2259   inline bool isEXTLoad(const SDNode *N) {
2260     return isa<LoadSDNode>(N) &&
2261       cast<LoadSDNode>(N)->getExtensionType() == ISD::EXTLOAD;
2262   }
2263
2264   /// Returns true if the specified node is a SEXTLOAD.
2265   inline bool isSEXTLoad(const SDNode *N) {
2266     return isa<LoadSDNode>(N) &&
2267       cast<LoadSDNode>(N)->getExtensionType() == ISD::SEXTLOAD;
2268   }
2269
2270   /// Returns true if the specified node is a ZEXTLOAD.
2271   inline bool isZEXTLoad(const SDNode *N) {
2272     return isa<LoadSDNode>(N) &&
2273       cast<LoadSDNode>(N)->getExtensionType() == ISD::ZEXTLOAD;
2274   }
2275
2276   /// Returns true if the specified node is an unindexed load.
2277   inline bool isUNINDEXEDLoad(const SDNode *N) {
2278     return isa<LoadSDNode>(N) &&
2279       cast<LoadSDNode>(N)->getAddressingMode() == ISD::UNINDEXED;
2280   }
2281
2282   /// Returns true if the specified node is a non-truncating
2283   /// and unindexed store.
2284   inline bool isNormalStore(const SDNode *N) {
2285     const StoreSDNode *St = dyn_cast<StoreSDNode>(N);
2286     return St && !St->isTruncatingStore() &&
2287       St->getAddressingMode() == ISD::UNINDEXED;
2288   }
2289
2290   /// Returns true if the specified node is a non-truncating store.
2291   inline bool isNON_TRUNCStore(const SDNode *N) {
2292     return isa<StoreSDNode>(N) && !cast<StoreSDNode>(N)->isTruncatingStore();
2293   }
2294
2295   /// Returns true if the specified node is a truncating store.
2296   inline bool isTRUNCStore(const SDNode *N) {
2297     return isa<StoreSDNode>(N) && cast<StoreSDNode>(N)->isTruncatingStore();
2298   }
2299
2300   /// Returns true if the specified node is an unindexed store.
2301   inline bool isUNINDEXEDStore(const SDNode *N) {
2302     return isa<StoreSDNode>(N) &&
2303       cast<StoreSDNode>(N)->getAddressingMode() == ISD::UNINDEXED;
2304   }
2305 }
2306
2307 } // end llvm namespace
2308
2309 #endif