add a helper class
[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 was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source 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/CodeGen/ValueTypes.h"
23 #include "llvm/Value.h"
24 #include "llvm/ADT/GraphTraits.h"
25 #include "llvm/ADT/GraphTraits.h"
26 #include "llvm/ADT/iterator"
27 #include "llvm/Support/DataTypes.h"
28 #include <cassert>
29 #include <vector>
30
31 namespace llvm {
32
33 class SelectionDAG;
34 class GlobalValue;
35 class MachineBasicBlock;
36 class SDNode;
37 template <typename T> struct simplify_type;
38
39 /// ISD namespace - This namespace contains an enum which represents all of the
40 /// SelectionDAG node types and value types.
41 ///
42 namespace ISD {
43   //===--------------------------------------------------------------------===//
44   /// ISD::NodeType enum - This enum defines all of the operators valid in a
45   /// SelectionDAG.
46   ///
47   enum NodeType {
48     // EntryToken - This is the marker used to indicate the start of the region.
49     EntryToken,
50
51     // Token factor - This node takes multiple tokens as input and produces a
52     // single token result.  This is used to represent the fact that the operand
53     // operators are independent of each other.
54     TokenFactor,
55     
56     // AssertSext, AssertZext - These nodes record if a register contains a 
57     // value that has already been zero or sign extended from a narrower type.  
58     // These nodes take two operands.  The first is the node that has already 
59     // been extended, and the second is a value type node indicating the width
60     // of the extension
61     AssertSext, AssertZext,
62
63     // Various leaf nodes.
64     Constant, ConstantFP, GlobalAddress, FrameIndex, ConstantPool,
65     BasicBlock, ExternalSymbol, VALUETYPE, CONDCODE, Register,
66     
67     // TargetConstant - Like Constant, but the DAG does not do any folding or
68     // simplification of the constant.  This is used by the DAG->DAG selector.
69     TargetConstant,
70     
71     // TargetGlobalAddress - Like GlobalAddress, but the DAG does no folding or
72     // anything else with this node, and this is valid in the target-specific
73     // dag, turning into a GlobalAddress operand.
74     TargetGlobalAddress,
75     TargetFrameIndex,
76     TargetConstantPool,
77
78     // CopyToReg - This node has three operands: a chain, a register number to
79     // set to this value, and a value.  
80     CopyToReg,
81
82     // CopyFromReg - This node indicates that the input value is a virtual or
83     // physical register that is defined outside of the scope of this
84     // SelectionDAG.  The register is available from the RegSDNode object.
85     CopyFromReg,
86
87     // ImplicitDef - This node indicates that the specified register is
88     // implicitly defined by some operation (e.g. its a live-in argument).  The
89     // two operands to this are the token chain coming in and the register.
90     // The only result is the token chain going out.
91     ImplicitDef,
92
93     // UNDEF - An undefined node
94     UNDEF,
95
96     // EXTRACT_ELEMENT - This is used to get the first or second (determined by
97     // a Constant, which is required to be operand #1), element of the aggregate
98     // value specified as operand #0.  This is only for use before legalization,
99     // for values that will be broken into multiple registers.
100     EXTRACT_ELEMENT,
101
102     // BUILD_PAIR - This is the opposite of EXTRACT_ELEMENT in some ways.  Given
103     // two values of the same integer value type, this produces a value twice as
104     // big.  Like EXTRACT_ELEMENT, this can only be used before legalization.
105     BUILD_PAIR,
106
107
108     // Simple integer binary arithmetic operators.
109     ADD, SUB, MUL, SDIV, UDIV, SREM, UREM,
110     
111     // Simple binary floating point operators.
112     FADD, FSUB, FMUL, FDIV, FREM,
113
114     // MULHU/MULHS - Multiply high - Multiply two integers of type iN, producing
115     // an unsigned/signed value of type i[2*n], then return the top part.
116     MULHU, MULHS,
117
118     // Bitwise operators.
119     AND, OR, XOR, SHL, SRA, SRL,
120
121     // Counting operators
122     CTTZ, CTLZ, CTPOP,
123
124     // Select
125     SELECT, 
126     
127     // Select with condition operator - This selects between a true value and 
128     // a false value (ops #2 and #3) based on the boolean result of comparing
129     // the lhs and rhs (ops #0 and #1) of a conditional expression with the 
130     // condition code in op #4, a CondCodeSDNode.
131     SELECT_CC,
132
133     // SetCC operator - This evaluates to a boolean (i1) true value if the
134     // condition is true.  The operands to this are the left and right operands
135     // to compare (ops #0, and #1) and the condition code to compare them with
136     // (op #2) as a CondCodeSDNode.
137     SETCC,
138
139     // ADD_PARTS/SUB_PARTS - These operators take two logical operands which are
140     // broken into a multiple pieces each, and return the resulting pieces of
141     // doing an atomic add/sub operation.  This is used to handle add/sub of
142     // expanded types.  The operation ordering is:
143     //       [Lo,Hi] = op [LoLHS,HiLHS], [LoRHS,HiRHS]
144     ADD_PARTS, SUB_PARTS,
145
146     // SHL_PARTS/SRA_PARTS/SRL_PARTS - These operators are used for expanded
147     // integer shift operations, just like ADD/SUB_PARTS.  The operation
148     // ordering is:
149     //       [Lo,Hi] = op [LoLHS,HiLHS], Amt
150     SHL_PARTS, SRA_PARTS, SRL_PARTS,
151
152     // Conversion operators.  These are all single input single output
153     // operations.  For all of these, the result type must be strictly
154     // wider or narrower (depending on the operation) than the source
155     // type.
156
157     // SIGN_EXTEND - Used for integer types, replicating the sign bit
158     // into new bits.
159     SIGN_EXTEND,
160
161     // ZERO_EXTEND - Used for integer types, zeroing the new bits.
162     ZERO_EXTEND,
163
164     // ANY_EXTEND - Used for integer types.  The high bits are undefined.
165     ANY_EXTEND,
166     
167     // TRUNCATE - Completely drop the high bits.
168     TRUNCATE,
169
170     // [SU]INT_TO_FP - These operators convert integers (whose interpreted sign
171     // depends on the first letter) to floating point.
172     SINT_TO_FP,
173     UINT_TO_FP,
174
175     // SIGN_EXTEND_INREG - This operator atomically performs a SHL/SRA pair to
176     // sign extend a small value in a large integer register (e.g. sign
177     // extending the low 8 bits of a 32-bit register to fill the top 24 bits
178     // with the 7th bit).  The size of the smaller type is indicated by the 1th
179     // operand, a ValueType node.
180     SIGN_EXTEND_INREG,
181
182     // FP_TO_[US]INT - Convert a floating point value to a signed or unsigned
183     // integer.
184     FP_TO_SINT,
185     FP_TO_UINT,
186
187     // FP_ROUND - Perform a rounding operation from the current
188     // precision down to the specified precision (currently always 64->32).
189     FP_ROUND,
190
191     // FP_ROUND_INREG - This operator takes a floating point register, and
192     // rounds it to a floating point value.  It then promotes it and returns it
193     // in a register of the same size.  This operation effectively just discards
194     // excess precision.  The type to round down to is specified by the 1th
195     // operation, a VTSDNode (currently always 64->32->64).
196     FP_ROUND_INREG,
197
198     // FP_EXTEND - Extend a smaller FP type into a larger FP type.
199     FP_EXTEND,
200
201     // FNEG, FABS, FSQRT, FSIN, FCOS - Perform unary floating point negation,
202     // absolute value, square root, sine and cosine operations.
203     FNEG, FABS, FSQRT, FSIN, FCOS,
204
205     // Other operators.  LOAD and STORE have token chains as their first
206     // operand, then the same operands as an LLVM load/store instruction, then a
207     // SRCVALUE node that provides alias analysis information.
208     LOAD, STORE,
209
210     // EXTLOAD, SEXTLOAD, ZEXTLOAD - These three operators all load a value from
211     // memory and extend them to a larger value (e.g. load a byte into a word
212     // register).  All three of these have four operands, a token chain, a
213     // pointer to load from, a SRCVALUE for alias analysis, and a VALUETYPE node
214     // indicating the type to load.
215     //
216     // SEXTLOAD loads the integer operand and sign extends it to a larger
217     //          integer result type.
218     // ZEXTLOAD loads the integer operand and zero extends it to a larger
219     //          integer result type.
220     // EXTLOAD  is used for two things: floating point extending loads, and
221     //          integer extending loads where it doesn't matter what the high
222     //          bits are set to.  The code generator is allowed to codegen this
223     //          into whichever operation is more efficient.
224     EXTLOAD, SEXTLOAD, ZEXTLOAD,
225
226     // TRUNCSTORE - This operators truncates (for integer) or rounds (for FP) a
227     // value and stores it to memory in one operation.  This can be used for
228     // either integer or floating point operands.  The first four operands of
229     // this are the same as a standard store.  The fifth is the ValueType to
230     // store it as (which will be smaller than the source value).
231     TRUNCSTORE,
232
233     // DYNAMIC_STACKALLOC - Allocate some number of bytes on the stack aligned
234     // to a specified boundary.  The first operand is the token chain, the
235     // second is the number of bytes to allocate, and the third is the alignment
236     // boundary.  The size is guaranteed to be a multiple of the stack 
237     // alignment, and the alignment is guaranteed to be bigger than the stack 
238     // alignment (if required) or 0 to get standard stack alignment.
239     DYNAMIC_STACKALLOC,
240
241     // Control flow instructions.  These all have token chains.
242
243     // BR - Unconditional branch.  The first operand is the chain
244     // operand, the second is the MBB to branch to.
245     BR,
246
247     // BRCOND - Conditional branch.  The first operand is the chain,
248     // the second is the condition, the third is the block to branch
249     // to if the condition is true.
250     BRCOND,
251
252     // BRCONDTWOWAY - Two-way conditional branch.  The first operand is the
253     // chain, the second is the condition, the third is the block to branch to
254     // if true, and the forth is the block to branch to if false.  Targets
255     // usually do not implement this, preferring to have legalize demote the
256     // operation to BRCOND/BR pairs when necessary.
257     BRCONDTWOWAY,
258
259     // BR_CC - Conditional branch.  The behavior is like that of SELECT_CC, in
260     // that the condition is represented as condition code, and two nodes to
261     // compare, rather than as a combined SetCC node.  The operands in order are
262     // chain, cc, lhs, rhs, block to branch to if condition is true.
263     BR_CC,
264     
265     // BRTWOWAY_CC - Two-way conditional branch.  The operands in order are
266     // chain, cc, lhs, rhs, block to branch to if condition is true, block to
267     // branch to if condition is false.  Targets usually do not implement this,
268     // preferring to have legalize demote the operation to BRCOND/BR pairs.
269     BRTWOWAY_CC,
270     
271     // RET - Return from function.  The first operand is the chain,
272     // and any subsequent operands are the return values for the
273     // function.  This operation can have variable number of operands.
274     RET,
275
276     // CALL - Call to a function pointer.  The first operand is the chain, the
277     // second is the destination function pointer (a GlobalAddress for a direct
278     // call).  Arguments have already been lowered to explicit DAGs according to
279     // the calling convention in effect here.  TAILCALL is the same as CALL, but
280     // the callee is known not to access the stack of the caller.
281     CALL,
282     TAILCALL,
283
284     // MEMSET/MEMCPY/MEMMOVE - The first operand is the chain, and the rest
285     // correspond to the operands of the LLVM intrinsic functions.  The only
286     // result is a token chain.  The alignment argument is guaranteed to be a
287     // Constant node.
288     MEMSET,
289     MEMMOVE,
290     MEMCPY,
291
292     // CALLSEQ_START/CALLSEQ_END - These operators mark the beginning and end of
293     // a call sequence, and carry arbitrary information that target might want
294     // to know.  The first operand is a chain, the rest are specified by the
295     // target and not touched by the DAG optimizers.
296     CALLSEQ_START,  // Beginning of a call sequence
297     CALLSEQ_END,    // End of a call sequence
298
299     // SRCVALUE - This corresponds to a Value*, and is used to associate memory
300     // locations with their value.  This allows one use alias analysis
301     // information in the backend.
302     SRCVALUE,
303
304     // PCMARKER - This corresponds to the pcmarker intrinsic.
305     PCMARKER,
306
307     // READPORT, WRITEPORT, READIO, WRITEIO - These correspond to the LLVM
308     // intrinsics of the same name.  The first operand is a token chain, the
309     // other operands match the intrinsic.  These produce a token chain in
310     // addition to a value (if any).
311     READPORT, WRITEPORT, READIO, WRITEIO,
312     
313     // HANDLENODE node - Used as a handle for various purposes.
314     HANDLENODE,
315
316     // BUILTIN_OP_END - This must be the last enum value in this list.
317     BUILTIN_OP_END,
318   };
319
320   //===--------------------------------------------------------------------===//
321   /// ISD::CondCode enum - These are ordered carefully to make the bitfields
322   /// below work out, when considering SETFALSE (something that never exists
323   /// dynamically) as 0.  "U" -> Unsigned (for integer operands) or Unordered
324   /// (for floating point), "L" -> Less than, "G" -> Greater than, "E" -> Equal
325   /// to.  If the "N" column is 1, the result of the comparison is undefined if
326   /// the input is a NAN.
327   ///
328   /// All of these (except for the 'always folded ops') should be handled for
329   /// floating point.  For integer, only the SETEQ,SETNE,SETLT,SETLE,SETGT,
330   /// SETGE,SETULT,SETULE,SETUGT, and SETUGE opcodes are used.
331   ///
332   /// Note that these are laid out in a specific order to allow bit-twiddling
333   /// to transform conditions.
334   enum CondCode {
335     // Opcode          N U L G E       Intuitive operation
336     SETFALSE,      //    0 0 0 0       Always false (always folded)
337     SETOEQ,        //    0 0 0 1       True if ordered and equal
338     SETOGT,        //    0 0 1 0       True if ordered and greater than
339     SETOGE,        //    0 0 1 1       True if ordered and greater than or equal
340     SETOLT,        //    0 1 0 0       True if ordered and less than
341     SETOLE,        //    0 1 0 1       True if ordered and less than or equal
342     SETONE,        //    0 1 1 0       True if ordered and operands are unequal
343     SETO,          //    0 1 1 1       True if ordered (no nans)
344     SETUO,         //    1 0 0 0       True if unordered: isnan(X) | isnan(Y)
345     SETUEQ,        //    1 0 0 1       True if unordered or equal
346     SETUGT,        //    1 0 1 0       True if unordered or greater than
347     SETUGE,        //    1 0 1 1       True if unordered, greater than, or equal
348     SETULT,        //    1 1 0 0       True if unordered or less than
349     SETULE,        //    1 1 0 1       True if unordered, less than, or equal
350     SETUNE,        //    1 1 1 0       True if unordered or not equal
351     SETTRUE,       //    1 1 1 1       Always true (always folded)
352     // Don't care operations: undefined if the input is a nan.
353     SETFALSE2,     //  1 X 0 0 0       Always false (always folded)
354     SETEQ,         //  1 X 0 0 1       True if equal
355     SETGT,         //  1 X 0 1 0       True if greater than
356     SETGE,         //  1 X 0 1 1       True if greater than or equal
357     SETLT,         //  1 X 1 0 0       True if less than
358     SETLE,         //  1 X 1 0 1       True if less than or equal
359     SETNE,         //  1 X 1 1 0       True if not equal
360     SETTRUE2,      //  1 X 1 1 1       Always true (always folded)
361
362     SETCC_INVALID,      // Marker value.
363   };
364
365   /// isSignedIntSetCC - Return true if this is a setcc instruction that
366   /// performs a signed comparison when used with integer operands.
367   inline bool isSignedIntSetCC(CondCode Code) {
368     return Code == SETGT || Code == SETGE || Code == SETLT || Code == SETLE;
369   }
370
371   /// isUnsignedIntSetCC - Return true if this is a setcc instruction that
372   /// performs an unsigned comparison when used with integer operands.
373   inline bool isUnsignedIntSetCC(CondCode Code) {
374     return Code == SETUGT || Code == SETUGE || Code == SETULT || Code == SETULE;
375   }
376
377   /// isTrueWhenEqual - Return true if the specified condition returns true if
378   /// the two operands to the condition are equal.  Note that if one of the two
379   /// operands is a NaN, this value is meaningless.
380   inline bool isTrueWhenEqual(CondCode Cond) {
381     return ((int)Cond & 1) != 0;
382   }
383
384   /// getUnorderedFlavor - This function returns 0 if the condition is always
385   /// false if an operand is a NaN, 1 if the condition is always true if the
386   /// operand is a NaN, and 2 if the condition is undefined if the operand is a
387   /// NaN.
388   inline unsigned getUnorderedFlavor(CondCode Cond) {
389     return ((int)Cond >> 3) & 3;
390   }
391
392   /// getSetCCInverse - Return the operation corresponding to !(X op Y), where
393   /// 'op' is a valid SetCC operation.
394   CondCode getSetCCInverse(CondCode Operation, bool isInteger);
395
396   /// getSetCCSwappedOperands - Return the operation corresponding to (Y op X)
397   /// when given the operation for (X op Y).
398   CondCode getSetCCSwappedOperands(CondCode Operation);
399
400   /// getSetCCOrOperation - Return the result of a logical OR between different
401   /// comparisons of identical values: ((X op1 Y) | (X op2 Y)).  This
402   /// function returns SETCC_INVALID if it is not possible to represent the
403   /// resultant comparison.
404   CondCode getSetCCOrOperation(CondCode Op1, CondCode Op2, bool isInteger);
405
406   /// getSetCCAndOperation - Return the result of a logical AND between
407   /// different comparisons of identical values: ((X op1 Y) & (X op2 Y)).  This
408   /// function returns SETCC_INVALID if it is not possible to represent the
409   /// resultant comparison.
410   CondCode getSetCCAndOperation(CondCode Op1, CondCode Op2, bool isInteger);
411 }  // end llvm::ISD namespace
412
413
414 //===----------------------------------------------------------------------===//
415 /// SDOperand - Unlike LLVM values, Selection DAG nodes may return multiple
416 /// values as the result of a computation.  Many nodes return multiple values,
417 /// from loads (which define a token and a return value) to ADDC (which returns
418 /// a result and a carry value), to calls (which may return an arbitrary number
419 /// of values).
420 ///
421 /// As such, each use of a SelectionDAG computation must indicate the node that
422 /// computes it as well as which return value to use from that node.  This pair
423 /// of information is represented with the SDOperand value type.
424 ///
425 class SDOperand {
426 public:
427   SDNode *Val;        // The node defining the value we are using.
428   unsigned ResNo;     // Which return value of the node we are using.
429
430   SDOperand() : Val(0) {}
431   SDOperand(SDNode *val, unsigned resno) : Val(val), ResNo(resno) {}
432
433   bool operator==(const SDOperand &O) const {
434     return Val == O.Val && ResNo == O.ResNo;
435   }
436   bool operator!=(const SDOperand &O) const {
437     return !operator==(O);
438   }
439   bool operator<(const SDOperand &O) const {
440     return Val < O.Val || (Val == O.Val && ResNo < O.ResNo);
441   }
442
443   SDOperand getValue(unsigned R) const {
444     return SDOperand(Val, R);
445   }
446
447   /// getValueType - Return the ValueType of the referenced return value.
448   ///
449   inline MVT::ValueType getValueType() const;
450
451   // Forwarding methods - These forward to the corresponding methods in SDNode.
452   inline unsigned getOpcode() const;
453   inline unsigned getNodeDepth() const;
454   inline unsigned getNumOperands() const;
455   inline const SDOperand &getOperand(unsigned i) const;
456   inline bool isTargetOpcode() const;
457   inline unsigned getTargetOpcode() const;
458
459   /// hasOneUse - Return true if there is exactly one operation using this
460   /// result value of the defining operator.
461   inline bool hasOneUse() const;
462 };
463
464
465 /// simplify_type specializations - Allow casting operators to work directly on
466 /// SDOperands as if they were SDNode*'s.
467 template<> struct simplify_type<SDOperand> {
468   typedef SDNode* SimpleType;
469   static SimpleType getSimplifiedValue(const SDOperand &Val) {
470     return static_cast<SimpleType>(Val.Val);
471   }
472 };
473 template<> struct simplify_type<const SDOperand> {
474   typedef SDNode* SimpleType;
475   static SimpleType getSimplifiedValue(const SDOperand &Val) {
476     return static_cast<SimpleType>(Val.Val);
477   }
478 };
479
480
481 /// SDNode - Represents one node in the SelectionDAG.
482 ///
483 class SDNode {
484   /// NodeType - The operation that this node performs.
485   ///
486   unsigned short NodeType;
487
488   /// NodeDepth - Node depth is defined as MAX(Node depth of children)+1.  This
489   /// means that leaves have a depth of 1, things that use only leaves have a
490   /// depth of 2, etc.
491   unsigned short NodeDepth;
492
493   /// Operands - The values that are used by this operation.
494   ///
495   std::vector<SDOperand> Operands;
496
497   /// Values - The types of the values this node defines.  SDNode's may define
498   /// multiple values simultaneously.
499   std::vector<MVT::ValueType> Values;
500
501   /// Uses - These are all of the SDNode's that use a value produced by this
502   /// node.
503   std::vector<SDNode*> Uses;
504 public:
505
506   //===--------------------------------------------------------------------===//
507   //  Accessors
508   //
509   unsigned getOpcode()  const { return NodeType; }
510   bool isTargetOpcode() const { return NodeType >= ISD::BUILTIN_OP_END; }
511   unsigned getTargetOpcode() const {
512     assert(isTargetOpcode() && "Not a target opcode!");
513     return NodeType - ISD::BUILTIN_OP_END;
514   }
515
516   size_t use_size() const { return Uses.size(); }
517   bool use_empty() const { return Uses.empty(); }
518   bool hasOneUse() const { return Uses.size() == 1; }
519
520   /// getNodeDepth - Return the distance from this node to the leaves in the
521   /// graph.  The leaves have a depth of 1.
522   unsigned getNodeDepth() const { return NodeDepth; }
523
524   typedef std::vector<SDNode*>::const_iterator use_iterator;
525   use_iterator use_begin() const { return Uses.begin(); }
526   use_iterator use_end() const { return Uses.end(); }
527
528   /// hasNUsesOfValue - Return true if there are exactly NUSES uses of the
529   /// indicated value.  This method ignores uses of other values defined by this
530   /// operation.
531   bool hasNUsesOfValue(unsigned NUses, unsigned Value);
532
533   /// getNumOperands - Return the number of values used by this operation.
534   ///
535   unsigned getNumOperands() const { return Operands.size(); }
536
537   const SDOperand &getOperand(unsigned Num) {
538     assert(Num < Operands.size() && "Invalid child # of SDNode!");
539     return Operands[Num];
540   }
541
542   const SDOperand &getOperand(unsigned Num) const {
543     assert(Num < Operands.size() && "Invalid child # of SDNode!");
544     return Operands[Num];
545   }
546   typedef std::vector<SDOperand>::const_iterator op_iterator;
547   op_iterator op_begin() const { return Operands.begin(); }
548   op_iterator op_end() const { return Operands.end(); }
549
550
551   /// getNumValues - Return the number of values defined/returned by this
552   /// operator.
553   ///
554   unsigned getNumValues() const { return Values.size(); }
555
556   /// getValueType - Return the type of a specified result.
557   ///
558   MVT::ValueType getValueType(unsigned ResNo) const {
559     assert(ResNo < Values.size() && "Illegal result number!");
560     return Values[ResNo];
561   }
562
563   typedef std::vector<MVT::ValueType>::const_iterator value_iterator;
564   value_iterator value_begin() const { return Values.begin(); }
565   value_iterator value_end() const { return Values.end(); }
566
567   /// getOperationName - Return the opcode of this operation for printing.
568   ///
569   const char* getOperationName(const SelectionDAG *G = 0) const;
570   void dump() const;
571   void dump(const SelectionDAG *G) const;
572
573   static bool classof(const SDNode *) { return true; }
574
575
576   /// setAdjCallChain - This method should only be used by the legalizer.
577   void setAdjCallChain(SDOperand N);
578
579 protected:
580   friend class SelectionDAG;
581
582   SDNode(unsigned NT, MVT::ValueType VT) : NodeType(NT), NodeDepth(1) {
583     Values.reserve(1);
584     Values.push_back(VT);
585   }
586   SDNode(unsigned NT, SDOperand Op)
587     : NodeType(NT), NodeDepth(Op.Val->getNodeDepth()+1) {
588     Operands.reserve(1); Operands.push_back(Op);
589     Op.Val->Uses.push_back(this);
590   }
591   SDNode(unsigned NT, SDOperand N1, SDOperand N2)
592     : NodeType(NT) {
593     if (N1.Val->getNodeDepth() > N2.Val->getNodeDepth())
594       NodeDepth = N1.Val->getNodeDepth()+1;
595     else
596       NodeDepth = N2.Val->getNodeDepth()+1;
597     Operands.reserve(2); Operands.push_back(N1); Operands.push_back(N2);
598     N1.Val->Uses.push_back(this); N2.Val->Uses.push_back(this);
599   }
600   SDNode(unsigned NT, SDOperand N1, SDOperand N2, SDOperand N3)
601     : NodeType(NT) {
602     unsigned ND = N1.Val->getNodeDepth();
603     if (ND < N2.Val->getNodeDepth())
604       ND = N2.Val->getNodeDepth();
605     if (ND < N3.Val->getNodeDepth())
606       ND = N3.Val->getNodeDepth();
607     NodeDepth = ND+1;
608
609     Operands.reserve(3); Operands.push_back(N1); Operands.push_back(N2);
610     Operands.push_back(N3);
611     N1.Val->Uses.push_back(this); N2.Val->Uses.push_back(this);
612     N3.Val->Uses.push_back(this);
613   }
614   SDNode(unsigned NT, SDOperand N1, SDOperand N2, SDOperand N3, SDOperand N4)
615     : NodeType(NT) {
616     unsigned ND = N1.Val->getNodeDepth();
617     if (ND < N2.Val->getNodeDepth())
618       ND = N2.Val->getNodeDepth();
619     if (ND < N3.Val->getNodeDepth())
620       ND = N3.Val->getNodeDepth();
621     if (ND < N4.Val->getNodeDepth())
622       ND = N4.Val->getNodeDepth();
623     NodeDepth = ND+1;
624
625     Operands.reserve(4); Operands.push_back(N1); Operands.push_back(N2);
626     Operands.push_back(N3); Operands.push_back(N4);
627     N1.Val->Uses.push_back(this); N2.Val->Uses.push_back(this);
628     N3.Val->Uses.push_back(this); N4.Val->Uses.push_back(this);
629   }
630   SDNode(unsigned NT, std::vector<SDOperand> &Nodes) : NodeType(NT) {
631     Operands.swap(Nodes);
632     unsigned ND = 0;
633     for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
634       Operands[i].Val->Uses.push_back(this);
635       if (ND < Operands[i].Val->getNodeDepth())
636         ND = Operands[i].Val->getNodeDepth();
637     }
638     NodeDepth = ND+1;
639   }
640
641   virtual ~SDNode() {}
642
643   /// MorphNodeTo - This clears the return value and operands list, and sets the
644   /// opcode of the node to the specified value.  This should only be used by
645   /// the SelectionDAG class.
646   void MorphNodeTo(unsigned Opc) {
647     NodeType = Opc;
648     Values.clear();
649     
650     // Clear the operands list, updating used nodes to remove this from their
651     // use list.
652     while (!Operands.empty()) {
653       SDNode *O = Operands.back().Val;
654       Operands.pop_back();
655       O->removeUser(this);
656     }
657   }
658   
659   void setValueTypes(MVT::ValueType VT) {
660     Values.reserve(1);
661     Values.push_back(VT);
662   }
663   void setValueTypes(MVT::ValueType VT1, MVT::ValueType VT2) {
664     Values.reserve(2);
665     Values.push_back(VT1);
666     Values.push_back(VT2);
667   }
668   /// Note: this method destroys the vector passed in.
669   void setValueTypes(std::vector<MVT::ValueType> &VTs) {
670     std::swap(Values, VTs);
671   }
672   
673   void setOperands(SDOperand Op0) {
674     Operands.reserve(1);
675     Operands.push_back(Op0);
676     Op0.Val->Uses.push_back(this);
677   }
678   void setOperands(SDOperand Op0, SDOperand Op1) {
679     Operands.reserve(2);
680     Operands.push_back(Op0);
681     Operands.push_back(Op1);
682     Op0.Val->Uses.push_back(this); Op1.Val->Uses.push_back(this);
683   }
684   void setOperands(SDOperand Op0, SDOperand Op1, SDOperand Op2) {
685     Operands.reserve(3);
686     Operands.push_back(Op0);
687     Operands.push_back(Op1);
688     Operands.push_back(Op2);
689     Op0.Val->Uses.push_back(this); Op1.Val->Uses.push_back(this);
690     Op2.Val->Uses.push_back(this);
691   }
692   void setOperands(SDOperand Op0, SDOperand Op1, SDOperand Op2, SDOperand Op3) {
693     Operands.reserve(4);
694     Operands.push_back(Op0);
695     Operands.push_back(Op1);
696     Operands.push_back(Op2);
697     Operands.push_back(Op3);
698     Op0.Val->Uses.push_back(this); Op1.Val->Uses.push_back(this);
699     Op2.Val->Uses.push_back(this); Op3.Val->Uses.push_back(this);
700   }
701   void setOperands(SDOperand Op0, SDOperand Op1, SDOperand Op2, SDOperand Op3,
702                    SDOperand Op4) {
703     Operands.reserve(5);
704     Operands.push_back(Op0);
705     Operands.push_back(Op1);
706     Operands.push_back(Op2);
707     Operands.push_back(Op3);
708     Operands.push_back(Op4);
709     Op0.Val->Uses.push_back(this); Op1.Val->Uses.push_back(this);
710     Op2.Val->Uses.push_back(this); Op3.Val->Uses.push_back(this);
711     Op4.Val->Uses.push_back(this);
712   }
713   void addUser(SDNode *User) {
714     Uses.push_back(User);
715   }
716   void removeUser(SDNode *User) {
717     // Remove this user from the operand's use list.
718     for (unsigned i = Uses.size(); ; --i) {
719       assert(i != 0 && "Didn't find user!");
720       if (Uses[i-1] == User) {
721         Uses[i-1] = Uses.back();
722         Uses.pop_back();
723         return;
724       }
725     }
726   }
727 };
728
729
730 // Define inline functions from the SDOperand class.
731
732 inline unsigned SDOperand::getOpcode() const {
733   return Val->getOpcode();
734 }
735 inline unsigned SDOperand::getNodeDepth() const {
736   return Val->getNodeDepth();
737 }
738 inline MVT::ValueType SDOperand::getValueType() const {
739   return Val->getValueType(ResNo);
740 }
741 inline unsigned SDOperand::getNumOperands() const {
742   return Val->getNumOperands();
743 }
744 inline const SDOperand &SDOperand::getOperand(unsigned i) const {
745   return Val->getOperand(i);
746 }
747 inline bool SDOperand::isTargetOpcode() const {
748   return Val->isTargetOpcode();
749 }
750 inline unsigned SDOperand::getTargetOpcode() const {
751   return Val->getTargetOpcode();
752 }
753 inline bool SDOperand::hasOneUse() const {
754   return Val->hasNUsesOfValue(1, ResNo);
755 }
756
757 /// HandleSDNode - This class is used to form a handle around another node that
758 /// is persistant and is updated across invocations of replaceAllUsesWith on its
759 /// operand.  This node should be directly created by end-users and not added to
760 /// the AllNodes list.
761 class HandleSDNode : public SDNode {
762 public:
763   HandleSDNode(SDOperand X) : SDNode(ISD::HANDLENODE, X) {}
764   ~HandleSDNode() {
765     MorphNodeTo(ISD::HANDLENODE);  // Drops operand uses.
766   }
767   
768   SDOperand getValue() const { return getOperand(0); }
769 };
770
771
772 class ConstantSDNode : public SDNode {
773   uint64_t Value;
774 protected:
775   friend class SelectionDAG;
776   ConstantSDNode(bool isTarget, uint64_t val, MVT::ValueType VT)
777     : SDNode(isTarget ? ISD::TargetConstant : ISD::Constant, VT), Value(val) {
778   }
779 public:
780
781   uint64_t getValue() const { return Value; }
782
783   int64_t getSignExtended() const {
784     unsigned Bits = MVT::getSizeInBits(getValueType(0));
785     return ((int64_t)Value << (64-Bits)) >> (64-Bits);
786   }
787
788   bool isNullValue() const { return Value == 0; }
789   bool isAllOnesValue() const {
790     int NumBits = MVT::getSizeInBits(getValueType(0));
791     if (NumBits == 64) return Value+1 == 0;
792     return Value == (1ULL << NumBits)-1;
793   }
794
795   static bool classof(const ConstantSDNode *) { return true; }
796   static bool classof(const SDNode *N) {
797     return N->getOpcode() == ISD::Constant ||
798            N->getOpcode() == ISD::TargetConstant;
799   }
800 };
801
802 class ConstantFPSDNode : public SDNode {
803   double Value;
804 protected:
805   friend class SelectionDAG;
806   ConstantFPSDNode(double val, MVT::ValueType VT)
807     : SDNode(ISD::ConstantFP, VT), Value(val) {
808   }
809 public:
810
811   double getValue() const { return Value; }
812
813   /// isExactlyValue - We don't rely on operator== working on double values, as
814   /// it returns true for things that are clearly not equal, like -0.0 and 0.0.
815   /// As such, this method can be used to do an exact bit-for-bit comparison of
816   /// two floating point values.
817   bool isExactlyValue(double V) const;
818
819   static bool classof(const ConstantFPSDNode *) { return true; }
820   static bool classof(const SDNode *N) {
821     return N->getOpcode() == ISD::ConstantFP;
822   }
823 };
824
825 class GlobalAddressSDNode : public SDNode {
826   GlobalValue *TheGlobal;
827 protected:
828   friend class SelectionDAG;
829   GlobalAddressSDNode(bool isTarget, const GlobalValue *GA, MVT::ValueType VT)
830     : SDNode(isTarget ? ISD::TargetGlobalAddress : ISD::GlobalAddress, VT) {
831     TheGlobal = const_cast<GlobalValue*>(GA);
832   }
833 public:
834
835   GlobalValue *getGlobal() const { return TheGlobal; }
836
837   static bool classof(const GlobalAddressSDNode *) { return true; }
838   static bool classof(const SDNode *N) {
839     return N->getOpcode() == ISD::GlobalAddress ||
840            N->getOpcode() == ISD::TargetGlobalAddress;
841   }
842 };
843
844
845 class FrameIndexSDNode : public SDNode {
846   int FI;
847 protected:
848   friend class SelectionDAG;
849   FrameIndexSDNode(int fi, MVT::ValueType VT, bool isTarg)
850     : SDNode(isTarg ? ISD::TargetFrameIndex : ISD::FrameIndex, VT), FI(fi) {}
851 public:
852
853   int getIndex() const { return FI; }
854
855   static bool classof(const FrameIndexSDNode *) { return true; }
856   static bool classof(const SDNode *N) {
857     return N->getOpcode() == ISD::FrameIndex ||
858            N->getOpcode() == ISD::TargetFrameIndex;
859   }
860 };
861
862 class ConstantPoolSDNode : public SDNode {
863   Constant *C;
864 protected:
865   friend class SelectionDAG;
866   ConstantPoolSDNode(Constant *c, MVT::ValueType VT, bool isTarget)
867     : SDNode(isTarget ? ISD::TargetConstantPool : ISD::ConstantPool, VT),
868     C(c) {}
869 public:
870
871   Constant *get() const { return C; }
872
873   static bool classof(const ConstantPoolSDNode *) { return true; }
874   static bool classof(const SDNode *N) {
875     return N->getOpcode() == ISD::ConstantPool ||
876            N->getOpcode() == ISD::TargetConstantPool;
877   }
878 };
879
880 class BasicBlockSDNode : public SDNode {
881   MachineBasicBlock *MBB;
882 protected:
883   friend class SelectionDAG;
884   BasicBlockSDNode(MachineBasicBlock *mbb)
885     : SDNode(ISD::BasicBlock, MVT::Other), MBB(mbb) {}
886 public:
887
888   MachineBasicBlock *getBasicBlock() const { return MBB; }
889
890   static bool classof(const BasicBlockSDNode *) { return true; }
891   static bool classof(const SDNode *N) {
892     return N->getOpcode() == ISD::BasicBlock;
893   }
894 };
895
896 class SrcValueSDNode : public SDNode {
897   const Value *V;
898   int offset;
899 protected:
900   friend class SelectionDAG;
901   SrcValueSDNode(const Value* v, int o)
902     : SDNode(ISD::SRCVALUE, MVT::Other), V(v), offset(o) {}
903
904 public:
905   const Value *getValue() const { return V; }
906   int getOffset() const { return offset; }
907
908   static bool classof(const SrcValueSDNode *) { return true; }
909   static bool classof(const SDNode *N) {
910     return N->getOpcode() == ISD::SRCVALUE;
911   }
912 };
913
914
915 class RegisterSDNode : public SDNode {
916   unsigned Reg;
917 protected:
918   friend class SelectionDAG;
919   RegisterSDNode(unsigned reg, MVT::ValueType VT)
920     : SDNode(ISD::Register, VT), Reg(reg) {}
921 public:
922
923   unsigned getReg() const { return Reg; }
924
925   static bool classof(const RegisterSDNode *) { return true; }
926   static bool classof(const SDNode *N) {
927     return N->getOpcode() == ISD::Register;
928   }
929 };
930
931 class ExternalSymbolSDNode : public SDNode {
932   const char *Symbol;
933 protected:
934   friend class SelectionDAG;
935   ExternalSymbolSDNode(const char *Sym, MVT::ValueType VT)
936     : SDNode(ISD::ExternalSymbol, VT), Symbol(Sym) {
937     }
938 public:
939
940   const char *getSymbol() const { return Symbol; }
941
942   static bool classof(const ExternalSymbolSDNode *) { return true; }
943   static bool classof(const SDNode *N) {
944     return N->getOpcode() == ISD::ExternalSymbol;
945   }
946 };
947
948 class CondCodeSDNode : public SDNode {
949   ISD::CondCode Condition;
950 protected:
951   friend class SelectionDAG;
952   CondCodeSDNode(ISD::CondCode Cond)
953     : SDNode(ISD::CONDCODE, MVT::Other), Condition(Cond) {
954   }
955 public:
956
957   ISD::CondCode get() const { return Condition; }
958
959   static bool classof(const CondCodeSDNode *) { return true; }
960   static bool classof(const SDNode *N) {
961     return N->getOpcode() == ISD::CONDCODE;
962   }
963 };
964
965 /// VTSDNode - This class is used to represent MVT::ValueType's, which are used
966 /// to parameterize some operations.
967 class VTSDNode : public SDNode {
968   MVT::ValueType ValueType;
969 protected:
970   friend class SelectionDAG;
971   VTSDNode(MVT::ValueType VT)
972     : SDNode(ISD::VALUETYPE, MVT::Other), ValueType(VT) {}
973 public:
974
975   MVT::ValueType getVT() const { return ValueType; }
976
977   static bool classof(const VTSDNode *) { return true; }
978   static bool classof(const SDNode *N) {
979     return N->getOpcode() == ISD::VALUETYPE;
980   }
981 };
982
983
984 class SDNodeIterator : public forward_iterator<SDNode, ptrdiff_t> {
985   SDNode *Node;
986   unsigned Operand;
987
988   SDNodeIterator(SDNode *N, unsigned Op) : Node(N), Operand(Op) {}
989 public:
990   bool operator==(const SDNodeIterator& x) const {
991     return Operand == x.Operand;
992   }
993   bool operator!=(const SDNodeIterator& x) const { return !operator==(x); }
994
995   const SDNodeIterator &operator=(const SDNodeIterator &I) {
996     assert(I.Node == Node && "Cannot assign iterators to two different nodes!");
997     Operand = I.Operand;
998     return *this;
999   }
1000
1001   pointer operator*() const {
1002     return Node->getOperand(Operand).Val;
1003   }
1004   pointer operator->() const { return operator*(); }
1005
1006   SDNodeIterator& operator++() {                // Preincrement
1007     ++Operand;
1008     return *this;
1009   }
1010   SDNodeIterator operator++(int) { // Postincrement
1011     SDNodeIterator tmp = *this; ++*this; return tmp;
1012   }
1013
1014   static SDNodeIterator begin(SDNode *N) { return SDNodeIterator(N, 0); }
1015   static SDNodeIterator end  (SDNode *N) {
1016     return SDNodeIterator(N, N->getNumOperands());
1017   }
1018
1019   unsigned getOperand() const { return Operand; }
1020   const SDNode *getNode() const { return Node; }
1021 };
1022
1023 template <> struct GraphTraits<SDNode*> {
1024   typedef SDNode NodeType;
1025   typedef SDNodeIterator ChildIteratorType;
1026   static inline NodeType *getEntryNode(SDNode *N) { return N; }
1027   static inline ChildIteratorType child_begin(NodeType *N) {
1028     return SDNodeIterator::begin(N);
1029   }
1030   static inline ChildIteratorType child_end(NodeType *N) {
1031     return SDNodeIterator::end(N);
1032   }
1033 };
1034
1035 } // end llvm namespace
1036
1037 #endif