DAGCombiner.cpp revision 202878
1193323Sed//===-- DAGCombiner.cpp - Implement a DAG node combiner -------------------===//
2193323Sed//
3193323Sed//                     The LLVM Compiler Infrastructure
4193323Sed//
5193323Sed// This file is distributed under the University of Illinois Open Source
6193323Sed// License. See LICENSE.TXT for details.
7193323Sed//
8193323Sed//===----------------------------------------------------------------------===//
9193323Sed//
10193323Sed// This pass combines dag nodes to form fewer, simpler DAG nodes.  It can be run
11193323Sed// both before and after the DAG is legalized.
12193323Sed//
13193323Sed// This pass is not a substitute for the LLVM IR instcombine pass. This pass is
14193323Sed// primarily intended to handle simplification opportunities that are implicit
15193323Sed// in the LLVM IR and exposed by the various codegen lowering phases.
16193323Sed//
17193323Sed//===----------------------------------------------------------------------===//
18193323Sed
19193323Sed#define DEBUG_TYPE "dagcombine"
20193323Sed#include "llvm/CodeGen/SelectionDAG.h"
21193323Sed#include "llvm/DerivedTypes.h"
22198090Srdivacky#include "llvm/LLVMContext.h"
23193323Sed#include "llvm/CodeGen/MachineFunction.h"
24193323Sed#include "llvm/CodeGen/MachineFrameInfo.h"
25193323Sed#include "llvm/CodeGen/PseudoSourceValue.h"
26193323Sed#include "llvm/Analysis/AliasAnalysis.h"
27193323Sed#include "llvm/Target/TargetData.h"
28193323Sed#include "llvm/Target/TargetFrameInfo.h"
29193323Sed#include "llvm/Target/TargetLowering.h"
30193323Sed#include "llvm/Target/TargetMachine.h"
31193323Sed#include "llvm/Target/TargetOptions.h"
32193323Sed#include "llvm/ADT/SmallPtrSet.h"
33193323Sed#include "llvm/ADT/Statistic.h"
34193323Sed#include "llvm/Support/CommandLine.h"
35193323Sed#include "llvm/Support/Debug.h"
36198090Srdivacky#include "llvm/Support/ErrorHandling.h"
37193323Sed#include "llvm/Support/MathExtras.h"
38198090Srdivacky#include "llvm/Support/raw_ostream.h"
39193323Sed#include <algorithm>
40193323Sedusing namespace llvm;
41193323Sed
42193323SedSTATISTIC(NodesCombined   , "Number of dag nodes combined");
43193323SedSTATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created");
44193323SedSTATISTIC(PostIndexedNodes, "Number of post-indexed nodes created");
45193323SedSTATISTIC(OpsNarrowed     , "Number of load/op/store narrowed");
46193323Sed
47193323Sednamespace {
48193323Sed  static cl::opt<bool>
49193323Sed    CombinerAA("combiner-alias-analysis", cl::Hidden,
50193323Sed               cl::desc("Turn on alias analysis during testing"));
51193323Sed
52193323Sed  static cl::opt<bool>
53193323Sed    CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden,
54193323Sed               cl::desc("Include global information in alias analysis"));
55193323Sed
56193323Sed//------------------------------ DAGCombiner ---------------------------------//
57193323Sed
58198892Srdivacky  class DAGCombiner {
59193323Sed    SelectionDAG &DAG;
60193323Sed    const TargetLowering &TLI;
61193323Sed    CombineLevel Level;
62193323Sed    CodeGenOpt::Level OptLevel;
63193323Sed    bool LegalOperations;
64193323Sed    bool LegalTypes;
65193323Sed
66193323Sed    // Worklist of all of the nodes that need to be simplified.
67193323Sed    std::vector<SDNode*> WorkList;
68193323Sed
69193323Sed    // AA - Used for DAG load/store alias analysis.
70193323Sed    AliasAnalysis &AA;
71193323Sed
72193323Sed    /// AddUsersToWorkList - When an instruction is simplified, add all users of
73193323Sed    /// the instruction to the work lists because they might get more simplified
74193323Sed    /// now.
75193323Sed    ///
76193323Sed    void AddUsersToWorkList(SDNode *N) {
77193323Sed      for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
78193323Sed           UI != UE; ++UI)
79193323Sed        AddToWorkList(*UI);
80193323Sed    }
81193323Sed
82193323Sed    /// visit - call the node-specific routine that knows how to fold each
83193323Sed    /// particular type of node.
84193323Sed    SDValue visit(SDNode *N);
85193323Sed
86193323Sed  public:
87193323Sed    /// AddToWorkList - Add to the work list making sure it's instance is at the
88193323Sed    /// the back (next to be processed.)
89193323Sed    void AddToWorkList(SDNode *N) {
90193323Sed      removeFromWorkList(N);
91193323Sed      WorkList.push_back(N);
92193323Sed    }
93193323Sed
94193323Sed    /// removeFromWorkList - remove all instances of N from the worklist.
95193323Sed    ///
96193323Sed    void removeFromWorkList(SDNode *N) {
97193323Sed      WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), N),
98193323Sed                     WorkList.end());
99193323Sed    }
100193323Sed
101193323Sed    SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
102193323Sed                      bool AddTo = true);
103193323Sed
104193323Sed    SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) {
105193323Sed      return CombineTo(N, &Res, 1, AddTo);
106193323Sed    }
107193323Sed
108193323Sed    SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1,
109193323Sed                      bool AddTo = true) {
110193323Sed      SDValue To[] = { Res0, Res1 };
111193323Sed      return CombineTo(N, To, 2, AddTo);
112193323Sed    }
113193323Sed
114193323Sed    void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO);
115193323Sed
116193323Sed  private:
117193323Sed
118193323Sed    /// SimplifyDemandedBits - Check the specified integer node value to see if
119193323Sed    /// it can be simplified or if things it uses can be simplified by bit
120193323Sed    /// propagation.  If so, return true.
121193323Sed    bool SimplifyDemandedBits(SDValue Op) {
122200581Srdivacky      unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits();
123200581Srdivacky      APInt Demanded = APInt::getAllOnesValue(BitWidth);
124193323Sed      return SimplifyDemandedBits(Op, Demanded);
125193323Sed    }
126193323Sed
127193323Sed    bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded);
128193323Sed
129193323Sed    bool CombineToPreIndexedLoadStore(SDNode *N);
130193323Sed    bool CombineToPostIndexedLoadStore(SDNode *N);
131193323Sed
132193323Sed
133193323Sed    /// combine - call the node-specific routine that knows how to fold each
134193323Sed    /// particular type of node. If that doesn't do anything, try the
135193323Sed    /// target-specific DAG combines.
136193323Sed    SDValue combine(SDNode *N);
137193323Sed
138193323Sed    // Visitation implementation - Implement dag node combining for different
139193323Sed    // node types.  The semantics are as follows:
140193323Sed    // Return Value:
141193323Sed    //   SDValue.getNode() == 0 - No change was made
142193323Sed    //   SDValue.getNode() == N - N was replaced, is dead and has been handled.
143193323Sed    //   otherwise              - N should be replaced by the returned Operand.
144193323Sed    //
145193323Sed    SDValue visitTokenFactor(SDNode *N);
146193323Sed    SDValue visitMERGE_VALUES(SDNode *N);
147193323Sed    SDValue visitADD(SDNode *N);
148193323Sed    SDValue visitSUB(SDNode *N);
149193323Sed    SDValue visitADDC(SDNode *N);
150193323Sed    SDValue visitADDE(SDNode *N);
151193323Sed    SDValue visitMUL(SDNode *N);
152193323Sed    SDValue visitSDIV(SDNode *N);
153193323Sed    SDValue visitUDIV(SDNode *N);
154193323Sed    SDValue visitSREM(SDNode *N);
155193323Sed    SDValue visitUREM(SDNode *N);
156193323Sed    SDValue visitMULHU(SDNode *N);
157193323Sed    SDValue visitMULHS(SDNode *N);
158193323Sed    SDValue visitSMUL_LOHI(SDNode *N);
159193323Sed    SDValue visitUMUL_LOHI(SDNode *N);
160193323Sed    SDValue visitSDIVREM(SDNode *N);
161193323Sed    SDValue visitUDIVREM(SDNode *N);
162193323Sed    SDValue visitAND(SDNode *N);
163193323Sed    SDValue visitOR(SDNode *N);
164193323Sed    SDValue visitXOR(SDNode *N);
165193323Sed    SDValue SimplifyVBinOp(SDNode *N);
166193323Sed    SDValue visitSHL(SDNode *N);
167193323Sed    SDValue visitSRA(SDNode *N);
168193323Sed    SDValue visitSRL(SDNode *N);
169193323Sed    SDValue visitCTLZ(SDNode *N);
170193323Sed    SDValue visitCTTZ(SDNode *N);
171193323Sed    SDValue visitCTPOP(SDNode *N);
172193323Sed    SDValue visitSELECT(SDNode *N);
173193323Sed    SDValue visitSELECT_CC(SDNode *N);
174193323Sed    SDValue visitSETCC(SDNode *N);
175193323Sed    SDValue visitSIGN_EXTEND(SDNode *N);
176193323Sed    SDValue visitZERO_EXTEND(SDNode *N);
177193323Sed    SDValue visitANY_EXTEND(SDNode *N);
178193323Sed    SDValue visitSIGN_EXTEND_INREG(SDNode *N);
179193323Sed    SDValue visitTRUNCATE(SDNode *N);
180193323Sed    SDValue visitBIT_CONVERT(SDNode *N);
181193323Sed    SDValue visitBUILD_PAIR(SDNode *N);
182193323Sed    SDValue visitFADD(SDNode *N);
183193323Sed    SDValue visitFSUB(SDNode *N);
184193323Sed    SDValue visitFMUL(SDNode *N);
185193323Sed    SDValue visitFDIV(SDNode *N);
186193323Sed    SDValue visitFREM(SDNode *N);
187193323Sed    SDValue visitFCOPYSIGN(SDNode *N);
188193323Sed    SDValue visitSINT_TO_FP(SDNode *N);
189193323Sed    SDValue visitUINT_TO_FP(SDNode *N);
190193323Sed    SDValue visitFP_TO_SINT(SDNode *N);
191193323Sed    SDValue visitFP_TO_UINT(SDNode *N);
192193323Sed    SDValue visitFP_ROUND(SDNode *N);
193193323Sed    SDValue visitFP_ROUND_INREG(SDNode *N);
194193323Sed    SDValue visitFP_EXTEND(SDNode *N);
195193323Sed    SDValue visitFNEG(SDNode *N);
196193323Sed    SDValue visitFABS(SDNode *N);
197193323Sed    SDValue visitBRCOND(SDNode *N);
198193323Sed    SDValue visitBR_CC(SDNode *N);
199193323Sed    SDValue visitLOAD(SDNode *N);
200193323Sed    SDValue visitSTORE(SDNode *N);
201193323Sed    SDValue visitINSERT_VECTOR_ELT(SDNode *N);
202193323Sed    SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
203193323Sed    SDValue visitBUILD_VECTOR(SDNode *N);
204193323Sed    SDValue visitCONCAT_VECTORS(SDNode *N);
205193323Sed    SDValue visitVECTOR_SHUFFLE(SDNode *N);
206193323Sed
207193323Sed    SDValue XformToShuffleWithZero(SDNode *N);
208193323Sed    SDValue ReassociateOps(unsigned Opc, DebugLoc DL, SDValue LHS, SDValue RHS);
209193323Sed
210193323Sed    SDValue visitShiftByConstant(SDNode *N, unsigned Amt);
211193323Sed
212193323Sed    bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
213193323Sed    SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
214193323Sed    SDValue SimplifySelect(DebugLoc DL, SDValue N0, SDValue N1, SDValue N2);
215193323Sed    SDValue SimplifySelectCC(DebugLoc DL, SDValue N0, SDValue N1, SDValue N2,
216193323Sed                             SDValue N3, ISD::CondCode CC,
217193323Sed                             bool NotExtCompare = false);
218198090Srdivacky    SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
219193323Sed                          DebugLoc DL, bool foldBooleans = true);
220193323Sed    SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
221193323Sed                                         unsigned HiOp);
222198090Srdivacky    SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
223198090Srdivacky    SDValue ConstantFoldBIT_CONVERTofBUILD_VECTOR(SDNode *, EVT);
224193323Sed    SDValue BuildSDIV(SDNode *N);
225193323Sed    SDValue BuildUDIV(SDNode *N);
226193323Sed    SDNode *MatchRotate(SDValue LHS, SDValue RHS, DebugLoc DL);
227193323Sed    SDValue ReduceLoadWidth(SDNode *N);
228193323Sed    SDValue ReduceLoadOpStoreWidth(SDNode *N);
229193323Sed
230193323Sed    SDValue GetDemandedBits(SDValue V, const APInt &Mask);
231193323Sed
232193323Sed    /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
233193323Sed    /// looking for aliasing nodes and adding them to the Aliases vector.
234193323Sed    void GatherAllAliases(SDNode *N, SDValue OriginalChain,
235193323Sed                          SmallVector<SDValue, 8> &Aliases);
236193323Sed
237193323Sed    /// isAlias - Return true if there is any possibility that the two addresses
238193323Sed    /// overlap.
239193323Sed    bool isAlias(SDValue Ptr1, int64_t Size1,
240193323Sed                 const Value *SrcValue1, int SrcValueOffset1,
241198090Srdivacky                 unsigned SrcValueAlign1,
242193323Sed                 SDValue Ptr2, int64_t Size2,
243198090Srdivacky                 const Value *SrcValue2, int SrcValueOffset2,
244198090Srdivacky                 unsigned SrcValueAlign2) const;
245193323Sed
246193323Sed    /// FindAliasInfo - Extracts the relevant alias information from the memory
247193323Sed    /// node.  Returns true if the operand was a load.
248193323Sed    bool FindAliasInfo(SDNode *N,
249193323Sed                       SDValue &Ptr, int64_t &Size,
250198090Srdivacky                       const Value *&SrcValue, int &SrcValueOffset,
251198090Srdivacky                       unsigned &SrcValueAlignment) const;
252193323Sed
253193323Sed    /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes,
254193323Sed    /// looking for a better chain (aliasing node.)
255193323Sed    SDValue FindBetterChain(SDNode *N, SDValue Chain);
256193323Sed
257193323Sed    /// getShiftAmountTy - Returns a type large enough to hold any valid
258193323Sed    /// shift amount - before type legalization these can be huge.
259198090Srdivacky    EVT getShiftAmountTy() {
260193323Sed      return LegalTypes ?  TLI.getShiftAmountTy() : TLI.getPointerTy();
261193323Sed    }
262193323Sed
263193323Sedpublic:
264193323Sed    DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
265193323Sed      : DAG(D),
266193323Sed        TLI(D.getTargetLoweringInfo()),
267193323Sed        Level(Unrestricted),
268193323Sed        OptLevel(OL),
269193323Sed        LegalOperations(false),
270193323Sed        LegalTypes(false),
271193323Sed        AA(A) {}
272193323Sed
273193323Sed    /// Run - runs the dag combiner on all nodes in the work list
274193323Sed    void Run(CombineLevel AtLevel);
275193323Sed  };
276193323Sed}
277193323Sed
278193323Sed
279193323Sednamespace {
280193323Sed/// WorkListRemover - This class is a DAGUpdateListener that removes any deleted
281193323Sed/// nodes from the worklist.
282198892Srdivackyclass WorkListRemover : public SelectionDAG::DAGUpdateListener {
283193323Sed  DAGCombiner &DC;
284193323Sedpublic:
285193323Sed  explicit WorkListRemover(DAGCombiner &dc) : DC(dc) {}
286193323Sed
287193323Sed  virtual void NodeDeleted(SDNode *N, SDNode *E) {
288193323Sed    DC.removeFromWorkList(N);
289193323Sed  }
290193323Sed
291193323Sed  virtual void NodeUpdated(SDNode *N) {
292193323Sed    // Ignore updates.
293193323Sed  }
294193323Sed};
295193323Sed}
296193323Sed
297193323Sed//===----------------------------------------------------------------------===//
298193323Sed//  TargetLowering::DAGCombinerInfo implementation
299193323Sed//===----------------------------------------------------------------------===//
300193323Sed
301193323Sedvoid TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
302193323Sed  ((DAGCombiner*)DC)->AddToWorkList(N);
303193323Sed}
304193323Sed
305193323SedSDValue TargetLowering::DAGCombinerInfo::
306193323SedCombineTo(SDNode *N, const std::vector<SDValue> &To, bool AddTo) {
307193323Sed  return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
308193323Sed}
309193323Sed
310193323SedSDValue TargetLowering::DAGCombinerInfo::
311193323SedCombineTo(SDNode *N, SDValue Res, bool AddTo) {
312193323Sed  return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
313193323Sed}
314193323Sed
315193323Sed
316193323SedSDValue TargetLowering::DAGCombinerInfo::
317193323SedCombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
318193323Sed  return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
319193323Sed}
320193323Sed
321193323Sedvoid TargetLowering::DAGCombinerInfo::
322193323SedCommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
323193323Sed  return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
324193323Sed}
325193323Sed
326193323Sed//===----------------------------------------------------------------------===//
327193323Sed// Helper Functions
328193323Sed//===----------------------------------------------------------------------===//
329193323Sed
330193323Sed/// isNegatibleForFree - Return 1 if we can compute the negated form of the
331193323Sed/// specified expression for the same cost as the expression itself, or 2 if we
332193323Sed/// can compute the negated form more cheaply than the expression itself.
333193323Sedstatic char isNegatibleForFree(SDValue Op, bool LegalOperations,
334193323Sed                               unsigned Depth = 0) {
335193323Sed  // No compile time optimizations on this type.
336193323Sed  if (Op.getValueType() == MVT::ppcf128)
337193323Sed    return 0;
338193323Sed
339193323Sed  // fneg is removable even if it has multiple uses.
340193323Sed  if (Op.getOpcode() == ISD::FNEG) return 2;
341193323Sed
342193323Sed  // Don't allow anything with multiple uses.
343193323Sed  if (!Op.hasOneUse()) return 0;
344193323Sed
345193323Sed  // Don't recurse exponentially.
346193323Sed  if (Depth > 6) return 0;
347193323Sed
348193323Sed  switch (Op.getOpcode()) {
349193323Sed  default: return false;
350193323Sed  case ISD::ConstantFP:
351193323Sed    // Don't invert constant FP values after legalize.  The negated constant
352193323Sed    // isn't necessarily legal.
353193323Sed    return LegalOperations ? 0 : 1;
354193323Sed  case ISD::FADD:
355193323Sed    // FIXME: determine better conditions for this xform.
356193323Sed    if (!UnsafeFPMath) return 0;
357193323Sed
358193323Sed    // fold (fsub (fadd A, B)) -> (fsub (fneg A), B)
359193323Sed    if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, Depth+1))
360193323Sed      return V;
361193323Sed    // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
362193323Sed    return isNegatibleForFree(Op.getOperand(1), LegalOperations, Depth+1);
363193323Sed  case ISD::FSUB:
364193323Sed    // We can't turn -(A-B) into B-A when we honor signed zeros.
365193323Sed    if (!UnsafeFPMath) return 0;
366193323Sed
367193323Sed    // fold (fneg (fsub A, B)) -> (fsub B, A)
368193323Sed    return 1;
369193323Sed
370193323Sed  case ISD::FMUL:
371193323Sed  case ISD::FDIV:
372193323Sed    if (HonorSignDependentRoundingFPMath()) return 0;
373193323Sed
374193323Sed    // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
375193323Sed    if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, Depth+1))
376193323Sed      return V;
377193323Sed
378193323Sed    return isNegatibleForFree(Op.getOperand(1), LegalOperations, Depth+1);
379193323Sed
380193323Sed  case ISD::FP_EXTEND:
381193323Sed  case ISD::FP_ROUND:
382193323Sed  case ISD::FSIN:
383193323Sed    return isNegatibleForFree(Op.getOperand(0), LegalOperations, Depth+1);
384193323Sed  }
385193323Sed}
386193323Sed
387193323Sed/// GetNegatedExpression - If isNegatibleForFree returns true, this function
388193323Sed/// returns the newly negated expression.
389193323Sedstatic SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
390193323Sed                                    bool LegalOperations, unsigned Depth = 0) {
391193323Sed  // fneg is removable even if it has multiple uses.
392193323Sed  if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
393193323Sed
394193323Sed  // Don't allow anything with multiple uses.
395193323Sed  assert(Op.hasOneUse() && "Unknown reuse!");
396193323Sed
397193323Sed  assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
398193323Sed  switch (Op.getOpcode()) {
399198090Srdivacky  default: llvm_unreachable("Unknown code");
400193323Sed  case ISD::ConstantFP: {
401193323Sed    APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
402193323Sed    V.changeSign();
403193323Sed    return DAG.getConstantFP(V, Op.getValueType());
404193323Sed  }
405193323Sed  case ISD::FADD:
406193323Sed    // FIXME: determine better conditions for this xform.
407193323Sed    assert(UnsafeFPMath);
408193323Sed
409193323Sed    // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
410193323Sed    if (isNegatibleForFree(Op.getOperand(0), LegalOperations, Depth+1))
411193323Sed      return DAG.getNode(ISD::FSUB, Op.getDebugLoc(), Op.getValueType(),
412193323Sed                         GetNegatedExpression(Op.getOperand(0), DAG,
413193323Sed                                              LegalOperations, Depth+1),
414193323Sed                         Op.getOperand(1));
415193323Sed    // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
416193323Sed    return DAG.getNode(ISD::FSUB, Op.getDebugLoc(), Op.getValueType(),
417193323Sed                       GetNegatedExpression(Op.getOperand(1), DAG,
418193323Sed                                            LegalOperations, Depth+1),
419193323Sed                       Op.getOperand(0));
420193323Sed  case ISD::FSUB:
421193323Sed    // We can't turn -(A-B) into B-A when we honor signed zeros.
422193323Sed    assert(UnsafeFPMath);
423193323Sed
424193323Sed    // fold (fneg (fsub 0, B)) -> B
425193323Sed    if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
426193323Sed      if (N0CFP->getValueAPF().isZero())
427193323Sed        return Op.getOperand(1);
428193323Sed
429193323Sed    // fold (fneg (fsub A, B)) -> (fsub B, A)
430193323Sed    return DAG.getNode(ISD::FSUB, Op.getDebugLoc(), Op.getValueType(),
431193323Sed                       Op.getOperand(1), Op.getOperand(0));
432193323Sed
433193323Sed  case ISD::FMUL:
434193323Sed  case ISD::FDIV:
435193323Sed    assert(!HonorSignDependentRoundingFPMath());
436193323Sed
437193323Sed    // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
438193323Sed    if (isNegatibleForFree(Op.getOperand(0), LegalOperations, Depth+1))
439193323Sed      return DAG.getNode(Op.getOpcode(), Op.getDebugLoc(), Op.getValueType(),
440193323Sed                         GetNegatedExpression(Op.getOperand(0), DAG,
441193323Sed                                              LegalOperations, Depth+1),
442193323Sed                         Op.getOperand(1));
443193323Sed
444193323Sed    // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
445193323Sed    return DAG.getNode(Op.getOpcode(), Op.getDebugLoc(), Op.getValueType(),
446193323Sed                       Op.getOperand(0),
447193323Sed                       GetNegatedExpression(Op.getOperand(1), DAG,
448193323Sed                                            LegalOperations, Depth+1));
449193323Sed
450193323Sed  case ISD::FP_EXTEND:
451193323Sed  case ISD::FSIN:
452193323Sed    return DAG.getNode(Op.getOpcode(), Op.getDebugLoc(), Op.getValueType(),
453193323Sed                       GetNegatedExpression(Op.getOperand(0), DAG,
454193323Sed                                            LegalOperations, Depth+1));
455193323Sed  case ISD::FP_ROUND:
456193323Sed      return DAG.getNode(ISD::FP_ROUND, Op.getDebugLoc(), Op.getValueType(),
457193323Sed                         GetNegatedExpression(Op.getOperand(0), DAG,
458193323Sed                                              LegalOperations, Depth+1),
459193323Sed                         Op.getOperand(1));
460193323Sed  }
461193323Sed}
462193323Sed
463193323Sed
464193323Sed// isSetCCEquivalent - Return true if this node is a setcc, or is a select_cc
465193323Sed// that selects between the values 1 and 0, making it equivalent to a setcc.
466193323Sed// Also, set the incoming LHS, RHS, and CC references to the appropriate
467193323Sed// nodes based on the type of node we are checking.  This simplifies life a
468193323Sed// bit for the callers.
469193323Sedstatic bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
470193323Sed                              SDValue &CC) {
471193323Sed  if (N.getOpcode() == ISD::SETCC) {
472193323Sed    LHS = N.getOperand(0);
473193323Sed    RHS = N.getOperand(1);
474193323Sed    CC  = N.getOperand(2);
475193323Sed    return true;
476193323Sed  }
477193323Sed  if (N.getOpcode() == ISD::SELECT_CC &&
478193323Sed      N.getOperand(2).getOpcode() == ISD::Constant &&
479193323Sed      N.getOperand(3).getOpcode() == ISD::Constant &&
480193323Sed      cast<ConstantSDNode>(N.getOperand(2))->getAPIntValue() == 1 &&
481193323Sed      cast<ConstantSDNode>(N.getOperand(3))->isNullValue()) {
482193323Sed    LHS = N.getOperand(0);
483193323Sed    RHS = N.getOperand(1);
484193323Sed    CC  = N.getOperand(4);
485193323Sed    return true;
486193323Sed  }
487193323Sed  return false;
488193323Sed}
489193323Sed
490193323Sed// isOneUseSetCC - Return true if this is a SetCC-equivalent operation with only
491193323Sed// one use.  If this is true, it allows the users to invert the operation for
492193323Sed// free when it is profitable to do so.
493193323Sedstatic bool isOneUseSetCC(SDValue N) {
494193323Sed  SDValue N0, N1, N2;
495193323Sed  if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
496193323Sed    return true;
497193323Sed  return false;
498193323Sed}
499193323Sed
500193323SedSDValue DAGCombiner::ReassociateOps(unsigned Opc, DebugLoc DL,
501193323Sed                                    SDValue N0, SDValue N1) {
502198090Srdivacky  EVT VT = N0.getValueType();
503193323Sed  if (N0.getOpcode() == Opc && isa<ConstantSDNode>(N0.getOperand(1))) {
504193323Sed    if (isa<ConstantSDNode>(N1)) {
505193323Sed      // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
506193323Sed      SDValue OpNode =
507193323Sed        DAG.FoldConstantArithmetic(Opc, VT,
508193323Sed                                   cast<ConstantSDNode>(N0.getOperand(1)),
509193323Sed                                   cast<ConstantSDNode>(N1));
510193323Sed      return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
511193323Sed    } else if (N0.hasOneUse()) {
512193323Sed      // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one use
513193323Sed      SDValue OpNode = DAG.getNode(Opc, N0.getDebugLoc(), VT,
514193323Sed                                   N0.getOperand(0), N1);
515193323Sed      AddToWorkList(OpNode.getNode());
516193323Sed      return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
517193323Sed    }
518193323Sed  }
519193323Sed
520193323Sed  if (N1.getOpcode() == Opc && isa<ConstantSDNode>(N1.getOperand(1))) {
521193323Sed    if (isa<ConstantSDNode>(N0)) {
522193323Sed      // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
523193323Sed      SDValue OpNode =
524193323Sed        DAG.FoldConstantArithmetic(Opc, VT,
525193323Sed                                   cast<ConstantSDNode>(N1.getOperand(1)),
526193323Sed                                   cast<ConstantSDNode>(N0));
527193323Sed      return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
528193323Sed    } else if (N1.hasOneUse()) {
529193323Sed      // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one use
530193323Sed      SDValue OpNode = DAG.getNode(Opc, N0.getDebugLoc(), VT,
531193323Sed                                   N1.getOperand(0), N0);
532193323Sed      AddToWorkList(OpNode.getNode());
533193323Sed      return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
534193323Sed    }
535193323Sed  }
536193323Sed
537193323Sed  return SDValue();
538193323Sed}
539193323Sed
540193323SedSDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
541193323Sed                               bool AddTo) {
542193323Sed  assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
543193323Sed  ++NodesCombined;
544202375Srdivacky  DEBUG(dbgs() << "\nReplacing.1 ";
545198090Srdivacky        N->dump(&DAG);
546202375Srdivacky        dbgs() << "\nWith: ";
547198090Srdivacky        To[0].getNode()->dump(&DAG);
548202375Srdivacky        dbgs() << " and " << NumTo-1 << " other values\n";
549198090Srdivacky        for (unsigned i = 0, e = NumTo; i != e; ++i)
550200581Srdivacky          assert((!To[i].getNode() ||
551200581Srdivacky                  N->getValueType(i) == To[i].getValueType()) &&
552193323Sed                 "Cannot combine value to value of different type!"));
553193323Sed  WorkListRemover DeadNodes(*this);
554193323Sed  DAG.ReplaceAllUsesWith(N, To, &DeadNodes);
555193323Sed
556193323Sed  if (AddTo) {
557193323Sed    // Push the new nodes and any users onto the worklist
558193323Sed    for (unsigned i = 0, e = NumTo; i != e; ++i) {
559193323Sed      if (To[i].getNode()) {
560193323Sed        AddToWorkList(To[i].getNode());
561193323Sed        AddUsersToWorkList(To[i].getNode());
562193323Sed      }
563193323Sed    }
564193323Sed  }
565193323Sed
566193323Sed  // Finally, if the node is now dead, remove it from the graph.  The node
567193323Sed  // may not be dead if the replacement process recursively simplified to
568193323Sed  // something else needing this node.
569193323Sed  if (N->use_empty()) {
570193323Sed    // Nodes can be reintroduced into the worklist.  Make sure we do not
571193323Sed    // process a node that has been replaced.
572193323Sed    removeFromWorkList(N);
573193323Sed
574193323Sed    // Finally, since the node is now dead, remove it from the graph.
575193323Sed    DAG.DeleteNode(N);
576193323Sed  }
577193323Sed  return SDValue(N, 0);
578193323Sed}
579193323Sed
580193323Sedvoid
581193323SedDAGCombiner::CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &
582193323Sed                                                                          TLO) {
583193323Sed  // Replace all uses.  If any nodes become isomorphic to other nodes and
584193323Sed  // are deleted, make sure to remove them from our worklist.
585193323Sed  WorkListRemover DeadNodes(*this);
586193323Sed  DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New, &DeadNodes);
587193323Sed
588193323Sed  // Push the new node and any (possibly new) users onto the worklist.
589193323Sed  AddToWorkList(TLO.New.getNode());
590193323Sed  AddUsersToWorkList(TLO.New.getNode());
591193323Sed
592193323Sed  // Finally, if the node is now dead, remove it from the graph.  The node
593193323Sed  // may not be dead if the replacement process recursively simplified to
594193323Sed  // something else needing this node.
595193323Sed  if (TLO.Old.getNode()->use_empty()) {
596193323Sed    removeFromWorkList(TLO.Old.getNode());
597193323Sed
598193323Sed    // If the operands of this node are only used by the node, they will now
599193323Sed    // be dead.  Make sure to visit them first to delete dead nodes early.
600193323Sed    for (unsigned i = 0, e = TLO.Old.getNode()->getNumOperands(); i != e; ++i)
601193323Sed      if (TLO.Old.getNode()->getOperand(i).getNode()->hasOneUse())
602193323Sed        AddToWorkList(TLO.Old.getNode()->getOperand(i).getNode());
603193323Sed
604193323Sed    DAG.DeleteNode(TLO.Old.getNode());
605193323Sed  }
606193323Sed}
607193323Sed
608193323Sed/// SimplifyDemandedBits - Check the specified integer node value to see if
609193323Sed/// it can be simplified or if things it uses can be simplified by bit
610193323Sed/// propagation.  If so, return true.
611193323Sedbool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
612193323Sed  TargetLowering::TargetLoweringOpt TLO(DAG);
613193323Sed  APInt KnownZero, KnownOne;
614193323Sed  if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
615193323Sed    return false;
616193323Sed
617193323Sed  // Revisit the node.
618193323Sed  AddToWorkList(Op.getNode());
619193323Sed
620193323Sed  // Replace the old value with the new one.
621193323Sed  ++NodesCombined;
622202375Srdivacky  DEBUG(dbgs() << "\nReplacing.2 ";
623198090Srdivacky        TLO.Old.getNode()->dump(&DAG);
624202375Srdivacky        dbgs() << "\nWith: ";
625198090Srdivacky        TLO.New.getNode()->dump(&DAG);
626202375Srdivacky        dbgs() << '\n');
627193323Sed
628193323Sed  CommitTargetLoweringOpt(TLO);
629193323Sed  return true;
630193323Sed}
631193323Sed
632193323Sed//===----------------------------------------------------------------------===//
633193323Sed//  Main DAG Combiner implementation
634193323Sed//===----------------------------------------------------------------------===//
635193323Sed
636193323Sedvoid DAGCombiner::Run(CombineLevel AtLevel) {
637193323Sed  // set the instance variables, so that the various visit routines may use it.
638193323Sed  Level = AtLevel;
639193323Sed  LegalOperations = Level >= NoIllegalOperations;
640193323Sed  LegalTypes = Level >= NoIllegalTypes;
641193323Sed
642193323Sed  // Add all the dag nodes to the worklist.
643193323Sed  WorkList.reserve(DAG.allnodes_size());
644193323Sed  for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
645193323Sed       E = DAG.allnodes_end(); I != E; ++I)
646193323Sed    WorkList.push_back(I);
647193323Sed
648193323Sed  // Create a dummy node (which is not added to allnodes), that adds a reference
649193323Sed  // to the root node, preventing it from being deleted, and tracking any
650193323Sed  // changes of the root.
651193323Sed  HandleSDNode Dummy(DAG.getRoot());
652193323Sed
653193323Sed  // The root of the dag may dangle to deleted nodes until the dag combiner is
654193323Sed  // done.  Set it to null to avoid confusion.
655193323Sed  DAG.setRoot(SDValue());
656193323Sed
657193323Sed  // while the worklist isn't empty, inspect the node on the end of it and
658193323Sed  // try and combine it.
659193323Sed  while (!WorkList.empty()) {
660193323Sed    SDNode *N = WorkList.back();
661193323Sed    WorkList.pop_back();
662193323Sed
663193323Sed    // If N has no uses, it is dead.  Make sure to revisit all N's operands once
664193323Sed    // N is deleted from the DAG, since they too may now be dead or may have a
665193323Sed    // reduced number of uses, allowing other xforms.
666193323Sed    if (N->use_empty() && N != &Dummy) {
667193323Sed      for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
668193323Sed        AddToWorkList(N->getOperand(i).getNode());
669193323Sed
670193323Sed      DAG.DeleteNode(N);
671193323Sed      continue;
672193323Sed    }
673193323Sed
674193323Sed    SDValue RV = combine(N);
675193323Sed
676193323Sed    if (RV.getNode() == 0)
677193323Sed      continue;
678193323Sed
679193323Sed    ++NodesCombined;
680193323Sed
681193323Sed    // If we get back the same node we passed in, rather than a new node or
682193323Sed    // zero, we know that the node must have defined multiple values and
683193323Sed    // CombineTo was used.  Since CombineTo takes care of the worklist
684193323Sed    // mechanics for us, we have no work to do in this case.
685193323Sed    if (RV.getNode() == N)
686193323Sed      continue;
687193323Sed
688193323Sed    assert(N->getOpcode() != ISD::DELETED_NODE &&
689193323Sed           RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
690193323Sed           "Node was deleted but visit returned new node!");
691193323Sed
692202375Srdivacky    DEBUG(dbgs() << "\nReplacing.3 ";
693198090Srdivacky          N->dump(&DAG);
694202375Srdivacky          dbgs() << "\nWith: ";
695198090Srdivacky          RV.getNode()->dump(&DAG);
696202375Srdivacky          dbgs() << '\n');
697193323Sed    WorkListRemover DeadNodes(*this);
698193323Sed    if (N->getNumValues() == RV.getNode()->getNumValues())
699193323Sed      DAG.ReplaceAllUsesWith(N, RV.getNode(), &DeadNodes);
700193323Sed    else {
701193323Sed      assert(N->getValueType(0) == RV.getValueType() &&
702193323Sed             N->getNumValues() == 1 && "Type mismatch");
703193323Sed      SDValue OpV = RV;
704193323Sed      DAG.ReplaceAllUsesWith(N, &OpV, &DeadNodes);
705193323Sed    }
706193323Sed
707193323Sed    // Push the new node and any users onto the worklist
708193323Sed    AddToWorkList(RV.getNode());
709193323Sed    AddUsersToWorkList(RV.getNode());
710193323Sed
711193323Sed    // Add any uses of the old node to the worklist in case this node is the
712193323Sed    // last one that uses them.  They may become dead after this node is
713193323Sed    // deleted.
714193323Sed    for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
715193323Sed      AddToWorkList(N->getOperand(i).getNode());
716193323Sed
717193323Sed    // Finally, if the node is now dead, remove it from the graph.  The node
718193323Sed    // may not be dead if the replacement process recursively simplified to
719193323Sed    // something else needing this node.
720193323Sed    if (N->use_empty()) {
721193323Sed      // Nodes can be reintroduced into the worklist.  Make sure we do not
722193323Sed      // process a node that has been replaced.
723193323Sed      removeFromWorkList(N);
724193323Sed
725193323Sed      // Finally, since the node is now dead, remove it from the graph.
726193323Sed      DAG.DeleteNode(N);
727193323Sed    }
728193323Sed  }
729193323Sed
730193323Sed  // If the root changed (e.g. it was a dead load, update the root).
731193323Sed  DAG.setRoot(Dummy.getValue());
732193323Sed}
733193323Sed
734193323SedSDValue DAGCombiner::visit(SDNode *N) {
735193323Sed  switch(N->getOpcode()) {
736193323Sed  default: break;
737193323Sed  case ISD::TokenFactor:        return visitTokenFactor(N);
738193323Sed  case ISD::MERGE_VALUES:       return visitMERGE_VALUES(N);
739193323Sed  case ISD::ADD:                return visitADD(N);
740193323Sed  case ISD::SUB:                return visitSUB(N);
741193323Sed  case ISD::ADDC:               return visitADDC(N);
742193323Sed  case ISD::ADDE:               return visitADDE(N);
743193323Sed  case ISD::MUL:                return visitMUL(N);
744193323Sed  case ISD::SDIV:               return visitSDIV(N);
745193323Sed  case ISD::UDIV:               return visitUDIV(N);
746193323Sed  case ISD::SREM:               return visitSREM(N);
747193323Sed  case ISD::UREM:               return visitUREM(N);
748193323Sed  case ISD::MULHU:              return visitMULHU(N);
749193323Sed  case ISD::MULHS:              return visitMULHS(N);
750193323Sed  case ISD::SMUL_LOHI:          return visitSMUL_LOHI(N);
751193323Sed  case ISD::UMUL_LOHI:          return visitUMUL_LOHI(N);
752193323Sed  case ISD::SDIVREM:            return visitSDIVREM(N);
753193323Sed  case ISD::UDIVREM:            return visitUDIVREM(N);
754193323Sed  case ISD::AND:                return visitAND(N);
755193323Sed  case ISD::OR:                 return visitOR(N);
756193323Sed  case ISD::XOR:                return visitXOR(N);
757193323Sed  case ISD::SHL:                return visitSHL(N);
758193323Sed  case ISD::SRA:                return visitSRA(N);
759193323Sed  case ISD::SRL:                return visitSRL(N);
760193323Sed  case ISD::CTLZ:               return visitCTLZ(N);
761193323Sed  case ISD::CTTZ:               return visitCTTZ(N);
762193323Sed  case ISD::CTPOP:              return visitCTPOP(N);
763193323Sed  case ISD::SELECT:             return visitSELECT(N);
764193323Sed  case ISD::SELECT_CC:          return visitSELECT_CC(N);
765193323Sed  case ISD::SETCC:              return visitSETCC(N);
766193323Sed  case ISD::SIGN_EXTEND:        return visitSIGN_EXTEND(N);
767193323Sed  case ISD::ZERO_EXTEND:        return visitZERO_EXTEND(N);
768193323Sed  case ISD::ANY_EXTEND:         return visitANY_EXTEND(N);
769193323Sed  case ISD::SIGN_EXTEND_INREG:  return visitSIGN_EXTEND_INREG(N);
770193323Sed  case ISD::TRUNCATE:           return visitTRUNCATE(N);
771193323Sed  case ISD::BIT_CONVERT:        return visitBIT_CONVERT(N);
772193323Sed  case ISD::BUILD_PAIR:         return visitBUILD_PAIR(N);
773193323Sed  case ISD::FADD:               return visitFADD(N);
774193323Sed  case ISD::FSUB:               return visitFSUB(N);
775193323Sed  case ISD::FMUL:               return visitFMUL(N);
776193323Sed  case ISD::FDIV:               return visitFDIV(N);
777193323Sed  case ISD::FREM:               return visitFREM(N);
778193323Sed  case ISD::FCOPYSIGN:          return visitFCOPYSIGN(N);
779193323Sed  case ISD::SINT_TO_FP:         return visitSINT_TO_FP(N);
780193323Sed  case ISD::UINT_TO_FP:         return visitUINT_TO_FP(N);
781193323Sed  case ISD::FP_TO_SINT:         return visitFP_TO_SINT(N);
782193323Sed  case ISD::FP_TO_UINT:         return visitFP_TO_UINT(N);
783193323Sed  case ISD::FP_ROUND:           return visitFP_ROUND(N);
784193323Sed  case ISD::FP_ROUND_INREG:     return visitFP_ROUND_INREG(N);
785193323Sed  case ISD::FP_EXTEND:          return visitFP_EXTEND(N);
786193323Sed  case ISD::FNEG:               return visitFNEG(N);
787193323Sed  case ISD::FABS:               return visitFABS(N);
788193323Sed  case ISD::BRCOND:             return visitBRCOND(N);
789193323Sed  case ISD::BR_CC:              return visitBR_CC(N);
790193323Sed  case ISD::LOAD:               return visitLOAD(N);
791193323Sed  case ISD::STORE:              return visitSTORE(N);
792193323Sed  case ISD::INSERT_VECTOR_ELT:  return visitINSERT_VECTOR_ELT(N);
793193323Sed  case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
794193323Sed  case ISD::BUILD_VECTOR:       return visitBUILD_VECTOR(N);
795193323Sed  case ISD::CONCAT_VECTORS:     return visitCONCAT_VECTORS(N);
796193323Sed  case ISD::VECTOR_SHUFFLE:     return visitVECTOR_SHUFFLE(N);
797193323Sed  }
798193323Sed  return SDValue();
799193323Sed}
800193323Sed
801193323SedSDValue DAGCombiner::combine(SDNode *N) {
802193323Sed  SDValue RV = visit(N);
803193323Sed
804193323Sed  // If nothing happened, try a target-specific DAG combine.
805193323Sed  if (RV.getNode() == 0) {
806193323Sed    assert(N->getOpcode() != ISD::DELETED_NODE &&
807193323Sed           "Node was deleted but visit returned NULL!");
808193323Sed
809193323Sed    if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
810193323Sed        TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
811193323Sed
812193323Sed      // Expose the DAG combiner to the target combiner impls.
813193323Sed      TargetLowering::DAGCombinerInfo
814198090Srdivacky        DagCombineInfo(DAG, !LegalTypes, !LegalOperations, false, this);
815193323Sed
816193323Sed      RV = TLI.PerformDAGCombine(N, DagCombineInfo);
817193323Sed    }
818193323Sed  }
819193323Sed
820193323Sed  // If N is a commutative binary node, try commuting it to enable more
821193323Sed  // sdisel CSE.
822193323Sed  if (RV.getNode() == 0 &&
823193323Sed      SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
824193323Sed      N->getNumValues() == 1) {
825193323Sed    SDValue N0 = N->getOperand(0);
826193323Sed    SDValue N1 = N->getOperand(1);
827193323Sed
828193323Sed    // Constant operands are canonicalized to RHS.
829193323Sed    if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
830193323Sed      SDValue Ops[] = { N1, N0 };
831193323Sed      SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(),
832193323Sed                                            Ops, 2);
833193323Sed      if (CSENode)
834193323Sed        return SDValue(CSENode, 0);
835193323Sed    }
836193323Sed  }
837193323Sed
838193323Sed  return RV;
839193323Sed}
840193323Sed
841193323Sed/// getInputChainForNode - Given a node, return its input chain if it has one,
842193323Sed/// otherwise return a null sd operand.
843193323Sedstatic SDValue getInputChainForNode(SDNode *N) {
844193323Sed  if (unsigned NumOps = N->getNumOperands()) {
845193323Sed    if (N->getOperand(0).getValueType() == MVT::Other)
846193323Sed      return N->getOperand(0);
847193323Sed    else if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
848193323Sed      return N->getOperand(NumOps-1);
849193323Sed    for (unsigned i = 1; i < NumOps-1; ++i)
850193323Sed      if (N->getOperand(i).getValueType() == MVT::Other)
851193323Sed        return N->getOperand(i);
852193323Sed  }
853193323Sed  return SDValue();
854193323Sed}
855193323Sed
856193323SedSDValue DAGCombiner::visitTokenFactor(SDNode *N) {
857193323Sed  // If N has two operands, where one has an input chain equal to the other,
858193323Sed  // the 'other' chain is redundant.
859193323Sed  if (N->getNumOperands() == 2) {
860193323Sed    if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
861193323Sed      return N->getOperand(0);
862193323Sed    if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
863193323Sed      return N->getOperand(1);
864193323Sed  }
865193323Sed
866193323Sed  SmallVector<SDNode *, 8> TFs;     // List of token factors to visit.
867193323Sed  SmallVector<SDValue, 8> Ops;    // Ops for replacing token factor.
868193323Sed  SmallPtrSet<SDNode*, 16> SeenOps;
869193323Sed  bool Changed = false;             // If we should replace this token factor.
870193323Sed
871193323Sed  // Start out with this token factor.
872193323Sed  TFs.push_back(N);
873193323Sed
874193323Sed  // Iterate through token factors.  The TFs grows when new token factors are
875193323Sed  // encountered.
876193323Sed  for (unsigned i = 0; i < TFs.size(); ++i) {
877193323Sed    SDNode *TF = TFs[i];
878193323Sed
879193323Sed    // Check each of the operands.
880193323Sed    for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
881193323Sed      SDValue Op = TF->getOperand(i);
882193323Sed
883193323Sed      switch (Op.getOpcode()) {
884193323Sed      case ISD::EntryToken:
885193323Sed        // Entry tokens don't need to be added to the list. They are
886193323Sed        // rededundant.
887193323Sed        Changed = true;
888193323Sed        break;
889193323Sed
890193323Sed      case ISD::TokenFactor:
891198090Srdivacky        if (Op.hasOneUse() &&
892193323Sed            std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
893193323Sed          // Queue up for processing.
894193323Sed          TFs.push_back(Op.getNode());
895193323Sed          // Clean up in case the token factor is removed.
896193323Sed          AddToWorkList(Op.getNode());
897193323Sed          Changed = true;
898193323Sed          break;
899193323Sed        }
900193323Sed        // Fall thru
901193323Sed
902193323Sed      default:
903193323Sed        // Only add if it isn't already in the list.
904193323Sed        if (SeenOps.insert(Op.getNode()))
905193323Sed          Ops.push_back(Op);
906193323Sed        else
907193323Sed          Changed = true;
908193323Sed        break;
909193323Sed      }
910193323Sed    }
911193323Sed  }
912198090Srdivacky
913193323Sed  SDValue Result;
914193323Sed
915193323Sed  // If we've change things around then replace token factor.
916193323Sed  if (Changed) {
917193323Sed    if (Ops.empty()) {
918193323Sed      // The entry token is the only possible outcome.
919193323Sed      Result = DAG.getEntryNode();
920193323Sed    } else {
921193323Sed      // New and improved token factor.
922193323Sed      Result = DAG.getNode(ISD::TokenFactor, N->getDebugLoc(),
923193323Sed                           MVT::Other, &Ops[0], Ops.size());
924193323Sed    }
925193323Sed
926193323Sed    // Don't add users to work list.
927193323Sed    return CombineTo(N, Result, false);
928193323Sed  }
929193323Sed
930193323Sed  return Result;
931193323Sed}
932193323Sed
933193323Sed/// MERGE_VALUES can always be eliminated.
934193323SedSDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
935193323Sed  WorkListRemover DeadNodes(*this);
936198090Srdivacky  // Replacing results may cause a different MERGE_VALUES to suddenly
937198090Srdivacky  // be CSE'd with N, and carry its uses with it. Iterate until no
938198090Srdivacky  // uses remain, to ensure that the node can be safely deleted.
939198090Srdivacky  do {
940198090Srdivacky    for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
941198090Srdivacky      DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i),
942198090Srdivacky                                    &DeadNodes);
943198090Srdivacky  } while (!N->use_empty());
944193323Sed  removeFromWorkList(N);
945193323Sed  DAG.DeleteNode(N);
946193323Sed  return SDValue(N, 0);   // Return N so it doesn't get rechecked!
947193323Sed}
948193323Sed
949193323Sedstatic
950193323SedSDValue combineShlAddConstant(DebugLoc DL, SDValue N0, SDValue N1,
951193323Sed                              SelectionDAG &DAG) {
952198090Srdivacky  EVT VT = N0.getValueType();
953193323Sed  SDValue N00 = N0.getOperand(0);
954193323Sed  SDValue N01 = N0.getOperand(1);
955193323Sed  ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N01);
956193323Sed
957193323Sed  if (N01C && N00.getOpcode() == ISD::ADD && N00.getNode()->hasOneUse() &&
958193323Sed      isa<ConstantSDNode>(N00.getOperand(1))) {
959193323Sed    // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
960193323Sed    N0 = DAG.getNode(ISD::ADD, N0.getDebugLoc(), VT,
961193323Sed                     DAG.getNode(ISD::SHL, N00.getDebugLoc(), VT,
962193323Sed                                 N00.getOperand(0), N01),
963193323Sed                     DAG.getNode(ISD::SHL, N01.getDebugLoc(), VT,
964193323Sed                                 N00.getOperand(1), N01));
965193323Sed    return DAG.getNode(ISD::ADD, DL, VT, N0, N1);
966193323Sed  }
967193323Sed
968193323Sed  return SDValue();
969193323Sed}
970193323Sed
971193323SedSDValue DAGCombiner::visitADD(SDNode *N) {
972193323Sed  SDValue N0 = N->getOperand(0);
973193323Sed  SDValue N1 = N->getOperand(1);
974193323Sed  ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
975193323Sed  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
976198090Srdivacky  EVT VT = N0.getValueType();
977193323Sed
978193323Sed  // fold vector ops
979193323Sed  if (VT.isVector()) {
980193323Sed    SDValue FoldedVOp = SimplifyVBinOp(N);
981193323Sed    if (FoldedVOp.getNode()) return FoldedVOp;
982193323Sed  }
983193323Sed
984193323Sed  // fold (add x, undef) -> undef
985193323Sed  if (N0.getOpcode() == ISD::UNDEF)
986193323Sed    return N0;
987193323Sed  if (N1.getOpcode() == ISD::UNDEF)
988193323Sed    return N1;
989193323Sed  // fold (add c1, c2) -> c1+c2
990193323Sed  if (N0C && N1C)
991193323Sed    return DAG.FoldConstantArithmetic(ISD::ADD, VT, N0C, N1C);
992193323Sed  // canonicalize constant to RHS
993193323Sed  if (N0C && !N1C)
994193323Sed    return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N1, N0);
995193323Sed  // fold (add x, 0) -> x
996193323Sed  if (N1C && N1C->isNullValue())
997193323Sed    return N0;
998193323Sed  // fold (add Sym, c) -> Sym+c
999193323Sed  if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1000193323Sed    if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1001193323Sed        GA->getOpcode() == ISD::GlobalAddress)
1002193323Sed      return DAG.getGlobalAddress(GA->getGlobal(), VT,
1003193323Sed                                  GA->getOffset() +
1004193323Sed                                    (uint64_t)N1C->getSExtValue());
1005193323Sed  // fold ((c1-A)+c2) -> (c1+c2)-A
1006193323Sed  if (N1C && N0.getOpcode() == ISD::SUB)
1007193323Sed    if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
1008193323Sed      return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
1009193323Sed                         DAG.getConstant(N1C->getAPIntValue()+
1010193323Sed                                         N0C->getAPIntValue(), VT),
1011193323Sed                         N0.getOperand(1));
1012193323Sed  // reassociate add
1013193323Sed  SDValue RADD = ReassociateOps(ISD::ADD, N->getDebugLoc(), N0, N1);
1014193323Sed  if (RADD.getNode() != 0)
1015193323Sed    return RADD;
1016193323Sed  // fold ((0-A) + B) -> B-A
1017193323Sed  if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
1018193323Sed      cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
1019193323Sed    return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N1, N0.getOperand(1));
1020193323Sed  // fold (A + (0-B)) -> A-B
1021193323Sed  if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
1022193323Sed      cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
1023193323Sed    return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N0, N1.getOperand(1));
1024193323Sed  // fold (A+(B-A)) -> B
1025193323Sed  if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1026193323Sed    return N1.getOperand(0);
1027193323Sed  // fold ((B-A)+A) -> B
1028193323Sed  if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1029193323Sed    return N0.getOperand(0);
1030193323Sed  // fold (A+(B-(A+C))) to (B-C)
1031193323Sed  if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1032193323Sed      N0 == N1.getOperand(1).getOperand(0))
1033193323Sed    return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N1.getOperand(0),
1034193323Sed                       N1.getOperand(1).getOperand(1));
1035193323Sed  // fold (A+(B-(C+A))) to (B-C)
1036193323Sed  if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1037193323Sed      N0 == N1.getOperand(1).getOperand(1))
1038193323Sed    return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N1.getOperand(0),
1039193323Sed                       N1.getOperand(1).getOperand(0));
1040193323Sed  // fold (A+((B-A)+or-C)) to (B+or-C)
1041193323Sed  if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1042193323Sed      N1.getOperand(0).getOpcode() == ISD::SUB &&
1043193323Sed      N0 == N1.getOperand(0).getOperand(1))
1044193323Sed    return DAG.getNode(N1.getOpcode(), N->getDebugLoc(), VT,
1045193323Sed                       N1.getOperand(0).getOperand(0), N1.getOperand(1));
1046193323Sed
1047193323Sed  // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1048193323Sed  if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1049193323Sed    SDValue N00 = N0.getOperand(0);
1050193323Sed    SDValue N01 = N0.getOperand(1);
1051193323Sed    SDValue N10 = N1.getOperand(0);
1052193323Sed    SDValue N11 = N1.getOperand(1);
1053193323Sed
1054193323Sed    if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1055193323Sed      return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
1056193323Sed                         DAG.getNode(ISD::ADD, N0.getDebugLoc(), VT, N00, N10),
1057193323Sed                         DAG.getNode(ISD::ADD, N1.getDebugLoc(), VT, N01, N11));
1058193323Sed  }
1059193323Sed
1060193323Sed  if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1061193323Sed    return SDValue(N, 0);
1062193323Sed
1063193323Sed  // fold (a+b) -> (a|b) iff a and b share no bits.
1064193323Sed  if (VT.isInteger() && !VT.isVector()) {
1065193323Sed    APInt LHSZero, LHSOne;
1066193323Sed    APInt RHSZero, RHSOne;
1067193323Sed    APInt Mask = APInt::getAllOnesValue(VT.getSizeInBits());
1068193323Sed    DAG.ComputeMaskedBits(N0, Mask, LHSZero, LHSOne);
1069193323Sed
1070193323Sed    if (LHSZero.getBoolValue()) {
1071193323Sed      DAG.ComputeMaskedBits(N1, Mask, RHSZero, RHSOne);
1072193323Sed
1073193323Sed      // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1074193323Sed      // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1075193323Sed      if ((RHSZero & (~LHSZero & Mask)) == (~LHSZero & Mask) ||
1076193323Sed          (LHSZero & (~RHSZero & Mask)) == (~RHSZero & Mask))
1077193323Sed        return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, N0, N1);
1078193323Sed    }
1079193323Sed  }
1080193323Sed
1081193323Sed  // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1082193323Sed  if (N0.getOpcode() == ISD::SHL && N0.getNode()->hasOneUse()) {
1083193323Sed    SDValue Result = combineShlAddConstant(N->getDebugLoc(), N0, N1, DAG);
1084193323Sed    if (Result.getNode()) return Result;
1085193323Sed  }
1086193323Sed  if (N1.getOpcode() == ISD::SHL && N1.getNode()->hasOneUse()) {
1087193323Sed    SDValue Result = combineShlAddConstant(N->getDebugLoc(), N1, N0, DAG);
1088193323Sed    if (Result.getNode()) return Result;
1089193323Sed  }
1090193323Sed
1091202878Srdivacky  // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1092202878Srdivacky  if (N1.getOpcode() == ISD::SHL &&
1093202878Srdivacky      N1.getOperand(0).getOpcode() == ISD::SUB)
1094202878Srdivacky    if (ConstantSDNode *C =
1095202878Srdivacky          dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0)))
1096202878Srdivacky      if (C->getAPIntValue() == 0)
1097202878Srdivacky        return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N0,
1098202878Srdivacky                           DAG.getNode(ISD::SHL, N->getDebugLoc(), VT,
1099202878Srdivacky                                       N1.getOperand(0).getOperand(1),
1100202878Srdivacky                                       N1.getOperand(1)));
1101202878Srdivacky  if (N0.getOpcode() == ISD::SHL &&
1102202878Srdivacky      N0.getOperand(0).getOpcode() == ISD::SUB)
1103202878Srdivacky    if (ConstantSDNode *C =
1104202878Srdivacky          dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0)))
1105202878Srdivacky      if (C->getAPIntValue() == 0)
1106202878Srdivacky        return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N1,
1107202878Srdivacky                           DAG.getNode(ISD::SHL, N->getDebugLoc(), VT,
1108202878Srdivacky                                       N0.getOperand(0).getOperand(1),
1109202878Srdivacky                                       N0.getOperand(1)));
1110202878Srdivacky
1111193323Sed  return SDValue();
1112193323Sed}
1113193323Sed
1114193323SedSDValue DAGCombiner::visitADDC(SDNode *N) {
1115193323Sed  SDValue N0 = N->getOperand(0);
1116193323Sed  SDValue N1 = N->getOperand(1);
1117193323Sed  ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1118193323Sed  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1119198090Srdivacky  EVT VT = N0.getValueType();
1120193323Sed
1121193323Sed  // If the flag result is dead, turn this into an ADD.
1122193323Sed  if (N->hasNUsesOfValue(0, 1))
1123193323Sed    return CombineTo(N, DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N1, N0),
1124193323Sed                     DAG.getNode(ISD::CARRY_FALSE,
1125193323Sed                                 N->getDebugLoc(), MVT::Flag));
1126193323Sed
1127193323Sed  // canonicalize constant to RHS.
1128193323Sed  if (N0C && !N1C)
1129193323Sed    return DAG.getNode(ISD::ADDC, N->getDebugLoc(), N->getVTList(), N1, N0);
1130193323Sed
1131193323Sed  // fold (addc x, 0) -> x + no carry out
1132193323Sed  if (N1C && N1C->isNullValue())
1133193323Sed    return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1134193323Sed                                        N->getDebugLoc(), MVT::Flag));
1135193323Sed
1136193323Sed  // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1137193323Sed  APInt LHSZero, LHSOne;
1138193323Sed  APInt RHSZero, RHSOne;
1139193323Sed  APInt Mask = APInt::getAllOnesValue(VT.getSizeInBits());
1140193323Sed  DAG.ComputeMaskedBits(N0, Mask, LHSZero, LHSOne);
1141193323Sed
1142193323Sed  if (LHSZero.getBoolValue()) {
1143193323Sed    DAG.ComputeMaskedBits(N1, Mask, RHSZero, RHSOne);
1144193323Sed
1145193323Sed    // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1146193323Sed    // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1147193323Sed    if ((RHSZero & (~LHSZero & Mask)) == (~LHSZero & Mask) ||
1148193323Sed        (LHSZero & (~RHSZero & Mask)) == (~RHSZero & Mask))
1149193323Sed      return CombineTo(N, DAG.getNode(ISD::OR, N->getDebugLoc(), VT, N0, N1),
1150193323Sed                       DAG.getNode(ISD::CARRY_FALSE,
1151193323Sed                                   N->getDebugLoc(), MVT::Flag));
1152193323Sed  }
1153193323Sed
1154193323Sed  return SDValue();
1155193323Sed}
1156193323Sed
1157193323SedSDValue DAGCombiner::visitADDE(SDNode *N) {
1158193323Sed  SDValue N0 = N->getOperand(0);
1159193323Sed  SDValue N1 = N->getOperand(1);
1160193323Sed  SDValue CarryIn = N->getOperand(2);
1161193323Sed  ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1162193323Sed  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1163193323Sed
1164193323Sed  // canonicalize constant to RHS
1165193323Sed  if (N0C && !N1C)
1166193323Sed    return DAG.getNode(ISD::ADDE, N->getDebugLoc(), N->getVTList(),
1167193323Sed                       N1, N0, CarryIn);
1168193323Sed
1169193323Sed  // fold (adde x, y, false) -> (addc x, y)
1170193323Sed  if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1171193323Sed    return DAG.getNode(ISD::ADDC, N->getDebugLoc(), N->getVTList(), N1, N0);
1172193323Sed
1173193323Sed  return SDValue();
1174193323Sed}
1175193323Sed
1176193323SedSDValue DAGCombiner::visitSUB(SDNode *N) {
1177193323Sed  SDValue N0 = N->getOperand(0);
1178193323Sed  SDValue N1 = N->getOperand(1);
1179193323Sed  ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1180193323Sed  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1181198090Srdivacky  EVT VT = N0.getValueType();
1182193323Sed
1183193323Sed  // fold vector ops
1184193323Sed  if (VT.isVector()) {
1185193323Sed    SDValue FoldedVOp = SimplifyVBinOp(N);
1186193323Sed    if (FoldedVOp.getNode()) return FoldedVOp;
1187193323Sed  }
1188193323Sed
1189193323Sed  // fold (sub x, x) -> 0
1190193323Sed  if (N0 == N1)
1191193323Sed    return DAG.getConstant(0, N->getValueType(0));
1192193323Sed  // fold (sub c1, c2) -> c1-c2
1193193323Sed  if (N0C && N1C)
1194193323Sed    return DAG.FoldConstantArithmetic(ISD::SUB, VT, N0C, N1C);
1195193323Sed  // fold (sub x, c) -> (add x, -c)
1196193323Sed  if (N1C)
1197193323Sed    return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0,
1198193323Sed                       DAG.getConstant(-N1C->getAPIntValue(), VT));
1199202878Srdivacky  // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1200202878Srdivacky  if (N0C && N0C->isAllOnesValue())
1201202878Srdivacky    return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT, N1, N0);
1202193323Sed  // fold (A+B)-A -> B
1203193323Sed  if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1204193323Sed    return N0.getOperand(1);
1205193323Sed  // fold (A+B)-B -> A
1206193323Sed  if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1207193323Sed    return N0.getOperand(0);
1208193323Sed  // fold ((A+(B+or-C))-B) -> A+or-C
1209193323Sed  if (N0.getOpcode() == ISD::ADD &&
1210193323Sed      (N0.getOperand(1).getOpcode() == ISD::SUB ||
1211193323Sed       N0.getOperand(1).getOpcode() == ISD::ADD) &&
1212193323Sed      N0.getOperand(1).getOperand(0) == N1)
1213193323Sed    return DAG.getNode(N0.getOperand(1).getOpcode(), N->getDebugLoc(), VT,
1214193323Sed                       N0.getOperand(0), N0.getOperand(1).getOperand(1));
1215193323Sed  // fold ((A+(C+B))-B) -> A+C
1216193323Sed  if (N0.getOpcode() == ISD::ADD &&
1217193323Sed      N0.getOperand(1).getOpcode() == ISD::ADD &&
1218193323Sed      N0.getOperand(1).getOperand(1) == N1)
1219193323Sed    return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT,
1220193323Sed                       N0.getOperand(0), N0.getOperand(1).getOperand(0));
1221193323Sed  // fold ((A-(B-C))-C) -> A-B
1222193323Sed  if (N0.getOpcode() == ISD::SUB &&
1223193323Sed      N0.getOperand(1).getOpcode() == ISD::SUB &&
1224193323Sed      N0.getOperand(1).getOperand(1) == N1)
1225193323Sed    return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
1226193323Sed                       N0.getOperand(0), N0.getOperand(1).getOperand(0));
1227193323Sed
1228193323Sed  // If either operand of a sub is undef, the result is undef
1229193323Sed  if (N0.getOpcode() == ISD::UNDEF)
1230193323Sed    return N0;
1231193323Sed  if (N1.getOpcode() == ISD::UNDEF)
1232193323Sed    return N1;
1233193323Sed
1234193323Sed  // If the relocation model supports it, consider symbol offsets.
1235193323Sed  if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1236193323Sed    if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1237193323Sed      // fold (sub Sym, c) -> Sym-c
1238193323Sed      if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1239193323Sed        return DAG.getGlobalAddress(GA->getGlobal(), VT,
1240193323Sed                                    GA->getOffset() -
1241193323Sed                                      (uint64_t)N1C->getSExtValue());
1242193323Sed      // fold (sub Sym+c1, Sym+c2) -> c1-c2
1243193323Sed      if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1244193323Sed        if (GA->getGlobal() == GB->getGlobal())
1245193323Sed          return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1246193323Sed                                 VT);
1247193323Sed    }
1248193323Sed
1249193323Sed  return SDValue();
1250193323Sed}
1251193323Sed
1252193323SedSDValue DAGCombiner::visitMUL(SDNode *N) {
1253193323Sed  SDValue N0 = N->getOperand(0);
1254193323Sed  SDValue N1 = N->getOperand(1);
1255193323Sed  ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1256193323Sed  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1257198090Srdivacky  EVT VT = N0.getValueType();
1258193323Sed
1259193323Sed  // fold vector ops
1260193323Sed  if (VT.isVector()) {
1261193323Sed    SDValue FoldedVOp = SimplifyVBinOp(N);
1262193323Sed    if (FoldedVOp.getNode()) return FoldedVOp;
1263193323Sed  }
1264193323Sed
1265193323Sed  // fold (mul x, undef) -> 0
1266193323Sed  if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1267193323Sed    return DAG.getConstant(0, VT);
1268193323Sed  // fold (mul c1, c2) -> c1*c2
1269193323Sed  if (N0C && N1C)
1270193323Sed    return DAG.FoldConstantArithmetic(ISD::MUL, VT, N0C, N1C);
1271193323Sed  // canonicalize constant to RHS
1272193323Sed  if (N0C && !N1C)
1273193323Sed    return DAG.getNode(ISD::MUL, N->getDebugLoc(), VT, N1, N0);
1274193323Sed  // fold (mul x, 0) -> 0
1275193323Sed  if (N1C && N1C->isNullValue())
1276193323Sed    return N1;
1277193323Sed  // fold (mul x, -1) -> 0-x
1278193323Sed  if (N1C && N1C->isAllOnesValue())
1279193323Sed    return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
1280193323Sed                       DAG.getConstant(0, VT), N0);
1281193323Sed  // fold (mul x, (1 << c)) -> x << c
1282193323Sed  if (N1C && N1C->getAPIntValue().isPowerOf2())
1283193323Sed    return DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, N0,
1284193323Sed                       DAG.getConstant(N1C->getAPIntValue().logBase2(),
1285193323Sed                                       getShiftAmountTy()));
1286193323Sed  // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
1287193323Sed  if (N1C && (-N1C->getAPIntValue()).isPowerOf2()) {
1288193323Sed    unsigned Log2Val = (-N1C->getAPIntValue()).logBase2();
1289193323Sed    // FIXME: If the input is something that is easily negated (e.g. a
1290193323Sed    // single-use add), we should put the negate there.
1291193323Sed    return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
1292193323Sed                       DAG.getConstant(0, VT),
1293193323Sed                       DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, N0,
1294193323Sed                            DAG.getConstant(Log2Val, getShiftAmountTy())));
1295193323Sed  }
1296193323Sed  // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
1297193323Sed  if (N1C && N0.getOpcode() == ISD::SHL &&
1298193323Sed      isa<ConstantSDNode>(N0.getOperand(1))) {
1299193323Sed    SDValue C3 = DAG.getNode(ISD::SHL, N->getDebugLoc(), VT,
1300193323Sed                             N1, N0.getOperand(1));
1301193323Sed    AddToWorkList(C3.getNode());
1302193323Sed    return DAG.getNode(ISD::MUL, N->getDebugLoc(), VT,
1303193323Sed                       N0.getOperand(0), C3);
1304193323Sed  }
1305193323Sed
1306193323Sed  // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
1307193323Sed  // use.
1308193323Sed  {
1309193323Sed    SDValue Sh(0,0), Y(0,0);
1310193323Sed    // Check for both (mul (shl X, C), Y)  and  (mul Y, (shl X, C)).
1311193323Sed    if (N0.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N0.getOperand(1)) &&
1312193323Sed        N0.getNode()->hasOneUse()) {
1313193323Sed      Sh = N0; Y = N1;
1314193323Sed    } else if (N1.getOpcode() == ISD::SHL &&
1315193323Sed               isa<ConstantSDNode>(N1.getOperand(1)) &&
1316193323Sed               N1.getNode()->hasOneUse()) {
1317193323Sed      Sh = N1; Y = N0;
1318193323Sed    }
1319193323Sed
1320193323Sed    if (Sh.getNode()) {
1321193323Sed      SDValue Mul = DAG.getNode(ISD::MUL, N->getDebugLoc(), VT,
1322193323Sed                                Sh.getOperand(0), Y);
1323193323Sed      return DAG.getNode(ISD::SHL, N->getDebugLoc(), VT,
1324193323Sed                         Mul, Sh.getOperand(1));
1325193323Sed    }
1326193323Sed  }
1327193323Sed
1328193323Sed  // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
1329193323Sed  if (N1C && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
1330193323Sed      isa<ConstantSDNode>(N0.getOperand(1)))
1331193323Sed    return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT,
1332193323Sed                       DAG.getNode(ISD::MUL, N0.getDebugLoc(), VT,
1333193323Sed                                   N0.getOperand(0), N1),
1334193323Sed                       DAG.getNode(ISD::MUL, N1.getDebugLoc(), VT,
1335193323Sed                                   N0.getOperand(1), N1));
1336193323Sed
1337193323Sed  // reassociate mul
1338193323Sed  SDValue RMUL = ReassociateOps(ISD::MUL, N->getDebugLoc(), N0, N1);
1339193323Sed  if (RMUL.getNode() != 0)
1340193323Sed    return RMUL;
1341193323Sed
1342193323Sed  return SDValue();
1343193323Sed}
1344193323Sed
1345193323SedSDValue DAGCombiner::visitSDIV(SDNode *N) {
1346193323Sed  SDValue N0 = N->getOperand(0);
1347193323Sed  SDValue N1 = N->getOperand(1);
1348193323Sed  ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1349193323Sed  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1350198090Srdivacky  EVT VT = N->getValueType(0);
1351193323Sed
1352193323Sed  // fold vector ops
1353193323Sed  if (VT.isVector()) {
1354193323Sed    SDValue FoldedVOp = SimplifyVBinOp(N);
1355193323Sed    if (FoldedVOp.getNode()) return FoldedVOp;
1356193323Sed  }
1357193323Sed
1358193323Sed  // fold (sdiv c1, c2) -> c1/c2
1359193323Sed  if (N0C && N1C && !N1C->isNullValue())
1360193323Sed    return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C);
1361193323Sed  // fold (sdiv X, 1) -> X
1362193323Sed  if (N1C && N1C->getSExtValue() == 1LL)
1363193323Sed    return N0;
1364193323Sed  // fold (sdiv X, -1) -> 0-X
1365193323Sed  if (N1C && N1C->isAllOnesValue())
1366193323Sed    return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
1367193323Sed                       DAG.getConstant(0, VT), N0);
1368193323Sed  // If we know the sign bits of both operands are zero, strength reduce to a
1369193323Sed  // udiv instead.  Handles (X&15) /s 4 -> X&15 >> 2
1370193323Sed  if (!VT.isVector()) {
1371193323Sed    if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
1372193323Sed      return DAG.getNode(ISD::UDIV, N->getDebugLoc(), N1.getValueType(),
1373193323Sed                         N0, N1);
1374193323Sed  }
1375193323Sed  // fold (sdiv X, pow2) -> simple ops after legalize
1376193323Sed  if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap() &&
1377193323Sed      (isPowerOf2_64(N1C->getSExtValue()) ||
1378193323Sed       isPowerOf2_64(-N1C->getSExtValue()))) {
1379193323Sed    // If dividing by powers of two is cheap, then don't perform the following
1380193323Sed    // fold.
1381193323Sed    if (TLI.isPow2DivCheap())
1382193323Sed      return SDValue();
1383193323Sed
1384193323Sed    int64_t pow2 = N1C->getSExtValue();
1385193323Sed    int64_t abs2 = pow2 > 0 ? pow2 : -pow2;
1386193323Sed    unsigned lg2 = Log2_64(abs2);
1387193323Sed
1388193323Sed    // Splat the sign bit into the register
1389193323Sed    SDValue SGN = DAG.getNode(ISD::SRA, N->getDebugLoc(), VT, N0,
1390193323Sed                              DAG.getConstant(VT.getSizeInBits()-1,
1391193323Sed                                              getShiftAmountTy()));
1392193323Sed    AddToWorkList(SGN.getNode());
1393193323Sed
1394193323Sed    // Add (N0 < 0) ? abs2 - 1 : 0;
1395193323Sed    SDValue SRL = DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, SGN,
1396193323Sed                              DAG.getConstant(VT.getSizeInBits() - lg2,
1397193323Sed                                              getShiftAmountTy()));
1398193323Sed    SDValue ADD = DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0, SRL);
1399193323Sed    AddToWorkList(SRL.getNode());
1400193323Sed    AddToWorkList(ADD.getNode());    // Divide by pow2
1401193323Sed    SDValue SRA = DAG.getNode(ISD::SRA, N->getDebugLoc(), VT, ADD,
1402193323Sed                              DAG.getConstant(lg2, getShiftAmountTy()));
1403193323Sed
1404193323Sed    // If we're dividing by a positive value, we're done.  Otherwise, we must
1405193323Sed    // negate the result.
1406193323Sed    if (pow2 > 0)
1407193323Sed      return SRA;
1408193323Sed
1409193323Sed    AddToWorkList(SRA.getNode());
1410193323Sed    return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
1411193323Sed                       DAG.getConstant(0, VT), SRA);
1412193323Sed  }
1413193323Sed
1414193323Sed  // if integer divide is expensive and we satisfy the requirements, emit an
1415193323Sed  // alternate sequence.
1416193323Sed  if (N1C && (N1C->getSExtValue() < -1 || N1C->getSExtValue() > 1) &&
1417193323Sed      !TLI.isIntDivCheap()) {
1418193323Sed    SDValue Op = BuildSDIV(N);
1419193323Sed    if (Op.getNode()) return Op;
1420193323Sed  }
1421193323Sed
1422193323Sed  // undef / X -> 0
1423193323Sed  if (N0.getOpcode() == ISD::UNDEF)
1424193323Sed    return DAG.getConstant(0, VT);
1425193323Sed  // X / undef -> undef
1426193323Sed  if (N1.getOpcode() == ISD::UNDEF)
1427193323Sed    return N1;
1428193323Sed
1429193323Sed  return SDValue();
1430193323Sed}
1431193323Sed
1432193323SedSDValue DAGCombiner::visitUDIV(SDNode *N) {
1433193323Sed  SDValue N0 = N->getOperand(0);
1434193323Sed  SDValue N1 = N->getOperand(1);
1435193323Sed  ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1436193323Sed  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1437198090Srdivacky  EVT VT = N->getValueType(0);
1438193323Sed
1439193323Sed  // fold vector ops
1440193323Sed  if (VT.isVector()) {
1441193323Sed    SDValue FoldedVOp = SimplifyVBinOp(N);
1442193323Sed    if (FoldedVOp.getNode()) return FoldedVOp;
1443193323Sed  }
1444193323Sed
1445193323Sed  // fold (udiv c1, c2) -> c1/c2
1446193323Sed  if (N0C && N1C && !N1C->isNullValue())
1447193323Sed    return DAG.FoldConstantArithmetic(ISD::UDIV, VT, N0C, N1C);
1448193323Sed  // fold (udiv x, (1 << c)) -> x >>u c
1449193323Sed  if (N1C && N1C->getAPIntValue().isPowerOf2())
1450193323Sed    return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0,
1451193323Sed                       DAG.getConstant(N1C->getAPIntValue().logBase2(),
1452193323Sed                                       getShiftAmountTy()));
1453193323Sed  // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
1454193323Sed  if (N1.getOpcode() == ISD::SHL) {
1455193323Sed    if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
1456193323Sed      if (SHC->getAPIntValue().isPowerOf2()) {
1457198090Srdivacky        EVT ADDVT = N1.getOperand(1).getValueType();
1458193323Sed        SDValue Add = DAG.getNode(ISD::ADD, N->getDebugLoc(), ADDVT,
1459193323Sed                                  N1.getOperand(1),
1460193323Sed                                  DAG.getConstant(SHC->getAPIntValue()
1461193323Sed                                                                  .logBase2(),
1462193323Sed                                                  ADDVT));
1463193323Sed        AddToWorkList(Add.getNode());
1464193323Sed        return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0, Add);
1465193323Sed      }
1466193323Sed    }
1467193323Sed  }
1468193323Sed  // fold (udiv x, c) -> alternate
1469193323Sed  if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap()) {
1470193323Sed    SDValue Op = BuildUDIV(N);
1471193323Sed    if (Op.getNode()) return Op;
1472193323Sed  }
1473193323Sed
1474193323Sed  // undef / X -> 0
1475193323Sed  if (N0.getOpcode() == ISD::UNDEF)
1476193323Sed    return DAG.getConstant(0, VT);
1477193323Sed  // X / undef -> undef
1478193323Sed  if (N1.getOpcode() == ISD::UNDEF)
1479193323Sed    return N1;
1480193323Sed
1481193323Sed  return SDValue();
1482193323Sed}
1483193323Sed
1484193323SedSDValue DAGCombiner::visitSREM(SDNode *N) {
1485193323Sed  SDValue N0 = N->getOperand(0);
1486193323Sed  SDValue N1 = N->getOperand(1);
1487193323Sed  ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1488193323Sed  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1489198090Srdivacky  EVT VT = N->getValueType(0);
1490193323Sed
1491193323Sed  // fold (srem c1, c2) -> c1%c2
1492193323Sed  if (N0C && N1C && !N1C->isNullValue())
1493193323Sed    return DAG.FoldConstantArithmetic(ISD::SREM, VT, N0C, N1C);
1494193323Sed  // If we know the sign bits of both operands are zero, strength reduce to a
1495193323Sed  // urem instead.  Handles (X & 0x0FFFFFFF) %s 16 -> X&15
1496193323Sed  if (!VT.isVector()) {
1497193323Sed    if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
1498193323Sed      return DAG.getNode(ISD::UREM, N->getDebugLoc(), VT, N0, N1);
1499193323Sed  }
1500193323Sed
1501193323Sed  // If X/C can be simplified by the division-by-constant logic, lower
1502193323Sed  // X%C to the equivalent of X-X/C*C.
1503193323Sed  if (N1C && !N1C->isNullValue()) {
1504193323Sed    SDValue Div = DAG.getNode(ISD::SDIV, N->getDebugLoc(), VT, N0, N1);
1505193323Sed    AddToWorkList(Div.getNode());
1506193323Sed    SDValue OptimizedDiv = combine(Div.getNode());
1507193323Sed    if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
1508193323Sed      SDValue Mul = DAG.getNode(ISD::MUL, N->getDebugLoc(), VT,
1509193323Sed                                OptimizedDiv, N1);
1510193323Sed      SDValue Sub = DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N0, Mul);
1511193323Sed      AddToWorkList(Mul.getNode());
1512193323Sed      return Sub;
1513193323Sed    }
1514193323Sed  }
1515193323Sed
1516193323Sed  // undef % X -> 0
1517193323Sed  if (N0.getOpcode() == ISD::UNDEF)
1518193323Sed    return DAG.getConstant(0, VT);
1519193323Sed  // X % undef -> undef
1520193323Sed  if (N1.getOpcode() == ISD::UNDEF)
1521193323Sed    return N1;
1522193323Sed
1523193323Sed  return SDValue();
1524193323Sed}
1525193323Sed
1526193323SedSDValue DAGCombiner::visitUREM(SDNode *N) {
1527193323Sed  SDValue N0 = N->getOperand(0);
1528193323Sed  SDValue N1 = N->getOperand(1);
1529193323Sed  ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1530193323Sed  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1531198090Srdivacky  EVT VT = N->getValueType(0);
1532193323Sed
1533193323Sed  // fold (urem c1, c2) -> c1%c2
1534193323Sed  if (N0C && N1C && !N1C->isNullValue())
1535193323Sed    return DAG.FoldConstantArithmetic(ISD::UREM, VT, N0C, N1C);
1536193323Sed  // fold (urem x, pow2) -> (and x, pow2-1)
1537193323Sed  if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2())
1538193323Sed    return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0,
1539193323Sed                       DAG.getConstant(N1C->getAPIntValue()-1,VT));
1540193323Sed  // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
1541193323Sed  if (N1.getOpcode() == ISD::SHL) {
1542193323Sed    if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
1543193323Sed      if (SHC->getAPIntValue().isPowerOf2()) {
1544193323Sed        SDValue Add =
1545193323Sed          DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N1,
1546193323Sed                 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()),
1547193323Sed                                 VT));
1548193323Sed        AddToWorkList(Add.getNode());
1549193323Sed        return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0, Add);
1550193323Sed      }
1551193323Sed    }
1552193323Sed  }
1553193323Sed
1554193323Sed  // If X/C can be simplified by the division-by-constant logic, lower
1555193323Sed  // X%C to the equivalent of X-X/C*C.
1556193323Sed  if (N1C && !N1C->isNullValue()) {
1557193323Sed    SDValue Div = DAG.getNode(ISD::UDIV, N->getDebugLoc(), VT, N0, N1);
1558193323Sed    AddToWorkList(Div.getNode());
1559193323Sed    SDValue OptimizedDiv = combine(Div.getNode());
1560193323Sed    if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
1561193323Sed      SDValue Mul = DAG.getNode(ISD::MUL, N->getDebugLoc(), VT,
1562193323Sed                                OptimizedDiv, N1);
1563193323Sed      SDValue Sub = DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N0, Mul);
1564193323Sed      AddToWorkList(Mul.getNode());
1565193323Sed      return Sub;
1566193323Sed    }
1567193323Sed  }
1568193323Sed
1569193323Sed  // undef % X -> 0
1570193323Sed  if (N0.getOpcode() == ISD::UNDEF)
1571193323Sed    return DAG.getConstant(0, VT);
1572193323Sed  // X % undef -> undef
1573193323Sed  if (N1.getOpcode() == ISD::UNDEF)
1574193323Sed    return N1;
1575193323Sed
1576193323Sed  return SDValue();
1577193323Sed}
1578193323Sed
1579193323SedSDValue DAGCombiner::visitMULHS(SDNode *N) {
1580193323Sed  SDValue N0 = N->getOperand(0);
1581193323Sed  SDValue N1 = N->getOperand(1);
1582193323Sed  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1583198090Srdivacky  EVT VT = N->getValueType(0);
1584193323Sed
1585193323Sed  // fold (mulhs x, 0) -> 0
1586193323Sed  if (N1C && N1C->isNullValue())
1587193323Sed    return N1;
1588193323Sed  // fold (mulhs x, 1) -> (sra x, size(x)-1)
1589193323Sed  if (N1C && N1C->getAPIntValue() == 1)
1590193323Sed    return DAG.getNode(ISD::SRA, N->getDebugLoc(), N0.getValueType(), N0,
1591193323Sed                       DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
1592193323Sed                                       getShiftAmountTy()));
1593193323Sed  // fold (mulhs x, undef) -> 0
1594193323Sed  if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1595193323Sed    return DAG.getConstant(0, VT);
1596193323Sed
1597193323Sed  return SDValue();
1598193323Sed}
1599193323Sed
1600193323SedSDValue DAGCombiner::visitMULHU(SDNode *N) {
1601193323Sed  SDValue N0 = N->getOperand(0);
1602193323Sed  SDValue N1 = N->getOperand(1);
1603193323Sed  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1604198090Srdivacky  EVT VT = N->getValueType(0);
1605193323Sed
1606193323Sed  // fold (mulhu x, 0) -> 0
1607193323Sed  if (N1C && N1C->isNullValue())
1608193323Sed    return N1;
1609193323Sed  // fold (mulhu x, 1) -> 0
1610193323Sed  if (N1C && N1C->getAPIntValue() == 1)
1611193323Sed    return DAG.getConstant(0, N0.getValueType());
1612193323Sed  // fold (mulhu x, undef) -> 0
1613193323Sed  if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1614193323Sed    return DAG.getConstant(0, VT);
1615193323Sed
1616193323Sed  return SDValue();
1617193323Sed}
1618193323Sed
1619193323Sed/// SimplifyNodeWithTwoResults - Perform optimizations common to nodes that
1620193323Sed/// compute two values. LoOp and HiOp give the opcodes for the two computations
1621193323Sed/// that are being performed. Return true if a simplification was made.
1622193323Sed///
1623193323SedSDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
1624193323Sed                                                unsigned HiOp) {
1625193323Sed  // If the high half is not needed, just compute the low half.
1626193323Sed  bool HiExists = N->hasAnyUseOfValue(1);
1627193323Sed  if (!HiExists &&
1628193323Sed      (!LegalOperations ||
1629193323Sed       TLI.isOperationLegal(LoOp, N->getValueType(0)))) {
1630193323Sed    SDValue Res = DAG.getNode(LoOp, N->getDebugLoc(), N->getValueType(0),
1631193323Sed                              N->op_begin(), N->getNumOperands());
1632193323Sed    return CombineTo(N, Res, Res);
1633193323Sed  }
1634193323Sed
1635193323Sed  // If the low half is not needed, just compute the high half.
1636193323Sed  bool LoExists = N->hasAnyUseOfValue(0);
1637193323Sed  if (!LoExists &&
1638193323Sed      (!LegalOperations ||
1639193323Sed       TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
1640193323Sed    SDValue Res = DAG.getNode(HiOp, N->getDebugLoc(), N->getValueType(1),
1641193323Sed                              N->op_begin(), N->getNumOperands());
1642193323Sed    return CombineTo(N, Res, Res);
1643193323Sed  }
1644193323Sed
1645193323Sed  // If both halves are used, return as it is.
1646193323Sed  if (LoExists && HiExists)
1647193323Sed    return SDValue();
1648193323Sed
1649193323Sed  // If the two computed results can be simplified separately, separate them.
1650193323Sed  if (LoExists) {
1651193323Sed    SDValue Lo = DAG.getNode(LoOp, N->getDebugLoc(), N->getValueType(0),
1652193323Sed                             N->op_begin(), N->getNumOperands());
1653193323Sed    AddToWorkList(Lo.getNode());
1654193323Sed    SDValue LoOpt = combine(Lo.getNode());
1655193323Sed    if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
1656193323Sed        (!LegalOperations ||
1657193323Sed         TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
1658193323Sed      return CombineTo(N, LoOpt, LoOpt);
1659193323Sed  }
1660193323Sed
1661193323Sed  if (HiExists) {
1662193323Sed    SDValue Hi = DAG.getNode(HiOp, N->getDebugLoc(), N->getValueType(1),
1663193323Sed                             N->op_begin(), N->getNumOperands());
1664193323Sed    AddToWorkList(Hi.getNode());
1665193323Sed    SDValue HiOpt = combine(Hi.getNode());
1666193323Sed    if (HiOpt.getNode() && HiOpt != Hi &&
1667193323Sed        (!LegalOperations ||
1668193323Sed         TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
1669193323Sed      return CombineTo(N, HiOpt, HiOpt);
1670193323Sed  }
1671193323Sed
1672193323Sed  return SDValue();
1673193323Sed}
1674193323Sed
1675193323SedSDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
1676193323Sed  SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
1677193323Sed  if (Res.getNode()) return Res;
1678193323Sed
1679193323Sed  return SDValue();
1680193323Sed}
1681193323Sed
1682193323SedSDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
1683193323Sed  SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
1684193323Sed  if (Res.getNode()) return Res;
1685193323Sed
1686193323Sed  return SDValue();
1687193323Sed}
1688193323Sed
1689193323SedSDValue DAGCombiner::visitSDIVREM(SDNode *N) {
1690193323Sed  SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
1691193323Sed  if (Res.getNode()) return Res;
1692193323Sed
1693193323Sed  return SDValue();
1694193323Sed}
1695193323Sed
1696193323SedSDValue DAGCombiner::visitUDIVREM(SDNode *N) {
1697193323Sed  SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
1698193323Sed  if (Res.getNode()) return Res;
1699193323Sed
1700193323Sed  return SDValue();
1701193323Sed}
1702193323Sed
1703193323Sed/// SimplifyBinOpWithSameOpcodeHands - If this is a binary operator with
1704193323Sed/// two operands of the same opcode, try to simplify it.
1705193323SedSDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
1706193323Sed  SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
1707198090Srdivacky  EVT VT = N0.getValueType();
1708193323Sed  assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
1709193323Sed
1710202375Srdivacky  // Bail early if none of these transforms apply.
1711202375Srdivacky  if (N0.getNode()->getNumOperands() == 0) return SDValue();
1712202375Srdivacky
1713193323Sed  // For each of OP in AND/OR/XOR:
1714193323Sed  // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
1715193323Sed  // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
1716193323Sed  // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
1717202375Srdivacky  // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y))
1718200581Srdivacky  //
1719200581Srdivacky  // do not sink logical op inside of a vector extend, since it may combine
1720200581Srdivacky  // into a vsetcc.
1721202375Srdivacky  EVT Op0VT = N0.getOperand(0).getValueType();
1722202375Srdivacky  if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
1723202375Srdivacky       N0.getOpcode() == ISD::ANY_EXTEND  ||
1724193323Sed       N0.getOpcode() == ISD::SIGN_EXTEND ||
1725202375Srdivacky       (N0.getOpcode() == ISD::TRUNCATE && TLI.isTypeLegal(Op0VT))) &&
1726200581Srdivacky      !VT.isVector() &&
1727202375Srdivacky      Op0VT == N1.getOperand(0).getValueType() &&
1728202375Srdivacky      (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
1729193323Sed    SDValue ORNode = DAG.getNode(N->getOpcode(), N0.getDebugLoc(),
1730193323Sed                                 N0.getOperand(0).getValueType(),
1731193323Sed                                 N0.getOperand(0), N1.getOperand(0));
1732193323Sed    AddToWorkList(ORNode.getNode());
1733193323Sed    return DAG.getNode(N0.getOpcode(), N->getDebugLoc(), VT, ORNode);
1734193323Sed  }
1735193323Sed
1736193323Sed  // For each of OP in SHL/SRL/SRA/AND...
1737193323Sed  //   fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
1738193323Sed  //   fold (or  (OP x, z), (OP y, z)) -> (OP (or  x, y), z)
1739193323Sed  //   fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
1740193323Sed  if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
1741193323Sed       N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
1742193323Sed      N0.getOperand(1) == N1.getOperand(1)) {
1743193323Sed    SDValue ORNode = DAG.getNode(N->getOpcode(), N0.getDebugLoc(),
1744193323Sed                                 N0.getOperand(0).getValueType(),
1745193323Sed                                 N0.getOperand(0), N1.getOperand(0));
1746193323Sed    AddToWorkList(ORNode.getNode());
1747193323Sed    return DAG.getNode(N0.getOpcode(), N->getDebugLoc(), VT,
1748193323Sed                       ORNode, N0.getOperand(1));
1749193323Sed  }
1750193323Sed
1751193323Sed  return SDValue();
1752193323Sed}
1753193323Sed
1754193323SedSDValue DAGCombiner::visitAND(SDNode *N) {
1755193323Sed  SDValue N0 = N->getOperand(0);
1756193323Sed  SDValue N1 = N->getOperand(1);
1757193323Sed  SDValue LL, LR, RL, RR, CC0, CC1;
1758193323Sed  ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1759193323Sed  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1760198090Srdivacky  EVT VT = N1.getValueType();
1761193323Sed  unsigned BitWidth = VT.getSizeInBits();
1762193323Sed
1763193323Sed  // fold vector ops
1764193323Sed  if (VT.isVector()) {
1765193323Sed    SDValue FoldedVOp = SimplifyVBinOp(N);
1766193323Sed    if (FoldedVOp.getNode()) return FoldedVOp;
1767193323Sed  }
1768193323Sed
1769193323Sed  // fold (and x, undef) -> 0
1770193323Sed  if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1771193323Sed    return DAG.getConstant(0, VT);
1772193323Sed  // fold (and c1, c2) -> c1&c2
1773193323Sed  if (N0C && N1C)
1774193323Sed    return DAG.FoldConstantArithmetic(ISD::AND, VT, N0C, N1C);
1775193323Sed  // canonicalize constant to RHS
1776193323Sed  if (N0C && !N1C)
1777193323Sed    return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N1, N0);
1778193323Sed  // fold (and x, -1) -> x
1779193323Sed  if (N1C && N1C->isAllOnesValue())
1780193323Sed    return N0;
1781193323Sed  // if (and x, c) is known to be zero, return 0
1782193323Sed  if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
1783193323Sed                                   APInt::getAllOnesValue(BitWidth)))
1784193323Sed    return DAG.getConstant(0, VT);
1785193323Sed  // reassociate and
1786193323Sed  SDValue RAND = ReassociateOps(ISD::AND, N->getDebugLoc(), N0, N1);
1787193323Sed  if (RAND.getNode() != 0)
1788193323Sed    return RAND;
1789193323Sed  // fold (and (or x, 0xFFFF), 0xFF) -> 0xFF
1790193323Sed  if (N1C && N0.getOpcode() == ISD::OR)
1791193323Sed    if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
1792193323Sed      if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
1793193323Sed        return N1;
1794193323Sed  // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
1795193323Sed  if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
1796193323Sed    SDValue N0Op0 = N0.getOperand(0);
1797193323Sed    APInt Mask = ~N1C->getAPIntValue();
1798193323Sed    Mask.trunc(N0Op0.getValueSizeInBits());
1799193323Sed    if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
1800193323Sed      SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(),
1801193323Sed                                 N0.getValueType(), N0Op0);
1802193323Sed
1803193323Sed      // Replace uses of the AND with uses of the Zero extend node.
1804193323Sed      CombineTo(N, Zext);
1805193323Sed
1806193323Sed      // We actually want to replace all uses of the any_extend with the
1807193323Sed      // zero_extend, to avoid duplicating things.  This will later cause this
1808193323Sed      // AND to be folded.
1809193323Sed      CombineTo(N0.getNode(), Zext);
1810193323Sed      return SDValue(N, 0);   // Return N so it doesn't get rechecked!
1811193323Sed    }
1812193323Sed  }
1813193323Sed  // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
1814193323Sed  if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
1815193323Sed    ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
1816193323Sed    ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
1817193323Sed
1818193323Sed    if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
1819193323Sed        LL.getValueType().isInteger()) {
1820193323Sed      // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
1821193323Sed      if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
1822193323Sed        SDValue ORNode = DAG.getNode(ISD::OR, N0.getDebugLoc(),
1823193323Sed                                     LR.getValueType(), LL, RL);
1824193323Sed        AddToWorkList(ORNode.getNode());
1825193323Sed        return DAG.getSetCC(N->getDebugLoc(), VT, ORNode, LR, Op1);
1826193323Sed      }
1827193323Sed      // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
1828193323Sed      if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
1829193323Sed        SDValue ANDNode = DAG.getNode(ISD::AND, N0.getDebugLoc(),
1830193323Sed                                      LR.getValueType(), LL, RL);
1831193323Sed        AddToWorkList(ANDNode.getNode());
1832193323Sed        return DAG.getSetCC(N->getDebugLoc(), VT, ANDNode, LR, Op1);
1833193323Sed      }
1834193323Sed      // fold (and (setgt X,  -1), (setgt Y,  -1)) -> (setgt (or X, Y), -1)
1835193323Sed      if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
1836193323Sed        SDValue ORNode = DAG.getNode(ISD::OR, N0.getDebugLoc(),
1837193323Sed                                     LR.getValueType(), LL, RL);
1838193323Sed        AddToWorkList(ORNode.getNode());
1839193323Sed        return DAG.getSetCC(N->getDebugLoc(), VT, ORNode, LR, Op1);
1840193323Sed      }
1841193323Sed    }
1842193323Sed    // canonicalize equivalent to ll == rl
1843193323Sed    if (LL == RR && LR == RL) {
1844193323Sed      Op1 = ISD::getSetCCSwappedOperands(Op1);
1845193323Sed      std::swap(RL, RR);
1846193323Sed    }
1847193323Sed    if (LL == RL && LR == RR) {
1848193323Sed      bool isInteger = LL.getValueType().isInteger();
1849193323Sed      ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
1850193323Sed      if (Result != ISD::SETCC_INVALID &&
1851193323Sed          (!LegalOperations || TLI.isCondCodeLegal(Result, LL.getValueType())))
1852193323Sed        return DAG.getSetCC(N->getDebugLoc(), N0.getValueType(),
1853193323Sed                            LL, LR, Result);
1854193323Sed    }
1855193323Sed  }
1856193323Sed
1857193323Sed  // Simplify: (and (op x...), (op y...))  -> (op (and x, y))
1858193323Sed  if (N0.getOpcode() == N1.getOpcode()) {
1859193323Sed    SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
1860193323Sed    if (Tmp.getNode()) return Tmp;
1861193323Sed  }
1862193323Sed
1863193323Sed  // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
1864193323Sed  // fold (and (sra)) -> (and (srl)) when possible.
1865193323Sed  if (!VT.isVector() &&
1866193323Sed      SimplifyDemandedBits(SDValue(N, 0)))
1867193323Sed    return SDValue(N, 0);
1868202375Srdivacky
1869193323Sed  // fold (zext_inreg (extload x)) -> (zextload x)
1870193323Sed  if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
1871193323Sed    LoadSDNode *LN0 = cast<LoadSDNode>(N0);
1872198090Srdivacky    EVT MemVT = LN0->getMemoryVT();
1873193323Sed    // If we zero all the possible extended bits, then we can turn this into
1874193323Sed    // a zextload if we are running before legalize or the operation is legal.
1875193323Sed    unsigned BitWidth = N1.getValueSizeInBits();
1876193323Sed    if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
1877198090Srdivacky                                     BitWidth - MemVT.getSizeInBits())) &&
1878193323Sed        ((!LegalOperations && !LN0->isVolatile()) ||
1879198090Srdivacky         TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
1880193323Sed      SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, N0.getDebugLoc(), VT,
1881193323Sed                                       LN0->getChain(), LN0->getBasePtr(),
1882193323Sed                                       LN0->getSrcValue(),
1883198090Srdivacky                                       LN0->getSrcValueOffset(), MemVT,
1884193323Sed                                       LN0->isVolatile(), LN0->getAlignment());
1885193323Sed      AddToWorkList(N);
1886193323Sed      CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
1887193323Sed      return SDValue(N, 0);   // Return N so it doesn't get rechecked!
1888193323Sed    }
1889193323Sed  }
1890193323Sed  // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
1891193323Sed  if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
1892193323Sed      N0.hasOneUse()) {
1893193323Sed    LoadSDNode *LN0 = cast<LoadSDNode>(N0);
1894198090Srdivacky    EVT MemVT = LN0->getMemoryVT();
1895193323Sed    // If we zero all the possible extended bits, then we can turn this into
1896193323Sed    // a zextload if we are running before legalize or the operation is legal.
1897193323Sed    unsigned BitWidth = N1.getValueSizeInBits();
1898193323Sed    if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
1899198090Srdivacky                                     BitWidth - MemVT.getSizeInBits())) &&
1900193323Sed        ((!LegalOperations && !LN0->isVolatile()) ||
1901198090Srdivacky         TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
1902193323Sed      SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, N0.getDebugLoc(), VT,
1903193323Sed                                       LN0->getChain(),
1904193323Sed                                       LN0->getBasePtr(), LN0->getSrcValue(),
1905198090Srdivacky                                       LN0->getSrcValueOffset(), MemVT,
1906193323Sed                                       LN0->isVolatile(), LN0->getAlignment());
1907193323Sed      AddToWorkList(N);
1908193323Sed      CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
1909193323Sed      return SDValue(N, 0);   // Return N so it doesn't get rechecked!
1910193323Sed    }
1911193323Sed  }
1912193323Sed
1913193323Sed  // fold (and (load x), 255) -> (zextload x, i8)
1914193323Sed  // fold (and (extload x, i16), 255) -> (zextload x, i8)
1915202375Srdivacky  // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
1916202375Srdivacky  if (N1C && (N0.getOpcode() == ISD::LOAD ||
1917202375Srdivacky              (N0.getOpcode() == ISD::ANY_EXTEND &&
1918202375Srdivacky               N0.getOperand(0).getOpcode() == ISD::LOAD))) {
1919202375Srdivacky    bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
1920202375Srdivacky    LoadSDNode *LN0 = HasAnyExt
1921202375Srdivacky      ? cast<LoadSDNode>(N0.getOperand(0))
1922202375Srdivacky      : cast<LoadSDNode>(N0);
1923193323Sed    if (LN0->getExtensionType() != ISD::SEXTLOAD &&
1924202375Srdivacky        LN0->isUnindexed() && N0.hasOneUse() && LN0->hasOneUse()) {
1925193323Sed      uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
1926202375Srdivacky      if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
1927202375Srdivacky        EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
1928202375Srdivacky        EVT LoadedVT = LN0->getMemoryVT();
1929193323Sed
1930202375Srdivacky        if (ExtVT == LoadedVT &&
1931202375Srdivacky            (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
1932202375Srdivacky          EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
1933202375Srdivacky
1934202375Srdivacky          SDValue NewLoad =
1935202375Srdivacky            DAG.getExtLoad(ISD::ZEXTLOAD, LN0->getDebugLoc(), LoadResultTy,
1936202375Srdivacky                           LN0->getChain(), LN0->getBasePtr(),
1937202375Srdivacky                           LN0->getSrcValue(), LN0->getSrcValueOffset(),
1938202375Srdivacky                           ExtVT, LN0->isVolatile(), LN0->getAlignment());
1939202375Srdivacky          AddToWorkList(N);
1940202375Srdivacky          CombineTo(LN0, NewLoad, NewLoad.getValue(1));
1941202375Srdivacky          return SDValue(N, 0);   // Return N so it doesn't get rechecked!
1942202375Srdivacky        }
1943202375Srdivacky
1944202375Srdivacky        // Do not change the width of a volatile load.
1945202375Srdivacky        // Do not generate loads of non-round integer types since these can
1946202375Srdivacky        // be expensive (and would be wrong if the type is not byte sized).
1947202375Srdivacky        if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
1948202375Srdivacky            (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
1949202375Srdivacky          EVT PtrType = LN0->getOperand(1).getValueType();
1950193323Sed
1951202375Srdivacky          unsigned Alignment = LN0->getAlignment();
1952202375Srdivacky          SDValue NewPtr = LN0->getBasePtr();
1953193323Sed
1954202375Srdivacky          // For big endian targets, we need to add an offset to the pointer
1955202375Srdivacky          // to load the correct bytes.  For little endian systems, we merely
1956202375Srdivacky          // need to read fewer bytes from the same pointer.
1957202375Srdivacky          if (TLI.isBigEndian()) {
1958202375Srdivacky            unsigned LVTStoreBytes = LoadedVT.getStoreSize();
1959202375Srdivacky            unsigned EVTStoreBytes = ExtVT.getStoreSize();
1960202375Srdivacky            unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
1961202375Srdivacky            NewPtr = DAG.getNode(ISD::ADD, LN0->getDebugLoc(), PtrType,
1962202375Srdivacky                                 NewPtr, DAG.getConstant(PtrOff, PtrType));
1963202375Srdivacky            Alignment = MinAlign(Alignment, PtrOff);
1964202375Srdivacky          }
1965193323Sed
1966202375Srdivacky          AddToWorkList(NewPtr.getNode());
1967202375Srdivacky
1968202375Srdivacky          EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
1969202375Srdivacky          SDValue Load =
1970202375Srdivacky            DAG.getExtLoad(ISD::ZEXTLOAD, LN0->getDebugLoc(), LoadResultTy,
1971202375Srdivacky                           LN0->getChain(), NewPtr,
1972202375Srdivacky                           LN0->getSrcValue(), LN0->getSrcValueOffset(),
1973202375Srdivacky                           ExtVT, LN0->isVolatile(), Alignment);
1974202375Srdivacky          AddToWorkList(N);
1975202375Srdivacky          CombineTo(LN0, Load, Load.getValue(1));
1976202375Srdivacky          return SDValue(N, 0);   // Return N so it doesn't get rechecked!
1977193323Sed        }
1978193323Sed      }
1979193323Sed    }
1980193323Sed  }
1981193323Sed
1982193323Sed  return SDValue();
1983193323Sed}
1984193323Sed
1985193323SedSDValue DAGCombiner::visitOR(SDNode *N) {
1986193323Sed  SDValue N0 = N->getOperand(0);
1987193323Sed  SDValue N1 = N->getOperand(1);
1988193323Sed  SDValue LL, LR, RL, RR, CC0, CC1;
1989193323Sed  ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1990193323Sed  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1991198090Srdivacky  EVT VT = N1.getValueType();
1992193323Sed
1993193323Sed  // fold vector ops
1994193323Sed  if (VT.isVector()) {
1995193323Sed    SDValue FoldedVOp = SimplifyVBinOp(N);
1996193323Sed    if (FoldedVOp.getNode()) return FoldedVOp;
1997193323Sed  }
1998193323Sed
1999193323Sed  // fold (or x, undef) -> -1
2000200581Srdivacky  if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF) {
2001200581Srdivacky    EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
2002200581Srdivacky    return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT);
2003200581Srdivacky  }
2004193323Sed  // fold (or c1, c2) -> c1|c2
2005193323Sed  if (N0C && N1C)
2006193323Sed    return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C);
2007193323Sed  // canonicalize constant to RHS
2008193323Sed  if (N0C && !N1C)
2009193323Sed    return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, N1, N0);
2010193323Sed  // fold (or x, 0) -> x
2011193323Sed  if (N1C && N1C->isNullValue())
2012193323Sed    return N0;
2013193323Sed  // fold (or x, -1) -> -1
2014193323Sed  if (N1C && N1C->isAllOnesValue())
2015193323Sed    return N1;
2016193323Sed  // fold (or x, c) -> c iff (x & ~c) == 0
2017193323Sed  if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
2018193323Sed    return N1;
2019193323Sed  // reassociate or
2020193323Sed  SDValue ROR = ReassociateOps(ISD::OR, N->getDebugLoc(), N0, N1);
2021193323Sed  if (ROR.getNode() != 0)
2022193323Sed    return ROR;
2023193323Sed  // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
2024193323Sed  if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
2025193323Sed             isa<ConstantSDNode>(N0.getOperand(1))) {
2026193323Sed    ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
2027193323Sed    return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
2028193323Sed                       DAG.getNode(ISD::OR, N0.getDebugLoc(), VT,
2029193323Sed                                   N0.getOperand(0), N1),
2030193323Sed                       DAG.FoldConstantArithmetic(ISD::OR, VT, N1C, C1));
2031193323Sed  }
2032193323Sed  // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
2033193323Sed  if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2034193323Sed    ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2035193323Sed    ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2036193323Sed
2037193323Sed    if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2038193323Sed        LL.getValueType().isInteger()) {
2039193323Sed      // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
2040193323Sed      // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
2041193323Sed      if (cast<ConstantSDNode>(LR)->isNullValue() &&
2042193323Sed          (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
2043193323Sed        SDValue ORNode = DAG.getNode(ISD::OR, LR.getDebugLoc(),
2044193323Sed                                     LR.getValueType(), LL, RL);
2045193323Sed        AddToWorkList(ORNode.getNode());
2046193323Sed        return DAG.getSetCC(N->getDebugLoc(), VT, ORNode, LR, Op1);
2047193323Sed      }
2048193323Sed      // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
2049193323Sed      // fold (or (setgt X, -1), (setgt Y  -1)) -> (setgt (and X, Y), -1)
2050193323Sed      if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
2051193323Sed          (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
2052193323Sed        SDValue ANDNode = DAG.getNode(ISD::AND, LR.getDebugLoc(),
2053193323Sed                                      LR.getValueType(), LL, RL);
2054193323Sed        AddToWorkList(ANDNode.getNode());
2055193323Sed        return DAG.getSetCC(N->getDebugLoc(), VT, ANDNode, LR, Op1);
2056193323Sed      }
2057193323Sed    }
2058193323Sed    // canonicalize equivalent to ll == rl
2059193323Sed    if (LL == RR && LR == RL) {
2060193323Sed      Op1 = ISD::getSetCCSwappedOperands(Op1);
2061193323Sed      std::swap(RL, RR);
2062193323Sed    }
2063193323Sed    if (LL == RL && LR == RR) {
2064193323Sed      bool isInteger = LL.getValueType().isInteger();
2065193323Sed      ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
2066193323Sed      if (Result != ISD::SETCC_INVALID &&
2067193323Sed          (!LegalOperations || TLI.isCondCodeLegal(Result, LL.getValueType())))
2068193323Sed        return DAG.getSetCC(N->getDebugLoc(), N0.getValueType(),
2069193323Sed                            LL, LR, Result);
2070193323Sed    }
2071193323Sed  }
2072193323Sed
2073193323Sed  // Simplify: (or (op x...), (op y...))  -> (op (or x, y))
2074193323Sed  if (N0.getOpcode() == N1.getOpcode()) {
2075193323Sed    SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
2076193323Sed    if (Tmp.getNode()) return Tmp;
2077193323Sed  }
2078193323Sed
2079193323Sed  // (or (and X, C1), (and Y, C2))  -> (and (or X, Y), C3) if possible.
2080193323Sed  if (N0.getOpcode() == ISD::AND &&
2081193323Sed      N1.getOpcode() == ISD::AND &&
2082193323Sed      N0.getOperand(1).getOpcode() == ISD::Constant &&
2083193323Sed      N1.getOperand(1).getOpcode() == ISD::Constant &&
2084193323Sed      // Don't increase # computations.
2085193323Sed      (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
2086193323Sed    // We can only do this xform if we know that bits from X that are set in C2
2087193323Sed    // but not in C1 are already zero.  Likewise for Y.
2088193323Sed    const APInt &LHSMask =
2089193323Sed      cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
2090193323Sed    const APInt &RHSMask =
2091193323Sed      cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
2092193323Sed
2093193323Sed    if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
2094193323Sed        DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
2095193323Sed      SDValue X = DAG.getNode(ISD::OR, N0.getDebugLoc(), VT,
2096193323Sed                              N0.getOperand(0), N1.getOperand(0));
2097193323Sed      return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, X,
2098193323Sed                         DAG.getConstant(LHSMask | RHSMask, VT));
2099193323Sed    }
2100193323Sed  }
2101193323Sed
2102193323Sed  // See if this is some rotate idiom.
2103193323Sed  if (SDNode *Rot = MatchRotate(N0, N1, N->getDebugLoc()))
2104193323Sed    return SDValue(Rot, 0);
2105193323Sed
2106193323Sed  return SDValue();
2107193323Sed}
2108193323Sed
2109193323Sed/// MatchRotateHalf - Match "(X shl/srl V1) & V2" where V2 may not be present.
2110193323Sedstatic bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
2111193323Sed  if (Op.getOpcode() == ISD::AND) {
2112193323Sed    if (isa<ConstantSDNode>(Op.getOperand(1))) {
2113193323Sed      Mask = Op.getOperand(1);
2114193323Sed      Op = Op.getOperand(0);
2115193323Sed    } else {
2116193323Sed      return false;
2117193323Sed    }
2118193323Sed  }
2119193323Sed
2120193323Sed  if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
2121193323Sed    Shift = Op;
2122193323Sed    return true;
2123193323Sed  }
2124193323Sed
2125193323Sed  return false;
2126193323Sed}
2127193323Sed
2128193323Sed// MatchRotate - Handle an 'or' of two operands.  If this is one of the many
2129193323Sed// idioms for rotate, and if the target supports rotation instructions, generate
2130193323Sed// a rot[lr].
2131193323SedSDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, DebugLoc DL) {
2132193323Sed  // Must be a legal type.  Expanded 'n promoted things won't work with rotates.
2133198090Srdivacky  EVT VT = LHS.getValueType();
2134193323Sed  if (!TLI.isTypeLegal(VT)) return 0;
2135193323Sed
2136193323Sed  // The target must have at least one rotate flavor.
2137193323Sed  bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
2138193323Sed  bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
2139193323Sed  if (!HasROTL && !HasROTR) return 0;
2140193323Sed
2141193323Sed  // Match "(X shl/srl V1) & V2" where V2 may not be present.
2142193323Sed  SDValue LHSShift;   // The shift.
2143193323Sed  SDValue LHSMask;    // AND value if any.
2144193323Sed  if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
2145193323Sed    return 0; // Not part of a rotate.
2146193323Sed
2147193323Sed  SDValue RHSShift;   // The shift.
2148193323Sed  SDValue RHSMask;    // AND value if any.
2149193323Sed  if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
2150193323Sed    return 0; // Not part of a rotate.
2151193323Sed
2152193323Sed  if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
2153193323Sed    return 0;   // Not shifting the same value.
2154193323Sed
2155193323Sed  if (LHSShift.getOpcode() == RHSShift.getOpcode())
2156193323Sed    return 0;   // Shifts must disagree.
2157193323Sed
2158193323Sed  // Canonicalize shl to left side in a shl/srl pair.
2159193323Sed  if (RHSShift.getOpcode() == ISD::SHL) {
2160193323Sed    std::swap(LHS, RHS);
2161193323Sed    std::swap(LHSShift, RHSShift);
2162193323Sed    std::swap(LHSMask , RHSMask );
2163193323Sed  }
2164193323Sed
2165193323Sed  unsigned OpSizeInBits = VT.getSizeInBits();
2166193323Sed  SDValue LHSShiftArg = LHSShift.getOperand(0);
2167193323Sed  SDValue LHSShiftAmt = LHSShift.getOperand(1);
2168193323Sed  SDValue RHSShiftAmt = RHSShift.getOperand(1);
2169193323Sed
2170193323Sed  // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
2171193323Sed  // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
2172193323Sed  if (LHSShiftAmt.getOpcode() == ISD::Constant &&
2173193323Sed      RHSShiftAmt.getOpcode() == ISD::Constant) {
2174193323Sed    uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
2175193323Sed    uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
2176193323Sed    if ((LShVal + RShVal) != OpSizeInBits)
2177193323Sed      return 0;
2178193323Sed
2179193323Sed    SDValue Rot;
2180193323Sed    if (HasROTL)
2181193323Sed      Rot = DAG.getNode(ISD::ROTL, DL, VT, LHSShiftArg, LHSShiftAmt);
2182193323Sed    else
2183193323Sed      Rot = DAG.getNode(ISD::ROTR, DL, VT, LHSShiftArg, RHSShiftAmt);
2184193323Sed
2185193323Sed    // If there is an AND of either shifted operand, apply it to the result.
2186193323Sed    if (LHSMask.getNode() || RHSMask.getNode()) {
2187193323Sed      APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
2188193323Sed
2189193323Sed      if (LHSMask.getNode()) {
2190193323Sed        APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
2191193323Sed        Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
2192193323Sed      }
2193193323Sed      if (RHSMask.getNode()) {
2194193323Sed        APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
2195193323Sed        Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
2196193323Sed      }
2197193323Sed
2198193323Sed      Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, VT));
2199193323Sed    }
2200193323Sed
2201193323Sed    return Rot.getNode();
2202193323Sed  }
2203193323Sed
2204193323Sed  // If there is a mask here, and we have a variable shift, we can't be sure
2205193323Sed  // that we're masking out the right stuff.
2206193323Sed  if (LHSMask.getNode() || RHSMask.getNode())
2207193323Sed    return 0;
2208193323Sed
2209193323Sed  // fold (or (shl x, y), (srl x, (sub 32, y))) -> (rotl x, y)
2210193323Sed  // fold (or (shl x, y), (srl x, (sub 32, y))) -> (rotr x, (sub 32, y))
2211193323Sed  if (RHSShiftAmt.getOpcode() == ISD::SUB &&
2212193323Sed      LHSShiftAmt == RHSShiftAmt.getOperand(1)) {
2213193323Sed    if (ConstantSDNode *SUBC =
2214193323Sed          dyn_cast<ConstantSDNode>(RHSShiftAmt.getOperand(0))) {
2215193323Sed      if (SUBC->getAPIntValue() == OpSizeInBits) {
2216193323Sed        if (HasROTL)
2217193323Sed          return DAG.getNode(ISD::ROTL, DL, VT,
2218193323Sed                             LHSShiftArg, LHSShiftAmt).getNode();
2219193323Sed        else
2220193323Sed          return DAG.getNode(ISD::ROTR, DL, VT,
2221193323Sed                             LHSShiftArg, RHSShiftAmt).getNode();
2222193323Sed      }
2223193323Sed    }
2224193323Sed  }
2225193323Sed
2226193323Sed  // fold (or (shl x, (sub 32, y)), (srl x, r)) -> (rotr x, y)
2227193323Sed  // fold (or (shl x, (sub 32, y)), (srl x, r)) -> (rotl x, (sub 32, y))
2228193323Sed  if (LHSShiftAmt.getOpcode() == ISD::SUB &&
2229193323Sed      RHSShiftAmt == LHSShiftAmt.getOperand(1)) {
2230193323Sed    if (ConstantSDNode *SUBC =
2231193323Sed          dyn_cast<ConstantSDNode>(LHSShiftAmt.getOperand(0))) {
2232193323Sed      if (SUBC->getAPIntValue() == OpSizeInBits) {
2233193323Sed        if (HasROTR)
2234193323Sed          return DAG.getNode(ISD::ROTR, DL, VT,
2235193323Sed                             LHSShiftArg, RHSShiftAmt).getNode();
2236193323Sed        else
2237193323Sed          return DAG.getNode(ISD::ROTL, DL, VT,
2238193323Sed                             LHSShiftArg, LHSShiftAmt).getNode();
2239193323Sed      }
2240193323Sed    }
2241193323Sed  }
2242193323Sed
2243193323Sed  // Look for sign/zext/any-extended or truncate cases:
2244193323Sed  if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND
2245193323Sed       || LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND
2246193323Sed       || LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND
2247193323Sed       || LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
2248193323Sed      (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND
2249193323Sed       || RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND
2250193323Sed       || RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND
2251193323Sed       || RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
2252193323Sed    SDValue LExtOp0 = LHSShiftAmt.getOperand(0);
2253193323Sed    SDValue RExtOp0 = RHSShiftAmt.getOperand(0);
2254193323Sed    if (RExtOp0.getOpcode() == ISD::SUB &&
2255193323Sed        RExtOp0.getOperand(1) == LExtOp0) {
2256193323Sed      // fold (or (shl x, (*ext y)), (srl x, (*ext (sub 32, y)))) ->
2257193323Sed      //   (rotl x, y)
2258193323Sed      // fold (or (shl x, (*ext y)), (srl x, (*ext (sub 32, y)))) ->
2259193323Sed      //   (rotr x, (sub 32, y))
2260193323Sed      if (ConstantSDNode *SUBC =
2261193323Sed            dyn_cast<ConstantSDNode>(RExtOp0.getOperand(0))) {
2262193323Sed        if (SUBC->getAPIntValue() == OpSizeInBits) {
2263193323Sed          return DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
2264193323Sed                             LHSShiftArg,
2265193323Sed                             HasROTL ? LHSShiftAmt : RHSShiftAmt).getNode();
2266193323Sed        }
2267193323Sed      }
2268193323Sed    } else if (LExtOp0.getOpcode() == ISD::SUB &&
2269193323Sed               RExtOp0 == LExtOp0.getOperand(1)) {
2270193323Sed      // fold (or (shl x, (*ext (sub 32, y))), (srl x, (*ext y))) ->
2271193323Sed      //   (rotr x, y)
2272193323Sed      // fold (or (shl x, (*ext (sub 32, y))), (srl x, (*ext y))) ->
2273193323Sed      //   (rotl x, (sub 32, y))
2274193323Sed      if (ConstantSDNode *SUBC =
2275193323Sed            dyn_cast<ConstantSDNode>(LExtOp0.getOperand(0))) {
2276193323Sed        if (SUBC->getAPIntValue() == OpSizeInBits) {
2277193323Sed          return DAG.getNode(HasROTR ? ISD::ROTR : ISD::ROTL, DL, VT,
2278193323Sed                             LHSShiftArg,
2279193323Sed                             HasROTR ? RHSShiftAmt : LHSShiftAmt).getNode();
2280193323Sed        }
2281193323Sed      }
2282193323Sed    }
2283193323Sed  }
2284193323Sed
2285193323Sed  return 0;
2286193323Sed}
2287193323Sed
2288193323SedSDValue DAGCombiner::visitXOR(SDNode *N) {
2289193323Sed  SDValue N0 = N->getOperand(0);
2290193323Sed  SDValue N1 = N->getOperand(1);
2291193323Sed  SDValue LHS, RHS, CC;
2292193323Sed  ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2293193323Sed  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2294198090Srdivacky  EVT VT = N0.getValueType();
2295193323Sed
2296193323Sed  // fold vector ops
2297193323Sed  if (VT.isVector()) {
2298193323Sed    SDValue FoldedVOp = SimplifyVBinOp(N);
2299193323Sed    if (FoldedVOp.getNode()) return FoldedVOp;
2300193323Sed  }
2301193323Sed
2302193323Sed  // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
2303193323Sed  if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
2304193323Sed    return DAG.getConstant(0, VT);
2305193323Sed  // fold (xor x, undef) -> undef
2306193323Sed  if (N0.getOpcode() == ISD::UNDEF)
2307193323Sed    return N0;
2308193323Sed  if (N1.getOpcode() == ISD::UNDEF)
2309193323Sed    return N1;
2310193323Sed  // fold (xor c1, c2) -> c1^c2
2311193323Sed  if (N0C && N1C)
2312193323Sed    return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C);
2313193323Sed  // canonicalize constant to RHS
2314193323Sed  if (N0C && !N1C)
2315193323Sed    return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT, N1, N0);
2316193323Sed  // fold (xor x, 0) -> x
2317193323Sed  if (N1C && N1C->isNullValue())
2318193323Sed    return N0;
2319193323Sed  // reassociate xor
2320193323Sed  SDValue RXOR = ReassociateOps(ISD::XOR, N->getDebugLoc(), N0, N1);
2321193323Sed  if (RXOR.getNode() != 0)
2322193323Sed    return RXOR;
2323193323Sed
2324193323Sed  // fold !(x cc y) -> (x !cc y)
2325193323Sed  if (N1C && N1C->getAPIntValue() == 1 && isSetCCEquivalent(N0, LHS, RHS, CC)) {
2326193323Sed    bool isInt = LHS.getValueType().isInteger();
2327193323Sed    ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
2328193323Sed                                               isInt);
2329193323Sed
2330193323Sed    if (!LegalOperations || TLI.isCondCodeLegal(NotCC, LHS.getValueType())) {
2331193323Sed      switch (N0.getOpcode()) {
2332193323Sed      default:
2333198090Srdivacky        llvm_unreachable("Unhandled SetCC Equivalent!");
2334193323Sed      case ISD::SETCC:
2335193323Sed        return DAG.getSetCC(N->getDebugLoc(), VT, LHS, RHS, NotCC);
2336193323Sed      case ISD::SELECT_CC:
2337193323Sed        return DAG.getSelectCC(N->getDebugLoc(), LHS, RHS, N0.getOperand(2),
2338193323Sed                               N0.getOperand(3), NotCC);
2339193323Sed      }
2340193323Sed    }
2341193323Sed  }
2342193323Sed
2343193323Sed  // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
2344193323Sed  if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
2345193323Sed      N0.getNode()->hasOneUse() &&
2346193323Sed      isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
2347193323Sed    SDValue V = N0.getOperand(0);
2348193323Sed    V = DAG.getNode(ISD::XOR, N0.getDebugLoc(), V.getValueType(), V,
2349193323Sed                    DAG.getConstant(1, V.getValueType()));
2350193323Sed    AddToWorkList(V.getNode());
2351193323Sed    return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT, V);
2352193323Sed  }
2353193323Sed
2354193323Sed  // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
2355193323Sed  if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
2356193323Sed      (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
2357193323Sed    SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
2358193323Sed    if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
2359193323Sed      unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
2360193323Sed      LHS = DAG.getNode(ISD::XOR, LHS.getDebugLoc(), VT, LHS, N1); // LHS = ~LHS
2361193323Sed      RHS = DAG.getNode(ISD::XOR, RHS.getDebugLoc(), VT, RHS, N1); // RHS = ~RHS
2362193323Sed      AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
2363193323Sed      return DAG.getNode(NewOpcode, N->getDebugLoc(), VT, LHS, RHS);
2364193323Sed    }
2365193323Sed  }
2366193323Sed  // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
2367193323Sed  if (N1C && N1C->isAllOnesValue() &&
2368193323Sed      (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
2369193323Sed    SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
2370193323Sed    if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
2371193323Sed      unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
2372193323Sed      LHS = DAG.getNode(ISD::XOR, LHS.getDebugLoc(), VT, LHS, N1); // LHS = ~LHS
2373193323Sed      RHS = DAG.getNode(ISD::XOR, RHS.getDebugLoc(), VT, RHS, N1); // RHS = ~RHS
2374193323Sed      AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
2375193323Sed      return DAG.getNode(NewOpcode, N->getDebugLoc(), VT, LHS, RHS);
2376193323Sed    }
2377193323Sed  }
2378193323Sed  // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
2379193323Sed  if (N1C && N0.getOpcode() == ISD::XOR) {
2380193323Sed    ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
2381193323Sed    ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2382193323Sed    if (N00C)
2383193323Sed      return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT, N0.getOperand(1),
2384193323Sed                         DAG.getConstant(N1C->getAPIntValue() ^
2385193323Sed                                         N00C->getAPIntValue(), VT));
2386193323Sed    if (N01C)
2387193323Sed      return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT, N0.getOperand(0),
2388193323Sed                         DAG.getConstant(N1C->getAPIntValue() ^
2389193323Sed                                         N01C->getAPIntValue(), VT));
2390193323Sed  }
2391193323Sed  // fold (xor x, x) -> 0
2392193323Sed  if (N0 == N1) {
2393193323Sed    if (!VT.isVector()) {
2394193323Sed      return DAG.getConstant(0, VT);
2395193323Sed    } else if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT)){
2396193323Sed      // Produce a vector of zeros.
2397193323Sed      SDValue El = DAG.getConstant(0, VT.getVectorElementType());
2398193323Sed      std::vector<SDValue> Ops(VT.getVectorNumElements(), El);
2399193323Sed      return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(), VT,
2400193323Sed                         &Ops[0], Ops.size());
2401193323Sed    }
2402193323Sed  }
2403193323Sed
2404193323Sed  // Simplify: xor (op x...), (op y...)  -> (op (xor x, y))
2405193323Sed  if (N0.getOpcode() == N1.getOpcode()) {
2406193323Sed    SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
2407193323Sed    if (Tmp.getNode()) return Tmp;
2408193323Sed  }
2409193323Sed
2410193323Sed  // Simplify the expression using non-local knowledge.
2411193323Sed  if (!VT.isVector() &&
2412193323Sed      SimplifyDemandedBits(SDValue(N, 0)))
2413193323Sed    return SDValue(N, 0);
2414193323Sed
2415193323Sed  return SDValue();
2416193323Sed}
2417193323Sed
2418193323Sed/// visitShiftByConstant - Handle transforms common to the three shifts, when
2419193323Sed/// the shift amount is a constant.
2420193323SedSDValue DAGCombiner::visitShiftByConstant(SDNode *N, unsigned Amt) {
2421193323Sed  SDNode *LHS = N->getOperand(0).getNode();
2422193323Sed  if (!LHS->hasOneUse()) return SDValue();
2423193323Sed
2424193323Sed  // We want to pull some binops through shifts, so that we have (and (shift))
2425193323Sed  // instead of (shift (and)), likewise for add, or, xor, etc.  This sort of
2426193323Sed  // thing happens with address calculations, so it's important to canonicalize
2427193323Sed  // it.
2428193323Sed  bool HighBitSet = false;  // Can we transform this if the high bit is set?
2429193323Sed
2430193323Sed  switch (LHS->getOpcode()) {
2431193323Sed  default: return SDValue();
2432193323Sed  case ISD::OR:
2433193323Sed  case ISD::XOR:
2434193323Sed    HighBitSet = false; // We can only transform sra if the high bit is clear.
2435193323Sed    break;
2436193323Sed  case ISD::AND:
2437193323Sed    HighBitSet = true;  // We can only transform sra if the high bit is set.
2438193323Sed    break;
2439193323Sed  case ISD::ADD:
2440193323Sed    if (N->getOpcode() != ISD::SHL)
2441193323Sed      return SDValue(); // only shl(add) not sr[al](add).
2442193323Sed    HighBitSet = false; // We can only transform sra if the high bit is clear.
2443193323Sed    break;
2444193323Sed  }
2445193323Sed
2446193323Sed  // We require the RHS of the binop to be a constant as well.
2447193323Sed  ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
2448193323Sed  if (!BinOpCst) return SDValue();
2449193323Sed
2450193323Sed  // FIXME: disable this unless the input to the binop is a shift by a constant.
2451193323Sed  // If it is not a shift, it pessimizes some common cases like:
2452193323Sed  //
2453193323Sed  //    void foo(int *X, int i) { X[i & 1235] = 1; }
2454193323Sed  //    int bar(int *X, int i) { return X[i & 255]; }
2455193323Sed  SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
2456193323Sed  if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
2457193323Sed       BinOpLHSVal->getOpcode() != ISD::SRA &&
2458193323Sed       BinOpLHSVal->getOpcode() != ISD::SRL) ||
2459193323Sed      !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
2460193323Sed    return SDValue();
2461193323Sed
2462198090Srdivacky  EVT VT = N->getValueType(0);
2463193323Sed
2464193323Sed  // If this is a signed shift right, and the high bit is modified by the
2465193323Sed  // logical operation, do not perform the transformation. The highBitSet
2466193323Sed  // boolean indicates the value of the high bit of the constant which would
2467193323Sed  // cause it to be modified for this operation.
2468193323Sed  if (N->getOpcode() == ISD::SRA) {
2469193323Sed    bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
2470193323Sed    if (BinOpRHSSignSet != HighBitSet)
2471193323Sed      return SDValue();
2472193323Sed  }
2473193323Sed
2474193323Sed  // Fold the constants, shifting the binop RHS by the shift amount.
2475193323Sed  SDValue NewRHS = DAG.getNode(N->getOpcode(), LHS->getOperand(1).getDebugLoc(),
2476193323Sed                               N->getValueType(0),
2477193323Sed                               LHS->getOperand(1), N->getOperand(1));
2478193323Sed
2479193323Sed  // Create the new shift.
2480193323Sed  SDValue NewShift = DAG.getNode(N->getOpcode(), LHS->getOperand(0).getDebugLoc(),
2481193323Sed                                 VT, LHS->getOperand(0), N->getOperand(1));
2482193323Sed
2483193323Sed  // Create the new binop.
2484193323Sed  return DAG.getNode(LHS->getOpcode(), N->getDebugLoc(), VT, NewShift, NewRHS);
2485193323Sed}
2486193323Sed
2487193323SedSDValue DAGCombiner::visitSHL(SDNode *N) {
2488193323Sed  SDValue N0 = N->getOperand(0);
2489193323Sed  SDValue N1 = N->getOperand(1);
2490193323Sed  ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2491193323Sed  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2492198090Srdivacky  EVT VT = N0.getValueType();
2493200581Srdivacky  unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
2494193323Sed
2495193323Sed  // fold (shl c1, c2) -> c1<<c2
2496193323Sed  if (N0C && N1C)
2497193323Sed    return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C);
2498193323Sed  // fold (shl 0, x) -> 0
2499193323Sed  if (N0C && N0C->isNullValue())
2500193323Sed    return N0;
2501193323Sed  // fold (shl x, c >= size(x)) -> undef
2502193323Sed  if (N1C && N1C->getZExtValue() >= OpSizeInBits)
2503193323Sed    return DAG.getUNDEF(VT);
2504193323Sed  // fold (shl x, 0) -> x
2505193323Sed  if (N1C && N1C->isNullValue())
2506193323Sed    return N0;
2507193323Sed  // if (shl x, c) is known to be zero, return 0
2508193323Sed  if (DAG.MaskedValueIsZero(SDValue(N, 0),
2509200581Srdivacky                            APInt::getAllOnesValue(OpSizeInBits)))
2510193323Sed    return DAG.getConstant(0, VT);
2511193323Sed  // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
2512193323Sed  if (N1.getOpcode() == ISD::TRUNCATE &&
2513193323Sed      N1.getOperand(0).getOpcode() == ISD::AND &&
2514193323Sed      N1.hasOneUse() && N1.getOperand(0).hasOneUse()) {
2515193323Sed    SDValue N101 = N1.getOperand(0).getOperand(1);
2516193323Sed    if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) {
2517198090Srdivacky      EVT TruncVT = N1.getValueType();
2518193323Sed      SDValue N100 = N1.getOperand(0).getOperand(0);
2519193323Sed      APInt TruncC = N101C->getAPIntValue();
2520193323Sed      TruncC.trunc(TruncVT.getSizeInBits());
2521193323Sed      return DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, N0,
2522193323Sed                         DAG.getNode(ISD::AND, N->getDebugLoc(), TruncVT,
2523193323Sed                                     DAG.getNode(ISD::TRUNCATE,
2524193323Sed                                                 N->getDebugLoc(),
2525193323Sed                                                 TruncVT, N100),
2526193323Sed                                     DAG.getConstant(TruncC, TruncVT)));
2527193323Sed    }
2528193323Sed  }
2529193323Sed
2530193323Sed  if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
2531193323Sed    return SDValue(N, 0);
2532193323Sed
2533193323Sed  // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
2534193323Sed  if (N1C && N0.getOpcode() == ISD::SHL &&
2535193323Sed      N0.getOperand(1).getOpcode() == ISD::Constant) {
2536193323Sed    uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
2537193323Sed    uint64_t c2 = N1C->getZExtValue();
2538193323Sed    if (c1 + c2 > OpSizeInBits)
2539193323Sed      return DAG.getConstant(0, VT);
2540193323Sed    return DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, N0.getOperand(0),
2541193323Sed                       DAG.getConstant(c1 + c2, N1.getValueType()));
2542193323Sed  }
2543193323Sed  // fold (shl (srl x, c1), c2) -> (shl (and x, (shl -1, c1)), (sub c2, c1)) or
2544193323Sed  //                               (srl (and x, (shl -1, c1)), (sub c1, c2))
2545193323Sed  if (N1C && N0.getOpcode() == ISD::SRL &&
2546193323Sed      N0.getOperand(1).getOpcode() == ISD::Constant) {
2547193323Sed    uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
2548198090Srdivacky    if (c1 < VT.getSizeInBits()) {
2549198090Srdivacky      uint64_t c2 = N1C->getZExtValue();
2550198090Srdivacky      SDValue HiBitsMask =
2551198090Srdivacky        DAG.getConstant(APInt::getHighBitsSet(VT.getSizeInBits(),
2552198090Srdivacky                                              VT.getSizeInBits() - c1),
2553198090Srdivacky                        VT);
2554198090Srdivacky      SDValue Mask = DAG.getNode(ISD::AND, N0.getDebugLoc(), VT,
2555198090Srdivacky                                 N0.getOperand(0),
2556198090Srdivacky                                 HiBitsMask);
2557198090Srdivacky      if (c2 > c1)
2558198090Srdivacky        return DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, Mask,
2559198090Srdivacky                           DAG.getConstant(c2-c1, N1.getValueType()));
2560198090Srdivacky      else
2561198090Srdivacky        return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, Mask,
2562198090Srdivacky                           DAG.getConstant(c1-c2, N1.getValueType()));
2563198090Srdivacky    }
2564193323Sed  }
2565193323Sed  // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
2566198090Srdivacky  if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
2567198090Srdivacky    SDValue HiBitsMask =
2568198090Srdivacky      DAG.getConstant(APInt::getHighBitsSet(VT.getSizeInBits(),
2569198090Srdivacky                                            VT.getSizeInBits() -
2570198090Srdivacky                                              N1C->getZExtValue()),
2571198090Srdivacky                      VT);
2572193323Sed    return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0.getOperand(0),
2573198090Srdivacky                       HiBitsMask);
2574198090Srdivacky  }
2575193323Sed
2576193323Sed  return N1C ? visitShiftByConstant(N, N1C->getZExtValue()) : SDValue();
2577193323Sed}
2578193323Sed
2579193323SedSDValue DAGCombiner::visitSRA(SDNode *N) {
2580193323Sed  SDValue N0 = N->getOperand(0);
2581193323Sed  SDValue N1 = N->getOperand(1);
2582193323Sed  ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2583193323Sed  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2584198090Srdivacky  EVT VT = N0.getValueType();
2585200581Srdivacky  unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
2586193323Sed
2587193323Sed  // fold (sra c1, c2) -> (sra c1, c2)
2588193323Sed  if (N0C && N1C)
2589193323Sed    return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C);
2590193323Sed  // fold (sra 0, x) -> 0
2591193323Sed  if (N0C && N0C->isNullValue())
2592193323Sed    return N0;
2593193323Sed  // fold (sra -1, x) -> -1
2594193323Sed  if (N0C && N0C->isAllOnesValue())
2595193323Sed    return N0;
2596193323Sed  // fold (sra x, (setge c, size(x))) -> undef
2597200581Srdivacky  if (N1C && N1C->getZExtValue() >= OpSizeInBits)
2598193323Sed    return DAG.getUNDEF(VT);
2599193323Sed  // fold (sra x, 0) -> x
2600193323Sed  if (N1C && N1C->isNullValue())
2601193323Sed    return N0;
2602193323Sed  // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
2603193323Sed  // sext_inreg.
2604193323Sed  if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
2605200581Srdivacky    unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
2606202375Srdivacky    EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
2607202375Srdivacky    if (VT.isVector())
2608202375Srdivacky      ExtVT = EVT::getVectorVT(*DAG.getContext(),
2609202375Srdivacky                               ExtVT, VT.getVectorNumElements());
2610202375Srdivacky    if ((!LegalOperations ||
2611202375Srdivacky         TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
2612193323Sed      return DAG.getNode(ISD::SIGN_EXTEND_INREG, N->getDebugLoc(), VT,
2613202375Srdivacky                         N0.getOperand(0), DAG.getValueType(ExtVT));
2614193323Sed  }
2615193323Sed
2616193323Sed  // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
2617193323Sed  if (N1C && N0.getOpcode() == ISD::SRA) {
2618193323Sed    if (ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2619193323Sed      unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
2620200581Srdivacky      if (Sum >= OpSizeInBits) Sum = OpSizeInBits-1;
2621193323Sed      return DAG.getNode(ISD::SRA, N->getDebugLoc(), VT, N0.getOperand(0),
2622193323Sed                         DAG.getConstant(Sum, N1C->getValueType(0)));
2623193323Sed    }
2624193323Sed  }
2625193323Sed
2626193323Sed  // fold (sra (shl X, m), (sub result_size, n))
2627193323Sed  // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
2628193323Sed  // result_size - n != m.
2629193323Sed  // If truncate is free for the target sext(shl) is likely to result in better
2630193323Sed  // code.
2631193323Sed  if (N0.getOpcode() == ISD::SHL) {
2632193323Sed    // Get the two constanst of the shifts, CN0 = m, CN = n.
2633193323Sed    const ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2634193323Sed    if (N01C && N1C) {
2635193323Sed      // Determine what the truncate's result bitsize and type would be.
2636198090Srdivacky      EVT TruncVT =
2637200581Srdivacky        EVT::getIntegerVT(*DAG.getContext(), OpSizeInBits - N1C->getZExtValue());
2638193323Sed      // Determine the residual right-shift amount.
2639193323Sed      signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
2640193323Sed
2641193323Sed      // If the shift is not a no-op (in which case this should be just a sign
2642193323Sed      // extend already), the truncated to type is legal, sign_extend is legal
2643193323Sed      // on that type, and the the truncate to that type is both legal and free,
2644193323Sed      // perform the transform.
2645193323Sed      if ((ShiftAmt > 0) &&
2646193323Sed          TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
2647193323Sed          TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
2648193323Sed          TLI.isTruncateFree(VT, TruncVT)) {
2649193323Sed
2650193323Sed          SDValue Amt = DAG.getConstant(ShiftAmt, getShiftAmountTy());
2651193323Sed          SDValue Shift = DAG.getNode(ISD::SRL, N0.getDebugLoc(), VT,
2652193323Sed                                      N0.getOperand(0), Amt);
2653193323Sed          SDValue Trunc = DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(), TruncVT,
2654193323Sed                                      Shift);
2655193323Sed          return DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(),
2656193323Sed                             N->getValueType(0), Trunc);
2657193323Sed      }
2658193323Sed    }
2659193323Sed  }
2660193323Sed
2661193323Sed  // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
2662193323Sed  if (N1.getOpcode() == ISD::TRUNCATE &&
2663193323Sed      N1.getOperand(0).getOpcode() == ISD::AND &&
2664193323Sed      N1.hasOneUse() && N1.getOperand(0).hasOneUse()) {
2665193323Sed    SDValue N101 = N1.getOperand(0).getOperand(1);
2666193323Sed    if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) {
2667198090Srdivacky      EVT TruncVT = N1.getValueType();
2668193323Sed      SDValue N100 = N1.getOperand(0).getOperand(0);
2669193323Sed      APInt TruncC = N101C->getAPIntValue();
2670200581Srdivacky      TruncC.trunc(TruncVT.getScalarType().getSizeInBits());
2671193323Sed      return DAG.getNode(ISD::SRA, N->getDebugLoc(), VT, N0,
2672193323Sed                         DAG.getNode(ISD::AND, N->getDebugLoc(),
2673193323Sed                                     TruncVT,
2674193323Sed                                     DAG.getNode(ISD::TRUNCATE,
2675193323Sed                                                 N->getDebugLoc(),
2676193323Sed                                                 TruncVT, N100),
2677193323Sed                                     DAG.getConstant(TruncC, TruncVT)));
2678193323Sed    }
2679193323Sed  }
2680193323Sed
2681193323Sed  // Simplify, based on bits shifted out of the LHS.
2682193323Sed  if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
2683193323Sed    return SDValue(N, 0);
2684193323Sed
2685193323Sed
2686193323Sed  // If the sign bit is known to be zero, switch this to a SRL.
2687193323Sed  if (DAG.SignBitIsZero(N0))
2688193323Sed    return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0, N1);
2689193323Sed
2690193323Sed  return N1C ? visitShiftByConstant(N, N1C->getZExtValue()) : SDValue();
2691193323Sed}
2692193323Sed
2693193323SedSDValue DAGCombiner::visitSRL(SDNode *N) {
2694193323Sed  SDValue N0 = N->getOperand(0);
2695193323Sed  SDValue N1 = N->getOperand(1);
2696193323Sed  ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2697193323Sed  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2698198090Srdivacky  EVT VT = N0.getValueType();
2699200581Srdivacky  unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
2700193323Sed
2701193323Sed  // fold (srl c1, c2) -> c1 >>u c2
2702193323Sed  if (N0C && N1C)
2703193323Sed    return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C);
2704193323Sed  // fold (srl 0, x) -> 0
2705193323Sed  if (N0C && N0C->isNullValue())
2706193323Sed    return N0;
2707193323Sed  // fold (srl x, c >= size(x)) -> undef
2708193323Sed  if (N1C && N1C->getZExtValue() >= OpSizeInBits)
2709193323Sed    return DAG.getUNDEF(VT);
2710193323Sed  // fold (srl x, 0) -> x
2711193323Sed  if (N1C && N1C->isNullValue())
2712193323Sed    return N0;
2713193323Sed  // if (srl x, c) is known to be zero, return 0
2714193323Sed  if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
2715193323Sed                                   APInt::getAllOnesValue(OpSizeInBits)))
2716193323Sed    return DAG.getConstant(0, VT);
2717193323Sed
2718193323Sed  // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
2719193323Sed  if (N1C && N0.getOpcode() == ISD::SRL &&
2720193323Sed      N0.getOperand(1).getOpcode() == ISD::Constant) {
2721193323Sed    uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
2722193323Sed    uint64_t c2 = N1C->getZExtValue();
2723193323Sed    if (c1 + c2 > OpSizeInBits)
2724193323Sed      return DAG.getConstant(0, VT);
2725193323Sed    return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0.getOperand(0),
2726193323Sed                       DAG.getConstant(c1 + c2, N1.getValueType()));
2727193323Sed  }
2728193323Sed
2729193323Sed  // fold (srl (anyextend x), c) -> (anyextend (srl x, c))
2730193323Sed  if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2731193323Sed    // Shifting in all undef bits?
2732198090Srdivacky    EVT SmallVT = N0.getOperand(0).getValueType();
2733193323Sed    if (N1C->getZExtValue() >= SmallVT.getSizeInBits())
2734193323Sed      return DAG.getUNDEF(VT);
2735193323Sed
2736193323Sed    SDValue SmallShift = DAG.getNode(ISD::SRL, N0.getDebugLoc(), SmallVT,
2737193323Sed                                     N0.getOperand(0), N1);
2738193323Sed    AddToWorkList(SmallShift.getNode());
2739193323Sed    return DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, SmallShift);
2740193323Sed  }
2741193323Sed
2742193323Sed  // fold (srl (sra X, Y), 31) -> (srl X, 31).  This srl only looks at the sign
2743193323Sed  // bit, which is unmodified by sra.
2744193323Sed  if (N1C && N1C->getZExtValue() + 1 == VT.getSizeInBits()) {
2745193323Sed    if (N0.getOpcode() == ISD::SRA)
2746193323Sed      return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0.getOperand(0), N1);
2747193323Sed  }
2748193323Sed
2749193323Sed  // fold (srl (ctlz x), "5") -> x  iff x has one bit set (the low bit).
2750193323Sed  if (N1C && N0.getOpcode() == ISD::CTLZ &&
2751193323Sed      N1C->getAPIntValue() == Log2_32(VT.getSizeInBits())) {
2752193323Sed    APInt KnownZero, KnownOne;
2753193323Sed    APInt Mask = APInt::getAllOnesValue(VT.getSizeInBits());
2754193323Sed    DAG.ComputeMaskedBits(N0.getOperand(0), Mask, KnownZero, KnownOne);
2755193323Sed
2756193323Sed    // If any of the input bits are KnownOne, then the input couldn't be all
2757193323Sed    // zeros, thus the result of the srl will always be zero.
2758193323Sed    if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT);
2759193323Sed
2760193323Sed    // If all of the bits input the to ctlz node are known to be zero, then
2761193323Sed    // the result of the ctlz is "32" and the result of the shift is one.
2762193323Sed    APInt UnknownBits = ~KnownZero & Mask;
2763193323Sed    if (UnknownBits == 0) return DAG.getConstant(1, VT);
2764193323Sed
2765193323Sed    // Otherwise, check to see if there is exactly one bit input to the ctlz.
2766193323Sed    if ((UnknownBits & (UnknownBits - 1)) == 0) {
2767193323Sed      // Okay, we know that only that the single bit specified by UnknownBits
2768193323Sed      // could be set on input to the CTLZ node. If this bit is set, the SRL
2769193323Sed      // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
2770193323Sed      // to an SRL/XOR pair, which is likely to simplify more.
2771193323Sed      unsigned ShAmt = UnknownBits.countTrailingZeros();
2772193323Sed      SDValue Op = N0.getOperand(0);
2773193323Sed
2774193323Sed      if (ShAmt) {
2775193323Sed        Op = DAG.getNode(ISD::SRL, N0.getDebugLoc(), VT, Op,
2776193323Sed                         DAG.getConstant(ShAmt, getShiftAmountTy()));
2777193323Sed        AddToWorkList(Op.getNode());
2778193323Sed      }
2779193323Sed
2780193323Sed      return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT,
2781193323Sed                         Op, DAG.getConstant(1, VT));
2782193323Sed    }
2783193323Sed  }
2784193323Sed
2785193323Sed  // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
2786193323Sed  if (N1.getOpcode() == ISD::TRUNCATE &&
2787193323Sed      N1.getOperand(0).getOpcode() == ISD::AND &&
2788193323Sed      N1.hasOneUse() && N1.getOperand(0).hasOneUse()) {
2789193323Sed    SDValue N101 = N1.getOperand(0).getOperand(1);
2790193323Sed    if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) {
2791198090Srdivacky      EVT TruncVT = N1.getValueType();
2792193323Sed      SDValue N100 = N1.getOperand(0).getOperand(0);
2793193323Sed      APInt TruncC = N101C->getAPIntValue();
2794193323Sed      TruncC.trunc(TruncVT.getSizeInBits());
2795193323Sed      return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0,
2796193323Sed                         DAG.getNode(ISD::AND, N->getDebugLoc(),
2797193323Sed                                     TruncVT,
2798193323Sed                                     DAG.getNode(ISD::TRUNCATE,
2799193323Sed                                                 N->getDebugLoc(),
2800193323Sed                                                 TruncVT, N100),
2801193323Sed                                     DAG.getConstant(TruncC, TruncVT)));
2802193323Sed    }
2803193323Sed  }
2804193323Sed
2805193323Sed  // fold operands of srl based on knowledge that the low bits are not
2806193323Sed  // demanded.
2807193323Sed  if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
2808193323Sed    return SDValue(N, 0);
2809193323Sed
2810201360Srdivacky  if (N1C) {
2811201360Srdivacky    SDValue NewSRL = visitShiftByConstant(N, N1C->getZExtValue());
2812201360Srdivacky    if (NewSRL.getNode())
2813201360Srdivacky      return NewSRL;
2814201360Srdivacky  }
2815201360Srdivacky
2816201360Srdivacky  // Here is a common situation. We want to optimize:
2817201360Srdivacky  //
2818201360Srdivacky  //   %a = ...
2819201360Srdivacky  //   %b = and i32 %a, 2
2820201360Srdivacky  //   %c = srl i32 %b, 1
2821201360Srdivacky  //   brcond i32 %c ...
2822201360Srdivacky  //
2823201360Srdivacky  // into
2824201360Srdivacky  //
2825201360Srdivacky  //   %a = ...
2826201360Srdivacky  //   %b = and %a, 2
2827201360Srdivacky  //   %c = setcc eq %b, 0
2828201360Srdivacky  //   brcond %c ...
2829201360Srdivacky  //
2830201360Srdivacky  // However when after the source operand of SRL is optimized into AND, the SRL
2831201360Srdivacky  // itself may not be optimized further. Look for it and add the BRCOND into
2832201360Srdivacky  // the worklist.
2833202375Srdivacky  if (N->hasOneUse()) {
2834202375Srdivacky    SDNode *Use = *N->use_begin();
2835202375Srdivacky    if (Use->getOpcode() == ISD::BRCOND)
2836202375Srdivacky      AddToWorkList(Use);
2837202375Srdivacky    else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
2838202375Srdivacky      // Also look pass the truncate.
2839202375Srdivacky      Use = *Use->use_begin();
2840202375Srdivacky      if (Use->getOpcode() == ISD::BRCOND)
2841202375Srdivacky        AddToWorkList(Use);
2842202375Srdivacky    }
2843202375Srdivacky  }
2844201360Srdivacky
2845201360Srdivacky  return SDValue();
2846193323Sed}
2847193323Sed
2848193323SedSDValue DAGCombiner::visitCTLZ(SDNode *N) {
2849193323Sed  SDValue N0 = N->getOperand(0);
2850198090Srdivacky  EVT VT = N->getValueType(0);
2851193323Sed
2852193323Sed  // fold (ctlz c1) -> c2
2853193323Sed  if (isa<ConstantSDNode>(N0))
2854193323Sed    return DAG.getNode(ISD::CTLZ, N->getDebugLoc(), VT, N0);
2855193323Sed  return SDValue();
2856193323Sed}
2857193323Sed
2858193323SedSDValue DAGCombiner::visitCTTZ(SDNode *N) {
2859193323Sed  SDValue N0 = N->getOperand(0);
2860198090Srdivacky  EVT VT = N->getValueType(0);
2861193323Sed
2862193323Sed  // fold (cttz c1) -> c2
2863193323Sed  if (isa<ConstantSDNode>(N0))
2864193323Sed    return DAG.getNode(ISD::CTTZ, N->getDebugLoc(), VT, N0);
2865193323Sed  return SDValue();
2866193323Sed}
2867193323Sed
2868193323SedSDValue DAGCombiner::visitCTPOP(SDNode *N) {
2869193323Sed  SDValue N0 = N->getOperand(0);
2870198090Srdivacky  EVT VT = N->getValueType(0);
2871193323Sed
2872193323Sed  // fold (ctpop c1) -> c2
2873193323Sed  if (isa<ConstantSDNode>(N0))
2874193323Sed    return DAG.getNode(ISD::CTPOP, N->getDebugLoc(), VT, N0);
2875193323Sed  return SDValue();
2876193323Sed}
2877193323Sed
2878193323SedSDValue DAGCombiner::visitSELECT(SDNode *N) {
2879193323Sed  SDValue N0 = N->getOperand(0);
2880193323Sed  SDValue N1 = N->getOperand(1);
2881193323Sed  SDValue N2 = N->getOperand(2);
2882193323Sed  ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2883193323Sed  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2884193323Sed  ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
2885198090Srdivacky  EVT VT = N->getValueType(0);
2886198090Srdivacky  EVT VT0 = N0.getValueType();
2887193323Sed
2888193323Sed  // fold (select C, X, X) -> X
2889193323Sed  if (N1 == N2)
2890193323Sed    return N1;
2891193323Sed  // fold (select true, X, Y) -> X
2892193323Sed  if (N0C && !N0C->isNullValue())
2893193323Sed    return N1;
2894193323Sed  // fold (select false, X, Y) -> Y
2895193323Sed  if (N0C && N0C->isNullValue())
2896193323Sed    return N2;
2897193323Sed  // fold (select C, 1, X) -> (or C, X)
2898193323Sed  if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
2899193323Sed    return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, N0, N2);
2900193323Sed  // fold (select C, 0, 1) -> (xor C, 1)
2901193323Sed  if (VT.isInteger() &&
2902193323Sed      (VT0 == MVT::i1 ||
2903193323Sed       (VT0.isInteger() &&
2904193323Sed        TLI.getBooleanContents() == TargetLowering::ZeroOrOneBooleanContent)) &&
2905193323Sed      N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
2906193323Sed    SDValue XORNode;
2907193323Sed    if (VT == VT0)
2908193323Sed      return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT0,
2909193323Sed                         N0, DAG.getConstant(1, VT0));
2910193323Sed    XORNode = DAG.getNode(ISD::XOR, N0.getDebugLoc(), VT0,
2911193323Sed                          N0, DAG.getConstant(1, VT0));
2912193323Sed    AddToWorkList(XORNode.getNode());
2913193323Sed    if (VT.bitsGT(VT0))
2914193323Sed      return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT, XORNode);
2915193323Sed    return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, XORNode);
2916193323Sed  }
2917193323Sed  // fold (select C, 0, X) -> (and (not C), X)
2918193323Sed  if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
2919193323Sed    SDValue NOTNode = DAG.getNOT(N0.getDebugLoc(), N0, VT);
2920193323Sed    AddToWorkList(NOTNode.getNode());
2921193323Sed    return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, NOTNode, N2);
2922193323Sed  }
2923193323Sed  // fold (select C, X, 1) -> (or (not C), X)
2924193323Sed  if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
2925193323Sed    SDValue NOTNode = DAG.getNOT(N0.getDebugLoc(), N0, VT);
2926193323Sed    AddToWorkList(NOTNode.getNode());
2927193323Sed    return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, NOTNode, N1);
2928193323Sed  }
2929193323Sed  // fold (select C, X, 0) -> (and C, X)
2930193323Sed  if (VT == MVT::i1 && N2C && N2C->isNullValue())
2931193323Sed    return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0, N1);
2932193323Sed  // fold (select X, X, Y) -> (or X, Y)
2933193323Sed  // fold (select X, 1, Y) -> (or X, Y)
2934193323Sed  if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1)))
2935193323Sed    return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, N0, N2);
2936193323Sed  // fold (select X, Y, X) -> (and X, Y)
2937193323Sed  // fold (select X, Y, 0) -> (and X, Y)
2938193323Sed  if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0)))
2939193323Sed    return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0, N1);
2940193323Sed
2941193323Sed  // If we can fold this based on the true/false value, do so.
2942193323Sed  if (SimplifySelectOps(N, N1, N2))
2943193323Sed    return SDValue(N, 0);  // Don't revisit N.
2944193323Sed
2945193323Sed  // fold selects based on a setcc into other things, such as min/max/abs
2946193323Sed  if (N0.getOpcode() == ISD::SETCC) {
2947193323Sed    // FIXME:
2948193323Sed    // Check against MVT::Other for SELECT_CC, which is a workaround for targets
2949193323Sed    // having to say they don't support SELECT_CC on every type the DAG knows
2950193323Sed    // about, since there is no way to mark an opcode illegal at all value types
2951198090Srdivacky    if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other) &&
2952198090Srdivacky        TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT))
2953193323Sed      return DAG.getNode(ISD::SELECT_CC, N->getDebugLoc(), VT,
2954193323Sed                         N0.getOperand(0), N0.getOperand(1),
2955193323Sed                         N1, N2, N0.getOperand(2));
2956193323Sed    return SimplifySelect(N->getDebugLoc(), N0, N1, N2);
2957193323Sed  }
2958193323Sed
2959193323Sed  return SDValue();
2960193323Sed}
2961193323Sed
2962193323SedSDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
2963193323Sed  SDValue N0 = N->getOperand(0);
2964193323Sed  SDValue N1 = N->getOperand(1);
2965193323Sed  SDValue N2 = N->getOperand(2);
2966193323Sed  SDValue N3 = N->getOperand(3);
2967193323Sed  SDValue N4 = N->getOperand(4);
2968193323Sed  ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
2969193323Sed
2970193323Sed  // fold select_cc lhs, rhs, x, x, cc -> x
2971193323Sed  if (N2 == N3)
2972193323Sed    return N2;
2973193323Sed
2974193323Sed  // Determine if the condition we're dealing with is constant
2975193323Sed  SDValue SCC = SimplifySetCC(TLI.getSetCCResultType(N0.getValueType()),
2976193323Sed                              N0, N1, CC, N->getDebugLoc(), false);
2977193323Sed  if (SCC.getNode()) AddToWorkList(SCC.getNode());
2978193323Sed
2979193323Sed  if (ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode())) {
2980193323Sed    if (!SCCC->isNullValue())
2981193323Sed      return N2;    // cond always true -> true val
2982193323Sed    else
2983193323Sed      return N3;    // cond always false -> false val
2984193323Sed  }
2985193323Sed
2986193323Sed  // Fold to a simpler select_cc
2987193323Sed  if (SCC.getNode() && SCC.getOpcode() == ISD::SETCC)
2988193323Sed    return DAG.getNode(ISD::SELECT_CC, N->getDebugLoc(), N2.getValueType(),
2989193323Sed                       SCC.getOperand(0), SCC.getOperand(1), N2, N3,
2990193323Sed                       SCC.getOperand(2));
2991193323Sed
2992193323Sed  // If we can fold this based on the true/false value, do so.
2993193323Sed  if (SimplifySelectOps(N, N2, N3))
2994193323Sed    return SDValue(N, 0);  // Don't revisit N.
2995193323Sed
2996193323Sed  // fold select_cc into other things, such as min/max/abs
2997193323Sed  return SimplifySelectCC(N->getDebugLoc(), N0, N1, N2, N3, CC);
2998193323Sed}
2999193323Sed
3000193323SedSDValue DAGCombiner::visitSETCC(SDNode *N) {
3001193323Sed  return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
3002193323Sed                       cast<CondCodeSDNode>(N->getOperand(2))->get(),
3003193323Sed                       N->getDebugLoc());
3004193323Sed}
3005193323Sed
3006193323Sed// ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
3007193323Sed// "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
3008193323Sed// transformation. Returns true if extension are possible and the above
3009193323Sed// mentioned transformation is profitable.
3010193323Sedstatic bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
3011193323Sed                                    unsigned ExtOpc,
3012193323Sed                                    SmallVector<SDNode*, 4> &ExtendNodes,
3013193323Sed                                    const TargetLowering &TLI) {
3014193323Sed  bool HasCopyToRegUses = false;
3015193323Sed  bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
3016193323Sed  for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
3017193323Sed                            UE = N0.getNode()->use_end();
3018193323Sed       UI != UE; ++UI) {
3019193323Sed    SDNode *User = *UI;
3020193323Sed    if (User == N)
3021193323Sed      continue;
3022193323Sed    if (UI.getUse().getResNo() != N0.getResNo())
3023193323Sed      continue;
3024193323Sed    // FIXME: Only extend SETCC N, N and SETCC N, c for now.
3025193323Sed    if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
3026193323Sed      ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
3027193323Sed      if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
3028193323Sed        // Sign bits will be lost after a zext.
3029193323Sed        return false;
3030193323Sed      bool Add = false;
3031193323Sed      for (unsigned i = 0; i != 2; ++i) {
3032193323Sed        SDValue UseOp = User->getOperand(i);
3033193323Sed        if (UseOp == N0)
3034193323Sed          continue;
3035193323Sed        if (!isa<ConstantSDNode>(UseOp))
3036193323Sed          return false;
3037193323Sed        Add = true;
3038193323Sed      }
3039193323Sed      if (Add)
3040193323Sed        ExtendNodes.push_back(User);
3041193323Sed      continue;
3042193323Sed    }
3043193323Sed    // If truncates aren't free and there are users we can't
3044193323Sed    // extend, it isn't worthwhile.
3045193323Sed    if (!isTruncFree)
3046193323Sed      return false;
3047193323Sed    // Remember if this value is live-out.
3048193323Sed    if (User->getOpcode() == ISD::CopyToReg)
3049193323Sed      HasCopyToRegUses = true;
3050193323Sed  }
3051193323Sed
3052193323Sed  if (HasCopyToRegUses) {
3053193323Sed    bool BothLiveOut = false;
3054193323Sed    for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
3055193323Sed         UI != UE; ++UI) {
3056193323Sed      SDUse &Use = UI.getUse();
3057193323Sed      if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
3058193323Sed        BothLiveOut = true;
3059193323Sed        break;
3060193323Sed      }
3061193323Sed    }
3062193323Sed    if (BothLiveOut)
3063193323Sed      // Both unextended and extended values are live out. There had better be
3064193323Sed      // good a reason for the transformation.
3065193323Sed      return ExtendNodes.size();
3066193323Sed  }
3067193323Sed  return true;
3068193323Sed}
3069193323Sed
3070193323SedSDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
3071193323Sed  SDValue N0 = N->getOperand(0);
3072198090Srdivacky  EVT VT = N->getValueType(0);
3073193323Sed
3074193323Sed  // fold (sext c1) -> c1
3075193323Sed  if (isa<ConstantSDNode>(N0))
3076193323Sed    return DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(), VT, N0);
3077193323Sed
3078193323Sed  // fold (sext (sext x)) -> (sext x)
3079193323Sed  // fold (sext (aext x)) -> (sext x)
3080193323Sed  if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
3081193323Sed    return DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(), VT,
3082193323Sed                       N0.getOperand(0));
3083193323Sed
3084193323Sed  if (N0.getOpcode() == ISD::TRUNCATE) {
3085193323Sed    // fold (sext (truncate (load x))) -> (sext (smaller load x))
3086193323Sed    // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
3087193323Sed    SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
3088193323Sed    if (NarrowLoad.getNode()) {
3089193323Sed      if (NarrowLoad.getNode() != N0.getNode())
3090193323Sed        CombineTo(N0.getNode(), NarrowLoad);
3091193323Sed      return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3092193323Sed    }
3093193323Sed
3094193323Sed    // See if the value being truncated is already sign extended.  If so, just
3095193323Sed    // eliminate the trunc/sext pair.
3096193323Sed    SDValue Op = N0.getOperand(0);
3097202375Srdivacky    unsigned OpBits   = Op.getValueType().getScalarType().getSizeInBits();
3098202375Srdivacky    unsigned MidBits  = N0.getValueType().getScalarType().getSizeInBits();
3099202375Srdivacky    unsigned DestBits = VT.getScalarType().getSizeInBits();
3100193323Sed    unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
3101193323Sed
3102193323Sed    if (OpBits == DestBits) {
3103193323Sed      // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
3104193323Sed      // bits, it is already ready.
3105193323Sed      if (NumSignBits > DestBits-MidBits)
3106193323Sed        return Op;
3107193323Sed    } else if (OpBits < DestBits) {
3108193323Sed      // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
3109193323Sed      // bits, just sext from i32.
3110193323Sed      if (NumSignBits > OpBits-MidBits)
3111193323Sed        return DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(), VT, Op);
3112193323Sed    } else {
3113193323Sed      // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
3114193323Sed      // bits, just truncate to i32.
3115193323Sed      if (NumSignBits > OpBits-MidBits)
3116193323Sed        return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, Op);
3117193323Sed    }
3118193323Sed
3119193323Sed    // fold (sext (truncate x)) -> (sextinreg x).
3120193323Sed    if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
3121193323Sed                                                 N0.getValueType())) {
3122202375Srdivacky      if (OpBits < DestBits)
3123193323Sed        Op = DAG.getNode(ISD::ANY_EXTEND, N0.getDebugLoc(), VT, Op);
3124202375Srdivacky      else if (OpBits > DestBits)
3125193323Sed        Op = DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(), VT, Op);
3126193323Sed      return DAG.getNode(ISD::SIGN_EXTEND_INREG, N->getDebugLoc(), VT, Op,
3127202375Srdivacky                         DAG.getValueType(N0.getValueType()));
3128193323Sed    }
3129193323Sed  }
3130193323Sed
3131193323Sed  // fold (sext (load x)) -> (sext (truncate (sextload x)))
3132193323Sed  if (ISD::isNON_EXTLoad(N0.getNode()) &&
3133193323Sed      ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
3134193323Sed       TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()))) {
3135193323Sed    bool DoXform = true;
3136193323Sed    SmallVector<SDNode*, 4> SetCCs;
3137193323Sed    if (!N0.hasOneUse())
3138193323Sed      DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
3139193323Sed    if (DoXform) {
3140193323Sed      LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3141193323Sed      SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, N->getDebugLoc(), VT,
3142193323Sed                                       LN0->getChain(),
3143193323Sed                                       LN0->getBasePtr(), LN0->getSrcValue(),
3144193323Sed                                       LN0->getSrcValueOffset(),
3145193323Sed                                       N0.getValueType(),
3146193323Sed                                       LN0->isVolatile(), LN0->getAlignment());
3147193323Sed      CombineTo(N, ExtLoad);
3148193323Sed      SDValue Trunc = DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(),
3149193323Sed                                  N0.getValueType(), ExtLoad);
3150193323Sed      CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
3151193323Sed
3152193323Sed      // Extend SetCC uses if necessary.
3153193323Sed      for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
3154193323Sed        SDNode *SetCC = SetCCs[i];
3155193323Sed        SmallVector<SDValue, 4> Ops;
3156193323Sed
3157193323Sed        for (unsigned j = 0; j != 2; ++j) {
3158193323Sed          SDValue SOp = SetCC->getOperand(j);
3159193323Sed          if (SOp == Trunc)
3160193323Sed            Ops.push_back(ExtLoad);
3161193323Sed          else
3162193323Sed            Ops.push_back(DAG.getNode(ISD::SIGN_EXTEND,
3163193323Sed                                      N->getDebugLoc(), VT, SOp));
3164193323Sed        }
3165193323Sed
3166193323Sed        Ops.push_back(SetCC->getOperand(2));
3167193323Sed        CombineTo(SetCC, DAG.getNode(ISD::SETCC, N->getDebugLoc(),
3168193323Sed                                     SetCC->getValueType(0),
3169193323Sed                                     &Ops[0], Ops.size()));
3170193323Sed      }
3171193323Sed
3172193323Sed      return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3173193323Sed    }
3174193323Sed  }
3175193323Sed
3176193323Sed  // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
3177193323Sed  // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
3178193323Sed  if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
3179193323Sed      ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
3180193323Sed    LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3181198090Srdivacky    EVT MemVT = LN0->getMemoryVT();
3182193323Sed    if ((!LegalOperations && !LN0->isVolatile()) ||
3183198090Srdivacky        TLI.isLoadExtLegal(ISD::SEXTLOAD, MemVT)) {
3184193323Sed      SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, N->getDebugLoc(), VT,
3185193323Sed                                       LN0->getChain(),
3186193323Sed                                       LN0->getBasePtr(), LN0->getSrcValue(),
3187198090Srdivacky                                       LN0->getSrcValueOffset(), MemVT,
3188193323Sed                                       LN0->isVolatile(), LN0->getAlignment());
3189193323Sed      CombineTo(N, ExtLoad);
3190193323Sed      CombineTo(N0.getNode(),
3191193323Sed                DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(),
3192193323Sed                            N0.getValueType(), ExtLoad),
3193193323Sed                ExtLoad.getValue(1));
3194193323Sed      return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3195193323Sed    }
3196193323Sed  }
3197193323Sed
3198193323Sed  if (N0.getOpcode() == ISD::SETCC) {
3199198090Srdivacky    // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
3200198090Srdivacky    if (VT.isVector() &&
3201198090Srdivacky        // We know that the # elements of the results is the same as the
3202198090Srdivacky        // # elements of the compare (and the # elements of the compare result
3203198090Srdivacky        // for that matter).  Check to see that they are the same size.  If so,
3204198090Srdivacky        // we know that the element size of the sext'd result matches the
3205198090Srdivacky        // element size of the compare operands.
3206198090Srdivacky        VT.getSizeInBits() == N0.getOperand(0).getValueType().getSizeInBits() &&
3207198090Srdivacky
3208198090Srdivacky        // Only do this before legalize for now.
3209198090Srdivacky        !LegalOperations) {
3210198090Srdivacky      return DAG.getVSetCC(N->getDebugLoc(), VT, N0.getOperand(0),
3211198090Srdivacky                           N0.getOperand(1),
3212198090Srdivacky                           cast<CondCodeSDNode>(N0.getOperand(2))->get());
3213198090Srdivacky    }
3214198090Srdivacky
3215198090Srdivacky    // sext(setcc x, y, cc) -> (select_cc x, y, -1, 0, cc)
3216198090Srdivacky    SDValue NegOne =
3217198090Srdivacky      DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), VT);
3218193323Sed    SDValue SCC =
3219193323Sed      SimplifySelectCC(N->getDebugLoc(), N0.getOperand(0), N0.getOperand(1),
3220198090Srdivacky                       NegOne, DAG.getConstant(0, VT),
3221193323Sed                       cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
3222193323Sed    if (SCC.getNode()) return SCC;
3223193323Sed  }
3224198090Srdivacky
3225198090Srdivacky
3226193323Sed
3227193323Sed  // fold (sext x) -> (zext x) if the sign bit is known zero.
3228193323Sed  if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
3229193323Sed      DAG.SignBitIsZero(N0))
3230193323Sed    return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT, N0);
3231193323Sed
3232193323Sed  return SDValue();
3233193323Sed}
3234193323Sed
3235193323SedSDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
3236193323Sed  SDValue N0 = N->getOperand(0);
3237198090Srdivacky  EVT VT = N->getValueType(0);
3238193323Sed
3239193323Sed  // fold (zext c1) -> c1
3240193323Sed  if (isa<ConstantSDNode>(N0))
3241193323Sed    return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT, N0);
3242193323Sed  // fold (zext (zext x)) -> (zext x)
3243193323Sed  // fold (zext (aext x)) -> (zext x)
3244193323Sed  if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
3245193323Sed    return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT,
3246193323Sed                       N0.getOperand(0));
3247193323Sed
3248193323Sed  // fold (zext (truncate (load x))) -> (zext (smaller load x))
3249193323Sed  // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
3250193323Sed  if (N0.getOpcode() == ISD::TRUNCATE) {
3251193323Sed    SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
3252193323Sed    if (NarrowLoad.getNode()) {
3253193323Sed      if (NarrowLoad.getNode() != N0.getNode())
3254193323Sed        CombineTo(N0.getNode(), NarrowLoad);
3255193323Sed      return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT, NarrowLoad);
3256193323Sed    }
3257193323Sed  }
3258193323Sed
3259193323Sed  // fold (zext (truncate x)) -> (and x, mask)
3260193323Sed  if (N0.getOpcode() == ISD::TRUNCATE &&
3261202375Srdivacky      (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT)) &&
3262202375Srdivacky      (!TLI.isTruncateFree(N0.getOperand(0).getValueType(),
3263202375Srdivacky                           N0.getValueType()) ||
3264202375Srdivacky       !TLI.isZExtFree(N0.getValueType(), VT))) {
3265193323Sed    SDValue Op = N0.getOperand(0);
3266193323Sed    if (Op.getValueType().bitsLT(VT)) {
3267193323Sed      Op = DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, Op);
3268193323Sed    } else if (Op.getValueType().bitsGT(VT)) {
3269193323Sed      Op = DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, Op);
3270193323Sed    }
3271200581Srdivacky    return DAG.getZeroExtendInReg(Op, N->getDebugLoc(),
3272200581Srdivacky                                  N0.getValueType().getScalarType());
3273193323Sed  }
3274193323Sed
3275193323Sed  // Fold (zext (and (trunc x), cst)) -> (and x, cst),
3276193323Sed  // if either of the casts is not free.
3277193323Sed  if (N0.getOpcode() == ISD::AND &&
3278193323Sed      N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
3279193323Sed      N0.getOperand(1).getOpcode() == ISD::Constant &&
3280193323Sed      (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
3281193323Sed                           N0.getValueType()) ||
3282193323Sed       !TLI.isZExtFree(N0.getValueType(), VT))) {
3283193323Sed    SDValue X = N0.getOperand(0).getOperand(0);
3284193323Sed    if (X.getValueType().bitsLT(VT)) {
3285193323Sed      X = DAG.getNode(ISD::ANY_EXTEND, X.getDebugLoc(), VT, X);
3286193323Sed    } else if (X.getValueType().bitsGT(VT)) {
3287193323Sed      X = DAG.getNode(ISD::TRUNCATE, X.getDebugLoc(), VT, X);
3288193323Sed    }
3289193323Sed    APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3290193323Sed    Mask.zext(VT.getSizeInBits());
3291193323Sed    return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
3292193323Sed                       X, DAG.getConstant(Mask, VT));
3293193323Sed  }
3294193323Sed
3295193323Sed  // fold (zext (load x)) -> (zext (truncate (zextload x)))
3296193323Sed  if (ISD::isNON_EXTLoad(N0.getNode()) &&
3297193323Sed      ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
3298193323Sed       TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()))) {
3299193323Sed    bool DoXform = true;
3300193323Sed    SmallVector<SDNode*, 4> SetCCs;
3301193323Sed    if (!N0.hasOneUse())
3302193323Sed      DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
3303193323Sed    if (DoXform) {
3304193323Sed      LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3305193323Sed      SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, N->getDebugLoc(), VT,
3306193323Sed                                       LN0->getChain(),
3307193323Sed                                       LN0->getBasePtr(), LN0->getSrcValue(),
3308193323Sed                                       LN0->getSrcValueOffset(),
3309193323Sed                                       N0.getValueType(),
3310193323Sed                                       LN0->isVolatile(), LN0->getAlignment());
3311193323Sed      CombineTo(N, ExtLoad);
3312193323Sed      SDValue Trunc = DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(),
3313193323Sed                                  N0.getValueType(), ExtLoad);
3314193323Sed      CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
3315193323Sed
3316193323Sed      // Extend SetCC uses if necessary.
3317193323Sed      for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
3318193323Sed        SDNode *SetCC = SetCCs[i];
3319193323Sed        SmallVector<SDValue, 4> Ops;
3320193323Sed
3321193323Sed        for (unsigned j = 0; j != 2; ++j) {
3322193323Sed          SDValue SOp = SetCC->getOperand(j);
3323193323Sed          if (SOp == Trunc)
3324193323Sed            Ops.push_back(ExtLoad);
3325193323Sed          else
3326193323Sed            Ops.push_back(DAG.getNode(ISD::ZERO_EXTEND,
3327193323Sed                                      N->getDebugLoc(), VT, SOp));
3328193323Sed        }
3329193323Sed
3330193323Sed        Ops.push_back(SetCC->getOperand(2));
3331193323Sed        CombineTo(SetCC, DAG.getNode(ISD::SETCC, N->getDebugLoc(),
3332193323Sed                                     SetCC->getValueType(0),
3333193323Sed                                     &Ops[0], Ops.size()));
3334193323Sed      }
3335193323Sed
3336193323Sed      return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3337193323Sed    }
3338193323Sed  }
3339193323Sed
3340193323Sed  // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
3341193323Sed  // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
3342193323Sed  if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
3343193323Sed      ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
3344193323Sed    LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3345198090Srdivacky    EVT MemVT = LN0->getMemoryVT();
3346193323Sed    if ((!LegalOperations && !LN0->isVolatile()) ||
3347198090Srdivacky        TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT)) {
3348193323Sed      SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, N->getDebugLoc(), VT,
3349193323Sed                                       LN0->getChain(),
3350193323Sed                                       LN0->getBasePtr(), LN0->getSrcValue(),
3351198090Srdivacky                                       LN0->getSrcValueOffset(), MemVT,
3352193323Sed                                       LN0->isVolatile(), LN0->getAlignment());
3353193323Sed      CombineTo(N, ExtLoad);
3354193323Sed      CombineTo(N0.getNode(),
3355193323Sed                DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(), N0.getValueType(),
3356193323Sed                            ExtLoad),
3357193323Sed                ExtLoad.getValue(1));
3358193323Sed      return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3359193323Sed    }
3360193323Sed  }
3361193323Sed
3362193323Sed  // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
3363193323Sed  if (N0.getOpcode() == ISD::SETCC) {
3364193323Sed    SDValue SCC =
3365193323Sed      SimplifySelectCC(N->getDebugLoc(), N0.getOperand(0), N0.getOperand(1),
3366193323Sed                       DAG.getConstant(1, VT), DAG.getConstant(0, VT),
3367193323Sed                       cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
3368193323Sed    if (SCC.getNode()) return SCC;
3369193323Sed  }
3370193323Sed
3371200581Srdivacky  // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
3372200581Srdivacky  if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
3373200581Srdivacky      isa<ConstantSDNode>(N0.getOperand(1)) &&
3374200581Srdivacky      N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
3375200581Srdivacky      N0.hasOneUse()) {
3376200581Srdivacky    if (N0.getOpcode() == ISD::SHL) {
3377200581Srdivacky      // If the original shl may be shifting out bits, do not perform this
3378200581Srdivacky      // transformation.
3379200581Srdivacky      unsigned ShAmt = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
3380200581Srdivacky      unsigned KnownZeroBits = N0.getOperand(0).getValueType().getSizeInBits() -
3381200581Srdivacky        N0.getOperand(0).getOperand(0).getValueType().getSizeInBits();
3382200581Srdivacky      if (ShAmt > KnownZeroBits)
3383200581Srdivacky        return SDValue();
3384200581Srdivacky    }
3385200581Srdivacky    DebugLoc dl = N->getDebugLoc();
3386200581Srdivacky    return DAG.getNode(N0.getOpcode(), dl, VT,
3387200581Srdivacky                       DAG.getNode(ISD::ZERO_EXTEND, dl, VT, N0.getOperand(0)),
3388202375Srdivacky                       DAG.getNode(ISD::ZERO_EXTEND, dl,
3389202375Srdivacky                                   N0.getOperand(1).getValueType(),
3390202375Srdivacky                                   N0.getOperand(1)));
3391200581Srdivacky  }
3392200581Srdivacky
3393193323Sed  return SDValue();
3394193323Sed}
3395193323Sed
3396193323SedSDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
3397193323Sed  SDValue N0 = N->getOperand(0);
3398198090Srdivacky  EVT VT = N->getValueType(0);
3399193323Sed
3400193323Sed  // fold (aext c1) -> c1
3401193323Sed  if (isa<ConstantSDNode>(N0))
3402193323Sed    return DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, N0);
3403193323Sed  // fold (aext (aext x)) -> (aext x)
3404193323Sed  // fold (aext (zext x)) -> (zext x)
3405193323Sed  // fold (aext (sext x)) -> (sext x)
3406193323Sed  if (N0.getOpcode() == ISD::ANY_EXTEND  ||
3407193323Sed      N0.getOpcode() == ISD::ZERO_EXTEND ||
3408193323Sed      N0.getOpcode() == ISD::SIGN_EXTEND)
3409193323Sed    return DAG.getNode(N0.getOpcode(), N->getDebugLoc(), VT, N0.getOperand(0));
3410193323Sed
3411193323Sed  // fold (aext (truncate (load x))) -> (aext (smaller load x))
3412193323Sed  // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
3413193323Sed  if (N0.getOpcode() == ISD::TRUNCATE) {
3414193323Sed    SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
3415193323Sed    if (NarrowLoad.getNode()) {
3416193323Sed      if (NarrowLoad.getNode() != N0.getNode())
3417193323Sed        CombineTo(N0.getNode(), NarrowLoad);
3418193323Sed      return DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, NarrowLoad);
3419193323Sed    }
3420193323Sed  }
3421193323Sed
3422193323Sed  // fold (aext (truncate x))
3423193323Sed  if (N0.getOpcode() == ISD::TRUNCATE) {
3424193323Sed    SDValue TruncOp = N0.getOperand(0);
3425193323Sed    if (TruncOp.getValueType() == VT)
3426193323Sed      return TruncOp; // x iff x size == zext size.
3427193323Sed    if (TruncOp.getValueType().bitsGT(VT))
3428193323Sed      return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, TruncOp);
3429193323Sed    return DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, TruncOp);
3430193323Sed  }
3431193323Sed
3432193323Sed  // Fold (aext (and (trunc x), cst)) -> (and x, cst)
3433193323Sed  // if the trunc is not free.
3434193323Sed  if (N0.getOpcode() == ISD::AND &&
3435193323Sed      N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
3436193323Sed      N0.getOperand(1).getOpcode() == ISD::Constant &&
3437193323Sed      !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
3438193323Sed                          N0.getValueType())) {
3439193323Sed    SDValue X = N0.getOperand(0).getOperand(0);
3440193323Sed    if (X.getValueType().bitsLT(VT)) {
3441193323Sed      X = DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, X);
3442193323Sed    } else if (X.getValueType().bitsGT(VT)) {
3443193323Sed      X = DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, X);
3444193323Sed    }
3445193323Sed    APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3446193323Sed    Mask.zext(VT.getSizeInBits());
3447193323Sed    return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
3448193323Sed                       X, DAG.getConstant(Mask, VT));
3449193323Sed  }
3450193323Sed
3451193323Sed  // fold (aext (load x)) -> (aext (truncate (extload x)))
3452193323Sed  if (ISD::isNON_EXTLoad(N0.getNode()) &&
3453193323Sed      ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
3454193323Sed       TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
3455193323Sed    bool DoXform = true;
3456193323Sed    SmallVector<SDNode*, 4> SetCCs;
3457193323Sed    if (!N0.hasOneUse())
3458193323Sed      DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
3459193323Sed    if (DoXform) {
3460193323Sed      LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3461193323Sed      SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, N->getDebugLoc(), VT,
3462193323Sed                                       LN0->getChain(),
3463193323Sed                                       LN0->getBasePtr(), LN0->getSrcValue(),
3464193323Sed                                       LN0->getSrcValueOffset(),
3465193323Sed                                       N0.getValueType(),
3466193323Sed                                       LN0->isVolatile(), LN0->getAlignment());
3467193323Sed      CombineTo(N, ExtLoad);
3468193323Sed      SDValue Trunc = DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(),
3469193323Sed                                  N0.getValueType(), ExtLoad);
3470193323Sed      CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
3471193323Sed
3472193323Sed      // Extend SetCC uses if necessary.
3473193323Sed      for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
3474193323Sed        SDNode *SetCC = SetCCs[i];
3475193323Sed        SmallVector<SDValue, 4> Ops;
3476193323Sed
3477193323Sed        for (unsigned j = 0; j != 2; ++j) {
3478193323Sed          SDValue SOp = SetCC->getOperand(j);
3479193323Sed          if (SOp == Trunc)
3480193323Sed            Ops.push_back(ExtLoad);
3481193323Sed          else
3482193323Sed            Ops.push_back(DAG.getNode(ISD::ANY_EXTEND,
3483193323Sed                                      N->getDebugLoc(), VT, SOp));
3484193323Sed        }
3485193323Sed
3486193323Sed        Ops.push_back(SetCC->getOperand(2));
3487193323Sed        CombineTo(SetCC, DAG.getNode(ISD::SETCC, N->getDebugLoc(),
3488193323Sed                                     SetCC->getValueType(0),
3489193323Sed                                     &Ops[0], Ops.size()));
3490193323Sed      }
3491193323Sed
3492193323Sed      return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3493193323Sed    }
3494193323Sed  }
3495193323Sed
3496193323Sed  // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
3497193323Sed  // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
3498193323Sed  // fold (aext ( extload x)) -> (aext (truncate (extload  x)))
3499193323Sed  if (N0.getOpcode() == ISD::LOAD &&
3500193323Sed      !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
3501193323Sed      N0.hasOneUse()) {
3502193323Sed    LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3503198090Srdivacky    EVT MemVT = LN0->getMemoryVT();
3504193323Sed    SDValue ExtLoad = DAG.getExtLoad(LN0->getExtensionType(), N->getDebugLoc(),
3505193323Sed                                     VT, LN0->getChain(), LN0->getBasePtr(),
3506193323Sed                                     LN0->getSrcValue(),
3507198090Srdivacky                                     LN0->getSrcValueOffset(), MemVT,
3508193323Sed                                     LN0->isVolatile(), LN0->getAlignment());
3509193323Sed    CombineTo(N, ExtLoad);
3510193323Sed    CombineTo(N0.getNode(),
3511193323Sed              DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(),
3512193323Sed                          N0.getValueType(), ExtLoad),
3513193323Sed              ExtLoad.getValue(1));
3514193323Sed    return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3515193323Sed  }
3516193323Sed
3517193323Sed  // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
3518193323Sed  if (N0.getOpcode() == ISD::SETCC) {
3519193323Sed    SDValue SCC =
3520193323Sed      SimplifySelectCC(N->getDebugLoc(), N0.getOperand(0), N0.getOperand(1),
3521193323Sed                       DAG.getConstant(1, VT), DAG.getConstant(0, VT),
3522193323Sed                       cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
3523193323Sed    if (SCC.getNode())
3524193323Sed      return SCC;
3525193323Sed  }
3526193323Sed
3527193323Sed  return SDValue();
3528193323Sed}
3529193323Sed
3530193323Sed/// GetDemandedBits - See if the specified operand can be simplified with the
3531193323Sed/// knowledge that only the bits specified by Mask are used.  If so, return the
3532193323Sed/// simpler operand, otherwise return a null SDValue.
3533193323SedSDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
3534193323Sed  switch (V.getOpcode()) {
3535193323Sed  default: break;
3536193323Sed  case ISD::OR:
3537193323Sed  case ISD::XOR:
3538193323Sed    // If the LHS or RHS don't contribute bits to the or, drop them.
3539193323Sed    if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
3540193323Sed      return V.getOperand(1);
3541193323Sed    if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
3542193323Sed      return V.getOperand(0);
3543193323Sed    break;
3544193323Sed  case ISD::SRL:
3545193323Sed    // Only look at single-use SRLs.
3546193323Sed    if (!V.getNode()->hasOneUse())
3547193323Sed      break;
3548193323Sed    if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
3549193323Sed      // See if we can recursively simplify the LHS.
3550193323Sed      unsigned Amt = RHSC->getZExtValue();
3551193323Sed
3552193323Sed      // Watch out for shift count overflow though.
3553193323Sed      if (Amt >= Mask.getBitWidth()) break;
3554193323Sed      APInt NewMask = Mask << Amt;
3555193323Sed      SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
3556193323Sed      if (SimplifyLHS.getNode())
3557193323Sed        return DAG.getNode(ISD::SRL, V.getDebugLoc(), V.getValueType(),
3558193323Sed                           SimplifyLHS, V.getOperand(1));
3559193323Sed    }
3560193323Sed  }
3561193323Sed  return SDValue();
3562193323Sed}
3563193323Sed
3564193323Sed/// ReduceLoadWidth - If the result of a wider load is shifted to right of N
3565193323Sed/// bits and then truncated to a narrower type and where N is a multiple
3566193323Sed/// of number of bits of the narrower type, transform it to a narrower load
3567193323Sed/// from address + N / num of bits of new type. If the result is to be
3568193323Sed/// extended, also fold the extension to form a extending load.
3569193323SedSDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
3570193323Sed  unsigned Opc = N->getOpcode();
3571193323Sed  ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
3572193323Sed  SDValue N0 = N->getOperand(0);
3573198090Srdivacky  EVT VT = N->getValueType(0);
3574198090Srdivacky  EVT ExtVT = VT;
3575193323Sed
3576193323Sed  // This transformation isn't valid for vector loads.
3577193323Sed  if (VT.isVector())
3578193323Sed    return SDValue();
3579193323Sed
3580202375Srdivacky  // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
3581193323Sed  // extended to VT.
3582193323Sed  if (Opc == ISD::SIGN_EXTEND_INREG) {
3583193323Sed    ExtType = ISD::SEXTLOAD;
3584198090Srdivacky    ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
3585198090Srdivacky    if (LegalOperations && !TLI.isLoadExtLegal(ISD::SEXTLOAD, ExtVT))
3586193323Sed      return SDValue();
3587193323Sed  }
3588193323Sed
3589198090Srdivacky  unsigned EVTBits = ExtVT.getSizeInBits();
3590193323Sed  unsigned ShAmt = 0;
3591198090Srdivacky  if (N0.getOpcode() == ISD::SRL && N0.hasOneUse() && ExtVT.isRound()) {
3592193323Sed    if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
3593193323Sed      ShAmt = N01->getZExtValue();
3594193323Sed      // Is the shift amount a multiple of size of VT?
3595193323Sed      if ((ShAmt & (EVTBits-1)) == 0) {
3596193323Sed        N0 = N0.getOperand(0);
3597198090Srdivacky        // Is the load width a multiple of size of VT?
3598198090Srdivacky        if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
3599193323Sed          return SDValue();
3600193323Sed      }
3601193323Sed    }
3602193323Sed  }
3603193323Sed
3604193323Sed  // Do not generate loads of non-round integer types since these can
3605193323Sed  // be expensive (and would be wrong if the type is not byte sized).
3606198090Srdivacky  if (isa<LoadSDNode>(N0) && N0.hasOneUse() && ExtVT.isRound() &&
3607193323Sed      cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits() > EVTBits &&
3608193323Sed      // Do not change the width of a volatile load.
3609193323Sed      !cast<LoadSDNode>(N0)->isVolatile()) {
3610193323Sed    LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3611198090Srdivacky    EVT PtrType = N0.getOperand(1).getValueType();
3612193323Sed
3613193323Sed    // For big endian targets, we need to adjust the offset to the pointer to
3614193323Sed    // load the correct bytes.
3615193323Sed    if (TLI.isBigEndian()) {
3616193323Sed      unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
3617198090Srdivacky      unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
3618193323Sed      ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
3619193323Sed    }
3620193323Sed
3621193323Sed    uint64_t PtrOff =  ShAmt / 8;
3622193323Sed    unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
3623193323Sed    SDValue NewPtr = DAG.getNode(ISD::ADD, LN0->getDebugLoc(),
3624193323Sed                                 PtrType, LN0->getBasePtr(),
3625193323Sed                                 DAG.getConstant(PtrOff, PtrType));
3626193323Sed    AddToWorkList(NewPtr.getNode());
3627193323Sed
3628193323Sed    SDValue Load = (ExtType == ISD::NON_EXTLOAD)
3629193323Sed      ? DAG.getLoad(VT, N0.getDebugLoc(), LN0->getChain(), NewPtr,
3630193323Sed                    LN0->getSrcValue(), LN0->getSrcValueOffset() + PtrOff,
3631193323Sed                    LN0->isVolatile(), NewAlign)
3632193323Sed      : DAG.getExtLoad(ExtType, N0.getDebugLoc(), VT, LN0->getChain(), NewPtr,
3633193323Sed                       LN0->getSrcValue(), LN0->getSrcValueOffset() + PtrOff,
3634198090Srdivacky                       ExtVT, LN0->isVolatile(), NewAlign);
3635193323Sed
3636193323Sed    // Replace the old load's chain with the new load's chain.
3637193323Sed    WorkListRemover DeadNodes(*this);
3638193323Sed    DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1),
3639193323Sed                                  &DeadNodes);
3640193323Sed
3641193323Sed    // Return the new loaded value.
3642193323Sed    return Load;
3643193323Sed  }
3644193323Sed
3645193323Sed  return SDValue();
3646193323Sed}
3647193323Sed
3648193323SedSDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
3649193323Sed  SDValue N0 = N->getOperand(0);
3650193323Sed  SDValue N1 = N->getOperand(1);
3651198090Srdivacky  EVT VT = N->getValueType(0);
3652198090Srdivacky  EVT EVT = cast<VTSDNode>(N1)->getVT();
3653200581Srdivacky  unsigned VTBits = VT.getScalarType().getSizeInBits();
3654202375Srdivacky  unsigned EVTBits = EVT.getScalarType().getSizeInBits();
3655193323Sed
3656193323Sed  // fold (sext_in_reg c1) -> c1
3657193323Sed  if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
3658193323Sed    return DAG.getNode(ISD::SIGN_EXTEND_INREG, N->getDebugLoc(), VT, N0, N1);
3659193323Sed
3660193323Sed  // If the input is already sign extended, just drop the extension.
3661200581Srdivacky  if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
3662193323Sed    return N0;
3663193323Sed
3664193323Sed  // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
3665193323Sed  if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
3666193323Sed      EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT())) {
3667193323Sed    return DAG.getNode(ISD::SIGN_EXTEND_INREG, N->getDebugLoc(), VT,
3668193323Sed                       N0.getOperand(0), N1);
3669193323Sed  }
3670193323Sed
3671193323Sed  // fold (sext_in_reg (sext x)) -> (sext x)
3672193323Sed  // fold (sext_in_reg (aext x)) -> (sext x)
3673193323Sed  // if x is small enough.
3674193323Sed  if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
3675193323Sed    SDValue N00 = N0.getOperand(0);
3676200581Srdivacky    if (N00.getValueType().getScalarType().getSizeInBits() < EVTBits)
3677193323Sed      return DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(), VT, N00, N1);
3678193323Sed  }
3679193323Sed
3680193323Sed  // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
3681193323Sed  if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
3682193323Sed    return DAG.getZeroExtendInReg(N0, N->getDebugLoc(), EVT);
3683193323Sed
3684193323Sed  // fold operands of sext_in_reg based on knowledge that the top bits are not
3685193323Sed  // demanded.
3686193323Sed  if (SimplifyDemandedBits(SDValue(N, 0)))
3687193323Sed    return SDValue(N, 0);
3688193323Sed
3689193323Sed  // fold (sext_in_reg (load x)) -> (smaller sextload x)
3690193323Sed  // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
3691193323Sed  SDValue NarrowLoad = ReduceLoadWidth(N);
3692193323Sed  if (NarrowLoad.getNode())
3693193323Sed    return NarrowLoad;
3694193323Sed
3695193323Sed  // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
3696193323Sed  // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
3697193323Sed  // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
3698193323Sed  if (N0.getOpcode() == ISD::SRL) {
3699193323Sed    if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
3700200581Srdivacky      if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
3701193323Sed        // We can turn this into an SRA iff the input to the SRL is already sign
3702193323Sed        // extended enough.
3703193323Sed        unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
3704200581Srdivacky        if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
3705193323Sed          return DAG.getNode(ISD::SRA, N->getDebugLoc(), VT,
3706193323Sed                             N0.getOperand(0), N0.getOperand(1));
3707193323Sed      }
3708193323Sed  }
3709193323Sed
3710193323Sed  // fold (sext_inreg (extload x)) -> (sextload x)
3711193323Sed  if (ISD::isEXTLoad(N0.getNode()) &&
3712193323Sed      ISD::isUNINDEXEDLoad(N0.getNode()) &&
3713193323Sed      EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
3714193323Sed      ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
3715193323Sed       TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
3716193323Sed    LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3717193323Sed    SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, N->getDebugLoc(), VT,
3718193323Sed                                     LN0->getChain(),
3719193323Sed                                     LN0->getBasePtr(), LN0->getSrcValue(),
3720193323Sed                                     LN0->getSrcValueOffset(), EVT,
3721193323Sed                                     LN0->isVolatile(), LN0->getAlignment());
3722193323Sed    CombineTo(N, ExtLoad);
3723193323Sed    CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3724193323Sed    return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3725193323Sed  }
3726193323Sed  // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
3727193323Sed  if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
3728193323Sed      N0.hasOneUse() &&
3729193323Sed      EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
3730193323Sed      ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
3731193323Sed       TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
3732193323Sed    LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3733193323Sed    SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, N->getDebugLoc(), VT,
3734193323Sed                                     LN0->getChain(),
3735193323Sed                                     LN0->getBasePtr(), LN0->getSrcValue(),
3736193323Sed                                     LN0->getSrcValueOffset(), EVT,
3737193323Sed                                     LN0->isVolatile(), LN0->getAlignment());
3738193323Sed    CombineTo(N, ExtLoad);
3739193323Sed    CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3740193323Sed    return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3741193323Sed  }
3742193323Sed  return SDValue();
3743193323Sed}
3744193323Sed
3745193323SedSDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
3746193323Sed  SDValue N0 = N->getOperand(0);
3747198090Srdivacky  EVT VT = N->getValueType(0);
3748193323Sed
3749193323Sed  // noop truncate
3750193323Sed  if (N0.getValueType() == N->getValueType(0))
3751193323Sed    return N0;
3752193323Sed  // fold (truncate c1) -> c1
3753193323Sed  if (isa<ConstantSDNode>(N0))
3754193323Sed    return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, N0);
3755193323Sed  // fold (truncate (truncate x)) -> (truncate x)
3756193323Sed  if (N0.getOpcode() == ISD::TRUNCATE)
3757193323Sed    return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, N0.getOperand(0));
3758193323Sed  // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
3759193323Sed  if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::SIGN_EXTEND||
3760193323Sed      N0.getOpcode() == ISD::ANY_EXTEND) {
3761193323Sed    if (N0.getOperand(0).getValueType().bitsLT(VT))
3762193323Sed      // if the source is smaller than the dest, we still need an extend
3763193323Sed      return DAG.getNode(N0.getOpcode(), N->getDebugLoc(), VT,
3764193323Sed                         N0.getOperand(0));
3765193323Sed    else if (N0.getOperand(0).getValueType().bitsGT(VT))
3766193323Sed      // if the source is larger than the dest, than we just need the truncate
3767193323Sed      return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, N0.getOperand(0));
3768193323Sed    else
3769193323Sed      // if the source and dest are the same type, we can drop both the extend
3770202375Srdivacky      // and the truncate.
3771193323Sed      return N0.getOperand(0);
3772193323Sed  }
3773193323Sed
3774193323Sed  // See if we can simplify the input to this truncate through knowledge that
3775193323Sed  // only the low bits are being used.  For example "trunc (or (shl x, 8), y)"
3776193323Sed  // -> trunc y
3777193323Sed  SDValue Shorter =
3778193323Sed    GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
3779193323Sed                                             VT.getSizeInBits()));
3780193323Sed  if (Shorter.getNode())
3781193323Sed    return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, Shorter);
3782193323Sed
3783193323Sed  // fold (truncate (load x)) -> (smaller load x)
3784193323Sed  // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
3785193323Sed  return ReduceLoadWidth(N);
3786193323Sed}
3787193323Sed
3788193323Sedstatic SDNode *getBuildPairElt(SDNode *N, unsigned i) {
3789193323Sed  SDValue Elt = N->getOperand(i);
3790193323Sed  if (Elt.getOpcode() != ISD::MERGE_VALUES)
3791193323Sed    return Elt.getNode();
3792193323Sed  return Elt.getOperand(Elt.getResNo()).getNode();
3793193323Sed}
3794193323Sed
3795193323Sed/// CombineConsecutiveLoads - build_pair (load, load) -> load
3796193323Sed/// if load locations are consecutive.
3797198090SrdivackySDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
3798193323Sed  assert(N->getOpcode() == ISD::BUILD_PAIR);
3799193323Sed
3800193574Sed  LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
3801193574Sed  LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
3802193574Sed  if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse())
3803193323Sed    return SDValue();
3804198090Srdivacky  EVT LD1VT = LD1->getValueType(0);
3805193323Sed
3806193323Sed  if (ISD::isNON_EXTLoad(LD2) &&
3807193323Sed      LD2->hasOneUse() &&
3808193323Sed      // If both are volatile this would reduce the number of volatile loads.
3809193323Sed      // If one is volatile it might be ok, but play conservative and bail out.
3810193574Sed      !LD1->isVolatile() &&
3811193574Sed      !LD2->isVolatile() &&
3812200581Srdivacky      DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
3813193574Sed    unsigned Align = LD1->getAlignment();
3814193323Sed    unsigned NewAlign = TLI.getTargetData()->
3815198090Srdivacky      getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
3816193323Sed
3817193323Sed    if (NewAlign <= Align &&
3818193323Sed        (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
3819193574Sed      return DAG.getLoad(VT, N->getDebugLoc(), LD1->getChain(),
3820193574Sed                         LD1->getBasePtr(), LD1->getSrcValue(),
3821193574Sed                         LD1->getSrcValueOffset(), false, Align);
3822193323Sed  }
3823193323Sed
3824193323Sed  return SDValue();
3825193323Sed}
3826193323Sed
3827193323SedSDValue DAGCombiner::visitBIT_CONVERT(SDNode *N) {
3828193323Sed  SDValue N0 = N->getOperand(0);
3829198090Srdivacky  EVT VT = N->getValueType(0);
3830193323Sed
3831193323Sed  // If the input is a BUILD_VECTOR with all constant elements, fold this now.
3832193323Sed  // Only do this before legalize, since afterward the target may be depending
3833193323Sed  // on the bitconvert.
3834193323Sed  // First check to see if this is all constant.
3835193323Sed  if (!LegalTypes &&
3836193323Sed      N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
3837193323Sed      VT.isVector()) {
3838193323Sed    bool isSimple = true;
3839193323Sed    for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i)
3840193323Sed      if (N0.getOperand(i).getOpcode() != ISD::UNDEF &&
3841193323Sed          N0.getOperand(i).getOpcode() != ISD::Constant &&
3842193323Sed          N0.getOperand(i).getOpcode() != ISD::ConstantFP) {
3843193323Sed        isSimple = false;
3844193323Sed        break;
3845193323Sed      }
3846193323Sed
3847198090Srdivacky    EVT DestEltVT = N->getValueType(0).getVectorElementType();
3848193323Sed    assert(!DestEltVT.isVector() &&
3849193323Sed           "Element type of vector ValueType must not be vector!");
3850193323Sed    if (isSimple)
3851193323Sed      return ConstantFoldBIT_CONVERTofBUILD_VECTOR(N0.getNode(), DestEltVT);
3852193323Sed  }
3853193323Sed
3854193323Sed  // If the input is a constant, let getNode fold it.
3855193323Sed  if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
3856193323Sed    SDValue Res = DAG.getNode(ISD::BIT_CONVERT, N->getDebugLoc(), VT, N0);
3857198090Srdivacky    if (Res.getNode() != N) {
3858198090Srdivacky      if (!LegalOperations ||
3859198090Srdivacky          TLI.isOperationLegal(Res.getNode()->getOpcode(), VT))
3860198090Srdivacky        return Res;
3861198090Srdivacky
3862198090Srdivacky      // Folding it resulted in an illegal node, and it's too late to
3863198090Srdivacky      // do that. Clean up the old node and forego the transformation.
3864198090Srdivacky      // Ideally this won't happen very often, because instcombine
3865198090Srdivacky      // and the earlier dagcombine runs (where illegal nodes are
3866198090Srdivacky      // permitted) should have folded most of them already.
3867198090Srdivacky      DAG.DeleteNode(Res.getNode());
3868198090Srdivacky    }
3869193323Sed  }
3870193323Sed
3871193323Sed  // (conv (conv x, t1), t2) -> (conv x, t2)
3872193323Sed  if (N0.getOpcode() == ISD::BIT_CONVERT)
3873193323Sed    return DAG.getNode(ISD::BIT_CONVERT, N->getDebugLoc(), VT,
3874193323Sed                       N0.getOperand(0));
3875193323Sed
3876193323Sed  // fold (conv (load x)) -> (load (conv*)x)
3877193323Sed  // If the resultant load doesn't need a higher alignment than the original!
3878193323Sed  if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
3879193323Sed      // Do not change the width of a volatile load.
3880193323Sed      !cast<LoadSDNode>(N0)->isVolatile() &&
3881193323Sed      (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT))) {
3882193323Sed    LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3883193323Sed    unsigned Align = TLI.getTargetData()->
3884198090Srdivacky      getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
3885193323Sed    unsigned OrigAlign = LN0->getAlignment();
3886193323Sed
3887193323Sed    if (Align <= OrigAlign) {
3888193323Sed      SDValue Load = DAG.getLoad(VT, N->getDebugLoc(), LN0->getChain(),
3889193323Sed                                 LN0->getBasePtr(),
3890193323Sed                                 LN0->getSrcValue(), LN0->getSrcValueOffset(),
3891193323Sed                                 LN0->isVolatile(), OrigAlign);
3892193323Sed      AddToWorkList(N);
3893193323Sed      CombineTo(N0.getNode(),
3894193323Sed                DAG.getNode(ISD::BIT_CONVERT, N0.getDebugLoc(),
3895193323Sed                            N0.getValueType(), Load),
3896193323Sed                Load.getValue(1));
3897193323Sed      return Load;
3898193323Sed    }
3899193323Sed  }
3900193323Sed
3901193323Sed  // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
3902193323Sed  // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
3903193323Sed  // This often reduces constant pool loads.
3904193323Sed  if ((N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FABS) &&
3905193323Sed      N0.getNode()->hasOneUse() && VT.isInteger() && !VT.isVector()) {
3906193323Sed    SDValue NewConv = DAG.getNode(ISD::BIT_CONVERT, N0.getDebugLoc(), VT,
3907193323Sed                                  N0.getOperand(0));
3908193323Sed    AddToWorkList(NewConv.getNode());
3909193323Sed
3910193323Sed    APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
3911193323Sed    if (N0.getOpcode() == ISD::FNEG)
3912193323Sed      return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT,
3913193323Sed                         NewConv, DAG.getConstant(SignBit, VT));
3914193323Sed    assert(N0.getOpcode() == ISD::FABS);
3915193323Sed    return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
3916193323Sed                       NewConv, DAG.getConstant(~SignBit, VT));
3917193323Sed  }
3918193323Sed
3919193323Sed  // fold (bitconvert (fcopysign cst, x)) ->
3920193323Sed  //         (or (and (bitconvert x), sign), (and cst, (not sign)))
3921193323Sed  // Note that we don't handle (copysign x, cst) because this can always be
3922193323Sed  // folded to an fneg or fabs.
3923193323Sed  if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
3924193323Sed      isa<ConstantFPSDNode>(N0.getOperand(0)) &&
3925193323Sed      VT.isInteger() && !VT.isVector()) {
3926193323Sed    unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
3927198090Srdivacky    EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
3928193323Sed    if (TLI.isTypeLegal(IntXVT) || !LegalTypes) {
3929193323Sed      SDValue X = DAG.getNode(ISD::BIT_CONVERT, N0.getDebugLoc(),
3930193323Sed                              IntXVT, N0.getOperand(1));
3931193323Sed      AddToWorkList(X.getNode());
3932193323Sed
3933193323Sed      // If X has a different width than the result/lhs, sext it or truncate it.
3934193323Sed      unsigned VTWidth = VT.getSizeInBits();
3935193323Sed      if (OrigXWidth < VTWidth) {
3936193323Sed        X = DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(), VT, X);
3937193323Sed        AddToWorkList(X.getNode());
3938193323Sed      } else if (OrigXWidth > VTWidth) {
3939193323Sed        // To get the sign bit in the right place, we have to shift it right
3940193323Sed        // before truncating.
3941193323Sed        X = DAG.getNode(ISD::SRL, X.getDebugLoc(),
3942193323Sed                        X.getValueType(), X,
3943193323Sed                        DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
3944193323Sed        AddToWorkList(X.getNode());
3945193323Sed        X = DAG.getNode(ISD::TRUNCATE, X.getDebugLoc(), VT, X);
3946193323Sed        AddToWorkList(X.getNode());
3947193323Sed      }
3948193323Sed
3949193323Sed      APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
3950193323Sed      X = DAG.getNode(ISD::AND, X.getDebugLoc(), VT,
3951193323Sed                      X, DAG.getConstant(SignBit, VT));
3952193323Sed      AddToWorkList(X.getNode());
3953193323Sed
3954193323Sed      SDValue Cst = DAG.getNode(ISD::BIT_CONVERT, N0.getDebugLoc(),
3955193323Sed                                VT, N0.getOperand(0));
3956193323Sed      Cst = DAG.getNode(ISD::AND, Cst.getDebugLoc(), VT,
3957193323Sed                        Cst, DAG.getConstant(~SignBit, VT));
3958193323Sed      AddToWorkList(Cst.getNode());
3959193323Sed
3960193323Sed      return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, X, Cst);
3961193323Sed    }
3962193323Sed  }
3963193323Sed
3964193323Sed  // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
3965193323Sed  if (N0.getOpcode() == ISD::BUILD_PAIR) {
3966193323Sed    SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
3967193323Sed    if (CombineLD.getNode())
3968193323Sed      return CombineLD;
3969193323Sed  }
3970193323Sed
3971193323Sed  return SDValue();
3972193323Sed}
3973193323Sed
3974193323SedSDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
3975198090Srdivacky  EVT VT = N->getValueType(0);
3976193323Sed  return CombineConsecutiveLoads(N, VT);
3977193323Sed}
3978193323Sed
3979193323Sed/// ConstantFoldBIT_CONVERTofBUILD_VECTOR - We know that BV is a build_vector
3980193323Sed/// node with Constant, ConstantFP or Undef operands.  DstEltVT indicates the
3981193323Sed/// destination element value type.
3982193323SedSDValue DAGCombiner::
3983198090SrdivackyConstantFoldBIT_CONVERTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
3984198090Srdivacky  EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
3985193323Sed
3986193323Sed  // If this is already the right type, we're done.
3987193323Sed  if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
3988193323Sed
3989193323Sed  unsigned SrcBitSize = SrcEltVT.getSizeInBits();
3990193323Sed  unsigned DstBitSize = DstEltVT.getSizeInBits();
3991193323Sed
3992193323Sed  // If this is a conversion of N elements of one type to N elements of another
3993193323Sed  // type, convert each element.  This handles FP<->INT cases.
3994193323Sed  if (SrcBitSize == DstBitSize) {
3995193323Sed    SmallVector<SDValue, 8> Ops;
3996193323Sed    for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
3997193323Sed      SDValue Op = BV->getOperand(i);
3998193323Sed      // If the vector element type is not legal, the BUILD_VECTOR operands
3999193323Sed      // are promoted and implicitly truncated.  Make that explicit here.
4000193323Sed      if (Op.getValueType() != SrcEltVT)
4001193323Sed        Op = DAG.getNode(ISD::TRUNCATE, BV->getDebugLoc(), SrcEltVT, Op);
4002193323Sed      Ops.push_back(DAG.getNode(ISD::BIT_CONVERT, BV->getDebugLoc(),
4003193323Sed                                DstEltVT, Op));
4004193323Sed      AddToWorkList(Ops.back().getNode());
4005193323Sed    }
4006198090Srdivacky    EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
4007193323Sed                              BV->getValueType(0).getVectorNumElements());
4008193323Sed    return DAG.getNode(ISD::BUILD_VECTOR, BV->getDebugLoc(), VT,
4009193323Sed                       &Ops[0], Ops.size());
4010193323Sed  }
4011193323Sed
4012193323Sed  // Otherwise, we're growing or shrinking the elements.  To avoid having to
4013193323Sed  // handle annoying details of growing/shrinking FP values, we convert them to
4014193323Sed  // int first.
4015193323Sed  if (SrcEltVT.isFloatingPoint()) {
4016193323Sed    // Convert the input float vector to a int vector where the elements are the
4017193323Sed    // same sizes.
4018193323Sed    assert((SrcEltVT == MVT::f32 || SrcEltVT == MVT::f64) && "Unknown FP VT!");
4019198090Srdivacky    EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
4020193323Sed    BV = ConstantFoldBIT_CONVERTofBUILD_VECTOR(BV, IntVT).getNode();
4021193323Sed    SrcEltVT = IntVT;
4022193323Sed  }
4023193323Sed
4024193323Sed  // Now we know the input is an integer vector.  If the output is a FP type,
4025193323Sed  // convert to integer first, then to FP of the right size.
4026193323Sed  if (DstEltVT.isFloatingPoint()) {
4027193323Sed    assert((DstEltVT == MVT::f32 || DstEltVT == MVT::f64) && "Unknown FP VT!");
4028198090Srdivacky    EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
4029193323Sed    SDNode *Tmp = ConstantFoldBIT_CONVERTofBUILD_VECTOR(BV, TmpVT).getNode();
4030193323Sed
4031193323Sed    // Next, convert to FP elements of the same size.
4032193323Sed    return ConstantFoldBIT_CONVERTofBUILD_VECTOR(Tmp, DstEltVT);
4033193323Sed  }
4034193323Sed
4035193323Sed  // Okay, we know the src/dst types are both integers of differing types.
4036193323Sed  // Handling growing first.
4037193323Sed  assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
4038193323Sed  if (SrcBitSize < DstBitSize) {
4039193323Sed    unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
4040193323Sed
4041193323Sed    SmallVector<SDValue, 8> Ops;
4042193323Sed    for (unsigned i = 0, e = BV->getNumOperands(); i != e;
4043193323Sed         i += NumInputsPerOutput) {
4044193323Sed      bool isLE = TLI.isLittleEndian();
4045193323Sed      APInt NewBits = APInt(DstBitSize, 0);
4046193323Sed      bool EltIsUndef = true;
4047193323Sed      for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
4048193323Sed        // Shift the previously computed bits over.
4049193323Sed        NewBits <<= SrcBitSize;
4050193323Sed        SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
4051193323Sed        if (Op.getOpcode() == ISD::UNDEF) continue;
4052193323Sed        EltIsUndef = false;
4053193323Sed
4054193323Sed        NewBits |= (APInt(cast<ConstantSDNode>(Op)->getAPIntValue()).
4055193323Sed                    zextOrTrunc(SrcBitSize).zext(DstBitSize));
4056193323Sed      }
4057193323Sed
4058193323Sed      if (EltIsUndef)
4059193323Sed        Ops.push_back(DAG.getUNDEF(DstEltVT));
4060193323Sed      else
4061193323Sed        Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
4062193323Sed    }
4063193323Sed
4064198090Srdivacky    EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
4065193323Sed    return DAG.getNode(ISD::BUILD_VECTOR, BV->getDebugLoc(), VT,
4066193323Sed                       &Ops[0], Ops.size());
4067193323Sed  }
4068193323Sed
4069193323Sed  // Finally, this must be the case where we are shrinking elements: each input
4070193323Sed  // turns into multiple outputs.
4071193323Sed  bool isS2V = ISD::isScalarToVector(BV);
4072193323Sed  unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
4073198090Srdivacky  EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
4074198090Srdivacky                            NumOutputsPerInput*BV->getNumOperands());
4075193323Sed  SmallVector<SDValue, 8> Ops;
4076193323Sed
4077193323Sed  for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
4078193323Sed    if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
4079193323Sed      for (unsigned j = 0; j != NumOutputsPerInput; ++j)
4080193323Sed        Ops.push_back(DAG.getUNDEF(DstEltVT));
4081193323Sed      continue;
4082193323Sed    }
4083193323Sed
4084193323Sed    APInt OpVal = APInt(cast<ConstantSDNode>(BV->getOperand(i))->
4085193323Sed                        getAPIntValue()).zextOrTrunc(SrcBitSize);
4086193323Sed
4087193323Sed    for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
4088193323Sed      APInt ThisVal = APInt(OpVal).trunc(DstBitSize);
4089193323Sed      Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
4090193323Sed      if (isS2V && i == 0 && j == 0 && APInt(ThisVal).zext(SrcBitSize) == OpVal)
4091193323Sed        // Simply turn this into a SCALAR_TO_VECTOR of the new type.
4092193323Sed        return DAG.getNode(ISD::SCALAR_TO_VECTOR, BV->getDebugLoc(), VT,
4093193323Sed                           Ops[0]);
4094193323Sed      OpVal = OpVal.lshr(DstBitSize);
4095193323Sed    }
4096193323Sed
4097193323Sed    // For big endian targets, swap the order of the pieces of each element.
4098193323Sed    if (TLI.isBigEndian())
4099193323Sed      std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
4100193323Sed  }
4101193323Sed
4102193323Sed  return DAG.getNode(ISD::BUILD_VECTOR, BV->getDebugLoc(), VT,
4103193323Sed                     &Ops[0], Ops.size());
4104193323Sed}
4105193323Sed
4106193323SedSDValue DAGCombiner::visitFADD(SDNode *N) {
4107193323Sed  SDValue N0 = N->getOperand(0);
4108193323Sed  SDValue N1 = N->getOperand(1);
4109193323Sed  ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
4110193323Sed  ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
4111198090Srdivacky  EVT VT = N->getValueType(0);
4112193323Sed
4113193323Sed  // fold vector ops
4114193323Sed  if (VT.isVector()) {
4115193323Sed    SDValue FoldedVOp = SimplifyVBinOp(N);
4116193323Sed    if (FoldedVOp.getNode()) return FoldedVOp;
4117193323Sed  }
4118193323Sed
4119193323Sed  // fold (fadd c1, c2) -> (fadd c1, c2)
4120193323Sed  if (N0CFP && N1CFP && VT != MVT::ppcf128)
4121193323Sed    return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N0, N1);
4122193323Sed  // canonicalize constant to RHS
4123193323Sed  if (N0CFP && !N1CFP)
4124193323Sed    return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N1, N0);
4125193323Sed  // fold (fadd A, 0) -> A
4126193323Sed  if (UnsafeFPMath && N1CFP && N1CFP->getValueAPF().isZero())
4127193323Sed    return N0;
4128193323Sed  // fold (fadd A, (fneg B)) -> (fsub A, B)
4129193323Sed  if (isNegatibleForFree(N1, LegalOperations) == 2)
4130193323Sed    return DAG.getNode(ISD::FSUB, N->getDebugLoc(), VT, N0,
4131193323Sed                       GetNegatedExpression(N1, DAG, LegalOperations));
4132193323Sed  // fold (fadd (fneg A), B) -> (fsub B, A)
4133193323Sed  if (isNegatibleForFree(N0, LegalOperations) == 2)
4134193323Sed    return DAG.getNode(ISD::FSUB, N->getDebugLoc(), VT, N1,
4135193323Sed                       GetNegatedExpression(N0, DAG, LegalOperations));
4136193323Sed
4137193323Sed  // If allowed, fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
4138193323Sed  if (UnsafeFPMath && N1CFP && N0.getOpcode() == ISD::FADD &&
4139193323Sed      N0.getNode()->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1)))
4140193323Sed    return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N0.getOperand(0),
4141193323Sed                       DAG.getNode(ISD::FADD, N->getDebugLoc(), VT,
4142193323Sed                                   N0.getOperand(1), N1));
4143193323Sed
4144193323Sed  return SDValue();
4145193323Sed}
4146193323Sed
4147193323SedSDValue DAGCombiner::visitFSUB(SDNode *N) {
4148193323Sed  SDValue N0 = N->getOperand(0);
4149193323Sed  SDValue N1 = N->getOperand(1);
4150193323Sed  ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
4151193323Sed  ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
4152198090Srdivacky  EVT VT = N->getValueType(0);
4153193323Sed
4154193323Sed  // fold vector ops
4155193323Sed  if (VT.isVector()) {
4156193323Sed    SDValue FoldedVOp = SimplifyVBinOp(N);
4157193323Sed    if (FoldedVOp.getNode()) return FoldedVOp;
4158193323Sed  }
4159193323Sed
4160193323Sed  // fold (fsub c1, c2) -> c1-c2
4161193323Sed  if (N0CFP && N1CFP && VT != MVT::ppcf128)
4162193323Sed    return DAG.getNode(ISD::FSUB, N->getDebugLoc(), VT, N0, N1);
4163193323Sed  // fold (fsub A, 0) -> A
4164193323Sed  if (UnsafeFPMath && N1CFP && N1CFP->getValueAPF().isZero())
4165193323Sed    return N0;
4166193323Sed  // fold (fsub 0, B) -> -B
4167193323Sed  if (UnsafeFPMath && N0CFP && N0CFP->getValueAPF().isZero()) {
4168193323Sed    if (isNegatibleForFree(N1, LegalOperations))
4169193323Sed      return GetNegatedExpression(N1, DAG, LegalOperations);
4170193323Sed    if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
4171193323Sed      return DAG.getNode(ISD::FNEG, N->getDebugLoc(), VT, N1);
4172193323Sed  }
4173193323Sed  // fold (fsub A, (fneg B)) -> (fadd A, B)
4174193323Sed  if (isNegatibleForFree(N1, LegalOperations))
4175193323Sed    return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N0,
4176193323Sed                       GetNegatedExpression(N1, DAG, LegalOperations));
4177193323Sed
4178193323Sed  return SDValue();
4179193323Sed}
4180193323Sed
4181193323SedSDValue DAGCombiner::visitFMUL(SDNode *N) {
4182193323Sed  SDValue N0 = N->getOperand(0);
4183193323Sed  SDValue N1 = N->getOperand(1);
4184193323Sed  ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
4185193323Sed  ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
4186198090Srdivacky  EVT VT = N->getValueType(0);
4187193323Sed
4188193323Sed  // fold vector ops
4189193323Sed  if (VT.isVector()) {
4190193323Sed    SDValue FoldedVOp = SimplifyVBinOp(N);
4191193323Sed    if (FoldedVOp.getNode()) return FoldedVOp;
4192193323Sed  }
4193193323Sed
4194193323Sed  // fold (fmul c1, c2) -> c1*c2
4195193323Sed  if (N0CFP && N1CFP && VT != MVT::ppcf128)
4196193323Sed    return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT, N0, N1);
4197193323Sed  // canonicalize constant to RHS
4198193323Sed  if (N0CFP && !N1CFP)
4199193323Sed    return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT, N1, N0);
4200193323Sed  // fold (fmul A, 0) -> 0
4201193323Sed  if (UnsafeFPMath && N1CFP && N1CFP->getValueAPF().isZero())
4202193323Sed    return N1;
4203193574Sed  // fold (fmul A, 0) -> 0, vector edition.
4204193574Sed  if (UnsafeFPMath && ISD::isBuildVectorAllZeros(N1.getNode()))
4205193574Sed    return N1;
4206193323Sed  // fold (fmul X, 2.0) -> (fadd X, X)
4207193323Sed  if (N1CFP && N1CFP->isExactlyValue(+2.0))
4208193323Sed    return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N0, N0);
4209198090Srdivacky  // fold (fmul X, -1.0) -> (fneg X)
4210193323Sed  if (N1CFP && N1CFP->isExactlyValue(-1.0))
4211193323Sed    if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
4212193323Sed      return DAG.getNode(ISD::FNEG, N->getDebugLoc(), VT, N0);
4213193323Sed
4214193323Sed  // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
4215193323Sed  if (char LHSNeg = isNegatibleForFree(N0, LegalOperations)) {
4216193323Sed    if (char RHSNeg = isNegatibleForFree(N1, LegalOperations)) {
4217193323Sed      // Both can be negated for free, check to see if at least one is cheaper
4218193323Sed      // negated.
4219193323Sed      if (LHSNeg == 2 || RHSNeg == 2)
4220193323Sed        return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT,
4221193323Sed                           GetNegatedExpression(N0, DAG, LegalOperations),
4222193323Sed                           GetNegatedExpression(N1, DAG, LegalOperations));
4223193323Sed    }
4224193323Sed  }
4225193323Sed
4226193323Sed  // If allowed, fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
4227193323Sed  if (UnsafeFPMath && N1CFP && N0.getOpcode() == ISD::FMUL &&
4228193323Sed      N0.getNode()->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1)))
4229193323Sed    return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT, N0.getOperand(0),
4230193323Sed                       DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT,
4231193323Sed                                   N0.getOperand(1), N1));
4232193323Sed
4233193323Sed  return SDValue();
4234193323Sed}
4235193323Sed
4236193323SedSDValue DAGCombiner::visitFDIV(SDNode *N) {
4237193323Sed  SDValue N0 = N->getOperand(0);
4238193323Sed  SDValue N1 = N->getOperand(1);
4239193323Sed  ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
4240193323Sed  ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
4241198090Srdivacky  EVT VT = N->getValueType(0);
4242193323Sed
4243193323Sed  // fold vector ops
4244193323Sed  if (VT.isVector()) {
4245193323Sed    SDValue FoldedVOp = SimplifyVBinOp(N);
4246193323Sed    if (FoldedVOp.getNode()) return FoldedVOp;
4247193323Sed  }
4248193323Sed
4249193323Sed  // fold (fdiv c1, c2) -> c1/c2
4250193323Sed  if (N0CFP && N1CFP && VT != MVT::ppcf128)
4251193323Sed    return DAG.getNode(ISD::FDIV, N->getDebugLoc(), VT, N0, N1);
4252193323Sed
4253193323Sed
4254193323Sed  // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
4255193323Sed  if (char LHSNeg = isNegatibleForFree(N0, LegalOperations)) {
4256193323Sed    if (char RHSNeg = isNegatibleForFree(N1, LegalOperations)) {
4257193323Sed      // Both can be negated for free, check to see if at least one is cheaper
4258193323Sed      // negated.
4259193323Sed      if (LHSNeg == 2 || RHSNeg == 2)
4260193323Sed        return DAG.getNode(ISD::FDIV, N->getDebugLoc(), VT,
4261193323Sed                           GetNegatedExpression(N0, DAG, LegalOperations),
4262193323Sed                           GetNegatedExpression(N1, DAG, LegalOperations));
4263193323Sed    }
4264193323Sed  }
4265193323Sed
4266193323Sed  return SDValue();
4267193323Sed}
4268193323Sed
4269193323SedSDValue DAGCombiner::visitFREM(SDNode *N) {
4270193323Sed  SDValue N0 = N->getOperand(0);
4271193323Sed  SDValue N1 = N->getOperand(1);
4272193323Sed  ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
4273193323Sed  ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
4274198090Srdivacky  EVT VT = N->getValueType(0);
4275193323Sed
4276193323Sed  // fold (frem c1, c2) -> fmod(c1,c2)
4277193323Sed  if (N0CFP && N1CFP && VT != MVT::ppcf128)
4278193323Sed    return DAG.getNode(ISD::FREM, N->getDebugLoc(), VT, N0, N1);
4279193323Sed
4280193323Sed  return SDValue();
4281193323Sed}
4282193323Sed
4283193323SedSDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
4284193323Sed  SDValue N0 = N->getOperand(0);
4285193323Sed  SDValue N1 = N->getOperand(1);
4286193323Sed  ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
4287193323Sed  ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
4288198090Srdivacky  EVT VT = N->getValueType(0);
4289193323Sed
4290193323Sed  if (N0CFP && N1CFP && VT != MVT::ppcf128)  // Constant fold
4291193323Sed    return DAG.getNode(ISD::FCOPYSIGN, N->getDebugLoc(), VT, N0, N1);
4292193323Sed
4293193323Sed  if (N1CFP) {
4294193323Sed    const APFloat& V = N1CFP->getValueAPF();
4295193323Sed    // copysign(x, c1) -> fabs(x)       iff ispos(c1)
4296193323Sed    // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
4297193323Sed    if (!V.isNegative()) {
4298193323Sed      if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
4299193323Sed        return DAG.getNode(ISD::FABS, N->getDebugLoc(), VT, N0);
4300193323Sed    } else {
4301193323Sed      if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
4302193323Sed        return DAG.getNode(ISD::FNEG, N->getDebugLoc(), VT,
4303193323Sed                           DAG.getNode(ISD::FABS, N0.getDebugLoc(), VT, N0));
4304193323Sed    }
4305193323Sed  }
4306193323Sed
4307193323Sed  // copysign(fabs(x), y) -> copysign(x, y)
4308193323Sed  // copysign(fneg(x), y) -> copysign(x, y)
4309193323Sed  // copysign(copysign(x,z), y) -> copysign(x, y)
4310193323Sed  if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
4311193323Sed      N0.getOpcode() == ISD::FCOPYSIGN)
4312193323Sed    return DAG.getNode(ISD::FCOPYSIGN, N->getDebugLoc(), VT,
4313193323Sed                       N0.getOperand(0), N1);
4314193323Sed
4315193323Sed  // copysign(x, abs(y)) -> abs(x)
4316193323Sed  if (N1.getOpcode() == ISD::FABS)
4317193323Sed    return DAG.getNode(ISD::FABS, N->getDebugLoc(), VT, N0);
4318193323Sed
4319193323Sed  // copysign(x, copysign(y,z)) -> copysign(x, z)
4320193323Sed  if (N1.getOpcode() == ISD::FCOPYSIGN)
4321193323Sed    return DAG.getNode(ISD::FCOPYSIGN, N->getDebugLoc(), VT,
4322193323Sed                       N0, N1.getOperand(1));
4323193323Sed
4324193323Sed  // copysign(x, fp_extend(y)) -> copysign(x, y)
4325193323Sed  // copysign(x, fp_round(y)) -> copysign(x, y)
4326193323Sed  if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
4327193323Sed    return DAG.getNode(ISD::FCOPYSIGN, N->getDebugLoc(), VT,
4328193323Sed                       N0, N1.getOperand(0));
4329193323Sed
4330193323Sed  return SDValue();
4331193323Sed}
4332193323Sed
4333193323SedSDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
4334193323Sed  SDValue N0 = N->getOperand(0);
4335193323Sed  ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4336198090Srdivacky  EVT VT = N->getValueType(0);
4337198090Srdivacky  EVT OpVT = N0.getValueType();
4338193323Sed
4339193323Sed  // fold (sint_to_fp c1) -> c1fp
4340193323Sed  if (N0C && OpVT != MVT::ppcf128)
4341193323Sed    return DAG.getNode(ISD::SINT_TO_FP, N->getDebugLoc(), VT, N0);
4342193323Sed
4343193323Sed  // If the input is a legal type, and SINT_TO_FP is not legal on this target,
4344193323Sed  // but UINT_TO_FP is legal on this target, try to convert.
4345193323Sed  if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
4346193323Sed      TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
4347193323Sed    // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
4348193323Sed    if (DAG.SignBitIsZero(N0))
4349193323Sed      return DAG.getNode(ISD::UINT_TO_FP, N->getDebugLoc(), VT, N0);
4350193323Sed  }
4351193323Sed
4352193323Sed  return SDValue();
4353193323Sed}
4354193323Sed
4355193323SedSDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
4356193323Sed  SDValue N0 = N->getOperand(0);
4357193323Sed  ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4358198090Srdivacky  EVT VT = N->getValueType(0);
4359198090Srdivacky  EVT OpVT = N0.getValueType();
4360193323Sed
4361193323Sed  // fold (uint_to_fp c1) -> c1fp
4362193323Sed  if (N0C && OpVT != MVT::ppcf128)
4363193323Sed    return DAG.getNode(ISD::UINT_TO_FP, N->getDebugLoc(), VT, N0);
4364193323Sed
4365193323Sed  // If the input is a legal type, and UINT_TO_FP is not legal on this target,
4366193323Sed  // but SINT_TO_FP is legal on this target, try to convert.
4367193323Sed  if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
4368193323Sed      TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
4369193323Sed    // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
4370193323Sed    if (DAG.SignBitIsZero(N0))
4371193323Sed      return DAG.getNode(ISD::SINT_TO_FP, N->getDebugLoc(), VT, N0);
4372193323Sed  }
4373193323Sed
4374193323Sed  return SDValue();
4375193323Sed}
4376193323Sed
4377193323SedSDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
4378193323Sed  SDValue N0 = N->getOperand(0);
4379193323Sed  ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
4380198090Srdivacky  EVT VT = N->getValueType(0);
4381193323Sed
4382193323Sed  // fold (fp_to_sint c1fp) -> c1
4383193323Sed  if (N0CFP)
4384193323Sed    return DAG.getNode(ISD::FP_TO_SINT, N->getDebugLoc(), VT, N0);
4385193323Sed
4386193323Sed  return SDValue();
4387193323Sed}
4388193323Sed
4389193323SedSDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
4390193323Sed  SDValue N0 = N->getOperand(0);
4391193323Sed  ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
4392198090Srdivacky  EVT VT = N->getValueType(0);
4393193323Sed
4394193323Sed  // fold (fp_to_uint c1fp) -> c1
4395193323Sed  if (N0CFP && VT != MVT::ppcf128)
4396193323Sed    return DAG.getNode(ISD::FP_TO_UINT, N->getDebugLoc(), VT, N0);
4397193323Sed
4398193323Sed  return SDValue();
4399193323Sed}
4400193323Sed
4401193323SedSDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
4402193323Sed  SDValue N0 = N->getOperand(0);
4403193323Sed  SDValue N1 = N->getOperand(1);
4404193323Sed  ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
4405198090Srdivacky  EVT VT = N->getValueType(0);
4406193323Sed
4407193323Sed  // fold (fp_round c1fp) -> c1fp
4408193323Sed  if (N0CFP && N0.getValueType() != MVT::ppcf128)
4409193323Sed    return DAG.getNode(ISD::FP_ROUND, N->getDebugLoc(), VT, N0, N1);
4410193323Sed
4411193323Sed  // fold (fp_round (fp_extend x)) -> x
4412193323Sed  if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
4413193323Sed    return N0.getOperand(0);
4414193323Sed
4415193323Sed  // fold (fp_round (fp_round x)) -> (fp_round x)
4416193323Sed  if (N0.getOpcode() == ISD::FP_ROUND) {
4417193323Sed    // This is a value preserving truncation if both round's are.
4418193323Sed    bool IsTrunc = N->getConstantOperandVal(1) == 1 &&
4419193323Sed                   N0.getNode()->getConstantOperandVal(1) == 1;
4420193323Sed    return DAG.getNode(ISD::FP_ROUND, N->getDebugLoc(), VT, N0.getOperand(0),
4421193323Sed                       DAG.getIntPtrConstant(IsTrunc));
4422193323Sed  }
4423193323Sed
4424193323Sed  // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
4425193323Sed  if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
4426193323Sed    SDValue Tmp = DAG.getNode(ISD::FP_ROUND, N0.getDebugLoc(), VT,
4427193323Sed                              N0.getOperand(0), N1);
4428193323Sed    AddToWorkList(Tmp.getNode());
4429193323Sed    return DAG.getNode(ISD::FCOPYSIGN, N->getDebugLoc(), VT,
4430193323Sed                       Tmp, N0.getOperand(1));
4431193323Sed  }
4432193323Sed
4433193323Sed  return SDValue();
4434193323Sed}
4435193323Sed
4436193323SedSDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
4437193323Sed  SDValue N0 = N->getOperand(0);
4438198090Srdivacky  EVT VT = N->getValueType(0);
4439198090Srdivacky  EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
4440193323Sed  ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
4441193323Sed
4442193323Sed  // fold (fp_round_inreg c1fp) -> c1fp
4443193323Sed  if (N0CFP && (TLI.isTypeLegal(EVT) || !LegalTypes)) {
4444193323Sed    SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT);
4445193323Sed    return DAG.getNode(ISD::FP_EXTEND, N->getDebugLoc(), VT, Round);
4446193323Sed  }
4447193323Sed
4448193323Sed  return SDValue();
4449193323Sed}
4450193323Sed
4451193323SedSDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
4452193323Sed  SDValue N0 = N->getOperand(0);
4453193323Sed  ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
4454198090Srdivacky  EVT VT = N->getValueType(0);
4455193323Sed
4456193323Sed  // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
4457193323Sed  if (N->hasOneUse() &&
4458193323Sed      N->use_begin()->getOpcode() == ISD::FP_ROUND)
4459193323Sed    return SDValue();
4460193323Sed
4461193323Sed  // fold (fp_extend c1fp) -> c1fp
4462193323Sed  if (N0CFP && VT != MVT::ppcf128)
4463193323Sed    return DAG.getNode(ISD::FP_EXTEND, N->getDebugLoc(), VT, N0);
4464193323Sed
4465193323Sed  // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
4466193323Sed  // value of X.
4467193323Sed  if (N0.getOpcode() == ISD::FP_ROUND
4468193323Sed      && N0.getNode()->getConstantOperandVal(1) == 1) {
4469193323Sed    SDValue In = N0.getOperand(0);
4470193323Sed    if (In.getValueType() == VT) return In;
4471193323Sed    if (VT.bitsLT(In.getValueType()))
4472193323Sed      return DAG.getNode(ISD::FP_ROUND, N->getDebugLoc(), VT,
4473193323Sed                         In, N0.getOperand(1));
4474193323Sed    return DAG.getNode(ISD::FP_EXTEND, N->getDebugLoc(), VT, In);
4475193323Sed  }
4476193323Sed
4477193323Sed  // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
4478193323Sed  if (ISD::isNON_EXTLoad(N0.getNode()) && N0.hasOneUse() &&
4479193323Sed      ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
4480193323Sed       TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
4481193323Sed    LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4482193323Sed    SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, N->getDebugLoc(), VT,
4483193323Sed                                     LN0->getChain(),
4484193323Sed                                     LN0->getBasePtr(), LN0->getSrcValue(),
4485193323Sed                                     LN0->getSrcValueOffset(),
4486193323Sed                                     N0.getValueType(),
4487193323Sed                                     LN0->isVolatile(), LN0->getAlignment());
4488193323Sed    CombineTo(N, ExtLoad);
4489193323Sed    CombineTo(N0.getNode(),
4490193323Sed              DAG.getNode(ISD::FP_ROUND, N0.getDebugLoc(),
4491193323Sed                          N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)),
4492193323Sed              ExtLoad.getValue(1));
4493193323Sed    return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4494193323Sed  }
4495193323Sed
4496193323Sed  return SDValue();
4497193323Sed}
4498193323Sed
4499193323SedSDValue DAGCombiner::visitFNEG(SDNode *N) {
4500193323Sed  SDValue N0 = N->getOperand(0);
4501198396Srdivacky  EVT VT = N->getValueType(0);
4502193323Sed
4503193323Sed  if (isNegatibleForFree(N0, LegalOperations))
4504193323Sed    return GetNegatedExpression(N0, DAG, LegalOperations);
4505193323Sed
4506193323Sed  // Transform fneg(bitconvert(x)) -> bitconvert(x^sign) to avoid loading
4507193323Sed  // constant pool values.
4508198396Srdivacky  if (N0.getOpcode() == ISD::BIT_CONVERT &&
4509198396Srdivacky      !VT.isVector() &&
4510198396Srdivacky      N0.getNode()->hasOneUse() &&
4511198396Srdivacky      N0.getOperand(0).getValueType().isInteger()) {
4512193323Sed    SDValue Int = N0.getOperand(0);
4513198090Srdivacky    EVT IntVT = Int.getValueType();
4514193323Sed    if (IntVT.isInteger() && !IntVT.isVector()) {
4515193323Sed      Int = DAG.getNode(ISD::XOR, N0.getDebugLoc(), IntVT, Int,
4516193323Sed              DAG.getConstant(APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
4517193323Sed      AddToWorkList(Int.getNode());
4518193323Sed      return DAG.getNode(ISD::BIT_CONVERT, N->getDebugLoc(),
4519198396Srdivacky                         VT, Int);
4520193323Sed    }
4521193323Sed  }
4522193323Sed
4523193323Sed  return SDValue();
4524193323Sed}
4525193323Sed
4526193323SedSDValue DAGCombiner::visitFABS(SDNode *N) {
4527193323Sed  SDValue N0 = N->getOperand(0);
4528193323Sed  ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
4529198090Srdivacky  EVT VT = N->getValueType(0);
4530193323Sed
4531193323Sed  // fold (fabs c1) -> fabs(c1)
4532193323Sed  if (N0CFP && VT != MVT::ppcf128)
4533193323Sed    return DAG.getNode(ISD::FABS, N->getDebugLoc(), VT, N0);
4534193323Sed  // fold (fabs (fabs x)) -> (fabs x)
4535193323Sed  if (N0.getOpcode() == ISD::FABS)
4536193323Sed    return N->getOperand(0);
4537193323Sed  // fold (fabs (fneg x)) -> (fabs x)
4538193323Sed  // fold (fabs (fcopysign x, y)) -> (fabs x)
4539193323Sed  if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
4540193323Sed    return DAG.getNode(ISD::FABS, N->getDebugLoc(), VT, N0.getOperand(0));
4541193323Sed
4542193323Sed  // Transform fabs(bitconvert(x)) -> bitconvert(x&~sign) to avoid loading
4543193323Sed  // constant pool values.
4544193323Sed  if (N0.getOpcode() == ISD::BIT_CONVERT && N0.getNode()->hasOneUse() &&
4545193323Sed      N0.getOperand(0).getValueType().isInteger() &&
4546193323Sed      !N0.getOperand(0).getValueType().isVector()) {
4547193323Sed    SDValue Int = N0.getOperand(0);
4548198090Srdivacky    EVT IntVT = Int.getValueType();
4549193323Sed    if (IntVT.isInteger() && !IntVT.isVector()) {
4550193323Sed      Int = DAG.getNode(ISD::AND, N0.getDebugLoc(), IntVT, Int,
4551193323Sed             DAG.getConstant(~APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
4552193323Sed      AddToWorkList(Int.getNode());
4553193323Sed      return DAG.getNode(ISD::BIT_CONVERT, N->getDebugLoc(),
4554193323Sed                         N->getValueType(0), Int);
4555193323Sed    }
4556193323Sed  }
4557193323Sed
4558193323Sed  return SDValue();
4559193323Sed}
4560193323Sed
4561193323SedSDValue DAGCombiner::visitBRCOND(SDNode *N) {
4562193323Sed  SDValue Chain = N->getOperand(0);
4563193323Sed  SDValue N1 = N->getOperand(1);
4564193323Sed  SDValue N2 = N->getOperand(2);
4565193323Sed
4566199481Srdivacky  // If N is a constant we could fold this into a fallthrough or unconditional
4567199481Srdivacky  // branch. However that doesn't happen very often in normal code, because
4568199481Srdivacky  // Instcombine/SimplifyCFG should have handled the available opportunities.
4569199481Srdivacky  // If we did this folding here, it would be necessary to update the
4570199481Srdivacky  // MachineBasicBlock CFG, which is awkward.
4571199481Srdivacky
4572193323Sed  // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
4573193323Sed  // on the target.
4574193323Sed  if (N1.getOpcode() == ISD::SETCC &&
4575193323Sed      TLI.isOperationLegalOrCustom(ISD::BR_CC, MVT::Other)) {
4576193323Sed    return DAG.getNode(ISD::BR_CC, N->getDebugLoc(), MVT::Other,
4577193323Sed                       Chain, N1.getOperand(2),
4578193323Sed                       N1.getOperand(0), N1.getOperand(1), N2);
4579193323Sed  }
4580193323Sed
4581202375Srdivacky  SDNode *Trunc = 0;
4582202375Srdivacky  if (N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) {
4583202375Srdivacky    // Look pass truncate.
4584202375Srdivacky    Trunc = N1.getNode();
4585202375Srdivacky    N1 = N1.getOperand(0);
4586202375Srdivacky  }
4587202375Srdivacky
4588193323Sed  if (N1.hasOneUse() && N1.getOpcode() == ISD::SRL) {
4589193323Sed    // Match this pattern so that we can generate simpler code:
4590193323Sed    //
4591193323Sed    //   %a = ...
4592193323Sed    //   %b = and i32 %a, 2
4593193323Sed    //   %c = srl i32 %b, 1
4594193323Sed    //   brcond i32 %c ...
4595193323Sed    //
4596193323Sed    // into
4597193323Sed    //
4598193323Sed    //   %a = ...
4599202375Srdivacky    //   %b = and i32 %a, 2
4600193323Sed    //   %c = setcc eq %b, 0
4601193323Sed    //   brcond %c ...
4602193323Sed    //
4603193323Sed    // This applies only when the AND constant value has one bit set and the
4604193323Sed    // SRL constant is equal to the log2 of the AND constant. The back-end is
4605193323Sed    // smart enough to convert the result into a TEST/JMP sequence.
4606193323Sed    SDValue Op0 = N1.getOperand(0);
4607193323Sed    SDValue Op1 = N1.getOperand(1);
4608193323Sed
4609193323Sed    if (Op0.getOpcode() == ISD::AND &&
4610193323Sed        Op1.getOpcode() == ISD::Constant) {
4611193323Sed      SDValue AndOp1 = Op0.getOperand(1);
4612193323Sed
4613193323Sed      if (AndOp1.getOpcode() == ISD::Constant) {
4614193323Sed        const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
4615193323Sed
4616193323Sed        if (AndConst.isPowerOf2() &&
4617193323Sed            cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
4618193323Sed          SDValue SetCC =
4619193323Sed            DAG.getSetCC(N->getDebugLoc(),
4620193323Sed                         TLI.getSetCCResultType(Op0.getValueType()),
4621193323Sed                         Op0, DAG.getConstant(0, Op0.getValueType()),
4622193323Sed                         ISD::SETNE);
4623193323Sed
4624202375Srdivacky          SDValue NewBRCond = DAG.getNode(ISD::BRCOND, N->getDebugLoc(),
4625202375Srdivacky                                          MVT::Other, Chain, SetCC, N2);
4626202375Srdivacky          // Don't add the new BRCond into the worklist or else SimplifySelectCC
4627202375Srdivacky          // will convert it back to (X & C1) >> C2.
4628202375Srdivacky          CombineTo(N, NewBRCond, false);
4629202375Srdivacky          // Truncate is dead.
4630202375Srdivacky          if (Trunc) {
4631202375Srdivacky            removeFromWorkList(Trunc);
4632202375Srdivacky            DAG.DeleteNode(Trunc);
4633202375Srdivacky          }
4634193323Sed          // Replace the uses of SRL with SETCC
4635193323Sed          DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
4636193323Sed          removeFromWorkList(N1.getNode());
4637193323Sed          DAG.DeleteNode(N1.getNode());
4638202375Srdivacky          return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4639193323Sed        }
4640193323Sed      }
4641193323Sed    }
4642193323Sed  }
4643193323Sed
4644193323Sed  return SDValue();
4645193323Sed}
4646193323Sed
4647193323Sed// Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
4648193323Sed//
4649193323SedSDValue DAGCombiner::visitBR_CC(SDNode *N) {
4650193323Sed  CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
4651193323Sed  SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
4652193323Sed
4653199481Srdivacky  // If N is a constant we could fold this into a fallthrough or unconditional
4654199481Srdivacky  // branch. However that doesn't happen very often in normal code, because
4655199481Srdivacky  // Instcombine/SimplifyCFG should have handled the available opportunities.
4656199481Srdivacky  // If we did this folding here, it would be necessary to update the
4657199481Srdivacky  // MachineBasicBlock CFG, which is awkward.
4658199481Srdivacky
4659193323Sed  // Use SimplifySetCC to simplify SETCC's.
4660193323Sed  SDValue Simp = SimplifySetCC(TLI.getSetCCResultType(CondLHS.getValueType()),
4661193323Sed                               CondLHS, CondRHS, CC->get(), N->getDebugLoc(),
4662193323Sed                               false);
4663193323Sed  if (Simp.getNode()) AddToWorkList(Simp.getNode());
4664193323Sed
4665193323Sed  // fold to a simpler setcc
4666193323Sed  if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
4667193323Sed    return DAG.getNode(ISD::BR_CC, N->getDebugLoc(), MVT::Other,
4668193323Sed                       N->getOperand(0), Simp.getOperand(2),
4669193323Sed                       Simp.getOperand(0), Simp.getOperand(1),
4670193323Sed                       N->getOperand(4));
4671193323Sed
4672193323Sed  return SDValue();
4673193323Sed}
4674193323Sed
4675193323Sed/// CombineToPreIndexedLoadStore - Try turning a load / store into a
4676193323Sed/// pre-indexed load / store when the base pointer is an add or subtract
4677193323Sed/// and it has other uses besides the load / store. After the
4678193323Sed/// transformation, the new indexed load / store has effectively folded
4679193323Sed/// the add / subtract in and all of its other uses are redirected to the
4680193323Sed/// new load / store.
4681193323Sedbool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
4682193323Sed  if (!LegalOperations)
4683193323Sed    return false;
4684193323Sed
4685193323Sed  bool isLoad = true;
4686193323Sed  SDValue Ptr;
4687198090Srdivacky  EVT VT;
4688193323Sed  if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
4689193323Sed    if (LD->isIndexed())
4690193323Sed      return false;
4691193323Sed    VT = LD->getMemoryVT();
4692193323Sed    if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
4693193323Sed        !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
4694193323Sed      return false;
4695193323Sed    Ptr = LD->getBasePtr();
4696193323Sed  } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
4697193323Sed    if (ST->isIndexed())
4698193323Sed      return false;
4699193323Sed    VT = ST->getMemoryVT();
4700193323Sed    if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
4701193323Sed        !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
4702193323Sed      return false;
4703193323Sed    Ptr = ST->getBasePtr();
4704193323Sed    isLoad = false;
4705193323Sed  } else {
4706193323Sed    return false;
4707193323Sed  }
4708193323Sed
4709193323Sed  // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
4710193323Sed  // out.  There is no reason to make this a preinc/predec.
4711193323Sed  if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
4712193323Sed      Ptr.getNode()->hasOneUse())
4713193323Sed    return false;
4714193323Sed
4715193323Sed  // Ask the target to do addressing mode selection.
4716193323Sed  SDValue BasePtr;
4717193323Sed  SDValue Offset;
4718193323Sed  ISD::MemIndexedMode AM = ISD::UNINDEXED;
4719193323Sed  if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
4720193323Sed    return false;
4721193323Sed  // Don't create a indexed load / store with zero offset.
4722193323Sed  if (isa<ConstantSDNode>(Offset) &&
4723193323Sed      cast<ConstantSDNode>(Offset)->isNullValue())
4724193323Sed    return false;
4725193323Sed
4726193323Sed  // Try turning it into a pre-indexed load / store except when:
4727193323Sed  // 1) The new base ptr is a frame index.
4728193323Sed  // 2) If N is a store and the new base ptr is either the same as or is a
4729193323Sed  //    predecessor of the value being stored.
4730193323Sed  // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
4731193323Sed  //    that would create a cycle.
4732193323Sed  // 4) All uses are load / store ops that use it as old base ptr.
4733193323Sed
4734193323Sed  // Check #1.  Preinc'ing a frame index would require copying the stack pointer
4735193323Sed  // (plus the implicit offset) to a register to preinc anyway.
4736193323Sed  if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
4737193323Sed    return false;
4738193323Sed
4739193323Sed  // Check #2.
4740193323Sed  if (!isLoad) {
4741193323Sed    SDValue Val = cast<StoreSDNode>(N)->getValue();
4742193323Sed    if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
4743193323Sed      return false;
4744193323Sed  }
4745193323Sed
4746193323Sed  // Now check for #3 and #4.
4747193323Sed  bool RealUse = false;
4748193323Sed  for (SDNode::use_iterator I = Ptr.getNode()->use_begin(),
4749193323Sed         E = Ptr.getNode()->use_end(); I != E; ++I) {
4750193323Sed    SDNode *Use = *I;
4751193323Sed    if (Use == N)
4752193323Sed      continue;
4753193323Sed    if (Use->isPredecessorOf(N))
4754193323Sed      return false;
4755193323Sed
4756193323Sed    if (!((Use->getOpcode() == ISD::LOAD &&
4757193323Sed           cast<LoadSDNode>(Use)->getBasePtr() == Ptr) ||
4758193323Sed          (Use->getOpcode() == ISD::STORE &&
4759193323Sed           cast<StoreSDNode>(Use)->getBasePtr() == Ptr)))
4760193323Sed      RealUse = true;
4761193323Sed  }
4762193323Sed
4763193323Sed  if (!RealUse)
4764193323Sed    return false;
4765193323Sed
4766193323Sed  SDValue Result;
4767193323Sed  if (isLoad)
4768193323Sed    Result = DAG.getIndexedLoad(SDValue(N,0), N->getDebugLoc(),
4769193323Sed                                BasePtr, Offset, AM);
4770193323Sed  else
4771193323Sed    Result = DAG.getIndexedStore(SDValue(N,0), N->getDebugLoc(),
4772193323Sed                                 BasePtr, Offset, AM);
4773193323Sed  ++PreIndexedNodes;
4774193323Sed  ++NodesCombined;
4775202375Srdivacky  DEBUG(dbgs() << "\nReplacing.4 ";
4776198090Srdivacky        N->dump(&DAG);
4777202375Srdivacky        dbgs() << "\nWith: ";
4778198090Srdivacky        Result.getNode()->dump(&DAG);
4779202375Srdivacky        dbgs() << '\n');
4780193323Sed  WorkListRemover DeadNodes(*this);
4781193323Sed  if (isLoad) {
4782193323Sed    DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0),
4783193323Sed                                  &DeadNodes);
4784193323Sed    DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2),
4785193323Sed                                  &DeadNodes);
4786193323Sed  } else {
4787193323Sed    DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1),
4788193323Sed                                  &DeadNodes);
4789193323Sed  }
4790193323Sed
4791193323Sed  // Finally, since the node is now dead, remove it from the graph.
4792193323Sed  DAG.DeleteNode(N);
4793193323Sed
4794193323Sed  // Replace the uses of Ptr with uses of the updated base value.
4795193323Sed  DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0),
4796193323Sed                                &DeadNodes);
4797193323Sed  removeFromWorkList(Ptr.getNode());
4798193323Sed  DAG.DeleteNode(Ptr.getNode());
4799193323Sed
4800193323Sed  return true;
4801193323Sed}
4802193323Sed
4803193323Sed/// CombineToPostIndexedLoadStore - Try to combine a load / store with a
4804193323Sed/// add / sub of the base pointer node into a post-indexed load / store.
4805193323Sed/// The transformation folded the add / subtract into the new indexed
4806193323Sed/// load / store effectively and all of its uses are redirected to the
4807193323Sed/// new load / store.
4808193323Sedbool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
4809193323Sed  if (!LegalOperations)
4810193323Sed    return false;
4811193323Sed
4812193323Sed  bool isLoad = true;
4813193323Sed  SDValue Ptr;
4814198090Srdivacky  EVT VT;
4815193323Sed  if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
4816193323Sed    if (LD->isIndexed())
4817193323Sed      return false;
4818193323Sed    VT = LD->getMemoryVT();
4819193323Sed    if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
4820193323Sed        !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
4821193323Sed      return false;
4822193323Sed    Ptr = LD->getBasePtr();
4823193323Sed  } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
4824193323Sed    if (ST->isIndexed())
4825193323Sed      return false;
4826193323Sed    VT = ST->getMemoryVT();
4827193323Sed    if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
4828193323Sed        !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
4829193323Sed      return false;
4830193323Sed    Ptr = ST->getBasePtr();
4831193323Sed    isLoad = false;
4832193323Sed  } else {
4833193323Sed    return false;
4834193323Sed  }
4835193323Sed
4836193323Sed  if (Ptr.getNode()->hasOneUse())
4837193323Sed    return false;
4838193323Sed
4839193323Sed  for (SDNode::use_iterator I = Ptr.getNode()->use_begin(),
4840193323Sed         E = Ptr.getNode()->use_end(); I != E; ++I) {
4841193323Sed    SDNode *Op = *I;
4842193323Sed    if (Op == N ||
4843193323Sed        (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
4844193323Sed      continue;
4845193323Sed
4846193323Sed    SDValue BasePtr;
4847193323Sed    SDValue Offset;
4848193323Sed    ISD::MemIndexedMode AM = ISD::UNINDEXED;
4849193323Sed    if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
4850198090Srdivacky      if (Ptr == Offset && Op->getOpcode() == ISD::ADD)
4851193323Sed        std::swap(BasePtr, Offset);
4852193323Sed      if (Ptr != BasePtr)
4853193323Sed        continue;
4854193323Sed      // Don't create a indexed load / store with zero offset.
4855193323Sed      if (isa<ConstantSDNode>(Offset) &&
4856193323Sed          cast<ConstantSDNode>(Offset)->isNullValue())
4857193323Sed        continue;
4858193323Sed
4859193323Sed      // Try turning it into a post-indexed load / store except when
4860193323Sed      // 1) All uses are load / store ops that use it as base ptr.
4861193323Sed      // 2) Op must be independent of N, i.e. Op is neither a predecessor
4862193323Sed      //    nor a successor of N. Otherwise, if Op is folded that would
4863193323Sed      //    create a cycle.
4864193323Sed
4865193323Sed      if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
4866193323Sed        continue;
4867193323Sed
4868193323Sed      // Check for #1.
4869193323Sed      bool TryNext = false;
4870193323Sed      for (SDNode::use_iterator II = BasePtr.getNode()->use_begin(),
4871193323Sed             EE = BasePtr.getNode()->use_end(); II != EE; ++II) {
4872193323Sed        SDNode *Use = *II;
4873193323Sed        if (Use == Ptr.getNode())
4874193323Sed          continue;
4875193323Sed
4876193323Sed        // If all the uses are load / store addresses, then don't do the
4877193323Sed        // transformation.
4878193323Sed        if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
4879193323Sed          bool RealUse = false;
4880193323Sed          for (SDNode::use_iterator III = Use->use_begin(),
4881193323Sed                 EEE = Use->use_end(); III != EEE; ++III) {
4882193323Sed            SDNode *UseUse = *III;
4883193323Sed            if (!((UseUse->getOpcode() == ISD::LOAD &&
4884193323Sed                   cast<LoadSDNode>(UseUse)->getBasePtr().getNode() == Use) ||
4885193323Sed                  (UseUse->getOpcode() == ISD::STORE &&
4886193323Sed                   cast<StoreSDNode>(UseUse)->getBasePtr().getNode() == Use)))
4887193323Sed              RealUse = true;
4888193323Sed          }
4889193323Sed
4890193323Sed          if (!RealUse) {
4891193323Sed            TryNext = true;
4892193323Sed            break;
4893193323Sed          }
4894193323Sed        }
4895193323Sed      }
4896193323Sed
4897193323Sed      if (TryNext)
4898193323Sed        continue;
4899193323Sed
4900193323Sed      // Check for #2
4901193323Sed      if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
4902193323Sed        SDValue Result = isLoad
4903193323Sed          ? DAG.getIndexedLoad(SDValue(N,0), N->getDebugLoc(),
4904193323Sed                               BasePtr, Offset, AM)
4905193323Sed          : DAG.getIndexedStore(SDValue(N,0), N->getDebugLoc(),
4906193323Sed                                BasePtr, Offset, AM);
4907193323Sed        ++PostIndexedNodes;
4908193323Sed        ++NodesCombined;
4909202375Srdivacky        DEBUG(dbgs() << "\nReplacing.5 ";
4910198090Srdivacky              N->dump(&DAG);
4911202375Srdivacky              dbgs() << "\nWith: ";
4912198090Srdivacky              Result.getNode()->dump(&DAG);
4913202375Srdivacky              dbgs() << '\n');
4914193323Sed        WorkListRemover DeadNodes(*this);
4915193323Sed        if (isLoad) {
4916193323Sed          DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0),
4917193323Sed                                        &DeadNodes);
4918193323Sed          DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2),
4919193323Sed                                        &DeadNodes);
4920193323Sed        } else {
4921193323Sed          DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1),
4922193323Sed                                        &DeadNodes);
4923193323Sed        }
4924193323Sed
4925193323Sed        // Finally, since the node is now dead, remove it from the graph.
4926193323Sed        DAG.DeleteNode(N);
4927193323Sed
4928193323Sed        // Replace the uses of Use with uses of the updated base value.
4929193323Sed        DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
4930193323Sed                                      Result.getValue(isLoad ? 1 : 0),
4931193323Sed                                      &DeadNodes);
4932193323Sed        removeFromWorkList(Op);
4933193323Sed        DAG.DeleteNode(Op);
4934193323Sed        return true;
4935193323Sed      }
4936193323Sed    }
4937193323Sed  }
4938193323Sed
4939193323Sed  return false;
4940193323Sed}
4941193323Sed
4942193323SedSDValue DAGCombiner::visitLOAD(SDNode *N) {
4943193323Sed  LoadSDNode *LD  = cast<LoadSDNode>(N);
4944193323Sed  SDValue Chain = LD->getChain();
4945193323Sed  SDValue Ptr   = LD->getBasePtr();
4946193323Sed
4947193323Sed  // Try to infer better alignment information than the load already has.
4948193323Sed  if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
4949200581Srdivacky    if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
4950193323Sed      if (Align > LD->getAlignment())
4951193323Sed        return DAG.getExtLoad(LD->getExtensionType(), N->getDebugLoc(),
4952193323Sed                              LD->getValueType(0),
4953193323Sed                              Chain, Ptr, LD->getSrcValue(),
4954193323Sed                              LD->getSrcValueOffset(), LD->getMemoryVT(),
4955193323Sed                              LD->isVolatile(), Align);
4956193323Sed    }
4957193323Sed  }
4958193323Sed
4959193323Sed  // If load is not volatile and there are no uses of the loaded value (and
4960193323Sed  // the updated indexed value in case of indexed loads), change uses of the
4961193323Sed  // chain value into uses of the chain input (i.e. delete the dead load).
4962193323Sed  if (!LD->isVolatile()) {
4963193323Sed    if (N->getValueType(1) == MVT::Other) {
4964193323Sed      // Unindexed loads.
4965193323Sed      if (N->hasNUsesOfValue(0, 0)) {
4966193323Sed        // It's not safe to use the two value CombineTo variant here. e.g.
4967193323Sed        // v1, chain2 = load chain1, loc
4968193323Sed        // v2, chain3 = load chain2, loc
4969193323Sed        // v3         = add v2, c
4970193323Sed        // Now we replace use of chain2 with chain1.  This makes the second load
4971193323Sed        // isomorphic to the one we are deleting, and thus makes this load live.
4972202375Srdivacky        DEBUG(dbgs() << "\nReplacing.6 ";
4973198090Srdivacky              N->dump(&DAG);
4974202375Srdivacky              dbgs() << "\nWith chain: ";
4975198090Srdivacky              Chain.getNode()->dump(&DAG);
4976202375Srdivacky              dbgs() << "\n");
4977193323Sed        WorkListRemover DeadNodes(*this);
4978193323Sed        DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain, &DeadNodes);
4979193323Sed
4980193323Sed        if (N->use_empty()) {
4981193323Sed          removeFromWorkList(N);
4982193323Sed          DAG.DeleteNode(N);
4983193323Sed        }
4984193323Sed
4985193323Sed        return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4986193323Sed      }
4987193323Sed    } else {
4988193323Sed      // Indexed loads.
4989193323Sed      assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
4990193323Sed      if (N->hasNUsesOfValue(0, 0) && N->hasNUsesOfValue(0, 1)) {
4991193323Sed        SDValue Undef = DAG.getUNDEF(N->getValueType(0));
4992202375Srdivacky        DEBUG(dbgs() << "\nReplacing.6 ";
4993198090Srdivacky              N->dump(&DAG);
4994202375Srdivacky              dbgs() << "\nWith: ";
4995198090Srdivacky              Undef.getNode()->dump(&DAG);
4996202375Srdivacky              dbgs() << " and 2 other values\n");
4997193323Sed        WorkListRemover DeadNodes(*this);
4998193323Sed        DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef, &DeadNodes);
4999193323Sed        DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1),
5000193323Sed                                      DAG.getUNDEF(N->getValueType(1)),
5001193323Sed                                      &DeadNodes);
5002193323Sed        DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain, &DeadNodes);
5003193323Sed        removeFromWorkList(N);
5004193323Sed        DAG.DeleteNode(N);
5005193323Sed        return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5006193323Sed      }
5007193323Sed    }
5008193323Sed  }
5009193323Sed
5010193323Sed  // If this load is directly stored, replace the load value with the stored
5011193323Sed  // value.
5012193323Sed  // TODO: Handle store large -> read small portion.
5013193323Sed  // TODO: Handle TRUNCSTORE/LOADEXT
5014193323Sed  if (LD->getExtensionType() == ISD::NON_EXTLOAD &&
5015193323Sed      !LD->isVolatile()) {
5016193323Sed    if (ISD::isNON_TRUNCStore(Chain.getNode())) {
5017193323Sed      StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
5018193323Sed      if (PrevST->getBasePtr() == Ptr &&
5019193323Sed          PrevST->getValue().getValueType() == N->getValueType(0))
5020193323Sed      return CombineTo(N, Chain.getOperand(1), Chain);
5021193323Sed    }
5022193323Sed  }
5023193323Sed
5024193323Sed  if (CombinerAA) {
5025193323Sed    // Walk up chain skipping non-aliasing memory nodes.
5026193323Sed    SDValue BetterChain = FindBetterChain(N, Chain);
5027193323Sed
5028193323Sed    // If there is a better chain.
5029193323Sed    if (Chain != BetterChain) {
5030193323Sed      SDValue ReplLoad;
5031193323Sed
5032193323Sed      // Replace the chain to void dependency.
5033193323Sed      if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
5034193323Sed        ReplLoad = DAG.getLoad(N->getValueType(0), LD->getDebugLoc(),
5035193323Sed                               BetterChain, Ptr,
5036193323Sed                               LD->getSrcValue(), LD->getSrcValueOffset(),
5037193323Sed                               LD->isVolatile(), LD->getAlignment());
5038193323Sed      } else {
5039193323Sed        ReplLoad = DAG.getExtLoad(LD->getExtensionType(), LD->getDebugLoc(),
5040193323Sed                                  LD->getValueType(0),
5041193323Sed                                  BetterChain, Ptr, LD->getSrcValue(),
5042193323Sed                                  LD->getSrcValueOffset(),
5043193323Sed                                  LD->getMemoryVT(),
5044193323Sed                                  LD->isVolatile(),
5045193323Sed                                  LD->getAlignment());
5046193323Sed      }
5047193323Sed
5048193323Sed      // Create token factor to keep old chain connected.
5049193323Sed      SDValue Token = DAG.getNode(ISD::TokenFactor, N->getDebugLoc(),
5050193323Sed                                  MVT::Other, Chain, ReplLoad.getValue(1));
5051198090Srdivacky
5052198090Srdivacky      // Make sure the new and old chains are cleaned up.
5053198090Srdivacky      AddToWorkList(Token.getNode());
5054198090Srdivacky
5055193323Sed      // Replace uses with load result and token factor. Don't add users
5056193323Sed      // to work list.
5057193323Sed      return CombineTo(N, ReplLoad.getValue(0), Token, false);
5058193323Sed    }
5059193323Sed  }
5060193323Sed
5061193323Sed  // Try transforming N to an indexed load.
5062193323Sed  if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
5063193323Sed    return SDValue(N, 0);
5064193323Sed
5065193323Sed  return SDValue();
5066193323Sed}
5067193323Sed
5068193323Sed
5069193323Sed/// ReduceLoadOpStoreWidth - Look for sequence of load / op / store where op is
5070193323Sed/// one of 'or', 'xor', and 'and' of immediates. If 'op' is only touching some
5071193323Sed/// of the loaded bits, try narrowing the load and store if it would end up
5072193323Sed/// being a win for performance or code size.
5073193323SedSDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
5074193323Sed  StoreSDNode *ST  = cast<StoreSDNode>(N);
5075193323Sed  if (ST->isVolatile())
5076193323Sed    return SDValue();
5077193323Sed
5078193323Sed  SDValue Chain = ST->getChain();
5079193323Sed  SDValue Value = ST->getValue();
5080193323Sed  SDValue Ptr   = ST->getBasePtr();
5081198090Srdivacky  EVT VT = Value.getValueType();
5082193323Sed
5083193323Sed  if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
5084193323Sed    return SDValue();
5085193323Sed
5086193323Sed  unsigned Opc = Value.getOpcode();
5087193323Sed  if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
5088193323Sed      Value.getOperand(1).getOpcode() != ISD::Constant)
5089193323Sed    return SDValue();
5090193323Sed
5091193323Sed  SDValue N0 = Value.getOperand(0);
5092193323Sed  if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse()) {
5093193323Sed    LoadSDNode *LD = cast<LoadSDNode>(N0);
5094193323Sed    if (LD->getBasePtr() != Ptr)
5095193323Sed      return SDValue();
5096193323Sed
5097193323Sed    // Find the type to narrow it the load / op / store to.
5098193323Sed    SDValue N1 = Value.getOperand(1);
5099193323Sed    unsigned BitWidth = N1.getValueSizeInBits();
5100193323Sed    APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
5101193323Sed    if (Opc == ISD::AND)
5102193323Sed      Imm ^= APInt::getAllOnesValue(BitWidth);
5103193323Sed    if (Imm == 0 || Imm.isAllOnesValue())
5104193323Sed      return SDValue();
5105193323Sed    unsigned ShAmt = Imm.countTrailingZeros();
5106193323Sed    unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
5107193323Sed    unsigned NewBW = NextPowerOf2(MSB - ShAmt);
5108198090Srdivacky    EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
5109193323Sed    while (NewBW < BitWidth &&
5110193323Sed           !(TLI.isOperationLegalOrCustom(Opc, NewVT) &&
5111193323Sed             TLI.isNarrowingProfitable(VT, NewVT))) {
5112193323Sed      NewBW = NextPowerOf2(NewBW);
5113198090Srdivacky      NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
5114193323Sed    }
5115193323Sed    if (NewBW >= BitWidth)
5116193323Sed      return SDValue();
5117193323Sed
5118193323Sed    // If the lsb changed does not start at the type bitwidth boundary,
5119193323Sed    // start at the previous one.
5120193323Sed    if (ShAmt % NewBW)
5121193323Sed      ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
5122193323Sed    APInt Mask = APInt::getBitsSet(BitWidth, ShAmt, ShAmt + NewBW);
5123193323Sed    if ((Imm & Mask) == Imm) {
5124193323Sed      APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
5125193323Sed      if (Opc == ISD::AND)
5126193323Sed        NewImm ^= APInt::getAllOnesValue(NewBW);
5127193323Sed      uint64_t PtrOff = ShAmt / 8;
5128193323Sed      // For big endian targets, we need to adjust the offset to the pointer to
5129193323Sed      // load the correct bytes.
5130193323Sed      if (TLI.isBigEndian())
5131193323Sed        PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
5132193323Sed
5133193323Sed      unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
5134193323Sed      if (NewAlign <
5135198090Srdivacky          TLI.getTargetData()->getABITypeAlignment(NewVT.getTypeForEVT(*DAG.getContext())))
5136193323Sed        return SDValue();
5137193323Sed
5138193323Sed      SDValue NewPtr = DAG.getNode(ISD::ADD, LD->getDebugLoc(),
5139193323Sed                                   Ptr.getValueType(), Ptr,
5140193323Sed                                   DAG.getConstant(PtrOff, Ptr.getValueType()));
5141193323Sed      SDValue NewLD = DAG.getLoad(NewVT, N0.getDebugLoc(),
5142193323Sed                                  LD->getChain(), NewPtr,
5143193323Sed                                  LD->getSrcValue(), LD->getSrcValueOffset(),
5144193323Sed                                  LD->isVolatile(), NewAlign);
5145193323Sed      SDValue NewVal = DAG.getNode(Opc, Value.getDebugLoc(), NewVT, NewLD,
5146193323Sed                                   DAG.getConstant(NewImm, NewVT));
5147193323Sed      SDValue NewST = DAG.getStore(Chain, N->getDebugLoc(),
5148193323Sed                                   NewVal, NewPtr,
5149193323Sed                                   ST->getSrcValue(), ST->getSrcValueOffset(),
5150193323Sed                                   false, NewAlign);
5151193323Sed
5152193323Sed      AddToWorkList(NewPtr.getNode());
5153193323Sed      AddToWorkList(NewLD.getNode());
5154193323Sed      AddToWorkList(NewVal.getNode());
5155193323Sed      WorkListRemover DeadNodes(*this);
5156193323Sed      DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1),
5157193323Sed                                    &DeadNodes);
5158193323Sed      ++OpsNarrowed;
5159193323Sed      return NewST;
5160193323Sed    }
5161193323Sed  }
5162193323Sed
5163193323Sed  return SDValue();
5164193323Sed}
5165193323Sed
5166193323SedSDValue DAGCombiner::visitSTORE(SDNode *N) {
5167193323Sed  StoreSDNode *ST  = cast<StoreSDNode>(N);
5168193323Sed  SDValue Chain = ST->getChain();
5169193323Sed  SDValue Value = ST->getValue();
5170193323Sed  SDValue Ptr   = ST->getBasePtr();
5171193323Sed
5172193323Sed  // Try to infer better alignment information than the store already has.
5173193323Sed  if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
5174200581Srdivacky    if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
5175193323Sed      if (Align > ST->getAlignment())
5176193323Sed        return DAG.getTruncStore(Chain, N->getDebugLoc(), Value,
5177193323Sed                                 Ptr, ST->getSrcValue(),
5178193323Sed                                 ST->getSrcValueOffset(), ST->getMemoryVT(),
5179193323Sed                                 ST->isVolatile(), Align);
5180193323Sed    }
5181193323Sed  }
5182193323Sed
5183193323Sed  // If this is a store of a bit convert, store the input value if the
5184193323Sed  // resultant store does not need a higher alignment than the original.
5185193323Sed  if (Value.getOpcode() == ISD::BIT_CONVERT && !ST->isTruncatingStore() &&
5186193323Sed      ST->isUnindexed()) {
5187193323Sed    unsigned OrigAlign = ST->getAlignment();
5188198090Srdivacky    EVT SVT = Value.getOperand(0).getValueType();
5189193323Sed    unsigned Align = TLI.getTargetData()->
5190198090Srdivacky      getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
5191193323Sed    if (Align <= OrigAlign &&
5192193323Sed        ((!LegalOperations && !ST->isVolatile()) ||
5193193323Sed         TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
5194193323Sed      return DAG.getStore(Chain, N->getDebugLoc(), Value.getOperand(0),
5195193323Sed                          Ptr, ST->getSrcValue(),
5196193323Sed                          ST->getSrcValueOffset(), ST->isVolatile(), OrigAlign);
5197193323Sed  }
5198193323Sed
5199193323Sed  // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
5200193323Sed  if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
5201193323Sed    // NOTE: If the original store is volatile, this transform must not increase
5202193323Sed    // the number of stores.  For example, on x86-32 an f64 can be stored in one
5203193323Sed    // processor operation but an i64 (which is not legal) requires two.  So the
5204193323Sed    // transform should not be done in this case.
5205193323Sed    if (Value.getOpcode() != ISD::TargetConstantFP) {
5206193323Sed      SDValue Tmp;
5207198090Srdivacky      switch (CFP->getValueType(0).getSimpleVT().SimpleTy) {
5208198090Srdivacky      default: llvm_unreachable("Unknown FP type");
5209193323Sed      case MVT::f80:    // We don't do this for these yet.
5210193323Sed      case MVT::f128:
5211193323Sed      case MVT::ppcf128:
5212193323Sed        break;
5213193323Sed      case MVT::f32:
5214193323Sed        if (((TLI.isTypeLegal(MVT::i32) || !LegalTypes) && !LegalOperations &&
5215193323Sed             !ST->isVolatile()) ||
5216193323Sed            TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
5217193323Sed          Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
5218193323Sed                              bitcastToAPInt().getZExtValue(), MVT::i32);
5219193323Sed          return DAG.getStore(Chain, N->getDebugLoc(), Tmp,
5220193323Sed                              Ptr, ST->getSrcValue(),
5221193323Sed                              ST->getSrcValueOffset(), ST->isVolatile(),
5222193323Sed                              ST->getAlignment());
5223193323Sed        }
5224193323Sed        break;
5225193323Sed      case MVT::f64:
5226193323Sed        if (((TLI.isTypeLegal(MVT::i64) || !LegalTypes) && !LegalOperations &&
5227193323Sed             !ST->isVolatile()) ||
5228193323Sed            TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
5229193323Sed          Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
5230193323Sed                                getZExtValue(), MVT::i64);
5231193323Sed          return DAG.getStore(Chain, N->getDebugLoc(), Tmp,
5232193323Sed                              Ptr, ST->getSrcValue(),
5233193323Sed                              ST->getSrcValueOffset(), ST->isVolatile(),
5234193323Sed                              ST->getAlignment());
5235193323Sed        } else if (!ST->isVolatile() &&
5236193323Sed                   TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
5237193323Sed          // Many FP stores are not made apparent until after legalize, e.g. for
5238193323Sed          // argument passing.  Since this is so common, custom legalize the
5239193323Sed          // 64-bit integer store into two 32-bit stores.
5240193323Sed          uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
5241193323Sed          SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
5242193323Sed          SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32);
5243193323Sed          if (TLI.isBigEndian()) std::swap(Lo, Hi);
5244193323Sed
5245193323Sed          int SVOffset = ST->getSrcValueOffset();
5246193323Sed          unsigned Alignment = ST->getAlignment();
5247193323Sed          bool isVolatile = ST->isVolatile();
5248193323Sed
5249193323Sed          SDValue St0 = DAG.getStore(Chain, ST->getDebugLoc(), Lo,
5250193323Sed                                     Ptr, ST->getSrcValue(),
5251193323Sed                                     ST->getSrcValueOffset(),
5252193323Sed                                     isVolatile, ST->getAlignment());
5253193323Sed          Ptr = DAG.getNode(ISD::ADD, N->getDebugLoc(), Ptr.getValueType(), Ptr,
5254193323Sed                            DAG.getConstant(4, Ptr.getValueType()));
5255193323Sed          SVOffset += 4;
5256193323Sed          Alignment = MinAlign(Alignment, 4U);
5257193323Sed          SDValue St1 = DAG.getStore(Chain, ST->getDebugLoc(), Hi,
5258193323Sed                                     Ptr, ST->getSrcValue(),
5259193323Sed                                     SVOffset, isVolatile, Alignment);
5260193323Sed          return DAG.getNode(ISD::TokenFactor, N->getDebugLoc(), MVT::Other,
5261193323Sed                             St0, St1);
5262193323Sed        }
5263193323Sed
5264193323Sed        break;
5265193323Sed      }
5266193323Sed    }
5267193323Sed  }
5268193323Sed
5269193323Sed  if (CombinerAA) {
5270193323Sed    // Walk up chain skipping non-aliasing memory nodes.
5271193323Sed    SDValue BetterChain = FindBetterChain(N, Chain);
5272193323Sed
5273193323Sed    // If there is a better chain.
5274193323Sed    if (Chain != BetterChain) {
5275198090Srdivacky      SDValue ReplStore;
5276198090Srdivacky
5277193323Sed      // Replace the chain to avoid dependency.
5278193323Sed      if (ST->isTruncatingStore()) {
5279193323Sed        ReplStore = DAG.getTruncStore(BetterChain, N->getDebugLoc(), Value, Ptr,
5280193323Sed                                      ST->getSrcValue(),ST->getSrcValueOffset(),
5281193323Sed                                      ST->getMemoryVT(),
5282193323Sed                                      ST->isVolatile(), ST->getAlignment());
5283193323Sed      } else {
5284193323Sed        ReplStore = DAG.getStore(BetterChain, N->getDebugLoc(), Value, Ptr,
5285193323Sed                                 ST->getSrcValue(), ST->getSrcValueOffset(),
5286193323Sed                                 ST->isVolatile(), ST->getAlignment());
5287193323Sed      }
5288193323Sed
5289193323Sed      // Create token to keep both nodes around.
5290193323Sed      SDValue Token = DAG.getNode(ISD::TokenFactor, N->getDebugLoc(),
5291193323Sed                                  MVT::Other, Chain, ReplStore);
5292193323Sed
5293198090Srdivacky      // Make sure the new and old chains are cleaned up.
5294198090Srdivacky      AddToWorkList(Token.getNode());
5295198090Srdivacky
5296193323Sed      // Don't add users to work list.
5297193323Sed      return CombineTo(N, Token, false);
5298193323Sed    }
5299193323Sed  }
5300193323Sed
5301193323Sed  // Try transforming N to an indexed store.
5302193323Sed  if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
5303193323Sed    return SDValue(N, 0);
5304193323Sed
5305193323Sed  // FIXME: is there such a thing as a truncating indexed store?
5306193323Sed  if (ST->isTruncatingStore() && ST->isUnindexed() &&
5307193323Sed      Value.getValueType().isInteger()) {
5308193323Sed    // See if we can simplify the input to this truncstore with knowledge that
5309193323Sed    // only the low bits are being used.  For example:
5310193323Sed    // "truncstore (or (shl x, 8), y), i8"  -> "truncstore y, i8"
5311193323Sed    SDValue Shorter =
5312193323Sed      GetDemandedBits(Value,
5313193323Sed                      APInt::getLowBitsSet(Value.getValueSizeInBits(),
5314193323Sed                                           ST->getMemoryVT().getSizeInBits()));
5315193323Sed    AddToWorkList(Value.getNode());
5316193323Sed    if (Shorter.getNode())
5317193323Sed      return DAG.getTruncStore(Chain, N->getDebugLoc(), Shorter,
5318193323Sed                               Ptr, ST->getSrcValue(),
5319193323Sed                               ST->getSrcValueOffset(), ST->getMemoryVT(),
5320193323Sed                               ST->isVolatile(), ST->getAlignment());
5321193323Sed
5322193323Sed    // Otherwise, see if we can simplify the operation with
5323193323Sed    // SimplifyDemandedBits, which only works if the value has a single use.
5324193323Sed    if (SimplifyDemandedBits(Value,
5325193323Sed                             APInt::getLowBitsSet(
5326200581Srdivacky                               Value.getValueType().getScalarType().getSizeInBits(),
5327193323Sed                               ST->getMemoryVT().getSizeInBits())))
5328193323Sed      return SDValue(N, 0);
5329193323Sed  }
5330193323Sed
5331193323Sed  // If this is a load followed by a store to the same location, then the store
5332193323Sed  // is dead/noop.
5333193323Sed  if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
5334193323Sed    if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
5335193323Sed        ST->isUnindexed() && !ST->isVolatile() &&
5336193323Sed        // There can't be any side effects between the load and store, such as
5337193323Sed        // a call or store.
5338193323Sed        Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
5339193323Sed      // The store is dead, remove it.
5340193323Sed      return Chain;
5341193323Sed    }
5342193323Sed  }
5343193323Sed
5344193323Sed  // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
5345193323Sed  // truncating store.  We can do this even if this is already a truncstore.
5346193323Sed  if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
5347193323Sed      && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
5348193323Sed      TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
5349193323Sed                            ST->getMemoryVT())) {
5350193323Sed    return DAG.getTruncStore(Chain, N->getDebugLoc(), Value.getOperand(0),
5351193323Sed                             Ptr, ST->getSrcValue(),
5352193323Sed                             ST->getSrcValueOffset(), ST->getMemoryVT(),
5353193323Sed                             ST->isVolatile(), ST->getAlignment());
5354193323Sed  }
5355193323Sed
5356193323Sed  return ReduceLoadOpStoreWidth(N);
5357193323Sed}
5358193323Sed
5359193323SedSDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
5360193323Sed  SDValue InVec = N->getOperand(0);
5361193323Sed  SDValue InVal = N->getOperand(1);
5362193323Sed  SDValue EltNo = N->getOperand(2);
5363193323Sed
5364193323Sed  // If the invec is a BUILD_VECTOR and if EltNo is a constant, build a new
5365193323Sed  // vector with the inserted element.
5366193323Sed  if (InVec.getOpcode() == ISD::BUILD_VECTOR && isa<ConstantSDNode>(EltNo)) {
5367193323Sed    unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
5368193323Sed    SmallVector<SDValue, 8> Ops(InVec.getNode()->op_begin(),
5369193323Sed                                InVec.getNode()->op_end());
5370193323Sed    if (Elt < Ops.size())
5371193323Sed      Ops[Elt] = InVal;
5372193323Sed    return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(),
5373193323Sed                       InVec.getValueType(), &Ops[0], Ops.size());
5374193323Sed  }
5375193323Sed  // If the invec is an UNDEF and if EltNo is a constant, create a new
5376193323Sed  // BUILD_VECTOR with undef elements and the inserted element.
5377193323Sed  if (!LegalOperations && InVec.getOpcode() == ISD::UNDEF &&
5378193323Sed      isa<ConstantSDNode>(EltNo)) {
5379198090Srdivacky    EVT VT = InVec.getValueType();
5380198090Srdivacky    EVT EltVT = VT.getVectorElementType();
5381193323Sed    unsigned NElts = VT.getVectorNumElements();
5382198090Srdivacky    SmallVector<SDValue, 8> Ops(NElts, DAG.getUNDEF(EltVT));
5383193323Sed
5384193323Sed    unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
5385193323Sed    if (Elt < Ops.size())
5386193323Sed      Ops[Elt] = InVal;
5387193323Sed    return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(),
5388193323Sed                       InVec.getValueType(), &Ops[0], Ops.size());
5389193323Sed  }
5390193323Sed  return SDValue();
5391193323Sed}
5392193323Sed
5393193323SedSDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
5394193323Sed  // (vextract (scalar_to_vector val, 0) -> val
5395193323Sed  SDValue InVec = N->getOperand(0);
5396193323Sed
5397193323Sed if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5398193323Sed   // If the operand is wider than the vector element type then it is implicitly
5399193323Sed   // truncated.  Make that explicit here.
5400198090Srdivacky   EVT EltVT = InVec.getValueType().getVectorElementType();
5401193323Sed   SDValue InOp = InVec.getOperand(0);
5402193323Sed   if (InOp.getValueType() != EltVT)
5403193323Sed     return DAG.getNode(ISD::TRUNCATE, InVec.getDebugLoc(), EltVT, InOp);
5404193323Sed   return InOp;
5405193323Sed }
5406193323Sed
5407193323Sed  // Perform only after legalization to ensure build_vector / vector_shuffle
5408193323Sed  // optimizations have already been done.
5409193323Sed  if (!LegalOperations) return SDValue();
5410193323Sed
5411193323Sed  // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
5412193323Sed  // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
5413193323Sed  // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
5414193323Sed  SDValue EltNo = N->getOperand(1);
5415193323Sed
5416193323Sed  if (isa<ConstantSDNode>(EltNo)) {
5417193323Sed    unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
5418193323Sed    bool NewLoad = false;
5419193323Sed    bool BCNumEltsChanged = false;
5420198090Srdivacky    EVT VT = InVec.getValueType();
5421198090Srdivacky    EVT ExtVT = VT.getVectorElementType();
5422198090Srdivacky    EVT LVT = ExtVT;
5423193323Sed
5424193323Sed    if (InVec.getOpcode() == ISD::BIT_CONVERT) {
5425198090Srdivacky      EVT BCVT = InVec.getOperand(0).getValueType();
5426198090Srdivacky      if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
5427193323Sed        return SDValue();
5428193323Sed      if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
5429193323Sed        BCNumEltsChanged = true;
5430193323Sed      InVec = InVec.getOperand(0);
5431198090Srdivacky      ExtVT = BCVT.getVectorElementType();
5432193323Sed      NewLoad = true;
5433193323Sed    }
5434193323Sed
5435193323Sed    LoadSDNode *LN0 = NULL;
5436193323Sed    const ShuffleVectorSDNode *SVN = NULL;
5437193323Sed    if (ISD::isNormalLoad(InVec.getNode())) {
5438193323Sed      LN0 = cast<LoadSDNode>(InVec);
5439193323Sed    } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
5440198090Srdivacky               InVec.getOperand(0).getValueType() == ExtVT &&
5441193323Sed               ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
5442193323Sed      LN0 = cast<LoadSDNode>(InVec.getOperand(0));
5443193323Sed    } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
5444193323Sed      // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
5445193323Sed      // =>
5446193323Sed      // (load $addr+1*size)
5447193323Sed
5448193323Sed      // If the bit convert changed the number of elements, it is unsafe
5449193323Sed      // to examine the mask.
5450193323Sed      if (BCNumEltsChanged)
5451193323Sed        return SDValue();
5452193323Sed
5453193323Sed      // Select the input vector, guarding against out of range extract vector.
5454193323Sed      unsigned NumElems = VT.getVectorNumElements();
5455193323Sed      int Idx = (Elt > NumElems) ? -1 : SVN->getMaskElt(Elt);
5456193323Sed      InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
5457193323Sed
5458193323Sed      if (InVec.getOpcode() == ISD::BIT_CONVERT)
5459193323Sed        InVec = InVec.getOperand(0);
5460193323Sed      if (ISD::isNormalLoad(InVec.getNode())) {
5461193323Sed        LN0 = cast<LoadSDNode>(InVec);
5462193323Sed        Elt = (Idx < (int)NumElems) ? Idx : Idx - NumElems;
5463193323Sed      }
5464193323Sed    }
5465193323Sed
5466193323Sed    if (!LN0 || !LN0->hasOneUse() || LN0->isVolatile())
5467193323Sed      return SDValue();
5468193323Sed
5469193323Sed    unsigned Align = LN0->getAlignment();
5470193323Sed    if (NewLoad) {
5471193323Sed      // Check the resultant load doesn't need a higher alignment than the
5472193323Sed      // original load.
5473193323Sed      unsigned NewAlign =
5474198090Srdivacky        TLI.getTargetData()->getABITypeAlignment(LVT.getTypeForEVT(*DAG.getContext()));
5475193323Sed
5476193323Sed      if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, LVT))
5477193323Sed        return SDValue();
5478193323Sed
5479193323Sed      Align = NewAlign;
5480193323Sed    }
5481193323Sed
5482193323Sed    SDValue NewPtr = LN0->getBasePtr();
5483193323Sed    if (Elt) {
5484193323Sed      unsigned PtrOff = LVT.getSizeInBits() * Elt / 8;
5485198090Srdivacky      EVT PtrType = NewPtr.getValueType();
5486193323Sed      if (TLI.isBigEndian())
5487193323Sed        PtrOff = VT.getSizeInBits() / 8 - PtrOff;
5488193323Sed      NewPtr = DAG.getNode(ISD::ADD, N->getDebugLoc(), PtrType, NewPtr,
5489193323Sed                           DAG.getConstant(PtrOff, PtrType));
5490193323Sed    }
5491193323Sed
5492193323Sed    return DAG.getLoad(LVT, N->getDebugLoc(), LN0->getChain(), NewPtr,
5493193323Sed                       LN0->getSrcValue(), LN0->getSrcValueOffset(),
5494193323Sed                       LN0->isVolatile(), Align);
5495193323Sed  }
5496193323Sed
5497193323Sed  return SDValue();
5498193323Sed}
5499193323Sed
5500193323SedSDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
5501193323Sed  unsigned NumInScalars = N->getNumOperands();
5502198090Srdivacky  EVT VT = N->getValueType(0);
5503193323Sed
5504193323Sed  // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
5505193323Sed  // operations.  If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
5506193323Sed  // at most two distinct vectors, turn this into a shuffle node.
5507193323Sed  SDValue VecIn1, VecIn2;
5508193323Sed  for (unsigned i = 0; i != NumInScalars; ++i) {
5509193323Sed    // Ignore undef inputs.
5510193323Sed    if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
5511193323Sed
5512193323Sed    // If this input is something other than a EXTRACT_VECTOR_ELT with a
5513193323Sed    // constant index, bail out.
5514193323Sed    if (N->getOperand(i).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5515193323Sed        !isa<ConstantSDNode>(N->getOperand(i).getOperand(1))) {
5516193323Sed      VecIn1 = VecIn2 = SDValue(0, 0);
5517193323Sed      break;
5518193323Sed    }
5519193323Sed
5520193323Sed    // If the input vector type disagrees with the result of the build_vector,
5521193323Sed    // we can't make a shuffle.
5522193323Sed    SDValue ExtractedFromVec = N->getOperand(i).getOperand(0);
5523193323Sed    if (ExtractedFromVec.getValueType() != VT) {
5524193323Sed      VecIn1 = VecIn2 = SDValue(0, 0);
5525193323Sed      break;
5526193323Sed    }
5527193323Sed
5528193323Sed    // Otherwise, remember this.  We allow up to two distinct input vectors.
5529193323Sed    if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
5530193323Sed      continue;
5531193323Sed
5532193323Sed    if (VecIn1.getNode() == 0) {
5533193323Sed      VecIn1 = ExtractedFromVec;
5534193323Sed    } else if (VecIn2.getNode() == 0) {
5535193323Sed      VecIn2 = ExtractedFromVec;
5536193323Sed    } else {
5537193323Sed      // Too many inputs.
5538193323Sed      VecIn1 = VecIn2 = SDValue(0, 0);
5539193323Sed      break;
5540193323Sed    }
5541193323Sed  }
5542193323Sed
5543193323Sed  // If everything is good, we can make a shuffle operation.
5544193323Sed  if (VecIn1.getNode()) {
5545193323Sed    SmallVector<int, 8> Mask;
5546193323Sed    for (unsigned i = 0; i != NumInScalars; ++i) {
5547193323Sed      if (N->getOperand(i).getOpcode() == ISD::UNDEF) {
5548193323Sed        Mask.push_back(-1);
5549193323Sed        continue;
5550193323Sed      }
5551193323Sed
5552193323Sed      // If extracting from the first vector, just use the index directly.
5553193323Sed      SDValue Extract = N->getOperand(i);
5554193323Sed      SDValue ExtVal = Extract.getOperand(1);
5555193323Sed      if (Extract.getOperand(0) == VecIn1) {
5556193323Sed        unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
5557193323Sed        if (ExtIndex > VT.getVectorNumElements())
5558193323Sed          return SDValue();
5559193323Sed
5560193323Sed        Mask.push_back(ExtIndex);
5561193323Sed        continue;
5562193323Sed      }
5563193323Sed
5564193323Sed      // Otherwise, use InIdx + VecSize
5565193323Sed      unsigned Idx = cast<ConstantSDNode>(ExtVal)->getZExtValue();
5566193323Sed      Mask.push_back(Idx+NumInScalars);
5567193323Sed    }
5568193323Sed
5569193323Sed    // Add count and size info.
5570193323Sed    if (!TLI.isTypeLegal(VT) && LegalTypes)
5571193323Sed      return SDValue();
5572193323Sed
5573193323Sed    // Return the new VECTOR_SHUFFLE node.
5574193323Sed    SDValue Ops[2];
5575193323Sed    Ops[0] = VecIn1;
5576193323Sed    Ops[1] = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5577193323Sed    return DAG.getVectorShuffle(VT, N->getDebugLoc(), Ops[0], Ops[1], &Mask[0]);
5578193323Sed  }
5579193323Sed
5580193323Sed  return SDValue();
5581193323Sed}
5582193323Sed
5583193323SedSDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
5584193323Sed  // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
5585193323Sed  // EXTRACT_SUBVECTOR operations.  If so, and if the EXTRACT_SUBVECTOR vector
5586193323Sed  // inputs come from at most two distinct vectors, turn this into a shuffle
5587193323Sed  // node.
5588193323Sed
5589193323Sed  // If we only have one input vector, we don't need to do any concatenation.
5590193323Sed  if (N->getNumOperands() == 1)
5591193323Sed    return N->getOperand(0);
5592193323Sed
5593193323Sed  return SDValue();
5594193323Sed}
5595193323Sed
5596193323SedSDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
5597193323Sed  return SDValue();
5598193323Sed
5599198090Srdivacky  EVT VT = N->getValueType(0);
5600193323Sed  unsigned NumElts = VT.getVectorNumElements();
5601193323Sed
5602193323Sed  SDValue N0 = N->getOperand(0);
5603193323Sed
5604193323Sed  assert(N0.getValueType().getVectorNumElements() == NumElts &&
5605193323Sed        "Vector shuffle must be normalized in DAG");
5606193323Sed
5607193323Sed  // FIXME: implement canonicalizations from DAG.getVectorShuffle()
5608193323Sed
5609193323Sed  // If it is a splat, check if the argument vector is a build_vector with
5610193323Sed  // all scalar elements the same.
5611193323Sed  if (cast<ShuffleVectorSDNode>(N)->isSplat()) {
5612193323Sed    SDNode *V = N0.getNode();
5613193323Sed
5614193323Sed
5615193323Sed    // If this is a bit convert that changes the element type of the vector but
5616193323Sed    // not the number of vector elements, look through it.  Be careful not to
5617193323Sed    // look though conversions that change things like v4f32 to v2f64.
5618193323Sed    if (V->getOpcode() == ISD::BIT_CONVERT) {
5619193323Sed      SDValue ConvInput = V->getOperand(0);
5620193323Sed      if (ConvInput.getValueType().isVector() &&
5621193323Sed          ConvInput.getValueType().getVectorNumElements() == NumElts)
5622193323Sed        V = ConvInput.getNode();
5623193323Sed    }
5624193323Sed
5625193323Sed    if (V->getOpcode() == ISD::BUILD_VECTOR) {
5626193323Sed      unsigned NumElems = V->getNumOperands();
5627193323Sed      unsigned BaseIdx = cast<ShuffleVectorSDNode>(N)->getSplatIndex();
5628193323Sed      if (NumElems > BaseIdx) {
5629193323Sed        SDValue Base;
5630193323Sed        bool AllSame = true;
5631193323Sed        for (unsigned i = 0; i != NumElems; ++i) {
5632193323Sed          if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
5633193323Sed            Base = V->getOperand(i);
5634193323Sed            break;
5635193323Sed          }
5636193323Sed        }
5637193323Sed        // Splat of <u, u, u, u>, return <u, u, u, u>
5638193323Sed        if (!Base.getNode())
5639193323Sed          return N0;
5640193323Sed        for (unsigned i = 0; i != NumElems; ++i) {
5641193323Sed          if (V->getOperand(i) != Base) {
5642193323Sed            AllSame = false;
5643193323Sed            break;
5644193323Sed          }
5645193323Sed        }
5646193323Sed        // Splat of <x, x, x, x>, return <x, x, x, x>
5647193323Sed        if (AllSame)
5648193323Sed          return N0;
5649193323Sed      }
5650193323Sed    }
5651193323Sed  }
5652193323Sed  return SDValue();
5653193323Sed}
5654193323Sed
5655193323Sed/// XformToShuffleWithZero - Returns a vector_shuffle if it able to transform
5656193323Sed/// an AND to a vector_shuffle with the destination vector and a zero vector.
5657193323Sed/// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
5658193323Sed///      vector_shuffle V, Zero, <0, 4, 2, 4>
5659193323SedSDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
5660198090Srdivacky  EVT VT = N->getValueType(0);
5661193323Sed  DebugLoc dl = N->getDebugLoc();
5662193323Sed  SDValue LHS = N->getOperand(0);
5663193323Sed  SDValue RHS = N->getOperand(1);
5664193323Sed  if (N->getOpcode() == ISD::AND) {
5665193323Sed    if (RHS.getOpcode() == ISD::BIT_CONVERT)
5666193323Sed      RHS = RHS.getOperand(0);
5667193323Sed    if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
5668193323Sed      SmallVector<int, 8> Indices;
5669193323Sed      unsigned NumElts = RHS.getNumOperands();
5670193323Sed      for (unsigned i = 0; i != NumElts; ++i) {
5671193323Sed        SDValue Elt = RHS.getOperand(i);
5672193323Sed        if (!isa<ConstantSDNode>(Elt))
5673193323Sed          return SDValue();
5674193323Sed        else if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
5675193323Sed          Indices.push_back(i);
5676193323Sed        else if (cast<ConstantSDNode>(Elt)->isNullValue())
5677193323Sed          Indices.push_back(NumElts);
5678193323Sed        else
5679193323Sed          return SDValue();
5680193323Sed      }
5681193323Sed
5682193323Sed      // Let's see if the target supports this vector_shuffle.
5683198090Srdivacky      EVT RVT = RHS.getValueType();
5684193323Sed      if (!TLI.isVectorClearMaskLegal(Indices, RVT))
5685193323Sed        return SDValue();
5686193323Sed
5687193323Sed      // Return the new VECTOR_SHUFFLE node.
5688198090Srdivacky      EVT EltVT = RVT.getVectorElementType();
5689193323Sed      SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
5690198090Srdivacky                                     DAG.getConstant(0, EltVT));
5691193323Sed      SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(),
5692193323Sed                                 RVT, &ZeroOps[0], ZeroOps.size());
5693193323Sed      LHS = DAG.getNode(ISD::BIT_CONVERT, dl, RVT, LHS);
5694193323Sed      SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
5695193323Sed      return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Shuf);
5696193323Sed    }
5697193323Sed  }
5698193323Sed
5699193323Sed  return SDValue();
5700193323Sed}
5701193323Sed
5702193323Sed/// SimplifyVBinOp - Visit a binary vector operation, like ADD.
5703193323SedSDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
5704193323Sed  // After legalize, the target may be depending on adds and other
5705193323Sed  // binary ops to provide legal ways to construct constants or other
5706193323Sed  // things. Simplifying them may result in a loss of legality.
5707193323Sed  if (LegalOperations) return SDValue();
5708193323Sed
5709198090Srdivacky  EVT VT = N->getValueType(0);
5710193323Sed  assert(VT.isVector() && "SimplifyVBinOp only works on vectors!");
5711193323Sed
5712198090Srdivacky  EVT EltType = VT.getVectorElementType();
5713193323Sed  SDValue LHS = N->getOperand(0);
5714193323Sed  SDValue RHS = N->getOperand(1);
5715193323Sed  SDValue Shuffle = XformToShuffleWithZero(N);
5716193323Sed  if (Shuffle.getNode()) return Shuffle;
5717193323Sed
5718193323Sed  // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
5719193323Sed  // this operation.
5720193323Sed  if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
5721193323Sed      RHS.getOpcode() == ISD::BUILD_VECTOR) {
5722193323Sed    SmallVector<SDValue, 8> Ops;
5723193323Sed    for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
5724193323Sed      SDValue LHSOp = LHS.getOperand(i);
5725193323Sed      SDValue RHSOp = RHS.getOperand(i);
5726193323Sed      // If these two elements can't be folded, bail out.
5727193323Sed      if ((LHSOp.getOpcode() != ISD::UNDEF &&
5728193323Sed           LHSOp.getOpcode() != ISD::Constant &&
5729193323Sed           LHSOp.getOpcode() != ISD::ConstantFP) ||
5730193323Sed          (RHSOp.getOpcode() != ISD::UNDEF &&
5731193323Sed           RHSOp.getOpcode() != ISD::Constant &&
5732193323Sed           RHSOp.getOpcode() != ISD::ConstantFP))
5733193323Sed        break;
5734193323Sed
5735193323Sed      // Can't fold divide by zero.
5736193323Sed      if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
5737193323Sed          N->getOpcode() == ISD::FDIV) {
5738193323Sed        if ((RHSOp.getOpcode() == ISD::Constant &&
5739193323Sed             cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
5740193323Sed            (RHSOp.getOpcode() == ISD::ConstantFP &&
5741193323Sed             cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
5742193323Sed          break;
5743193323Sed      }
5744193323Sed
5745193323Sed      Ops.push_back(DAG.getNode(N->getOpcode(), LHS.getDebugLoc(),
5746193323Sed                                EltType, LHSOp, RHSOp));
5747193323Sed      AddToWorkList(Ops.back().getNode());
5748193323Sed      assert((Ops.back().getOpcode() == ISD::UNDEF ||
5749193323Sed              Ops.back().getOpcode() == ISD::Constant ||
5750193323Sed              Ops.back().getOpcode() == ISD::ConstantFP) &&
5751193323Sed             "Scalar binop didn't fold!");
5752193323Sed    }
5753193323Sed
5754193323Sed    if (Ops.size() == LHS.getNumOperands()) {
5755198090Srdivacky      EVT VT = LHS.getValueType();
5756193323Sed      return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(), VT,
5757193323Sed                         &Ops[0], Ops.size());
5758193323Sed    }
5759193323Sed  }
5760193323Sed
5761193323Sed  return SDValue();
5762193323Sed}
5763193323Sed
5764193323SedSDValue DAGCombiner::SimplifySelect(DebugLoc DL, SDValue N0,
5765193323Sed                                    SDValue N1, SDValue N2){
5766193323Sed  assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
5767193323Sed
5768193323Sed  SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
5769193323Sed                                 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5770193323Sed
5771193323Sed  // If we got a simplified select_cc node back from SimplifySelectCC, then
5772193323Sed  // break it down into a new SETCC node, and a new SELECT node, and then return
5773193323Sed  // the SELECT node, since we were called with a SELECT node.
5774193323Sed  if (SCC.getNode()) {
5775193323Sed    // Check to see if we got a select_cc back (to turn into setcc/select).
5776193323Sed    // Otherwise, just return whatever node we got back, like fabs.
5777193323Sed    if (SCC.getOpcode() == ISD::SELECT_CC) {
5778193323Sed      SDValue SETCC = DAG.getNode(ISD::SETCC, N0.getDebugLoc(),
5779193323Sed                                  N0.getValueType(),
5780193323Sed                                  SCC.getOperand(0), SCC.getOperand(1),
5781193323Sed                                  SCC.getOperand(4));
5782193323Sed      AddToWorkList(SETCC.getNode());
5783193323Sed      return DAG.getNode(ISD::SELECT, SCC.getDebugLoc(), SCC.getValueType(),
5784193323Sed                         SCC.getOperand(2), SCC.getOperand(3), SETCC);
5785193323Sed    }
5786193323Sed
5787193323Sed    return SCC;
5788193323Sed  }
5789193323Sed  return SDValue();
5790193323Sed}
5791193323Sed
5792193323Sed/// SimplifySelectOps - Given a SELECT or a SELECT_CC node, where LHS and RHS
5793193323Sed/// are the two values being selected between, see if we can simplify the
5794193323Sed/// select.  Callers of this should assume that TheSelect is deleted if this
5795193323Sed/// returns true.  As such, they should return the appropriate thing (e.g. the
5796193323Sed/// node) back to the top-level of the DAG combiner loop to avoid it being
5797193323Sed/// looked at.
5798193323Sedbool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
5799193323Sed                                    SDValue RHS) {
5800193323Sed
5801193323Sed  // If this is a select from two identical things, try to pull the operation
5802193323Sed  // through the select.
5803193323Sed  if (LHS.getOpcode() == RHS.getOpcode() && LHS.hasOneUse() && RHS.hasOneUse()){
5804193323Sed    // If this is a load and the token chain is identical, replace the select
5805193323Sed    // of two loads with a load through a select of the address to load from.
5806193323Sed    // This triggers in things like "select bool X, 10.0, 123.0" after the FP
5807193323Sed    // constants have been dropped into the constant pool.
5808193323Sed    if (LHS.getOpcode() == ISD::LOAD &&
5809193323Sed        // Do not let this transformation reduce the number of volatile loads.
5810193323Sed        !cast<LoadSDNode>(LHS)->isVolatile() &&
5811193323Sed        !cast<LoadSDNode>(RHS)->isVolatile() &&
5812193323Sed        // Token chains must be identical.
5813193323Sed        LHS.getOperand(0) == RHS.getOperand(0)) {
5814193323Sed      LoadSDNode *LLD = cast<LoadSDNode>(LHS);
5815193323Sed      LoadSDNode *RLD = cast<LoadSDNode>(RHS);
5816193323Sed
5817193323Sed      // If this is an EXTLOAD, the VT's must match.
5818193323Sed      if (LLD->getMemoryVT() == RLD->getMemoryVT()) {
5819198892Srdivacky        // FIXME: this discards src value information.  This is
5820198892Srdivacky        // over-conservative. It would be beneficial to be able to remember
5821202375Srdivacky        // both potential memory locations.  Since we are discarding
5822202375Srdivacky        // src value info, don't do the transformation if the memory
5823202375Srdivacky        // locations are not in the default address space.
5824202375Srdivacky        unsigned LLDAddrSpace = 0, RLDAddrSpace = 0;
5825202375Srdivacky        if (const Value *LLDVal = LLD->getMemOperand()->getValue()) {
5826202375Srdivacky          if (const PointerType *PT = dyn_cast<PointerType>(LLDVal->getType()))
5827202375Srdivacky            LLDAddrSpace = PT->getAddressSpace();
5828202375Srdivacky        }
5829202375Srdivacky        if (const Value *RLDVal = RLD->getMemOperand()->getValue()) {
5830202375Srdivacky          if (const PointerType *PT = dyn_cast<PointerType>(RLDVal->getType()))
5831202375Srdivacky            RLDAddrSpace = PT->getAddressSpace();
5832202375Srdivacky        }
5833193323Sed        SDValue Addr;
5834202375Srdivacky        if (LLDAddrSpace == 0 && RLDAddrSpace == 0) {
5835202375Srdivacky          if (TheSelect->getOpcode() == ISD::SELECT) {
5836202375Srdivacky            // Check that the condition doesn't reach either load.  If so, folding
5837202375Srdivacky            // this will induce a cycle into the DAG.
5838202375Srdivacky            if ((!LLD->hasAnyUseOfValue(1) ||
5839202375Srdivacky                 !LLD->isPredecessorOf(TheSelect->getOperand(0).getNode())) &&
5840202375Srdivacky                (!RLD->hasAnyUseOfValue(1) ||
5841202375Srdivacky                 !RLD->isPredecessorOf(TheSelect->getOperand(0).getNode()))) {
5842202375Srdivacky              Addr = DAG.getNode(ISD::SELECT, TheSelect->getDebugLoc(),
5843202375Srdivacky                                 LLD->getBasePtr().getValueType(),
5844202375Srdivacky                                 TheSelect->getOperand(0), LLD->getBasePtr(),
5845202375Srdivacky                                 RLD->getBasePtr());
5846202375Srdivacky            }
5847202375Srdivacky          } else {
5848202375Srdivacky            // Check that the condition doesn't reach either load.  If so, folding
5849202375Srdivacky            // this will induce a cycle into the DAG.
5850202375Srdivacky            if ((!LLD->hasAnyUseOfValue(1) ||
5851202375Srdivacky                 (!LLD->isPredecessorOf(TheSelect->getOperand(0).getNode()) &&
5852202375Srdivacky                  !LLD->isPredecessorOf(TheSelect->getOperand(1).getNode()))) &&
5853202375Srdivacky                (!RLD->hasAnyUseOfValue(1) ||
5854202375Srdivacky                 (!RLD->isPredecessorOf(TheSelect->getOperand(0).getNode()) &&
5855202375Srdivacky                  !RLD->isPredecessorOf(TheSelect->getOperand(1).getNode())))) {
5856202375Srdivacky              Addr = DAG.getNode(ISD::SELECT_CC, TheSelect->getDebugLoc(),
5857202375Srdivacky                                 LLD->getBasePtr().getValueType(),
5858202375Srdivacky                                 TheSelect->getOperand(0),
5859202375Srdivacky                                 TheSelect->getOperand(1),
5860202375Srdivacky                                 LLD->getBasePtr(), RLD->getBasePtr(),
5861202375Srdivacky                                 TheSelect->getOperand(4));
5862202375Srdivacky            }
5863193323Sed          }
5864193323Sed        }
5865193323Sed
5866193323Sed        if (Addr.getNode()) {
5867193323Sed          SDValue Load;
5868193323Sed          if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
5869193323Sed            Load = DAG.getLoad(TheSelect->getValueType(0),
5870193323Sed                               TheSelect->getDebugLoc(),
5871193323Sed                               LLD->getChain(),
5872198892Srdivacky                               Addr, 0, 0,
5873193323Sed                               LLD->isVolatile(),
5874193323Sed                               LLD->getAlignment());
5875193323Sed          } else {
5876193323Sed            Load = DAG.getExtLoad(LLD->getExtensionType(),
5877193323Sed                                  TheSelect->getDebugLoc(),
5878193323Sed                                  TheSelect->getValueType(0),
5879198892Srdivacky                                  LLD->getChain(), Addr, 0, 0,
5880193323Sed                                  LLD->getMemoryVT(),
5881193323Sed                                  LLD->isVolatile(),
5882193323Sed                                  LLD->getAlignment());
5883193323Sed          }
5884193323Sed
5885193323Sed          // Users of the select now use the result of the load.
5886193323Sed          CombineTo(TheSelect, Load);
5887193323Sed
5888193323Sed          // Users of the old loads now use the new load's chain.  We know the
5889193323Sed          // old-load value is dead now.
5890193323Sed          CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
5891193323Sed          CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
5892193323Sed          return true;
5893193323Sed        }
5894193323Sed      }
5895193323Sed    }
5896193323Sed  }
5897193323Sed
5898193323Sed  return false;
5899193323Sed}
5900193323Sed
5901193323Sed/// SimplifySelectCC - Simplify an expression of the form (N0 cond N1) ? N2 : N3
5902193323Sed/// where 'cond' is the comparison specified by CC.
5903193323SedSDValue DAGCombiner::SimplifySelectCC(DebugLoc DL, SDValue N0, SDValue N1,
5904193323Sed                                      SDValue N2, SDValue N3,
5905193323Sed                                      ISD::CondCode CC, bool NotExtCompare) {
5906193323Sed  // (x ? y : y) -> y.
5907193323Sed  if (N2 == N3) return N2;
5908193323Sed
5909198090Srdivacky  EVT VT = N2.getValueType();
5910193323Sed  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
5911193323Sed  ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
5912193323Sed  ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
5913193323Sed
5914193323Sed  // Determine if the condition we're dealing with is constant
5915193323Sed  SDValue SCC = SimplifySetCC(TLI.getSetCCResultType(N0.getValueType()),
5916193323Sed                              N0, N1, CC, DL, false);
5917193323Sed  if (SCC.getNode()) AddToWorkList(SCC.getNode());
5918193323Sed  ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
5919193323Sed
5920193323Sed  // fold select_cc true, x, y -> x
5921193323Sed  if (SCCC && !SCCC->isNullValue())
5922193323Sed    return N2;
5923193323Sed  // fold select_cc false, x, y -> y
5924193323Sed  if (SCCC && SCCC->isNullValue())
5925193323Sed    return N3;
5926193323Sed
5927193323Sed  // Check to see if we can simplify the select into an fabs node
5928193323Sed  if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
5929193323Sed    // Allow either -0.0 or 0.0
5930193323Sed    if (CFP->getValueAPF().isZero()) {
5931193323Sed      // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
5932193323Sed      if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
5933193323Sed          N0 == N2 && N3.getOpcode() == ISD::FNEG &&
5934193323Sed          N2 == N3.getOperand(0))
5935193323Sed        return DAG.getNode(ISD::FABS, DL, VT, N0);
5936193323Sed
5937193323Sed      // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
5938193323Sed      if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
5939193323Sed          N0 == N3 && N2.getOpcode() == ISD::FNEG &&
5940193323Sed          N2.getOperand(0) == N3)
5941193323Sed        return DAG.getNode(ISD::FABS, DL, VT, N3);
5942193323Sed    }
5943193323Sed  }
5944193323Sed
5945193323Sed  // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
5946193323Sed  // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
5947193323Sed  // in it.  This is a win when the constant is not otherwise available because
5948193323Sed  // it replaces two constant pool loads with one.  We only do this if the FP
5949193323Sed  // type is known to be legal, because if it isn't, then we are before legalize
5950193323Sed  // types an we want the other legalization to happen first (e.g. to avoid
5951193323Sed  // messing with soft float) and if the ConstantFP is not legal, because if
5952193323Sed  // it is legal, we may not need to store the FP constant in a constant pool.
5953193323Sed  if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
5954193323Sed    if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
5955193323Sed      if (TLI.isTypeLegal(N2.getValueType()) &&
5956193323Sed          (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
5957193323Sed           TargetLowering::Legal) &&
5958193323Sed          // If both constants have multiple uses, then we won't need to do an
5959193323Sed          // extra load, they are likely around in registers for other users.
5960193323Sed          (TV->hasOneUse() || FV->hasOneUse())) {
5961193323Sed        Constant *Elts[] = {
5962193323Sed          const_cast<ConstantFP*>(FV->getConstantFPValue()),
5963193323Sed          const_cast<ConstantFP*>(TV->getConstantFPValue())
5964193323Sed        };
5965193323Sed        const Type *FPTy = Elts[0]->getType();
5966193323Sed        const TargetData &TD = *TLI.getTargetData();
5967193323Sed
5968193323Sed        // Create a ConstantArray of the two constants.
5969193323Sed        Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts, 2);
5970193323Sed        SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
5971193323Sed                                            TD.getPrefTypeAlignment(FPTy));
5972193323Sed        unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
5973193323Sed
5974193323Sed        // Get the offsets to the 0 and 1 element of the array so that we can
5975193323Sed        // select between them.
5976193323Sed        SDValue Zero = DAG.getIntPtrConstant(0);
5977193323Sed        unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
5978193323Sed        SDValue One = DAG.getIntPtrConstant(EltSize);
5979193323Sed
5980193323Sed        SDValue Cond = DAG.getSetCC(DL,
5981193323Sed                                    TLI.getSetCCResultType(N0.getValueType()),
5982193323Sed                                    N0, N1, CC);
5983193323Sed        SDValue CstOffset = DAG.getNode(ISD::SELECT, DL, Zero.getValueType(),
5984193323Sed                                        Cond, One, Zero);
5985193323Sed        CPIdx = DAG.getNode(ISD::ADD, DL, TLI.getPointerTy(), CPIdx,
5986193323Sed                            CstOffset);
5987193323Sed        return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
5988193323Sed                           PseudoSourceValue::getConstantPool(), 0, false,
5989193323Sed                           Alignment);
5990193323Sed
5991193323Sed      }
5992193323Sed    }
5993193323Sed
5994193323Sed  // Check to see if we can perform the "gzip trick", transforming
5995193323Sed  // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
5996193323Sed  if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
5997193323Sed      N0.getValueType().isInteger() &&
5998193323Sed      N2.getValueType().isInteger() &&
5999193323Sed      (N1C->isNullValue() ||                         // (a < 0) ? b : 0
6000193323Sed       (N1C->getAPIntValue() == 1 && N0 == N2))) {   // (a < 1) ? a : 0
6001198090Srdivacky    EVT XType = N0.getValueType();
6002198090Srdivacky    EVT AType = N2.getValueType();
6003193323Sed    if (XType.bitsGE(AType)) {
6004193323Sed      // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
6005193323Sed      // single-bit constant.
6006193323Sed      if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
6007193323Sed        unsigned ShCtV = N2C->getAPIntValue().logBase2();
6008193323Sed        ShCtV = XType.getSizeInBits()-ShCtV-1;
6009193323Sed        SDValue ShCt = DAG.getConstant(ShCtV, getShiftAmountTy());
6010193323Sed        SDValue Shift = DAG.getNode(ISD::SRL, N0.getDebugLoc(),
6011193323Sed                                    XType, N0, ShCt);
6012193323Sed        AddToWorkList(Shift.getNode());
6013193323Sed
6014193323Sed        if (XType.bitsGT(AType)) {
6015193323Sed          Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
6016193323Sed          AddToWorkList(Shift.getNode());
6017193323Sed        }
6018193323Sed
6019193323Sed        return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
6020193323Sed      }
6021193323Sed
6022193323Sed      SDValue Shift = DAG.getNode(ISD::SRA, N0.getDebugLoc(),
6023193323Sed                                  XType, N0,
6024193323Sed                                  DAG.getConstant(XType.getSizeInBits()-1,
6025193323Sed                                                  getShiftAmountTy()));
6026193323Sed      AddToWorkList(Shift.getNode());
6027193323Sed
6028193323Sed      if (XType.bitsGT(AType)) {
6029193323Sed        Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
6030193323Sed        AddToWorkList(Shift.getNode());
6031193323Sed      }
6032193323Sed
6033193323Sed      return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
6034193323Sed    }
6035193323Sed  }
6036193323Sed
6037193323Sed  // fold select C, 16, 0 -> shl C, 4
6038193323Sed  if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
6039193323Sed      TLI.getBooleanContents() == TargetLowering::ZeroOrOneBooleanContent) {
6040193323Sed
6041193323Sed    // If the caller doesn't want us to simplify this into a zext of a compare,
6042193323Sed    // don't do it.
6043193323Sed    if (NotExtCompare && N2C->getAPIntValue() == 1)
6044193323Sed      return SDValue();
6045193323Sed
6046193323Sed    // Get a SetCC of the condition
6047193323Sed    // FIXME: Should probably make sure that setcc is legal if we ever have a
6048193323Sed    // target where it isn't.
6049193323Sed    SDValue Temp, SCC;
6050193323Sed    // cast from setcc result type to select result type
6051193323Sed    if (LegalTypes) {
6052193323Sed      SCC  = DAG.getSetCC(DL, TLI.getSetCCResultType(N0.getValueType()),
6053193323Sed                          N0, N1, CC);
6054193323Sed      if (N2.getValueType().bitsLT(SCC.getValueType()))
6055193323Sed        Temp = DAG.getZeroExtendInReg(SCC, N2.getDebugLoc(), N2.getValueType());
6056193323Sed      else
6057193323Sed        Temp = DAG.getNode(ISD::ZERO_EXTEND, N2.getDebugLoc(),
6058193323Sed                           N2.getValueType(), SCC);
6059193323Sed    } else {
6060193323Sed      SCC  = DAG.getSetCC(N0.getDebugLoc(), MVT::i1, N0, N1, CC);
6061193323Sed      Temp = DAG.getNode(ISD::ZERO_EXTEND, N2.getDebugLoc(),
6062193323Sed                         N2.getValueType(), SCC);
6063193323Sed    }
6064193323Sed
6065193323Sed    AddToWorkList(SCC.getNode());
6066193323Sed    AddToWorkList(Temp.getNode());
6067193323Sed
6068193323Sed    if (N2C->getAPIntValue() == 1)
6069193323Sed      return Temp;
6070193323Sed
6071193323Sed    // shl setcc result by log2 n2c
6072193323Sed    return DAG.getNode(ISD::SHL, DL, N2.getValueType(), Temp,
6073193323Sed                       DAG.getConstant(N2C->getAPIntValue().logBase2(),
6074193323Sed                                       getShiftAmountTy()));
6075193323Sed  }
6076193323Sed
6077193323Sed  // Check to see if this is the equivalent of setcc
6078193323Sed  // FIXME: Turn all of these into setcc if setcc if setcc is legal
6079193323Sed  // otherwise, go ahead with the folds.
6080193323Sed  if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
6081198090Srdivacky    EVT XType = N0.getValueType();
6082193323Sed    if (!LegalOperations ||
6083193323Sed        TLI.isOperationLegal(ISD::SETCC, TLI.getSetCCResultType(XType))) {
6084193323Sed      SDValue Res = DAG.getSetCC(DL, TLI.getSetCCResultType(XType), N0, N1, CC);
6085193323Sed      if (Res.getValueType() != VT)
6086193323Sed        Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
6087193323Sed      return Res;
6088193323Sed    }
6089193323Sed
6090193323Sed    // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
6091193323Sed    if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
6092193323Sed        (!LegalOperations ||
6093193323Sed         TLI.isOperationLegal(ISD::CTLZ, XType))) {
6094193323Sed      SDValue Ctlz = DAG.getNode(ISD::CTLZ, N0.getDebugLoc(), XType, N0);
6095193323Sed      return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
6096193323Sed                         DAG.getConstant(Log2_32(XType.getSizeInBits()),
6097193323Sed                                         getShiftAmountTy()));
6098193323Sed    }
6099193323Sed    // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
6100193323Sed    if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
6101193323Sed      SDValue NegN0 = DAG.getNode(ISD::SUB, N0.getDebugLoc(),
6102193323Sed                                  XType, DAG.getConstant(0, XType), N0);
6103193323Sed      SDValue NotN0 = DAG.getNOT(N0.getDebugLoc(), N0, XType);
6104193323Sed      return DAG.getNode(ISD::SRL, DL, XType,
6105193323Sed                         DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
6106193323Sed                         DAG.getConstant(XType.getSizeInBits()-1,
6107193323Sed                                         getShiftAmountTy()));
6108193323Sed    }
6109193323Sed    // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
6110193323Sed    if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
6111193323Sed      SDValue Sign = DAG.getNode(ISD::SRL, N0.getDebugLoc(), XType, N0,
6112193323Sed                                 DAG.getConstant(XType.getSizeInBits()-1,
6113193323Sed                                                 getShiftAmountTy()));
6114193323Sed      return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType));
6115193323Sed    }
6116193323Sed  }
6117193323Sed
6118193323Sed  // Check to see if this is an integer abs. select_cc setl[te] X, 0, -X, X ->
6119193323Sed  // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
6120193323Sed  if (N1C && N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE) &&
6121193323Sed      N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1) &&
6122193323Sed      N2.getOperand(0) == N1 && N0.getValueType().isInteger()) {
6123198090Srdivacky    EVT XType = N0.getValueType();
6124193323Sed    SDValue Shift = DAG.getNode(ISD::SRA, N0.getDebugLoc(), XType, N0,
6125193323Sed                                DAG.getConstant(XType.getSizeInBits()-1,
6126193323Sed                                                getShiftAmountTy()));
6127193323Sed    SDValue Add = DAG.getNode(ISD::ADD, N0.getDebugLoc(), XType,
6128193323Sed                              N0, Shift);
6129193323Sed    AddToWorkList(Shift.getNode());
6130193323Sed    AddToWorkList(Add.getNode());
6131193323Sed    return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
6132193323Sed  }
6133193323Sed  // Check to see if this is an integer abs. select_cc setgt X, -1, X, -X ->
6134193323Sed  // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
6135193323Sed  if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT &&
6136193323Sed      N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1)) {
6137193323Sed    if (ConstantSDNode *SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0))) {
6138198090Srdivacky      EVT XType = N0.getValueType();
6139193323Sed      if (SubC->isNullValue() && XType.isInteger()) {
6140193323Sed        SDValue Shift = DAG.getNode(ISD::SRA, N0.getDebugLoc(), XType,
6141193323Sed                                    N0,
6142193323Sed                                    DAG.getConstant(XType.getSizeInBits()-1,
6143193323Sed                                                    getShiftAmountTy()));
6144193323Sed        SDValue Add = DAG.getNode(ISD::ADD, N0.getDebugLoc(),
6145193323Sed                                  XType, N0, Shift);
6146193323Sed        AddToWorkList(Shift.getNode());
6147193323Sed        AddToWorkList(Add.getNode());
6148193323Sed        return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
6149193323Sed      }
6150193323Sed    }
6151193323Sed  }
6152193323Sed
6153193323Sed  return SDValue();
6154193323Sed}
6155193323Sed
6156193323Sed/// SimplifySetCC - This is a stub for TargetLowering::SimplifySetCC.
6157198090SrdivackySDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
6158193323Sed                                   SDValue N1, ISD::CondCode Cond,
6159193323Sed                                   DebugLoc DL, bool foldBooleans) {
6160193323Sed  TargetLowering::DAGCombinerInfo
6161198090Srdivacky    DagCombineInfo(DAG, !LegalTypes, !LegalOperations, false, this);
6162193323Sed  return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
6163193323Sed}
6164193323Sed
6165193323Sed/// BuildSDIVSequence - Given an ISD::SDIV node expressing a divide by constant,
6166193323Sed/// return a DAG expression to select that will generate the same value by
6167193323Sed/// multiplying by a magic number.  See:
6168193323Sed/// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
6169193323SedSDValue DAGCombiner::BuildSDIV(SDNode *N) {
6170193323Sed  std::vector<SDNode*> Built;
6171193323Sed  SDValue S = TLI.BuildSDIV(N, DAG, &Built);
6172193323Sed
6173193323Sed  for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
6174193323Sed       ii != ee; ++ii)
6175193323Sed    AddToWorkList(*ii);
6176193323Sed  return S;
6177193323Sed}
6178193323Sed
6179193323Sed/// BuildUDIVSequence - Given an ISD::UDIV node expressing a divide by constant,
6180193323Sed/// return a DAG expression to select that will generate the same value by
6181193323Sed/// multiplying by a magic number.  See:
6182193323Sed/// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
6183193323SedSDValue DAGCombiner::BuildUDIV(SDNode *N) {
6184193323Sed  std::vector<SDNode*> Built;
6185193323Sed  SDValue S = TLI.BuildUDIV(N, DAG, &Built);
6186193323Sed
6187193323Sed  for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
6188193323Sed       ii != ee; ++ii)
6189193323Sed    AddToWorkList(*ii);
6190193323Sed  return S;
6191193323Sed}
6192193323Sed
6193198090Srdivacky/// FindBaseOffset - Return true if base is a frame index, which is known not
6194198090Srdivacky// to alias with anything but itself.  Provides base object and offset as results.
6195198090Srdivackystatic bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
6196198090Srdivacky                           GlobalValue *&GV, void *&CV) {
6197193323Sed  // Assume it is a primitive operation.
6198198090Srdivacky  Base = Ptr; Offset = 0; GV = 0; CV = 0;
6199193323Sed
6200193323Sed  // If it's an adding a simple constant then integrate the offset.
6201193323Sed  if (Base.getOpcode() == ISD::ADD) {
6202193323Sed    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
6203193323Sed      Base = Base.getOperand(0);
6204193323Sed      Offset += C->getZExtValue();
6205193323Sed    }
6206193323Sed  }
6207198090Srdivacky
6208198090Srdivacky  // Return the underlying GlobalValue, and update the Offset.  Return false
6209198090Srdivacky  // for GlobalAddressSDNode since the same GlobalAddress may be represented
6210198090Srdivacky  // by multiple nodes with different offsets.
6211198090Srdivacky  if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
6212198090Srdivacky    GV = G->getGlobal();
6213198090Srdivacky    Offset += G->getOffset();
6214198090Srdivacky    return false;
6215198090Srdivacky  }
6216193323Sed
6217198090Srdivacky  // Return the underlying Constant value, and update the Offset.  Return false
6218198090Srdivacky  // for ConstantSDNodes since the same constant pool entry may be represented
6219198090Srdivacky  // by multiple nodes with different offsets.
6220198090Srdivacky  if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
6221198090Srdivacky    CV = C->isMachineConstantPoolEntry() ? (void *)C->getMachineCPVal()
6222198090Srdivacky                                         : (void *)C->getConstVal();
6223198090Srdivacky    Offset += C->getOffset();
6224198090Srdivacky    return false;
6225198090Srdivacky  }
6226193323Sed  // If it's any of the following then it can't alias with anything but itself.
6227198090Srdivacky  return isa<FrameIndexSDNode>(Base);
6228193323Sed}
6229193323Sed
6230193323Sed/// isAlias - Return true if there is any possibility that the two addresses
6231193323Sed/// overlap.
6232193323Sedbool DAGCombiner::isAlias(SDValue Ptr1, int64_t Size1,
6233193323Sed                          const Value *SrcValue1, int SrcValueOffset1,
6234198090Srdivacky                          unsigned SrcValueAlign1,
6235193323Sed                          SDValue Ptr2, int64_t Size2,
6236198090Srdivacky                          const Value *SrcValue2, int SrcValueOffset2,
6237198090Srdivacky                          unsigned SrcValueAlign2) const {
6238193323Sed  // If they are the same then they must be aliases.
6239193323Sed  if (Ptr1 == Ptr2) return true;
6240193323Sed
6241193323Sed  // Gather base node and offset information.
6242193323Sed  SDValue Base1, Base2;
6243193323Sed  int64_t Offset1, Offset2;
6244198090Srdivacky  GlobalValue *GV1, *GV2;
6245198090Srdivacky  void *CV1, *CV2;
6246198090Srdivacky  bool isFrameIndex1 = FindBaseOffset(Ptr1, Base1, Offset1, GV1, CV1);
6247198090Srdivacky  bool isFrameIndex2 = FindBaseOffset(Ptr2, Base2, Offset2, GV2, CV2);
6248193323Sed
6249198090Srdivacky  // If they have a same base address then check to see if they overlap.
6250198090Srdivacky  if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
6251193323Sed    return !((Offset1 + Size1) <= Offset2 || (Offset2 + Size2) <= Offset1);
6252193323Sed
6253198090Srdivacky  // If we know what the bases are, and they aren't identical, then we know they
6254198090Srdivacky  // cannot alias.
6255198090Srdivacky  if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
6256198090Srdivacky    return false;
6257193323Sed
6258198090Srdivacky  // If we know required SrcValue1 and SrcValue2 have relatively large alignment
6259198090Srdivacky  // compared to the size and offset of the access, we may be able to prove they
6260198090Srdivacky  // do not alias.  This check is conservative for now to catch cases created by
6261198090Srdivacky  // splitting vector types.
6262198090Srdivacky  if ((SrcValueAlign1 == SrcValueAlign2) &&
6263198090Srdivacky      (SrcValueOffset1 != SrcValueOffset2) &&
6264198090Srdivacky      (Size1 == Size2) && (SrcValueAlign1 > Size1)) {
6265198090Srdivacky    int64_t OffAlign1 = SrcValueOffset1 % SrcValueAlign1;
6266198090Srdivacky    int64_t OffAlign2 = SrcValueOffset2 % SrcValueAlign1;
6267198090Srdivacky
6268198090Srdivacky    // There is no overlap between these relatively aligned accesses of similar
6269198090Srdivacky    // size, return no alias.
6270198090Srdivacky    if ((OffAlign1 + Size1) <= OffAlign2 || (OffAlign2 + Size2) <= OffAlign1)
6271198090Srdivacky      return false;
6272198090Srdivacky  }
6273198090Srdivacky
6274193323Sed  if (CombinerGlobalAA) {
6275193323Sed    // Use alias analysis information.
6276193323Sed    int64_t MinOffset = std::min(SrcValueOffset1, SrcValueOffset2);
6277193323Sed    int64_t Overlap1 = Size1 + SrcValueOffset1 - MinOffset;
6278193323Sed    int64_t Overlap2 = Size2 + SrcValueOffset2 - MinOffset;
6279193323Sed    AliasAnalysis::AliasResult AAResult =
6280193323Sed                             AA.alias(SrcValue1, Overlap1, SrcValue2, Overlap2);
6281193323Sed    if (AAResult == AliasAnalysis::NoAlias)
6282193323Sed      return false;
6283193323Sed  }
6284193323Sed
6285193323Sed  // Otherwise we have to assume they alias.
6286193323Sed  return true;
6287193323Sed}
6288193323Sed
6289193323Sed/// FindAliasInfo - Extracts the relevant alias information from the memory
6290193323Sed/// node.  Returns true if the operand was a load.
6291193323Sedbool DAGCombiner::FindAliasInfo(SDNode *N,
6292193323Sed                        SDValue &Ptr, int64_t &Size,
6293198090Srdivacky                        const Value *&SrcValue,
6294198090Srdivacky                        int &SrcValueOffset,
6295198090Srdivacky                        unsigned &SrcValueAlign) const {
6296193323Sed  if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
6297193323Sed    Ptr = LD->getBasePtr();
6298193323Sed    Size = LD->getMemoryVT().getSizeInBits() >> 3;
6299193323Sed    SrcValue = LD->getSrcValue();
6300193323Sed    SrcValueOffset = LD->getSrcValueOffset();
6301198090Srdivacky    SrcValueAlign = LD->getOriginalAlignment();
6302193323Sed    return true;
6303193323Sed  } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
6304193323Sed    Ptr = ST->getBasePtr();
6305193323Sed    Size = ST->getMemoryVT().getSizeInBits() >> 3;
6306193323Sed    SrcValue = ST->getSrcValue();
6307193323Sed    SrcValueOffset = ST->getSrcValueOffset();
6308198090Srdivacky    SrcValueAlign = ST->getOriginalAlignment();
6309193323Sed  } else {
6310198090Srdivacky    llvm_unreachable("FindAliasInfo expected a memory operand");
6311193323Sed  }
6312193323Sed
6313193323Sed  return false;
6314193323Sed}
6315193323Sed
6316193323Sed/// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
6317193323Sed/// looking for aliasing nodes and adding them to the Aliases vector.
6318193323Sedvoid DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
6319193323Sed                                   SmallVector<SDValue, 8> &Aliases) {
6320193323Sed  SmallVector<SDValue, 8> Chains;     // List of chains to visit.
6321198090Srdivacky  SmallPtrSet<SDNode *, 16> Visited;  // Visited node set.
6322193323Sed
6323193323Sed  // Get alias information for node.
6324193323Sed  SDValue Ptr;
6325198090Srdivacky  int64_t Size;
6326198090Srdivacky  const Value *SrcValue;
6327198090Srdivacky  int SrcValueOffset;
6328198090Srdivacky  unsigned SrcValueAlign;
6329198090Srdivacky  bool IsLoad = FindAliasInfo(N, Ptr, Size, SrcValue, SrcValueOffset,
6330198090Srdivacky                              SrcValueAlign);
6331193323Sed
6332193323Sed  // Starting off.
6333193323Sed  Chains.push_back(OriginalChain);
6334198090Srdivacky  unsigned Depth = 0;
6335198090Srdivacky
6336193323Sed  // Look at each chain and determine if it is an alias.  If so, add it to the
6337193323Sed  // aliases list.  If not, then continue up the chain looking for the next
6338193323Sed  // candidate.
6339193323Sed  while (!Chains.empty()) {
6340193323Sed    SDValue Chain = Chains.back();
6341193323Sed    Chains.pop_back();
6342198090Srdivacky
6343198090Srdivacky    // For TokenFactor nodes, look at each operand and only continue up the
6344198090Srdivacky    // chain until we find two aliases.  If we've seen two aliases, assume we'll
6345198090Srdivacky    // find more and revert to original chain since the xform is unlikely to be
6346198090Srdivacky    // profitable.
6347198090Srdivacky    //
6348198090Srdivacky    // FIXME: The depth check could be made to return the last non-aliasing
6349198090Srdivacky    // chain we found before we hit a tokenfactor rather than the original
6350198090Srdivacky    // chain.
6351198090Srdivacky    if (Depth > 6 || Aliases.size() == 2) {
6352198090Srdivacky      Aliases.clear();
6353198090Srdivacky      Aliases.push_back(OriginalChain);
6354198090Srdivacky      break;
6355198090Srdivacky    }
6356193323Sed
6357198090Srdivacky    // Don't bother if we've been before.
6358198090Srdivacky    if (!Visited.insert(Chain.getNode()))
6359198090Srdivacky      continue;
6360193323Sed
6361193323Sed    switch (Chain.getOpcode()) {
6362193323Sed    case ISD::EntryToken:
6363193323Sed      // Entry token is ideal chain operand, but handled in FindBetterChain.
6364193323Sed      break;
6365193323Sed
6366193323Sed    case ISD::LOAD:
6367193323Sed    case ISD::STORE: {
6368193323Sed      // Get alias information for Chain.
6369193323Sed      SDValue OpPtr;
6370198090Srdivacky      int64_t OpSize;
6371198090Srdivacky      const Value *OpSrcValue;
6372198090Srdivacky      int OpSrcValueOffset;
6373198090Srdivacky      unsigned OpSrcValueAlign;
6374193323Sed      bool IsOpLoad = FindAliasInfo(Chain.getNode(), OpPtr, OpSize,
6375198090Srdivacky                                    OpSrcValue, OpSrcValueOffset,
6376198090Srdivacky                                    OpSrcValueAlign);
6377193323Sed
6378193323Sed      // If chain is alias then stop here.
6379193323Sed      if (!(IsLoad && IsOpLoad) &&
6380198090Srdivacky          isAlias(Ptr, Size, SrcValue, SrcValueOffset, SrcValueAlign,
6381198090Srdivacky                  OpPtr, OpSize, OpSrcValue, OpSrcValueOffset,
6382198090Srdivacky                  OpSrcValueAlign)) {
6383193323Sed        Aliases.push_back(Chain);
6384193323Sed      } else {
6385193323Sed        // Look further up the chain.
6386193323Sed        Chains.push_back(Chain.getOperand(0));
6387198090Srdivacky        ++Depth;
6388193323Sed      }
6389193323Sed      break;
6390193323Sed    }
6391193323Sed
6392193323Sed    case ISD::TokenFactor:
6393198090Srdivacky      // We have to check each of the operands of the token factor for "small"
6394198090Srdivacky      // token factors, so we queue them up.  Adding the operands to the queue
6395198090Srdivacky      // (stack) in reverse order maintains the original order and increases the
6396198090Srdivacky      // likelihood that getNode will find a matching token factor (CSE.)
6397198090Srdivacky      if (Chain.getNumOperands() > 16) {
6398198090Srdivacky        Aliases.push_back(Chain);
6399198090Srdivacky        break;
6400198090Srdivacky      }
6401193323Sed      for (unsigned n = Chain.getNumOperands(); n;)
6402193323Sed        Chains.push_back(Chain.getOperand(--n));
6403198090Srdivacky      ++Depth;
6404193323Sed      break;
6405193323Sed
6406193323Sed    default:
6407193323Sed      // For all other instructions we will just have to take what we can get.
6408193323Sed      Aliases.push_back(Chain);
6409193323Sed      break;
6410193323Sed    }
6411193323Sed  }
6412193323Sed}
6413193323Sed
6414193323Sed/// FindBetterChain - Walk up chain skipping non-aliasing memory nodes, looking
6415193323Sed/// for a better chain (aliasing node.)
6416193323SedSDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
6417193323Sed  SmallVector<SDValue, 8> Aliases;  // Ops for replacing token factor.
6418193323Sed
6419193323Sed  // Accumulate all the aliases to this node.
6420193323Sed  GatherAllAliases(N, OldChain, Aliases);
6421193323Sed
6422193323Sed  if (Aliases.size() == 0) {
6423193323Sed    // If no operands then chain to entry token.
6424193323Sed    return DAG.getEntryNode();
6425193323Sed  } else if (Aliases.size() == 1) {
6426193323Sed    // If a single operand then chain to it.  We don't need to revisit it.
6427193323Sed    return Aliases[0];
6428193323Sed  }
6429198090Srdivacky
6430193323Sed  // Construct a custom tailored token factor.
6431198090Srdivacky  return DAG.getNode(ISD::TokenFactor, N->getDebugLoc(), MVT::Other,
6432198090Srdivacky                     &Aliases[0], Aliases.size());
6433193323Sed}
6434193323Sed
6435193323Sed// SelectionDAG::Combine - This is the entry point for the file.
6436193323Sed//
6437193323Sedvoid SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
6438193323Sed                           CodeGenOpt::Level OptLevel) {
6439193323Sed  /// run - This is the main entry point to this class.
6440193323Sed  ///
6441193323Sed  DAGCombiner(*this, AA, OptLevel).Run(Level);
6442193323Sed}
6443