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