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