SelectionDAG.cpp revision eea805e74ce49f98e03c87a20cf2e6a6ff1b7c52
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/Target/TargetLowering.h"
20#include <iostream>
21#include <set>
22#include <cmath>
23#include <algorithm>
24using namespace llvm;
25
26static bool isCommutativeBinOp(unsigned Opcode) {
27  switch (Opcode) {
28  case ISD::ADD:
29  case ISD::MUL:
30  case ISD::AND:
31  case ISD::OR:
32  case ISD::XOR: return true;
33  default: return false; // FIXME: Need commutative info for user ops!
34  }
35}
36
37static bool isAssociativeBinOp(unsigned Opcode) {
38  switch (Opcode) {
39  case ISD::ADD:
40  case ISD::MUL:
41  case ISD::AND:
42  case ISD::OR:
43  case ISD::XOR: return true;
44  default: return false; // FIXME: Need associative info for user ops!
45  }
46}
47
48static unsigned ExactLog2(uint64_t Val) {
49  unsigned Count = 0;
50  while (Val != 1) {
51    Val >>= 1;
52    ++Count;
53  }
54  return Count;
55}
56
57// isInvertibleForFree - Return true if there is no cost to emitting the logical
58// inverse of this node.
59static bool isInvertibleForFree(SDOperand N) {
60  if (isa<ConstantSDNode>(N.Val)) return true;
61  if (isa<SetCCSDNode>(N.Val) && N.Val->hasOneUse())
62    return true;
63  return false;
64}
65
66
67/// getSetCCSwappedOperands - Return the operation corresponding to (Y op X)
68/// when given the operation for (X op Y).
69ISD::CondCode ISD::getSetCCSwappedOperands(ISD::CondCode Operation) {
70  // To perform this operation, we just need to swap the L and G bits of the
71  // operation.
72  unsigned OldL = (Operation >> 2) & 1;
73  unsigned OldG = (Operation >> 1) & 1;
74  return ISD::CondCode((Operation & ~6) |  // Keep the N, U, E bits
75                       (OldL << 1) |       // New G bit
76                       (OldG << 2));        // New L bit.
77}
78
79/// getSetCCInverse - Return the operation corresponding to !(X op Y), where
80/// 'op' is a valid SetCC operation.
81ISD::CondCode ISD::getSetCCInverse(ISD::CondCode Op, bool isInteger) {
82  unsigned Operation = Op;
83  if (isInteger)
84    Operation ^= 7;   // Flip L, G, E bits, but not U.
85  else
86    Operation ^= 15;  // Flip all of the condition bits.
87  if (Operation > ISD::SETTRUE2)
88    Operation &= ~8;     // Don't let N and U bits get set.
89  return ISD::CondCode(Operation);
90}
91
92
93/// isSignedOp - For an integer comparison, return 1 if the comparison is a
94/// signed operation and 2 if the result is an unsigned comparison.  Return zero
95/// if the operation does not depend on the sign of the input (setne and seteq).
96static int isSignedOp(ISD::CondCode Opcode) {
97  switch (Opcode) {
98  default: assert(0 && "Illegal integer setcc operation!");
99  case ISD::SETEQ:
100  case ISD::SETNE: return 0;
101  case ISD::SETLT:
102  case ISD::SETLE:
103  case ISD::SETGT:
104  case ISD::SETGE: return 1;
105  case ISD::SETULT:
106  case ISD::SETULE:
107  case ISD::SETUGT:
108  case ISD::SETUGE: return 2;
109  }
110}
111
112/// getSetCCOrOperation - Return the result of a logical OR between different
113/// comparisons of identical values: ((X op1 Y) | (X op2 Y)).  This function
114/// returns SETCC_INVALID if it is not possible to represent the resultant
115/// comparison.
116ISD::CondCode ISD::getSetCCOrOperation(ISD::CondCode Op1, ISD::CondCode Op2,
117                                       bool isInteger) {
118  if (isInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
119    // Cannot fold a signed integer setcc with an unsigned integer setcc.
120    return ISD::SETCC_INVALID;
121
122  unsigned Op = Op1 | Op2;  // Combine all of the condition bits.
123
124  // If the N and U bits get set then the resultant comparison DOES suddenly
125  // care about orderedness, and is true when ordered.
126  if (Op > ISD::SETTRUE2)
127    Op &= ~16;     // Clear the N bit.
128  return ISD::CondCode(Op);
129}
130
131/// getSetCCAndOperation - Return the result of a logical AND between different
132/// comparisons of identical values: ((X op1 Y) & (X op2 Y)).  This
133/// function returns zero if it is not possible to represent the resultant
134/// comparison.
135ISD::CondCode ISD::getSetCCAndOperation(ISD::CondCode Op1, ISD::CondCode Op2,
136                                        bool isInteger) {
137  if (isInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
138    // Cannot fold a signed setcc with an unsigned setcc.
139    return ISD::SETCC_INVALID;
140
141  // Combine all of the condition bits.
142  return ISD::CondCode(Op1 & Op2);
143}
144
145const TargetMachine &SelectionDAG::getTarget() const {
146  return TLI.getTargetMachine();
147}
148
149
150/// RemoveDeadNodes - This method deletes all unreachable nodes in the
151/// SelectionDAG, including nodes (like loads) that have uses of their token
152/// chain but no other uses and no side effect.  If a node is passed in as an
153/// argument, it is used as the seed for node deletion.
154void SelectionDAG::RemoveDeadNodes(SDNode *N) {
155  std::set<SDNode*> AllNodeSet(AllNodes.begin(), AllNodes.end());
156
157  // Create a dummy node (which is not added to allnodes), that adds a reference
158  // to the root node, preventing it from being deleted.
159  SDNode *DummyNode = new SDNode(ISD::EntryToken, getRoot());
160
161  DeleteNodeIfDead(N, &AllNodeSet);
162
163 Restart:
164  unsigned NumNodes = AllNodeSet.size();
165  for (std::set<SDNode*>::iterator I = AllNodeSet.begin(), E = AllNodeSet.end();
166       I != E; ++I) {
167    // Try to delete this node.
168    DeleteNodeIfDead(*I, &AllNodeSet);
169
170    // If we actually deleted any nodes, do not use invalid iterators in
171    // AllNodeSet.
172    if (AllNodeSet.size() != NumNodes)
173      goto Restart;
174  }
175
176  // Restore AllNodes.
177  if (AllNodes.size() != NumNodes)
178    AllNodes.assign(AllNodeSet.begin(), AllNodeSet.end());
179
180  // If the root changed (e.g. it was a dead load, update the root).
181  setRoot(DummyNode->getOperand(0));
182
183  // Now that we are done with the dummy node, delete it.
184  DummyNode->getOperand(0).Val->removeUser(DummyNode);
185  delete DummyNode;
186}
187
188void SelectionDAG::DeleteNodeIfDead(SDNode *N, void *NodeSet) {
189  if (!N->use_empty())
190    return;
191
192  // Okay, we really are going to delete this node.  First take this out of the
193  // appropriate CSE map.
194  switch (N->getOpcode()) {
195  case ISD::Constant:
196    Constants.erase(std::make_pair(cast<ConstantSDNode>(N)->getValue(),
197                                   N->getValueType(0)));
198    break;
199  case ISD::ConstantFP: {
200    union {
201      double DV;
202      uint64_t IV;
203    };
204    DV = cast<ConstantFPSDNode>(N)->getValue();
205    ConstantFPs.erase(std::make_pair(IV, N->getValueType(0)));
206    break;
207  }
208  case ISD::GlobalAddress:
209    GlobalValues.erase(cast<GlobalAddressSDNode>(N)->getGlobal());
210    break;
211  case ISD::FrameIndex:
212    FrameIndices.erase(cast<FrameIndexSDNode>(N)->getIndex());
213    break;
214  case ISD::ConstantPool:
215    ConstantPoolIndices.erase(cast<ConstantPoolSDNode>(N)->getIndex());
216    break;
217  case ISD::BasicBlock:
218    BBNodes.erase(cast<BasicBlockSDNode>(N)->getBasicBlock());
219    break;
220  case ISD::ExternalSymbol:
221    ExternalSymbols.erase(cast<ExternalSymbolSDNode>(N)->getSymbol());
222    break;
223
224  case ISD::LOAD:
225    Loads.erase(std::make_pair(N->getOperand(1),
226                               std::make_pair(N->getOperand(0),
227                                              N->getValueType(0))));
228    break;
229  case ISD::SETCC:
230    SetCCs.erase(std::make_pair(std::make_pair(N->getOperand(0),
231                                               N->getOperand(1)),
232                                std::make_pair(
233                                     cast<SetCCSDNode>(N)->getCondition(),
234                                     N->getValueType(0))));
235    break;
236  case ISD::TRUNCSTORE:
237  case ISD::SIGN_EXTEND_INREG:
238  case ISD::FP_ROUND_INREG:
239  case ISD::EXTLOAD:
240  case ISD::SEXTLOAD:
241  case ISD::ZEXTLOAD: {
242    EVTStruct NN;
243    NN.Opcode = N->getOpcode();
244    NN.VT = N->getValueType(0);
245    NN.EVT = cast<MVTSDNode>(N)->getExtraValueType();
246    for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
247      NN.Ops.push_back(N->getOperand(i));
248    MVTSDNodes.erase(NN);
249    break;
250  }
251  default:
252    if (N->getNumOperands() == 1)
253      UnaryOps.erase(std::make_pair(N->getOpcode(),
254                                    std::make_pair(N->getOperand(0),
255                                                   N->getValueType(0))));
256    else if (N->getNumOperands() == 2)
257      BinaryOps.erase(std::make_pair(N->getOpcode(),
258                                     std::make_pair(N->getOperand(0),
259                                                    N->getOperand(1))));
260    break;
261  }
262
263  // Next, brutally remove the operand list.
264  while (!N->Operands.empty()) {
265    SDNode *O = N->Operands.back().Val;
266    N->Operands.pop_back();
267    O->removeUser(N);
268
269    // Now that we removed this operand, see if there are no uses of it left.
270    DeleteNodeIfDead(O, NodeSet);
271  }
272
273  // Remove the node from the nodes set and delete it.
274  std::set<SDNode*> &AllNodeSet = *(std::set<SDNode*>*)NodeSet;
275  AllNodeSet.erase(N);
276
277  // Now that the node is gone, check to see if any of the operands of this node
278  // are dead now.
279  delete N;
280}
281
282
283SelectionDAG::~SelectionDAG() {
284  for (unsigned i = 0, e = AllNodes.size(); i != e; ++i)
285    delete AllNodes[i];
286}
287
288SDOperand SelectionDAG::getZeroExtendInReg(SDOperand Op, MVT::ValueType VT) {
289  if (Op.getValueType() == VT) return Op;
290  int64_t Imm = ~0ULL >> 64-MVT::getSizeInBits(VT);
291  return getNode(ISD::AND, Op.getValueType(), Op,
292                 getConstant(Imm, Op.getValueType()));
293}
294
295SDOperand SelectionDAG::getConstant(uint64_t Val, MVT::ValueType VT) {
296  assert(MVT::isInteger(VT) && "Cannot create FP integer constant!");
297  // Mask out any bits that are not valid for this constant.
298  if (VT != MVT::i64)
299    Val &= ((uint64_t)1 << MVT::getSizeInBits(VT)) - 1;
300
301  SDNode *&N = Constants[std::make_pair(Val, VT)];
302  if (N) return SDOperand(N, 0);
303  N = new ConstantSDNode(Val, VT);
304  AllNodes.push_back(N);
305  return SDOperand(N, 0);
306}
307
308SDOperand SelectionDAG::getConstantFP(double Val, MVT::ValueType VT) {
309  assert(MVT::isFloatingPoint(VT) && "Cannot create integer FP constant!");
310  if (VT == MVT::f32)
311    Val = (float)Val;  // Mask out extra precision.
312
313  // Do the map lookup using the actual bit pattern for the floating point
314  // value, so that we don't have problems with 0.0 comparing equal to -0.0, and
315  // we don't have issues with SNANs.
316  union {
317    double DV;
318    uint64_t IV;
319  };
320
321  DV = Val;
322
323  SDNode *&N = ConstantFPs[std::make_pair(IV, VT)];
324  if (N) return SDOperand(N, 0);
325  N = new ConstantFPSDNode(Val, VT);
326  AllNodes.push_back(N);
327  return SDOperand(N, 0);
328}
329
330
331
332SDOperand SelectionDAG::getGlobalAddress(const GlobalValue *GV,
333                                         MVT::ValueType VT) {
334  SDNode *&N = GlobalValues[GV];
335  if (N) return SDOperand(N, 0);
336  N = new GlobalAddressSDNode(GV,VT);
337  AllNodes.push_back(N);
338  return SDOperand(N, 0);
339}
340
341SDOperand SelectionDAG::getFrameIndex(int FI, MVT::ValueType VT) {
342  SDNode *&N = FrameIndices[FI];
343  if (N) return SDOperand(N, 0);
344  N = new FrameIndexSDNode(FI, VT);
345  AllNodes.push_back(N);
346  return SDOperand(N, 0);
347}
348
349SDOperand SelectionDAG::getConstantPool(unsigned CPIdx, MVT::ValueType VT) {
350  SDNode *N = ConstantPoolIndices[CPIdx];
351  if (N) return SDOperand(N, 0);
352  N = new ConstantPoolSDNode(CPIdx, VT);
353  AllNodes.push_back(N);
354  return SDOperand(N, 0);
355}
356
357SDOperand SelectionDAG::getBasicBlock(MachineBasicBlock *MBB) {
358  SDNode *&N = BBNodes[MBB];
359  if (N) return SDOperand(N, 0);
360  N = new BasicBlockSDNode(MBB);
361  AllNodes.push_back(N);
362  return SDOperand(N, 0);
363}
364
365SDOperand SelectionDAG::getExternalSymbol(const char *Sym, MVT::ValueType VT) {
366  SDNode *&N = ExternalSymbols[Sym];
367  if (N) return SDOperand(N, 0);
368  N = new ExternalSymbolSDNode(Sym, VT);
369  AllNodes.push_back(N);
370  return SDOperand(N, 0);
371}
372
373SDOperand SelectionDAG::getSetCC(ISD::CondCode Cond, MVT::ValueType VT,
374                                 SDOperand N1, SDOperand N2) {
375  // These setcc operations always fold.
376  switch (Cond) {
377  default: break;
378  case ISD::SETFALSE:
379  case ISD::SETFALSE2: return getConstant(0, VT);
380  case ISD::SETTRUE:
381  case ISD::SETTRUE2:  return getConstant(1, VT);
382  }
383
384  if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.Val)) {
385    uint64_t C2 = N2C->getValue();
386    if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val)) {
387      uint64_t C1 = N1C->getValue();
388
389      // Sign extend the operands if required
390      if (ISD::isSignedIntSetCC(Cond)) {
391        C1 = N1C->getSignExtended();
392        C2 = N2C->getSignExtended();
393      }
394
395      switch (Cond) {
396      default: assert(0 && "Unknown integer setcc!");
397      case ISD::SETEQ:  return getConstant(C1 == C2, VT);
398      case ISD::SETNE:  return getConstant(C1 != C2, VT);
399      case ISD::SETULT: return getConstant(C1 <  C2, VT);
400      case ISD::SETUGT: return getConstant(C1 >  C2, VT);
401      case ISD::SETULE: return getConstant(C1 <= C2, VT);
402      case ISD::SETUGE: return getConstant(C1 >= C2, VT);
403      case ISD::SETLT:  return getConstant((int64_t)C1 <  (int64_t)C2, VT);
404      case ISD::SETGT:  return getConstant((int64_t)C1 >  (int64_t)C2, VT);
405      case ISD::SETLE:  return getConstant((int64_t)C1 <= (int64_t)C2, VT);
406      case ISD::SETGE:  return getConstant((int64_t)C1 >= (int64_t)C2, VT);
407      }
408    } else {
409      uint64_t MinVal, MaxVal;
410      unsigned OperandBitSize = MVT::getSizeInBits(N2C->getValueType(0));
411      if (ISD::isSignedIntSetCC(Cond)) {
412        MinVal = 1ULL << (OperandBitSize-1);
413        if (OperandBitSize != 1)   // Avoid X >> 64, which is undefined.
414          MaxVal = ~0ULL >> (65-OperandBitSize);
415        else
416          MaxVal = 0;
417      } else {
418        MinVal = 0;
419        MaxVal = ~0ULL >> (64-OperandBitSize);
420      }
421
422      // Canonicalize GE/LE comparisons to use GT/LT comparisons.
423      if (Cond == ISD::SETGE || Cond == ISD::SETUGE) {
424        if (C2 == MinVal) return getConstant(1, VT);   // X >= MIN --> true
425        --C2;                                          // X >= C1 --> X > (C1-1)
426        Cond = (Cond == ISD::SETGE) ? ISD::SETGT : ISD::SETUGT;
427        N2 = getConstant(C2, N2.getValueType());
428        N2C = cast<ConstantSDNode>(N2.Val);
429      }
430
431      if (Cond == ISD::SETLE || Cond == ISD::SETULE) {
432        if (C2 == MaxVal) return getConstant(1, VT);   // X <= MAX --> true
433        ++C2;                                          // X <= C1 --> X < (C1+1)
434        Cond = (Cond == ISD::SETLE) ? ISD::SETLT : ISD::SETULT;
435        N2 = getConstant(C2, N2.getValueType());
436        N2C = cast<ConstantSDNode>(N2.Val);
437      }
438
439      // If we have setult X, 1, turn it into seteq X, 0
440      if ((Cond == ISD::SETLT || Cond == ISD::SETULT) && C2 == MinVal+1)
441        return getSetCC(ISD::SETEQ, VT, N1,
442                        getConstant(MinVal, N1.getValueType()));
443      // If we have setult X, 1, turn it into seteq X, 0
444      else if ((Cond == ISD::SETGT || Cond == ISD::SETUGT) && C2 == MaxVal-1)
445        return getSetCC(ISD::SETEQ, VT, N1,
446                        getConstant(MaxVal, N1.getValueType()));
447
448      // If we have "setcc X, C1", check to see if we can shrink the immediate
449      // by changing cc.
450
451      // SETUGT X, SINTMAX  -> SETLT X, 0
452      if (Cond == ISD::SETUGT && OperandBitSize != 1 &&
453          C2 == (~0ULL >> (65-OperandBitSize)))
454        return getSetCC(ISD::SETLT, VT, N1, getConstant(0, N2.getValueType()));
455
456      // FIXME: Implement the rest of these.
457
458    }
459  } else if (isa<ConstantSDNode>(N1.Val)) {
460      // Ensure that the constant occurs on the RHS.
461    return getSetCC(ISD::getSetCCSwappedOperands(Cond), VT, N2, N1);
462  }
463
464  if (ConstantFPSDNode *N1C = dyn_cast<ConstantFPSDNode>(N1.Val))
465    if (ConstantFPSDNode *N2C = dyn_cast<ConstantFPSDNode>(N2.Val)) {
466      double C1 = N1C->getValue(), C2 = N2C->getValue();
467
468      switch (Cond) {
469      default: break; // FIXME: Implement the rest of these!
470      case ISD::SETEQ:  return getConstant(C1 == C2, VT);
471      case ISD::SETNE:  return getConstant(C1 != C2, VT);
472      case ISD::SETLT:  return getConstant(C1 < C2, VT);
473      case ISD::SETGT:  return getConstant(C1 > C2, VT);
474      case ISD::SETLE:  return getConstant(C1 <= C2, VT);
475      case ISD::SETGE:  return getConstant(C1 >= C2, VT);
476      }
477    } else {
478      // Ensure that the constant occurs on the RHS.
479      Cond = ISD::getSetCCSwappedOperands(Cond);
480      std::swap(N1, N2);
481    }
482
483  if (N1 == N2) {
484    // We can always fold X == Y for integer setcc's.
485    if (MVT::isInteger(N1.getValueType()))
486      return getConstant(ISD::isTrueWhenEqual(Cond), VT);
487    unsigned UOF = ISD::getUnorderedFlavor(Cond);
488    if (UOF == 2)   // FP operators that are undefined on NaNs.
489      return getConstant(ISD::isTrueWhenEqual(Cond), VT);
490    if (UOF == ISD::isTrueWhenEqual(Cond))
491      return getConstant(UOF, VT);
492    // Otherwise, we can't fold it.  However, we can simplify it to SETUO/SETO
493    // if it is not already.
494    Cond = UOF == 0 ? ISD::SETUO : ISD::SETO;
495  }
496
497  if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
498      MVT::isInteger(N1.getValueType())) {
499    if (N1.getOpcode() == ISD::ADD || N1.getOpcode() == ISD::SUB ||
500        N1.getOpcode() == ISD::XOR) {
501      // Simplify (X+Y) == (X+Z) -->  Y == Z
502      if (N1.getOpcode() == N2.getOpcode()) {
503        if (N1.getOperand(0) == N2.getOperand(0))
504          return getSetCC(Cond, VT, N1.getOperand(1), N2.getOperand(1));
505        if (N1.getOperand(1) == N2.getOperand(1))
506          return getSetCC(Cond, VT, N1.getOperand(0), N2.getOperand(0));
507        if (isCommutativeBinOp(N1.getOpcode())) {
508          // If X op Y == Y op X, try other combinations.
509          if (N1.getOperand(0) == N2.getOperand(1))
510            return getSetCC(Cond, VT, N1.getOperand(1), N2.getOperand(0));
511          if (N1.getOperand(1) == N2.getOperand(0))
512            return getSetCC(Cond, VT, N1.getOperand(1), N2.getOperand(1));
513        }
514      }
515
516      // FIXME: move this stuff to the DAG Combiner when it exists!
517
518      // Simplify (X+Z) == X -->  Z == 0
519      if (N1.getOperand(0) == N2)
520        return getSetCC(Cond, VT, N1.getOperand(1),
521                        getConstant(0, N1.getValueType()));
522      if (N1.getOperand(1) == N2) {
523        if (isCommutativeBinOp(N1.getOpcode()))
524          return getSetCC(Cond, VT, N1.getOperand(0),
525                          getConstant(0, N1.getValueType()));
526        else {
527          assert(N1.getOpcode() == ISD::SUB && "Unexpected operation!");
528          // (Z-X) == X  --> Z == X<<1
529          return getSetCC(Cond, VT, N1.getOperand(0),
530                          getNode(ISD::SHL, N2.getValueType(),
531                                  N2, getConstant(1, TLI.getShiftAmountTy())));
532        }
533      }
534    }
535
536    if (N2.getOpcode() == ISD::ADD || N2.getOpcode() == ISD::SUB ||
537        N2.getOpcode() == ISD::XOR) {
538      // Simplify  X == (X+Z) -->  Z == 0
539      if (N2.getOperand(0) == N1)
540        return getSetCC(Cond, VT, N2.getOperand(1),
541                        getConstant(0, N2.getValueType()));
542      else if (N2.getOperand(1) == N1)
543        return getSetCC(Cond, VT, N2.getOperand(0),
544                        getConstant(0, N2.getValueType()));
545    }
546  }
547
548  SetCCSDNode *&N = SetCCs[std::make_pair(std::make_pair(N1, N2),
549                                          std::make_pair(Cond, VT))];
550  if (N) return SDOperand(N, 0);
551  N = new SetCCSDNode(Cond, N1, N2);
552  N->setValueTypes(VT);
553  AllNodes.push_back(N);
554  return SDOperand(N, 0);
555}
556
557
558
559/// getNode - Gets or creates the specified node.
560///
561SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT) {
562  SDNode *N = new SDNode(Opcode, VT);
563  AllNodes.push_back(N);
564  return SDOperand(N, 0);
565}
566
567SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT,
568                                SDOperand Operand) {
569  if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Operand.Val)) {
570    uint64_t Val = C->getValue();
571    switch (Opcode) {
572    default: break;
573    case ISD::SIGN_EXTEND: return getConstant(C->getSignExtended(), VT);
574    case ISD::ZERO_EXTEND: return getConstant(Val, VT);
575    case ISD::TRUNCATE:    return getConstant(Val, VT);
576    case ISD::SINT_TO_FP:  return getConstantFP(C->getSignExtended(), VT);
577    case ISD::UINT_TO_FP:  return getConstantFP(C->getValue(), VT);
578    }
579  }
580
581  if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Operand.Val))
582    switch (Opcode) {
583    case ISD::FNEG:
584      return getConstantFP(-C->getValue(), VT);
585    case ISD::FP_ROUND:
586    case ISD::FP_EXTEND:
587      return getConstantFP(C->getValue(), VT);
588    case ISD::FP_TO_SINT:
589      return getConstant((int64_t)C->getValue(), VT);
590    case ISD::FP_TO_UINT:
591      return getConstant((uint64_t)C->getValue(), VT);
592    }
593
594  unsigned OpOpcode = Operand.Val->getOpcode();
595  switch (Opcode) {
596  case ISD::TokenFactor:
597    return Operand;         // Factor of one node?  No factor.
598  case ISD::SIGN_EXTEND:
599    if (Operand.getValueType() == VT) return Operand;   // noop extension
600    if (OpOpcode == ISD::SIGN_EXTEND || OpOpcode == ISD::ZERO_EXTEND)
601      return getNode(OpOpcode, VT, Operand.Val->getOperand(0));
602    break;
603  case ISD::ZERO_EXTEND:
604    if (Operand.getValueType() == VT) return Operand;   // noop extension
605    if (OpOpcode == ISD::ZERO_EXTEND)   // (zext (zext x)) -> (zext x)
606      return getNode(ISD::ZERO_EXTEND, VT, Operand.Val->getOperand(0));
607    break;
608  case ISD::TRUNCATE:
609    if (Operand.getValueType() == VT) return Operand;   // noop truncate
610    if (OpOpcode == ISD::TRUNCATE)
611      return getNode(ISD::TRUNCATE, VT, Operand.Val->getOperand(0));
612    else if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND) {
613      // If the source is smaller than the dest, we still need an extend.
614      if (Operand.Val->getOperand(0).getValueType() < VT)
615        return getNode(OpOpcode, VT, Operand.Val->getOperand(0));
616      else if (Operand.Val->getOperand(0).getValueType() > VT)
617        return getNode(ISD::TRUNCATE, VT, Operand.Val->getOperand(0));
618      else
619        return Operand.Val->getOperand(0);
620    }
621    break;
622  case ISD::FNEG:
623    if (OpOpcode == ISD::SUB)   // -(X-Y) -> (Y-X)
624      return getNode(ISD::SUB, VT, Operand.Val->getOperand(1),
625                     Operand.Val->getOperand(0));
626    if (OpOpcode == ISD::FNEG)  // --X -> X
627      return Operand.Val->getOperand(0);
628    break;
629  case ISD::FABS:
630    if (OpOpcode == ISD::FNEG)  // abs(-X) -> abs(X)
631      return getNode(ISD::FABS, VT, Operand.Val->getOperand(0));
632    break;
633  }
634
635  SDNode *&N = UnaryOps[std::make_pair(Opcode, std::make_pair(Operand, VT))];
636  if (N) return SDOperand(N, 0);
637  N = new SDNode(Opcode, Operand);
638  N->setValueTypes(VT);
639  AllNodes.push_back(N);
640  return SDOperand(N, 0);
641}
642
643SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT,
644                                SDOperand N1, SDOperand N2) {
645#ifndef NDEBUG
646  switch (Opcode) {
647  case ISD::TokenFactor:
648    assert(VT == MVT::Other && N1.getValueType() == MVT::Other &&
649           N2.getValueType() == MVT::Other && "Invalid token factor!");
650    break;
651  case ISD::AND:
652  case ISD::OR:
653  case ISD::XOR:
654  case ISD::UDIV:
655  case ISD::UREM:
656    assert(MVT::isInteger(VT) && "This operator does not apply to FP types!");
657    // fall through
658  case ISD::ADD:
659  case ISD::SUB:
660  case ISD::MUL:
661  case ISD::SDIV:
662  case ISD::SREM:
663    assert(N1.getValueType() == N2.getValueType() &&
664           N1.getValueType() == VT && "Binary operator types must match!");
665    break;
666
667  case ISD::SHL:
668  case ISD::SRA:
669  case ISD::SRL:
670    assert(VT == N1.getValueType() &&
671           "Shift operators return type must be the same as their first arg");
672    assert(MVT::isInteger(VT) && MVT::isInteger(N2.getValueType()) &&
673           VT != MVT::i1 && "Shifts only work on integers");
674    break;
675  default: break;
676  }
677#endif
678
679  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val);
680  ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.Val);
681  if (N1C) {
682    if (N2C) {
683      uint64_t C1 = N1C->getValue(), C2 = N2C->getValue();
684      switch (Opcode) {
685      case ISD::ADD: return getConstant(C1 + C2, VT);
686      case ISD::SUB: return getConstant(C1 - C2, VT);
687      case ISD::MUL: return getConstant(C1 * C2, VT);
688      case ISD::UDIV:
689        if (C2) return getConstant(C1 / C2, VT);
690        break;
691      case ISD::UREM :
692        if (C2) return getConstant(C1 % C2, VT);
693        break;
694      case ISD::SDIV :
695        if (C2) return getConstant(N1C->getSignExtended() /
696                                   N2C->getSignExtended(), VT);
697        break;
698      case ISD::SREM :
699        if (C2) return getConstant(N1C->getSignExtended() %
700                                   N2C->getSignExtended(), VT);
701        break;
702      case ISD::AND  : return getConstant(C1 & C2, VT);
703      case ISD::OR   : return getConstant(C1 | C2, VT);
704      case ISD::XOR  : return getConstant(C1 ^ C2, VT);
705      case ISD::SHL  : return getConstant(C1 << (int)C2, VT);
706      case ISD::SRL  : return getConstant(C1 >> (unsigned)C2, VT);
707      case ISD::SRA  : return getConstant(N1C->getSignExtended() >>(int)C2, VT);
708      default: break;
709      }
710
711    } else {      // Cannonicalize constant to RHS if commutative
712      if (isCommutativeBinOp(Opcode)) {
713        std::swap(N1C, N2C);
714        std::swap(N1, N2);
715      }
716    }
717
718    switch (Opcode) {
719    default: break;
720    case ISD::SHL:    // shl  0, X -> 0
721      if (N1C->isNullValue()) return N1;
722      break;
723    case ISD::SRL:    // srl  0, X -> 0
724      if (N1C->isNullValue()) return N1;
725      break;
726    case ISD::SRA:    // sra -1, X -> -1
727      if (N1C->isAllOnesValue()) return N1;
728      break;
729    }
730  }
731
732  if (N2C) {
733    uint64_t C2 = N2C->getValue();
734
735    switch (Opcode) {
736    case ISD::ADD:
737      if (!C2) return N1;         // add X, 0 -> X
738      break;
739    case ISD::SUB:
740      if (!C2) return N1;         // sub X, 0 -> X
741      break;
742    case ISD::MUL:
743      if (!C2) return N2;         // mul X, 0 -> 0
744      if (N2C->isAllOnesValue()) // mul X, -1 -> 0-X
745        return getNode(ISD::SUB, VT, getConstant(0, VT), N1);
746
747      // FIXME: Move this to the DAG combiner when it exists.
748      if ((C2 & C2-1) == 0) {
749        SDOperand ShAmt = getConstant(ExactLog2(C2), TLI.getShiftAmountTy());
750        return getNode(ISD::SHL, VT, N1, ShAmt);
751      }
752      break;
753
754    case ISD::UDIV:
755      // FIXME: Move this to the DAG combiner when it exists.
756      if ((C2 & C2-1) == 0 && C2) {
757        SDOperand ShAmt = getConstant(ExactLog2(C2), TLI.getShiftAmountTy());
758        return getNode(ISD::SRL, VT, N1, ShAmt);
759      }
760      break;
761
762    case ISD::SHL:
763    case ISD::SRL:
764    case ISD::SRA:
765      // If the shift amount is bigger than the size of the data, then all the
766      // bits are shifted out.  Simplify to loading constant zero.
767      if (C2 >= MVT::getSizeInBits(N1.getValueType())) {
768        return getNode(ISD::UNDEF, N1.getValueType());
769      }
770      if (C2 == 0) return N1;
771      break;
772
773    case ISD::AND:
774      if (!C2) return N2;         // X and 0 -> 0
775      if (N2C->isAllOnesValue())
776        return N1;                // X and -1 -> X
777
778      // FIXME: Should add a corresponding version of this for
779      // ZERO_EXTEND/SIGN_EXTEND by converting them to an ANY_EXTEND node which
780      // we don't have yet.
781
782      // and (sign_extend_inreg x:16:32), 1 -> and x, 1
783      if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
784        // If we are masking out the part of our input that was extended, just
785        // mask the input to the extension directly.
786        unsigned ExtendBits =
787          MVT::getSizeInBits(cast<MVTSDNode>(N1)->getExtraValueType());
788        if ((C2 & (~0ULL << ExtendBits)) == 0)
789          return getNode(ISD::AND, VT, N1.getOperand(0), N2);
790      }
791      if (N1.getOpcode() == ISD::AND)
792        if (ConstantSDNode *OpRHS = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
793          return getNode(ISD::AND, VT, N1.getOperand(0),
794                         getNode(ISD::AND, VT, N1.getOperand(1), N2));
795
796      // If we are anding the result of a setcc, and we know setcc always
797      // returns 0 or 1, simplify the RHS to either be 0 or 1
798      if (N1.getOpcode() == ISD::SETCC &&
799          TLI.getSetCCResultContents() == TargetLowering::ZeroOrOneSetCCResult)
800        if (C2 & 1)
801          return N1;
802        else
803          return getConstant(0, VT);
804
805      if (N1.getOpcode() == ISD::ZEXTLOAD) {
806        // If we are anding the result of a zext load, realize that the top bits
807        // of the loaded value are already zero to simplify C2.
808        unsigned SrcBits =
809          MVT::getSizeInBits(cast<MVTSDNode>(N1)->getExtraValueType());
810        uint64_t C3 = C2 & (~0ULL >> (64-SrcBits));
811        if (C3 != C2)
812          return getNode(ISD::AND, VT, N1, getConstant(C3, VT));
813        else if (C2 == (~0ULL >> (64-SrcBits)))
814          return N1;   // Anding out just what is already masked.
815      }
816      break;
817    case ISD::OR:
818      if (!C2)return N1;          // X or 0 -> X
819      if (N2C->isAllOnesValue())
820	return N2;                // X or -1 -> -1
821      break;
822    case ISD::XOR:
823      if (!C2) return N1;        // X xor 0 -> X
824      if (N2C->isAllOnesValue()) {
825        if (SetCCSDNode *SetCC = dyn_cast<SetCCSDNode>(N1.Val)){
826          // !(X op Y) -> (X !op Y)
827          bool isInteger = MVT::isInteger(SetCC->getOperand(0).getValueType());
828          return getSetCC(ISD::getSetCCInverse(SetCC->getCondition(),isInteger),
829                          SetCC->getValueType(0),
830                          SetCC->getOperand(0), SetCC->getOperand(1));
831        } else if (N1.getOpcode() == ISD::AND || N1.getOpcode() == ISD::OR) {
832          SDNode *Op = N1.Val;
833          // !(X or Y) -> (!X and !Y) iff X or Y are freely invertible
834          // !(X and Y) -> (!X or !Y) iff X or Y are freely invertible
835          SDOperand LHS = Op->getOperand(0), RHS = Op->getOperand(1);
836          if (isInvertibleForFree(RHS) || isInvertibleForFree(LHS)) {
837            LHS = getNode(ISD::XOR, VT, LHS, N2);  // RHS = ~LHS
838            RHS = getNode(ISD::XOR, VT, RHS, N2);  // RHS = ~RHS
839            if (Op->getOpcode() == ISD::AND)
840              return getNode(ISD::OR, VT, LHS, RHS);
841            return getNode(ISD::AND, VT, LHS, RHS);
842          }
843        }
844	// X xor -1 -> not(x)  ?
845      }
846      break;
847    }
848
849    // Reassociate ((X op C1) op C2) if possible.
850    if (N1.getOpcode() == Opcode && isAssociativeBinOp(Opcode))
851      if (ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N1.Val->getOperand(1)))
852        return getNode(Opcode, VT, N1.Val->getOperand(0),
853                       getNode(Opcode, VT, N2, N1.Val->getOperand(1)));
854  }
855
856  ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1.Val);
857  ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2.Val);
858  if (N1CFP)
859    if (N2CFP) {
860      double C1 = N1CFP->getValue(), C2 = N2CFP->getValue();
861      switch (Opcode) {
862      case ISD::ADD: return getConstantFP(C1 + C2, VT);
863      case ISD::SUB: return getConstantFP(C1 - C2, VT);
864      case ISD::MUL: return getConstantFP(C1 * C2, VT);
865      case ISD::SDIV:
866        if (C2) return getConstantFP(C1 / C2, VT);
867        break;
868      case ISD::SREM :
869        if (C2) return getConstantFP(fmod(C1, C2), VT);
870        break;
871      default: break;
872      }
873
874    } else {      // Cannonicalize constant to RHS if commutative
875      if (isCommutativeBinOp(Opcode)) {
876        std::swap(N1CFP, N2CFP);
877        std::swap(N1, N2);
878      }
879    }
880
881  // Finally, fold operations that do not require constants.
882  switch (Opcode) {
883  case ISD::TokenFactor:
884    if (N1.getOpcode() == ISD::EntryToken)
885      return N2;
886    if (N2.getOpcode() == ISD::EntryToken)
887      return N1;
888    break;
889
890  case ISD::AND:
891  case ISD::OR:
892    if (SetCCSDNode *LHS = dyn_cast<SetCCSDNode>(N1.Val))
893      if (SetCCSDNode *RHS = dyn_cast<SetCCSDNode>(N2.Val)) {
894        SDOperand LL = LHS->getOperand(0), RL = RHS->getOperand(0);
895        SDOperand LR = LHS->getOperand(1), RR = RHS->getOperand(1);
896        ISD::CondCode Op2 = RHS->getCondition();
897
898        // (X op1 Y) | (Y op2 X) -> (X op1 Y) | (X swapop2 Y)
899        if (LL == RR && LR == RL) {
900          Op2 = ISD::getSetCCSwappedOperands(Op2);
901          goto MatchedBackwards;
902        }
903
904        if (LL == RL && LR == RR) {
905        MatchedBackwards:
906          ISD::CondCode Result;
907          bool isInteger = MVT::isInteger(LL.getValueType());
908          if (Opcode == ISD::OR)
909            Result = ISD::getSetCCOrOperation(LHS->getCondition(), Op2,
910                                              isInteger);
911          else
912            Result = ISD::getSetCCAndOperation(LHS->getCondition(), Op2,
913                                               isInteger);
914          if (Result != ISD::SETCC_INVALID)
915            return getSetCC(Result, LHS->getValueType(0), LL, LR);
916        }
917      }
918    break;
919  case ISD::XOR:
920    if (N1 == N2) return getConstant(0, VT);  // xor X, Y -> 0
921    break;
922  case ISD::ADD:
923    if (N2.getOpcode() == ISD::FNEG)          // (A+ (-B) -> A-B
924      return getNode(ISD::SUB, VT, N1, N2.getOperand(0));
925    if (N1.getOpcode() == ISD::FNEG)          // ((-A)+B) -> B-A
926      return getNode(ISD::SUB, VT, N2, N1.getOperand(0));
927    if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
928        cast<ConstantSDNode>(N1.getOperand(0))->getValue() == 0)
929      return getNode(ISD::SUB, VT, N2, N1.getOperand(1)); // (0-A)+B -> B-A
930    if (N2.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N2.getOperand(0)) &&
931        cast<ConstantSDNode>(N2.getOperand(0))->getValue() == 0)
932      return getNode(ISD::SUB, VT, N1, N2.getOperand(1)); // A+(0-B) -> A-B
933    break;
934  case ISD::SUB:
935    if (N1.getOpcode() == ISD::ADD) {
936      if (N1.Val->getOperand(0) == N2)
937        return N1.Val->getOperand(1);         // (A+B)-A == B
938      if (N1.Val->getOperand(1) == N2)
939        return N1.Val->getOperand(0);         // (A+B)-B == A
940    }
941    if (N2.getOpcode() == ISD::FNEG)          // (A- (-B) -> A+B
942      return getNode(ISD::ADD, VT, N1, N2.getOperand(0));
943    break;
944  // FIXME: figure out how to safely handle things like
945  // int foo(int x) { return 1 << (x & 255); }
946  // int bar() { return foo(256); }
947#if 0
948  case ISD::SHL:
949  case ISD::SRL:
950  case ISD::SRA:
951    if (N2.getOpcode() == ISD::SIGN_EXTEND_INREG &&
952        cast<MVTSDNode>(N2)->getExtraValueType() != MVT::i1)
953      return getNode(Opcode, VT, N1, N2.getOperand(0));
954    else if (N2.getOpcode() == ISD::AND)
955      if (ConstantSDNode *AndRHS = dyn_cast<ConstantSDNode>(N2.getOperand(1))) {
956        // If the and is only masking out bits that cannot effect the shift,
957        // eliminate the and.
958        unsigned NumBits = MVT::getSizeInBits(VT);
959        if ((AndRHS->getValue() & (NumBits-1)) == NumBits-1)
960          return getNode(Opcode, VT, N1, N2.getOperand(0));
961      }
962    break;
963#endif
964  }
965
966  SDNode *&N = BinaryOps[std::make_pair(Opcode, std::make_pair(N1, N2))];
967  if (N) return SDOperand(N, 0);
968  N = new SDNode(Opcode, N1, N2);
969  N->setValueTypes(VT);
970
971  AllNodes.push_back(N);
972  return SDOperand(N, 0);
973}
974
975SDOperand SelectionDAG::getLoad(MVT::ValueType VT,
976                                SDOperand Chain, SDOperand Ptr) {
977  SDNode *&N = Loads[std::make_pair(Ptr, std::make_pair(Chain, VT))];
978  if (N) return SDOperand(N, 0);
979  N = new SDNode(ISD::LOAD, Chain, Ptr);
980
981  // Loads have a token chain.
982  N->setValueTypes(VT, MVT::Other);
983  AllNodes.push_back(N);
984  return SDOperand(N, 0);
985}
986
987
988SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT,
989                                SDOperand N1, SDOperand N2, SDOperand N3) {
990  // Perform various simplifications.
991  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val);
992  ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.Val);
993  ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.Val);
994  switch (Opcode) {
995  case ISD::SELECT:
996    if (N1C)
997      if (N1C->getValue())
998        return N2;             // select true, X, Y -> X
999      else
1000        return N3;             // select false, X, Y -> Y
1001
1002    if (N2 == N3) return N2;   // select C, X, X -> X
1003
1004    if (VT == MVT::i1) {  // Boolean SELECT
1005      if (N2C) {
1006        if (N2C->getValue())   // select C, 1, X -> C | X
1007          return getNode(ISD::OR, VT, N1, N3);
1008        else                   // select C, 0, X -> ~C & X
1009          return getNode(ISD::AND, VT,
1010                         getNode(ISD::XOR, N1.getValueType(), N1,
1011                                 getConstant(1, N1.getValueType())), N3);
1012      } else if (N3C) {
1013        if (N3C->getValue())   // select C, X, 1 -> ~C | X
1014          return getNode(ISD::OR, VT,
1015                         getNode(ISD::XOR, N1.getValueType(), N1,
1016                                 getConstant(1, N1.getValueType())), N2);
1017        else                   // select C, X, 0 -> C & X
1018          return getNode(ISD::AND, VT, N1, N2);
1019      }
1020
1021      if (N1 == N2)   // X ? X : Y --> X ? 1 : Y --> X | Y
1022        return getNode(ISD::OR, VT, N1, N3);
1023      if (N1 == N3)   // X ? Y : X --> X ? Y : 0 --> X & Y
1024        return getNode(ISD::AND, VT, N1, N2);
1025    }
1026
1027    // If this is a selectcc, check to see if we can simplify the result.
1028    if (SetCCSDNode *SetCC = dyn_cast<SetCCSDNode>(N1)) {
1029      if (ConstantFPSDNode *CFP =
1030          dyn_cast<ConstantFPSDNode>(SetCC->getOperand(1)))
1031        if (CFP->getValue() == 0.0) {   // Allow either -0.0 or 0.0
1032          // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
1033          if ((SetCC->getCondition() == ISD::SETGE ||
1034               SetCC->getCondition() == ISD::SETGT) &&
1035              N2 == SetCC->getOperand(0) && N3.getOpcode() == ISD::FNEG &&
1036              N3.getOperand(0) == N2)
1037            return getNode(ISD::FABS, VT, N2);
1038
1039          // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
1040          if ((SetCC->getCondition() == ISD::SETLT ||
1041               SetCC->getCondition() == ISD::SETLE) &&
1042              N3 == SetCC->getOperand(0) && N2.getOpcode() == ISD::FNEG &&
1043              N2.getOperand(0) == N3)
1044            return getNode(ISD::FABS, VT, N3);
1045        }
1046      // select (setlt X, 0), A, 0 -> and (sra X, size(X)-1, A)
1047      if (ConstantSDNode *CN =
1048          dyn_cast<ConstantSDNode>(SetCC->getOperand(1)))
1049        if (CN->getValue() == 0 && N3C && N3C->getValue() == 0)
1050          if (SetCC->getCondition() == ISD::SETLT) {
1051            MVT::ValueType XType = SetCC->getOperand(0).getValueType();
1052            MVT::ValueType AType = N2.getValueType();
1053            if (XType >= AType) {
1054              SDOperand Shift = getNode(ISD::SRA, XType, SetCC->getOperand(0),
1055                getConstant(MVT::getSizeInBits(XType)-1,
1056                            TLI.getShiftAmountTy()));
1057              if (XType > AType)
1058                Shift = getNode(ISD::TRUNCATE, AType, Shift);
1059              return getNode(ISD::AND, AType, Shift, N2);
1060            }
1061          }
1062    }
1063    break;
1064  case ISD::BRCOND:
1065    if (N2C)
1066      if (N2C->getValue()) // Unconditional branch
1067        return getNode(ISD::BR, MVT::Other, N1, N3);
1068      else
1069        return N1;         // Never-taken branch
1070    break;
1071  // FIXME: figure out how to safely handle things like
1072  // int foo(int x) { return 1 << (x & 255); }
1073  // int bar() { return foo(256); }
1074#if 0
1075  case ISD::SRA_PARTS:
1076  case ISD::SRL_PARTS:
1077  case ISD::SHL_PARTS:
1078    if (N3.getOpcode() == ISD::SIGN_EXTEND_INREG &&
1079        cast<MVTSDNode>(N3)->getExtraValueType() != MVT::i1)
1080      return getNode(Opcode, VT, N1, N2, N3.getOperand(0));
1081    else if (N3.getOpcode() == ISD::AND)
1082      if (ConstantSDNode *AndRHS = dyn_cast<ConstantSDNode>(N3.getOperand(1))) {
1083        // If the and is only masking out bits that cannot effect the shift,
1084        // eliminate the and.
1085        unsigned NumBits = MVT::getSizeInBits(VT)*2;
1086        if ((AndRHS->getValue() & (NumBits-1)) == NumBits-1)
1087          return getNode(Opcode, VT, N1, N2, N3.getOperand(0));
1088      }
1089    break;
1090#endif
1091  }
1092
1093  SDNode *N = new SDNode(Opcode, N1, N2, N3);
1094  switch (Opcode) {
1095  default:
1096    N->setValueTypes(VT);
1097    break;
1098  case ISD::DYNAMIC_STACKALLOC: // DYNAMIC_STACKALLOC produces pointer and chain
1099    N->setValueTypes(VT, MVT::Other);
1100    break;
1101
1102  case ISD::SRA_PARTS:
1103  case ISD::SRL_PARTS:
1104  case ISD::SHL_PARTS: {
1105    std::vector<MVT::ValueType> V(N->getNumOperands()-1, VT);
1106    N->setValueTypes(V);
1107    break;
1108  }
1109  }
1110
1111  // FIXME: memoize NODES
1112  AllNodes.push_back(N);
1113  return SDOperand(N, 0);
1114}
1115
1116SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT,
1117                                std::vector<SDOperand> &Children) {
1118  switch (Children.size()) {
1119  case 0: return getNode(Opcode, VT);
1120  case 1: return getNode(Opcode, VT, Children[0]);
1121  case 2: return getNode(Opcode, VT, Children[0], Children[1]);
1122  case 3: return getNode(Opcode, VT, Children[0], Children[1], Children[2]);
1123  default: break;
1124  }
1125
1126  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Children[1].Val);
1127  switch (Opcode) {
1128  default: break;
1129  case ISD::BRCONDTWOWAY:
1130    if (N1C)
1131      if (N1C->getValue()) // Unconditional branch to true dest.
1132        return getNode(ISD::BR, MVT::Other, Children[0], Children[2]);
1133      else                 // Unconditional branch to false dest.
1134        return getNode(ISD::BR, MVT::Other, Children[0], Children[3]);
1135    break;
1136  }
1137
1138  // FIXME: MEMOIZE!!
1139  SDNode *N = new SDNode(Opcode, Children);
1140  if (Opcode != ISD::ADD_PARTS && Opcode != ISD::SUB_PARTS) {
1141    N->setValueTypes(VT);
1142  } else {
1143    std::vector<MVT::ValueType> V(N->getNumOperands()/2, VT);
1144    N->setValueTypes(V);
1145  }
1146  AllNodes.push_back(N);
1147  return SDOperand(N, 0);
1148}
1149
1150SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT,SDOperand N1,
1151                                MVT::ValueType EVT) {
1152
1153  switch (Opcode) {
1154  default: assert(0 && "Bad opcode for this accessor!");
1155  case ISD::FP_ROUND_INREG:
1156    assert(VT == N1.getValueType() && "Not an inreg round!");
1157    assert(MVT::isFloatingPoint(VT) && MVT::isFloatingPoint(EVT) &&
1158           "Cannot FP_ROUND_INREG integer types");
1159    if (EVT == VT) return N1;  // Not actually rounding
1160    assert(EVT < VT && "Not rounding down!");
1161
1162    if (isa<ConstantFPSDNode>(N1))
1163      return getNode(ISD::FP_EXTEND, VT, getNode(ISD::FP_ROUND, EVT, N1));
1164    break;
1165  case ISD::SIGN_EXTEND_INREG:
1166    assert(VT == N1.getValueType() && "Not an inreg extend!");
1167    assert(MVT::isInteger(VT) && MVT::isInteger(EVT) &&
1168           "Cannot *_EXTEND_INREG FP types");
1169    if (EVT == VT) return N1;  // Not actually extending
1170    assert(EVT < VT && "Not extending!");
1171
1172    // Extending a constant?  Just return the extended constant.
1173    if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val)) {
1174      SDOperand Tmp = getNode(ISD::TRUNCATE, EVT, N1);
1175      return getNode(ISD::SIGN_EXTEND, VT, Tmp);
1176    }
1177
1178    // If we are sign extending an extension, use the original source.
1179    if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG)
1180      if (cast<MVTSDNode>(N1)->getExtraValueType() <= EVT)
1181        return N1;
1182
1183    // If we are sign extending a sextload, return just the load.
1184    if (N1.getOpcode() == ISD::SEXTLOAD && Opcode == ISD::SIGN_EXTEND_INREG)
1185      if (cast<MVTSDNode>(N1)->getExtraValueType() <= EVT)
1186        return N1;
1187
1188    // If we are extending the result of a setcc, and we already know the
1189    // contents of the top bits, eliminate the extension.
1190    if (N1.getOpcode() == ISD::SETCC &&
1191        TLI.getSetCCResultContents() ==
1192                        TargetLowering::ZeroOrNegativeOneSetCCResult)
1193      return N1;
1194
1195    // If we are sign extending the result of an (and X, C) operation, and we
1196    // know the extended bits are zeros already, don't do the extend.
1197    if (N1.getOpcode() == ISD::AND)
1198      if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
1199        uint64_t Mask = N1C->getValue();
1200        unsigned NumBits = MVT::getSizeInBits(EVT);
1201        if ((Mask & (~0ULL << (NumBits-1))) == 0)
1202          return N1;
1203      }
1204    break;
1205  }
1206
1207  EVTStruct NN;
1208  NN.Opcode = Opcode;
1209  NN.VT = VT;
1210  NN.EVT = EVT;
1211  NN.Ops.push_back(N1);
1212
1213  SDNode *&N = MVTSDNodes[NN];
1214  if (N) return SDOperand(N, 0);
1215  N = new MVTSDNode(Opcode, VT, N1, EVT);
1216  AllNodes.push_back(N);
1217  return SDOperand(N, 0);
1218}
1219
1220SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT,SDOperand N1,
1221                                SDOperand N2, MVT::ValueType EVT) {
1222  switch (Opcode) {
1223  default:  assert(0 && "Bad opcode for this accessor!");
1224  case ISD::EXTLOAD:
1225  case ISD::SEXTLOAD:
1226  case ISD::ZEXTLOAD:
1227    // If they are asking for an extending load from/to the same thing, return a
1228    // normal load.
1229    if (VT == EVT)
1230      return getNode(ISD::LOAD, VT, N1, N2);
1231    assert(EVT < VT && "Should only be an extending load, not truncating!");
1232    assert((Opcode == ISD::EXTLOAD || MVT::isInteger(VT)) &&
1233           "Cannot sign/zero extend a FP load!");
1234    assert(MVT::isInteger(VT) == MVT::isInteger(EVT) &&
1235           "Cannot convert from FP to Int or Int -> FP!");
1236    break;
1237  }
1238
1239  EVTStruct NN;
1240  NN.Opcode = Opcode;
1241  NN.VT = VT;
1242  NN.EVT = EVT;
1243  NN.Ops.push_back(N1);
1244  NN.Ops.push_back(N2);
1245
1246  SDNode *&N = MVTSDNodes[NN];
1247  if (N) return SDOperand(N, 0);
1248  N = new MVTSDNode(Opcode, VT, MVT::Other, N1, N2, EVT);
1249  AllNodes.push_back(N);
1250  return SDOperand(N, 0);
1251}
1252
1253SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT,SDOperand N1,
1254                                SDOperand N2, SDOperand N3, MVT::ValueType EVT) {
1255  switch (Opcode) {
1256  default:  assert(0 && "Bad opcode for this accessor!");
1257  case ISD::TRUNCSTORE:
1258#if 0 // FIXME: If the target supports EVT natively, convert to a truncate/store
1259    // If this is a truncating store of a constant, convert to the desired type
1260    // and store it instead.
1261    if (isa<Constant>(N1)) {
1262      SDOperand Op = getNode(ISD::TRUNCATE, EVT, N1);
1263      if (isa<Constant>(Op))
1264        N1 = Op;
1265    }
1266    // Also for ConstantFP?
1267#endif
1268    if (N1.getValueType() == EVT)       // Normal store?
1269      return getNode(ISD::STORE, VT, N1, N2, N3);
1270    assert(N2.getValueType() > EVT && "Not a truncation?");
1271    assert(MVT::isInteger(N2.getValueType()) == MVT::isInteger(EVT) &&
1272           "Can't do FP-INT conversion!");
1273    break;
1274  }
1275
1276  EVTStruct NN;
1277  NN.Opcode = Opcode;
1278  NN.VT = VT;
1279  NN.EVT = EVT;
1280  NN.Ops.push_back(N1);
1281  NN.Ops.push_back(N2);
1282  NN.Ops.push_back(N3);
1283
1284  SDNode *&N = MVTSDNodes[NN];
1285  if (N) return SDOperand(N, 0);
1286  N = new MVTSDNode(Opcode, VT, N1, N2, N3, EVT);
1287  AllNodes.push_back(N);
1288  return SDOperand(N, 0);
1289}
1290
1291
1292/// hasNUsesOfValue - Return true if there are exactly NUSES uses of the
1293/// indicated value.  This method ignores uses of other values defined by this
1294/// operation.
1295bool SDNode::hasNUsesOfValue(unsigned NUses, unsigned Value) {
1296  assert(Value < getNumValues() && "Bad value!");
1297
1298  // If there is only one value, this is easy.
1299  if (getNumValues() == 1)
1300    return use_size() == NUses;
1301  if (Uses.size() < NUses) return false;
1302
1303  SDOperand TheValue(this, Value);
1304
1305  std::set<SDNode*> UsersHandled;
1306
1307  for (std::vector<SDNode*>::iterator UI = Uses.begin(), E = Uses.end();
1308       UI != E; ++UI) {
1309    SDNode *User = *UI;
1310    if (User->getNumOperands() == 1 ||
1311        UsersHandled.insert(User).second)     // First time we've seen this?
1312      for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i)
1313        if (User->getOperand(i) == TheValue) {
1314          if (NUses == 0)
1315            return false;   // too many uses
1316          --NUses;
1317        }
1318  }
1319
1320  // Found exactly the right number of uses?
1321  return NUses == 0;
1322}
1323
1324
1325const char *SDNode::getOperationName() const {
1326  switch (getOpcode()) {
1327  default: return "<<Unknown>>";
1328  case ISD::PCMARKER:      return "PCMarker";
1329  case ISD::EntryToken:    return "EntryToken";
1330  case ISD::TokenFactor:   return "TokenFactor";
1331  case ISD::Constant:      return "Constant";
1332  case ISD::ConstantFP:    return "ConstantFP";
1333  case ISD::GlobalAddress: return "GlobalAddress";
1334  case ISD::FrameIndex:    return "FrameIndex";
1335  case ISD::BasicBlock:    return "BasicBlock";
1336  case ISD::ExternalSymbol: return "ExternalSymbol";
1337  case ISD::ConstantPool:  return "ConstantPoolIndex";
1338  case ISD::CopyToReg:     return "CopyToReg";
1339  case ISD::CopyFromReg:   return "CopyFromReg";
1340  case ISD::ImplicitDef:   return "ImplicitDef";
1341  case ISD::UNDEF:         return "undef";
1342
1343  // Unary operators
1344  case ISD::FABS:   return "fabs";
1345  case ISD::FNEG:   return "fneg";
1346
1347  // Binary operators
1348  case ISD::ADD:    return "add";
1349  case ISD::SUB:    return "sub";
1350  case ISD::MUL:    return "mul";
1351  case ISD::MULHU:  return "mulhu";
1352  case ISD::MULHS:  return "mulhs";
1353  case ISD::SDIV:   return "sdiv";
1354  case ISD::UDIV:   return "udiv";
1355  case ISD::SREM:   return "srem";
1356  case ISD::UREM:   return "urem";
1357  case ISD::AND:    return "and";
1358  case ISD::OR:     return "or";
1359  case ISD::XOR:    return "xor";
1360  case ISD::SHL:    return "shl";
1361  case ISD::SRA:    return "sra";
1362  case ISD::SRL:    return "srl";
1363
1364  case ISD::SELECT: return "select";
1365  case ISD::ADD_PARTS:   return "add_parts";
1366  case ISD::SUB_PARTS:   return "sub_parts";
1367  case ISD::SHL_PARTS:   return "shl_parts";
1368  case ISD::SRA_PARTS:   return "sra_parts";
1369  case ISD::SRL_PARTS:   return "srl_parts";
1370
1371    // Conversion operators.
1372  case ISD::SIGN_EXTEND: return "sign_extend";
1373  case ISD::ZERO_EXTEND: return "zero_extend";
1374  case ISD::SIGN_EXTEND_INREG: return "sign_extend_inreg";
1375  case ISD::TRUNCATE:    return "truncate";
1376  case ISD::FP_ROUND:    return "fp_round";
1377  case ISD::FP_ROUND_INREG: return "fp_round_inreg";
1378  case ISD::FP_EXTEND:   return "fp_extend";
1379
1380  case ISD::SINT_TO_FP:  return "sint_to_fp";
1381  case ISD::UINT_TO_FP:  return "uint_to_fp";
1382  case ISD::FP_TO_SINT:  return "fp_to_sint";
1383  case ISD::FP_TO_UINT:  return "fp_to_uint";
1384
1385    // Control flow instructions
1386  case ISD::BR:      return "br";
1387  case ISD::BRCOND:  return "brcond";
1388  case ISD::BRCONDTWOWAY:  return "brcondtwoway";
1389  case ISD::RET:     return "ret";
1390  case ISD::CALL:    return "call";
1391  case ISD::ADJCALLSTACKDOWN:  return "adjcallstackdown";
1392  case ISD::ADJCALLSTACKUP:    return "adjcallstackup";
1393
1394    // Other operators
1395  case ISD::LOAD:    return "load";
1396  case ISD::STORE:   return "store";
1397  case ISD::EXTLOAD:    return "extload";
1398  case ISD::SEXTLOAD:   return "sextload";
1399  case ISD::ZEXTLOAD:   return "zextload";
1400  case ISD::TRUNCSTORE: return "truncstore";
1401
1402  case ISD::DYNAMIC_STACKALLOC: return "dynamic_stackalloc";
1403  case ISD::EXTRACT_ELEMENT: return "extract_element";
1404  case ISD::BUILD_PAIR: return "build_pair";
1405  case ISD::MEMSET:  return "memset";
1406  case ISD::MEMCPY:  return "memcpy";
1407  case ISD::MEMMOVE: return "memmove";
1408
1409  case ISD::SETCC:
1410    const SetCCSDNode *SetCC = cast<SetCCSDNode>(this);
1411    switch (SetCC->getCondition()) {
1412    default: assert(0 && "Unknown setcc condition!");
1413    case ISD::SETOEQ:  return "setcc:setoeq";
1414    case ISD::SETOGT:  return "setcc:setogt";
1415    case ISD::SETOGE:  return "setcc:setoge";
1416    case ISD::SETOLT:  return "setcc:setolt";
1417    case ISD::SETOLE:  return "setcc:setole";
1418    case ISD::SETONE:  return "setcc:setone";
1419
1420    case ISD::SETO:    return "setcc:seto";
1421    case ISD::SETUO:   return "setcc:setuo";
1422    case ISD::SETUEQ:  return "setcc:setue";
1423    case ISD::SETUGT:  return "setcc:setugt";
1424    case ISD::SETUGE:  return "setcc:setuge";
1425    case ISD::SETULT:  return "setcc:setult";
1426    case ISD::SETULE:  return "setcc:setule";
1427    case ISD::SETUNE:  return "setcc:setune";
1428
1429    case ISD::SETEQ:   return "setcc:seteq";
1430    case ISD::SETGT:   return "setcc:setgt";
1431    case ISD::SETGE:   return "setcc:setge";
1432    case ISD::SETLT:   return "setcc:setlt";
1433    case ISD::SETLE:   return "setcc:setle";
1434    case ISD::SETNE:   return "setcc:setne";
1435    }
1436  }
1437}
1438
1439void SDNode::dump() const {
1440  std::cerr << (void*)this << ": ";
1441
1442  for (unsigned i = 0, e = getNumValues(); i != e; ++i) {
1443    if (i) std::cerr << ",";
1444    if (getValueType(i) == MVT::Other)
1445      std::cerr << "ch";
1446    else
1447      std::cerr << MVT::getValueTypeString(getValueType(i));
1448  }
1449  std::cerr << " = " << getOperationName();
1450
1451  std::cerr << " ";
1452  for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1453    if (i) std::cerr << ", ";
1454    std::cerr << (void*)getOperand(i).Val;
1455    if (unsigned RN = getOperand(i).ResNo)
1456      std::cerr << ":" << RN;
1457  }
1458
1459  if (const ConstantSDNode *CSDN = dyn_cast<ConstantSDNode>(this)) {
1460    std::cerr << "<" << CSDN->getValue() << ">";
1461  } else if (const ConstantFPSDNode *CSDN = dyn_cast<ConstantFPSDNode>(this)) {
1462    std::cerr << "<" << CSDN->getValue() << ">";
1463  } else if (const GlobalAddressSDNode *GADN =
1464             dyn_cast<GlobalAddressSDNode>(this)) {
1465    std::cerr << "<";
1466    WriteAsOperand(std::cerr, GADN->getGlobal()) << ">";
1467  } else if (const FrameIndexSDNode *FIDN =
1468	     dyn_cast<FrameIndexSDNode>(this)) {
1469    std::cerr << "<" << FIDN->getIndex() << ">";
1470  } else if (const ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(this)){
1471    std::cerr << "<" << CP->getIndex() << ">";
1472  } else if (const BasicBlockSDNode *BBDN =
1473	     dyn_cast<BasicBlockSDNode>(this)) {
1474    std::cerr << "<";
1475    const Value *LBB = (const Value*)BBDN->getBasicBlock()->getBasicBlock();
1476    if (LBB)
1477      std::cerr << LBB->getName() << " ";
1478    std::cerr << (const void*)BBDN->getBasicBlock() << ">";
1479  } else if (const RegSDNode *C2V = dyn_cast<RegSDNode>(this)) {
1480    std::cerr << "<reg #" << C2V->getReg() << ">";
1481  } else if (const ExternalSymbolSDNode *ES =
1482             dyn_cast<ExternalSymbolSDNode>(this)) {
1483    std::cerr << "'" << ES->getSymbol() << "'";
1484  } else if (const MVTSDNode *M = dyn_cast<MVTSDNode>(this)) {
1485    std::cerr << " - Ty = " << MVT::getValueTypeString(M->getExtraValueType());
1486  }
1487}
1488
1489static void DumpNodes(SDNode *N, unsigned indent) {
1490  for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1491    if (N->getOperand(i).Val->hasOneUse())
1492      DumpNodes(N->getOperand(i).Val, indent+2);
1493    else
1494      std::cerr << "\n" << std::string(indent+2, ' ')
1495                << (void*)N->getOperand(i).Val << ": <multiple use>";
1496
1497
1498  std::cerr << "\n" << std::string(indent, ' ');
1499  N->dump();
1500}
1501
1502void SelectionDAG::dump() const {
1503  std::cerr << "SelectionDAG has " << AllNodes.size() << " nodes:";
1504  std::vector<SDNode*> Nodes(AllNodes);
1505  std::sort(Nodes.begin(), Nodes.end());
1506
1507  for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
1508    if (!Nodes[i]->hasOneUse() && Nodes[i] != getRoot().Val)
1509      DumpNodes(Nodes[i], 2);
1510  }
1511
1512  DumpNodes(getRoot().Val, 2);
1513
1514  std::cerr << "\n\n";
1515}
1516
1517