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