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