SelectionDAG.cpp revision cb6682fa44e13262bdef7dd22b4ba90f8c2e7b97
1//===-- SelectionDAG.cpp - Implement the SelectionDAG data structures -----===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This implements the SelectionDAG class.
11//
12//===----------------------------------------------------------------------===//
13
14#include "llvm/CodeGen/SelectionDAG.h"
15#include "llvm/Constants.h"
16#include "llvm/GlobalValue.h"
17#include "llvm/Assembly/Writer.h"
18#include "llvm/CodeGen/MachineBasicBlock.h"
19#include "llvm/Support/MathExtras.h"
20#include "llvm/Target/TargetLowering.h"
21#include "llvm/Target/TargetInstrInfo.h"
22#include "llvm/Target/TargetMachine.h"
23#include <iostream>
24#include <set>
25#include <cmath>
26#include <algorithm>
27using namespace llvm;
28
29static bool isCommutativeBinOp(unsigned Opcode) {
30  switch (Opcode) {
31  case ISD::ADD:
32  case ISD::MUL:
33  case ISD::AND:
34  case ISD::OR:
35  case ISD::XOR: return true;
36  default: return false; // FIXME: Need commutative info for user ops!
37  }
38}
39
40static bool isAssociativeBinOp(unsigned Opcode) {
41  switch (Opcode) {
42  case ISD::ADD:
43  case ISD::MUL:
44  case ISD::AND:
45  case ISD::OR:
46  case ISD::XOR: return true;
47  default: return false; // FIXME: Need associative info for user ops!
48  }
49}
50
51// isInvertibleForFree - Return true if there is no cost to emitting the logical
52// inverse of this node.
53static bool isInvertibleForFree(SDOperand N) {
54  if (isa<ConstantSDNode>(N.Val)) return true;
55  if (N.Val->getOpcode() == ISD::SETCC && N.Val->hasOneUse())
56    return true;
57  return false;
58}
59
60
61/// getSetCCSwappedOperands - Return the operation corresponding to (Y op X)
62/// when given the operation for (X op Y).
63ISD::CondCode ISD::getSetCCSwappedOperands(ISD::CondCode Operation) {
64  // To perform this operation, we just need to swap the L and G bits of the
65  // operation.
66  unsigned OldL = (Operation >> 2) & 1;
67  unsigned OldG = (Operation >> 1) & 1;
68  return ISD::CondCode((Operation & ~6) |  // Keep the N, U, E bits
69                       (OldL << 1) |       // New G bit
70                       (OldG << 2));        // New L bit.
71}
72
73/// getSetCCInverse - Return the operation corresponding to !(X op Y), where
74/// 'op' is a valid SetCC operation.
75ISD::CondCode ISD::getSetCCInverse(ISD::CondCode Op, bool isInteger) {
76  unsigned Operation = Op;
77  if (isInteger)
78    Operation ^= 7;   // Flip L, G, E bits, but not U.
79  else
80    Operation ^= 15;  // Flip all of the condition bits.
81  if (Operation > ISD::SETTRUE2)
82    Operation &= ~8;     // Don't let N and U bits get set.
83  return ISD::CondCode(Operation);
84}
85
86
87/// isSignedOp - For an integer comparison, return 1 if the comparison is a
88/// signed operation and 2 if the result is an unsigned comparison.  Return zero
89/// if the operation does not depend on the sign of the input (setne and seteq).
90static int isSignedOp(ISD::CondCode Opcode) {
91  switch (Opcode) {
92  default: assert(0 && "Illegal integer setcc operation!");
93  case ISD::SETEQ:
94  case ISD::SETNE: return 0;
95  case ISD::SETLT:
96  case ISD::SETLE:
97  case ISD::SETGT:
98  case ISD::SETGE: return 1;
99  case ISD::SETULT:
100  case ISD::SETULE:
101  case ISD::SETUGT:
102  case ISD::SETUGE: return 2;
103  }
104}
105
106/// getSetCCOrOperation - Return the result of a logical OR between different
107/// comparisons of identical values: ((X op1 Y) | (X op2 Y)).  This function
108/// returns SETCC_INVALID if it is not possible to represent the resultant
109/// comparison.
110ISD::CondCode ISD::getSetCCOrOperation(ISD::CondCode Op1, ISD::CondCode Op2,
111                                       bool isInteger) {
112  if (isInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
113    // Cannot fold a signed integer setcc with an unsigned integer setcc.
114    return ISD::SETCC_INVALID;
115
116  unsigned Op = Op1 | Op2;  // Combine all of the condition bits.
117
118  // If the N and U bits get set then the resultant comparison DOES suddenly
119  // care about orderedness, and is true when ordered.
120  if (Op > ISD::SETTRUE2)
121    Op &= ~16;     // Clear the N bit.
122  return ISD::CondCode(Op);
123}
124
125/// getSetCCAndOperation - Return the result of a logical AND between different
126/// comparisons of identical values: ((X op1 Y) & (X op2 Y)).  This
127/// function returns zero if it is not possible to represent the resultant
128/// comparison.
129ISD::CondCode ISD::getSetCCAndOperation(ISD::CondCode Op1, ISD::CondCode Op2,
130                                        bool isInteger) {
131  if (isInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
132    // Cannot fold a signed setcc with an unsigned setcc.
133    return ISD::SETCC_INVALID;
134
135  // Combine all of the condition bits.
136  return ISD::CondCode(Op1 & Op2);
137}
138
139const TargetMachine &SelectionDAG::getTarget() const {
140  return TLI.getTargetMachine();
141}
142
143
144/// RemoveDeadNodes - This method deletes all unreachable nodes in the
145/// SelectionDAG, including nodes (like loads) that have uses of their token
146/// chain but no other uses and no side effect.  If a node is passed in as an
147/// argument, it is used as the seed for node deletion.
148void SelectionDAG::RemoveDeadNodes(SDNode *N) {
149  std::set<SDNode*> AllNodeSet(AllNodes.begin(), AllNodes.end());
150
151  // Create a dummy node (which is not added to allnodes), that adds a reference
152  // to the root node, preventing it from being deleted.
153  SDNode *DummyNode = new SDNode(ISD::EntryToken, getRoot());
154
155  // If we have a hint to start from, use it.
156  if (N) DeleteNodeIfDead(N, &AllNodeSet);
157
158 Restart:
159  unsigned NumNodes = AllNodeSet.size();
160  for (std::set<SDNode*>::iterator I = AllNodeSet.begin(), E = AllNodeSet.end();
161       I != E; ++I) {
162    // Try to delete this node.
163    DeleteNodeIfDead(*I, &AllNodeSet);
164
165    // If we actually deleted any nodes, do not use invalid iterators in
166    // AllNodeSet.
167    if (AllNodeSet.size() != NumNodes)
168      goto Restart;
169  }
170
171  // Restore AllNodes.
172  if (AllNodes.size() != NumNodes)
173    AllNodes.assign(AllNodeSet.begin(), AllNodeSet.end());
174
175  // If the root changed (e.g. it was a dead load, update the root).
176  setRoot(DummyNode->getOperand(0));
177
178  // Now that we are done with the dummy node, delete it.
179  DummyNode->getOperand(0).Val->removeUser(DummyNode);
180  delete DummyNode;
181}
182
183
184void SelectionDAG::DeleteNodeIfDead(SDNode *N, void *NodeSet) {
185  if (!N->use_empty())
186    return;
187
188  // Okay, we really are going to delete this node.  First take this out of the
189  // appropriate CSE map.
190  RemoveNodeFromCSEMaps(N);
191
192  // Next, brutally remove the operand list.  This is safe to do, as there are
193  // no cycles in the graph.
194  while (!N->Operands.empty()) {
195    SDNode *O = N->Operands.back().Val;
196    N->Operands.pop_back();
197    O->removeUser(N);
198
199    // Now that we removed this operand, see if there are no uses of it left.
200    DeleteNodeIfDead(O, NodeSet);
201  }
202
203  // Remove the node from the nodes set and delete it.
204  std::set<SDNode*> &AllNodeSet = *(std::set<SDNode*>*)NodeSet;
205  AllNodeSet.erase(N);
206
207  // Now that the node is gone, check to see if any of the operands of this node
208  // are dead now.
209  delete N;
210}
211
212/// RemoveNodeFromCSEMaps - Take the specified node out of the CSE map that
213/// correspond to it.  This is useful when we're about to delete or repurpose
214/// the node.  We don't want future request for structurally identical nodes
215/// to return N anymore.
216void SelectionDAG::RemoveNodeFromCSEMaps(SDNode *N) {
217  switch (N->getOpcode()) {
218  case ISD::Constant:
219    Constants.erase(std::make_pair(cast<ConstantSDNode>(N)->getValue(),
220                                   N->getValueType(0)));
221    break;
222  case ISD::TargetConstant:
223    TargetConstants.erase(std::make_pair(cast<ConstantSDNode>(N)->getValue(),
224                                         N->getValueType(0)));
225    break;
226  case ISD::ConstantFP: {
227    uint64_t V = DoubleToBits(cast<ConstantFPSDNode>(N)->getValue());
228    ConstantFPs.erase(std::make_pair(V, N->getValueType(0)));
229    break;
230  }
231  case ISD::CONDCODE:
232    assert(CondCodeNodes[cast<CondCodeSDNode>(N)->get()] &&
233           "Cond code doesn't exist!");
234    CondCodeNodes[cast<CondCodeSDNode>(N)->get()] = 0;
235    break;
236  case ISD::GlobalAddress:
237    GlobalValues.erase(cast<GlobalAddressSDNode>(N)->getGlobal());
238    break;
239  case ISD::FrameIndex:
240    FrameIndices.erase(cast<FrameIndexSDNode>(N)->getIndex());
241    break;
242  case ISD::ConstantPool:
243    ConstantPoolIndices.erase(cast<ConstantPoolSDNode>(N)->getIndex());
244    break;
245  case ISD::BasicBlock:
246    BBNodes.erase(cast<BasicBlockSDNode>(N)->getBasicBlock());
247    break;
248  case ISD::ExternalSymbol:
249    ExternalSymbols.erase(cast<ExternalSymbolSDNode>(N)->getSymbol());
250    break;
251  case ISD::VALUETYPE:
252    ValueTypeNodes[cast<VTSDNode>(N)->getVT()] = 0;
253    break;
254  case ISD::Register:
255    RegNodes[cast<RegisterSDNode>(N)->getReg()] = 0;
256    break;
257  case ISD::SRCVALUE: {
258    SrcValueSDNode *SVN = cast<SrcValueSDNode>(N);
259    ValueNodes.erase(std::make_pair(SVN->getValue(), SVN->getOffset()));
260    break;
261  }
262  case ISD::LOAD:
263    Loads.erase(std::make_pair(N->getOperand(1),
264                               std::make_pair(N->getOperand(0),
265                                              N->getValueType(0))));
266    break;
267  default:
268    if (N->getNumOperands() == 1)
269      UnaryOps.erase(std::make_pair(N->getOpcode(),
270                                    std::make_pair(N->getOperand(0),
271                                                   N->getValueType(0))));
272    else if (N->getNumOperands() == 2)
273      BinaryOps.erase(std::make_pair(N->getOpcode(),
274                                     std::make_pair(N->getOperand(0),
275                                                    N->getOperand(1))));
276    else if (N->getNumValues() == 1) {
277      std::vector<SDOperand> Ops(N->op_begin(), N->op_end());
278      OneResultNodes.erase(std::make_pair(N->getOpcode(),
279                                          std::make_pair(N->getValueType(0),
280                                                         Ops)));
281    } else {
282      // Remove the node from the ArbitraryNodes map.
283      std::vector<MVT::ValueType> RV(N->value_begin(), N->value_end());
284      std::vector<SDOperand>     Ops(N->op_begin(), N->op_end());
285      ArbitraryNodes.erase(std::make_pair(N->getOpcode(),
286                                          std::make_pair(RV, Ops)));
287    }
288    break;
289  }
290}
291
292/// AddNonLeafNodeToCSEMaps - Add the specified node back to the CSE maps.  It
293/// has been taken out and modified in some way.  If the specified node already
294/// exists in the CSE maps, do not modify the maps, but return the existing node
295/// instead.  If it doesn't exist, add it and return null.
296///
297SDNode *SelectionDAG::AddNonLeafNodeToCSEMaps(SDNode *N) {
298  assert(N->getNumOperands() && "This is a leaf node!");
299  if (N->getOpcode() == ISD::LOAD) {
300    SDNode *&L = Loads[std::make_pair(N->getOperand(1),
301                                      std::make_pair(N->getOperand(0),
302                                                     N->getValueType(0)))];
303    if (L) return L;
304    L = N;
305  } else if (N->getNumOperands() == 1) {
306    SDNode *&U = UnaryOps[std::make_pair(N->getOpcode(),
307                                         std::make_pair(N->getOperand(0),
308                                                        N->getValueType(0)))];
309    if (U) return U;
310    U = N;
311  } else if (N->getNumOperands() == 2) {
312    SDNode *&B = BinaryOps[std::make_pair(N->getOpcode(),
313                                          std::make_pair(N->getOperand(0),
314                                                         N->getOperand(1)))];
315    if (B) return B;
316    B = N;
317  } else if (N->getNumValues() == 1) {
318    std::vector<SDOperand> Ops(N->op_begin(), N->op_end());
319    SDNode *&ORN = OneResultNodes[std::make_pair(N->getOpcode(),
320                                  std::make_pair(N->getValueType(0), Ops))];
321    if (ORN) return ORN;
322    ORN = N;
323  } else {
324    // Remove the node from the ArbitraryNodes map.
325    std::vector<MVT::ValueType> RV(N->value_begin(), N->value_end());
326    std::vector<SDOperand>     Ops(N->op_begin(), N->op_end());
327    SDNode *&AN = ArbitraryNodes[std::make_pair(N->getOpcode(),
328                                                std::make_pair(RV, Ops))];
329    if (AN) return AN;
330    AN = N;
331  }
332  return 0;
333
334}
335
336
337
338SelectionDAG::~SelectionDAG() {
339  for (unsigned i = 0, e = AllNodes.size(); i != e; ++i)
340    delete AllNodes[i];
341}
342
343SDOperand SelectionDAG::getZeroExtendInReg(SDOperand Op, MVT::ValueType VT) {
344  if (Op.getValueType() == VT) return Op;
345  int64_t Imm = ~0ULL >> (64-MVT::getSizeInBits(VT));
346  return getNode(ISD::AND, Op.getValueType(), Op,
347                 getConstant(Imm, Op.getValueType()));
348}
349
350SDOperand SelectionDAG::getConstant(uint64_t Val, MVT::ValueType VT) {
351  assert(MVT::isInteger(VT) && "Cannot create FP integer constant!");
352  // Mask out any bits that are not valid for this constant.
353  if (VT != MVT::i64)
354    Val &= ((uint64_t)1 << MVT::getSizeInBits(VT)) - 1;
355
356  SDNode *&N = Constants[std::make_pair(Val, VT)];
357  if (N) return SDOperand(N, 0);
358  N = new ConstantSDNode(false, Val, VT);
359  AllNodes.push_back(N);
360  return SDOperand(N, 0);
361}
362
363SDOperand SelectionDAG::getTargetConstant(uint64_t Val, MVT::ValueType VT) {
364  assert(MVT::isInteger(VT) && "Cannot create FP integer constant!");
365  // Mask out any bits that are not valid for this constant.
366  if (VT != MVT::i64)
367    Val &= ((uint64_t)1 << MVT::getSizeInBits(VT)) - 1;
368
369  SDNode *&N = TargetConstants[std::make_pair(Val, VT)];
370  if (N) return SDOperand(N, 0);
371  N = new ConstantSDNode(true, Val, VT);
372  AllNodes.push_back(N);
373  return SDOperand(N, 0);
374}
375
376SDOperand SelectionDAG::getConstantFP(double Val, MVT::ValueType VT) {
377  assert(MVT::isFloatingPoint(VT) && "Cannot create integer FP constant!");
378  if (VT == MVT::f32)
379    Val = (float)Val;  // Mask out extra precision.
380
381  // Do the map lookup using the actual bit pattern for the floating point
382  // value, so that we don't have problems with 0.0 comparing equal to -0.0, and
383  // we don't have issues with SNANs.
384  SDNode *&N = ConstantFPs[std::make_pair(DoubleToBits(Val), VT)];
385  if (N) return SDOperand(N, 0);
386  N = new ConstantFPSDNode(Val, VT);
387  AllNodes.push_back(N);
388  return SDOperand(N, 0);
389}
390
391
392
393SDOperand SelectionDAG::getGlobalAddress(const GlobalValue *GV,
394                                         MVT::ValueType VT) {
395  SDNode *&N = GlobalValues[GV];
396  if (N) return SDOperand(N, 0);
397  N = new GlobalAddressSDNode(GV,VT);
398  AllNodes.push_back(N);
399  return SDOperand(N, 0);
400}
401
402SDOperand SelectionDAG::getFrameIndex(int FI, MVT::ValueType VT) {
403  SDNode *&N = FrameIndices[FI];
404  if (N) return SDOperand(N, 0);
405  N = new FrameIndexSDNode(FI, VT);
406  AllNodes.push_back(N);
407  return SDOperand(N, 0);
408}
409
410SDOperand SelectionDAG::getConstantPool(unsigned CPIdx, MVT::ValueType VT) {
411  SDNode *N = ConstantPoolIndices[CPIdx];
412  if (N) return SDOperand(N, 0);
413  N = new ConstantPoolSDNode(CPIdx, VT);
414  AllNodes.push_back(N);
415  return SDOperand(N, 0);
416}
417
418SDOperand SelectionDAG::getBasicBlock(MachineBasicBlock *MBB) {
419  SDNode *&N = BBNodes[MBB];
420  if (N) return SDOperand(N, 0);
421  N = new BasicBlockSDNode(MBB);
422  AllNodes.push_back(N);
423  return SDOperand(N, 0);
424}
425
426SDOperand SelectionDAG::getValueType(MVT::ValueType VT) {
427  if ((unsigned)VT >= ValueTypeNodes.size())
428    ValueTypeNodes.resize(VT+1);
429  if (ValueTypeNodes[VT] == 0) {
430    ValueTypeNodes[VT] = new VTSDNode(VT);
431    AllNodes.push_back(ValueTypeNodes[VT]);
432  }
433
434  return SDOperand(ValueTypeNodes[VT], 0);
435}
436
437SDOperand SelectionDAG::getExternalSymbol(const char *Sym, MVT::ValueType VT) {
438  SDNode *&N = ExternalSymbols[Sym];
439  if (N) return SDOperand(N, 0);
440  N = new ExternalSymbolSDNode(Sym, VT);
441  AllNodes.push_back(N);
442  return SDOperand(N, 0);
443}
444
445SDOperand SelectionDAG::getCondCode(ISD::CondCode Cond) {
446  if ((unsigned)Cond >= CondCodeNodes.size())
447    CondCodeNodes.resize(Cond+1);
448
449  if (CondCodeNodes[Cond] == 0) {
450    CondCodeNodes[Cond] = new CondCodeSDNode(Cond);
451    AllNodes.push_back(CondCodeNodes[Cond]);
452  }
453  return SDOperand(CondCodeNodes[Cond], 0);
454}
455
456SDOperand SelectionDAG::getRegister(unsigned Reg, MVT::ValueType VT) {
457  if (Reg >= RegNodes.size())
458    RegNodes.resize(Reg+1);
459  RegisterSDNode *&Result = RegNodes[Reg];
460  if (Result) {
461    assert(Result->getValueType(0) == VT &&
462           "Inconsistent value types for machine registers");
463  } else {
464    Result = new RegisterSDNode(Reg, VT);
465    AllNodes.push_back(Result);
466  }
467  return SDOperand(Result, 0);
468}
469
470SDOperand SelectionDAG::SimplifySetCC(MVT::ValueType VT, SDOperand N1,
471                                      SDOperand N2, ISD::CondCode Cond) {
472  // These setcc operations always fold.
473  switch (Cond) {
474  default: break;
475  case ISD::SETFALSE:
476  case ISD::SETFALSE2: return getConstant(0, VT);
477  case ISD::SETTRUE:
478  case ISD::SETTRUE2:  return getConstant(1, VT);
479  }
480
481  if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.Val)) {
482    uint64_t C2 = N2C->getValue();
483    if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val)) {
484      uint64_t C1 = N1C->getValue();
485
486      // Sign extend the operands if required
487      if (ISD::isSignedIntSetCC(Cond)) {
488        C1 = N1C->getSignExtended();
489        C2 = N2C->getSignExtended();
490      }
491
492      switch (Cond) {
493      default: assert(0 && "Unknown integer setcc!");
494      case ISD::SETEQ:  return getConstant(C1 == C2, VT);
495      case ISD::SETNE:  return getConstant(C1 != C2, VT);
496      case ISD::SETULT: return getConstant(C1 <  C2, VT);
497      case ISD::SETUGT: return getConstant(C1 >  C2, VT);
498      case ISD::SETULE: return getConstant(C1 <= C2, VT);
499      case ISD::SETUGE: return getConstant(C1 >= C2, VT);
500      case ISD::SETLT:  return getConstant((int64_t)C1 <  (int64_t)C2, VT);
501      case ISD::SETGT:  return getConstant((int64_t)C1 >  (int64_t)C2, VT);
502      case ISD::SETLE:  return getConstant((int64_t)C1 <= (int64_t)C2, VT);
503      case ISD::SETGE:  return getConstant((int64_t)C1 >= (int64_t)C2, VT);
504      }
505    } else {
506      // If the LHS is a ZERO_EXTEND and if this is an ==/!= comparison, perform
507      // the comparison on the input.
508      if (N1.getOpcode() == ISD::ZERO_EXTEND) {
509        unsigned InSize = MVT::getSizeInBits(N1.getOperand(0).getValueType());
510
511        // If the comparison constant has bits in the upper part, the
512        // zero-extended value could never match.
513        if (C2 & (~0ULL << InSize)) {
514          unsigned VSize = MVT::getSizeInBits(N1.getValueType());
515          switch (Cond) {
516          case ISD::SETUGT:
517          case ISD::SETUGE:
518          case ISD::SETEQ: return getConstant(0, VT);
519          case ISD::SETULT:
520          case ISD::SETULE:
521          case ISD::SETNE: return getConstant(1, VT);
522          case ISD::SETGT:
523          case ISD::SETGE:
524            // True if the sign bit of C2 is set.
525            return getConstant((C2 & (1ULL << VSize)) != 0, VT);
526          case ISD::SETLT:
527          case ISD::SETLE:
528            // True if the sign bit of C2 isn't set.
529            return getConstant((C2 & (1ULL << VSize)) == 0, VT);
530          default:
531            break;
532          }
533        }
534
535        // Otherwise, we can perform the comparison with the low bits.
536        switch (Cond) {
537        case ISD::SETEQ:
538        case ISD::SETNE:
539        case ISD::SETUGT:
540        case ISD::SETUGE:
541        case ISD::SETULT:
542        case ISD::SETULE:
543          return getSetCC(VT, N1.getOperand(0),
544                          getConstant(C2, N1.getOperand(0).getValueType()),
545                          Cond);
546        default:
547          break;   // todo, be more careful with signed comparisons
548        }
549      }
550
551      uint64_t MinVal, MaxVal;
552      unsigned OperandBitSize = MVT::getSizeInBits(N2C->getValueType(0));
553      if (ISD::isSignedIntSetCC(Cond)) {
554        MinVal = 1ULL << (OperandBitSize-1);
555        if (OperandBitSize != 1)   // Avoid X >> 64, which is undefined.
556          MaxVal = ~0ULL >> (65-OperandBitSize);
557        else
558          MaxVal = 0;
559      } else {
560        MinVal = 0;
561        MaxVal = ~0ULL >> (64-OperandBitSize);
562      }
563
564      // Canonicalize GE/LE comparisons to use GT/LT comparisons.
565      if (Cond == ISD::SETGE || Cond == ISD::SETUGE) {
566        if (C2 == MinVal) return getConstant(1, VT);   // X >= MIN --> true
567        --C2;                                          // X >= C1 --> X > (C1-1)
568        return getSetCC(VT, N1, getConstant(C2, N2.getValueType()),
569                        (Cond == ISD::SETGE) ? ISD::SETGT : ISD::SETUGT);
570      }
571
572      if (Cond == ISD::SETLE || Cond == ISD::SETULE) {
573        if (C2 == MaxVal) return getConstant(1, VT);   // X <= MAX --> true
574        ++C2;                                          // X <= C1 --> X < (C1+1)
575        return getSetCC(VT, N1, getConstant(C2, N2.getValueType()),
576                        (Cond == ISD::SETLE) ? ISD::SETLT : ISD::SETULT);
577      }
578
579      if ((Cond == ISD::SETLT || Cond == ISD::SETULT) && C2 == MinVal)
580        return getConstant(0, VT);      // X < MIN --> false
581
582      // Canonicalize setgt X, Min --> setne X, Min
583      if ((Cond == ISD::SETGT || Cond == ISD::SETUGT) && C2 == MinVal)
584        return getSetCC(VT, N1, N2, ISD::SETNE);
585
586      // If we have setult X, 1, turn it into seteq X, 0
587      if ((Cond == ISD::SETLT || Cond == ISD::SETULT) && C2 == MinVal+1)
588        return getSetCC(VT, N1, getConstant(MinVal, N1.getValueType()),
589                        ISD::SETEQ);
590      // If we have setugt X, Max-1, turn it into seteq X, Max
591      else if ((Cond == ISD::SETGT || Cond == ISD::SETUGT) && C2 == MaxVal-1)
592        return getSetCC(VT, N1, getConstant(MaxVal, N1.getValueType()),
593                        ISD::SETEQ);
594
595      // If we have "setcc X, C1", check to see if we can shrink the immediate
596      // by changing cc.
597
598      // SETUGT X, SINTMAX  -> SETLT X, 0
599      if (Cond == ISD::SETUGT && OperandBitSize != 1 &&
600          C2 == (~0ULL >> (65-OperandBitSize)))
601        return getSetCC(VT, N1, getConstant(0, N2.getValueType()), ISD::SETLT);
602
603      // FIXME: Implement the rest of these.
604
605
606      // Fold bit comparisons when we can.
607      if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
608          VT == N1.getValueType() && N1.getOpcode() == ISD::AND)
609        if (ConstantSDNode *AndRHS =
610                    dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
611          if (Cond == ISD::SETNE && C2 == 0) {// (X & 8) != 0  -->  (X & 8) >> 3
612            // Perform the xform if the AND RHS is a single bit.
613            if ((AndRHS->getValue() & (AndRHS->getValue()-1)) == 0) {
614              return getNode(ISD::SRL, VT, N1,
615                             getConstant(Log2_64(AndRHS->getValue()),
616                                                   TLI.getShiftAmountTy()));
617            }
618          } else if (Cond == ISD::SETEQ && C2 == AndRHS->getValue()) {
619            // (X & 8) == 8  -->  (X & 8) >> 3
620            // Perform the xform if C2 is a single bit.
621            if ((C2 & (C2-1)) == 0) {
622              return getNode(ISD::SRL, VT, N1,
623                             getConstant(Log2_64(C2),TLI.getShiftAmountTy()));
624            }
625          }
626        }
627    }
628  } else if (isa<ConstantSDNode>(N1.Val)) {
629      // Ensure that the constant occurs on the RHS.
630    return getSetCC(VT, N2, N1, ISD::getSetCCSwappedOperands(Cond));
631  }
632
633  if (ConstantFPSDNode *N1C = dyn_cast<ConstantFPSDNode>(N1.Val))
634    if (ConstantFPSDNode *N2C = dyn_cast<ConstantFPSDNode>(N2.Val)) {
635      double C1 = N1C->getValue(), C2 = N2C->getValue();
636
637      switch (Cond) {
638      default: break; // FIXME: Implement the rest of these!
639      case ISD::SETEQ:  return getConstant(C1 == C2, VT);
640      case ISD::SETNE:  return getConstant(C1 != C2, VT);
641      case ISD::SETLT:  return getConstant(C1 < C2, VT);
642      case ISD::SETGT:  return getConstant(C1 > C2, VT);
643      case ISD::SETLE:  return getConstant(C1 <= C2, VT);
644      case ISD::SETGE:  return getConstant(C1 >= C2, VT);
645      }
646    } else {
647      // Ensure that the constant occurs on the RHS.
648      return getSetCC(VT, N2, N1, ISD::getSetCCSwappedOperands(Cond));
649    }
650
651  if (N1 == N2) {
652    // We can always fold X == Y for integer setcc's.
653    if (MVT::isInteger(N1.getValueType()))
654      return getConstant(ISD::isTrueWhenEqual(Cond), VT);
655    unsigned UOF = ISD::getUnorderedFlavor(Cond);
656    if (UOF == 2)   // FP operators that are undefined on NaNs.
657      return getConstant(ISD::isTrueWhenEqual(Cond), VT);
658    if (UOF == unsigned(ISD::isTrueWhenEqual(Cond)))
659      return getConstant(UOF, VT);
660    // Otherwise, we can't fold it.  However, we can simplify it to SETUO/SETO
661    // if it is not already.
662    ISD::CondCode NewCond = UOF == 0 ? ISD::SETUO : ISD::SETO;
663    if (NewCond != Cond)
664      return getSetCC(VT, N1, N2, NewCond);
665  }
666
667  if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
668      MVT::isInteger(N1.getValueType())) {
669    if (N1.getOpcode() == ISD::ADD || N1.getOpcode() == ISD::SUB ||
670        N1.getOpcode() == ISD::XOR) {
671      // Simplify (X+Y) == (X+Z) -->  Y == Z
672      if (N1.getOpcode() == N2.getOpcode()) {
673        if (N1.getOperand(0) == N2.getOperand(0))
674          return getSetCC(VT, N1.getOperand(1), N2.getOperand(1), Cond);
675        if (N1.getOperand(1) == N2.getOperand(1))
676          return getSetCC(VT, N1.getOperand(0), N2.getOperand(0), Cond);
677        if (isCommutativeBinOp(N1.getOpcode())) {
678          // If X op Y == Y op X, try other combinations.
679          if (N1.getOperand(0) == N2.getOperand(1))
680            return getSetCC(VT, N1.getOperand(1), N2.getOperand(0), Cond);
681          if (N1.getOperand(1) == N2.getOperand(0))
682            return getSetCC(VT, N1.getOperand(1), N2.getOperand(1), Cond);
683        }
684      }
685
686      // FIXME: move this stuff to the DAG Combiner when it exists!
687
688      // Simplify (X+Z) == X -->  Z == 0
689      if (N1.getOperand(0) == N2)
690        return getSetCC(VT, N1.getOperand(1),
691                        getConstant(0, N1.getValueType()), Cond);
692      if (N1.getOperand(1) == N2) {
693        if (isCommutativeBinOp(N1.getOpcode()))
694          return getSetCC(VT, N1.getOperand(0),
695                          getConstant(0, N1.getValueType()), Cond);
696        else {
697          assert(N1.getOpcode() == ISD::SUB && "Unexpected operation!");
698          // (Z-X) == X  --> Z == X<<1
699          return getSetCC(VT, N1.getOperand(0),
700                          getNode(ISD::SHL, N2.getValueType(),
701                                  N2, getConstant(1, TLI.getShiftAmountTy())),
702                          Cond);
703        }
704      }
705    }
706
707    if (N2.getOpcode() == ISD::ADD || N2.getOpcode() == ISD::SUB ||
708        N2.getOpcode() == ISD::XOR) {
709      // Simplify  X == (X+Z) -->  Z == 0
710      if (N2.getOperand(0) == N1) {
711        return getSetCC(VT, N2.getOperand(1),
712                        getConstant(0, N2.getValueType()), Cond);
713      } else if (N2.getOperand(1) == N1) {
714        if (isCommutativeBinOp(N2.getOpcode())) {
715          return getSetCC(VT, N2.getOperand(0),
716                          getConstant(0, N2.getValueType()), Cond);
717        } else {
718          assert(N2.getOpcode() == ISD::SUB && "Unexpected operation!");
719          // X == (Z-X)  --> X<<1 == Z
720          return getSetCC(VT, getNode(ISD::SHL, N2.getValueType(), N1,
721                                      getConstant(1, TLI.getShiftAmountTy())),
722                          N2.getOperand(0), Cond);
723        }
724      }
725    }
726  }
727
728  // Fold away ALL boolean setcc's.
729  if (N1.getValueType() == MVT::i1) {
730    switch (Cond) {
731    default: assert(0 && "Unknown integer setcc!");
732    case ISD::SETEQ:  // X == Y  -> (X^Y)^1
733      N1 = getNode(ISD::XOR, MVT::i1,
734                   getNode(ISD::XOR, MVT::i1, N1, N2),
735                   getConstant(1, MVT::i1));
736      break;
737    case ISD::SETNE:  // X != Y   -->  (X^Y)
738      N1 = getNode(ISD::XOR, MVT::i1, N1, N2);
739      break;
740    case ISD::SETGT:  // X >s Y   -->  X == 0 & Y == 1  -->  X^1 & Y
741    case ISD::SETULT: // X <u Y   -->  X == 0 & Y == 1  -->  X^1 & Y
742      N1 = getNode(ISD::AND, MVT::i1, N2,
743                   getNode(ISD::XOR, MVT::i1, N1, getConstant(1, MVT::i1)));
744      break;
745    case ISD::SETLT:  // X <s Y   --> X == 1 & Y == 0  -->  Y^1 & X
746    case ISD::SETUGT: // X >u Y   --> X == 1 & Y == 0  -->  Y^1 & X
747      N1 = getNode(ISD::AND, MVT::i1, N1,
748                   getNode(ISD::XOR, MVT::i1, N2, getConstant(1, MVT::i1)));
749      break;
750    case ISD::SETULE: // X <=u Y  --> X == 0 | Y == 1  -->  X^1 | Y
751    case ISD::SETGE:  // X >=s Y  --> X == 0 | Y == 1  -->  X^1 | Y
752      N1 = getNode(ISD::OR, MVT::i1, N2,
753                   getNode(ISD::XOR, MVT::i1, N1, getConstant(1, MVT::i1)));
754      break;
755    case ISD::SETUGE: // X >=u Y  --> X == 1 | Y == 0  -->  Y^1 | X
756    case ISD::SETLE:  // X <=s Y  --> X == 1 | Y == 0  -->  Y^1 | X
757      N1 = getNode(ISD::OR, MVT::i1, N1,
758                   getNode(ISD::XOR, MVT::i1, N2, getConstant(1, MVT::i1)));
759      break;
760    }
761    if (VT != MVT::i1)
762      N1 = getNode(ISD::ZERO_EXTEND, VT, N1);
763    return N1;
764  }
765
766  // Could not fold it.
767  return SDOperand();
768}
769
770SDOperand SelectionDAG::SimplifySelectCC(SDOperand N1, SDOperand N2,
771                                         SDOperand N3, SDOperand N4,
772                                         ISD::CondCode CC) {
773  MVT::ValueType VT = N3.getValueType();
774  ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.Val);
775  ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.Val);
776  ConstantSDNode *N4C = dyn_cast<ConstantSDNode>(N4.Val);
777
778  // Check to see if we can simplify the select into an fabs node
779  if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N2)) {
780    // Allow either -0.0 or 0.0
781    if (CFP->getValue() == 0.0) {
782      // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
783      if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
784          N1 == N3 && N4.getOpcode() == ISD::FNEG &&
785          N1 == N4.getOperand(0))
786        return getNode(ISD::FABS, VT, N1);
787
788      // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
789      if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
790          N1 == N4 && N3.getOpcode() == ISD::FNEG &&
791          N3.getOperand(0) == N4)
792        return getNode(ISD::FABS, VT, N4);
793    }
794  }
795
796  // Check to see if we can perform the "gzip trick", transforming
797  // select_cc setlt X, 0, A, 0 -> and (sra X, size(X)-1), A
798  if (N2C && N2C->isNullValue() && N4C && N4C->isNullValue() &&
799      MVT::isInteger(N1.getValueType()) &&
800      MVT::isInteger(N3.getValueType()) && CC == ISD::SETLT) {
801    MVT::ValueType XType = N1.getValueType();
802    MVT::ValueType AType = N3.getValueType();
803    if (XType >= AType) {
804      // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
805      // single-bit constant.  FIXME: remove once the dag combiner
806      // exists.
807      if (N3C && ((N3C->getValue() & (N3C->getValue()-1)) == 0)) {
808        unsigned ShCtV = Log2_64(N3C->getValue());
809        ShCtV = MVT::getSizeInBits(XType)-ShCtV-1;
810        SDOperand ShCt = getConstant(ShCtV, TLI.getShiftAmountTy());
811        SDOperand Shift = getNode(ISD::SRL, XType, N1, ShCt);
812        if (XType > AType)
813          Shift = getNode(ISD::TRUNCATE, AType, Shift);
814        return getNode(ISD::AND, AType, Shift, N3);
815      }
816      SDOperand Shift = getNode(ISD::SRA, XType, N1,
817                                getConstant(MVT::getSizeInBits(XType)-1,
818                                            TLI.getShiftAmountTy()));
819      if (XType > AType)
820        Shift = getNode(ISD::TRUNCATE, AType, Shift);
821      return getNode(ISD::AND, AType, Shift, N3);
822    }
823  }
824
825  // Check to see if this is an integer abs. select_cc setl[te] X, 0, -X, X ->
826  // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
827  if (N2C && N2C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE) &&
828      N1 == N4 && N3.getOpcode() == ISD::SUB && N1 == N3.getOperand(1)) {
829    if (ConstantSDNode *SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0))) {
830      MVT::ValueType XType = N1.getValueType();
831      if (SubC->isNullValue() && MVT::isInteger(XType)) {
832        SDOperand Shift = getNode(ISD::SRA, XType, N1,
833                                  getConstant(MVT::getSizeInBits(XType)-1,
834                                              TLI.getShiftAmountTy()));
835        return getNode(ISD::XOR, XType, getNode(ISD::ADD, XType, N1, Shift),
836                       Shift);
837      }
838    }
839  }
840
841  // Could not fold it.
842  return SDOperand();
843}
844
845/// getNode - Gets or creates the specified node.
846///
847SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT) {
848  SDNode *N = new SDNode(Opcode, VT);
849  AllNodes.push_back(N);
850  return SDOperand(N, 0);
851}
852
853SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT,
854                                SDOperand Operand) {
855  if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Operand.Val)) {
856    uint64_t Val = C->getValue();
857    switch (Opcode) {
858    default: break;
859    case ISD::SIGN_EXTEND: return getConstant(C->getSignExtended(), VT);
860    case ISD::ZERO_EXTEND: return getConstant(Val, VT);
861    case ISD::TRUNCATE:    return getConstant(Val, VT);
862    case ISD::SINT_TO_FP:  return getConstantFP(C->getSignExtended(), VT);
863    case ISD::UINT_TO_FP:  return getConstantFP(C->getValue(), VT);
864    }
865  }
866
867  if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Operand.Val))
868    switch (Opcode) {
869    case ISD::FNEG:
870      return getConstantFP(-C->getValue(), VT);
871    case ISD::FP_ROUND:
872    case ISD::FP_EXTEND:
873      return getConstantFP(C->getValue(), VT);
874    case ISD::FP_TO_SINT:
875      return getConstant((int64_t)C->getValue(), VT);
876    case ISD::FP_TO_UINT:
877      return getConstant((uint64_t)C->getValue(), VT);
878    }
879
880  unsigned OpOpcode = Operand.Val->getOpcode();
881  switch (Opcode) {
882  case ISD::TokenFactor:
883    return Operand;         // Factor of one node?  No factor.
884  case ISD::SIGN_EXTEND:
885    if (Operand.getValueType() == VT) return Operand;   // noop extension
886    if (OpOpcode == ISD::SIGN_EXTEND || OpOpcode == ISD::ZERO_EXTEND)
887      return getNode(OpOpcode, VT, Operand.Val->getOperand(0));
888    break;
889  case ISD::ZERO_EXTEND:
890    if (Operand.getValueType() == VT) return Operand;   // noop extension
891    if (OpOpcode == ISD::ZERO_EXTEND)   // (zext (zext x)) -> (zext x)
892      return getNode(ISD::ZERO_EXTEND, VT, Operand.Val->getOperand(0));
893    break;
894  case ISD::TRUNCATE:
895    if (Operand.getValueType() == VT) return Operand;   // noop truncate
896    if (OpOpcode == ISD::TRUNCATE)
897      return getNode(ISD::TRUNCATE, VT, Operand.Val->getOperand(0));
898    else if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND) {
899      // If the source is smaller than the dest, we still need an extend.
900      if (Operand.Val->getOperand(0).getValueType() < VT)
901        return getNode(OpOpcode, VT, Operand.Val->getOperand(0));
902      else if (Operand.Val->getOperand(0).getValueType() > VT)
903        return getNode(ISD::TRUNCATE, VT, Operand.Val->getOperand(0));
904      else
905        return Operand.Val->getOperand(0);
906    }
907    break;
908  case ISD::FNEG:
909    if (OpOpcode == ISD::SUB)   // -(X-Y) -> (Y-X)
910      return getNode(ISD::SUB, VT, Operand.Val->getOperand(1),
911                     Operand.Val->getOperand(0));
912    if (OpOpcode == ISD::FNEG)  // --X -> X
913      return Operand.Val->getOperand(0);
914    break;
915  case ISD::FABS:
916    if (OpOpcode == ISD::FNEG)  // abs(-X) -> abs(X)
917      return getNode(ISD::FABS, VT, Operand.Val->getOperand(0));
918    break;
919  }
920
921  SDNode *&N = UnaryOps[std::make_pair(Opcode, std::make_pair(Operand, VT))];
922  if (N) return SDOperand(N, 0);
923  N = new SDNode(Opcode, Operand);
924  N->setValueTypes(VT);
925  AllNodes.push_back(N);
926  return SDOperand(N, 0);
927}
928
929/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero.  We use
930/// this predicate to simplify operations downstream.  V and Mask are known to
931/// be the same type.
932static bool MaskedValueIsZero(const SDOperand &Op, uint64_t Mask,
933                              const TargetLowering &TLI) {
934  unsigned SrcBits;
935  if (Mask == 0) return true;
936
937  // If we know the result of a setcc has the top bits zero, use this info.
938  switch (Op.getOpcode()) {
939  case ISD::Constant:
940    return (cast<ConstantSDNode>(Op)->getValue() & Mask) == 0;
941
942  case ISD::SETCC:
943    return ((Mask & 1) == 0) &&
944           TLI.getSetCCResultContents() == TargetLowering::ZeroOrOneSetCCResult;
945
946  case ISD::ZEXTLOAD:
947    SrcBits = MVT::getSizeInBits(cast<VTSDNode>(Op.getOperand(3))->getVT());
948    return (Mask & ((1ULL << SrcBits)-1)) == 0; // Returning only the zext bits.
949  case ISD::ZERO_EXTEND:
950    SrcBits = MVT::getSizeInBits(Op.getOperand(0).getValueType());
951    return MaskedValueIsZero(Op.getOperand(0),Mask & ((1ULL << SrcBits)-1),TLI);
952
953  case ISD::AND:
954    // (X & C1) & C2 == 0   iff   C1 & C2 == 0.
955    if (ConstantSDNode *AndRHS = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
956      return MaskedValueIsZero(Op.getOperand(0),AndRHS->getValue() & Mask, TLI);
957
958    // FALL THROUGH
959  case ISD::OR:
960  case ISD::XOR:
961    return MaskedValueIsZero(Op.getOperand(0), Mask, TLI) &&
962           MaskedValueIsZero(Op.getOperand(1), Mask, TLI);
963  case ISD::SELECT:
964    return MaskedValueIsZero(Op.getOperand(1), Mask, TLI) &&
965           MaskedValueIsZero(Op.getOperand(2), Mask, TLI);
966
967  case ISD::SRL:
968    // (ushr X, C1) & C2 == 0   iff  X & (C2 << C1) == 0
969    if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
970      uint64_t NewVal = Mask << ShAmt->getValue();
971      SrcBits = MVT::getSizeInBits(Op.getValueType());
972      if (SrcBits != 64) NewVal &= (1ULL << SrcBits)-1;
973      return MaskedValueIsZero(Op.getOperand(0), NewVal, TLI);
974    }
975    return false;
976  case ISD::SHL:
977    // (ushl X, C1) & C2 == 0   iff  X & (C2 >> C1) == 0
978    if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
979      uint64_t NewVal = Mask >> ShAmt->getValue();
980      return MaskedValueIsZero(Op.getOperand(0), NewVal, TLI);
981    }
982    return false;
983    // TODO we could handle some SRA cases here.
984  default: break;
985  }
986
987  return false;
988}
989
990
991
992SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT,
993                                SDOperand N1, SDOperand N2) {
994#ifndef NDEBUG
995  switch (Opcode) {
996  case ISD::TokenFactor:
997    assert(VT == MVT::Other && N1.getValueType() == MVT::Other &&
998           N2.getValueType() == MVT::Other && "Invalid token factor!");
999    break;
1000  case ISD::AND:
1001  case ISD::OR:
1002  case ISD::XOR:
1003  case ISD::UDIV:
1004  case ISD::UREM:
1005  case ISD::MULHU:
1006  case ISD::MULHS:
1007    assert(MVT::isInteger(VT) && "This operator does not apply to FP types!");
1008    // fall through
1009  case ISD::ADD:
1010  case ISD::SUB:
1011  case ISD::MUL:
1012  case ISD::SDIV:
1013  case ISD::SREM:
1014    assert(N1.getValueType() == N2.getValueType() &&
1015           N1.getValueType() == VT && "Binary operator types must match!");
1016    break;
1017
1018  case ISD::SHL:
1019  case ISD::SRA:
1020  case ISD::SRL:
1021    assert(VT == N1.getValueType() &&
1022           "Shift operators return type must be the same as their first arg");
1023    assert(MVT::isInteger(VT) && MVT::isInteger(N2.getValueType()) &&
1024           VT != MVT::i1 && "Shifts only work on integers");
1025    break;
1026  case ISD::FP_ROUND_INREG: {
1027    MVT::ValueType EVT = cast<VTSDNode>(N2)->getVT();
1028    assert(VT == N1.getValueType() && "Not an inreg round!");
1029    assert(MVT::isFloatingPoint(VT) && MVT::isFloatingPoint(EVT) &&
1030           "Cannot FP_ROUND_INREG integer types");
1031    assert(EVT <= VT && "Not rounding down!");
1032    break;
1033  }
1034  case ISD::SIGN_EXTEND_INREG: {
1035    MVT::ValueType EVT = cast<VTSDNode>(N2)->getVT();
1036    assert(VT == N1.getValueType() && "Not an inreg extend!");
1037    assert(MVT::isInteger(VT) && MVT::isInteger(EVT) &&
1038           "Cannot *_EXTEND_INREG FP types");
1039    assert(EVT <= VT && "Not extending!");
1040  }
1041
1042  default: break;
1043  }
1044#endif
1045
1046  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val);
1047  ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.Val);
1048  if (N1C) {
1049    if (N2C) {
1050      uint64_t C1 = N1C->getValue(), C2 = N2C->getValue();
1051      switch (Opcode) {
1052      case ISD::ADD: return getConstant(C1 + C2, VT);
1053      case ISD::SUB: return getConstant(C1 - C2, VT);
1054      case ISD::MUL: return getConstant(C1 * C2, VT);
1055      case ISD::UDIV:
1056        if (C2) return getConstant(C1 / C2, VT);
1057        break;
1058      case ISD::UREM :
1059        if (C2) return getConstant(C1 % C2, VT);
1060        break;
1061      case ISD::SDIV :
1062        if (C2) return getConstant(N1C->getSignExtended() /
1063                                   N2C->getSignExtended(), VT);
1064        break;
1065      case ISD::SREM :
1066        if (C2) return getConstant(N1C->getSignExtended() %
1067                                   N2C->getSignExtended(), VT);
1068        break;
1069      case ISD::AND  : return getConstant(C1 & C2, VT);
1070      case ISD::OR   : return getConstant(C1 | C2, VT);
1071      case ISD::XOR  : return getConstant(C1 ^ C2, VT);
1072      case ISD::SHL  : return getConstant(C1 << (int)C2, VT);
1073      case ISD::SRL  : return getConstant(C1 >> (unsigned)C2, VT);
1074      case ISD::SRA  : return getConstant(N1C->getSignExtended() >>(int)C2, VT);
1075      default: break;
1076      }
1077
1078    } else {      // Cannonicalize constant to RHS if commutative
1079      if (isCommutativeBinOp(Opcode)) {
1080        std::swap(N1C, N2C);
1081        std::swap(N1, N2);
1082      }
1083    }
1084
1085    switch (Opcode) {
1086    default: break;
1087    case ISD::SHL:    // shl  0, X -> 0
1088      if (N1C->isNullValue()) return N1;
1089      break;
1090    case ISD::SRL:    // srl  0, X -> 0
1091      if (N1C->isNullValue()) return N1;
1092      break;
1093    case ISD::SRA:    // sra -1, X -> -1
1094      if (N1C->isAllOnesValue()) return N1;
1095      break;
1096    case ISD::SIGN_EXTEND_INREG:  // SIGN_EXTEND_INREG N1C, EVT
1097      // Extending a constant?  Just return the extended constant.
1098      SDOperand Tmp = getNode(ISD::TRUNCATE, cast<VTSDNode>(N2)->getVT(), N1);
1099      return getNode(ISD::SIGN_EXTEND, VT, Tmp);
1100    }
1101  }
1102
1103  if (N2C) {
1104    uint64_t C2 = N2C->getValue();
1105
1106    switch (Opcode) {
1107    case ISD::ADD:
1108      if (!C2) return N1;         // add X, 0 -> X
1109      break;
1110    case ISD::SUB:
1111      if (!C2) return N1;         // sub X, 0 -> X
1112      return getNode(ISD::ADD, VT, N1, getConstant(-C2, VT));
1113    case ISD::MUL:
1114      if (!C2) return N2;         // mul X, 0 -> 0
1115      if (N2C->isAllOnesValue()) // mul X, -1 -> 0-X
1116        return getNode(ISD::SUB, VT, getConstant(0, VT), N1);
1117
1118      // FIXME: Move this to the DAG combiner when it exists.
1119      if ((C2 & C2-1) == 0) {
1120        SDOperand ShAmt = getConstant(Log2_64(C2), TLI.getShiftAmountTy());
1121        return getNode(ISD::SHL, VT, N1, ShAmt);
1122      }
1123      break;
1124
1125    case ISD::MULHU:
1126    case ISD::MULHS:
1127      if (!C2) return N2;         // mul X, 0 -> 0
1128
1129      if (C2 == 1)                // 0X*01 -> 0X  hi(0X) == 0
1130        return getConstant(0, VT);
1131
1132      // Many others could be handled here, including -1, powers of 2, etc.
1133      break;
1134
1135    case ISD::UDIV:
1136      // FIXME: Move this to the DAG combiner when it exists.
1137      if ((C2 & C2-1) == 0 && C2) {
1138        SDOperand ShAmt = getConstant(Log2_64(C2), TLI.getShiftAmountTy());
1139        return getNode(ISD::SRL, VT, N1, ShAmt);
1140      }
1141      break;
1142
1143    case ISD::SHL:
1144    case ISD::SRL:
1145    case ISD::SRA:
1146      // If the shift amount is bigger than the size of the data, then all the
1147      // bits are shifted out.  Simplify to undef.
1148      if (C2 >= MVT::getSizeInBits(N1.getValueType())) {
1149        return getNode(ISD::UNDEF, N1.getValueType());
1150      }
1151      if (C2 == 0) return N1;
1152
1153      if (Opcode == ISD::SRA) {
1154        // If the sign bit is known to be zero, switch this to a SRL.
1155        if (MaskedValueIsZero(N1,
1156                              1ULL << MVT::getSizeInBits(N1.getValueType())-1,
1157                              TLI))
1158          return getNode(ISD::SRL, N1.getValueType(), N1, N2);
1159      } else {
1160        // If the part left over is known to be zero, the whole thing is zero.
1161        uint64_t TypeMask = ~0ULL >> (64-MVT::getSizeInBits(N1.getValueType()));
1162        if (Opcode == ISD::SRL) {
1163          if (MaskedValueIsZero(N1, TypeMask << C2, TLI))
1164            return getConstant(0, N1.getValueType());
1165        } else if (Opcode == ISD::SHL) {
1166          if (MaskedValueIsZero(N1, TypeMask >> C2, TLI))
1167            return getConstant(0, N1.getValueType());
1168        }
1169      }
1170
1171      if (Opcode == ISD::SHL && N1.getNumOperands() == 2)
1172        if (ConstantSDNode *OpSA = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
1173          unsigned OpSAC = OpSA->getValue();
1174          if (N1.getOpcode() == ISD::SHL) {
1175            if (C2+OpSAC >= MVT::getSizeInBits(N1.getValueType()))
1176              return getConstant(0, N1.getValueType());
1177            return getNode(ISD::SHL, N1.getValueType(), N1.getOperand(0),
1178                           getConstant(C2+OpSAC, N2.getValueType()));
1179          } else if (N1.getOpcode() == ISD::SRL) {
1180            // (X >> C1) << C2:  if C2 > C1, ((X & ~0<<C1) << C2-C1)
1181            SDOperand Mask = getNode(ISD::AND, VT, N1.getOperand(0),
1182                                     getConstant(~0ULL << OpSAC, VT));
1183            if (C2 > OpSAC) {
1184              return getNode(ISD::SHL, VT, Mask,
1185                             getConstant(C2-OpSAC, N2.getValueType()));
1186            } else {
1187              // (X >> C1) << C2:  if C2 <= C1, ((X & ~0<<C1) >> C1-C2)
1188              return getNode(ISD::SRL, VT, Mask,
1189                             getConstant(OpSAC-C2, N2.getValueType()));
1190            }
1191          } else if (N1.getOpcode() == ISD::SRA) {
1192            // if C1 == C2, just mask out low bits.
1193            if (C2 == OpSAC)
1194              return getNode(ISD::AND, VT, N1.getOperand(0),
1195                             getConstant(~0ULL << C2, VT));
1196          }
1197        }
1198      break;
1199
1200    case ISD::AND:
1201      if (!C2) return N2;         // X and 0 -> 0
1202      if (N2C->isAllOnesValue())
1203        return N1;                // X and -1 -> X
1204
1205      if (MaskedValueIsZero(N1, C2, TLI))  // X and 0 -> 0
1206        return getConstant(0, VT);
1207
1208      {
1209        uint64_t NotC2 = ~C2;
1210        if (VT != MVT::i64)
1211          NotC2 &= (1ULL << MVT::getSizeInBits(VT))-1;
1212
1213        if (MaskedValueIsZero(N1, NotC2, TLI))
1214          return N1;                // if (X & ~C2) -> 0, the and is redundant
1215      }
1216
1217      // FIXME: Should add a corresponding version of this for
1218      // ZERO_EXTEND/SIGN_EXTEND by converting them to an ANY_EXTEND node which
1219      // we don't have yet.
1220
1221      // and (sign_extend_inreg x:16:32), 1 -> and x, 1
1222      if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1223        // If we are masking out the part of our input that was extended, just
1224        // mask the input to the extension directly.
1225        unsigned ExtendBits =
1226          MVT::getSizeInBits(cast<VTSDNode>(N1.getOperand(1))->getVT());
1227        if ((C2 & (~0ULL << ExtendBits)) == 0)
1228          return getNode(ISD::AND, VT, N1.getOperand(0), N2);
1229      } else if (N1.getOpcode() == ISD::OR) {
1230        if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
1231          if ((ORI->getValue() & C2) == C2) {
1232            // If the 'or' is setting all of the bits that we are masking for,
1233            // we know the result of the AND will be the AND mask itself.
1234            return N2;
1235          }
1236      }
1237      break;
1238    case ISD::OR:
1239      if (!C2)return N1;          // X or 0 -> X
1240      if (N2C->isAllOnesValue())
1241        return N2;                // X or -1 -> -1
1242      break;
1243    case ISD::XOR:
1244      if (!C2) return N1;        // X xor 0 -> X
1245      if (N2C->isAllOnesValue()) {
1246        if (N1.Val->getOpcode() == ISD::SETCC){
1247          SDNode *SetCC = N1.Val;
1248          // !(X op Y) -> (X !op Y)
1249          bool isInteger = MVT::isInteger(SetCC->getOperand(0).getValueType());
1250          ISD::CondCode CC = cast<CondCodeSDNode>(SetCC->getOperand(2))->get();
1251          return getSetCC(SetCC->getValueType(0),
1252                          SetCC->getOperand(0), SetCC->getOperand(1),
1253                          ISD::getSetCCInverse(CC, isInteger));
1254        } else if (N1.getOpcode() == ISD::AND || N1.getOpcode() == ISD::OR) {
1255          SDNode *Op = N1.Val;
1256          // !(X or Y) -> (!X and !Y) iff X or Y are freely invertible
1257          // !(X and Y) -> (!X or !Y) iff X or Y are freely invertible
1258          SDOperand LHS = Op->getOperand(0), RHS = Op->getOperand(1);
1259          if (isInvertibleForFree(RHS) || isInvertibleForFree(LHS)) {
1260            LHS = getNode(ISD::XOR, VT, LHS, N2);  // RHS = ~LHS
1261            RHS = getNode(ISD::XOR, VT, RHS, N2);  // RHS = ~RHS
1262            if (Op->getOpcode() == ISD::AND)
1263              return getNode(ISD::OR, VT, LHS, RHS);
1264            return getNode(ISD::AND, VT, LHS, RHS);
1265          }
1266        }
1267        // X xor -1 -> not(x)  ?
1268      }
1269      break;
1270    }
1271
1272    // Reassociate ((X op C1) op C2) if possible.
1273    if (N1.getOpcode() == Opcode && isAssociativeBinOp(Opcode))
1274      if (ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N1.Val->getOperand(1)))
1275        return getNode(Opcode, VT, N1.Val->getOperand(0),
1276                       getNode(Opcode, VT, N2, N1.Val->getOperand(1)));
1277  }
1278
1279  ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1.Val);
1280  ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2.Val);
1281  if (N1CFP) {
1282    if (N2CFP) {
1283      double C1 = N1CFP->getValue(), C2 = N2CFP->getValue();
1284      switch (Opcode) {
1285      case ISD::ADD: return getConstantFP(C1 + C2, VT);
1286      case ISD::SUB: return getConstantFP(C1 - C2, VT);
1287      case ISD::MUL: return getConstantFP(C1 * C2, VT);
1288      case ISD::SDIV:
1289        if (C2) return getConstantFP(C1 / C2, VT);
1290        break;
1291      case ISD::SREM :
1292        if (C2) return getConstantFP(fmod(C1, C2), VT);
1293        break;
1294      default: break;
1295      }
1296
1297    } else {      // Cannonicalize constant to RHS if commutative
1298      if (isCommutativeBinOp(Opcode)) {
1299        std::swap(N1CFP, N2CFP);
1300        std::swap(N1, N2);
1301      }
1302    }
1303
1304    if (Opcode == ISD::FP_ROUND_INREG)
1305      return getNode(ISD::FP_EXTEND, VT,
1306                     getNode(ISD::FP_ROUND, cast<VTSDNode>(N2)->getVT(), N1));
1307  }
1308
1309  // Finally, fold operations that do not require constants.
1310  switch (Opcode) {
1311  case ISD::TokenFactor:
1312    if (N1.getOpcode() == ISD::EntryToken)
1313      return N2;
1314    if (N2.getOpcode() == ISD::EntryToken)
1315      return N1;
1316    break;
1317
1318  case ISD::AND:
1319  case ISD::OR:
1320    if (N1.Val->getOpcode() == ISD::SETCC && N2.Val->getOpcode() == ISD::SETCC){
1321      SDNode *LHS = N1.Val, *RHS = N2.Val;
1322      SDOperand LL = LHS->getOperand(0), RL = RHS->getOperand(0);
1323      SDOperand LR = LHS->getOperand(1), RR = RHS->getOperand(1);
1324      ISD::CondCode Op1 = cast<CondCodeSDNode>(LHS->getOperand(2))->get();
1325      ISD::CondCode Op2 = cast<CondCodeSDNode>(RHS->getOperand(2))->get();
1326
1327      if (LR == RR && isa<ConstantSDNode>(LR) &&
1328          Op2 == Op1 && MVT::isInteger(LL.getValueType())) {
1329        // (X != 0) | (Y != 0) -> (X|Y != 0)
1330        // (X == 0) & (Y == 0) -> (X|Y == 0)
1331        // (X <  0) | (Y <  0) -> (X|Y < 0)
1332        if (cast<ConstantSDNode>(LR)->getValue() == 0 &&
1333            ((Op2 == ISD::SETEQ && Opcode == ISD::AND) ||
1334             (Op2 == ISD::SETNE && Opcode == ISD::OR) ||
1335             (Op2 == ISD::SETLT && Opcode == ISD::OR)))
1336          return getSetCC(VT, getNode(ISD::OR, LR.getValueType(), LL, RL), LR,
1337                          Op2);
1338
1339        if (cast<ConstantSDNode>(LR)->isAllOnesValue()) {
1340          // (X == -1) & (Y == -1) -> (X&Y == -1)
1341          // (X != -1) | (Y != -1) -> (X&Y != -1)
1342          // (X >  -1) | (Y >  -1) -> (X&Y >  -1)
1343          if ((Opcode == ISD::AND && Op2 == ISD::SETEQ) ||
1344              (Opcode == ISD::OR  && Op2 == ISD::SETNE) ||
1345              (Opcode == ISD::OR  && Op2 == ISD::SETGT))
1346            return getSetCC(VT, getNode(ISD::AND, LR.getValueType(), LL, RL),
1347                            LR, Op2);
1348          // (X >  -1) & (Y >  -1) -> (X|Y > -1)
1349          if (Opcode == ISD::AND && Op2 == ISD::SETGT)
1350            return getSetCC(VT, getNode(ISD::OR, LR.getValueType(), LL, RL),
1351                            LR, Op2);
1352        }
1353      }
1354
1355      // (X op1 Y) | (Y op2 X) -> (X op1 Y) | (X swapop2 Y)
1356      if (LL == RR && LR == RL) {
1357        Op2 = ISD::getSetCCSwappedOperands(Op2);
1358        goto MatchedBackwards;
1359      }
1360
1361      if (LL == RL && LR == RR) {
1362      MatchedBackwards:
1363        ISD::CondCode Result;
1364        bool isInteger = MVT::isInteger(LL.getValueType());
1365        if (Opcode == ISD::OR)
1366          Result = ISD::getSetCCOrOperation(Op1, Op2, isInteger);
1367        else
1368          Result = ISD::getSetCCAndOperation(Op1, Op2, isInteger);
1369
1370        if (Result != ISD::SETCC_INVALID)
1371          return getSetCC(LHS->getValueType(0), LL, LR, Result);
1372      }
1373    }
1374
1375    // and/or zext(a), zext(b) -> zext(and/or a, b)
1376    if (N1.getOpcode() == ISD::ZERO_EXTEND &&
1377        N2.getOpcode() == ISD::ZERO_EXTEND &&
1378        N1.getOperand(0).getValueType() == N2.getOperand(0).getValueType())
1379      return getNode(ISD::ZERO_EXTEND, VT,
1380                     getNode(Opcode, N1.getOperand(0).getValueType(),
1381                             N1.getOperand(0), N2.getOperand(0)));
1382    break;
1383  case ISD::XOR:
1384    if (N1 == N2) return getConstant(0, VT);  // xor X, Y -> 0
1385    break;
1386  case ISD::ADD:
1387    if (N2.getOpcode() == ISD::FNEG)          // (A+ (-B) -> A-B
1388      return getNode(ISD::SUB, VT, N1, N2.getOperand(0));
1389    if (N1.getOpcode() == ISD::FNEG)          // ((-A)+B) -> B-A
1390      return getNode(ISD::SUB, VT, N2, N1.getOperand(0));
1391    if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
1392        cast<ConstantSDNode>(N1.getOperand(0))->getValue() == 0)
1393      return getNode(ISD::SUB, VT, N2, N1.getOperand(1)); // (0-A)+B -> B-A
1394    if (N2.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N2.getOperand(0)) &&
1395        cast<ConstantSDNode>(N2.getOperand(0))->getValue() == 0)
1396      return getNode(ISD::SUB, VT, N1, N2.getOperand(1)); // A+(0-B) -> A-B
1397    if (N2.getOpcode() == ISD::SUB && N1 == N2.Val->getOperand(1) &&
1398        !MVT::isFloatingPoint(N2.getValueType()))
1399      return N2.Val->getOperand(0); // A+(B-A) -> B
1400    break;
1401  case ISD::SUB:
1402    if (N1.getOpcode() == ISD::ADD) {
1403      if (N1.Val->getOperand(0) == N2 &&
1404          !MVT::isFloatingPoint(N2.getValueType()))
1405        return N1.Val->getOperand(1);         // (A+B)-A == B
1406      if (N1.Val->getOperand(1) == N2 &&
1407          !MVT::isFloatingPoint(N2.getValueType()))
1408        return N1.Val->getOperand(0);         // (A+B)-B == A
1409    }
1410    if (N2.getOpcode() == ISD::FNEG)          // (A- (-B) -> A+B
1411      return getNode(ISD::ADD, VT, N1, N2.getOperand(0));
1412    break;
1413  case ISD::FP_ROUND_INREG:
1414    if (cast<VTSDNode>(N2)->getVT() == VT) return N1;  // Not actually rounding.
1415    break;
1416  case ISD::SIGN_EXTEND_INREG: {
1417    MVT::ValueType EVT = cast<VTSDNode>(N2)->getVT();
1418    if (EVT == VT) return N1;  // Not actually extending
1419
1420    // If we are sign extending an extension, use the original source.
1421    if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG)
1422      if (cast<VTSDNode>(N1.getOperand(1))->getVT() <= EVT)
1423        return N1;
1424
1425    // If we are sign extending a sextload, return just the load.
1426    if (N1.getOpcode() == ISD::SEXTLOAD)
1427      if (cast<VTSDNode>(N1.getOperand(3))->getVT() <= EVT)
1428        return N1;
1429
1430    // If we are extending the result of a setcc, and we already know the
1431    // contents of the top bits, eliminate the extension.
1432    if (N1.getOpcode() == ISD::SETCC &&
1433        TLI.getSetCCResultContents() ==
1434                        TargetLowering::ZeroOrNegativeOneSetCCResult)
1435      return N1;
1436
1437    // If we are sign extending the result of an (and X, C) operation, and we
1438    // know the extended bits are zeros already, don't do the extend.
1439    if (N1.getOpcode() == ISD::AND)
1440      if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
1441        uint64_t Mask = N1C->getValue();
1442        unsigned NumBits = MVT::getSizeInBits(EVT);
1443        if ((Mask & (~0ULL << (NumBits-1))) == 0)
1444          return N1;
1445      }
1446    break;
1447  }
1448
1449  // FIXME: figure out how to safely handle things like
1450  // int foo(int x) { return 1 << (x & 255); }
1451  // int bar() { return foo(256); }
1452#if 0
1453  case ISD::SHL:
1454  case ISD::SRL:
1455  case ISD::SRA:
1456    if (N2.getOpcode() == ISD::SIGN_EXTEND_INREG &&
1457        cast<VTSDNode>(N2.getOperand(1))->getVT() != MVT::i1)
1458      return getNode(Opcode, VT, N1, N2.getOperand(0));
1459    else if (N2.getOpcode() == ISD::AND)
1460      if (ConstantSDNode *AndRHS = dyn_cast<ConstantSDNode>(N2.getOperand(1))) {
1461        // If the and is only masking out bits that cannot effect the shift,
1462        // eliminate the and.
1463        unsigned NumBits = MVT::getSizeInBits(VT);
1464        if ((AndRHS->getValue() & (NumBits-1)) == NumBits-1)
1465          return getNode(Opcode, VT, N1, N2.getOperand(0));
1466      }
1467    break;
1468#endif
1469  }
1470
1471  // Memoize this node if possible.
1472  SDNode *N;
1473  if (Opcode != ISD::CALLSEQ_START && Opcode != ISD::CALLSEQ_END) {
1474    SDNode *&BON = BinaryOps[std::make_pair(Opcode, std::make_pair(N1, N2))];
1475    if (BON) return SDOperand(BON, 0);
1476
1477    BON = N = new SDNode(Opcode, N1, N2);
1478  } else {
1479    N = new SDNode(Opcode, N1, N2);
1480  }
1481
1482  N->setValueTypes(VT);
1483  AllNodes.push_back(N);
1484  return SDOperand(N, 0);
1485}
1486
1487// setAdjCallChain - This method changes the token chain of an
1488// CALLSEQ_START/END node to be the specified operand.
1489void SDNode::setAdjCallChain(SDOperand N) {
1490  assert(N.getValueType() == MVT::Other);
1491  assert((getOpcode() == ISD::CALLSEQ_START ||
1492          getOpcode() == ISD::CALLSEQ_END) && "Cannot adjust this node!");
1493
1494  Operands[0].Val->removeUser(this);
1495  Operands[0] = N;
1496  N.Val->Uses.push_back(this);
1497}
1498
1499
1500
1501SDOperand SelectionDAG::getLoad(MVT::ValueType VT,
1502                                SDOperand Chain, SDOperand Ptr,
1503                                SDOperand SV) {
1504  SDNode *&N = Loads[std::make_pair(Ptr, std::make_pair(Chain, VT))];
1505  if (N) return SDOperand(N, 0);
1506  N = new SDNode(ISD::LOAD, Chain, Ptr, SV);
1507
1508  // Loads have a token chain.
1509  N->setValueTypes(VT, MVT::Other);
1510  AllNodes.push_back(N);
1511  return SDOperand(N, 0);
1512}
1513
1514
1515SDOperand SelectionDAG::getExtLoad(unsigned Opcode, MVT::ValueType VT,
1516                                   SDOperand Chain, SDOperand Ptr, SDOperand SV,
1517                                   MVT::ValueType EVT) {
1518  std::vector<SDOperand> Ops;
1519  Ops.reserve(4);
1520  Ops.push_back(Chain);
1521  Ops.push_back(Ptr);
1522  Ops.push_back(SV);
1523  Ops.push_back(getValueType(EVT));
1524  std::vector<MVT::ValueType> VTs;
1525  VTs.reserve(2);
1526  VTs.push_back(VT); VTs.push_back(MVT::Other);  // Add token chain.
1527  return getNode(Opcode, VTs, Ops);
1528}
1529
1530SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT,
1531                                SDOperand N1, SDOperand N2, SDOperand N3) {
1532  // Perform various simplifications.
1533  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val);
1534  ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.Val);
1535  ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.Val);
1536  switch (Opcode) {
1537  case ISD::SETCC: {
1538    // Use SimplifySetCC  to simplify SETCC's.
1539    SDOperand Simp = SimplifySetCC(VT, N1, N2, cast<CondCodeSDNode>(N3)->get());
1540    if (Simp.Val) return Simp;
1541    break;
1542  }
1543  case ISD::SELECT:
1544    if (N1C)
1545      if (N1C->getValue())
1546        return N2;             // select true, X, Y -> X
1547      else
1548        return N3;             // select false, X, Y -> Y
1549
1550    if (N2 == N3) return N2;   // select C, X, X -> X
1551
1552    if (VT == MVT::i1) {  // Boolean SELECT
1553      if (N2C) {
1554        if (N2C->getValue())   // select C, 1, X -> C | X
1555          return getNode(ISD::OR, VT, N1, N3);
1556        else                   // select C, 0, X -> ~C & X
1557          return getNode(ISD::AND, VT,
1558                         getNode(ISD::XOR, N1.getValueType(), N1,
1559                                 getConstant(1, N1.getValueType())), N3);
1560      } else if (N3C) {
1561        if (N3C->getValue())   // select C, X, 1 -> ~C | X
1562          return getNode(ISD::OR, VT,
1563                         getNode(ISD::XOR, N1.getValueType(), N1,
1564                                 getConstant(1, N1.getValueType())), N2);
1565        else                   // select C, X, 0 -> C & X
1566          return getNode(ISD::AND, VT, N1, N2);
1567      }
1568
1569      if (N1 == N2)   // X ? X : Y --> X ? 1 : Y --> X | Y
1570        return getNode(ISD::OR, VT, N1, N3);
1571      if (N1 == N3)   // X ? Y : X --> X ? Y : 0 --> X & Y
1572        return getNode(ISD::AND, VT, N1, N2);
1573    }
1574    if (N1.getOpcode() == ISD::SETCC) {
1575      SDOperand Simp = SimplifySelectCC(N1.getOperand(0), N1.getOperand(1), N2,
1576                             N3, cast<CondCodeSDNode>(N1.getOperand(2))->get());
1577      if (Simp.Val) return Simp;
1578    }
1579    break;
1580  case ISD::BRCOND:
1581    if (N2C)
1582      if (N2C->getValue()) // Unconditional branch
1583        return getNode(ISD::BR, MVT::Other, N1, N3);
1584      else
1585        return N1;         // Never-taken branch
1586    break;
1587  }
1588
1589  std::vector<SDOperand> Ops;
1590  Ops.reserve(3);
1591  Ops.push_back(N1);
1592  Ops.push_back(N2);
1593  Ops.push_back(N3);
1594
1595  // Memoize nodes.
1596  SDNode *&N = OneResultNodes[std::make_pair(Opcode, std::make_pair(VT, Ops))];
1597  if (N) return SDOperand(N, 0);
1598
1599  N = new SDNode(Opcode, N1, N2, N3);
1600  N->setValueTypes(VT);
1601  AllNodes.push_back(N);
1602  return SDOperand(N, 0);
1603}
1604
1605SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT,
1606                                SDOperand N1, SDOperand N2, SDOperand N3,
1607                                SDOperand N4) {
1608  std::vector<SDOperand> Ops;
1609  Ops.reserve(4);
1610  Ops.push_back(N1);
1611  Ops.push_back(N2);
1612  Ops.push_back(N3);
1613  Ops.push_back(N4);
1614  return getNode(Opcode, VT, Ops);
1615}
1616
1617SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT,
1618                                SDOperand N1, SDOperand N2, SDOperand N3,
1619                                SDOperand N4, SDOperand N5) {
1620  if (ISD::SELECT_CC == Opcode) {
1621    assert(N1.getValueType() == N2.getValueType() &&
1622           "LHS and RHS of condition must have same type!");
1623    assert(N3.getValueType() == N4.getValueType() &&
1624           "True and False arms of SelectCC must have same type!");
1625    assert(N3.getValueType() == VT &&
1626           "select_cc node must be of same type as true and false value!");
1627    SDOperand Simp = SimplifySelectCC(N1, N2, N3, N4,
1628                                      cast<CondCodeSDNode>(N5)->get());
1629    if (Simp.Val) return Simp;
1630  }
1631
1632  std::vector<SDOperand> Ops;
1633  Ops.reserve(5);
1634  Ops.push_back(N1);
1635  Ops.push_back(N2);
1636  Ops.push_back(N3);
1637  Ops.push_back(N4);
1638  Ops.push_back(N5);
1639  return getNode(Opcode, VT, Ops);
1640}
1641
1642
1643SDOperand SelectionDAG::getSrcValue(const Value *V, int Offset) {
1644  assert((!V || isa<PointerType>(V->getType())) &&
1645         "SrcValue is not a pointer?");
1646  SDNode *&N = ValueNodes[std::make_pair(V, Offset)];
1647  if (N) return SDOperand(N, 0);
1648
1649  N = new SrcValueSDNode(V, Offset);
1650  AllNodes.push_back(N);
1651  return SDOperand(N, 0);
1652}
1653
1654SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT,
1655                                std::vector<SDOperand> &Ops) {
1656  switch (Ops.size()) {
1657  case 0: return getNode(Opcode, VT);
1658  case 1: return getNode(Opcode, VT, Ops[0]);
1659  case 2: return getNode(Opcode, VT, Ops[0], Ops[1]);
1660  case 3: return getNode(Opcode, VT, Ops[0], Ops[1], Ops[2]);
1661  default: break;
1662  }
1663
1664  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Ops[1].Val);
1665  switch (Opcode) {
1666  default: break;
1667  case ISD::BRCONDTWOWAY:
1668    if (N1C)
1669      if (N1C->getValue()) // Unconditional branch to true dest.
1670        return getNode(ISD::BR, MVT::Other, Ops[0], Ops[2]);
1671      else                 // Unconditional branch to false dest.
1672        return getNode(ISD::BR, MVT::Other, Ops[0], Ops[3]);
1673    break;
1674  case ISD::BRTWOWAY_CC:
1675    assert(Ops.size() == 6 && "BRTWOWAY_CC takes 6 operands!");
1676    assert(Ops[2].getValueType() == Ops[3].getValueType() &&
1677           "LHS and RHS of comparison must have same type!");
1678    break;
1679  case ISD::TRUNCSTORE: {
1680    assert(Ops.size() == 5 && "TRUNCSTORE takes 5 operands!");
1681    MVT::ValueType EVT = cast<VTSDNode>(Ops[4])->getVT();
1682#if 0 // FIXME: If the target supports EVT natively, convert to a truncate/store
1683    // If this is a truncating store of a constant, convert to the desired type
1684    // and store it instead.
1685    if (isa<Constant>(Ops[0])) {
1686      SDOperand Op = getNode(ISD::TRUNCATE, EVT, N1);
1687      if (isa<Constant>(Op))
1688        N1 = Op;
1689    }
1690    // Also for ConstantFP?
1691#endif
1692    if (Ops[0].getValueType() == EVT)       // Normal store?
1693      return getNode(ISD::STORE, VT, Ops[0], Ops[1], Ops[2], Ops[3]);
1694    assert(Ops[1].getValueType() > EVT && "Not a truncation?");
1695    assert(MVT::isInteger(Ops[1].getValueType()) == MVT::isInteger(EVT) &&
1696           "Can't do FP-INT conversion!");
1697    break;
1698  }
1699  }
1700
1701  // Memoize nodes.
1702  SDNode *&N = OneResultNodes[std::make_pair(Opcode, std::make_pair(VT, Ops))];
1703  if (N) return SDOperand(N, 0);
1704  N = new SDNode(Opcode, Ops);
1705  N->setValueTypes(VT);
1706  AllNodes.push_back(N);
1707  return SDOperand(N, 0);
1708}
1709
1710SDOperand SelectionDAG::getNode(unsigned Opcode,
1711                                std::vector<MVT::ValueType> &ResultTys,
1712                                std::vector<SDOperand> &Ops) {
1713  if (ResultTys.size() == 1)
1714    return getNode(Opcode, ResultTys[0], Ops);
1715
1716  switch (Opcode) {
1717  case ISD::EXTLOAD:
1718  case ISD::SEXTLOAD:
1719  case ISD::ZEXTLOAD: {
1720    MVT::ValueType EVT = cast<VTSDNode>(Ops[3])->getVT();
1721    assert(Ops.size() == 4 && ResultTys.size() == 2 && "Bad *EXTLOAD!");
1722    // If they are asking for an extending load from/to the same thing, return a
1723    // normal load.
1724    if (ResultTys[0] == EVT)
1725      return getLoad(ResultTys[0], Ops[0], Ops[1], Ops[2]);
1726    assert(EVT < ResultTys[0] &&
1727           "Should only be an extending load, not truncating!");
1728    assert((Opcode == ISD::EXTLOAD || MVT::isInteger(ResultTys[0])) &&
1729           "Cannot sign/zero extend a FP load!");
1730    assert(MVT::isInteger(ResultTys[0]) == MVT::isInteger(EVT) &&
1731           "Cannot convert from FP to Int or Int -> FP!");
1732    break;
1733  }
1734
1735  // FIXME: figure out how to safely handle things like
1736  // int foo(int x) { return 1 << (x & 255); }
1737  // int bar() { return foo(256); }
1738#if 0
1739  case ISD::SRA_PARTS:
1740  case ISD::SRL_PARTS:
1741  case ISD::SHL_PARTS:
1742    if (N3.getOpcode() == ISD::SIGN_EXTEND_INREG &&
1743        cast<VTSDNode>(N3.getOperand(1))->getVT() != MVT::i1)
1744      return getNode(Opcode, VT, N1, N2, N3.getOperand(0));
1745    else if (N3.getOpcode() == ISD::AND)
1746      if (ConstantSDNode *AndRHS = dyn_cast<ConstantSDNode>(N3.getOperand(1))) {
1747        // If the and is only masking out bits that cannot effect the shift,
1748        // eliminate the and.
1749        unsigned NumBits = MVT::getSizeInBits(VT)*2;
1750        if ((AndRHS->getValue() & (NumBits-1)) == NumBits-1)
1751          return getNode(Opcode, VT, N1, N2, N3.getOperand(0));
1752      }
1753    break;
1754#endif
1755  }
1756
1757  // Memoize the node.
1758  SDNode *&N = ArbitraryNodes[std::make_pair(Opcode, std::make_pair(ResultTys,
1759                                                                    Ops))];
1760  if (N) return SDOperand(N, 0);
1761  N = new SDNode(Opcode, Ops);
1762  N->setValueTypes(ResultTys);
1763  AllNodes.push_back(N);
1764  return SDOperand(N, 0);
1765}
1766
1767
1768/// SelectNodeTo - These are used for target selectors to *mutate* the
1769/// specified node to have the specified return type, Target opcode, and
1770/// operands.  Note that target opcodes are stored as
1771/// ISD::BUILTIN_OP_END+TargetOpcode in the node opcode field.
1772void SelectionDAG::SelectNodeTo(SDNode *N, MVT::ValueType VT,
1773                                unsigned TargetOpc, SDOperand Op1) {
1774  RemoveNodeFromCSEMaps(N);
1775  N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc);
1776  N->setValueTypes(VT);
1777  N->setOperands(Op1);
1778}
1779void SelectionDAG::SelectNodeTo(SDNode *N, MVT::ValueType VT,
1780                                unsigned TargetOpc, SDOperand Op1,
1781                                SDOperand Op2) {
1782  RemoveNodeFromCSEMaps(N);
1783  N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc);
1784  N->setValueTypes(VT);
1785  N->setOperands(Op1, Op2);
1786}
1787void SelectionDAG::SelectNodeTo(SDNode *N, MVT::ValueType VT,
1788                                unsigned TargetOpc, SDOperand Op1,
1789                                SDOperand Op2, SDOperand Op3) {
1790  RemoveNodeFromCSEMaps(N);
1791  N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc);
1792  N->setValueTypes(VT);
1793  N->setOperands(Op1, Op2, Op3);
1794}
1795
1796/// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
1797/// This can cause recursive merging of nodes in the DAG.
1798///
1799void SelectionDAG::ReplaceAllUsesWith(SDNode *From, SDNode *To) {
1800  assert(From != To && "Cannot replace uses of with self");
1801  while (!From->use_empty()) {
1802    // Process users until they are all gone.
1803    SDNode *U = *From->use_begin();
1804
1805    // This node is about to morph, remove its old self from the CSE maps.
1806    RemoveNodeFromCSEMaps(U);
1807
1808    for (unsigned i = 0, e = U->getNumOperands(); i != e; ++i)
1809      if (U->getOperand(i).Val == From) {
1810        assert(From->getValueType(U->getOperand(i).ResNo) ==
1811               To->getValueType(U->getOperand(i).ResNo));
1812        From->removeUser(U);
1813        U->Operands[i].Val = To;
1814        To->addUser(U);
1815      }
1816
1817    // Now that we have modified U, add it back to the CSE maps.  If it already
1818    // exists there, recursively merge the results together.
1819    if (SDNode *Existing = AddNonLeafNodeToCSEMaps(U))
1820      ReplaceAllUsesWith(U, Existing);
1821      // U is now dead.
1822  }
1823}
1824
1825
1826
1827/// hasNUsesOfValue - Return true if there are exactly NUSES uses of the
1828/// indicated value.  This method ignores uses of other values defined by this
1829/// operation.
1830bool SDNode::hasNUsesOfValue(unsigned NUses, unsigned Value) {
1831  assert(Value < getNumValues() && "Bad value!");
1832
1833  // If there is only one value, this is easy.
1834  if (getNumValues() == 1)
1835    return use_size() == NUses;
1836  if (Uses.size() < NUses) return false;
1837
1838  SDOperand TheValue(this, Value);
1839
1840  std::set<SDNode*> UsersHandled;
1841
1842  for (std::vector<SDNode*>::iterator UI = Uses.begin(), E = Uses.end();
1843       UI != E; ++UI) {
1844    SDNode *User = *UI;
1845    if (User->getNumOperands() == 1 ||
1846        UsersHandled.insert(User).second)     // First time we've seen this?
1847      for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i)
1848        if (User->getOperand(i) == TheValue) {
1849          if (NUses == 0)
1850            return false;   // too many uses
1851          --NUses;
1852        }
1853  }
1854
1855  // Found exactly the right number of uses?
1856  return NUses == 0;
1857}
1858
1859
1860const char *SDNode::getOperationName(const SelectionDAG *G) const {
1861  switch (getOpcode()) {
1862  default:
1863    if (getOpcode() < ISD::BUILTIN_OP_END)
1864      return "<<Unknown DAG Node>>";
1865    else {
1866      if (G)
1867        if (const TargetInstrInfo *TII = G->getTarget().getInstrInfo())
1868          return TII->getName(getOpcode()-ISD::BUILTIN_OP_END);
1869      return "<<Unknown Target Node>>";
1870    }
1871
1872  case ISD::PCMARKER:      return "PCMarker";
1873  case ISD::SRCVALUE:      return "SrcValue";
1874  case ISD::EntryToken:    return "EntryToken";
1875  case ISD::TokenFactor:   return "TokenFactor";
1876  case ISD::Constant:      return "Constant";
1877  case ISD::TargetConstant: return "TargetConstant";
1878  case ISD::ConstantFP:    return "ConstantFP";
1879  case ISD::GlobalAddress: return "GlobalAddress";
1880  case ISD::FrameIndex:    return "FrameIndex";
1881  case ISD::BasicBlock:    return "BasicBlock";
1882  case ISD::Register:      return "Register";
1883  case ISD::ExternalSymbol: return "ExternalSymbol";
1884  case ISD::ConstantPool:  return "ConstantPoolIndex";
1885  case ISD::CopyToReg:     return "CopyToReg";
1886  case ISD::CopyFromReg:   return "CopyFromReg";
1887  case ISD::ImplicitDef:   return "ImplicitDef";
1888  case ISD::UNDEF:         return "undef";
1889
1890  // Unary operators
1891  case ISD::FABS:   return "fabs";
1892  case ISD::FNEG:   return "fneg";
1893  case ISD::FSQRT:  return "fsqrt";
1894  case ISD::FSIN:   return "fsin";
1895  case ISD::FCOS:   return "fcos";
1896
1897  // Binary operators
1898  case ISD::ADD:    return "add";
1899  case ISD::SUB:    return "sub";
1900  case ISD::MUL:    return "mul";
1901  case ISD::MULHU:  return "mulhu";
1902  case ISD::MULHS:  return "mulhs";
1903  case ISD::SDIV:   return "sdiv";
1904  case ISD::UDIV:   return "udiv";
1905  case ISD::SREM:   return "srem";
1906  case ISD::UREM:   return "urem";
1907  case ISD::AND:    return "and";
1908  case ISD::OR:     return "or";
1909  case ISD::XOR:    return "xor";
1910  case ISD::SHL:    return "shl";
1911  case ISD::SRA:    return "sra";
1912  case ISD::SRL:    return "srl";
1913
1914  case ISD::SETCC:       return "setcc";
1915  case ISD::SELECT:      return "select";
1916  case ISD::SELECT_CC:   return "select_cc";
1917  case ISD::ADD_PARTS:   return "add_parts";
1918  case ISD::SUB_PARTS:   return "sub_parts";
1919  case ISD::SHL_PARTS:   return "shl_parts";
1920  case ISD::SRA_PARTS:   return "sra_parts";
1921  case ISD::SRL_PARTS:   return "srl_parts";
1922
1923  // Conversion operators.
1924  case ISD::SIGN_EXTEND: return "sign_extend";
1925  case ISD::ZERO_EXTEND: return "zero_extend";
1926  case ISD::SIGN_EXTEND_INREG: return "sign_extend_inreg";
1927  case ISD::TRUNCATE:    return "truncate";
1928  case ISD::FP_ROUND:    return "fp_round";
1929  case ISD::FP_ROUND_INREG: return "fp_round_inreg";
1930  case ISD::FP_EXTEND:   return "fp_extend";
1931
1932  case ISD::SINT_TO_FP:  return "sint_to_fp";
1933  case ISD::UINT_TO_FP:  return "uint_to_fp";
1934  case ISD::FP_TO_SINT:  return "fp_to_sint";
1935  case ISD::FP_TO_UINT:  return "fp_to_uint";
1936
1937    // Control flow instructions
1938  case ISD::BR:      return "br";
1939  case ISD::BRCOND:  return "brcond";
1940  case ISD::BRCONDTWOWAY:  return "brcondtwoway";
1941  case ISD::BR_CC:  return "br_cc";
1942  case ISD::BRTWOWAY_CC:  return "brtwoway_cc";
1943  case ISD::RET:     return "ret";
1944  case ISD::CALL:    return "call";
1945  case ISD::TAILCALL:return "tailcall";
1946  case ISD::CALLSEQ_START:  return "callseq_start";
1947  case ISD::CALLSEQ_END:    return "callseq_end";
1948
1949    // Other operators
1950  case ISD::LOAD:    return "load";
1951  case ISD::STORE:   return "store";
1952  case ISD::EXTLOAD:    return "extload";
1953  case ISD::SEXTLOAD:   return "sextload";
1954  case ISD::ZEXTLOAD:   return "zextload";
1955  case ISD::TRUNCSTORE: return "truncstore";
1956
1957  case ISD::DYNAMIC_STACKALLOC: return "dynamic_stackalloc";
1958  case ISD::EXTRACT_ELEMENT: return "extract_element";
1959  case ISD::BUILD_PAIR: return "build_pair";
1960  case ISD::MEMSET:  return "memset";
1961  case ISD::MEMCPY:  return "memcpy";
1962  case ISD::MEMMOVE: return "memmove";
1963
1964  // Bit counting
1965  case ISD::CTPOP:   return "ctpop";
1966  case ISD::CTTZ:    return "cttz";
1967  case ISD::CTLZ:    return "ctlz";
1968
1969  // IO Intrinsics
1970  case ISD::READPORT: return "readport";
1971  case ISD::WRITEPORT: return "writeport";
1972  case ISD::READIO: return "readio";
1973  case ISD::WRITEIO: return "writeio";
1974
1975  case ISD::CONDCODE:
1976    switch (cast<CondCodeSDNode>(this)->get()) {
1977    default: assert(0 && "Unknown setcc condition!");
1978    case ISD::SETOEQ:  return "setoeq";
1979    case ISD::SETOGT:  return "setogt";
1980    case ISD::SETOGE:  return "setoge";
1981    case ISD::SETOLT:  return "setolt";
1982    case ISD::SETOLE:  return "setole";
1983    case ISD::SETONE:  return "setone";
1984
1985    case ISD::SETO:    return "seto";
1986    case ISD::SETUO:   return "setuo";
1987    case ISD::SETUEQ:  return "setue";
1988    case ISD::SETUGT:  return "setugt";
1989    case ISD::SETUGE:  return "setuge";
1990    case ISD::SETULT:  return "setult";
1991    case ISD::SETULE:  return "setule";
1992    case ISD::SETUNE:  return "setune";
1993
1994    case ISD::SETEQ:   return "seteq";
1995    case ISD::SETGT:   return "setgt";
1996    case ISD::SETGE:   return "setge";
1997    case ISD::SETLT:   return "setlt";
1998    case ISD::SETLE:   return "setle";
1999    case ISD::SETNE:   return "setne";
2000    }
2001  }
2002}
2003
2004void SDNode::dump() const { dump(0); }
2005void SDNode::dump(const SelectionDAG *G) const {
2006  std::cerr << (void*)this << ": ";
2007
2008  for (unsigned i = 0, e = getNumValues(); i != e; ++i) {
2009    if (i) std::cerr << ",";
2010    if (getValueType(i) == MVT::Other)
2011      std::cerr << "ch";
2012    else
2013      std::cerr << MVT::getValueTypeString(getValueType(i));
2014  }
2015  std::cerr << " = " << getOperationName(G);
2016
2017  std::cerr << " ";
2018  for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2019    if (i) std::cerr << ", ";
2020    std::cerr << (void*)getOperand(i).Val;
2021    if (unsigned RN = getOperand(i).ResNo)
2022      std::cerr << ":" << RN;
2023  }
2024
2025  if (const ConstantSDNode *CSDN = dyn_cast<ConstantSDNode>(this)) {
2026    std::cerr << "<" << CSDN->getValue() << ">";
2027  } else if (const ConstantFPSDNode *CSDN = dyn_cast<ConstantFPSDNode>(this)) {
2028    std::cerr << "<" << CSDN->getValue() << ">";
2029  } else if (const GlobalAddressSDNode *GADN =
2030             dyn_cast<GlobalAddressSDNode>(this)) {
2031    std::cerr << "<";
2032    WriteAsOperand(std::cerr, GADN->getGlobal()) << ">";
2033  } else if (const FrameIndexSDNode *FIDN = dyn_cast<FrameIndexSDNode>(this)) {
2034    std::cerr << "<" << FIDN->getIndex() << ">";
2035  } else if (const ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(this)){
2036    std::cerr << "<" << CP->getIndex() << ">";
2037  } else if (const BasicBlockSDNode *BBDN = dyn_cast<BasicBlockSDNode>(this)) {
2038    std::cerr << "<";
2039    const Value *LBB = (const Value*)BBDN->getBasicBlock()->getBasicBlock();
2040    if (LBB)
2041      std::cerr << LBB->getName() << " ";
2042    std::cerr << (const void*)BBDN->getBasicBlock() << ">";
2043  } else if (const RegisterSDNode *C2V = dyn_cast<RegisterSDNode>(this)) {
2044    std::cerr << " #" << C2V->getReg();
2045  } else if (const ExternalSymbolSDNode *ES =
2046             dyn_cast<ExternalSymbolSDNode>(this)) {
2047    std::cerr << "'" << ES->getSymbol() << "'";
2048  } else if (const SrcValueSDNode *M = dyn_cast<SrcValueSDNode>(this)) {
2049    if (M->getValue())
2050      std::cerr << "<" << M->getValue() << ":" << M->getOffset() << ">";
2051    else
2052      std::cerr << "<null:" << M->getOffset() << ">";
2053  }
2054}
2055
2056static void DumpNodes(SDNode *N, unsigned indent, const SelectionDAG *G) {
2057  for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
2058    if (N->getOperand(i).Val->hasOneUse())
2059      DumpNodes(N->getOperand(i).Val, indent+2, G);
2060    else
2061      std::cerr << "\n" << std::string(indent+2, ' ')
2062                << (void*)N->getOperand(i).Val << ": <multiple use>";
2063
2064
2065  std::cerr << "\n" << std::string(indent, ' ');
2066  N->dump(G);
2067}
2068
2069void SelectionDAG::dump() const {
2070  std::cerr << "SelectionDAG has " << AllNodes.size() << " nodes:";
2071  std::vector<SDNode*> Nodes(AllNodes);
2072  std::sort(Nodes.begin(), Nodes.end());
2073
2074  for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
2075    if (!Nodes[i]->hasOneUse() && Nodes[i] != getRoot().Val)
2076      DumpNodes(Nodes[i], 2, this);
2077  }
2078
2079  DumpNodes(getRoot().Val, 2, this);
2080
2081  std::cerr << "\n\n";
2082}
2083
2084