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