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