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