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