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