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