DAGCombiner.cpp revision 84750587bf859a048580f7f13b1b2710d0b681fb
1//===-- DAGCombiner.cpp - Implement a DAG node combiner -------------------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file was developed by Nate Begeman and is distributed under the
6// University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This pass combines dag nodes to form fewer, simpler DAG nodes.  It can be run
11// both before and after the DAG is legalized.
12//
13// FIXME: Missing folds
14// sdiv, udiv, srem, urem (X, const) where X is an integer can be expanded into
15//  a sequence of multiplies, shifts, and adds.  This should be controlled by
16//  some kind of hint from the target that int div is expensive.
17// various folds of mulh[s,u] by constants such as -1, powers of 2, etc.
18//
19// FIXME: select C, pow2, pow2 -> something smart
20// FIXME: trunc(select X, Y, Z) -> select X, trunc(Y), trunc(Z)
21// FIXME: Dead stores -> nuke
22// FIXME: shr X, (and Y,31) -> shr X, Y   (TRICKY!)
23// FIXME: mul (x, const) -> shifts + adds
24// FIXME: undef values
25// FIXME: divide by zero is currently left unfolded.  do we want to turn this
26//        into an undef?
27// FIXME: select ne (select cc, 1, 0), 0, true, false -> select cc, true, false
28//
29//===----------------------------------------------------------------------===//
30
31#define DEBUG_TYPE "dagcombine"
32#include "llvm/ADT/Statistic.h"
33#include "llvm/CodeGen/SelectionDAG.h"
34#include "llvm/Support/Debug.h"
35#include "llvm/Support/MathExtras.h"
36#include "llvm/Target/TargetLowering.h"
37#include "llvm/Support/Compiler.h"
38#include <algorithm>
39#include <cmath>
40#include <iostream>
41using namespace llvm;
42
43namespace {
44  static Statistic<> NodesCombined ("dagcombiner",
45				    "Number of dag nodes combined");
46
47  class VISIBILITY_HIDDEN DAGCombiner {
48    SelectionDAG &DAG;
49    TargetLowering &TLI;
50    bool AfterLegalize;
51
52    // Worklist of all of the nodes that need to be simplified.
53    std::vector<SDNode*> WorkList;
54
55    /// AddUsersToWorkList - When an instruction is simplified, add all users of
56    /// the instruction to the work lists because they might get more simplified
57    /// now.
58    ///
59    void AddUsersToWorkList(SDNode *N) {
60      for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
61           UI != UE; ++UI)
62        WorkList.push_back(*UI);
63    }
64
65    /// removeFromWorkList - remove all instances of N from the worklist.
66    ///
67    void removeFromWorkList(SDNode *N) {
68      WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), N),
69                     WorkList.end());
70    }
71
72  public:
73    void AddToWorkList(SDNode *N) {
74      WorkList.push_back(N);
75    }
76
77    SDOperand CombineTo(SDNode *N, const SDOperand *To, unsigned NumTo) {
78      assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
79      ++NodesCombined;
80      DEBUG(std::cerr << "\nReplacing "; N->dump();
81            std::cerr << "\nWith: "; To[0].Val->dump(&DAG);
82            std::cerr << " and " << NumTo-1 << " other values\n");
83      std::vector<SDNode*> NowDead;
84      DAG.ReplaceAllUsesWith(N, To, &NowDead);
85
86      // Push the new nodes and any users onto the worklist
87      for (unsigned i = 0, e = NumTo; i != e; ++i) {
88        WorkList.push_back(To[i].Val);
89        AddUsersToWorkList(To[i].Val);
90      }
91
92      // Nodes can end up on the worklist more than once.  Make sure we do
93      // not process a node that has been replaced.
94      removeFromWorkList(N);
95      for (unsigned i = 0, e = NowDead.size(); i != e; ++i)
96        removeFromWorkList(NowDead[i]);
97
98      // Finally, since the node is now dead, remove it from the graph.
99      DAG.DeleteNode(N);
100      return SDOperand(N, 0);
101    }
102
103    SDOperand CombineTo(SDNode *N, SDOperand Res) {
104      return CombineTo(N, &Res, 1);
105    }
106
107    SDOperand CombineTo(SDNode *N, SDOperand Res0, SDOperand Res1) {
108      SDOperand To[] = { Res0, Res1 };
109      return CombineTo(N, To, 2);
110    }
111  private:
112
113    /// SimplifyDemandedBits - Check the specified integer node value to see if
114    /// it can be simplified or if things it uses can be simplified by bit
115    /// propagation.  If so, return true.
116    bool SimplifyDemandedBits(SDOperand Op) {
117      TargetLowering::TargetLoweringOpt TLO(DAG);
118      uint64_t KnownZero, KnownOne;
119      uint64_t Demanded = MVT::getIntVTBitMask(Op.getValueType());
120      if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
121        return false;
122
123      // Revisit the node.
124      WorkList.push_back(Op.Val);
125
126      // Replace the old value with the new one.
127      ++NodesCombined;
128      DEBUG(std::cerr << "\nReplacing "; TLO.Old.Val->dump();
129            std::cerr << "\nWith: "; TLO.New.Val->dump(&DAG));
130
131      std::vector<SDNode*> NowDead;
132      DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New, NowDead);
133
134      // Push the new node and any (possibly new) users onto the worklist.
135      WorkList.push_back(TLO.New.Val);
136      AddUsersToWorkList(TLO.New.Val);
137
138      // Nodes can end up on the worklist more than once.  Make sure we do
139      // not process a node that has been replaced.
140      for (unsigned i = 0, e = NowDead.size(); i != e; ++i)
141        removeFromWorkList(NowDead[i]);
142
143      // Finally, if the node is now dead, remove it from the graph.  The node
144      // may not be dead if the replacement process recursively simplified to
145      // something else needing this node.
146      if (TLO.Old.Val->use_empty()) {
147        removeFromWorkList(TLO.Old.Val);
148        DAG.DeleteNode(TLO.Old.Val);
149      }
150      return true;
151    }
152
153    /// visit - call the node-specific routine that knows how to fold each
154    /// particular type of node.
155    SDOperand visit(SDNode *N);
156
157    // Visitation implementation - Implement dag node combining for different
158    // node types.  The semantics are as follows:
159    // Return Value:
160    //   SDOperand.Val == 0   - No change was made
161    //   SDOperand.Val == N   - N was replaced, is dead, and is already handled.
162    //   otherwise            - N should be replaced by the returned Operand.
163    //
164    SDOperand visitTokenFactor(SDNode *N);
165    SDOperand visitADD(SDNode *N);
166    SDOperand visitSUB(SDNode *N);
167    SDOperand visitMUL(SDNode *N);
168    SDOperand visitSDIV(SDNode *N);
169    SDOperand visitUDIV(SDNode *N);
170    SDOperand visitSREM(SDNode *N);
171    SDOperand visitUREM(SDNode *N);
172    SDOperand visitMULHU(SDNode *N);
173    SDOperand visitMULHS(SDNode *N);
174    SDOperand visitAND(SDNode *N);
175    SDOperand visitOR(SDNode *N);
176    SDOperand visitXOR(SDNode *N);
177    SDOperand visitVBinOp(SDNode *N, ISD::NodeType IntOp, ISD::NodeType FPOp);
178    SDOperand visitSHL(SDNode *N);
179    SDOperand visitSRA(SDNode *N);
180    SDOperand visitSRL(SDNode *N);
181    SDOperand visitCTLZ(SDNode *N);
182    SDOperand visitCTTZ(SDNode *N);
183    SDOperand visitCTPOP(SDNode *N);
184    SDOperand visitSELECT(SDNode *N);
185    SDOperand visitSELECT_CC(SDNode *N);
186    SDOperand visitSETCC(SDNode *N);
187    SDOperand visitSIGN_EXTEND(SDNode *N);
188    SDOperand visitZERO_EXTEND(SDNode *N);
189    SDOperand visitANY_EXTEND(SDNode *N);
190    SDOperand visitSIGN_EXTEND_INREG(SDNode *N);
191    SDOperand visitTRUNCATE(SDNode *N);
192    SDOperand visitBIT_CONVERT(SDNode *N);
193    SDOperand visitVBIT_CONVERT(SDNode *N);
194    SDOperand visitFADD(SDNode *N);
195    SDOperand visitFSUB(SDNode *N);
196    SDOperand visitFMUL(SDNode *N);
197    SDOperand visitFDIV(SDNode *N);
198    SDOperand visitFREM(SDNode *N);
199    SDOperand visitFCOPYSIGN(SDNode *N);
200    SDOperand visitSINT_TO_FP(SDNode *N);
201    SDOperand visitUINT_TO_FP(SDNode *N);
202    SDOperand visitFP_TO_SINT(SDNode *N);
203    SDOperand visitFP_TO_UINT(SDNode *N);
204    SDOperand visitFP_ROUND(SDNode *N);
205    SDOperand visitFP_ROUND_INREG(SDNode *N);
206    SDOperand visitFP_EXTEND(SDNode *N);
207    SDOperand visitFNEG(SDNode *N);
208    SDOperand visitFABS(SDNode *N);
209    SDOperand visitBRCOND(SDNode *N);
210    SDOperand visitBR_CC(SDNode *N);
211    SDOperand visitLOAD(SDNode *N);
212    SDOperand visitXEXTLOAD(SDNode *N);
213    SDOperand visitSTORE(SDNode *N);
214    SDOperand visitINSERT_VECTOR_ELT(SDNode *N);
215    SDOperand visitVINSERT_VECTOR_ELT(SDNode *N);
216    SDOperand visitVBUILD_VECTOR(SDNode *N);
217    SDOperand visitVECTOR_SHUFFLE(SDNode *N);
218    SDOperand visitVVECTOR_SHUFFLE(SDNode *N);
219
220    SDOperand XformToShuffleWithZero(SDNode *N);
221    SDOperand ReassociateOps(unsigned Opc, SDOperand LHS, SDOperand RHS);
222
223    bool SimplifySelectOps(SDNode *SELECT, SDOperand LHS, SDOperand RHS);
224    SDOperand SimplifyBinOpWithSameOpcodeHands(SDNode *N);
225    SDOperand SimplifySelect(SDOperand N0, SDOperand N1, SDOperand N2);
226    SDOperand SimplifySelectCC(SDOperand N0, SDOperand N1, SDOperand N2,
227                               SDOperand N3, ISD::CondCode CC);
228    SDOperand SimplifySetCC(MVT::ValueType VT, SDOperand N0, SDOperand N1,
229                            ISD::CondCode Cond, bool foldBooleans = true);
230    SDOperand ConstantFoldVBIT_CONVERTofVBUILD_VECTOR(SDNode *, MVT::ValueType);
231    SDOperand BuildSDIV(SDNode *N);
232    SDOperand BuildUDIV(SDNode *N);
233    SDNode *MatchRotate(SDOperand LHS, SDOperand RHS);
234public:
235    DAGCombiner(SelectionDAG &D)
236      : DAG(D), TLI(D.getTargetLoweringInfo()), AfterLegalize(false) {}
237
238    /// Run - runs the dag combiner on all nodes in the work list
239    void Run(bool RunningAfterLegalize);
240  };
241}
242
243//===----------------------------------------------------------------------===//
244//  TargetLowering::DAGCombinerInfo implementation
245//===----------------------------------------------------------------------===//
246
247void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
248  ((DAGCombiner*)DC)->AddToWorkList(N);
249}
250
251SDOperand TargetLowering::DAGCombinerInfo::
252CombineTo(SDNode *N, const std::vector<SDOperand> &To) {
253  return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size());
254}
255
256SDOperand TargetLowering::DAGCombinerInfo::
257CombineTo(SDNode *N, SDOperand Res) {
258  return ((DAGCombiner*)DC)->CombineTo(N, Res);
259}
260
261
262SDOperand TargetLowering::DAGCombinerInfo::
263CombineTo(SDNode *N, SDOperand Res0, SDOperand Res1) {
264  return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1);
265}
266
267
268
269
270//===----------------------------------------------------------------------===//
271
272
273// isSetCCEquivalent - Return true if this node is a setcc, or is a select_cc
274// that selects between the values 1 and 0, making it equivalent to a setcc.
275// Also, set the incoming LHS, RHS, and CC references to the appropriate
276// nodes based on the type of node we are checking.  This simplifies life a
277// bit for the callers.
278static bool isSetCCEquivalent(SDOperand N, SDOperand &LHS, SDOperand &RHS,
279                              SDOperand &CC) {
280  if (N.getOpcode() == ISD::SETCC) {
281    LHS = N.getOperand(0);
282    RHS = N.getOperand(1);
283    CC  = N.getOperand(2);
284    return true;
285  }
286  if (N.getOpcode() == ISD::SELECT_CC &&
287      N.getOperand(2).getOpcode() == ISD::Constant &&
288      N.getOperand(3).getOpcode() == ISD::Constant &&
289      cast<ConstantSDNode>(N.getOperand(2))->getValue() == 1 &&
290      cast<ConstantSDNode>(N.getOperand(3))->isNullValue()) {
291    LHS = N.getOperand(0);
292    RHS = N.getOperand(1);
293    CC  = N.getOperand(4);
294    return true;
295  }
296  return false;
297}
298
299// isOneUseSetCC - Return true if this is a SetCC-equivalent operation with only
300// one use.  If this is true, it allows the users to invert the operation for
301// free when it is profitable to do so.
302static bool isOneUseSetCC(SDOperand N) {
303  SDOperand N0, N1, N2;
304  if (isSetCCEquivalent(N, N0, N1, N2) && N.Val->hasOneUse())
305    return true;
306  return false;
307}
308
309SDOperand DAGCombiner::ReassociateOps(unsigned Opc, SDOperand N0, SDOperand N1){
310  MVT::ValueType VT = N0.getValueType();
311  // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one use
312  // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
313  if (N0.getOpcode() == Opc && isa<ConstantSDNode>(N0.getOperand(1))) {
314    if (isa<ConstantSDNode>(N1)) {
315      SDOperand OpNode = DAG.getNode(Opc, VT, N0.getOperand(1), N1);
316      AddToWorkList(OpNode.Val);
317      return DAG.getNode(Opc, VT, OpNode, N0.getOperand(0));
318    } else if (N0.hasOneUse()) {
319      SDOperand OpNode = DAG.getNode(Opc, VT, N0.getOperand(0), N1);
320      AddToWorkList(OpNode.Val);
321      return DAG.getNode(Opc, VT, OpNode, N0.getOperand(1));
322    }
323  }
324  // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one use
325  // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
326  if (N1.getOpcode() == Opc && isa<ConstantSDNode>(N1.getOperand(1))) {
327    if (isa<ConstantSDNode>(N0)) {
328      SDOperand OpNode = DAG.getNode(Opc, VT, N1.getOperand(1), N0);
329      AddToWorkList(OpNode.Val);
330      return DAG.getNode(Opc, VT, OpNode, N1.getOperand(0));
331    } else if (N1.hasOneUse()) {
332      SDOperand OpNode = DAG.getNode(Opc, VT, N1.getOperand(0), N0);
333      AddToWorkList(OpNode.Val);
334      return DAG.getNode(Opc, VT, OpNode, N1.getOperand(1));
335    }
336  }
337  return SDOperand();
338}
339
340void DAGCombiner::Run(bool RunningAfterLegalize) {
341  // set the instance variable, so that the various visit routines may use it.
342  AfterLegalize = RunningAfterLegalize;
343
344  // Add all the dag nodes to the worklist.
345  for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
346       E = DAG.allnodes_end(); I != E; ++I)
347    WorkList.push_back(I);
348
349  // Create a dummy node (which is not added to allnodes), that adds a reference
350  // to the root node, preventing it from being deleted, and tracking any
351  // changes of the root.
352  HandleSDNode Dummy(DAG.getRoot());
353
354
355  /// DagCombineInfo - Expose the DAG combiner to the target combiner impls.
356  TargetLowering::DAGCombinerInfo
357    DagCombineInfo(DAG, !RunningAfterLegalize, this);
358
359  // while the worklist isn't empty, inspect the node on the end of it and
360  // try and combine it.
361  while (!WorkList.empty()) {
362    SDNode *N = WorkList.back();
363    WorkList.pop_back();
364
365    // If N has no uses, it is dead.  Make sure to revisit all N's operands once
366    // N is deleted from the DAG, since they too may now be dead or may have a
367    // reduced number of uses, allowing other xforms.
368    if (N->use_empty() && N != &Dummy) {
369      for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
370        WorkList.push_back(N->getOperand(i).Val);
371
372      removeFromWorkList(N);
373      DAG.DeleteNode(N);
374      continue;
375    }
376
377    SDOperand RV = visit(N);
378
379    // If nothing happened, try a target-specific DAG combine.
380    if (RV.Val == 0) {
381      assert(N->getOpcode() != ISD::DELETED_NODE &&
382             "Node was deleted but visit returned NULL!");
383      if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
384          TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode()))
385        RV = TLI.PerformDAGCombine(N, DagCombineInfo);
386    }
387
388    if (RV.Val) {
389      ++NodesCombined;
390      // If we get back the same node we passed in, rather than a new node or
391      // zero, we know that the node must have defined multiple values and
392      // CombineTo was used.  Since CombineTo takes care of the worklist
393      // mechanics for us, we have no work to do in this case.
394      if (RV.Val != N) {
395        assert(N->getOpcode() != ISD::DELETED_NODE &&
396               RV.Val->getOpcode() != ISD::DELETED_NODE &&
397               "Node was deleted but visit returned new node!");
398
399        DEBUG(std::cerr << "\nReplacing "; N->dump();
400              std::cerr << "\nWith: "; RV.Val->dump(&DAG);
401              std::cerr << '\n');
402        std::vector<SDNode*> NowDead;
403        SDOperand OpV = RV;
404        DAG.ReplaceAllUsesWith(N, &OpV, &NowDead);
405
406        // Push the new node and any users onto the worklist
407        WorkList.push_back(RV.Val);
408        AddUsersToWorkList(RV.Val);
409
410        // Nodes can end up on the worklist more than once.  Make sure we do
411        // not process a node that has been replaced.
412        removeFromWorkList(N);
413        for (unsigned i = 0, e = NowDead.size(); i != e; ++i)
414          removeFromWorkList(NowDead[i]);
415
416        // Finally, since the node is now dead, remove it from the graph.
417        DAG.DeleteNode(N);
418      }
419    }
420  }
421
422  // If the root changed (e.g. it was a dead load, update the root).
423  DAG.setRoot(Dummy.getValue());
424}
425
426SDOperand DAGCombiner::visit(SDNode *N) {
427  switch(N->getOpcode()) {
428  default: break;
429  case ISD::TokenFactor:        return visitTokenFactor(N);
430  case ISD::ADD:                return visitADD(N);
431  case ISD::SUB:                return visitSUB(N);
432  case ISD::MUL:                return visitMUL(N);
433  case ISD::SDIV:               return visitSDIV(N);
434  case ISD::UDIV:               return visitUDIV(N);
435  case ISD::SREM:               return visitSREM(N);
436  case ISD::UREM:               return visitUREM(N);
437  case ISD::MULHU:              return visitMULHU(N);
438  case ISD::MULHS:              return visitMULHS(N);
439  case ISD::AND:                return visitAND(N);
440  case ISD::OR:                 return visitOR(N);
441  case ISD::XOR:                return visitXOR(N);
442  case ISD::SHL:                return visitSHL(N);
443  case ISD::SRA:                return visitSRA(N);
444  case ISD::SRL:                return visitSRL(N);
445  case ISD::CTLZ:               return visitCTLZ(N);
446  case ISD::CTTZ:               return visitCTTZ(N);
447  case ISD::CTPOP:              return visitCTPOP(N);
448  case ISD::SELECT:             return visitSELECT(N);
449  case ISD::SELECT_CC:          return visitSELECT_CC(N);
450  case ISD::SETCC:              return visitSETCC(N);
451  case ISD::SIGN_EXTEND:        return visitSIGN_EXTEND(N);
452  case ISD::ZERO_EXTEND:        return visitZERO_EXTEND(N);
453  case ISD::ANY_EXTEND:         return visitANY_EXTEND(N);
454  case ISD::SIGN_EXTEND_INREG:  return visitSIGN_EXTEND_INREG(N);
455  case ISD::TRUNCATE:           return visitTRUNCATE(N);
456  case ISD::BIT_CONVERT:        return visitBIT_CONVERT(N);
457  case ISD::VBIT_CONVERT:       return visitVBIT_CONVERT(N);
458  case ISD::FADD:               return visitFADD(N);
459  case ISD::FSUB:               return visitFSUB(N);
460  case ISD::FMUL:               return visitFMUL(N);
461  case ISD::FDIV:               return visitFDIV(N);
462  case ISD::FREM:               return visitFREM(N);
463  case ISD::FCOPYSIGN:          return visitFCOPYSIGN(N);
464  case ISD::SINT_TO_FP:         return visitSINT_TO_FP(N);
465  case ISD::UINT_TO_FP:         return visitUINT_TO_FP(N);
466  case ISD::FP_TO_SINT:         return visitFP_TO_SINT(N);
467  case ISD::FP_TO_UINT:         return visitFP_TO_UINT(N);
468  case ISD::FP_ROUND:           return visitFP_ROUND(N);
469  case ISD::FP_ROUND_INREG:     return visitFP_ROUND_INREG(N);
470  case ISD::FP_EXTEND:          return visitFP_EXTEND(N);
471  case ISD::FNEG:               return visitFNEG(N);
472  case ISD::FABS:               return visitFABS(N);
473  case ISD::BRCOND:             return visitBRCOND(N);
474  case ISD::BR_CC:              return visitBR_CC(N);
475  case ISD::LOAD:               return visitLOAD(N);
476  case ISD::EXTLOAD:
477  case ISD::SEXTLOAD:
478  case ISD::ZEXTLOAD:           return visitXEXTLOAD(N);
479  case ISD::STORE:              return visitSTORE(N);
480  case ISD::INSERT_VECTOR_ELT:  return visitINSERT_VECTOR_ELT(N);
481  case ISD::VINSERT_VECTOR_ELT: return visitVINSERT_VECTOR_ELT(N);
482  case ISD::VBUILD_VECTOR:      return visitVBUILD_VECTOR(N);
483  case ISD::VECTOR_SHUFFLE:     return visitVECTOR_SHUFFLE(N);
484  case ISD::VVECTOR_SHUFFLE:    return visitVVECTOR_SHUFFLE(N);
485  case ISD::VADD:               return visitVBinOp(N, ISD::ADD , ISD::FADD);
486  case ISD::VSUB:               return visitVBinOp(N, ISD::SUB , ISD::FSUB);
487  case ISD::VMUL:               return visitVBinOp(N, ISD::MUL , ISD::FMUL);
488  case ISD::VSDIV:              return visitVBinOp(N, ISD::SDIV, ISD::FDIV);
489  case ISD::VUDIV:              return visitVBinOp(N, ISD::UDIV, ISD::UDIV);
490  case ISD::VAND:               return visitVBinOp(N, ISD::AND , ISD::AND);
491  case ISD::VOR:                return visitVBinOp(N, ISD::OR  , ISD::OR);
492  case ISD::VXOR:               return visitVBinOp(N, ISD::XOR , ISD::XOR);
493  }
494  return SDOperand();
495}
496
497SDOperand DAGCombiner::visitTokenFactor(SDNode *N) {
498  SmallVector<SDOperand, 8> Ops;
499  bool Changed = false;
500
501  // If the token factor has two operands and one is the entry token, replace
502  // the token factor with the other operand.
503  if (N->getNumOperands() == 2) {
504    if (N->getOperand(0).getOpcode() == ISD::EntryToken ||
505        N->getOperand(0) == N->getOperand(1))
506      return N->getOperand(1);
507    if (N->getOperand(1).getOpcode() == ISD::EntryToken)
508      return N->getOperand(0);
509  }
510
511  // fold (tokenfactor (tokenfactor)) -> tokenfactor
512  for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
513    SDOperand Op = N->getOperand(i);
514    if (Op.getOpcode() == ISD::TokenFactor && Op.hasOneUse()) {
515      AddToWorkList(Op.Val);  // Remove dead node.
516      Changed = true;
517      for (unsigned j = 0, e = Op.getNumOperands(); j != e; ++j)
518        Ops.push_back(Op.getOperand(j));
519    } else if (i == 0 || N->getOperand(i) != N->getOperand(i-1)) {
520      Ops.push_back(Op);
521    } else {
522      // Deleted an operand that was the same as the last one.
523      Changed = true;
524    }
525  }
526  if (Changed)
527    return DAG.getNode(ISD::TokenFactor, MVT::Other, &Ops[0], Ops.size());
528  return SDOperand();
529}
530
531SDOperand DAGCombiner::visitADD(SDNode *N) {
532  SDOperand N0 = N->getOperand(0);
533  SDOperand N1 = N->getOperand(1);
534  ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
535  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
536  MVT::ValueType VT = N0.getValueType();
537
538  // fold (add c1, c2) -> c1+c2
539  if (N0C && N1C)
540    return DAG.getNode(ISD::ADD, VT, N0, N1);
541  // canonicalize constant to RHS
542  if (N0C && !N1C)
543    return DAG.getNode(ISD::ADD, VT, N1, N0);
544  // fold (add x, 0) -> x
545  if (N1C && N1C->isNullValue())
546    return N0;
547  // fold ((c1-A)+c2) -> (c1+c2)-A
548  if (N1C && N0.getOpcode() == ISD::SUB)
549    if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
550      return DAG.getNode(ISD::SUB, VT,
551                         DAG.getConstant(N1C->getValue()+N0C->getValue(), VT),
552                         N0.getOperand(1));
553  // reassociate add
554  SDOperand RADD = ReassociateOps(ISD::ADD, N0, N1);
555  if (RADD.Val != 0)
556    return RADD;
557  // fold ((0-A) + B) -> B-A
558  if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
559      cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
560    return DAG.getNode(ISD::SUB, VT, N1, N0.getOperand(1));
561  // fold (A + (0-B)) -> A-B
562  if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
563      cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
564    return DAG.getNode(ISD::SUB, VT, N0, N1.getOperand(1));
565  // fold (A+(B-A)) -> B
566  if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
567    return N1.getOperand(0);
568
569  if (!MVT::isVector(VT) && SimplifyDemandedBits(SDOperand(N, 0)))
570    return SDOperand(N, 0);
571
572  // fold (a+b) -> (a|b) iff a and b share no bits.
573  if (MVT::isInteger(VT) && !MVT::isVector(VT)) {
574    uint64_t LHSZero, LHSOne;
575    uint64_t RHSZero, RHSOne;
576    uint64_t Mask = MVT::getIntVTBitMask(VT);
577    TLI.ComputeMaskedBits(N0, Mask, LHSZero, LHSOne);
578    if (LHSZero) {
579      TLI.ComputeMaskedBits(N1, Mask, RHSZero, RHSOne);
580
581      // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
582      // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
583      if ((RHSZero & (~LHSZero & Mask)) == (~LHSZero & Mask) ||
584          (LHSZero & (~RHSZero & Mask)) == (~RHSZero & Mask))
585        return DAG.getNode(ISD::OR, VT, N0, N1);
586    }
587  }
588
589  return SDOperand();
590}
591
592SDOperand DAGCombiner::visitSUB(SDNode *N) {
593  SDOperand N0 = N->getOperand(0);
594  SDOperand N1 = N->getOperand(1);
595  ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.Val);
596  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val);
597  MVT::ValueType VT = N0.getValueType();
598
599  // fold (sub x, x) -> 0
600  if (N0 == N1)
601    return DAG.getConstant(0, N->getValueType(0));
602  // fold (sub c1, c2) -> c1-c2
603  if (N0C && N1C)
604    return DAG.getNode(ISD::SUB, VT, N0, N1);
605  // fold (sub x, c) -> (add x, -c)
606  if (N1C)
607    return DAG.getNode(ISD::ADD, VT, N0, DAG.getConstant(-N1C->getValue(), VT));
608  // fold (A+B)-A -> B
609  if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
610    return N0.getOperand(1);
611  // fold (A+B)-B -> A
612  if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
613    return N0.getOperand(0);
614  return SDOperand();
615}
616
617SDOperand DAGCombiner::visitMUL(SDNode *N) {
618  SDOperand N0 = N->getOperand(0);
619  SDOperand N1 = N->getOperand(1);
620  ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
621  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
622  MVT::ValueType VT = N0.getValueType();
623
624  // fold (mul c1, c2) -> c1*c2
625  if (N0C && N1C)
626    return DAG.getNode(ISD::MUL, VT, N0, N1);
627  // canonicalize constant to RHS
628  if (N0C && !N1C)
629    return DAG.getNode(ISD::MUL, VT, N1, N0);
630  // fold (mul x, 0) -> 0
631  if (N1C && N1C->isNullValue())
632    return N1;
633  // fold (mul x, -1) -> 0-x
634  if (N1C && N1C->isAllOnesValue())
635    return DAG.getNode(ISD::SUB, VT, DAG.getConstant(0, VT), N0);
636  // fold (mul x, (1 << c)) -> x << c
637  if (N1C && isPowerOf2_64(N1C->getValue()))
638    return DAG.getNode(ISD::SHL, VT, N0,
639                       DAG.getConstant(Log2_64(N1C->getValue()),
640                                       TLI.getShiftAmountTy()));
641  // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
642  if (N1C && isPowerOf2_64(-N1C->getSignExtended())) {
643    // FIXME: If the input is something that is easily negated (e.g. a
644    // single-use add), we should put the negate there.
645    return DAG.getNode(ISD::SUB, VT, DAG.getConstant(0, VT),
646                       DAG.getNode(ISD::SHL, VT, N0,
647                            DAG.getConstant(Log2_64(-N1C->getSignExtended()),
648                                            TLI.getShiftAmountTy())));
649  }
650
651  // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
652  if (N1C && N0.getOpcode() == ISD::SHL &&
653      isa<ConstantSDNode>(N0.getOperand(1))) {
654    SDOperand C3 = DAG.getNode(ISD::SHL, VT, N1, N0.getOperand(1));
655    AddToWorkList(C3.Val);
656    return DAG.getNode(ISD::MUL, VT, N0.getOperand(0), C3);
657  }
658
659  // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
660  // use.
661  {
662    SDOperand Sh(0,0), Y(0,0);
663    // Check for both (mul (shl X, C), Y)  and  (mul Y, (shl X, C)).
664    if (N0.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N0.getOperand(1)) &&
665        N0.Val->hasOneUse()) {
666      Sh = N0; Y = N1;
667    } else if (N1.getOpcode() == ISD::SHL &&
668               isa<ConstantSDNode>(N1.getOperand(1)) && N1.Val->hasOneUse()) {
669      Sh = N1; Y = N0;
670    }
671    if (Sh.Val) {
672      SDOperand Mul = DAG.getNode(ISD::MUL, VT, Sh.getOperand(0), Y);
673      return DAG.getNode(ISD::SHL, VT, Mul, Sh.getOperand(1));
674    }
675  }
676  // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
677  if (N1C && N0.getOpcode() == ISD::ADD && N0.Val->hasOneUse() &&
678      isa<ConstantSDNode>(N0.getOperand(1))) {
679    return DAG.getNode(ISD::ADD, VT,
680                       DAG.getNode(ISD::MUL, VT, N0.getOperand(0), N1),
681                       DAG.getNode(ISD::MUL, VT, N0.getOperand(1), N1));
682  }
683
684  // reassociate mul
685  SDOperand RMUL = ReassociateOps(ISD::MUL, N0, N1);
686  if (RMUL.Val != 0)
687    return RMUL;
688  return SDOperand();
689}
690
691SDOperand DAGCombiner::visitSDIV(SDNode *N) {
692  SDOperand N0 = N->getOperand(0);
693  SDOperand N1 = N->getOperand(1);
694  ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.Val);
695  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val);
696  MVT::ValueType VT = N->getValueType(0);
697
698  // fold (sdiv c1, c2) -> c1/c2
699  if (N0C && N1C && !N1C->isNullValue())
700    return DAG.getNode(ISD::SDIV, VT, N0, N1);
701  // fold (sdiv X, 1) -> X
702  if (N1C && N1C->getSignExtended() == 1LL)
703    return N0;
704  // fold (sdiv X, -1) -> 0-X
705  if (N1C && N1C->isAllOnesValue())
706    return DAG.getNode(ISD::SUB, VT, DAG.getConstant(0, VT), N0);
707  // If we know the sign bits of both operands are zero, strength reduce to a
708  // udiv instead.  Handles (X&15) /s 4 -> X&15 >> 2
709  uint64_t SignBit = 1ULL << (MVT::getSizeInBits(VT)-1);
710  if (TLI.MaskedValueIsZero(N1, SignBit) &&
711      TLI.MaskedValueIsZero(N0, SignBit))
712    return DAG.getNode(ISD::UDIV, N1.getValueType(), N0, N1);
713  // fold (sdiv X, pow2) -> simple ops after legalize
714  if (N1C && N1C->getValue() && !TLI.isIntDivCheap() &&
715      (isPowerOf2_64(N1C->getSignExtended()) ||
716       isPowerOf2_64(-N1C->getSignExtended()))) {
717    // If dividing by powers of two is cheap, then don't perform the following
718    // fold.
719    if (TLI.isPow2DivCheap())
720      return SDOperand();
721    int64_t pow2 = N1C->getSignExtended();
722    int64_t abs2 = pow2 > 0 ? pow2 : -pow2;
723    unsigned lg2 = Log2_64(abs2);
724    // Splat the sign bit into the register
725    SDOperand SGN = DAG.getNode(ISD::SRA, VT, N0,
726                                DAG.getConstant(MVT::getSizeInBits(VT)-1,
727                                                TLI.getShiftAmountTy()));
728    AddToWorkList(SGN.Val);
729    // Add (N0 < 0) ? abs2 - 1 : 0;
730    SDOperand SRL = DAG.getNode(ISD::SRL, VT, SGN,
731                                DAG.getConstant(MVT::getSizeInBits(VT)-lg2,
732                                                TLI.getShiftAmountTy()));
733    SDOperand ADD = DAG.getNode(ISD::ADD, VT, N0, SRL);
734    AddToWorkList(SRL.Val);
735    AddToWorkList(ADD.Val);    // Divide by pow2
736    SDOperand SRA = DAG.getNode(ISD::SRA, VT, ADD,
737                                DAG.getConstant(lg2, TLI.getShiftAmountTy()));
738    // If we're dividing by a positive value, we're done.  Otherwise, we must
739    // negate the result.
740    if (pow2 > 0)
741      return SRA;
742    AddToWorkList(SRA.Val);
743    return DAG.getNode(ISD::SUB, VT, DAG.getConstant(0, VT), SRA);
744  }
745  // if integer divide is expensive and we satisfy the requirements, emit an
746  // alternate sequence.
747  if (N1C && (N1C->getSignExtended() < -1 || N1C->getSignExtended() > 1) &&
748      !TLI.isIntDivCheap()) {
749    SDOperand Op = BuildSDIV(N);
750    if (Op.Val) return Op;
751  }
752  return SDOperand();
753}
754
755SDOperand DAGCombiner::visitUDIV(SDNode *N) {
756  SDOperand N0 = N->getOperand(0);
757  SDOperand N1 = N->getOperand(1);
758  ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.Val);
759  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val);
760  MVT::ValueType VT = N->getValueType(0);
761
762  // fold (udiv c1, c2) -> c1/c2
763  if (N0C && N1C && !N1C->isNullValue())
764    return DAG.getNode(ISD::UDIV, VT, N0, N1);
765  // fold (udiv x, (1 << c)) -> x >>u c
766  if (N1C && isPowerOf2_64(N1C->getValue()))
767    return DAG.getNode(ISD::SRL, VT, N0,
768                       DAG.getConstant(Log2_64(N1C->getValue()),
769                                       TLI.getShiftAmountTy()));
770  // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
771  if (N1.getOpcode() == ISD::SHL) {
772    if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
773      if (isPowerOf2_64(SHC->getValue())) {
774        MVT::ValueType ADDVT = N1.getOperand(1).getValueType();
775        SDOperand Add = DAG.getNode(ISD::ADD, ADDVT, N1.getOperand(1),
776                                    DAG.getConstant(Log2_64(SHC->getValue()),
777                                                    ADDVT));
778        AddToWorkList(Add.Val);
779        return DAG.getNode(ISD::SRL, VT, N0, Add);
780      }
781    }
782  }
783  // fold (udiv x, c) -> alternate
784  if (N1C && N1C->getValue() && !TLI.isIntDivCheap()) {
785    SDOperand Op = BuildUDIV(N);
786    if (Op.Val) return Op;
787  }
788  return SDOperand();
789}
790
791SDOperand DAGCombiner::visitSREM(SDNode *N) {
792  SDOperand N0 = N->getOperand(0);
793  SDOperand N1 = N->getOperand(1);
794  ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
795  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
796  MVT::ValueType VT = N->getValueType(0);
797
798  // fold (srem c1, c2) -> c1%c2
799  if (N0C && N1C && !N1C->isNullValue())
800    return DAG.getNode(ISD::SREM, VT, N0, N1);
801  // If we know the sign bits of both operands are zero, strength reduce to a
802  // urem instead.  Handles (X & 0x0FFFFFFF) %s 16 -> X&15
803  uint64_t SignBit = 1ULL << (MVT::getSizeInBits(VT)-1);
804  if (TLI.MaskedValueIsZero(N1, SignBit) &&
805      TLI.MaskedValueIsZero(N0, SignBit))
806    return DAG.getNode(ISD::UREM, VT, N0, N1);
807  return SDOperand();
808}
809
810SDOperand DAGCombiner::visitUREM(SDNode *N) {
811  SDOperand N0 = N->getOperand(0);
812  SDOperand N1 = N->getOperand(1);
813  ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
814  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
815  MVT::ValueType VT = N->getValueType(0);
816
817  // fold (urem c1, c2) -> c1%c2
818  if (N0C && N1C && !N1C->isNullValue())
819    return DAG.getNode(ISD::UREM, VT, N0, N1);
820  // fold (urem x, pow2) -> (and x, pow2-1)
821  if (N1C && !N1C->isNullValue() && isPowerOf2_64(N1C->getValue()))
822    return DAG.getNode(ISD::AND, VT, N0, DAG.getConstant(N1C->getValue()-1,VT));
823  // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
824  if (N1.getOpcode() == ISD::SHL) {
825    if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
826      if (isPowerOf2_64(SHC->getValue())) {
827        SDOperand Add = DAG.getNode(ISD::ADD, VT, N1,DAG.getConstant(~0ULL,VT));
828        AddToWorkList(Add.Val);
829        return DAG.getNode(ISD::AND, VT, N0, Add);
830      }
831    }
832  }
833  return SDOperand();
834}
835
836SDOperand DAGCombiner::visitMULHS(SDNode *N) {
837  SDOperand N0 = N->getOperand(0);
838  SDOperand N1 = N->getOperand(1);
839  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
840
841  // fold (mulhs x, 0) -> 0
842  if (N1C && N1C->isNullValue())
843    return N1;
844  // fold (mulhs x, 1) -> (sra x, size(x)-1)
845  if (N1C && N1C->getValue() == 1)
846    return DAG.getNode(ISD::SRA, N0.getValueType(), N0,
847                       DAG.getConstant(MVT::getSizeInBits(N0.getValueType())-1,
848                                       TLI.getShiftAmountTy()));
849  return SDOperand();
850}
851
852SDOperand DAGCombiner::visitMULHU(SDNode *N) {
853  SDOperand N0 = N->getOperand(0);
854  SDOperand N1 = N->getOperand(1);
855  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
856
857  // fold (mulhu x, 0) -> 0
858  if (N1C && N1C->isNullValue())
859    return N1;
860  // fold (mulhu x, 1) -> 0
861  if (N1C && N1C->getValue() == 1)
862    return DAG.getConstant(0, N0.getValueType());
863  return SDOperand();
864}
865
866/// SimplifyBinOpWithSameOpcodeHands - If this is a binary operator with
867/// two operands of the same opcode, try to simplify it.
868SDOperand DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
869  SDOperand N0 = N->getOperand(0), N1 = N->getOperand(1);
870  MVT::ValueType VT = N0.getValueType();
871  assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
872
873  // For each of OP in AND/OR/XOR:
874  // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
875  // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
876  // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
877  // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y))
878  if ((N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND||
879       N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::TRUNCATE) &&
880      N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()) {
881    SDOperand ORNode = DAG.getNode(N->getOpcode(),
882                                   N0.getOperand(0).getValueType(),
883                                   N0.getOperand(0), N1.getOperand(0));
884    AddToWorkList(ORNode.Val);
885    return DAG.getNode(N0.getOpcode(), VT, ORNode);
886  }
887
888  // For each of OP in SHL/SRL/SRA/AND...
889  //   fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
890  //   fold (or  (OP x, z), (OP y, z)) -> (OP (or  x, y), z)
891  //   fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
892  if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
893       N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
894      N0.getOperand(1) == N1.getOperand(1)) {
895    SDOperand ORNode = DAG.getNode(N->getOpcode(),
896                                   N0.getOperand(0).getValueType(),
897                                   N0.getOperand(0), N1.getOperand(0));
898    AddToWorkList(ORNode.Val);
899    return DAG.getNode(N0.getOpcode(), VT, ORNode, N0.getOperand(1));
900  }
901
902  return SDOperand();
903}
904
905SDOperand DAGCombiner::visitAND(SDNode *N) {
906  SDOperand N0 = N->getOperand(0);
907  SDOperand N1 = N->getOperand(1);
908  SDOperand LL, LR, RL, RR, CC0, CC1;
909  ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
910  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
911  MVT::ValueType VT = N1.getValueType();
912  unsigned OpSizeInBits = MVT::getSizeInBits(VT);
913
914  // fold (and c1, c2) -> c1&c2
915  if (N0C && N1C)
916    return DAG.getNode(ISD::AND, VT, N0, N1);
917  // canonicalize constant to RHS
918  if (N0C && !N1C)
919    return DAG.getNode(ISD::AND, VT, N1, N0);
920  // fold (and x, -1) -> x
921  if (N1C && N1C->isAllOnesValue())
922    return N0;
923  // if (and x, c) is known to be zero, return 0
924  if (N1C && TLI.MaskedValueIsZero(SDOperand(N, 0), MVT::getIntVTBitMask(VT)))
925    return DAG.getConstant(0, VT);
926  // reassociate and
927  SDOperand RAND = ReassociateOps(ISD::AND, N0, N1);
928  if (RAND.Val != 0)
929    return RAND;
930  // fold (and (or x, 0xFFFF), 0xFF) -> 0xFF
931  if (N1C && N0.getOpcode() == ISD::OR)
932    if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
933      if ((ORI->getValue() & N1C->getValue()) == N1C->getValue())
934        return N1;
935  // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
936  if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
937    unsigned InMask = MVT::getIntVTBitMask(N0.getOperand(0).getValueType());
938    if (TLI.MaskedValueIsZero(N0.getOperand(0),
939                              ~N1C->getValue() & InMask)) {
940      SDOperand Zext = DAG.getNode(ISD::ZERO_EXTEND, N0.getValueType(),
941                                   N0.getOperand(0));
942
943      // Replace uses of the AND with uses of the Zero extend node.
944      CombineTo(N, Zext);
945
946      // We actually want to replace all uses of the any_extend with the
947      // zero_extend, to avoid duplicating things.  This will later cause this
948      // AND to be folded.
949      CombineTo(N0.Val, Zext);
950      return SDOperand(N, 0);   // Return N so it doesn't get rechecked!
951    }
952  }
953  // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
954  if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
955    ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
956    ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
957
958    if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
959        MVT::isInteger(LL.getValueType())) {
960      // fold (X == 0) & (Y == 0) -> (X|Y == 0)
961      if (cast<ConstantSDNode>(LR)->getValue() == 0 && Op1 == ISD::SETEQ) {
962        SDOperand ORNode = DAG.getNode(ISD::OR, LR.getValueType(), LL, RL);
963        AddToWorkList(ORNode.Val);
964        return DAG.getSetCC(VT, ORNode, LR, Op1);
965      }
966      // fold (X == -1) & (Y == -1) -> (X&Y == -1)
967      if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
968        SDOperand ANDNode = DAG.getNode(ISD::AND, LR.getValueType(), LL, RL);
969        AddToWorkList(ANDNode.Val);
970        return DAG.getSetCC(VT, ANDNode, LR, Op1);
971      }
972      // fold (X >  -1) & (Y >  -1) -> (X|Y > -1)
973      if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
974        SDOperand ORNode = DAG.getNode(ISD::OR, LR.getValueType(), LL, RL);
975        AddToWorkList(ORNode.Val);
976        return DAG.getSetCC(VT, ORNode, LR, Op1);
977      }
978    }
979    // canonicalize equivalent to ll == rl
980    if (LL == RR && LR == RL) {
981      Op1 = ISD::getSetCCSwappedOperands(Op1);
982      std::swap(RL, RR);
983    }
984    if (LL == RL && LR == RR) {
985      bool isInteger = MVT::isInteger(LL.getValueType());
986      ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
987      if (Result != ISD::SETCC_INVALID)
988        return DAG.getSetCC(N0.getValueType(), LL, LR, Result);
989    }
990  }
991
992  // Simplify: and (op x...), (op y...)  -> (op (and x, y))
993  if (N0.getOpcode() == N1.getOpcode()) {
994    SDOperand Tmp = SimplifyBinOpWithSameOpcodeHands(N);
995    if (Tmp.Val) return Tmp;
996  }
997
998  // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
999  // fold (and (sra)) -> (and (srl)) when possible.
1000  if (!MVT::isVector(VT) &&
1001      SimplifyDemandedBits(SDOperand(N, 0)))
1002    return SDOperand(N, 0);
1003  // fold (zext_inreg (extload x)) -> (zextload x)
1004  if (N0.getOpcode() == ISD::EXTLOAD) {
1005    MVT::ValueType EVT = cast<VTSDNode>(N0.getOperand(3))->getVT();
1006    // If we zero all the possible extended bits, then we can turn this into
1007    // a zextload if we are running before legalize or the operation is legal.
1008    if (TLI.MaskedValueIsZero(N1, ~0ULL << MVT::getSizeInBits(EVT)) &&
1009        (!AfterLegalize || TLI.isOperationLegal(ISD::ZEXTLOAD, EVT))) {
1010      SDOperand ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, VT, N0.getOperand(0),
1011                                         N0.getOperand(1), N0.getOperand(2),
1012                                         EVT);
1013      AddToWorkList(N);
1014      CombineTo(N0.Val, ExtLoad, ExtLoad.getValue(1));
1015      return SDOperand(N, 0);   // Return N so it doesn't get rechecked!
1016    }
1017  }
1018  // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
1019  if (N0.getOpcode() == ISD::SEXTLOAD && N0.hasOneUse()) {
1020    MVT::ValueType EVT = cast<VTSDNode>(N0.getOperand(3))->getVT();
1021    // If we zero all the possible extended bits, then we can turn this into
1022    // a zextload if we are running before legalize or the operation is legal.
1023    if (TLI.MaskedValueIsZero(N1, ~0ULL << MVT::getSizeInBits(EVT)) &&
1024        (!AfterLegalize || TLI.isOperationLegal(ISD::ZEXTLOAD, EVT))) {
1025      SDOperand ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, VT, N0.getOperand(0),
1026                                         N0.getOperand(1), N0.getOperand(2),
1027                                         EVT);
1028      AddToWorkList(N);
1029      CombineTo(N0.Val, ExtLoad, ExtLoad.getValue(1));
1030      return SDOperand(N, 0);   // Return N so it doesn't get rechecked!
1031    }
1032  }
1033
1034  // fold (and (load x), 255) -> (zextload x, i8)
1035  // fold (and (extload x, i16), 255) -> (zextload x, i8)
1036  if (N1C &&
1037      (N0.getOpcode() == ISD::LOAD || N0.getOpcode() == ISD::EXTLOAD ||
1038       N0.getOpcode() == ISD::ZEXTLOAD) &&
1039      N0.hasOneUse()) {
1040    MVT::ValueType EVT, LoadedVT;
1041    if (N1C->getValue() == 255)
1042      EVT = MVT::i8;
1043    else if (N1C->getValue() == 65535)
1044      EVT = MVT::i16;
1045    else if (N1C->getValue() == ~0U)
1046      EVT = MVT::i32;
1047    else
1048      EVT = MVT::Other;
1049
1050    LoadedVT = N0.getOpcode() == ISD::LOAD ? VT :
1051                           cast<VTSDNode>(N0.getOperand(3))->getVT();
1052    if (EVT != MVT::Other && LoadedVT > EVT &&
1053        (!AfterLegalize || TLI.isOperationLegal(ISD::ZEXTLOAD, EVT))) {
1054      MVT::ValueType PtrType = N0.getOperand(1).getValueType();
1055      // For big endian targets, we need to add an offset to the pointer to load
1056      // the correct bytes.  For little endian systems, we merely need to read
1057      // fewer bytes from the same pointer.
1058      unsigned PtrOff =
1059        (MVT::getSizeInBits(LoadedVT) - MVT::getSizeInBits(EVT)) / 8;
1060      SDOperand NewPtr = N0.getOperand(1);
1061      if (!TLI.isLittleEndian())
1062        NewPtr = DAG.getNode(ISD::ADD, PtrType, NewPtr,
1063                             DAG.getConstant(PtrOff, PtrType));
1064      AddToWorkList(NewPtr.Val);
1065      SDOperand Load =
1066        DAG.getExtLoad(ISD::ZEXTLOAD, VT, N0.getOperand(0), NewPtr,
1067                       N0.getOperand(2), EVT);
1068      AddToWorkList(N);
1069      CombineTo(N0.Val, Load, Load.getValue(1));
1070      return SDOperand(N, 0);   // Return N so it doesn't get rechecked!
1071    }
1072  }
1073
1074  return SDOperand();
1075}
1076
1077SDOperand DAGCombiner::visitOR(SDNode *N) {
1078  SDOperand N0 = N->getOperand(0);
1079  SDOperand N1 = N->getOperand(1);
1080  SDOperand LL, LR, RL, RR, CC0, CC1;
1081  ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1082  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1083  MVT::ValueType VT = N1.getValueType();
1084  unsigned OpSizeInBits = MVT::getSizeInBits(VT);
1085
1086  // fold (or c1, c2) -> c1|c2
1087  if (N0C && N1C)
1088    return DAG.getNode(ISD::OR, VT, N0, N1);
1089  // canonicalize constant to RHS
1090  if (N0C && !N1C)
1091    return DAG.getNode(ISD::OR, VT, N1, N0);
1092  // fold (or x, 0) -> x
1093  if (N1C && N1C->isNullValue())
1094    return N0;
1095  // fold (or x, -1) -> -1
1096  if (N1C && N1C->isAllOnesValue())
1097    return N1;
1098  // fold (or x, c) -> c iff (x & ~c) == 0
1099  if (N1C &&
1100      TLI.MaskedValueIsZero(N0,~N1C->getValue() & (~0ULL>>(64-OpSizeInBits))))
1101    return N1;
1102  // reassociate or
1103  SDOperand ROR = ReassociateOps(ISD::OR, N0, N1);
1104  if (ROR.Val != 0)
1105    return ROR;
1106  // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
1107  if (N1C && N0.getOpcode() == ISD::AND && N0.Val->hasOneUse() &&
1108             isa<ConstantSDNode>(N0.getOperand(1))) {
1109    ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
1110    return DAG.getNode(ISD::AND, VT, DAG.getNode(ISD::OR, VT, N0.getOperand(0),
1111                                                 N1),
1112                       DAG.getConstant(N1C->getValue() | C1->getValue(), VT));
1113  }
1114  // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
1115  if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
1116    ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
1117    ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
1118
1119    if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
1120        MVT::isInteger(LL.getValueType())) {
1121      // fold (X != 0) | (Y != 0) -> (X|Y != 0)
1122      // fold (X <  0) | (Y <  0) -> (X|Y < 0)
1123      if (cast<ConstantSDNode>(LR)->getValue() == 0 &&
1124          (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
1125        SDOperand ORNode = DAG.getNode(ISD::OR, LR.getValueType(), LL, RL);
1126        AddToWorkList(ORNode.Val);
1127        return DAG.getSetCC(VT, ORNode, LR, Op1);
1128      }
1129      // fold (X != -1) | (Y != -1) -> (X&Y != -1)
1130      // fold (X >  -1) | (Y >  -1) -> (X&Y >  -1)
1131      if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
1132          (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
1133        SDOperand ANDNode = DAG.getNode(ISD::AND, LR.getValueType(), LL, RL);
1134        AddToWorkList(ANDNode.Val);
1135        return DAG.getSetCC(VT, ANDNode, LR, Op1);
1136      }
1137    }
1138    // canonicalize equivalent to ll == rl
1139    if (LL == RR && LR == RL) {
1140      Op1 = ISD::getSetCCSwappedOperands(Op1);
1141      std::swap(RL, RR);
1142    }
1143    if (LL == RL && LR == RR) {
1144      bool isInteger = MVT::isInteger(LL.getValueType());
1145      ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
1146      if (Result != ISD::SETCC_INVALID)
1147        return DAG.getSetCC(N0.getValueType(), LL, LR, Result);
1148    }
1149  }
1150
1151  // Simplify: or (op x...), (op y...)  -> (op (or x, y))
1152  if (N0.getOpcode() == N1.getOpcode()) {
1153    SDOperand Tmp = SimplifyBinOpWithSameOpcodeHands(N);
1154    if (Tmp.Val) return Tmp;
1155  }
1156
1157  // (X & C1) | (Y & C2)  -> (X|Y) & C3  if possible.
1158  if (N0.getOpcode() == ISD::AND &&
1159      N1.getOpcode() == ISD::AND &&
1160      N0.getOperand(1).getOpcode() == ISD::Constant &&
1161      N1.getOperand(1).getOpcode() == ISD::Constant &&
1162      // Don't increase # computations.
1163      (N0.Val->hasOneUse() || N1.Val->hasOneUse())) {
1164    // We can only do this xform if we know that bits from X that are set in C2
1165    // but not in C1 are already zero.  Likewise for Y.
1166    uint64_t LHSMask = cast<ConstantSDNode>(N0.getOperand(1))->getValue();
1167    uint64_t RHSMask = cast<ConstantSDNode>(N1.getOperand(1))->getValue();
1168
1169    if (TLI.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
1170        TLI.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
1171      SDOperand X =DAG.getNode(ISD::OR, VT, N0.getOperand(0), N1.getOperand(0));
1172      return DAG.getNode(ISD::AND, VT, X, DAG.getConstant(LHSMask|RHSMask, VT));
1173    }
1174  }
1175
1176
1177  // See if this is some rotate idiom.
1178  if (SDNode *Rot = MatchRotate(N0, N1))
1179    return SDOperand(Rot, 0);
1180
1181  return SDOperand();
1182}
1183
1184
1185/// MatchRotateHalf - Match "(X shl/srl V1) & V2" where V2 may not be present.
1186static bool MatchRotateHalf(SDOperand Op, SDOperand &Shift, SDOperand &Mask) {
1187  if (Op.getOpcode() == ISD::AND) {
1188    if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1189      Mask = Op.getOperand(1);
1190      Op = Op.getOperand(0);
1191    } else {
1192      return false;
1193    }
1194  }
1195
1196  if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
1197    Shift = Op;
1198    return true;
1199  }
1200  return false;
1201}
1202
1203
1204// MatchRotate - Handle an 'or' of two operands.  If this is one of the many
1205// idioms for rotate, and if the target supports rotation instructions, generate
1206// a rot[lr].
1207SDNode *DAGCombiner::MatchRotate(SDOperand LHS, SDOperand RHS) {
1208  // Must be a legal type.  Expanded an promoted things won't work with rotates.
1209  MVT::ValueType VT = LHS.getValueType();
1210  if (!TLI.isTypeLegal(VT)) return 0;
1211
1212  // The target must have at least one rotate flavor.
1213  bool HasROTL = TLI.isOperationLegal(ISD::ROTL, VT);
1214  bool HasROTR = TLI.isOperationLegal(ISD::ROTR, VT);
1215  if (!HasROTL && !HasROTR) return 0;
1216
1217  // Match "(X shl/srl V1) & V2" where V2 may not be present.
1218  SDOperand LHSShift;   // The shift.
1219  SDOperand LHSMask;    // AND value if any.
1220  if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
1221    return 0; // Not part of a rotate.
1222
1223  SDOperand RHSShift;   // The shift.
1224  SDOperand RHSMask;    // AND value if any.
1225  if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
1226    return 0; // Not part of a rotate.
1227
1228  if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
1229    return 0;   // Not shifting the same value.
1230
1231  if (LHSShift.getOpcode() == RHSShift.getOpcode())
1232    return 0;   // Shifts must disagree.
1233
1234  // Canonicalize shl to left side in a shl/srl pair.
1235  if (RHSShift.getOpcode() == ISD::SHL) {
1236    std::swap(LHS, RHS);
1237    std::swap(LHSShift, RHSShift);
1238    std::swap(LHSMask , RHSMask );
1239  }
1240
1241  unsigned OpSizeInBits = MVT::getSizeInBits(VT);
1242
1243  // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
1244  // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
1245  if (LHSShift.getOperand(1).getOpcode() == ISD::Constant &&
1246      RHSShift.getOperand(1).getOpcode() == ISD::Constant) {
1247    uint64_t LShVal = cast<ConstantSDNode>(LHSShift.getOperand(1))->getValue();
1248    uint64_t RShVal = cast<ConstantSDNode>(RHSShift.getOperand(1))->getValue();
1249    if ((LShVal + RShVal) != OpSizeInBits)
1250      return 0;
1251
1252    SDOperand Rot;
1253    if (HasROTL)
1254      Rot = DAG.getNode(ISD::ROTL, VT, LHSShift.getOperand(0),
1255                        LHSShift.getOperand(1));
1256    else
1257      Rot = DAG.getNode(ISD::ROTR, VT, LHSShift.getOperand(0),
1258                        RHSShift.getOperand(1));
1259
1260    // If there is an AND of either shifted operand, apply it to the result.
1261    if (LHSMask.Val || RHSMask.Val) {
1262      uint64_t Mask = MVT::getIntVTBitMask(VT);
1263
1264      if (LHSMask.Val) {
1265        uint64_t RHSBits = (1ULL << LShVal)-1;
1266        Mask &= cast<ConstantSDNode>(LHSMask)->getValue() | RHSBits;
1267      }
1268      if (RHSMask.Val) {
1269        uint64_t LHSBits = ~((1ULL << (OpSizeInBits-RShVal))-1);
1270        Mask &= cast<ConstantSDNode>(RHSMask)->getValue() | LHSBits;
1271      }
1272
1273      Rot = DAG.getNode(ISD::AND, VT, Rot, DAG.getConstant(Mask, VT));
1274    }
1275
1276    return Rot.Val;
1277  }
1278
1279  // If there is a mask here, and we have a variable shift, we can't be sure
1280  // that we're masking out the right stuff.
1281  if (LHSMask.Val || RHSMask.Val)
1282    return 0;
1283
1284  // fold (or (shl x, y), (srl x, (sub 32, y))) -> (rotl x, y)
1285  // fold (or (shl x, y), (srl x, (sub 32, y))) -> (rotr x, (sub 32, y))
1286  if (RHSShift.getOperand(1).getOpcode() == ISD::SUB &&
1287      LHSShift.getOperand(1) == RHSShift.getOperand(1).getOperand(1)) {
1288    if (ConstantSDNode *SUBC =
1289          dyn_cast<ConstantSDNode>(RHSShift.getOperand(1).getOperand(0))) {
1290      if (SUBC->getValue() == OpSizeInBits)
1291        if (HasROTL)
1292          return DAG.getNode(ISD::ROTL, VT, LHSShift.getOperand(0),
1293                             LHSShift.getOperand(1)).Val;
1294        else
1295          return DAG.getNode(ISD::ROTR, VT, LHSShift.getOperand(0),
1296                             LHSShift.getOperand(1)).Val;
1297    }
1298  }
1299
1300  // fold (or (shl x, (sub 32, y)), (srl x, r)) -> (rotr x, y)
1301  // fold (or (shl x, (sub 32, y)), (srl x, r)) -> (rotl x, (sub 32, y))
1302  if (LHSShift.getOperand(1).getOpcode() == ISD::SUB &&
1303      RHSShift.getOperand(1) == LHSShift.getOperand(1).getOperand(1)) {
1304    if (ConstantSDNode *SUBC =
1305          dyn_cast<ConstantSDNode>(LHSShift.getOperand(1).getOperand(0))) {
1306      if (SUBC->getValue() == OpSizeInBits)
1307        if (HasROTL)
1308          return DAG.getNode(ISD::ROTL, VT, LHSShift.getOperand(0),
1309                             LHSShift.getOperand(1)).Val;
1310        else
1311          return DAG.getNode(ISD::ROTR, VT, LHSShift.getOperand(0),
1312                             RHSShift.getOperand(1)).Val;
1313    }
1314  }
1315
1316  return 0;
1317}
1318
1319
1320SDOperand DAGCombiner::visitXOR(SDNode *N) {
1321  SDOperand N0 = N->getOperand(0);
1322  SDOperand N1 = N->getOperand(1);
1323  SDOperand LHS, RHS, CC;
1324  ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1325  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1326  MVT::ValueType VT = N0.getValueType();
1327
1328  // fold (xor c1, c2) -> c1^c2
1329  if (N0C && N1C)
1330    return DAG.getNode(ISD::XOR, VT, N0, N1);
1331  // canonicalize constant to RHS
1332  if (N0C && !N1C)
1333    return DAG.getNode(ISD::XOR, VT, N1, N0);
1334  // fold (xor x, 0) -> x
1335  if (N1C && N1C->isNullValue())
1336    return N0;
1337  // reassociate xor
1338  SDOperand RXOR = ReassociateOps(ISD::XOR, N0, N1);
1339  if (RXOR.Val != 0)
1340    return RXOR;
1341  // fold !(x cc y) -> (x !cc y)
1342  if (N1C && N1C->getValue() == 1 && isSetCCEquivalent(N0, LHS, RHS, CC)) {
1343    bool isInt = MVT::isInteger(LHS.getValueType());
1344    ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
1345                                               isInt);
1346    if (N0.getOpcode() == ISD::SETCC)
1347      return DAG.getSetCC(VT, LHS, RHS, NotCC);
1348    if (N0.getOpcode() == ISD::SELECT_CC)
1349      return DAG.getSelectCC(LHS, RHS, N0.getOperand(2),N0.getOperand(3),NotCC);
1350    assert(0 && "Unhandled SetCC Equivalent!");
1351    abort();
1352  }
1353  // fold !(x or y) -> (!x and !y) iff x or y are setcc
1354  if (N1C && N1C->getValue() == 1 &&
1355      (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
1356    SDOperand LHS = N0.getOperand(0), RHS = N0.getOperand(1);
1357    if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
1358      unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
1359      LHS = DAG.getNode(ISD::XOR, VT, LHS, N1);  // RHS = ~LHS
1360      RHS = DAG.getNode(ISD::XOR, VT, RHS, N1);  // RHS = ~RHS
1361      AddToWorkList(LHS.Val); AddToWorkList(RHS.Val);
1362      return DAG.getNode(NewOpcode, VT, LHS, RHS);
1363    }
1364  }
1365  // fold !(x or y) -> (!x and !y) iff x or y are constants
1366  if (N1C && N1C->isAllOnesValue() &&
1367      (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
1368    SDOperand LHS = N0.getOperand(0), RHS = N0.getOperand(1);
1369    if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
1370      unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
1371      LHS = DAG.getNode(ISD::XOR, VT, LHS, N1);  // RHS = ~LHS
1372      RHS = DAG.getNode(ISD::XOR, VT, RHS, N1);  // RHS = ~RHS
1373      AddToWorkList(LHS.Val); AddToWorkList(RHS.Val);
1374      return DAG.getNode(NewOpcode, VT, LHS, RHS);
1375    }
1376  }
1377  // fold (xor (xor x, c1), c2) -> (xor x, c1^c2)
1378  if (N1C && N0.getOpcode() == ISD::XOR) {
1379    ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
1380    ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
1381    if (N00C)
1382      return DAG.getNode(ISD::XOR, VT, N0.getOperand(1),
1383                         DAG.getConstant(N1C->getValue()^N00C->getValue(), VT));
1384    if (N01C)
1385      return DAG.getNode(ISD::XOR, VT, N0.getOperand(0),
1386                         DAG.getConstant(N1C->getValue()^N01C->getValue(), VT));
1387  }
1388  // fold (xor x, x) -> 0
1389  if (N0 == N1) {
1390    if (!MVT::isVector(VT)) {
1391      return DAG.getConstant(0, VT);
1392    } else if (!AfterLegalize || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT)) {
1393      // Produce a vector of zeros.
1394      SDOperand El = DAG.getConstant(0, MVT::getVectorBaseType(VT));
1395      std::vector<SDOperand> Ops(MVT::getVectorNumElements(VT), El);
1396      return DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
1397    }
1398  }
1399
1400  // Simplify: xor (op x...), (op y...)  -> (op (xor x, y))
1401  if (N0.getOpcode() == N1.getOpcode()) {
1402    SDOperand Tmp = SimplifyBinOpWithSameOpcodeHands(N);
1403    if (Tmp.Val) return Tmp;
1404  }
1405
1406  // Simplify the expression using non-local knowledge.
1407  if (!MVT::isVector(VT) &&
1408      SimplifyDemandedBits(SDOperand(N, 0)))
1409    return SDOperand(N, 0);
1410
1411  return SDOperand();
1412}
1413
1414SDOperand DAGCombiner::visitSHL(SDNode *N) {
1415  SDOperand N0 = N->getOperand(0);
1416  SDOperand N1 = N->getOperand(1);
1417  ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1418  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1419  MVT::ValueType VT = N0.getValueType();
1420  unsigned OpSizeInBits = MVT::getSizeInBits(VT);
1421
1422  // fold (shl c1, c2) -> c1<<c2
1423  if (N0C && N1C)
1424    return DAG.getNode(ISD::SHL, VT, N0, N1);
1425  // fold (shl 0, x) -> 0
1426  if (N0C && N0C->isNullValue())
1427    return N0;
1428  // fold (shl x, c >= size(x)) -> undef
1429  if (N1C && N1C->getValue() >= OpSizeInBits)
1430    return DAG.getNode(ISD::UNDEF, VT);
1431  // fold (shl x, 0) -> x
1432  if (N1C && N1C->isNullValue())
1433    return N0;
1434  // if (shl x, c) is known to be zero, return 0
1435  if (TLI.MaskedValueIsZero(SDOperand(N, 0), MVT::getIntVTBitMask(VT)))
1436    return DAG.getConstant(0, VT);
1437  if (SimplifyDemandedBits(SDOperand(N, 0)))
1438    return SDOperand(N, 0);
1439  // fold (shl (shl x, c1), c2) -> 0 or (shl x, c1+c2)
1440  if (N1C && N0.getOpcode() == ISD::SHL &&
1441      N0.getOperand(1).getOpcode() == ISD::Constant) {
1442    uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getValue();
1443    uint64_t c2 = N1C->getValue();
1444    if (c1 + c2 > OpSizeInBits)
1445      return DAG.getConstant(0, VT);
1446    return DAG.getNode(ISD::SHL, VT, N0.getOperand(0),
1447                       DAG.getConstant(c1 + c2, N1.getValueType()));
1448  }
1449  // fold (shl (srl x, c1), c2) -> (shl (and x, -1 << c1), c2-c1) or
1450  //                               (srl (and x, -1 << c1), c1-c2)
1451  if (N1C && N0.getOpcode() == ISD::SRL &&
1452      N0.getOperand(1).getOpcode() == ISD::Constant) {
1453    uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getValue();
1454    uint64_t c2 = N1C->getValue();
1455    SDOperand Mask = DAG.getNode(ISD::AND, VT, N0.getOperand(0),
1456                                 DAG.getConstant(~0ULL << c1, VT));
1457    if (c2 > c1)
1458      return DAG.getNode(ISD::SHL, VT, Mask,
1459                         DAG.getConstant(c2-c1, N1.getValueType()));
1460    else
1461      return DAG.getNode(ISD::SRL, VT, Mask,
1462                         DAG.getConstant(c1-c2, N1.getValueType()));
1463  }
1464  // fold (shl (sra x, c1), c1) -> (and x, -1 << c1)
1465  if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1))
1466    return DAG.getNode(ISD::AND, VT, N0.getOperand(0),
1467                       DAG.getConstant(~0ULL << N1C->getValue(), VT));
1468  // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1<<c2)
1469  if (N1C && N0.getOpcode() == ISD::ADD && N0.Val->hasOneUse() &&
1470      isa<ConstantSDNode>(N0.getOperand(1))) {
1471    return DAG.getNode(ISD::ADD, VT,
1472                       DAG.getNode(ISD::SHL, VT, N0.getOperand(0), N1),
1473                       DAG.getNode(ISD::SHL, VT, N0.getOperand(1), N1));
1474  }
1475  return SDOperand();
1476}
1477
1478SDOperand DAGCombiner::visitSRA(SDNode *N) {
1479  SDOperand N0 = N->getOperand(0);
1480  SDOperand N1 = N->getOperand(1);
1481  ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1482  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1483  MVT::ValueType VT = N0.getValueType();
1484
1485  // fold (sra c1, c2) -> c1>>c2
1486  if (N0C && N1C)
1487    return DAG.getNode(ISD::SRA, VT, N0, N1);
1488  // fold (sra 0, x) -> 0
1489  if (N0C && N0C->isNullValue())
1490    return N0;
1491  // fold (sra -1, x) -> -1
1492  if (N0C && N0C->isAllOnesValue())
1493    return N0;
1494  // fold (sra x, c >= size(x)) -> undef
1495  if (N1C && N1C->getValue() >= MVT::getSizeInBits(VT))
1496    return DAG.getNode(ISD::UNDEF, VT);
1497  // fold (sra x, 0) -> x
1498  if (N1C && N1C->isNullValue())
1499    return N0;
1500  // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
1501  // sext_inreg.
1502  if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
1503    unsigned LowBits = MVT::getSizeInBits(VT) - (unsigned)N1C->getValue();
1504    MVT::ValueType EVT;
1505    switch (LowBits) {
1506    default: EVT = MVT::Other; break;
1507    case  1: EVT = MVT::i1;    break;
1508    case  8: EVT = MVT::i8;    break;
1509    case 16: EVT = MVT::i16;   break;
1510    case 32: EVT = MVT::i32;   break;
1511    }
1512    if (EVT > MVT::Other && TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, EVT))
1513      return DAG.getNode(ISD::SIGN_EXTEND_INREG, VT, N0.getOperand(0),
1514                         DAG.getValueType(EVT));
1515  }
1516
1517  // fold (sra (sra x, c1), c2) -> (sra x, c1+c2)
1518  if (N1C && N0.getOpcode() == ISD::SRA) {
1519    if (ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
1520      unsigned Sum = N1C->getValue() + C1->getValue();
1521      if (Sum >= MVT::getSizeInBits(VT)) Sum = MVT::getSizeInBits(VT)-1;
1522      return DAG.getNode(ISD::SRA, VT, N0.getOperand(0),
1523                         DAG.getConstant(Sum, N1C->getValueType(0)));
1524    }
1525  }
1526
1527  // Simplify, based on bits shifted out of the LHS.
1528  if (N1C && SimplifyDemandedBits(SDOperand(N, 0)))
1529    return SDOperand(N, 0);
1530
1531
1532  // If the sign bit is known to be zero, switch this to a SRL.
1533  if (TLI.MaskedValueIsZero(N0, MVT::getIntVTSignBit(VT)))
1534    return DAG.getNode(ISD::SRL, VT, N0, N1);
1535  return SDOperand();
1536}
1537
1538SDOperand DAGCombiner::visitSRL(SDNode *N) {
1539  SDOperand N0 = N->getOperand(0);
1540  SDOperand N1 = N->getOperand(1);
1541  ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1542  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1543  MVT::ValueType VT = N0.getValueType();
1544  unsigned OpSizeInBits = MVT::getSizeInBits(VT);
1545
1546  // fold (srl c1, c2) -> c1 >>u c2
1547  if (N0C && N1C)
1548    return DAG.getNode(ISD::SRL, VT, N0, N1);
1549  // fold (srl 0, x) -> 0
1550  if (N0C && N0C->isNullValue())
1551    return N0;
1552  // fold (srl x, c >= size(x)) -> undef
1553  if (N1C && N1C->getValue() >= OpSizeInBits)
1554    return DAG.getNode(ISD::UNDEF, VT);
1555  // fold (srl x, 0) -> x
1556  if (N1C && N1C->isNullValue())
1557    return N0;
1558  // if (srl x, c) is known to be zero, return 0
1559  if (N1C && TLI.MaskedValueIsZero(SDOperand(N, 0), ~0ULL >> (64-OpSizeInBits)))
1560    return DAG.getConstant(0, VT);
1561  // fold (srl (srl x, c1), c2) -> 0 or (srl x, c1+c2)
1562  if (N1C && N0.getOpcode() == ISD::SRL &&
1563      N0.getOperand(1).getOpcode() == ISD::Constant) {
1564    uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getValue();
1565    uint64_t c2 = N1C->getValue();
1566    if (c1 + c2 > OpSizeInBits)
1567      return DAG.getConstant(0, VT);
1568    return DAG.getNode(ISD::SRL, VT, N0.getOperand(0),
1569                       DAG.getConstant(c1 + c2, N1.getValueType()));
1570  }
1571
1572  // fold (srl (anyextend x), c) -> (anyextend (srl x, c))
1573  if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
1574    // Shifting in all undef bits?
1575    MVT::ValueType SmallVT = N0.getOperand(0).getValueType();
1576    if (N1C->getValue() >= MVT::getSizeInBits(SmallVT))
1577      return DAG.getNode(ISD::UNDEF, VT);
1578
1579    SDOperand SmallShift = DAG.getNode(ISD::SRL, SmallVT, N0.getOperand(0), N1);
1580    AddToWorkList(SmallShift.Val);
1581    return DAG.getNode(ISD::ANY_EXTEND, VT, SmallShift);
1582  }
1583
1584  // fold (srl (ctlz x), "5") -> x  iff x has one bit set (the low bit).
1585  if (N1C && N0.getOpcode() == ISD::CTLZ &&
1586      N1C->getValue() == Log2_32(MVT::getSizeInBits(VT))) {
1587    uint64_t KnownZero, KnownOne, Mask = MVT::getIntVTBitMask(VT);
1588    TLI.ComputeMaskedBits(N0.getOperand(0), Mask, KnownZero, KnownOne);
1589
1590    // If any of the input bits are KnownOne, then the input couldn't be all
1591    // zeros, thus the result of the srl will always be zero.
1592    if (KnownOne) return DAG.getConstant(0, VT);
1593
1594    // If all of the bits input the to ctlz node are known to be zero, then
1595    // the result of the ctlz is "32" and the result of the shift is one.
1596    uint64_t UnknownBits = ~KnownZero & Mask;
1597    if (UnknownBits == 0) return DAG.getConstant(1, VT);
1598
1599    // Otherwise, check to see if there is exactly one bit input to the ctlz.
1600    if ((UnknownBits & (UnknownBits-1)) == 0) {
1601      // Okay, we know that only that the single bit specified by UnknownBits
1602      // could be set on input to the CTLZ node.  If this bit is set, the SRL
1603      // will return 0, if it is clear, it returns 1.  Change the CTLZ/SRL pair
1604      // to an SRL,XOR pair, which is likely to simplify more.
1605      unsigned ShAmt = CountTrailingZeros_64(UnknownBits);
1606      SDOperand Op = N0.getOperand(0);
1607      if (ShAmt) {
1608        Op = DAG.getNode(ISD::SRL, VT, Op,
1609                         DAG.getConstant(ShAmt, TLI.getShiftAmountTy()));
1610        AddToWorkList(Op.Val);
1611      }
1612      return DAG.getNode(ISD::XOR, VT, Op, DAG.getConstant(1, VT));
1613    }
1614  }
1615
1616  return SDOperand();
1617}
1618
1619SDOperand DAGCombiner::visitCTLZ(SDNode *N) {
1620  SDOperand N0 = N->getOperand(0);
1621  MVT::ValueType VT = N->getValueType(0);
1622
1623  // fold (ctlz c1) -> c2
1624  if (isa<ConstantSDNode>(N0))
1625    return DAG.getNode(ISD::CTLZ, VT, N0);
1626  return SDOperand();
1627}
1628
1629SDOperand DAGCombiner::visitCTTZ(SDNode *N) {
1630  SDOperand N0 = N->getOperand(0);
1631  MVT::ValueType VT = N->getValueType(0);
1632
1633  // fold (cttz c1) -> c2
1634  if (isa<ConstantSDNode>(N0))
1635    return DAG.getNode(ISD::CTTZ, VT, N0);
1636  return SDOperand();
1637}
1638
1639SDOperand DAGCombiner::visitCTPOP(SDNode *N) {
1640  SDOperand N0 = N->getOperand(0);
1641  MVT::ValueType VT = N->getValueType(0);
1642
1643  // fold (ctpop c1) -> c2
1644  if (isa<ConstantSDNode>(N0))
1645    return DAG.getNode(ISD::CTPOP, VT, N0);
1646  return SDOperand();
1647}
1648
1649SDOperand DAGCombiner::visitSELECT(SDNode *N) {
1650  SDOperand N0 = N->getOperand(0);
1651  SDOperand N1 = N->getOperand(1);
1652  SDOperand N2 = N->getOperand(2);
1653  ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1654  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1655  ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
1656  MVT::ValueType VT = N->getValueType(0);
1657
1658  // fold select C, X, X -> X
1659  if (N1 == N2)
1660    return N1;
1661  // fold select true, X, Y -> X
1662  if (N0C && !N0C->isNullValue())
1663    return N1;
1664  // fold select false, X, Y -> Y
1665  if (N0C && N0C->isNullValue())
1666    return N2;
1667  // fold select C, 1, X -> C | X
1668  if (MVT::i1 == VT && N1C && N1C->getValue() == 1)
1669    return DAG.getNode(ISD::OR, VT, N0, N2);
1670  // fold select C, 0, X -> ~C & X
1671  // FIXME: this should check for C type == X type, not i1?
1672  if (MVT::i1 == VT && N1C && N1C->isNullValue()) {
1673    SDOperand XORNode = DAG.getNode(ISD::XOR, VT, N0, DAG.getConstant(1, VT));
1674    AddToWorkList(XORNode.Val);
1675    return DAG.getNode(ISD::AND, VT, XORNode, N2);
1676  }
1677  // fold select C, X, 1 -> ~C | X
1678  if (MVT::i1 == VT && N2C && N2C->getValue() == 1) {
1679    SDOperand XORNode = DAG.getNode(ISD::XOR, VT, N0, DAG.getConstant(1, VT));
1680    AddToWorkList(XORNode.Val);
1681    return DAG.getNode(ISD::OR, VT, XORNode, N1);
1682  }
1683  // fold select C, X, 0 -> C & X
1684  // FIXME: this should check for C type == X type, not i1?
1685  if (MVT::i1 == VT && N2C && N2C->isNullValue())
1686    return DAG.getNode(ISD::AND, VT, N0, N1);
1687  // fold  X ? X : Y --> X ? 1 : Y --> X | Y
1688  if (MVT::i1 == VT && N0 == N1)
1689    return DAG.getNode(ISD::OR, VT, N0, N2);
1690  // fold X ? Y : X --> X ? Y : 0 --> X & Y
1691  if (MVT::i1 == VT && N0 == N2)
1692    return DAG.getNode(ISD::AND, VT, N0, N1);
1693
1694  // If we can fold this based on the true/false value, do so.
1695  if (SimplifySelectOps(N, N1, N2))
1696    return SDOperand(N, 0);  // Don't revisit N.
1697
1698  // fold selects based on a setcc into other things, such as min/max/abs
1699  if (N0.getOpcode() == ISD::SETCC)
1700    // FIXME:
1701    // Check against MVT::Other for SELECT_CC, which is a workaround for targets
1702    // having to say they don't support SELECT_CC on every type the DAG knows
1703    // about, since there is no way to mark an opcode illegal at all value types
1704    if (TLI.isOperationLegal(ISD::SELECT_CC, MVT::Other))
1705      return DAG.getNode(ISD::SELECT_CC, VT, N0.getOperand(0), N0.getOperand(1),
1706                         N1, N2, N0.getOperand(2));
1707    else
1708      return SimplifySelect(N0, N1, N2);
1709  return SDOperand();
1710}
1711
1712SDOperand DAGCombiner::visitSELECT_CC(SDNode *N) {
1713  SDOperand N0 = N->getOperand(0);
1714  SDOperand N1 = N->getOperand(1);
1715  SDOperand N2 = N->getOperand(2);
1716  SDOperand N3 = N->getOperand(3);
1717  SDOperand N4 = N->getOperand(4);
1718  ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1719  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1720  ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
1721  ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
1722
1723  // fold select_cc lhs, rhs, x, x, cc -> x
1724  if (N2 == N3)
1725    return N2;
1726
1727  // Determine if the condition we're dealing with is constant
1728  SDOperand SCC = SimplifySetCC(TLI.getSetCCResultTy(), N0, N1, CC, false);
1729
1730  if (ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.Val)) {
1731    if (SCCC->getValue())
1732      return N2;    // cond always true -> true val
1733    else
1734      return N3;    // cond always false -> false val
1735  }
1736
1737  // Fold to a simpler select_cc
1738  if (SCC.Val && SCC.getOpcode() == ISD::SETCC)
1739    return DAG.getNode(ISD::SELECT_CC, N2.getValueType(),
1740                       SCC.getOperand(0), SCC.getOperand(1), N2, N3,
1741                       SCC.getOperand(2));
1742
1743  // If we can fold this based on the true/false value, do so.
1744  if (SimplifySelectOps(N, N2, N3))
1745    return SDOperand(N, 0);  // Don't revisit N.
1746
1747  // fold select_cc into other things, such as min/max/abs
1748  return SimplifySelectCC(N0, N1, N2, N3, CC);
1749}
1750
1751SDOperand DAGCombiner::visitSETCC(SDNode *N) {
1752  return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
1753                       cast<CondCodeSDNode>(N->getOperand(2))->get());
1754}
1755
1756SDOperand DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
1757  SDOperand N0 = N->getOperand(0);
1758  MVT::ValueType VT = N->getValueType(0);
1759
1760  // fold (sext c1) -> c1
1761  if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0))
1762    return DAG.getNode(ISD::SIGN_EXTEND, VT, N0);
1763
1764  // fold (sext (sext x)) -> (sext x)
1765  // fold (sext (aext x)) -> (sext x)
1766  if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
1767    return DAG.getNode(ISD::SIGN_EXTEND, VT, N0.getOperand(0));
1768
1769  // fold (sext (truncate x)) -> (sextinreg x) iff x size == sext size.
1770  if (N0.getOpcode() == ISD::TRUNCATE && N0.getOperand(0).getValueType() == VT&&
1771      (!AfterLegalize ||
1772       TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, N0.getValueType())))
1773    return DAG.getNode(ISD::SIGN_EXTEND_INREG, VT, N0.getOperand(0),
1774                       DAG.getValueType(N0.getValueType()));
1775
1776  // fold (sext (load x)) -> (sext (truncate (sextload x)))
1777  if (N0.getOpcode() == ISD::LOAD && N0.hasOneUse() &&
1778      (!AfterLegalize||TLI.isOperationLegal(ISD::SEXTLOAD, N0.getValueType()))){
1779    SDOperand ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, VT, N0.getOperand(0),
1780                                       N0.getOperand(1), N0.getOperand(2),
1781                                       N0.getValueType());
1782    CombineTo(N, ExtLoad);
1783    CombineTo(N0.Val, DAG.getNode(ISD::TRUNCATE, N0.getValueType(), ExtLoad),
1784              ExtLoad.getValue(1));
1785    return SDOperand(N, 0);   // Return N so it doesn't get rechecked!
1786  }
1787
1788  // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
1789  // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
1790  if ((N0.getOpcode() == ISD::SEXTLOAD || N0.getOpcode() == ISD::EXTLOAD) &&
1791      N0.hasOneUse()) {
1792    MVT::ValueType EVT = cast<VTSDNode>(N0.getOperand(3))->getVT();
1793    SDOperand ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, VT, N0.getOperand(0),
1794                                       N0.getOperand(1), N0.getOperand(2), EVT);
1795    CombineTo(N, ExtLoad);
1796    CombineTo(N0.Val, DAG.getNode(ISD::TRUNCATE, N0.getValueType(), ExtLoad),
1797              ExtLoad.getValue(1));
1798    return SDOperand(N, 0);   // Return N so it doesn't get rechecked!
1799  }
1800
1801  return SDOperand();
1802}
1803
1804SDOperand DAGCombiner::visitZERO_EXTEND(SDNode *N) {
1805  SDOperand N0 = N->getOperand(0);
1806  MVT::ValueType VT = N->getValueType(0);
1807
1808  // fold (zext c1) -> c1
1809  if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0))
1810    return DAG.getNode(ISD::ZERO_EXTEND, VT, N0);
1811  // fold (zext (zext x)) -> (zext x)
1812  // fold (zext (aext x)) -> (zext x)
1813  if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
1814    return DAG.getNode(ISD::ZERO_EXTEND, VT, N0.getOperand(0));
1815  // fold (zext (truncate x)) -> (zextinreg x) iff x size == zext size.
1816  if (N0.getOpcode() == ISD::TRUNCATE && N0.getOperand(0).getValueType() == VT&&
1817      (!AfterLegalize || TLI.isOperationLegal(ISD::AND, N0.getValueType())))
1818    return DAG.getZeroExtendInReg(N0.getOperand(0), N0.getValueType());
1819  // fold (zext (load x)) -> (zext (truncate (zextload x)))
1820  if (N0.getOpcode() == ISD::LOAD && N0.hasOneUse() &&
1821      (!AfterLegalize||TLI.isOperationLegal(ISD::ZEXTLOAD, N0.getValueType()))){
1822    SDOperand ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, VT, N0.getOperand(0),
1823                                       N0.getOperand(1), N0.getOperand(2),
1824                                       N0.getValueType());
1825    CombineTo(N, ExtLoad);
1826    CombineTo(N0.Val, DAG.getNode(ISD::TRUNCATE, N0.getValueType(), ExtLoad),
1827              ExtLoad.getValue(1));
1828    return SDOperand(N, 0);   // Return N so it doesn't get rechecked!
1829  }
1830
1831  // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
1832  // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
1833  if ((N0.getOpcode() == ISD::ZEXTLOAD || N0.getOpcode() == ISD::EXTLOAD) &&
1834      N0.hasOneUse()) {
1835    MVT::ValueType EVT = cast<VTSDNode>(N0.getOperand(3))->getVT();
1836    SDOperand ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, VT, N0.getOperand(0),
1837                                       N0.getOperand(1), N0.getOperand(2), EVT);
1838    CombineTo(N, ExtLoad);
1839    CombineTo(N0.Val, DAG.getNode(ISD::TRUNCATE, N0.getValueType(), ExtLoad),
1840              ExtLoad.getValue(1));
1841    return SDOperand(N, 0);   // Return N so it doesn't get rechecked!
1842  }
1843  return SDOperand();
1844}
1845
1846SDOperand DAGCombiner::visitANY_EXTEND(SDNode *N) {
1847  SDOperand N0 = N->getOperand(0);
1848  MVT::ValueType VT = N->getValueType(0);
1849
1850  // fold (aext c1) -> c1
1851  if (isa<ConstantSDNode>(N0))
1852    return DAG.getNode(ISD::ANY_EXTEND, VT, N0);
1853  // fold (aext (aext x)) -> (aext x)
1854  // fold (aext (zext x)) -> (zext x)
1855  // fold (aext (sext x)) -> (sext x)
1856  if (N0.getOpcode() == ISD::ANY_EXTEND  ||
1857      N0.getOpcode() == ISD::ZERO_EXTEND ||
1858      N0.getOpcode() == ISD::SIGN_EXTEND)
1859    return DAG.getNode(N0.getOpcode(), VT, N0.getOperand(0));
1860
1861  // fold (aext (truncate x))
1862  if (N0.getOpcode() == ISD::TRUNCATE) {
1863    SDOperand TruncOp = N0.getOperand(0);
1864    if (TruncOp.getValueType() == VT)
1865      return TruncOp; // x iff x size == zext size.
1866    if (TruncOp.getValueType() > VT)
1867      return DAG.getNode(ISD::TRUNCATE, VT, TruncOp);
1868    return DAG.getNode(ISD::ANY_EXTEND, VT, TruncOp);
1869  }
1870  // fold (aext (load x)) -> (aext (truncate (extload x)))
1871  if (N0.getOpcode() == ISD::LOAD && N0.hasOneUse() &&
1872      (!AfterLegalize||TLI.isOperationLegal(ISD::EXTLOAD, N0.getValueType()))) {
1873    SDOperand ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, VT, N0.getOperand(0),
1874                                       N0.getOperand(1), N0.getOperand(2),
1875                                       N0.getValueType());
1876    CombineTo(N, ExtLoad);
1877    CombineTo(N0.Val, DAG.getNode(ISD::TRUNCATE, N0.getValueType(), ExtLoad),
1878              ExtLoad.getValue(1));
1879    return SDOperand(N, 0);   // Return N so it doesn't get rechecked!
1880  }
1881
1882  // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
1883  // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
1884  // fold (aext ( extload x)) -> (aext (truncate (extload  x)))
1885  if ((N0.getOpcode() == ISD::ZEXTLOAD || N0.getOpcode() == ISD::EXTLOAD ||
1886       N0.getOpcode() == ISD::SEXTLOAD) &&
1887      N0.hasOneUse()) {
1888    MVT::ValueType EVT = cast<VTSDNode>(N0.getOperand(3))->getVT();
1889    SDOperand ExtLoad = DAG.getExtLoad(N0.getOpcode(), VT, N0.getOperand(0),
1890                                       N0.getOperand(1), N0.getOperand(2), EVT);
1891    CombineTo(N, ExtLoad);
1892    CombineTo(N0.Val, DAG.getNode(ISD::TRUNCATE, N0.getValueType(), ExtLoad),
1893              ExtLoad.getValue(1));
1894    return SDOperand(N, 0);   // Return N so it doesn't get rechecked!
1895  }
1896  return SDOperand();
1897}
1898
1899
1900SDOperand DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
1901  SDOperand N0 = N->getOperand(0);
1902  SDOperand N1 = N->getOperand(1);
1903  MVT::ValueType VT = N->getValueType(0);
1904  MVT::ValueType EVT = cast<VTSDNode>(N1)->getVT();
1905  unsigned EVTBits = MVT::getSizeInBits(EVT);
1906
1907  // fold (sext_in_reg c1) -> c1
1908  if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
1909    return DAG.getNode(ISD::SIGN_EXTEND_INREG, VT, N0, N1);
1910
1911  // If the input is already sign extended, just drop the extension.
1912  if (TLI.ComputeNumSignBits(N0) >= MVT::getSizeInBits(VT)-EVTBits+1)
1913    return N0;
1914
1915  // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
1916  if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
1917      EVT < cast<VTSDNode>(N0.getOperand(1))->getVT()) {
1918    return DAG.getNode(ISD::SIGN_EXTEND_INREG, VT, N0.getOperand(0), N1);
1919  }
1920
1921  // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is zero
1922  if (TLI.MaskedValueIsZero(N0, 1ULL << (EVTBits-1)))
1923    return DAG.getZeroExtendInReg(N0, EVT);
1924
1925  // fold (sext_in_reg (srl X, 24), i8) -> sra X, 24
1926  // fold (sext_in_reg (srl X, 23), i8) -> sra X, 23 iff possible.
1927  // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
1928  if (N0.getOpcode() == ISD::SRL) {
1929    if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
1930      if (ShAmt->getValue()+EVTBits <= MVT::getSizeInBits(VT)) {
1931        // We can turn this into an SRA iff the input to the SRL is already sign
1932        // extended enough.
1933        unsigned InSignBits = TLI.ComputeNumSignBits(N0.getOperand(0));
1934        if (MVT::getSizeInBits(VT)-(ShAmt->getValue()+EVTBits) < InSignBits)
1935          return DAG.getNode(ISD::SRA, VT, N0.getOperand(0), N0.getOperand(1));
1936      }
1937  }
1938
1939  // fold (sext_inreg (extload x)) -> (sextload x)
1940  if (N0.getOpcode() == ISD::EXTLOAD &&
1941      EVT == cast<VTSDNode>(N0.getOperand(3))->getVT() &&
1942      (!AfterLegalize || TLI.isOperationLegal(ISD::SEXTLOAD, EVT))) {
1943    SDOperand ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, VT, N0.getOperand(0),
1944                                       N0.getOperand(1), N0.getOperand(2),
1945                                       EVT);
1946    CombineTo(N, ExtLoad);
1947    CombineTo(N0.Val, ExtLoad, ExtLoad.getValue(1));
1948    return SDOperand(N, 0);   // Return N so it doesn't get rechecked!
1949  }
1950  // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
1951  if (N0.getOpcode() == ISD::ZEXTLOAD && N0.hasOneUse() &&
1952      EVT == cast<VTSDNode>(N0.getOperand(3))->getVT() &&
1953      (!AfterLegalize || TLI.isOperationLegal(ISD::SEXTLOAD, EVT))) {
1954    SDOperand ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, VT, N0.getOperand(0),
1955                                       N0.getOperand(1), N0.getOperand(2),
1956                                       EVT);
1957    CombineTo(N, ExtLoad);
1958    CombineTo(N0.Val, ExtLoad, ExtLoad.getValue(1));
1959    return SDOperand(N, 0);   // Return N so it doesn't get rechecked!
1960  }
1961  return SDOperand();
1962}
1963
1964SDOperand DAGCombiner::visitTRUNCATE(SDNode *N) {
1965  SDOperand N0 = N->getOperand(0);
1966  MVT::ValueType VT = N->getValueType(0);
1967
1968  // noop truncate
1969  if (N0.getValueType() == N->getValueType(0))
1970    return N0;
1971  // fold (truncate c1) -> c1
1972  if (isa<ConstantSDNode>(N0))
1973    return DAG.getNode(ISD::TRUNCATE, VT, N0);
1974  // fold (truncate (truncate x)) -> (truncate x)
1975  if (N0.getOpcode() == ISD::TRUNCATE)
1976    return DAG.getNode(ISD::TRUNCATE, VT, N0.getOperand(0));
1977  // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
1978  if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::SIGN_EXTEND||
1979      N0.getOpcode() == ISD::ANY_EXTEND) {
1980    if (N0.getValueType() < VT)
1981      // if the source is smaller than the dest, we still need an extend
1982      return DAG.getNode(N0.getOpcode(), VT, N0.getOperand(0));
1983    else if (N0.getValueType() > VT)
1984      // if the source is larger than the dest, than we just need the truncate
1985      return DAG.getNode(ISD::TRUNCATE, VT, N0.getOperand(0));
1986    else
1987      // if the source and dest are the same type, we can drop both the extend
1988      // and the truncate
1989      return N0.getOperand(0);
1990  }
1991  // fold (truncate (load x)) -> (smaller load x)
1992  if (N0.getOpcode() == ISD::LOAD && N0.hasOneUse()) {
1993    assert(MVT::getSizeInBits(N0.getValueType()) > MVT::getSizeInBits(VT) &&
1994           "Cannot truncate to larger type!");
1995    MVT::ValueType PtrType = N0.getOperand(1).getValueType();
1996    // For big endian targets, we need to add an offset to the pointer to load
1997    // the correct bytes.  For little endian systems, we merely need to read
1998    // fewer bytes from the same pointer.
1999    uint64_t PtrOff =
2000      (MVT::getSizeInBits(N0.getValueType()) - MVT::getSizeInBits(VT)) / 8;
2001    SDOperand NewPtr = TLI.isLittleEndian() ? N0.getOperand(1) :
2002      DAG.getNode(ISD::ADD, PtrType, N0.getOperand(1),
2003                  DAG.getConstant(PtrOff, PtrType));
2004    AddToWorkList(NewPtr.Val);
2005    SDOperand Load = DAG.getLoad(VT, N0.getOperand(0), NewPtr,N0.getOperand(2));
2006    AddToWorkList(N);
2007    CombineTo(N0.Val, Load, Load.getValue(1));
2008    return SDOperand(N, 0);   // Return N so it doesn't get rechecked!
2009  }
2010  return SDOperand();
2011}
2012
2013SDOperand DAGCombiner::visitBIT_CONVERT(SDNode *N) {
2014  SDOperand N0 = N->getOperand(0);
2015  MVT::ValueType VT = N->getValueType(0);
2016
2017  // If the input is a constant, let getNode() fold it.
2018  if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
2019    SDOperand Res = DAG.getNode(ISD::BIT_CONVERT, VT, N0);
2020    if (Res.Val != N) return Res;
2021  }
2022
2023  if (N0.getOpcode() == ISD::BIT_CONVERT)  // conv(conv(x,t1),t2) -> conv(x,t2)
2024    return DAG.getNode(ISD::BIT_CONVERT, VT, N0.getOperand(0));
2025
2026  // fold (conv (load x)) -> (load (conv*)x)
2027  // FIXME: These xforms need to know that the resultant load doesn't need a
2028  // higher alignment than the original!
2029  if (0 && N0.getOpcode() == ISD::LOAD && N0.hasOneUse()) {
2030    SDOperand Load = DAG.getLoad(VT, N0.getOperand(0), N0.getOperand(1),
2031                                 N0.getOperand(2));
2032    AddToWorkList(N);
2033    CombineTo(N0.Val, DAG.getNode(ISD::BIT_CONVERT, N0.getValueType(), Load),
2034              Load.getValue(1));
2035    return Load;
2036  }
2037
2038  return SDOperand();
2039}
2040
2041SDOperand DAGCombiner::visitVBIT_CONVERT(SDNode *N) {
2042  SDOperand N0 = N->getOperand(0);
2043  MVT::ValueType VT = N->getValueType(0);
2044
2045  // If the input is a VBUILD_VECTOR with all constant elements, fold this now.
2046  // First check to see if this is all constant.
2047  if (N0.getOpcode() == ISD::VBUILD_VECTOR && N0.Val->hasOneUse() &&
2048      VT == MVT::Vector) {
2049    bool isSimple = true;
2050    for (unsigned i = 0, e = N0.getNumOperands()-2; i != e; ++i)
2051      if (N0.getOperand(i).getOpcode() != ISD::UNDEF &&
2052          N0.getOperand(i).getOpcode() != ISD::Constant &&
2053          N0.getOperand(i).getOpcode() != ISD::ConstantFP) {
2054        isSimple = false;
2055        break;
2056      }
2057
2058    MVT::ValueType DestEltVT = cast<VTSDNode>(N->getOperand(2))->getVT();
2059    if (isSimple && !MVT::isVector(DestEltVT)) {
2060      return ConstantFoldVBIT_CONVERTofVBUILD_VECTOR(N0.Val, DestEltVT);
2061    }
2062  }
2063
2064  return SDOperand();
2065}
2066
2067/// ConstantFoldVBIT_CONVERTofVBUILD_VECTOR - We know that BV is a vbuild_vector
2068/// node with Constant, ConstantFP or Undef operands.  DstEltVT indicates the
2069/// destination element value type.
2070SDOperand DAGCombiner::
2071ConstantFoldVBIT_CONVERTofVBUILD_VECTOR(SDNode *BV, MVT::ValueType DstEltVT) {
2072  MVT::ValueType SrcEltVT = BV->getOperand(0).getValueType();
2073
2074  // If this is already the right type, we're done.
2075  if (SrcEltVT == DstEltVT) return SDOperand(BV, 0);
2076
2077  unsigned SrcBitSize = MVT::getSizeInBits(SrcEltVT);
2078  unsigned DstBitSize = MVT::getSizeInBits(DstEltVT);
2079
2080  // If this is a conversion of N elements of one type to N elements of another
2081  // type, convert each element.  This handles FP<->INT cases.
2082  if (SrcBitSize == DstBitSize) {
2083    SmallVector<SDOperand, 8> Ops;
2084    for (unsigned i = 0, e = BV->getNumOperands()-2; i != e; ++i) {
2085      Ops.push_back(DAG.getNode(ISD::BIT_CONVERT, DstEltVT, BV->getOperand(i)));
2086      AddToWorkList(Ops.back().Val);
2087    }
2088    Ops.push_back(*(BV->op_end()-2)); // Add num elements.
2089    Ops.push_back(DAG.getValueType(DstEltVT));
2090    return DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, &Ops[0], Ops.size());
2091  }
2092
2093  // Otherwise, we're growing or shrinking the elements.  To avoid having to
2094  // handle annoying details of growing/shrinking FP values, we convert them to
2095  // int first.
2096  if (MVT::isFloatingPoint(SrcEltVT)) {
2097    // Convert the input float vector to a int vector where the elements are the
2098    // same sizes.
2099    assert((SrcEltVT == MVT::f32 || SrcEltVT == MVT::f64) && "Unknown FP VT!");
2100    MVT::ValueType IntVT = SrcEltVT == MVT::f32 ? MVT::i32 : MVT::i64;
2101    BV = ConstantFoldVBIT_CONVERTofVBUILD_VECTOR(BV, IntVT).Val;
2102    SrcEltVT = IntVT;
2103  }
2104
2105  // Now we know the input is an integer vector.  If the output is a FP type,
2106  // convert to integer first, then to FP of the right size.
2107  if (MVT::isFloatingPoint(DstEltVT)) {
2108    assert((DstEltVT == MVT::f32 || DstEltVT == MVT::f64) && "Unknown FP VT!");
2109    MVT::ValueType TmpVT = DstEltVT == MVT::f32 ? MVT::i32 : MVT::i64;
2110    SDNode *Tmp = ConstantFoldVBIT_CONVERTofVBUILD_VECTOR(BV, TmpVT).Val;
2111
2112    // Next, convert to FP elements of the same size.
2113    return ConstantFoldVBIT_CONVERTofVBUILD_VECTOR(Tmp, DstEltVT);
2114  }
2115
2116  // Okay, we know the src/dst types are both integers of differing types.
2117  // Handling growing first.
2118  assert(MVT::isInteger(SrcEltVT) && MVT::isInteger(DstEltVT));
2119  if (SrcBitSize < DstBitSize) {
2120    unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
2121
2122    SmallVector<SDOperand, 8> Ops;
2123    for (unsigned i = 0, e = BV->getNumOperands()-2; i != e;
2124         i += NumInputsPerOutput) {
2125      bool isLE = TLI.isLittleEndian();
2126      uint64_t NewBits = 0;
2127      bool EltIsUndef = true;
2128      for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
2129        // Shift the previously computed bits over.
2130        NewBits <<= SrcBitSize;
2131        SDOperand Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
2132        if (Op.getOpcode() == ISD::UNDEF) continue;
2133        EltIsUndef = false;
2134
2135        NewBits |= cast<ConstantSDNode>(Op)->getValue();
2136      }
2137
2138      if (EltIsUndef)
2139        Ops.push_back(DAG.getNode(ISD::UNDEF, DstEltVT));
2140      else
2141        Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
2142    }
2143
2144    Ops.push_back(DAG.getConstant(Ops.size(), MVT::i32)); // Add num elements.
2145    Ops.push_back(DAG.getValueType(DstEltVT));            // Add element size.
2146    return DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, &Ops[0], Ops.size());
2147  }
2148
2149  // Finally, this must be the case where we are shrinking elements: each input
2150  // turns into multiple outputs.
2151  unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
2152  SmallVector<SDOperand, 8> Ops;
2153  for (unsigned i = 0, e = BV->getNumOperands()-2; i != e; ++i) {
2154    if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
2155      for (unsigned j = 0; j != NumOutputsPerInput; ++j)
2156        Ops.push_back(DAG.getNode(ISD::UNDEF, DstEltVT));
2157      continue;
2158    }
2159    uint64_t OpVal = cast<ConstantSDNode>(BV->getOperand(i))->getValue();
2160
2161    for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
2162      unsigned ThisVal = OpVal & ((1ULL << DstBitSize)-1);
2163      OpVal >>= DstBitSize;
2164      Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
2165    }
2166
2167    // For big endian targets, swap the order of the pieces of each element.
2168    if (!TLI.isLittleEndian())
2169      std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
2170  }
2171  Ops.push_back(DAG.getConstant(Ops.size(), MVT::i32)); // Add num elements.
2172  Ops.push_back(DAG.getValueType(DstEltVT));            // Add element size.
2173  return DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, &Ops[0], Ops.size());
2174}
2175
2176
2177
2178SDOperand DAGCombiner::visitFADD(SDNode *N) {
2179  SDOperand N0 = N->getOperand(0);
2180  SDOperand N1 = N->getOperand(1);
2181  ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
2182  ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
2183  MVT::ValueType VT = N->getValueType(0);
2184
2185  // fold (fadd c1, c2) -> c1+c2
2186  if (N0CFP && N1CFP)
2187    return DAG.getNode(ISD::FADD, VT, N0, N1);
2188  // canonicalize constant to RHS
2189  if (N0CFP && !N1CFP)
2190    return DAG.getNode(ISD::FADD, VT, N1, N0);
2191  // fold (A + (-B)) -> A-B
2192  if (N1.getOpcode() == ISD::FNEG)
2193    return DAG.getNode(ISD::FSUB, VT, N0, N1.getOperand(0));
2194  // fold ((-A) + B) -> B-A
2195  if (N0.getOpcode() == ISD::FNEG)
2196    return DAG.getNode(ISD::FSUB, VT, N1, N0.getOperand(0));
2197  return SDOperand();
2198}
2199
2200SDOperand DAGCombiner::visitFSUB(SDNode *N) {
2201  SDOperand N0 = N->getOperand(0);
2202  SDOperand N1 = N->getOperand(1);
2203  ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
2204  ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
2205  MVT::ValueType VT = N->getValueType(0);
2206
2207  // fold (fsub c1, c2) -> c1-c2
2208  if (N0CFP && N1CFP)
2209    return DAG.getNode(ISD::FSUB, VT, N0, N1);
2210  // fold (A-(-B)) -> A+B
2211  if (N1.getOpcode() == ISD::FNEG)
2212    return DAG.getNode(ISD::FADD, VT, N0, N1.getOperand(0));
2213  return SDOperand();
2214}
2215
2216SDOperand DAGCombiner::visitFMUL(SDNode *N) {
2217  SDOperand N0 = N->getOperand(0);
2218  SDOperand N1 = N->getOperand(1);
2219  ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
2220  ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
2221  MVT::ValueType VT = N->getValueType(0);
2222
2223  // fold (fmul c1, c2) -> c1*c2
2224  if (N0CFP && N1CFP)
2225    return DAG.getNode(ISD::FMUL, VT, N0, N1);
2226  // canonicalize constant to RHS
2227  if (N0CFP && !N1CFP)
2228    return DAG.getNode(ISD::FMUL, VT, N1, N0);
2229  // fold (fmul X, 2.0) -> (fadd X, X)
2230  if (N1CFP && N1CFP->isExactlyValue(+2.0))
2231    return DAG.getNode(ISD::FADD, VT, N0, N0);
2232  return SDOperand();
2233}
2234
2235SDOperand DAGCombiner::visitFDIV(SDNode *N) {
2236  SDOperand N0 = N->getOperand(0);
2237  SDOperand N1 = N->getOperand(1);
2238  ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
2239  ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
2240  MVT::ValueType VT = N->getValueType(0);
2241
2242  // fold (fdiv c1, c2) -> c1/c2
2243  if (N0CFP && N1CFP)
2244    return DAG.getNode(ISD::FDIV, VT, N0, N1);
2245  return SDOperand();
2246}
2247
2248SDOperand DAGCombiner::visitFREM(SDNode *N) {
2249  SDOperand N0 = N->getOperand(0);
2250  SDOperand N1 = N->getOperand(1);
2251  ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
2252  ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
2253  MVT::ValueType VT = N->getValueType(0);
2254
2255  // fold (frem c1, c2) -> fmod(c1,c2)
2256  if (N0CFP && N1CFP)
2257    return DAG.getNode(ISD::FREM, VT, N0, N1);
2258  return SDOperand();
2259}
2260
2261SDOperand DAGCombiner::visitFCOPYSIGN(SDNode *N) {
2262  SDOperand N0 = N->getOperand(0);
2263  SDOperand N1 = N->getOperand(1);
2264  ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
2265  ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
2266  MVT::ValueType VT = N->getValueType(0);
2267
2268  if (N0CFP && N1CFP)  // Constant fold
2269    return DAG.getNode(ISD::FCOPYSIGN, VT, N0, N1);
2270
2271  if (N1CFP) {
2272    // copysign(x, c1) -> fabs(x)       iff ispos(c1)
2273    // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
2274    union {
2275      double d;
2276      int64_t i;
2277    } u;
2278    u.d = N1CFP->getValue();
2279    if (u.i >= 0)
2280      return DAG.getNode(ISD::FABS, VT, N0);
2281    else
2282      return DAG.getNode(ISD::FNEG, VT, DAG.getNode(ISD::FABS, VT, N0));
2283  }
2284
2285  // copysign(fabs(x), y) -> copysign(x, y)
2286  // copysign(fneg(x), y) -> copysign(x, y)
2287  // copysign(copysign(x,z), y) -> copysign(x, y)
2288  if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
2289      N0.getOpcode() == ISD::FCOPYSIGN)
2290    return DAG.getNode(ISD::FCOPYSIGN, VT, N0.getOperand(0), N1);
2291
2292  // copysign(x, abs(y)) -> abs(x)
2293  if (N1.getOpcode() == ISD::FABS)
2294    return DAG.getNode(ISD::FABS, VT, N0);
2295
2296  // copysign(x, copysign(y,z)) -> copysign(x, z)
2297  if (N1.getOpcode() == ISD::FCOPYSIGN)
2298    return DAG.getNode(ISD::FCOPYSIGN, VT, N0, N1.getOperand(1));
2299
2300  // copysign(x, fp_extend(y)) -> copysign(x, y)
2301  // copysign(x, fp_round(y)) -> copysign(x, y)
2302  if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
2303    return DAG.getNode(ISD::FCOPYSIGN, VT, N0, N1.getOperand(0));
2304
2305  return SDOperand();
2306}
2307
2308
2309
2310SDOperand DAGCombiner::visitSINT_TO_FP(SDNode *N) {
2311  SDOperand N0 = N->getOperand(0);
2312  ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2313  MVT::ValueType VT = N->getValueType(0);
2314
2315  // fold (sint_to_fp c1) -> c1fp
2316  if (N0C)
2317    return DAG.getNode(ISD::SINT_TO_FP, VT, N0);
2318  return SDOperand();
2319}
2320
2321SDOperand DAGCombiner::visitUINT_TO_FP(SDNode *N) {
2322  SDOperand N0 = N->getOperand(0);
2323  ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2324  MVT::ValueType VT = N->getValueType(0);
2325
2326  // fold (uint_to_fp c1) -> c1fp
2327  if (N0C)
2328    return DAG.getNode(ISD::UINT_TO_FP, VT, N0);
2329  return SDOperand();
2330}
2331
2332SDOperand DAGCombiner::visitFP_TO_SINT(SDNode *N) {
2333  SDOperand N0 = N->getOperand(0);
2334  ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
2335  MVT::ValueType VT = N->getValueType(0);
2336
2337  // fold (fp_to_sint c1fp) -> c1
2338  if (N0CFP)
2339    return DAG.getNode(ISD::FP_TO_SINT, VT, N0);
2340  return SDOperand();
2341}
2342
2343SDOperand DAGCombiner::visitFP_TO_UINT(SDNode *N) {
2344  SDOperand N0 = N->getOperand(0);
2345  ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
2346  MVT::ValueType VT = N->getValueType(0);
2347
2348  // fold (fp_to_uint c1fp) -> c1
2349  if (N0CFP)
2350    return DAG.getNode(ISD::FP_TO_UINT, VT, N0);
2351  return SDOperand();
2352}
2353
2354SDOperand DAGCombiner::visitFP_ROUND(SDNode *N) {
2355  SDOperand N0 = N->getOperand(0);
2356  ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
2357  MVT::ValueType VT = N->getValueType(0);
2358
2359  // fold (fp_round c1fp) -> c1fp
2360  if (N0CFP)
2361    return DAG.getNode(ISD::FP_ROUND, VT, N0);
2362
2363  // fold (fp_round (fp_extend x)) -> x
2364  if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
2365    return N0.getOperand(0);
2366
2367  // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
2368  if (N0.getOpcode() == ISD::FCOPYSIGN && N0.Val->hasOneUse()) {
2369    SDOperand Tmp = DAG.getNode(ISD::FP_ROUND, VT, N0.getOperand(0));
2370    AddToWorkList(Tmp.Val);
2371    return DAG.getNode(ISD::FCOPYSIGN, VT, Tmp, N0.getOperand(1));
2372  }
2373
2374  return SDOperand();
2375}
2376
2377SDOperand DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
2378  SDOperand N0 = N->getOperand(0);
2379  MVT::ValueType VT = N->getValueType(0);
2380  MVT::ValueType EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
2381  ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
2382
2383  // fold (fp_round_inreg c1fp) -> c1fp
2384  if (N0CFP) {
2385    SDOperand Round = DAG.getConstantFP(N0CFP->getValue(), EVT);
2386    return DAG.getNode(ISD::FP_EXTEND, VT, Round);
2387  }
2388  return SDOperand();
2389}
2390
2391SDOperand DAGCombiner::visitFP_EXTEND(SDNode *N) {
2392  SDOperand N0 = N->getOperand(0);
2393  ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
2394  MVT::ValueType VT = N->getValueType(0);
2395
2396  // fold (fp_extend c1fp) -> c1fp
2397  if (N0CFP)
2398    return DAG.getNode(ISD::FP_EXTEND, VT, N0);
2399
2400  // fold (fpext (load x)) -> (fpext (fpround (extload x)))
2401  if (N0.getOpcode() == ISD::LOAD && N0.hasOneUse() &&
2402      (!AfterLegalize||TLI.isOperationLegal(ISD::EXTLOAD, N0.getValueType()))) {
2403    SDOperand ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, VT, N0.getOperand(0),
2404                                       N0.getOperand(1), N0.getOperand(2),
2405                                       N0.getValueType());
2406    CombineTo(N, ExtLoad);
2407    CombineTo(N0.Val, DAG.getNode(ISD::FP_ROUND, N0.getValueType(), ExtLoad),
2408              ExtLoad.getValue(1));
2409    return SDOperand(N, 0);   // Return N so it doesn't get rechecked!
2410  }
2411
2412
2413  return SDOperand();
2414}
2415
2416SDOperand DAGCombiner::visitFNEG(SDNode *N) {
2417  SDOperand N0 = N->getOperand(0);
2418  ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
2419  MVT::ValueType VT = N->getValueType(0);
2420
2421  // fold (fneg c1) -> -c1
2422  if (N0CFP)
2423    return DAG.getNode(ISD::FNEG, VT, N0);
2424  // fold (fneg (sub x, y)) -> (sub y, x)
2425  if (N0.getOpcode() == ISD::SUB)
2426    return DAG.getNode(ISD::SUB, VT, N0.getOperand(1), N0.getOperand(0));
2427  // fold (fneg (fneg x)) -> x
2428  if (N0.getOpcode() == ISD::FNEG)
2429    return N0.getOperand(0);
2430  return SDOperand();
2431}
2432
2433SDOperand DAGCombiner::visitFABS(SDNode *N) {
2434  SDOperand N0 = N->getOperand(0);
2435  ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
2436  MVT::ValueType VT = N->getValueType(0);
2437
2438  // fold (fabs c1) -> fabs(c1)
2439  if (N0CFP)
2440    return DAG.getNode(ISD::FABS, VT, N0);
2441  // fold (fabs (fabs x)) -> (fabs x)
2442  if (N0.getOpcode() == ISD::FABS)
2443    return N->getOperand(0);
2444  // fold (fabs (fneg x)) -> (fabs x)
2445  // fold (fabs (fcopysign x, y)) -> (fabs x)
2446  if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
2447    return DAG.getNode(ISD::FABS, VT, N0.getOperand(0));
2448
2449  return SDOperand();
2450}
2451
2452SDOperand DAGCombiner::visitBRCOND(SDNode *N) {
2453  SDOperand Chain = N->getOperand(0);
2454  SDOperand N1 = N->getOperand(1);
2455  SDOperand N2 = N->getOperand(2);
2456  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2457
2458  // never taken branch, fold to chain
2459  if (N1C && N1C->isNullValue())
2460    return Chain;
2461  // unconditional branch
2462  if (N1C && N1C->getValue() == 1)
2463    return DAG.getNode(ISD::BR, MVT::Other, Chain, N2);
2464  // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
2465  // on the target.
2466  if (N1.getOpcode() == ISD::SETCC &&
2467      TLI.isOperationLegal(ISD::BR_CC, MVT::Other)) {
2468    return DAG.getNode(ISD::BR_CC, MVT::Other, Chain, N1.getOperand(2),
2469                       N1.getOperand(0), N1.getOperand(1), N2);
2470  }
2471  return SDOperand();
2472}
2473
2474// Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
2475//
2476SDOperand DAGCombiner::visitBR_CC(SDNode *N) {
2477  CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
2478  SDOperand CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
2479
2480  // Use SimplifySetCC  to simplify SETCC's.
2481  SDOperand Simp = SimplifySetCC(MVT::i1, CondLHS, CondRHS, CC->get(), false);
2482  ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(Simp.Val);
2483
2484  // fold br_cc true, dest -> br dest (unconditional branch)
2485  if (SCCC && SCCC->getValue())
2486    return DAG.getNode(ISD::BR, MVT::Other, N->getOperand(0),
2487                       N->getOperand(4));
2488  // fold br_cc false, dest -> unconditional fall through
2489  if (SCCC && SCCC->isNullValue())
2490    return N->getOperand(0);
2491  // fold to a simpler setcc
2492  if (Simp.Val && Simp.getOpcode() == ISD::SETCC)
2493    return DAG.getNode(ISD::BR_CC, MVT::Other, N->getOperand(0),
2494                       Simp.getOperand(2), Simp.getOperand(0),
2495                       Simp.getOperand(1), N->getOperand(4));
2496  return SDOperand();
2497}
2498
2499SDOperand DAGCombiner::visitLOAD(SDNode *N) {
2500  SDOperand Chain    = N->getOperand(0);
2501  SDOperand Ptr      = N->getOperand(1);
2502  SDOperand SrcValue = N->getOperand(2);
2503
2504  // If there are no uses of the loaded value, change uses of the chain value
2505  // into uses of the chain input (i.e. delete the dead load).
2506  if (N->hasNUsesOfValue(0, 0))
2507    return CombineTo(N, DAG.getNode(ISD::UNDEF, N->getValueType(0)), Chain);
2508
2509  // If this load is directly stored, replace the load value with the stored
2510  // value.
2511  // TODO: Handle store large -> read small portion.
2512  // TODO: Handle TRUNCSTORE/EXTLOAD
2513  if (Chain.getOpcode() == ISD::STORE && Chain.getOperand(2) == Ptr &&
2514      Chain.getOperand(1).getValueType() == N->getValueType(0))
2515    return CombineTo(N, Chain.getOperand(1), Chain);
2516
2517  return SDOperand();
2518}
2519
2520/// visitXEXTLOAD - Handle EXTLOAD/ZEXTLOAD/SEXTLOAD.
2521SDOperand DAGCombiner::visitXEXTLOAD(SDNode *N) {
2522  SDOperand Chain    = N->getOperand(0);
2523  SDOperand Ptr      = N->getOperand(1);
2524  SDOperand SrcValue = N->getOperand(2);
2525  SDOperand EVT      = N->getOperand(3);
2526
2527  // If there are no uses of the loaded value, change uses of the chain value
2528  // into uses of the chain input (i.e. delete the dead load).
2529  if (N->hasNUsesOfValue(0, 0))
2530    return CombineTo(N, DAG.getNode(ISD::UNDEF, N->getValueType(0)), Chain);
2531
2532  return SDOperand();
2533}
2534
2535SDOperand DAGCombiner::visitSTORE(SDNode *N) {
2536  SDOperand Chain    = N->getOperand(0);
2537  SDOperand Value    = N->getOperand(1);
2538  SDOperand Ptr      = N->getOperand(2);
2539  SDOperand SrcValue = N->getOperand(3);
2540
2541  // If this is a store that kills a previous store, remove the previous store.
2542  if (Chain.getOpcode() == ISD::STORE && Chain.getOperand(2) == Ptr &&
2543      Chain.Val->hasOneUse() /* Avoid introducing DAG cycles */ &&
2544      // Make sure that these stores are the same value type:
2545      // FIXME: we really care that the second store is >= size of the first.
2546      Value.getValueType() == Chain.getOperand(1).getValueType()) {
2547    // Create a new store of Value that replaces both stores.
2548    SDNode *PrevStore = Chain.Val;
2549    if (PrevStore->getOperand(1) == Value) // Same value multiply stored.
2550      return Chain;
2551    SDOperand NewStore = DAG.getNode(ISD::STORE, MVT::Other,
2552                                     PrevStore->getOperand(0), Value, Ptr,
2553                                     SrcValue);
2554    CombineTo(N, NewStore);                 // Nuke this store.
2555    CombineTo(PrevStore, NewStore);  // Nuke the previous store.
2556    return SDOperand(N, 0);
2557  }
2558
2559  // If this is a store of a bit convert, store the input value.
2560  // FIXME: This needs to know that the resultant store does not need a
2561  // higher alignment than the original.
2562  if (0 && Value.getOpcode() == ISD::BIT_CONVERT)
2563    return DAG.getNode(ISD::STORE, MVT::Other, Chain, Value.getOperand(0),
2564                       Ptr, SrcValue);
2565
2566  return SDOperand();
2567}
2568
2569SDOperand DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
2570  SDOperand InVec = N->getOperand(0);
2571  SDOperand InVal = N->getOperand(1);
2572  SDOperand EltNo = N->getOperand(2);
2573
2574  // If the invec is a BUILD_VECTOR and if EltNo is a constant, build a new
2575  // vector with the inserted element.
2576  if (InVec.getOpcode() == ISD::BUILD_VECTOR && isa<ConstantSDNode>(EltNo)) {
2577    unsigned Elt = cast<ConstantSDNode>(EltNo)->getValue();
2578    SmallVector<SDOperand, 8> Ops(InVec.Val->op_begin(), InVec.Val->op_end());
2579    if (Elt < Ops.size())
2580      Ops[Elt] = InVal;
2581    return DAG.getNode(ISD::BUILD_VECTOR, InVec.getValueType(),
2582                       &Ops[0], Ops.size());
2583  }
2584
2585  return SDOperand();
2586}
2587
2588SDOperand DAGCombiner::visitVINSERT_VECTOR_ELT(SDNode *N) {
2589  SDOperand InVec = N->getOperand(0);
2590  SDOperand InVal = N->getOperand(1);
2591  SDOperand EltNo = N->getOperand(2);
2592  SDOperand NumElts = N->getOperand(3);
2593  SDOperand EltType = N->getOperand(4);
2594
2595  // If the invec is a VBUILD_VECTOR and if EltNo is a constant, build a new
2596  // vector with the inserted element.
2597  if (InVec.getOpcode() == ISD::VBUILD_VECTOR && isa<ConstantSDNode>(EltNo)) {
2598    unsigned Elt = cast<ConstantSDNode>(EltNo)->getValue();
2599    SmallVector<SDOperand, 8> Ops(InVec.Val->op_begin(), InVec.Val->op_end());
2600    if (Elt < Ops.size()-2)
2601      Ops[Elt] = InVal;
2602    return DAG.getNode(ISD::VBUILD_VECTOR, InVec.getValueType(),
2603                       &Ops[0], Ops.size());
2604  }
2605
2606  return SDOperand();
2607}
2608
2609SDOperand DAGCombiner::visitVBUILD_VECTOR(SDNode *N) {
2610  unsigned NumInScalars = N->getNumOperands()-2;
2611  SDOperand NumElts = N->getOperand(NumInScalars);
2612  SDOperand EltType = N->getOperand(NumInScalars+1);
2613
2614  // Check to see if this is a VBUILD_VECTOR of a bunch of VEXTRACT_VECTOR_ELT
2615  // operations.  If so, and if the EXTRACT_ELT vector inputs come from at most
2616  // two distinct vectors, turn this into a shuffle node.
2617  SDOperand VecIn1, VecIn2;
2618  for (unsigned i = 0; i != NumInScalars; ++i) {
2619    // Ignore undef inputs.
2620    if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
2621
2622    // If this input is something other than a VEXTRACT_VECTOR_ELT with a
2623    // constant index, bail out.
2624    if (N->getOperand(i).getOpcode() != ISD::VEXTRACT_VECTOR_ELT ||
2625        !isa<ConstantSDNode>(N->getOperand(i).getOperand(1))) {
2626      VecIn1 = VecIn2 = SDOperand(0, 0);
2627      break;
2628    }
2629
2630    // If the input vector type disagrees with the result of the vbuild_vector,
2631    // we can't make a shuffle.
2632    SDOperand ExtractedFromVec = N->getOperand(i).getOperand(0);
2633    if (*(ExtractedFromVec.Val->op_end()-2) != NumElts ||
2634        *(ExtractedFromVec.Val->op_end()-1) != EltType) {
2635      VecIn1 = VecIn2 = SDOperand(0, 0);
2636      break;
2637    }
2638
2639    // Otherwise, remember this.  We allow up to two distinct input vectors.
2640    if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
2641      continue;
2642
2643    if (VecIn1.Val == 0) {
2644      VecIn1 = ExtractedFromVec;
2645    } else if (VecIn2.Val == 0) {
2646      VecIn2 = ExtractedFromVec;
2647    } else {
2648      // Too many inputs.
2649      VecIn1 = VecIn2 = SDOperand(0, 0);
2650      break;
2651    }
2652  }
2653
2654  // If everything is good, we can make a shuffle operation.
2655  if (VecIn1.Val) {
2656    SmallVector<SDOperand, 8> BuildVecIndices;
2657    for (unsigned i = 0; i != NumInScalars; ++i) {
2658      if (N->getOperand(i).getOpcode() == ISD::UNDEF) {
2659        BuildVecIndices.push_back(DAG.getNode(ISD::UNDEF, MVT::i32));
2660        continue;
2661      }
2662
2663      SDOperand Extract = N->getOperand(i);
2664
2665      // If extracting from the first vector, just use the index directly.
2666      if (Extract.getOperand(0) == VecIn1) {
2667        BuildVecIndices.push_back(Extract.getOperand(1));
2668        continue;
2669      }
2670
2671      // Otherwise, use InIdx + VecSize
2672      unsigned Idx = cast<ConstantSDNode>(Extract.getOperand(1))->getValue();
2673      BuildVecIndices.push_back(DAG.getConstant(Idx+NumInScalars, MVT::i32));
2674    }
2675
2676    // Add count and size info.
2677    BuildVecIndices.push_back(NumElts);
2678    BuildVecIndices.push_back(DAG.getValueType(MVT::i32));
2679
2680    // Return the new VVECTOR_SHUFFLE node.
2681    SDOperand Ops[5];
2682    Ops[0] = VecIn1;
2683    if (VecIn2.Val) {
2684      Ops[1] = VecIn2;
2685    } else {
2686       // Use an undef vbuild_vector as input for the second operand.
2687      std::vector<SDOperand> UnOps(NumInScalars,
2688                                   DAG.getNode(ISD::UNDEF,
2689                                           cast<VTSDNode>(EltType)->getVT()));
2690      UnOps.push_back(NumElts);
2691      UnOps.push_back(EltType);
2692      Ops[1] = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector,
2693                           &UnOps[0], UnOps.size());
2694      AddToWorkList(Ops[1].Val);
2695    }
2696    Ops[2] = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector,
2697                         &BuildVecIndices[0], BuildVecIndices.size());
2698    Ops[3] = NumElts;
2699    Ops[4] = EltType;
2700    return DAG.getNode(ISD::VVECTOR_SHUFFLE, MVT::Vector, Ops, 5);
2701  }
2702
2703  return SDOperand();
2704}
2705
2706SDOperand DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
2707  SDOperand ShufMask = N->getOperand(2);
2708  unsigned NumElts = ShufMask.getNumOperands();
2709
2710  // If the shuffle mask is an identity operation on the LHS, return the LHS.
2711  bool isIdentity = true;
2712  for (unsigned i = 0; i != NumElts; ++i) {
2713    if (ShufMask.getOperand(i).getOpcode() != ISD::UNDEF &&
2714        cast<ConstantSDNode>(ShufMask.getOperand(i))->getValue() != i) {
2715      isIdentity = false;
2716      break;
2717    }
2718  }
2719  if (isIdentity) return N->getOperand(0);
2720
2721  // If the shuffle mask is an identity operation on the RHS, return the RHS.
2722  isIdentity = true;
2723  for (unsigned i = 0; i != NumElts; ++i) {
2724    if (ShufMask.getOperand(i).getOpcode() != ISD::UNDEF &&
2725        cast<ConstantSDNode>(ShufMask.getOperand(i))->getValue() != i+NumElts) {
2726      isIdentity = false;
2727      break;
2728    }
2729  }
2730  if (isIdentity) return N->getOperand(1);
2731
2732  // Check if the shuffle is a unary shuffle, i.e. one of the vectors is not
2733  // needed at all.
2734  bool isUnary = true;
2735  bool isSplat = true;
2736  int VecNum = -1;
2737  unsigned BaseIdx = 0;
2738  for (unsigned i = 0; i != NumElts; ++i)
2739    if (ShufMask.getOperand(i).getOpcode() != ISD::UNDEF) {
2740      unsigned Idx = cast<ConstantSDNode>(ShufMask.getOperand(i))->getValue();
2741      int V = (Idx < NumElts) ? 0 : 1;
2742      if (VecNum == -1) {
2743        VecNum = V;
2744        BaseIdx = Idx;
2745      } else {
2746        if (BaseIdx != Idx)
2747          isSplat = false;
2748        if (VecNum != V) {
2749          isUnary = false;
2750          break;
2751        }
2752      }
2753    }
2754
2755  SDOperand N0 = N->getOperand(0);
2756  SDOperand N1 = N->getOperand(1);
2757  // Normalize unary shuffle so the RHS is undef.
2758  if (isUnary && VecNum == 1)
2759    std::swap(N0, N1);
2760
2761  // If it is a splat, check if the argument vector is a build_vector with
2762  // all scalar elements the same.
2763  if (isSplat) {
2764    SDNode *V = N0.Val;
2765    if (V->getOpcode() == ISD::BIT_CONVERT)
2766      V = V->getOperand(0).Val;
2767    if (V->getOpcode() == ISD::BUILD_VECTOR) {
2768      unsigned NumElems = V->getNumOperands()-2;
2769      if (NumElems > BaseIdx) {
2770        SDOperand Base;
2771        bool AllSame = true;
2772        for (unsigned i = 0; i != NumElems; ++i) {
2773          if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
2774            Base = V->getOperand(i);
2775            break;
2776          }
2777        }
2778        // Splat of <u, u, u, u>, return <u, u, u, u>
2779        if (!Base.Val)
2780          return N0;
2781        for (unsigned i = 0; i != NumElems; ++i) {
2782          if (V->getOperand(i).getOpcode() != ISD::UNDEF &&
2783              V->getOperand(i) != Base) {
2784            AllSame = false;
2785            break;
2786          }
2787        }
2788        // Splat of <x, x, x, x>, return <x, x, x, x>
2789        if (AllSame)
2790          return N0;
2791      }
2792    }
2793  }
2794
2795  // If it is a unary or the LHS and the RHS are the same node, turn the RHS
2796  // into an undef.
2797  if (isUnary || N0 == N1) {
2798    if (N0.getOpcode() == ISD::UNDEF)
2799      return DAG.getNode(ISD::UNDEF, N->getValueType(0));
2800    // Check the SHUFFLE mask, mapping any inputs from the 2nd operand into the
2801    // first operand.
2802    SmallVector<SDOperand, 8> MappedOps;
2803    for (unsigned i = 0, e = ShufMask.getNumOperands(); i != e; ++i) {
2804      if (ShufMask.getOperand(i).getOpcode() == ISD::UNDEF ||
2805          cast<ConstantSDNode>(ShufMask.getOperand(i))->getValue() < NumElts) {
2806        MappedOps.push_back(ShufMask.getOperand(i));
2807      } else {
2808        unsigned NewIdx =
2809           cast<ConstantSDNode>(ShufMask.getOperand(i))->getValue() - NumElts;
2810        MappedOps.push_back(DAG.getConstant(NewIdx, MVT::i32));
2811      }
2812    }
2813    ShufMask = DAG.getNode(ISD::BUILD_VECTOR, ShufMask.getValueType(),
2814                           &MappedOps[0], MappedOps.size());
2815    AddToWorkList(ShufMask.Val);
2816    return DAG.getNode(ISD::VECTOR_SHUFFLE, N->getValueType(0),
2817                       N0,
2818                       DAG.getNode(ISD::UNDEF, N->getValueType(0)),
2819                       ShufMask);
2820  }
2821
2822  return SDOperand();
2823}
2824
2825SDOperand DAGCombiner::visitVVECTOR_SHUFFLE(SDNode *N) {
2826  SDOperand ShufMask = N->getOperand(2);
2827  unsigned NumElts = ShufMask.getNumOperands()-2;
2828
2829  // If the shuffle mask is an identity operation on the LHS, return the LHS.
2830  bool isIdentity = true;
2831  for (unsigned i = 0; i != NumElts; ++i) {
2832    if (ShufMask.getOperand(i).getOpcode() != ISD::UNDEF &&
2833        cast<ConstantSDNode>(ShufMask.getOperand(i))->getValue() != i) {
2834      isIdentity = false;
2835      break;
2836    }
2837  }
2838  if (isIdentity) return N->getOperand(0);
2839
2840  // If the shuffle mask is an identity operation on the RHS, return the RHS.
2841  isIdentity = true;
2842  for (unsigned i = 0; i != NumElts; ++i) {
2843    if (ShufMask.getOperand(i).getOpcode() != ISD::UNDEF &&
2844        cast<ConstantSDNode>(ShufMask.getOperand(i))->getValue() != i+NumElts) {
2845      isIdentity = false;
2846      break;
2847    }
2848  }
2849  if (isIdentity) return N->getOperand(1);
2850
2851  // Check if the shuffle is a unary shuffle, i.e. one of the vectors is not
2852  // needed at all.
2853  bool isUnary = true;
2854  bool isSplat = true;
2855  int VecNum = -1;
2856  unsigned BaseIdx = 0;
2857  for (unsigned i = 0; i != NumElts; ++i)
2858    if (ShufMask.getOperand(i).getOpcode() != ISD::UNDEF) {
2859      unsigned Idx = cast<ConstantSDNode>(ShufMask.getOperand(i))->getValue();
2860      int V = (Idx < NumElts) ? 0 : 1;
2861      if (VecNum == -1) {
2862        VecNum = V;
2863        BaseIdx = Idx;
2864      } else {
2865        if (BaseIdx != Idx)
2866          isSplat = false;
2867        if (VecNum != V) {
2868          isUnary = false;
2869          break;
2870        }
2871      }
2872    }
2873
2874  SDOperand N0 = N->getOperand(0);
2875  SDOperand N1 = N->getOperand(1);
2876  // Normalize unary shuffle so the RHS is undef.
2877  if (isUnary && VecNum == 1)
2878    std::swap(N0, N1);
2879
2880  // If it is a splat, check if the argument vector is a build_vector with
2881  // all scalar elements the same.
2882  if (isSplat) {
2883    SDNode *V = N0.Val;
2884    if (V->getOpcode() == ISD::VBIT_CONVERT)
2885      V = V->getOperand(0).Val;
2886    if (V->getOpcode() == ISD::VBUILD_VECTOR) {
2887      unsigned NumElems = V->getNumOperands()-2;
2888      if (NumElems > BaseIdx) {
2889        SDOperand Base;
2890        bool AllSame = true;
2891        for (unsigned i = 0; i != NumElems; ++i) {
2892          if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
2893            Base = V->getOperand(i);
2894            break;
2895          }
2896        }
2897        // Splat of <u, u, u, u>, return <u, u, u, u>
2898        if (!Base.Val)
2899          return N0;
2900        for (unsigned i = 0; i != NumElems; ++i) {
2901          if (V->getOperand(i).getOpcode() != ISD::UNDEF &&
2902              V->getOperand(i) != Base) {
2903            AllSame = false;
2904            break;
2905          }
2906        }
2907        // Splat of <x, x, x, x>, return <x, x, x, x>
2908        if (AllSame)
2909          return N0;
2910      }
2911    }
2912  }
2913
2914  // If it is a unary or the LHS and the RHS are the same node, turn the RHS
2915  // into an undef.
2916  if (isUnary || N0 == N1) {
2917    // Check the SHUFFLE mask, mapping any inputs from the 2nd operand into the
2918    // first operand.
2919    SmallVector<SDOperand, 8> MappedOps;
2920    for (unsigned i = 0; i != NumElts; ++i) {
2921      if (ShufMask.getOperand(i).getOpcode() == ISD::UNDEF ||
2922          cast<ConstantSDNode>(ShufMask.getOperand(i))->getValue() < NumElts) {
2923        MappedOps.push_back(ShufMask.getOperand(i));
2924      } else {
2925        unsigned NewIdx =
2926          cast<ConstantSDNode>(ShufMask.getOperand(i))->getValue() - NumElts;
2927        MappedOps.push_back(DAG.getConstant(NewIdx, MVT::i32));
2928      }
2929    }
2930    // Add the type/#elts values.
2931    MappedOps.push_back(ShufMask.getOperand(NumElts));
2932    MappedOps.push_back(ShufMask.getOperand(NumElts+1));
2933
2934    ShufMask = DAG.getNode(ISD::VBUILD_VECTOR, ShufMask.getValueType(),
2935                           &MappedOps[0], MappedOps.size());
2936    AddToWorkList(ShufMask.Val);
2937
2938    // Build the undef vector.
2939    SDOperand UDVal = DAG.getNode(ISD::UNDEF, MappedOps[0].getValueType());
2940    for (unsigned i = 0; i != NumElts; ++i)
2941      MappedOps[i] = UDVal;
2942    MappedOps[NumElts  ] = *(N0.Val->op_end()-2);
2943    MappedOps[NumElts+1] = *(N0.Val->op_end()-1);
2944    UDVal = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector,
2945                        &MappedOps[0], MappedOps.size());
2946
2947    return DAG.getNode(ISD::VVECTOR_SHUFFLE, MVT::Vector,
2948                       N0, UDVal, ShufMask,
2949                       MappedOps[NumElts], MappedOps[NumElts+1]);
2950  }
2951
2952  return SDOperand();
2953}
2954
2955/// XformToShuffleWithZero - Returns a vector_shuffle if it able to transform
2956/// a VAND to a vector_shuffle with the destination vector and a zero vector.
2957/// e.g. VAND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
2958///      vector_shuffle V, Zero, <0, 4, 2, 4>
2959SDOperand DAGCombiner::XformToShuffleWithZero(SDNode *N) {
2960  SDOperand LHS = N->getOperand(0);
2961  SDOperand RHS = N->getOperand(1);
2962  if (N->getOpcode() == ISD::VAND) {
2963    SDOperand DstVecSize = *(LHS.Val->op_end()-2);
2964    SDOperand DstVecEVT  = *(LHS.Val->op_end()-1);
2965    if (RHS.getOpcode() == ISD::VBIT_CONVERT)
2966      RHS = RHS.getOperand(0);
2967    if (RHS.getOpcode() == ISD::VBUILD_VECTOR) {
2968      std::vector<SDOperand> IdxOps;
2969      unsigned NumOps = RHS.getNumOperands();
2970      unsigned NumElts = NumOps-2;
2971      MVT::ValueType EVT = cast<VTSDNode>(RHS.getOperand(NumOps-1))->getVT();
2972      for (unsigned i = 0; i != NumElts; ++i) {
2973        SDOperand Elt = RHS.getOperand(i);
2974        if (!isa<ConstantSDNode>(Elt))
2975          return SDOperand();
2976        else if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
2977          IdxOps.push_back(DAG.getConstant(i, EVT));
2978        else if (cast<ConstantSDNode>(Elt)->isNullValue())
2979          IdxOps.push_back(DAG.getConstant(NumElts, EVT));
2980        else
2981          return SDOperand();
2982      }
2983
2984      // Let's see if the target supports this vector_shuffle.
2985      if (!TLI.isVectorClearMaskLegal(IdxOps, EVT, DAG))
2986        return SDOperand();
2987
2988      // Return the new VVECTOR_SHUFFLE node.
2989      SDOperand NumEltsNode = DAG.getConstant(NumElts, MVT::i32);
2990      SDOperand EVTNode = DAG.getValueType(EVT);
2991      std::vector<SDOperand> Ops;
2992      LHS = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, LHS, NumEltsNode,
2993                        EVTNode);
2994      Ops.push_back(LHS);
2995      AddToWorkList(LHS.Val);
2996      std::vector<SDOperand> ZeroOps(NumElts, DAG.getConstant(0, EVT));
2997      ZeroOps.push_back(NumEltsNode);
2998      ZeroOps.push_back(EVTNode);
2999      Ops.push_back(DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector,
3000                                &ZeroOps[0], ZeroOps.size()));
3001      IdxOps.push_back(NumEltsNode);
3002      IdxOps.push_back(EVTNode);
3003      Ops.push_back(DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector,
3004                                &IdxOps[0], IdxOps.size()));
3005      Ops.push_back(NumEltsNode);
3006      Ops.push_back(EVTNode);
3007      SDOperand Result = DAG.getNode(ISD::VVECTOR_SHUFFLE, MVT::Vector,
3008                                     &Ops[0], Ops.size());
3009      if (NumEltsNode != DstVecSize || EVTNode != DstVecEVT) {
3010        Result = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Result,
3011                             DstVecSize, DstVecEVT);
3012      }
3013      return Result;
3014    }
3015  }
3016  return SDOperand();
3017}
3018
3019/// visitVBinOp - Visit a binary vector operation, like VADD.  IntOp indicates
3020/// the scalar operation of the vop if it is operating on an integer vector
3021/// (e.g. ADD) and FPOp indicates the FP version (e.g. FADD).
3022SDOperand DAGCombiner::visitVBinOp(SDNode *N, ISD::NodeType IntOp,
3023                                   ISD::NodeType FPOp) {
3024  MVT::ValueType EltType = cast<VTSDNode>(*(N->op_end()-1))->getVT();
3025  ISD::NodeType ScalarOp = MVT::isInteger(EltType) ? IntOp : FPOp;
3026  SDOperand LHS = N->getOperand(0);
3027  SDOperand RHS = N->getOperand(1);
3028  SDOperand Shuffle = XformToShuffleWithZero(N);
3029  if (Shuffle.Val) return Shuffle;
3030
3031  // If the LHS and RHS are VBUILD_VECTOR nodes, see if we can constant fold
3032  // this operation.
3033  if (LHS.getOpcode() == ISD::VBUILD_VECTOR &&
3034      RHS.getOpcode() == ISD::VBUILD_VECTOR) {
3035    SmallVector<SDOperand, 8> Ops;
3036    for (unsigned i = 0, e = LHS.getNumOperands()-2; i != e; ++i) {
3037      SDOperand LHSOp = LHS.getOperand(i);
3038      SDOperand RHSOp = RHS.getOperand(i);
3039      // If these two elements can't be folded, bail out.
3040      if ((LHSOp.getOpcode() != ISD::UNDEF &&
3041           LHSOp.getOpcode() != ISD::Constant &&
3042           LHSOp.getOpcode() != ISD::ConstantFP) ||
3043          (RHSOp.getOpcode() != ISD::UNDEF &&
3044           RHSOp.getOpcode() != ISD::Constant &&
3045           RHSOp.getOpcode() != ISD::ConstantFP))
3046        break;
3047      // Can't fold divide by zero.
3048      if (N->getOpcode() == ISD::VSDIV || N->getOpcode() == ISD::VUDIV) {
3049        if ((RHSOp.getOpcode() == ISD::Constant &&
3050             cast<ConstantSDNode>(RHSOp.Val)->isNullValue()) ||
3051            (RHSOp.getOpcode() == ISD::ConstantFP &&
3052             !cast<ConstantFPSDNode>(RHSOp.Val)->getValue()))
3053          break;
3054      }
3055      Ops.push_back(DAG.getNode(ScalarOp, EltType, LHSOp, RHSOp));
3056      AddToWorkList(Ops.back().Val);
3057      assert((Ops.back().getOpcode() == ISD::UNDEF ||
3058              Ops.back().getOpcode() == ISD::Constant ||
3059              Ops.back().getOpcode() == ISD::ConstantFP) &&
3060             "Scalar binop didn't fold!");
3061    }
3062
3063    if (Ops.size() == LHS.getNumOperands()-2) {
3064      Ops.push_back(*(LHS.Val->op_end()-2));
3065      Ops.push_back(*(LHS.Val->op_end()-1));
3066      return DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, &Ops[0], Ops.size());
3067    }
3068  }
3069
3070  return SDOperand();
3071}
3072
3073SDOperand DAGCombiner::SimplifySelect(SDOperand N0, SDOperand N1, SDOperand N2){
3074  assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
3075
3076  SDOperand SCC = SimplifySelectCC(N0.getOperand(0), N0.getOperand(1), N1, N2,
3077                                 cast<CondCodeSDNode>(N0.getOperand(2))->get());
3078  // If we got a simplified select_cc node back from SimplifySelectCC, then
3079  // break it down into a new SETCC node, and a new SELECT node, and then return
3080  // the SELECT node, since we were called with a SELECT node.
3081  if (SCC.Val) {
3082    // Check to see if we got a select_cc back (to turn into setcc/select).
3083    // Otherwise, just return whatever node we got back, like fabs.
3084    if (SCC.getOpcode() == ISD::SELECT_CC) {
3085      SDOperand SETCC = DAG.getNode(ISD::SETCC, N0.getValueType(),
3086                                    SCC.getOperand(0), SCC.getOperand(1),
3087                                    SCC.getOperand(4));
3088      AddToWorkList(SETCC.Val);
3089      return DAG.getNode(ISD::SELECT, SCC.getValueType(), SCC.getOperand(2),
3090                         SCC.getOperand(3), SETCC);
3091    }
3092    return SCC;
3093  }
3094  return SDOperand();
3095}
3096
3097/// SimplifySelectOps - Given a SELECT or a SELECT_CC node, where LHS and RHS
3098/// are the two values being selected between, see if we can simplify the
3099/// select.  Callers of this should assume that TheSelect is deleted if this
3100/// returns true.  As such, they should return the appropriate thing (e.g. the
3101/// node) back to the top-level of the DAG combiner loop to avoid it being
3102/// looked at.
3103///
3104bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDOperand LHS,
3105                                    SDOperand RHS) {
3106
3107  // If this is a select from two identical things, try to pull the operation
3108  // through the select.
3109  if (LHS.getOpcode() == RHS.getOpcode() && LHS.hasOneUse() && RHS.hasOneUse()){
3110#if 0
3111    std::cerr << "SELECT: ["; LHS.Val->dump();
3112    std::cerr << "] ["; RHS.Val->dump();
3113    std::cerr << "]\n";
3114#endif
3115
3116    // If this is a load and the token chain is identical, replace the select
3117    // of two loads with a load through a select of the address to load from.
3118    // This triggers in things like "select bool X, 10.0, 123.0" after the FP
3119    // constants have been dropped into the constant pool.
3120    if ((LHS.getOpcode() == ISD::LOAD ||
3121         LHS.getOpcode() == ISD::EXTLOAD ||
3122         LHS.getOpcode() == ISD::ZEXTLOAD ||
3123         LHS.getOpcode() == ISD::SEXTLOAD) &&
3124        // Token chains must be identical.
3125        LHS.getOperand(0) == RHS.getOperand(0) &&
3126        // If this is an EXTLOAD, the VT's must match.
3127        (LHS.getOpcode() == ISD::LOAD ||
3128         LHS.getOperand(3) == RHS.getOperand(3))) {
3129      // FIXME: this conflates two src values, discarding one.  This is not
3130      // the right thing to do, but nothing uses srcvalues now.  When they do,
3131      // turn SrcValue into a list of locations.
3132      SDOperand Addr;
3133      if (TheSelect->getOpcode() == ISD::SELECT)
3134        Addr = DAG.getNode(ISD::SELECT, LHS.getOperand(1).getValueType(),
3135                           TheSelect->getOperand(0), LHS.getOperand(1),
3136                           RHS.getOperand(1));
3137      else
3138        Addr = DAG.getNode(ISD::SELECT_CC, LHS.getOperand(1).getValueType(),
3139                           TheSelect->getOperand(0),
3140                           TheSelect->getOperand(1),
3141                           LHS.getOperand(1), RHS.getOperand(1),
3142                           TheSelect->getOperand(4));
3143
3144      SDOperand Load;
3145      if (LHS.getOpcode() == ISD::LOAD)
3146        Load = DAG.getLoad(TheSelect->getValueType(0), LHS.getOperand(0),
3147                           Addr, LHS.getOperand(2));
3148      else
3149        Load = DAG.getExtLoad(LHS.getOpcode(), TheSelect->getValueType(0),
3150                              LHS.getOperand(0), Addr, LHS.getOperand(2),
3151                              cast<VTSDNode>(LHS.getOperand(3))->getVT());
3152      // Users of the select now use the result of the load.
3153      CombineTo(TheSelect, Load);
3154
3155      // Users of the old loads now use the new load's chain.  We know the
3156      // old-load value is dead now.
3157      CombineTo(LHS.Val, Load.getValue(0), Load.getValue(1));
3158      CombineTo(RHS.Val, Load.getValue(0), Load.getValue(1));
3159      return true;
3160    }
3161  }
3162
3163  return false;
3164}
3165
3166SDOperand DAGCombiner::SimplifySelectCC(SDOperand N0, SDOperand N1,
3167                                        SDOperand N2, SDOperand N3,
3168                                        ISD::CondCode CC) {
3169
3170  MVT::ValueType VT = N2.getValueType();
3171  //ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.Val);
3172  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val);
3173  ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.Val);
3174  ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.Val);
3175
3176  // Determine if the condition we're dealing with is constant
3177  SDOperand SCC = SimplifySetCC(TLI.getSetCCResultTy(), N0, N1, CC, false);
3178  ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.Val);
3179
3180  // fold select_cc true, x, y -> x
3181  if (SCCC && SCCC->getValue())
3182    return N2;
3183  // fold select_cc false, x, y -> y
3184  if (SCCC && SCCC->getValue() == 0)
3185    return N3;
3186
3187  // Check to see if we can simplify the select into an fabs node
3188  if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
3189    // Allow either -0.0 or 0.0
3190    if (CFP->getValue() == 0.0) {
3191      // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
3192      if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
3193          N0 == N2 && N3.getOpcode() == ISD::FNEG &&
3194          N2 == N3.getOperand(0))
3195        return DAG.getNode(ISD::FABS, VT, N0);
3196
3197      // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
3198      if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
3199          N0 == N3 && N2.getOpcode() == ISD::FNEG &&
3200          N2.getOperand(0) == N3)
3201        return DAG.getNode(ISD::FABS, VT, N3);
3202    }
3203  }
3204
3205  // Check to see if we can perform the "gzip trick", transforming
3206  // select_cc setlt X, 0, A, 0 -> and (sra X, size(X)-1), A
3207  if (N1C && N1C->isNullValue() && N3C && N3C->isNullValue() &&
3208      MVT::isInteger(N0.getValueType()) &&
3209      MVT::isInteger(N2.getValueType()) && CC == ISD::SETLT) {
3210    MVT::ValueType XType = N0.getValueType();
3211    MVT::ValueType AType = N2.getValueType();
3212    if (XType >= AType) {
3213      // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
3214      // single-bit constant.
3215      if (N2C && ((N2C->getValue() & (N2C->getValue()-1)) == 0)) {
3216        unsigned ShCtV = Log2_64(N2C->getValue());
3217        ShCtV = MVT::getSizeInBits(XType)-ShCtV-1;
3218        SDOperand ShCt = DAG.getConstant(ShCtV, TLI.getShiftAmountTy());
3219        SDOperand Shift = DAG.getNode(ISD::SRL, XType, N0, ShCt);
3220        AddToWorkList(Shift.Val);
3221        if (XType > AType) {
3222          Shift = DAG.getNode(ISD::TRUNCATE, AType, Shift);
3223          AddToWorkList(Shift.Val);
3224        }
3225        return DAG.getNode(ISD::AND, AType, Shift, N2);
3226      }
3227      SDOperand Shift = DAG.getNode(ISD::SRA, XType, N0,
3228                                    DAG.getConstant(MVT::getSizeInBits(XType)-1,
3229                                                    TLI.getShiftAmountTy()));
3230      AddToWorkList(Shift.Val);
3231      if (XType > AType) {
3232        Shift = DAG.getNode(ISD::TRUNCATE, AType, Shift);
3233        AddToWorkList(Shift.Val);
3234      }
3235      return DAG.getNode(ISD::AND, AType, Shift, N2);
3236    }
3237  }
3238
3239  // fold select C, 16, 0 -> shl C, 4
3240  if (N2C && N3C && N3C->isNullValue() && isPowerOf2_64(N2C->getValue()) &&
3241      TLI.getSetCCResultContents() == TargetLowering::ZeroOrOneSetCCResult) {
3242    // Get a SetCC of the condition
3243    // FIXME: Should probably make sure that setcc is legal if we ever have a
3244    // target where it isn't.
3245    SDOperand Temp, SCC;
3246    // cast from setcc result type to select result type
3247    if (AfterLegalize) {
3248      SCC  = DAG.getSetCC(TLI.getSetCCResultTy(), N0, N1, CC);
3249      Temp = DAG.getZeroExtendInReg(SCC, N2.getValueType());
3250    } else {
3251      SCC  = DAG.getSetCC(MVT::i1, N0, N1, CC);
3252      Temp = DAG.getNode(ISD::ZERO_EXTEND, N2.getValueType(), SCC);
3253    }
3254    AddToWorkList(SCC.Val);
3255    AddToWorkList(Temp.Val);
3256    // shl setcc result by log2 n2c
3257    return DAG.getNode(ISD::SHL, N2.getValueType(), Temp,
3258                       DAG.getConstant(Log2_64(N2C->getValue()),
3259                                       TLI.getShiftAmountTy()));
3260  }
3261
3262  // Check to see if this is the equivalent of setcc
3263  // FIXME: Turn all of these into setcc if setcc if setcc is legal
3264  // otherwise, go ahead with the folds.
3265  if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getValue() == 1ULL)) {
3266    MVT::ValueType XType = N0.getValueType();
3267    if (TLI.isOperationLegal(ISD::SETCC, TLI.getSetCCResultTy())) {
3268      SDOperand Res = DAG.getSetCC(TLI.getSetCCResultTy(), N0, N1, CC);
3269      if (Res.getValueType() != VT)
3270        Res = DAG.getNode(ISD::ZERO_EXTEND, VT, Res);
3271      return Res;
3272    }
3273
3274    // seteq X, 0 -> srl (ctlz X, log2(size(X)))
3275    if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
3276        TLI.isOperationLegal(ISD::CTLZ, XType)) {
3277      SDOperand Ctlz = DAG.getNode(ISD::CTLZ, XType, N0);
3278      return DAG.getNode(ISD::SRL, XType, Ctlz,
3279                         DAG.getConstant(Log2_32(MVT::getSizeInBits(XType)),
3280                                         TLI.getShiftAmountTy()));
3281    }
3282    // setgt X, 0 -> srl (and (-X, ~X), size(X)-1)
3283    if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
3284      SDOperand NegN0 = DAG.getNode(ISD::SUB, XType, DAG.getConstant(0, XType),
3285                                    N0);
3286      SDOperand NotN0 = DAG.getNode(ISD::XOR, XType, N0,
3287                                    DAG.getConstant(~0ULL, XType));
3288      return DAG.getNode(ISD::SRL, XType,
3289                         DAG.getNode(ISD::AND, XType, NegN0, NotN0),
3290                         DAG.getConstant(MVT::getSizeInBits(XType)-1,
3291                                         TLI.getShiftAmountTy()));
3292    }
3293    // setgt X, -1 -> xor (srl (X, size(X)-1), 1)
3294    if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
3295      SDOperand Sign = DAG.getNode(ISD::SRL, XType, N0,
3296                                   DAG.getConstant(MVT::getSizeInBits(XType)-1,
3297                                                   TLI.getShiftAmountTy()));
3298      return DAG.getNode(ISD::XOR, XType, Sign, DAG.getConstant(1, XType));
3299    }
3300  }
3301
3302  // Check to see if this is an integer abs. select_cc setl[te] X, 0, -X, X ->
3303  // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
3304  if (N1C && N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE) &&
3305      N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1)) {
3306    if (ConstantSDNode *SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0))) {
3307      MVT::ValueType XType = N0.getValueType();
3308      if (SubC->isNullValue() && MVT::isInteger(XType)) {
3309        SDOperand Shift = DAG.getNode(ISD::SRA, XType, N0,
3310                                    DAG.getConstant(MVT::getSizeInBits(XType)-1,
3311                                                    TLI.getShiftAmountTy()));
3312        SDOperand Add = DAG.getNode(ISD::ADD, XType, N0, Shift);
3313        AddToWorkList(Shift.Val);
3314        AddToWorkList(Add.Val);
3315        return DAG.getNode(ISD::XOR, XType, Add, Shift);
3316      }
3317    }
3318  }
3319
3320  return SDOperand();
3321}
3322
3323SDOperand DAGCombiner::SimplifySetCC(MVT::ValueType VT, SDOperand N0,
3324                                     SDOperand N1, ISD::CondCode Cond,
3325                                     bool foldBooleans) {
3326  // These setcc operations always fold.
3327  switch (Cond) {
3328  default: break;
3329  case ISD::SETFALSE:
3330  case ISD::SETFALSE2: return DAG.getConstant(0, VT);
3331  case ISD::SETTRUE:
3332  case ISD::SETTRUE2:  return DAG.getConstant(1, VT);
3333  }
3334
3335  if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val)) {
3336    uint64_t C1 = N1C->getValue();
3337    if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.Val)) {
3338      uint64_t C0 = N0C->getValue();
3339
3340      // Sign extend the operands if required
3341      if (ISD::isSignedIntSetCC(Cond)) {
3342        C0 = N0C->getSignExtended();
3343        C1 = N1C->getSignExtended();
3344      }
3345
3346      switch (Cond) {
3347      default: assert(0 && "Unknown integer setcc!");
3348      case ISD::SETEQ:  return DAG.getConstant(C0 == C1, VT);
3349      case ISD::SETNE:  return DAG.getConstant(C0 != C1, VT);
3350      case ISD::SETULT: return DAG.getConstant(C0 <  C1, VT);
3351      case ISD::SETUGT: return DAG.getConstant(C0 >  C1, VT);
3352      case ISD::SETULE: return DAG.getConstant(C0 <= C1, VT);
3353      case ISD::SETUGE: return DAG.getConstant(C0 >= C1, VT);
3354      case ISD::SETLT:  return DAG.getConstant((int64_t)C0 <  (int64_t)C1, VT);
3355      case ISD::SETGT:  return DAG.getConstant((int64_t)C0 >  (int64_t)C1, VT);
3356      case ISD::SETLE:  return DAG.getConstant((int64_t)C0 <= (int64_t)C1, VT);
3357      case ISD::SETGE:  return DAG.getConstant((int64_t)C0 >= (int64_t)C1, VT);
3358      }
3359    } else {
3360      // If the LHS is '(srl (ctlz x), 5)', the RHS is 0/1, and this is an
3361      // equality comparison, then we're just comparing whether X itself is
3362      // zero.
3363      if (N0.getOpcode() == ISD::SRL && (C1 == 0 || C1 == 1) &&
3364          N0.getOperand(0).getOpcode() == ISD::CTLZ &&
3365          N0.getOperand(1).getOpcode() == ISD::Constant) {
3366        unsigned ShAmt = cast<ConstantSDNode>(N0.getOperand(1))->getValue();
3367        if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
3368            ShAmt == Log2_32(MVT::getSizeInBits(N0.getValueType()))) {
3369          if ((C1 == 0) == (Cond == ISD::SETEQ)) {
3370            // (srl (ctlz x), 5) == 0  -> X != 0
3371            // (srl (ctlz x), 5) != 1  -> X != 0
3372            Cond = ISD::SETNE;
3373          } else {
3374            // (srl (ctlz x), 5) != 0  -> X == 0
3375            // (srl (ctlz x), 5) == 1  -> X == 0
3376            Cond = ISD::SETEQ;
3377          }
3378          SDOperand Zero = DAG.getConstant(0, N0.getValueType());
3379          return DAG.getSetCC(VT, N0.getOperand(0).getOperand(0),
3380                              Zero, Cond);
3381        }
3382      }
3383
3384      // If the LHS is a ZERO_EXTEND, perform the comparison on the input.
3385      if (N0.getOpcode() == ISD::ZERO_EXTEND) {
3386        unsigned InSize = MVT::getSizeInBits(N0.getOperand(0).getValueType());
3387
3388        // If the comparison constant has bits in the upper part, the
3389        // zero-extended value could never match.
3390        if (C1 & (~0ULL << InSize)) {
3391          unsigned VSize = MVT::getSizeInBits(N0.getValueType());
3392          switch (Cond) {
3393          case ISD::SETUGT:
3394          case ISD::SETUGE:
3395          case ISD::SETEQ: return DAG.getConstant(0, VT);
3396          case ISD::SETULT:
3397          case ISD::SETULE:
3398          case ISD::SETNE: return DAG.getConstant(1, VT);
3399          case ISD::SETGT:
3400          case ISD::SETGE:
3401            // True if the sign bit of C1 is set.
3402            return DAG.getConstant((C1 & (1ULL << VSize)) != 0, VT);
3403          case ISD::SETLT:
3404          case ISD::SETLE:
3405            // True if the sign bit of C1 isn't set.
3406            return DAG.getConstant((C1 & (1ULL << VSize)) == 0, VT);
3407          default:
3408            break;
3409          }
3410        }
3411
3412        // Otherwise, we can perform the comparison with the low bits.
3413        switch (Cond) {
3414        case ISD::SETEQ:
3415        case ISD::SETNE:
3416        case ISD::SETUGT:
3417        case ISD::SETUGE:
3418        case ISD::SETULT:
3419        case ISD::SETULE:
3420          return DAG.getSetCC(VT, N0.getOperand(0),
3421                          DAG.getConstant(C1, N0.getOperand(0).getValueType()),
3422                          Cond);
3423        default:
3424          break;   // todo, be more careful with signed comparisons
3425        }
3426      } else if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
3427                 (Cond == ISD::SETEQ || Cond == ISD::SETNE)) {
3428        MVT::ValueType ExtSrcTy = cast<VTSDNode>(N0.getOperand(1))->getVT();
3429        unsigned ExtSrcTyBits = MVT::getSizeInBits(ExtSrcTy);
3430        MVT::ValueType ExtDstTy = N0.getValueType();
3431        unsigned ExtDstTyBits = MVT::getSizeInBits(ExtDstTy);
3432
3433        // If the extended part has any inconsistent bits, it cannot ever
3434        // compare equal.  In other words, they have to be all ones or all
3435        // zeros.
3436        uint64_t ExtBits =
3437          (~0ULL >> (64-ExtSrcTyBits)) & (~0ULL << (ExtDstTyBits-1));
3438        if ((C1 & ExtBits) != 0 && (C1 & ExtBits) != ExtBits)
3439          return DAG.getConstant(Cond == ISD::SETNE, VT);
3440
3441        SDOperand ZextOp;
3442        MVT::ValueType Op0Ty = N0.getOperand(0).getValueType();
3443        if (Op0Ty == ExtSrcTy) {
3444          ZextOp = N0.getOperand(0);
3445        } else {
3446          int64_t Imm = ~0ULL >> (64-ExtSrcTyBits);
3447          ZextOp = DAG.getNode(ISD::AND, Op0Ty, N0.getOperand(0),
3448                               DAG.getConstant(Imm, Op0Ty));
3449        }
3450        AddToWorkList(ZextOp.Val);
3451        // Otherwise, make this a use of a zext.
3452        return DAG.getSetCC(VT, ZextOp,
3453                            DAG.getConstant(C1 & (~0ULL>>(64-ExtSrcTyBits)),
3454                                            ExtDstTy),
3455                            Cond);
3456      } else if ((N1C->getValue() == 0 || N1C->getValue() == 1) &&
3457                 (Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
3458                 (N0.getOpcode() == ISD::XOR ||
3459                  (N0.getOpcode() == ISD::AND &&
3460                   N0.getOperand(0).getOpcode() == ISD::XOR &&
3461                   N0.getOperand(1) == N0.getOperand(0).getOperand(1))) &&
3462                 isa<ConstantSDNode>(N0.getOperand(1)) &&
3463                 cast<ConstantSDNode>(N0.getOperand(1))->getValue() == 1) {
3464        // If this is (X^1) == 0/1, swap the RHS and eliminate the xor.  We can
3465        // only do this if the top bits are known zero.
3466        if (TLI.MaskedValueIsZero(N1,
3467                                  MVT::getIntVTBitMask(N0.getValueType())-1)) {
3468          // Okay, get the un-inverted input value.
3469          SDOperand Val;
3470          if (N0.getOpcode() == ISD::XOR)
3471            Val = N0.getOperand(0);
3472          else {
3473            assert(N0.getOpcode() == ISD::AND &&
3474                   N0.getOperand(0).getOpcode() == ISD::XOR);
3475            // ((X^1)&1)^1 -> X & 1
3476            Val = DAG.getNode(ISD::AND, N0.getValueType(),
3477                              N0.getOperand(0).getOperand(0), N0.getOperand(1));
3478          }
3479          return DAG.getSetCC(VT, Val, N1,
3480                              Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ);
3481        }
3482      }
3483
3484      uint64_t MinVal, MaxVal;
3485      unsigned OperandBitSize = MVT::getSizeInBits(N1C->getValueType(0));
3486      if (ISD::isSignedIntSetCC(Cond)) {
3487        MinVal = 1ULL << (OperandBitSize-1);
3488        if (OperandBitSize != 1)   // Avoid X >> 64, which is undefined.
3489          MaxVal = ~0ULL >> (65-OperandBitSize);
3490        else
3491          MaxVal = 0;
3492      } else {
3493        MinVal = 0;
3494        MaxVal = ~0ULL >> (64-OperandBitSize);
3495      }
3496
3497      // Canonicalize GE/LE comparisons to use GT/LT comparisons.
3498      if (Cond == ISD::SETGE || Cond == ISD::SETUGE) {
3499        if (C1 == MinVal) return DAG.getConstant(1, VT);   // X >= MIN --> true
3500        --C1;                                          // X >= C0 --> X > (C0-1)
3501        return DAG.getSetCC(VT, N0, DAG.getConstant(C1, N1.getValueType()),
3502                        (Cond == ISD::SETGE) ? ISD::SETGT : ISD::SETUGT);
3503      }
3504
3505      if (Cond == ISD::SETLE || Cond == ISD::SETULE) {
3506        if (C1 == MaxVal) return DAG.getConstant(1, VT);   // X <= MAX --> true
3507        ++C1;                                          // X <= C0 --> X < (C0+1)
3508        return DAG.getSetCC(VT, N0, DAG.getConstant(C1, N1.getValueType()),
3509                        (Cond == ISD::SETLE) ? ISD::SETLT : ISD::SETULT);
3510      }
3511
3512      if ((Cond == ISD::SETLT || Cond == ISD::SETULT) && C1 == MinVal)
3513        return DAG.getConstant(0, VT);      // X < MIN --> false
3514
3515      // Canonicalize setgt X, Min --> setne X, Min
3516      if ((Cond == ISD::SETGT || Cond == ISD::SETUGT) && C1 == MinVal)
3517        return DAG.getSetCC(VT, N0, N1, ISD::SETNE);
3518      // Canonicalize setlt X, Max --> setne X, Max
3519      if ((Cond == ISD::SETLT || Cond == ISD::SETULT) && C1 == MaxVal)
3520        return DAG.getSetCC(VT, N0, N1, ISD::SETNE);
3521
3522      // If we have setult X, 1, turn it into seteq X, 0
3523      if ((Cond == ISD::SETLT || Cond == ISD::SETULT) && C1 == MinVal+1)
3524        return DAG.getSetCC(VT, N0, DAG.getConstant(MinVal, N0.getValueType()),
3525                        ISD::SETEQ);
3526      // If we have setugt X, Max-1, turn it into seteq X, Max
3527      else if ((Cond == ISD::SETGT || Cond == ISD::SETUGT) && C1 == MaxVal-1)
3528        return DAG.getSetCC(VT, N0, DAG.getConstant(MaxVal, N0.getValueType()),
3529                        ISD::SETEQ);
3530
3531      // If we have "setcc X, C0", check to see if we can shrink the immediate
3532      // by changing cc.
3533
3534      // SETUGT X, SINTMAX  -> SETLT X, 0
3535      if (Cond == ISD::SETUGT && OperandBitSize != 1 &&
3536          C1 == (~0ULL >> (65-OperandBitSize)))
3537        return DAG.getSetCC(VT, N0, DAG.getConstant(0, N1.getValueType()),
3538                            ISD::SETLT);
3539
3540      // FIXME: Implement the rest of these.
3541
3542      // Fold bit comparisons when we can.
3543      if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
3544          VT == N0.getValueType() && N0.getOpcode() == ISD::AND)
3545        if (ConstantSDNode *AndRHS =
3546                    dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
3547          if (Cond == ISD::SETNE && C1 == 0) {// (X & 8) != 0  -->  (X & 8) >> 3
3548            // Perform the xform if the AND RHS is a single bit.
3549            if ((AndRHS->getValue() & (AndRHS->getValue()-1)) == 0) {
3550              return DAG.getNode(ISD::SRL, VT, N0,
3551                             DAG.getConstant(Log2_64(AndRHS->getValue()),
3552                                                   TLI.getShiftAmountTy()));
3553            }
3554          } else if (Cond == ISD::SETEQ && C1 == AndRHS->getValue()) {
3555            // (X & 8) == 8  -->  (X & 8) >> 3
3556            // Perform the xform if C1 is a single bit.
3557            if ((C1 & (C1-1)) == 0) {
3558              return DAG.getNode(ISD::SRL, VT, N0,
3559                          DAG.getConstant(Log2_64(C1),TLI.getShiftAmountTy()));
3560            }
3561          }
3562        }
3563    }
3564  } else if (isa<ConstantSDNode>(N0.Val)) {
3565      // Ensure that the constant occurs on the RHS.
3566    return DAG.getSetCC(VT, N1, N0, ISD::getSetCCSwappedOperands(Cond));
3567  }
3568
3569  if (ConstantFPSDNode *N0C = dyn_cast<ConstantFPSDNode>(N0.Val))
3570    if (ConstantFPSDNode *N1C = dyn_cast<ConstantFPSDNode>(N1.Val)) {
3571      double C0 = N0C->getValue(), C1 = N1C->getValue();
3572
3573      switch (Cond) {
3574      default: break; // FIXME: Implement the rest of these!
3575      case ISD::SETEQ:  return DAG.getConstant(C0 == C1, VT);
3576      case ISD::SETNE:  return DAG.getConstant(C0 != C1, VT);
3577      case ISD::SETLT:  return DAG.getConstant(C0 < C1, VT);
3578      case ISD::SETGT:  return DAG.getConstant(C0 > C1, VT);
3579      case ISD::SETLE:  return DAG.getConstant(C0 <= C1, VT);
3580      case ISD::SETGE:  return DAG.getConstant(C0 >= C1, VT);
3581      }
3582    } else {
3583      // Ensure that the constant occurs on the RHS.
3584      return DAG.getSetCC(VT, N1, N0, ISD::getSetCCSwappedOperands(Cond));
3585    }
3586
3587  if (N0 == N1) {
3588    // We can always fold X == Y for integer setcc's.
3589    if (MVT::isInteger(N0.getValueType()))
3590      return DAG.getConstant(ISD::isTrueWhenEqual(Cond), VT);
3591    unsigned UOF = ISD::getUnorderedFlavor(Cond);
3592    if (UOF == 2)   // FP operators that are undefined on NaNs.
3593      return DAG.getConstant(ISD::isTrueWhenEqual(Cond), VT);
3594    if (UOF == unsigned(ISD::isTrueWhenEqual(Cond)))
3595      return DAG.getConstant(UOF, VT);
3596    // Otherwise, we can't fold it.  However, we can simplify it to SETUO/SETO
3597    // if it is not already.
3598    ISD::CondCode NewCond = UOF == 0 ? ISD::SETO : ISD::SETUO;
3599    if (NewCond != Cond)
3600      return DAG.getSetCC(VT, N0, N1, NewCond);
3601  }
3602
3603  if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
3604      MVT::isInteger(N0.getValueType())) {
3605    if (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::SUB ||
3606        N0.getOpcode() == ISD::XOR) {
3607      // Simplify (X+Y) == (X+Z) -->  Y == Z
3608      if (N0.getOpcode() == N1.getOpcode()) {
3609        if (N0.getOperand(0) == N1.getOperand(0))
3610          return DAG.getSetCC(VT, N0.getOperand(1), N1.getOperand(1), Cond);
3611        if (N0.getOperand(1) == N1.getOperand(1))
3612          return DAG.getSetCC(VT, N0.getOperand(0), N1.getOperand(0), Cond);
3613        if (DAG.isCommutativeBinOp(N0.getOpcode())) {
3614          // If X op Y == Y op X, try other combinations.
3615          if (N0.getOperand(0) == N1.getOperand(1))
3616            return DAG.getSetCC(VT, N0.getOperand(1), N1.getOperand(0), Cond);
3617          if (N0.getOperand(1) == N1.getOperand(0))
3618            return DAG.getSetCC(VT, N0.getOperand(0), N1.getOperand(1), Cond);
3619        }
3620      }
3621
3622      if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(N1)) {
3623        if (ConstantSDNode *LHSR = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
3624          // Turn (X+C1) == C2 --> X == C2-C1
3625          if (N0.getOpcode() == ISD::ADD && N0.Val->hasOneUse()) {
3626            return DAG.getSetCC(VT, N0.getOperand(0),
3627                              DAG.getConstant(RHSC->getValue()-LHSR->getValue(),
3628                                N0.getValueType()), Cond);
3629          }
3630
3631          // Turn (X^C1) == C2 into X == C1^C2 iff X&~C1 = 0.
3632          if (N0.getOpcode() == ISD::XOR)
3633            // If we know that all of the inverted bits are zero, don't bother
3634            // performing the inversion.
3635            if (TLI.MaskedValueIsZero(N0.getOperand(0), ~LHSR->getValue()))
3636              return DAG.getSetCC(VT, N0.getOperand(0),
3637                              DAG.getConstant(LHSR->getValue()^RHSC->getValue(),
3638                                              N0.getValueType()), Cond);
3639        }
3640
3641        // Turn (C1-X) == C2 --> X == C1-C2
3642        if (ConstantSDNode *SUBC = dyn_cast<ConstantSDNode>(N0.getOperand(0))) {
3643          if (N0.getOpcode() == ISD::SUB && N0.Val->hasOneUse()) {
3644            return DAG.getSetCC(VT, N0.getOperand(1),
3645                             DAG.getConstant(SUBC->getValue()-RHSC->getValue(),
3646                                             N0.getValueType()), Cond);
3647          }
3648        }
3649      }
3650
3651      // Simplify (X+Z) == X -->  Z == 0
3652      if (N0.getOperand(0) == N1)
3653        return DAG.getSetCC(VT, N0.getOperand(1),
3654                        DAG.getConstant(0, N0.getValueType()), Cond);
3655      if (N0.getOperand(1) == N1) {
3656        if (DAG.isCommutativeBinOp(N0.getOpcode()))
3657          return DAG.getSetCC(VT, N0.getOperand(0),
3658                          DAG.getConstant(0, N0.getValueType()), Cond);
3659        else {
3660          assert(N0.getOpcode() == ISD::SUB && "Unexpected operation!");
3661          // (Z-X) == X  --> Z == X<<1
3662          SDOperand SH = DAG.getNode(ISD::SHL, N1.getValueType(),
3663                                     N1,
3664                                     DAG.getConstant(1,TLI.getShiftAmountTy()));
3665          AddToWorkList(SH.Val);
3666          return DAG.getSetCC(VT, N0.getOperand(0), SH, Cond);
3667        }
3668      }
3669    }
3670
3671    if (N1.getOpcode() == ISD::ADD || N1.getOpcode() == ISD::SUB ||
3672        N1.getOpcode() == ISD::XOR) {
3673      // Simplify  X == (X+Z) -->  Z == 0
3674      if (N1.getOperand(0) == N0) {
3675        return DAG.getSetCC(VT, N1.getOperand(1),
3676                        DAG.getConstant(0, N1.getValueType()), Cond);
3677      } else if (N1.getOperand(1) == N0) {
3678        if (DAG.isCommutativeBinOp(N1.getOpcode())) {
3679          return DAG.getSetCC(VT, N1.getOperand(0),
3680                          DAG.getConstant(0, N1.getValueType()), Cond);
3681        } else {
3682          assert(N1.getOpcode() == ISD::SUB && "Unexpected operation!");
3683          // X == (Z-X)  --> X<<1 == Z
3684          SDOperand SH = DAG.getNode(ISD::SHL, N1.getValueType(), N0,
3685                                     DAG.getConstant(1,TLI.getShiftAmountTy()));
3686          AddToWorkList(SH.Val);
3687          return DAG.getSetCC(VT, SH, N1.getOperand(0), Cond);
3688        }
3689      }
3690    }
3691  }
3692
3693  // Fold away ALL boolean setcc's.
3694  SDOperand Temp;
3695  if (N0.getValueType() == MVT::i1 && foldBooleans) {
3696    switch (Cond) {
3697    default: assert(0 && "Unknown integer setcc!");
3698    case ISD::SETEQ:  // X == Y  -> (X^Y)^1
3699      Temp = DAG.getNode(ISD::XOR, MVT::i1, N0, N1);
3700      N0 = DAG.getNode(ISD::XOR, MVT::i1, Temp, DAG.getConstant(1, MVT::i1));
3701      AddToWorkList(Temp.Val);
3702      break;
3703    case ISD::SETNE:  // X != Y   -->  (X^Y)
3704      N0 = DAG.getNode(ISD::XOR, MVT::i1, N0, N1);
3705      break;
3706    case ISD::SETGT:  // X >s Y   -->  X == 0 & Y == 1  -->  X^1 & Y
3707    case ISD::SETULT: // X <u Y   -->  X == 0 & Y == 1  -->  X^1 & Y
3708      Temp = DAG.getNode(ISD::XOR, MVT::i1, N0, DAG.getConstant(1, MVT::i1));
3709      N0 = DAG.getNode(ISD::AND, MVT::i1, N1, Temp);
3710      AddToWorkList(Temp.Val);
3711      break;
3712    case ISD::SETLT:  // X <s Y   --> X == 1 & Y == 0  -->  Y^1 & X
3713    case ISD::SETUGT: // X >u Y   --> X == 1 & Y == 0  -->  Y^1 & X
3714      Temp = DAG.getNode(ISD::XOR, MVT::i1, N1, DAG.getConstant(1, MVT::i1));
3715      N0 = DAG.getNode(ISD::AND, MVT::i1, N0, Temp);
3716      AddToWorkList(Temp.Val);
3717      break;
3718    case ISD::SETULE: // X <=u Y  --> X == 0 | Y == 1  -->  X^1 | Y
3719    case ISD::SETGE:  // X >=s Y  --> X == 0 | Y == 1  -->  X^1 | Y
3720      Temp = DAG.getNode(ISD::XOR, MVT::i1, N0, DAG.getConstant(1, MVT::i1));
3721      N0 = DAG.getNode(ISD::OR, MVT::i1, N1, Temp);
3722      AddToWorkList(Temp.Val);
3723      break;
3724    case ISD::SETUGE: // X >=u Y  --> X == 1 | Y == 0  -->  Y^1 | X
3725    case ISD::SETLE:  // X <=s Y  --> X == 1 | Y == 0  -->  Y^1 | X
3726      Temp = DAG.getNode(ISD::XOR, MVT::i1, N1, DAG.getConstant(1, MVT::i1));
3727      N0 = DAG.getNode(ISD::OR, MVT::i1, N0, Temp);
3728      break;
3729    }
3730    if (VT != MVT::i1) {
3731      AddToWorkList(N0.Val);
3732      // FIXME: If running after legalize, we probably can't do this.
3733      N0 = DAG.getNode(ISD::ZERO_EXTEND, VT, N0);
3734    }
3735    return N0;
3736  }
3737
3738  // Could not fold it.
3739  return SDOperand();
3740}
3741
3742/// BuildSDIVSequence - Given an ISD::SDIV node expressing a divide by constant,
3743/// return a DAG expression to select that will generate the same value by
3744/// multiplying by a magic number.  See:
3745/// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
3746SDOperand DAGCombiner::BuildSDIV(SDNode *N) {
3747  std::vector<SDNode*> Built;
3748  SDOperand S = TLI.BuildSDIV(N, DAG, &Built);
3749
3750  for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
3751       ii != ee; ++ii)
3752    AddToWorkList(*ii);
3753  return S;
3754}
3755
3756/// BuildUDIVSequence - Given an ISD::UDIV node expressing a divide by constant,
3757/// return a DAG expression to select that will generate the same value by
3758/// multiplying by a magic number.  See:
3759/// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
3760SDOperand DAGCombiner::BuildUDIV(SDNode *N) {
3761  std::vector<SDNode*> Built;
3762  SDOperand S = TLI.BuildUDIV(N, DAG, &Built);
3763
3764  for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
3765       ii != ee; ++ii)
3766    AddToWorkList(*ii);
3767  return S;
3768}
3769
3770// SelectionDAG::Combine - This is the entry point for the file.
3771//
3772void SelectionDAG::Combine(bool RunningAfterLegalize) {
3773  /// run - This is the main entry point to this class.
3774  ///
3775  DAGCombiner(*this).Run(RunningAfterLegalize);
3776}
3777