SelectionDAG.cpp revision 706aa9685ad74e4825544064bf28aa5b42578812
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 ((Cond == ISD::SETLT || Cond == ISD::SETULT) && C2 == MinVal)
440        return getConstant(0, VT);      // X < MIN --> false
441
442      // Canonicalize setgt X, Min --> setne X, Min
443      if ((Cond == ISD::SETGT || Cond == ISD::SETUGT) && C2 == MinVal)
444        return getSetCC(ISD::SETNE, VT, N1, N2);
445
446      // If we have setult X, 1, turn it into seteq X, 0
447      if ((Cond == ISD::SETLT || Cond == ISD::SETULT) && C2 == MinVal+1)
448        return getSetCC(ISD::SETEQ, VT, N1,
449                        getConstant(MinVal, N1.getValueType()));
450      // If we have setugt X, Max-1, turn it into seteq X, Max
451      else if ((Cond == ISD::SETGT || Cond == ISD::SETUGT) && C2 == MaxVal-1)
452        return getSetCC(ISD::SETEQ, VT, N1,
453                        getConstant(MaxVal, N1.getValueType()));
454
455      // If we have "setcc X, C1", check to see if we can shrink the immediate
456      // by changing cc.
457
458      // SETUGT X, SINTMAX  -> SETLT X, 0
459      if (Cond == ISD::SETUGT && OperandBitSize != 1 &&
460          C2 == (~0ULL >> (65-OperandBitSize)))
461        return getSetCC(ISD::SETLT, VT, N1, getConstant(0, N2.getValueType()));
462
463      // FIXME: Implement the rest of these.
464
465    }
466  } else if (isa<ConstantSDNode>(N1.Val)) {
467      // Ensure that the constant occurs on the RHS.
468    return getSetCC(ISD::getSetCCSwappedOperands(Cond), VT, N2, N1);
469  }
470
471  if (ConstantFPSDNode *N1C = dyn_cast<ConstantFPSDNode>(N1.Val))
472    if (ConstantFPSDNode *N2C = dyn_cast<ConstantFPSDNode>(N2.Val)) {
473      double C1 = N1C->getValue(), C2 = N2C->getValue();
474
475      switch (Cond) {
476      default: break; // FIXME: Implement the rest of these!
477      case ISD::SETEQ:  return getConstant(C1 == C2, VT);
478      case ISD::SETNE:  return getConstant(C1 != C2, VT);
479      case ISD::SETLT:  return getConstant(C1 < C2, VT);
480      case ISD::SETGT:  return getConstant(C1 > C2, VT);
481      case ISD::SETLE:  return getConstant(C1 <= C2, VT);
482      case ISD::SETGE:  return getConstant(C1 >= C2, VT);
483      }
484    } else {
485      // Ensure that the constant occurs on the RHS.
486      Cond = ISD::getSetCCSwappedOperands(Cond);
487      std::swap(N1, N2);
488    }
489
490  if (N1 == N2) {
491    // We can always fold X == Y for integer setcc's.
492    if (MVT::isInteger(N1.getValueType()))
493      return getConstant(ISD::isTrueWhenEqual(Cond), VT);
494    unsigned UOF = ISD::getUnorderedFlavor(Cond);
495    if (UOF == 2)   // FP operators that are undefined on NaNs.
496      return getConstant(ISD::isTrueWhenEqual(Cond), VT);
497    if (UOF == ISD::isTrueWhenEqual(Cond))
498      return getConstant(UOF, VT);
499    // Otherwise, we can't fold it.  However, we can simplify it to SETUO/SETO
500    // if it is not already.
501    Cond = UOF == 0 ? ISD::SETUO : ISD::SETO;
502  }
503
504  if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
505      MVT::isInteger(N1.getValueType())) {
506    if (N1.getOpcode() == ISD::ADD || N1.getOpcode() == ISD::SUB ||
507        N1.getOpcode() == ISD::XOR) {
508      // Simplify (X+Y) == (X+Z) -->  Y == Z
509      if (N1.getOpcode() == N2.getOpcode()) {
510        if (N1.getOperand(0) == N2.getOperand(0))
511          return getSetCC(Cond, VT, N1.getOperand(1), N2.getOperand(1));
512        if (N1.getOperand(1) == N2.getOperand(1))
513          return getSetCC(Cond, VT, N1.getOperand(0), N2.getOperand(0));
514        if (isCommutativeBinOp(N1.getOpcode())) {
515          // If X op Y == Y op X, try other combinations.
516          if (N1.getOperand(0) == N2.getOperand(1))
517            return getSetCC(Cond, VT, N1.getOperand(1), N2.getOperand(0));
518          if (N1.getOperand(1) == N2.getOperand(0))
519            return getSetCC(Cond, VT, N1.getOperand(1), N2.getOperand(1));
520        }
521      }
522
523      // FIXME: move this stuff to the DAG Combiner when it exists!
524
525      // Simplify (X+Z) == X -->  Z == 0
526      if (N1.getOperand(0) == N2)
527        return getSetCC(Cond, VT, N1.getOperand(1),
528                        getConstant(0, N1.getValueType()));
529      if (N1.getOperand(1) == N2) {
530        if (isCommutativeBinOp(N1.getOpcode()))
531          return getSetCC(Cond, VT, N1.getOperand(0),
532                          getConstant(0, N1.getValueType()));
533        else {
534          assert(N1.getOpcode() == ISD::SUB && "Unexpected operation!");
535          // (Z-X) == X  --> Z == X<<1
536          return getSetCC(Cond, VT, N1.getOperand(0),
537                          getNode(ISD::SHL, N2.getValueType(),
538                                  N2, getConstant(1, TLI.getShiftAmountTy())));
539        }
540      }
541    }
542
543    if (N2.getOpcode() == ISD::ADD || N2.getOpcode() == ISD::SUB ||
544        N2.getOpcode() == ISD::XOR) {
545      // Simplify  X == (X+Z) -->  Z == 0
546      if (N2.getOperand(0) == N1)
547        return getSetCC(Cond, VT, N2.getOperand(1),
548                        getConstant(0, N2.getValueType()));
549      else if (N2.getOperand(1) == N1)
550        return getSetCC(Cond, VT, N2.getOperand(0),
551                        getConstant(0, N2.getValueType()));
552    }
553  }
554
555  SetCCSDNode *&N = SetCCs[std::make_pair(std::make_pair(N1, N2),
556                                          std::make_pair(Cond, VT))];
557  if (N) return SDOperand(N, 0);
558  N = new SetCCSDNode(Cond, N1, N2);
559  N->setValueTypes(VT);
560  AllNodes.push_back(N);
561  return SDOperand(N, 0);
562}
563
564
565
566/// getNode - Gets or creates the specified node.
567///
568SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT) {
569  SDNode *N = new SDNode(Opcode, VT);
570  AllNodes.push_back(N);
571  return SDOperand(N, 0);
572}
573
574SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT,
575                                SDOperand Operand) {
576  if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Operand.Val)) {
577    uint64_t Val = C->getValue();
578    switch (Opcode) {
579    default: break;
580    case ISD::SIGN_EXTEND: return getConstant(C->getSignExtended(), VT);
581    case ISD::ZERO_EXTEND: return getConstant(Val, VT);
582    case ISD::TRUNCATE:    return getConstant(Val, VT);
583    case ISD::SINT_TO_FP:  return getConstantFP(C->getSignExtended(), VT);
584    case ISD::UINT_TO_FP:  return getConstantFP(C->getValue(), VT);
585    }
586  }
587
588  if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Operand.Val))
589    switch (Opcode) {
590    case ISD::FNEG:
591      return getConstantFP(-C->getValue(), VT);
592    case ISD::FP_ROUND:
593    case ISD::FP_EXTEND:
594      return getConstantFP(C->getValue(), VT);
595    case ISD::FP_TO_SINT:
596      return getConstant((int64_t)C->getValue(), VT);
597    case ISD::FP_TO_UINT:
598      return getConstant((uint64_t)C->getValue(), VT);
599    }
600
601  unsigned OpOpcode = Operand.Val->getOpcode();
602  switch (Opcode) {
603  case ISD::TokenFactor:
604    return Operand;         // Factor of one node?  No factor.
605  case ISD::SIGN_EXTEND:
606    if (Operand.getValueType() == VT) return Operand;   // noop extension
607    if (OpOpcode == ISD::SIGN_EXTEND || OpOpcode == ISD::ZERO_EXTEND)
608      return getNode(OpOpcode, VT, Operand.Val->getOperand(0));
609    break;
610  case ISD::ZERO_EXTEND:
611    if (Operand.getValueType() == VT) return Operand;   // noop extension
612    if (OpOpcode == ISD::ZERO_EXTEND)   // (zext (zext x)) -> (zext x)
613      return getNode(ISD::ZERO_EXTEND, VT, Operand.Val->getOperand(0));
614    break;
615  case ISD::TRUNCATE:
616    if (Operand.getValueType() == VT) return Operand;   // noop truncate
617    if (OpOpcode == ISD::TRUNCATE)
618      return getNode(ISD::TRUNCATE, VT, Operand.Val->getOperand(0));
619    else if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND) {
620      // If the source is smaller than the dest, we still need an extend.
621      if (Operand.Val->getOperand(0).getValueType() < VT)
622        return getNode(OpOpcode, VT, Operand.Val->getOperand(0));
623      else if (Operand.Val->getOperand(0).getValueType() > VT)
624        return getNode(ISD::TRUNCATE, VT, Operand.Val->getOperand(0));
625      else
626        return Operand.Val->getOperand(0);
627    }
628    break;
629  case ISD::FNEG:
630    if (OpOpcode == ISD::SUB)   // -(X-Y) -> (Y-X)
631      return getNode(ISD::SUB, VT, Operand.Val->getOperand(1),
632                     Operand.Val->getOperand(0));
633    if (OpOpcode == ISD::FNEG)  // --X -> X
634      return Operand.Val->getOperand(0);
635    break;
636  case ISD::FABS:
637    if (OpOpcode == ISD::FNEG)  // abs(-X) -> abs(X)
638      return getNode(ISD::FABS, VT, Operand.Val->getOperand(0));
639    break;
640  }
641
642  SDNode *&N = UnaryOps[std::make_pair(Opcode, std::make_pair(Operand, VT))];
643  if (N) return SDOperand(N, 0);
644  N = new SDNode(Opcode, Operand);
645  N->setValueTypes(VT);
646  AllNodes.push_back(N);
647  return SDOperand(N, 0);
648}
649
650/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero.  We use
651/// this predicate to simplify operations downstream.  V and Mask are known to
652/// be the same type.
653static bool MaskedValueIsZero(const SDOperand &Op, uint64_t Mask,
654                              const TargetLowering &TLI) {
655  unsigned SrcBits;
656  if (Mask == 0) return true;
657
658  // If we know the result of a setcc has the top bits zero, use this info.
659  switch (Op.getOpcode()) {
660  case ISD::UNDEF:
661    return true;
662  case ISD::Constant:
663    return (cast<ConstantSDNode>(Op)->getValue() & Mask) == 0;
664
665  case ISD::SETCC:
666    return ((Mask & 1) == 0) &&
667           TLI.getSetCCResultContents() == TargetLowering::ZeroOrOneSetCCResult;
668
669  case ISD::ZEXTLOAD:
670    SrcBits = MVT::getSizeInBits(cast<MVTSDNode>(Op)->getExtraValueType());
671    return (Mask & ((1ULL << SrcBits)-1)) == 0; // Returning only the zext bits.
672  case ISD::ZERO_EXTEND:
673    SrcBits = MVT::getSizeInBits(Op.getOperand(0).getValueType());
674    return MaskedValueIsZero(Op.getOperand(0),Mask & ((1ULL << SrcBits)-1),TLI);
675
676  case ISD::AND:
677    // (X & C1) & C2 == 0   iff   C1 & C2 == 0.
678    if (ConstantSDNode *AndRHS = dyn_cast<ConstantSDNode>(Op.getOperand(0)))
679      return MaskedValueIsZero(Op.getOperand(0),AndRHS->getValue() & Mask, TLI);
680
681    // FALL THROUGH
682  case ISD::OR:
683  case ISD::XOR:
684    return MaskedValueIsZero(Op.getOperand(0), Mask, TLI) &&
685           MaskedValueIsZero(Op.getOperand(1), Mask, TLI);
686  case ISD::SELECT:
687    return MaskedValueIsZero(Op.getOperand(1), Mask, TLI) &&
688           MaskedValueIsZero(Op.getOperand(2), Mask, TLI);
689
690  // TODO: (shl X, C1) & C2 == 0   iff  (-1 << C1) & C2 == 0
691  // TODO: (ushr X, C1) & C2 == 0   iff  (-1 >> C1) & C2 == 0
692  default: break;
693  }
694
695  return false;
696}
697
698
699
700SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT,
701                                SDOperand N1, SDOperand N2) {
702#ifndef NDEBUG
703  switch (Opcode) {
704  case ISD::TokenFactor:
705    assert(VT == MVT::Other && N1.getValueType() == MVT::Other &&
706           N2.getValueType() == MVT::Other && "Invalid token factor!");
707    break;
708  case ISD::AND:
709  case ISD::OR:
710  case ISD::XOR:
711  case ISD::UDIV:
712  case ISD::UREM:
713    assert(MVT::isInteger(VT) && "This operator does not apply to FP types!");
714    // fall through
715  case ISD::ADD:
716  case ISD::SUB:
717  case ISD::MUL:
718  case ISD::SDIV:
719  case ISD::SREM:
720    assert(N1.getValueType() == N2.getValueType() &&
721           N1.getValueType() == VT && "Binary operator types must match!");
722    break;
723
724  case ISD::SHL:
725  case ISD::SRA:
726  case ISD::SRL:
727    assert(VT == N1.getValueType() &&
728           "Shift operators return type must be the same as their first arg");
729    assert(MVT::isInteger(VT) && MVT::isInteger(N2.getValueType()) &&
730           VT != MVT::i1 && "Shifts only work on integers");
731    break;
732  default: break;
733  }
734#endif
735
736  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val);
737  ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.Val);
738  if (N1C) {
739    if (N2C) {
740      uint64_t C1 = N1C->getValue(), C2 = N2C->getValue();
741      switch (Opcode) {
742      case ISD::ADD: return getConstant(C1 + C2, VT);
743      case ISD::SUB: return getConstant(C1 - C2, VT);
744      case ISD::MUL: return getConstant(C1 * C2, VT);
745      case ISD::UDIV:
746        if (C2) return getConstant(C1 / C2, VT);
747        break;
748      case ISD::UREM :
749        if (C2) return getConstant(C1 % C2, VT);
750        break;
751      case ISD::SDIV :
752        if (C2) return getConstant(N1C->getSignExtended() /
753                                   N2C->getSignExtended(), VT);
754        break;
755      case ISD::SREM :
756        if (C2) return getConstant(N1C->getSignExtended() %
757                                   N2C->getSignExtended(), VT);
758        break;
759      case ISD::AND  : return getConstant(C1 & C2, VT);
760      case ISD::OR   : return getConstant(C1 | C2, VT);
761      case ISD::XOR  : return getConstant(C1 ^ C2, VT);
762      case ISD::SHL  : return getConstant(C1 << (int)C2, VT);
763      case ISD::SRL  : return getConstant(C1 >> (unsigned)C2, VT);
764      case ISD::SRA  : return getConstant(N1C->getSignExtended() >>(int)C2, VT);
765      default: break;
766      }
767
768    } else {      // Cannonicalize constant to RHS if commutative
769      if (isCommutativeBinOp(Opcode)) {
770        std::swap(N1C, N2C);
771        std::swap(N1, N2);
772      }
773    }
774
775    switch (Opcode) {
776    default: break;
777    case ISD::SHL:    // shl  0, X -> 0
778      if (N1C->isNullValue()) return N1;
779      break;
780    case ISD::SRL:    // srl  0, X -> 0
781      if (N1C->isNullValue()) return N1;
782      break;
783    case ISD::SRA:    // sra -1, X -> -1
784      if (N1C->isAllOnesValue()) return N1;
785      break;
786    }
787  }
788
789  if (N2C) {
790    uint64_t C2 = N2C->getValue();
791
792    switch (Opcode) {
793    case ISD::ADD:
794      if (!C2) return N1;         // add X, 0 -> X
795      break;
796    case ISD::SUB:
797      if (!C2) return N1;         // sub X, 0 -> X
798      break;
799    case ISD::MUL:
800      if (!C2) return N2;         // mul X, 0 -> 0
801      if (N2C->isAllOnesValue()) // mul X, -1 -> 0-X
802        return getNode(ISD::SUB, VT, getConstant(0, VT), N1);
803
804      // FIXME: Move this to the DAG combiner when it exists.
805      if ((C2 & C2-1) == 0) {
806        SDOperand ShAmt = getConstant(ExactLog2(C2), TLI.getShiftAmountTy());
807        return getNode(ISD::SHL, VT, N1, ShAmt);
808      }
809      break;
810
811    case ISD::UDIV:
812      // FIXME: Move this to the DAG combiner when it exists.
813      if ((C2 & C2-1) == 0 && C2) {
814        SDOperand ShAmt = getConstant(ExactLog2(C2), TLI.getShiftAmountTy());
815        return getNode(ISD::SRL, VT, N1, ShAmt);
816      }
817      break;
818
819    case ISD::SHL:
820    case ISD::SRL:
821    case ISD::SRA:
822      // If the shift amount is bigger than the size of the data, then all the
823      // bits are shifted out.  Simplify to undef.
824      if (C2 >= MVT::getSizeInBits(N1.getValueType())) {
825        return getNode(ISD::UNDEF, N1.getValueType());
826      }
827      if (C2 == 0) return N1;
828      break;
829
830    case ISD::AND:
831      if (!C2) return N2;         // X and 0 -> 0
832      if (N2C->isAllOnesValue())
833        return N1;                // X and -1 -> X
834
835      if (MaskedValueIsZero(N1, C2, TLI))  // X and 0 -> 0
836        return getConstant(0, VT);
837
838      if (MaskedValueIsZero(N1, ~C2, TLI))
839        return N1;                // if (X & ~C2) -> 0, the and is redundant
840
841      // FIXME: Should add a corresponding version of this for
842      // ZERO_EXTEND/SIGN_EXTEND by converting them to an ANY_EXTEND node which
843      // we don't have yet.
844
845      // and (sign_extend_inreg x:16:32), 1 -> and x, 1
846      if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
847        // If we are masking out the part of our input that was extended, just
848        // mask the input to the extension directly.
849        unsigned ExtendBits =
850          MVT::getSizeInBits(cast<MVTSDNode>(N1)->getExtraValueType());
851        if ((C2 & (~0ULL << ExtendBits)) == 0)
852          return getNode(ISD::AND, VT, N1.getOperand(0), N2);
853      }
854      break;
855    case ISD::OR:
856      if (!C2)return N1;          // X or 0 -> X
857      if (N2C->isAllOnesValue())
858	return N2;                // X or -1 -> -1
859      break;
860    case ISD::XOR:
861      if (!C2) return N1;        // X xor 0 -> X
862      if (N2C->isAllOnesValue()) {
863        if (SetCCSDNode *SetCC = dyn_cast<SetCCSDNode>(N1.Val)){
864          // !(X op Y) -> (X !op Y)
865          bool isInteger = MVT::isInteger(SetCC->getOperand(0).getValueType());
866          return getSetCC(ISD::getSetCCInverse(SetCC->getCondition(),isInteger),
867                          SetCC->getValueType(0),
868                          SetCC->getOperand(0), SetCC->getOperand(1));
869        } else if (N1.getOpcode() == ISD::AND || N1.getOpcode() == ISD::OR) {
870          SDNode *Op = N1.Val;
871          // !(X or Y) -> (!X and !Y) iff X or Y are freely invertible
872          // !(X and Y) -> (!X or !Y) iff X or Y are freely invertible
873          SDOperand LHS = Op->getOperand(0), RHS = Op->getOperand(1);
874          if (isInvertibleForFree(RHS) || isInvertibleForFree(LHS)) {
875            LHS = getNode(ISD::XOR, VT, LHS, N2);  // RHS = ~LHS
876            RHS = getNode(ISD::XOR, VT, RHS, N2);  // RHS = ~RHS
877            if (Op->getOpcode() == ISD::AND)
878              return getNode(ISD::OR, VT, LHS, RHS);
879            return getNode(ISD::AND, VT, LHS, RHS);
880          }
881        }
882	// X xor -1 -> not(x)  ?
883      }
884      break;
885    }
886
887    // Reassociate ((X op C1) op C2) if possible.
888    if (N1.getOpcode() == Opcode && isAssociativeBinOp(Opcode))
889      if (ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N1.Val->getOperand(1)))
890        return getNode(Opcode, VT, N1.Val->getOperand(0),
891                       getNode(Opcode, VT, N2, N1.Val->getOperand(1)));
892  }
893
894  ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1.Val);
895  ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2.Val);
896  if (N1CFP)
897    if (N2CFP) {
898      double C1 = N1CFP->getValue(), C2 = N2CFP->getValue();
899      switch (Opcode) {
900      case ISD::ADD: return getConstantFP(C1 + C2, VT);
901      case ISD::SUB: return getConstantFP(C1 - C2, VT);
902      case ISD::MUL: return getConstantFP(C1 * C2, VT);
903      case ISD::SDIV:
904        if (C2) return getConstantFP(C1 / C2, VT);
905        break;
906      case ISD::SREM :
907        if (C2) return getConstantFP(fmod(C1, C2), VT);
908        break;
909      default: break;
910      }
911
912    } else {      // Cannonicalize constant to RHS if commutative
913      if (isCommutativeBinOp(Opcode)) {
914        std::swap(N1CFP, N2CFP);
915        std::swap(N1, N2);
916      }
917    }
918
919  // Finally, fold operations that do not require constants.
920  switch (Opcode) {
921  case ISD::TokenFactor:
922    if (N1.getOpcode() == ISD::EntryToken)
923      return N2;
924    if (N2.getOpcode() == ISD::EntryToken)
925      return N1;
926    break;
927
928  case ISD::AND:
929  case ISD::OR:
930    if (SetCCSDNode *LHS = dyn_cast<SetCCSDNode>(N1.Val))
931      if (SetCCSDNode *RHS = dyn_cast<SetCCSDNode>(N2.Val)) {
932        SDOperand LL = LHS->getOperand(0), RL = RHS->getOperand(0);
933        SDOperand LR = LHS->getOperand(1), RR = RHS->getOperand(1);
934        ISD::CondCode Op2 = RHS->getCondition();
935
936        // (X != 0) | (Y != 0) -> (X|Y != 0)
937        // (X == 0) & (Y == 0) -> (X|Y == 0)
938        if (LR == RR && isa<ConstantSDNode>(LR) &&
939            cast<ConstantSDNode>(LR)->getValue() == 0 &&
940            Op2 == LHS->getCondition() && MVT::isInteger(LL.getValueType())) {
941          if ((Op2 == ISD::SETEQ && Opcode == ISD::AND) ||
942              (Op2 == ISD::SETNE && Opcode == ISD::OR))
943            return getSetCC(Op2, VT,
944                            getNode(ISD::OR, LR.getValueType(), LL, RL), LR);
945        }
946
947        // (X op1 Y) | (Y op2 X) -> (X op1 Y) | (X swapop2 Y)
948        if (LL == RR && LR == RL) {
949          Op2 = ISD::getSetCCSwappedOperands(Op2);
950          goto MatchedBackwards;
951        }
952
953        if (LL == RL && LR == RR) {
954        MatchedBackwards:
955          ISD::CondCode Result;
956          bool isInteger = MVT::isInteger(LL.getValueType());
957          if (Opcode == ISD::OR)
958            Result = ISD::getSetCCOrOperation(LHS->getCondition(), Op2,
959                                              isInteger);
960          else
961            Result = ISD::getSetCCAndOperation(LHS->getCondition(), Op2,
962                                               isInteger);
963          if (Result != ISD::SETCC_INVALID)
964            return getSetCC(Result, LHS->getValueType(0), LL, LR);
965        }
966      }
967    break;
968  case ISD::XOR:
969    if (N1 == N2) return getConstant(0, VT);  // xor X, Y -> 0
970    break;
971  case ISD::ADD:
972    if (N2.getOpcode() == ISD::FNEG)          // (A+ (-B) -> A-B
973      return getNode(ISD::SUB, VT, N1, N2.getOperand(0));
974    if (N1.getOpcode() == ISD::FNEG)          // ((-A)+B) -> B-A
975      return getNode(ISD::SUB, VT, N2, N1.getOperand(0));
976    if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
977        cast<ConstantSDNode>(N1.getOperand(0))->getValue() == 0)
978      return getNode(ISD::SUB, VT, N2, N1.getOperand(1)); // (0-A)+B -> B-A
979    if (N2.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N2.getOperand(0)) &&
980        cast<ConstantSDNode>(N2.getOperand(0))->getValue() == 0)
981      return getNode(ISD::SUB, VT, N1, N2.getOperand(1)); // A+(0-B) -> A-B
982    break;
983  case ISD::SUB:
984    if (N1.getOpcode() == ISD::ADD) {
985      if (N1.Val->getOperand(0) == N2)
986        return N1.Val->getOperand(1);         // (A+B)-A == B
987      if (N1.Val->getOperand(1) == N2)
988        return N1.Val->getOperand(0);         // (A+B)-B == A
989    }
990    if (N2.getOpcode() == ISD::FNEG)          // (A- (-B) -> A+B
991      return getNode(ISD::ADD, VT, N1, N2.getOperand(0));
992    break;
993  // FIXME: figure out how to safely handle things like
994  // int foo(int x) { return 1 << (x & 255); }
995  // int bar() { return foo(256); }
996#if 0
997  case ISD::SHL:
998  case ISD::SRL:
999  case ISD::SRA:
1000    if (N2.getOpcode() == ISD::SIGN_EXTEND_INREG &&
1001        cast<MVTSDNode>(N2)->getExtraValueType() != MVT::i1)
1002      return getNode(Opcode, VT, N1, N2.getOperand(0));
1003    else if (N2.getOpcode() == ISD::AND)
1004      if (ConstantSDNode *AndRHS = dyn_cast<ConstantSDNode>(N2.getOperand(1))) {
1005        // If the and is only masking out bits that cannot effect the shift,
1006        // eliminate the and.
1007        unsigned NumBits = MVT::getSizeInBits(VT);
1008        if ((AndRHS->getValue() & (NumBits-1)) == NumBits-1)
1009          return getNode(Opcode, VT, N1, N2.getOperand(0));
1010      }
1011    break;
1012#endif
1013  }
1014
1015  SDNode *&N = BinaryOps[std::make_pair(Opcode, std::make_pair(N1, N2))];
1016  if (N) return SDOperand(N, 0);
1017  N = new SDNode(Opcode, N1, N2);
1018  N->setValueTypes(VT);
1019
1020  AllNodes.push_back(N);
1021  return SDOperand(N, 0);
1022}
1023
1024SDOperand SelectionDAG::getLoad(MVT::ValueType VT,
1025                                SDOperand Chain, SDOperand Ptr) {
1026  SDNode *&N = Loads[std::make_pair(Ptr, std::make_pair(Chain, VT))];
1027  if (N) return SDOperand(N, 0);
1028  N = new SDNode(ISD::LOAD, Chain, Ptr);
1029
1030  // Loads have a token chain.
1031  N->setValueTypes(VT, MVT::Other);
1032  AllNodes.push_back(N);
1033  return SDOperand(N, 0);
1034}
1035
1036
1037SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT,
1038                                SDOperand N1, SDOperand N2, SDOperand N3) {
1039  // Perform various simplifications.
1040  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val);
1041  ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.Val);
1042  ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.Val);
1043  switch (Opcode) {
1044  case ISD::SELECT:
1045    if (N1C)
1046      if (N1C->getValue())
1047        return N2;             // select true, X, Y -> X
1048      else
1049        return N3;             // select false, X, Y -> Y
1050
1051    if (N2 == N3) return N2;   // select C, X, X -> X
1052
1053    if (VT == MVT::i1) {  // Boolean SELECT
1054      if (N2C) {
1055        if (N2C->getValue())   // select C, 1, X -> C | X
1056          return getNode(ISD::OR, VT, N1, N3);
1057        else                   // select C, 0, X -> ~C & X
1058          return getNode(ISD::AND, VT,
1059                         getNode(ISD::XOR, N1.getValueType(), N1,
1060                                 getConstant(1, N1.getValueType())), N3);
1061      } else if (N3C) {
1062        if (N3C->getValue())   // select C, X, 1 -> ~C | X
1063          return getNode(ISD::OR, VT,
1064                         getNode(ISD::XOR, N1.getValueType(), N1,
1065                                 getConstant(1, N1.getValueType())), N2);
1066        else                   // select C, X, 0 -> C & X
1067          return getNode(ISD::AND, VT, N1, N2);
1068      }
1069
1070      if (N1 == N2)   // X ? X : Y --> X ? 1 : Y --> X | Y
1071        return getNode(ISD::OR, VT, N1, N3);
1072      if (N1 == N3)   // X ? Y : X --> X ? Y : 0 --> X & Y
1073        return getNode(ISD::AND, VT, N1, N2);
1074    }
1075
1076    // If this is a selectcc, check to see if we can simplify the result.
1077    if (SetCCSDNode *SetCC = dyn_cast<SetCCSDNode>(N1)) {
1078      if (ConstantFPSDNode *CFP =
1079          dyn_cast<ConstantFPSDNode>(SetCC->getOperand(1)))
1080        if (CFP->getValue() == 0.0) {   // Allow either -0.0 or 0.0
1081          // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
1082          if ((SetCC->getCondition() == ISD::SETGE ||
1083               SetCC->getCondition() == ISD::SETGT) &&
1084              N2 == SetCC->getOperand(0) && N3.getOpcode() == ISD::FNEG &&
1085              N3.getOperand(0) == N2)
1086            return getNode(ISD::FABS, VT, N2);
1087
1088          // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
1089          if ((SetCC->getCondition() == ISD::SETLT ||
1090               SetCC->getCondition() == ISD::SETLE) &&
1091              N3 == SetCC->getOperand(0) && N2.getOpcode() == ISD::FNEG &&
1092              N2.getOperand(0) == N3)
1093            return getNode(ISD::FABS, VT, N3);
1094        }
1095      // select (setlt X, 0), A, 0 -> and (sra X, size(X)-1, A)
1096      if (ConstantSDNode *CN =
1097          dyn_cast<ConstantSDNode>(SetCC->getOperand(1)))
1098        if (CN->getValue() == 0 && N3C && N3C->getValue() == 0)
1099          if (SetCC->getCondition() == ISD::SETLT) {
1100            MVT::ValueType XType = SetCC->getOperand(0).getValueType();
1101            MVT::ValueType AType = N2.getValueType();
1102            if (XType >= AType) {
1103              SDOperand Shift = getNode(ISD::SRA, XType, SetCC->getOperand(0),
1104                getConstant(MVT::getSizeInBits(XType)-1,
1105                            TLI.getShiftAmountTy()));
1106              if (XType > AType)
1107                Shift = getNode(ISD::TRUNCATE, AType, Shift);
1108              return getNode(ISD::AND, AType, Shift, N2);
1109            }
1110          }
1111    }
1112    break;
1113  case ISD::BRCOND:
1114    if (N2C)
1115      if (N2C->getValue()) // Unconditional branch
1116        return getNode(ISD::BR, MVT::Other, N1, N3);
1117      else
1118        return N1;         // Never-taken branch
1119    break;
1120  // FIXME: figure out how to safely handle things like
1121  // int foo(int x) { return 1 << (x & 255); }
1122  // int bar() { return foo(256); }
1123#if 0
1124  case ISD::SRA_PARTS:
1125  case ISD::SRL_PARTS:
1126  case ISD::SHL_PARTS:
1127    if (N3.getOpcode() == ISD::SIGN_EXTEND_INREG &&
1128        cast<MVTSDNode>(N3)->getExtraValueType() != MVT::i1)
1129      return getNode(Opcode, VT, N1, N2, N3.getOperand(0));
1130    else if (N3.getOpcode() == ISD::AND)
1131      if (ConstantSDNode *AndRHS = dyn_cast<ConstantSDNode>(N3.getOperand(1))) {
1132        // If the and is only masking out bits that cannot effect the shift,
1133        // eliminate the and.
1134        unsigned NumBits = MVT::getSizeInBits(VT)*2;
1135        if ((AndRHS->getValue() & (NumBits-1)) == NumBits-1)
1136          return getNode(Opcode, VT, N1, N2, N3.getOperand(0));
1137      }
1138    break;
1139#endif
1140  }
1141
1142  SDNode *N = new SDNode(Opcode, N1, N2, N3);
1143  switch (Opcode) {
1144  default:
1145    N->setValueTypes(VT);
1146    break;
1147  case ISD::DYNAMIC_STACKALLOC: // DYNAMIC_STACKALLOC produces pointer and chain
1148    N->setValueTypes(VT, MVT::Other);
1149    break;
1150
1151  case ISD::SRA_PARTS:
1152  case ISD::SRL_PARTS:
1153  case ISD::SHL_PARTS: {
1154    std::vector<MVT::ValueType> V(N->getNumOperands()-1, VT);
1155    N->setValueTypes(V);
1156    break;
1157  }
1158  }
1159
1160  // FIXME: memoize NODES
1161  AllNodes.push_back(N);
1162  return SDOperand(N, 0);
1163}
1164
1165SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT,
1166                                std::vector<SDOperand> &Children) {
1167  switch (Children.size()) {
1168  case 0: return getNode(Opcode, VT);
1169  case 1: return getNode(Opcode, VT, Children[0]);
1170  case 2: return getNode(Opcode, VT, Children[0], Children[1]);
1171  case 3: return getNode(Opcode, VT, Children[0], Children[1], Children[2]);
1172  default: break;
1173  }
1174
1175  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Children[1].Val);
1176  switch (Opcode) {
1177  default: break;
1178  case ISD::BRCONDTWOWAY:
1179    if (N1C)
1180      if (N1C->getValue()) // Unconditional branch to true dest.
1181        return getNode(ISD::BR, MVT::Other, Children[0], Children[2]);
1182      else                 // Unconditional branch to false dest.
1183        return getNode(ISD::BR, MVT::Other, Children[0], Children[3]);
1184    break;
1185  }
1186
1187  // FIXME: MEMOIZE!!
1188  SDNode *N = new SDNode(Opcode, Children);
1189  if (Opcode != ISD::ADD_PARTS && Opcode != ISD::SUB_PARTS) {
1190    N->setValueTypes(VT);
1191  } else {
1192    std::vector<MVT::ValueType> V(N->getNumOperands()/2, VT);
1193    N->setValueTypes(V);
1194  }
1195  AllNodes.push_back(N);
1196  return SDOperand(N, 0);
1197}
1198
1199SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT,SDOperand N1,
1200                                MVT::ValueType EVT) {
1201
1202  switch (Opcode) {
1203  default: assert(0 && "Bad opcode for this accessor!");
1204  case ISD::FP_ROUND_INREG:
1205    assert(VT == N1.getValueType() && "Not an inreg round!");
1206    assert(MVT::isFloatingPoint(VT) && MVT::isFloatingPoint(EVT) &&
1207           "Cannot FP_ROUND_INREG integer types");
1208    if (EVT == VT) return N1;  // Not actually rounding
1209    assert(EVT < VT && "Not rounding down!");
1210
1211    if (isa<ConstantFPSDNode>(N1))
1212      return getNode(ISD::FP_EXTEND, VT, getNode(ISD::FP_ROUND, EVT, N1));
1213    break;
1214  case ISD::SIGN_EXTEND_INREG:
1215    assert(VT == N1.getValueType() && "Not an inreg extend!");
1216    assert(MVT::isInteger(VT) && MVT::isInteger(EVT) &&
1217           "Cannot *_EXTEND_INREG FP types");
1218    if (EVT == VT) return N1;  // Not actually extending
1219    assert(EVT < VT && "Not extending!");
1220
1221    // Extending a constant?  Just return the extended constant.
1222    if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val)) {
1223      SDOperand Tmp = getNode(ISD::TRUNCATE, EVT, N1);
1224      return getNode(ISD::SIGN_EXTEND, VT, Tmp);
1225    }
1226
1227    // If we are sign extending an extension, use the original source.
1228    if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG)
1229      if (cast<MVTSDNode>(N1)->getExtraValueType() <= EVT)
1230        return N1;
1231
1232    // If we are sign extending a sextload, return just the load.
1233    if (N1.getOpcode() == ISD::SEXTLOAD && Opcode == ISD::SIGN_EXTEND_INREG)
1234      if (cast<MVTSDNode>(N1)->getExtraValueType() <= EVT)
1235        return N1;
1236
1237    // If we are extending the result of a setcc, and we already know the
1238    // contents of the top bits, eliminate the extension.
1239    if (N1.getOpcode() == ISD::SETCC &&
1240        TLI.getSetCCResultContents() ==
1241                        TargetLowering::ZeroOrNegativeOneSetCCResult)
1242      return N1;
1243
1244    // If we are sign extending the result of an (and X, C) operation, and we
1245    // know the extended bits are zeros already, don't do the extend.
1246    if (N1.getOpcode() == ISD::AND)
1247      if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
1248        uint64_t Mask = N1C->getValue();
1249        unsigned NumBits = MVT::getSizeInBits(EVT);
1250        if ((Mask & (~0ULL << (NumBits-1))) == 0)
1251          return N1;
1252      }
1253    break;
1254  }
1255
1256  EVTStruct NN;
1257  NN.Opcode = Opcode;
1258  NN.VT = VT;
1259  NN.EVT = EVT;
1260  NN.Ops.push_back(N1);
1261
1262  SDNode *&N = MVTSDNodes[NN];
1263  if (N) return SDOperand(N, 0);
1264  N = new MVTSDNode(Opcode, VT, N1, EVT);
1265  AllNodes.push_back(N);
1266  return SDOperand(N, 0);
1267}
1268
1269SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT,SDOperand N1,
1270                                SDOperand N2, MVT::ValueType EVT) {
1271  switch (Opcode) {
1272  default:  assert(0 && "Bad opcode for this accessor!");
1273  case ISD::EXTLOAD:
1274  case ISD::SEXTLOAD:
1275  case ISD::ZEXTLOAD:
1276    // If they are asking for an extending load from/to the same thing, return a
1277    // normal load.
1278    if (VT == EVT)
1279      return getNode(ISD::LOAD, VT, N1, N2);
1280    assert(EVT < VT && "Should only be an extending load, not truncating!");
1281    assert((Opcode == ISD::EXTLOAD || MVT::isInteger(VT)) &&
1282           "Cannot sign/zero extend a FP load!");
1283    assert(MVT::isInteger(VT) == MVT::isInteger(EVT) &&
1284           "Cannot convert from FP to Int or Int -> FP!");
1285    break;
1286  }
1287
1288  EVTStruct NN;
1289  NN.Opcode = Opcode;
1290  NN.VT = VT;
1291  NN.EVT = EVT;
1292  NN.Ops.push_back(N1);
1293  NN.Ops.push_back(N2);
1294
1295  SDNode *&N = MVTSDNodes[NN];
1296  if (N) return SDOperand(N, 0);
1297  N = new MVTSDNode(Opcode, VT, MVT::Other, N1, N2, EVT);
1298  AllNodes.push_back(N);
1299  return SDOperand(N, 0);
1300}
1301
1302SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT,SDOperand N1,
1303                                SDOperand N2, SDOperand N3, MVT::ValueType EVT) {
1304  switch (Opcode) {
1305  default:  assert(0 && "Bad opcode for this accessor!");
1306  case ISD::TRUNCSTORE:
1307#if 0 // FIXME: If the target supports EVT natively, convert to a truncate/store
1308    // If this is a truncating store of a constant, convert to the desired type
1309    // and store it instead.
1310    if (isa<Constant>(N1)) {
1311      SDOperand Op = getNode(ISD::TRUNCATE, EVT, N1);
1312      if (isa<Constant>(Op))
1313        N1 = Op;
1314    }
1315    // Also for ConstantFP?
1316#endif
1317    if (N1.getValueType() == EVT)       // Normal store?
1318      return getNode(ISD::STORE, VT, N1, N2, N3);
1319    assert(N2.getValueType() > EVT && "Not a truncation?");
1320    assert(MVT::isInteger(N2.getValueType()) == MVT::isInteger(EVT) &&
1321           "Can't do FP-INT conversion!");
1322    break;
1323  }
1324
1325  EVTStruct NN;
1326  NN.Opcode = Opcode;
1327  NN.VT = VT;
1328  NN.EVT = EVT;
1329  NN.Ops.push_back(N1);
1330  NN.Ops.push_back(N2);
1331  NN.Ops.push_back(N3);
1332
1333  SDNode *&N = MVTSDNodes[NN];
1334  if (N) return SDOperand(N, 0);
1335  N = new MVTSDNode(Opcode, VT, N1, N2, N3, EVT);
1336  AllNodes.push_back(N);
1337  return SDOperand(N, 0);
1338}
1339
1340
1341/// hasNUsesOfValue - Return true if there are exactly NUSES uses of the
1342/// indicated value.  This method ignores uses of other values defined by this
1343/// operation.
1344bool SDNode::hasNUsesOfValue(unsigned NUses, unsigned Value) {
1345  assert(Value < getNumValues() && "Bad value!");
1346
1347  // If there is only one value, this is easy.
1348  if (getNumValues() == 1)
1349    return use_size() == NUses;
1350  if (Uses.size() < NUses) return false;
1351
1352  SDOperand TheValue(this, Value);
1353
1354  std::set<SDNode*> UsersHandled;
1355
1356  for (std::vector<SDNode*>::iterator UI = Uses.begin(), E = Uses.end();
1357       UI != E; ++UI) {
1358    SDNode *User = *UI;
1359    if (User->getNumOperands() == 1 ||
1360        UsersHandled.insert(User).second)     // First time we've seen this?
1361      for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i)
1362        if (User->getOperand(i) == TheValue) {
1363          if (NUses == 0)
1364            return false;   // too many uses
1365          --NUses;
1366        }
1367  }
1368
1369  // Found exactly the right number of uses?
1370  return NUses == 0;
1371}
1372
1373
1374const char *SDNode::getOperationName() const {
1375  switch (getOpcode()) {
1376  default: return "<<Unknown>>";
1377  case ISD::PCMARKER:      return "PCMarker";
1378  case ISD::EntryToken:    return "EntryToken";
1379  case ISD::TokenFactor:   return "TokenFactor";
1380  case ISD::Constant:      return "Constant";
1381  case ISD::ConstantFP:    return "ConstantFP";
1382  case ISD::GlobalAddress: return "GlobalAddress";
1383  case ISD::FrameIndex:    return "FrameIndex";
1384  case ISD::BasicBlock:    return "BasicBlock";
1385  case ISD::ExternalSymbol: return "ExternalSymbol";
1386  case ISD::ConstantPool:  return "ConstantPoolIndex";
1387  case ISD::CopyToReg:     return "CopyToReg";
1388  case ISD::CopyFromReg:   return "CopyFromReg";
1389  case ISD::ImplicitDef:   return "ImplicitDef";
1390  case ISD::UNDEF:         return "undef";
1391
1392  // Unary operators
1393  case ISD::FABS:   return "fabs";
1394  case ISD::FNEG:   return "fneg";
1395
1396  // Binary operators
1397  case ISD::ADD:    return "add";
1398  case ISD::SUB:    return "sub";
1399  case ISD::MUL:    return "mul";
1400  case ISD::MULHU:  return "mulhu";
1401  case ISD::MULHS:  return "mulhs";
1402  case ISD::SDIV:   return "sdiv";
1403  case ISD::UDIV:   return "udiv";
1404  case ISD::SREM:   return "srem";
1405  case ISD::UREM:   return "urem";
1406  case ISD::AND:    return "and";
1407  case ISD::OR:     return "or";
1408  case ISD::XOR:    return "xor";
1409  case ISD::SHL:    return "shl";
1410  case ISD::SRA:    return "sra";
1411  case ISD::SRL:    return "srl";
1412
1413  case ISD::SELECT: return "select";
1414  case ISD::ADD_PARTS:   return "add_parts";
1415  case ISD::SUB_PARTS:   return "sub_parts";
1416  case ISD::SHL_PARTS:   return "shl_parts";
1417  case ISD::SRA_PARTS:   return "sra_parts";
1418  case ISD::SRL_PARTS:   return "srl_parts";
1419
1420    // Conversion operators.
1421  case ISD::SIGN_EXTEND: return "sign_extend";
1422  case ISD::ZERO_EXTEND: return "zero_extend";
1423  case ISD::SIGN_EXTEND_INREG: return "sign_extend_inreg";
1424  case ISD::TRUNCATE:    return "truncate";
1425  case ISD::FP_ROUND:    return "fp_round";
1426  case ISD::FP_ROUND_INREG: return "fp_round_inreg";
1427  case ISD::FP_EXTEND:   return "fp_extend";
1428
1429  case ISD::SINT_TO_FP:  return "sint_to_fp";
1430  case ISD::UINT_TO_FP:  return "uint_to_fp";
1431  case ISD::FP_TO_SINT:  return "fp_to_sint";
1432  case ISD::FP_TO_UINT:  return "fp_to_uint";
1433
1434    // Control flow instructions
1435  case ISD::BR:      return "br";
1436  case ISD::BRCOND:  return "brcond";
1437  case ISD::BRCONDTWOWAY:  return "brcondtwoway";
1438  case ISD::RET:     return "ret";
1439  case ISD::CALL:    return "call";
1440  case ISD::ADJCALLSTACKDOWN:  return "adjcallstackdown";
1441  case ISD::ADJCALLSTACKUP:    return "adjcallstackup";
1442
1443    // Other operators
1444  case ISD::LOAD:    return "load";
1445  case ISD::STORE:   return "store";
1446  case ISD::EXTLOAD:    return "extload";
1447  case ISD::SEXTLOAD:   return "sextload";
1448  case ISD::ZEXTLOAD:   return "zextload";
1449  case ISD::TRUNCSTORE: return "truncstore";
1450
1451  case ISD::DYNAMIC_STACKALLOC: return "dynamic_stackalloc";
1452  case ISD::EXTRACT_ELEMENT: return "extract_element";
1453  case ISD::BUILD_PAIR: return "build_pair";
1454  case ISD::MEMSET:  return "memset";
1455  case ISD::MEMCPY:  return "memcpy";
1456  case ISD::MEMMOVE: return "memmove";
1457
1458  case ISD::SETCC:
1459    const SetCCSDNode *SetCC = cast<SetCCSDNode>(this);
1460    switch (SetCC->getCondition()) {
1461    default: assert(0 && "Unknown setcc condition!");
1462    case ISD::SETOEQ:  return "setcc:setoeq";
1463    case ISD::SETOGT:  return "setcc:setogt";
1464    case ISD::SETOGE:  return "setcc:setoge";
1465    case ISD::SETOLT:  return "setcc:setolt";
1466    case ISD::SETOLE:  return "setcc:setole";
1467    case ISD::SETONE:  return "setcc:setone";
1468
1469    case ISD::SETO:    return "setcc:seto";
1470    case ISD::SETUO:   return "setcc:setuo";
1471    case ISD::SETUEQ:  return "setcc:setue";
1472    case ISD::SETUGT:  return "setcc:setugt";
1473    case ISD::SETUGE:  return "setcc:setuge";
1474    case ISD::SETULT:  return "setcc:setult";
1475    case ISD::SETULE:  return "setcc:setule";
1476    case ISD::SETUNE:  return "setcc:setune";
1477
1478    case ISD::SETEQ:   return "setcc:seteq";
1479    case ISD::SETGT:   return "setcc:setgt";
1480    case ISD::SETGE:   return "setcc:setge";
1481    case ISD::SETLT:   return "setcc:setlt";
1482    case ISD::SETLE:   return "setcc:setle";
1483    case ISD::SETNE:   return "setcc:setne";
1484    }
1485  }
1486}
1487
1488void SDNode::dump() const {
1489  std::cerr << (void*)this << ": ";
1490
1491  for (unsigned i = 0, e = getNumValues(); i != e; ++i) {
1492    if (i) std::cerr << ",";
1493    if (getValueType(i) == MVT::Other)
1494      std::cerr << "ch";
1495    else
1496      std::cerr << MVT::getValueTypeString(getValueType(i));
1497  }
1498  std::cerr << " = " << getOperationName();
1499
1500  std::cerr << " ";
1501  for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1502    if (i) std::cerr << ", ";
1503    std::cerr << (void*)getOperand(i).Val;
1504    if (unsigned RN = getOperand(i).ResNo)
1505      std::cerr << ":" << RN;
1506  }
1507
1508  if (const ConstantSDNode *CSDN = dyn_cast<ConstantSDNode>(this)) {
1509    std::cerr << "<" << CSDN->getValue() << ">";
1510  } else if (const ConstantFPSDNode *CSDN = dyn_cast<ConstantFPSDNode>(this)) {
1511    std::cerr << "<" << CSDN->getValue() << ">";
1512  } else if (const GlobalAddressSDNode *GADN =
1513             dyn_cast<GlobalAddressSDNode>(this)) {
1514    std::cerr << "<";
1515    WriteAsOperand(std::cerr, GADN->getGlobal()) << ">";
1516  } else if (const FrameIndexSDNode *FIDN =
1517	     dyn_cast<FrameIndexSDNode>(this)) {
1518    std::cerr << "<" << FIDN->getIndex() << ">";
1519  } else if (const ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(this)){
1520    std::cerr << "<" << CP->getIndex() << ">";
1521  } else if (const BasicBlockSDNode *BBDN =
1522	     dyn_cast<BasicBlockSDNode>(this)) {
1523    std::cerr << "<";
1524    const Value *LBB = (const Value*)BBDN->getBasicBlock()->getBasicBlock();
1525    if (LBB)
1526      std::cerr << LBB->getName() << " ";
1527    std::cerr << (const void*)BBDN->getBasicBlock() << ">";
1528  } else if (const RegSDNode *C2V = dyn_cast<RegSDNode>(this)) {
1529    std::cerr << "<reg #" << C2V->getReg() << ">";
1530  } else if (const ExternalSymbolSDNode *ES =
1531             dyn_cast<ExternalSymbolSDNode>(this)) {
1532    std::cerr << "'" << ES->getSymbol() << "'";
1533  } else if (const MVTSDNode *M = dyn_cast<MVTSDNode>(this)) {
1534    std::cerr << " - Ty = " << MVT::getValueTypeString(M->getExtraValueType());
1535  }
1536}
1537
1538static void DumpNodes(SDNode *N, unsigned indent) {
1539  for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1540    if (N->getOperand(i).Val->hasOneUse())
1541      DumpNodes(N->getOperand(i).Val, indent+2);
1542    else
1543      std::cerr << "\n" << std::string(indent+2, ' ')
1544                << (void*)N->getOperand(i).Val << ": <multiple use>";
1545
1546
1547  std::cerr << "\n" << std::string(indent, ' ');
1548  N->dump();
1549}
1550
1551void SelectionDAG::dump() const {
1552  std::cerr << "SelectionDAG has " << AllNodes.size() << " nodes:";
1553  std::vector<SDNode*> Nodes(AllNodes);
1554  std::sort(Nodes.begin(), Nodes.end());
1555
1556  for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
1557    if (!Nodes[i]->hasOneUse() && Nodes[i] != getRoot().Val)
1558      DumpNodes(Nodes[i], 2);
1559  }
1560
1561  DumpNodes(getRoot().Val, 2);
1562
1563  std::cerr << "\n\n";
1564}
1565
1566