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