[ARM] Promote helper function to SelectionDAG.
[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   /// \brief If this is a constant FP splat and the splatted constant FP is an
1718   /// exact power or 2, return the log base 2 integer value.  Otherwise,
1719   /// return -1.
1720   ///
1721   /// The BitWidth specifies the necessary bit precision.
1722   int32_t getConstantFPSplatPow2ToLog2Int(BitVector *UndefElements,
1723                                           uint32_t BitWidth) const;
1724
1725   bool isConstant() const;
1726
1727   static inline bool classof(const SDNode *N) {
1728     return N->getOpcode() == ISD::BUILD_VECTOR;
1729   }
1730 };
1731
1732 /// An SDNode that holds an arbitrary LLVM IR Value. This is
1733 /// used when the SelectionDAG needs to make a simple reference to something
1734 /// in the LLVM IR representation.
1735 ///
1736 class SrcValueSDNode : public SDNode {
1737   const Value *V;
1738   friend class SelectionDAG;
1739   /// Create a SrcValue for a general value.
1740   explicit SrcValueSDNode(const Value *v)
1741     : SDNode(ISD::SRCVALUE, 0, DebugLoc(), getSDVTList(MVT::Other)), V(v) {}
1742
1743 public:
1744   /// Return the contained Value.
1745   const Value *getValue() const { return V; }
1746
1747   static bool classof(const SDNode *N) {
1748     return N->getOpcode() == ISD::SRCVALUE;
1749   }
1750 };
1751
1752 class MDNodeSDNode : public SDNode {
1753   const MDNode *MD;
1754   friend class SelectionDAG;
1755   explicit MDNodeSDNode(const MDNode *md)
1756   : SDNode(ISD::MDNODE_SDNODE, 0, DebugLoc(), getSDVTList(MVT::Other)), MD(md)
1757   {}
1758 public:
1759
1760   const MDNode *getMD() const { return MD; }
1761
1762   static bool classof(const SDNode *N) {
1763     return N->getOpcode() == ISD::MDNODE_SDNODE;
1764   }
1765 };
1766
1767 class RegisterSDNode : public SDNode {
1768   unsigned Reg;
1769   friend class SelectionDAG;
1770   RegisterSDNode(unsigned reg, EVT VT)
1771     : SDNode(ISD::Register, 0, DebugLoc(), getSDVTList(VT)), Reg(reg) {
1772   }
1773 public:
1774
1775   unsigned getReg() const { return Reg; }
1776
1777   static bool classof(const SDNode *N) {
1778     return N->getOpcode() == ISD::Register;
1779   }
1780 };
1781
1782 class RegisterMaskSDNode : public SDNode {
1783   // The memory for RegMask is not owned by the node.
1784   const uint32_t *RegMask;
1785   friend class SelectionDAG;
1786   RegisterMaskSDNode(const uint32_t *mask)
1787     : SDNode(ISD::RegisterMask, 0, DebugLoc(), getSDVTList(MVT::Untyped)),
1788       RegMask(mask) {}
1789 public:
1790
1791   const uint32_t *getRegMask() const { return RegMask; }
1792
1793   static bool classof(const SDNode *N) {
1794     return N->getOpcode() == ISD::RegisterMask;
1795   }
1796 };
1797
1798 class BlockAddressSDNode : public SDNode {
1799   const BlockAddress *BA;
1800   int64_t Offset;
1801   unsigned char TargetFlags;
1802   friend class SelectionDAG;
1803   BlockAddressSDNode(unsigned NodeTy, EVT VT, const BlockAddress *ba,
1804                      int64_t o, unsigned char Flags)
1805     : SDNode(NodeTy, 0, DebugLoc(), getSDVTList(VT)),
1806              BA(ba), Offset(o), TargetFlags(Flags) {
1807   }
1808 public:
1809   const BlockAddress *getBlockAddress() const { return BA; }
1810   int64_t getOffset() const { return Offset; }
1811   unsigned char getTargetFlags() const { return TargetFlags; }
1812
1813   static bool classof(const SDNode *N) {
1814     return N->getOpcode() == ISD::BlockAddress ||
1815            N->getOpcode() == ISD::TargetBlockAddress;
1816   }
1817 };
1818
1819 class EHLabelSDNode : public SDNode {
1820   SDUse Chain;
1821   MCSymbol *Label;
1822   friend class SelectionDAG;
1823   EHLabelSDNode(unsigned Order, DebugLoc dl, SDValue ch, MCSymbol *L)
1824     : SDNode(ISD::EH_LABEL, Order, dl, getSDVTList(MVT::Other)), Label(L) {
1825     InitOperands(&Chain, ch);
1826   }
1827 public:
1828   MCSymbol *getLabel() const { return Label; }
1829
1830   static bool classof(const SDNode *N) {
1831     return N->getOpcode() == ISD::EH_LABEL;
1832   }
1833 };
1834
1835 class ExternalSymbolSDNode : public SDNode {
1836   const char *Symbol;
1837   unsigned char TargetFlags;
1838
1839   friend class SelectionDAG;
1840   ExternalSymbolSDNode(bool isTarget, const char *Sym, unsigned char TF, EVT VT)
1841     : SDNode(isTarget ? ISD::TargetExternalSymbol : ISD::ExternalSymbol,
1842              0, DebugLoc(), getSDVTList(VT)), Symbol(Sym), TargetFlags(TF) {
1843   }
1844 public:
1845
1846   const char *getSymbol() const { return Symbol; }
1847   unsigned char getTargetFlags() const { return TargetFlags; }
1848
1849   static bool classof(const SDNode *N) {
1850     return N->getOpcode() == ISD::ExternalSymbol ||
1851            N->getOpcode() == ISD::TargetExternalSymbol;
1852   }
1853 };
1854
1855 class MCSymbolSDNode : public SDNode {
1856   MCSymbol *Symbol;
1857
1858   friend class SelectionDAG;
1859   MCSymbolSDNode(MCSymbol *Symbol, EVT VT)
1860       : SDNode(ISD::MCSymbol, 0, DebugLoc(), getSDVTList(VT)), Symbol(Symbol) {}
1861
1862 public:
1863   MCSymbol *getMCSymbol() const { return Symbol; }
1864
1865   static bool classof(const SDNode *N) {
1866     return N->getOpcode() == ISD::MCSymbol;
1867   }
1868 };
1869
1870 class CondCodeSDNode : public SDNode {
1871   ISD::CondCode Condition;
1872   friend class SelectionDAG;
1873   explicit CondCodeSDNode(ISD::CondCode Cond)
1874     : SDNode(ISD::CONDCODE, 0, DebugLoc(), getSDVTList(MVT::Other)),
1875       Condition(Cond) {
1876   }
1877 public:
1878
1879   ISD::CondCode get() const { return Condition; }
1880
1881   static bool classof(const SDNode *N) {
1882     return N->getOpcode() == ISD::CONDCODE;
1883   }
1884 };
1885
1886 /// NOTE: avoid using this node as this may disappear in the
1887 /// future and most targets don't support it.
1888 class CvtRndSatSDNode : public SDNode {
1889   ISD::CvtCode CvtCode;
1890   friend class SelectionDAG;
1891   explicit CvtRndSatSDNode(EVT VT, unsigned Order, DebugLoc dl,
1892                            ArrayRef<SDValue> Ops, ISD::CvtCode Code)
1893     : SDNode(ISD::CONVERT_RNDSAT, Order, dl, getSDVTList(VT), Ops),
1894       CvtCode(Code) {
1895     assert(Ops.size() == 5 && "wrong number of operations");
1896   }
1897 public:
1898   ISD::CvtCode getCvtCode() const { return CvtCode; }
1899
1900   static bool classof(const SDNode *N) {
1901     return N->getOpcode() == ISD::CONVERT_RNDSAT;
1902   }
1903 };
1904
1905 /// This class is used to represent EVT's, which are used
1906 /// to parameterize some operations.
1907 class VTSDNode : public SDNode {
1908   EVT ValueType;
1909   friend class SelectionDAG;
1910   explicit VTSDNode(EVT VT)
1911     : SDNode(ISD::VALUETYPE, 0, DebugLoc(), getSDVTList(MVT::Other)),
1912       ValueType(VT) {
1913   }
1914 public:
1915
1916   EVT getVT() const { return ValueType; }
1917
1918   static bool classof(const SDNode *N) {
1919     return N->getOpcode() == ISD::VALUETYPE;
1920   }
1921 };
1922
1923 /// Base class for LoadSDNode and StoreSDNode
1924 class LSBaseSDNode : public MemSDNode {
1925   //! Operand array for load and store
1926   /*!
1927     \note Moving this array to the base class captures more
1928     common functionality shared between LoadSDNode and
1929     StoreSDNode
1930    */
1931   SDUse Ops[4];
1932 public:
1933   LSBaseSDNode(ISD::NodeType NodeTy, unsigned Order, DebugLoc dl,
1934                SDValue *Operands, unsigned numOperands,
1935                SDVTList VTs, ISD::MemIndexedMode AM, EVT MemVT,
1936                MachineMemOperand *MMO)
1937     : MemSDNode(NodeTy, Order, dl, VTs, MemVT, MMO) {
1938     SubclassData |= AM << 2;
1939     assert(getAddressingMode() == AM && "MemIndexedMode encoding error!");
1940     InitOperands(Ops, Operands, numOperands);
1941     assert((getOffset().getOpcode() == ISD::UNDEF || isIndexed()) &&
1942            "Only indexed loads and stores have a non-undef offset operand");
1943   }
1944
1945   const SDValue &getOffset() const {
1946     return getOperand(getOpcode() == ISD::LOAD ? 2 : 3);
1947   }
1948
1949   /// Return the addressing mode for this load or store:
1950   /// unindexed, pre-inc, pre-dec, post-inc, or post-dec.
1951   ISD::MemIndexedMode getAddressingMode() const {
1952     return ISD::MemIndexedMode((SubclassData >> 2) & 7);
1953   }
1954
1955   /// Return true if this is a pre/post inc/dec load/store.
1956   bool isIndexed() const { return getAddressingMode() != ISD::UNINDEXED; }
1957
1958   /// Return true if this is NOT a pre/post inc/dec load/store.
1959   bool isUnindexed() const { return getAddressingMode() == ISD::UNINDEXED; }
1960
1961   static bool classof(const SDNode *N) {
1962     return N->getOpcode() == ISD::LOAD ||
1963            N->getOpcode() == ISD::STORE;
1964   }
1965 };
1966
1967 /// This class is used to represent ISD::LOAD nodes.
1968 class LoadSDNode : public LSBaseSDNode {
1969   friend class SelectionDAG;
1970   LoadSDNode(SDValue *ChainPtrOff, unsigned Order, DebugLoc dl, SDVTList VTs,
1971              ISD::MemIndexedMode AM, ISD::LoadExtType ETy, EVT MemVT,
1972              MachineMemOperand *MMO)
1973     : LSBaseSDNode(ISD::LOAD, Order, dl, ChainPtrOff, 3, VTs, AM, MemVT, MMO) {
1974     SubclassData |= (unsigned short)ETy;
1975     assert(getExtensionType() == ETy && "LoadExtType encoding error!");
1976     assert(readMem() && "Load MachineMemOperand is not a load!");
1977     assert(!writeMem() && "Load MachineMemOperand is a store!");
1978   }
1979 public:
1980
1981   /// Return whether this is a plain node,
1982   /// or one of the varieties of value-extending loads.
1983   ISD::LoadExtType getExtensionType() const {
1984     return ISD::LoadExtType(SubclassData & 3);
1985   }
1986
1987   const SDValue &getBasePtr() const { return getOperand(1); }
1988   const SDValue &getOffset() const { return getOperand(2); }
1989
1990   static bool classof(const SDNode *N) {
1991     return N->getOpcode() == ISD::LOAD;
1992   }
1993 };
1994
1995 /// This class is used to represent ISD::STORE nodes.
1996 class StoreSDNode : public LSBaseSDNode {
1997   friend class SelectionDAG;
1998   StoreSDNode(SDValue *ChainValuePtrOff, unsigned Order, DebugLoc dl,
1999               SDVTList VTs, ISD::MemIndexedMode AM, bool isTrunc, EVT MemVT,
2000               MachineMemOperand *MMO)
2001     : LSBaseSDNode(ISD::STORE, Order, dl, ChainValuePtrOff, 4,
2002                    VTs, AM, MemVT, MMO) {
2003     SubclassData |= (unsigned short)isTrunc;
2004     assert(isTruncatingStore() == isTrunc && "isTrunc encoding error!");
2005     assert(!readMem() && "Store MachineMemOperand is a load!");
2006     assert(writeMem() && "Store MachineMemOperand is not a store!");
2007   }
2008 public:
2009
2010   /// Return true if the op does a truncation before store.
2011   /// For integers this is the same as doing a TRUNCATE and storing the result.
2012   /// For floats, it is the same as doing an FP_ROUND and storing the result.
2013   bool isTruncatingStore() const { return SubclassData & 1; }
2014
2015   const SDValue &getValue() const { return getOperand(1); }
2016   const SDValue &getBasePtr() const { return getOperand(2); }
2017   const SDValue &getOffset() const { return getOperand(3); }
2018
2019   static bool classof(const SDNode *N) {
2020     return N->getOpcode() == ISD::STORE;
2021   }
2022 };
2023
2024 /// This base class is used to represent MLOAD and MSTORE nodes
2025 class MaskedLoadStoreSDNode : public MemSDNode {
2026   // Operands
2027   SDUse Ops[4];
2028 public:
2029   friend class SelectionDAG;
2030   MaskedLoadStoreSDNode(ISD::NodeType NodeTy, unsigned Order, DebugLoc dl,
2031                         SDValue *Operands, unsigned numOperands, SDVTList VTs,
2032                         EVT MemVT, MachineMemOperand *MMO)
2033       : MemSDNode(NodeTy, Order, dl, VTs, MemVT, MMO) {
2034     InitOperands(Ops, Operands, numOperands);
2035   }
2036
2037   // In the both nodes address is Op1, mask is Op2:
2038   // MaskedLoadSDNode (Chain, ptr, mask, src0), src0 is a passthru value
2039   // MaskedStoreSDNode (Chain, ptr, mask, data)
2040   // Mask is a vector of i1 elements
2041   const SDValue &getBasePtr() const { return getOperand(1); }
2042   const SDValue &getMask() const    { return getOperand(2); }
2043
2044   static bool classof(const SDNode *N) {
2045     return N->getOpcode() == ISD::MLOAD ||
2046            N->getOpcode() == ISD::MSTORE;
2047   }
2048 };
2049
2050 /// This class is used to represent an MLOAD node
2051 class MaskedLoadSDNode : public MaskedLoadStoreSDNode {
2052 public:
2053   friend class SelectionDAG;
2054   MaskedLoadSDNode(unsigned Order, DebugLoc dl, SDValue *Operands,
2055                    unsigned numOperands, SDVTList VTs, ISD::LoadExtType ETy,
2056                    EVT MemVT, MachineMemOperand *MMO)
2057     : MaskedLoadStoreSDNode(ISD::MLOAD, Order, dl, Operands, numOperands,
2058                             VTs, MemVT, MMO) {
2059     SubclassData |= (unsigned short)ETy;
2060   }
2061
2062   ISD::LoadExtType getExtensionType() const {
2063     return ISD::LoadExtType(SubclassData & 3);
2064   }
2065   const SDValue &getSrc0() const { return getOperand(3); }
2066   static bool classof(const SDNode *N) {
2067     return N->getOpcode() == ISD::MLOAD;
2068   }
2069 };
2070
2071 /// This class is used to represent an MSTORE node
2072 class MaskedStoreSDNode : public MaskedLoadStoreSDNode {
2073
2074 public:
2075   friend class SelectionDAG;
2076   MaskedStoreSDNode(unsigned Order, DebugLoc dl, SDValue *Operands,
2077                     unsigned numOperands, SDVTList VTs, bool isTrunc, EVT MemVT,
2078                     MachineMemOperand *MMO)
2079     : MaskedLoadStoreSDNode(ISD::MSTORE, Order, dl, Operands, numOperands,
2080                             VTs, MemVT, MMO) {
2081       SubclassData |= (unsigned short)isTrunc;
2082   }
2083   /// Return true if the op does a truncation before store.
2084   /// For integers this is the same as doing a TRUNCATE and storing the result.
2085   /// For floats, it is the same as doing an FP_ROUND and storing the result.
2086   bool isTruncatingStore() const { return SubclassData & 1; }
2087
2088   const SDValue &getValue() const { return getOperand(3); }
2089
2090   static bool classof(const SDNode *N) {
2091     return N->getOpcode() == ISD::MSTORE;
2092   }
2093 };
2094
2095 /// This is a base class used to represent
2096 /// MGATHER and MSCATTER nodes
2097 ///
2098 class MaskedGatherScatterSDNode : public MemSDNode {
2099   // Operands
2100   SDUse Ops[5];
2101 public:
2102   friend class SelectionDAG;
2103   MaskedGatherScatterSDNode(ISD::NodeType NodeTy, unsigned Order, DebugLoc dl,
2104                             ArrayRef<SDValue> Operands, SDVTList VTs, EVT MemVT,
2105                             MachineMemOperand *MMO)
2106     : MemSDNode(NodeTy, Order, dl, VTs, MemVT, MMO) {
2107     assert(Operands.size() == 5 && "Incompatible number of operands");
2108     InitOperands(Ops, Operands.data(), Operands.size());
2109   }
2110
2111   // In the both nodes address is Op1, mask is Op2:
2112   // MaskedGatherSDNode  (Chain, src0, mask, base, index), src0 is a passthru value
2113   // MaskedScatterSDNode (Chain, value, mask, base, index)
2114   // Mask is a vector of i1 elements
2115   const SDValue &getBasePtr() const { return getOperand(3); }
2116   const SDValue &getIndex()   const { return getOperand(4); }
2117   const SDValue &getMask()    const { return getOperand(2); }
2118   const SDValue &getValue()   const { return getOperand(1); }
2119
2120   static bool classof(const SDNode *N) {
2121     return N->getOpcode() == ISD::MGATHER ||
2122            N->getOpcode() == ISD::MSCATTER;
2123   }
2124 };
2125
2126 /// This class is used to represent an MGATHER node
2127 ///
2128 class MaskedGatherSDNode : public MaskedGatherScatterSDNode {
2129 public:
2130   friend class SelectionDAG;
2131   MaskedGatherSDNode(unsigned Order, DebugLoc dl, ArrayRef<SDValue> Operands,
2132                      SDVTList VTs, EVT MemVT, MachineMemOperand *MMO)
2133     : MaskedGatherScatterSDNode(ISD::MGATHER, Order, dl, Operands, VTs, MemVT,
2134                                 MMO) {
2135     assert(getValue().getValueType() == getValueType(0) &&
2136            "Incompatible type of the PathThru value in MaskedGatherSDNode");
2137     assert(getMask().getValueType().getVectorNumElements() ==
2138                getValueType(0).getVectorNumElements() &&
2139            "Vector width mismatch between mask and data");
2140     assert(getMask().getValueType().getScalarType() == MVT::i1 &&
2141            "Vector width mismatch between mask and data");
2142   }
2143
2144   static bool classof(const SDNode *N) {
2145     return N->getOpcode() == ISD::MGATHER;
2146   }
2147 };
2148
2149 /// This class is used to represent an MSCATTER node
2150 ///
2151 class MaskedScatterSDNode : public MaskedGatherScatterSDNode {
2152
2153 public:
2154   friend class SelectionDAG;
2155   MaskedScatterSDNode(unsigned Order, DebugLoc dl,ArrayRef<SDValue> Operands,
2156                       SDVTList VTs, EVT MemVT, MachineMemOperand *MMO)
2157       : MaskedGatherScatterSDNode(ISD::MSCATTER, Order, dl, Operands, VTs,
2158                                   MemVT, MMO) {
2159     assert(getMask().getValueType().getVectorNumElements() ==
2160                getValue().getValueType().getVectorNumElements() &&
2161            "Vector width mismatch between mask and data");
2162     assert(getMask().getValueType().getScalarType() == MVT::i1 &&
2163            "Vector width mismatch between mask and data");
2164   }
2165
2166   static bool classof(const SDNode *N) {
2167     return N->getOpcode() == ISD::MSCATTER;
2168   }
2169 };
2170
2171 /// An SDNode that represents everything that will be needed
2172 /// to construct a MachineInstr. These nodes are created during the
2173 /// instruction selection proper phase.
2174 class MachineSDNode : public SDNode {
2175 public:
2176   typedef MachineMemOperand **mmo_iterator;
2177
2178 private:
2179   friend class SelectionDAG;
2180   MachineSDNode(unsigned Opc, unsigned Order, const DebugLoc DL, SDVTList VTs)
2181     : SDNode(Opc, Order, DL, VTs), MemRefs(nullptr), MemRefsEnd(nullptr) {}
2182
2183   /// Operands for this instruction, if they fit here. If
2184   /// they don't, this field is unused.
2185   SDUse LocalOperands[4];
2186
2187   /// Memory reference descriptions for this instruction.
2188   mmo_iterator MemRefs;
2189   mmo_iterator MemRefsEnd;
2190
2191 public:
2192   mmo_iterator memoperands_begin() const { return MemRefs; }
2193   mmo_iterator memoperands_end() const { return MemRefsEnd; }
2194   bool memoperands_empty() const { return MemRefsEnd == MemRefs; }
2195
2196   /// Assign this MachineSDNodes's memory reference descriptor
2197   /// list. This does not transfer ownership.
2198   void setMemRefs(mmo_iterator NewMemRefs, mmo_iterator NewMemRefsEnd) {
2199     for (mmo_iterator MMI = NewMemRefs, MME = NewMemRefsEnd; MMI != MME; ++MMI)
2200       assert(*MMI && "Null mem ref detected!");
2201     MemRefs = NewMemRefs;
2202     MemRefsEnd = NewMemRefsEnd;
2203   }
2204
2205   static bool classof(const SDNode *N) {
2206     return N->isMachineOpcode();
2207   }
2208 };
2209
2210 class SDNodeIterator : public std::iterator<std::forward_iterator_tag,
2211                                             SDNode, ptrdiff_t> {
2212   const SDNode *Node;
2213   unsigned Operand;
2214
2215   SDNodeIterator(const SDNode *N, unsigned Op) : Node(N), Operand(Op) {}
2216 public:
2217   bool operator==(const SDNodeIterator& x) const {
2218     return Operand == x.Operand;
2219   }
2220   bool operator!=(const SDNodeIterator& x) const { return !operator==(x); }
2221
2222   pointer operator*() const {
2223     return Node->getOperand(Operand).getNode();
2224   }
2225   pointer operator->() const { return operator*(); }
2226
2227   SDNodeIterator& operator++() {                // Preincrement
2228     ++Operand;
2229     return *this;
2230   }
2231   SDNodeIterator operator++(int) { // Postincrement
2232     SDNodeIterator tmp = *this; ++*this; return tmp;
2233   }
2234   size_t operator-(SDNodeIterator Other) const {
2235     assert(Node == Other.Node &&
2236            "Cannot compare iterators of two different nodes!");
2237     return Operand - Other.Operand;
2238   }
2239
2240   static SDNodeIterator begin(const SDNode *N) { return SDNodeIterator(N, 0); }
2241   static SDNodeIterator end  (const SDNode *N) {
2242     return SDNodeIterator(N, N->getNumOperands());
2243   }
2244
2245   unsigned getOperand() const { return Operand; }
2246   const SDNode *getNode() const { return Node; }
2247 };
2248
2249 template <> struct GraphTraits<SDNode*> {
2250   typedef SDNode NodeType;
2251   typedef SDNodeIterator ChildIteratorType;
2252   static inline NodeType *getEntryNode(SDNode *N) { return N; }
2253   static inline ChildIteratorType child_begin(NodeType *N) {
2254     return SDNodeIterator::begin(N);
2255   }
2256   static inline ChildIteratorType child_end(NodeType *N) {
2257     return SDNodeIterator::end(N);
2258   }
2259 };
2260
2261 /// The largest SDNode class.
2262 typedef MaskedGatherScatterSDNode LargestSDNode;
2263
2264 /// The SDNode class with the greatest alignment requirement.
2265 typedef GlobalAddressSDNode MostAlignedSDNode;
2266
2267 namespace ISD {
2268   /// Returns true if the specified node is a non-extending and unindexed load.
2269   inline bool isNormalLoad(const SDNode *N) {
2270     const LoadSDNode *Ld = dyn_cast<LoadSDNode>(N);
2271     return Ld && Ld->getExtensionType() == ISD::NON_EXTLOAD &&
2272       Ld->getAddressingMode() == ISD::UNINDEXED;
2273   }
2274
2275   /// Returns true if the specified node is a non-extending load.
2276   inline bool isNON_EXTLoad(const SDNode *N) {
2277     return isa<LoadSDNode>(N) &&
2278       cast<LoadSDNode>(N)->getExtensionType() == ISD::NON_EXTLOAD;
2279   }
2280
2281   /// Returns true if the specified node is a EXTLOAD.
2282   inline bool isEXTLoad(const SDNode *N) {
2283     return isa<LoadSDNode>(N) &&
2284       cast<LoadSDNode>(N)->getExtensionType() == ISD::EXTLOAD;
2285   }
2286
2287   /// Returns true if the specified node is a SEXTLOAD.
2288   inline bool isSEXTLoad(const SDNode *N) {
2289     return isa<LoadSDNode>(N) &&
2290       cast<LoadSDNode>(N)->getExtensionType() == ISD::SEXTLOAD;
2291   }
2292
2293   /// Returns true if the specified node is a ZEXTLOAD.
2294   inline bool isZEXTLoad(const SDNode *N) {
2295     return isa<LoadSDNode>(N) &&
2296       cast<LoadSDNode>(N)->getExtensionType() == ISD::ZEXTLOAD;
2297   }
2298
2299   /// Returns true if the specified node is an unindexed load.
2300   inline bool isUNINDEXEDLoad(const SDNode *N) {
2301     return isa<LoadSDNode>(N) &&
2302       cast<LoadSDNode>(N)->getAddressingMode() == ISD::UNINDEXED;
2303   }
2304
2305   /// Returns true if the specified node is a non-truncating
2306   /// and unindexed store.
2307   inline bool isNormalStore(const SDNode *N) {
2308     const StoreSDNode *St = dyn_cast<StoreSDNode>(N);
2309     return St && !St->isTruncatingStore() &&
2310       St->getAddressingMode() == ISD::UNINDEXED;
2311   }
2312
2313   /// Returns true if the specified node is a non-truncating store.
2314   inline bool isNON_TRUNCStore(const SDNode *N) {
2315     return isa<StoreSDNode>(N) && !cast<StoreSDNode>(N)->isTruncatingStore();
2316   }
2317
2318   /// Returns true if the specified node is a truncating store.
2319   inline bool isTRUNCStore(const SDNode *N) {
2320     return isa<StoreSDNode>(N) && cast<StoreSDNode>(N)->isTruncatingStore();
2321   }
2322
2323   /// Returns true if the specified node is an unindexed store.
2324   inline bool isUNINDEXEDStore(const SDNode *N) {
2325     return isa<StoreSDNode>(N) &&
2326       cast<StoreSDNode>(N)->getAddressingMode() == ISD::UNINDEXED;
2327   }
2328 }
2329
2330 } // end llvm namespace
2331
2332 #endif