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