SelectionDAG.cpp revision 4a9b4f1943c6c56c749c8709ed28680408afc577
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 <iostream>
20#include <set>
21#include <cmath>
22#include <algorithm>
23using namespace llvm;
24
25static bool isCommutativeBinOp(unsigned Opcode) {
26  switch (Opcode) {
27  case ISD::ADD:
28  case ISD::MUL:
29  case ISD::AND:
30  case ISD::OR:
31  case ISD::XOR: return true;
32  default: return false; // FIXME: Need commutative info for user ops!
33  }
34}
35
36static bool isAssociativeBinOp(unsigned Opcode) {
37  switch (Opcode) {
38  case ISD::ADD:
39  case ISD::MUL:
40  case ISD::AND:
41  case ISD::OR:
42  case ISD::XOR: return true;
43  default: return false; // FIXME: Need associative info for user ops!
44  }
45}
46
47static unsigned ExactLog2(uint64_t Val) {
48  unsigned Count = 0;
49  while (Val != 1) {
50    Val >>= 1;
51    ++Count;
52  }
53  return Count;
54}
55
56// isInvertibleForFree - Return true if there is no cost to emitting the logical
57// inverse of this node.
58static bool isInvertibleForFree(SDOperand N) {
59  if (isa<ConstantSDNode>(N.Val)) return true;
60  if (isa<SetCCSDNode>(N.Val) && N.Val->hasOneUse())
61    return true;
62  return false;
63}
64
65
66/// getSetCCSwappedOperands - Return the operation corresponding to (Y op X)
67/// when given the operation for (X op Y).
68ISD::CondCode ISD::getSetCCSwappedOperands(ISD::CondCode Operation) {
69  // To perform this operation, we just need to swap the L and G bits of the
70  // operation.
71  unsigned OldL = (Operation >> 2) & 1;
72  unsigned OldG = (Operation >> 1) & 1;
73  return ISD::CondCode((Operation & ~6) |  // Keep the N, U, E bits
74                       (OldL << 1) |       // New G bit
75                       (OldG << 2));        // New L bit.
76}
77
78/// getSetCCInverse - Return the operation corresponding to !(X op Y), where
79/// 'op' is a valid SetCC operation.
80ISD::CondCode ISD::getSetCCInverse(ISD::CondCode Op, bool isInteger) {
81  unsigned Operation = Op;
82  if (isInteger)
83    Operation ^= 7;   // Flip L, G, E bits, but not U.
84  else
85    Operation ^= 15;  // Flip all of the condition bits.
86  if (Operation > ISD::SETTRUE2)
87    Operation &= ~8;     // Don't let N and U bits get set.
88  return ISD::CondCode(Operation);
89}
90
91
92/// isSignedOp - For an integer comparison, return 1 if the comparison is a
93/// signed operation and 2 if the result is an unsigned comparison.  Return zero
94/// if the operation does not depend on the sign of the input (setne and seteq).
95static int isSignedOp(ISD::CondCode Opcode) {
96  switch (Opcode) {
97  default: assert(0 && "Illegal integer setcc operation!");
98  case ISD::SETEQ:
99  case ISD::SETNE: return 0;
100  case ISD::SETLT:
101  case ISD::SETLE:
102  case ISD::SETGT:
103  case ISD::SETGE: return 1;
104  case ISD::SETULT:
105  case ISD::SETULE:
106  case ISD::SETUGT:
107  case ISD::SETUGE: return 2;
108  }
109}
110
111/// getSetCCOrOperation - Return the result of a logical OR between different
112/// comparisons of identical values: ((X op1 Y) | (X op2 Y)).  This function
113/// returns SETCC_INVALID if it is not possible to represent the resultant
114/// comparison.
115ISD::CondCode ISD::getSetCCOrOperation(ISD::CondCode Op1, ISD::CondCode Op2,
116                                       bool isInteger) {
117  if (isInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
118    // Cannot fold a signed integer setcc with an unsigned integer setcc.
119    return ISD::SETCC_INVALID;
120
121  unsigned Op = Op1 | Op2;  // Combine all of the condition bits.
122
123  // If the N and U bits get set then the resultant comparison DOES suddenly
124  // care about orderedness, and is true when ordered.
125  if (Op > ISD::SETTRUE2)
126    Op &= ~16;     // Clear the N bit.
127  return ISD::CondCode(Op);
128}
129
130/// getSetCCAndOperation - Return the result of a logical AND between different
131/// comparisons of identical values: ((X op1 Y) & (X op2 Y)).  This
132/// function returns zero if it is not possible to represent the resultant
133/// comparison.
134ISD::CondCode ISD::getSetCCAndOperation(ISD::CondCode Op1, ISD::CondCode Op2,
135                                        bool isInteger) {
136  if (isInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
137    // Cannot fold a signed setcc with an unsigned setcc.
138    return ISD::SETCC_INVALID;
139
140  // Combine all of the condition bits.
141  return ISD::CondCode(Op1 & Op2);
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  DeleteNodeIfDead(N, &AllNodeSet);
156
157 Restart:
158  unsigned NumNodes = AllNodeSet.size();
159  for (std::set<SDNode*>::iterator I = AllNodeSet.begin(), E = AllNodeSet.end();
160       I != E; ++I) {
161    // Try to delete this node.
162    DeleteNodeIfDead(*I, &AllNodeSet);
163
164    // If we actually deleted any nodes, do not use invalid iterators in
165    // AllNodeSet.
166    if (AllNodeSet.size() != NumNodes)
167      goto Restart;
168  }
169
170  // Restore AllNodes.
171  if (AllNodes.size() != NumNodes)
172    AllNodes.assign(AllNodeSet.begin(), AllNodeSet.end());
173
174  // If the root changed (e.g. it was a dead load, update the root).
175  setRoot(DummyNode->getOperand(0));
176
177  // Now that we are done with the dummy node, delete it.
178  DummyNode->getOperand(0).Val->removeUser(DummyNode);
179  delete DummyNode;
180}
181
182void SelectionDAG::DeleteNodeIfDead(SDNode *N, void *NodeSet) {
183  if (!N->use_empty())
184    return;
185
186  // Okay, we really are going to delete this node.  First take this out of the
187  // appropriate CSE map.
188  switch (N->getOpcode()) {
189  case ISD::Constant:
190    Constants.erase(std::make_pair(cast<ConstantSDNode>(N)->getValue(),
191                                   N->getValueType(0)));
192    break;
193  case ISD::ConstantFP:
194    ConstantFPs.erase(std::make_pair(cast<ConstantFPSDNode>(N)->getValue(),
195                                     N->getValueType(0)));
196    break;
197  case ISD::GlobalAddress:
198    GlobalValues.erase(cast<GlobalAddressSDNode>(N)->getGlobal());
199    break;
200  case ISD::FrameIndex:
201    FrameIndices.erase(cast<FrameIndexSDNode>(N)->getIndex());
202    break;
203  case ISD::ConstantPool:
204    ConstantPoolIndices.erase(cast<ConstantPoolSDNode>(N)->getIndex());
205    break;
206  case ISD::BasicBlock:
207    BBNodes.erase(cast<BasicBlockSDNode>(N)->getBasicBlock());
208    break;
209  case ISD::ExternalSymbol:
210    ExternalSymbols.erase(cast<ExternalSymbolSDNode>(N)->getSymbol());
211    break;
212
213  case ISD::LOAD:
214    Loads.erase(std::make_pair(N->getOperand(1),
215                               std::make_pair(N->getOperand(0),
216                                              N->getValueType(0))));
217    break;
218  case ISD::SETCC:
219    SetCCs.erase(std::make_pair(std::make_pair(N->getOperand(0),
220                                               N->getOperand(1)),
221                                std::make_pair(
222                                     cast<SetCCSDNode>(N)->getCondition(),
223                                     N->getValueType(0))));
224    break;
225  case ISD::TRUNCSTORE:
226  case ISD::SIGN_EXTEND_INREG:
227  case ISD::ZERO_EXTEND_INREG:
228  case ISD::FP_ROUND_INREG:
229  case ISD::EXTLOAD:
230  case ISD::SEXTLOAD:
231  case ISD::ZEXTLOAD: {
232    EVTStruct NN;
233    NN.Opcode = ISD::TRUNCSTORE;
234    NN.VT = N->getValueType(0);
235    NN.EVT = cast<MVTSDNode>(N)->getExtraValueType();
236    for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
237      NN.Ops.push_back(N->getOperand(i));
238    MVTSDNodes.erase(NN);
239    break;
240  }
241  default:
242    if (N->getNumOperands() == 1)
243      UnaryOps.erase(std::make_pair(N->getOpcode(),
244                                    std::make_pair(N->getOperand(0),
245                                                   N->getValueType(0))));
246    else if (N->getNumOperands() == 2)
247      BinaryOps.erase(std::make_pair(N->getOpcode(),
248                                     std::make_pair(N->getOperand(0),
249                                                    N->getOperand(1))));
250    break;
251  }
252
253  // Next, brutally remove the operand list.
254  while (!N->Operands.empty()) {
255    SDNode *O = N->Operands.back().Val;
256    N->Operands.pop_back();
257    O->removeUser(N);
258
259    // Now that we removed this operand, see if there are no uses of it left.
260    DeleteNodeIfDead(O, NodeSet);
261  }
262
263  // Remove the node from the nodes set and delete it.
264  std::set<SDNode*> &AllNodeSet = *(std::set<SDNode*>*)NodeSet;
265  AllNodeSet.erase(N);
266
267  // Now that the node is gone, check to see if any of the operands of this node
268  // are dead now.
269  delete N;
270}
271
272
273SelectionDAG::~SelectionDAG() {
274  for (unsigned i = 0, e = AllNodes.size(); i != e; ++i)
275    delete AllNodes[i];
276}
277
278SDOperand SelectionDAG::getConstant(uint64_t Val, MVT::ValueType VT) {
279  assert(MVT::isInteger(VT) && "Cannot create FP integer constant!");
280  // Mask out any bits that are not valid for this constant.
281  if (VT != MVT::i64)
282    Val &= ((uint64_t)1 << MVT::getSizeInBits(VT)) - 1;
283
284  SDNode *&N = Constants[std::make_pair(Val, VT)];
285  if (N) return SDOperand(N, 0);
286  N = new ConstantSDNode(Val, VT);
287  AllNodes.push_back(N);
288  return SDOperand(N, 0);
289}
290
291SDOperand SelectionDAG::getConstantFP(double Val, MVT::ValueType VT) {
292  assert(MVT::isFloatingPoint(VT) && "Cannot create integer FP constant!");
293  if (VT == MVT::f32)
294    Val = (float)Val;  // Mask out extra precision.
295
296  SDNode *&N = ConstantFPs[std::make_pair(Val, VT)];
297  if (N) return SDOperand(N, 0);
298  N = new ConstantFPSDNode(Val, VT);
299  AllNodes.push_back(N);
300  return SDOperand(N, 0);
301}
302
303
304
305SDOperand SelectionDAG::getGlobalAddress(const GlobalValue *GV,
306                                         MVT::ValueType VT) {
307  SDNode *&N = GlobalValues[GV];
308  if (N) return SDOperand(N, 0);
309  N = new GlobalAddressSDNode(GV,VT);
310  AllNodes.push_back(N);
311  return SDOperand(N, 0);
312}
313
314SDOperand SelectionDAG::getFrameIndex(int FI, MVT::ValueType VT) {
315  SDNode *&N = FrameIndices[FI];
316  if (N) return SDOperand(N, 0);
317  N = new FrameIndexSDNode(FI, VT);
318  AllNodes.push_back(N);
319  return SDOperand(N, 0);
320}
321
322SDOperand SelectionDAG::getConstantPool(unsigned CPIdx, MVT::ValueType VT) {
323  SDNode *N = ConstantPoolIndices[CPIdx];
324  if (N) return SDOperand(N, 0);
325  N = new ConstantPoolSDNode(CPIdx, VT);
326  AllNodes.push_back(N);
327  return SDOperand(N, 0);
328}
329
330SDOperand SelectionDAG::getBasicBlock(MachineBasicBlock *MBB) {
331  SDNode *&N = BBNodes[MBB];
332  if (N) return SDOperand(N, 0);
333  N = new BasicBlockSDNode(MBB);
334  AllNodes.push_back(N);
335  return SDOperand(N, 0);
336}
337
338SDOperand SelectionDAG::getExternalSymbol(const char *Sym, MVT::ValueType VT) {
339  SDNode *&N = ExternalSymbols[Sym];
340  if (N) return SDOperand(N, 0);
341  N = new ExternalSymbolSDNode(Sym, VT);
342  AllNodes.push_back(N);
343  return SDOperand(N, 0);
344}
345
346SDOperand SelectionDAG::getSetCC(ISD::CondCode Cond, MVT::ValueType VT,
347                                 SDOperand N1, SDOperand N2) {
348  // These setcc operations always fold.
349  switch (Cond) {
350  default: break;
351  case ISD::SETFALSE:
352  case ISD::SETFALSE2: return getConstant(0, VT);
353  case ISD::SETTRUE:
354  case ISD::SETTRUE2:  return getConstant(1, VT);
355  }
356
357  if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val))
358    if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.Val)) {
359      uint64_t C1 = N1C->getValue(), C2 = N2C->getValue();
360
361      // Sign extend the operands if required
362      if (ISD::isSignedIntSetCC(Cond)) {
363        C1 = N1C->getSignExtended();
364        C2 = N2C->getSignExtended();
365      }
366
367      switch (Cond) {
368      default: assert(0 && "Unknown integer setcc!");
369      case ISD::SETEQ:  return getConstant(C1 == C2, VT);
370      case ISD::SETNE:  return getConstant(C1 != C2, VT);
371      case ISD::SETULT: return getConstant(C1 <  C2, VT);
372      case ISD::SETUGT: return getConstant(C1 >  C2, VT);
373      case ISD::SETULE: return getConstant(C1 <= C2, VT);
374      case ISD::SETUGE: return getConstant(C1 >= C2, VT);
375      case ISD::SETLT:  return getConstant((int64_t)C1 <  (int64_t)C2, VT);
376      case ISD::SETGT:  return getConstant((int64_t)C1 >  (int64_t)C2, VT);
377      case ISD::SETLE:  return getConstant((int64_t)C1 <= (int64_t)C2, VT);
378      case ISD::SETGE:  return getConstant((int64_t)C1 >= (int64_t)C2, VT);
379      }
380    } else {
381      // Ensure that the constant occurs on the RHS.
382      Cond = ISD::getSetCCSwappedOperands(Cond);
383      std::swap(N1, N2);
384    }
385
386  if (ConstantFPSDNode *N1C = dyn_cast<ConstantFPSDNode>(N1.Val))
387    if (ConstantFPSDNode *N2C = dyn_cast<ConstantFPSDNode>(N2.Val)) {
388      double C1 = N1C->getValue(), C2 = N2C->getValue();
389
390      switch (Cond) {
391      default: break; // FIXME: Implement the rest of these!
392      case ISD::SETEQ:  return getConstant(C1 == C2, VT);
393      case ISD::SETNE:  return getConstant(C1 != C2, VT);
394      case ISD::SETLT:  return getConstant(C1 < C2, VT);
395      case ISD::SETGT:  return getConstant(C1 > C2, VT);
396      case ISD::SETLE:  return getConstant(C1 <= C2, VT);
397      case ISD::SETGE:  return getConstant(C1 >= C2, VT);
398      }
399    } else {
400      // Ensure that the constant occurs on the RHS.
401      Cond = ISD::getSetCCSwappedOperands(Cond);
402      std::swap(N1, N2);
403    }
404
405  if (N1 == N2) {
406    // We can always fold X == Y for integer setcc's.
407    if (MVT::isInteger(N1.getValueType()))
408      return getConstant(ISD::isTrueWhenEqual(Cond), VT);
409    unsigned UOF = ISD::getUnorderedFlavor(Cond);
410    if (UOF == 2)   // FP operators that are undefined on NaNs.
411      return getConstant(ISD::isTrueWhenEqual(Cond), VT);
412    if (UOF == ISD::isTrueWhenEqual(Cond))
413      return getConstant(UOF, VT);
414    // Otherwise, we can't fold it.  However, we can simplify it to SETUO/SETO
415    // if it is not already.
416    Cond = UOF == 0 ? ISD::SETUO : ISD::SETO;
417  }
418
419  if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
420      MVT::isInteger(N1.getValueType())) {
421    if (N1.getOpcode() == ISD::ADD || N1.getOpcode() == ISD::SUB ||
422        N1.getOpcode() == ISD::XOR) {
423      // Simplify (X+Y) == (X+Z) -->  Y == Z
424      if (N1.getOpcode() == N2.getOpcode()) {
425        if (N1.getOperand(0) == N2.getOperand(0))
426          return getSetCC(Cond, VT, N1.getOperand(1), N2.getOperand(1));
427        if (N1.getOperand(1) == N2.getOperand(1))
428          return getSetCC(Cond, VT, N1.getOperand(0), N2.getOperand(0));
429        if (isCommutativeBinOp(N1.getOpcode())) {
430          // If X op Y == Y op X, try other combinations.
431          if (N1.getOperand(0) == N2.getOperand(1))
432            return getSetCC(Cond, VT, N1.getOperand(1), N2.getOperand(0));
433          if (N1.getOperand(1) == N2.getOperand(0))
434            return getSetCC(Cond, VT, N1.getOperand(1), N2.getOperand(1));
435        }
436      }
437
438      // Simplify (X+Z) == X -->  Z == 0
439      if (N1.getOperand(0) == N2)
440        return getSetCC(Cond, VT, N1.getOperand(1),
441                        getConstant(0, N1.getValueType()));
442      if (N1.getOperand(1) == N2) {
443        if (isCommutativeBinOp(N1.getOpcode()))
444          return getSetCC(Cond, VT, N1.getOperand(0),
445                          getConstant(0, N1.getValueType()));
446        else {
447          assert(N1.getOpcode() == ISD::SUB && "Unexpected operation!");
448          // (Z-X) == X  --> Z == X<<1
449          return getSetCC(Cond, VT, N1.getOperand(0),
450                          getNode(ISD::SHL, N2.getValueType(),
451                                  N2, getConstant(1, MVT::i8)));
452        }
453      }
454    }
455
456    if (N2.getOpcode() == ISD::ADD || N2.getOpcode() == ISD::SUB ||
457        N2.getOpcode() == ISD::XOR) {
458      // Simplify  X == (X+Z) -->  Z == 0
459      if (N2.getOperand(0) == N1)
460        return getSetCC(Cond, VT, N2.getOperand(1),
461                        getConstant(0, N2.getValueType()));
462      else if (N2.getOperand(1) == N1)
463        return getSetCC(Cond, VT, N2.getOperand(0),
464                        getConstant(0, N2.getValueType()));
465    }
466  }
467
468  SetCCSDNode *&N = SetCCs[std::make_pair(std::make_pair(N1, N2),
469                                          std::make_pair(Cond, VT))];
470  if (N) return SDOperand(N, 0);
471  N = new SetCCSDNode(Cond, N1, N2);
472  N->setValueTypes(VT);
473  AllNodes.push_back(N);
474  return SDOperand(N, 0);
475}
476
477
478
479/// getNode - Gets or creates the specified node.
480///
481SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT) {
482  SDNode *N = new SDNode(Opcode, VT);
483  AllNodes.push_back(N);
484  return SDOperand(N, 0);
485}
486
487SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT,
488                                SDOperand Operand) {
489  if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Operand.Val)) {
490    uint64_t Val = C->getValue();
491    switch (Opcode) {
492    default: break;
493    case ISD::SIGN_EXTEND: return getConstant(C->getSignExtended(), VT);
494    case ISD::ZERO_EXTEND: return getConstant(Val, VT);
495    case ISD::TRUNCATE:    return getConstant(Val, VT);
496    case ISD::SINT_TO_FP:  return getConstantFP(C->getSignExtended(), VT);
497    case ISD::UINT_TO_FP:  return getConstantFP(C->getValue(), VT);
498    }
499  }
500
501  if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Operand.Val))
502    switch (Opcode) {
503    case ISD::FP_ROUND:
504    case ISD::FP_EXTEND:
505      return getConstantFP(C->getValue(), VT);
506    case ISD::FP_TO_SINT:
507      return getConstant((int64_t)C->getValue(), VT);
508    case ISD::FP_TO_UINT:
509      return getConstant((uint64_t)C->getValue(), VT);
510    }
511
512  unsigned OpOpcode = Operand.Val->getOpcode();
513  switch (Opcode) {
514  case ISD::SIGN_EXTEND:
515    if (Operand.getValueType() == VT) return Operand;   // noop extension
516    if (OpOpcode == ISD::SIGN_EXTEND || OpOpcode == ISD::ZERO_EXTEND)
517      return getNode(OpOpcode, VT, Operand.Val->getOperand(0));
518    break;
519  case ISD::ZERO_EXTEND:
520    if (Operand.getValueType() == VT) return Operand;   // noop extension
521    if (OpOpcode == ISD::ZERO_EXTEND)
522      return getNode(ISD::ZERO_EXTEND, VT, Operand.Val->getOperand(0));
523    break;
524  case ISD::TRUNCATE:
525    if (Operand.getValueType() == VT) return Operand;   // noop truncate
526    if (OpOpcode == ISD::TRUNCATE)
527      return getNode(ISD::TRUNCATE, VT, Operand.Val->getOperand(0));
528    else if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND) {
529      // If the source is smaller than the dest, we still need an extend.
530      if (Operand.Val->getOperand(0).getValueType() < VT)
531        return getNode(OpOpcode, VT, Operand.Val->getOperand(0));
532      else if (Operand.Val->getOperand(0).getValueType() > VT)
533        return getNode(ISD::TRUNCATE, VT, Operand.Val->getOperand(0));
534      else
535        return Operand.Val->getOperand(0);
536    }
537    break;
538  }
539
540  SDNode *&N = UnaryOps[std::make_pair(Opcode, std::make_pair(Operand, VT))];
541  if (N) return SDOperand(N, 0);
542  N = new SDNode(Opcode, Operand);
543  N->setValueTypes(VT);
544  AllNodes.push_back(N);
545  return SDOperand(N, 0);
546}
547
548SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT,
549                                SDOperand N1, SDOperand N2) {
550#ifndef NDEBUG
551  switch (Opcode) {
552  case ISD::AND:
553  case ISD::OR:
554  case ISD::XOR:
555  case ISD::UDIV:
556  case ISD::UREM:
557    assert(MVT::isInteger(VT) && "This operator does not apply to FP types!");
558    // fall through
559  case ISD::ADD:
560  case ISD::SUB:
561  case ISD::MUL:
562  case ISD::SDIV:
563  case ISD::SREM:
564    assert(N1.getValueType() == N2.getValueType() &&
565           N1.getValueType() == VT && "Binary operator types must match!");
566    break;
567
568  case ISD::SHL:
569  case ISD::SRA:
570  case ISD::SRL:
571    assert(VT == N1.getValueType() &&
572           "Shift operators return type must be the same as their first arg");
573    assert(MVT::isInteger(VT) && MVT::isInteger(N2.getValueType()) &&
574           VT != MVT::i1 && "Shifts only work on integers");
575    break;
576  default: break;
577  }
578#endif
579
580  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val);
581  ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.Val);
582  if (N1C) {
583    if (N2C) {
584      uint64_t C1 = N1C->getValue(), C2 = N2C->getValue();
585      switch (Opcode) {
586      case ISD::ADD: return getConstant(C1 + C2, VT);
587      case ISD::SUB: return getConstant(C1 - C2, VT);
588      case ISD::MUL: return getConstant(C1 * C2, VT);
589      case ISD::UDIV:
590        if (C2) return getConstant(C1 / C2, VT);
591        break;
592      case ISD::UREM :
593        if (C2) return getConstant(C1 % C2, VT);
594        break;
595      case ISD::SDIV :
596        if (C2) return getConstant(N1C->getSignExtended() /
597                                   N2C->getSignExtended(), VT);
598        break;
599      case ISD::SREM :
600        if (C2) return getConstant(N1C->getSignExtended() %
601                                   N2C->getSignExtended(), VT);
602        break;
603      case ISD::AND  : return getConstant(C1 & C2, VT);
604      case ISD::OR   : return getConstant(C1 | C2, VT);
605      case ISD::XOR  : return getConstant(C1 ^ C2, VT);
606      case ISD::SHL  : return getConstant(C1 << (int)C2, VT);
607      case ISD::SRL  : return getConstant(C1 >> (unsigned)C2, VT);
608      case ISD::SRA  : return getConstant(N1C->getSignExtended() >>(int)C2, VT);
609      default: break;
610      }
611
612    } else {      // Cannonicalize constant to RHS if commutative
613      if (isCommutativeBinOp(Opcode)) {
614        std::swap(N1C, N2C);
615        std::swap(N1, N2);
616      }
617    }
618  }
619
620  if (N2C) {
621    uint64_t C2 = N2C->getValue();
622
623    switch (Opcode) {
624    case ISD::ADD:
625      if (!C2) return N1;         // add X, 0 -> X
626      break;
627    case ISD::SUB:
628      if (!C2) return N1;         // sub X, 0 -> X
629      break;
630    case ISD::MUL:
631      if (!C2) return N2;         // mul X, 0 -> 0
632      if (N2C->isAllOnesValue()) // mul X, -1 -> 0-X
633        return getNode(ISD::SUB, VT, getConstant(0, VT), N1);
634
635      // FIXME: This should only be done if the target supports shift
636      // operations.
637      if ((C2 & C2-1) == 0) {
638        SDOperand ShAmt = getConstant(ExactLog2(C2), MVT::i8);
639        return getNode(ISD::SHL, VT, N1, ShAmt);
640      }
641      break;
642
643    case ISD::UDIV:
644      // FIXME: This should only be done if the target supports shift
645      // operations.
646      if ((C2 & C2-1) == 0 && C2) {
647        SDOperand ShAmt = getConstant(ExactLog2(C2), MVT::i8);
648        return getNode(ISD::SRL, VT, N1, ShAmt);
649      }
650      break;
651
652    case ISD::SHL:
653    case ISD::SRL:
654    case ISD::SRA:
655      if (C2 == 0) return N1;
656      break;
657
658    case ISD::AND:
659      if (!C2) return N2;         // X and 0 -> 0
660      if (N2C->isAllOnesValue())
661	return N1;                // X and -1 -> X
662      break;
663    case ISD::OR:
664      if (!C2)return N1;          // X or 0 -> X
665      if (N2C->isAllOnesValue())
666	return N2;                // X or -1 -> -1
667      break;
668    case ISD::XOR:
669      if (!C2) return N1;        // X xor 0 -> X
670      if (N2C->isAllOnesValue()) {
671        if (SetCCSDNode *SetCC = dyn_cast<SetCCSDNode>(N1.Val)){
672          // !(X op Y) -> (X !op Y)
673          bool isInteger = MVT::isInteger(SetCC->getOperand(0).getValueType());
674          return getSetCC(ISD::getSetCCInverse(SetCC->getCondition(),isInteger),
675                          SetCC->getValueType(0),
676                          SetCC->getOperand(0), SetCC->getOperand(1));
677        } else if (N1.getOpcode() == ISD::AND || N1.getOpcode() == ISD::OR) {
678          SDNode *Op = N1.Val;
679          // !(X or Y) -> (!X and !Y) iff X or Y are freely invertible
680          // !(X and Y) -> (!X or !Y) iff X or Y are freely invertible
681          SDOperand LHS = Op->getOperand(0), RHS = Op->getOperand(1);
682          if (isInvertibleForFree(RHS) || isInvertibleForFree(LHS)) {
683            LHS = getNode(ISD::XOR, VT, LHS, N2);  // RHS = ~LHS
684            RHS = getNode(ISD::XOR, VT, RHS, N2);  // RHS = ~RHS
685            if (Op->getOpcode() == ISD::AND)
686              return getNode(ISD::OR, VT, LHS, RHS);
687            return getNode(ISD::AND, VT, LHS, RHS);
688          }
689        }
690	// X xor -1 -> not(x)  ?
691      }
692      break;
693    }
694
695    // Reassociate ((X op C1) op C2) if possible.
696    if (N1.getOpcode() == Opcode && isAssociativeBinOp(Opcode))
697      if (ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N1.Val->getOperand(1)))
698        return getNode(Opcode, VT, N1.Val->getOperand(0),
699                       getNode(Opcode, VT, N2, N1.Val->getOperand(1)));
700  }
701
702  ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1.Val);
703  ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2.Val);
704  if (N1CFP)
705    if (N2CFP) {
706      double C1 = N1CFP->getValue(), C2 = N2CFP->getValue();
707      switch (Opcode) {
708      case ISD::ADD: return getConstantFP(C1 + C2, VT);
709      case ISD::SUB: return getConstantFP(C1 - C2, VT);
710      case ISD::MUL: return getConstantFP(C1 * C2, VT);
711      case ISD::SDIV:
712        if (C2) return getConstantFP(C1 / C2, VT);
713        break;
714      case ISD::SREM :
715        if (C2) return getConstantFP(fmod(C1, C2), VT);
716        break;
717      default: break;
718      }
719
720    } else {      // Cannonicalize constant to RHS if commutative
721      if (isCommutativeBinOp(Opcode)) {
722        std::swap(N1CFP, N2CFP);
723        std::swap(N1, N2);
724      }
725    }
726
727  // Finally, fold operations that do not require constants.
728  switch (Opcode) {
729  case ISD::AND:
730  case ISD::OR:
731    if (SetCCSDNode *LHS = dyn_cast<SetCCSDNode>(N1.Val))
732      if (SetCCSDNode *RHS = dyn_cast<SetCCSDNode>(N2.Val)) {
733        SDOperand LL = LHS->getOperand(0), RL = RHS->getOperand(0);
734        SDOperand LR = LHS->getOperand(1), RR = RHS->getOperand(1);
735        ISD::CondCode Op2 = RHS->getCondition();
736
737        // (X op1 Y) | (Y op2 X) -> (X op1 Y) | (X swapop2 Y)
738        if (LL == RR && LR == RL) {
739          Op2 = ISD::getSetCCSwappedOperands(Op2);
740          goto MatchedBackwards;
741        }
742
743        if (LL == RL && LR == RR) {
744        MatchedBackwards:
745          ISD::CondCode Result;
746          bool isInteger = MVT::isInteger(LL.getValueType());
747          if (Opcode == ISD::OR)
748            Result = ISD::getSetCCOrOperation(LHS->getCondition(), Op2,
749                                              isInteger);
750          else
751            Result = ISD::getSetCCAndOperation(LHS->getCondition(), Op2,
752                                               isInteger);
753          if (Result != ISD::SETCC_INVALID)
754            return getSetCC(Result, LHS->getValueType(0), LL, LR);
755        }
756      }
757    break;
758  case ISD::XOR:
759    if (N1 == N2) return getConstant(0, VT);  // xor X, Y -> 0
760    break;
761  case ISD::SUB:
762    if (N1.getOpcode() == ISD::ADD) {
763      if (N1.Val->getOperand(0) == N2)
764        return N1.Val->getOperand(1);         // (A+B)-A == B
765      if (N1.Val->getOperand(1) == N2)
766        return N1.Val->getOperand(0);         // (A+B)-B == A
767    }
768    break;
769  }
770
771  SDNode *&N = BinaryOps[std::make_pair(Opcode, std::make_pair(N1, N2))];
772  if (N) return SDOperand(N, 0);
773  N = new SDNode(Opcode, N1, N2);
774  N->setValueTypes(VT);
775
776  AllNodes.push_back(N);
777  return SDOperand(N, 0);
778}
779
780SDOperand SelectionDAG::getLoad(MVT::ValueType VT,
781                                SDOperand Chain, SDOperand Ptr) {
782  SDNode *&N = Loads[std::make_pair(Ptr, std::make_pair(Chain, VT))];
783  if (N) return SDOperand(N, 0);
784  N = new SDNode(ISD::LOAD, Chain, Ptr);
785
786  // Loads have a token chain.
787  N->setValueTypes(VT, MVT::Other);
788  AllNodes.push_back(N);
789  return SDOperand(N, 0);
790}
791
792
793SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT,
794                                SDOperand N1, SDOperand N2, SDOperand N3) {
795  // Perform various simplifications.
796  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val);
797  ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.Val);
798  ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.Val);
799  switch (Opcode) {
800  case ISD::SELECT:
801    if (N1C)
802      if (N1C->getValue())
803        return N2;             // select true, X, Y -> X
804      else
805        return N3;             // select false, X, Y -> Y
806
807    if (N2 == N3) return N2;   // select C, X, X -> X
808
809    if (VT == MVT::i1) {  // Boolean SELECT
810      if (N2C) {
811        if (N3C) {
812          if (N2C->getValue()) // select C, 1, 0 -> C
813            return N1;
814          return getNode(ISD::XOR, VT, N1, N3); // select C, 0, 1 -> ~C
815        }
816
817        if (N2C->getValue())   // select C, 1, X -> C | X
818          return getNode(ISD::OR, VT, N1, N3);
819        else                   // select C, 0, X -> ~C & X
820          return getNode(ISD::AND, VT,
821                         getNode(ISD::XOR, N1.getValueType(), N1,
822                                 getConstant(1, N1.getValueType())), N3);
823      } else if (N3C) {
824        if (N3C->getValue())   // select C, X, 1 -> ~C | X
825          return getNode(ISD::OR, VT,
826                         getNode(ISD::XOR, N1.getValueType(), N1,
827                                 getConstant(1, N1.getValueType())), N2);
828        else                   // select C, X, 0 -> C & X
829          return getNode(ISD::AND, VT, N1, N2);
830      }
831    }
832
833    break;
834  case ISD::BRCOND:
835    if (N2C)
836      if (N2C->getValue()) // Unconditional branch
837        return getNode(ISD::BR, MVT::Other, N1, N3);
838      else
839        return N1;         // Never-taken branch
840    break;
841  }
842
843  SDNode *N = new SDNode(Opcode, N1, N2, N3);
844  switch (Opcode) {
845  default:
846    N->setValueTypes(VT);
847    break;
848  case ISD::DYNAMIC_STACKALLOC: // DYNAMIC_STACKALLOC produces pointer and chain
849    N->setValueTypes(VT, MVT::Other);
850    break;
851  }
852
853  // FIXME: memoize NODES
854  AllNodes.push_back(N);
855  return SDOperand(N, 0);
856}
857
858SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT,
859                                std::vector<SDOperand> &Children) {
860  switch (Children.size()) {
861  case 0: return getNode(Opcode, VT);
862  case 1: return getNode(Opcode, VT, Children[0]);
863  case 2: return getNode(Opcode, VT, Children[0], Children[1]);
864  case 3: return getNode(Opcode, VT, Children[0], Children[1], Children[2]);
865  default:
866    // FIXME: MEMOIZE!!
867    SDNode *N = new SDNode(Opcode, Children);
868    N->setValueTypes(VT);
869    AllNodes.push_back(N);
870    return SDOperand(N, 0);
871  }
872}
873
874SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT,SDOperand N1,
875                                MVT::ValueType EVT) {
876
877  switch (Opcode) {
878  default: assert(0 && "Bad opcode for this accessor!");
879  case ISD::FP_ROUND_INREG:
880    assert(VT == N1.getValueType() && "Not an inreg round!");
881    assert(MVT::isFloatingPoint(VT) && MVT::isFloatingPoint(EVT) &&
882           "Cannot FP_ROUND_INREG integer types");
883    if (EVT == VT) return N1;  // Not actually rounding
884    assert(EVT < VT && "Not rounding down!");
885    break;
886  case ISD::ZERO_EXTEND_INREG:
887  case ISD::SIGN_EXTEND_INREG:
888    assert(VT == N1.getValueType() && "Not an inreg extend!");
889    assert(MVT::isInteger(VT) && MVT::isInteger(EVT) &&
890           "Cannot *_EXTEND_INREG FP types");
891    if (EVT == VT) return N1;  // Not actually extending
892    assert(EVT < VT && "Not extending!");
893
894    // If we are sign extending an extension, use the original source.
895    if (N1.getOpcode() == ISD::ZERO_EXTEND_INREG ||
896        N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
897      if (N1.getOpcode() == Opcode &&
898          cast<MVTSDNode>(N1)->getExtraValueType() <= EVT)
899        return N1;
900    }
901
902    break;
903  }
904
905  EVTStruct NN;
906  NN.Opcode = Opcode;
907  NN.VT = VT;
908  NN.EVT = EVT;
909  NN.Ops.push_back(N1);
910
911  SDNode *&N = MVTSDNodes[NN];
912  if (N) return SDOperand(N, 0);
913  N = new MVTSDNode(Opcode, VT, N1, EVT);
914  AllNodes.push_back(N);
915  return SDOperand(N, 0);
916}
917
918SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT,SDOperand N1,
919                                SDOperand N2, MVT::ValueType EVT) {
920  switch (Opcode) {
921  default:  assert(0 && "Bad opcode for this accessor!");
922  case ISD::EXTLOAD:
923  case ISD::SEXTLOAD:
924  case ISD::ZEXTLOAD:
925    // If they are asking for an extending loat from/to the same thing, return a
926    // normal load.
927    if (VT == EVT)
928      return getNode(ISD::LOAD, VT, N1, N2);
929    assert(EVT < VT && "Should only be an extending load, not truncating!");
930    assert((Opcode == ISD::EXTLOAD || MVT::isInteger(VT)) &&
931           "Cannot sign/zero extend a FP load!");
932    assert(MVT::isInteger(VT) == MVT::isInteger(EVT) &&
933           "Cannot convert from FP to Int or Int -> FP!");
934    break;
935  }
936
937  EVTStruct NN;
938  NN.Opcode = Opcode;
939  NN.VT = VT;
940  NN.EVT = EVT;
941  NN.Ops.push_back(N1);
942  NN.Ops.push_back(N2);
943
944  SDNode *&N = MVTSDNodes[NN];
945  if (N) return SDOperand(N, 0);
946  N = new MVTSDNode(Opcode, VT, MVT::Other, N1, N2, EVT);
947  AllNodes.push_back(N);
948  return SDOperand(N, 0);
949}
950
951SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT,SDOperand N1,
952                                SDOperand N2, SDOperand N3, MVT::ValueType EVT) {
953  switch (Opcode) {
954  default:  assert(0 && "Bad opcode for this accessor!");
955  case ISD::TRUNCSTORE:
956#if 0 // FIXME: If the target supports EVT natively, convert to a truncate/store
957    // If this is a truncating store of a constant, convert to the desired type
958    // and store it instead.
959    if (isa<Constant>(N1)) {
960      SDOperand Op = getNode(ISD::TRUNCATE, EVT, N1);
961      if (isa<Constant>(Op))
962        N1 = Op;
963    }
964    // Also for ConstantFP?
965#endif
966    if (N1.getValueType() == EVT)       // Normal store?
967      return getNode(ISD::STORE, VT, N1, N2, N3);
968    assert(N2.getValueType() > EVT && "Not a truncation?");
969    assert(MVT::isInteger(N2.getValueType()) == MVT::isInteger(EVT) &&
970           "Can't do FP-INT conversion!");
971    break;
972  }
973
974  EVTStruct NN;
975  NN.Opcode = Opcode;
976  NN.VT = VT;
977  NN.EVT = EVT;
978  NN.Ops.push_back(N1);
979  NN.Ops.push_back(N2);
980  NN.Ops.push_back(N3);
981
982  SDNode *&N = MVTSDNodes[NN];
983  if (N) return SDOperand(N, 0);
984  N = new MVTSDNode(Opcode, VT, N1, N2, N3, EVT);
985  AllNodes.push_back(N);
986  return SDOperand(N, 0);
987}
988
989
990/// hasNUsesOfValue - Return true if there are exactly NUSES uses of the
991/// indicated value.  This method ignores uses of other values defined by this
992/// operation.
993bool SDNode::hasNUsesOfValue(unsigned NUses, unsigned Value) {
994  assert(Value < getNumValues() && "Bad value!");
995
996  // If there is only one value, this is easy.
997  if (getNumValues() == 1)
998    return use_size() == NUses;
999  if (Uses.size() < NUses) return false;
1000
1001  SDOperand TheValue(this, Value);
1002
1003  std::set<SDNode*> UsersHandled;
1004
1005  for (std::vector<SDNode*>::iterator UI = Uses.begin(), E = Uses.end();
1006       UI != E; ++UI) {
1007    SDNode *User = *UI;
1008    if (User->getNumOperands() == 1 ||
1009        UsersHandled.insert(User).second)     // First time we've seen this?
1010      for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i)
1011        if (User->getOperand(i) == TheValue) {
1012          if (NUses == 0)
1013            return false;   // too many uses
1014          --NUses;
1015        }
1016  }
1017
1018  // Found exactly the right number of uses?
1019  return NUses == 0;
1020}
1021
1022
1023const char *SDNode::getOperationName() const {
1024  switch (getOpcode()) {
1025  default: return "<<Unknown>>";
1026  case ISD::EntryToken:    return "EntryToken";
1027  case ISD::TokenFactor:   return "TokenFactor";
1028  case ISD::Constant:      return "Constant";
1029  case ISD::ConstantFP:    return "ConstantFP";
1030  case ISD::GlobalAddress: return "GlobalAddress";
1031  case ISD::FrameIndex:    return "FrameIndex";
1032  case ISD::BasicBlock:    return "BasicBlock";
1033  case ISD::ExternalSymbol: return "ExternalSymbol";
1034  case ISD::ConstantPool:  return "ConstantPoolIndex";
1035  case ISD::CopyToReg:     return "CopyToReg";
1036  case ISD::CopyFromReg:   return "CopyFromReg";
1037  case ISD::ImplicitDef:   return "ImplicitDef";
1038
1039  case ISD::ADD:    return "add";
1040  case ISD::SUB:    return "sub";
1041  case ISD::MUL:    return "mul";
1042  case ISD::SDIV:   return "sdiv";
1043  case ISD::UDIV:   return "udiv";
1044  case ISD::SREM:   return "srem";
1045  case ISD::UREM:   return "urem";
1046  case ISD::AND:    return "and";
1047  case ISD::OR:     return "or";
1048  case ISD::XOR:    return "xor";
1049  case ISD::SHL:    return "shl";
1050  case ISD::SRA:    return "sra";
1051  case ISD::SRL:    return "srl";
1052
1053  case ISD::SELECT: return "select";
1054  case ISD::ADDC:   return "addc";
1055  case ISD::SUBB:   return "subb";
1056
1057    // Conversion operators.
1058  case ISD::SIGN_EXTEND: return "sign_extend";
1059  case ISD::ZERO_EXTEND: return "zero_extend";
1060  case ISD::SIGN_EXTEND_INREG: return "sign_extend_inreg";
1061  case ISD::ZERO_EXTEND_INREG: return "zero_extend_inreg";
1062  case ISD::TRUNCATE:    return "truncate";
1063  case ISD::FP_ROUND:    return "fp_round";
1064  case ISD::FP_ROUND_INREG: return "fp_round_inreg";
1065  case ISD::FP_EXTEND:   return "fp_extend";
1066
1067  case ISD::SINT_TO_FP:  return "sint_to_fp";
1068  case ISD::UINT_TO_FP:  return "uint_to_fp";
1069  case ISD::FP_TO_SINT:  return "fp_to_sint";
1070  case ISD::FP_TO_UINT:  return "fp_to_uint";
1071
1072    // Control flow instructions
1073  case ISD::BR:      return "br";
1074  case ISD::BRCOND:  return "brcond";
1075  case ISD::RET:     return "ret";
1076  case ISD::CALL:    return "call";
1077  case ISD::ADJCALLSTACKDOWN:  return "adjcallstackdown";
1078  case ISD::ADJCALLSTACKUP:    return "adjcallstackup";
1079
1080    // Other operators
1081  case ISD::LOAD:    return "load";
1082  case ISD::STORE:   return "store";
1083  case ISD::EXTLOAD:    return "extload";
1084  case ISD::SEXTLOAD:   return "sextload";
1085  case ISD::ZEXTLOAD:   return "zextload";
1086  case ISD::TRUNCSTORE: return "truncstore";
1087
1088  case ISD::DYNAMIC_STACKALLOC: return "dynamic_stackalloc";
1089  case ISD::EXTRACT_ELEMENT: return "extract_element";
1090  case ISD::BUILD_PAIR: return "build_pair";
1091  case ISD::MEMSET:  return "memset";
1092  case ISD::MEMCPY:  return "memcpy";
1093  case ISD::MEMMOVE: return "memmove";
1094
1095  case ISD::SETCC:
1096    const SetCCSDNode *SetCC = cast<SetCCSDNode>(this);
1097    switch (SetCC->getCondition()) {
1098    default: assert(0 && "Unknown setcc condition!");
1099    case ISD::SETOEQ:  return "setcc:setoeq";
1100    case ISD::SETOGT:  return "setcc:setogt";
1101    case ISD::SETOGE:  return "setcc:setoge";
1102    case ISD::SETOLT:  return "setcc:setolt";
1103    case ISD::SETOLE:  return "setcc:setole";
1104    case ISD::SETONE:  return "setcc:setone";
1105
1106    case ISD::SETO:    return "setcc:seto";
1107    case ISD::SETUO:   return "setcc:setuo";
1108    case ISD::SETUEQ:  return "setcc:setue";
1109    case ISD::SETUGT:  return "setcc:setugt";
1110    case ISD::SETUGE:  return "setcc:setuge";
1111    case ISD::SETULT:  return "setcc:setult";
1112    case ISD::SETULE:  return "setcc:setule";
1113    case ISD::SETUNE:  return "setcc:setune";
1114
1115    case ISD::SETEQ:   return "setcc:seteq";
1116    case ISD::SETGT:   return "setcc:setgt";
1117    case ISD::SETGE:   return "setcc:setge";
1118    case ISD::SETLT:   return "setcc:setlt";
1119    case ISD::SETLE:   return "setcc:setle";
1120    case ISD::SETNE:   return "setcc:setne";
1121    }
1122  }
1123}
1124
1125void SDNode::dump() const {
1126  std::cerr << (void*)this << ": ";
1127
1128  for (unsigned i = 0, e = getNumValues(); i != e; ++i) {
1129    if (i) std::cerr << ",";
1130    if (getValueType(i) == MVT::Other)
1131      std::cerr << "ch";
1132    else
1133      std::cerr << MVT::getValueTypeString(getValueType(i));
1134  }
1135  std::cerr << " = " << getOperationName();
1136
1137  std::cerr << " ";
1138  for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1139    if (i) std::cerr << ", ";
1140    std::cerr << (void*)getOperand(i).Val;
1141    if (unsigned RN = getOperand(i).ResNo)
1142      std::cerr << ":" << RN;
1143  }
1144
1145  if (const ConstantSDNode *CSDN = dyn_cast<ConstantSDNode>(this)) {
1146    std::cerr << "<" << CSDN->getValue() << ">";
1147  } else if (const ConstantFPSDNode *CSDN = dyn_cast<ConstantFPSDNode>(this)) {
1148    std::cerr << "<" << CSDN->getValue() << ">";
1149  } else if (const GlobalAddressSDNode *GADN =
1150             dyn_cast<GlobalAddressSDNode>(this)) {
1151    std::cerr << "<";
1152    WriteAsOperand(std::cerr, GADN->getGlobal()) << ">";
1153  } else if (const FrameIndexSDNode *FIDN =
1154	     dyn_cast<FrameIndexSDNode>(this)) {
1155    std::cerr << "<" << FIDN->getIndex() << ">";
1156  } else if (const ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(this)){
1157    std::cerr << "<" << CP->getIndex() << ">";
1158  } else if (const BasicBlockSDNode *BBDN =
1159	     dyn_cast<BasicBlockSDNode>(this)) {
1160    std::cerr << "<";
1161    const Value *LBB = (const Value*)BBDN->getBasicBlock()->getBasicBlock();
1162    if (LBB)
1163      std::cerr << LBB->getName() << " ";
1164    std::cerr << (const void*)BBDN->getBasicBlock() << ">";
1165  } else if (const RegSDNode *C2V = dyn_cast<RegSDNode>(this)) {
1166    std::cerr << "<reg #" << C2V->getReg() << ">";
1167  } else if (const ExternalSymbolSDNode *ES =
1168             dyn_cast<ExternalSymbolSDNode>(this)) {
1169    std::cerr << "'" << ES->getSymbol() << "'";
1170  } else if (const MVTSDNode *M = dyn_cast<MVTSDNode>(this)) {
1171    std::cerr << " - Ty = " << MVT::getValueTypeString(M->getExtraValueType());
1172  }
1173}
1174
1175static void DumpNodes(SDNode *N, unsigned indent) {
1176  for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1177    if (N->getOperand(i).Val->hasOneUse())
1178      DumpNodes(N->getOperand(i).Val, indent+2);
1179    else
1180      std::cerr << "\n" << std::string(indent+2, ' ')
1181                << (void*)N->getOperand(i).Val << ": <multiple use>";
1182
1183
1184  std::cerr << "\n" << std::string(indent, ' ');
1185  N->dump();
1186}
1187
1188void SelectionDAG::dump() const {
1189  std::cerr << "SelectionDAG has " << AllNodes.size() << " nodes:";
1190  std::vector<SDNode*> Nodes(AllNodes);
1191  std::sort(Nodes.begin(), Nodes.end());
1192
1193  for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
1194    if (!Nodes[i]->hasOneUse() && Nodes[i] != getRoot().Val)
1195      DumpNodes(Nodes[i], 2);
1196  }
1197
1198  DumpNodes(getRoot().Val, 2);
1199
1200  std::cerr << "\n\n";
1201}
1202
1203