Using FoldingSet in SelectionDAG::getVTList.
[oota-llvm.git] / include / llvm / CodeGen / SelectionDAG.h
1 //===-- llvm/CodeGen/SelectionDAG.h - InstSelection DAG ---------*- 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 SelectionDAG class, and transitively defines the
11 // SDNode class and subclasses.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #ifndef LLVM_CODEGEN_SELECTIONDAG_H
16 #define LLVM_CODEGEN_SELECTIONDAG_H
17
18 #include "llvm/ADT/DenseSet.h"
19 #include "llvm/ADT/StringMap.h"
20 #include "llvm/ADT/ilist.h"
21 #include "llvm/CodeGen/DAGCombine.h"
22 #include "llvm/CodeGen/SelectionDAGNodes.h"
23 #include "llvm/Support/RecyclingAllocator.h"
24 #include "llvm/Target/TargetMachine.h"
25 #include <cassert>
26 #include <map>
27 #include <string>
28 #include <vector>
29
30 namespace llvm {
31
32 class AliasAnalysis;
33 class MachineConstantPoolValue;
34 class MachineFunction;
35 class MDNode;
36 class SDDbgValue;
37 class TargetLowering;
38 class TargetSelectionDAGInfo;
39 class TargetTransformInfo;
40
41 class SDVTListNode : public FoldingSetNode {
42   friend struct FoldingSetTrait<SDVTListNode>;
43   /// FastID - A reference to an Interned FoldingSetNodeID for this node.
44   /// The Allocator in SelectionDAG holds the data.
45   /// SDVTList contains all types which are frequently accessed in SelectionDAG.
46   /// The size of this list is not expected big so it won't introduce memory penalty.
47   FoldingSetNodeIDRef FastID;
48   const EVT *VTs;
49   unsigned int NumVTs;
50   /// The hash value for SDVTList is fixed so cache it to avoid hash calculation
51   unsigned HashValue;
52 public:
53   SDVTListNode(const FoldingSetNodeIDRef ID, const EVT *VT, unsigned int Num) :
54       FastID(ID), VTs(VT), NumVTs(Num) {
55     HashValue = ID.ComputeHash();
56   }
57   SDVTList getSDVTList() {
58     SDVTList result = {VTs, NumVTs};
59     return result;
60   }
61 };
62
63 // Specialize FoldingSetTrait for SDVTListNode
64 // To avoid computing temp FoldingSetNodeID and hash value.
65 template<> struct FoldingSetTrait<SDVTListNode> : DefaultFoldingSetTrait<SDVTListNode> {
66   static void Profile(const SDVTListNode &X, FoldingSetNodeID& ID) {
67     ID = X.FastID;
68   }
69   static bool Equals(const SDVTListNode &X, const FoldingSetNodeID &ID,
70                      unsigned IDHash, FoldingSetNodeID &TempID) {
71     if (X.HashValue != IDHash)
72       return false;
73     return ID == X.FastID;
74   }
75   static unsigned ComputeHash(const SDVTListNode &X, FoldingSetNodeID &TempID) {
76     return X.HashValue;
77   }
78 };
79
80 template<> struct ilist_traits<SDNode> : public ilist_default_traits<SDNode> {
81 private:
82   mutable ilist_half_node<SDNode> Sentinel;
83 public:
84   SDNode *createSentinel() const {
85     return static_cast<SDNode*>(&Sentinel);
86   }
87   static void destroySentinel(SDNode *) {}
88
89   SDNode *provideInitialHead() const { return createSentinel(); }
90   SDNode *ensureHead(SDNode*) const { return createSentinel(); }
91   static void noteHead(SDNode*, SDNode*) {}
92
93   static void deleteNode(SDNode *) {
94     llvm_unreachable("ilist_traits<SDNode> shouldn't see a deleteNode call!");
95   }
96 private:
97   static void createNode(const SDNode &);
98 };
99
100 /// SDDbgInfo - Keeps track of dbg_value information through SDISel.  We do
101 /// not build SDNodes for these so as not to perturb the generated code;
102 /// instead the info is kept off to the side in this structure. Each SDNode may
103 /// have one or more associated dbg_value entries. This information is kept in
104 /// DbgValMap.
105 /// Byval parameters are handled separately because they don't use alloca's,
106 /// which busts the normal mechanism.  There is good reason for handling all
107 /// parameters separately:  they may not have code generated for them, they
108 /// should always go at the beginning of the function regardless of other code
109 /// motion, and debug info for them is potentially useful even if the parameter
110 /// is unused.  Right now only byval parameters are handled separately.
111 class SDDbgInfo {
112   SmallVector<SDDbgValue*, 32> DbgValues;
113   SmallVector<SDDbgValue*, 32> ByvalParmDbgValues;
114   typedef DenseMap<const SDNode*, SmallVector<SDDbgValue*, 2> > DbgValMapType;
115   DbgValMapType DbgValMap;
116
117   void operator=(const SDDbgInfo&) LLVM_DELETED_FUNCTION;
118   SDDbgInfo(const SDDbgInfo&) LLVM_DELETED_FUNCTION;
119 public:
120   SDDbgInfo() {}
121
122   void add(SDDbgValue *V, const SDNode *Node, bool isParameter) {
123     if (isParameter) {
124       ByvalParmDbgValues.push_back(V);
125     } else     DbgValues.push_back(V);
126     if (Node)
127       DbgValMap[Node].push_back(V);
128   }
129
130   void clear() {
131     DbgValMap.clear();
132     DbgValues.clear();
133     ByvalParmDbgValues.clear();
134   }
135
136   bool empty() const {
137     return DbgValues.empty() && ByvalParmDbgValues.empty();
138   }
139
140   ArrayRef<SDDbgValue*> getSDDbgValues(const SDNode *Node) {
141     DbgValMapType::iterator I = DbgValMap.find(Node);
142     if (I != DbgValMap.end())
143       return I->second;
144     return ArrayRef<SDDbgValue*>();
145   }
146
147   typedef SmallVectorImpl<SDDbgValue*>::iterator DbgIterator;
148   DbgIterator DbgBegin() { return DbgValues.begin(); }
149   DbgIterator DbgEnd()   { return DbgValues.end(); }
150   DbgIterator ByvalParmDbgBegin() { return ByvalParmDbgValues.begin(); }
151   DbgIterator ByvalParmDbgEnd()   { return ByvalParmDbgValues.end(); }
152 };
153
154 class SelectionDAG;
155 void checkForCycles(const SDNode *N);
156 void checkForCycles(const SelectionDAG *DAG);
157
158 /// SelectionDAG class - This is used to represent a portion of an LLVM function
159 /// in a low-level Data Dependence DAG representation suitable for instruction
160 /// selection.  This DAG is constructed as the first step of instruction
161 /// selection in order to allow implementation of machine specific optimizations
162 /// and code simplifications.
163 ///
164 /// The representation used by the SelectionDAG is a target-independent
165 /// representation, which has some similarities to the GCC RTL representation,
166 /// but is significantly more simple, powerful, and is a graph form instead of a
167 /// linear form.
168 ///
169 class SelectionDAG {
170   const TargetMachine &TM;
171   const TargetSelectionDAGInfo &TSI;
172   const TargetTransformInfo *TTI;
173   MachineFunction *MF;
174   LLVMContext *Context;
175   CodeGenOpt::Level OptLevel;
176
177   /// EntryNode - The starting token.
178   SDNode EntryNode;
179
180   /// Root - The root of the entire DAG.
181   SDValue Root;
182
183   /// AllNodes - A linked list of nodes in the current DAG.
184   ilist<SDNode> AllNodes;
185
186   /// NodeAllocatorType - The AllocatorType for allocating SDNodes. We use
187   /// pool allocation with recycling.
188   typedef RecyclingAllocator<BumpPtrAllocator, SDNode, sizeof(LargestSDNode),
189                              AlignOf<MostAlignedSDNode>::Alignment>
190     NodeAllocatorType;
191
192   /// NodeAllocator - Pool allocation for nodes.
193   NodeAllocatorType NodeAllocator;
194
195   /// CSEMap - This structure is used to memoize nodes, automatically performing
196   /// CSE with existing nodes when a duplicate is requested.
197   FoldingSet<SDNode> CSEMap;
198
199   /// OperandAllocator - Pool allocation for machine-opcode SDNode operands.
200   BumpPtrAllocator OperandAllocator;
201
202   /// Allocator - Pool allocation for misc. objects that are created once per
203   /// SelectionDAG.
204   BumpPtrAllocator Allocator;
205
206   /// DbgInfo - Tracks dbg_value information through SDISel.
207   SDDbgInfo *DbgInfo;
208
209 public:
210   /// DAGUpdateListener - Clients of various APIs that cause global effects on
211   /// the DAG can optionally implement this interface.  This allows the clients
212   /// to handle the various sorts of updates that happen.
213   ///
214   /// A DAGUpdateListener automatically registers itself with DAG when it is
215   /// constructed, and removes itself when destroyed in RAII fashion.
216   struct DAGUpdateListener {
217     DAGUpdateListener *const Next;
218     SelectionDAG &DAG;
219
220     explicit DAGUpdateListener(SelectionDAG &D)
221       : Next(D.UpdateListeners), DAG(D) {
222       DAG.UpdateListeners = this;
223     }
224
225     virtual ~DAGUpdateListener() {
226       assert(DAG.UpdateListeners == this &&
227              "DAGUpdateListeners must be destroyed in LIFO order");
228       DAG.UpdateListeners = Next;
229     }
230
231     /// NodeDeleted - The node N that was deleted and, if E is not null, an
232     /// equivalent node E that replaced it.
233     virtual void NodeDeleted(SDNode *N, SDNode *E);
234
235     /// NodeUpdated - The node N that was updated.
236     virtual void NodeUpdated(SDNode *N);
237   };
238
239 private:
240   /// DAGUpdateListener is a friend so it can manipulate the listener stack.
241   friend struct DAGUpdateListener;
242
243   /// UpdateListeners - Linked list of registered DAGUpdateListener instances.
244   /// This stack is maintained by DAGUpdateListener RAII.
245   DAGUpdateListener *UpdateListeners;
246
247   /// setGraphColorHelper - Implementation of setSubgraphColor.
248   /// Return whether we had to truncate the search.
249   ///
250   bool setSubgraphColorHelper(SDNode *N, const char *Color,
251                               DenseSet<SDNode *> &visited,
252                               int level, bool &printed);
253
254   void operator=(const SelectionDAG&) LLVM_DELETED_FUNCTION;
255   SelectionDAG(const SelectionDAG&) LLVM_DELETED_FUNCTION;
256
257 public:
258   explicit SelectionDAG(const TargetMachine &TM, llvm::CodeGenOpt::Level);
259   ~SelectionDAG();
260
261   /// init - Prepare this SelectionDAG to process code in the given
262   /// MachineFunction.
263   ///
264   void init(MachineFunction &mf, const TargetTransformInfo *TTI);
265
266   /// clear - Clear state and free memory necessary to make this
267   /// SelectionDAG ready to process a new block.
268   ///
269   void clear();
270
271   MachineFunction &getMachineFunction() const { return *MF; }
272   const TargetMachine &getTarget() const { return TM; }
273   const TargetLowering &getTargetLoweringInfo() const {
274     return *TM.getTargetLowering();
275   }
276   const TargetSelectionDAGInfo &getSelectionDAGInfo() const { return TSI; }
277   const TargetTransformInfo *getTargetTransformInfo() const { return TTI; }
278   LLVMContext *getContext() const {return Context; }
279
280   /// viewGraph - Pop up a GraphViz/gv window with the DAG rendered using 'dot'.
281   ///
282   void viewGraph(const std::string &Title);
283   void viewGraph();
284
285 #ifndef NDEBUG
286   std::map<const SDNode *, std::string> NodeGraphAttrs;
287 #endif
288
289   /// clearGraphAttrs - Clear all previously defined node graph attributes.
290   /// Intended to be used from a debugging tool (eg. gdb).
291   void clearGraphAttrs();
292
293   /// setGraphAttrs - Set graph attributes for a node. (eg. "color=red".)
294   ///
295   void setGraphAttrs(const SDNode *N, const char *Attrs);
296
297   /// getGraphAttrs - Get graph attributes for a node. (eg. "color=red".)
298   /// Used from getNodeAttributes.
299   const std::string getGraphAttrs(const SDNode *N) const;
300
301   /// setGraphColor - Convenience for setting node color attribute.
302   ///
303   void setGraphColor(const SDNode *N, const char *Color);
304
305   /// setGraphColor - Convenience for setting subgraph color attribute.
306   ///
307   void setSubgraphColor(SDNode *N, const char *Color);
308
309   typedef ilist<SDNode>::const_iterator allnodes_const_iterator;
310   allnodes_const_iterator allnodes_begin() const { return AllNodes.begin(); }
311   allnodes_const_iterator allnodes_end() const { return AllNodes.end(); }
312   typedef ilist<SDNode>::iterator allnodes_iterator;
313   allnodes_iterator allnodes_begin() { return AllNodes.begin(); }
314   allnodes_iterator allnodes_end() { return AllNodes.end(); }
315   ilist<SDNode>::size_type allnodes_size() const {
316     return AllNodes.size();
317   }
318
319   /// getRoot - Return the root tag of the SelectionDAG.
320   ///
321   const SDValue &getRoot() const { return Root; }
322
323   /// getEntryNode - Return the token chain corresponding to the entry of the
324   /// function.
325   SDValue getEntryNode() const {
326     return SDValue(const_cast<SDNode *>(&EntryNode), 0);
327   }
328
329   /// setRoot - Set the current root tag of the SelectionDAG.
330   ///
331   const SDValue &setRoot(SDValue N) {
332     assert((!N.getNode() || N.getValueType() == MVT::Other) &&
333            "DAG root value is not a chain!");
334     if (N.getNode())
335       checkForCycles(N.getNode());
336     Root = N;
337     if (N.getNode())
338       checkForCycles(this);
339     return Root;
340   }
341
342   /// Combine - This iterates over the nodes in the SelectionDAG, folding
343   /// certain types of nodes together, or eliminating superfluous nodes.  The
344   /// Level argument controls whether Combine is allowed to produce nodes and
345   /// types that are illegal on the target.
346   void Combine(CombineLevel Level, AliasAnalysis &AA,
347                CodeGenOpt::Level OptLevel);
348
349   /// LegalizeTypes - This transforms the SelectionDAG into a SelectionDAG that
350   /// only uses types natively supported by the target.  Returns "true" if it
351   /// made any changes.
352   ///
353   /// Note that this is an involved process that may invalidate pointers into
354   /// the graph.
355   bool LegalizeTypes();
356
357   /// Legalize - This transforms the SelectionDAG into a SelectionDAG that is
358   /// compatible with the target instruction selector, as indicated by the
359   /// TargetLowering object.
360   ///
361   /// Note that this is an involved process that may invalidate pointers into
362   /// the graph.
363   void Legalize();
364
365   /// LegalizeVectors - This transforms the SelectionDAG into a SelectionDAG
366   /// that only uses vector math operations supported by the target.  This is
367   /// necessary as a separate step from Legalize because unrolling a vector
368   /// operation can introduce illegal types, which requires running
369   /// LegalizeTypes again.
370   ///
371   /// This returns true if it made any changes; in that case, LegalizeTypes
372   /// is called again before Legalize.
373   ///
374   /// Note that this is an involved process that may invalidate pointers into
375   /// the graph.
376   bool LegalizeVectors();
377
378   /// RemoveDeadNodes - This method deletes all unreachable nodes in the
379   /// SelectionDAG.
380   void RemoveDeadNodes();
381
382   /// DeleteNode - Remove the specified node from the system.  This node must
383   /// have no referrers.
384   void DeleteNode(SDNode *N);
385
386   /// getVTList - Return an SDVTList that represents the list of values
387   /// specified.
388   SDVTList getVTList(EVT VT);
389   SDVTList getVTList(EVT VT1, EVT VT2);
390   SDVTList getVTList(EVT VT1, EVT VT2, EVT VT3);
391   SDVTList getVTList(EVT VT1, EVT VT2, EVT VT3, EVT VT4);
392   SDVTList getVTList(const EVT *VTs, unsigned NumVTs);
393
394   //===--------------------------------------------------------------------===//
395   // Node creation methods.
396   //
397   SDValue getConstant(uint64_t Val, EVT VT, bool isTarget = false);
398   SDValue getConstant(const APInt &Val, EVT VT, bool isTarget = false);
399   SDValue getConstant(const ConstantInt &Val, EVT VT, bool isTarget = false);
400   SDValue getIntPtrConstant(uint64_t Val, bool isTarget = false);
401   SDValue getTargetConstant(uint64_t Val, EVT VT) {
402     return getConstant(Val, VT, true);
403   }
404   SDValue getTargetConstant(const APInt &Val, EVT VT) {
405     return getConstant(Val, VT, true);
406   }
407   SDValue getTargetConstant(const ConstantInt &Val, EVT VT) {
408     return getConstant(Val, VT, true);
409   }
410   // The forms below that take a double should only be used for simple
411   // constants that can be exactly represented in VT.  No checks are made.
412   SDValue getConstantFP(double Val, EVT VT, bool isTarget = false);
413   SDValue getConstantFP(const APFloat& Val, EVT VT, bool isTarget = false);
414   SDValue getConstantFP(const ConstantFP &CF, EVT VT, bool isTarget = false);
415   SDValue getTargetConstantFP(double Val, EVT VT) {
416     return getConstantFP(Val, VT, true);
417   }
418   SDValue getTargetConstantFP(const APFloat& Val, EVT VT) {
419     return getConstantFP(Val, VT, true);
420   }
421   SDValue getTargetConstantFP(const ConstantFP &Val, EVT VT) {
422     return getConstantFP(Val, VT, true);
423   }
424   SDValue getGlobalAddress(const GlobalValue *GV, SDLoc DL, EVT VT,
425                            int64_t offset = 0, bool isTargetGA = false,
426                            unsigned char TargetFlags = 0);
427   SDValue getTargetGlobalAddress(const GlobalValue *GV, SDLoc DL, EVT VT,
428                                  int64_t offset = 0,
429                                  unsigned char TargetFlags = 0) {
430     return getGlobalAddress(GV, DL, VT, offset, true, TargetFlags);
431   }
432   SDValue getFrameIndex(int FI, EVT VT, bool isTarget = false);
433   SDValue getTargetFrameIndex(int FI, EVT VT) {
434     return getFrameIndex(FI, VT, true);
435   }
436   SDValue getJumpTable(int JTI, EVT VT, bool isTarget = false,
437                        unsigned char TargetFlags = 0);
438   SDValue getTargetJumpTable(int JTI, EVT VT, unsigned char TargetFlags = 0) {
439     return getJumpTable(JTI, VT, true, TargetFlags);
440   }
441   SDValue getConstantPool(const Constant *C, EVT VT,
442                           unsigned Align = 0, int Offs = 0, bool isT=false,
443                           unsigned char TargetFlags = 0);
444   SDValue getTargetConstantPool(const Constant *C, EVT VT,
445                                 unsigned Align = 0, int Offset = 0,
446                                 unsigned char TargetFlags = 0) {
447     return getConstantPool(C, VT, Align, Offset, true, TargetFlags);
448   }
449   SDValue getConstantPool(MachineConstantPoolValue *C, EVT VT,
450                           unsigned Align = 0, int Offs = 0, bool isT=false,
451                           unsigned char TargetFlags = 0);
452   SDValue getTargetConstantPool(MachineConstantPoolValue *C,
453                                   EVT VT, unsigned Align = 0,
454                                   int Offset = 0, unsigned char TargetFlags=0) {
455     return getConstantPool(C, VT, Align, Offset, true, TargetFlags);
456   }
457   SDValue getTargetIndex(int Index, EVT VT, int64_t Offset = 0,
458                          unsigned char TargetFlags = 0);
459   // When generating a branch to a BB, we don't in general know enough
460   // to provide debug info for the BB at that time, so keep this one around.
461   SDValue getBasicBlock(MachineBasicBlock *MBB);
462   SDValue getBasicBlock(MachineBasicBlock *MBB, SDLoc dl);
463   SDValue getExternalSymbol(const char *Sym, EVT VT);
464   SDValue getExternalSymbol(const char *Sym, SDLoc dl, EVT VT);
465   SDValue getTargetExternalSymbol(const char *Sym, EVT VT,
466                                   unsigned char TargetFlags = 0);
467   SDValue getValueType(EVT);
468   SDValue getRegister(unsigned Reg, EVT VT);
469   SDValue getRegisterMask(const uint32_t *RegMask);
470   SDValue getEHLabel(SDLoc dl, SDValue Root, MCSymbol *Label);
471   SDValue getBlockAddress(const BlockAddress *BA, EVT VT,
472                           int64_t Offset = 0, bool isTarget = false,
473                           unsigned char TargetFlags = 0);
474   SDValue getTargetBlockAddress(const BlockAddress *BA, EVT VT,
475                                 int64_t Offset = 0,
476                                 unsigned char TargetFlags = 0) {
477     return getBlockAddress(BA, VT, Offset, true, TargetFlags);
478   }
479
480   SDValue getCopyToReg(SDValue Chain, SDLoc dl, unsigned Reg, SDValue N) {
481     return getNode(ISD::CopyToReg, dl, MVT::Other, Chain,
482                    getRegister(Reg, N.getValueType()), N);
483   }
484
485   // This version of the getCopyToReg method takes an extra operand, which
486   // indicates that there is potentially an incoming glue value (if Glue is not
487   // null) and that there should be a glue result.
488   SDValue getCopyToReg(SDValue Chain, SDLoc dl, unsigned Reg, SDValue N,
489                        SDValue Glue) {
490     SDVTList VTs = getVTList(MVT::Other, MVT::Glue);
491     SDValue Ops[] = { Chain, getRegister(Reg, N.getValueType()), N, Glue };
492     return getNode(ISD::CopyToReg, dl, VTs, Ops, Glue.getNode() ? 4 : 3);
493   }
494
495   // Similar to last getCopyToReg() except parameter Reg is a SDValue
496   SDValue getCopyToReg(SDValue Chain, SDLoc dl, SDValue Reg, SDValue N,
497                          SDValue Glue) {
498     SDVTList VTs = getVTList(MVT::Other, MVT::Glue);
499     SDValue Ops[] = { Chain, Reg, N, Glue };
500     return getNode(ISD::CopyToReg, dl, VTs, Ops, Glue.getNode() ? 4 : 3);
501   }
502
503   SDValue getCopyFromReg(SDValue Chain, SDLoc dl, unsigned Reg, EVT VT) {
504     SDVTList VTs = getVTList(VT, MVT::Other);
505     SDValue Ops[] = { Chain, getRegister(Reg, VT) };
506     return getNode(ISD::CopyFromReg, dl, VTs, Ops, 2);
507   }
508
509   // This version of the getCopyFromReg method takes an extra operand, which
510   // indicates that there is potentially an incoming glue value (if Glue is not
511   // null) and that there should be a glue result.
512   SDValue getCopyFromReg(SDValue Chain, SDLoc dl, unsigned Reg, EVT VT,
513                            SDValue Glue) {
514     SDVTList VTs = getVTList(VT, MVT::Other, MVT::Glue);
515     SDValue Ops[] = { Chain, getRegister(Reg, VT), Glue };
516     return getNode(ISD::CopyFromReg, dl, VTs, Ops, Glue.getNode() ? 3 : 2);
517   }
518
519   SDValue getCondCode(ISD::CondCode Cond);
520
521   /// Returns the ConvertRndSat Note: Avoid using this node because it may
522   /// disappear in the future and most targets don't support it.
523   SDValue getConvertRndSat(EVT VT, SDLoc dl, SDValue Val, SDValue DTy,
524                            SDValue STy,
525                            SDValue Rnd, SDValue Sat, ISD::CvtCode Code);
526
527   /// getVectorShuffle - Return an ISD::VECTOR_SHUFFLE node.  The number of
528   /// elements in VT, which must be a vector type, must match the number of
529   /// mask elements NumElts.  A integer mask element equal to -1 is treated as
530   /// undefined.
531   SDValue getVectorShuffle(EVT VT, SDLoc dl, SDValue N1, SDValue N2,
532                            const int *MaskElts);
533
534   /// getAnyExtOrTrunc - Convert Op, which must be of integer type, to the
535   /// integer type VT, by either any-extending or truncating it.
536   SDValue getAnyExtOrTrunc(SDValue Op, SDLoc DL, EVT VT);
537
538   /// getSExtOrTrunc - Convert Op, which must be of integer type, to the
539   /// integer type VT, by either sign-extending or truncating it.
540   SDValue getSExtOrTrunc(SDValue Op, SDLoc DL, EVT VT);
541
542   /// getZExtOrTrunc - Convert Op, which must be of integer type, to the
543   /// integer type VT, by either zero-extending or truncating it.
544   SDValue getZExtOrTrunc(SDValue Op, SDLoc DL, EVT VT);
545
546   /// getZeroExtendInReg - Return the expression required to zero extend the Op
547   /// value assuming it was the smaller SrcTy value.
548   SDValue getZeroExtendInReg(SDValue Op, SDLoc DL, EVT SrcTy);
549
550   /// getNOT - Create a bitwise NOT operation as (XOR Val, -1).
551   SDValue getNOT(SDLoc DL, SDValue Val, EVT VT);
552
553   /// getCALLSEQ_START - Return a new CALLSEQ_START node, which always must have
554   /// a glue result (to ensure it's not CSE'd).  CALLSEQ_START does not have a
555   /// useful SDLoc.
556   SDValue getCALLSEQ_START(SDValue Chain, SDValue Op, SDLoc DL) {
557     SDVTList VTs = getVTList(MVT::Other, MVT::Glue);
558     SDValue Ops[] = { Chain,  Op };
559     return getNode(ISD::CALLSEQ_START, DL, VTs, Ops, 2);
560   }
561
562   /// getCALLSEQ_END - Return a new CALLSEQ_END node, which always must have a
563   /// glue result (to ensure it's not CSE'd).  CALLSEQ_END does not have
564   /// a useful SDLoc.
565   SDValue getCALLSEQ_END(SDValue Chain, SDValue Op1, SDValue Op2,
566                            SDValue InGlue, SDLoc DL) {
567     SDVTList NodeTys = getVTList(MVT::Other, MVT::Glue);
568     SmallVector<SDValue, 4> Ops;
569     Ops.push_back(Chain);
570     Ops.push_back(Op1);
571     Ops.push_back(Op2);
572     Ops.push_back(InGlue);
573     return getNode(ISD::CALLSEQ_END, DL, NodeTys, &Ops[0],
574                    (unsigned)Ops.size() - (InGlue.getNode() == 0 ? 1 : 0));
575   }
576
577   /// getUNDEF - Return an UNDEF node.  UNDEF does not have a useful SDLoc.
578   SDValue getUNDEF(EVT VT) {
579     return getNode(ISD::UNDEF, SDLoc(), VT);
580   }
581
582   /// getGLOBAL_OFFSET_TABLE - Return a GLOBAL_OFFSET_TABLE node.  This does
583   /// not have a useful SDLoc.
584   SDValue getGLOBAL_OFFSET_TABLE(EVT VT) {
585     return getNode(ISD::GLOBAL_OFFSET_TABLE, SDLoc(), VT);
586   }
587
588   /// getNode - Gets or creates the specified node.
589   ///
590   SDValue getNode(unsigned Opcode, SDLoc DL, EVT VT);
591   SDValue getNode(unsigned Opcode, SDLoc DL, EVT VT, SDValue N);
592   SDValue getNode(unsigned Opcode, SDLoc DL, EVT VT, SDValue N1, SDValue N2);
593   SDValue getNode(unsigned Opcode, SDLoc DL, EVT VT,
594                   SDValue N1, SDValue N2, SDValue N3);
595   SDValue getNode(unsigned Opcode, SDLoc DL, EVT VT,
596                   SDValue N1, SDValue N2, SDValue N3, SDValue N4);
597   SDValue getNode(unsigned Opcode, SDLoc DL, EVT VT,
598                   SDValue N1, SDValue N2, SDValue N3, SDValue N4,
599                   SDValue N5);
600   SDValue getNode(unsigned Opcode, SDLoc DL, EVT VT,
601                   const SDUse *Ops, unsigned NumOps);
602   SDValue getNode(unsigned Opcode, SDLoc DL, EVT VT,
603                   const SDValue *Ops, unsigned NumOps);
604   SDValue getNode(unsigned Opcode, SDLoc DL,
605                   ArrayRef<EVT> ResultTys,
606                   const SDValue *Ops, unsigned NumOps);
607   SDValue getNode(unsigned Opcode, SDLoc DL, const EVT *VTs, unsigned NumVTs,
608                   const SDValue *Ops, unsigned NumOps);
609   SDValue getNode(unsigned Opcode, SDLoc DL, SDVTList VTs,
610                   const SDValue *Ops, unsigned NumOps);
611   SDValue getNode(unsigned Opcode, SDLoc DL, SDVTList VTs);
612   SDValue getNode(unsigned Opcode, SDLoc DL, SDVTList VTs, SDValue N);
613   SDValue getNode(unsigned Opcode, SDLoc DL, SDVTList VTs,
614                   SDValue N1, SDValue N2);
615   SDValue getNode(unsigned Opcode, SDLoc DL, SDVTList VTs,
616                   SDValue N1, SDValue N2, SDValue N3);
617   SDValue getNode(unsigned Opcode, SDLoc DL, SDVTList VTs,
618                   SDValue N1, SDValue N2, SDValue N3, SDValue N4);
619   SDValue getNode(unsigned Opcode, SDLoc DL, SDVTList VTs,
620                   SDValue N1, SDValue N2, SDValue N3, SDValue N4,
621                   SDValue N5);
622
623   /// getStackArgumentTokenFactor - Compute a TokenFactor to force all
624   /// the incoming stack arguments to be loaded from the stack. This is
625   /// used in tail call lowering to protect stack arguments from being
626   /// clobbered.
627   SDValue getStackArgumentTokenFactor(SDValue Chain);
628
629   SDValue getMemcpy(SDValue Chain, SDLoc dl, SDValue Dst, SDValue Src,
630                     SDValue Size, unsigned Align, bool isVol, bool AlwaysInline,
631                     MachinePointerInfo DstPtrInfo,
632                     MachinePointerInfo SrcPtrInfo);
633
634   SDValue getMemmove(SDValue Chain, SDLoc dl, SDValue Dst, SDValue Src,
635                      SDValue Size, unsigned Align, bool isVol,
636                      MachinePointerInfo DstPtrInfo,
637                      MachinePointerInfo SrcPtrInfo);
638
639   SDValue getMemset(SDValue Chain, SDLoc dl, SDValue Dst, SDValue Src,
640                     SDValue Size, unsigned Align, bool isVol,
641                     MachinePointerInfo DstPtrInfo);
642
643   /// getSetCC - Helper function to make it easier to build SetCC's if you just
644   /// have an ISD::CondCode instead of an SDValue.
645   ///
646   SDValue getSetCC(SDLoc DL, EVT VT, SDValue LHS, SDValue RHS,
647                    ISD::CondCode Cond) {
648     assert(LHS.getValueType().isVector() == RHS.getValueType().isVector() &&
649       "Cannot compare scalars to vectors");
650     assert(LHS.getValueType().isVector() == VT.isVector() &&
651       "Cannot compare scalars to vectors");
652     assert(Cond != ISD::SETCC_INVALID &&
653         "Cannot create a setCC of an invalid node.");
654     return getNode(ISD::SETCC, DL, VT, LHS, RHS, getCondCode(Cond));
655   }
656
657   // getSelect - Helper function to make it easier to build Select's if you just
658   // have operands and don't want to check for vector.
659   SDValue getSelect(SDLoc DL, EVT VT, SDValue Cond,
660                     SDValue LHS, SDValue RHS) {
661     assert(LHS.getValueType() == RHS.getValueType() &&
662            "Cannot use select on differing types");
663     assert(VT.isVector() == LHS.getValueType().isVector() &&
664            "Cannot mix vectors and scalars");
665     return getNode(Cond.getValueType().isVector() ? ISD::VSELECT : ISD::SELECT, DL, VT,
666                    Cond, LHS, RHS);
667   }
668
669   /// getSelectCC - Helper function to make it easier to build SelectCC's if you
670   /// just have an ISD::CondCode instead of an SDValue.
671   ///
672   SDValue getSelectCC(SDLoc DL, SDValue LHS, SDValue RHS,
673                       SDValue True, SDValue False, ISD::CondCode Cond) {
674     return getNode(ISD::SELECT_CC, DL, True.getValueType(),
675                    LHS, RHS, True, False, getCondCode(Cond));
676   }
677
678   /// getVAArg - VAArg produces a result and token chain, and takes a pointer
679   /// and a source value as input.
680   SDValue getVAArg(EVT VT, SDLoc dl, SDValue Chain, SDValue Ptr,
681                    SDValue SV, unsigned Align);
682
683   /// getAtomic - Gets a node for an atomic op, produces result and chain and
684   /// takes 3 operands
685   SDValue getAtomic(unsigned Opcode, SDLoc dl, EVT MemVT, SDValue Chain,
686                     SDValue Ptr, SDValue Cmp, SDValue Swp,
687                     MachinePointerInfo PtrInfo, unsigned Alignment,
688                     AtomicOrdering Ordering,
689                     SynchronizationScope SynchScope);
690   SDValue getAtomic(unsigned Opcode, SDLoc dl, EVT MemVT, SDValue Chain,
691                     SDValue Ptr, SDValue Cmp, SDValue Swp,
692                     MachineMemOperand *MMO,
693                     AtomicOrdering Ordering,
694                     SynchronizationScope SynchScope);
695
696   /// getAtomic - Gets a node for an atomic op, produces result (if relevant)
697   /// and chain and takes 2 operands.
698   SDValue getAtomic(unsigned Opcode, SDLoc dl, EVT MemVT, SDValue Chain,
699                     SDValue Ptr, SDValue Val, const Value* PtrVal,
700                     unsigned Alignment, AtomicOrdering Ordering,
701                     SynchronizationScope SynchScope);
702   SDValue getAtomic(unsigned Opcode, SDLoc dl, EVT MemVT, SDValue Chain,
703                     SDValue Ptr, SDValue Val, MachineMemOperand *MMO,
704                     AtomicOrdering Ordering,
705                     SynchronizationScope SynchScope);
706
707   /// getAtomic - Gets a node for an atomic op, produces result and chain and
708   /// takes 1 operand.
709   SDValue getAtomic(unsigned Opcode, SDLoc dl, EVT MemVT, EVT VT,
710                     SDValue Chain, SDValue Ptr, const Value* PtrVal,
711                     unsigned Alignment,
712                     AtomicOrdering Ordering,
713                     SynchronizationScope SynchScope);
714   SDValue getAtomic(unsigned Opcode, SDLoc dl, EVT MemVT, EVT VT,
715                     SDValue Chain, SDValue Ptr, MachineMemOperand *MMO,
716                     AtomicOrdering Ordering,
717                     SynchronizationScope SynchScope);
718
719   /// getAtomic - Gets a node for an atomic op, produces result and chain and
720   /// takes N operands.
721   SDValue getAtomic(unsigned Opcode, SDLoc dl, EVT MemVT, SDVTList VTList,
722                     SDValue* Ops, unsigned NumOps, MachineMemOperand *MMO,
723                     AtomicOrdering Ordering,
724                     SynchronizationScope SynchScope);
725
726   /// getMemIntrinsicNode - Creates a MemIntrinsicNode that may produce a
727   /// result and takes a list of operands. Opcode may be INTRINSIC_VOID,
728   /// INTRINSIC_W_CHAIN, or a target-specific opcode with a value not
729   /// less than FIRST_TARGET_MEMORY_OPCODE.
730   SDValue getMemIntrinsicNode(unsigned Opcode, SDLoc dl,
731                               const EVT *VTs, unsigned NumVTs,
732                               const SDValue *Ops, unsigned NumOps,
733                               EVT MemVT, MachinePointerInfo PtrInfo,
734                               unsigned Align = 0, bool Vol = false,
735                               bool ReadMem = true, bool WriteMem = true);
736
737   SDValue getMemIntrinsicNode(unsigned Opcode, SDLoc dl, SDVTList VTList,
738                               const SDValue *Ops, unsigned NumOps,
739                               EVT MemVT, MachinePointerInfo PtrInfo,
740                               unsigned Align = 0, bool Vol = false,
741                               bool ReadMem = true, bool WriteMem = true);
742
743   SDValue getMemIntrinsicNode(unsigned Opcode, SDLoc dl, SDVTList VTList,
744                               const SDValue *Ops, unsigned NumOps,
745                               EVT MemVT, MachineMemOperand *MMO);
746
747   /// getMergeValues - Create a MERGE_VALUES node from the given operands.
748   SDValue getMergeValues(const SDValue *Ops, unsigned NumOps, SDLoc dl);
749
750   /// getLoad - Loads are not normal binary operators: their result type is not
751   /// determined by their operands, and they produce a value AND a token chain.
752   ///
753   SDValue getLoad(EVT VT, SDLoc dl, SDValue Chain, SDValue Ptr,
754                   MachinePointerInfo PtrInfo, bool isVolatile,
755                   bool isNonTemporal, bool isInvariant, unsigned Alignment,
756                   const MDNode *TBAAInfo = 0, const MDNode *Ranges = 0);
757   SDValue getExtLoad(ISD::LoadExtType ExtType, SDLoc dl, EVT VT,
758                      SDValue Chain, SDValue Ptr, MachinePointerInfo PtrInfo,
759                      EVT MemVT, bool isVolatile,
760                      bool isNonTemporal, unsigned Alignment,
761                      const MDNode *TBAAInfo = 0);
762   SDValue getIndexedLoad(SDValue OrigLoad, SDLoc dl, SDValue Base,
763                          SDValue Offset, ISD::MemIndexedMode AM);
764   SDValue getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType,
765                   EVT VT, SDLoc dl,
766                   SDValue Chain, SDValue Ptr, SDValue Offset,
767                   MachinePointerInfo PtrInfo, EVT MemVT,
768                   bool isVolatile, bool isNonTemporal, bool isInvariant,
769                   unsigned Alignment, const MDNode *TBAAInfo = 0,
770                   const MDNode *Ranges = 0);
771   SDValue getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType,
772                   EVT VT, SDLoc dl,
773                   SDValue Chain, SDValue Ptr, SDValue Offset,
774                   EVT MemVT, MachineMemOperand *MMO);
775
776   /// getStore - Helper function to build ISD::STORE nodes.
777   ///
778   SDValue getStore(SDValue Chain, SDLoc dl, SDValue Val, SDValue Ptr,
779                    MachinePointerInfo PtrInfo, bool isVolatile,
780                    bool isNonTemporal, unsigned Alignment,
781                    const MDNode *TBAAInfo = 0);
782   SDValue getStore(SDValue Chain, SDLoc dl, SDValue Val, SDValue Ptr,
783                    MachineMemOperand *MMO);
784   SDValue getTruncStore(SDValue Chain, SDLoc dl, SDValue Val, SDValue Ptr,
785                         MachinePointerInfo PtrInfo, EVT TVT,
786                         bool isNonTemporal, bool isVolatile,
787                         unsigned Alignment,
788                         const MDNode *TBAAInfo = 0);
789   SDValue getTruncStore(SDValue Chain, SDLoc dl, SDValue Val, SDValue Ptr,
790                         EVT TVT, MachineMemOperand *MMO);
791   SDValue getIndexedStore(SDValue OrigStoe, SDLoc dl, SDValue Base,
792                            SDValue Offset, ISD::MemIndexedMode AM);
793
794   /// getSrcValue - Construct a node to track a Value* through the backend.
795   SDValue getSrcValue(const Value *v);
796
797   /// getMDNode - Return an MDNodeSDNode which holds an MDNode.
798   SDValue getMDNode(const MDNode *MD);
799
800   /// getShiftAmountOperand - Return the specified value casted to
801   /// the target's desired shift amount type.
802   SDValue getShiftAmountOperand(EVT LHSTy, SDValue Op);
803
804   /// UpdateNodeOperands - *Mutate* the specified node in-place to have the
805   /// specified operands.  If the resultant node already exists in the DAG,
806   /// this does not modify the specified node, instead it returns the node that
807   /// already exists.  If the resultant node does not exist in the DAG, the
808   /// input node is returned.  As a degenerate case, if you specify the same
809   /// input operands as the node already has, the input node is returned.
810   SDNode *UpdateNodeOperands(SDNode *N, SDValue Op);
811   SDNode *UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2);
812   SDNode *UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2,
813                                SDValue Op3);
814   SDNode *UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2,
815                                SDValue Op3, SDValue Op4);
816   SDNode *UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2,
817                                SDValue Op3, SDValue Op4, SDValue Op5);
818   SDNode *UpdateNodeOperands(SDNode *N,
819                                const SDValue *Ops, unsigned NumOps);
820
821   /// SelectNodeTo - These are used for target selectors to *mutate* the
822   /// specified node to have the specified return type, Target opcode, and
823   /// operands.  Note that target opcodes are stored as
824   /// ~TargetOpcode in the node opcode field.  The resultant node is returned.
825   SDNode *SelectNodeTo(SDNode *N, unsigned TargetOpc, EVT VT);
826   SDNode *SelectNodeTo(SDNode *N, unsigned TargetOpc, EVT VT, SDValue Op1);
827   SDNode *SelectNodeTo(SDNode *N, unsigned TargetOpc, EVT VT,
828                        SDValue Op1, SDValue Op2);
829   SDNode *SelectNodeTo(SDNode *N, unsigned TargetOpc, EVT VT,
830                        SDValue Op1, SDValue Op2, SDValue Op3);
831   SDNode *SelectNodeTo(SDNode *N, unsigned TargetOpc, EVT VT,
832                        const SDValue *Ops, unsigned NumOps);
833   SDNode *SelectNodeTo(SDNode *N, unsigned TargetOpc, EVT VT1, EVT VT2);
834   SDNode *SelectNodeTo(SDNode *N, unsigned TargetOpc, EVT VT1,
835                        EVT VT2, const SDValue *Ops, unsigned NumOps);
836   SDNode *SelectNodeTo(SDNode *N, unsigned TargetOpc, EVT VT1,
837                        EVT VT2, EVT VT3, const SDValue *Ops, unsigned NumOps);
838   SDNode *SelectNodeTo(SDNode *N, unsigned MachineOpc, EVT VT1,
839                        EVT VT2, EVT VT3, EVT VT4, const SDValue *Ops,
840                        unsigned NumOps);
841   SDNode *SelectNodeTo(SDNode *N, unsigned TargetOpc, EVT VT1,
842                        EVT VT2, SDValue Op1);
843   SDNode *SelectNodeTo(SDNode *N, unsigned TargetOpc, EVT VT1,
844                        EVT VT2, SDValue Op1, SDValue Op2);
845   SDNode *SelectNodeTo(SDNode *N, unsigned TargetOpc, EVT VT1,
846                        EVT VT2, SDValue Op1, SDValue Op2, SDValue Op3);
847   SDNode *SelectNodeTo(SDNode *N, unsigned TargetOpc, EVT VT1,
848                        EVT VT2, EVT VT3, SDValue Op1, SDValue Op2, SDValue Op3);
849   SDNode *SelectNodeTo(SDNode *N, unsigned TargetOpc, SDVTList VTs,
850                        const SDValue *Ops, unsigned NumOps);
851
852   /// MorphNodeTo - This *mutates* the specified node to have the specified
853   /// return type, opcode, and operands.
854   SDNode *MorphNodeTo(SDNode *N, unsigned Opc, SDVTList VTs,
855                       const SDValue *Ops, unsigned NumOps);
856
857   /// getMachineNode - These are used for target selectors to create a new node
858   /// with specified return type(s), MachineInstr opcode, and operands.
859   ///
860   /// Note that getMachineNode returns the resultant node.  If there is already
861   /// a node of the specified opcode and operands, it returns that node instead
862   /// of the current one.
863   MachineSDNode *getMachineNode(unsigned Opcode, SDLoc dl, EVT VT);
864   MachineSDNode *getMachineNode(unsigned Opcode, SDLoc dl, EVT VT,
865                                 SDValue Op1);
866   MachineSDNode *getMachineNode(unsigned Opcode, SDLoc dl, EVT VT,
867                                 SDValue Op1, SDValue Op2);
868   MachineSDNode *getMachineNode(unsigned Opcode, SDLoc dl, EVT VT,
869                                 SDValue Op1, SDValue Op2, SDValue Op3);
870   MachineSDNode *getMachineNode(unsigned Opcode, SDLoc dl, EVT VT,
871                                 ArrayRef<SDValue> Ops);
872   MachineSDNode *getMachineNode(unsigned Opcode, SDLoc dl, EVT VT1, EVT VT2);
873   MachineSDNode *getMachineNode(unsigned Opcode, SDLoc dl, EVT VT1, EVT VT2,
874                                 SDValue Op1);
875   MachineSDNode *getMachineNode(unsigned Opcode, SDLoc dl, EVT VT1, EVT VT2,
876                                 SDValue Op1, SDValue Op2);
877   MachineSDNode *getMachineNode(unsigned Opcode, SDLoc dl, EVT VT1, EVT VT2,
878                                 SDValue Op1, SDValue Op2, SDValue Op3);
879   MachineSDNode *getMachineNode(unsigned Opcode, SDLoc dl, EVT VT1, EVT VT2,
880                                 ArrayRef<SDValue> Ops);
881   MachineSDNode *getMachineNode(unsigned Opcode, SDLoc dl, EVT VT1, EVT VT2,
882                                 EVT VT3, SDValue Op1, SDValue Op2);
883   MachineSDNode *getMachineNode(unsigned Opcode, SDLoc dl, EVT VT1, EVT VT2,
884                                 EVT VT3, SDValue Op1, SDValue Op2,
885                                 SDValue Op3);
886   MachineSDNode *getMachineNode(unsigned Opcode, SDLoc dl, EVT VT1, EVT VT2,
887                                 EVT VT3, ArrayRef<SDValue> Ops);
888   MachineSDNode *getMachineNode(unsigned Opcode, SDLoc dl, EVT VT1, EVT VT2,
889                                 EVT VT3, EVT VT4, ArrayRef<SDValue> Ops);
890   MachineSDNode *getMachineNode(unsigned Opcode, SDLoc dl,
891                                 ArrayRef<EVT> ResultTys,
892                                 ArrayRef<SDValue> Ops);
893   MachineSDNode *getMachineNode(unsigned Opcode, SDLoc dl, SDVTList VTs,
894                                 ArrayRef<SDValue> Ops);
895
896   /// getTargetExtractSubreg - A convenience function for creating
897   /// TargetInstrInfo::EXTRACT_SUBREG nodes.
898   SDValue getTargetExtractSubreg(int SRIdx, SDLoc DL, EVT VT,
899                                  SDValue Operand);
900
901   /// getTargetInsertSubreg - A convenience function for creating
902   /// TargetInstrInfo::INSERT_SUBREG nodes.
903   SDValue getTargetInsertSubreg(int SRIdx, SDLoc DL, EVT VT,
904                                 SDValue Operand, SDValue Subreg);
905
906   /// getNodeIfExists - Get the specified node if it's already available, or
907   /// else return NULL.
908   SDNode *getNodeIfExists(unsigned Opcode, SDVTList VTs,
909                           const SDValue *Ops, unsigned NumOps);
910
911   /// getDbgValue - Creates a SDDbgValue node.
912   ///
913   SDDbgValue *getDbgValue(MDNode *MDPtr, SDNode *N, unsigned R, uint64_t Off,
914                           DebugLoc DL, unsigned O);
915   SDDbgValue *getDbgValue(MDNode *MDPtr, const Value *C, uint64_t Off,
916                           DebugLoc DL, unsigned O);
917   SDDbgValue *getDbgValue(MDNode *MDPtr, unsigned FI, uint64_t Off,
918                           DebugLoc DL, unsigned O);
919
920   /// RemoveDeadNode - Remove the specified node from the system. If any of its
921   /// operands then becomes dead, remove them as well. Inform UpdateListener
922   /// for each node deleted.
923   void RemoveDeadNode(SDNode *N);
924
925   /// RemoveDeadNodes - This method deletes the unreachable nodes in the
926   /// given list, and any nodes that become unreachable as a result.
927   void RemoveDeadNodes(SmallVectorImpl<SDNode *> &DeadNodes);
928
929   /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
930   /// This can cause recursive merging of nodes in the DAG.  Use the first
931   /// version if 'From' is known to have a single result, use the second
932   /// if you have two nodes with identical results (or if 'To' has a superset
933   /// of the results of 'From'), use the third otherwise.
934   ///
935   /// These methods all take an optional UpdateListener, which (if not null) is
936   /// informed about nodes that are deleted and modified due to recursive
937   /// changes in the dag.
938   ///
939   /// These functions only replace all existing uses. It's possible that as
940   /// these replacements are being performed, CSE may cause the From node
941   /// to be given new uses. These new uses of From are left in place, and
942   /// not automatically transferred to To.
943   ///
944   void ReplaceAllUsesWith(SDValue From, SDValue Op);
945   void ReplaceAllUsesWith(SDNode *From, SDNode *To);
946   void ReplaceAllUsesWith(SDNode *From, const SDValue *To);
947
948   /// ReplaceAllUsesOfValueWith - Replace any uses of From with To, leaving
949   /// uses of other values produced by From.Val alone.
950   void ReplaceAllUsesOfValueWith(SDValue From, SDValue To);
951
952   /// ReplaceAllUsesOfValuesWith - Like ReplaceAllUsesOfValueWith, but
953   /// for multiple values at once. This correctly handles the case where
954   /// there is an overlap between the From values and the To values.
955   void ReplaceAllUsesOfValuesWith(const SDValue *From, const SDValue *To,
956                                   unsigned Num);
957
958   /// AssignTopologicalOrder - Topological-sort the AllNodes list and a
959   /// assign a unique node id for each node in the DAG based on their
960   /// topological order. Returns the number of nodes.
961   unsigned AssignTopologicalOrder();
962
963   /// RepositionNode - Move node N in the AllNodes list to be immediately
964   /// before the given iterator Position. This may be used to update the
965   /// topological ordering when the list of nodes is modified.
966   void RepositionNode(allnodes_iterator Position, SDNode *N) {
967     AllNodes.insert(Position, AllNodes.remove(N));
968   }
969
970   /// isCommutativeBinOp - Returns true if the opcode is a commutative binary
971   /// operation.
972   static bool isCommutativeBinOp(unsigned Opcode) {
973     // FIXME: This should get its info from the td file, so that we can include
974     // target info.
975     switch (Opcode) {
976     case ISD::ADD:
977     case ISD::MUL:
978     case ISD::MULHU:
979     case ISD::MULHS:
980     case ISD::SMUL_LOHI:
981     case ISD::UMUL_LOHI:
982     case ISD::FADD:
983     case ISD::FMUL:
984     case ISD::AND:
985     case ISD::OR:
986     case ISD::XOR:
987     case ISD::SADDO:
988     case ISD::UADDO:
989     case ISD::ADDC:
990     case ISD::ADDE: return true;
991     default: return false;
992     }
993   }
994
995   /// Returns an APFloat semantics tag appropriate for the given type. If VT is
996   /// a vector type, the element semantics are returned.
997   static const fltSemantics &EVTToAPFloatSemantics(EVT VT) {
998     switch (VT.getScalarType().getSimpleVT().SimpleTy) {
999     default: llvm_unreachable("Unknown FP format");
1000     case MVT::f16:     return APFloat::IEEEhalf;
1001     case MVT::f32:     return APFloat::IEEEsingle;
1002     case MVT::f64:     return APFloat::IEEEdouble;
1003     case MVT::f80:     return APFloat::x87DoubleExtended;
1004     case MVT::f128:    return APFloat::IEEEquad;
1005     case MVT::ppcf128: return APFloat::PPCDoubleDouble;
1006     }
1007   }
1008
1009   /// AddDbgValue - Add a dbg_value SDNode. If SD is non-null that means the
1010   /// value is produced by SD.
1011   void AddDbgValue(SDDbgValue *DB, SDNode *SD, bool isParameter);
1012
1013   /// GetDbgValues - Get the debug values which reference the given SDNode.
1014   ArrayRef<SDDbgValue*> GetDbgValues(const SDNode* SD) {
1015     return DbgInfo->getSDDbgValues(SD);
1016   }
1017
1018   /// TransferDbgValues - Transfer SDDbgValues.
1019   void TransferDbgValues(SDValue From, SDValue To);
1020
1021   /// hasDebugValues - Return true if there are any SDDbgValue nodes associated
1022   /// with this SelectionDAG.
1023   bool hasDebugValues() const { return !DbgInfo->empty(); }
1024
1025   SDDbgInfo::DbgIterator DbgBegin() { return DbgInfo->DbgBegin(); }
1026   SDDbgInfo::DbgIterator DbgEnd()   { return DbgInfo->DbgEnd(); }
1027   SDDbgInfo::DbgIterator ByvalParmDbgBegin() {
1028     return DbgInfo->ByvalParmDbgBegin();
1029   }
1030   SDDbgInfo::DbgIterator ByvalParmDbgEnd()   {
1031     return DbgInfo->ByvalParmDbgEnd();
1032   }
1033
1034   void dump() const;
1035
1036   /// CreateStackTemporary - Create a stack temporary, suitable for holding the
1037   /// specified value type.  If minAlign is specified, the slot size will have
1038   /// at least that alignment.
1039   SDValue CreateStackTemporary(EVT VT, unsigned minAlign = 1);
1040
1041   /// CreateStackTemporary - Create a stack temporary suitable for holding
1042   /// either of the specified value types.
1043   SDValue CreateStackTemporary(EVT VT1, EVT VT2);
1044
1045   /// FoldConstantArithmetic -
1046   SDValue FoldConstantArithmetic(unsigned Opcode, EVT VT,
1047                                  SDNode *Cst1, SDNode *Cst2);
1048
1049   /// FoldSetCC - Constant fold a setcc to true or false.
1050   SDValue FoldSetCC(EVT VT, SDValue N1,
1051                     SDValue N2, ISD::CondCode Cond, SDLoc dl);
1052
1053   /// SignBitIsZero - Return true if the sign bit of Op is known to be zero.  We
1054   /// use this predicate to simplify operations downstream.
1055   bool SignBitIsZero(SDValue Op, unsigned Depth = 0) const;
1056
1057   /// MaskedValueIsZero - Return true if 'Op & Mask' is known to be zero.  We
1058   /// use this predicate to simplify operations downstream.  Op and Mask are
1059   /// known to be the same type.
1060   bool MaskedValueIsZero(SDValue Op, const APInt &Mask, unsigned Depth = 0)
1061     const;
1062
1063   /// ComputeMaskedBits - Determine which of the bits specified in Mask are
1064   /// known to be either zero or one and return them in the KnownZero/KnownOne
1065   /// bitsets.  This code only analyzes bits in Mask, in order to short-circuit
1066   /// processing.  Targets can implement the computeMaskedBitsForTargetNode
1067   /// method in the TargetLowering class to allow target nodes to be understood.
1068   void ComputeMaskedBits(SDValue Op, APInt &KnownZero, APInt &KnownOne,
1069                          unsigned Depth = 0) const;
1070
1071   /// ComputeNumSignBits - Return the number of times the sign bit of the
1072   /// register is replicated into the other bits.  We know that at least 1 bit
1073   /// is always equal to the sign bit (itself), but other cases can give us
1074   /// information.  For example, immediately after an "SRA X, 2", we know that
1075   /// the top 3 bits are all equal to each other, so we return 3.  Targets can
1076   /// implement the ComputeNumSignBitsForTarget method in the TargetLowering
1077   /// class to allow target nodes to be understood.
1078   unsigned ComputeNumSignBits(SDValue Op, unsigned Depth = 0) const;
1079
1080   /// isBaseWithConstantOffset - Return true if the specified operand is an
1081   /// ISD::ADD with a ConstantSDNode on the right-hand side, or if it is an
1082   /// ISD::OR with a ConstantSDNode that is guaranteed to have the same
1083   /// semantics as an ADD.  This handles the equivalence:
1084   ///     X|Cst == X+Cst iff X&Cst = 0.
1085   bool isBaseWithConstantOffset(SDValue Op) const;
1086
1087   /// isKnownNeverNan - Test whether the given SDValue is known to never be NaN.
1088   bool isKnownNeverNaN(SDValue Op) const;
1089
1090   /// isKnownNeverZero - Test whether the given SDValue is known to never be
1091   /// positive or negative Zero.
1092   bool isKnownNeverZero(SDValue Op) const;
1093
1094   /// isEqualTo - Test whether two SDValues are known to compare equal. This
1095   /// is true if they are the same value, or if one is negative zero and the
1096   /// other positive zero.
1097   bool isEqualTo(SDValue A, SDValue B) const;
1098
1099   /// UnrollVectorOp - Utility function used by legalize and lowering to
1100   /// "unroll" a vector operation by splitting out the scalars and operating
1101   /// on each element individually.  If the ResNE is 0, fully unroll the vector
1102   /// op. If ResNE is less than the width of the vector op, unroll up to ResNE.
1103   /// If the  ResNE is greater than the width of the vector op, unroll the
1104   /// vector op and fill the end of the resulting vector with UNDEFS.
1105   SDValue UnrollVectorOp(SDNode *N, unsigned ResNE = 0);
1106
1107   /// isConsecutiveLoad - Return true if LD is loading 'Bytes' bytes from a
1108   /// location that is 'Dist' units away from the location that the 'Base' load
1109   /// is loading from.
1110   bool isConsecutiveLoad(LoadSDNode *LD, LoadSDNode *Base,
1111                          unsigned Bytes, int Dist) const;
1112
1113   /// InferPtrAlignment - Infer alignment of a load / store address. Return 0 if
1114   /// it cannot be inferred.
1115   unsigned InferPtrAlignment(SDValue Ptr) const;
1116
1117 private:
1118   bool RemoveNodeFromCSEMaps(SDNode *N);
1119   void AddModifiedNodeToCSEMaps(SDNode *N);
1120   SDNode *FindModifiedNodeSlot(SDNode *N, SDValue Op, void *&InsertPos);
1121   SDNode *FindModifiedNodeSlot(SDNode *N, SDValue Op1, SDValue Op2,
1122                                void *&InsertPos);
1123   SDNode *FindModifiedNodeSlot(SDNode *N, const SDValue *Ops, unsigned NumOps,
1124                                void *&InsertPos);
1125   SDNode *UpdadeSDLocOnMergedSDNode(SDNode *N, SDLoc loc);
1126
1127   void DeleteNodeNotInCSEMaps(SDNode *N);
1128   void DeallocateNode(SDNode *N);
1129
1130   unsigned getEVTAlignment(EVT MemoryVT) const;
1131
1132   void allnodes_clear();
1133
1134   /// VTList - List of non-single value types.
1135   FoldingSet<SDVTListNode> VTListMap;
1136
1137   /// CondCodeNodes - Maps to auto-CSE operations.
1138   std::vector<CondCodeSDNode*> CondCodeNodes;
1139
1140   std::vector<SDNode*> ValueTypeNodes;
1141   std::map<EVT, SDNode*, EVT::compareRawBits> ExtendedValueTypeNodes;
1142   StringMap<SDNode*> ExternalSymbols;
1143
1144   std::map<std::pair<std::string, unsigned char>,SDNode*> TargetExternalSymbols;
1145 };
1146
1147 template <> struct GraphTraits<SelectionDAG*> : public GraphTraits<SDNode*> {
1148   typedef SelectionDAG::allnodes_iterator nodes_iterator;
1149   static nodes_iterator nodes_begin(SelectionDAG *G) {
1150     return G->allnodes_begin();
1151   }
1152   static nodes_iterator nodes_end(SelectionDAG *G) {
1153     return G->allnodes_end();
1154   }
1155 };
1156
1157 }  // end namespace llvm
1158
1159 #endif