DAGCombiner.cpp revision 6ea2dee6f675bd5eb32de08b4eecfe21ebe107a0
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: make truncate see through SIGN_EXTEND and AND
26// FIXME: divide by zero is currently left unfolded.  do we want to turn this
27//        into an undef?
28// FIXME: select ne (select cc, 1, 0), 0, true, false -> select cc, true, false
29//
30//===----------------------------------------------------------------------===//
31
32#define DEBUG_TYPE "dagcombine"
33#include "llvm/ADT/Statistic.h"
34#include "llvm/CodeGen/SelectionDAG.h"
35#include "llvm/Support/Debug.h"
36#include "llvm/Support/MathExtras.h"
37#include "llvm/Target/TargetLowering.h"
38#include <algorithm>
39#include <cmath>
40#include <iostream>
41using namespace llvm;
42
43namespace {
44  Statistic<> NodesCombined ("dagcombiner", "Number of dag nodes combined");
45
46  class DAGCombiner {
47    SelectionDAG &DAG;
48    TargetLowering &TLI;
49    bool AfterLegalize;
50
51    // Worklist of all of the nodes that need to be simplified.
52    std::vector<SDNode*> WorkList;
53
54    /// AddUsersToWorkList - When an instruction is simplified, add all users of
55    /// the instruction to the work lists because they might get more simplified
56    /// now.
57    ///
58    void AddUsersToWorkList(SDNode *N) {
59      for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
60           UI != UE; ++UI)
61        WorkList.push_back(*UI);
62    }
63
64    /// removeFromWorkList - remove all instances of N from the worklist.
65    ///
66    void removeFromWorkList(SDNode *N) {
67      WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), N),
68                     WorkList.end());
69    }
70
71  public:
72    void AddToWorkList(SDNode *N) {
73      WorkList.push_back(N);
74    }
75
76    SDOperand CombineTo(SDNode *N, const std::vector<SDOperand> &To) {
77      ++NodesCombined;
78      DEBUG(std::cerr << "\nReplacing "; N->dump();
79            std::cerr << "\nWith: "; To[0].Val->dump();
80            std::cerr << " and " << To.size()-1 << " other values\n");
81      std::vector<SDNode*> NowDead;
82      DAG.ReplaceAllUsesWith(N, To, &NowDead);
83
84      // Push the new nodes and any users onto the worklist
85      for (unsigned i = 0, e = To.size(); i != e; ++i) {
86        WorkList.push_back(To[i].Val);
87        AddUsersToWorkList(To[i].Val);
88      }
89
90      // Nodes can end up on the worklist more than once.  Make sure we do
91      // not process a node that has been replaced.
92      removeFromWorkList(N);
93      for (unsigned i = 0, e = NowDead.size(); i != e; ++i)
94        removeFromWorkList(NowDead[i]);
95
96      // Finally, since the node is now dead, remove it from the graph.
97      DAG.DeleteNode(N);
98      return SDOperand(N, 0);
99    }
100
101    SDOperand CombineTo(SDNode *N, SDOperand Res) {
102      std::vector<SDOperand> To;
103      To.push_back(Res);
104      return CombineTo(N, To);
105    }
106
107    SDOperand CombineTo(SDNode *N, SDOperand Res0, SDOperand Res1) {
108      std::vector<SDOperand> To;
109      To.push_back(Res0);
110      To.push_back(Res1);
111      return CombineTo(N, To);
112    }
113  private:
114
115    /// SimplifyDemandedBits - Check the specified integer node value to see if
116    /// it can be simplified or if things it uses can be simplified by bit
117    /// propagation.  If so, return true.
118    bool SimplifyDemandedBits(SDOperand Op) {
119      TargetLowering::TargetLoweringOpt TLO(DAG);
120      uint64_t KnownZero, KnownOne;
121      uint64_t Demanded = MVT::getIntVTBitMask(Op.getValueType());
122      if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
123        return false;
124
125      // Revisit the node.
126      WorkList.push_back(Op.Val);
127
128      // Replace the old value with the new one.
129      ++NodesCombined;
130      DEBUG(std::cerr << "\nReplacing "; TLO.Old.Val->dump();
131            std::cerr << "\nWith: "; TLO.New.Val->dump());
132
133      std::vector<SDNode*> NowDead;
134      DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New, NowDead);
135
136      // Push the new node and any (possibly new) users onto the worklist.
137      WorkList.push_back(TLO.New.Val);
138      AddUsersToWorkList(TLO.New.Val);
139
140      // Nodes can end up on the worklist more than once.  Make sure we do
141      // not process a node that has been replaced.
142      for (unsigned i = 0, e = NowDead.size(); i != e; ++i)
143        removeFromWorkList(NowDead[i]);
144
145      // Finally, if the node is now dead, remove it from the graph.  The node
146      // may not be dead if the replacement process recursively simplified to
147      // something else needing this node.
148      if (TLO.Old.Val->use_empty()) {
149        removeFromWorkList(TLO.Old.Val);
150        DAG.DeleteNode(TLO.Old.Val);
151      }
152      return true;
153    }
154
155    /// visit - call the node-specific routine that knows how to fold each
156    /// particular type of node.
157    SDOperand visit(SDNode *N);
158
159    // Visitation implementation - Implement dag node combining for different
160    // node types.  The semantics are as follows:
161    // Return Value:
162    //   SDOperand.Val == 0   - No change was made
163    //   SDOperand.Val == N   - N was replaced, is dead, and is already handled.
164    //   otherwise            - N should be replaced by the returned Operand.
165    //
166    SDOperand visitTokenFactor(SDNode *N);
167    SDOperand visitADD(SDNode *N);
168    SDOperand visitSUB(SDNode *N);
169    SDOperand visitMUL(SDNode *N);
170    SDOperand visitSDIV(SDNode *N);
171    SDOperand visitUDIV(SDNode *N);
172    SDOperand visitSREM(SDNode *N);
173    SDOperand visitUREM(SDNode *N);
174    SDOperand visitMULHU(SDNode *N);
175    SDOperand visitMULHS(SDNode *N);
176    SDOperand visitAND(SDNode *N);
177    SDOperand visitOR(SDNode *N);
178    SDOperand visitXOR(SDNode *N);
179    SDOperand visitSHL(SDNode *N);
180    SDOperand visitSRA(SDNode *N);
181    SDOperand visitSRL(SDNode *N);
182    SDOperand visitCTLZ(SDNode *N);
183    SDOperand visitCTTZ(SDNode *N);
184    SDOperand visitCTPOP(SDNode *N);
185    SDOperand visitSELECT(SDNode *N);
186    SDOperand visitSELECT_CC(SDNode *N);
187    SDOperand visitSETCC(SDNode *N);
188    SDOperand visitSIGN_EXTEND(SDNode *N);
189    SDOperand visitZERO_EXTEND(SDNode *N);
190    SDOperand visitSIGN_EXTEND_INREG(SDNode *N);
191    SDOperand visitTRUNCATE(SDNode *N);
192    SDOperand visitBIT_CONVERT(SDNode *N);
193    SDOperand visitFADD(SDNode *N);
194    SDOperand visitFSUB(SDNode *N);
195    SDOperand visitFMUL(SDNode *N);
196    SDOperand visitFDIV(SDNode *N);
197    SDOperand visitFREM(SDNode *N);
198    SDOperand visitFCOPYSIGN(SDNode *N);
199    SDOperand visitSINT_TO_FP(SDNode *N);
200    SDOperand visitUINT_TO_FP(SDNode *N);
201    SDOperand visitFP_TO_SINT(SDNode *N);
202    SDOperand visitFP_TO_UINT(SDNode *N);
203    SDOperand visitFP_ROUND(SDNode *N);
204    SDOperand visitFP_ROUND_INREG(SDNode *N);
205    SDOperand visitFP_EXTEND(SDNode *N);
206    SDOperand visitFNEG(SDNode *N);
207    SDOperand visitFABS(SDNode *N);
208    SDOperand visitBRCOND(SDNode *N);
209    SDOperand visitBR_CC(SDNode *N);
210    SDOperand visitLOAD(SDNode *N);
211    SDOperand visitSTORE(SDNode *N);
212    SDOperand visitINSERT_VECTOR_ELT(SDNode *N);
213    SDOperand visitVINSERT_VECTOR_ELT(SDNode *N);
214
215    SDOperand ReassociateOps(unsigned Opc, SDOperand LHS, SDOperand RHS);
216
217    bool SimplifySelectOps(SDNode *SELECT, SDOperand LHS, SDOperand RHS);
218    SDOperand SimplifySelect(SDOperand N0, SDOperand N1, SDOperand N2);
219    SDOperand SimplifySelectCC(SDOperand N0, SDOperand N1, SDOperand N2,
220                               SDOperand N3, ISD::CondCode CC);
221    SDOperand SimplifySetCC(MVT::ValueType VT, SDOperand N0, SDOperand N1,
222                            ISD::CondCode Cond, bool foldBooleans = true);
223
224    SDOperand BuildSDIV(SDNode *N);
225    SDOperand BuildUDIV(SDNode *N);
226public:
227    DAGCombiner(SelectionDAG &D)
228      : DAG(D), TLI(D.getTargetLoweringInfo()), AfterLegalize(false) {}
229
230    /// Run - runs the dag combiner on all nodes in the work list
231    void Run(bool RunningAfterLegalize);
232  };
233}
234
235//===----------------------------------------------------------------------===//
236//  TargetLowering::DAGCombinerInfo implementation
237//===----------------------------------------------------------------------===//
238
239void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
240  ((DAGCombiner*)DC)->AddToWorkList(N);
241}
242
243SDOperand TargetLowering::DAGCombinerInfo::
244CombineTo(SDNode *N, const std::vector<SDOperand> &To) {
245  return ((DAGCombiner*)DC)->CombineTo(N, To);
246}
247
248SDOperand TargetLowering::DAGCombinerInfo::
249CombineTo(SDNode *N, SDOperand Res) {
250  return ((DAGCombiner*)DC)->CombineTo(N, Res);
251}
252
253
254SDOperand TargetLowering::DAGCombinerInfo::
255CombineTo(SDNode *N, SDOperand Res0, SDOperand Res1) {
256  return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1);
257}
258
259
260
261
262//===----------------------------------------------------------------------===//
263
264
265struct ms {
266  int64_t m;  // magic number
267  int64_t s;  // shift amount
268};
269
270struct mu {
271  uint64_t m; // magic number
272  int64_t a;  // add indicator
273  int64_t s;  // shift amount
274};
275
276/// magic - calculate the magic numbers required to codegen an integer sdiv as
277/// a sequence of multiply and shifts.  Requires that the divisor not be 0, 1,
278/// or -1.
279static ms magic32(int32_t d) {
280  int32_t p;
281  uint32_t ad, anc, delta, q1, r1, q2, r2, t;
282  const uint32_t two31 = 0x80000000U;
283  struct ms mag;
284
285  ad = abs(d);
286  t = two31 + ((uint32_t)d >> 31);
287  anc = t - 1 - t%ad;   // absolute value of nc
288  p = 31;               // initialize p
289  q1 = two31/anc;       // initialize q1 = 2p/abs(nc)
290  r1 = two31 - q1*anc;  // initialize r1 = rem(2p,abs(nc))
291  q2 = two31/ad;        // initialize q2 = 2p/abs(d)
292  r2 = two31 - q2*ad;   // initialize r2 = rem(2p,abs(d))
293  do {
294    p = p + 1;
295    q1 = 2*q1;        // update q1 = 2p/abs(nc)
296    r1 = 2*r1;        // update r1 = rem(2p/abs(nc))
297    if (r1 >= anc) {  // must be unsigned comparison
298      q1 = q1 + 1;
299      r1 = r1 - anc;
300    }
301    q2 = 2*q2;        // update q2 = 2p/abs(d)
302    r2 = 2*r2;        // update r2 = rem(2p/abs(d))
303    if (r2 >= ad) {   // must be unsigned comparison
304      q2 = q2 + 1;
305      r2 = r2 - ad;
306    }
307    delta = ad - r2;
308  } while (q1 < delta || (q1 == delta && r1 == 0));
309
310  mag.m = (int32_t)(q2 + 1); // make sure to sign extend
311  if (d < 0) mag.m = -mag.m; // resulting magic number
312  mag.s = p - 32;            // resulting shift
313  return mag;
314}
315
316/// magicu - calculate the magic numbers required to codegen an integer udiv as
317/// a sequence of multiply, add and shifts.  Requires that the divisor not be 0.
318static mu magicu32(uint32_t d) {
319  int32_t p;
320  uint32_t nc, delta, q1, r1, q2, r2;
321  struct mu magu;
322  magu.a = 0;               // initialize "add" indicator
323  nc = - 1 - (-d)%d;
324  p = 31;                   // initialize p
325  q1 = 0x80000000/nc;       // initialize q1 = 2p/nc
326  r1 = 0x80000000 - q1*nc;  // initialize r1 = rem(2p,nc)
327  q2 = 0x7FFFFFFF/d;        // initialize q2 = (2p-1)/d
328  r2 = 0x7FFFFFFF - q2*d;   // initialize r2 = rem((2p-1),d)
329  do {
330    p = p + 1;
331    if (r1 >= nc - r1 ) {
332      q1 = 2*q1 + 1;  // update q1
333      r1 = 2*r1 - nc; // update r1
334    }
335    else {
336      q1 = 2*q1; // update q1
337      r1 = 2*r1; // update r1
338    }
339    if (r2 + 1 >= d - r2) {
340      if (q2 >= 0x7FFFFFFF) magu.a = 1;
341      q2 = 2*q2 + 1;     // update q2
342      r2 = 2*r2 + 1 - d; // update r2
343    }
344    else {
345      if (q2 >= 0x80000000) magu.a = 1;
346      q2 = 2*q2;     // update q2
347      r2 = 2*r2 + 1; // update r2
348    }
349    delta = d - 1 - r2;
350  } while (p < 64 && (q1 < delta || (q1 == delta && r1 == 0)));
351  magu.m = q2 + 1; // resulting magic number
352  magu.s = p - 32;  // resulting shift
353  return magu;
354}
355
356/// magic - calculate the magic numbers required to codegen an integer sdiv as
357/// a sequence of multiply and shifts.  Requires that the divisor not be 0, 1,
358/// or -1.
359static ms magic64(int64_t d) {
360  int64_t p;
361  uint64_t ad, anc, delta, q1, r1, q2, r2, t;
362  const uint64_t two63 = 9223372036854775808ULL; // 2^63
363  struct ms mag;
364
365  ad = d >= 0 ? d : -d;
366  t = two63 + ((uint64_t)d >> 63);
367  anc = t - 1 - t%ad;   // absolute value of nc
368  p = 63;               // initialize p
369  q1 = two63/anc;       // initialize q1 = 2p/abs(nc)
370  r1 = two63 - q1*anc;  // initialize r1 = rem(2p,abs(nc))
371  q2 = two63/ad;        // initialize q2 = 2p/abs(d)
372  r2 = two63 - q2*ad;   // initialize r2 = rem(2p,abs(d))
373  do {
374    p = p + 1;
375    q1 = 2*q1;        // update q1 = 2p/abs(nc)
376    r1 = 2*r1;        // update r1 = rem(2p/abs(nc))
377    if (r1 >= anc) {  // must be unsigned comparison
378      q1 = q1 + 1;
379      r1 = r1 - anc;
380    }
381    q2 = 2*q2;        // update q2 = 2p/abs(d)
382    r2 = 2*r2;        // update r2 = rem(2p/abs(d))
383    if (r2 >= ad) {   // must be unsigned comparison
384      q2 = q2 + 1;
385      r2 = r2 - ad;
386    }
387    delta = ad - r2;
388  } while (q1 < delta || (q1 == delta && r1 == 0));
389
390  mag.m = q2 + 1;
391  if (d < 0) mag.m = -mag.m; // resulting magic number
392  mag.s = p - 64;            // resulting shift
393  return mag;
394}
395
396/// magicu - calculate the magic numbers required to codegen an integer udiv as
397/// a sequence of multiply, add and shifts.  Requires that the divisor not be 0.
398static mu magicu64(uint64_t d)
399{
400  int64_t p;
401  uint64_t nc, delta, q1, r1, q2, r2;
402  struct mu magu;
403  magu.a = 0;               // initialize "add" indicator
404  nc = - 1 - (-d)%d;
405  p = 63;                   // initialize p
406  q1 = 0x8000000000000000ull/nc;       // initialize q1 = 2p/nc
407  r1 = 0x8000000000000000ull - q1*nc;  // initialize r1 = rem(2p,nc)
408  q2 = 0x7FFFFFFFFFFFFFFFull/d;        // initialize q2 = (2p-1)/d
409  r2 = 0x7FFFFFFFFFFFFFFFull - q2*d;   // initialize r2 = rem((2p-1),d)
410  do {
411    p = p + 1;
412    if (r1 >= nc - r1 ) {
413      q1 = 2*q1 + 1;  // update q1
414      r1 = 2*r1 - nc; // update r1
415    }
416    else {
417      q1 = 2*q1; // update q1
418      r1 = 2*r1; // update r1
419    }
420    if (r2 + 1 >= d - r2) {
421      if (q2 >= 0x7FFFFFFFFFFFFFFFull) magu.a = 1;
422      q2 = 2*q2 + 1;     // update q2
423      r2 = 2*r2 + 1 - d; // update r2
424    }
425    else {
426      if (q2 >= 0x8000000000000000ull) magu.a = 1;
427      q2 = 2*q2;     // update q2
428      r2 = 2*r2 + 1; // update r2
429    }
430    delta = d - 1 - r2;
431  } while (p < 64 && (q1 < delta || (q1 == delta && r1 == 0)));
432  magu.m = q2 + 1; // resulting magic number
433  magu.s = p - 64;  // resulting shift
434  return magu;
435}
436
437// isSetCCEquivalent - Return true if this node is a setcc, or is a select_cc
438// that selects between the values 1 and 0, making it equivalent to a setcc.
439// Also, set the incoming LHS, RHS, and CC references to the appropriate
440// nodes based on the type of node we are checking.  This simplifies life a
441// bit for the callers.
442static bool isSetCCEquivalent(SDOperand N, SDOperand &LHS, SDOperand &RHS,
443                              SDOperand &CC) {
444  if (N.getOpcode() == ISD::SETCC) {
445    LHS = N.getOperand(0);
446    RHS = N.getOperand(1);
447    CC  = N.getOperand(2);
448    return true;
449  }
450  if (N.getOpcode() == ISD::SELECT_CC &&
451      N.getOperand(2).getOpcode() == ISD::Constant &&
452      N.getOperand(3).getOpcode() == ISD::Constant &&
453      cast<ConstantSDNode>(N.getOperand(2))->getValue() == 1 &&
454      cast<ConstantSDNode>(N.getOperand(3))->isNullValue()) {
455    LHS = N.getOperand(0);
456    RHS = N.getOperand(1);
457    CC  = N.getOperand(4);
458    return true;
459  }
460  return false;
461}
462
463// isOneUseSetCC - Return true if this is a SetCC-equivalent operation with only
464// one use.  If this is true, it allows the users to invert the operation for
465// free when it is profitable to do so.
466static bool isOneUseSetCC(SDOperand N) {
467  SDOperand N0, N1, N2;
468  if (isSetCCEquivalent(N, N0, N1, N2) && N.Val->hasOneUse())
469    return true;
470  return false;
471}
472
473// FIXME: This should probably go in the ISD class rather than being duplicated
474// in several files.
475static bool isCommutativeBinOp(unsigned Opcode) {
476  switch (Opcode) {
477    case ISD::ADD:
478    case ISD::MUL:
479    case ISD::AND:
480    case ISD::OR:
481    case ISD::XOR: return true;
482    default: return false; // FIXME: Need commutative info for user ops!
483  }
484}
485
486SDOperand DAGCombiner::ReassociateOps(unsigned Opc, SDOperand N0, SDOperand N1){
487  MVT::ValueType VT = N0.getValueType();
488  // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one use
489  // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
490  if (N0.getOpcode() == Opc && isa<ConstantSDNode>(N0.getOperand(1))) {
491    if (isa<ConstantSDNode>(N1)) {
492      SDOperand OpNode = DAG.getNode(Opc, VT, N0.getOperand(1), N1);
493      AddToWorkList(OpNode.Val);
494      return DAG.getNode(Opc, VT, OpNode, N0.getOperand(0));
495    } else if (N0.hasOneUse()) {
496      SDOperand OpNode = DAG.getNode(Opc, VT, N0.getOperand(0), N1);
497      AddToWorkList(OpNode.Val);
498      return DAG.getNode(Opc, VT, OpNode, N0.getOperand(1));
499    }
500  }
501  // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one use
502  // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
503  if (N1.getOpcode() == Opc && isa<ConstantSDNode>(N1.getOperand(1))) {
504    if (isa<ConstantSDNode>(N0)) {
505      SDOperand OpNode = DAG.getNode(Opc, VT, N1.getOperand(1), N0);
506      AddToWorkList(OpNode.Val);
507      return DAG.getNode(Opc, VT, OpNode, N1.getOperand(0));
508    } else if (N1.hasOneUse()) {
509      SDOperand OpNode = DAG.getNode(Opc, VT, N1.getOperand(0), N0);
510      AddToWorkList(OpNode.Val);
511      return DAG.getNode(Opc, VT, OpNode, N1.getOperand(1));
512    }
513  }
514  return SDOperand();
515}
516
517void DAGCombiner::Run(bool RunningAfterLegalize) {
518  // set the instance variable, so that the various visit routines may use it.
519  AfterLegalize = RunningAfterLegalize;
520
521  // Add all the dag nodes to the worklist.
522  for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
523       E = DAG.allnodes_end(); I != E; ++I)
524    WorkList.push_back(I);
525
526  // Create a dummy node (which is not added to allnodes), that adds a reference
527  // to the root node, preventing it from being deleted, and tracking any
528  // changes of the root.
529  HandleSDNode Dummy(DAG.getRoot());
530
531
532  /// DagCombineInfo - Expose the DAG combiner to the target combiner impls.
533  TargetLowering::DAGCombinerInfo
534    DagCombineInfo(DAG, !RunningAfterLegalize, this);
535
536  // while the worklist isn't empty, inspect the node on the end of it and
537  // try and combine it.
538  while (!WorkList.empty()) {
539    SDNode *N = WorkList.back();
540    WorkList.pop_back();
541
542    // If N has no uses, it is dead.  Make sure to revisit all N's operands once
543    // N is deleted from the DAG, since they too may now be dead or may have a
544    // reduced number of uses, allowing other xforms.
545    if (N->use_empty() && N != &Dummy) {
546      for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
547        WorkList.push_back(N->getOperand(i).Val);
548
549      removeFromWorkList(N);
550      DAG.DeleteNode(N);
551      continue;
552    }
553
554    SDOperand RV = visit(N);
555
556    // If nothing happened, try a target-specific DAG combine.
557    if (RV.Val == 0) {
558      if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
559          TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode()))
560        RV = TLI.PerformDAGCombine(N, DagCombineInfo);
561    }
562
563    if (RV.Val) {
564      ++NodesCombined;
565      // If we get back the same node we passed in, rather than a new node or
566      // zero, we know that the node must have defined multiple values and
567      // CombineTo was used.  Since CombineTo takes care of the worklist
568      // mechanics for us, we have no work to do in this case.
569      if (RV.Val != N) {
570        DEBUG(std::cerr << "\nReplacing "; N->dump();
571              std::cerr << "\nWith: "; RV.Val->dump();
572              std::cerr << '\n');
573        std::vector<SDNode*> NowDead;
574        DAG.ReplaceAllUsesWith(N, std::vector<SDOperand>(1, RV), &NowDead);
575
576        // Push the new node and any users onto the worklist
577        WorkList.push_back(RV.Val);
578        AddUsersToWorkList(RV.Val);
579
580        // Nodes can end up on the worklist more than once.  Make sure we do
581        // not process a node that has been replaced.
582        removeFromWorkList(N);
583        for (unsigned i = 0, e = NowDead.size(); i != e; ++i)
584          removeFromWorkList(NowDead[i]);
585
586        // Finally, since the node is now dead, remove it from the graph.
587        DAG.DeleteNode(N);
588      }
589    }
590  }
591
592  // If the root changed (e.g. it was a dead load, update the root).
593  DAG.setRoot(Dummy.getValue());
594}
595
596SDOperand DAGCombiner::visit(SDNode *N) {
597  switch(N->getOpcode()) {
598  default: break;
599  case ISD::TokenFactor:        return visitTokenFactor(N);
600  case ISD::ADD:                return visitADD(N);
601  case ISD::SUB:                return visitSUB(N);
602  case ISD::MUL:                return visitMUL(N);
603  case ISD::SDIV:               return visitSDIV(N);
604  case ISD::UDIV:               return visitUDIV(N);
605  case ISD::SREM:               return visitSREM(N);
606  case ISD::UREM:               return visitUREM(N);
607  case ISD::MULHU:              return visitMULHU(N);
608  case ISD::MULHS:              return visitMULHS(N);
609  case ISD::AND:                return visitAND(N);
610  case ISD::OR:                 return visitOR(N);
611  case ISD::XOR:                return visitXOR(N);
612  case ISD::SHL:                return visitSHL(N);
613  case ISD::SRA:                return visitSRA(N);
614  case ISD::SRL:                return visitSRL(N);
615  case ISD::CTLZ:               return visitCTLZ(N);
616  case ISD::CTTZ:               return visitCTTZ(N);
617  case ISD::CTPOP:              return visitCTPOP(N);
618  case ISD::SELECT:             return visitSELECT(N);
619  case ISD::SELECT_CC:          return visitSELECT_CC(N);
620  case ISD::SETCC:              return visitSETCC(N);
621  case ISD::SIGN_EXTEND:        return visitSIGN_EXTEND(N);
622  case ISD::ZERO_EXTEND:        return visitZERO_EXTEND(N);
623  case ISD::SIGN_EXTEND_INREG:  return visitSIGN_EXTEND_INREG(N);
624  case ISD::TRUNCATE:           return visitTRUNCATE(N);
625  case ISD::BIT_CONVERT:        return visitBIT_CONVERT(N);
626  case ISD::FADD:               return visitFADD(N);
627  case ISD::FSUB:               return visitFSUB(N);
628  case ISD::FMUL:               return visitFMUL(N);
629  case ISD::FDIV:               return visitFDIV(N);
630  case ISD::FREM:               return visitFREM(N);
631  case ISD::FCOPYSIGN:          return visitFCOPYSIGN(N);
632  case ISD::SINT_TO_FP:         return visitSINT_TO_FP(N);
633  case ISD::UINT_TO_FP:         return visitUINT_TO_FP(N);
634  case ISD::FP_TO_SINT:         return visitFP_TO_SINT(N);
635  case ISD::FP_TO_UINT:         return visitFP_TO_UINT(N);
636  case ISD::FP_ROUND:           return visitFP_ROUND(N);
637  case ISD::FP_ROUND_INREG:     return visitFP_ROUND_INREG(N);
638  case ISD::FP_EXTEND:          return visitFP_EXTEND(N);
639  case ISD::FNEG:               return visitFNEG(N);
640  case ISD::FABS:               return visitFABS(N);
641  case ISD::BRCOND:             return visitBRCOND(N);
642  case ISD::BR_CC:              return visitBR_CC(N);
643  case ISD::LOAD:               return visitLOAD(N);
644  case ISD::STORE:              return visitSTORE(N);
645  case ISD::INSERT_VECTOR_ELT:  return visitINSERT_VECTOR_ELT(N);
646  case ISD::VINSERT_VECTOR_ELT: return visitVINSERT_VECTOR_ELT(N);
647  }
648  return SDOperand();
649}
650
651SDOperand DAGCombiner::visitTokenFactor(SDNode *N) {
652  std::vector<SDOperand> Ops;
653  bool Changed = false;
654
655  // If the token factor has two operands and one is the entry token, replace
656  // the token factor with the other operand.
657  if (N->getNumOperands() == 2) {
658    if (N->getOperand(0).getOpcode() == ISD::EntryToken)
659      return N->getOperand(1);
660    if (N->getOperand(1).getOpcode() == ISD::EntryToken)
661      return N->getOperand(0);
662  }
663
664  // fold (tokenfactor (tokenfactor)) -> tokenfactor
665  for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
666    SDOperand Op = N->getOperand(i);
667    if (Op.getOpcode() == ISD::TokenFactor && Op.hasOneUse()) {
668      AddToWorkList(Op.Val);  // Remove dead node.
669      Changed = true;
670      for (unsigned j = 0, e = Op.getNumOperands(); j != e; ++j)
671        Ops.push_back(Op.getOperand(j));
672    } else {
673      Ops.push_back(Op);
674    }
675  }
676  if (Changed)
677    return DAG.getNode(ISD::TokenFactor, MVT::Other, Ops);
678  return SDOperand();
679}
680
681SDOperand DAGCombiner::visitADD(SDNode *N) {
682  SDOperand N0 = N->getOperand(0);
683  SDOperand N1 = N->getOperand(1);
684  ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
685  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
686  MVT::ValueType VT = N0.getValueType();
687
688  // fold (add c1, c2) -> c1+c2
689  if (N0C && N1C)
690    return DAG.getNode(ISD::ADD, VT, N0, N1);
691  // canonicalize constant to RHS
692  if (N0C && !N1C)
693    return DAG.getNode(ISD::ADD, VT, N1, N0);
694  // fold (add x, 0) -> x
695  if (N1C && N1C->isNullValue())
696    return N0;
697  // fold ((c1-A)+c2) -> (c1+c2)-A
698  if (N1C && N0.getOpcode() == ISD::SUB)
699    if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
700      return DAG.getNode(ISD::SUB, VT,
701                         DAG.getConstant(N1C->getValue()+N0C->getValue(), VT),
702                         N0.getOperand(1));
703  // reassociate add
704  SDOperand RADD = ReassociateOps(ISD::ADD, N0, N1);
705  if (RADD.Val != 0)
706    return RADD;
707  // fold ((0-A) + B) -> B-A
708  if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
709      cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
710    return DAG.getNode(ISD::SUB, VT, N1, N0.getOperand(1));
711  // fold (A + (0-B)) -> A-B
712  if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
713      cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
714    return DAG.getNode(ISD::SUB, VT, N0, N1.getOperand(1));
715  // fold (A+(B-A)) -> B
716  if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
717    return N1.getOperand(0);
718
719  if (!MVT::isVector(VT) && SimplifyDemandedBits(SDOperand(N, 0)))
720    return SDOperand();
721
722  // fold (a+b) -> (a|b) iff a and b share no bits.
723  if (MVT::isInteger(VT) && !MVT::isVector(VT)) {
724    uint64_t LHSZero, LHSOne;
725    uint64_t RHSZero, RHSOne;
726    uint64_t Mask = MVT::getIntVTBitMask(VT);
727    TLI.ComputeMaskedBits(N0, Mask, LHSZero, LHSOne);
728    if (LHSZero) {
729      TLI.ComputeMaskedBits(N1, Mask, RHSZero, RHSOne);
730
731      // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
732      // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
733      if ((RHSZero & (~LHSZero & Mask)) == (~LHSZero & Mask) ||
734          (LHSZero & (~RHSZero & Mask)) == (~RHSZero & Mask))
735        return DAG.getNode(ISD::OR, VT, N0, N1);
736    }
737  }
738
739  return SDOperand();
740}
741
742SDOperand DAGCombiner::visitSUB(SDNode *N) {
743  SDOperand N0 = N->getOperand(0);
744  SDOperand N1 = N->getOperand(1);
745  ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.Val);
746  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val);
747  MVT::ValueType VT = N0.getValueType();
748
749  // fold (sub x, x) -> 0
750  if (N0 == N1)
751    return DAG.getConstant(0, N->getValueType(0));
752  // fold (sub c1, c2) -> c1-c2
753  if (N0C && N1C)
754    return DAG.getNode(ISD::SUB, VT, N0, N1);
755  // fold (sub x, c) -> (add x, -c)
756  if (N1C)
757    return DAG.getNode(ISD::ADD, VT, N0, DAG.getConstant(-N1C->getValue(), VT));
758  // fold (A+B)-A -> B
759  if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
760    return N0.getOperand(1);
761  // fold (A+B)-B -> A
762  if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
763    return N0.getOperand(0);
764  return SDOperand();
765}
766
767SDOperand DAGCombiner::visitMUL(SDNode *N) {
768  SDOperand N0 = N->getOperand(0);
769  SDOperand N1 = N->getOperand(1);
770  ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
771  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
772  MVT::ValueType VT = N0.getValueType();
773
774  // fold (mul c1, c2) -> c1*c2
775  if (N0C && N1C)
776    return DAG.getNode(ISD::MUL, VT, N0, N1);
777  // canonicalize constant to RHS
778  if (N0C && !N1C)
779    return DAG.getNode(ISD::MUL, VT, N1, N0);
780  // fold (mul x, 0) -> 0
781  if (N1C && N1C->isNullValue())
782    return N1;
783  // fold (mul x, -1) -> 0-x
784  if (N1C && N1C->isAllOnesValue())
785    return DAG.getNode(ISD::SUB, VT, DAG.getConstant(0, VT), N0);
786  // fold (mul x, (1 << c)) -> x << c
787  if (N1C && isPowerOf2_64(N1C->getValue()))
788    return DAG.getNode(ISD::SHL, VT, N0,
789                       DAG.getConstant(Log2_64(N1C->getValue()),
790                                       TLI.getShiftAmountTy()));
791  // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
792  if (N1C && isPowerOf2_64(-N1C->getSignExtended())) {
793    // FIXME: If the input is something that is easily negated (e.g. a
794    // single-use add), we should put the negate there.
795    return DAG.getNode(ISD::SUB, VT, DAG.getConstant(0, VT),
796                       DAG.getNode(ISD::SHL, VT, N0,
797                            DAG.getConstant(Log2_64(-N1C->getSignExtended()),
798                                            TLI.getShiftAmountTy())));
799  }
800
801  // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
802  if (N1C && N0.getOpcode() == ISD::SHL &&
803      isa<ConstantSDNode>(N0.getOperand(1))) {
804    SDOperand C3 = DAG.getNode(ISD::SHL, VT, N1, N0.getOperand(1));
805    AddToWorkList(C3.Val);
806    return DAG.getNode(ISD::MUL, VT, N0.getOperand(0), C3);
807  }
808
809  // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
810  // use.
811  {
812    SDOperand Sh(0,0), Y(0,0);
813    // Check for both (mul (shl X, C), Y)  and  (mul Y, (shl X, C)).
814    if (N0.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N0.getOperand(1)) &&
815        N0.Val->hasOneUse()) {
816      Sh = N0; Y = N1;
817    } else if (N1.getOpcode() == ISD::SHL &&
818               isa<ConstantSDNode>(N1.getOperand(1)) && N1.Val->hasOneUse()) {
819      Sh = N1; Y = N0;
820    }
821    if (Sh.Val) {
822      SDOperand Mul = DAG.getNode(ISD::MUL, VT, Sh.getOperand(0), Y);
823      return DAG.getNode(ISD::SHL, VT, Mul, Sh.getOperand(1));
824    }
825  }
826  // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
827  if (N1C && N0.getOpcode() == ISD::ADD && N0.Val->hasOneUse() &&
828      isa<ConstantSDNode>(N0.getOperand(1))) {
829    return DAG.getNode(ISD::ADD, VT,
830                       DAG.getNode(ISD::MUL, VT, N0.getOperand(0), N1),
831                       DAG.getNode(ISD::MUL, VT, N0.getOperand(1), N1));
832  }
833
834  // reassociate mul
835  SDOperand RMUL = ReassociateOps(ISD::MUL, N0, N1);
836  if (RMUL.Val != 0)
837    return RMUL;
838  return SDOperand();
839}
840
841SDOperand DAGCombiner::visitSDIV(SDNode *N) {
842  SDOperand N0 = N->getOperand(0);
843  SDOperand N1 = N->getOperand(1);
844  ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.Val);
845  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val);
846  MVT::ValueType VT = N->getValueType(0);
847
848  // fold (sdiv c1, c2) -> c1/c2
849  if (N0C && N1C && !N1C->isNullValue())
850    return DAG.getNode(ISD::SDIV, VT, N0, N1);
851  // fold (sdiv X, 1) -> X
852  if (N1C && N1C->getSignExtended() == 1LL)
853    return N0;
854  // fold (sdiv X, -1) -> 0-X
855  if (N1C && N1C->isAllOnesValue())
856    return DAG.getNode(ISD::SUB, VT, DAG.getConstant(0, VT), N0);
857  // If we know the sign bits of both operands are zero, strength reduce to a
858  // udiv instead.  Handles (X&15) /s 4 -> X&15 >> 2
859  uint64_t SignBit = 1ULL << (MVT::getSizeInBits(VT)-1);
860  if (TLI.MaskedValueIsZero(N1, SignBit) &&
861      TLI.MaskedValueIsZero(N0, SignBit))
862    return DAG.getNode(ISD::UDIV, N1.getValueType(), N0, N1);
863  // fold (sdiv X, pow2) -> simple ops after legalize
864  if (N1C && N1C->getValue() && !TLI.isIntDivCheap() &&
865      (isPowerOf2_64(N1C->getSignExtended()) ||
866       isPowerOf2_64(-N1C->getSignExtended()))) {
867    // If dividing by powers of two is cheap, then don't perform the following
868    // fold.
869    if (TLI.isPow2DivCheap())
870      return SDOperand();
871    int64_t pow2 = N1C->getSignExtended();
872    int64_t abs2 = pow2 > 0 ? pow2 : -pow2;
873    unsigned lg2 = Log2_64(abs2);
874    // Splat the sign bit into the register
875    SDOperand SGN = DAG.getNode(ISD::SRA, VT, N0,
876                                DAG.getConstant(MVT::getSizeInBits(VT)-1,
877                                                TLI.getShiftAmountTy()));
878    AddToWorkList(SGN.Val);
879    // Add (N0 < 0) ? abs2 - 1 : 0;
880    SDOperand SRL = DAG.getNode(ISD::SRL, VT, SGN,
881                                DAG.getConstant(MVT::getSizeInBits(VT)-lg2,
882                                                TLI.getShiftAmountTy()));
883    SDOperand ADD = DAG.getNode(ISD::ADD, VT, N0, SRL);
884    AddToWorkList(SRL.Val);
885    AddToWorkList(ADD.Val);    // Divide by pow2
886    SDOperand SRA = DAG.getNode(ISD::SRA, VT, ADD,
887                                DAG.getConstant(lg2, TLI.getShiftAmountTy()));
888    // If we're dividing by a positive value, we're done.  Otherwise, we must
889    // negate the result.
890    if (pow2 > 0)
891      return SRA;
892    AddToWorkList(SRA.Val);
893    return DAG.getNode(ISD::SUB, VT, DAG.getConstant(0, VT), SRA);
894  }
895  // if integer divide is expensive and we satisfy the requirements, emit an
896  // alternate sequence.
897  if (N1C && (N1C->getSignExtended() < -1 || N1C->getSignExtended() > 1) &&
898      !TLI.isIntDivCheap()) {
899    SDOperand Op = BuildSDIV(N);
900    if (Op.Val) return Op;
901  }
902  return SDOperand();
903}
904
905SDOperand DAGCombiner::visitUDIV(SDNode *N) {
906  SDOperand N0 = N->getOperand(0);
907  SDOperand N1 = N->getOperand(1);
908  ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.Val);
909  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val);
910  MVT::ValueType VT = N->getValueType(0);
911
912  // fold (udiv c1, c2) -> c1/c2
913  if (N0C && N1C && !N1C->isNullValue())
914    return DAG.getNode(ISD::UDIV, VT, N0, N1);
915  // fold (udiv x, (1 << c)) -> x >>u c
916  if (N1C && isPowerOf2_64(N1C->getValue()))
917    return DAG.getNode(ISD::SRL, VT, N0,
918                       DAG.getConstant(Log2_64(N1C->getValue()),
919                                       TLI.getShiftAmountTy()));
920  // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
921  if (N1.getOpcode() == ISD::SHL) {
922    if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
923      if (isPowerOf2_64(SHC->getValue())) {
924        MVT::ValueType ADDVT = N1.getOperand(1).getValueType();
925        SDOperand Add = DAG.getNode(ISD::ADD, ADDVT, N1.getOperand(1),
926                                    DAG.getConstant(Log2_64(SHC->getValue()),
927                                                    ADDVT));
928        AddToWorkList(Add.Val);
929        return DAG.getNode(ISD::SRL, VT, N0, Add);
930      }
931    }
932  }
933  // fold (udiv x, c) -> alternate
934  if (N1C && N1C->getValue() && !TLI.isIntDivCheap()) {
935    SDOperand Op = BuildUDIV(N);
936    if (Op.Val) return Op;
937  }
938  return SDOperand();
939}
940
941SDOperand DAGCombiner::visitSREM(SDNode *N) {
942  SDOperand N0 = N->getOperand(0);
943  SDOperand N1 = N->getOperand(1);
944  ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
945  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
946  MVT::ValueType VT = N->getValueType(0);
947
948  // fold (srem c1, c2) -> c1%c2
949  if (N0C && N1C && !N1C->isNullValue())
950    return DAG.getNode(ISD::SREM, VT, N0, N1);
951  // If we know the sign bits of both operands are zero, strength reduce to a
952  // urem instead.  Handles (X & 0x0FFFFFFF) %s 16 -> X&15
953  uint64_t SignBit = 1ULL << (MVT::getSizeInBits(VT)-1);
954  if (TLI.MaskedValueIsZero(N1, SignBit) &&
955      TLI.MaskedValueIsZero(N0, SignBit))
956    return DAG.getNode(ISD::UREM, VT, N0, N1);
957  return SDOperand();
958}
959
960SDOperand DAGCombiner::visitUREM(SDNode *N) {
961  SDOperand N0 = N->getOperand(0);
962  SDOperand N1 = N->getOperand(1);
963  ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
964  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
965  MVT::ValueType VT = N->getValueType(0);
966
967  // fold (urem c1, c2) -> c1%c2
968  if (N0C && N1C && !N1C->isNullValue())
969    return DAG.getNode(ISD::UREM, VT, N0, N1);
970  // fold (urem x, pow2) -> (and x, pow2-1)
971  if (N1C && !N1C->isNullValue() && isPowerOf2_64(N1C->getValue()))
972    return DAG.getNode(ISD::AND, VT, N0, DAG.getConstant(N1C->getValue()-1,VT));
973  // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
974  if (N1.getOpcode() == ISD::SHL) {
975    if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
976      if (isPowerOf2_64(SHC->getValue())) {
977        SDOperand Add = DAG.getNode(ISD::ADD, VT, N1,DAG.getConstant(~0ULL,VT));
978        AddToWorkList(Add.Val);
979        return DAG.getNode(ISD::AND, VT, N0, Add);
980      }
981    }
982  }
983  return SDOperand();
984}
985
986SDOperand DAGCombiner::visitMULHS(SDNode *N) {
987  SDOperand N0 = N->getOperand(0);
988  SDOperand N1 = N->getOperand(1);
989  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
990
991  // fold (mulhs x, 0) -> 0
992  if (N1C && N1C->isNullValue())
993    return N1;
994  // fold (mulhs x, 1) -> (sra x, size(x)-1)
995  if (N1C && N1C->getValue() == 1)
996    return DAG.getNode(ISD::SRA, N0.getValueType(), N0,
997                       DAG.getConstant(MVT::getSizeInBits(N0.getValueType())-1,
998                                       TLI.getShiftAmountTy()));
999  return SDOperand();
1000}
1001
1002SDOperand DAGCombiner::visitMULHU(SDNode *N) {
1003  SDOperand N0 = N->getOperand(0);
1004  SDOperand N1 = N->getOperand(1);
1005  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1006
1007  // fold (mulhu x, 0) -> 0
1008  if (N1C && N1C->isNullValue())
1009    return N1;
1010  // fold (mulhu x, 1) -> 0
1011  if (N1C && N1C->getValue() == 1)
1012    return DAG.getConstant(0, N0.getValueType());
1013  return SDOperand();
1014}
1015
1016SDOperand DAGCombiner::visitAND(SDNode *N) {
1017  SDOperand N0 = N->getOperand(0);
1018  SDOperand N1 = N->getOperand(1);
1019  SDOperand LL, LR, RL, RR, CC0, CC1;
1020  ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1021  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1022  MVT::ValueType VT = N1.getValueType();
1023  unsigned OpSizeInBits = MVT::getSizeInBits(VT);
1024
1025  // fold (and c1, c2) -> c1&c2
1026  if (N0C && N1C)
1027    return DAG.getNode(ISD::AND, VT, N0, N1);
1028  // canonicalize constant to RHS
1029  if (N0C && !N1C)
1030    return DAG.getNode(ISD::AND, VT, N1, N0);
1031  // fold (and x, -1) -> x
1032  if (N1C && N1C->isAllOnesValue())
1033    return N0;
1034  // if (and x, c) is known to be zero, return 0
1035  if (N1C && TLI.MaskedValueIsZero(SDOperand(N, 0), MVT::getIntVTBitMask(VT)))
1036    return DAG.getConstant(0, VT);
1037  // reassociate and
1038  SDOperand RAND = ReassociateOps(ISD::AND, N0, N1);
1039  if (RAND.Val != 0)
1040    return RAND;
1041  // fold (and (or x, 0xFFFF), 0xFF) -> 0xFF
1042  if (N1C && N0.getOpcode() == ISD::OR)
1043    if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
1044      if ((ORI->getValue() & N1C->getValue()) == N1C->getValue())
1045        return N1;
1046  // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
1047  if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
1048    unsigned InMask = MVT::getIntVTBitMask(N0.getOperand(0).getValueType());
1049    if (TLI.MaskedValueIsZero(N0.getOperand(0),
1050                              ~N1C->getValue() & InMask)) {
1051      SDOperand Zext = DAG.getNode(ISD::ZERO_EXTEND, N0.getValueType(),
1052                                   N0.getOperand(0));
1053
1054      // Replace uses of the AND with uses of the Zero extend node.
1055      CombineTo(N, Zext);
1056
1057      // We actually want to replace all uses of the any_extend with the
1058      // zero_extend, to avoid duplicating things.  This will later cause this
1059      // AND to be folded.
1060      CombineTo(N0.Val, Zext);
1061      return SDOperand();
1062    }
1063  }
1064  // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
1065  if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
1066    ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
1067    ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
1068
1069    if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
1070        MVT::isInteger(LL.getValueType())) {
1071      // fold (X == 0) & (Y == 0) -> (X|Y == 0)
1072      if (cast<ConstantSDNode>(LR)->getValue() == 0 && Op1 == ISD::SETEQ) {
1073        SDOperand ORNode = DAG.getNode(ISD::OR, LR.getValueType(), LL, RL);
1074        AddToWorkList(ORNode.Val);
1075        return DAG.getSetCC(VT, ORNode, LR, Op1);
1076      }
1077      // fold (X == -1) & (Y == -1) -> (X&Y == -1)
1078      if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
1079        SDOperand ANDNode = DAG.getNode(ISD::AND, LR.getValueType(), LL, RL);
1080        AddToWorkList(ANDNode.Val);
1081        return DAG.getSetCC(VT, ANDNode, LR, Op1);
1082      }
1083      // fold (X >  -1) & (Y >  -1) -> (X|Y > -1)
1084      if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
1085        SDOperand ORNode = DAG.getNode(ISD::OR, LR.getValueType(), LL, RL);
1086        AddToWorkList(ORNode.Val);
1087        return DAG.getSetCC(VT, ORNode, LR, Op1);
1088      }
1089    }
1090    // canonicalize equivalent to ll == rl
1091    if (LL == RR && LR == RL) {
1092      Op1 = ISD::getSetCCSwappedOperands(Op1);
1093      std::swap(RL, RR);
1094    }
1095    if (LL == RL && LR == RR) {
1096      bool isInteger = MVT::isInteger(LL.getValueType());
1097      ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
1098      if (Result != ISD::SETCC_INVALID)
1099        return DAG.getSetCC(N0.getValueType(), LL, LR, Result);
1100    }
1101  }
1102  // fold (and (zext x), (zext y)) -> (zext (and x, y))
1103  if (N0.getOpcode() == ISD::ZERO_EXTEND &&
1104      N1.getOpcode() == ISD::ZERO_EXTEND &&
1105      N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()) {
1106    SDOperand ANDNode = DAG.getNode(ISD::AND, N0.getOperand(0).getValueType(),
1107                                    N0.getOperand(0), N1.getOperand(0));
1108    AddToWorkList(ANDNode.Val);
1109    return DAG.getNode(ISD::ZERO_EXTEND, VT, ANDNode);
1110  }
1111  // fold (and (shl/srl/sra x), (shl/srl/sra y)) -> (shl/srl/sra (and x, y))
1112  if (((N0.getOpcode() == ISD::SHL && N1.getOpcode() == ISD::SHL) ||
1113       (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SRL) ||
1114       (N0.getOpcode() == ISD::SRA && N1.getOpcode() == ISD::SRA)) &&
1115      N0.getOperand(1) == N1.getOperand(1)) {
1116    SDOperand ANDNode = DAG.getNode(ISD::AND, N0.getOperand(0).getValueType(),
1117                                    N0.getOperand(0), N1.getOperand(0));
1118    AddToWorkList(ANDNode.Val);
1119    return DAG.getNode(N0.getOpcode(), VT, ANDNode, N0.getOperand(1));
1120  }
1121  // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
1122  // fold (and (sra)) -> (and (srl)) when possible.
1123  if (!MVT::isVector(VT) &&
1124      SimplifyDemandedBits(SDOperand(N, 0)))
1125    return SDOperand();
1126  // fold (zext_inreg (extload x)) -> (zextload x)
1127  if (N0.getOpcode() == ISD::EXTLOAD) {
1128    MVT::ValueType EVT = cast<VTSDNode>(N0.getOperand(3))->getVT();
1129    // If we zero all the possible extended bits, then we can turn this into
1130    // a zextload if we are running before legalize or the operation is legal.
1131    if (TLI.MaskedValueIsZero(N1, ~0ULL << MVT::getSizeInBits(EVT)) &&
1132        (!AfterLegalize || TLI.isOperationLegal(ISD::ZEXTLOAD, EVT))) {
1133      SDOperand ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, VT, N0.getOperand(0),
1134                                         N0.getOperand(1), N0.getOperand(2),
1135                                         EVT);
1136      AddToWorkList(N);
1137      CombineTo(N0.Val, ExtLoad, ExtLoad.getValue(1));
1138      return SDOperand();
1139    }
1140  }
1141  // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
1142  if (N0.getOpcode() == ISD::SEXTLOAD && N0.hasOneUse()) {
1143    MVT::ValueType EVT = cast<VTSDNode>(N0.getOperand(3))->getVT();
1144    // If we zero all the possible extended bits, then we can turn this into
1145    // a zextload if we are running before legalize or the operation is legal.
1146    if (TLI.MaskedValueIsZero(N1, ~0ULL << MVT::getSizeInBits(EVT)) &&
1147        (!AfterLegalize || TLI.isOperationLegal(ISD::ZEXTLOAD, EVT))) {
1148      SDOperand ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, VT, N0.getOperand(0),
1149                                         N0.getOperand(1), N0.getOperand(2),
1150                                         EVT);
1151      AddToWorkList(N);
1152      CombineTo(N0.Val, ExtLoad, ExtLoad.getValue(1));
1153      return SDOperand();
1154    }
1155  }
1156
1157  // fold (and (load x), 255) -> (zextload x, i8)
1158  // fold (and (extload x, i16), 255) -> (zextload x, i8)
1159  if (N1C &&
1160      (N0.getOpcode() == ISD::LOAD || N0.getOpcode() == ISD::EXTLOAD ||
1161       N0.getOpcode() == ISD::ZEXTLOAD) &&
1162      N0.hasOneUse()) {
1163    MVT::ValueType EVT, LoadedVT;
1164    if (N1C->getValue() == 255)
1165      EVT = MVT::i8;
1166    else if (N1C->getValue() == 65535)
1167      EVT = MVT::i16;
1168    else if (N1C->getValue() == ~0U)
1169      EVT = MVT::i32;
1170    else
1171      EVT = MVT::Other;
1172
1173    LoadedVT = N0.getOpcode() == ISD::LOAD ? VT :
1174                           cast<VTSDNode>(N0.getOperand(3))->getVT();
1175    if (EVT != MVT::Other && LoadedVT > EVT) {
1176      MVT::ValueType PtrType = N0.getOperand(1).getValueType();
1177      // For big endian targets, we need to add an offset to the pointer to load
1178      // the correct bytes.  For little endian systems, we merely need to read
1179      // fewer bytes from the same pointer.
1180      unsigned PtrOff =
1181        (MVT::getSizeInBits(LoadedVT) - MVT::getSizeInBits(EVT)) / 8;
1182      SDOperand NewPtr = N0.getOperand(1);
1183      if (!TLI.isLittleEndian())
1184        NewPtr = DAG.getNode(ISD::ADD, PtrType, NewPtr,
1185                             DAG.getConstant(PtrOff, PtrType));
1186      AddToWorkList(NewPtr.Val);
1187      SDOperand Load =
1188        DAG.getExtLoad(ISD::ZEXTLOAD, VT, N0.getOperand(0), NewPtr,
1189                       N0.getOperand(2), EVT);
1190      AddToWorkList(N);
1191      CombineTo(N0.Val, Load, Load.getValue(1));
1192      return SDOperand();
1193    }
1194  }
1195
1196  return SDOperand();
1197}
1198
1199SDOperand DAGCombiner::visitOR(SDNode *N) {
1200  SDOperand N0 = N->getOperand(0);
1201  SDOperand N1 = N->getOperand(1);
1202  SDOperand LL, LR, RL, RR, CC0, CC1;
1203  ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1204  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1205  MVT::ValueType VT = N1.getValueType();
1206  unsigned OpSizeInBits = MVT::getSizeInBits(VT);
1207
1208  // fold (or c1, c2) -> c1|c2
1209  if (N0C && N1C)
1210    return DAG.getNode(ISD::OR, VT, N0, N1);
1211  // canonicalize constant to RHS
1212  if (N0C && !N1C)
1213    return DAG.getNode(ISD::OR, VT, N1, N0);
1214  // fold (or x, 0) -> x
1215  if (N1C && N1C->isNullValue())
1216    return N0;
1217  // fold (or x, -1) -> -1
1218  if (N1C && N1C->isAllOnesValue())
1219    return N1;
1220  // fold (or x, c) -> c iff (x & ~c) == 0
1221  if (N1C &&
1222      TLI.MaskedValueIsZero(N0,~N1C->getValue() & (~0ULL>>(64-OpSizeInBits))))
1223    return N1;
1224  // reassociate or
1225  SDOperand ROR = ReassociateOps(ISD::OR, N0, N1);
1226  if (ROR.Val != 0)
1227    return ROR;
1228  // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
1229  if (N1C && N0.getOpcode() == ISD::AND && N0.Val->hasOneUse() &&
1230             isa<ConstantSDNode>(N0.getOperand(1))) {
1231    ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
1232    return DAG.getNode(ISD::AND, VT, DAG.getNode(ISD::OR, VT, N0.getOperand(0),
1233                                                 N1),
1234                       DAG.getConstant(N1C->getValue() | C1->getValue(), VT));
1235  }
1236  // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
1237  if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
1238    ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
1239    ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
1240
1241    if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
1242        MVT::isInteger(LL.getValueType())) {
1243      // fold (X != 0) | (Y != 0) -> (X|Y != 0)
1244      // fold (X <  0) | (Y <  0) -> (X|Y < 0)
1245      if (cast<ConstantSDNode>(LR)->getValue() == 0 &&
1246          (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
1247        SDOperand ORNode = DAG.getNode(ISD::OR, LR.getValueType(), LL, RL);
1248        AddToWorkList(ORNode.Val);
1249        return DAG.getSetCC(VT, ORNode, LR, Op1);
1250      }
1251      // fold (X != -1) | (Y != -1) -> (X&Y != -1)
1252      // fold (X >  -1) | (Y >  -1) -> (X&Y >  -1)
1253      if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
1254          (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
1255        SDOperand ANDNode = DAG.getNode(ISD::AND, LR.getValueType(), LL, RL);
1256        AddToWorkList(ANDNode.Val);
1257        return DAG.getSetCC(VT, ANDNode, LR, Op1);
1258      }
1259    }
1260    // canonicalize equivalent to ll == rl
1261    if (LL == RR && LR == RL) {
1262      Op1 = ISD::getSetCCSwappedOperands(Op1);
1263      std::swap(RL, RR);
1264    }
1265    if (LL == RL && LR == RR) {
1266      bool isInteger = MVT::isInteger(LL.getValueType());
1267      ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
1268      if (Result != ISD::SETCC_INVALID)
1269        return DAG.getSetCC(N0.getValueType(), LL, LR, Result);
1270    }
1271  }
1272  // fold (or (zext x), (zext y)) -> (zext (or x, y))
1273  if (N0.getOpcode() == ISD::ZERO_EXTEND &&
1274      N1.getOpcode() == ISD::ZERO_EXTEND &&
1275      N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()) {
1276    SDOperand ORNode = DAG.getNode(ISD::OR, N0.getOperand(0).getValueType(),
1277                                   N0.getOperand(0), N1.getOperand(0));
1278    AddToWorkList(ORNode.Val);
1279    return DAG.getNode(ISD::ZERO_EXTEND, VT, ORNode);
1280  }
1281  // fold (or (shl/srl/sra x), (shl/srl/sra y)) -> (shl/srl/sra (or x, y))
1282  if (((N0.getOpcode() == ISD::SHL && N1.getOpcode() == ISD::SHL) ||
1283       (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SRL) ||
1284       (N0.getOpcode() == ISD::SRA && N1.getOpcode() == ISD::SRA)) &&
1285      N0.getOperand(1) == N1.getOperand(1)) {
1286    SDOperand ORNode = DAG.getNode(ISD::OR, N0.getOperand(0).getValueType(),
1287                                   N0.getOperand(0), N1.getOperand(0));
1288    AddToWorkList(ORNode.Val);
1289    return DAG.getNode(N0.getOpcode(), VT, ORNode, N0.getOperand(1));
1290  }
1291  // canonicalize shl to left side in a shl/srl pair, to match rotate
1292  if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
1293    std::swap(N0, N1);
1294  // check for rotl, rotr
1295  if (N0.getOpcode() == ISD::SHL && N1.getOpcode() == ISD::SRL &&
1296      N0.getOperand(0) == N1.getOperand(0) &&
1297      TLI.isOperationLegal(ISD::ROTL, VT) && TLI.isTypeLegal(VT)) {
1298    // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
1299    if (N0.getOperand(1).getOpcode() == ISD::Constant &&
1300        N1.getOperand(1).getOpcode() == ISD::Constant) {
1301      uint64_t c1val = cast<ConstantSDNode>(N0.getOperand(1))->getValue();
1302      uint64_t c2val = cast<ConstantSDNode>(N1.getOperand(1))->getValue();
1303      if ((c1val + c2val) == OpSizeInBits)
1304        return DAG.getNode(ISD::ROTL, VT, N0.getOperand(0), N0.getOperand(1));
1305    }
1306    // fold (or (shl x, y), (srl x, (sub 32, y))) -> (rotl x, y)
1307    if (N1.getOperand(1).getOpcode() == ISD::SUB &&
1308        N0.getOperand(1) == N1.getOperand(1).getOperand(1))
1309      if (ConstantSDNode *SUBC =
1310          dyn_cast<ConstantSDNode>(N1.getOperand(1).getOperand(0)))
1311        if (SUBC->getValue() == OpSizeInBits)
1312          return DAG.getNode(ISD::ROTL, VT, N0.getOperand(0), N0.getOperand(1));
1313    // fold (or (shl x, (sub 32, y)), (srl x, r)) -> (rotr x, y)
1314    if (N0.getOperand(1).getOpcode() == ISD::SUB &&
1315        N1.getOperand(1) == N0.getOperand(1).getOperand(1))
1316      if (ConstantSDNode *SUBC =
1317          dyn_cast<ConstantSDNode>(N0.getOperand(1).getOperand(0)))
1318        if (SUBC->getValue() == OpSizeInBits) {
1319          if (TLI.isOperationLegal(ISD::ROTR, VT) && TLI.isTypeLegal(VT))
1320            return DAG.getNode(ISD::ROTR, VT, N0.getOperand(0),
1321                               N1.getOperand(1));
1322          else
1323            return DAG.getNode(ISD::ROTL, VT, N0.getOperand(0),
1324                               N0.getOperand(1));
1325        }
1326  }
1327  return SDOperand();
1328}
1329
1330SDOperand DAGCombiner::visitXOR(SDNode *N) {
1331  SDOperand N0 = N->getOperand(0);
1332  SDOperand N1 = N->getOperand(1);
1333  SDOperand LHS, RHS, CC;
1334  ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1335  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1336  MVT::ValueType VT = N0.getValueType();
1337
1338  // fold (xor c1, c2) -> c1^c2
1339  if (N0C && N1C)
1340    return DAG.getNode(ISD::XOR, VT, N0, N1);
1341  // canonicalize constant to RHS
1342  if (N0C && !N1C)
1343    return DAG.getNode(ISD::XOR, VT, N1, N0);
1344  // fold (xor x, 0) -> x
1345  if (N1C && N1C->isNullValue())
1346    return N0;
1347  // reassociate xor
1348  SDOperand RXOR = ReassociateOps(ISD::XOR, N0, N1);
1349  if (RXOR.Val != 0)
1350    return RXOR;
1351  // fold !(x cc y) -> (x !cc y)
1352  if (N1C && N1C->getValue() == 1 && isSetCCEquivalent(N0, LHS, RHS, CC)) {
1353    bool isInt = MVT::isInteger(LHS.getValueType());
1354    ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
1355                                               isInt);
1356    if (N0.getOpcode() == ISD::SETCC)
1357      return DAG.getSetCC(VT, LHS, RHS, NotCC);
1358    if (N0.getOpcode() == ISD::SELECT_CC)
1359      return DAG.getSelectCC(LHS, RHS, N0.getOperand(2),N0.getOperand(3),NotCC);
1360    assert(0 && "Unhandled SetCC Equivalent!");
1361    abort();
1362  }
1363  // fold !(x or y) -> (!x and !y) iff x or y are setcc
1364  if (N1C && N1C->getValue() == 1 &&
1365      (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
1366    SDOperand LHS = N0.getOperand(0), RHS = N0.getOperand(1);
1367    if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
1368      unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
1369      LHS = DAG.getNode(ISD::XOR, VT, LHS, N1);  // RHS = ~LHS
1370      RHS = DAG.getNode(ISD::XOR, VT, RHS, N1);  // RHS = ~RHS
1371      AddToWorkList(LHS.Val); AddToWorkList(RHS.Val);
1372      return DAG.getNode(NewOpcode, VT, LHS, RHS);
1373    }
1374  }
1375  // fold !(x or y) -> (!x and !y) iff x or y are constants
1376  if (N1C && N1C->isAllOnesValue() &&
1377      (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
1378    SDOperand LHS = N0.getOperand(0), RHS = N0.getOperand(1);
1379    if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
1380      unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
1381      LHS = DAG.getNode(ISD::XOR, VT, LHS, N1);  // RHS = ~LHS
1382      RHS = DAG.getNode(ISD::XOR, VT, RHS, N1);  // RHS = ~RHS
1383      AddToWorkList(LHS.Val); AddToWorkList(RHS.Val);
1384      return DAG.getNode(NewOpcode, VT, LHS, RHS);
1385    }
1386  }
1387  // fold (xor (xor x, c1), c2) -> (xor x, c1^c2)
1388  if (N1C && N0.getOpcode() == ISD::XOR) {
1389    ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
1390    ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
1391    if (N00C)
1392      return DAG.getNode(ISD::XOR, VT, N0.getOperand(1),
1393                         DAG.getConstant(N1C->getValue()^N00C->getValue(), VT));
1394    if (N01C)
1395      return DAG.getNode(ISD::XOR, VT, N0.getOperand(0),
1396                         DAG.getConstant(N1C->getValue()^N01C->getValue(), VT));
1397  }
1398  // fold (xor x, x) -> 0
1399  if (N0 == N1)
1400    return DAG.getConstant(0, VT);
1401  // fold (xor (zext x), (zext y)) -> (zext (xor x, y))
1402  if (N0.getOpcode() == ISD::ZERO_EXTEND &&
1403      N1.getOpcode() == ISD::ZERO_EXTEND &&
1404      N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()) {
1405    SDOperand XORNode = DAG.getNode(ISD::XOR, N0.getOperand(0).getValueType(),
1406                                   N0.getOperand(0), N1.getOperand(0));
1407    AddToWorkList(XORNode.Val);
1408    return DAG.getNode(ISD::ZERO_EXTEND, VT, XORNode);
1409  }
1410  // fold (xor (shl/srl/sra x), (shl/srl/sra y)) -> (shl/srl/sra (xor x, y))
1411  if (((N0.getOpcode() == ISD::SHL && N1.getOpcode() == ISD::SHL) ||
1412       (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SRL) ||
1413       (N0.getOpcode() == ISD::SRA && N1.getOpcode() == ISD::SRA)) &&
1414      N0.getOperand(1) == N1.getOperand(1)) {
1415    SDOperand XORNode = DAG.getNode(ISD::XOR, N0.getOperand(0).getValueType(),
1416                                    N0.getOperand(0), N1.getOperand(0));
1417    AddToWorkList(XORNode.Val);
1418    return DAG.getNode(N0.getOpcode(), VT, XORNode, N0.getOperand(1));
1419  }
1420  return SDOperand();
1421}
1422
1423SDOperand DAGCombiner::visitSHL(SDNode *N) {
1424  SDOperand N0 = N->getOperand(0);
1425  SDOperand N1 = N->getOperand(1);
1426  ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1427  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1428  MVT::ValueType VT = N0.getValueType();
1429  unsigned OpSizeInBits = MVT::getSizeInBits(VT);
1430
1431  // fold (shl c1, c2) -> c1<<c2
1432  if (N0C && N1C)
1433    return DAG.getNode(ISD::SHL, VT, N0, N1);
1434  // fold (shl 0, x) -> 0
1435  if (N0C && N0C->isNullValue())
1436    return N0;
1437  // fold (shl x, c >= size(x)) -> undef
1438  if (N1C && N1C->getValue() >= OpSizeInBits)
1439    return DAG.getNode(ISD::UNDEF, VT);
1440  // fold (shl x, 0) -> x
1441  if (N1C && N1C->isNullValue())
1442    return N0;
1443  // if (shl x, c) is known to be zero, return 0
1444  if (TLI.MaskedValueIsZero(SDOperand(N, 0), MVT::getIntVTBitMask(VT)))
1445    return DAG.getConstant(0, VT);
1446  if (SimplifyDemandedBits(SDOperand(N, 0)))
1447    return SDOperand();
1448  // fold (shl (shl x, c1), c2) -> 0 or (shl x, c1+c2)
1449  if (N1C && N0.getOpcode() == ISD::SHL &&
1450      N0.getOperand(1).getOpcode() == ISD::Constant) {
1451    uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getValue();
1452    uint64_t c2 = N1C->getValue();
1453    if (c1 + c2 > OpSizeInBits)
1454      return DAG.getConstant(0, VT);
1455    return DAG.getNode(ISD::SHL, VT, N0.getOperand(0),
1456                       DAG.getConstant(c1 + c2, N1.getValueType()));
1457  }
1458  // fold (shl (srl x, c1), c2) -> (shl (and x, -1 << c1), c2-c1) or
1459  //                               (srl (and x, -1 << c1), c1-c2)
1460  if (N1C && N0.getOpcode() == ISD::SRL &&
1461      N0.getOperand(1).getOpcode() == ISD::Constant) {
1462    uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getValue();
1463    uint64_t c2 = N1C->getValue();
1464    SDOperand Mask = DAG.getNode(ISD::AND, VT, N0.getOperand(0),
1465                                 DAG.getConstant(~0ULL << c1, VT));
1466    if (c2 > c1)
1467      return DAG.getNode(ISD::SHL, VT, Mask,
1468                         DAG.getConstant(c2-c1, N1.getValueType()));
1469    else
1470      return DAG.getNode(ISD::SRL, VT, Mask,
1471                         DAG.getConstant(c1-c2, N1.getValueType()));
1472  }
1473  // fold (shl (sra x, c1), c1) -> (and x, -1 << c1)
1474  if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1))
1475    return DAG.getNode(ISD::AND, VT, N0.getOperand(0),
1476                       DAG.getConstant(~0ULL << N1C->getValue(), VT));
1477  // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1<<c2)
1478  if (N1C && N0.getOpcode() == ISD::ADD && N0.Val->hasOneUse() &&
1479      isa<ConstantSDNode>(N0.getOperand(1))) {
1480    return DAG.getNode(ISD::ADD, VT,
1481                       DAG.getNode(ISD::SHL, VT, N0.getOperand(0), N1),
1482                       DAG.getNode(ISD::SHL, VT, N0.getOperand(1), N1));
1483  }
1484  return SDOperand();
1485}
1486
1487SDOperand DAGCombiner::visitSRA(SDNode *N) {
1488  SDOperand N0 = N->getOperand(0);
1489  SDOperand N1 = N->getOperand(1);
1490  ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1491  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1492  MVT::ValueType VT = N0.getValueType();
1493
1494  // fold (sra c1, c2) -> c1>>c2
1495  if (N0C && N1C)
1496    return DAG.getNode(ISD::SRA, VT, N0, N1);
1497  // fold (sra 0, x) -> 0
1498  if (N0C && N0C->isNullValue())
1499    return N0;
1500  // fold (sra -1, x) -> -1
1501  if (N0C && N0C->isAllOnesValue())
1502    return N0;
1503  // fold (sra x, c >= size(x)) -> undef
1504  if (N1C && N1C->getValue() >= MVT::getSizeInBits(VT))
1505    return DAG.getNode(ISD::UNDEF, VT);
1506  // fold (sra x, 0) -> x
1507  if (N1C && N1C->isNullValue())
1508    return N0;
1509  // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
1510  // sext_inreg.
1511  if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
1512    unsigned LowBits = MVT::getSizeInBits(VT) - (unsigned)N1C->getValue();
1513    MVT::ValueType EVT;
1514    switch (LowBits) {
1515    default: EVT = MVT::Other; break;
1516    case  1: EVT = MVT::i1;    break;
1517    case  8: EVT = MVT::i8;    break;
1518    case 16: EVT = MVT::i16;   break;
1519    case 32: EVT = MVT::i32;   break;
1520    }
1521    if (EVT > MVT::Other && TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, EVT))
1522      return DAG.getNode(ISD::SIGN_EXTEND_INREG, VT, N0.getOperand(0),
1523                         DAG.getValueType(EVT));
1524  }
1525
1526  // fold (sra (sra x, c1), c2) -> (sra x, c1+c2)
1527  if (N1C && N0.getOpcode() == ISD::SRA) {
1528    if (ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
1529      unsigned Sum = N1C->getValue() + C1->getValue();
1530      if (Sum >= MVT::getSizeInBits(VT)) Sum = MVT::getSizeInBits(VT)-1;
1531      return DAG.getNode(ISD::SRA, VT, N0.getOperand(0),
1532                         DAG.getConstant(Sum, N1C->getValueType(0)));
1533    }
1534  }
1535
1536  // If the sign bit is known to be zero, switch this to a SRL.
1537  if (TLI.MaskedValueIsZero(N0, MVT::getIntVTSignBit(VT)))
1538    return DAG.getNode(ISD::SRL, VT, N0, N1);
1539  return SDOperand();
1540}
1541
1542SDOperand DAGCombiner::visitSRL(SDNode *N) {
1543  SDOperand N0 = N->getOperand(0);
1544  SDOperand N1 = N->getOperand(1);
1545  ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1546  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1547  MVT::ValueType VT = N0.getValueType();
1548  unsigned OpSizeInBits = MVT::getSizeInBits(VT);
1549
1550  // fold (srl c1, c2) -> c1 >>u c2
1551  if (N0C && N1C)
1552    return DAG.getNode(ISD::SRL, VT, N0, N1);
1553  // fold (srl 0, x) -> 0
1554  if (N0C && N0C->isNullValue())
1555    return N0;
1556  // fold (srl x, c >= size(x)) -> undef
1557  if (N1C && N1C->getValue() >= OpSizeInBits)
1558    return DAG.getNode(ISD::UNDEF, VT);
1559  // fold (srl x, 0) -> x
1560  if (N1C && N1C->isNullValue())
1561    return N0;
1562  // if (srl x, c) is known to be zero, return 0
1563  if (N1C && TLI.MaskedValueIsZero(SDOperand(N, 0), ~0ULL >> (64-OpSizeInBits)))
1564    return DAG.getConstant(0, VT);
1565  // fold (srl (srl x, c1), c2) -> 0 or (srl x, c1+c2)
1566  if (N1C && N0.getOpcode() == ISD::SRL &&
1567      N0.getOperand(1).getOpcode() == ISD::Constant) {
1568    uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getValue();
1569    uint64_t c2 = N1C->getValue();
1570    if (c1 + c2 > OpSizeInBits)
1571      return DAG.getConstant(0, VT);
1572    return DAG.getNode(ISD::SRL, VT, N0.getOperand(0),
1573                       DAG.getConstant(c1 + c2, N1.getValueType()));
1574  }
1575  return SDOperand();
1576}
1577
1578SDOperand DAGCombiner::visitCTLZ(SDNode *N) {
1579  SDOperand N0 = N->getOperand(0);
1580  ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1581  MVT::ValueType VT = N->getValueType(0);
1582
1583  // fold (ctlz c1) -> c2
1584  if (N0C)
1585    return DAG.getNode(ISD::CTLZ, VT, N0);
1586  return SDOperand();
1587}
1588
1589SDOperand DAGCombiner::visitCTTZ(SDNode *N) {
1590  SDOperand N0 = N->getOperand(0);
1591  ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1592  MVT::ValueType VT = N->getValueType(0);
1593
1594  // fold (cttz c1) -> c2
1595  if (N0C)
1596    return DAG.getNode(ISD::CTTZ, VT, N0);
1597  return SDOperand();
1598}
1599
1600SDOperand DAGCombiner::visitCTPOP(SDNode *N) {
1601  SDOperand N0 = N->getOperand(0);
1602  ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1603  MVT::ValueType VT = N->getValueType(0);
1604
1605  // fold (ctpop c1) -> c2
1606  if (N0C)
1607    return DAG.getNode(ISD::CTPOP, VT, N0);
1608  return SDOperand();
1609}
1610
1611SDOperand DAGCombiner::visitSELECT(SDNode *N) {
1612  SDOperand N0 = N->getOperand(0);
1613  SDOperand N1 = N->getOperand(1);
1614  SDOperand N2 = N->getOperand(2);
1615  ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1616  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1617  ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
1618  MVT::ValueType VT = N->getValueType(0);
1619
1620  // fold select C, X, X -> X
1621  if (N1 == N2)
1622    return N1;
1623  // fold select true, X, Y -> X
1624  if (N0C && !N0C->isNullValue())
1625    return N1;
1626  // fold select false, X, Y -> Y
1627  if (N0C && N0C->isNullValue())
1628    return N2;
1629  // fold select C, 1, X -> C | X
1630  if (MVT::i1 == VT && N1C && N1C->getValue() == 1)
1631    return DAG.getNode(ISD::OR, VT, N0, N2);
1632  // fold select C, 0, X -> ~C & X
1633  // FIXME: this should check for C type == X type, not i1?
1634  if (MVT::i1 == VT && N1C && N1C->isNullValue()) {
1635    SDOperand XORNode = DAG.getNode(ISD::XOR, VT, N0, DAG.getConstant(1, VT));
1636    AddToWorkList(XORNode.Val);
1637    return DAG.getNode(ISD::AND, VT, XORNode, N2);
1638  }
1639  // fold select C, X, 1 -> ~C | X
1640  if (MVT::i1 == VT && N2C && N2C->getValue() == 1) {
1641    SDOperand XORNode = DAG.getNode(ISD::XOR, VT, N0, DAG.getConstant(1, VT));
1642    AddToWorkList(XORNode.Val);
1643    return DAG.getNode(ISD::OR, VT, XORNode, N1);
1644  }
1645  // fold select C, X, 0 -> C & X
1646  // FIXME: this should check for C type == X type, not i1?
1647  if (MVT::i1 == VT && N2C && N2C->isNullValue())
1648    return DAG.getNode(ISD::AND, VT, N0, N1);
1649  // fold  X ? X : Y --> X ? 1 : Y --> X | Y
1650  if (MVT::i1 == VT && N0 == N1)
1651    return DAG.getNode(ISD::OR, VT, N0, N2);
1652  // fold X ? Y : X --> X ? Y : 0 --> X & Y
1653  if (MVT::i1 == VT && N0 == N2)
1654    return DAG.getNode(ISD::AND, VT, N0, N1);
1655  // If we can fold this based on the true/false value, do so.
1656  if (SimplifySelectOps(N, N1, N2))
1657    return SDOperand();
1658  // fold selects based on a setcc into other things, such as min/max/abs
1659  if (N0.getOpcode() == ISD::SETCC)
1660    // FIXME:
1661    // Check against MVT::Other for SELECT_CC, which is a workaround for targets
1662    // having to say they don't support SELECT_CC on every type the DAG knows
1663    // about, since there is no way to mark an opcode illegal at all value types
1664    if (TLI.isOperationLegal(ISD::SELECT_CC, MVT::Other))
1665      return DAG.getNode(ISD::SELECT_CC, VT, N0.getOperand(0), N0.getOperand(1),
1666                         N1, N2, N0.getOperand(2));
1667    else
1668      return SimplifySelect(N0, N1, N2);
1669  return SDOperand();
1670}
1671
1672SDOperand DAGCombiner::visitSELECT_CC(SDNode *N) {
1673  SDOperand N0 = N->getOperand(0);
1674  SDOperand N1 = N->getOperand(1);
1675  SDOperand N2 = N->getOperand(2);
1676  SDOperand N3 = N->getOperand(3);
1677  SDOperand N4 = N->getOperand(4);
1678  ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1679  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1680  ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
1681  ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
1682
1683  // Determine if the condition we're dealing with is constant
1684  SDOperand SCC = SimplifySetCC(TLI.getSetCCResultTy(), N0, N1, CC, false);
1685  ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.Val);
1686
1687  // fold select_cc lhs, rhs, x, x, cc -> x
1688  if (N2 == N3)
1689    return N2;
1690
1691  // If we can fold this based on the true/false value, do so.
1692  if (SimplifySelectOps(N, N2, N3))
1693    return SDOperand();
1694
1695  // fold select_cc into other things, such as min/max/abs
1696  return SimplifySelectCC(N0, N1, N2, N3, CC);
1697}
1698
1699SDOperand DAGCombiner::visitSETCC(SDNode *N) {
1700  return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
1701                       cast<CondCodeSDNode>(N->getOperand(2))->get());
1702}
1703
1704SDOperand DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
1705  SDOperand N0 = N->getOperand(0);
1706  ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1707  MVT::ValueType VT = N->getValueType(0);
1708
1709  // fold (sext c1) -> c1
1710  if (N0C)
1711    return DAG.getNode(ISD::SIGN_EXTEND, VT, N0);
1712  // fold (sext (sext x)) -> (sext x)
1713  if (N0.getOpcode() == ISD::SIGN_EXTEND)
1714    return DAG.getNode(ISD::SIGN_EXTEND, VT, N0.getOperand(0));
1715  // fold (sext (truncate x)) -> (sextinreg x) iff x size == sext size.
1716  if (N0.getOpcode() == ISD::TRUNCATE && N0.getOperand(0).getValueType() == VT&&
1717      (!AfterLegalize ||
1718       TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, N0.getValueType())))
1719    return DAG.getNode(ISD::SIGN_EXTEND_INREG, VT, N0.getOperand(0),
1720                       DAG.getValueType(N0.getValueType()));
1721  // fold (sext (load x)) -> (sext (truncate (sextload x)))
1722  if (N0.getOpcode() == ISD::LOAD && N0.hasOneUse() &&
1723      (!AfterLegalize||TLI.isOperationLegal(ISD::SEXTLOAD, N0.getValueType()))){
1724    SDOperand ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, VT, N0.getOperand(0),
1725                                       N0.getOperand(1), N0.getOperand(2),
1726                                       N0.getValueType());
1727    CombineTo(N, ExtLoad);
1728    CombineTo(N0.Val, DAG.getNode(ISD::TRUNCATE, N0.getValueType(), ExtLoad),
1729              ExtLoad.getValue(1));
1730    return SDOperand();
1731  }
1732
1733  // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
1734  // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
1735  if ((N0.getOpcode() == ISD::SEXTLOAD || N0.getOpcode() == ISD::EXTLOAD) &&
1736      N0.hasOneUse()) {
1737    SDOperand ExtLoad = DAG.getNode(ISD::SEXTLOAD, VT, N0.getOperand(0),
1738                                    N0.getOperand(1), N0.getOperand(2),
1739                                    N0.getOperand(3));
1740    CombineTo(N, ExtLoad);
1741    CombineTo(N0.Val, DAG.getNode(ISD::TRUNCATE, N0.getValueType(), ExtLoad),
1742              ExtLoad.getValue(1));
1743    return SDOperand();
1744  }
1745
1746  return SDOperand();
1747}
1748
1749SDOperand DAGCombiner::visitZERO_EXTEND(SDNode *N) {
1750  SDOperand N0 = N->getOperand(0);
1751  ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1752  MVT::ValueType VT = N->getValueType(0);
1753
1754  // fold (zext c1) -> c1
1755  if (N0C)
1756    return DAG.getNode(ISD::ZERO_EXTEND, VT, N0);
1757  // fold (zext (zext x)) -> (zext x)
1758  if (N0.getOpcode() == ISD::ZERO_EXTEND)
1759    return DAG.getNode(ISD::ZERO_EXTEND, VT, N0.getOperand(0));
1760  // fold (zext (truncate x)) -> (zextinreg x) iff x size == zext size.
1761  if (N0.getOpcode() == ISD::TRUNCATE && N0.getOperand(0).getValueType() == VT&&
1762      (!AfterLegalize || TLI.isOperationLegal(ISD::AND, N0.getValueType())))
1763    return DAG.getZeroExtendInReg(N0.getOperand(0), N0.getValueType());
1764  // fold (zext (load x)) -> (zext (truncate (zextload x)))
1765  if (N0.getOpcode() == ISD::LOAD && N0.hasOneUse() &&
1766      (!AfterLegalize||TLI.isOperationLegal(ISD::ZEXTLOAD, N0.getValueType()))){
1767    SDOperand ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, VT, N0.getOperand(0),
1768                                       N0.getOperand(1), N0.getOperand(2),
1769                                       N0.getValueType());
1770    CombineTo(N, ExtLoad);
1771    CombineTo(N0.Val, DAG.getNode(ISD::TRUNCATE, N0.getValueType(), ExtLoad),
1772              ExtLoad.getValue(1));
1773    return SDOperand();
1774  }
1775
1776  // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
1777  // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
1778  if ((N0.getOpcode() == ISD::ZEXTLOAD || N0.getOpcode() == ISD::EXTLOAD) &&
1779      N0.hasOneUse()) {
1780    SDOperand ExtLoad = DAG.getNode(ISD::ZEXTLOAD, VT, N0.getOperand(0),
1781                                    N0.getOperand(1), N0.getOperand(2),
1782                                    N0.getOperand(3));
1783    CombineTo(N, ExtLoad);
1784    CombineTo(N0.Val, DAG.getNode(ISD::TRUNCATE, N0.getValueType(), ExtLoad),
1785              ExtLoad.getValue(1));
1786    return SDOperand();
1787  }
1788  return SDOperand();
1789}
1790
1791SDOperand DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
1792  SDOperand N0 = N->getOperand(0);
1793  SDOperand N1 = N->getOperand(1);
1794  ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1795  MVT::ValueType VT = N->getValueType(0);
1796  MVT::ValueType EVT = cast<VTSDNode>(N1)->getVT();
1797  unsigned EVTBits = MVT::getSizeInBits(EVT);
1798
1799  // fold (sext_in_reg c1) -> c1
1800  if (N0C) {
1801    SDOperand Truncate = DAG.getConstant(N0C->getValue(), EVT);
1802    return DAG.getNode(ISD::SIGN_EXTEND, VT, Truncate);
1803  }
1804  // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt1
1805  if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
1806      cast<VTSDNode>(N0.getOperand(1))->getVT() <= EVT) {
1807    return N0;
1808  }
1809  // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
1810  if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
1811      EVT < cast<VTSDNode>(N0.getOperand(1))->getVT()) {
1812    return DAG.getNode(ISD::SIGN_EXTEND_INREG, VT, N0.getOperand(0), N1);
1813  }
1814  // fold (sext_in_reg (assert_sext x)) -> (assert_sext x)
1815  if (N0.getOpcode() == ISD::AssertSext &&
1816      cast<VTSDNode>(N0.getOperand(1))->getVT() <= EVT) {
1817    return N0;
1818  }
1819  // fold (sext_in_reg (sextload x)) -> (sextload x)
1820  if (N0.getOpcode() == ISD::SEXTLOAD &&
1821      cast<VTSDNode>(N0.getOperand(3))->getVT() <= EVT) {
1822    return N0;
1823  }
1824  // fold (sext_in_reg (setcc x)) -> setcc x iff (setcc x) == 0 or -1
1825  if (N0.getOpcode() == ISD::SETCC &&
1826      TLI.getSetCCResultContents() ==
1827        TargetLowering::ZeroOrNegativeOneSetCCResult)
1828    return N0;
1829  // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is zero
1830  if (TLI.MaskedValueIsZero(N0, 1ULL << (EVTBits-1)))
1831    return DAG.getZeroExtendInReg(N0, EVT);
1832  // fold (sext_in_reg (srl x)) -> sra x
1833  if (N0.getOpcode() == ISD::SRL &&
1834      N0.getOperand(1).getOpcode() == ISD::Constant &&
1835      cast<ConstantSDNode>(N0.getOperand(1))->getValue() == EVTBits) {
1836    return DAG.getNode(ISD::SRA, N0.getValueType(), N0.getOperand(0),
1837                       N0.getOperand(1));
1838  }
1839  // fold (sext_inreg (extload x)) -> (sextload x)
1840  if (N0.getOpcode() == ISD::EXTLOAD &&
1841      EVT == cast<VTSDNode>(N0.getOperand(3))->getVT() &&
1842      (!AfterLegalize || TLI.isOperationLegal(ISD::SEXTLOAD, EVT))) {
1843    SDOperand ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, VT, N0.getOperand(0),
1844                                       N0.getOperand(1), N0.getOperand(2),
1845                                       EVT);
1846    CombineTo(N, ExtLoad);
1847    CombineTo(N0.Val, ExtLoad, ExtLoad.getValue(1));
1848    return SDOperand();
1849  }
1850  // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
1851  if (N0.getOpcode() == ISD::ZEXTLOAD && N0.hasOneUse() &&
1852      EVT == cast<VTSDNode>(N0.getOperand(3))->getVT() &&
1853      (!AfterLegalize || TLI.isOperationLegal(ISD::SEXTLOAD, EVT))) {
1854    SDOperand ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, VT, N0.getOperand(0),
1855                                       N0.getOperand(1), N0.getOperand(2),
1856                                       EVT);
1857    CombineTo(N, ExtLoad);
1858    CombineTo(N0.Val, ExtLoad, ExtLoad.getValue(1));
1859    return SDOperand();
1860  }
1861  return SDOperand();
1862}
1863
1864SDOperand DAGCombiner::visitTRUNCATE(SDNode *N) {
1865  SDOperand N0 = N->getOperand(0);
1866  ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1867  MVT::ValueType VT = N->getValueType(0);
1868
1869  // noop truncate
1870  if (N0.getValueType() == N->getValueType(0))
1871    return N0;
1872  // fold (truncate c1) -> c1
1873  if (N0C)
1874    return DAG.getNode(ISD::TRUNCATE, VT, N0);
1875  // fold (truncate (truncate x)) -> (truncate x)
1876  if (N0.getOpcode() == ISD::TRUNCATE)
1877    return DAG.getNode(ISD::TRUNCATE, VT, N0.getOperand(0));
1878  // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
1879  if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::SIGN_EXTEND){
1880    if (N0.getValueType() < VT)
1881      // if the source is smaller than the dest, we still need an extend
1882      return DAG.getNode(N0.getOpcode(), VT, N0.getOperand(0));
1883    else if (N0.getValueType() > VT)
1884      // if the source is larger than the dest, than we just need the truncate
1885      return DAG.getNode(ISD::TRUNCATE, VT, N0.getOperand(0));
1886    else
1887      // if the source and dest are the same type, we can drop both the extend
1888      // and the truncate
1889      return N0.getOperand(0);
1890  }
1891  // fold (truncate (load x)) -> (smaller load x)
1892  if (N0.getOpcode() == ISD::LOAD && N0.hasOneUse()) {
1893    assert(MVT::getSizeInBits(N0.getValueType()) > MVT::getSizeInBits(VT) &&
1894           "Cannot truncate to larger type!");
1895    MVT::ValueType PtrType = N0.getOperand(1).getValueType();
1896    // For big endian targets, we need to add an offset to the pointer to load
1897    // the correct bytes.  For little endian systems, we merely need to read
1898    // fewer bytes from the same pointer.
1899    uint64_t PtrOff =
1900      (MVT::getSizeInBits(N0.getValueType()) - MVT::getSizeInBits(VT)) / 8;
1901    SDOperand NewPtr = TLI.isLittleEndian() ? N0.getOperand(1) :
1902      DAG.getNode(ISD::ADD, PtrType, N0.getOperand(1),
1903                  DAG.getConstant(PtrOff, PtrType));
1904    AddToWorkList(NewPtr.Val);
1905    SDOperand Load = DAG.getLoad(VT, N0.getOperand(0), NewPtr,N0.getOperand(2));
1906    AddToWorkList(N);
1907    CombineTo(N0.Val, Load, Load.getValue(1));
1908    return SDOperand();
1909  }
1910  return SDOperand();
1911}
1912
1913SDOperand DAGCombiner::visitBIT_CONVERT(SDNode *N) {
1914  SDOperand N0 = N->getOperand(0);
1915  MVT::ValueType VT = N->getValueType(0);
1916
1917  // If the input is a constant, let getNode() fold it.
1918  if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
1919    SDOperand Res = DAG.getNode(ISD::BIT_CONVERT, VT, N0);
1920    if (Res.Val != N) return Res;
1921  }
1922
1923  if (N0.getOpcode() == ISD::BIT_CONVERT)  // conv(conv(x,t1),t2) -> conv(x,t2)
1924    return DAG.getNode(ISD::BIT_CONVERT, VT, N0.getOperand(0));
1925
1926  // fold (conv (load x)) -> (load (conv*)x)
1927  // FIXME: These xforms need to know that the resultant load doesn't need a
1928  // higher alignment than the original!
1929  if (0 && N0.getOpcode() == ISD::LOAD && N0.hasOneUse()) {
1930    SDOperand Load = DAG.getLoad(VT, N0.getOperand(0), N0.getOperand(1),
1931                                 N0.getOperand(2));
1932    AddToWorkList(N);
1933    CombineTo(N0.Val, DAG.getNode(ISD::BIT_CONVERT, N0.getValueType(), Load),
1934              Load.getValue(1));
1935    return Load;
1936  }
1937
1938  return SDOperand();
1939}
1940
1941SDOperand DAGCombiner::visitFADD(SDNode *N) {
1942  SDOperand N0 = N->getOperand(0);
1943  SDOperand N1 = N->getOperand(1);
1944  ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
1945  ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
1946  MVT::ValueType VT = N->getValueType(0);
1947
1948  // fold (fadd c1, c2) -> c1+c2
1949  if (N0CFP && N1CFP)
1950    return DAG.getNode(ISD::FADD, VT, N0, N1);
1951  // canonicalize constant to RHS
1952  if (N0CFP && !N1CFP)
1953    return DAG.getNode(ISD::FADD, VT, N1, N0);
1954  // fold (A + (-B)) -> A-B
1955  if (N1.getOpcode() == ISD::FNEG)
1956    return DAG.getNode(ISD::FSUB, VT, N0, N1.getOperand(0));
1957  // fold ((-A) + B) -> B-A
1958  if (N0.getOpcode() == ISD::FNEG)
1959    return DAG.getNode(ISD::FSUB, VT, N1, N0.getOperand(0));
1960  return SDOperand();
1961}
1962
1963SDOperand DAGCombiner::visitFSUB(SDNode *N) {
1964  SDOperand N0 = N->getOperand(0);
1965  SDOperand N1 = N->getOperand(1);
1966  ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
1967  ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
1968  MVT::ValueType VT = N->getValueType(0);
1969
1970  // fold (fsub c1, c2) -> c1-c2
1971  if (N0CFP && N1CFP)
1972    return DAG.getNode(ISD::FSUB, VT, N0, N1);
1973  // fold (A-(-B)) -> A+B
1974  if (N1.getOpcode() == ISD::FNEG)
1975    return DAG.getNode(ISD::FADD, VT, N0, N1.getOperand(0));
1976  return SDOperand();
1977}
1978
1979SDOperand DAGCombiner::visitFMUL(SDNode *N) {
1980  SDOperand N0 = N->getOperand(0);
1981  SDOperand N1 = N->getOperand(1);
1982  ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
1983  ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
1984  MVT::ValueType VT = N->getValueType(0);
1985
1986  // fold (fmul c1, c2) -> c1*c2
1987  if (N0CFP && N1CFP)
1988    return DAG.getNode(ISD::FMUL, VT, N0, N1);
1989  // canonicalize constant to RHS
1990  if (N0CFP && !N1CFP)
1991    return DAG.getNode(ISD::FMUL, VT, N1, N0);
1992  // fold (fmul X, 2.0) -> (fadd X, X)
1993  if (N1CFP && N1CFP->isExactlyValue(+2.0))
1994    return DAG.getNode(ISD::FADD, VT, N0, N0);
1995  return SDOperand();
1996}
1997
1998SDOperand DAGCombiner::visitFDIV(SDNode *N) {
1999  SDOperand N0 = N->getOperand(0);
2000  SDOperand N1 = N->getOperand(1);
2001  ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
2002  ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
2003  MVT::ValueType VT = N->getValueType(0);
2004
2005  // fold (fdiv c1, c2) -> c1/c2
2006  if (N0CFP && N1CFP)
2007    return DAG.getNode(ISD::FDIV, VT, N0, N1);
2008  return SDOperand();
2009}
2010
2011SDOperand DAGCombiner::visitFREM(SDNode *N) {
2012  SDOperand N0 = N->getOperand(0);
2013  SDOperand N1 = N->getOperand(1);
2014  ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
2015  ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
2016  MVT::ValueType VT = N->getValueType(0);
2017
2018  // fold (frem c1, c2) -> fmod(c1,c2)
2019  if (N0CFP && N1CFP)
2020    return DAG.getNode(ISD::FREM, VT, N0, N1);
2021  return SDOperand();
2022}
2023
2024SDOperand DAGCombiner::visitFCOPYSIGN(SDNode *N) {
2025  SDOperand N0 = N->getOperand(0);
2026  SDOperand N1 = N->getOperand(1);
2027  ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
2028  ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
2029  MVT::ValueType VT = N->getValueType(0);
2030
2031  if (N0CFP && N1CFP)  // Constant fold
2032    return DAG.getNode(ISD::FCOPYSIGN, VT, N0, N1);
2033
2034  if (N1CFP) {
2035    // copysign(x, c1) -> fabs(x)       iff ispos(c1)
2036    // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
2037    union {
2038      double d;
2039      int64_t i;
2040    } u;
2041    u.d = N1CFP->getValue();
2042    if (u.i >= 0)
2043      return DAG.getNode(ISD::FABS, VT, N0);
2044    else
2045      return DAG.getNode(ISD::FNEG, VT, DAG.getNode(ISD::FABS, VT, N0));
2046  }
2047
2048  // copysign(fabs(x), y) -> copysign(x, y)
2049  // copysign(fneg(x), y) -> copysign(x, y)
2050  // copysign(copysign(x,z), y) -> copysign(x, y)
2051  if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
2052      N0.getOpcode() == ISD::FCOPYSIGN)
2053    return DAG.getNode(ISD::FCOPYSIGN, VT, N0.getOperand(0), N1);
2054
2055  // copysign(x, abs(y)) -> abs(x)
2056  if (N1.getOpcode() == ISD::FABS)
2057    return DAG.getNode(ISD::FABS, VT, N0);
2058
2059  // copysign(x, copysign(y,z)) -> copysign(x, z)
2060  if (N1.getOpcode() == ISD::FCOPYSIGN)
2061    return DAG.getNode(ISD::FCOPYSIGN, VT, N0, N1.getOperand(1));
2062
2063  // copysign(x, fp_extend(y)) -> copysign(x, y)
2064  // copysign(x, fp_round(y)) -> copysign(x, y)
2065  if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
2066    return DAG.getNode(ISD::FCOPYSIGN, VT, N0, N1.getOperand(0));
2067
2068  return SDOperand();
2069}
2070
2071
2072
2073SDOperand DAGCombiner::visitSINT_TO_FP(SDNode *N) {
2074  SDOperand N0 = N->getOperand(0);
2075  ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2076  MVT::ValueType VT = N->getValueType(0);
2077
2078  // fold (sint_to_fp c1) -> c1fp
2079  if (N0C)
2080    return DAG.getNode(ISD::SINT_TO_FP, VT, N0);
2081  return SDOperand();
2082}
2083
2084SDOperand DAGCombiner::visitUINT_TO_FP(SDNode *N) {
2085  SDOperand N0 = N->getOperand(0);
2086  ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2087  MVT::ValueType VT = N->getValueType(0);
2088
2089  // fold (uint_to_fp c1) -> c1fp
2090  if (N0C)
2091    return DAG.getNode(ISD::UINT_TO_FP, VT, N0);
2092  return SDOperand();
2093}
2094
2095SDOperand DAGCombiner::visitFP_TO_SINT(SDNode *N) {
2096  SDOperand N0 = N->getOperand(0);
2097  ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
2098  MVT::ValueType VT = N->getValueType(0);
2099
2100  // fold (fp_to_sint c1fp) -> c1
2101  if (N0CFP)
2102    return DAG.getNode(ISD::FP_TO_SINT, VT, N0);
2103  return SDOperand();
2104}
2105
2106SDOperand DAGCombiner::visitFP_TO_UINT(SDNode *N) {
2107  SDOperand N0 = N->getOperand(0);
2108  ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
2109  MVT::ValueType VT = N->getValueType(0);
2110
2111  // fold (fp_to_uint c1fp) -> c1
2112  if (N0CFP)
2113    return DAG.getNode(ISD::FP_TO_UINT, VT, N0);
2114  return SDOperand();
2115}
2116
2117SDOperand DAGCombiner::visitFP_ROUND(SDNode *N) {
2118  SDOperand N0 = N->getOperand(0);
2119  ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
2120  MVT::ValueType VT = N->getValueType(0);
2121
2122  // fold (fp_round c1fp) -> c1fp
2123  if (N0CFP)
2124    return DAG.getNode(ISD::FP_ROUND, VT, N0);
2125
2126  // fold (fp_round (fp_extend x)) -> x
2127  if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
2128    return N0.getOperand(0);
2129
2130  // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
2131  if (N0.getOpcode() == ISD::FCOPYSIGN && N0.Val->hasOneUse()) {
2132    SDOperand Tmp = DAG.getNode(ISD::FP_ROUND, VT, N0.getOperand(0));
2133    AddToWorkList(Tmp.Val);
2134    return DAG.getNode(ISD::FCOPYSIGN, VT, Tmp, N0.getOperand(1));
2135  }
2136
2137  return SDOperand();
2138}
2139
2140SDOperand DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
2141  SDOperand N0 = N->getOperand(0);
2142  MVT::ValueType VT = N->getValueType(0);
2143  MVT::ValueType EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
2144  ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
2145
2146  // fold (fp_round_inreg c1fp) -> c1fp
2147  if (N0CFP) {
2148    SDOperand Round = DAG.getConstantFP(N0CFP->getValue(), EVT);
2149    return DAG.getNode(ISD::FP_EXTEND, VT, Round);
2150  }
2151  return SDOperand();
2152}
2153
2154SDOperand DAGCombiner::visitFP_EXTEND(SDNode *N) {
2155  SDOperand N0 = N->getOperand(0);
2156  ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
2157  MVT::ValueType VT = N->getValueType(0);
2158
2159  // fold (fp_extend c1fp) -> c1fp
2160  if (N0CFP)
2161    return DAG.getNode(ISD::FP_EXTEND, VT, N0);
2162  return SDOperand();
2163}
2164
2165SDOperand DAGCombiner::visitFNEG(SDNode *N) {
2166  SDOperand N0 = N->getOperand(0);
2167  ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
2168  MVT::ValueType VT = N->getValueType(0);
2169
2170  // fold (fneg c1) -> -c1
2171  if (N0CFP)
2172    return DAG.getNode(ISD::FNEG, VT, N0);
2173  // fold (fneg (sub x, y)) -> (sub y, x)
2174  if (N0.getOpcode() == ISD::SUB)
2175    return DAG.getNode(ISD::SUB, VT, N0.getOperand(1), N0.getOperand(0));
2176  // fold (fneg (fneg x)) -> x
2177  if (N0.getOpcode() == ISD::FNEG)
2178    return N0.getOperand(0);
2179  return SDOperand();
2180}
2181
2182SDOperand DAGCombiner::visitFABS(SDNode *N) {
2183  SDOperand N0 = N->getOperand(0);
2184  ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
2185  MVT::ValueType VT = N->getValueType(0);
2186
2187  // fold (fabs c1) -> fabs(c1)
2188  if (N0CFP)
2189    return DAG.getNode(ISD::FABS, VT, N0);
2190  // fold (fabs (fabs x)) -> (fabs x)
2191  if (N0.getOpcode() == ISD::FABS)
2192    return N->getOperand(0);
2193  // fold (fabs (fneg x)) -> (fabs x)
2194  // fold (fabs (fcopysign x, y)) -> (fabs x)
2195  if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
2196    return DAG.getNode(ISD::FABS, VT, N0.getOperand(0));
2197
2198  return SDOperand();
2199}
2200
2201SDOperand DAGCombiner::visitBRCOND(SDNode *N) {
2202  SDOperand Chain = N->getOperand(0);
2203  SDOperand N1 = N->getOperand(1);
2204  SDOperand N2 = N->getOperand(2);
2205  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2206
2207  // never taken branch, fold to chain
2208  if (N1C && N1C->isNullValue())
2209    return Chain;
2210  // unconditional branch
2211  if (N1C && N1C->getValue() == 1)
2212    return DAG.getNode(ISD::BR, MVT::Other, Chain, N2);
2213  // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
2214  // on the target.
2215  if (N1.getOpcode() == ISD::SETCC &&
2216      TLI.isOperationLegal(ISD::BR_CC, MVT::Other)) {
2217    return DAG.getNode(ISD::BR_CC, MVT::Other, Chain, N1.getOperand(2),
2218                       N1.getOperand(0), N1.getOperand(1), N2);
2219  }
2220  return SDOperand();
2221}
2222
2223// Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
2224//
2225SDOperand DAGCombiner::visitBR_CC(SDNode *N) {
2226  CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
2227  SDOperand CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
2228
2229  // Use SimplifySetCC  to simplify SETCC's.
2230  SDOperand Simp = SimplifySetCC(MVT::i1, CondLHS, CondRHS, CC->get(), false);
2231  ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(Simp.Val);
2232
2233  // fold br_cc true, dest -> br dest (unconditional branch)
2234  if (SCCC && SCCC->getValue())
2235    return DAG.getNode(ISD::BR, MVT::Other, N->getOperand(0),
2236                       N->getOperand(4));
2237  // fold br_cc false, dest -> unconditional fall through
2238  if (SCCC && SCCC->isNullValue())
2239    return N->getOperand(0);
2240  // fold to a simpler setcc
2241  if (Simp.Val && Simp.getOpcode() == ISD::SETCC)
2242    return DAG.getNode(ISD::BR_CC, MVT::Other, N->getOperand(0),
2243                       Simp.getOperand(2), Simp.getOperand(0),
2244                       Simp.getOperand(1), N->getOperand(4));
2245  return SDOperand();
2246}
2247
2248SDOperand DAGCombiner::visitLOAD(SDNode *N) {
2249  SDOperand Chain    = N->getOperand(0);
2250  SDOperand Ptr      = N->getOperand(1);
2251  SDOperand SrcValue = N->getOperand(2);
2252
2253  // If this load is directly stored, replace the load value with the stored
2254  // value.
2255  // TODO: Handle store large -> read small portion.
2256  // TODO: Handle TRUNCSTORE/EXTLOAD
2257  if (Chain.getOpcode() == ISD::STORE && Chain.getOperand(2) == Ptr &&
2258      Chain.getOperand(1).getValueType() == N->getValueType(0))
2259    return CombineTo(N, Chain.getOperand(1), Chain);
2260
2261  return SDOperand();
2262}
2263
2264SDOperand DAGCombiner::visitSTORE(SDNode *N) {
2265  SDOperand Chain    = N->getOperand(0);
2266  SDOperand Value    = N->getOperand(1);
2267  SDOperand Ptr      = N->getOperand(2);
2268  SDOperand SrcValue = N->getOperand(3);
2269
2270  // If this is a store that kills a previous store, remove the previous store.
2271  if (Chain.getOpcode() == ISD::STORE && Chain.getOperand(2) == Ptr &&
2272      Chain.Val->hasOneUse() /* Avoid introducing DAG cycles */ &&
2273      // Make sure that these stores are the same value type:
2274      // FIXME: we really care that the second store is >= size of the first.
2275      Value.getValueType() == Chain.getOperand(1).getValueType()) {
2276    // Create a new store of Value that replaces both stores.
2277    SDNode *PrevStore = Chain.Val;
2278    if (PrevStore->getOperand(1) == Value) // Same value multiply stored.
2279      return Chain;
2280    SDOperand NewStore = DAG.getNode(ISD::STORE, MVT::Other,
2281                                     PrevStore->getOperand(0), Value, Ptr,
2282                                     SrcValue);
2283    CombineTo(N, NewStore);                 // Nuke this store.
2284    CombineTo(PrevStore, NewStore);  // Nuke the previous store.
2285    return SDOperand(N, 0);
2286  }
2287
2288  // If this is a store of a bit convert, store the input value.
2289  // FIXME: This needs to know that the resultant store does not need a
2290  // higher alignment than the original.
2291  if (0 && Value.getOpcode() == ISD::BIT_CONVERT)
2292    return DAG.getNode(ISD::STORE, MVT::Other, Chain, Value.getOperand(0),
2293                       Ptr, SrcValue);
2294
2295  return SDOperand();
2296}
2297
2298SDOperand DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
2299  SDOperand InVec = N->getOperand(0);
2300  SDOperand InVal = N->getOperand(1);
2301  SDOperand EltNo = N->getOperand(2);
2302
2303  // If the invec is a BUILD_VECTOR and if EltNo is a constant, build a new
2304  // vector with the inserted element.
2305  if (InVec.getOpcode() == ISD::BUILD_VECTOR && isa<ConstantSDNode>(EltNo)) {
2306    unsigned Elt = cast<ConstantSDNode>(EltNo)->getValue();
2307    std::vector<SDOperand> Ops(InVec.Val->op_begin(), InVec.Val->op_end());
2308    if (Elt < Ops.size())
2309      Ops[Elt] = InVal;
2310    return DAG.getNode(ISD::BUILD_VECTOR, InVec.getValueType(), Ops);
2311  }
2312
2313  return SDOperand();
2314}
2315
2316SDOperand DAGCombiner::visitVINSERT_VECTOR_ELT(SDNode *N) {
2317  SDOperand InVec = N->getOperand(0);
2318  SDOperand InVal = N->getOperand(1);
2319  SDOperand EltNo = N->getOperand(2);
2320  SDOperand NumElts = N->getOperand(3);
2321  SDOperand EltType = N->getOperand(4);
2322
2323  // If the invec is a VBUILD_VECTOR and if EltNo is a constant, build a new
2324  // vector with the inserted element.
2325  if (InVec.getOpcode() == ISD::VBUILD_VECTOR && isa<ConstantSDNode>(EltNo)) {
2326    unsigned Elt = cast<ConstantSDNode>(EltNo)->getValue();
2327    std::vector<SDOperand> Ops(InVec.Val->op_begin(), InVec.Val->op_end());
2328    if (Elt < Ops.size()-2)
2329      Ops[Elt] = InVal;
2330    return DAG.getNode(ISD::VBUILD_VECTOR, InVec.getValueType(), Ops);
2331  }
2332
2333  return SDOperand();
2334}
2335
2336SDOperand DAGCombiner::SimplifySelect(SDOperand N0, SDOperand N1, SDOperand N2){
2337  assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
2338
2339  SDOperand SCC = SimplifySelectCC(N0.getOperand(0), N0.getOperand(1), N1, N2,
2340                                 cast<CondCodeSDNode>(N0.getOperand(2))->get());
2341  // If we got a simplified select_cc node back from SimplifySelectCC, then
2342  // break it down into a new SETCC node, and a new SELECT node, and then return
2343  // the SELECT node, since we were called with a SELECT node.
2344  if (SCC.Val) {
2345    // Check to see if we got a select_cc back (to turn into setcc/select).
2346    // Otherwise, just return whatever node we got back, like fabs.
2347    if (SCC.getOpcode() == ISD::SELECT_CC) {
2348      SDOperand SETCC = DAG.getNode(ISD::SETCC, N0.getValueType(),
2349                                    SCC.getOperand(0), SCC.getOperand(1),
2350                                    SCC.getOperand(4));
2351      AddToWorkList(SETCC.Val);
2352      return DAG.getNode(ISD::SELECT, SCC.getValueType(), SCC.getOperand(2),
2353                         SCC.getOperand(3), SETCC);
2354    }
2355    return SCC;
2356  }
2357  return SDOperand();
2358}
2359
2360/// SimplifySelectOps - Given a SELECT or a SELECT_CC node, where LHS and RHS
2361/// are the two values being selected between, see if we can simplify the
2362/// select.
2363///
2364bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDOperand LHS,
2365                                    SDOperand RHS) {
2366
2367  // If this is a select from two identical things, try to pull the operation
2368  // through the select.
2369  if (LHS.getOpcode() == RHS.getOpcode() && LHS.hasOneUse() && RHS.hasOneUse()){
2370#if 0
2371    std::cerr << "SELECT: ["; LHS.Val->dump();
2372    std::cerr << "] ["; RHS.Val->dump();
2373    std::cerr << "]\n";
2374#endif
2375
2376    // If this is a load and the token chain is identical, replace the select
2377    // of two loads with a load through a select of the address to load from.
2378    // This triggers in things like "select bool X, 10.0, 123.0" after the FP
2379    // constants have been dropped into the constant pool.
2380    if ((LHS.getOpcode() == ISD::LOAD ||
2381         LHS.getOpcode() == ISD::EXTLOAD ||
2382         LHS.getOpcode() == ISD::ZEXTLOAD ||
2383         LHS.getOpcode() == ISD::SEXTLOAD) &&
2384        // Token chains must be identical.
2385        LHS.getOperand(0) == RHS.getOperand(0) &&
2386        // If this is an EXTLOAD, the VT's must match.
2387        (LHS.getOpcode() == ISD::LOAD ||
2388         LHS.getOperand(3) == RHS.getOperand(3))) {
2389      // FIXME: this conflates two src values, discarding one.  This is not
2390      // the right thing to do, but nothing uses srcvalues now.  When they do,
2391      // turn SrcValue into a list of locations.
2392      SDOperand Addr;
2393      if (TheSelect->getOpcode() == ISD::SELECT)
2394        Addr = DAG.getNode(ISD::SELECT, LHS.getOperand(1).getValueType(),
2395                           TheSelect->getOperand(0), LHS.getOperand(1),
2396                           RHS.getOperand(1));
2397      else
2398        Addr = DAG.getNode(ISD::SELECT_CC, LHS.getOperand(1).getValueType(),
2399                           TheSelect->getOperand(0),
2400                           TheSelect->getOperand(1),
2401                           LHS.getOperand(1), RHS.getOperand(1),
2402                           TheSelect->getOperand(4));
2403
2404      SDOperand Load;
2405      if (LHS.getOpcode() == ISD::LOAD)
2406        Load = DAG.getLoad(TheSelect->getValueType(0), LHS.getOperand(0),
2407                           Addr, LHS.getOperand(2));
2408      else
2409        Load = DAG.getExtLoad(LHS.getOpcode(), TheSelect->getValueType(0),
2410                              LHS.getOperand(0), Addr, LHS.getOperand(2),
2411                              cast<VTSDNode>(LHS.getOperand(3))->getVT());
2412      // Users of the select now use the result of the load.
2413      CombineTo(TheSelect, Load);
2414
2415      // Users of the old loads now use the new load's chain.  We know the
2416      // old-load value is dead now.
2417      CombineTo(LHS.Val, Load.getValue(0), Load.getValue(1));
2418      CombineTo(RHS.Val, Load.getValue(0), Load.getValue(1));
2419      return true;
2420    }
2421  }
2422
2423  return false;
2424}
2425
2426SDOperand DAGCombiner::SimplifySelectCC(SDOperand N0, SDOperand N1,
2427                                        SDOperand N2, SDOperand N3,
2428                                        ISD::CondCode CC) {
2429
2430  MVT::ValueType VT = N2.getValueType();
2431  ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.Val);
2432  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val);
2433  ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.Val);
2434  ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.Val);
2435
2436  // Determine if the condition we're dealing with is constant
2437  SDOperand SCC = SimplifySetCC(TLI.getSetCCResultTy(), N0, N1, CC, false);
2438  ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.Val);
2439
2440  // fold select_cc true, x, y -> x
2441  if (SCCC && SCCC->getValue())
2442    return N2;
2443  // fold select_cc false, x, y -> y
2444  if (SCCC && SCCC->getValue() == 0)
2445    return N3;
2446
2447  // Check to see if we can simplify the select into an fabs node
2448  if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
2449    // Allow either -0.0 or 0.0
2450    if (CFP->getValue() == 0.0) {
2451      // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
2452      if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
2453          N0 == N2 && N3.getOpcode() == ISD::FNEG &&
2454          N2 == N3.getOperand(0))
2455        return DAG.getNode(ISD::FABS, VT, N0);
2456
2457      // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
2458      if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
2459          N0 == N3 && N2.getOpcode() == ISD::FNEG &&
2460          N2.getOperand(0) == N3)
2461        return DAG.getNode(ISD::FABS, VT, N3);
2462    }
2463  }
2464
2465  // Check to see if we can perform the "gzip trick", transforming
2466  // select_cc setlt X, 0, A, 0 -> and (sra X, size(X)-1), A
2467  if (N1C && N1C->isNullValue() && N3C && N3C->isNullValue() &&
2468      MVT::isInteger(N0.getValueType()) &&
2469      MVT::isInteger(N2.getValueType()) && CC == ISD::SETLT) {
2470    MVT::ValueType XType = N0.getValueType();
2471    MVT::ValueType AType = N2.getValueType();
2472    if (XType >= AType) {
2473      // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
2474      // single-bit constant.
2475      if (N2C && ((N2C->getValue() & (N2C->getValue()-1)) == 0)) {
2476        unsigned ShCtV = Log2_64(N2C->getValue());
2477        ShCtV = MVT::getSizeInBits(XType)-ShCtV-1;
2478        SDOperand ShCt = DAG.getConstant(ShCtV, TLI.getShiftAmountTy());
2479        SDOperand Shift = DAG.getNode(ISD::SRL, XType, N0, ShCt);
2480        AddToWorkList(Shift.Val);
2481        if (XType > AType) {
2482          Shift = DAG.getNode(ISD::TRUNCATE, AType, Shift);
2483          AddToWorkList(Shift.Val);
2484        }
2485        return DAG.getNode(ISD::AND, AType, Shift, N2);
2486      }
2487      SDOperand Shift = DAG.getNode(ISD::SRA, XType, N0,
2488                                    DAG.getConstant(MVT::getSizeInBits(XType)-1,
2489                                                    TLI.getShiftAmountTy()));
2490      AddToWorkList(Shift.Val);
2491      if (XType > AType) {
2492        Shift = DAG.getNode(ISD::TRUNCATE, AType, Shift);
2493        AddToWorkList(Shift.Val);
2494      }
2495      return DAG.getNode(ISD::AND, AType, Shift, N2);
2496    }
2497  }
2498
2499  // fold select C, 16, 0 -> shl C, 4
2500  if (N2C && N3C && N3C->isNullValue() && isPowerOf2_64(N2C->getValue()) &&
2501      TLI.getSetCCResultContents() == TargetLowering::ZeroOrOneSetCCResult) {
2502    // Get a SetCC of the condition
2503    // FIXME: Should probably make sure that setcc is legal if we ever have a
2504    // target where it isn't.
2505    SDOperand Temp, SCC;
2506    // cast from setcc result type to select result type
2507    if (AfterLegalize) {
2508      SCC  = DAG.getSetCC(TLI.getSetCCResultTy(), N0, N1, CC);
2509      Temp = DAG.getZeroExtendInReg(SCC, N2.getValueType());
2510    } else {
2511      SCC  = DAG.getSetCC(MVT::i1, N0, N1, CC);
2512      Temp = DAG.getNode(ISD::ZERO_EXTEND, N2.getValueType(), SCC);
2513    }
2514    AddToWorkList(SCC.Val);
2515    AddToWorkList(Temp.Val);
2516    // shl setcc result by log2 n2c
2517    return DAG.getNode(ISD::SHL, N2.getValueType(), Temp,
2518                       DAG.getConstant(Log2_64(N2C->getValue()),
2519                                       TLI.getShiftAmountTy()));
2520  }
2521
2522  // Check to see if this is the equivalent of setcc
2523  // FIXME: Turn all of these into setcc if setcc if setcc is legal
2524  // otherwise, go ahead with the folds.
2525  if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getValue() == 1ULL)) {
2526    MVT::ValueType XType = N0.getValueType();
2527    if (TLI.isOperationLegal(ISD::SETCC, TLI.getSetCCResultTy())) {
2528      SDOperand Res = DAG.getSetCC(TLI.getSetCCResultTy(), N0, N1, CC);
2529      if (Res.getValueType() != VT)
2530        Res = DAG.getNode(ISD::ZERO_EXTEND, VT, Res);
2531      return Res;
2532    }
2533
2534    // seteq X, 0 -> srl (ctlz X, log2(size(X)))
2535    if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
2536        TLI.isOperationLegal(ISD::CTLZ, XType)) {
2537      SDOperand Ctlz = DAG.getNode(ISD::CTLZ, XType, N0);
2538      return DAG.getNode(ISD::SRL, XType, Ctlz,
2539                         DAG.getConstant(Log2_32(MVT::getSizeInBits(XType)),
2540                                         TLI.getShiftAmountTy()));
2541    }
2542    // setgt X, 0 -> srl (and (-X, ~X), size(X)-1)
2543    if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
2544      SDOperand NegN0 = DAG.getNode(ISD::SUB, XType, DAG.getConstant(0, XType),
2545                                    N0);
2546      SDOperand NotN0 = DAG.getNode(ISD::XOR, XType, N0,
2547                                    DAG.getConstant(~0ULL, XType));
2548      return DAG.getNode(ISD::SRL, XType,
2549                         DAG.getNode(ISD::AND, XType, NegN0, NotN0),
2550                         DAG.getConstant(MVT::getSizeInBits(XType)-1,
2551                                         TLI.getShiftAmountTy()));
2552    }
2553    // setgt X, -1 -> xor (srl (X, size(X)-1), 1)
2554    if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
2555      SDOperand Sign = DAG.getNode(ISD::SRL, XType, N0,
2556                                   DAG.getConstant(MVT::getSizeInBits(XType)-1,
2557                                                   TLI.getShiftAmountTy()));
2558      return DAG.getNode(ISD::XOR, XType, Sign, DAG.getConstant(1, XType));
2559    }
2560  }
2561
2562  // Check to see if this is an integer abs. select_cc setl[te] X, 0, -X, X ->
2563  // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
2564  if (N1C && N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE) &&
2565      N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1)) {
2566    if (ConstantSDNode *SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0))) {
2567      MVT::ValueType XType = N0.getValueType();
2568      if (SubC->isNullValue() && MVT::isInteger(XType)) {
2569        SDOperand Shift = DAG.getNode(ISD::SRA, XType, N0,
2570                                    DAG.getConstant(MVT::getSizeInBits(XType)-1,
2571                                                    TLI.getShiftAmountTy()));
2572        SDOperand Add = DAG.getNode(ISD::ADD, XType, N0, Shift);
2573        AddToWorkList(Shift.Val);
2574        AddToWorkList(Add.Val);
2575        return DAG.getNode(ISD::XOR, XType, Add, Shift);
2576      }
2577    }
2578  }
2579
2580  return SDOperand();
2581}
2582
2583SDOperand DAGCombiner::SimplifySetCC(MVT::ValueType VT, SDOperand N0,
2584                                     SDOperand N1, ISD::CondCode Cond,
2585                                     bool foldBooleans) {
2586  // These setcc operations always fold.
2587  switch (Cond) {
2588  default: break;
2589  case ISD::SETFALSE:
2590  case ISD::SETFALSE2: return DAG.getConstant(0, VT);
2591  case ISD::SETTRUE:
2592  case ISD::SETTRUE2:  return DAG.getConstant(1, VT);
2593  }
2594
2595  if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val)) {
2596    uint64_t C1 = N1C->getValue();
2597    if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.Val)) {
2598      uint64_t C0 = N0C->getValue();
2599
2600      // Sign extend the operands if required
2601      if (ISD::isSignedIntSetCC(Cond)) {
2602        C0 = N0C->getSignExtended();
2603        C1 = N1C->getSignExtended();
2604      }
2605
2606      switch (Cond) {
2607      default: assert(0 && "Unknown integer setcc!");
2608      case ISD::SETEQ:  return DAG.getConstant(C0 == C1, VT);
2609      case ISD::SETNE:  return DAG.getConstant(C0 != C1, VT);
2610      case ISD::SETULT: return DAG.getConstant(C0 <  C1, VT);
2611      case ISD::SETUGT: return DAG.getConstant(C0 >  C1, VT);
2612      case ISD::SETULE: return DAG.getConstant(C0 <= C1, VT);
2613      case ISD::SETUGE: return DAG.getConstant(C0 >= C1, VT);
2614      case ISD::SETLT:  return DAG.getConstant((int64_t)C0 <  (int64_t)C1, VT);
2615      case ISD::SETGT:  return DAG.getConstant((int64_t)C0 >  (int64_t)C1, VT);
2616      case ISD::SETLE:  return DAG.getConstant((int64_t)C0 <= (int64_t)C1, VT);
2617      case ISD::SETGE:  return DAG.getConstant((int64_t)C0 >= (int64_t)C1, VT);
2618      }
2619    } else {
2620      // If the LHS is a ZERO_EXTEND, perform the comparison on the input.
2621      if (N0.getOpcode() == ISD::ZERO_EXTEND) {
2622        unsigned InSize = MVT::getSizeInBits(N0.getOperand(0).getValueType());
2623
2624        // If the comparison constant has bits in the upper part, the
2625        // zero-extended value could never match.
2626        if (C1 & (~0ULL << InSize)) {
2627          unsigned VSize = MVT::getSizeInBits(N0.getValueType());
2628          switch (Cond) {
2629          case ISD::SETUGT:
2630          case ISD::SETUGE:
2631          case ISD::SETEQ: return DAG.getConstant(0, VT);
2632          case ISD::SETULT:
2633          case ISD::SETULE:
2634          case ISD::SETNE: return DAG.getConstant(1, VT);
2635          case ISD::SETGT:
2636          case ISD::SETGE:
2637            // True if the sign bit of C1 is set.
2638            return DAG.getConstant((C1 & (1ULL << VSize)) != 0, VT);
2639          case ISD::SETLT:
2640          case ISD::SETLE:
2641            // True if the sign bit of C1 isn't set.
2642            return DAG.getConstant((C1 & (1ULL << VSize)) == 0, VT);
2643          default:
2644            break;
2645          }
2646        }
2647
2648        // Otherwise, we can perform the comparison with the low bits.
2649        switch (Cond) {
2650        case ISD::SETEQ:
2651        case ISD::SETNE:
2652        case ISD::SETUGT:
2653        case ISD::SETUGE:
2654        case ISD::SETULT:
2655        case ISD::SETULE:
2656          return DAG.getSetCC(VT, N0.getOperand(0),
2657                          DAG.getConstant(C1, N0.getOperand(0).getValueType()),
2658                          Cond);
2659        default:
2660          break;   // todo, be more careful with signed comparisons
2661        }
2662      } else if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
2663                 (Cond == ISD::SETEQ || Cond == ISD::SETNE)) {
2664        MVT::ValueType ExtSrcTy = cast<VTSDNode>(N0.getOperand(1))->getVT();
2665        unsigned ExtSrcTyBits = MVT::getSizeInBits(ExtSrcTy);
2666        MVT::ValueType ExtDstTy = N0.getValueType();
2667        unsigned ExtDstTyBits = MVT::getSizeInBits(ExtDstTy);
2668
2669        // If the extended part has any inconsistent bits, it cannot ever
2670        // compare equal.  In other words, they have to be all ones or all
2671        // zeros.
2672        uint64_t ExtBits =
2673          (~0ULL >> (64-ExtSrcTyBits)) & (~0ULL << (ExtDstTyBits-1));
2674        if ((C1 & ExtBits) != 0 && (C1 & ExtBits) != ExtBits)
2675          return DAG.getConstant(Cond == ISD::SETNE, VT);
2676
2677        SDOperand ZextOp;
2678        MVT::ValueType Op0Ty = N0.getOperand(0).getValueType();
2679        if (Op0Ty == ExtSrcTy) {
2680          ZextOp = N0.getOperand(0);
2681        } else {
2682          int64_t Imm = ~0ULL >> (64-ExtSrcTyBits);
2683          ZextOp = DAG.getNode(ISD::AND, Op0Ty, N0.getOperand(0),
2684                               DAG.getConstant(Imm, Op0Ty));
2685        }
2686        AddToWorkList(ZextOp.Val);
2687        // Otherwise, make this a use of a zext.
2688        return DAG.getSetCC(VT, ZextOp,
2689                            DAG.getConstant(C1 & (~0ULL>>(64-ExtSrcTyBits)),
2690                                            ExtDstTy),
2691                            Cond);
2692      } else if ((N1C->getValue() == 0 || N1C->getValue() == 1) &&
2693                 (Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
2694                 (N0.getOpcode() == ISD::XOR ||
2695                  (N0.getOpcode() == ISD::AND &&
2696                   N0.getOperand(0).getOpcode() == ISD::XOR &&
2697                   N0.getOperand(1) == N0.getOperand(0).getOperand(1))) &&
2698                 isa<ConstantSDNode>(N0.getOperand(1)) &&
2699                 cast<ConstantSDNode>(N0.getOperand(1))->getValue() == 1) {
2700        // If this is (X^1) == 0/1, swap the RHS and eliminate the xor.  We can
2701        // only do this if the top bits are known zero.
2702        if (TLI.MaskedValueIsZero(N1,
2703                                  MVT::getIntVTBitMask(N0.getValueType())-1)) {
2704          // Okay, get the un-inverted input value.
2705          SDOperand Val;
2706          if (N0.getOpcode() == ISD::XOR)
2707            Val = N0.getOperand(0);
2708          else {
2709            assert(N0.getOpcode() == ISD::AND &&
2710                   N0.getOperand(0).getOpcode() == ISD::XOR);
2711            // ((X^1)&1)^1 -> X & 1
2712            Val = DAG.getNode(ISD::AND, N0.getValueType(),
2713                              N0.getOperand(0).getOperand(0), N0.getOperand(1));
2714          }
2715          return DAG.getSetCC(VT, Val, N1,
2716                              Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ);
2717        }
2718      }
2719
2720      uint64_t MinVal, MaxVal;
2721      unsigned OperandBitSize = MVT::getSizeInBits(N1C->getValueType(0));
2722      if (ISD::isSignedIntSetCC(Cond)) {
2723        MinVal = 1ULL << (OperandBitSize-1);
2724        if (OperandBitSize != 1)   // Avoid X >> 64, which is undefined.
2725          MaxVal = ~0ULL >> (65-OperandBitSize);
2726        else
2727          MaxVal = 0;
2728      } else {
2729        MinVal = 0;
2730        MaxVal = ~0ULL >> (64-OperandBitSize);
2731      }
2732
2733      // Canonicalize GE/LE comparisons to use GT/LT comparisons.
2734      if (Cond == ISD::SETGE || Cond == ISD::SETUGE) {
2735        if (C1 == MinVal) return DAG.getConstant(1, VT);   // X >= MIN --> true
2736        --C1;                                          // X >= C0 --> X > (C0-1)
2737        return DAG.getSetCC(VT, N0, DAG.getConstant(C1, N1.getValueType()),
2738                        (Cond == ISD::SETGE) ? ISD::SETGT : ISD::SETUGT);
2739      }
2740
2741      if (Cond == ISD::SETLE || Cond == ISD::SETULE) {
2742        if (C1 == MaxVal) return DAG.getConstant(1, VT);   // X <= MAX --> true
2743        ++C1;                                          // X <= C0 --> X < (C0+1)
2744        return DAG.getSetCC(VT, N0, DAG.getConstant(C1, N1.getValueType()),
2745                        (Cond == ISD::SETLE) ? ISD::SETLT : ISD::SETULT);
2746      }
2747
2748      if ((Cond == ISD::SETLT || Cond == ISD::SETULT) && C1 == MinVal)
2749        return DAG.getConstant(0, VT);      // X < MIN --> false
2750
2751      // Canonicalize setgt X, Min --> setne X, Min
2752      if ((Cond == ISD::SETGT || Cond == ISD::SETUGT) && C1 == MinVal)
2753        return DAG.getSetCC(VT, N0, N1, ISD::SETNE);
2754      // Canonicalize setlt X, Max --> setne X, Max
2755      if ((Cond == ISD::SETLT || Cond == ISD::SETULT) && C1 == MaxVal)
2756        return DAG.getSetCC(VT, N0, N1, ISD::SETNE);
2757
2758      // If we have setult X, 1, turn it into seteq X, 0
2759      if ((Cond == ISD::SETLT || Cond == ISD::SETULT) && C1 == MinVal+1)
2760        return DAG.getSetCC(VT, N0, DAG.getConstant(MinVal, N0.getValueType()),
2761                        ISD::SETEQ);
2762      // If we have setugt X, Max-1, turn it into seteq X, Max
2763      else if ((Cond == ISD::SETGT || Cond == ISD::SETUGT) && C1 == MaxVal-1)
2764        return DAG.getSetCC(VT, N0, DAG.getConstant(MaxVal, N0.getValueType()),
2765                        ISD::SETEQ);
2766
2767      // If we have "setcc X, C0", check to see if we can shrink the immediate
2768      // by changing cc.
2769
2770      // SETUGT X, SINTMAX  -> SETLT X, 0
2771      if (Cond == ISD::SETUGT && OperandBitSize != 1 &&
2772          C1 == (~0ULL >> (65-OperandBitSize)))
2773        return DAG.getSetCC(VT, N0, DAG.getConstant(0, N1.getValueType()),
2774                            ISD::SETLT);
2775
2776      // FIXME: Implement the rest of these.
2777
2778      // Fold bit comparisons when we can.
2779      if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
2780          VT == N0.getValueType() && N0.getOpcode() == ISD::AND)
2781        if (ConstantSDNode *AndRHS =
2782                    dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2783          if (Cond == ISD::SETNE && C1 == 0) {// (X & 8) != 0  -->  (X & 8) >> 3
2784            // Perform the xform if the AND RHS is a single bit.
2785            if ((AndRHS->getValue() & (AndRHS->getValue()-1)) == 0) {
2786              return DAG.getNode(ISD::SRL, VT, N0,
2787                             DAG.getConstant(Log2_64(AndRHS->getValue()),
2788                                                   TLI.getShiftAmountTy()));
2789            }
2790          } else if (Cond == ISD::SETEQ && C1 == AndRHS->getValue()) {
2791            // (X & 8) == 8  -->  (X & 8) >> 3
2792            // Perform the xform if C1 is a single bit.
2793            if ((C1 & (C1-1)) == 0) {
2794              return DAG.getNode(ISD::SRL, VT, N0,
2795                             DAG.getConstant(Log2_64(C1),TLI.getShiftAmountTy()));
2796            }
2797          }
2798        }
2799    }
2800  } else if (isa<ConstantSDNode>(N0.Val)) {
2801      // Ensure that the constant occurs on the RHS.
2802    return DAG.getSetCC(VT, N1, N0, ISD::getSetCCSwappedOperands(Cond));
2803  }
2804
2805  if (ConstantFPSDNode *N0C = dyn_cast<ConstantFPSDNode>(N0.Val))
2806    if (ConstantFPSDNode *N1C = dyn_cast<ConstantFPSDNode>(N1.Val)) {
2807      double C0 = N0C->getValue(), C1 = N1C->getValue();
2808
2809      switch (Cond) {
2810      default: break; // FIXME: Implement the rest of these!
2811      case ISD::SETEQ:  return DAG.getConstant(C0 == C1, VT);
2812      case ISD::SETNE:  return DAG.getConstant(C0 != C1, VT);
2813      case ISD::SETLT:  return DAG.getConstant(C0 < C1, VT);
2814      case ISD::SETGT:  return DAG.getConstant(C0 > C1, VT);
2815      case ISD::SETLE:  return DAG.getConstant(C0 <= C1, VT);
2816      case ISD::SETGE:  return DAG.getConstant(C0 >= C1, VT);
2817      }
2818    } else {
2819      // Ensure that the constant occurs on the RHS.
2820      return DAG.getSetCC(VT, N1, N0, ISD::getSetCCSwappedOperands(Cond));
2821    }
2822
2823  if (N0 == N1) {
2824    // We can always fold X == Y for integer setcc's.
2825    if (MVT::isInteger(N0.getValueType()))
2826      return DAG.getConstant(ISD::isTrueWhenEqual(Cond), VT);
2827    unsigned UOF = ISD::getUnorderedFlavor(Cond);
2828    if (UOF == 2)   // FP operators that are undefined on NaNs.
2829      return DAG.getConstant(ISD::isTrueWhenEqual(Cond), VT);
2830    if (UOF == unsigned(ISD::isTrueWhenEqual(Cond)))
2831      return DAG.getConstant(UOF, VT);
2832    // Otherwise, we can't fold it.  However, we can simplify it to SETUO/SETO
2833    // if it is not already.
2834    ISD::CondCode NewCond = UOF == 0 ? ISD::SETO : ISD::SETUO;
2835    if (NewCond != Cond)
2836      return DAG.getSetCC(VT, N0, N1, NewCond);
2837  }
2838
2839  if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
2840      MVT::isInteger(N0.getValueType())) {
2841    if (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::SUB ||
2842        N0.getOpcode() == ISD::XOR) {
2843      // Simplify (X+Y) == (X+Z) -->  Y == Z
2844      if (N0.getOpcode() == N1.getOpcode()) {
2845        if (N0.getOperand(0) == N1.getOperand(0))
2846          return DAG.getSetCC(VT, N0.getOperand(1), N1.getOperand(1), Cond);
2847        if (N0.getOperand(1) == N1.getOperand(1))
2848          return DAG.getSetCC(VT, N0.getOperand(0), N1.getOperand(0), Cond);
2849        if (isCommutativeBinOp(N0.getOpcode())) {
2850          // If X op Y == Y op X, try other combinations.
2851          if (N0.getOperand(0) == N1.getOperand(1))
2852            return DAG.getSetCC(VT, N0.getOperand(1), N1.getOperand(0), Cond);
2853          if (N0.getOperand(1) == N1.getOperand(0))
2854            return DAG.getSetCC(VT, N0.getOperand(0), N1.getOperand(1), Cond);
2855        }
2856      }
2857
2858      if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(N1)) {
2859        if (ConstantSDNode *LHSR = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2860          // Turn (X+C1) == C2 --> X == C2-C1
2861          if (N0.getOpcode() == ISD::ADD && N0.Val->hasOneUse()) {
2862            return DAG.getSetCC(VT, N0.getOperand(0),
2863                              DAG.getConstant(RHSC->getValue()-LHSR->getValue(),
2864                                N0.getValueType()), Cond);
2865          }
2866
2867          // Turn (X^C1) == C2 into X == C1^C2 iff X&~C1 = 0.
2868          if (N0.getOpcode() == ISD::XOR)
2869            // If we know that all of the inverted bits are zero, don't bother
2870            // performing the inversion.
2871            if (TLI.MaskedValueIsZero(N0.getOperand(0), ~LHSR->getValue()))
2872              return DAG.getSetCC(VT, N0.getOperand(0),
2873                              DAG.getConstant(LHSR->getValue()^RHSC->getValue(),
2874                                              N0.getValueType()), Cond);
2875        }
2876
2877        // Turn (C1-X) == C2 --> X == C1-C2
2878        if (ConstantSDNode *SUBC = dyn_cast<ConstantSDNode>(N0.getOperand(0))) {
2879          if (N0.getOpcode() == ISD::SUB && N0.Val->hasOneUse()) {
2880            return DAG.getSetCC(VT, N0.getOperand(1),
2881                             DAG.getConstant(SUBC->getValue()-RHSC->getValue(),
2882                                             N0.getValueType()), Cond);
2883          }
2884        }
2885      }
2886
2887      // Simplify (X+Z) == X -->  Z == 0
2888      if (N0.getOperand(0) == N1)
2889        return DAG.getSetCC(VT, N0.getOperand(1),
2890                        DAG.getConstant(0, N0.getValueType()), Cond);
2891      if (N0.getOperand(1) == N1) {
2892        if (isCommutativeBinOp(N0.getOpcode()))
2893          return DAG.getSetCC(VT, N0.getOperand(0),
2894                          DAG.getConstant(0, N0.getValueType()), Cond);
2895        else {
2896          assert(N0.getOpcode() == ISD::SUB && "Unexpected operation!");
2897          // (Z-X) == X  --> Z == X<<1
2898          SDOperand SH = DAG.getNode(ISD::SHL, N1.getValueType(),
2899                                     N1,
2900                                     DAG.getConstant(1,TLI.getShiftAmountTy()));
2901          AddToWorkList(SH.Val);
2902          return DAG.getSetCC(VT, N0.getOperand(0), SH, Cond);
2903        }
2904      }
2905    }
2906
2907    if (N1.getOpcode() == ISD::ADD || N1.getOpcode() == ISD::SUB ||
2908        N1.getOpcode() == ISD::XOR) {
2909      // Simplify  X == (X+Z) -->  Z == 0
2910      if (N1.getOperand(0) == N0) {
2911        return DAG.getSetCC(VT, N1.getOperand(1),
2912                        DAG.getConstant(0, N1.getValueType()), Cond);
2913      } else if (N1.getOperand(1) == N0) {
2914        if (isCommutativeBinOp(N1.getOpcode())) {
2915          return DAG.getSetCC(VT, N1.getOperand(0),
2916                          DAG.getConstant(0, N1.getValueType()), Cond);
2917        } else {
2918          assert(N1.getOpcode() == ISD::SUB && "Unexpected operation!");
2919          // X == (Z-X)  --> X<<1 == Z
2920          SDOperand SH = DAG.getNode(ISD::SHL, N1.getValueType(), N0,
2921                                     DAG.getConstant(1,TLI.getShiftAmountTy()));
2922          AddToWorkList(SH.Val);
2923          return DAG.getSetCC(VT, SH, N1.getOperand(0), Cond);
2924        }
2925      }
2926    }
2927  }
2928
2929  // Fold away ALL boolean setcc's.
2930  SDOperand Temp;
2931  if (N0.getValueType() == MVT::i1 && foldBooleans) {
2932    switch (Cond) {
2933    default: assert(0 && "Unknown integer setcc!");
2934    case ISD::SETEQ:  // X == Y  -> (X^Y)^1
2935      Temp = DAG.getNode(ISD::XOR, MVT::i1, N0, N1);
2936      N0 = DAG.getNode(ISD::XOR, MVT::i1, Temp, DAG.getConstant(1, MVT::i1));
2937      AddToWorkList(Temp.Val);
2938      break;
2939    case ISD::SETNE:  // X != Y   -->  (X^Y)
2940      N0 = DAG.getNode(ISD::XOR, MVT::i1, N0, N1);
2941      break;
2942    case ISD::SETGT:  // X >s Y   -->  X == 0 & Y == 1  -->  X^1 & Y
2943    case ISD::SETULT: // X <u Y   -->  X == 0 & Y == 1  -->  X^1 & Y
2944      Temp = DAG.getNode(ISD::XOR, MVT::i1, N0, DAG.getConstant(1, MVT::i1));
2945      N0 = DAG.getNode(ISD::AND, MVT::i1, N1, Temp);
2946      AddToWorkList(Temp.Val);
2947      break;
2948    case ISD::SETLT:  // X <s Y   --> X == 1 & Y == 0  -->  Y^1 & X
2949    case ISD::SETUGT: // X >u Y   --> X == 1 & Y == 0  -->  Y^1 & X
2950      Temp = DAG.getNode(ISD::XOR, MVT::i1, N1, DAG.getConstant(1, MVT::i1));
2951      N0 = DAG.getNode(ISD::AND, MVT::i1, N0, Temp);
2952      AddToWorkList(Temp.Val);
2953      break;
2954    case ISD::SETULE: // X <=u Y  --> X == 0 | Y == 1  -->  X^1 | Y
2955    case ISD::SETGE:  // X >=s Y  --> X == 0 | Y == 1  -->  X^1 | Y
2956      Temp = DAG.getNode(ISD::XOR, MVT::i1, N0, DAG.getConstant(1, MVT::i1));
2957      N0 = DAG.getNode(ISD::OR, MVT::i1, N1, Temp);
2958      AddToWorkList(Temp.Val);
2959      break;
2960    case ISD::SETUGE: // X >=u Y  --> X == 1 | Y == 0  -->  Y^1 | X
2961    case ISD::SETLE:  // X <=s Y  --> X == 1 | Y == 0  -->  Y^1 | X
2962      Temp = DAG.getNode(ISD::XOR, MVT::i1, N1, DAG.getConstant(1, MVT::i1));
2963      N0 = DAG.getNode(ISD::OR, MVT::i1, N0, Temp);
2964      break;
2965    }
2966    if (VT != MVT::i1) {
2967      AddToWorkList(N0.Val);
2968      // FIXME: If running after legalize, we probably can't do this.
2969      N0 = DAG.getNode(ISD::ZERO_EXTEND, VT, N0);
2970    }
2971    return N0;
2972  }
2973
2974  // Could not fold it.
2975  return SDOperand();
2976}
2977
2978/// BuildSDIVSequence - Given an ISD::SDIV node expressing a divide by constant,
2979/// return a DAG expression to select that will generate the same value by
2980/// multiplying by a magic number.  See:
2981/// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
2982SDOperand DAGCombiner::BuildSDIV(SDNode *N) {
2983  MVT::ValueType VT = N->getValueType(0);
2984
2985  // Check to see if we can do this.
2986  if (!TLI.isTypeLegal(VT) || (VT != MVT::i32 && VT != MVT::i64))
2987    return SDOperand();       // BuildSDIV only operates on i32 or i64
2988  if (!TLI.isOperationLegal(ISD::MULHS, VT))
2989    return SDOperand();       // Make sure the target supports MULHS.
2990
2991  int64_t d = cast<ConstantSDNode>(N->getOperand(1))->getSignExtended();
2992  ms magics = (VT == MVT::i32) ? magic32(d) : magic64(d);
2993
2994  // Multiply the numerator (operand 0) by the magic value
2995  SDOperand Q = DAG.getNode(ISD::MULHS, VT, N->getOperand(0),
2996                            DAG.getConstant(magics.m, VT));
2997  // If d > 0 and m < 0, add the numerator
2998  if (d > 0 && magics.m < 0) {
2999    Q = DAG.getNode(ISD::ADD, VT, Q, N->getOperand(0));
3000    AddToWorkList(Q.Val);
3001  }
3002  // If d < 0 and m > 0, subtract the numerator.
3003  if (d < 0 && magics.m > 0) {
3004    Q = DAG.getNode(ISD::SUB, VT, Q, N->getOperand(0));
3005    AddToWorkList(Q.Val);
3006  }
3007  // Shift right algebraic if shift value is nonzero
3008  if (magics.s > 0) {
3009    Q = DAG.getNode(ISD::SRA, VT, Q,
3010                    DAG.getConstant(magics.s, TLI.getShiftAmountTy()));
3011    AddToWorkList(Q.Val);
3012  }
3013  // Extract the sign bit and add it to the quotient
3014  SDOperand T =
3015    DAG.getNode(ISD::SRL, VT, Q, DAG.getConstant(MVT::getSizeInBits(VT)-1,
3016                                                 TLI.getShiftAmountTy()));
3017  AddToWorkList(T.Val);
3018  return DAG.getNode(ISD::ADD, VT, Q, T);
3019}
3020
3021/// BuildUDIVSequence - Given an ISD::UDIV node expressing a divide by constant,
3022/// return a DAG expression to select that will generate the same value by
3023/// multiplying by a magic number.  See:
3024/// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
3025SDOperand DAGCombiner::BuildUDIV(SDNode *N) {
3026  MVT::ValueType VT = N->getValueType(0);
3027
3028  // Check to see if we can do this.
3029  if (!TLI.isTypeLegal(VT) || (VT != MVT::i32 && VT != MVT::i64))
3030    return SDOperand();       // BuildUDIV only operates on i32 or i64
3031  if (!TLI.isOperationLegal(ISD::MULHU, VT))
3032    return SDOperand();       // Make sure the target supports MULHU.
3033
3034  uint64_t d = cast<ConstantSDNode>(N->getOperand(1))->getValue();
3035  mu magics = (VT == MVT::i32) ? magicu32(d) : magicu64(d);
3036
3037  // Multiply the numerator (operand 0) by the magic value
3038  SDOperand Q = DAG.getNode(ISD::MULHU, VT, N->getOperand(0),
3039                            DAG.getConstant(magics.m, VT));
3040  AddToWorkList(Q.Val);
3041
3042  if (magics.a == 0) {
3043    return DAG.getNode(ISD::SRL, VT, Q,
3044                       DAG.getConstant(magics.s, TLI.getShiftAmountTy()));
3045  } else {
3046    SDOperand NPQ = DAG.getNode(ISD::SUB, VT, N->getOperand(0), Q);
3047    AddToWorkList(NPQ.Val);
3048    NPQ = DAG.getNode(ISD::SRL, VT, NPQ,
3049                      DAG.getConstant(1, TLI.getShiftAmountTy()));
3050    AddToWorkList(NPQ.Val);
3051    NPQ = DAG.getNode(ISD::ADD, VT, NPQ, Q);
3052    AddToWorkList(NPQ.Val);
3053    return DAG.getNode(ISD::SRL, VT, NPQ,
3054                       DAG.getConstant(magics.s-1, TLI.getShiftAmountTy()));
3055  }
3056}
3057
3058// SelectionDAG::Combine - This is the entry point for the file.
3059//
3060void SelectionDAG::Combine(bool RunningAfterLegalize) {
3061  /// run - This is the main entry point to this class.
3062  ///
3063  DAGCombiner(*this).Run(RunningAfterLegalize);
3064}
3065