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