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