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