DAGCombiner.cpp revision 5bce67a95feb136389ca630cc5dd6a81e97ff1eb
1//===-- DAGCombiner.cpp - Implement a DAG node combiner -------------------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This pass combines dag nodes to form fewer, simpler DAG nodes.  It can be run
11// both before and after the DAG is legalized.
12//
13// This pass is not a substitute for the LLVM IR instcombine pass. This pass is
14// primarily intended to handle simplification opportunities that are implicit
15// in the LLVM IR and exposed by the various codegen lowering phases.
16//
17//===----------------------------------------------------------------------===//
18
19#define DEBUG_TYPE "dagcombine"
20#include "llvm/CodeGen/SelectionDAG.h"
21#include "llvm/ADT/SmallPtrSet.h"
22#include "llvm/ADT/Statistic.h"
23#include "llvm/Analysis/AliasAnalysis.h"
24#include "llvm/CodeGen/MachineFrameInfo.h"
25#include "llvm/CodeGen/MachineFunction.h"
26#include "llvm/IR/DataLayout.h"
27#include "llvm/IR/DerivedTypes.h"
28#include "llvm/IR/Function.h"
29#include "llvm/IR/LLVMContext.h"
30#include "llvm/Support/CommandLine.h"
31#include "llvm/Support/Debug.h"
32#include "llvm/Support/ErrorHandling.h"
33#include "llvm/Support/MathExtras.h"
34#include "llvm/Support/raw_ostream.h"
35#include "llvm/Target/TargetLowering.h"
36#include "llvm/Target/TargetMachine.h"
37#include "llvm/Target/TargetOptions.h"
38#include <algorithm>
39using namespace llvm;
40
41STATISTIC(NodesCombined   , "Number of dag nodes combined");
42STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created");
43STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created");
44STATISTIC(OpsNarrowed     , "Number of load/op/store narrowed");
45STATISTIC(LdStFP2Int      , "Number of fp load/store pairs transformed to int");
46
47namespace {
48  static cl::opt<bool>
49    CombinerAA("combiner-alias-analysis", cl::Hidden,
50               cl::desc("Turn on alias analysis during testing"));
51
52  static cl::opt<bool>
53    CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden,
54               cl::desc("Include global information in alias analysis"));
55
56//------------------------------ DAGCombiner ---------------------------------//
57
58  class DAGCombiner {
59    SelectionDAG &DAG;
60    const TargetLowering &TLI;
61    CombineLevel Level;
62    CodeGenOpt::Level OptLevel;
63    bool LegalOperations;
64    bool LegalTypes;
65
66    // Worklist of all of the nodes that need to be simplified.
67    //
68    // This has the semantics that when adding to the worklist,
69    // the item added must be next to be processed. It should
70    // also only appear once. The naive approach to this takes
71    // linear time.
72    //
73    // To reduce the insert/remove time to logarithmic, we use
74    // a set and a vector to maintain our worklist.
75    //
76    // The set contains the items on the worklist, but does not
77    // maintain the order they should be visited.
78    //
79    // The vector maintains the order nodes should be visited, but may
80    // contain duplicate or removed nodes. When choosing a node to
81    // visit, we pop off the order stack until we find an item that is
82    // also in the contents set. All operations are O(log N).
83    SmallPtrSet<SDNode*, 64> WorkListContents;
84    SmallVector<SDNode*, 64> WorkListOrder;
85
86    // AA - Used for DAG load/store alias analysis.
87    AliasAnalysis &AA;
88
89    /// AddUsersToWorkList - When an instruction is simplified, add all users of
90    /// the instruction to the work lists because they might get more simplified
91    /// now.
92    ///
93    void AddUsersToWorkList(SDNode *N) {
94      for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
95           UI != UE; ++UI)
96        AddToWorkList(*UI);
97    }
98
99    /// visit - call the node-specific routine that knows how to fold each
100    /// particular type of node.
101    SDValue visit(SDNode *N);
102
103  public:
104    /// AddToWorkList - Add to the work list making sure its instance is at the
105    /// back (next to be processed.)
106    void AddToWorkList(SDNode *N) {
107      WorkListContents.insert(N);
108      WorkListOrder.push_back(N);
109    }
110
111    /// removeFromWorkList - remove all instances of N from the worklist.
112    ///
113    void removeFromWorkList(SDNode *N) {
114      WorkListContents.erase(N);
115    }
116
117    SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
118                      bool AddTo = true);
119
120    SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) {
121      return CombineTo(N, &Res, 1, AddTo);
122    }
123
124    SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1,
125                      bool AddTo = true) {
126      SDValue To[] = { Res0, Res1 };
127      return CombineTo(N, To, 2, AddTo);
128    }
129
130    void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO);
131
132  private:
133
134    /// SimplifyDemandedBits - Check the specified integer node value to see if
135    /// it can be simplified or if things it uses can be simplified by bit
136    /// propagation.  If so, return true.
137    bool SimplifyDemandedBits(SDValue Op) {
138      unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits();
139      APInt Demanded = APInt::getAllOnesValue(BitWidth);
140      return SimplifyDemandedBits(Op, Demanded);
141    }
142
143    bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded);
144
145    bool CombineToPreIndexedLoadStore(SDNode *N);
146    bool CombineToPostIndexedLoadStore(SDNode *N);
147
148    void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad);
149    SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace);
150    SDValue SExtPromoteOperand(SDValue Op, EVT PVT);
151    SDValue ZExtPromoteOperand(SDValue Op, EVT PVT);
152    SDValue PromoteIntBinOp(SDValue Op);
153    SDValue PromoteIntShiftOp(SDValue Op);
154    SDValue PromoteExtend(SDValue Op);
155    bool PromoteLoad(SDValue Op);
156
157    void ExtendSetCCUses(SmallVector<SDNode*, 4> SetCCs,
158                         SDValue Trunc, SDValue ExtLoad, SDLoc DL,
159                         ISD::NodeType ExtType);
160
161    /// combine - call the node-specific routine that knows how to fold each
162    /// particular type of node. If that doesn't do anything, try the
163    /// target-specific DAG combines.
164    SDValue combine(SDNode *N);
165
166    // Visitation implementation - Implement dag node combining for different
167    // node types.  The semantics are as follows:
168    // Return Value:
169    //   SDValue.getNode() == 0 - No change was made
170    //   SDValue.getNode() == N - N was replaced, is dead and has been handled.
171    //   otherwise              - N should be replaced by the returned Operand.
172    //
173    SDValue visitTokenFactor(SDNode *N);
174    SDValue visitMERGE_VALUES(SDNode *N);
175    SDValue visitADD(SDNode *N);
176    SDValue visitSUB(SDNode *N);
177    SDValue visitADDC(SDNode *N);
178    SDValue visitSUBC(SDNode *N);
179    SDValue visitADDE(SDNode *N);
180    SDValue visitSUBE(SDNode *N);
181    SDValue visitMUL(SDNode *N);
182    SDValue visitSDIV(SDNode *N);
183    SDValue visitUDIV(SDNode *N);
184    SDValue visitSREM(SDNode *N);
185    SDValue visitUREM(SDNode *N);
186    SDValue visitMULHU(SDNode *N);
187    SDValue visitMULHS(SDNode *N);
188    SDValue visitSMUL_LOHI(SDNode *N);
189    SDValue visitUMUL_LOHI(SDNode *N);
190    SDValue visitSMULO(SDNode *N);
191    SDValue visitUMULO(SDNode *N);
192    SDValue visitSDIVREM(SDNode *N);
193    SDValue visitUDIVREM(SDNode *N);
194    SDValue visitAND(SDNode *N);
195    SDValue visitOR(SDNode *N);
196    SDValue visitXOR(SDNode *N);
197    SDValue SimplifyVBinOp(SDNode *N);
198    SDValue SimplifyVUnaryOp(SDNode *N);
199    SDValue visitSHL(SDNode *N);
200    SDValue visitSRA(SDNode *N);
201    SDValue visitSRL(SDNode *N);
202    SDValue visitCTLZ(SDNode *N);
203    SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
204    SDValue visitCTTZ(SDNode *N);
205    SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
206    SDValue visitCTPOP(SDNode *N);
207    SDValue visitSELECT(SDNode *N);
208    SDValue visitVSELECT(SDNode *N);
209    SDValue visitSELECT_CC(SDNode *N);
210    SDValue visitSETCC(SDNode *N);
211    SDValue visitSIGN_EXTEND(SDNode *N);
212    SDValue visitZERO_EXTEND(SDNode *N);
213    SDValue visitANY_EXTEND(SDNode *N);
214    SDValue visitSIGN_EXTEND_INREG(SDNode *N);
215    SDValue visitTRUNCATE(SDNode *N);
216    SDValue visitBITCAST(SDNode *N);
217    SDValue visitBUILD_PAIR(SDNode *N);
218    SDValue visitFADD(SDNode *N);
219    SDValue visitFSUB(SDNode *N);
220    SDValue visitFMUL(SDNode *N);
221    SDValue visitFMA(SDNode *N);
222    SDValue visitFDIV(SDNode *N);
223    SDValue visitFREM(SDNode *N);
224    SDValue visitFCOPYSIGN(SDNode *N);
225    SDValue visitSINT_TO_FP(SDNode *N);
226    SDValue visitUINT_TO_FP(SDNode *N);
227    SDValue visitFP_TO_SINT(SDNode *N);
228    SDValue visitFP_TO_UINT(SDNode *N);
229    SDValue visitFP_ROUND(SDNode *N);
230    SDValue visitFP_ROUND_INREG(SDNode *N);
231    SDValue visitFP_EXTEND(SDNode *N);
232    SDValue visitFNEG(SDNode *N);
233    SDValue visitFABS(SDNode *N);
234    SDValue visitFCEIL(SDNode *N);
235    SDValue visitFTRUNC(SDNode *N);
236    SDValue visitFFLOOR(SDNode *N);
237    SDValue visitBRCOND(SDNode *N);
238    SDValue visitBR_CC(SDNode *N);
239    SDValue visitLOAD(SDNode *N);
240    SDValue visitSTORE(SDNode *N);
241    SDValue visitINSERT_VECTOR_ELT(SDNode *N);
242    SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
243    SDValue visitBUILD_VECTOR(SDNode *N);
244    SDValue visitCONCAT_VECTORS(SDNode *N);
245    SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
246    SDValue visitVECTOR_SHUFFLE(SDNode *N);
247
248    SDValue XformToShuffleWithZero(SDNode *N);
249    SDValue ReassociateOps(unsigned Opc, SDLoc DL, SDValue LHS, SDValue RHS);
250
251    SDValue visitShiftByConstant(SDNode *N, unsigned Amt);
252
253    bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
254    SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
255    SDValue SimplifySelect(SDLoc DL, SDValue N0, SDValue N1, SDValue N2);
256    SDValue SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, SDValue N2,
257                             SDValue N3, ISD::CondCode CC,
258                             bool NotExtCompare = false);
259    SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
260                          SDLoc DL, bool foldBooleans = true);
261    SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
262                                         unsigned HiOp);
263    SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
264    SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
265    SDValue BuildSDIV(SDNode *N);
266    SDValue BuildUDIV(SDNode *N);
267    SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
268                               bool DemandHighBits = true);
269    SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
270    SDNode *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL);
271    SDValue ReduceLoadWidth(SDNode *N);
272    SDValue ReduceLoadOpStoreWidth(SDNode *N);
273    SDValue TransformFPLoadStorePair(SDNode *N);
274    SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
275    SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
276
277    SDValue GetDemandedBits(SDValue V, const APInt &Mask);
278
279    /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
280    /// looking for aliasing nodes and adding them to the Aliases vector.
281    void GatherAllAliases(SDNode *N, SDValue OriginalChain,
282                          SmallVector<SDValue, 8> &Aliases);
283
284    /// isAlias - Return true if there is any possibility that the two addresses
285    /// overlap.
286    bool isAlias(SDValue Ptr1, int64_t Size1,
287                 const Value *SrcValue1, int SrcValueOffset1,
288                 unsigned SrcValueAlign1,
289                 const MDNode *TBAAInfo1,
290                 SDValue Ptr2, int64_t Size2,
291                 const Value *SrcValue2, int SrcValueOffset2,
292                 unsigned SrcValueAlign2,
293                 const MDNode *TBAAInfo2) const;
294
295    /// isAlias - Return true if there is any possibility that the two addresses
296    /// overlap.
297    bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1);
298
299    /// FindAliasInfo - Extracts the relevant alias information from the memory
300    /// node.  Returns true if the operand was a load.
301    bool FindAliasInfo(SDNode *N,
302                       SDValue &Ptr, int64_t &Size,
303                       const Value *&SrcValue, int &SrcValueOffset,
304                       unsigned &SrcValueAlignment,
305                       const MDNode *&TBAAInfo) const;
306
307    /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes,
308    /// looking for a better chain (aliasing node.)
309    SDValue FindBetterChain(SDNode *N, SDValue Chain);
310
311    /// Merge consecutive store operations into a wide store.
312    /// This optimization uses wide integers or vectors when possible.
313    /// \return True if some memory operations were changed.
314    bool MergeConsecutiveStores(StoreSDNode *N);
315
316  public:
317    DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
318      : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
319        OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {}
320
321    /// Run - runs the dag combiner on all nodes in the work list
322    void Run(CombineLevel AtLevel);
323
324    SelectionDAG &getDAG() const { return DAG; }
325
326    /// getShiftAmountTy - Returns a type large enough to hold any valid
327    /// shift amount - before type legalization these can be huge.
328    EVT getShiftAmountTy(EVT LHSTy) {
329      assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
330      if (LHSTy.isVector())
331        return LHSTy;
332      return LegalTypes ? TLI.getScalarShiftAmountTy(LHSTy) : TLI.getPointerTy();
333    }
334
335    /// isTypeLegal - This method returns true if we are running before type
336    /// legalization or if the specified VT is legal.
337    bool isTypeLegal(const EVT &VT) {
338      if (!LegalTypes) return true;
339      return TLI.isTypeLegal(VT);
340    }
341
342    /// getSetCCResultType - Convenience wrapper around
343    /// TargetLowering::getSetCCResultType
344    EVT getSetCCResultType(EVT VT) const {
345      return TLI.getSetCCResultType(*DAG.getContext(), VT);
346    }
347  };
348}
349
350
351namespace {
352/// WorkListRemover - This class is a DAGUpdateListener that removes any deleted
353/// nodes from the worklist.
354class WorkListRemover : public SelectionDAG::DAGUpdateListener {
355  DAGCombiner &DC;
356public:
357  explicit WorkListRemover(DAGCombiner &dc)
358    : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
359
360  virtual void NodeDeleted(SDNode *N, SDNode *E) {
361    DC.removeFromWorkList(N);
362  }
363};
364}
365
366//===----------------------------------------------------------------------===//
367//  TargetLowering::DAGCombinerInfo implementation
368//===----------------------------------------------------------------------===//
369
370void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
371  ((DAGCombiner*)DC)->AddToWorkList(N);
372}
373
374void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
375  ((DAGCombiner*)DC)->removeFromWorkList(N);
376}
377
378SDValue TargetLowering::DAGCombinerInfo::
379CombineTo(SDNode *N, const std::vector<SDValue> &To, bool AddTo) {
380  return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
381}
382
383SDValue TargetLowering::DAGCombinerInfo::
384CombineTo(SDNode *N, SDValue Res, bool AddTo) {
385  return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
386}
387
388
389SDValue TargetLowering::DAGCombinerInfo::
390CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
391  return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
392}
393
394void TargetLowering::DAGCombinerInfo::
395CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
396  return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
397}
398
399//===----------------------------------------------------------------------===//
400// Helper Functions
401//===----------------------------------------------------------------------===//
402
403/// isNegatibleForFree - Return 1 if we can compute the negated form of the
404/// specified expression for the same cost as the expression itself, or 2 if we
405/// can compute the negated form more cheaply than the expression itself.
406static char isNegatibleForFree(SDValue Op, bool LegalOperations,
407                               const TargetLowering &TLI,
408                               const TargetOptions *Options,
409                               unsigned Depth = 0) {
410  // fneg is removable even if it has multiple uses.
411  if (Op.getOpcode() == ISD::FNEG) return 2;
412
413  // Don't allow anything with multiple uses.
414  if (!Op.hasOneUse()) return 0;
415
416  // Don't recurse exponentially.
417  if (Depth > 6) return 0;
418
419  switch (Op.getOpcode()) {
420  default: return false;
421  case ISD::ConstantFP:
422    // Don't invert constant FP values after legalize.  The negated constant
423    // isn't necessarily legal.
424    return LegalOperations ? 0 : 1;
425  case ISD::FADD:
426    // FIXME: determine better conditions for this xform.
427    if (!Options->UnsafeFPMath) return 0;
428
429    // After operation legalization, it might not be legal to create new FSUBs.
430    if (LegalOperations &&
431        !TLI.isOperationLegalOrCustom(ISD::FSUB,  Op.getValueType()))
432      return 0;
433
434    // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
435    if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
436                                    Options, Depth + 1))
437      return V;
438    // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
439    return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
440                              Depth + 1);
441  case ISD::FSUB:
442    // We can't turn -(A-B) into B-A when we honor signed zeros.
443    if (!Options->UnsafeFPMath) return 0;
444
445    // fold (fneg (fsub A, B)) -> (fsub B, A)
446    return 1;
447
448  case ISD::FMUL:
449  case ISD::FDIV:
450    if (Options->HonorSignDependentRoundingFPMath()) return 0;
451
452    // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
453    if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
454                                    Options, Depth + 1))
455      return V;
456
457    return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
458                              Depth + 1);
459
460  case ISD::FP_EXTEND:
461  case ISD::FP_ROUND:
462  case ISD::FSIN:
463    return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
464                              Depth + 1);
465  }
466}
467
468/// GetNegatedExpression - If isNegatibleForFree returns true, this function
469/// returns the newly negated expression.
470static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
471                                    bool LegalOperations, unsigned Depth = 0) {
472  // fneg is removable even if it has multiple uses.
473  if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
474
475  // Don't allow anything with multiple uses.
476  assert(Op.hasOneUse() && "Unknown reuse!");
477
478  assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
479  switch (Op.getOpcode()) {
480  default: llvm_unreachable("Unknown code");
481  case ISD::ConstantFP: {
482    APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
483    V.changeSign();
484    return DAG.getConstantFP(V, Op.getValueType());
485  }
486  case ISD::FADD:
487    // FIXME: determine better conditions for this xform.
488    assert(DAG.getTarget().Options.UnsafeFPMath);
489
490    // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
491    if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
492                           DAG.getTargetLoweringInfo(),
493                           &DAG.getTarget().Options, Depth+1))
494      return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
495                         GetNegatedExpression(Op.getOperand(0), DAG,
496                                              LegalOperations, Depth+1),
497                         Op.getOperand(1));
498    // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
499    return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
500                       GetNegatedExpression(Op.getOperand(1), DAG,
501                                            LegalOperations, Depth+1),
502                       Op.getOperand(0));
503  case ISD::FSUB:
504    // We can't turn -(A-B) into B-A when we honor signed zeros.
505    assert(DAG.getTarget().Options.UnsafeFPMath);
506
507    // fold (fneg (fsub 0, B)) -> B
508    if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
509      if (N0CFP->getValueAPF().isZero())
510        return Op.getOperand(1);
511
512    // fold (fneg (fsub A, B)) -> (fsub B, A)
513    return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
514                       Op.getOperand(1), Op.getOperand(0));
515
516  case ISD::FMUL:
517  case ISD::FDIV:
518    assert(!DAG.getTarget().Options.HonorSignDependentRoundingFPMath());
519
520    // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
521    if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
522                           DAG.getTargetLoweringInfo(),
523                           &DAG.getTarget().Options, Depth+1))
524      return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
525                         GetNegatedExpression(Op.getOperand(0), DAG,
526                                              LegalOperations, Depth+1),
527                         Op.getOperand(1));
528
529    // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
530    return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
531                       Op.getOperand(0),
532                       GetNegatedExpression(Op.getOperand(1), DAG,
533                                            LegalOperations, Depth+1));
534
535  case ISD::FP_EXTEND:
536  case ISD::FSIN:
537    return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
538                       GetNegatedExpression(Op.getOperand(0), DAG,
539                                            LegalOperations, Depth+1));
540  case ISD::FP_ROUND:
541      return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
542                         GetNegatedExpression(Op.getOperand(0), DAG,
543                                              LegalOperations, Depth+1),
544                         Op.getOperand(1));
545  }
546}
547
548
549// isSetCCEquivalent - Return true if this node is a setcc, or is a select_cc
550// that selects between the values 1 and 0, making it equivalent to a setcc.
551// Also, set the incoming LHS, RHS, and CC references to the appropriate
552// nodes based on the type of node we are checking.  This simplifies life a
553// bit for the callers.
554static bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
555                              SDValue &CC) {
556  if (N.getOpcode() == ISD::SETCC) {
557    LHS = N.getOperand(0);
558    RHS = N.getOperand(1);
559    CC  = N.getOperand(2);
560    return true;
561  }
562  if (N.getOpcode() == ISD::SELECT_CC &&
563      N.getOperand(2).getOpcode() == ISD::Constant &&
564      N.getOperand(3).getOpcode() == ISD::Constant &&
565      cast<ConstantSDNode>(N.getOperand(2))->getAPIntValue() == 1 &&
566      cast<ConstantSDNode>(N.getOperand(3))->isNullValue()) {
567    LHS = N.getOperand(0);
568    RHS = N.getOperand(1);
569    CC  = N.getOperand(4);
570    return true;
571  }
572  return false;
573}
574
575// isOneUseSetCC - Return true if this is a SetCC-equivalent operation with only
576// one use.  If this is true, it allows the users to invert the operation for
577// free when it is profitable to do so.
578static bool isOneUseSetCC(SDValue N) {
579  SDValue N0, N1, N2;
580  if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
581    return true;
582  return false;
583}
584
585SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL,
586                                    SDValue N0, SDValue N1) {
587  EVT VT = N0.getValueType();
588  if (N0.getOpcode() == Opc && isa<ConstantSDNode>(N0.getOperand(1))) {
589    if (isa<ConstantSDNode>(N1)) {
590      // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
591      SDValue OpNode =
592        DAG.FoldConstantArithmetic(Opc, VT,
593                                   cast<ConstantSDNode>(N0.getOperand(1)),
594                                   cast<ConstantSDNode>(N1));
595      return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
596    }
597    if (N0.hasOneUse()) {
598      // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one use
599      SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT,
600                                   N0.getOperand(0), N1);
601      AddToWorkList(OpNode.getNode());
602      return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
603    }
604  }
605
606  if (N1.getOpcode() == Opc && isa<ConstantSDNode>(N1.getOperand(1))) {
607    if (isa<ConstantSDNode>(N0)) {
608      // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
609      SDValue OpNode =
610        DAG.FoldConstantArithmetic(Opc, VT,
611                                   cast<ConstantSDNode>(N1.getOperand(1)),
612                                   cast<ConstantSDNode>(N0));
613      return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
614    }
615    if (N1.hasOneUse()) {
616      // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one use
617      SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT,
618                                   N1.getOperand(0), N0);
619      AddToWorkList(OpNode.getNode());
620      return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
621    }
622  }
623
624  return SDValue();
625}
626
627SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
628                               bool AddTo) {
629  assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
630  ++NodesCombined;
631  DEBUG(dbgs() << "\nReplacing.1 ";
632        N->dump(&DAG);
633        dbgs() << "\nWith: ";
634        To[0].getNode()->dump(&DAG);
635        dbgs() << " and " << NumTo-1 << " other values\n";
636        for (unsigned i = 0, e = NumTo; i != e; ++i)
637          assert((!To[i].getNode() ||
638                  N->getValueType(i) == To[i].getValueType()) &&
639                 "Cannot combine value to value of different type!"));
640  WorkListRemover DeadNodes(*this);
641  DAG.ReplaceAllUsesWith(N, To);
642  if (AddTo) {
643    // Push the new nodes and any users onto the worklist
644    for (unsigned i = 0, e = NumTo; i != e; ++i) {
645      if (To[i].getNode()) {
646        AddToWorkList(To[i].getNode());
647        AddUsersToWorkList(To[i].getNode());
648      }
649    }
650  }
651
652  // Finally, if the node is now dead, remove it from the graph.  The node
653  // may not be dead if the replacement process recursively simplified to
654  // something else needing this node.
655  if (N->use_empty()) {
656    // Nodes can be reintroduced into the worklist.  Make sure we do not
657    // process a node that has been replaced.
658    removeFromWorkList(N);
659
660    // Finally, since the node is now dead, remove it from the graph.
661    DAG.DeleteNode(N);
662  }
663  return SDValue(N, 0);
664}
665
666void DAGCombiner::
667CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
668  // Replace all uses.  If any nodes become isomorphic to other nodes and
669  // are deleted, make sure to remove them from our worklist.
670  WorkListRemover DeadNodes(*this);
671  DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
672
673  // Push the new node and any (possibly new) users onto the worklist.
674  AddToWorkList(TLO.New.getNode());
675  AddUsersToWorkList(TLO.New.getNode());
676
677  // Finally, if the node is now dead, remove it from the graph.  The node
678  // may not be dead if the replacement process recursively simplified to
679  // something else needing this node.
680  if (TLO.Old.getNode()->use_empty()) {
681    removeFromWorkList(TLO.Old.getNode());
682
683    // If the operands of this node are only used by the node, they will now
684    // be dead.  Make sure to visit them first to delete dead nodes early.
685    for (unsigned i = 0, e = TLO.Old.getNode()->getNumOperands(); i != e; ++i)
686      if (TLO.Old.getNode()->getOperand(i).getNode()->hasOneUse())
687        AddToWorkList(TLO.Old.getNode()->getOperand(i).getNode());
688
689    DAG.DeleteNode(TLO.Old.getNode());
690  }
691}
692
693/// SimplifyDemandedBits - Check the specified integer node value to see if
694/// it can be simplified or if things it uses can be simplified by bit
695/// propagation.  If so, return true.
696bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
697  TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
698  APInt KnownZero, KnownOne;
699  if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
700    return false;
701
702  // Revisit the node.
703  AddToWorkList(Op.getNode());
704
705  // Replace the old value with the new one.
706  ++NodesCombined;
707  DEBUG(dbgs() << "\nReplacing.2 ";
708        TLO.Old.getNode()->dump(&DAG);
709        dbgs() << "\nWith: ";
710        TLO.New.getNode()->dump(&DAG);
711        dbgs() << '\n');
712
713  CommitTargetLoweringOpt(TLO);
714  return true;
715}
716
717void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
718  SDLoc dl(Load);
719  EVT VT = Load->getValueType(0);
720  SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
721
722  DEBUG(dbgs() << "\nReplacing.9 ";
723        Load->dump(&DAG);
724        dbgs() << "\nWith: ";
725        Trunc.getNode()->dump(&DAG);
726        dbgs() << '\n');
727  WorkListRemover DeadNodes(*this);
728  DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
729  DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
730  removeFromWorkList(Load);
731  DAG.DeleteNode(Load);
732  AddToWorkList(Trunc.getNode());
733}
734
735SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
736  Replace = false;
737  SDLoc dl(Op);
738  if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
739    EVT MemVT = LD->getMemoryVT();
740    ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
741      ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
742                                                  : ISD::EXTLOAD)
743      : LD->getExtensionType();
744    Replace = true;
745    return DAG.getExtLoad(ExtType, dl, PVT,
746                          LD->getChain(), LD->getBasePtr(),
747                          LD->getPointerInfo(),
748                          MemVT, LD->isVolatile(),
749                          LD->isNonTemporal(), LD->getAlignment());
750  }
751
752  unsigned Opc = Op.getOpcode();
753  switch (Opc) {
754  default: break;
755  case ISD::AssertSext:
756    return DAG.getNode(ISD::AssertSext, dl, PVT,
757                       SExtPromoteOperand(Op.getOperand(0), PVT),
758                       Op.getOperand(1));
759  case ISD::AssertZext:
760    return DAG.getNode(ISD::AssertZext, dl, PVT,
761                       ZExtPromoteOperand(Op.getOperand(0), PVT),
762                       Op.getOperand(1));
763  case ISD::Constant: {
764    unsigned ExtOpc =
765      Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
766    return DAG.getNode(ExtOpc, dl, PVT, Op);
767  }
768  }
769
770  if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
771    return SDValue();
772  return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
773}
774
775SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
776  if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
777    return SDValue();
778  EVT OldVT = Op.getValueType();
779  SDLoc dl(Op);
780  bool Replace = false;
781  SDValue NewOp = PromoteOperand(Op, PVT, Replace);
782  if (NewOp.getNode() == 0)
783    return SDValue();
784  AddToWorkList(NewOp.getNode());
785
786  if (Replace)
787    ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
788  return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
789                     DAG.getValueType(OldVT));
790}
791
792SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
793  EVT OldVT = Op.getValueType();
794  SDLoc dl(Op);
795  bool Replace = false;
796  SDValue NewOp = PromoteOperand(Op, PVT, Replace);
797  if (NewOp.getNode() == 0)
798    return SDValue();
799  AddToWorkList(NewOp.getNode());
800
801  if (Replace)
802    ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
803  return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
804}
805
806/// PromoteIntBinOp - Promote the specified integer binary operation if the
807/// target indicates it is beneficial. e.g. On x86, it's usually better to
808/// promote i16 operations to i32 since i16 instructions are longer.
809SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
810  if (!LegalOperations)
811    return SDValue();
812
813  EVT VT = Op.getValueType();
814  if (VT.isVector() || !VT.isInteger())
815    return SDValue();
816
817  // If operation type is 'undesirable', e.g. i16 on x86, consider
818  // promoting it.
819  unsigned Opc = Op.getOpcode();
820  if (TLI.isTypeDesirableForOp(Opc, VT))
821    return SDValue();
822
823  EVT PVT = VT;
824  // Consult target whether it is a good idea to promote this operation and
825  // what's the right type to promote it to.
826  if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
827    assert(PVT != VT && "Don't know what type to promote to!");
828
829    bool Replace0 = false;
830    SDValue N0 = Op.getOperand(0);
831    SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
832    if (NN0.getNode() == 0)
833      return SDValue();
834
835    bool Replace1 = false;
836    SDValue N1 = Op.getOperand(1);
837    SDValue NN1;
838    if (N0 == N1)
839      NN1 = NN0;
840    else {
841      NN1 = PromoteOperand(N1, PVT, Replace1);
842      if (NN1.getNode() == 0)
843        return SDValue();
844    }
845
846    AddToWorkList(NN0.getNode());
847    if (NN1.getNode())
848      AddToWorkList(NN1.getNode());
849
850    if (Replace0)
851      ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
852    if (Replace1)
853      ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
854
855    DEBUG(dbgs() << "\nPromoting ";
856          Op.getNode()->dump(&DAG));
857    SDLoc dl(Op);
858    return DAG.getNode(ISD::TRUNCATE, dl, VT,
859                       DAG.getNode(Opc, dl, PVT, NN0, NN1));
860  }
861  return SDValue();
862}
863
864/// PromoteIntShiftOp - Promote the specified integer shift operation if the
865/// target indicates it is beneficial. e.g. On x86, it's usually better to
866/// promote i16 operations to i32 since i16 instructions are longer.
867SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
868  if (!LegalOperations)
869    return SDValue();
870
871  EVT VT = Op.getValueType();
872  if (VT.isVector() || !VT.isInteger())
873    return SDValue();
874
875  // If operation type is 'undesirable', e.g. i16 on x86, consider
876  // promoting it.
877  unsigned Opc = Op.getOpcode();
878  if (TLI.isTypeDesirableForOp(Opc, VT))
879    return SDValue();
880
881  EVT PVT = VT;
882  // Consult target whether it is a good idea to promote this operation and
883  // what's the right type to promote it to.
884  if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
885    assert(PVT != VT && "Don't know what type to promote to!");
886
887    bool Replace = false;
888    SDValue N0 = Op.getOperand(0);
889    if (Opc == ISD::SRA)
890      N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
891    else if (Opc == ISD::SRL)
892      N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
893    else
894      N0 = PromoteOperand(N0, PVT, Replace);
895    if (N0.getNode() == 0)
896      return SDValue();
897
898    AddToWorkList(N0.getNode());
899    if (Replace)
900      ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
901
902    DEBUG(dbgs() << "\nPromoting ";
903          Op.getNode()->dump(&DAG));
904    SDLoc dl(Op);
905    return DAG.getNode(ISD::TRUNCATE, dl, VT,
906                       DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
907  }
908  return SDValue();
909}
910
911SDValue DAGCombiner::PromoteExtend(SDValue Op) {
912  if (!LegalOperations)
913    return SDValue();
914
915  EVT VT = Op.getValueType();
916  if (VT.isVector() || !VT.isInteger())
917    return SDValue();
918
919  // If operation type is 'undesirable', e.g. i16 on x86, consider
920  // promoting it.
921  unsigned Opc = Op.getOpcode();
922  if (TLI.isTypeDesirableForOp(Opc, VT))
923    return SDValue();
924
925  EVT PVT = VT;
926  // Consult target whether it is a good idea to promote this operation and
927  // what's the right type to promote it to.
928  if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
929    assert(PVT != VT && "Don't know what type to promote to!");
930    // fold (aext (aext x)) -> (aext x)
931    // fold (aext (zext x)) -> (zext x)
932    // fold (aext (sext x)) -> (sext x)
933    DEBUG(dbgs() << "\nPromoting ";
934          Op.getNode()->dump(&DAG));
935    return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
936  }
937  return SDValue();
938}
939
940bool DAGCombiner::PromoteLoad(SDValue Op) {
941  if (!LegalOperations)
942    return false;
943
944  EVT VT = Op.getValueType();
945  if (VT.isVector() || !VT.isInteger())
946    return false;
947
948  // If operation type is 'undesirable', e.g. i16 on x86, consider
949  // promoting it.
950  unsigned Opc = Op.getOpcode();
951  if (TLI.isTypeDesirableForOp(Opc, VT))
952    return false;
953
954  EVT PVT = VT;
955  // Consult target whether it is a good idea to promote this operation and
956  // what's the right type to promote it to.
957  if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
958    assert(PVT != VT && "Don't know what type to promote to!");
959
960    SDLoc dl(Op);
961    SDNode *N = Op.getNode();
962    LoadSDNode *LD = cast<LoadSDNode>(N);
963    EVT MemVT = LD->getMemoryVT();
964    ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
965      ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
966                                                  : ISD::EXTLOAD)
967      : LD->getExtensionType();
968    SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
969                                   LD->getChain(), LD->getBasePtr(),
970                                   LD->getPointerInfo(),
971                                   MemVT, LD->isVolatile(),
972                                   LD->isNonTemporal(), LD->getAlignment());
973    SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
974
975    DEBUG(dbgs() << "\nPromoting ";
976          N->dump(&DAG);
977          dbgs() << "\nTo: ";
978          Result.getNode()->dump(&DAG);
979          dbgs() << '\n');
980    WorkListRemover DeadNodes(*this);
981    DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
982    DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
983    removeFromWorkList(N);
984    DAG.DeleteNode(N);
985    AddToWorkList(Result.getNode());
986    return true;
987  }
988  return false;
989}
990
991
992//===----------------------------------------------------------------------===//
993//  Main DAG Combiner implementation
994//===----------------------------------------------------------------------===//
995
996void DAGCombiner::Run(CombineLevel AtLevel) {
997  // set the instance variables, so that the various visit routines may use it.
998  Level = AtLevel;
999  LegalOperations = Level >= AfterLegalizeVectorOps;
1000  LegalTypes = Level >= AfterLegalizeTypes;
1001
1002  // Add all the dag nodes to the worklist.
1003  for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
1004       E = DAG.allnodes_end(); I != E; ++I)
1005    AddToWorkList(I);
1006
1007  // Create a dummy node (which is not added to allnodes), that adds a reference
1008  // to the root node, preventing it from being deleted, and tracking any
1009  // changes of the root.
1010  HandleSDNode Dummy(DAG.getRoot());
1011
1012  // The root of the dag may dangle to deleted nodes until the dag combiner is
1013  // done.  Set it to null to avoid confusion.
1014  DAG.setRoot(SDValue());
1015
1016  // while the worklist isn't empty, find a node and
1017  // try and combine it.
1018  while (!WorkListContents.empty()) {
1019    SDNode *N;
1020    // The WorkListOrder holds the SDNodes in order, but it may contain duplicates.
1021    // In order to avoid a linear scan, we use a set (O(log N)) to hold what the
1022    // worklist *should* contain, and check the node we want to visit is should
1023    // actually be visited.
1024    do {
1025      N = WorkListOrder.pop_back_val();
1026    } while (!WorkListContents.erase(N));
1027
1028    // If N has no uses, it is dead.  Make sure to revisit all N's operands once
1029    // N is deleted from the DAG, since they too may now be dead or may have a
1030    // reduced number of uses, allowing other xforms.
1031    if (N->use_empty() && N != &Dummy) {
1032      for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1033        AddToWorkList(N->getOperand(i).getNode());
1034
1035      DAG.DeleteNode(N);
1036      continue;
1037    }
1038
1039    SDValue RV = combine(N);
1040
1041    if (RV.getNode() == 0)
1042      continue;
1043
1044    ++NodesCombined;
1045
1046    // If we get back the same node we passed in, rather than a new node or
1047    // zero, we know that the node must have defined multiple values and
1048    // CombineTo was used.  Since CombineTo takes care of the worklist
1049    // mechanics for us, we have no work to do in this case.
1050    if (RV.getNode() == N)
1051      continue;
1052
1053    assert(N->getOpcode() != ISD::DELETED_NODE &&
1054           RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1055           "Node was deleted but visit returned new node!");
1056
1057    DEBUG(dbgs() << "\nReplacing.3 ";
1058          N->dump(&DAG);
1059          dbgs() << "\nWith: ";
1060          RV.getNode()->dump(&DAG);
1061          dbgs() << '\n');
1062
1063    // Transfer debug value.
1064    DAG.TransferDbgValues(SDValue(N, 0), RV);
1065    WorkListRemover DeadNodes(*this);
1066    if (N->getNumValues() == RV.getNode()->getNumValues())
1067      DAG.ReplaceAllUsesWith(N, RV.getNode());
1068    else {
1069      assert(N->getValueType(0) == RV.getValueType() &&
1070             N->getNumValues() == 1 && "Type mismatch");
1071      SDValue OpV = RV;
1072      DAG.ReplaceAllUsesWith(N, &OpV);
1073    }
1074
1075    // Push the new node and any users onto the worklist
1076    AddToWorkList(RV.getNode());
1077    AddUsersToWorkList(RV.getNode());
1078
1079    // Add any uses of the old node to the worklist in case this node is the
1080    // last one that uses them.  They may become dead after this node is
1081    // deleted.
1082    for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1083      AddToWorkList(N->getOperand(i).getNode());
1084
1085    // Finally, if the node is now dead, remove it from the graph.  The node
1086    // may not be dead if the replacement process recursively simplified to
1087    // something else needing this node.
1088    if (N->use_empty()) {
1089      // Nodes can be reintroduced into the worklist.  Make sure we do not
1090      // process a node that has been replaced.
1091      removeFromWorkList(N);
1092
1093      // Finally, since the node is now dead, remove it from the graph.
1094      DAG.DeleteNode(N);
1095    }
1096  }
1097
1098  // If the root changed (e.g. it was a dead load, update the root).
1099  DAG.setRoot(Dummy.getValue());
1100  DAG.RemoveDeadNodes();
1101}
1102
1103SDValue DAGCombiner::visit(SDNode *N) {
1104  switch (N->getOpcode()) {
1105  default: break;
1106  case ISD::TokenFactor:        return visitTokenFactor(N);
1107  case ISD::MERGE_VALUES:       return visitMERGE_VALUES(N);
1108  case ISD::ADD:                return visitADD(N);
1109  case ISD::SUB:                return visitSUB(N);
1110  case ISD::ADDC:               return visitADDC(N);
1111  case ISD::SUBC:               return visitSUBC(N);
1112  case ISD::ADDE:               return visitADDE(N);
1113  case ISD::SUBE:               return visitSUBE(N);
1114  case ISD::MUL:                return visitMUL(N);
1115  case ISD::SDIV:               return visitSDIV(N);
1116  case ISD::UDIV:               return visitUDIV(N);
1117  case ISD::SREM:               return visitSREM(N);
1118  case ISD::UREM:               return visitUREM(N);
1119  case ISD::MULHU:              return visitMULHU(N);
1120  case ISD::MULHS:              return visitMULHS(N);
1121  case ISD::SMUL_LOHI:          return visitSMUL_LOHI(N);
1122  case ISD::UMUL_LOHI:          return visitUMUL_LOHI(N);
1123  case ISD::SMULO:              return visitSMULO(N);
1124  case ISD::UMULO:              return visitUMULO(N);
1125  case ISD::SDIVREM:            return visitSDIVREM(N);
1126  case ISD::UDIVREM:            return visitUDIVREM(N);
1127  case ISD::AND:                return visitAND(N);
1128  case ISD::OR:                 return visitOR(N);
1129  case ISD::XOR:                return visitXOR(N);
1130  case ISD::SHL:                return visitSHL(N);
1131  case ISD::SRA:                return visitSRA(N);
1132  case ISD::SRL:                return visitSRL(N);
1133  case ISD::CTLZ:               return visitCTLZ(N);
1134  case ISD::CTLZ_ZERO_UNDEF:    return visitCTLZ_ZERO_UNDEF(N);
1135  case ISD::CTTZ:               return visitCTTZ(N);
1136  case ISD::CTTZ_ZERO_UNDEF:    return visitCTTZ_ZERO_UNDEF(N);
1137  case ISD::CTPOP:              return visitCTPOP(N);
1138  case ISD::SELECT:             return visitSELECT(N);
1139  case ISD::VSELECT:            return visitVSELECT(N);
1140  case ISD::SELECT_CC:          return visitSELECT_CC(N);
1141  case ISD::SETCC:              return visitSETCC(N);
1142  case ISD::SIGN_EXTEND:        return visitSIGN_EXTEND(N);
1143  case ISD::ZERO_EXTEND:        return visitZERO_EXTEND(N);
1144  case ISD::ANY_EXTEND:         return visitANY_EXTEND(N);
1145  case ISD::SIGN_EXTEND_INREG:  return visitSIGN_EXTEND_INREG(N);
1146  case ISD::TRUNCATE:           return visitTRUNCATE(N);
1147  case ISD::BITCAST:            return visitBITCAST(N);
1148  case ISD::BUILD_PAIR:         return visitBUILD_PAIR(N);
1149  case ISD::FADD:               return visitFADD(N);
1150  case ISD::FSUB:               return visitFSUB(N);
1151  case ISD::FMUL:               return visitFMUL(N);
1152  case ISD::FMA:                return visitFMA(N);
1153  case ISD::FDIV:               return visitFDIV(N);
1154  case ISD::FREM:               return visitFREM(N);
1155  case ISD::FCOPYSIGN:          return visitFCOPYSIGN(N);
1156  case ISD::SINT_TO_FP:         return visitSINT_TO_FP(N);
1157  case ISD::UINT_TO_FP:         return visitUINT_TO_FP(N);
1158  case ISD::FP_TO_SINT:         return visitFP_TO_SINT(N);
1159  case ISD::FP_TO_UINT:         return visitFP_TO_UINT(N);
1160  case ISD::FP_ROUND:           return visitFP_ROUND(N);
1161  case ISD::FP_ROUND_INREG:     return visitFP_ROUND_INREG(N);
1162  case ISD::FP_EXTEND:          return visitFP_EXTEND(N);
1163  case ISD::FNEG:               return visitFNEG(N);
1164  case ISD::FABS:               return visitFABS(N);
1165  case ISD::FFLOOR:             return visitFFLOOR(N);
1166  case ISD::FCEIL:              return visitFCEIL(N);
1167  case ISD::FTRUNC:             return visitFTRUNC(N);
1168  case ISD::BRCOND:             return visitBRCOND(N);
1169  case ISD::BR_CC:              return visitBR_CC(N);
1170  case ISD::LOAD:               return visitLOAD(N);
1171  case ISD::STORE:              return visitSTORE(N);
1172  case ISD::INSERT_VECTOR_ELT:  return visitINSERT_VECTOR_ELT(N);
1173  case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1174  case ISD::BUILD_VECTOR:       return visitBUILD_VECTOR(N);
1175  case ISD::CONCAT_VECTORS:     return visitCONCAT_VECTORS(N);
1176  case ISD::EXTRACT_SUBVECTOR:  return visitEXTRACT_SUBVECTOR(N);
1177  case ISD::VECTOR_SHUFFLE:     return visitVECTOR_SHUFFLE(N);
1178  }
1179  return SDValue();
1180}
1181
1182SDValue DAGCombiner::combine(SDNode *N) {
1183  SDValue RV = visit(N);
1184
1185  // If nothing happened, try a target-specific DAG combine.
1186  if (RV.getNode() == 0) {
1187    assert(N->getOpcode() != ISD::DELETED_NODE &&
1188           "Node was deleted but visit returned NULL!");
1189
1190    if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1191        TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1192
1193      // Expose the DAG combiner to the target combiner impls.
1194      TargetLowering::DAGCombinerInfo
1195        DagCombineInfo(DAG, Level, false, this);
1196
1197      RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1198    }
1199  }
1200
1201  // If nothing happened still, try promoting the operation.
1202  if (RV.getNode() == 0) {
1203    switch (N->getOpcode()) {
1204    default: break;
1205    case ISD::ADD:
1206    case ISD::SUB:
1207    case ISD::MUL:
1208    case ISD::AND:
1209    case ISD::OR:
1210    case ISD::XOR:
1211      RV = PromoteIntBinOp(SDValue(N, 0));
1212      break;
1213    case ISD::SHL:
1214    case ISD::SRA:
1215    case ISD::SRL:
1216      RV = PromoteIntShiftOp(SDValue(N, 0));
1217      break;
1218    case ISD::SIGN_EXTEND:
1219    case ISD::ZERO_EXTEND:
1220    case ISD::ANY_EXTEND:
1221      RV = PromoteExtend(SDValue(N, 0));
1222      break;
1223    case ISD::LOAD:
1224      if (PromoteLoad(SDValue(N, 0)))
1225        RV = SDValue(N, 0);
1226      break;
1227    }
1228  }
1229
1230  // If N is a commutative binary node, try commuting it to enable more
1231  // sdisel CSE.
1232  if (RV.getNode() == 0 &&
1233      SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1234      N->getNumValues() == 1) {
1235    SDValue N0 = N->getOperand(0);
1236    SDValue N1 = N->getOperand(1);
1237
1238    // Constant operands are canonicalized to RHS.
1239    if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1240      SDValue Ops[] = { N1, N0 };
1241      SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(),
1242                                            Ops, 2);
1243      if (CSENode)
1244        return SDValue(CSENode, 0);
1245    }
1246  }
1247
1248  return RV;
1249}
1250
1251/// getInputChainForNode - Given a node, return its input chain if it has one,
1252/// otherwise return a null sd operand.
1253static SDValue getInputChainForNode(SDNode *N) {
1254  if (unsigned NumOps = N->getNumOperands()) {
1255    if (N->getOperand(0).getValueType() == MVT::Other)
1256      return N->getOperand(0);
1257    else if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1258      return N->getOperand(NumOps-1);
1259    for (unsigned i = 1; i < NumOps-1; ++i)
1260      if (N->getOperand(i).getValueType() == MVT::Other)
1261        return N->getOperand(i);
1262  }
1263  return SDValue();
1264}
1265
1266SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1267  // If N has two operands, where one has an input chain equal to the other,
1268  // the 'other' chain is redundant.
1269  if (N->getNumOperands() == 2) {
1270    if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1271      return N->getOperand(0);
1272    if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1273      return N->getOperand(1);
1274  }
1275
1276  SmallVector<SDNode *, 8> TFs;     // List of token factors to visit.
1277  SmallVector<SDValue, 8> Ops;    // Ops for replacing token factor.
1278  SmallPtrSet<SDNode*, 16> SeenOps;
1279  bool Changed = false;             // If we should replace this token factor.
1280
1281  // Start out with this token factor.
1282  TFs.push_back(N);
1283
1284  // Iterate through token factors.  The TFs grows when new token factors are
1285  // encountered.
1286  for (unsigned i = 0; i < TFs.size(); ++i) {
1287    SDNode *TF = TFs[i];
1288
1289    // Check each of the operands.
1290    for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
1291      SDValue Op = TF->getOperand(i);
1292
1293      switch (Op.getOpcode()) {
1294      case ISD::EntryToken:
1295        // Entry tokens don't need to be added to the list. They are
1296        // rededundant.
1297        Changed = true;
1298        break;
1299
1300      case ISD::TokenFactor:
1301        if (Op.hasOneUse() &&
1302            std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
1303          // Queue up for processing.
1304          TFs.push_back(Op.getNode());
1305          // Clean up in case the token factor is removed.
1306          AddToWorkList(Op.getNode());
1307          Changed = true;
1308          break;
1309        }
1310        // Fall thru
1311
1312      default:
1313        // Only add if it isn't already in the list.
1314        if (SeenOps.insert(Op.getNode()))
1315          Ops.push_back(Op);
1316        else
1317          Changed = true;
1318        break;
1319      }
1320    }
1321  }
1322
1323  SDValue Result;
1324
1325  // If we've change things around then replace token factor.
1326  if (Changed) {
1327    if (Ops.empty()) {
1328      // The entry token is the only possible outcome.
1329      Result = DAG.getEntryNode();
1330    } else {
1331      // New and improved token factor.
1332      Result = DAG.getNode(ISD::TokenFactor, SDLoc(N),
1333                           MVT::Other, &Ops[0], Ops.size());
1334    }
1335
1336    // Don't add users to work list.
1337    return CombineTo(N, Result, false);
1338  }
1339
1340  return Result;
1341}
1342
1343/// MERGE_VALUES can always be eliminated.
1344SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1345  WorkListRemover DeadNodes(*this);
1346  // Replacing results may cause a different MERGE_VALUES to suddenly
1347  // be CSE'd with N, and carry its uses with it. Iterate until no
1348  // uses remain, to ensure that the node can be safely deleted.
1349  // First add the users of this node to the work list so that they
1350  // can be tried again once they have new operands.
1351  AddUsersToWorkList(N);
1352  do {
1353    for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1354      DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1355  } while (!N->use_empty());
1356  removeFromWorkList(N);
1357  DAG.DeleteNode(N);
1358  return SDValue(N, 0);   // Return N so it doesn't get rechecked!
1359}
1360
1361static
1362SDValue combineShlAddConstant(SDLoc DL, SDValue N0, SDValue N1,
1363                              SelectionDAG &DAG) {
1364  EVT VT = N0.getValueType();
1365  SDValue N00 = N0.getOperand(0);
1366  SDValue N01 = N0.getOperand(1);
1367  ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N01);
1368
1369  if (N01C && N00.getOpcode() == ISD::ADD && N00.getNode()->hasOneUse() &&
1370      isa<ConstantSDNode>(N00.getOperand(1))) {
1371    // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1372    N0 = DAG.getNode(ISD::ADD, SDLoc(N0), VT,
1373                     DAG.getNode(ISD::SHL, SDLoc(N00), VT,
1374                                 N00.getOperand(0), N01),
1375                     DAG.getNode(ISD::SHL, SDLoc(N01), VT,
1376                                 N00.getOperand(1), N01));
1377    return DAG.getNode(ISD::ADD, DL, VT, N0, N1);
1378  }
1379
1380  return SDValue();
1381}
1382
1383SDValue DAGCombiner::visitADD(SDNode *N) {
1384  SDValue N0 = N->getOperand(0);
1385  SDValue N1 = N->getOperand(1);
1386  ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1387  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1388  EVT VT = N0.getValueType();
1389
1390  // fold vector ops
1391  if (VT.isVector()) {
1392    SDValue FoldedVOp = SimplifyVBinOp(N);
1393    if (FoldedVOp.getNode()) return FoldedVOp;
1394
1395    // fold (add x, 0) -> x, vector edition
1396    if (ISD::isBuildVectorAllZeros(N1.getNode()))
1397      return N0;
1398    if (ISD::isBuildVectorAllZeros(N0.getNode()))
1399      return N1;
1400  }
1401
1402  // fold (add x, undef) -> undef
1403  if (N0.getOpcode() == ISD::UNDEF)
1404    return N0;
1405  if (N1.getOpcode() == ISD::UNDEF)
1406    return N1;
1407  // fold (add c1, c2) -> c1+c2
1408  if (N0C && N1C)
1409    return DAG.FoldConstantArithmetic(ISD::ADD, VT, N0C, N1C);
1410  // canonicalize constant to RHS
1411  if (N0C && !N1C)
1412    return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
1413  // fold (add x, 0) -> x
1414  if (N1C && N1C->isNullValue())
1415    return N0;
1416  // fold (add Sym, c) -> Sym+c
1417  if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1418    if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1419        GA->getOpcode() == ISD::GlobalAddress)
1420      return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1421                                  GA->getOffset() +
1422                                    (uint64_t)N1C->getSExtValue());
1423  // fold ((c1-A)+c2) -> (c1+c2)-A
1424  if (N1C && N0.getOpcode() == ISD::SUB)
1425    if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
1426      return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1427                         DAG.getConstant(N1C->getAPIntValue()+
1428                                         N0C->getAPIntValue(), VT),
1429                         N0.getOperand(1));
1430  // reassociate add
1431  SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1);
1432  if (RADD.getNode() != 0)
1433    return RADD;
1434  // fold ((0-A) + B) -> B-A
1435  if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
1436      cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
1437    return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
1438  // fold (A + (0-B)) -> A-B
1439  if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
1440      cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
1441    return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
1442  // fold (A+(B-A)) -> B
1443  if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1444    return N1.getOperand(0);
1445  // fold ((B-A)+A) -> B
1446  if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1447    return N0.getOperand(0);
1448  // fold (A+(B-(A+C))) to (B-C)
1449  if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1450      N0 == N1.getOperand(1).getOperand(0))
1451    return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1452                       N1.getOperand(1).getOperand(1));
1453  // fold (A+(B-(C+A))) to (B-C)
1454  if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1455      N0 == N1.getOperand(1).getOperand(1))
1456    return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1457                       N1.getOperand(1).getOperand(0));
1458  // fold (A+((B-A)+or-C)) to (B+or-C)
1459  if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1460      N1.getOperand(0).getOpcode() == ISD::SUB &&
1461      N0 == N1.getOperand(0).getOperand(1))
1462    return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
1463                       N1.getOperand(0).getOperand(0), N1.getOperand(1));
1464
1465  // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1466  if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1467    SDValue N00 = N0.getOperand(0);
1468    SDValue N01 = N0.getOperand(1);
1469    SDValue N10 = N1.getOperand(0);
1470    SDValue N11 = N1.getOperand(1);
1471
1472    if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1473      return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1474                         DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1475                         DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1476  }
1477
1478  if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1479    return SDValue(N, 0);
1480
1481  // fold (a+b) -> (a|b) iff a and b share no bits.
1482  if (VT.isInteger() && !VT.isVector()) {
1483    APInt LHSZero, LHSOne;
1484    APInt RHSZero, RHSOne;
1485    DAG.ComputeMaskedBits(N0, LHSZero, LHSOne);
1486
1487    if (LHSZero.getBoolValue()) {
1488      DAG.ComputeMaskedBits(N1, RHSZero, RHSOne);
1489
1490      // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1491      // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1492      if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1493        return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1494    }
1495  }
1496
1497  // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1498  if (N0.getOpcode() == ISD::SHL && N0.getNode()->hasOneUse()) {
1499    SDValue Result = combineShlAddConstant(SDLoc(N), N0, N1, DAG);
1500    if (Result.getNode()) return Result;
1501  }
1502  if (N1.getOpcode() == ISD::SHL && N1.getNode()->hasOneUse()) {
1503    SDValue Result = combineShlAddConstant(SDLoc(N), N1, N0, DAG);
1504    if (Result.getNode()) return Result;
1505  }
1506
1507  // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1508  if (N1.getOpcode() == ISD::SHL &&
1509      N1.getOperand(0).getOpcode() == ISD::SUB)
1510    if (ConstantSDNode *C =
1511          dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0)))
1512      if (C->getAPIntValue() == 0)
1513        return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1514                           DAG.getNode(ISD::SHL, SDLoc(N), VT,
1515                                       N1.getOperand(0).getOperand(1),
1516                                       N1.getOperand(1)));
1517  if (N0.getOpcode() == ISD::SHL &&
1518      N0.getOperand(0).getOpcode() == ISD::SUB)
1519    if (ConstantSDNode *C =
1520          dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0)))
1521      if (C->getAPIntValue() == 0)
1522        return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1523                           DAG.getNode(ISD::SHL, SDLoc(N), VT,
1524                                       N0.getOperand(0).getOperand(1),
1525                                       N0.getOperand(1)));
1526
1527  if (N1.getOpcode() == ISD::AND) {
1528    SDValue AndOp0 = N1.getOperand(0);
1529    ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(N1->getOperand(1));
1530    unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1531    unsigned DestBits = VT.getScalarType().getSizeInBits();
1532
1533    // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1534    // and similar xforms where the inner op is either ~0 or 0.
1535    if (NumSignBits == DestBits && AndOp1 && AndOp1->isOne()) {
1536      SDLoc DL(N);
1537      return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1538    }
1539  }
1540
1541  // add (sext i1), X -> sub X, (zext i1)
1542  if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1543      N0.getOperand(0).getValueType() == MVT::i1 &&
1544      !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1545    SDLoc DL(N);
1546    SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1547    return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1548  }
1549
1550  return SDValue();
1551}
1552
1553SDValue DAGCombiner::visitADDC(SDNode *N) {
1554  SDValue N0 = N->getOperand(0);
1555  SDValue N1 = N->getOperand(1);
1556  ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1557  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1558  EVT VT = N0.getValueType();
1559
1560  // If the flag result is dead, turn this into an ADD.
1561  if (!N->hasAnyUseOfValue(1))
1562    return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
1563                     DAG.getNode(ISD::CARRY_FALSE,
1564                                 SDLoc(N), MVT::Glue));
1565
1566  // canonicalize constant to RHS.
1567  if (N0C && !N1C)
1568    return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
1569
1570  // fold (addc x, 0) -> x + no carry out
1571  if (N1C && N1C->isNullValue())
1572    return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1573                                        SDLoc(N), MVT::Glue));
1574
1575  // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1576  APInt LHSZero, LHSOne;
1577  APInt RHSZero, RHSOne;
1578  DAG.ComputeMaskedBits(N0, LHSZero, LHSOne);
1579
1580  if (LHSZero.getBoolValue()) {
1581    DAG.ComputeMaskedBits(N1, RHSZero, RHSOne);
1582
1583    // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1584    // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1585    if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1586      return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
1587                       DAG.getNode(ISD::CARRY_FALSE,
1588                                   SDLoc(N), MVT::Glue));
1589  }
1590
1591  return SDValue();
1592}
1593
1594SDValue DAGCombiner::visitADDE(SDNode *N) {
1595  SDValue N0 = N->getOperand(0);
1596  SDValue N1 = N->getOperand(1);
1597  SDValue CarryIn = N->getOperand(2);
1598  ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1599  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1600
1601  // canonicalize constant to RHS
1602  if (N0C && !N1C)
1603    return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
1604                       N1, N0, CarryIn);
1605
1606  // fold (adde x, y, false) -> (addc x, y)
1607  if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1608    return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
1609
1610  return SDValue();
1611}
1612
1613// Since it may not be valid to emit a fold to zero for vector initializers
1614// check if we can before folding.
1615static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
1616                             SelectionDAG &DAG, bool LegalOperations) {
1617  if (!VT.isVector()) {
1618    return DAG.getConstant(0, VT);
1619  }
1620  if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT)) {
1621    // Produce a vector of zeros.
1622    SDValue El = DAG.getConstant(0, VT.getVectorElementType());
1623    std::vector<SDValue> Ops(VT.getVectorNumElements(), El);
1624    return DAG.getNode(ISD::BUILD_VECTOR, DL, VT,
1625      &Ops[0], Ops.size());
1626  }
1627  return SDValue();
1628}
1629
1630SDValue DAGCombiner::visitSUB(SDNode *N) {
1631  SDValue N0 = N->getOperand(0);
1632  SDValue N1 = N->getOperand(1);
1633  ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1634  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1635  ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? 0 :
1636    dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
1637  EVT VT = N0.getValueType();
1638
1639  // fold vector ops
1640  if (VT.isVector()) {
1641    SDValue FoldedVOp = SimplifyVBinOp(N);
1642    if (FoldedVOp.getNode()) return FoldedVOp;
1643
1644    // fold (sub x, 0) -> x, vector edition
1645    if (ISD::isBuildVectorAllZeros(N1.getNode()))
1646      return N0;
1647  }
1648
1649  // fold (sub x, x) -> 0
1650  // FIXME: Refactor this and xor and other similar operations together.
1651  if (N0 == N1)
1652    return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations);
1653  // fold (sub c1, c2) -> c1-c2
1654  if (N0C && N1C)
1655    return DAG.FoldConstantArithmetic(ISD::SUB, VT, N0C, N1C);
1656  // fold (sub x, c) -> (add x, -c)
1657  if (N1C)
1658    return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0,
1659                       DAG.getConstant(-N1C->getAPIntValue(), VT));
1660  // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1661  if (N0C && N0C->isAllOnesValue())
1662    return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
1663  // fold A-(A-B) -> B
1664  if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1665    return N1.getOperand(1);
1666  // fold (A+B)-A -> B
1667  if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1668    return N0.getOperand(1);
1669  // fold (A+B)-B -> A
1670  if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1671    return N0.getOperand(0);
1672  // fold C2-(A+C1) -> (C2-C1)-A
1673  if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
1674    SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1675                                   VT);
1676    return DAG.getNode(ISD::SUB, SDLoc(N), VT, NewC,
1677                       N1.getOperand(0));
1678  }
1679  // fold ((A+(B+or-C))-B) -> A+or-C
1680  if (N0.getOpcode() == ISD::ADD &&
1681      (N0.getOperand(1).getOpcode() == ISD::SUB ||
1682       N0.getOperand(1).getOpcode() == ISD::ADD) &&
1683      N0.getOperand(1).getOperand(0) == N1)
1684    return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
1685                       N0.getOperand(0), N0.getOperand(1).getOperand(1));
1686  // fold ((A+(C+B))-B) -> A+C
1687  if (N0.getOpcode() == ISD::ADD &&
1688      N0.getOperand(1).getOpcode() == ISD::ADD &&
1689      N0.getOperand(1).getOperand(1) == N1)
1690    return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1691                       N0.getOperand(0), N0.getOperand(1).getOperand(0));
1692  // fold ((A-(B-C))-C) -> A-B
1693  if (N0.getOpcode() == ISD::SUB &&
1694      N0.getOperand(1).getOpcode() == ISD::SUB &&
1695      N0.getOperand(1).getOperand(1) == N1)
1696    return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1697                       N0.getOperand(0), N0.getOperand(1).getOperand(0));
1698
1699  // If either operand of a sub is undef, the result is undef
1700  if (N0.getOpcode() == ISD::UNDEF)
1701    return N0;
1702  if (N1.getOpcode() == ISD::UNDEF)
1703    return N1;
1704
1705  // If the relocation model supports it, consider symbol offsets.
1706  if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1707    if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1708      // fold (sub Sym, c) -> Sym-c
1709      if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1710        return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1711                                    GA->getOffset() -
1712                                      (uint64_t)N1C->getSExtValue());
1713      // fold (sub Sym+c1, Sym+c2) -> c1-c2
1714      if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1715        if (GA->getGlobal() == GB->getGlobal())
1716          return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1717                                 VT);
1718    }
1719
1720  return SDValue();
1721}
1722
1723SDValue DAGCombiner::visitSUBC(SDNode *N) {
1724  SDValue N0 = N->getOperand(0);
1725  SDValue N1 = N->getOperand(1);
1726  ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1727  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1728  EVT VT = N0.getValueType();
1729
1730  // If the flag result is dead, turn this into an SUB.
1731  if (!N->hasAnyUseOfValue(1))
1732    return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1),
1733                     DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1734                                 MVT::Glue));
1735
1736  // fold (subc x, x) -> 0 + no borrow
1737  if (N0 == N1)
1738    return CombineTo(N, DAG.getConstant(0, VT),
1739                     DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1740                                 MVT::Glue));
1741
1742  // fold (subc x, 0) -> x + no borrow
1743  if (N1C && N1C->isNullValue())
1744    return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1745                                        MVT::Glue));
1746
1747  // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
1748  if (N0C && N0C->isAllOnesValue())
1749    return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0),
1750                     DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1751                                 MVT::Glue));
1752
1753  return SDValue();
1754}
1755
1756SDValue DAGCombiner::visitSUBE(SDNode *N) {
1757  SDValue N0 = N->getOperand(0);
1758  SDValue N1 = N->getOperand(1);
1759  SDValue CarryIn = N->getOperand(2);
1760
1761  // fold (sube x, y, false) -> (subc x, y)
1762  if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1763    return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
1764
1765  return SDValue();
1766}
1767
1768/// isConstantSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
1769/// all the same constant or undefined.
1770static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) {
1771  BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N);
1772  if (!C)
1773    return false;
1774
1775  APInt SplatUndef;
1776  unsigned SplatBitSize;
1777  bool HasAnyUndefs;
1778  EVT EltVT = N->getValueType(0).getVectorElementType();
1779  return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
1780                             HasAnyUndefs) &&
1781          EltVT.getSizeInBits() >= SplatBitSize);
1782}
1783
1784SDValue DAGCombiner::visitMUL(SDNode *N) {
1785  SDValue N0 = N->getOperand(0);
1786  SDValue N1 = N->getOperand(1);
1787  EVT VT = N0.getValueType();
1788
1789  // fold (mul x, undef) -> 0
1790  if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1791    return DAG.getConstant(0, VT);
1792
1793  bool N0IsConst = false;
1794  bool N1IsConst = false;
1795  APInt ConstValue0, ConstValue1;
1796  // fold vector ops
1797  if (VT.isVector()) {
1798    SDValue FoldedVOp = SimplifyVBinOp(N);
1799    if (FoldedVOp.getNode()) return FoldedVOp;
1800
1801    N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
1802    N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
1803  } else {
1804    N0IsConst = dyn_cast<ConstantSDNode>(N0) != 0;
1805    ConstValue0 = N0IsConst? (dyn_cast<ConstantSDNode>(N0))->getAPIntValue() : APInt();
1806    N1IsConst = dyn_cast<ConstantSDNode>(N1) != 0;
1807    ConstValue1 = N1IsConst? (dyn_cast<ConstantSDNode>(N1))->getAPIntValue() : APInt();
1808  }
1809
1810  // fold (mul c1, c2) -> c1*c2
1811  if (N0IsConst && N1IsConst)
1812    return DAG.FoldConstantArithmetic(ISD::MUL, VT, N0.getNode(), N1.getNode());
1813
1814  // canonicalize constant to RHS
1815  if (N0IsConst && !N1IsConst)
1816    return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
1817  // fold (mul x, 0) -> 0
1818  if (N1IsConst && ConstValue1 == 0)
1819    return N1;
1820  // fold (mul x, 1) -> x
1821  if (N1IsConst && ConstValue1 == 1)
1822    return N0;
1823  // fold (mul x, -1) -> 0-x
1824  if (N1IsConst && ConstValue1.isAllOnesValue())
1825    return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1826                       DAG.getConstant(0, VT), N0);
1827  // fold (mul x, (1 << c)) -> x << c
1828  if (N1IsConst && ConstValue1.isPowerOf2())
1829    return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
1830                       DAG.getConstant(ConstValue1.logBase2(),
1831                                       getShiftAmountTy(N0.getValueType())));
1832  // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
1833  if (N1IsConst && (-ConstValue1).isPowerOf2()) {
1834    unsigned Log2Val = (-ConstValue1).logBase2();
1835    // FIXME: If the input is something that is easily negated (e.g. a
1836    // single-use add), we should put the negate there.
1837    return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1838                       DAG.getConstant(0, VT),
1839                       DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
1840                            DAG.getConstant(Log2Val,
1841                                      getShiftAmountTy(N0.getValueType()))));
1842  }
1843
1844  APInt Val;
1845  // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
1846  if (N1IsConst && N0.getOpcode() == ISD::SHL &&
1847      (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1848                     isa<ConstantSDNode>(N0.getOperand(1)))) {
1849    SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
1850                             N1, N0.getOperand(1));
1851    AddToWorkList(C3.getNode());
1852    return DAG.getNode(ISD::MUL, SDLoc(N), VT,
1853                       N0.getOperand(0), C3);
1854  }
1855
1856  // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
1857  // use.
1858  {
1859    SDValue Sh(0,0), Y(0,0);
1860    // Check for both (mul (shl X, C), Y)  and  (mul Y, (shl X, C)).
1861    if (N0.getOpcode() == ISD::SHL &&
1862        (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1863                       isa<ConstantSDNode>(N0.getOperand(1))) &&
1864        N0.getNode()->hasOneUse()) {
1865      Sh = N0; Y = N1;
1866    } else if (N1.getOpcode() == ISD::SHL &&
1867               isa<ConstantSDNode>(N1.getOperand(1)) &&
1868               N1.getNode()->hasOneUse()) {
1869      Sh = N1; Y = N0;
1870    }
1871
1872    if (Sh.getNode()) {
1873      SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
1874                                Sh.getOperand(0), Y);
1875      return DAG.getNode(ISD::SHL, SDLoc(N), VT,
1876                         Mul, Sh.getOperand(1));
1877    }
1878  }
1879
1880  // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
1881  if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
1882      (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1883                     isa<ConstantSDNode>(N0.getOperand(1))))
1884    return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1885                       DAG.getNode(ISD::MUL, SDLoc(N0), VT,
1886                                   N0.getOperand(0), N1),
1887                       DAG.getNode(ISD::MUL, SDLoc(N1), VT,
1888                                   N0.getOperand(1), N1));
1889
1890  // reassociate mul
1891  SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1);
1892  if (RMUL.getNode() != 0)
1893    return RMUL;
1894
1895  return SDValue();
1896}
1897
1898SDValue DAGCombiner::visitSDIV(SDNode *N) {
1899  SDValue N0 = N->getOperand(0);
1900  SDValue N1 = N->getOperand(1);
1901  ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1902  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1903  EVT VT = N->getValueType(0);
1904
1905  // fold vector ops
1906  if (VT.isVector()) {
1907    SDValue FoldedVOp = SimplifyVBinOp(N);
1908    if (FoldedVOp.getNode()) return FoldedVOp;
1909  }
1910
1911  // fold (sdiv c1, c2) -> c1/c2
1912  if (N0C && N1C && !N1C->isNullValue())
1913    return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C);
1914  // fold (sdiv X, 1) -> X
1915  if (N1C && N1C->getAPIntValue() == 1LL)
1916    return N0;
1917  // fold (sdiv X, -1) -> 0-X
1918  if (N1C && N1C->isAllOnesValue())
1919    return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1920                       DAG.getConstant(0, VT), N0);
1921  // If we know the sign bits of both operands are zero, strength reduce to a
1922  // udiv instead.  Handles (X&15) /s 4 -> X&15 >> 2
1923  if (!VT.isVector()) {
1924    if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
1925      return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(),
1926                         N0, N1);
1927  }
1928  // fold (sdiv X, pow2) -> simple ops after legalize
1929  if (N1C && !N1C->isNullValue() &&
1930      (N1C->getAPIntValue().isPowerOf2() ||
1931       (-N1C->getAPIntValue()).isPowerOf2())) {
1932    // If dividing by powers of two is cheap, then don't perform the following
1933    // fold.
1934    if (TLI.isPow2DivCheap())
1935      return SDValue();
1936
1937    unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
1938
1939    // Splat the sign bit into the register
1940    SDValue SGN = DAG.getNode(ISD::SRA, SDLoc(N), VT, N0,
1941                              DAG.getConstant(VT.getSizeInBits()-1,
1942                                       getShiftAmountTy(N0.getValueType())));
1943    AddToWorkList(SGN.getNode());
1944
1945    // Add (N0 < 0) ? abs2 - 1 : 0;
1946    SDValue SRL = DAG.getNode(ISD::SRL, SDLoc(N), VT, SGN,
1947                              DAG.getConstant(VT.getSizeInBits() - lg2,
1948                                       getShiftAmountTy(SGN.getValueType())));
1949    SDValue ADD = DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, SRL);
1950    AddToWorkList(SRL.getNode());
1951    AddToWorkList(ADD.getNode());    // Divide by pow2
1952    SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), VT, ADD,
1953                  DAG.getConstant(lg2, getShiftAmountTy(ADD.getValueType())));
1954
1955    // If we're dividing by a positive value, we're done.  Otherwise, we must
1956    // negate the result.
1957    if (N1C->getAPIntValue().isNonNegative())
1958      return SRA;
1959
1960    AddToWorkList(SRA.getNode());
1961    return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1962                       DAG.getConstant(0, VT), SRA);
1963  }
1964
1965  // if integer divide is expensive and we satisfy the requirements, emit an
1966  // alternate sequence.
1967  if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap()) {
1968    SDValue Op = BuildSDIV(N);
1969    if (Op.getNode()) return Op;
1970  }
1971
1972  // undef / X -> 0
1973  if (N0.getOpcode() == ISD::UNDEF)
1974    return DAG.getConstant(0, VT);
1975  // X / undef -> undef
1976  if (N1.getOpcode() == ISD::UNDEF)
1977    return N1;
1978
1979  return SDValue();
1980}
1981
1982SDValue DAGCombiner::visitUDIV(SDNode *N) {
1983  SDValue N0 = N->getOperand(0);
1984  SDValue N1 = N->getOperand(1);
1985  ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1986  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1987  EVT VT = N->getValueType(0);
1988
1989  // fold vector ops
1990  if (VT.isVector()) {
1991    SDValue FoldedVOp = SimplifyVBinOp(N);
1992    if (FoldedVOp.getNode()) return FoldedVOp;
1993  }
1994
1995  // fold (udiv c1, c2) -> c1/c2
1996  if (N0C && N1C && !N1C->isNullValue())
1997    return DAG.FoldConstantArithmetic(ISD::UDIV, VT, N0C, N1C);
1998  // fold (udiv x, (1 << c)) -> x >>u c
1999  if (N1C && N1C->getAPIntValue().isPowerOf2())
2000    return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0,
2001                       DAG.getConstant(N1C->getAPIntValue().logBase2(),
2002                                       getShiftAmountTy(N0.getValueType())));
2003  // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2004  if (N1.getOpcode() == ISD::SHL) {
2005    if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2006      if (SHC->getAPIntValue().isPowerOf2()) {
2007        EVT ADDVT = N1.getOperand(1).getValueType();
2008        SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N), ADDVT,
2009                                  N1.getOperand(1),
2010                                  DAG.getConstant(SHC->getAPIntValue()
2011                                                                  .logBase2(),
2012                                                  ADDVT));
2013        AddToWorkList(Add.getNode());
2014        return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, Add);
2015      }
2016    }
2017  }
2018  // fold (udiv x, c) -> alternate
2019  if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap()) {
2020    SDValue Op = BuildUDIV(N);
2021    if (Op.getNode()) return Op;
2022  }
2023
2024  // undef / X -> 0
2025  if (N0.getOpcode() == ISD::UNDEF)
2026    return DAG.getConstant(0, VT);
2027  // X / undef -> undef
2028  if (N1.getOpcode() == ISD::UNDEF)
2029    return N1;
2030
2031  return SDValue();
2032}
2033
2034SDValue DAGCombiner::visitSREM(SDNode *N) {
2035  SDValue N0 = N->getOperand(0);
2036  SDValue N1 = N->getOperand(1);
2037  ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2038  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2039  EVT VT = N->getValueType(0);
2040
2041  // fold (srem c1, c2) -> c1%c2
2042  if (N0C && N1C && !N1C->isNullValue())
2043    return DAG.FoldConstantArithmetic(ISD::SREM, VT, N0C, N1C);
2044  // If we know the sign bits of both operands are zero, strength reduce to a
2045  // urem instead.  Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2046  if (!VT.isVector()) {
2047    if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2048      return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1);
2049  }
2050
2051  // If X/C can be simplified by the division-by-constant logic, lower
2052  // X%C to the equivalent of X-X/C*C.
2053  if (N1C && !N1C->isNullValue()) {
2054    SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1);
2055    AddToWorkList(Div.getNode());
2056    SDValue OptimizedDiv = combine(Div.getNode());
2057    if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2058      SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2059                                OptimizedDiv, N1);
2060      SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2061      AddToWorkList(Mul.getNode());
2062      return Sub;
2063    }
2064  }
2065
2066  // undef % X -> 0
2067  if (N0.getOpcode() == ISD::UNDEF)
2068    return DAG.getConstant(0, VT);
2069  // X % undef -> undef
2070  if (N1.getOpcode() == ISD::UNDEF)
2071    return N1;
2072
2073  return SDValue();
2074}
2075
2076SDValue DAGCombiner::visitUREM(SDNode *N) {
2077  SDValue N0 = N->getOperand(0);
2078  SDValue N1 = N->getOperand(1);
2079  ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2080  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2081  EVT VT = N->getValueType(0);
2082
2083  // fold (urem c1, c2) -> c1%c2
2084  if (N0C && N1C && !N1C->isNullValue())
2085    return DAG.FoldConstantArithmetic(ISD::UREM, VT, N0C, N1C);
2086  // fold (urem x, pow2) -> (and x, pow2-1)
2087  if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2())
2088    return DAG.getNode(ISD::AND, SDLoc(N), VT, N0,
2089                       DAG.getConstant(N1C->getAPIntValue()-1,VT));
2090  // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2091  if (N1.getOpcode() == ISD::SHL) {
2092    if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2093      if (SHC->getAPIntValue().isPowerOf2()) {
2094        SDValue Add =
2095          DAG.getNode(ISD::ADD, SDLoc(N), VT, N1,
2096                 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()),
2097                                 VT));
2098        AddToWorkList(Add.getNode());
2099        return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, Add);
2100      }
2101    }
2102  }
2103
2104  // If X/C can be simplified by the division-by-constant logic, lower
2105  // X%C to the equivalent of X-X/C*C.
2106  if (N1C && !N1C->isNullValue()) {
2107    SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1);
2108    AddToWorkList(Div.getNode());
2109    SDValue OptimizedDiv = combine(Div.getNode());
2110    if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2111      SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2112                                OptimizedDiv, N1);
2113      SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2114      AddToWorkList(Mul.getNode());
2115      return Sub;
2116    }
2117  }
2118
2119  // undef % X -> 0
2120  if (N0.getOpcode() == ISD::UNDEF)
2121    return DAG.getConstant(0, VT);
2122  // X % undef -> undef
2123  if (N1.getOpcode() == ISD::UNDEF)
2124    return N1;
2125
2126  return SDValue();
2127}
2128
2129SDValue DAGCombiner::visitMULHS(SDNode *N) {
2130  SDValue N0 = N->getOperand(0);
2131  SDValue N1 = N->getOperand(1);
2132  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2133  EVT VT = N->getValueType(0);
2134  SDLoc DL(N);
2135
2136  // fold (mulhs x, 0) -> 0
2137  if (N1C && N1C->isNullValue())
2138    return N1;
2139  // fold (mulhs x, 1) -> (sra x, size(x)-1)
2140  if (N1C && N1C->getAPIntValue() == 1)
2141    return DAG.getNode(ISD::SRA, SDLoc(N), N0.getValueType(), N0,
2142                       DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
2143                                       getShiftAmountTy(N0.getValueType())));
2144  // fold (mulhs x, undef) -> 0
2145  if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2146    return DAG.getConstant(0, VT);
2147
2148  // If the type twice as wide is legal, transform the mulhs to a wider multiply
2149  // plus a shift.
2150  if (VT.isSimple() && !VT.isVector()) {
2151    MVT Simple = VT.getSimpleVT();
2152    unsigned SimpleSize = Simple.getSizeInBits();
2153    EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2154    if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2155      N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2156      N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2157      N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2158      N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2159            DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2160      return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2161    }
2162  }
2163
2164  return SDValue();
2165}
2166
2167SDValue DAGCombiner::visitMULHU(SDNode *N) {
2168  SDValue N0 = N->getOperand(0);
2169  SDValue N1 = N->getOperand(1);
2170  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2171  EVT VT = N->getValueType(0);
2172  SDLoc DL(N);
2173
2174  // fold (mulhu x, 0) -> 0
2175  if (N1C && N1C->isNullValue())
2176    return N1;
2177  // fold (mulhu x, 1) -> 0
2178  if (N1C && N1C->getAPIntValue() == 1)
2179    return DAG.getConstant(0, N0.getValueType());
2180  // fold (mulhu x, undef) -> 0
2181  if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2182    return DAG.getConstant(0, VT);
2183
2184  // If the type twice as wide is legal, transform the mulhu to a wider multiply
2185  // plus a shift.
2186  if (VT.isSimple() && !VT.isVector()) {
2187    MVT Simple = VT.getSimpleVT();
2188    unsigned SimpleSize = Simple.getSizeInBits();
2189    EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2190    if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2191      N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2192      N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2193      N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2194      N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2195            DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2196      return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2197    }
2198  }
2199
2200  return SDValue();
2201}
2202
2203/// SimplifyNodeWithTwoResults - Perform optimizations common to nodes that
2204/// compute two values. LoOp and HiOp give the opcodes for the two computations
2205/// that are being performed. Return true if a simplification was made.
2206///
2207SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2208                                                unsigned HiOp) {
2209  // If the high half is not needed, just compute the low half.
2210  bool HiExists = N->hasAnyUseOfValue(1);
2211  if (!HiExists &&
2212      (!LegalOperations ||
2213       TLI.isOperationLegal(LoOp, N->getValueType(0)))) {
2214    SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0),
2215                              N->op_begin(), N->getNumOperands());
2216    return CombineTo(N, Res, Res);
2217  }
2218
2219  // If the low half is not needed, just compute the high half.
2220  bool LoExists = N->hasAnyUseOfValue(0);
2221  if (!LoExists &&
2222      (!LegalOperations ||
2223       TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2224    SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1),
2225                              N->op_begin(), N->getNumOperands());
2226    return CombineTo(N, Res, Res);
2227  }
2228
2229  // If both halves are used, return as it is.
2230  if (LoExists && HiExists)
2231    return SDValue();
2232
2233  // If the two computed results can be simplified separately, separate them.
2234  if (LoExists) {
2235    SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0),
2236                             N->op_begin(), N->getNumOperands());
2237    AddToWorkList(Lo.getNode());
2238    SDValue LoOpt = combine(Lo.getNode());
2239    if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2240        (!LegalOperations ||
2241         TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2242      return CombineTo(N, LoOpt, LoOpt);
2243  }
2244
2245  if (HiExists) {
2246    SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1),
2247                             N->op_begin(), N->getNumOperands());
2248    AddToWorkList(Hi.getNode());
2249    SDValue HiOpt = combine(Hi.getNode());
2250    if (HiOpt.getNode() && HiOpt != Hi &&
2251        (!LegalOperations ||
2252         TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2253      return CombineTo(N, HiOpt, HiOpt);
2254  }
2255
2256  return SDValue();
2257}
2258
2259SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2260  SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
2261  if (Res.getNode()) return Res;
2262
2263  EVT VT = N->getValueType(0);
2264  SDLoc DL(N);
2265
2266  // If the type twice as wide is legal, transform the mulhu to a wider multiply
2267  // plus a shift.
2268  if (VT.isSimple() && !VT.isVector()) {
2269    MVT Simple = VT.getSimpleVT();
2270    unsigned SimpleSize = Simple.getSizeInBits();
2271    EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2272    if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2273      SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2274      SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2275      Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2276      // Compute the high part as N1.
2277      Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2278            DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2279      Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2280      // Compute the low part as N0.
2281      Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2282      return CombineTo(N, Lo, Hi);
2283    }
2284  }
2285
2286  return SDValue();
2287}
2288
2289SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2290  SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
2291  if (Res.getNode()) return Res;
2292
2293  EVT VT = N->getValueType(0);
2294  SDLoc DL(N);
2295
2296  // If the type twice as wide is legal, transform the mulhu to a wider multiply
2297  // plus a shift.
2298  if (VT.isSimple() && !VT.isVector()) {
2299    MVT Simple = VT.getSimpleVT();
2300    unsigned SimpleSize = Simple.getSizeInBits();
2301    EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2302    if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2303      SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2304      SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2305      Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2306      // Compute the high part as N1.
2307      Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2308            DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2309      Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2310      // Compute the low part as N0.
2311      Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2312      return CombineTo(N, Lo, Hi);
2313    }
2314  }
2315
2316  return SDValue();
2317}
2318
2319SDValue DAGCombiner::visitSMULO(SDNode *N) {
2320  // (smulo x, 2) -> (saddo x, x)
2321  if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2322    if (C2->getAPIntValue() == 2)
2323      return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
2324                         N->getOperand(0), N->getOperand(0));
2325
2326  return SDValue();
2327}
2328
2329SDValue DAGCombiner::visitUMULO(SDNode *N) {
2330  // (umulo x, 2) -> (uaddo x, x)
2331  if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2332    if (C2->getAPIntValue() == 2)
2333      return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
2334                         N->getOperand(0), N->getOperand(0));
2335
2336  return SDValue();
2337}
2338
2339SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2340  SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
2341  if (Res.getNode()) return Res;
2342
2343  return SDValue();
2344}
2345
2346SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2347  SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
2348  if (Res.getNode()) return Res;
2349
2350  return SDValue();
2351}
2352
2353/// SimplifyBinOpWithSameOpcodeHands - If this is a binary operator with
2354/// two operands of the same opcode, try to simplify it.
2355SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2356  SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2357  EVT VT = N0.getValueType();
2358  assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2359
2360  // Bail early if none of these transforms apply.
2361  if (N0.getNode()->getNumOperands() == 0) return SDValue();
2362
2363  // For each of OP in AND/OR/XOR:
2364  // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2365  // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2366  // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2367  // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2368  //
2369  // do not sink logical op inside of a vector extend, since it may combine
2370  // into a vsetcc.
2371  EVT Op0VT = N0.getOperand(0).getValueType();
2372  if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2373       N0.getOpcode() == ISD::SIGN_EXTEND ||
2374       // Avoid infinite looping with PromoteIntBinOp.
2375       (N0.getOpcode() == ISD::ANY_EXTEND &&
2376        (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2377       (N0.getOpcode() == ISD::TRUNCATE &&
2378        (!TLI.isZExtFree(VT, Op0VT) ||
2379         !TLI.isTruncateFree(Op0VT, VT)) &&
2380        TLI.isTypeLegal(Op0VT))) &&
2381      !VT.isVector() &&
2382      Op0VT == N1.getOperand(0).getValueType() &&
2383      (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2384    SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2385                                 N0.getOperand(0).getValueType(),
2386                                 N0.getOperand(0), N1.getOperand(0));
2387    AddToWorkList(ORNode.getNode());
2388    return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
2389  }
2390
2391  // For each of OP in SHL/SRL/SRA/AND...
2392  //   fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2393  //   fold (or  (OP x, z), (OP y, z)) -> (OP (or  x, y), z)
2394  //   fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2395  if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2396       N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2397      N0.getOperand(1) == N1.getOperand(1)) {
2398    SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2399                                 N0.getOperand(0).getValueType(),
2400                                 N0.getOperand(0), N1.getOperand(0));
2401    AddToWorkList(ORNode.getNode());
2402    return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
2403                       ORNode, N0.getOperand(1));
2404  }
2405
2406  // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2407  // Only perform this optimization after type legalization and before
2408  // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2409  // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2410  // we don't want to undo this promotion.
2411  // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2412  // on scalars.
2413  if ((N0.getOpcode() == ISD::BITCAST ||
2414       N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2415      Level == AfterLegalizeTypes) {
2416    SDValue In0 = N0.getOperand(0);
2417    SDValue In1 = N1.getOperand(0);
2418    EVT In0Ty = In0.getValueType();
2419    EVT In1Ty = In1.getValueType();
2420    SDLoc DL(N);
2421    // If both incoming values are integers, and the original types are the
2422    // same.
2423    if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2424      SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2425      SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
2426      AddToWorkList(Op.getNode());
2427      return BC;
2428    }
2429  }
2430
2431  // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2432  // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2433  // If both shuffles use the same mask, and both shuffle within a single
2434  // vector, then it is worthwhile to move the swizzle after the operation.
2435  // The type-legalizer generates this pattern when loading illegal
2436  // vector types from memory. In many cases this allows additional shuffle
2437  // optimizations.
2438  if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
2439      N0.getOperand(1).getOpcode() == ISD::UNDEF &&
2440      N1.getOperand(1).getOpcode() == ISD::UNDEF) {
2441    ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2442    ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2443
2444    assert(N0.getOperand(0).getValueType() == N1.getOperand(1).getValueType() &&
2445           "Inputs to shuffles are not the same type");
2446
2447    unsigned NumElts = VT.getVectorNumElements();
2448
2449    // Check that both shuffles use the same mask. The masks are known to be of
2450    // the same length because the result vector type is the same.
2451    bool SameMask = true;
2452    for (unsigned i = 0; i != NumElts; ++i) {
2453      int Idx0 = SVN0->getMaskElt(i);
2454      int Idx1 = SVN1->getMaskElt(i);
2455      if (Idx0 != Idx1) {
2456        SameMask = false;
2457        break;
2458      }
2459    }
2460
2461    if (SameMask) {
2462      SDValue Op = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2463                               N0.getOperand(0), N1.getOperand(0));
2464      AddToWorkList(Op.getNode());
2465      return DAG.getVectorShuffle(VT, SDLoc(N), Op,
2466                                  DAG.getUNDEF(VT), &SVN0->getMask()[0]);
2467    }
2468  }
2469
2470  return SDValue();
2471}
2472
2473SDValue DAGCombiner::visitAND(SDNode *N) {
2474  SDValue N0 = N->getOperand(0);
2475  SDValue N1 = N->getOperand(1);
2476  SDValue LL, LR, RL, RR, CC0, CC1;
2477  ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2478  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2479  EVT VT = N1.getValueType();
2480  unsigned BitWidth = VT.getScalarType().getSizeInBits();
2481
2482  // fold vector ops
2483  if (VT.isVector()) {
2484    SDValue FoldedVOp = SimplifyVBinOp(N);
2485    if (FoldedVOp.getNode()) return FoldedVOp;
2486
2487    // fold (and x, 0) -> 0, vector edition
2488    if (ISD::isBuildVectorAllZeros(N0.getNode()))
2489      return N0;
2490    if (ISD::isBuildVectorAllZeros(N1.getNode()))
2491      return N1;
2492
2493    // fold (and x, -1) -> x, vector edition
2494    if (ISD::isBuildVectorAllOnes(N0.getNode()))
2495      return N1;
2496    if (ISD::isBuildVectorAllOnes(N1.getNode()))
2497      return N0;
2498  }
2499
2500  // fold (and x, undef) -> 0
2501  if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2502    return DAG.getConstant(0, VT);
2503  // fold (and c1, c2) -> c1&c2
2504  if (N0C && N1C)
2505    return DAG.FoldConstantArithmetic(ISD::AND, VT, N0C, N1C);
2506  // canonicalize constant to RHS
2507  if (N0C && !N1C)
2508    return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
2509  // fold (and x, -1) -> x
2510  if (N1C && N1C->isAllOnesValue())
2511    return N0;
2512  // if (and x, c) is known to be zero, return 0
2513  if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
2514                                   APInt::getAllOnesValue(BitWidth)))
2515    return DAG.getConstant(0, VT);
2516  // reassociate and
2517  SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1);
2518  if (RAND.getNode() != 0)
2519    return RAND;
2520  // fold (and (or x, C), D) -> D if (C & D) == D
2521  if (N1C && N0.getOpcode() == ISD::OR)
2522    if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
2523      if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
2524        return N1;
2525  // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2526  if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2527    SDValue N0Op0 = N0.getOperand(0);
2528    APInt Mask = ~N1C->getAPIntValue();
2529    Mask = Mask.trunc(N0Op0.getValueSizeInBits());
2530    if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
2531      SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
2532                                 N0.getValueType(), N0Op0);
2533
2534      // Replace uses of the AND with uses of the Zero extend node.
2535      CombineTo(N, Zext);
2536
2537      // We actually want to replace all uses of the any_extend with the
2538      // zero_extend, to avoid duplicating things.  This will later cause this
2539      // AND to be folded.
2540      CombineTo(N0.getNode(), Zext);
2541      return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2542    }
2543  }
2544  // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
2545  // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2546  // already be zero by virtue of the width of the base type of the load.
2547  //
2548  // the 'X' node here can either be nothing or an extract_vector_elt to catch
2549  // more cases.
2550  if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
2551       N0.getOperand(0).getOpcode() == ISD::LOAD) ||
2552      N0.getOpcode() == ISD::LOAD) {
2553    LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
2554                                         N0 : N0.getOperand(0) );
2555
2556    // Get the constant (if applicable) the zero'th operand is being ANDed with.
2557    // This can be a pure constant or a vector splat, in which case we treat the
2558    // vector as a scalar and use the splat value.
2559    APInt Constant = APInt::getNullValue(1);
2560    if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2561      Constant = C->getAPIntValue();
2562    } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
2563      APInt SplatValue, SplatUndef;
2564      unsigned SplatBitSize;
2565      bool HasAnyUndefs;
2566      bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
2567                                             SplatBitSize, HasAnyUndefs);
2568      if (IsSplat) {
2569        // Undef bits can contribute to a possible optimisation if set, so
2570        // set them.
2571        SplatValue |= SplatUndef;
2572
2573        // The splat value may be something like "0x00FFFFFF", which means 0 for
2574        // the first vector value and FF for the rest, repeating. We need a mask
2575        // that will apply equally to all members of the vector, so AND all the
2576        // lanes of the constant together.
2577        EVT VT = Vector->getValueType(0);
2578        unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
2579
2580        // If the splat value has been compressed to a bitlength lower
2581        // than the size of the vector lane, we need to re-expand it to
2582        // the lane size.
2583        if (BitWidth > SplatBitSize)
2584          for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
2585               SplatBitSize < BitWidth;
2586               SplatBitSize = SplatBitSize * 2)
2587            SplatValue |= SplatValue.shl(SplatBitSize);
2588
2589        Constant = APInt::getAllOnesValue(BitWidth);
2590        for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
2591          Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
2592      }
2593    }
2594
2595    // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
2596    // actually legal and isn't going to get expanded, else this is a false
2597    // optimisation.
2598    bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
2599                                                    Load->getMemoryVT());
2600
2601    // Resize the constant to the same size as the original memory access before
2602    // extension. If it is still the AllOnesValue then this AND is completely
2603    // unneeded.
2604    Constant =
2605      Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
2606
2607    bool B;
2608    switch (Load->getExtensionType()) {
2609    default: B = false; break;
2610    case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
2611    case ISD::ZEXTLOAD:
2612    case ISD::NON_EXTLOAD: B = true; break;
2613    }
2614
2615    if (B && Constant.isAllOnesValue()) {
2616      // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
2617      // preserve semantics once we get rid of the AND.
2618      SDValue NewLoad(Load, 0);
2619      if (Load->getExtensionType() == ISD::EXTLOAD) {
2620        NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
2621                              Load->getValueType(0), SDLoc(Load),
2622                              Load->getChain(), Load->getBasePtr(),
2623                              Load->getOffset(), Load->getMemoryVT(),
2624                              Load->getMemOperand());
2625        // Replace uses of the EXTLOAD with the new ZEXTLOAD.
2626        if (Load->getNumValues() == 3) {
2627          // PRE/POST_INC loads have 3 values.
2628          SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
2629                           NewLoad.getValue(2) };
2630          CombineTo(Load, To, 3, true);
2631        } else {
2632          CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
2633        }
2634      }
2635
2636      // Fold the AND away, taking care not to fold to the old load node if we
2637      // replaced it.
2638      CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
2639
2640      return SDValue(N, 0); // Return N so it doesn't get rechecked!
2641    }
2642  }
2643  // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2644  if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2645    ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2646    ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2647
2648    if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2649        LL.getValueType().isInteger()) {
2650      // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2651      if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
2652        SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2653                                     LR.getValueType(), LL, RL);
2654        AddToWorkList(ORNode.getNode());
2655        return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2656      }
2657      // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2658      if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
2659        SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
2660                                      LR.getValueType(), LL, RL);
2661        AddToWorkList(ANDNode.getNode());
2662        return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
2663      }
2664      // fold (and (setgt X,  -1), (setgt Y,  -1)) -> (setgt (or X, Y), -1)
2665      if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
2666        SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2667                                     LR.getValueType(), LL, RL);
2668        AddToWorkList(ORNode.getNode());
2669        return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2670      }
2671    }
2672    // canonicalize equivalent to ll == rl
2673    if (LL == RR && LR == RL) {
2674      Op1 = ISD::getSetCCSwappedOperands(Op1);
2675      std::swap(RL, RR);
2676    }
2677    if (LL == RL && LR == RR) {
2678      bool isInteger = LL.getValueType().isInteger();
2679      ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2680      if (Result != ISD::SETCC_INVALID &&
2681          (!LegalOperations ||
2682           (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2683            TLI.isOperationLegal(ISD::SETCC,
2684                            getSetCCResultType(N0.getSimpleValueType())))))
2685        return DAG.getSetCC(SDLoc(N), N0.getValueType(),
2686                            LL, LR, Result);
2687    }
2688  }
2689
2690  // Simplify: (and (op x...), (op y...))  -> (op (and x, y))
2691  if (N0.getOpcode() == N1.getOpcode()) {
2692    SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
2693    if (Tmp.getNode()) return Tmp;
2694  }
2695
2696  // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
2697  // fold (and (sra)) -> (and (srl)) when possible.
2698  if (!VT.isVector() &&
2699      SimplifyDemandedBits(SDValue(N, 0)))
2700    return SDValue(N, 0);
2701
2702  // fold (zext_inreg (extload x)) -> (zextload x)
2703  if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
2704    LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2705    EVT MemVT = LN0->getMemoryVT();
2706    // If we zero all the possible extended bits, then we can turn this into
2707    // a zextload if we are running before legalize or the operation is legal.
2708    unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2709    if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2710                           BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2711        ((!LegalOperations && !LN0->isVolatile()) ||
2712         TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2713      SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2714                                       LN0->getChain(), LN0->getBasePtr(),
2715                                       LN0->getPointerInfo(), MemVT,
2716                                       LN0->isVolatile(), LN0->isNonTemporal(),
2717                                       LN0->getAlignment());
2718      AddToWorkList(N);
2719      CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2720      return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2721    }
2722  }
2723  // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
2724  if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
2725      N0.hasOneUse()) {
2726    LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2727    EVT MemVT = LN0->getMemoryVT();
2728    // If we zero all the possible extended bits, then we can turn this into
2729    // a zextload if we are running before legalize or the operation is legal.
2730    unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2731    if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2732                           BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2733        ((!LegalOperations && !LN0->isVolatile()) ||
2734         TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2735      SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2736                                       LN0->getChain(),
2737                                       LN0->getBasePtr(), LN0->getPointerInfo(),
2738                                       MemVT,
2739                                       LN0->isVolatile(), LN0->isNonTemporal(),
2740                                       LN0->getAlignment());
2741      AddToWorkList(N);
2742      CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2743      return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2744    }
2745  }
2746
2747  // fold (and (load x), 255) -> (zextload x, i8)
2748  // fold (and (extload x, i16), 255) -> (zextload x, i8)
2749  // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
2750  if (N1C && (N0.getOpcode() == ISD::LOAD ||
2751              (N0.getOpcode() == ISD::ANY_EXTEND &&
2752               N0.getOperand(0).getOpcode() == ISD::LOAD))) {
2753    bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
2754    LoadSDNode *LN0 = HasAnyExt
2755      ? cast<LoadSDNode>(N0.getOperand(0))
2756      : cast<LoadSDNode>(N0);
2757    if (LN0->getExtensionType() != ISD::SEXTLOAD &&
2758        LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
2759      uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
2760      if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
2761        EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
2762        EVT LoadedVT = LN0->getMemoryVT();
2763
2764        if (ExtVT == LoadedVT &&
2765            (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2766          EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2767
2768          SDValue NewLoad =
2769            DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
2770                           LN0->getChain(), LN0->getBasePtr(),
2771                           LN0->getPointerInfo(),
2772                           ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
2773                           LN0->getAlignment());
2774          AddToWorkList(N);
2775          CombineTo(LN0, NewLoad, NewLoad.getValue(1));
2776          return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2777        }
2778
2779        // Do not change the width of a volatile load.
2780        // Do not generate loads of non-round integer types since these can
2781        // be expensive (and would be wrong if the type is not byte sized).
2782        if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
2783            (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2784          EVT PtrType = LN0->getOperand(1).getValueType();
2785
2786          unsigned Alignment = LN0->getAlignment();
2787          SDValue NewPtr = LN0->getBasePtr();
2788
2789          // For big endian targets, we need to add an offset to the pointer
2790          // to load the correct bytes.  For little endian systems, we merely
2791          // need to read fewer bytes from the same pointer.
2792          if (TLI.isBigEndian()) {
2793            unsigned LVTStoreBytes = LoadedVT.getStoreSize();
2794            unsigned EVTStoreBytes = ExtVT.getStoreSize();
2795            unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
2796            NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0), PtrType,
2797                                 NewPtr, DAG.getConstant(PtrOff, PtrType));
2798            Alignment = MinAlign(Alignment, PtrOff);
2799          }
2800
2801          AddToWorkList(NewPtr.getNode());
2802
2803          EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2804          SDValue Load =
2805            DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
2806                           LN0->getChain(), NewPtr,
2807                           LN0->getPointerInfo(),
2808                           ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
2809                           Alignment);
2810          AddToWorkList(N);
2811          CombineTo(LN0, Load, Load.getValue(1));
2812          return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2813        }
2814      }
2815    }
2816  }
2817
2818  if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
2819      VT.getSizeInBits() <= 64) {
2820    if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2821      APInt ADDC = ADDI->getAPIntValue();
2822      if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2823        // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
2824        // immediate for an add, but it is legal if its top c2 bits are set,
2825        // transform the ADD so the immediate doesn't need to be materialized
2826        // in a register.
2827        if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
2828          APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
2829                                             SRLI->getZExtValue());
2830          if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
2831            ADDC |= Mask;
2832            if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2833              SDValue NewAdd =
2834                DAG.getNode(ISD::ADD, SDLoc(N0), VT,
2835                            N0.getOperand(0), DAG.getConstant(ADDC, VT));
2836              CombineTo(N0.getNode(), NewAdd);
2837              return SDValue(N, 0); // Return N so it doesn't get rechecked!
2838            }
2839          }
2840        }
2841      }
2842    }
2843  }
2844
2845  return SDValue();
2846}
2847
2848/// MatchBSwapHWord - Match (a >> 8) | (a << 8) as (bswap a) >> 16
2849///
2850SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
2851                                        bool DemandHighBits) {
2852  if (!LegalOperations)
2853    return SDValue();
2854
2855  EVT VT = N->getValueType(0);
2856  if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
2857    return SDValue();
2858  if (!TLI.isOperationLegal(ISD::BSWAP, VT))
2859    return SDValue();
2860
2861  // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
2862  bool LookPassAnd0 = false;
2863  bool LookPassAnd1 = false;
2864  if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
2865      std::swap(N0, N1);
2866  if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
2867      std::swap(N0, N1);
2868  if (N0.getOpcode() == ISD::AND) {
2869    if (!N0.getNode()->hasOneUse())
2870      return SDValue();
2871    ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2872    if (!N01C || N01C->getZExtValue() != 0xFF00)
2873      return SDValue();
2874    N0 = N0.getOperand(0);
2875    LookPassAnd0 = true;
2876  }
2877
2878  if (N1.getOpcode() == ISD::AND) {
2879    if (!N1.getNode()->hasOneUse())
2880      return SDValue();
2881    ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
2882    if (!N11C || N11C->getZExtValue() != 0xFF)
2883      return SDValue();
2884    N1 = N1.getOperand(0);
2885    LookPassAnd1 = true;
2886  }
2887
2888  if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
2889    std::swap(N0, N1);
2890  if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
2891    return SDValue();
2892  if (!N0.getNode()->hasOneUse() ||
2893      !N1.getNode()->hasOneUse())
2894    return SDValue();
2895
2896  ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2897  ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
2898  if (!N01C || !N11C)
2899    return SDValue();
2900  if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
2901    return SDValue();
2902
2903  // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
2904  SDValue N00 = N0->getOperand(0);
2905  if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
2906    if (!N00.getNode()->hasOneUse())
2907      return SDValue();
2908    ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
2909    if (!N001C || N001C->getZExtValue() != 0xFF)
2910      return SDValue();
2911    N00 = N00.getOperand(0);
2912    LookPassAnd0 = true;
2913  }
2914
2915  SDValue N10 = N1->getOperand(0);
2916  if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
2917    if (!N10.getNode()->hasOneUse())
2918      return SDValue();
2919    ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
2920    if (!N101C || N101C->getZExtValue() != 0xFF00)
2921      return SDValue();
2922    N10 = N10.getOperand(0);
2923    LookPassAnd1 = true;
2924  }
2925
2926  if (N00 != N10)
2927    return SDValue();
2928
2929  // Make sure everything beyond the low halfword is zero since the SRL 16
2930  // will clear the top bits.
2931  unsigned OpSizeInBits = VT.getSizeInBits();
2932  if (DemandHighBits && OpSizeInBits > 16 &&
2933      (!LookPassAnd0 || !LookPassAnd1) &&
2934      !DAG.MaskedValueIsZero(N10, APInt::getHighBitsSet(OpSizeInBits, 16)))
2935    return SDValue();
2936
2937  SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
2938  if (OpSizeInBits > 16)
2939    Res = DAG.getNode(ISD::SRL, SDLoc(N), VT, Res,
2940                      DAG.getConstant(OpSizeInBits-16, getShiftAmountTy(VT)));
2941  return Res;
2942}
2943
2944/// isBSwapHWordElement - Return true if the specified node is an element
2945/// that makes up a 32-bit packed halfword byteswap. i.e.
2946/// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
2947static bool isBSwapHWordElement(SDValue N, SmallVector<SDNode*,4> &Parts) {
2948  if (!N.getNode()->hasOneUse())
2949    return false;
2950
2951  unsigned Opc = N.getOpcode();
2952  if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
2953    return false;
2954
2955  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
2956  if (!N1C)
2957    return false;
2958
2959  unsigned Num;
2960  switch (N1C->getZExtValue()) {
2961  default:
2962    return false;
2963  case 0xFF:       Num = 0; break;
2964  case 0xFF00:     Num = 1; break;
2965  case 0xFF0000:   Num = 2; break;
2966  case 0xFF000000: Num = 3; break;
2967  }
2968
2969  // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
2970  SDValue N0 = N.getOperand(0);
2971  if (Opc == ISD::AND) {
2972    if (Num == 0 || Num == 2) {
2973      // (x >> 8) & 0xff
2974      // (x >> 8) & 0xff0000
2975      if (N0.getOpcode() != ISD::SRL)
2976        return false;
2977      ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2978      if (!C || C->getZExtValue() != 8)
2979        return false;
2980    } else {
2981      // (x << 8) & 0xff00
2982      // (x << 8) & 0xff000000
2983      if (N0.getOpcode() != ISD::SHL)
2984        return false;
2985      ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2986      if (!C || C->getZExtValue() != 8)
2987        return false;
2988    }
2989  } else if (Opc == ISD::SHL) {
2990    // (x & 0xff) << 8
2991    // (x & 0xff0000) << 8
2992    if (Num != 0 && Num != 2)
2993      return false;
2994    ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
2995    if (!C || C->getZExtValue() != 8)
2996      return false;
2997  } else { // Opc == ISD::SRL
2998    // (x & 0xff00) >> 8
2999    // (x & 0xff000000) >> 8
3000    if (Num != 1 && Num != 3)
3001      return false;
3002    ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3003    if (!C || C->getZExtValue() != 8)
3004      return false;
3005  }
3006
3007  if (Parts[Num])
3008    return false;
3009
3010  Parts[Num] = N0.getOperand(0).getNode();
3011  return true;
3012}
3013
3014/// MatchBSwapHWord - Match a 32-bit packed halfword bswap. That is
3015/// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
3016/// => (rotl (bswap x), 16)
3017SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3018  if (!LegalOperations)
3019    return SDValue();
3020
3021  EVT VT = N->getValueType(0);
3022  if (VT != MVT::i32)
3023    return SDValue();
3024  if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3025    return SDValue();
3026
3027  SmallVector<SDNode*,4> Parts(4, (SDNode*)0);
3028  // Look for either
3029  // (or (or (and), (and)), (or (and), (and)))
3030  // (or (or (or (and), (and)), (and)), (and))
3031  if (N0.getOpcode() != ISD::OR)
3032    return SDValue();
3033  SDValue N00 = N0.getOperand(0);
3034  SDValue N01 = N0.getOperand(1);
3035
3036  if (N1.getOpcode() == ISD::OR &&
3037      N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
3038    // (or (or (and), (and)), (or (and), (and)))
3039    SDValue N000 = N00.getOperand(0);
3040    if (!isBSwapHWordElement(N000, Parts))
3041      return SDValue();
3042
3043    SDValue N001 = N00.getOperand(1);
3044    if (!isBSwapHWordElement(N001, Parts))
3045      return SDValue();
3046    SDValue N010 = N01.getOperand(0);
3047    if (!isBSwapHWordElement(N010, Parts))
3048      return SDValue();
3049    SDValue N011 = N01.getOperand(1);
3050    if (!isBSwapHWordElement(N011, Parts))
3051      return SDValue();
3052  } else {
3053    // (or (or (or (and), (and)), (and)), (and))
3054    if (!isBSwapHWordElement(N1, Parts))
3055      return SDValue();
3056    if (!isBSwapHWordElement(N01, Parts))
3057      return SDValue();
3058    if (N00.getOpcode() != ISD::OR)
3059      return SDValue();
3060    SDValue N000 = N00.getOperand(0);
3061    if (!isBSwapHWordElement(N000, Parts))
3062      return SDValue();
3063    SDValue N001 = N00.getOperand(1);
3064    if (!isBSwapHWordElement(N001, Parts))
3065      return SDValue();
3066  }
3067
3068  // Make sure the parts are all coming from the same node.
3069  if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3070    return SDValue();
3071
3072  SDValue BSwap = DAG.getNode(ISD::BSWAP, SDLoc(N), VT,
3073                              SDValue(Parts[0],0));
3074
3075  // Result of the bswap should be rotated by 16. If it's not legal, than
3076  // do  (x << 16) | (x >> 16).
3077  SDValue ShAmt = DAG.getConstant(16, getShiftAmountTy(VT));
3078  if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3079    return DAG.getNode(ISD::ROTL, SDLoc(N), VT, BSwap, ShAmt);
3080  if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3081    return DAG.getNode(ISD::ROTR, SDLoc(N), VT, BSwap, ShAmt);
3082  return DAG.getNode(ISD::OR, SDLoc(N), VT,
3083                     DAG.getNode(ISD::SHL, SDLoc(N), VT, BSwap, ShAmt),
3084                     DAG.getNode(ISD::SRL, SDLoc(N), VT, BSwap, ShAmt));
3085}
3086
3087SDValue DAGCombiner::visitOR(SDNode *N) {
3088  SDValue N0 = N->getOperand(0);
3089  SDValue N1 = N->getOperand(1);
3090  SDValue LL, LR, RL, RR, CC0, CC1;
3091  ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3092  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3093  EVT VT = N1.getValueType();
3094
3095  // fold vector ops
3096  if (VT.isVector()) {
3097    SDValue FoldedVOp = SimplifyVBinOp(N);
3098    if (FoldedVOp.getNode()) return FoldedVOp;
3099
3100    // fold (or x, 0) -> x, vector edition
3101    if (ISD::isBuildVectorAllZeros(N0.getNode()))
3102      return N1;
3103    if (ISD::isBuildVectorAllZeros(N1.getNode()))
3104      return N0;
3105
3106    // fold (or x, -1) -> -1, vector edition
3107    if (ISD::isBuildVectorAllOnes(N0.getNode()))
3108      return N0;
3109    if (ISD::isBuildVectorAllOnes(N1.getNode()))
3110      return N1;
3111  }
3112
3113  // fold (or x, undef) -> -1
3114  if (!LegalOperations &&
3115      (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
3116    EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3117    return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT);
3118  }
3119  // fold (or c1, c2) -> c1|c2
3120  if (N0C && N1C)
3121    return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C);
3122  // canonicalize constant to RHS
3123  if (N0C && !N1C)
3124    return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
3125  // fold (or x, 0) -> x
3126  if (N1C && N1C->isNullValue())
3127    return N0;
3128  // fold (or x, -1) -> -1
3129  if (N1C && N1C->isAllOnesValue())
3130    return N1;
3131  // fold (or x, c) -> c iff (x & ~c) == 0
3132  if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3133    return N1;
3134
3135  // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3136  SDValue BSwap = MatchBSwapHWord(N, N0, N1);
3137  if (BSwap.getNode() != 0)
3138    return BSwap;
3139  BSwap = MatchBSwapHWordLow(N, N0, N1);
3140  if (BSwap.getNode() != 0)
3141    return BSwap;
3142
3143  // reassociate or
3144  SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1);
3145  if (ROR.getNode() != 0)
3146    return ROR;
3147  // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3148  // iff (c1 & c2) == 0.
3149  if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3150             isa<ConstantSDNode>(N0.getOperand(1))) {
3151    ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3152    if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0)
3153      return DAG.getNode(ISD::AND, SDLoc(N), VT,
3154                         DAG.getNode(ISD::OR, SDLoc(N0), VT,
3155                                     N0.getOperand(0), N1),
3156                         DAG.FoldConstantArithmetic(ISD::OR, VT, N1C, C1));
3157  }
3158  // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3159  if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3160    ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3161    ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3162
3163    if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
3164        LL.getValueType().isInteger()) {
3165      // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3166      // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3167      if (cast<ConstantSDNode>(LR)->isNullValue() &&
3168          (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3169        SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3170                                     LR.getValueType(), LL, RL);
3171        AddToWorkList(ORNode.getNode());
3172        return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
3173      }
3174      // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3175      // fold (or (setgt X, -1), (setgt Y  -1)) -> (setgt (and X, Y), -1)
3176      if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
3177          (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3178        SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3179                                      LR.getValueType(), LL, RL);
3180        AddToWorkList(ANDNode.getNode());
3181        return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
3182      }
3183    }
3184    // canonicalize equivalent to ll == rl
3185    if (LL == RR && LR == RL) {
3186      Op1 = ISD::getSetCCSwappedOperands(Op1);
3187      std::swap(RL, RR);
3188    }
3189    if (LL == RL && LR == RR) {
3190      bool isInteger = LL.getValueType().isInteger();
3191      ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3192      if (Result != ISD::SETCC_INVALID &&
3193          (!LegalOperations ||
3194           (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3195            TLI.isOperationLegal(ISD::SETCC,
3196              getSetCCResultType(N0.getValueType())))))
3197        return DAG.getSetCC(SDLoc(N), N0.getValueType(),
3198                            LL, LR, Result);
3199    }
3200  }
3201
3202  // Simplify: (or (op x...), (op y...))  -> (op (or x, y))
3203  if (N0.getOpcode() == N1.getOpcode()) {
3204    SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3205    if (Tmp.getNode()) return Tmp;
3206  }
3207
3208  // (or (and X, C1), (and Y, C2))  -> (and (or X, Y), C3) if possible.
3209  if (N0.getOpcode() == ISD::AND &&
3210      N1.getOpcode() == ISD::AND &&
3211      N0.getOperand(1).getOpcode() == ISD::Constant &&
3212      N1.getOperand(1).getOpcode() == ISD::Constant &&
3213      // Don't increase # computations.
3214      (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3215    // We can only do this xform if we know that bits from X that are set in C2
3216    // but not in C1 are already zero.  Likewise for Y.
3217    const APInt &LHSMask =
3218      cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3219    const APInt &RHSMask =
3220      cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
3221
3222    if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3223        DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3224      SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3225                              N0.getOperand(0), N1.getOperand(0));
3226      return DAG.getNode(ISD::AND, SDLoc(N), VT, X,
3227                         DAG.getConstant(LHSMask | RHSMask, VT));
3228    }
3229  }
3230
3231  // See if this is some rotate idiom.
3232  if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
3233    return SDValue(Rot, 0);
3234
3235  // Simplify the operands using demanded-bits information.
3236  if (!VT.isVector() &&
3237      SimplifyDemandedBits(SDValue(N, 0)))
3238    return SDValue(N, 0);
3239
3240  return SDValue();
3241}
3242
3243/// MatchRotateHalf - Match "(X shl/srl V1) & V2" where V2 may not be present.
3244static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3245  if (Op.getOpcode() == ISD::AND) {
3246    if (isa<ConstantSDNode>(Op.getOperand(1))) {
3247      Mask = Op.getOperand(1);
3248      Op = Op.getOperand(0);
3249    } else {
3250      return false;
3251    }
3252  }
3253
3254  if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3255    Shift = Op;
3256    return true;
3257  }
3258
3259  return false;
3260}
3261
3262// MatchRotate - Handle an 'or' of two operands.  If this is one of the many
3263// idioms for rotate, and if the target supports rotation instructions, generate
3264// a rot[lr].
3265SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
3266  // Must be a legal type.  Expanded 'n promoted things won't work with rotates.
3267  EVT VT = LHS.getValueType();
3268  if (!TLI.isTypeLegal(VT)) return 0;
3269
3270  // The target must have at least one rotate flavor.
3271  bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3272  bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
3273  if (!HasROTL && !HasROTR) return 0;
3274
3275  // Match "(X shl/srl V1) & V2" where V2 may not be present.
3276  SDValue LHSShift;   // The shift.
3277  SDValue LHSMask;    // AND value if any.
3278  if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
3279    return 0; // Not part of a rotate.
3280
3281  SDValue RHSShift;   // The shift.
3282  SDValue RHSMask;    // AND value if any.
3283  if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
3284    return 0; // Not part of a rotate.
3285
3286  if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
3287    return 0;   // Not shifting the same value.
3288
3289  if (LHSShift.getOpcode() == RHSShift.getOpcode())
3290    return 0;   // Shifts must disagree.
3291
3292  // Canonicalize shl to left side in a shl/srl pair.
3293  if (RHSShift.getOpcode() == ISD::SHL) {
3294    std::swap(LHS, RHS);
3295    std::swap(LHSShift, RHSShift);
3296    std::swap(LHSMask , RHSMask );
3297  }
3298
3299  unsigned OpSizeInBits = VT.getSizeInBits();
3300  SDValue LHSShiftArg = LHSShift.getOperand(0);
3301  SDValue LHSShiftAmt = LHSShift.getOperand(1);
3302  SDValue RHSShiftAmt = RHSShift.getOperand(1);
3303
3304  // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3305  // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
3306  if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3307      RHSShiftAmt.getOpcode() == ISD::Constant) {
3308    uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3309    uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
3310    if ((LShVal + RShVal) != OpSizeInBits)
3311      return 0;
3312
3313    SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3314                              LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
3315
3316    // If there is an AND of either shifted operand, apply it to the result.
3317    if (LHSMask.getNode() || RHSMask.getNode()) {
3318      APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
3319
3320      if (LHSMask.getNode()) {
3321        APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3322        Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
3323      }
3324      if (RHSMask.getNode()) {
3325        APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3326        Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
3327      }
3328
3329      Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, VT));
3330    }
3331
3332    return Rot.getNode();
3333  }
3334
3335  // If there is a mask here, and we have a variable shift, we can't be sure
3336  // that we're masking out the right stuff.
3337  if (LHSMask.getNode() || RHSMask.getNode())
3338    return 0;
3339
3340  // fold (or (shl x, y), (srl x, (sub 32, y))) -> (rotl x, y)
3341  // fold (or (shl x, y), (srl x, (sub 32, y))) -> (rotr x, (sub 32, y))
3342  if (RHSShiftAmt.getOpcode() == ISD::SUB &&
3343      LHSShiftAmt == RHSShiftAmt.getOperand(1)) {
3344    if (ConstantSDNode *SUBC =
3345          dyn_cast<ConstantSDNode>(RHSShiftAmt.getOperand(0))) {
3346      if (SUBC->getAPIntValue() == OpSizeInBits) {
3347        return DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT, LHSShiftArg,
3348                           HasROTL ? LHSShiftAmt : RHSShiftAmt).getNode();
3349      }
3350    }
3351  }
3352
3353  // fold (or (shl x, (sub 32, y)), (srl x, r)) -> (rotr x, y)
3354  // fold (or (shl x, (sub 32, y)), (srl x, r)) -> (rotl x, (sub 32, y))
3355  if (LHSShiftAmt.getOpcode() == ISD::SUB &&
3356      RHSShiftAmt == LHSShiftAmt.getOperand(1)) {
3357    if (ConstantSDNode *SUBC =
3358          dyn_cast<ConstantSDNode>(LHSShiftAmt.getOperand(0))) {
3359      if (SUBC->getAPIntValue() == OpSizeInBits) {
3360        return DAG.getNode(HasROTR ? ISD::ROTR : ISD::ROTL, DL, VT, LHSShiftArg,
3361                           HasROTR ? RHSShiftAmt : LHSShiftAmt).getNode();
3362      }
3363    }
3364  }
3365
3366  // Look for sign/zext/any-extended or truncate cases:
3367  if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3368       LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3369       LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3370       LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3371      (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3372       RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3373       RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3374       RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
3375    SDValue LExtOp0 = LHSShiftAmt.getOperand(0);
3376    SDValue RExtOp0 = RHSShiftAmt.getOperand(0);
3377    if (RExtOp0.getOpcode() == ISD::SUB &&
3378        RExtOp0.getOperand(1) == LExtOp0) {
3379      // fold (or (shl x, (*ext y)), (srl x, (*ext (sub 32, y)))) ->
3380      //   (rotl x, y)
3381      // fold (or (shl x, (*ext y)), (srl x, (*ext (sub 32, y)))) ->
3382      //   (rotr x, (sub 32, y))
3383      if (ConstantSDNode *SUBC =
3384            dyn_cast<ConstantSDNode>(RExtOp0.getOperand(0))) {
3385        if (SUBC->getAPIntValue() == OpSizeInBits) {
3386          return DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3387                             LHSShiftArg,
3388                             HasROTL ? LHSShiftAmt : RHSShiftAmt).getNode();
3389        }
3390      }
3391    } else if (LExtOp0.getOpcode() == ISD::SUB &&
3392               RExtOp0 == LExtOp0.getOperand(1)) {
3393      // fold (or (shl x, (*ext (sub 32, y))), (srl x, (*ext y))) ->
3394      //   (rotr x, y)
3395      // fold (or (shl x, (*ext (sub 32, y))), (srl x, (*ext y))) ->
3396      //   (rotl x, (sub 32, y))
3397      if (ConstantSDNode *SUBC =
3398            dyn_cast<ConstantSDNode>(LExtOp0.getOperand(0))) {
3399        if (SUBC->getAPIntValue() == OpSizeInBits) {
3400          return DAG.getNode(HasROTR ? ISD::ROTR : ISD::ROTL, DL, VT,
3401                             LHSShiftArg,
3402                             HasROTR ? RHSShiftAmt : LHSShiftAmt).getNode();
3403        }
3404      }
3405    }
3406  }
3407
3408  return 0;
3409}
3410
3411SDValue DAGCombiner::visitXOR(SDNode *N) {
3412  SDValue N0 = N->getOperand(0);
3413  SDValue N1 = N->getOperand(1);
3414  SDValue LHS, RHS, CC;
3415  ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3416  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3417  EVT VT = N0.getValueType();
3418
3419  // fold vector ops
3420  if (VT.isVector()) {
3421    SDValue FoldedVOp = SimplifyVBinOp(N);
3422    if (FoldedVOp.getNode()) return FoldedVOp;
3423
3424    // fold (xor x, 0) -> x, vector edition
3425    if (ISD::isBuildVectorAllZeros(N0.getNode()))
3426      return N1;
3427    if (ISD::isBuildVectorAllZeros(N1.getNode()))
3428      return N0;
3429  }
3430
3431  // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
3432  if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
3433    return DAG.getConstant(0, VT);
3434  // fold (xor x, undef) -> undef
3435  if (N0.getOpcode() == ISD::UNDEF)
3436    return N0;
3437  if (N1.getOpcode() == ISD::UNDEF)
3438    return N1;
3439  // fold (xor c1, c2) -> c1^c2
3440  if (N0C && N1C)
3441    return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C);
3442  // canonicalize constant to RHS
3443  if (N0C && !N1C)
3444    return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
3445  // fold (xor x, 0) -> x
3446  if (N1C && N1C->isNullValue())
3447    return N0;
3448  // reassociate xor
3449  SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1);
3450  if (RXOR.getNode() != 0)
3451    return RXOR;
3452
3453  // fold !(x cc y) -> (x !cc y)
3454  if (N1C && N1C->getAPIntValue() == 1 && isSetCCEquivalent(N0, LHS, RHS, CC)) {
3455    bool isInt = LHS.getValueType().isInteger();
3456    ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
3457                                               isInt);
3458
3459    if (!LegalOperations ||
3460        TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
3461      switch (N0.getOpcode()) {
3462      default:
3463        llvm_unreachable("Unhandled SetCC Equivalent!");
3464      case ISD::SETCC:
3465        return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
3466      case ISD::SELECT_CC:
3467        return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
3468                               N0.getOperand(3), NotCC);
3469      }
3470    }
3471  }
3472
3473  // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
3474  if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
3475      N0.getNode()->hasOneUse() &&
3476      isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
3477    SDValue V = N0.getOperand(0);
3478    V = DAG.getNode(ISD::XOR, SDLoc(N0), V.getValueType(), V,
3479                    DAG.getConstant(1, V.getValueType()));
3480    AddToWorkList(V.getNode());
3481    return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
3482  }
3483
3484  // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
3485  if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
3486      (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3487    SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3488    if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
3489      unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3490      LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3491      RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3492      AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
3493      return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3494    }
3495  }
3496  // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
3497  if (N1C && N1C->isAllOnesValue() &&
3498      (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3499    SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3500    if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
3501      unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3502      LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3503      RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3504      AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
3505      return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3506    }
3507  }
3508  // fold (xor (and x, y), y) -> (and (not x), y)
3509  if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3510      N0->getOperand(1) == N1) {
3511    SDValue X = N0->getOperand(0);
3512    SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
3513    AddToWorkList(NotX.getNode());
3514    return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
3515  }
3516  // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
3517  if (N1C && N0.getOpcode() == ISD::XOR) {
3518    ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
3519    ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3520    if (N00C)
3521      return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(1),
3522                         DAG.getConstant(N1C->getAPIntValue() ^
3523                                         N00C->getAPIntValue(), VT));
3524    if (N01C)
3525      return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(0),
3526                         DAG.getConstant(N1C->getAPIntValue() ^
3527                                         N01C->getAPIntValue(), VT));
3528  }
3529  // fold (xor x, x) -> 0
3530  if (N0 == N1)
3531    return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations);
3532
3533  // Simplify: xor (op x...), (op y...)  -> (op (xor x, y))
3534  if (N0.getOpcode() == N1.getOpcode()) {
3535    SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3536    if (Tmp.getNode()) return Tmp;
3537  }
3538
3539  // Simplify the expression using non-local knowledge.
3540  if (!VT.isVector() &&
3541      SimplifyDemandedBits(SDValue(N, 0)))
3542    return SDValue(N, 0);
3543
3544  return SDValue();
3545}
3546
3547/// visitShiftByConstant - Handle transforms common to the three shifts, when
3548/// the shift amount is a constant.
3549SDValue DAGCombiner::visitShiftByConstant(SDNode *N, unsigned Amt) {
3550  SDNode *LHS = N->getOperand(0).getNode();
3551  if (!LHS->hasOneUse()) return SDValue();
3552
3553  // We want to pull some binops through shifts, so that we have (and (shift))
3554  // instead of (shift (and)), likewise for add, or, xor, etc.  This sort of
3555  // thing happens with address calculations, so it's important to canonicalize
3556  // it.
3557  bool HighBitSet = false;  // Can we transform this if the high bit is set?
3558
3559  switch (LHS->getOpcode()) {
3560  default: return SDValue();
3561  case ISD::OR:
3562  case ISD::XOR:
3563    HighBitSet = false; // We can only transform sra if the high bit is clear.
3564    break;
3565  case ISD::AND:
3566    HighBitSet = true;  // We can only transform sra if the high bit is set.
3567    break;
3568  case ISD::ADD:
3569    if (N->getOpcode() != ISD::SHL)
3570      return SDValue(); // only shl(add) not sr[al](add).
3571    HighBitSet = false; // We can only transform sra if the high bit is clear.
3572    break;
3573  }
3574
3575  // We require the RHS of the binop to be a constant as well.
3576  ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
3577  if (!BinOpCst) return SDValue();
3578
3579  // FIXME: disable this unless the input to the binop is a shift by a constant.
3580  // If it is not a shift, it pessimizes some common cases like:
3581  //
3582  //    void foo(int *X, int i) { X[i & 1235] = 1; }
3583  //    int bar(int *X, int i) { return X[i & 255]; }
3584  SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
3585  if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
3586       BinOpLHSVal->getOpcode() != ISD::SRA &&
3587       BinOpLHSVal->getOpcode() != ISD::SRL) ||
3588      !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
3589    return SDValue();
3590
3591  EVT VT = N->getValueType(0);
3592
3593  // If this is a signed shift right, and the high bit is modified by the
3594  // logical operation, do not perform the transformation. The highBitSet
3595  // boolean indicates the value of the high bit of the constant which would
3596  // cause it to be modified for this operation.
3597  if (N->getOpcode() == ISD::SRA) {
3598    bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
3599    if (BinOpRHSSignSet != HighBitSet)
3600      return SDValue();
3601  }
3602
3603  // Fold the constants, shifting the binop RHS by the shift amount.
3604  SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
3605                               N->getValueType(0),
3606                               LHS->getOperand(1), N->getOperand(1));
3607
3608  // Create the new shift.
3609  SDValue NewShift = DAG.getNode(N->getOpcode(),
3610                                 SDLoc(LHS->getOperand(0)),
3611                                 VT, LHS->getOperand(0), N->getOperand(1));
3612
3613  // Create the new binop.
3614  return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
3615}
3616
3617SDValue DAGCombiner::visitSHL(SDNode *N) {
3618  SDValue N0 = N->getOperand(0);
3619  SDValue N1 = N->getOperand(1);
3620  ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3621  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3622  EVT VT = N0.getValueType();
3623  unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
3624
3625  // fold (shl c1, c2) -> c1<<c2
3626  if (N0C && N1C)
3627    return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C);
3628  // fold (shl 0, x) -> 0
3629  if (N0C && N0C->isNullValue())
3630    return N0;
3631  // fold (shl x, c >= size(x)) -> undef
3632  if (N1C && N1C->getZExtValue() >= OpSizeInBits)
3633    return DAG.getUNDEF(VT);
3634  // fold (shl x, 0) -> x
3635  if (N1C && N1C->isNullValue())
3636    return N0;
3637  // fold (shl undef, x) -> 0
3638  if (N0.getOpcode() == ISD::UNDEF)
3639    return DAG.getConstant(0, VT);
3640  // if (shl x, c) is known to be zero, return 0
3641  if (DAG.MaskedValueIsZero(SDValue(N, 0),
3642                            APInt::getAllOnesValue(OpSizeInBits)))
3643    return DAG.getConstant(0, VT);
3644  // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
3645  if (N1.getOpcode() == ISD::TRUNCATE &&
3646      N1.getOperand(0).getOpcode() == ISD::AND &&
3647      N1.hasOneUse() && N1.getOperand(0).hasOneUse()) {
3648    SDValue N101 = N1.getOperand(0).getOperand(1);
3649    if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) {
3650      EVT TruncVT = N1.getValueType();
3651      SDValue N100 = N1.getOperand(0).getOperand(0);
3652      APInt TruncC = N101C->getAPIntValue();
3653      TruncC = TruncC.trunc(TruncVT.getSizeInBits());
3654      return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
3655                         DAG.getNode(ISD::AND, SDLoc(N), TruncVT,
3656                                     DAG.getNode(ISD::TRUNCATE,
3657                                                 SDLoc(N),
3658                                                 TruncVT, N100),
3659                                     DAG.getConstant(TruncC, TruncVT)));
3660    }
3661  }
3662
3663  if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
3664    return SDValue(N, 0);
3665
3666  // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
3667  if (N1C && N0.getOpcode() == ISD::SHL &&
3668      N0.getOperand(1).getOpcode() == ISD::Constant) {
3669    uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
3670    uint64_t c2 = N1C->getZExtValue();
3671    if (c1 + c2 >= OpSizeInBits)
3672      return DAG.getConstant(0, VT);
3673    return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
3674                       DAG.getConstant(c1 + c2, N1.getValueType()));
3675  }
3676
3677  // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
3678  // For this to be valid, the second form must not preserve any of the bits
3679  // that are shifted out by the inner shift in the first form.  This means
3680  // the outer shift size must be >= the number of bits added by the ext.
3681  // As a corollary, we don't care what kind of ext it is.
3682  if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
3683              N0.getOpcode() == ISD::ANY_EXTEND ||
3684              N0.getOpcode() == ISD::SIGN_EXTEND) &&
3685      N0.getOperand(0).getOpcode() == ISD::SHL &&
3686      isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
3687    uint64_t c1 =
3688      cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
3689    uint64_t c2 = N1C->getZExtValue();
3690    EVT InnerShiftVT = N0.getOperand(0).getValueType();
3691    uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
3692    if (c2 >= OpSizeInBits - InnerShiftSize) {
3693      if (c1 + c2 >= OpSizeInBits)
3694        return DAG.getConstant(0, VT);
3695      return DAG.getNode(ISD::SHL, SDLoc(N0), VT,
3696                         DAG.getNode(N0.getOpcode(), SDLoc(N0), VT,
3697                                     N0.getOperand(0)->getOperand(0)),
3698                         DAG.getConstant(c1 + c2, N1.getValueType()));
3699    }
3700  }
3701
3702  // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
3703  //                               (and (srl x, (sub c1, c2), MASK)
3704  // Only fold this if the inner shift has no other uses -- if it does, folding
3705  // this will increase the total number of instructions.
3706  if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse() &&
3707      N0.getOperand(1).getOpcode() == ISD::Constant) {
3708    uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
3709    if (c1 < VT.getSizeInBits()) {
3710      uint64_t c2 = N1C->getZExtValue();
3711      APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
3712                                         VT.getSizeInBits() - c1);
3713      SDValue Shift;
3714      if (c2 > c1) {
3715        Mask = Mask.shl(c2-c1);
3716        Shift = DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
3717                            DAG.getConstant(c2-c1, N1.getValueType()));
3718      } else {
3719        Mask = Mask.lshr(c1-c2);
3720        Shift = DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
3721                            DAG.getConstant(c1-c2, N1.getValueType()));
3722      }
3723      return DAG.getNode(ISD::AND, SDLoc(N0), VT, Shift,
3724                         DAG.getConstant(Mask, VT));
3725    }
3726  }
3727  // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
3728  if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
3729    SDValue HiBitsMask =
3730      DAG.getConstant(APInt::getHighBitsSet(VT.getSizeInBits(),
3731                                            VT.getSizeInBits() -
3732                                              N1C->getZExtValue()),
3733                      VT);
3734    return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
3735                       HiBitsMask);
3736  }
3737
3738  if (N1C) {
3739    SDValue NewSHL = visitShiftByConstant(N, N1C->getZExtValue());
3740    if (NewSHL.getNode())
3741      return NewSHL;
3742  }
3743
3744  return SDValue();
3745}
3746
3747SDValue DAGCombiner::visitSRA(SDNode *N) {
3748  SDValue N0 = N->getOperand(0);
3749  SDValue N1 = N->getOperand(1);
3750  ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3751  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3752  EVT VT = N0.getValueType();
3753  unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
3754
3755  // fold (sra c1, c2) -> (sra c1, c2)
3756  if (N0C && N1C)
3757    return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C);
3758  // fold (sra 0, x) -> 0
3759  if (N0C && N0C->isNullValue())
3760    return N0;
3761  // fold (sra -1, x) -> -1
3762  if (N0C && N0C->isAllOnesValue())
3763    return N0;
3764  // fold (sra x, (setge c, size(x))) -> undef
3765  if (N1C && N1C->getZExtValue() >= OpSizeInBits)
3766    return DAG.getUNDEF(VT);
3767  // fold (sra x, 0) -> x
3768  if (N1C && N1C->isNullValue())
3769    return N0;
3770  // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
3771  // sext_inreg.
3772  if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
3773    unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
3774    EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
3775    if (VT.isVector())
3776      ExtVT = EVT::getVectorVT(*DAG.getContext(),
3777                               ExtVT, VT.getVectorNumElements());
3778    if ((!LegalOperations ||
3779         TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
3780      return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
3781                         N0.getOperand(0), DAG.getValueType(ExtVT));
3782  }
3783
3784  // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
3785  if (N1C && N0.getOpcode() == ISD::SRA) {
3786    if (ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
3787      unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
3788      if (Sum >= OpSizeInBits) Sum = OpSizeInBits-1;
3789      return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0.getOperand(0),
3790                         DAG.getConstant(Sum, N1C->getValueType(0)));
3791    }
3792  }
3793
3794  // fold (sra (shl X, m), (sub result_size, n))
3795  // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
3796  // result_size - n != m.
3797  // If truncate is free for the target sext(shl) is likely to result in better
3798  // code.
3799  if (N0.getOpcode() == ISD::SHL) {
3800    // Get the two constanst of the shifts, CN0 = m, CN = n.
3801    const ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3802    if (N01C && N1C) {
3803      // Determine what the truncate's result bitsize and type would be.
3804      EVT TruncVT =
3805        EVT::getIntegerVT(*DAG.getContext(),
3806                          OpSizeInBits - N1C->getZExtValue());
3807      // Determine the residual right-shift amount.
3808      signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
3809
3810      // If the shift is not a no-op (in which case this should be just a sign
3811      // extend already), the truncated to type is legal, sign_extend is legal
3812      // on that type, and the truncate to that type is both legal and free,
3813      // perform the transform.
3814      if ((ShiftAmt > 0) &&
3815          TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
3816          TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
3817          TLI.isTruncateFree(VT, TruncVT)) {
3818
3819          SDValue Amt = DAG.getConstant(ShiftAmt,
3820              getShiftAmountTy(N0.getOperand(0).getValueType()));
3821          SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0), VT,
3822                                      N0.getOperand(0), Amt);
3823          SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), TruncVT,
3824                                      Shift);
3825          return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N),
3826                             N->getValueType(0), Trunc);
3827      }
3828    }
3829  }
3830
3831  // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
3832  if (N1.getOpcode() == ISD::TRUNCATE &&
3833      N1.getOperand(0).getOpcode() == ISD::AND &&
3834      N1.hasOneUse() && N1.getOperand(0).hasOneUse()) {
3835    SDValue N101 = N1.getOperand(0).getOperand(1);
3836    if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) {
3837      EVT TruncVT = N1.getValueType();
3838      SDValue N100 = N1.getOperand(0).getOperand(0);
3839      APInt TruncC = N101C->getAPIntValue();
3840      TruncC = TruncC.trunc(TruncVT.getScalarType().getSizeInBits());
3841      return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0,
3842                         DAG.getNode(ISD::AND, SDLoc(N),
3843                                     TruncVT,
3844                                     DAG.getNode(ISD::TRUNCATE,
3845                                                 SDLoc(N),
3846                                                 TruncVT, N100),
3847                                     DAG.getConstant(TruncC, TruncVT)));
3848    }
3849  }
3850
3851  // fold (sra (trunc (sr x, c1)), c2) -> (trunc (sra x, c1+c2))
3852  //      if c1 is equal to the number of bits the trunc removes
3853  if (N0.getOpcode() == ISD::TRUNCATE &&
3854      (N0.getOperand(0).getOpcode() == ISD::SRL ||
3855       N0.getOperand(0).getOpcode() == ISD::SRA) &&
3856      N0.getOperand(0).hasOneUse() &&
3857      N0.getOperand(0).getOperand(1).hasOneUse() &&
3858      N1C && isa<ConstantSDNode>(N0.getOperand(0).getOperand(1))) {
3859    EVT LargeVT = N0.getOperand(0).getValueType();
3860    ConstantSDNode *LargeShiftAmt =
3861      cast<ConstantSDNode>(N0.getOperand(0).getOperand(1));
3862
3863    if (LargeVT.getScalarType().getSizeInBits() - OpSizeInBits ==
3864        LargeShiftAmt->getZExtValue()) {
3865      SDValue Amt =
3866        DAG.getConstant(LargeShiftAmt->getZExtValue() + N1C->getZExtValue(),
3867              getShiftAmountTy(N0.getOperand(0).getOperand(0).getValueType()));
3868      SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), LargeVT,
3869                                N0.getOperand(0).getOperand(0), Amt);
3870      return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, SRA);
3871    }
3872  }
3873
3874  // Simplify, based on bits shifted out of the LHS.
3875  if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
3876    return SDValue(N, 0);
3877
3878
3879  // If the sign bit is known to be zero, switch this to a SRL.
3880  if (DAG.SignBitIsZero(N0))
3881    return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
3882
3883  if (N1C) {
3884    SDValue NewSRA = visitShiftByConstant(N, N1C->getZExtValue());
3885    if (NewSRA.getNode())
3886      return NewSRA;
3887  }
3888
3889  return SDValue();
3890}
3891
3892SDValue DAGCombiner::visitSRL(SDNode *N) {
3893  SDValue N0 = N->getOperand(0);
3894  SDValue N1 = N->getOperand(1);
3895  ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3896  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3897  EVT VT = N0.getValueType();
3898  unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
3899
3900  // fold (srl c1, c2) -> c1 >>u c2
3901  if (N0C && N1C)
3902    return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C);
3903  // fold (srl 0, x) -> 0
3904  if (N0C && N0C->isNullValue())
3905    return N0;
3906  // fold (srl x, c >= size(x)) -> undef
3907  if (N1C && N1C->getZExtValue() >= OpSizeInBits)
3908    return DAG.getUNDEF(VT);
3909  // fold (srl x, 0) -> x
3910  if (N1C && N1C->isNullValue())
3911    return N0;
3912  // if (srl x, c) is known to be zero, return 0
3913  if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
3914                                   APInt::getAllOnesValue(OpSizeInBits)))
3915    return DAG.getConstant(0, VT);
3916
3917  // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
3918  if (N1C && N0.getOpcode() == ISD::SRL &&
3919      N0.getOperand(1).getOpcode() == ISD::Constant) {
3920    uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
3921    uint64_t c2 = N1C->getZExtValue();
3922    if (c1 + c2 >= OpSizeInBits)
3923      return DAG.getConstant(0, VT);
3924    return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
3925                       DAG.getConstant(c1 + c2, N1.getValueType()));
3926  }
3927
3928  // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
3929  if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
3930      N0.getOperand(0).getOpcode() == ISD::SRL &&
3931      isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
3932    uint64_t c1 =
3933      cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
3934    uint64_t c2 = N1C->getZExtValue();
3935    EVT InnerShiftVT = N0.getOperand(0).getValueType();
3936    EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
3937    uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
3938    // This is only valid if the OpSizeInBits + c1 = size of inner shift.
3939    if (c1 + OpSizeInBits == InnerShiftSize) {
3940      if (c1 + c2 >= InnerShiftSize)
3941        return DAG.getConstant(0, VT);
3942      return DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT,
3943                         DAG.getNode(ISD::SRL, SDLoc(N0), InnerShiftVT,
3944                                     N0.getOperand(0)->getOperand(0),
3945                                     DAG.getConstant(c1 + c2, ShiftCountVT)));
3946    }
3947  }
3948
3949  // fold (srl (shl x, c), c) -> (and x, cst2)
3950  if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1 &&
3951      N0.getValueSizeInBits() <= 64) {
3952    uint64_t ShAmt = N1C->getZExtValue()+64-N0.getValueSizeInBits();
3953    return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
3954                       DAG.getConstant(~0ULL >> ShAmt, VT));
3955  }
3956
3957  // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
3958  if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
3959    // Shifting in all undef bits?
3960    EVT SmallVT = N0.getOperand(0).getValueType();
3961    if (N1C->getZExtValue() >= SmallVT.getSizeInBits())
3962      return DAG.getUNDEF(VT);
3963
3964    if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
3965      uint64_t ShiftAmt = N1C->getZExtValue();
3966      SDValue SmallShift = DAG.getNode(ISD::SRL, SDLoc(N0), SmallVT,
3967                                       N0.getOperand(0),
3968                          DAG.getConstant(ShiftAmt, getShiftAmountTy(SmallVT)));
3969      AddToWorkList(SmallShift.getNode());
3970      APInt Mask = APInt::getAllOnesValue(VT.getSizeInBits()).lshr(ShiftAmt);
3971      return DAG.getNode(ISD::AND, SDLoc(N), VT,
3972                         DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, SmallShift),
3973                         DAG.getConstant(Mask, VT));
3974    }
3975  }
3976
3977  // fold (srl (sra X, Y), 31) -> (srl X, 31).  This srl only looks at the sign
3978  // bit, which is unmodified by sra.
3979  if (N1C && N1C->getZExtValue() + 1 == VT.getSizeInBits()) {
3980    if (N0.getOpcode() == ISD::SRA)
3981      return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
3982  }
3983
3984  // fold (srl (ctlz x), "5") -> x  iff x has one bit set (the low bit).
3985  if (N1C && N0.getOpcode() == ISD::CTLZ &&
3986      N1C->getAPIntValue() == Log2_32(VT.getSizeInBits())) {
3987    APInt KnownZero, KnownOne;
3988    DAG.ComputeMaskedBits(N0.getOperand(0), KnownZero, KnownOne);
3989
3990    // If any of the input bits are KnownOne, then the input couldn't be all
3991    // zeros, thus the result of the srl will always be zero.
3992    if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT);
3993
3994    // If all of the bits input the to ctlz node are known to be zero, then
3995    // the result of the ctlz is "32" and the result of the shift is one.
3996    APInt UnknownBits = ~KnownZero;
3997    if (UnknownBits == 0) return DAG.getConstant(1, VT);
3998
3999    // Otherwise, check to see if there is exactly one bit input to the ctlz.
4000    if ((UnknownBits & (UnknownBits - 1)) == 0) {
4001      // Okay, we know that only that the single bit specified by UnknownBits
4002      // could be set on input to the CTLZ node. If this bit is set, the SRL
4003      // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4004      // to an SRL/XOR pair, which is likely to simplify more.
4005      unsigned ShAmt = UnknownBits.countTrailingZeros();
4006      SDValue Op = N0.getOperand(0);
4007
4008      if (ShAmt) {
4009        Op = DAG.getNode(ISD::SRL, SDLoc(N0), VT, Op,
4010                  DAG.getConstant(ShAmt, getShiftAmountTy(Op.getValueType())));
4011        AddToWorkList(Op.getNode());
4012      }
4013
4014      return DAG.getNode(ISD::XOR, SDLoc(N), VT,
4015                         Op, DAG.getConstant(1, VT));
4016    }
4017  }
4018
4019  // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
4020  if (N1.getOpcode() == ISD::TRUNCATE &&
4021      N1.getOperand(0).getOpcode() == ISD::AND &&
4022      N1.hasOneUse() && N1.getOperand(0).hasOneUse()) {
4023    SDValue N101 = N1.getOperand(0).getOperand(1);
4024    if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) {
4025      EVT TruncVT = N1.getValueType();
4026      SDValue N100 = N1.getOperand(0).getOperand(0);
4027      APInt TruncC = N101C->getAPIntValue();
4028      TruncC = TruncC.trunc(TruncVT.getSizeInBits());
4029      return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0,
4030                         DAG.getNode(ISD::AND, SDLoc(N),
4031                                     TruncVT,
4032                                     DAG.getNode(ISD::TRUNCATE,
4033                                                 SDLoc(N),
4034                                                 TruncVT, N100),
4035                                     DAG.getConstant(TruncC, TruncVT)));
4036    }
4037  }
4038
4039  // fold operands of srl based on knowledge that the low bits are not
4040  // demanded.
4041  if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4042    return SDValue(N, 0);
4043
4044  if (N1C) {
4045    SDValue NewSRL = visitShiftByConstant(N, N1C->getZExtValue());
4046    if (NewSRL.getNode())
4047      return NewSRL;
4048  }
4049
4050  // Attempt to convert a srl of a load into a narrower zero-extending load.
4051  SDValue NarrowLoad = ReduceLoadWidth(N);
4052  if (NarrowLoad.getNode())
4053    return NarrowLoad;
4054
4055  // Here is a common situation. We want to optimize:
4056  //
4057  //   %a = ...
4058  //   %b = and i32 %a, 2
4059  //   %c = srl i32 %b, 1
4060  //   brcond i32 %c ...
4061  //
4062  // into
4063  //
4064  //   %a = ...
4065  //   %b = and %a, 2
4066  //   %c = setcc eq %b, 0
4067  //   brcond %c ...
4068  //
4069  // However when after the source operand of SRL is optimized into AND, the SRL
4070  // itself may not be optimized further. Look for it and add the BRCOND into
4071  // the worklist.
4072  if (N->hasOneUse()) {
4073    SDNode *Use = *N->use_begin();
4074    if (Use->getOpcode() == ISD::BRCOND)
4075      AddToWorkList(Use);
4076    else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4077      // Also look pass the truncate.
4078      Use = *Use->use_begin();
4079      if (Use->getOpcode() == ISD::BRCOND)
4080        AddToWorkList(Use);
4081    }
4082  }
4083
4084  return SDValue();
4085}
4086
4087SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4088  SDValue N0 = N->getOperand(0);
4089  EVT VT = N->getValueType(0);
4090
4091  // fold (ctlz c1) -> c2
4092  if (isa<ConstantSDNode>(N0))
4093    return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
4094  return SDValue();
4095}
4096
4097SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4098  SDValue N0 = N->getOperand(0);
4099  EVT VT = N->getValueType(0);
4100
4101  // fold (ctlz_zero_undef c1) -> c2
4102  if (isa<ConstantSDNode>(N0))
4103    return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4104  return SDValue();
4105}
4106
4107SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4108  SDValue N0 = N->getOperand(0);
4109  EVT VT = N->getValueType(0);
4110
4111  // fold (cttz c1) -> c2
4112  if (isa<ConstantSDNode>(N0))
4113    return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
4114  return SDValue();
4115}
4116
4117SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4118  SDValue N0 = N->getOperand(0);
4119  EVT VT = N->getValueType(0);
4120
4121  // fold (cttz_zero_undef c1) -> c2
4122  if (isa<ConstantSDNode>(N0))
4123    return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4124  return SDValue();
4125}
4126
4127SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4128  SDValue N0 = N->getOperand(0);
4129  EVT VT = N->getValueType(0);
4130
4131  // fold (ctpop c1) -> c2
4132  if (isa<ConstantSDNode>(N0))
4133    return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
4134  return SDValue();
4135}
4136
4137SDValue DAGCombiner::visitSELECT(SDNode *N) {
4138  SDValue N0 = N->getOperand(0);
4139  SDValue N1 = N->getOperand(1);
4140  SDValue N2 = N->getOperand(2);
4141  ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4142  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4143  ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
4144  EVT VT = N->getValueType(0);
4145  EVT VT0 = N0.getValueType();
4146
4147  // fold (select C, X, X) -> X
4148  if (N1 == N2)
4149    return N1;
4150  // fold (select true, X, Y) -> X
4151  if (N0C && !N0C->isNullValue())
4152    return N1;
4153  // fold (select false, X, Y) -> Y
4154  if (N0C && N0C->isNullValue())
4155    return N2;
4156  // fold (select C, 1, X) -> (or C, X)
4157  if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
4158    return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4159  // fold (select C, 0, 1) -> (xor C, 1)
4160  if (VT.isInteger() &&
4161      (VT0 == MVT::i1 ||
4162       (VT0.isInteger() &&
4163        TLI.getBooleanContents(false) ==
4164        TargetLowering::ZeroOrOneBooleanContent)) &&
4165      N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
4166    SDValue XORNode;
4167    if (VT == VT0)
4168      return DAG.getNode(ISD::XOR, SDLoc(N), VT0,
4169                         N0, DAG.getConstant(1, VT0));
4170    XORNode = DAG.getNode(ISD::XOR, SDLoc(N0), VT0,
4171                          N0, DAG.getConstant(1, VT0));
4172    AddToWorkList(XORNode.getNode());
4173    if (VT.bitsGT(VT0))
4174      return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
4175    return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
4176  }
4177  // fold (select C, 0, X) -> (and (not C), X)
4178  if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
4179    SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4180    AddToWorkList(NOTNode.getNode());
4181    return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
4182  }
4183  // fold (select C, X, 1) -> (or (not C), X)
4184  if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
4185    SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4186    AddToWorkList(NOTNode.getNode());
4187    return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
4188  }
4189  // fold (select C, X, 0) -> (and C, X)
4190  if (VT == MVT::i1 && N2C && N2C->isNullValue())
4191    return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4192  // fold (select X, X, Y) -> (or X, Y)
4193  // fold (select X, 1, Y) -> (or X, Y)
4194  if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1)))
4195    return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4196  // fold (select X, Y, X) -> (and X, Y)
4197  // fold (select X, Y, 0) -> (and X, Y)
4198  if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0)))
4199    return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4200
4201  // If we can fold this based on the true/false value, do so.
4202  if (SimplifySelectOps(N, N1, N2))
4203    return SDValue(N, 0);  // Don't revisit N.
4204
4205  // fold selects based on a setcc into other things, such as min/max/abs
4206  if (N0.getOpcode() == ISD::SETCC) {
4207    // FIXME:
4208    // Check against MVT::Other for SELECT_CC, which is a workaround for targets
4209    // having to say they don't support SELECT_CC on every type the DAG knows
4210    // about, since there is no way to mark an opcode illegal at all value types
4211    if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other) &&
4212        TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT))
4213      return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
4214                         N0.getOperand(0), N0.getOperand(1),
4215                         N1, N2, N0.getOperand(2));
4216    return SimplifySelect(SDLoc(N), N0, N1, N2);
4217  }
4218
4219  return SDValue();
4220}
4221
4222SDValue DAGCombiner::visitVSELECT(SDNode *N) {
4223  SDValue N0 = N->getOperand(0);
4224  SDValue N1 = N->getOperand(1);
4225  SDValue N2 = N->getOperand(2);
4226  SDLoc DL(N);
4227
4228  // Canonicalize integer abs.
4229  // vselect (setg[te] X,  0),  X, -X ->
4230  // vselect (setgt    X, -1),  X, -X ->
4231  // vselect (setl[te] X,  0), -X,  X ->
4232  // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
4233  if (N0.getOpcode() == ISD::SETCC) {
4234    SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4235    ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
4236    bool isAbs = false;
4237    bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
4238
4239    if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
4240         (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
4241        N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
4242      isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
4243    else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
4244             N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
4245      isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
4246
4247    if (isAbs) {
4248      EVT VT = LHS.getValueType();
4249      SDValue Shift = DAG.getNode(
4250          ISD::SRA, DL, VT, LHS,
4251          DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, VT));
4252      SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
4253      AddToWorkList(Shift.getNode());
4254      AddToWorkList(Add.getNode());
4255      return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
4256    }
4257  }
4258
4259  return SDValue();
4260}
4261
4262SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
4263  SDValue N0 = N->getOperand(0);
4264  SDValue N1 = N->getOperand(1);
4265  SDValue N2 = N->getOperand(2);
4266  SDValue N3 = N->getOperand(3);
4267  SDValue N4 = N->getOperand(4);
4268  ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
4269
4270  // fold select_cc lhs, rhs, x, x, cc -> x
4271  if (N2 == N3)
4272    return N2;
4273
4274  // Determine if the condition we're dealing with is constant
4275  SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
4276                              N0, N1, CC, SDLoc(N), false);
4277  if (SCC.getNode()) {
4278    AddToWorkList(SCC.getNode());
4279
4280    if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
4281      if (!SCCC->isNullValue())
4282        return N2;    // cond always true -> true val
4283      else
4284        return N3;    // cond always false -> false val
4285    }
4286
4287    // Fold to a simpler select_cc
4288    if (SCC.getOpcode() == ISD::SETCC)
4289      return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
4290                         SCC.getOperand(0), SCC.getOperand(1), N2, N3,
4291                         SCC.getOperand(2));
4292  }
4293
4294  // If we can fold this based on the true/false value, do so.
4295  if (SimplifySelectOps(N, N2, N3))
4296    return SDValue(N, 0);  // Don't revisit N.
4297
4298  // fold select_cc into other things, such as min/max/abs
4299  return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
4300}
4301
4302SDValue DAGCombiner::visitSETCC(SDNode *N) {
4303  return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
4304                       cast<CondCodeSDNode>(N->getOperand(2))->get(),
4305                       SDLoc(N));
4306}
4307
4308// ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
4309// "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
4310// transformation. Returns true if extension are possible and the above
4311// mentioned transformation is profitable.
4312static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
4313                                    unsigned ExtOpc,
4314                                    SmallVector<SDNode*, 4> &ExtendNodes,
4315                                    const TargetLowering &TLI) {
4316  bool HasCopyToRegUses = false;
4317  bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
4318  for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
4319                            UE = N0.getNode()->use_end();
4320       UI != UE; ++UI) {
4321    SDNode *User = *UI;
4322    if (User == N)
4323      continue;
4324    if (UI.getUse().getResNo() != N0.getResNo())
4325      continue;
4326    // FIXME: Only extend SETCC N, N and SETCC N, c for now.
4327    if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
4328      ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
4329      if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
4330        // Sign bits will be lost after a zext.
4331        return false;
4332      bool Add = false;
4333      for (unsigned i = 0; i != 2; ++i) {
4334        SDValue UseOp = User->getOperand(i);
4335        if (UseOp == N0)
4336          continue;
4337        if (!isa<ConstantSDNode>(UseOp))
4338          return false;
4339        Add = true;
4340      }
4341      if (Add)
4342        ExtendNodes.push_back(User);
4343      continue;
4344    }
4345    // If truncates aren't free and there are users we can't
4346    // extend, it isn't worthwhile.
4347    if (!isTruncFree)
4348      return false;
4349    // Remember if this value is live-out.
4350    if (User->getOpcode() == ISD::CopyToReg)
4351      HasCopyToRegUses = true;
4352  }
4353
4354  if (HasCopyToRegUses) {
4355    bool BothLiveOut = false;
4356    for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
4357         UI != UE; ++UI) {
4358      SDUse &Use = UI.getUse();
4359      if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
4360        BothLiveOut = true;
4361        break;
4362      }
4363    }
4364    if (BothLiveOut)
4365      // Both unextended and extended values are live out. There had better be
4366      // a good reason for the transformation.
4367      return ExtendNodes.size();
4368  }
4369  return true;
4370}
4371
4372void DAGCombiner::ExtendSetCCUses(SmallVector<SDNode*, 4> SetCCs,
4373                                  SDValue Trunc, SDValue ExtLoad, SDLoc DL,
4374                                  ISD::NodeType ExtType) {
4375  // Extend SetCC uses if necessary.
4376  for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
4377    SDNode *SetCC = SetCCs[i];
4378    SmallVector<SDValue, 4> Ops;
4379
4380    for (unsigned j = 0; j != 2; ++j) {
4381      SDValue SOp = SetCC->getOperand(j);
4382      if (SOp == Trunc)
4383        Ops.push_back(ExtLoad);
4384      else
4385        Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
4386    }
4387
4388    Ops.push_back(SetCC->getOperand(2));
4389    CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0),
4390                                 &Ops[0], Ops.size()));
4391  }
4392}
4393
4394SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
4395  SDValue N0 = N->getOperand(0);
4396  EVT VT = N->getValueType(0);
4397
4398  // fold (sext c1) -> c1
4399  if (isa<ConstantSDNode>(N0))
4400    return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N0);
4401
4402  // fold (sext (sext x)) -> (sext x)
4403  // fold (sext (aext x)) -> (sext x)
4404  if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
4405    return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
4406                       N0.getOperand(0));
4407
4408  if (N0.getOpcode() == ISD::TRUNCATE) {
4409    // fold (sext (truncate (load x))) -> (sext (smaller load x))
4410    // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
4411    SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4412    if (NarrowLoad.getNode()) {
4413      SDNode* oye = N0.getNode()->getOperand(0).getNode();
4414      if (NarrowLoad.getNode() != N0.getNode()) {
4415        CombineTo(N0.getNode(), NarrowLoad);
4416        // CombineTo deleted the truncate, if needed, but not what's under it.
4417        AddToWorkList(oye);
4418      }
4419      return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4420    }
4421
4422    // See if the value being truncated is already sign extended.  If so, just
4423    // eliminate the trunc/sext pair.
4424    SDValue Op = N0.getOperand(0);
4425    unsigned OpBits   = Op.getValueType().getScalarType().getSizeInBits();
4426    unsigned MidBits  = N0.getValueType().getScalarType().getSizeInBits();
4427    unsigned DestBits = VT.getScalarType().getSizeInBits();
4428    unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
4429
4430    if (OpBits == DestBits) {
4431      // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
4432      // bits, it is already ready.
4433      if (NumSignBits > DestBits-MidBits)
4434        return Op;
4435    } else if (OpBits < DestBits) {
4436      // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
4437      // bits, just sext from i32.
4438      if (NumSignBits > OpBits-MidBits)
4439        return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
4440    } else {
4441      // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
4442      // bits, just truncate to i32.
4443      if (NumSignBits > OpBits-MidBits)
4444        return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
4445    }
4446
4447    // fold (sext (truncate x)) -> (sextinreg x).
4448    if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
4449                                                 N0.getValueType())) {
4450      if (OpBits < DestBits)
4451        Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
4452      else if (OpBits > DestBits)
4453        Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
4454      return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
4455                         DAG.getValueType(N0.getValueType()));
4456    }
4457  }
4458
4459  // fold (sext (load x)) -> (sext (truncate (sextload x)))
4460  // None of the supported targets knows how to perform load and sign extend
4461  // on vectors in one instruction.  We only perform this transformation on
4462  // scalars.
4463  if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
4464      ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
4465       TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()))) {
4466    bool DoXform = true;
4467    SmallVector<SDNode*, 4> SetCCs;
4468    if (!N0.hasOneUse())
4469      DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
4470    if (DoXform) {
4471      LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4472      SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
4473                                       LN0->getChain(),
4474                                       LN0->getBasePtr(), LN0->getPointerInfo(),
4475                                       N0.getValueType(),
4476                                       LN0->isVolatile(), LN0->isNonTemporal(),
4477                                       LN0->getAlignment());
4478      CombineTo(N, ExtLoad);
4479      SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
4480                                  N0.getValueType(), ExtLoad);
4481      CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
4482      ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
4483                      ISD::SIGN_EXTEND);
4484      return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4485    }
4486  }
4487
4488  // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
4489  // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
4490  if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
4491      ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
4492    LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4493    EVT MemVT = LN0->getMemoryVT();
4494    if ((!LegalOperations && !LN0->isVolatile()) ||
4495        TLI.isLoadExtLegal(ISD::SEXTLOAD, MemVT)) {
4496      SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
4497                                       LN0->getChain(),
4498                                       LN0->getBasePtr(), LN0->getPointerInfo(),
4499                                       MemVT,
4500                                       LN0->isVolatile(), LN0->isNonTemporal(),
4501                                       LN0->getAlignment());
4502      CombineTo(N, ExtLoad);
4503      CombineTo(N0.getNode(),
4504                DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
4505                            N0.getValueType(), ExtLoad),
4506                ExtLoad.getValue(1));
4507      return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4508    }
4509  }
4510
4511  // fold (sext (and/or/xor (load x), cst)) ->
4512  //      (and/or/xor (sextload x), (sext cst))
4513  if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
4514       N0.getOpcode() == ISD::XOR) &&
4515      isa<LoadSDNode>(N0.getOperand(0)) &&
4516      N0.getOperand(1).getOpcode() == ISD::Constant &&
4517      TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()) &&
4518      (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
4519    LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
4520    if (LN0->getExtensionType() != ISD::ZEXTLOAD) {
4521      bool DoXform = true;
4522      SmallVector<SDNode*, 4> SetCCs;
4523      if (!N0.hasOneUse())
4524        DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
4525                                          SetCCs, TLI);
4526      if (DoXform) {
4527        SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
4528                                         LN0->getChain(), LN0->getBasePtr(),
4529                                         LN0->getPointerInfo(),
4530                                         LN0->getMemoryVT(),
4531                                         LN0->isVolatile(),
4532                                         LN0->isNonTemporal(),
4533                                         LN0->getAlignment());
4534        APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
4535        Mask = Mask.sext(VT.getSizeInBits());
4536        SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
4537                                  ExtLoad, DAG.getConstant(Mask, VT));
4538        SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
4539                                    SDLoc(N0.getOperand(0)),
4540                                    N0.getOperand(0).getValueType(), ExtLoad);
4541        CombineTo(N, And);
4542        CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
4543        ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
4544                        ISD::SIGN_EXTEND);
4545        return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4546      }
4547    }
4548  }
4549
4550  if (N0.getOpcode() == ISD::SETCC) {
4551    // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
4552    // Only do this before legalize for now.
4553    if (VT.isVector() && !LegalOperations &&
4554        TLI.getBooleanContents(true) ==
4555          TargetLowering::ZeroOrNegativeOneBooleanContent) {
4556      EVT N0VT = N0.getOperand(0).getValueType();
4557      // On some architectures (such as SSE/NEON/etc) the SETCC result type is
4558      // of the same size as the compared operands. Only optimize sext(setcc())
4559      // if this is the case.
4560      EVT SVT = getSetCCResultType(N0VT);
4561
4562      // We know that the # elements of the results is the same as the
4563      // # elements of the compare (and the # elements of the compare result
4564      // for that matter).  Check to see that they are the same size.  If so,
4565      // we know that the element size of the sext'd result matches the
4566      // element size of the compare operands.
4567      if (VT.getSizeInBits() == SVT.getSizeInBits())
4568        return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
4569                             N0.getOperand(1),
4570                             cast<CondCodeSDNode>(N0.getOperand(2))->get());
4571
4572      // If the desired elements are smaller or larger than the source
4573      // elements we can use a matching integer vector type and then
4574      // truncate/sign extend
4575      EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
4576      if (SVT == MatchingVectorType) {
4577        SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
4578                               N0.getOperand(0), N0.getOperand(1),
4579                               cast<CondCodeSDNode>(N0.getOperand(2))->get());
4580        return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
4581      }
4582    }
4583
4584    // sext(setcc x, y, cc) -> (select_cc x, y, -1, 0, cc)
4585    unsigned ElementWidth = VT.getScalarType().getSizeInBits();
4586    SDValue NegOne =
4587      DAG.getConstant(APInt::getAllOnesValue(ElementWidth), VT);
4588    SDValue SCC =
4589      SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
4590                       NegOne, DAG.getConstant(0, VT),
4591                       cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
4592    if (SCC.getNode()) return SCC;
4593    if (!VT.isVector() &&
4594        (!LegalOperations ||
4595         TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(VT)))) {
4596      return DAG.getSelect(SDLoc(N), VT,
4597                           DAG.getSetCC(SDLoc(N),
4598                                        getSetCCResultType(VT),
4599                                        N0.getOperand(0), N0.getOperand(1),
4600                                        cast<CondCodeSDNode>(N0.getOperand(2))->get()),
4601                           NegOne, DAG.getConstant(0, VT));
4602    }
4603  }
4604
4605  // fold (sext x) -> (zext x) if the sign bit is known zero.
4606  if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
4607      DAG.SignBitIsZero(N0))
4608    return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
4609
4610  return SDValue();
4611}
4612
4613// isTruncateOf - If N is a truncate of some other value, return true, record
4614// the value being truncated in Op and which of Op's bits are zero in KnownZero.
4615// This function computes KnownZero to avoid a duplicated call to
4616// ComputeMaskedBits in the caller.
4617static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
4618                         APInt &KnownZero) {
4619  APInt KnownOne;
4620  if (N->getOpcode() == ISD::TRUNCATE) {
4621    Op = N->getOperand(0);
4622    DAG.ComputeMaskedBits(Op, KnownZero, KnownOne);
4623    return true;
4624  }
4625
4626  if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
4627      cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
4628    return false;
4629
4630  SDValue Op0 = N->getOperand(0);
4631  SDValue Op1 = N->getOperand(1);
4632  assert(Op0.getValueType() == Op1.getValueType());
4633
4634  ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0);
4635  ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1);
4636  if (COp0 && COp0->isNullValue())
4637    Op = Op1;
4638  else if (COp1 && COp1->isNullValue())
4639    Op = Op0;
4640  else
4641    return false;
4642
4643  DAG.ComputeMaskedBits(Op, KnownZero, KnownOne);
4644
4645  if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
4646    return false;
4647
4648  return true;
4649}
4650
4651SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
4652  SDValue N0 = N->getOperand(0);
4653  EVT VT = N->getValueType(0);
4654
4655  // fold (zext c1) -> c1
4656  if (isa<ConstantSDNode>(N0))
4657    return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
4658  // fold (zext (zext x)) -> (zext x)
4659  // fold (zext (aext x)) -> (zext x)
4660  if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
4661    return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
4662                       N0.getOperand(0));
4663
4664  // fold (zext (truncate x)) -> (zext x) or
4665  //      (zext (truncate x)) -> (truncate x)
4666  // This is valid when the truncated bits of x are already zero.
4667  // FIXME: We should extend this to work for vectors too.
4668  SDValue Op;
4669  APInt KnownZero;
4670  if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
4671    APInt TruncatedBits =
4672      (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
4673      APInt(Op.getValueSizeInBits(), 0) :
4674      APInt::getBitsSet(Op.getValueSizeInBits(),
4675                        N0.getValueSizeInBits(),
4676                        std::min(Op.getValueSizeInBits(),
4677                                 VT.getSizeInBits()));
4678    if (TruncatedBits == (KnownZero & TruncatedBits)) {
4679      if (VT.bitsGT(Op.getValueType()))
4680        return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
4681      if (VT.bitsLT(Op.getValueType()))
4682        return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
4683
4684      return Op;
4685    }
4686  }
4687
4688  // fold (zext (truncate (load x))) -> (zext (smaller load x))
4689  // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
4690  if (N0.getOpcode() == ISD::TRUNCATE) {
4691    SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4692    if (NarrowLoad.getNode()) {
4693      SDNode* oye = N0.getNode()->getOperand(0).getNode();
4694      if (NarrowLoad.getNode() != N0.getNode()) {
4695        CombineTo(N0.getNode(), NarrowLoad);
4696        // CombineTo deleted the truncate, if needed, but not what's under it.
4697        AddToWorkList(oye);
4698      }
4699      return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4700    }
4701  }
4702
4703  // fold (zext (truncate x)) -> (and x, mask)
4704  if (N0.getOpcode() == ISD::TRUNCATE &&
4705      (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
4706
4707    // fold (zext (truncate (load x))) -> (zext (smaller load x))
4708    // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
4709    SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4710    if (NarrowLoad.getNode()) {
4711      SDNode* oye = N0.getNode()->getOperand(0).getNode();
4712      if (NarrowLoad.getNode() != N0.getNode()) {
4713        CombineTo(N0.getNode(), NarrowLoad);
4714        // CombineTo deleted the truncate, if needed, but not what's under it.
4715        AddToWorkList(oye);
4716      }
4717      return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4718    }
4719
4720    SDValue Op = N0.getOperand(0);
4721    if (Op.getValueType().bitsLT(VT)) {
4722      Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
4723      AddToWorkList(Op.getNode());
4724    } else if (Op.getValueType().bitsGT(VT)) {
4725      Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
4726      AddToWorkList(Op.getNode());
4727    }
4728    return DAG.getZeroExtendInReg(Op, SDLoc(N),
4729                                  N0.getValueType().getScalarType());
4730  }
4731
4732  // Fold (zext (and (trunc x), cst)) -> (and x, cst),
4733  // if either of the casts is not free.
4734  if (N0.getOpcode() == ISD::AND &&
4735      N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
4736      N0.getOperand(1).getOpcode() == ISD::Constant &&
4737      (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
4738                           N0.getValueType()) ||
4739       !TLI.isZExtFree(N0.getValueType(), VT))) {
4740    SDValue X = N0.getOperand(0).getOperand(0);
4741    if (X.getValueType().bitsLT(VT)) {
4742      X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
4743    } else if (X.getValueType().bitsGT(VT)) {
4744      X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
4745    }
4746    APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
4747    Mask = Mask.zext(VT.getSizeInBits());
4748    return DAG.getNode(ISD::AND, SDLoc(N), VT,
4749                       X, DAG.getConstant(Mask, VT));
4750  }
4751
4752  // fold (zext (load x)) -> (zext (truncate (zextload x)))
4753  // None of the supported targets knows how to perform load and vector_zext
4754  // on vectors in one instruction.  We only perform this transformation on
4755  // scalars.
4756  if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
4757      ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
4758       TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()))) {
4759    bool DoXform = true;
4760    SmallVector<SDNode*, 4> SetCCs;
4761    if (!N0.hasOneUse())
4762      DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
4763    if (DoXform) {
4764      LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4765      SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
4766                                       LN0->getChain(),
4767                                       LN0->getBasePtr(), LN0->getPointerInfo(),
4768                                       N0.getValueType(),
4769                                       LN0->isVolatile(), LN0->isNonTemporal(),
4770                                       LN0->getAlignment());
4771      CombineTo(N, ExtLoad);
4772      SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
4773                                  N0.getValueType(), ExtLoad);
4774      CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
4775
4776      ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
4777                      ISD::ZERO_EXTEND);
4778      return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4779    }
4780  }
4781
4782  // fold (zext (and/or/xor (load x), cst)) ->
4783  //      (and/or/xor (zextload x), (zext cst))
4784  if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
4785       N0.getOpcode() == ISD::XOR) &&
4786      isa<LoadSDNode>(N0.getOperand(0)) &&
4787      N0.getOperand(1).getOpcode() == ISD::Constant &&
4788      TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()) &&
4789      (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
4790    LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
4791    if (LN0->getExtensionType() != ISD::SEXTLOAD) {
4792      bool DoXform = true;
4793      SmallVector<SDNode*, 4> SetCCs;
4794      if (!N0.hasOneUse())
4795        DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
4796                                          SetCCs, TLI);
4797      if (DoXform) {
4798        SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
4799                                         LN0->getChain(), LN0->getBasePtr(),
4800                                         LN0->getPointerInfo(),
4801                                         LN0->getMemoryVT(),
4802                                         LN0->isVolatile(),
4803                                         LN0->isNonTemporal(),
4804                                         LN0->getAlignment());
4805        APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
4806        Mask = Mask.zext(VT.getSizeInBits());
4807        SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
4808                                  ExtLoad, DAG.getConstant(Mask, VT));
4809        SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
4810                                    SDLoc(N0.getOperand(0)),
4811                                    N0.getOperand(0).getValueType(), ExtLoad);
4812        CombineTo(N, And);
4813        CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
4814        ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
4815                        ISD::ZERO_EXTEND);
4816        return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4817      }
4818    }
4819  }
4820
4821  // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
4822  // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
4823  if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
4824      ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
4825    LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4826    EVT MemVT = LN0->getMemoryVT();
4827    if ((!LegalOperations && !LN0->isVolatile()) ||
4828        TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT)) {
4829      SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
4830                                       LN0->getChain(),
4831                                       LN0->getBasePtr(), LN0->getPointerInfo(),
4832                                       MemVT,
4833                                       LN0->isVolatile(), LN0->isNonTemporal(),
4834                                       LN0->getAlignment());
4835      CombineTo(N, ExtLoad);
4836      CombineTo(N0.getNode(),
4837                DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
4838                            ExtLoad),
4839                ExtLoad.getValue(1));
4840      return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4841    }
4842  }
4843
4844  if (N0.getOpcode() == ISD::SETCC) {
4845    if (!LegalOperations && VT.isVector()) {
4846      // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
4847      // Only do this before legalize for now.
4848      EVT N0VT = N0.getOperand(0).getValueType();
4849      EVT EltVT = VT.getVectorElementType();
4850      SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
4851                                    DAG.getConstant(1, EltVT));
4852      if (VT.getSizeInBits() == N0VT.getSizeInBits())
4853        // We know that the # elements of the results is the same as the
4854        // # elements of the compare (and the # elements of the compare result
4855        // for that matter).  Check to see that they are the same size.  If so,
4856        // we know that the element size of the sext'd result matches the
4857        // element size of the compare operands.
4858        return DAG.getNode(ISD::AND, SDLoc(N), VT,
4859                           DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
4860                                         N0.getOperand(1),
4861                                 cast<CondCodeSDNode>(N0.getOperand(2))->get()),
4862                           DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
4863                                       &OneOps[0], OneOps.size()));
4864
4865      // If the desired elements are smaller or larger than the source
4866      // elements we can use a matching integer vector type and then
4867      // truncate/sign extend
4868      EVT MatchingElementType =
4869        EVT::getIntegerVT(*DAG.getContext(),
4870                          N0VT.getScalarType().getSizeInBits());
4871      EVT MatchingVectorType =
4872        EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
4873                         N0VT.getVectorNumElements());
4874      SDValue VsetCC =
4875        DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
4876                      N0.getOperand(1),
4877                      cast<CondCodeSDNode>(N0.getOperand(2))->get());
4878      return DAG.getNode(ISD::AND, SDLoc(N), VT,
4879                         DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT),
4880                         DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
4881                                     &OneOps[0], OneOps.size()));
4882    }
4883
4884    // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
4885    SDValue SCC =
4886      SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
4887                       DAG.getConstant(1, VT), DAG.getConstant(0, VT),
4888                       cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
4889    if (SCC.getNode()) return SCC;
4890  }
4891
4892  // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
4893  if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
4894      isa<ConstantSDNode>(N0.getOperand(1)) &&
4895      N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
4896      N0.hasOneUse()) {
4897    SDValue ShAmt = N0.getOperand(1);
4898    unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
4899    if (N0.getOpcode() == ISD::SHL) {
4900      SDValue InnerZExt = N0.getOperand(0);
4901      // If the original shl may be shifting out bits, do not perform this
4902      // transformation.
4903      unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
4904        InnerZExt.getOperand(0).getValueType().getSizeInBits();
4905      if (ShAmtVal > KnownZeroBits)
4906        return SDValue();
4907    }
4908
4909    SDLoc DL(N);
4910
4911    // Ensure that the shift amount is wide enough for the shifted value.
4912    if (VT.getSizeInBits() >= 256)
4913      ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
4914
4915    return DAG.getNode(N0.getOpcode(), DL, VT,
4916                       DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
4917                       ShAmt);
4918  }
4919
4920  return SDValue();
4921}
4922
4923SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
4924  SDValue N0 = N->getOperand(0);
4925  EVT VT = N->getValueType(0);
4926
4927  // fold (aext c1) -> c1
4928  if (isa<ConstantSDNode>(N0))
4929    return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, N0);
4930  // fold (aext (aext x)) -> (aext x)
4931  // fold (aext (zext x)) -> (zext x)
4932  // fold (aext (sext x)) -> (sext x)
4933  if (N0.getOpcode() == ISD::ANY_EXTEND  ||
4934      N0.getOpcode() == ISD::ZERO_EXTEND ||
4935      N0.getOpcode() == ISD::SIGN_EXTEND)
4936    return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
4937
4938  // fold (aext (truncate (load x))) -> (aext (smaller load x))
4939  // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
4940  if (N0.getOpcode() == ISD::TRUNCATE) {
4941    SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4942    if (NarrowLoad.getNode()) {
4943      SDNode* oye = N0.getNode()->getOperand(0).getNode();
4944      if (NarrowLoad.getNode() != N0.getNode()) {
4945        CombineTo(N0.getNode(), NarrowLoad);
4946        // CombineTo deleted the truncate, if needed, but not what's under it.
4947        AddToWorkList(oye);
4948      }
4949      return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4950    }
4951  }
4952
4953  // fold (aext (truncate x))
4954  if (N0.getOpcode() == ISD::TRUNCATE) {
4955    SDValue TruncOp = N0.getOperand(0);
4956    if (TruncOp.getValueType() == VT)
4957      return TruncOp; // x iff x size == zext size.
4958    if (TruncOp.getValueType().bitsGT(VT))
4959      return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
4960    return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
4961  }
4962
4963  // Fold (aext (and (trunc x), cst)) -> (and x, cst)
4964  // if the trunc is not free.
4965  if (N0.getOpcode() == ISD::AND &&
4966      N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
4967      N0.getOperand(1).getOpcode() == ISD::Constant &&
4968      !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
4969                          N0.getValueType())) {
4970    SDValue X = N0.getOperand(0).getOperand(0);
4971    if (X.getValueType().bitsLT(VT)) {
4972      X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
4973    } else if (X.getValueType().bitsGT(VT)) {
4974      X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
4975    }
4976    APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
4977    Mask = Mask.zext(VT.getSizeInBits());
4978    return DAG.getNode(ISD::AND, SDLoc(N), VT,
4979                       X, DAG.getConstant(Mask, VT));
4980  }
4981
4982  // fold (aext (load x)) -> (aext (truncate (extload x)))
4983  // None of the supported targets knows how to perform load and any_ext
4984  // on vectors in one instruction.  We only perform this transformation on
4985  // scalars.
4986  if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
4987      ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
4988       TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
4989    bool DoXform = true;
4990    SmallVector<SDNode*, 4> SetCCs;
4991    if (!N0.hasOneUse())
4992      DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
4993    if (DoXform) {
4994      LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4995      SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
4996                                       LN0->getChain(),
4997                                       LN0->getBasePtr(), LN0->getPointerInfo(),
4998                                       N0.getValueType(),
4999                                       LN0->isVolatile(), LN0->isNonTemporal(),
5000                                       LN0->getAlignment());
5001      CombineTo(N, ExtLoad);
5002      SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5003                                  N0.getValueType(), ExtLoad);
5004      CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5005      ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5006                      ISD::ANY_EXTEND);
5007      return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5008    }
5009  }
5010
5011  // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
5012  // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
5013  // fold (aext ( extload x)) -> (aext (truncate (extload  x)))
5014  if (N0.getOpcode() == ISD::LOAD &&
5015      !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5016      N0.hasOneUse()) {
5017    LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5018    EVT MemVT = LN0->getMemoryVT();
5019    SDValue ExtLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(N),
5020                                     VT, LN0->getChain(), LN0->getBasePtr(),
5021                                     LN0->getPointerInfo(), MemVT,
5022                                     LN0->isVolatile(), LN0->isNonTemporal(),
5023                                     LN0->getAlignment());
5024    CombineTo(N, ExtLoad);
5025    CombineTo(N0.getNode(),
5026              DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5027                          N0.getValueType(), ExtLoad),
5028              ExtLoad.getValue(1));
5029    return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5030  }
5031
5032  if (N0.getOpcode() == ISD::SETCC) {
5033    // aext(setcc) -> sext_in_reg(vsetcc) for vectors.
5034    // Only do this before legalize for now.
5035    if (VT.isVector() && !LegalOperations) {
5036      EVT N0VT = N0.getOperand(0).getValueType();
5037        // We know that the # elements of the results is the same as the
5038        // # elements of the compare (and the # elements of the compare result
5039        // for that matter).  Check to see that they are the same size.  If so,
5040        // we know that the element size of the sext'd result matches the
5041        // element size of the compare operands.
5042      if (VT.getSizeInBits() == N0VT.getSizeInBits())
5043        return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5044                             N0.getOperand(1),
5045                             cast<CondCodeSDNode>(N0.getOperand(2))->get());
5046      // If the desired elements are smaller or larger than the source
5047      // elements we can use a matching integer vector type and then
5048      // truncate/sign extend
5049      else {
5050        EVT MatchingElementType =
5051          EVT::getIntegerVT(*DAG.getContext(),
5052                            N0VT.getScalarType().getSizeInBits());
5053        EVT MatchingVectorType =
5054          EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
5055                           N0VT.getVectorNumElements());
5056        SDValue VsetCC =
5057          DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5058                        N0.getOperand(1),
5059                        cast<CondCodeSDNode>(N0.getOperand(2))->get());
5060        return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
5061      }
5062    }
5063
5064    // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5065    SDValue SCC =
5066      SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5067                       DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5068                       cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5069    if (SCC.getNode())
5070      return SCC;
5071  }
5072
5073  return SDValue();
5074}
5075
5076/// GetDemandedBits - See if the specified operand can be simplified with the
5077/// knowledge that only the bits specified by Mask are used.  If so, return the
5078/// simpler operand, otherwise return a null SDValue.
5079SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
5080  switch (V.getOpcode()) {
5081  default: break;
5082  case ISD::Constant: {
5083    const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
5084    assert(CV != 0 && "Const value should be ConstSDNode.");
5085    const APInt &CVal = CV->getAPIntValue();
5086    APInt NewVal = CVal & Mask;
5087    if (NewVal != CVal) {
5088      return DAG.getConstant(NewVal, V.getValueType());
5089    }
5090    break;
5091  }
5092  case ISD::OR:
5093  case ISD::XOR:
5094    // If the LHS or RHS don't contribute bits to the or, drop them.
5095    if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
5096      return V.getOperand(1);
5097    if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
5098      return V.getOperand(0);
5099    break;
5100  case ISD::SRL:
5101    // Only look at single-use SRLs.
5102    if (!V.getNode()->hasOneUse())
5103      break;
5104    if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
5105      // See if we can recursively simplify the LHS.
5106      unsigned Amt = RHSC->getZExtValue();
5107
5108      // Watch out for shift count overflow though.
5109      if (Amt >= Mask.getBitWidth()) break;
5110      APInt NewMask = Mask << Amt;
5111      SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
5112      if (SimplifyLHS.getNode())
5113        return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
5114                           SimplifyLHS, V.getOperand(1));
5115    }
5116  }
5117  return SDValue();
5118}
5119
5120/// ReduceLoadWidth - If the result of a wider load is shifted to right of N
5121/// bits and then truncated to a narrower type and where N is a multiple
5122/// of number of bits of the narrower type, transform it to a narrower load
5123/// from address + N / num of bits of new type. If the result is to be
5124/// extended, also fold the extension to form a extending load.
5125SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
5126  unsigned Opc = N->getOpcode();
5127
5128  ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
5129  SDValue N0 = N->getOperand(0);
5130  EVT VT = N->getValueType(0);
5131  EVT ExtVT = VT;
5132
5133  // This transformation isn't valid for vector loads.
5134  if (VT.isVector())
5135    return SDValue();
5136
5137  // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
5138  // extended to VT.
5139  if (Opc == ISD::SIGN_EXTEND_INREG) {
5140    ExtType = ISD::SEXTLOAD;
5141    ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
5142  } else if (Opc == ISD::SRL) {
5143    // Another special-case: SRL is basically zero-extending a narrower value.
5144    ExtType = ISD::ZEXTLOAD;
5145    N0 = SDValue(N, 0);
5146    ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
5147    if (!N01) return SDValue();
5148    ExtVT = EVT::getIntegerVT(*DAG.getContext(),
5149                              VT.getSizeInBits() - N01->getZExtValue());
5150  }
5151  if (LegalOperations && !TLI.isLoadExtLegal(ExtType, ExtVT))
5152    return SDValue();
5153
5154  unsigned EVTBits = ExtVT.getSizeInBits();
5155
5156  // Do not generate loads of non-round integer types since these can
5157  // be expensive (and would be wrong if the type is not byte sized).
5158  if (!ExtVT.isRound())
5159    return SDValue();
5160
5161  unsigned ShAmt = 0;
5162  if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
5163    if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5164      ShAmt = N01->getZExtValue();
5165      // Is the shift amount a multiple of size of VT?
5166      if ((ShAmt & (EVTBits-1)) == 0) {
5167        N0 = N0.getOperand(0);
5168        // Is the load width a multiple of size of VT?
5169        if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
5170          return SDValue();
5171      }
5172
5173      // At this point, we must have a load or else we can't do the transform.
5174      if (!isa<LoadSDNode>(N0)) return SDValue();
5175
5176      // Because a SRL must be assumed to *need* to zero-extend the high bits
5177      // (as opposed to anyext the high bits), we can't combine the zextload
5178      // lowering of SRL and an sextload.
5179      if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
5180        return SDValue();
5181
5182      // If the shift amount is larger than the input type then we're not
5183      // accessing any of the loaded bytes.  If the load was a zextload/extload
5184      // then the result of the shift+trunc is zero/undef (handled elsewhere).
5185      if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
5186        return SDValue();
5187    }
5188  }
5189
5190  // If the load is shifted left (and the result isn't shifted back right),
5191  // we can fold the truncate through the shift.
5192  unsigned ShLeftAmt = 0;
5193  if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
5194      ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
5195    if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5196      ShLeftAmt = N01->getZExtValue();
5197      N0 = N0.getOperand(0);
5198    }
5199  }
5200
5201  // If we haven't found a load, we can't narrow it.  Don't transform one with
5202  // multiple uses, this would require adding a new load.
5203  if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
5204    return SDValue();
5205
5206  // Don't change the width of a volatile load.
5207  LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5208  if (LN0->isVolatile())
5209    return SDValue();
5210
5211  // Verify that we are actually reducing a load width here.
5212  if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
5213    return SDValue();
5214
5215  // For the transform to be legal, the load must produce only two values
5216  // (the value loaded and the chain).  Don't transform a pre-increment
5217  // load, for example, which produces an extra value.  Otherwise the
5218  // transformation is not equivalent, and the downstream logic to replace
5219  // uses gets things wrong.
5220  if (LN0->getNumValues() > 2)
5221    return SDValue();
5222
5223  EVT PtrType = N0.getOperand(1).getValueType();
5224
5225  if (PtrType == MVT::Untyped || PtrType.isExtended())
5226    // It's not possible to generate a constant of extended or untyped type.
5227    return SDValue();
5228
5229  // For big endian targets, we need to adjust the offset to the pointer to
5230  // load the correct bytes.
5231  if (TLI.isBigEndian()) {
5232    unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
5233    unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
5234    ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
5235  }
5236
5237  uint64_t PtrOff = ShAmt / 8;
5238  unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
5239  SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0),
5240                               PtrType, LN0->getBasePtr(),
5241                               DAG.getConstant(PtrOff, PtrType));
5242  AddToWorkList(NewPtr.getNode());
5243
5244  SDValue Load;
5245  if (ExtType == ISD::NON_EXTLOAD)
5246    Load =  DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
5247                        LN0->getPointerInfo().getWithOffset(PtrOff),
5248                        LN0->isVolatile(), LN0->isNonTemporal(),
5249                        LN0->isInvariant(), NewAlign);
5250  else
5251    Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
5252                          LN0->getPointerInfo().getWithOffset(PtrOff),
5253                          ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
5254                          NewAlign);
5255
5256  // Replace the old load's chain with the new load's chain.
5257  WorkListRemover DeadNodes(*this);
5258  DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
5259
5260  // Shift the result left, if we've swallowed a left shift.
5261  SDValue Result = Load;
5262  if (ShLeftAmt != 0) {
5263    EVT ShImmTy = getShiftAmountTy(Result.getValueType());
5264    if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
5265      ShImmTy = VT;
5266    // If the shift amount is as large as the result size (but, presumably,
5267    // no larger than the source) then the useful bits of the result are
5268    // zero; we can't simply return the shortened shift, because the result
5269    // of that operation is undefined.
5270    if (ShLeftAmt >= VT.getSizeInBits())
5271      Result = DAG.getConstant(0, VT);
5272    else
5273      Result = DAG.getNode(ISD::SHL, SDLoc(N0), VT,
5274                          Result, DAG.getConstant(ShLeftAmt, ShImmTy));
5275  }
5276
5277  // Return the new loaded value.
5278  return Result;
5279}
5280
5281SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
5282  SDValue N0 = N->getOperand(0);
5283  SDValue N1 = N->getOperand(1);
5284  EVT VT = N->getValueType(0);
5285  EVT EVT = cast<VTSDNode>(N1)->getVT();
5286  unsigned VTBits = VT.getScalarType().getSizeInBits();
5287  unsigned EVTBits = EVT.getScalarType().getSizeInBits();
5288
5289  // fold (sext_in_reg c1) -> c1
5290  if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
5291    return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
5292
5293  // If the input is already sign extended, just drop the extension.
5294  if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
5295    return N0;
5296
5297  // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
5298  if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
5299      EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT())) {
5300    return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
5301                       N0.getOperand(0), N1);
5302  }
5303
5304  // fold (sext_in_reg (sext x)) -> (sext x)
5305  // fold (sext_in_reg (aext x)) -> (sext x)
5306  // if x is small enough.
5307  if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
5308    SDValue N00 = N0.getOperand(0);
5309    if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
5310        (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
5311      return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
5312  }
5313
5314  // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
5315  if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
5316    return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
5317
5318  // fold operands of sext_in_reg based on knowledge that the top bits are not
5319  // demanded.
5320  if (SimplifyDemandedBits(SDValue(N, 0)))
5321    return SDValue(N, 0);
5322
5323  // fold (sext_in_reg (load x)) -> (smaller sextload x)
5324  // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
5325  SDValue NarrowLoad = ReduceLoadWidth(N);
5326  if (NarrowLoad.getNode())
5327    return NarrowLoad;
5328
5329  // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
5330  // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
5331  // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
5332  if (N0.getOpcode() == ISD::SRL) {
5333    if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
5334      if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
5335        // We can turn this into an SRA iff the input to the SRL is already sign
5336        // extended enough.
5337        unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
5338        if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
5339          return DAG.getNode(ISD::SRA, SDLoc(N), VT,
5340                             N0.getOperand(0), N0.getOperand(1));
5341      }
5342  }
5343
5344  // fold (sext_inreg (extload x)) -> (sextload x)
5345  if (ISD::isEXTLoad(N0.getNode()) &&
5346      ISD::isUNINDEXEDLoad(N0.getNode()) &&
5347      EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5348      ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5349       TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
5350    LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5351    SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5352                                     LN0->getChain(),
5353                                     LN0->getBasePtr(), LN0->getPointerInfo(),
5354                                     EVT,
5355                                     LN0->isVolatile(), LN0->isNonTemporal(),
5356                                     LN0->getAlignment());
5357    CombineTo(N, ExtLoad);
5358    CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5359    AddToWorkList(ExtLoad.getNode());
5360    return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5361  }
5362  // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
5363  if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5364      N0.hasOneUse() &&
5365      EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5366      ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5367       TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
5368    LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5369    SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5370                                     LN0->getChain(),
5371                                     LN0->getBasePtr(), LN0->getPointerInfo(),
5372                                     EVT,
5373                                     LN0->isVolatile(), LN0->isNonTemporal(),
5374                                     LN0->getAlignment());
5375    CombineTo(N, ExtLoad);
5376    CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5377    return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5378  }
5379
5380  // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
5381  if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
5382    SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
5383                                       N0.getOperand(1), false);
5384    if (BSwap.getNode() != 0)
5385      return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
5386                         BSwap, N1);
5387  }
5388
5389  return SDValue();
5390}
5391
5392SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
5393  SDValue N0 = N->getOperand(0);
5394  EVT VT = N->getValueType(0);
5395  bool isLE = TLI.isLittleEndian();
5396
5397  // noop truncate
5398  if (N0.getValueType() == N->getValueType(0))
5399    return N0;
5400  // fold (truncate c1) -> c1
5401  if (isa<ConstantSDNode>(N0))
5402    return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
5403  // fold (truncate (truncate x)) -> (truncate x)
5404  if (N0.getOpcode() == ISD::TRUNCATE)
5405    return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
5406  // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
5407  if (N0.getOpcode() == ISD::ZERO_EXTEND ||
5408      N0.getOpcode() == ISD::SIGN_EXTEND ||
5409      N0.getOpcode() == ISD::ANY_EXTEND) {
5410    if (N0.getOperand(0).getValueType().bitsLT(VT))
5411      // if the source is smaller than the dest, we still need an extend
5412      return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5413                         N0.getOperand(0));
5414    if (N0.getOperand(0).getValueType().bitsGT(VT))
5415      // if the source is larger than the dest, than we just need the truncate
5416      return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
5417    // if the source and dest are the same type, we can drop both the extend
5418    // and the truncate.
5419    return N0.getOperand(0);
5420  }
5421
5422  // Fold extract-and-trunc into a narrow extract. For example:
5423  //   i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
5424  //   i32 y = TRUNCATE(i64 x)
5425  //        -- becomes --
5426  //   v16i8 b = BITCAST (v2i64 val)
5427  //   i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
5428  //
5429  // Note: We only run this optimization after type legalization (which often
5430  // creates this pattern) and before operation legalization after which
5431  // we need to be more careful about the vector instructions that we generate.
5432  if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5433      LegalTypes && !LegalOperations && N0->hasOneUse()) {
5434
5435    EVT VecTy = N0.getOperand(0).getValueType();
5436    EVT ExTy = N0.getValueType();
5437    EVT TrTy = N->getValueType(0);
5438
5439    unsigned NumElem = VecTy.getVectorNumElements();
5440    unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
5441
5442    EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
5443    assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
5444
5445    SDValue EltNo = N0->getOperand(1);
5446    if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
5447      int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
5448      EVT IndexTy = N0->getOperand(1).getValueType();
5449      int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
5450
5451      SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
5452                              NVT, N0.getOperand(0));
5453
5454      return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
5455                         SDLoc(N), TrTy, V,
5456                         DAG.getConstant(Index, IndexTy));
5457    }
5458  }
5459
5460  // Fold a series of buildvector, bitcast, and truncate if possible.
5461  // For example fold
5462  //   (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
5463  //   (2xi32 (buildvector x, y)).
5464  if (Level == AfterLegalizeVectorOps && VT.isVector() &&
5465      N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
5466      N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
5467      N0.getOperand(0).hasOneUse()) {
5468
5469    SDValue BuildVect = N0.getOperand(0);
5470    EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
5471    EVT TruncVecEltTy = VT.getVectorElementType();
5472
5473    // Check that the element types match.
5474    if (BuildVectEltTy == TruncVecEltTy) {
5475      // Now we only need to compute the offset of the truncated elements.
5476      unsigned BuildVecNumElts =  BuildVect.getNumOperands();
5477      unsigned TruncVecNumElts = VT.getVectorNumElements();
5478      unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
5479
5480      assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
5481             "Invalid number of elements");
5482
5483      SmallVector<SDValue, 8> Opnds;
5484      for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
5485        Opnds.push_back(BuildVect.getOperand(i));
5486
5487      return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, &Opnds[0],
5488                         Opnds.size());
5489    }
5490  }
5491
5492  // See if we can simplify the input to this truncate through knowledge that
5493  // only the low bits are being used.
5494  // For example "trunc (or (shl x, 8), y)" // -> trunc y
5495  // Currently we only perform this optimization on scalars because vectors
5496  // may have different active low bits.
5497  if (!VT.isVector()) {
5498    SDValue Shorter =
5499      GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
5500                                               VT.getSizeInBits()));
5501    if (Shorter.getNode())
5502      return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
5503  }
5504  // fold (truncate (load x)) -> (smaller load x)
5505  // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
5506  if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
5507    SDValue Reduced = ReduceLoadWidth(N);
5508    if (Reduced.getNode())
5509      return Reduced;
5510  }
5511  // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
5512  // where ... are all 'undef'.
5513  if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
5514    SmallVector<EVT, 8> VTs;
5515    SDValue V;
5516    unsigned Idx = 0;
5517    unsigned NumDefs = 0;
5518
5519    for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
5520      SDValue X = N0.getOperand(i);
5521      if (X.getOpcode() != ISD::UNDEF) {
5522        V = X;
5523        Idx = i;
5524        NumDefs++;
5525      }
5526      // Stop if more than one members are non-undef.
5527      if (NumDefs > 1)
5528        break;
5529      VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
5530                                     VT.getVectorElementType(),
5531                                     X.getValueType().getVectorNumElements()));
5532    }
5533
5534    if (NumDefs == 0)
5535      return DAG.getUNDEF(VT);
5536
5537    if (NumDefs == 1) {
5538      assert(V.getNode() && "The single defined operand is empty!");
5539      SmallVector<SDValue, 8> Opnds;
5540      for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
5541        if (i != Idx) {
5542          Opnds.push_back(DAG.getUNDEF(VTs[i]));
5543          continue;
5544        }
5545        SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
5546        AddToWorkList(NV.getNode());
5547        Opnds.push_back(NV);
5548      }
5549      return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
5550                         &Opnds[0], Opnds.size());
5551    }
5552  }
5553
5554  // Simplify the operands using demanded-bits information.
5555  if (!VT.isVector() &&
5556      SimplifyDemandedBits(SDValue(N, 0)))
5557    return SDValue(N, 0);
5558
5559  return SDValue();
5560}
5561
5562static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
5563  SDValue Elt = N->getOperand(i);
5564  if (Elt.getOpcode() != ISD::MERGE_VALUES)
5565    return Elt.getNode();
5566  return Elt.getOperand(Elt.getResNo()).getNode();
5567}
5568
5569/// CombineConsecutiveLoads - build_pair (load, load) -> load
5570/// if load locations are consecutive.
5571SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
5572  assert(N->getOpcode() == ISD::BUILD_PAIR);
5573
5574  LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
5575  LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
5576  if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
5577      LD1->getPointerInfo().getAddrSpace() !=
5578         LD2->getPointerInfo().getAddrSpace())
5579    return SDValue();
5580  EVT LD1VT = LD1->getValueType(0);
5581
5582  if (ISD::isNON_EXTLoad(LD2) &&
5583      LD2->hasOneUse() &&
5584      // If both are volatile this would reduce the number of volatile loads.
5585      // If one is volatile it might be ok, but play conservative and bail out.
5586      !LD1->isVolatile() &&
5587      !LD2->isVolatile() &&
5588      DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
5589    unsigned Align = LD1->getAlignment();
5590    unsigned NewAlign = TLI.getDataLayout()->
5591      getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
5592
5593    if (NewAlign <= Align &&
5594        (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
5595      return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
5596                         LD1->getBasePtr(), LD1->getPointerInfo(),
5597                         false, false, false, Align);
5598  }
5599
5600  return SDValue();
5601}
5602
5603SDValue DAGCombiner::visitBITCAST(SDNode *N) {
5604  SDValue N0 = N->getOperand(0);
5605  EVT VT = N->getValueType(0);
5606
5607  // If the input is a BUILD_VECTOR with all constant elements, fold this now.
5608  // Only do this before legalize, since afterward the target may be depending
5609  // on the bitconvert.
5610  // First check to see if this is all constant.
5611  if (!LegalTypes &&
5612      N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
5613      VT.isVector()) {
5614    bool isSimple = true;
5615    for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i)
5616      if (N0.getOperand(i).getOpcode() != ISD::UNDEF &&
5617          N0.getOperand(i).getOpcode() != ISD::Constant &&
5618          N0.getOperand(i).getOpcode() != ISD::ConstantFP) {
5619        isSimple = false;
5620        break;
5621      }
5622
5623    EVT DestEltVT = N->getValueType(0).getVectorElementType();
5624    assert(!DestEltVT.isVector() &&
5625           "Element type of vector ValueType must not be vector!");
5626    if (isSimple)
5627      return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
5628  }
5629
5630  // If the input is a constant, let getNode fold it.
5631  if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
5632    SDValue Res = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
5633    if (Res.getNode() != N) {
5634      if (!LegalOperations ||
5635          TLI.isOperationLegal(Res.getNode()->getOpcode(), VT))
5636        return Res;
5637
5638      // Folding it resulted in an illegal node, and it's too late to
5639      // do that. Clean up the old node and forego the transformation.
5640      // Ideally this won't happen very often, because instcombine
5641      // and the earlier dagcombine runs (where illegal nodes are
5642      // permitted) should have folded most of them already.
5643      DAG.DeleteNode(Res.getNode());
5644    }
5645  }
5646
5647  // (conv (conv x, t1), t2) -> (conv x, t2)
5648  if (N0.getOpcode() == ISD::BITCAST)
5649    return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
5650                       N0.getOperand(0));
5651
5652  // fold (conv (load x)) -> (load (conv*)x)
5653  // If the resultant load doesn't need a higher alignment than the original!
5654  if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
5655      // Do not change the width of a volatile load.
5656      !cast<LoadSDNode>(N0)->isVolatile() &&
5657      (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT))) {
5658    LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5659    unsigned Align = TLI.getDataLayout()->
5660      getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
5661    unsigned OrigAlign = LN0->getAlignment();
5662
5663    if (Align <= OrigAlign) {
5664      SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
5665                                 LN0->getBasePtr(), LN0->getPointerInfo(),
5666                                 LN0->isVolatile(), LN0->isNonTemporal(),
5667                                 LN0->isInvariant(), OrigAlign);
5668      AddToWorkList(N);
5669      CombineTo(N0.getNode(),
5670                DAG.getNode(ISD::BITCAST, SDLoc(N0),
5671                            N0.getValueType(), Load),
5672                Load.getValue(1));
5673      return Load;
5674    }
5675  }
5676
5677  // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
5678  // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
5679  // This often reduces constant pool loads.
5680  if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(VT)) ||
5681       (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(VT))) &&
5682      N0.getNode()->hasOneUse() && VT.isInteger() &&
5683      !VT.isVector() && !N0.getValueType().isVector()) {
5684    SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
5685                                  N0.getOperand(0));
5686    AddToWorkList(NewConv.getNode());
5687
5688    APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
5689    if (N0.getOpcode() == ISD::FNEG)
5690      return DAG.getNode(ISD::XOR, SDLoc(N), VT,
5691                         NewConv, DAG.getConstant(SignBit, VT));
5692    assert(N0.getOpcode() == ISD::FABS);
5693    return DAG.getNode(ISD::AND, SDLoc(N), VT,
5694                       NewConv, DAG.getConstant(~SignBit, VT));
5695  }
5696
5697  // fold (bitconvert (fcopysign cst, x)) ->
5698  //         (or (and (bitconvert x), sign), (and cst, (not sign)))
5699  // Note that we don't handle (copysign x, cst) because this can always be
5700  // folded to an fneg or fabs.
5701  if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
5702      isa<ConstantFPSDNode>(N0.getOperand(0)) &&
5703      VT.isInteger() && !VT.isVector()) {
5704    unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
5705    EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
5706    if (isTypeLegal(IntXVT)) {
5707      SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
5708                              IntXVT, N0.getOperand(1));
5709      AddToWorkList(X.getNode());
5710
5711      // If X has a different width than the result/lhs, sext it or truncate it.
5712      unsigned VTWidth = VT.getSizeInBits();
5713      if (OrigXWidth < VTWidth) {
5714        X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
5715        AddToWorkList(X.getNode());
5716      } else if (OrigXWidth > VTWidth) {
5717        // To get the sign bit in the right place, we have to shift it right
5718        // before truncating.
5719        X = DAG.getNode(ISD::SRL, SDLoc(X),
5720                        X.getValueType(), X,
5721                        DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
5722        AddToWorkList(X.getNode());
5723        X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
5724        AddToWorkList(X.getNode());
5725      }
5726
5727      APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
5728      X = DAG.getNode(ISD::AND, SDLoc(X), VT,
5729                      X, DAG.getConstant(SignBit, VT));
5730      AddToWorkList(X.getNode());
5731
5732      SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
5733                                VT, N0.getOperand(0));
5734      Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
5735                        Cst, DAG.getConstant(~SignBit, VT));
5736      AddToWorkList(Cst.getNode());
5737
5738      return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
5739    }
5740  }
5741
5742  // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
5743  if (N0.getOpcode() == ISD::BUILD_PAIR) {
5744    SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
5745    if (CombineLD.getNode())
5746      return CombineLD;
5747  }
5748
5749  return SDValue();
5750}
5751
5752SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
5753  EVT VT = N->getValueType(0);
5754  return CombineConsecutiveLoads(N, VT);
5755}
5756
5757/// ConstantFoldBITCASTofBUILD_VECTOR - We know that BV is a build_vector
5758/// node with Constant, ConstantFP or Undef operands.  DstEltVT indicates the
5759/// destination element value type.
5760SDValue DAGCombiner::
5761ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
5762  EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
5763
5764  // If this is already the right type, we're done.
5765  if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
5766
5767  unsigned SrcBitSize = SrcEltVT.getSizeInBits();
5768  unsigned DstBitSize = DstEltVT.getSizeInBits();
5769
5770  // If this is a conversion of N elements of one type to N elements of another
5771  // type, convert each element.  This handles FP<->INT cases.
5772  if (SrcBitSize == DstBitSize) {
5773    EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
5774                              BV->getValueType(0).getVectorNumElements());
5775
5776    // Due to the FP element handling below calling this routine recursively,
5777    // we can end up with a scalar-to-vector node here.
5778    if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
5779      return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
5780                         DAG.getNode(ISD::BITCAST, SDLoc(BV),
5781                                     DstEltVT, BV->getOperand(0)));
5782
5783    SmallVector<SDValue, 8> Ops;
5784    for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
5785      SDValue Op = BV->getOperand(i);
5786      // If the vector element type is not legal, the BUILD_VECTOR operands
5787      // are promoted and implicitly truncated.  Make that explicit here.
5788      if (Op.getValueType() != SrcEltVT)
5789        Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
5790      Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
5791                                DstEltVT, Op));
5792      AddToWorkList(Ops.back().getNode());
5793    }
5794    return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT,
5795                       &Ops[0], Ops.size());
5796  }
5797
5798  // Otherwise, we're growing or shrinking the elements.  To avoid having to
5799  // handle annoying details of growing/shrinking FP values, we convert them to
5800  // int first.
5801  if (SrcEltVT.isFloatingPoint()) {
5802    // Convert the input float vector to a int vector where the elements are the
5803    // same sizes.
5804    assert((SrcEltVT == MVT::f32 || SrcEltVT == MVT::f64) && "Unknown FP VT!");
5805    EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
5806    BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
5807    SrcEltVT = IntVT;
5808  }
5809
5810  // Now we know the input is an integer vector.  If the output is a FP type,
5811  // convert to integer first, then to FP of the right size.
5812  if (DstEltVT.isFloatingPoint()) {
5813    assert((DstEltVT == MVT::f32 || DstEltVT == MVT::f64) && "Unknown FP VT!");
5814    EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
5815    SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
5816
5817    // Next, convert to FP elements of the same size.
5818    return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
5819  }
5820
5821  // Okay, we know the src/dst types are both integers of differing types.
5822  // Handling growing first.
5823  assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
5824  if (SrcBitSize < DstBitSize) {
5825    unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
5826
5827    SmallVector<SDValue, 8> Ops;
5828    for (unsigned i = 0, e = BV->getNumOperands(); i != e;
5829         i += NumInputsPerOutput) {
5830      bool isLE = TLI.isLittleEndian();
5831      APInt NewBits = APInt(DstBitSize, 0);
5832      bool EltIsUndef = true;
5833      for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
5834        // Shift the previously computed bits over.
5835        NewBits <<= SrcBitSize;
5836        SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
5837        if (Op.getOpcode() == ISD::UNDEF) continue;
5838        EltIsUndef = false;
5839
5840        NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
5841                   zextOrTrunc(SrcBitSize).zext(DstBitSize);
5842      }
5843
5844      if (EltIsUndef)
5845        Ops.push_back(DAG.getUNDEF(DstEltVT));
5846      else
5847        Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
5848    }
5849
5850    EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
5851    return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT,
5852                       &Ops[0], Ops.size());
5853  }
5854
5855  // Finally, this must be the case where we are shrinking elements: each input
5856  // turns into multiple outputs.
5857  bool isS2V = ISD::isScalarToVector(BV);
5858  unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
5859  EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
5860                            NumOutputsPerInput*BV->getNumOperands());
5861  SmallVector<SDValue, 8> Ops;
5862
5863  for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
5864    if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
5865      for (unsigned j = 0; j != NumOutputsPerInput; ++j)
5866        Ops.push_back(DAG.getUNDEF(DstEltVT));
5867      continue;
5868    }
5869
5870    APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
5871                  getAPIntValue().zextOrTrunc(SrcBitSize);
5872
5873    for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
5874      APInt ThisVal = OpVal.trunc(DstBitSize);
5875      Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
5876      if (isS2V && i == 0 && j == 0 && ThisVal.zext(SrcBitSize) == OpVal)
5877        // Simply turn this into a SCALAR_TO_VECTOR of the new type.
5878        return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
5879                           Ops[0]);
5880      OpVal = OpVal.lshr(DstBitSize);
5881    }
5882
5883    // For big endian targets, swap the order of the pieces of each element.
5884    if (TLI.isBigEndian())
5885      std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
5886  }
5887
5888  return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT,
5889                     &Ops[0], Ops.size());
5890}
5891
5892SDValue DAGCombiner::visitFADD(SDNode *N) {
5893  SDValue N0 = N->getOperand(0);
5894  SDValue N1 = N->getOperand(1);
5895  ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
5896  ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
5897  EVT VT = N->getValueType(0);
5898
5899  // fold vector ops
5900  if (VT.isVector()) {
5901    SDValue FoldedVOp = SimplifyVBinOp(N);
5902    if (FoldedVOp.getNode()) return FoldedVOp;
5903  }
5904
5905  // fold (fadd c1, c2) -> c1 + c2
5906  if (N0CFP && N1CFP)
5907    return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N1);
5908  // canonicalize constant to RHS
5909  if (N0CFP && !N1CFP)
5910    return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N0);
5911  // fold (fadd A, 0) -> A
5912  if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
5913      N1CFP->getValueAPF().isZero())
5914    return N0;
5915  // fold (fadd A, (fneg B)) -> (fsub A, B)
5916  if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
5917    isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
5918    return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0,
5919                       GetNegatedExpression(N1, DAG, LegalOperations));
5920  // fold (fadd (fneg A), B) -> (fsub B, A)
5921  if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
5922    isNegatibleForFree(N0, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
5923    return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N1,
5924                       GetNegatedExpression(N0, DAG, LegalOperations));
5925
5926  // If allowed, fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
5927  if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
5928      N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
5929      isa<ConstantFPSDNode>(N0.getOperand(1)))
5930    return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0.getOperand(0),
5931                       DAG.getNode(ISD::FADD, SDLoc(N), VT,
5932                                   N0.getOperand(1), N1));
5933
5934  // No FP constant should be created after legalization as Instruction
5935  // Selection pass has hard time in dealing with FP constant.
5936  //
5937  // We don't need test this condition for transformation like following, as
5938  // the DAG being transformed implies it is legal to take FP constant as
5939  // operand.
5940  //
5941  //  (fadd (fmul c, x), x) -> (fmul c+1, x)
5942  //
5943  bool AllowNewFpConst = (Level < AfterLegalizeDAG);
5944
5945  // If allow, fold (fadd (fneg x), x) -> 0.0
5946  if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
5947      N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1) {
5948    return DAG.getConstantFP(0.0, VT);
5949  }
5950
5951    // If allow, fold (fadd x, (fneg x)) -> 0.0
5952  if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
5953      N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0) {
5954    return DAG.getConstantFP(0.0, VT);
5955  }
5956
5957  // In unsafe math mode, we can fold chains of FADD's of the same value
5958  // into multiplications.  This transform is not safe in general because
5959  // we are reducing the number of rounding steps.
5960  if (DAG.getTarget().Options.UnsafeFPMath &&
5961      TLI.isOperationLegalOrCustom(ISD::FMUL, VT) &&
5962      !N0CFP && !N1CFP) {
5963    if (N0.getOpcode() == ISD::FMUL) {
5964      ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
5965      ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
5966
5967      // (fadd (fmul c, x), x) -> (fmul x, c+1)
5968      if (CFP00 && !CFP01 && N0.getOperand(1) == N1) {
5969        SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
5970                                     SDValue(CFP00, 0),
5971                                     DAG.getConstantFP(1.0, VT));
5972        return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
5973                           N1, NewCFP);
5974      }
5975
5976      // (fadd (fmul x, c), x) -> (fmul x, c+1)
5977      if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
5978        SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
5979                                     SDValue(CFP01, 0),
5980                                     DAG.getConstantFP(1.0, VT));
5981        return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
5982                           N1, NewCFP);
5983      }
5984
5985      // (fadd (fmul c, x), (fadd x, x)) -> (fmul x, c+2)
5986      if (CFP00 && !CFP01 && N1.getOpcode() == ISD::FADD &&
5987          N1.getOperand(0) == N1.getOperand(1) &&
5988          N0.getOperand(1) == N1.getOperand(0)) {
5989        SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
5990                                     SDValue(CFP00, 0),
5991                                     DAG.getConstantFP(2.0, VT));
5992        return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
5993                           N0.getOperand(1), NewCFP);
5994      }
5995
5996      // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
5997      if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
5998          N1.getOperand(0) == N1.getOperand(1) &&
5999          N0.getOperand(0) == N1.getOperand(0)) {
6000        SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6001                                     SDValue(CFP01, 0),
6002                                     DAG.getConstantFP(2.0, VT));
6003        return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6004                           N0.getOperand(0), NewCFP);
6005      }
6006    }
6007
6008    if (N1.getOpcode() == ISD::FMUL) {
6009      ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6010      ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
6011
6012      // (fadd x, (fmul c, x)) -> (fmul x, c+1)
6013      if (CFP10 && !CFP11 && N1.getOperand(1) == N0) {
6014        SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6015                                     SDValue(CFP10, 0),
6016                                     DAG.getConstantFP(1.0, VT));
6017        return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6018                           N0, NewCFP);
6019      }
6020
6021      // (fadd x, (fmul x, c)) -> (fmul x, c+1)
6022      if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
6023        SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6024                                     SDValue(CFP11, 0),
6025                                     DAG.getConstantFP(1.0, VT));
6026        return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6027                           N0, NewCFP);
6028      }
6029
6030
6031      // (fadd (fadd x, x), (fmul c, x)) -> (fmul x, c+2)
6032      if (CFP10 && !CFP11 && N0.getOpcode() == ISD::FADD &&
6033          N0.getOperand(0) == N0.getOperand(1) &&
6034          N1.getOperand(1) == N0.getOperand(0)) {
6035        SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6036                                     SDValue(CFP10, 0),
6037                                     DAG.getConstantFP(2.0, VT));
6038        return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6039                           N1.getOperand(1), NewCFP);
6040      }
6041
6042      // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
6043      if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
6044          N0.getOperand(0) == N0.getOperand(1) &&
6045          N1.getOperand(0) == N0.getOperand(0)) {
6046        SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6047                                     SDValue(CFP11, 0),
6048                                     DAG.getConstantFP(2.0, VT));
6049        return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6050                           N1.getOperand(0), NewCFP);
6051      }
6052    }
6053
6054    if (N0.getOpcode() == ISD::FADD && AllowNewFpConst) {
6055      ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6056      // (fadd (fadd x, x), x) -> (fmul x, 3.0)
6057      if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
6058          (N0.getOperand(0) == N1)) {
6059        return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6060                           N1, DAG.getConstantFP(3.0, VT));
6061      }
6062    }
6063
6064    if (N1.getOpcode() == ISD::FADD && AllowNewFpConst) {
6065      ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6066      // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
6067      if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
6068          N1.getOperand(0) == N0) {
6069        return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6070                           N0, DAG.getConstantFP(3.0, VT));
6071      }
6072    }
6073
6074    // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
6075    if (AllowNewFpConst &&
6076        N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
6077        N0.getOperand(0) == N0.getOperand(1) &&
6078        N1.getOperand(0) == N1.getOperand(1) &&
6079        N0.getOperand(0) == N1.getOperand(0)) {
6080      return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6081                         N0.getOperand(0),
6082                         DAG.getConstantFP(4.0, VT));
6083    }
6084  }
6085
6086  // FADD -> FMA combines:
6087  if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
6088       DAG.getTarget().Options.UnsafeFPMath) &&
6089      DAG.getTarget().getTargetLowering()->isFMAFasterThanMulAndAdd(VT) &&
6090      TLI.isOperationLegalOrCustom(ISD::FMA, VT)) {
6091
6092    // fold (fadd (fmul x, y), z) -> (fma x, y, z)
6093    if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse()) {
6094      return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6095                         N0.getOperand(0), N0.getOperand(1), N1);
6096    }
6097
6098    // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
6099    // Note: Commutes FADD operands.
6100    if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse()) {
6101      return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6102                         N1.getOperand(0), N1.getOperand(1), N0);
6103    }
6104  }
6105
6106  return SDValue();
6107}
6108
6109SDValue DAGCombiner::visitFSUB(SDNode *N) {
6110  SDValue N0 = N->getOperand(0);
6111  SDValue N1 = N->getOperand(1);
6112  ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6113  ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6114  EVT VT = N->getValueType(0);
6115  SDLoc dl(N);
6116
6117  // fold vector ops
6118  if (VT.isVector()) {
6119    SDValue FoldedVOp = SimplifyVBinOp(N);
6120    if (FoldedVOp.getNode()) return FoldedVOp;
6121  }
6122
6123  // fold (fsub c1, c2) -> c1-c2
6124  if (N0CFP && N1CFP)
6125    return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0, N1);
6126  // fold (fsub A, 0) -> A
6127  if (DAG.getTarget().Options.UnsafeFPMath &&
6128      N1CFP && N1CFP->getValueAPF().isZero())
6129    return N0;
6130  // fold (fsub 0, B) -> -B
6131  if (DAG.getTarget().Options.UnsafeFPMath &&
6132      N0CFP && N0CFP->getValueAPF().isZero()) {
6133    if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
6134      return GetNegatedExpression(N1, DAG, LegalOperations);
6135    if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6136      return DAG.getNode(ISD::FNEG, dl, VT, N1);
6137  }
6138  // fold (fsub A, (fneg B)) -> (fadd A, B)
6139  if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
6140    return DAG.getNode(ISD::FADD, dl, VT, N0,
6141                       GetNegatedExpression(N1, DAG, LegalOperations));
6142
6143  // If 'unsafe math' is enabled, fold
6144  //    (fsub x, x) -> 0.0 &
6145  //    (fsub x, (fadd x, y)) -> (fneg y) &
6146  //    (fsub x, (fadd y, x)) -> (fneg y)
6147  if (DAG.getTarget().Options.UnsafeFPMath) {
6148    if (N0 == N1)
6149      return DAG.getConstantFP(0.0f, VT);
6150
6151    if (N1.getOpcode() == ISD::FADD) {
6152      SDValue N10 = N1->getOperand(0);
6153      SDValue N11 = N1->getOperand(1);
6154
6155      if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI,
6156                                          &DAG.getTarget().Options))
6157        return GetNegatedExpression(N11, DAG, LegalOperations);
6158      else if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI,
6159                                               &DAG.getTarget().Options))
6160        return GetNegatedExpression(N10, DAG, LegalOperations);
6161    }
6162  }
6163
6164  // FSUB -> FMA combines:
6165  if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
6166       DAG.getTarget().Options.UnsafeFPMath) &&
6167      DAG.getTarget().getTargetLowering()->isFMAFasterThanMulAndAdd(VT) &&
6168      TLI.isOperationLegalOrCustom(ISD::FMA, VT)) {
6169
6170    // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
6171    if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse()) {
6172      return DAG.getNode(ISD::FMA, dl, VT,
6173                         N0.getOperand(0), N0.getOperand(1),
6174                         DAG.getNode(ISD::FNEG, dl, VT, N1));
6175    }
6176
6177    // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
6178    // Note: Commutes FSUB operands.
6179    if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse()) {
6180      return DAG.getNode(ISD::FMA, dl, VT,
6181                         DAG.getNode(ISD::FNEG, dl, VT,
6182                         N1.getOperand(0)),
6183                         N1.getOperand(1), N0);
6184    }
6185
6186    // fold (fsub (-(fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
6187    if (N0.getOpcode() == ISD::FNEG &&
6188        N0.getOperand(0).getOpcode() == ISD::FMUL &&
6189        N0->hasOneUse() && N0.getOperand(0).hasOneUse()) {
6190      SDValue N00 = N0.getOperand(0).getOperand(0);
6191      SDValue N01 = N0.getOperand(0).getOperand(1);
6192      return DAG.getNode(ISD::FMA, dl, VT,
6193                         DAG.getNode(ISD::FNEG, dl, VT, N00), N01,
6194                         DAG.getNode(ISD::FNEG, dl, VT, N1));
6195    }
6196  }
6197
6198  return SDValue();
6199}
6200
6201SDValue DAGCombiner::visitFMUL(SDNode *N) {
6202  SDValue N0 = N->getOperand(0);
6203  SDValue N1 = N->getOperand(1);
6204  ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6205  ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6206  EVT VT = N->getValueType(0);
6207  const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6208
6209  // fold vector ops
6210  if (VT.isVector()) {
6211    SDValue FoldedVOp = SimplifyVBinOp(N);
6212    if (FoldedVOp.getNode()) return FoldedVOp;
6213  }
6214
6215  // fold (fmul c1, c2) -> c1*c2
6216  if (N0CFP && N1CFP)
6217    return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, N1);
6218  // canonicalize constant to RHS
6219  if (N0CFP && !N1CFP)
6220    return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, N0);
6221  // fold (fmul A, 0) -> 0
6222  if (DAG.getTarget().Options.UnsafeFPMath &&
6223      N1CFP && N1CFP->getValueAPF().isZero())
6224    return N1;
6225  // fold (fmul A, 0) -> 0, vector edition.
6226  if (DAG.getTarget().Options.UnsafeFPMath &&
6227      ISD::isBuildVectorAllZeros(N1.getNode()))
6228    return N1;
6229  // fold (fmul A, 1.0) -> A
6230  if (N1CFP && N1CFP->isExactlyValue(1.0))
6231    return N0;
6232  // fold (fmul X, 2.0) -> (fadd X, X)
6233  if (N1CFP && N1CFP->isExactlyValue(+2.0))
6234    return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N0);
6235  // fold (fmul X, -1.0) -> (fneg X)
6236  if (N1CFP && N1CFP->isExactlyValue(-1.0))
6237    if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6238      return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
6239
6240  // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
6241  if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
6242                                       &DAG.getTarget().Options)) {
6243    if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
6244                                         &DAG.getTarget().Options)) {
6245      // Both can be negated for free, check to see if at least one is cheaper
6246      // negated.
6247      if (LHSNeg == 2 || RHSNeg == 2)
6248        return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6249                           GetNegatedExpression(N0, DAG, LegalOperations),
6250                           GetNegatedExpression(N1, DAG, LegalOperations));
6251    }
6252  }
6253
6254  // If allowed, fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
6255  if (DAG.getTarget().Options.UnsafeFPMath &&
6256      N1CFP && N0.getOpcode() == ISD::FMUL &&
6257      N0.getNode()->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1)))
6258    return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
6259                       DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6260                                   N0.getOperand(1), N1));
6261
6262  return SDValue();
6263}
6264
6265SDValue DAGCombiner::visitFMA(SDNode *N) {
6266  SDValue N0 = N->getOperand(0);
6267  SDValue N1 = N->getOperand(1);
6268  SDValue N2 = N->getOperand(2);
6269  ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6270  ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6271  EVT VT = N->getValueType(0);
6272  SDLoc dl(N);
6273
6274  if (DAG.getTarget().Options.UnsafeFPMath) {
6275    if (N0CFP && N0CFP->isZero())
6276      return N2;
6277    if (N1CFP && N1CFP->isZero())
6278      return N2;
6279  }
6280  if (N0CFP && N0CFP->isExactlyValue(1.0))
6281    return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
6282  if (N1CFP && N1CFP->isExactlyValue(1.0))
6283    return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
6284
6285  // Canonicalize (fma c, x, y) -> (fma x, c, y)
6286  if (N0CFP && !N1CFP)
6287    return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
6288
6289  // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
6290  if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6291      N2.getOpcode() == ISD::FMUL &&
6292      N0 == N2.getOperand(0) &&
6293      N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
6294    return DAG.getNode(ISD::FMUL, dl, VT, N0,
6295                       DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
6296  }
6297
6298
6299  // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
6300  if (DAG.getTarget().Options.UnsafeFPMath &&
6301      N0.getOpcode() == ISD::FMUL && N1CFP &&
6302      N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
6303    return DAG.getNode(ISD::FMA, dl, VT,
6304                       N0.getOperand(0),
6305                       DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
6306                       N2);
6307  }
6308
6309  // (fma x, 1, y) -> (fadd x, y)
6310  // (fma x, -1, y) -> (fadd (fneg x), y)
6311  if (N1CFP) {
6312    if (N1CFP->isExactlyValue(1.0))
6313      return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
6314
6315    if (N1CFP->isExactlyValue(-1.0) &&
6316        (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
6317      SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
6318      AddToWorkList(RHSNeg.getNode());
6319      return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
6320    }
6321  }
6322
6323  // (fma x, c, x) -> (fmul x, (c+1))
6324  if (DAG.getTarget().Options.UnsafeFPMath && N1CFP && N0 == N2) {
6325    return DAG.getNode(ISD::FMUL, dl, VT,
6326                       N0,
6327                       DAG.getNode(ISD::FADD, dl, VT,
6328                                   N1, DAG.getConstantFP(1.0, VT)));
6329  }
6330
6331  // (fma x, c, (fneg x)) -> (fmul x, (c-1))
6332  if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6333      N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0) {
6334    return DAG.getNode(ISD::FMUL, dl, VT,
6335                       N0,
6336                       DAG.getNode(ISD::FADD, dl, VT,
6337                                   N1, DAG.getConstantFP(-1.0, VT)));
6338  }
6339
6340
6341  return SDValue();
6342}
6343
6344SDValue DAGCombiner::visitFDIV(SDNode *N) {
6345  SDValue N0 = N->getOperand(0);
6346  SDValue N1 = N->getOperand(1);
6347  ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6348  ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6349  EVT VT = N->getValueType(0);
6350  const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6351
6352  // fold vector ops
6353  if (VT.isVector()) {
6354    SDValue FoldedVOp = SimplifyVBinOp(N);
6355    if (FoldedVOp.getNode()) return FoldedVOp;
6356  }
6357
6358  // fold (fdiv c1, c2) -> c1/c2
6359  if (N0CFP && N1CFP)
6360    return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
6361
6362  // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
6363  if (N1CFP && DAG.getTarget().Options.UnsafeFPMath) {
6364    // Compute the reciprocal 1.0 / c2.
6365    APFloat N1APF = N1CFP->getValueAPF();
6366    APFloat Recip(N1APF.getSemantics(), 1); // 1.0
6367    APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
6368    // Only do the transform if the reciprocal is a legal fp immediate that
6369    // isn't too nasty (eg NaN, denormal, ...).
6370    if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
6371        (!LegalOperations ||
6372         // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
6373         // backend)... we should handle this gracefully after Legalize.
6374         // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
6375         TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
6376         TLI.isFPImmLegal(Recip, VT)))
6377      return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0,
6378                         DAG.getConstantFP(Recip, VT));
6379  }
6380
6381  // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
6382  if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
6383                                       &DAG.getTarget().Options)) {
6384    if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
6385                                         &DAG.getTarget().Options)) {
6386      // Both can be negated for free, check to see if at least one is cheaper
6387      // negated.
6388      if (LHSNeg == 2 || RHSNeg == 2)
6389        return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
6390                           GetNegatedExpression(N0, DAG, LegalOperations),
6391                           GetNegatedExpression(N1, DAG, LegalOperations));
6392    }
6393  }
6394
6395  return SDValue();
6396}
6397
6398SDValue DAGCombiner::visitFREM(SDNode *N) {
6399  SDValue N0 = N->getOperand(0);
6400  SDValue N1 = N->getOperand(1);
6401  ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6402  ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6403  EVT VT = N->getValueType(0);
6404
6405  // fold (frem c1, c2) -> fmod(c1,c2)
6406  if (N0CFP && N1CFP)
6407    return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1);
6408
6409  return SDValue();
6410}
6411
6412SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
6413  SDValue N0 = N->getOperand(0);
6414  SDValue N1 = N->getOperand(1);
6415  ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6416  ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6417  EVT VT = N->getValueType(0);
6418
6419  if (N0CFP && N1CFP)  // Constant fold
6420    return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
6421
6422  if (N1CFP) {
6423    const APFloat& V = N1CFP->getValueAPF();
6424    // copysign(x, c1) -> fabs(x)       iff ispos(c1)
6425    // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
6426    if (!V.isNegative()) {
6427      if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
6428        return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
6429    } else {
6430      if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6431        return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
6432                           DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
6433    }
6434  }
6435
6436  // copysign(fabs(x), y) -> copysign(x, y)
6437  // copysign(fneg(x), y) -> copysign(x, y)
6438  // copysign(copysign(x,z), y) -> copysign(x, y)
6439  if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
6440      N0.getOpcode() == ISD::FCOPYSIGN)
6441    return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
6442                       N0.getOperand(0), N1);
6443
6444  // copysign(x, abs(y)) -> abs(x)
6445  if (N1.getOpcode() == ISD::FABS)
6446    return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
6447
6448  // copysign(x, copysign(y,z)) -> copysign(x, z)
6449  if (N1.getOpcode() == ISD::FCOPYSIGN)
6450    return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
6451                       N0, N1.getOperand(1));
6452
6453  // copysign(x, fp_extend(y)) -> copysign(x, y)
6454  // copysign(x, fp_round(y)) -> copysign(x, y)
6455  if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
6456    return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
6457                       N0, N1.getOperand(0));
6458
6459  return SDValue();
6460}
6461
6462SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
6463  SDValue N0 = N->getOperand(0);
6464  ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
6465  EVT VT = N->getValueType(0);
6466  EVT OpVT = N0.getValueType();
6467
6468  // fold (sint_to_fp c1) -> c1fp
6469  if (N0C &&
6470      // ...but only if the target supports immediate floating-point values
6471      (!LegalOperations ||
6472       TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
6473    return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
6474
6475  // If the input is a legal type, and SINT_TO_FP is not legal on this target,
6476  // but UINT_TO_FP is legal on this target, try to convert.
6477  if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
6478      TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
6479    // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
6480    if (DAG.SignBitIsZero(N0))
6481      return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
6482  }
6483
6484  // The next optimizations are desireable only if SELECT_CC can be lowered.
6485  // Check against MVT::Other for SELECT_CC, which is a workaround for targets
6486  // having to say they don't support SELECT_CC on every type the DAG knows
6487  // about, since there is no way to mark an opcode illegal at all value types
6488  // (See also visitSELECT)
6489  if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other)) {
6490    // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
6491    if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
6492        !VT.isVector() &&
6493        (!LegalOperations ||
6494         TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
6495      SDValue Ops[] =
6496        { N0.getOperand(0), N0.getOperand(1),
6497          DAG.getConstantFP(-1.0, VT) , DAG.getConstantFP(0.0, VT),
6498          N0.getOperand(2) };
6499      return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops, 5);
6500    }
6501
6502    // fold (sint_to_fp (zext (setcc x, y, cc))) ->
6503    //      (select_cc x, y, 1.0, 0.0,, cc)
6504    if (N0.getOpcode() == ISD::ZERO_EXTEND &&
6505        N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
6506        (!LegalOperations ||
6507         TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
6508      SDValue Ops[] =
6509        { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
6510          DAG.getConstantFP(1.0, VT) , DAG.getConstantFP(0.0, VT),
6511          N0.getOperand(0).getOperand(2) };
6512      return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops, 5);
6513    }
6514  }
6515
6516  return SDValue();
6517}
6518
6519SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
6520  SDValue N0 = N->getOperand(0);
6521  ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
6522  EVT VT = N->getValueType(0);
6523  EVT OpVT = N0.getValueType();
6524
6525  // fold (uint_to_fp c1) -> c1fp
6526  if (N0C &&
6527      // ...but only if the target supports immediate floating-point values
6528      (!LegalOperations ||
6529       TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
6530    return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
6531
6532  // If the input is a legal type, and UINT_TO_FP is not legal on this target,
6533  // but SINT_TO_FP is legal on this target, try to convert.
6534  if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
6535      TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
6536    // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
6537    if (DAG.SignBitIsZero(N0))
6538      return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
6539  }
6540
6541  // The next optimizations are desireable only if SELECT_CC can be lowered.
6542  // Check against MVT::Other for SELECT_CC, which is a workaround for targets
6543  // having to say they don't support SELECT_CC on every type the DAG knows
6544  // about, since there is no way to mark an opcode illegal at all value types
6545  // (See also visitSELECT)
6546  if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other)) {
6547    // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
6548
6549    if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
6550        (!LegalOperations ||
6551         TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
6552      SDValue Ops[] =
6553        { N0.getOperand(0), N0.getOperand(1),
6554          DAG.getConstantFP(1.0, VT),  DAG.getConstantFP(0.0, VT),
6555          N0.getOperand(2) };
6556      return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops, 5);
6557    }
6558  }
6559
6560  return SDValue();
6561}
6562
6563SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
6564  SDValue N0 = N->getOperand(0);
6565  ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6566  EVT VT = N->getValueType(0);
6567
6568  // fold (fp_to_sint c1fp) -> c1
6569  if (N0CFP)
6570    return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
6571
6572  return SDValue();
6573}
6574
6575SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
6576  SDValue N0 = N->getOperand(0);
6577  ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6578  EVT VT = N->getValueType(0);
6579
6580  // fold (fp_to_uint c1fp) -> c1
6581  if (N0CFP)
6582    return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
6583
6584  return SDValue();
6585}
6586
6587SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
6588  SDValue N0 = N->getOperand(0);
6589  SDValue N1 = N->getOperand(1);
6590  ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6591  EVT VT = N->getValueType(0);
6592
6593  // fold (fp_round c1fp) -> c1fp
6594  if (N0CFP)
6595    return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
6596
6597  // fold (fp_round (fp_extend x)) -> x
6598  if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
6599    return N0.getOperand(0);
6600
6601  // fold (fp_round (fp_round x)) -> (fp_round x)
6602  if (N0.getOpcode() == ISD::FP_ROUND) {
6603    // This is a value preserving truncation if both round's are.
6604    bool IsTrunc = N->getConstantOperandVal(1) == 1 &&
6605                   N0.getNode()->getConstantOperandVal(1) == 1;
6606    return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0.getOperand(0),
6607                       DAG.getIntPtrConstant(IsTrunc));
6608  }
6609
6610  // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
6611  if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
6612    SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
6613                              N0.getOperand(0), N1);
6614    AddToWorkList(Tmp.getNode());
6615    return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
6616                       Tmp, N0.getOperand(1));
6617  }
6618
6619  return SDValue();
6620}
6621
6622SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
6623  SDValue N0 = N->getOperand(0);
6624  EVT VT = N->getValueType(0);
6625  EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
6626  ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6627
6628  // fold (fp_round_inreg c1fp) -> c1fp
6629  if (N0CFP && isTypeLegal(EVT)) {
6630    SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT);
6631    return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, Round);
6632  }
6633
6634  return SDValue();
6635}
6636
6637SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
6638  SDValue N0 = N->getOperand(0);
6639  ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6640  EVT VT = N->getValueType(0);
6641
6642  // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
6643  if (N->hasOneUse() &&
6644      N->use_begin()->getOpcode() == ISD::FP_ROUND)
6645    return SDValue();
6646
6647  // fold (fp_extend c1fp) -> c1fp
6648  if (N0CFP)
6649    return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
6650
6651  // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
6652  // value of X.
6653  if (N0.getOpcode() == ISD::FP_ROUND
6654      && N0.getNode()->getConstantOperandVal(1) == 1) {
6655    SDValue In = N0.getOperand(0);
6656    if (In.getValueType() == VT) return In;
6657    if (VT.bitsLT(In.getValueType()))
6658      return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
6659                         In, N0.getOperand(1));
6660    return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
6661  }
6662
6663  // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
6664  if (ISD::isNON_EXTLoad(N0.getNode()) && N0.hasOneUse() &&
6665      ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6666       TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
6667    LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6668    SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
6669                                     LN0->getChain(),
6670                                     LN0->getBasePtr(), LN0->getPointerInfo(),
6671                                     N0.getValueType(),
6672                                     LN0->isVolatile(), LN0->isNonTemporal(),
6673                                     LN0->getAlignment());
6674    CombineTo(N, ExtLoad);
6675    CombineTo(N0.getNode(),
6676              DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
6677                          N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)),
6678              ExtLoad.getValue(1));
6679    return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6680  }
6681
6682  return SDValue();
6683}
6684
6685SDValue DAGCombiner::visitFNEG(SDNode *N) {
6686  SDValue N0 = N->getOperand(0);
6687  EVT VT = N->getValueType(0);
6688
6689  if (VT.isVector()) {
6690    SDValue FoldedVOp = SimplifyVUnaryOp(N);
6691    if (FoldedVOp.getNode()) return FoldedVOp;
6692  }
6693
6694  if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
6695                         &DAG.getTarget().Options))
6696    return GetNegatedExpression(N0, DAG, LegalOperations);
6697
6698  // Transform fneg(bitconvert(x)) -> bitconvert(x^sign) to avoid loading
6699  // constant pool values.
6700  if (!TLI.isFNegFree(VT) && N0.getOpcode() == ISD::BITCAST &&
6701      !VT.isVector() &&
6702      N0.getNode()->hasOneUse() &&
6703      N0.getOperand(0).getValueType().isInteger()) {
6704    SDValue Int = N0.getOperand(0);
6705    EVT IntVT = Int.getValueType();
6706    if (IntVT.isInteger() && !IntVT.isVector()) {
6707      Int = DAG.getNode(ISD::XOR, SDLoc(N0), IntVT, Int,
6708              DAG.getConstant(APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
6709      AddToWorkList(Int.getNode());
6710      return DAG.getNode(ISD::BITCAST, SDLoc(N),
6711                         VT, Int);
6712    }
6713  }
6714
6715  // (fneg (fmul c, x)) -> (fmul -c, x)
6716  if (N0.getOpcode() == ISD::FMUL) {
6717    ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
6718    if (CFP1) {
6719      return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6720                         N0.getOperand(0),
6721                         DAG.getNode(ISD::FNEG, SDLoc(N), VT,
6722                                     N0.getOperand(1)));
6723    }
6724  }
6725
6726  return SDValue();
6727}
6728
6729SDValue DAGCombiner::visitFCEIL(SDNode *N) {
6730  SDValue N0 = N->getOperand(0);
6731  ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6732  EVT VT = N->getValueType(0);
6733
6734  // fold (fceil c1) -> fceil(c1)
6735  if (N0CFP)
6736    return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
6737
6738  return SDValue();
6739}
6740
6741SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
6742  SDValue N0 = N->getOperand(0);
6743  ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6744  EVT VT = N->getValueType(0);
6745
6746  // fold (ftrunc c1) -> ftrunc(c1)
6747  if (N0CFP)
6748    return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
6749
6750  return SDValue();
6751}
6752
6753SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
6754  SDValue N0 = N->getOperand(0);
6755  ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6756  EVT VT = N->getValueType(0);
6757
6758  // fold (ffloor c1) -> ffloor(c1)
6759  if (N0CFP)
6760    return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
6761
6762  return SDValue();
6763}
6764
6765SDValue DAGCombiner::visitFABS(SDNode *N) {
6766  SDValue N0 = N->getOperand(0);
6767  ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6768  EVT VT = N->getValueType(0);
6769
6770  if (VT.isVector()) {
6771    SDValue FoldedVOp = SimplifyVUnaryOp(N);
6772    if (FoldedVOp.getNode()) return FoldedVOp;
6773  }
6774
6775  // fold (fabs c1) -> fabs(c1)
6776  if (N0CFP)
6777    return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
6778  // fold (fabs (fabs x)) -> (fabs x)
6779  if (N0.getOpcode() == ISD::FABS)
6780    return N->getOperand(0);
6781  // fold (fabs (fneg x)) -> (fabs x)
6782  // fold (fabs (fcopysign x, y)) -> (fabs x)
6783  if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
6784    return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
6785
6786  // Transform fabs(bitconvert(x)) -> bitconvert(x&~sign) to avoid loading
6787  // constant pool values.
6788  if (!TLI.isFAbsFree(VT) &&
6789      N0.getOpcode() == ISD::BITCAST && N0.getNode()->hasOneUse() &&
6790      N0.getOperand(0).getValueType().isInteger() &&
6791      !N0.getOperand(0).getValueType().isVector()) {
6792    SDValue Int = N0.getOperand(0);
6793    EVT IntVT = Int.getValueType();
6794    if (IntVT.isInteger() && !IntVT.isVector()) {
6795      Int = DAG.getNode(ISD::AND, SDLoc(N0), IntVT, Int,
6796             DAG.getConstant(~APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
6797      AddToWorkList(Int.getNode());
6798      return DAG.getNode(ISD::BITCAST, SDLoc(N),
6799                         N->getValueType(0), Int);
6800    }
6801  }
6802
6803  return SDValue();
6804}
6805
6806SDValue DAGCombiner::visitBRCOND(SDNode *N) {
6807  SDValue Chain = N->getOperand(0);
6808  SDValue N1 = N->getOperand(1);
6809  SDValue N2 = N->getOperand(2);
6810
6811  // If N is a constant we could fold this into a fallthrough or unconditional
6812  // branch. However that doesn't happen very often in normal code, because
6813  // Instcombine/SimplifyCFG should have handled the available opportunities.
6814  // If we did this folding here, it would be necessary to update the
6815  // MachineBasicBlock CFG, which is awkward.
6816
6817  // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
6818  // on the target.
6819  if (N1.getOpcode() == ISD::SETCC &&
6820      TLI.isOperationLegalOrCustom(ISD::BR_CC,
6821                                   N1.getOperand(0).getValueType())) {
6822    return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
6823                       Chain, N1.getOperand(2),
6824                       N1.getOperand(0), N1.getOperand(1), N2);
6825  }
6826
6827  if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
6828      ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
6829       (N1.getOperand(0).hasOneUse() &&
6830        N1.getOperand(0).getOpcode() == ISD::SRL))) {
6831    SDNode *Trunc = 0;
6832    if (N1.getOpcode() == ISD::TRUNCATE) {
6833      // Look pass the truncate.
6834      Trunc = N1.getNode();
6835      N1 = N1.getOperand(0);
6836    }
6837
6838    // Match this pattern so that we can generate simpler code:
6839    //
6840    //   %a = ...
6841    //   %b = and i32 %a, 2
6842    //   %c = srl i32 %b, 1
6843    //   brcond i32 %c ...
6844    //
6845    // into
6846    //
6847    //   %a = ...
6848    //   %b = and i32 %a, 2
6849    //   %c = setcc eq %b, 0
6850    //   brcond %c ...
6851    //
6852    // This applies only when the AND constant value has one bit set and the
6853    // SRL constant is equal to the log2 of the AND constant. The back-end is
6854    // smart enough to convert the result into a TEST/JMP sequence.
6855    SDValue Op0 = N1.getOperand(0);
6856    SDValue Op1 = N1.getOperand(1);
6857
6858    if (Op0.getOpcode() == ISD::AND &&
6859        Op1.getOpcode() == ISD::Constant) {
6860      SDValue AndOp1 = Op0.getOperand(1);
6861
6862      if (AndOp1.getOpcode() == ISD::Constant) {
6863        const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
6864
6865        if (AndConst.isPowerOf2() &&
6866            cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
6867          SDValue SetCC =
6868            DAG.getSetCC(SDLoc(N),
6869                         getSetCCResultType(Op0.getValueType()),
6870                         Op0, DAG.getConstant(0, Op0.getValueType()),
6871                         ISD::SETNE);
6872
6873          SDValue NewBRCond = DAG.getNode(ISD::BRCOND, SDLoc(N),
6874                                          MVT::Other, Chain, SetCC, N2);
6875          // Don't add the new BRCond into the worklist or else SimplifySelectCC
6876          // will convert it back to (X & C1) >> C2.
6877          CombineTo(N, NewBRCond, false);
6878          // Truncate is dead.
6879          if (Trunc) {
6880            removeFromWorkList(Trunc);
6881            DAG.DeleteNode(Trunc);
6882          }
6883          // Replace the uses of SRL with SETCC
6884          WorkListRemover DeadNodes(*this);
6885          DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
6886          removeFromWorkList(N1.getNode());
6887          DAG.DeleteNode(N1.getNode());
6888          return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6889        }
6890      }
6891    }
6892
6893    if (Trunc)
6894      // Restore N1 if the above transformation doesn't match.
6895      N1 = N->getOperand(1);
6896  }
6897
6898  // Transform br(xor(x, y)) -> br(x != y)
6899  // Transform br(xor(xor(x,y), 1)) -> br (x == y)
6900  if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
6901    SDNode *TheXor = N1.getNode();
6902    SDValue Op0 = TheXor->getOperand(0);
6903    SDValue Op1 = TheXor->getOperand(1);
6904    if (Op0.getOpcode() == Op1.getOpcode()) {
6905      // Avoid missing important xor optimizations.
6906      SDValue Tmp = visitXOR(TheXor);
6907      if (Tmp.getNode()) {
6908        if (Tmp.getNode() != TheXor) {
6909          DEBUG(dbgs() << "\nReplacing.8 ";
6910                TheXor->dump(&DAG);
6911                dbgs() << "\nWith: ";
6912                Tmp.getNode()->dump(&DAG);
6913                dbgs() << '\n');
6914          WorkListRemover DeadNodes(*this);
6915          DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
6916          removeFromWorkList(TheXor);
6917          DAG.DeleteNode(TheXor);
6918          return DAG.getNode(ISD::BRCOND, SDLoc(N),
6919                             MVT::Other, Chain, Tmp, N2);
6920        }
6921
6922        // visitXOR has changed XOR's operands or replaced the XOR completely,
6923        // bail out.
6924        return SDValue(N, 0);
6925      }
6926    }
6927
6928    if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
6929      bool Equal = false;
6930      if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
6931        if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
6932            Op0.getOpcode() == ISD::XOR) {
6933          TheXor = Op0.getNode();
6934          Equal = true;
6935        }
6936
6937      EVT SetCCVT = N1.getValueType();
6938      if (LegalTypes)
6939        SetCCVT = getSetCCResultType(SetCCVT);
6940      SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
6941                                   SetCCVT,
6942                                   Op0, Op1,
6943                                   Equal ? ISD::SETEQ : ISD::SETNE);
6944      // Replace the uses of XOR with SETCC
6945      WorkListRemover DeadNodes(*this);
6946      DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
6947      removeFromWorkList(N1.getNode());
6948      DAG.DeleteNode(N1.getNode());
6949      return DAG.getNode(ISD::BRCOND, SDLoc(N),
6950                         MVT::Other, Chain, SetCC, N2);
6951    }
6952  }
6953
6954  return SDValue();
6955}
6956
6957// Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
6958//
6959SDValue DAGCombiner::visitBR_CC(SDNode *N) {
6960  CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
6961  SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
6962
6963  // If N is a constant we could fold this into a fallthrough or unconditional
6964  // branch. However that doesn't happen very often in normal code, because
6965  // Instcombine/SimplifyCFG should have handled the available opportunities.
6966  // If we did this folding here, it would be necessary to update the
6967  // MachineBasicBlock CFG, which is awkward.
6968
6969  // Use SimplifySetCC to simplify SETCC's.
6970  SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
6971                               CondLHS, CondRHS, CC->get(), SDLoc(N),
6972                               false);
6973  if (Simp.getNode()) AddToWorkList(Simp.getNode());
6974
6975  // fold to a simpler setcc
6976  if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
6977    return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
6978                       N->getOperand(0), Simp.getOperand(2),
6979                       Simp.getOperand(0), Simp.getOperand(1),
6980                       N->getOperand(4));
6981
6982  return SDValue();
6983}
6984
6985/// canFoldInAddressingMode - Return true if 'Use' is a load or a store that
6986/// uses N as its base pointer and that N may be folded in the load / store
6987/// addressing mode.
6988static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
6989                                    SelectionDAG &DAG,
6990                                    const TargetLowering &TLI) {
6991  EVT VT;
6992  if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(Use)) {
6993    if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
6994      return false;
6995    VT = Use->getValueType(0);
6996  } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(Use)) {
6997    if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
6998      return false;
6999    VT = ST->getValue().getValueType();
7000  } else
7001    return false;
7002
7003  TargetLowering::AddrMode AM;
7004  if (N->getOpcode() == ISD::ADD) {
7005    ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7006    if (Offset)
7007      // [reg +/- imm]
7008      AM.BaseOffs = Offset->getSExtValue();
7009    else
7010      // [reg +/- reg]
7011      AM.Scale = 1;
7012  } else if (N->getOpcode() == ISD::SUB) {
7013    ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7014    if (Offset)
7015      // [reg +/- imm]
7016      AM.BaseOffs = -Offset->getSExtValue();
7017    else
7018      // [reg +/- reg]
7019      AM.Scale = 1;
7020  } else
7021    return false;
7022
7023  return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()));
7024}
7025
7026/// CombineToPreIndexedLoadStore - Try turning a load / store into a
7027/// pre-indexed load / store when the base pointer is an add or subtract
7028/// and it has other uses besides the load / store. After the
7029/// transformation, the new indexed load / store has effectively folded
7030/// the add / subtract in and all of its other uses are redirected to the
7031/// new load / store.
7032bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
7033  if (Level < AfterLegalizeDAG)
7034    return false;
7035
7036  bool isLoad = true;
7037  SDValue Ptr;
7038  EVT VT;
7039  if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
7040    if (LD->isIndexed())
7041      return false;
7042    VT = LD->getMemoryVT();
7043    if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
7044        !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
7045      return false;
7046    Ptr = LD->getBasePtr();
7047  } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
7048    if (ST->isIndexed())
7049      return false;
7050    VT = ST->getMemoryVT();
7051    if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
7052        !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
7053      return false;
7054    Ptr = ST->getBasePtr();
7055    isLoad = false;
7056  } else {
7057    return false;
7058  }
7059
7060  // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
7061  // out.  There is no reason to make this a preinc/predec.
7062  if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
7063      Ptr.getNode()->hasOneUse())
7064    return false;
7065
7066  // Ask the target to do addressing mode selection.
7067  SDValue BasePtr;
7068  SDValue Offset;
7069  ISD::MemIndexedMode AM = ISD::UNINDEXED;
7070  if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
7071    return false;
7072
7073  // Backends without true r+i pre-indexed forms may need to pass a
7074  // constant base with a variable offset so that constant coercion
7075  // will work with the patterns in canonical form.
7076  bool Swapped = false;
7077  if (isa<ConstantSDNode>(BasePtr)) {
7078    std::swap(BasePtr, Offset);
7079    Swapped = true;
7080  }
7081
7082  // Don't create a indexed load / store with zero offset.
7083  if (isa<ConstantSDNode>(Offset) &&
7084      cast<ConstantSDNode>(Offset)->isNullValue())
7085    return false;
7086
7087  // Try turning it into a pre-indexed load / store except when:
7088  // 1) The new base ptr is a frame index.
7089  // 2) If N is a store and the new base ptr is either the same as or is a
7090  //    predecessor of the value being stored.
7091  // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
7092  //    that would create a cycle.
7093  // 4) All uses are load / store ops that use it as old base ptr.
7094
7095  // Check #1.  Preinc'ing a frame index would require copying the stack pointer
7096  // (plus the implicit offset) to a register to preinc anyway.
7097  if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7098    return false;
7099
7100  // Check #2.
7101  if (!isLoad) {
7102    SDValue Val = cast<StoreSDNode>(N)->getValue();
7103    if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
7104      return false;
7105  }
7106
7107  // If the offset is a constant, there may be other adds of constants that
7108  // can be folded with this one. We should do this to avoid having to keep
7109  // a copy of the original base pointer.
7110  SmallVector<SDNode *, 16> OtherUses;
7111  if (isa<ConstantSDNode>(Offset))
7112    for (SDNode::use_iterator I = BasePtr.getNode()->use_begin(),
7113         E = BasePtr.getNode()->use_end(); I != E; ++I) {
7114      SDNode *Use = *I;
7115      if (Use == Ptr.getNode())
7116        continue;
7117
7118      if (Use->isPredecessorOf(N))
7119        continue;
7120
7121      if (Use->getOpcode() != ISD::ADD && Use->getOpcode() != ISD::SUB) {
7122        OtherUses.clear();
7123        break;
7124      }
7125
7126      SDValue Op0 = Use->getOperand(0), Op1 = Use->getOperand(1);
7127      if (Op1.getNode() == BasePtr.getNode())
7128        std::swap(Op0, Op1);
7129      assert(Op0.getNode() == BasePtr.getNode() &&
7130             "Use of ADD/SUB but not an operand");
7131
7132      if (!isa<ConstantSDNode>(Op1)) {
7133        OtherUses.clear();
7134        break;
7135      }
7136
7137      // FIXME: In some cases, we can be smarter about this.
7138      if (Op1.getValueType() != Offset.getValueType()) {
7139        OtherUses.clear();
7140        break;
7141      }
7142
7143      OtherUses.push_back(Use);
7144    }
7145
7146  if (Swapped)
7147    std::swap(BasePtr, Offset);
7148
7149  // Now check for #3 and #4.
7150  bool RealUse = false;
7151
7152  // Caches for hasPredecessorHelper
7153  SmallPtrSet<const SDNode *, 32> Visited;
7154  SmallVector<const SDNode *, 16> Worklist;
7155
7156  for (SDNode::use_iterator I = Ptr.getNode()->use_begin(),
7157         E = Ptr.getNode()->use_end(); I != E; ++I) {
7158    SDNode *Use = *I;
7159    if (Use == N)
7160      continue;
7161    if (N->hasPredecessorHelper(Use, Visited, Worklist))
7162      return false;
7163
7164    // If Ptr may be folded in addressing mode of other use, then it's
7165    // not profitable to do this transformation.
7166    if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
7167      RealUse = true;
7168  }
7169
7170  if (!RealUse)
7171    return false;
7172
7173  SDValue Result;
7174  if (isLoad)
7175    Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
7176                                BasePtr, Offset, AM);
7177  else
7178    Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
7179                                 BasePtr, Offset, AM);
7180  ++PreIndexedNodes;
7181  ++NodesCombined;
7182  DEBUG(dbgs() << "\nReplacing.4 ";
7183        N->dump(&DAG);
7184        dbgs() << "\nWith: ";
7185        Result.getNode()->dump(&DAG);
7186        dbgs() << '\n');
7187  WorkListRemover DeadNodes(*this);
7188  if (isLoad) {
7189    DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7190    DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
7191  } else {
7192    DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
7193  }
7194
7195  // Finally, since the node is now dead, remove it from the graph.
7196  DAG.DeleteNode(N);
7197
7198  if (Swapped)
7199    std::swap(BasePtr, Offset);
7200
7201  // Replace other uses of BasePtr that can be updated to use Ptr
7202  for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
7203    unsigned OffsetIdx = 1;
7204    if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
7205      OffsetIdx = 0;
7206    assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
7207           BasePtr.getNode() && "Expected BasePtr operand");
7208
7209    // We need to replace ptr0 in the following expression:
7210    //   x0 * offset0 + y0 * ptr0 = t0
7211    // knowing that
7212    //   x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
7213    //
7214    // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
7215    // indexed load/store and the expresion that needs to be re-written.
7216    //
7217    // Therefore, we have:
7218    //   t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
7219
7220    ConstantSDNode *CN =
7221      cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
7222    int X0, X1, Y0, Y1;
7223    APInt Offset0 = CN->getAPIntValue();
7224    APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
7225
7226    X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
7227    Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
7228    X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
7229    Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
7230
7231    unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
7232
7233    APInt CNV = Offset0;
7234    if (X0 < 0) CNV = -CNV;
7235    if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
7236    else CNV = CNV - Offset1;
7237
7238    // We can now generate the new expression.
7239    SDValue NewOp1 = DAG.getConstant(CNV, CN->getValueType(0));
7240    SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
7241
7242    SDValue NewUse = DAG.getNode(Opcode,
7243                                 SDLoc(OtherUses[i]),
7244                                 OtherUses[i]->getValueType(0), NewOp1, NewOp2);
7245    DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
7246    removeFromWorkList(OtherUses[i]);
7247    DAG.DeleteNode(OtherUses[i]);
7248  }
7249
7250  // Replace the uses of Ptr with uses of the updated base value.
7251  DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
7252  removeFromWorkList(Ptr.getNode());
7253  DAG.DeleteNode(Ptr.getNode());
7254
7255  return true;
7256}
7257
7258/// CombineToPostIndexedLoadStore - Try to combine a load / store with a
7259/// add / sub of the base pointer node into a post-indexed load / store.
7260/// The transformation folded the add / subtract into the new indexed
7261/// load / store effectively and all of its uses are redirected to the
7262/// new load / store.
7263bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
7264  if (Level < AfterLegalizeDAG)
7265    return false;
7266
7267  bool isLoad = true;
7268  SDValue Ptr;
7269  EVT VT;
7270  if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
7271    if (LD->isIndexed())
7272      return false;
7273    VT = LD->getMemoryVT();
7274    if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
7275        !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
7276      return false;
7277    Ptr = LD->getBasePtr();
7278  } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
7279    if (ST->isIndexed())
7280      return false;
7281    VT = ST->getMemoryVT();
7282    if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
7283        !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
7284      return false;
7285    Ptr = ST->getBasePtr();
7286    isLoad = false;
7287  } else {
7288    return false;
7289  }
7290
7291  if (Ptr.getNode()->hasOneUse())
7292    return false;
7293
7294  for (SDNode::use_iterator I = Ptr.getNode()->use_begin(),
7295         E = Ptr.getNode()->use_end(); I != E; ++I) {
7296    SDNode *Op = *I;
7297    if (Op == N ||
7298        (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
7299      continue;
7300
7301    SDValue BasePtr;
7302    SDValue Offset;
7303    ISD::MemIndexedMode AM = ISD::UNINDEXED;
7304    if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
7305      // Don't create a indexed load / store with zero offset.
7306      if (isa<ConstantSDNode>(Offset) &&
7307          cast<ConstantSDNode>(Offset)->isNullValue())
7308        continue;
7309
7310      // Try turning it into a post-indexed load / store except when
7311      // 1) All uses are load / store ops that use it as base ptr (and
7312      //    it may be folded as addressing mmode).
7313      // 2) Op must be independent of N, i.e. Op is neither a predecessor
7314      //    nor a successor of N. Otherwise, if Op is folded that would
7315      //    create a cycle.
7316
7317      if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7318        continue;
7319
7320      // Check for #1.
7321      bool TryNext = false;
7322      for (SDNode::use_iterator II = BasePtr.getNode()->use_begin(),
7323             EE = BasePtr.getNode()->use_end(); II != EE; ++II) {
7324        SDNode *Use = *II;
7325        if (Use == Ptr.getNode())
7326          continue;
7327
7328        // If all the uses are load / store addresses, then don't do the
7329        // transformation.
7330        if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
7331          bool RealUse = false;
7332          for (SDNode::use_iterator III = Use->use_begin(),
7333                 EEE = Use->use_end(); III != EEE; ++III) {
7334            SDNode *UseUse = *III;
7335            if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
7336              RealUse = true;
7337          }
7338
7339          if (!RealUse) {
7340            TryNext = true;
7341            break;
7342          }
7343        }
7344      }
7345
7346      if (TryNext)
7347        continue;
7348
7349      // Check for #2
7350      if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
7351        SDValue Result = isLoad
7352          ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
7353                               BasePtr, Offset, AM)
7354          : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
7355                                BasePtr, Offset, AM);
7356        ++PostIndexedNodes;
7357        ++NodesCombined;
7358        DEBUG(dbgs() << "\nReplacing.5 ";
7359              N->dump(&DAG);
7360              dbgs() << "\nWith: ";
7361              Result.getNode()->dump(&DAG);
7362              dbgs() << '\n');
7363        WorkListRemover DeadNodes(*this);
7364        if (isLoad) {
7365          DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7366          DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
7367        } else {
7368          DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
7369        }
7370
7371        // Finally, since the node is now dead, remove it from the graph.
7372        DAG.DeleteNode(N);
7373
7374        // Replace the uses of Use with uses of the updated base value.
7375        DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
7376                                      Result.getValue(isLoad ? 1 : 0));
7377        removeFromWorkList(Op);
7378        DAG.DeleteNode(Op);
7379        return true;
7380      }
7381    }
7382  }
7383
7384  return false;
7385}
7386
7387SDValue DAGCombiner::visitLOAD(SDNode *N) {
7388  LoadSDNode *LD  = cast<LoadSDNode>(N);
7389  SDValue Chain = LD->getChain();
7390  SDValue Ptr   = LD->getBasePtr();
7391
7392  // If load is not volatile and there are no uses of the loaded value (and
7393  // the updated indexed value in case of indexed loads), change uses of the
7394  // chain value into uses of the chain input (i.e. delete the dead load).
7395  if (!LD->isVolatile()) {
7396    if (N->getValueType(1) == MVT::Other) {
7397      // Unindexed loads.
7398      if (!N->hasAnyUseOfValue(0)) {
7399        // It's not safe to use the two value CombineTo variant here. e.g.
7400        // v1, chain2 = load chain1, loc
7401        // v2, chain3 = load chain2, loc
7402        // v3         = add v2, c
7403        // Now we replace use of chain2 with chain1.  This makes the second load
7404        // isomorphic to the one we are deleting, and thus makes this load live.
7405        DEBUG(dbgs() << "\nReplacing.6 ";
7406              N->dump(&DAG);
7407              dbgs() << "\nWith chain: ";
7408              Chain.getNode()->dump(&DAG);
7409              dbgs() << "\n");
7410        WorkListRemover DeadNodes(*this);
7411        DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
7412
7413        if (N->use_empty()) {
7414          removeFromWorkList(N);
7415          DAG.DeleteNode(N);
7416        }
7417
7418        return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7419      }
7420    } else {
7421      // Indexed loads.
7422      assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
7423      if (!N->hasAnyUseOfValue(0) && !N->hasAnyUseOfValue(1)) {
7424        SDValue Undef = DAG.getUNDEF(N->getValueType(0));
7425        DEBUG(dbgs() << "\nReplacing.7 ";
7426              N->dump(&DAG);
7427              dbgs() << "\nWith: ";
7428              Undef.getNode()->dump(&DAG);
7429              dbgs() << " and 2 other values\n");
7430        WorkListRemover DeadNodes(*this);
7431        DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
7432        DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1),
7433                                      DAG.getUNDEF(N->getValueType(1)));
7434        DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
7435        removeFromWorkList(N);
7436        DAG.DeleteNode(N);
7437        return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7438      }
7439    }
7440  }
7441
7442  // If this load is directly stored, replace the load value with the stored
7443  // value.
7444  // TODO: Handle store large -> read small portion.
7445  // TODO: Handle TRUNCSTORE/LOADEXT
7446  if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
7447    if (ISD::isNON_TRUNCStore(Chain.getNode())) {
7448      StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
7449      if (PrevST->getBasePtr() == Ptr &&
7450          PrevST->getValue().getValueType() == N->getValueType(0))
7451      return CombineTo(N, Chain.getOperand(1), Chain);
7452    }
7453  }
7454
7455  // Try to infer better alignment information than the load already has.
7456  if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
7457    if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
7458      if (Align > LD->getMemOperand()->getBaseAlignment()) {
7459        SDValue NewLoad =
7460               DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
7461                              LD->getValueType(0),
7462                              Chain, Ptr, LD->getPointerInfo(),
7463                              LD->getMemoryVT(),
7464                              LD->isVolatile(), LD->isNonTemporal(), Align);
7465        return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
7466      }
7467    }
7468  }
7469
7470  if (CombinerAA) {
7471    // Walk up chain skipping non-aliasing memory nodes.
7472    SDValue BetterChain = FindBetterChain(N, Chain);
7473
7474    // If there is a better chain.
7475    if (Chain != BetterChain) {
7476      SDValue ReplLoad;
7477
7478      // Replace the chain to void dependency.
7479      if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
7480        ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
7481                               BetterChain, Ptr, LD->getPointerInfo(),
7482                               LD->isVolatile(), LD->isNonTemporal(),
7483                               LD->isInvariant(), LD->getAlignment());
7484      } else {
7485        ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
7486                                  LD->getValueType(0),
7487                                  BetterChain, Ptr, LD->getPointerInfo(),
7488                                  LD->getMemoryVT(),
7489                                  LD->isVolatile(),
7490                                  LD->isNonTemporal(),
7491                                  LD->getAlignment());
7492      }
7493
7494      // Create token factor to keep old chain connected.
7495      SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
7496                                  MVT::Other, Chain, ReplLoad.getValue(1));
7497
7498      // Make sure the new and old chains are cleaned up.
7499      AddToWorkList(Token.getNode());
7500
7501      // Replace uses with load result and token factor. Don't add users
7502      // to work list.
7503      return CombineTo(N, ReplLoad.getValue(0), Token, false);
7504    }
7505  }
7506
7507  // Try transforming N to an indexed load.
7508  if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
7509    return SDValue(N, 0);
7510
7511  return SDValue();
7512}
7513
7514/// CheckForMaskedLoad - Check to see if V is (and load (ptr), imm), where the
7515/// load is having specific bytes cleared out.  If so, return the byte size
7516/// being masked out and the shift amount.
7517static std::pair<unsigned, unsigned>
7518CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
7519  std::pair<unsigned, unsigned> Result(0, 0);
7520
7521  // Check for the structure we're looking for.
7522  if (V->getOpcode() != ISD::AND ||
7523      !isa<ConstantSDNode>(V->getOperand(1)) ||
7524      !ISD::isNormalLoad(V->getOperand(0).getNode()))
7525    return Result;
7526
7527  // Check the chain and pointer.
7528  LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
7529  if (LD->getBasePtr() != Ptr) return Result;  // Not from same pointer.
7530
7531  // The store should be chained directly to the load or be an operand of a
7532  // tokenfactor.
7533  if (LD == Chain.getNode())
7534    ; // ok.
7535  else if (Chain->getOpcode() != ISD::TokenFactor)
7536    return Result; // Fail.
7537  else {
7538    bool isOk = false;
7539    for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
7540      if (Chain->getOperand(i).getNode() == LD) {
7541        isOk = true;
7542        break;
7543      }
7544    if (!isOk) return Result;
7545  }
7546
7547  // This only handles simple types.
7548  if (V.getValueType() != MVT::i16 &&
7549      V.getValueType() != MVT::i32 &&
7550      V.getValueType() != MVT::i64)
7551    return Result;
7552
7553  // Check the constant mask.  Invert it so that the bits being masked out are
7554  // 0 and the bits being kept are 1.  Use getSExtValue so that leading bits
7555  // follow the sign bit for uniformity.
7556  uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
7557  unsigned NotMaskLZ = countLeadingZeros(NotMask);
7558  if (NotMaskLZ & 7) return Result;  // Must be multiple of a byte.
7559  unsigned NotMaskTZ = countTrailingZeros(NotMask);
7560  if (NotMaskTZ & 7) return Result;  // Must be multiple of a byte.
7561  if (NotMaskLZ == 64) return Result;  // All zero mask.
7562
7563  // See if we have a continuous run of bits.  If so, we have 0*1+0*
7564  if (CountTrailingOnes_64(NotMask >> NotMaskTZ)+NotMaskTZ+NotMaskLZ != 64)
7565    return Result;
7566
7567  // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
7568  if (V.getValueType() != MVT::i64 && NotMaskLZ)
7569    NotMaskLZ -= 64-V.getValueSizeInBits();
7570
7571  unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
7572  switch (MaskedBytes) {
7573  case 1:
7574  case 2:
7575  case 4: break;
7576  default: return Result; // All one mask, or 5-byte mask.
7577  }
7578
7579  // Verify that the first bit starts at a multiple of mask so that the access
7580  // is aligned the same as the access width.
7581  if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
7582
7583  Result.first = MaskedBytes;
7584  Result.second = NotMaskTZ/8;
7585  return Result;
7586}
7587
7588
7589/// ShrinkLoadReplaceStoreWithStore - Check to see if IVal is something that
7590/// provides a value as specified by MaskInfo.  If so, replace the specified
7591/// store with a narrower store of truncated IVal.
7592static SDNode *
7593ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
7594                                SDValue IVal, StoreSDNode *St,
7595                                DAGCombiner *DC) {
7596  unsigned NumBytes = MaskInfo.first;
7597  unsigned ByteShift = MaskInfo.second;
7598  SelectionDAG &DAG = DC->getDAG();
7599
7600  // Check to see if IVal is all zeros in the part being masked in by the 'or'
7601  // that uses this.  If not, this is not a replacement.
7602  APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
7603                                  ByteShift*8, (ByteShift+NumBytes)*8);
7604  if (!DAG.MaskedValueIsZero(IVal, Mask)) return 0;
7605
7606  // Check that it is legal on the target to do this.  It is legal if the new
7607  // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
7608  // legalization.
7609  MVT VT = MVT::getIntegerVT(NumBytes*8);
7610  if (!DC->isTypeLegal(VT))
7611    return 0;
7612
7613  // Okay, we can do this!  Replace the 'St' store with a store of IVal that is
7614  // shifted by ByteShift and truncated down to NumBytes.
7615  if (ByteShift)
7616    IVal = DAG.getNode(ISD::SRL, SDLoc(IVal), IVal.getValueType(), IVal,
7617                       DAG.getConstant(ByteShift*8,
7618                                    DC->getShiftAmountTy(IVal.getValueType())));
7619
7620  // Figure out the offset for the store and the alignment of the access.
7621  unsigned StOffset;
7622  unsigned NewAlign = St->getAlignment();
7623
7624  if (DAG.getTargetLoweringInfo().isLittleEndian())
7625    StOffset = ByteShift;
7626  else
7627    StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
7628
7629  SDValue Ptr = St->getBasePtr();
7630  if (StOffset) {
7631    Ptr = DAG.getNode(ISD::ADD, SDLoc(IVal), Ptr.getValueType(),
7632                      Ptr, DAG.getConstant(StOffset, Ptr.getValueType()));
7633    NewAlign = MinAlign(NewAlign, StOffset);
7634  }
7635
7636  // Truncate down to the new size.
7637  IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
7638
7639  ++OpsNarrowed;
7640  return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
7641                      St->getPointerInfo().getWithOffset(StOffset),
7642                      false, false, NewAlign).getNode();
7643}
7644
7645
7646/// ReduceLoadOpStoreWidth - Look for sequence of load / op / store where op is
7647/// one of 'or', 'xor', and 'and' of immediates. If 'op' is only touching some
7648/// of the loaded bits, try narrowing the load and store if it would end up
7649/// being a win for performance or code size.
7650SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
7651  StoreSDNode *ST  = cast<StoreSDNode>(N);
7652  if (ST->isVolatile())
7653    return SDValue();
7654
7655  SDValue Chain = ST->getChain();
7656  SDValue Value = ST->getValue();
7657  SDValue Ptr   = ST->getBasePtr();
7658  EVT VT = Value.getValueType();
7659
7660  if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
7661    return SDValue();
7662
7663  unsigned Opc = Value.getOpcode();
7664
7665  // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
7666  // is a byte mask indicating a consecutive number of bytes, check to see if
7667  // Y is known to provide just those bytes.  If so, we try to replace the
7668  // load + replace + store sequence with a single (narrower) store, which makes
7669  // the load dead.
7670  if (Opc == ISD::OR) {
7671    std::pair<unsigned, unsigned> MaskedLoad;
7672    MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
7673    if (MaskedLoad.first)
7674      if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
7675                                                  Value.getOperand(1), ST,this))
7676        return SDValue(NewST, 0);
7677
7678    // Or is commutative, so try swapping X and Y.
7679    MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
7680    if (MaskedLoad.first)
7681      if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
7682                                                  Value.getOperand(0), ST,this))
7683        return SDValue(NewST, 0);
7684  }
7685
7686  if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
7687      Value.getOperand(1).getOpcode() != ISD::Constant)
7688    return SDValue();
7689
7690  SDValue N0 = Value.getOperand(0);
7691  if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7692      Chain == SDValue(N0.getNode(), 1)) {
7693    LoadSDNode *LD = cast<LoadSDNode>(N0);
7694    if (LD->getBasePtr() != Ptr ||
7695        LD->getPointerInfo().getAddrSpace() !=
7696        ST->getPointerInfo().getAddrSpace())
7697      return SDValue();
7698
7699    // Find the type to narrow it the load / op / store to.
7700    SDValue N1 = Value.getOperand(1);
7701    unsigned BitWidth = N1.getValueSizeInBits();
7702    APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
7703    if (Opc == ISD::AND)
7704      Imm ^= APInt::getAllOnesValue(BitWidth);
7705    if (Imm == 0 || Imm.isAllOnesValue())
7706      return SDValue();
7707    unsigned ShAmt = Imm.countTrailingZeros();
7708    unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
7709    unsigned NewBW = NextPowerOf2(MSB - ShAmt);
7710    EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
7711    while (NewBW < BitWidth &&
7712           !(TLI.isOperationLegalOrCustom(Opc, NewVT) &&
7713             TLI.isNarrowingProfitable(VT, NewVT))) {
7714      NewBW = NextPowerOf2(NewBW);
7715      NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
7716    }
7717    if (NewBW >= BitWidth)
7718      return SDValue();
7719
7720    // If the lsb changed does not start at the type bitwidth boundary,
7721    // start at the previous one.
7722    if (ShAmt % NewBW)
7723      ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
7724    APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
7725                                   std::min(BitWidth, ShAmt + NewBW));
7726    if ((Imm & Mask) == Imm) {
7727      APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
7728      if (Opc == ISD::AND)
7729        NewImm ^= APInt::getAllOnesValue(NewBW);
7730      uint64_t PtrOff = ShAmt / 8;
7731      // For big endian targets, we need to adjust the offset to the pointer to
7732      // load the correct bytes.
7733      if (TLI.isBigEndian())
7734        PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
7735
7736      unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
7737      Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
7738      if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy))
7739        return SDValue();
7740
7741      SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
7742                                   Ptr.getValueType(), Ptr,
7743                                   DAG.getConstant(PtrOff, Ptr.getValueType()));
7744      SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
7745                                  LD->getChain(), NewPtr,
7746                                  LD->getPointerInfo().getWithOffset(PtrOff),
7747                                  LD->isVolatile(), LD->isNonTemporal(),
7748                                  LD->isInvariant(), NewAlign);
7749      SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
7750                                   DAG.getConstant(NewImm, NewVT));
7751      SDValue NewST = DAG.getStore(Chain, SDLoc(N),
7752                                   NewVal, NewPtr,
7753                                   ST->getPointerInfo().getWithOffset(PtrOff),
7754                                   false, false, NewAlign);
7755
7756      AddToWorkList(NewPtr.getNode());
7757      AddToWorkList(NewLD.getNode());
7758      AddToWorkList(NewVal.getNode());
7759      WorkListRemover DeadNodes(*this);
7760      DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
7761      ++OpsNarrowed;
7762      return NewST;
7763    }
7764  }
7765
7766  return SDValue();
7767}
7768
7769/// TransformFPLoadStorePair - For a given floating point load / store pair,
7770/// if the load value isn't used by any other operations, then consider
7771/// transforming the pair to integer load / store operations if the target
7772/// deems the transformation profitable.
7773SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
7774  StoreSDNode *ST  = cast<StoreSDNode>(N);
7775  SDValue Chain = ST->getChain();
7776  SDValue Value = ST->getValue();
7777  if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
7778      Value.hasOneUse() &&
7779      Chain == SDValue(Value.getNode(), 1)) {
7780    LoadSDNode *LD = cast<LoadSDNode>(Value);
7781    EVT VT = LD->getMemoryVT();
7782    if (!VT.isFloatingPoint() ||
7783        VT != ST->getMemoryVT() ||
7784        LD->isNonTemporal() ||
7785        ST->isNonTemporal() ||
7786        LD->getPointerInfo().getAddrSpace() != 0 ||
7787        ST->getPointerInfo().getAddrSpace() != 0)
7788      return SDValue();
7789
7790    EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
7791    if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
7792        !TLI.isOperationLegal(ISD::STORE, IntVT) ||
7793        !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
7794        !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
7795      return SDValue();
7796
7797    unsigned LDAlign = LD->getAlignment();
7798    unsigned STAlign = ST->getAlignment();
7799    Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
7800    unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy);
7801    if (LDAlign < ABIAlign || STAlign < ABIAlign)
7802      return SDValue();
7803
7804    SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
7805                                LD->getChain(), LD->getBasePtr(),
7806                                LD->getPointerInfo(),
7807                                false, false, false, LDAlign);
7808
7809    SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
7810                                 NewLD, ST->getBasePtr(),
7811                                 ST->getPointerInfo(),
7812                                 false, false, STAlign);
7813
7814    AddToWorkList(NewLD.getNode());
7815    AddToWorkList(NewST.getNode());
7816    WorkListRemover DeadNodes(*this);
7817    DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
7818    ++LdStFP2Int;
7819    return NewST;
7820  }
7821
7822  return SDValue();
7823}
7824
7825/// Helper struct to parse and store a memory address as base + index + offset.
7826/// We ignore sign extensions when it is safe to do so.
7827/// The following two expressions are not equivalent. To differentiate we need
7828/// to store whether there was a sign extension involved in the index
7829/// computation.
7830///  (load (i64 add (i64 copyfromreg %c)
7831///                 (i64 signextend (add (i8 load %index)
7832///                                      (i8 1))))
7833/// vs
7834///
7835/// (load (i64 add (i64 copyfromreg %c)
7836///                (i64 signextend (i32 add (i32 signextend (i8 load %index))
7837///                                         (i32 1)))))
7838struct BaseIndexOffset {
7839  SDValue Base;
7840  SDValue Index;
7841  int64_t Offset;
7842  bool IsIndexSignExt;
7843
7844  BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
7845
7846  BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
7847                  bool IsIndexSignExt) :
7848    Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
7849
7850  bool equalBaseIndex(const BaseIndexOffset &Other) {
7851    return Other.Base == Base && Other.Index == Index &&
7852      Other.IsIndexSignExt == IsIndexSignExt;
7853  }
7854
7855  /// Parses tree in Ptr for base, index, offset addresses.
7856  static BaseIndexOffset match(SDValue Ptr) {
7857    bool IsIndexSignExt = false;
7858
7859    // Just Base or possibly anything else.
7860    if (Ptr->getOpcode() != ISD::ADD)
7861      return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
7862
7863    // Base + offset.
7864    if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
7865      int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
7866      return  BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
7867                              IsIndexSignExt);
7868    }
7869
7870    // Look at Base + Index + Offset cases.
7871    SDValue Base = Ptr->getOperand(0);
7872    SDValue IndexOffset = Ptr->getOperand(1);
7873
7874    // Skip signextends.
7875    if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
7876      IndexOffset = IndexOffset->getOperand(0);
7877      IsIndexSignExt = true;
7878    }
7879
7880    // Either the case of Base + Index (no offset) or something else.
7881    if (IndexOffset->getOpcode() != ISD::ADD)
7882      return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
7883
7884    // Now we have the case of Base + Index + offset.
7885    SDValue Index = IndexOffset->getOperand(0);
7886    SDValue Offset = IndexOffset->getOperand(1);
7887
7888    if (!isa<ConstantSDNode>(Offset))
7889      return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
7890
7891    // Ignore signextends.
7892    if (Index->getOpcode() == ISD::SIGN_EXTEND) {
7893      Index = Index->getOperand(0);
7894      IsIndexSignExt = true;
7895    } else IsIndexSignExt = false;
7896
7897    int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
7898    return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
7899  }
7900};
7901
7902/// Holds a pointer to an LSBaseSDNode as well as information on where it
7903/// is located in a sequence of memory operations connected by a chain.
7904struct MemOpLink {
7905  MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
7906    MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
7907  // Ptr to the mem node.
7908  LSBaseSDNode *MemNode;
7909  // Offset from the base ptr.
7910  int64_t OffsetFromBase;
7911  // What is the sequence number of this mem node.
7912  // Lowest mem operand in the DAG starts at zero.
7913  unsigned SequenceNum;
7914};
7915
7916/// Sorts store nodes in a link according to their offset from a shared
7917// base ptr.
7918struct ConsecutiveMemoryChainSorter {
7919  bool operator()(MemOpLink LHS, MemOpLink RHS) {
7920    return LHS.OffsetFromBase < RHS.OffsetFromBase;
7921  }
7922};
7923
7924bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
7925  EVT MemVT = St->getMemoryVT();
7926  int64_t ElementSizeBytes = MemVT.getSizeInBits()/8;
7927  bool NoVectors = DAG.getMachineFunction().getFunction()->getAttributes().
7928    hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
7929
7930  // Don't merge vectors into wider inputs.
7931  if (MemVT.isVector() || !MemVT.isSimple())
7932    return false;
7933
7934  // Perform an early exit check. Do not bother looking at stored values that
7935  // are not constants or loads.
7936  SDValue StoredVal = St->getValue();
7937  bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
7938  if (!isa<ConstantSDNode>(StoredVal) && !isa<ConstantFPSDNode>(StoredVal) &&
7939      !IsLoadSrc)
7940    return false;
7941
7942  // Only look at ends of store sequences.
7943  SDValue Chain = SDValue(St, 1);
7944  if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
7945    return false;
7946
7947  // This holds the base pointer, index, and the offset in bytes from the base
7948  // pointer.
7949  BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
7950
7951  // We must have a base and an offset.
7952  if (!BasePtr.Base.getNode())
7953    return false;
7954
7955  // Do not handle stores to undef base pointers.
7956  if (BasePtr.Base.getOpcode() == ISD::UNDEF)
7957    return false;
7958
7959  // Save the LoadSDNodes that we find in the chain.
7960  // We need to make sure that these nodes do not interfere with
7961  // any of the store nodes.
7962  SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
7963
7964  // Save the StoreSDNodes that we find in the chain.
7965  SmallVector<MemOpLink, 8> StoreNodes;
7966
7967  // Walk up the chain and look for nodes with offsets from the same
7968  // base pointer. Stop when reaching an instruction with a different kind
7969  // or instruction which has a different base pointer.
7970  unsigned Seq = 0;
7971  StoreSDNode *Index = St;
7972  while (Index) {
7973    // If the chain has more than one use, then we can't reorder the mem ops.
7974    if (Index != St && !SDValue(Index, 1)->hasOneUse())
7975      break;
7976
7977    // Find the base pointer and offset for this memory node.
7978    BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
7979
7980    // Check that the base pointer is the same as the original one.
7981    if (!Ptr.equalBaseIndex(BasePtr))
7982      break;
7983
7984    // Check that the alignment is the same.
7985    if (Index->getAlignment() != St->getAlignment())
7986      break;
7987
7988    // The memory operands must not be volatile.
7989    if (Index->isVolatile() || Index->isIndexed())
7990      break;
7991
7992    // No truncation.
7993    if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
7994      if (St->isTruncatingStore())
7995        break;
7996
7997    // The stored memory type must be the same.
7998    if (Index->getMemoryVT() != MemVT)
7999      break;
8000
8001    // We do not allow unaligned stores because we want to prevent overriding
8002    // stores.
8003    if (Index->getAlignment()*8 != MemVT.getSizeInBits())
8004      break;
8005
8006    // We found a potential memory operand to merge.
8007    StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
8008
8009    // Find the next memory operand in the chain. If the next operand in the
8010    // chain is a store then move up and continue the scan with the next
8011    // memory operand. If the next operand is a load save it and use alias
8012    // information to check if it interferes with anything.
8013    SDNode *NextInChain = Index->getChain().getNode();
8014    while (1) {
8015      if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
8016        // We found a store node. Use it for the next iteration.
8017        Index = STn;
8018        break;
8019      } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
8020        // Save the load node for later. Continue the scan.
8021        AliasLoadNodes.push_back(Ldn);
8022        NextInChain = Ldn->getChain().getNode();
8023        continue;
8024      } else {
8025        Index = NULL;
8026        break;
8027      }
8028    }
8029  }
8030
8031  // Check if there is anything to merge.
8032  if (StoreNodes.size() < 2)
8033    return false;
8034
8035  // Sort the memory operands according to their distance from the base pointer.
8036  std::sort(StoreNodes.begin(), StoreNodes.end(),
8037            ConsecutiveMemoryChainSorter());
8038
8039  // Scan the memory operations on the chain and find the first non-consecutive
8040  // store memory address.
8041  unsigned LastConsecutiveStore = 0;
8042  int64_t StartAddress = StoreNodes[0].OffsetFromBase;
8043  for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
8044
8045    // Check that the addresses are consecutive starting from the second
8046    // element in the list of stores.
8047    if (i > 0) {
8048      int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
8049      if (CurrAddress - StartAddress != (ElementSizeBytes * i))
8050        break;
8051    }
8052
8053    bool Alias = false;
8054    // Check if this store interferes with any of the loads that we found.
8055    for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
8056      if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
8057        Alias = true;
8058        break;
8059      }
8060    // We found a load that alias with this store. Stop the sequence.
8061    if (Alias)
8062      break;
8063
8064    // Mark this node as useful.
8065    LastConsecutiveStore = i;
8066  }
8067
8068  // The node with the lowest store address.
8069  LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
8070
8071  // Store the constants into memory as one consecutive store.
8072  if (!IsLoadSrc) {
8073    unsigned LastLegalType = 0;
8074    unsigned LastLegalVectorType = 0;
8075    bool NonZero = false;
8076    for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
8077      StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
8078      SDValue StoredVal = St->getValue();
8079
8080      if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
8081        NonZero |= !C->isNullValue();
8082      } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
8083        NonZero |= !C->getConstantFPValue()->isNullValue();
8084      } else {
8085        // Non constant.
8086        break;
8087      }
8088
8089      // Find a legal type for the constant store.
8090      unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
8091      EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
8092      if (TLI.isTypeLegal(StoreTy))
8093        LastLegalType = i+1;
8094      // Or check whether a truncstore is legal.
8095      else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
8096               TargetLowering::TypePromoteInteger) {
8097        EVT LegalizedStoredValueTy =
8098          TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
8099        if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy))
8100          LastLegalType = i+1;
8101      }
8102
8103      // Find a legal type for the vector store.
8104      EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
8105      if (TLI.isTypeLegal(Ty))
8106        LastLegalVectorType = i + 1;
8107    }
8108
8109    // We only use vectors if the constant is known to be zero and the
8110    // function is not marked with the noimplicitfloat attribute.
8111    if (NonZero || NoVectors)
8112      LastLegalVectorType = 0;
8113
8114    // Check if we found a legal integer type to store.
8115    if (LastLegalType == 0 && LastLegalVectorType == 0)
8116      return false;
8117
8118    bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
8119    unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
8120
8121    // Make sure we have something to merge.
8122    if (NumElem < 2)
8123      return false;
8124
8125    unsigned EarliestNodeUsed = 0;
8126    for (unsigned i=0; i < NumElem; ++i) {
8127      // Find a chain for the new wide-store operand. Notice that some
8128      // of the store nodes that we found may not be selected for inclusion
8129      // in the wide store. The chain we use needs to be the chain of the
8130      // earliest store node which is *used* and replaced by the wide store.
8131      if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
8132        EarliestNodeUsed = i;
8133    }
8134
8135    // The earliest Node in the DAG.
8136    LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
8137    SDLoc DL(StoreNodes[0].MemNode);
8138
8139    SDValue StoredVal;
8140    if (UseVector) {
8141      // Find a legal type for the vector store.
8142      EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
8143      assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
8144      StoredVal = DAG.getConstant(0, Ty);
8145    } else {
8146      unsigned StoreBW = NumElem * ElementSizeBytes * 8;
8147      APInt StoreInt(StoreBW, 0);
8148
8149      // Construct a single integer constant which is made of the smaller
8150      // constant inputs.
8151      bool IsLE = TLI.isLittleEndian();
8152      for (unsigned i = 0; i < NumElem ; ++i) {
8153        unsigned Idx = IsLE ?(NumElem - 1 - i) : i;
8154        StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
8155        SDValue Val = St->getValue();
8156        StoreInt<<=ElementSizeBytes*8;
8157        if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
8158          StoreInt|=C->getAPIntValue().zext(StoreBW);
8159        } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
8160          StoreInt|= C->getValueAPF().bitcastToAPInt().zext(StoreBW);
8161        } else {
8162          assert(false && "Invalid constant element type");
8163        }
8164      }
8165
8166      // Create the new Load and Store operations.
8167      EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
8168      StoredVal = DAG.getConstant(StoreInt, StoreTy);
8169    }
8170
8171    SDValue NewStore = DAG.getStore(EarliestOp->getChain(), DL, StoredVal,
8172                                    FirstInChain->getBasePtr(),
8173                                    FirstInChain->getPointerInfo(),
8174                                    false, false,
8175                                    FirstInChain->getAlignment());
8176
8177    // Replace the first store with the new store
8178    CombineTo(EarliestOp, NewStore);
8179    // Erase all other stores.
8180    for (unsigned i = 0; i < NumElem ; ++i) {
8181      if (StoreNodes[i].MemNode == EarliestOp)
8182        continue;
8183      StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
8184      // ReplaceAllUsesWith will replace all uses that existed when it was
8185      // called, but graph optimizations may cause new ones to appear. For
8186      // example, the case in pr14333 looks like
8187      //
8188      //  St's chain -> St -> another store -> X
8189      //
8190      // And the only difference from St to the other store is the chain.
8191      // When we change it's chain to be St's chain they become identical,
8192      // get CSEed and the net result is that X is now a use of St.
8193      // Since we know that St is redundant, just iterate.
8194      while (!St->use_empty())
8195        DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
8196      removeFromWorkList(St);
8197      DAG.DeleteNode(St);
8198    }
8199
8200    return true;
8201  }
8202
8203  // Below we handle the case of multiple consecutive stores that
8204  // come from multiple consecutive loads. We merge them into a single
8205  // wide load and a single wide store.
8206
8207  // Look for load nodes which are used by the stored values.
8208  SmallVector<MemOpLink, 8> LoadNodes;
8209
8210  // Find acceptable loads. Loads need to have the same chain (token factor),
8211  // must not be zext, volatile, indexed, and they must be consecutive.
8212  BaseIndexOffset LdBasePtr;
8213  for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
8214    StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
8215    LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
8216    if (!Ld) break;
8217
8218    // Loads must only have one use.
8219    if (!Ld->hasNUsesOfValue(1, 0))
8220      break;
8221
8222    // Check that the alignment is the same as the stores.
8223    if (Ld->getAlignment() != St->getAlignment())
8224      break;
8225
8226    // The memory operands must not be volatile.
8227    if (Ld->isVolatile() || Ld->isIndexed())
8228      break;
8229
8230    // We do not accept ext loads.
8231    if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
8232      break;
8233
8234    // The stored memory type must be the same.
8235    if (Ld->getMemoryVT() != MemVT)
8236      break;
8237
8238    BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
8239    // If this is not the first ptr that we check.
8240    if (LdBasePtr.Base.getNode()) {
8241      // The base ptr must be the same.
8242      if (!LdPtr.equalBaseIndex(LdBasePtr))
8243        break;
8244    } else {
8245      // Check that all other base pointers are the same as this one.
8246      LdBasePtr = LdPtr;
8247    }
8248
8249    // We found a potential memory operand to merge.
8250    LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
8251  }
8252
8253  if (LoadNodes.size() < 2)
8254    return false;
8255
8256  // Scan the memory operations on the chain and find the first non-consecutive
8257  // load memory address. These variables hold the index in the store node
8258  // array.
8259  unsigned LastConsecutiveLoad = 0;
8260  // This variable refers to the size and not index in the array.
8261  unsigned LastLegalVectorType = 0;
8262  unsigned LastLegalIntegerType = 0;
8263  StartAddress = LoadNodes[0].OffsetFromBase;
8264  SDValue FirstChain = LoadNodes[0].MemNode->getChain();
8265  for (unsigned i = 1; i < LoadNodes.size(); ++i) {
8266    // All loads much share the same chain.
8267    if (LoadNodes[i].MemNode->getChain() != FirstChain)
8268      break;
8269
8270    int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
8271    if (CurrAddress - StartAddress != (ElementSizeBytes * i))
8272      break;
8273    LastConsecutiveLoad = i;
8274
8275    // Find a legal type for the vector store.
8276    EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
8277    if (TLI.isTypeLegal(StoreTy))
8278      LastLegalVectorType = i + 1;
8279
8280    // Find a legal type for the integer store.
8281    unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
8282    StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
8283    if (TLI.isTypeLegal(StoreTy))
8284      LastLegalIntegerType = i + 1;
8285    // Or check whether a truncstore and extload is legal.
8286    else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
8287             TargetLowering::TypePromoteInteger) {
8288      EVT LegalizedStoredValueTy =
8289        TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy);
8290      if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
8291          TLI.isLoadExtLegal(ISD::ZEXTLOAD, StoreTy) &&
8292          TLI.isLoadExtLegal(ISD::SEXTLOAD, StoreTy) &&
8293          TLI.isLoadExtLegal(ISD::EXTLOAD, StoreTy))
8294        LastLegalIntegerType = i+1;
8295    }
8296  }
8297
8298  // Only use vector types if the vector type is larger than the integer type.
8299  // If they are the same, use integers.
8300  bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
8301  unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
8302
8303  // We add +1 here because the LastXXX variables refer to location while
8304  // the NumElem refers to array/index size.
8305  unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
8306  NumElem = std::min(LastLegalType, NumElem);
8307
8308  if (NumElem < 2)
8309    return false;
8310
8311  // The earliest Node in the DAG.
8312  unsigned EarliestNodeUsed = 0;
8313  LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
8314  for (unsigned i=1; i<NumElem; ++i) {
8315    // Find a chain for the new wide-store operand. Notice that some
8316    // of the store nodes that we found may not be selected for inclusion
8317    // in the wide store. The chain we use needs to be the chain of the
8318    // earliest store node which is *used* and replaced by the wide store.
8319    if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
8320      EarliestNodeUsed = i;
8321  }
8322
8323  // Find if it is better to use vectors or integers to load and store
8324  // to memory.
8325  EVT JointMemOpVT;
8326  if (UseVectorTy) {
8327    JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
8328  } else {
8329    unsigned StoreBW = NumElem * ElementSizeBytes * 8;
8330    JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
8331  }
8332
8333  SDLoc LoadDL(LoadNodes[0].MemNode);
8334  SDLoc StoreDL(StoreNodes[0].MemNode);
8335
8336  LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
8337  SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL,
8338                                FirstLoad->getChain(),
8339                                FirstLoad->getBasePtr(),
8340                                FirstLoad->getPointerInfo(),
8341                                false, false, false,
8342                                FirstLoad->getAlignment());
8343
8344  SDValue NewStore = DAG.getStore(EarliestOp->getChain(), StoreDL, NewLoad,
8345                                  FirstInChain->getBasePtr(),
8346                                  FirstInChain->getPointerInfo(), false, false,
8347                                  FirstInChain->getAlignment());
8348
8349  // Replace one of the loads with the new load.
8350  LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
8351  DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
8352                                SDValue(NewLoad.getNode(), 1));
8353
8354  // Remove the rest of the load chains.
8355  for (unsigned i = 1; i < NumElem ; ++i) {
8356    // Replace all chain users of the old load nodes with the chain of the new
8357    // load node.
8358    LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
8359    DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
8360  }
8361
8362  // Replace the first store with the new store.
8363  CombineTo(EarliestOp, NewStore);
8364  // Erase all other stores.
8365  for (unsigned i = 0; i < NumElem ; ++i) {
8366    // Remove all Store nodes.
8367    if (StoreNodes[i].MemNode == EarliestOp)
8368      continue;
8369    StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
8370    DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
8371    removeFromWorkList(St);
8372    DAG.DeleteNode(St);
8373  }
8374
8375  return true;
8376}
8377
8378SDValue DAGCombiner::visitSTORE(SDNode *N) {
8379  StoreSDNode *ST  = cast<StoreSDNode>(N);
8380  SDValue Chain = ST->getChain();
8381  SDValue Value = ST->getValue();
8382  SDValue Ptr   = ST->getBasePtr();
8383
8384  // If this is a store of a bit convert, store the input value if the
8385  // resultant store does not need a higher alignment than the original.
8386  if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
8387      ST->isUnindexed()) {
8388    unsigned OrigAlign = ST->getAlignment();
8389    EVT SVT = Value.getOperand(0).getValueType();
8390    unsigned Align = TLI.getDataLayout()->
8391      getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
8392    if (Align <= OrigAlign &&
8393        ((!LegalOperations && !ST->isVolatile()) ||
8394         TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
8395      return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
8396                          Ptr, ST->getPointerInfo(), ST->isVolatile(),
8397                          ST->isNonTemporal(), OrigAlign);
8398  }
8399
8400  // Turn 'store undef, Ptr' -> nothing.
8401  if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
8402    return Chain;
8403
8404  // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
8405  if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
8406    // NOTE: If the original store is volatile, this transform must not increase
8407    // the number of stores.  For example, on x86-32 an f64 can be stored in one
8408    // processor operation but an i64 (which is not legal) requires two.  So the
8409    // transform should not be done in this case.
8410    if (Value.getOpcode() != ISD::TargetConstantFP) {
8411      SDValue Tmp;
8412      switch (CFP->getValueType(0).getSimpleVT().SimpleTy) {
8413      default: llvm_unreachable("Unknown FP type");
8414      case MVT::f16:    // We don't do this for these yet.
8415      case MVT::f80:
8416      case MVT::f128:
8417      case MVT::ppcf128:
8418        break;
8419      case MVT::f32:
8420        if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
8421            TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
8422          Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
8423                              bitcastToAPInt().getZExtValue(), MVT::i32);
8424          return DAG.getStore(Chain, SDLoc(N), Tmp,
8425                              Ptr, ST->getPointerInfo(), ST->isVolatile(),
8426                              ST->isNonTemporal(), ST->getAlignment());
8427        }
8428        break;
8429      case MVT::f64:
8430        if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
8431             !ST->isVolatile()) ||
8432            TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
8433          Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
8434                                getZExtValue(), MVT::i64);
8435          return DAG.getStore(Chain, SDLoc(N), Tmp,
8436                              Ptr, ST->getPointerInfo(), ST->isVolatile(),
8437                              ST->isNonTemporal(), ST->getAlignment());
8438        }
8439
8440        if (!ST->isVolatile() &&
8441            TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
8442          // Many FP stores are not made apparent until after legalize, e.g. for
8443          // argument passing.  Since this is so common, custom legalize the
8444          // 64-bit integer store into two 32-bit stores.
8445          uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
8446          SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
8447          SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32);
8448          if (TLI.isBigEndian()) std::swap(Lo, Hi);
8449
8450          unsigned Alignment = ST->getAlignment();
8451          bool isVolatile = ST->isVolatile();
8452          bool isNonTemporal = ST->isNonTemporal();
8453
8454          SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
8455                                     Ptr, ST->getPointerInfo(),
8456                                     isVolatile, isNonTemporal,
8457                                     ST->getAlignment());
8458          Ptr = DAG.getNode(ISD::ADD, SDLoc(N), Ptr.getValueType(), Ptr,
8459                            DAG.getConstant(4, Ptr.getValueType()));
8460          Alignment = MinAlign(Alignment, 4U);
8461          SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
8462                                     Ptr, ST->getPointerInfo().getWithOffset(4),
8463                                     isVolatile, isNonTemporal,
8464                                     Alignment);
8465          return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
8466                             St0, St1);
8467        }
8468
8469        break;
8470      }
8471    }
8472  }
8473
8474  // Try to infer better alignment information than the store already has.
8475  if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
8476    if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
8477      if (Align > ST->getAlignment())
8478        return DAG.getTruncStore(Chain, SDLoc(N), Value,
8479                                 Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
8480                                 ST->isVolatile(), ST->isNonTemporal(), Align);
8481    }
8482  }
8483
8484  // Try transforming a pair floating point load / store ops to integer
8485  // load / store ops.
8486  SDValue NewST = TransformFPLoadStorePair(N);
8487  if (NewST.getNode())
8488    return NewST;
8489
8490  if (CombinerAA) {
8491    // Walk up chain skipping non-aliasing memory nodes.
8492    SDValue BetterChain = FindBetterChain(N, Chain);
8493
8494    // If there is a better chain.
8495    if (Chain != BetterChain) {
8496      SDValue ReplStore;
8497
8498      // Replace the chain to avoid dependency.
8499      if (ST->isTruncatingStore()) {
8500        ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr,
8501                                      ST->getPointerInfo(),
8502                                      ST->getMemoryVT(), ST->isVolatile(),
8503                                      ST->isNonTemporal(), ST->getAlignment());
8504      } else {
8505        ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr,
8506                                 ST->getPointerInfo(),
8507                                 ST->isVolatile(), ST->isNonTemporal(),
8508                                 ST->getAlignment());
8509      }
8510
8511      // Create token to keep both nodes around.
8512      SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
8513                                  MVT::Other, Chain, ReplStore);
8514
8515      // Make sure the new and old chains are cleaned up.
8516      AddToWorkList(Token.getNode());
8517
8518      // Don't add users to work list.
8519      return CombineTo(N, Token, false);
8520    }
8521  }
8522
8523  // Try transforming N to an indexed store.
8524  if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
8525    return SDValue(N, 0);
8526
8527  // FIXME: is there such a thing as a truncating indexed store?
8528  if (ST->isTruncatingStore() && ST->isUnindexed() &&
8529      Value.getValueType().isInteger()) {
8530    // See if we can simplify the input to this truncstore with knowledge that
8531    // only the low bits are being used.  For example:
8532    // "truncstore (or (shl x, 8), y), i8"  -> "truncstore y, i8"
8533    SDValue Shorter =
8534      GetDemandedBits(Value,
8535                      APInt::getLowBitsSet(
8536                        Value.getValueType().getScalarType().getSizeInBits(),
8537                        ST->getMemoryVT().getScalarType().getSizeInBits()));
8538    AddToWorkList(Value.getNode());
8539    if (Shorter.getNode())
8540      return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
8541                               Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
8542                               ST->isVolatile(), ST->isNonTemporal(),
8543                               ST->getAlignment());
8544
8545    // Otherwise, see if we can simplify the operation with
8546    // SimplifyDemandedBits, which only works if the value has a single use.
8547    if (SimplifyDemandedBits(Value,
8548                        APInt::getLowBitsSet(
8549                          Value.getValueType().getScalarType().getSizeInBits(),
8550                          ST->getMemoryVT().getScalarType().getSizeInBits())))
8551      return SDValue(N, 0);
8552  }
8553
8554  // If this is a load followed by a store to the same location, then the store
8555  // is dead/noop.
8556  if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
8557    if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
8558        ST->isUnindexed() && !ST->isVolatile() &&
8559        // There can't be any side effects between the load and store, such as
8560        // a call or store.
8561        Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
8562      // The store is dead, remove it.
8563      return Chain;
8564    }
8565  }
8566
8567  // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
8568  // truncating store.  We can do this even if this is already a truncstore.
8569  if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
8570      && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
8571      TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
8572                            ST->getMemoryVT())) {
8573    return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
8574                             Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
8575                             ST->isVolatile(), ST->isNonTemporal(),
8576                             ST->getAlignment());
8577  }
8578
8579  // Only perform this optimization before the types are legal, because we
8580  // don't want to perform this optimization on every DAGCombine invocation.
8581  if (!LegalTypes) {
8582    bool EverChanged = false;
8583
8584    do {
8585      // There can be multiple store sequences on the same chain.
8586      // Keep trying to merge store sequences until we are unable to do so
8587      // or until we merge the last store on the chain.
8588      bool Changed = MergeConsecutiveStores(ST);
8589      EverChanged |= Changed;
8590      if (!Changed) break;
8591    } while (ST->getOpcode() != ISD::DELETED_NODE);
8592
8593    if (EverChanged)
8594      return SDValue(N, 0);
8595  }
8596
8597  return ReduceLoadOpStoreWidth(N);
8598}
8599
8600SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
8601  SDValue InVec = N->getOperand(0);
8602  SDValue InVal = N->getOperand(1);
8603  SDValue EltNo = N->getOperand(2);
8604  SDLoc dl(N);
8605
8606  // If the inserted element is an UNDEF, just use the input vector.
8607  if (InVal.getOpcode() == ISD::UNDEF)
8608    return InVec;
8609
8610  EVT VT = InVec.getValueType();
8611
8612  // If we can't generate a legal BUILD_VECTOR, exit
8613  if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
8614    return SDValue();
8615
8616  // Check that we know which element is being inserted
8617  if (!isa<ConstantSDNode>(EltNo))
8618    return SDValue();
8619  unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
8620
8621  // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
8622  // be converted to a BUILD_VECTOR).  Fill in the Ops vector with the
8623  // vector elements.
8624  SmallVector<SDValue, 8> Ops;
8625  if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
8626    Ops.append(InVec.getNode()->op_begin(),
8627               InVec.getNode()->op_end());
8628  } else if (InVec.getOpcode() == ISD::UNDEF) {
8629    unsigned NElts = VT.getVectorNumElements();
8630    Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
8631  } else {
8632    return SDValue();
8633  }
8634
8635  // Insert the element
8636  if (Elt < Ops.size()) {
8637    // All the operands of BUILD_VECTOR must have the same type;
8638    // we enforce that here.
8639    EVT OpVT = Ops[0].getValueType();
8640    if (InVal.getValueType() != OpVT)
8641      InVal = OpVT.bitsGT(InVal.getValueType()) ?
8642                DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
8643                DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
8644    Ops[Elt] = InVal;
8645  }
8646
8647  // Return the new vector
8648  return DAG.getNode(ISD::BUILD_VECTOR, dl,
8649                     VT, &Ops[0], Ops.size());
8650}
8651
8652SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
8653  // (vextract (scalar_to_vector val, 0) -> val
8654  SDValue InVec = N->getOperand(0);
8655  EVT VT = InVec.getValueType();
8656  EVT NVT = N->getValueType(0);
8657
8658  if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
8659    // Check if the result type doesn't match the inserted element type. A
8660    // SCALAR_TO_VECTOR may truncate the inserted element and the
8661    // EXTRACT_VECTOR_ELT may widen the extracted vector.
8662    SDValue InOp = InVec.getOperand(0);
8663    if (InOp.getValueType() != NVT) {
8664      assert(InOp.getValueType().isInteger() && NVT.isInteger());
8665      return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
8666    }
8667    return InOp;
8668  }
8669
8670  SDValue EltNo = N->getOperand(1);
8671  bool ConstEltNo = isa<ConstantSDNode>(EltNo);
8672
8673  // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
8674  // We only perform this optimization before the op legalization phase because
8675  // we may introduce new vector instructions which are not backed by TD
8676  // patterns. For example on AVX, extracting elements from a wide vector
8677  // without using extract_subvector.
8678  if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
8679      && ConstEltNo && !LegalOperations) {
8680    int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
8681    int NumElem = VT.getVectorNumElements();
8682    ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
8683    // Find the new index to extract from.
8684    int OrigElt = SVOp->getMaskElt(Elt);
8685
8686    // Extracting an undef index is undef.
8687    if (OrigElt == -1)
8688      return DAG.getUNDEF(NVT);
8689
8690    // Select the right vector half to extract from.
8691    if (OrigElt < NumElem) {
8692      InVec = InVec->getOperand(0);
8693    } else {
8694      InVec = InVec->getOperand(1);
8695      OrigElt -= NumElem;
8696    }
8697
8698    EVT IndexTy = N->getOperand(1).getValueType();
8699    return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT,
8700                       InVec, DAG.getConstant(OrigElt, IndexTy));
8701  }
8702
8703  // Perform only after legalization to ensure build_vector / vector_shuffle
8704  // optimizations have already been done.
8705  if (!LegalOperations) return SDValue();
8706
8707  // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
8708  // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
8709  // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
8710
8711  if (ConstEltNo) {
8712    int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
8713    bool NewLoad = false;
8714    bool BCNumEltsChanged = false;
8715    EVT ExtVT = VT.getVectorElementType();
8716    EVT LVT = ExtVT;
8717
8718    // If the result of load has to be truncated, then it's not necessarily
8719    // profitable.
8720    if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
8721      return SDValue();
8722
8723    if (InVec.getOpcode() == ISD::BITCAST) {
8724      // Don't duplicate a load with other uses.
8725      if (!InVec.hasOneUse())
8726        return SDValue();
8727
8728      EVT BCVT = InVec.getOperand(0).getValueType();
8729      if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
8730        return SDValue();
8731      if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
8732        BCNumEltsChanged = true;
8733      InVec = InVec.getOperand(0);
8734      ExtVT = BCVT.getVectorElementType();
8735      NewLoad = true;
8736    }
8737
8738    LoadSDNode *LN0 = NULL;
8739    const ShuffleVectorSDNode *SVN = NULL;
8740    if (ISD::isNormalLoad(InVec.getNode())) {
8741      LN0 = cast<LoadSDNode>(InVec);
8742    } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
8743               InVec.getOperand(0).getValueType() == ExtVT &&
8744               ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
8745      // Don't duplicate a load with other uses.
8746      if (!InVec.hasOneUse())
8747        return SDValue();
8748
8749      LN0 = cast<LoadSDNode>(InVec.getOperand(0));
8750    } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
8751      // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
8752      // =>
8753      // (load $addr+1*size)
8754
8755      // Don't duplicate a load with other uses.
8756      if (!InVec.hasOneUse())
8757        return SDValue();
8758
8759      // If the bit convert changed the number of elements, it is unsafe
8760      // to examine the mask.
8761      if (BCNumEltsChanged)
8762        return SDValue();
8763
8764      // Select the input vector, guarding against out of range extract vector.
8765      unsigned NumElems = VT.getVectorNumElements();
8766      int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
8767      InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
8768
8769      if (InVec.getOpcode() == ISD::BITCAST) {
8770        // Don't duplicate a load with other uses.
8771        if (!InVec.hasOneUse())
8772          return SDValue();
8773
8774        InVec = InVec.getOperand(0);
8775      }
8776      if (ISD::isNormalLoad(InVec.getNode())) {
8777        LN0 = cast<LoadSDNode>(InVec);
8778        Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
8779      }
8780    }
8781
8782    // Make sure we found a non-volatile load and the extractelement is
8783    // the only use.
8784    if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
8785      return SDValue();
8786
8787    // If Idx was -1 above, Elt is going to be -1, so just return undef.
8788    if (Elt == -1)
8789      return DAG.getUNDEF(LVT);
8790
8791    unsigned Align = LN0->getAlignment();
8792    if (NewLoad) {
8793      // Check the resultant load doesn't need a higher alignment than the
8794      // original load.
8795      unsigned NewAlign =
8796        TLI.getDataLayout()
8797            ->getABITypeAlignment(LVT.getTypeForEVT(*DAG.getContext()));
8798
8799      if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, LVT))
8800        return SDValue();
8801
8802      Align = NewAlign;
8803    }
8804
8805    SDValue NewPtr = LN0->getBasePtr();
8806    unsigned PtrOff = 0;
8807
8808    if (Elt) {
8809      PtrOff = LVT.getSizeInBits() * Elt / 8;
8810      EVT PtrType = NewPtr.getValueType();
8811      if (TLI.isBigEndian())
8812        PtrOff = VT.getSizeInBits() / 8 - PtrOff;
8813      NewPtr = DAG.getNode(ISD::ADD, SDLoc(N), PtrType, NewPtr,
8814                           DAG.getConstant(PtrOff, PtrType));
8815    }
8816
8817    // The replacement we need to do here is a little tricky: we need to
8818    // replace an extractelement of a load with a load.
8819    // Use ReplaceAllUsesOfValuesWith to do the replacement.
8820    // Note that this replacement assumes that the extractvalue is the only
8821    // use of the load; that's okay because we don't want to perform this
8822    // transformation in other cases anyway.
8823    SDValue Load;
8824    SDValue Chain;
8825    if (NVT.bitsGT(LVT)) {
8826      // If the result type of vextract is wider than the load, then issue an
8827      // extending load instead.
8828      ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, LVT)
8829        ? ISD::ZEXTLOAD : ISD::EXTLOAD;
8830      Load = DAG.getExtLoad(ExtType, SDLoc(N), NVT, LN0->getChain(),
8831                            NewPtr, LN0->getPointerInfo().getWithOffset(PtrOff),
8832                            LVT, LN0->isVolatile(), LN0->isNonTemporal(),Align);
8833      Chain = Load.getValue(1);
8834    } else {
8835      Load = DAG.getLoad(LVT, SDLoc(N), LN0->getChain(), NewPtr,
8836                         LN0->getPointerInfo().getWithOffset(PtrOff),
8837                         LN0->isVolatile(), LN0->isNonTemporal(),
8838                         LN0->isInvariant(), Align);
8839      Chain = Load.getValue(1);
8840      if (NVT.bitsLT(LVT))
8841        Load = DAG.getNode(ISD::TRUNCATE, SDLoc(N), NVT, Load);
8842      else
8843        Load = DAG.getNode(ISD::BITCAST, SDLoc(N), NVT, Load);
8844    }
8845    WorkListRemover DeadNodes(*this);
8846    SDValue From[] = { SDValue(N, 0), SDValue(LN0,1) };
8847    SDValue To[] = { Load, Chain };
8848    DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
8849    // Since we're explcitly calling ReplaceAllUses, add the new node to the
8850    // worklist explicitly as well.
8851    AddToWorkList(Load.getNode());
8852    AddUsersToWorkList(Load.getNode()); // Add users too
8853    // Make sure to revisit this node to clean it up; it will usually be dead.
8854    AddToWorkList(N);
8855    return SDValue(N, 0);
8856  }
8857
8858  return SDValue();
8859}
8860
8861// Simplify (build_vec (ext )) to (bitcast (build_vec ))
8862SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
8863  // We perform this optimization post type-legalization because
8864  // the type-legalizer often scalarizes integer-promoted vectors.
8865  // Performing this optimization before may create bit-casts which
8866  // will be type-legalized to complex code sequences.
8867  // We perform this optimization only before the operation legalizer because we
8868  // may introduce illegal operations.
8869  if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
8870    return SDValue();
8871
8872  unsigned NumInScalars = N->getNumOperands();
8873  SDLoc dl(N);
8874  EVT VT = N->getValueType(0);
8875
8876  // Check to see if this is a BUILD_VECTOR of a bunch of values
8877  // which come from any_extend or zero_extend nodes. If so, we can create
8878  // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
8879  // optimizations. We do not handle sign-extend because we can't fill the sign
8880  // using shuffles.
8881  EVT SourceType = MVT::Other;
8882  bool AllAnyExt = true;
8883
8884  for (unsigned i = 0; i != NumInScalars; ++i) {
8885    SDValue In = N->getOperand(i);
8886    // Ignore undef inputs.
8887    if (In.getOpcode() == ISD::UNDEF) continue;
8888
8889    bool AnyExt  = In.getOpcode() == ISD::ANY_EXTEND;
8890    bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
8891
8892    // Abort if the element is not an extension.
8893    if (!ZeroExt && !AnyExt) {
8894      SourceType = MVT::Other;
8895      break;
8896    }
8897
8898    // The input is a ZeroExt or AnyExt. Check the original type.
8899    EVT InTy = In.getOperand(0).getValueType();
8900
8901    // Check that all of the widened source types are the same.
8902    if (SourceType == MVT::Other)
8903      // First time.
8904      SourceType = InTy;
8905    else if (InTy != SourceType) {
8906      // Multiple income types. Abort.
8907      SourceType = MVT::Other;
8908      break;
8909    }
8910
8911    // Check if all of the extends are ANY_EXTENDs.
8912    AllAnyExt &= AnyExt;
8913  }
8914
8915  // In order to have valid types, all of the inputs must be extended from the
8916  // same source type and all of the inputs must be any or zero extend.
8917  // Scalar sizes must be a power of two.
8918  EVT OutScalarTy = VT.getScalarType();
8919  bool ValidTypes = SourceType != MVT::Other &&
8920                 isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
8921                 isPowerOf2_32(SourceType.getSizeInBits());
8922
8923  // Create a new simpler BUILD_VECTOR sequence which other optimizations can
8924  // turn into a single shuffle instruction.
8925  if (!ValidTypes)
8926    return SDValue();
8927
8928  bool isLE = TLI.isLittleEndian();
8929  unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
8930  assert(ElemRatio > 1 && "Invalid element size ratio");
8931  SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
8932                               DAG.getConstant(0, SourceType);
8933
8934  unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
8935  SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
8936
8937  // Populate the new build_vector
8938  for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
8939    SDValue Cast = N->getOperand(i);
8940    assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
8941            Cast.getOpcode() == ISD::ZERO_EXTEND ||
8942            Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
8943    SDValue In;
8944    if (Cast.getOpcode() == ISD::UNDEF)
8945      In = DAG.getUNDEF(SourceType);
8946    else
8947      In = Cast->getOperand(0);
8948    unsigned Index = isLE ? (i * ElemRatio) :
8949                            (i * ElemRatio + (ElemRatio - 1));
8950
8951    assert(Index < Ops.size() && "Invalid index");
8952    Ops[Index] = In;
8953  }
8954
8955  // The type of the new BUILD_VECTOR node.
8956  EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
8957  assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
8958         "Invalid vector size");
8959  // Check if the new vector type is legal.
8960  if (!isTypeLegal(VecVT)) return SDValue();
8961
8962  // Make the new BUILD_VECTOR.
8963  SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, &Ops[0], Ops.size());
8964
8965  // The new BUILD_VECTOR node has the potential to be further optimized.
8966  AddToWorkList(BV.getNode());
8967  // Bitcast to the desired type.
8968  return DAG.getNode(ISD::BITCAST, dl, VT, BV);
8969}
8970
8971SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
8972  EVT VT = N->getValueType(0);
8973
8974  unsigned NumInScalars = N->getNumOperands();
8975  SDLoc dl(N);
8976
8977  EVT SrcVT = MVT::Other;
8978  unsigned Opcode = ISD::DELETED_NODE;
8979  unsigned NumDefs = 0;
8980
8981  for (unsigned i = 0; i != NumInScalars; ++i) {
8982    SDValue In = N->getOperand(i);
8983    unsigned Opc = In.getOpcode();
8984
8985    if (Opc == ISD::UNDEF)
8986      continue;
8987
8988    // If all scalar values are floats and converted from integers.
8989    if (Opcode == ISD::DELETED_NODE &&
8990        (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
8991      Opcode = Opc;
8992    }
8993
8994    if (Opc != Opcode)
8995      return SDValue();
8996
8997    EVT InVT = In.getOperand(0).getValueType();
8998
8999    // If all scalar values are typed differently, bail out. It's chosen to
9000    // simplify BUILD_VECTOR of integer types.
9001    if (SrcVT == MVT::Other)
9002      SrcVT = InVT;
9003    if (SrcVT != InVT)
9004      return SDValue();
9005    NumDefs++;
9006  }
9007
9008  // If the vector has just one element defined, it's not worth to fold it into
9009  // a vectorized one.
9010  if (NumDefs < 2)
9011    return SDValue();
9012
9013  assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
9014         && "Should only handle conversion from integer to float.");
9015  assert(SrcVT != MVT::Other && "Cannot determine source type!");
9016
9017  EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
9018
9019  if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
9020    return SDValue();
9021
9022  SmallVector<SDValue, 8> Opnds;
9023  for (unsigned i = 0; i != NumInScalars; ++i) {
9024    SDValue In = N->getOperand(i);
9025
9026    if (In.getOpcode() == ISD::UNDEF)
9027      Opnds.push_back(DAG.getUNDEF(SrcVT));
9028    else
9029      Opnds.push_back(In.getOperand(0));
9030  }
9031  SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT,
9032                           &Opnds[0], Opnds.size());
9033  AddToWorkList(BV.getNode());
9034
9035  return DAG.getNode(Opcode, dl, VT, BV);
9036}
9037
9038SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
9039  unsigned NumInScalars = N->getNumOperands();
9040  SDLoc dl(N);
9041  EVT VT = N->getValueType(0);
9042
9043  // A vector built entirely of undefs is undef.
9044  if (ISD::allOperandsUndef(N))
9045    return DAG.getUNDEF(VT);
9046
9047  SDValue V = reduceBuildVecExtToExtBuildVec(N);
9048  if (V.getNode())
9049    return V;
9050
9051  V = reduceBuildVecConvertToConvertBuildVec(N);
9052  if (V.getNode())
9053    return V;
9054
9055  // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
9056  // operations.  If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
9057  // at most two distinct vectors, turn this into a shuffle node.
9058
9059  // May only combine to shuffle after legalize if shuffle is legal.
9060  if (LegalOperations &&
9061      !TLI.isOperationLegalOrCustom(ISD::VECTOR_SHUFFLE, VT))
9062    return SDValue();
9063
9064  SDValue VecIn1, VecIn2;
9065  for (unsigned i = 0; i != NumInScalars; ++i) {
9066    // Ignore undef inputs.
9067    if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
9068
9069    // If this input is something other than a EXTRACT_VECTOR_ELT with a
9070    // constant index, bail out.
9071    if (N->getOperand(i).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
9072        !isa<ConstantSDNode>(N->getOperand(i).getOperand(1))) {
9073      VecIn1 = VecIn2 = SDValue(0, 0);
9074      break;
9075    }
9076
9077    // We allow up to two distinct input vectors.
9078    SDValue ExtractedFromVec = N->getOperand(i).getOperand(0);
9079    if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
9080      continue;
9081
9082    if (VecIn1.getNode() == 0) {
9083      VecIn1 = ExtractedFromVec;
9084    } else if (VecIn2.getNode() == 0) {
9085      VecIn2 = ExtractedFromVec;
9086    } else {
9087      // Too many inputs.
9088      VecIn1 = VecIn2 = SDValue(0, 0);
9089      break;
9090    }
9091  }
9092
9093    // If everything is good, we can make a shuffle operation.
9094  if (VecIn1.getNode()) {
9095    SmallVector<int, 8> Mask;
9096    for (unsigned i = 0; i != NumInScalars; ++i) {
9097      if (N->getOperand(i).getOpcode() == ISD::UNDEF) {
9098        Mask.push_back(-1);
9099        continue;
9100      }
9101
9102      // If extracting from the first vector, just use the index directly.
9103      SDValue Extract = N->getOperand(i);
9104      SDValue ExtVal = Extract.getOperand(1);
9105      if (Extract.getOperand(0) == VecIn1) {
9106        unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
9107        if (ExtIndex > VT.getVectorNumElements())
9108          return SDValue();
9109
9110        Mask.push_back(ExtIndex);
9111        continue;
9112      }
9113
9114      // Otherwise, use InIdx + VecSize
9115      unsigned Idx = cast<ConstantSDNode>(ExtVal)->getZExtValue();
9116      Mask.push_back(Idx+NumInScalars);
9117    }
9118
9119    // We can't generate a shuffle node with mismatched input and output types.
9120    // Attempt to transform a single input vector to the correct type.
9121    if ((VT != VecIn1.getValueType())) {
9122      // We don't support shuffeling between TWO values of different types.
9123      if (VecIn2.getNode() != 0)
9124        return SDValue();
9125
9126      // We only support widening of vectors which are half the size of the
9127      // output registers. For example XMM->YMM widening on X86 with AVX.
9128      if (VecIn1.getValueType().getSizeInBits()*2 != VT.getSizeInBits())
9129        return SDValue();
9130
9131      // If the input vector type has a different base type to the output
9132      // vector type, bail out.
9133      if (VecIn1.getValueType().getVectorElementType() !=
9134          VT.getVectorElementType())
9135        return SDValue();
9136
9137      // Widen the input vector by adding undef values.
9138      VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
9139                           VecIn1, DAG.getUNDEF(VecIn1.getValueType()));
9140    }
9141
9142    // If VecIn2 is unused then change it to undef.
9143    VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
9144
9145    // Check that we were able to transform all incoming values to the same
9146    // type.
9147    if (VecIn2.getValueType() != VecIn1.getValueType() ||
9148        VecIn1.getValueType() != VT)
9149          return SDValue();
9150
9151    // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
9152    if (!isTypeLegal(VT))
9153      return SDValue();
9154
9155    // Return the new VECTOR_SHUFFLE node.
9156    SDValue Ops[2];
9157    Ops[0] = VecIn1;
9158    Ops[1] = VecIn2;
9159    return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
9160  }
9161
9162  return SDValue();
9163}
9164
9165SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
9166  // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
9167  // EXTRACT_SUBVECTOR operations.  If so, and if the EXTRACT_SUBVECTOR vector
9168  // inputs come from at most two distinct vectors, turn this into a shuffle
9169  // node.
9170
9171  // If we only have one input vector, we don't need to do any concatenation.
9172  if (N->getNumOperands() == 1)
9173    return N->getOperand(0);
9174
9175  // Check if all of the operands are undefs.
9176  if (ISD::allOperandsUndef(N))
9177    return DAG.getUNDEF(N->getValueType(0));
9178
9179  // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
9180  // nodes often generate nop CONCAT_VECTOR nodes.
9181  // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
9182  // place the incoming vectors at the exact same location.
9183  SDValue SingleSource = SDValue();
9184  unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
9185
9186  for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
9187    SDValue Op = N->getOperand(i);
9188
9189    if (Op.getOpcode() == ISD::UNDEF)
9190      continue;
9191
9192    // Check if this is the identity extract:
9193    if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
9194      return SDValue();
9195
9196    // Find the single incoming vector for the extract_subvector.
9197    if (SingleSource.getNode()) {
9198      if (Op.getOperand(0) != SingleSource)
9199        return SDValue();
9200    } else {
9201      SingleSource = Op.getOperand(0);
9202
9203      // Check the source type is the same as the type of the result.
9204      // If not, this concat may extend the vector, so we can not
9205      // optimize it away.
9206      if (SingleSource.getValueType() != N->getValueType(0))
9207        return SDValue();
9208    }
9209
9210    unsigned IdentityIndex = i * PartNumElem;
9211    ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
9212    // The extract index must be constant.
9213    if (!CS)
9214      return SDValue();
9215
9216    // Check that we are reading from the identity index.
9217    if (CS->getZExtValue() != IdentityIndex)
9218      return SDValue();
9219  }
9220
9221  if (SingleSource.getNode())
9222    return SingleSource;
9223
9224  return SDValue();
9225}
9226
9227SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
9228  EVT NVT = N->getValueType(0);
9229  SDValue V = N->getOperand(0);
9230
9231  if (V->getOpcode() == ISD::CONCAT_VECTORS) {
9232    // Combine:
9233    //    (extract_subvec (concat V1, V2, ...), i)
9234    // Into:
9235    //    Vi if possible
9236    // Only operand 0 is checked as 'concat' assumes all inputs of the same type.
9237    if (V->getOperand(0).getValueType() != NVT)
9238      return SDValue();
9239    unsigned Idx = dyn_cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
9240    unsigned NumElems = NVT.getVectorNumElements();
9241    assert((Idx % NumElems) == 0 &&
9242           "IDX in concat is not a multiple of the result vector length.");
9243    return V->getOperand(Idx / NumElems);
9244  }
9245
9246  // Skip bitcasting
9247  if (V->getOpcode() == ISD::BITCAST)
9248    V = V.getOperand(0);
9249
9250  if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
9251    SDLoc dl(N);
9252    // Handle only simple case where vector being inserted and vector
9253    // being extracted are of same type, and are half size of larger vectors.
9254    EVT BigVT = V->getOperand(0).getValueType();
9255    EVT SmallVT = V->getOperand(1).getValueType();
9256    if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
9257      return SDValue();
9258
9259    // Only handle cases where both indexes are constants with the same type.
9260    ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
9261    ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
9262
9263    if (InsIdx && ExtIdx &&
9264        InsIdx->getValueType(0).getSizeInBits() <= 64 &&
9265        ExtIdx->getValueType(0).getSizeInBits() <= 64) {
9266      // Combine:
9267      //    (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
9268      // Into:
9269      //    indices are equal or bit offsets are equal => V1
9270      //    otherwise => (extract_subvec V1, ExtIdx)
9271      if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
9272          ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
9273        return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
9274      return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
9275                         DAG.getNode(ISD::BITCAST, dl,
9276                                     N->getOperand(0).getValueType(),
9277                                     V->getOperand(0)), N->getOperand(1));
9278    }
9279  }
9280
9281  return SDValue();
9282}
9283
9284// Tries to turn a shuffle of two CONCAT_VECTORS into a single concat.
9285static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
9286  EVT VT = N->getValueType(0);
9287  unsigned NumElts = VT.getVectorNumElements();
9288
9289  SDValue N0 = N->getOperand(0);
9290  SDValue N1 = N->getOperand(1);
9291  ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
9292
9293  SmallVector<SDValue, 4> Ops;
9294  EVT ConcatVT = N0.getOperand(0).getValueType();
9295  unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
9296  unsigned NumConcats = NumElts / NumElemsPerConcat;
9297
9298  // Look at every vector that's inserted. We're looking for exact
9299  // subvector-sized copies from a concatenated vector
9300  for (unsigned I = 0; I != NumConcats; ++I) {
9301    // Make sure we're dealing with a copy.
9302    unsigned Begin = I * NumElemsPerConcat;
9303    bool AllUndef = true, NoUndef = true;
9304    for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
9305      if (SVN->getMaskElt(J) >= 0)
9306        AllUndef = false;
9307      else
9308        NoUndef = false;
9309    }
9310
9311    if (NoUndef) {
9312      if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
9313        return SDValue();
9314
9315      for (unsigned J = 1; J != NumElemsPerConcat; ++J)
9316        if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
9317          return SDValue();
9318
9319      unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
9320      if (FirstElt < N0.getNumOperands())
9321        Ops.push_back(N0.getOperand(FirstElt));
9322      else
9323        Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
9324
9325    } else if (AllUndef) {
9326      Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
9327    } else { // Mixed with general masks and undefs, can't do optimization.
9328      return SDValue();
9329    }
9330  }
9331
9332  return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops.data(),
9333                     Ops.size());
9334}
9335
9336SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
9337  EVT VT = N->getValueType(0);
9338  unsigned NumElts = VT.getVectorNumElements();
9339
9340  SDValue N0 = N->getOperand(0);
9341  SDValue N1 = N->getOperand(1);
9342
9343  assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
9344
9345  // Canonicalize shuffle undef, undef -> undef
9346  if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
9347    return DAG.getUNDEF(VT);
9348
9349  ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
9350
9351  // Canonicalize shuffle v, v -> v, undef
9352  if (N0 == N1) {
9353    SmallVector<int, 8> NewMask;
9354    for (unsigned i = 0; i != NumElts; ++i) {
9355      int Idx = SVN->getMaskElt(i);
9356      if (Idx >= (int)NumElts) Idx -= NumElts;
9357      NewMask.push_back(Idx);
9358    }
9359    return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
9360                                &NewMask[0]);
9361  }
9362
9363  // Canonicalize shuffle undef, v -> v, undef.  Commute the shuffle mask.
9364  if (N0.getOpcode() == ISD::UNDEF) {
9365    SmallVector<int, 8> NewMask;
9366    for (unsigned i = 0; i != NumElts; ++i) {
9367      int Idx = SVN->getMaskElt(i);
9368      if (Idx >= 0) {
9369        if (Idx < (int)NumElts)
9370          Idx += NumElts;
9371        else
9372          Idx -= NumElts;
9373      }
9374      NewMask.push_back(Idx);
9375    }
9376    return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
9377                                &NewMask[0]);
9378  }
9379
9380  // Remove references to rhs if it is undef
9381  if (N1.getOpcode() == ISD::UNDEF) {
9382    bool Changed = false;
9383    SmallVector<int, 8> NewMask;
9384    for (unsigned i = 0; i != NumElts; ++i) {
9385      int Idx = SVN->getMaskElt(i);
9386      if (Idx >= (int)NumElts) {
9387        Idx = -1;
9388        Changed = true;
9389      }
9390      NewMask.push_back(Idx);
9391    }
9392    if (Changed)
9393      return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
9394  }
9395
9396  // If it is a splat, check if the argument vector is another splat or a
9397  // build_vector with all scalar elements the same.
9398  if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
9399    SDNode *V = N0.getNode();
9400
9401    // If this is a bit convert that changes the element type of the vector but
9402    // not the number of vector elements, look through it.  Be careful not to
9403    // look though conversions that change things like v4f32 to v2f64.
9404    if (V->getOpcode() == ISD::BITCAST) {
9405      SDValue ConvInput = V->getOperand(0);
9406      if (ConvInput.getValueType().isVector() &&
9407          ConvInput.getValueType().getVectorNumElements() == NumElts)
9408        V = ConvInput.getNode();
9409    }
9410
9411    if (V->getOpcode() == ISD::BUILD_VECTOR) {
9412      assert(V->getNumOperands() == NumElts &&
9413             "BUILD_VECTOR has wrong number of operands");
9414      SDValue Base;
9415      bool AllSame = true;
9416      for (unsigned i = 0; i != NumElts; ++i) {
9417        if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
9418          Base = V->getOperand(i);
9419          break;
9420        }
9421      }
9422      // Splat of <u, u, u, u>, return <u, u, u, u>
9423      if (!Base.getNode())
9424        return N0;
9425      for (unsigned i = 0; i != NumElts; ++i) {
9426        if (V->getOperand(i) != Base) {
9427          AllSame = false;
9428          break;
9429        }
9430      }
9431      // Splat of <x, x, x, x>, return <x, x, x, x>
9432      if (AllSame)
9433        return N0;
9434    }
9435  }
9436
9437  if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
9438      Level < AfterLegalizeVectorOps &&
9439      (N1.getOpcode() == ISD::UNDEF ||
9440      (N1.getOpcode() == ISD::CONCAT_VECTORS &&
9441       N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
9442    SDValue V = partitionShuffleOfConcats(N, DAG);
9443
9444    if (V.getNode())
9445      return V;
9446  }
9447
9448  // If this shuffle node is simply a swizzle of another shuffle node,
9449  // and it reverses the swizzle of the previous shuffle then we can
9450  // optimize shuffle(shuffle(x, undef), undef) -> x.
9451  if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
9452      N1.getOpcode() == ISD::UNDEF) {
9453
9454    ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
9455
9456    // Shuffle nodes can only reverse shuffles with a single non-undef value.
9457    if (N0.getOperand(1).getOpcode() != ISD::UNDEF)
9458      return SDValue();
9459
9460    // The incoming shuffle must be of the same type as the result of the
9461    // current shuffle.
9462    assert(OtherSV->getOperand(0).getValueType() == VT &&
9463           "Shuffle types don't match");
9464
9465    for (unsigned i = 0; i != NumElts; ++i) {
9466      int Idx = SVN->getMaskElt(i);
9467      assert(Idx < (int)NumElts && "Index references undef operand");
9468      // Next, this index comes from the first value, which is the incoming
9469      // shuffle. Adopt the incoming index.
9470      if (Idx >= 0)
9471        Idx = OtherSV->getMaskElt(Idx);
9472
9473      // The combined shuffle must map each index to itself.
9474      if (Idx >= 0 && (unsigned)Idx != i)
9475        return SDValue();
9476    }
9477
9478    return OtherSV->getOperand(0);
9479  }
9480
9481  return SDValue();
9482}
9483
9484/// XformToShuffleWithZero - Returns a vector_shuffle if it able to transform
9485/// an AND to a vector_shuffle with the destination vector and a zero vector.
9486/// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
9487///      vector_shuffle V, Zero, <0, 4, 2, 4>
9488SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
9489  EVT VT = N->getValueType(0);
9490  SDLoc dl(N);
9491  SDValue LHS = N->getOperand(0);
9492  SDValue RHS = N->getOperand(1);
9493  if (N->getOpcode() == ISD::AND) {
9494    if (RHS.getOpcode() == ISD::BITCAST)
9495      RHS = RHS.getOperand(0);
9496    if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
9497      SmallVector<int, 8> Indices;
9498      unsigned NumElts = RHS.getNumOperands();
9499      for (unsigned i = 0; i != NumElts; ++i) {
9500        SDValue Elt = RHS.getOperand(i);
9501        if (!isa<ConstantSDNode>(Elt))
9502          return SDValue();
9503
9504        if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
9505          Indices.push_back(i);
9506        else if (cast<ConstantSDNode>(Elt)->isNullValue())
9507          Indices.push_back(NumElts);
9508        else
9509          return SDValue();
9510      }
9511
9512      // Let's see if the target supports this vector_shuffle.
9513      EVT RVT = RHS.getValueType();
9514      if (!TLI.isVectorClearMaskLegal(Indices, RVT))
9515        return SDValue();
9516
9517      // Return the new VECTOR_SHUFFLE node.
9518      EVT EltVT = RVT.getVectorElementType();
9519      SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
9520                                     DAG.getConstant(0, EltVT));
9521      SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
9522                                 RVT, &ZeroOps[0], ZeroOps.size());
9523      LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
9524      SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
9525      return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
9526    }
9527  }
9528
9529  return SDValue();
9530}
9531
9532/// SimplifyVBinOp - Visit a binary vector operation, like ADD.
9533SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
9534  assert(N->getValueType(0).isVector() &&
9535         "SimplifyVBinOp only works on vectors!");
9536
9537  SDValue LHS = N->getOperand(0);
9538  SDValue RHS = N->getOperand(1);
9539  SDValue Shuffle = XformToShuffleWithZero(N);
9540  if (Shuffle.getNode()) return Shuffle;
9541
9542  // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
9543  // this operation.
9544  if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
9545      RHS.getOpcode() == ISD::BUILD_VECTOR) {
9546    SmallVector<SDValue, 8> Ops;
9547    for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
9548      SDValue LHSOp = LHS.getOperand(i);
9549      SDValue RHSOp = RHS.getOperand(i);
9550      // If these two elements can't be folded, bail out.
9551      if ((LHSOp.getOpcode() != ISD::UNDEF &&
9552           LHSOp.getOpcode() != ISD::Constant &&
9553           LHSOp.getOpcode() != ISD::ConstantFP) ||
9554          (RHSOp.getOpcode() != ISD::UNDEF &&
9555           RHSOp.getOpcode() != ISD::Constant &&
9556           RHSOp.getOpcode() != ISD::ConstantFP))
9557        break;
9558
9559      // Can't fold divide by zero.
9560      if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
9561          N->getOpcode() == ISD::FDIV) {
9562        if ((RHSOp.getOpcode() == ISD::Constant &&
9563             cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
9564            (RHSOp.getOpcode() == ISD::ConstantFP &&
9565             cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
9566          break;
9567      }
9568
9569      EVT VT = LHSOp.getValueType();
9570      EVT RVT = RHSOp.getValueType();
9571      if (RVT != VT) {
9572        // Integer BUILD_VECTOR operands may have types larger than the element
9573        // size (e.g., when the element type is not legal).  Prior to type
9574        // legalization, the types may not match between the two BUILD_VECTORS.
9575        // Truncate one of the operands to make them match.
9576        if (RVT.getSizeInBits() > VT.getSizeInBits()) {
9577          RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
9578        } else {
9579          LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
9580          VT = RVT;
9581        }
9582      }
9583      SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
9584                                   LHSOp, RHSOp);
9585      if (FoldOp.getOpcode() != ISD::UNDEF &&
9586          FoldOp.getOpcode() != ISD::Constant &&
9587          FoldOp.getOpcode() != ISD::ConstantFP)
9588        break;
9589      Ops.push_back(FoldOp);
9590      AddToWorkList(FoldOp.getNode());
9591    }
9592
9593    if (Ops.size() == LHS.getNumOperands())
9594      return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
9595                         LHS.getValueType(), &Ops[0], Ops.size());
9596  }
9597
9598  return SDValue();
9599}
9600
9601/// SimplifyVUnaryOp - Visit a binary vector operation, like FABS/FNEG.
9602SDValue DAGCombiner::SimplifyVUnaryOp(SDNode *N) {
9603  assert(N->getValueType(0).isVector() &&
9604         "SimplifyVUnaryOp only works on vectors!");
9605
9606  SDValue N0 = N->getOperand(0);
9607
9608  if (N0.getOpcode() != ISD::BUILD_VECTOR)
9609    return SDValue();
9610
9611  // Operand is a BUILD_VECTOR node, see if we can constant fold it.
9612  SmallVector<SDValue, 8> Ops;
9613  for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
9614    SDValue Op = N0.getOperand(i);
9615    if (Op.getOpcode() != ISD::UNDEF &&
9616        Op.getOpcode() != ISD::ConstantFP)
9617      break;
9618    EVT EltVT = Op.getValueType();
9619    SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(N0), EltVT, Op);
9620    if (FoldOp.getOpcode() != ISD::UNDEF &&
9621        FoldOp.getOpcode() != ISD::ConstantFP)
9622      break;
9623    Ops.push_back(FoldOp);
9624    AddToWorkList(FoldOp.getNode());
9625  }
9626
9627  if (Ops.size() != N0.getNumOperands())
9628    return SDValue();
9629
9630  return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
9631                     N0.getValueType(), &Ops[0], Ops.size());
9632}
9633
9634SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
9635                                    SDValue N1, SDValue N2){
9636  assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
9637
9638  SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
9639                                 cast<CondCodeSDNode>(N0.getOperand(2))->get());
9640
9641  // If we got a simplified select_cc node back from SimplifySelectCC, then
9642  // break it down into a new SETCC node, and a new SELECT node, and then return
9643  // the SELECT node, since we were called with a SELECT node.
9644  if (SCC.getNode()) {
9645    // Check to see if we got a select_cc back (to turn into setcc/select).
9646    // Otherwise, just return whatever node we got back, like fabs.
9647    if (SCC.getOpcode() == ISD::SELECT_CC) {
9648      SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
9649                                  N0.getValueType(),
9650                                  SCC.getOperand(0), SCC.getOperand(1),
9651                                  SCC.getOperand(4));
9652      AddToWorkList(SETCC.getNode());
9653      return DAG.getSelect(SDLoc(SCC), SCC.getValueType(),
9654                           SCC.getOperand(2), SCC.getOperand(3), SETCC);
9655    }
9656
9657    return SCC;
9658  }
9659  return SDValue();
9660}
9661
9662/// SimplifySelectOps - Given a SELECT or a SELECT_CC node, where LHS and RHS
9663/// are the two values being selected between, see if we can simplify the
9664/// select.  Callers of this should assume that TheSelect is deleted if this
9665/// returns true.  As such, they should return the appropriate thing (e.g. the
9666/// node) back to the top-level of the DAG combiner loop to avoid it being
9667/// looked at.
9668bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
9669                                    SDValue RHS) {
9670
9671  // Cannot simplify select with vector condition
9672  if (TheSelect->getOperand(0).getValueType().isVector()) return false;
9673
9674  // If this is a select from two identical things, try to pull the operation
9675  // through the select.
9676  if (LHS.getOpcode() != RHS.getOpcode() ||
9677      !LHS.hasOneUse() || !RHS.hasOneUse())
9678    return false;
9679
9680  // If this is a load and the token chain is identical, replace the select
9681  // of two loads with a load through a select of the address to load from.
9682  // This triggers in things like "select bool X, 10.0, 123.0" after the FP
9683  // constants have been dropped into the constant pool.
9684  if (LHS.getOpcode() == ISD::LOAD) {
9685    LoadSDNode *LLD = cast<LoadSDNode>(LHS);
9686    LoadSDNode *RLD = cast<LoadSDNode>(RHS);
9687
9688    // Token chains must be identical.
9689    if (LHS.getOperand(0) != RHS.getOperand(0) ||
9690        // Do not let this transformation reduce the number of volatile loads.
9691        LLD->isVolatile() || RLD->isVolatile() ||
9692        // If this is an EXTLOAD, the VT's must match.
9693        LLD->getMemoryVT() != RLD->getMemoryVT() ||
9694        // If this is an EXTLOAD, the kind of extension must match.
9695        (LLD->getExtensionType() != RLD->getExtensionType() &&
9696         // The only exception is if one of the extensions is anyext.
9697         LLD->getExtensionType() != ISD::EXTLOAD &&
9698         RLD->getExtensionType() != ISD::EXTLOAD) ||
9699        // FIXME: this discards src value information.  This is
9700        // over-conservative. It would be beneficial to be able to remember
9701        // both potential memory locations.  Since we are discarding
9702        // src value info, don't do the transformation if the memory
9703        // locations are not in the default address space.
9704        LLD->getPointerInfo().getAddrSpace() != 0 ||
9705        RLD->getPointerInfo().getAddrSpace() != 0 ||
9706        !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
9707                                      LLD->getBasePtr().getValueType()))
9708      return false;
9709
9710    // Check that the select condition doesn't reach either load.  If so,
9711    // folding this will induce a cycle into the DAG.  If not, this is safe to
9712    // xform, so create a select of the addresses.
9713    SDValue Addr;
9714    if (TheSelect->getOpcode() == ISD::SELECT) {
9715      SDNode *CondNode = TheSelect->getOperand(0).getNode();
9716      if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
9717          (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
9718        return false;
9719      // The loads must not depend on one another.
9720      if (LLD->isPredecessorOf(RLD) ||
9721          RLD->isPredecessorOf(LLD))
9722        return false;
9723      Addr = DAG.getSelect(SDLoc(TheSelect),
9724                           LLD->getBasePtr().getValueType(),
9725                           TheSelect->getOperand(0), LLD->getBasePtr(),
9726                           RLD->getBasePtr());
9727    } else {  // Otherwise SELECT_CC
9728      SDNode *CondLHS = TheSelect->getOperand(0).getNode();
9729      SDNode *CondRHS = TheSelect->getOperand(1).getNode();
9730
9731      if ((LLD->hasAnyUseOfValue(1) &&
9732           (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
9733          (RLD->hasAnyUseOfValue(1) &&
9734           (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
9735        return false;
9736
9737      Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
9738                         LLD->getBasePtr().getValueType(),
9739                         TheSelect->getOperand(0),
9740                         TheSelect->getOperand(1),
9741                         LLD->getBasePtr(), RLD->getBasePtr(),
9742                         TheSelect->getOperand(4));
9743    }
9744
9745    SDValue Load;
9746    if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
9747      Load = DAG.getLoad(TheSelect->getValueType(0),
9748                         SDLoc(TheSelect),
9749                         // FIXME: Discards pointer info.
9750                         LLD->getChain(), Addr, MachinePointerInfo(),
9751                         LLD->isVolatile(), LLD->isNonTemporal(),
9752                         LLD->isInvariant(), LLD->getAlignment());
9753    } else {
9754      Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
9755                            RLD->getExtensionType() : LLD->getExtensionType(),
9756                            SDLoc(TheSelect),
9757                            TheSelect->getValueType(0),
9758                            // FIXME: Discards pointer info.
9759                            LLD->getChain(), Addr, MachinePointerInfo(),
9760                            LLD->getMemoryVT(), LLD->isVolatile(),
9761                            LLD->isNonTemporal(), LLD->getAlignment());
9762    }
9763
9764    // Users of the select now use the result of the load.
9765    CombineTo(TheSelect, Load);
9766
9767    // Users of the old loads now use the new load's chain.  We know the
9768    // old-load value is dead now.
9769    CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
9770    CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
9771    return true;
9772  }
9773
9774  return false;
9775}
9776
9777/// SimplifySelectCC - Simplify an expression of the form (N0 cond N1) ? N2 : N3
9778/// where 'cond' is the comparison specified by CC.
9779SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
9780                                      SDValue N2, SDValue N3,
9781                                      ISD::CondCode CC, bool NotExtCompare) {
9782  // (x ? y : y) -> y.
9783  if (N2 == N3) return N2;
9784
9785  EVT VT = N2.getValueType();
9786  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
9787  ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
9788  ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
9789
9790  // Determine if the condition we're dealing with is constant
9791  SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
9792                              N0, N1, CC, DL, false);
9793  if (SCC.getNode()) AddToWorkList(SCC.getNode());
9794  ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
9795
9796  // fold select_cc true, x, y -> x
9797  if (SCCC && !SCCC->isNullValue())
9798    return N2;
9799  // fold select_cc false, x, y -> y
9800  if (SCCC && SCCC->isNullValue())
9801    return N3;
9802
9803  // Check to see if we can simplify the select into an fabs node
9804  if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
9805    // Allow either -0.0 or 0.0
9806    if (CFP->getValueAPF().isZero()) {
9807      // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
9808      if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
9809          N0 == N2 && N3.getOpcode() == ISD::FNEG &&
9810          N2 == N3.getOperand(0))
9811        return DAG.getNode(ISD::FABS, DL, VT, N0);
9812
9813      // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
9814      if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
9815          N0 == N3 && N2.getOpcode() == ISD::FNEG &&
9816          N2.getOperand(0) == N3)
9817        return DAG.getNode(ISD::FABS, DL, VT, N3);
9818    }
9819  }
9820
9821  // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
9822  // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
9823  // in it.  This is a win when the constant is not otherwise available because
9824  // it replaces two constant pool loads with one.  We only do this if the FP
9825  // type is known to be legal, because if it isn't, then we are before legalize
9826  // types an we want the other legalization to happen first (e.g. to avoid
9827  // messing with soft float) and if the ConstantFP is not legal, because if
9828  // it is legal, we may not need to store the FP constant in a constant pool.
9829  if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
9830    if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
9831      if (TLI.isTypeLegal(N2.getValueType()) &&
9832          (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
9833           TargetLowering::Legal) &&
9834          // If both constants have multiple uses, then we won't need to do an
9835          // extra load, they are likely around in registers for other users.
9836          (TV->hasOneUse() || FV->hasOneUse())) {
9837        Constant *Elts[] = {
9838          const_cast<ConstantFP*>(FV->getConstantFPValue()),
9839          const_cast<ConstantFP*>(TV->getConstantFPValue())
9840        };
9841        Type *FPTy = Elts[0]->getType();
9842        const DataLayout &TD = *TLI.getDataLayout();
9843
9844        // Create a ConstantArray of the two constants.
9845        Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
9846        SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
9847                                            TD.getPrefTypeAlignment(FPTy));
9848        unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
9849
9850        // Get the offsets to the 0 and 1 element of the array so that we can
9851        // select between them.
9852        SDValue Zero = DAG.getIntPtrConstant(0);
9853        unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
9854        SDValue One = DAG.getIntPtrConstant(EltSize);
9855
9856        SDValue Cond = DAG.getSetCC(DL,
9857                                    getSetCCResultType(N0.getValueType()),
9858                                    N0, N1, CC);
9859        AddToWorkList(Cond.getNode());
9860        SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
9861                                          Cond, One, Zero);
9862        AddToWorkList(CstOffset.getNode());
9863        CPIdx = DAG.getNode(ISD::ADD, DL, TLI.getPointerTy(), CPIdx,
9864                            CstOffset);
9865        AddToWorkList(CPIdx.getNode());
9866        return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
9867                           MachinePointerInfo::getConstantPool(), false,
9868                           false, false, Alignment);
9869
9870      }
9871    }
9872
9873  // Check to see if we can perform the "gzip trick", transforming
9874  // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
9875  if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
9876      (N1C->isNullValue() ||                         // (a < 0) ? b : 0
9877       (N1C->getAPIntValue() == 1 && N0 == N2))) {   // (a < 1) ? a : 0
9878    EVT XType = N0.getValueType();
9879    EVT AType = N2.getValueType();
9880    if (XType.bitsGE(AType)) {
9881      // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
9882      // single-bit constant.
9883      if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
9884        unsigned ShCtV = N2C->getAPIntValue().logBase2();
9885        ShCtV = XType.getSizeInBits()-ShCtV-1;
9886        SDValue ShCt = DAG.getConstant(ShCtV,
9887                                       getShiftAmountTy(N0.getValueType()));
9888        SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
9889                                    XType, N0, ShCt);
9890        AddToWorkList(Shift.getNode());
9891
9892        if (XType.bitsGT(AType)) {
9893          Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
9894          AddToWorkList(Shift.getNode());
9895        }
9896
9897        return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
9898      }
9899
9900      SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
9901                                  XType, N0,
9902                                  DAG.getConstant(XType.getSizeInBits()-1,
9903                                         getShiftAmountTy(N0.getValueType())));
9904      AddToWorkList(Shift.getNode());
9905
9906      if (XType.bitsGT(AType)) {
9907        Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
9908        AddToWorkList(Shift.getNode());
9909      }
9910
9911      return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
9912    }
9913  }
9914
9915  // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
9916  // where y is has a single bit set.
9917  // A plaintext description would be, we can turn the SELECT_CC into an AND
9918  // when the condition can be materialized as an all-ones register.  Any
9919  // single bit-test can be materialized as an all-ones register with
9920  // shift-left and shift-right-arith.
9921  if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
9922      N0->getValueType(0) == VT &&
9923      N1C && N1C->isNullValue() &&
9924      N2C && N2C->isNullValue()) {
9925    SDValue AndLHS = N0->getOperand(0);
9926    ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
9927    if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
9928      // Shift the tested bit over the sign bit.
9929      APInt AndMask = ConstAndRHS->getAPIntValue();
9930      SDValue ShlAmt =
9931        DAG.getConstant(AndMask.countLeadingZeros(),
9932                        getShiftAmountTy(AndLHS.getValueType()));
9933      SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
9934
9935      // Now arithmetic right shift it all the way over, so the result is either
9936      // all-ones, or zero.
9937      SDValue ShrAmt =
9938        DAG.getConstant(AndMask.getBitWidth()-1,
9939                        getShiftAmountTy(Shl.getValueType()));
9940      SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
9941
9942      return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
9943    }
9944  }
9945
9946  // fold select C, 16, 0 -> shl C, 4
9947  if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
9948    TLI.getBooleanContents(N0.getValueType().isVector()) ==
9949      TargetLowering::ZeroOrOneBooleanContent) {
9950
9951    // If the caller doesn't want us to simplify this into a zext of a compare,
9952    // don't do it.
9953    if (NotExtCompare && N2C->getAPIntValue() == 1)
9954      return SDValue();
9955
9956    // Get a SetCC of the condition
9957    // NOTE: Don't create a SETCC if it's not legal on this target.
9958    if (!LegalOperations ||
9959        TLI.isOperationLegal(ISD::SETCC,
9960          LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
9961      SDValue Temp, SCC;
9962      // cast from setcc result type to select result type
9963      if (LegalTypes) {
9964        SCC  = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
9965                            N0, N1, CC);
9966        if (N2.getValueType().bitsLT(SCC.getValueType()))
9967          Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
9968                                        N2.getValueType());
9969        else
9970          Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
9971                             N2.getValueType(), SCC);
9972      } else {
9973        SCC  = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
9974        Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
9975                           N2.getValueType(), SCC);
9976      }
9977
9978      AddToWorkList(SCC.getNode());
9979      AddToWorkList(Temp.getNode());
9980
9981      if (N2C->getAPIntValue() == 1)
9982        return Temp;
9983
9984      // shl setcc result by log2 n2c
9985      return DAG.getNode(ISD::SHL, DL, N2.getValueType(), Temp,
9986                         DAG.getConstant(N2C->getAPIntValue().logBase2(),
9987                                         getShiftAmountTy(Temp.getValueType())));
9988    }
9989  }
9990
9991  // Check to see if this is the equivalent of setcc
9992  // FIXME: Turn all of these into setcc if setcc if setcc is legal
9993  // otherwise, go ahead with the folds.
9994  if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
9995    EVT XType = N0.getValueType();
9996    if (!LegalOperations ||
9997        TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) {
9998      SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC);
9999      if (Res.getValueType() != VT)
10000        Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
10001      return Res;
10002    }
10003
10004    // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
10005    if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
10006        (!LegalOperations ||
10007         TLI.isOperationLegal(ISD::CTLZ, XType))) {
10008      SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0);
10009      return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
10010                         DAG.getConstant(Log2_32(XType.getSizeInBits()),
10011                                       getShiftAmountTy(Ctlz.getValueType())));
10012    }
10013    // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
10014    if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
10015      SDValue NegN0 = DAG.getNode(ISD::SUB, SDLoc(N0),
10016                                  XType, DAG.getConstant(0, XType), N0);
10017      SDValue NotN0 = DAG.getNOT(SDLoc(N0), N0, XType);
10018      return DAG.getNode(ISD::SRL, DL, XType,
10019                         DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
10020                         DAG.getConstant(XType.getSizeInBits()-1,
10021                                         getShiftAmountTy(XType)));
10022    }
10023    // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
10024    if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
10025      SDValue Sign = DAG.getNode(ISD::SRL, SDLoc(N0), XType, N0,
10026                                 DAG.getConstant(XType.getSizeInBits()-1,
10027                                         getShiftAmountTy(N0.getValueType())));
10028      return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType));
10029    }
10030  }
10031
10032  // Check to see if this is an integer abs.
10033  // select_cc setg[te] X,  0,  X, -X ->
10034  // select_cc setgt    X, -1,  X, -X ->
10035  // select_cc setl[te] X,  0, -X,  X ->
10036  // select_cc setlt    X,  1, -X,  X ->
10037  // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
10038  if (N1C) {
10039    ConstantSDNode *SubC = NULL;
10040    if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
10041         (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
10042        N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
10043      SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
10044    else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
10045              (N1C->isOne() && CC == ISD::SETLT)) &&
10046             N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
10047      SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
10048
10049    EVT XType = N0.getValueType();
10050    if (SubC && SubC->isNullValue() && XType.isInteger()) {
10051      SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0), XType,
10052                                  N0,
10053                                  DAG.getConstant(XType.getSizeInBits()-1,
10054                                         getShiftAmountTy(N0.getValueType())));
10055      SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0),
10056                                XType, N0, Shift);
10057      AddToWorkList(Shift.getNode());
10058      AddToWorkList(Add.getNode());
10059      return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
10060    }
10061  }
10062
10063  return SDValue();
10064}
10065
10066/// SimplifySetCC - This is a stub for TargetLowering::SimplifySetCC.
10067SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
10068                                   SDValue N1, ISD::CondCode Cond,
10069                                   SDLoc DL, bool foldBooleans) {
10070  TargetLowering::DAGCombinerInfo
10071    DagCombineInfo(DAG, Level, false, this);
10072  return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
10073}
10074
10075/// BuildSDIVSequence - Given an ISD::SDIV node expressing a divide by constant,
10076/// return a DAG expression to select that will generate the same value by
10077/// multiplying by a magic number.  See:
10078/// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
10079SDValue DAGCombiner::BuildSDIV(SDNode *N) {
10080  std::vector<SDNode*> Built;
10081  SDValue S = TLI.BuildSDIV(N, DAG, LegalOperations, &Built);
10082
10083  for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
10084       ii != ee; ++ii)
10085    AddToWorkList(*ii);
10086  return S;
10087}
10088
10089/// BuildUDIVSequence - Given an ISD::UDIV node expressing a divide by constant,
10090/// return a DAG expression to select that will generate the same value by
10091/// multiplying by a magic number.  See:
10092/// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
10093SDValue DAGCombiner::BuildUDIV(SDNode *N) {
10094  std::vector<SDNode*> Built;
10095  SDValue S = TLI.BuildUDIV(N, DAG, LegalOperations, &Built);
10096
10097  for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
10098       ii != ee; ++ii)
10099    AddToWorkList(*ii);
10100  return S;
10101}
10102
10103/// FindBaseOffset - Return true if base is a frame index, which is known not
10104// to alias with anything but itself.  Provides base object and offset as
10105// results.
10106static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
10107                           const GlobalValue *&GV, const void *&CV) {
10108  // Assume it is a primitive operation.
10109  Base = Ptr; Offset = 0; GV = 0; CV = 0;
10110
10111  // If it's an adding a simple constant then integrate the offset.
10112  if (Base.getOpcode() == ISD::ADD) {
10113    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
10114      Base = Base.getOperand(0);
10115      Offset += C->getZExtValue();
10116    }
10117  }
10118
10119  // Return the underlying GlobalValue, and update the Offset.  Return false
10120  // for GlobalAddressSDNode since the same GlobalAddress may be represented
10121  // by multiple nodes with different offsets.
10122  if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
10123    GV = G->getGlobal();
10124    Offset += G->getOffset();
10125    return false;
10126  }
10127
10128  // Return the underlying Constant value, and update the Offset.  Return false
10129  // for ConstantSDNodes since the same constant pool entry may be represented
10130  // by multiple nodes with different offsets.
10131  if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
10132    CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
10133                                         : (const void *)C->getConstVal();
10134    Offset += C->getOffset();
10135    return false;
10136  }
10137  // If it's any of the following then it can't alias with anything but itself.
10138  return isa<FrameIndexSDNode>(Base);
10139}
10140
10141/// isAlias - Return true if there is any possibility that the two addresses
10142/// overlap.
10143bool DAGCombiner::isAlias(SDValue Ptr1, int64_t Size1,
10144                          const Value *SrcValue1, int SrcValueOffset1,
10145                          unsigned SrcValueAlign1,
10146                          const MDNode *TBAAInfo1,
10147                          SDValue Ptr2, int64_t Size2,
10148                          const Value *SrcValue2, int SrcValueOffset2,
10149                          unsigned SrcValueAlign2,
10150                          const MDNode *TBAAInfo2) const {
10151  // If they are the same then they must be aliases.
10152  if (Ptr1 == Ptr2) return true;
10153
10154  // Gather base node and offset information.
10155  SDValue Base1, Base2;
10156  int64_t Offset1, Offset2;
10157  const GlobalValue *GV1, *GV2;
10158  const void *CV1, *CV2;
10159  bool isFrameIndex1 = FindBaseOffset(Ptr1, Base1, Offset1, GV1, CV1);
10160  bool isFrameIndex2 = FindBaseOffset(Ptr2, Base2, Offset2, GV2, CV2);
10161
10162  // If they have a same base address then check to see if they overlap.
10163  if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
10164    return !((Offset1 + Size1) <= Offset2 || (Offset2 + Size2) <= Offset1);
10165
10166  // It is possible for different frame indices to alias each other, mostly
10167  // when tail call optimization reuses return address slots for arguments.
10168  // To catch this case, look up the actual index of frame indices to compute
10169  // the real alias relationship.
10170  if (isFrameIndex1 && isFrameIndex2) {
10171    MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10172    Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
10173    Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
10174    return !((Offset1 + Size1) <= Offset2 || (Offset2 + Size2) <= Offset1);
10175  }
10176
10177  // Otherwise, if we know what the bases are, and they aren't identical, then
10178  // we know they cannot alias.
10179  if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
10180    return false;
10181
10182  // If we know required SrcValue1 and SrcValue2 have relatively large alignment
10183  // compared to the size and offset of the access, we may be able to prove they
10184  // do not alias.  This check is conservative for now to catch cases created by
10185  // splitting vector types.
10186  if ((SrcValueAlign1 == SrcValueAlign2) &&
10187      (SrcValueOffset1 != SrcValueOffset2) &&
10188      (Size1 == Size2) && (SrcValueAlign1 > Size1)) {
10189    int64_t OffAlign1 = SrcValueOffset1 % SrcValueAlign1;
10190    int64_t OffAlign2 = SrcValueOffset2 % SrcValueAlign1;
10191
10192    // There is no overlap between these relatively aligned accesses of similar
10193    // size, return no alias.
10194    if ((OffAlign1 + Size1) <= OffAlign2 || (OffAlign2 + Size2) <= OffAlign1)
10195      return false;
10196  }
10197
10198  if (CombinerGlobalAA) {
10199    // Use alias analysis information.
10200    int64_t MinOffset = std::min(SrcValueOffset1, SrcValueOffset2);
10201    int64_t Overlap1 = Size1 + SrcValueOffset1 - MinOffset;
10202    int64_t Overlap2 = Size2 + SrcValueOffset2 - MinOffset;
10203    AliasAnalysis::AliasResult AAResult =
10204      AA.alias(AliasAnalysis::Location(SrcValue1, Overlap1, TBAAInfo1),
10205               AliasAnalysis::Location(SrcValue2, Overlap2, TBAAInfo2));
10206    if (AAResult == AliasAnalysis::NoAlias)
10207      return false;
10208  }
10209
10210  // Otherwise we have to assume they alias.
10211  return true;
10212}
10213
10214bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) {
10215  SDValue Ptr0, Ptr1;
10216  int64_t Size0, Size1;
10217  const Value *SrcValue0, *SrcValue1;
10218  int SrcValueOffset0, SrcValueOffset1;
10219  unsigned SrcValueAlign0, SrcValueAlign1;
10220  const MDNode *SrcTBAAInfo0, *SrcTBAAInfo1;
10221  FindAliasInfo(Op0, Ptr0, Size0, SrcValue0, SrcValueOffset0,
10222                SrcValueAlign0, SrcTBAAInfo0);
10223  FindAliasInfo(Op1, Ptr1, Size1, SrcValue1, SrcValueOffset1,
10224                SrcValueAlign1, SrcTBAAInfo1);
10225  return isAlias(Ptr0, Size0, SrcValue0, SrcValueOffset0,
10226                 SrcValueAlign0, SrcTBAAInfo0,
10227                 Ptr1, Size1, SrcValue1, SrcValueOffset1,
10228                 SrcValueAlign1, SrcTBAAInfo1);
10229}
10230
10231/// FindAliasInfo - Extracts the relevant alias information from the memory
10232/// node.  Returns true if the operand was a load.
10233bool DAGCombiner::FindAliasInfo(SDNode *N,
10234                                SDValue &Ptr, int64_t &Size,
10235                                const Value *&SrcValue,
10236                                int &SrcValueOffset,
10237                                unsigned &SrcValueAlign,
10238                                const MDNode *&TBAAInfo) const {
10239  LSBaseSDNode *LS = cast<LSBaseSDNode>(N);
10240
10241  Ptr = LS->getBasePtr();
10242  Size = LS->getMemoryVT().getSizeInBits() >> 3;
10243  SrcValue = LS->getSrcValue();
10244  SrcValueOffset = LS->getSrcValueOffset();
10245  SrcValueAlign = LS->getOriginalAlignment();
10246  TBAAInfo = LS->getTBAAInfo();
10247  return isa<LoadSDNode>(LS);
10248}
10249
10250/// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
10251/// looking for aliasing nodes and adding them to the Aliases vector.
10252void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
10253                                   SmallVector<SDValue, 8> &Aliases) {
10254  SmallVector<SDValue, 8> Chains;     // List of chains to visit.
10255  SmallPtrSet<SDNode *, 16> Visited;  // Visited node set.
10256
10257  // Get alias information for node.
10258  SDValue Ptr;
10259  int64_t Size;
10260  const Value *SrcValue;
10261  int SrcValueOffset;
10262  unsigned SrcValueAlign;
10263  const MDNode *SrcTBAAInfo;
10264  bool IsLoad = FindAliasInfo(N, Ptr, Size, SrcValue, SrcValueOffset,
10265                              SrcValueAlign, SrcTBAAInfo);
10266
10267  // Starting off.
10268  Chains.push_back(OriginalChain);
10269  unsigned Depth = 0;
10270
10271  // Look at each chain and determine if it is an alias.  If so, add it to the
10272  // aliases list.  If not, then continue up the chain looking for the next
10273  // candidate.
10274  while (!Chains.empty()) {
10275    SDValue Chain = Chains.back();
10276    Chains.pop_back();
10277
10278    // For TokenFactor nodes, look at each operand and only continue up the
10279    // chain until we find two aliases.  If we've seen two aliases, assume we'll
10280    // find more and revert to original chain since the xform is unlikely to be
10281    // profitable.
10282    //
10283    // FIXME: The depth check could be made to return the last non-aliasing
10284    // chain we found before we hit a tokenfactor rather than the original
10285    // chain.
10286    if (Depth > 6 || Aliases.size() == 2) {
10287      Aliases.clear();
10288      Aliases.push_back(OriginalChain);
10289      break;
10290    }
10291
10292    // Don't bother if we've been before.
10293    if (!Visited.insert(Chain.getNode()))
10294      continue;
10295
10296    switch (Chain.getOpcode()) {
10297    case ISD::EntryToken:
10298      // Entry token is ideal chain operand, but handled in FindBetterChain.
10299      break;
10300
10301    case ISD::LOAD:
10302    case ISD::STORE: {
10303      // Get alias information for Chain.
10304      SDValue OpPtr;
10305      int64_t OpSize;
10306      const Value *OpSrcValue;
10307      int OpSrcValueOffset;
10308      unsigned OpSrcValueAlign;
10309      const MDNode *OpSrcTBAAInfo;
10310      bool IsOpLoad = FindAliasInfo(Chain.getNode(), OpPtr, OpSize,
10311                                    OpSrcValue, OpSrcValueOffset,
10312                                    OpSrcValueAlign,
10313                                    OpSrcTBAAInfo);
10314
10315      // If chain is alias then stop here.
10316      if (!(IsLoad && IsOpLoad) &&
10317          isAlias(Ptr, Size, SrcValue, SrcValueOffset, SrcValueAlign,
10318                  SrcTBAAInfo,
10319                  OpPtr, OpSize, OpSrcValue, OpSrcValueOffset,
10320                  OpSrcValueAlign, OpSrcTBAAInfo)) {
10321        Aliases.push_back(Chain);
10322      } else {
10323        // Look further up the chain.
10324        Chains.push_back(Chain.getOperand(0));
10325        ++Depth;
10326      }
10327      break;
10328    }
10329
10330    case ISD::TokenFactor:
10331      // We have to check each of the operands of the token factor for "small"
10332      // token factors, so we queue them up.  Adding the operands to the queue
10333      // (stack) in reverse order maintains the original order and increases the
10334      // likelihood that getNode will find a matching token factor (CSE.)
10335      if (Chain.getNumOperands() > 16) {
10336        Aliases.push_back(Chain);
10337        break;
10338      }
10339      for (unsigned n = Chain.getNumOperands(); n;)
10340        Chains.push_back(Chain.getOperand(--n));
10341      ++Depth;
10342      break;
10343
10344    default:
10345      // For all other instructions we will just have to take what we can get.
10346      Aliases.push_back(Chain);
10347      break;
10348    }
10349  }
10350}
10351
10352/// FindBetterChain - Walk up chain skipping non-aliasing memory nodes, looking
10353/// for a better chain (aliasing node.)
10354SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
10355  SmallVector<SDValue, 8> Aliases;  // Ops for replacing token factor.
10356
10357  // Accumulate all the aliases to this node.
10358  GatherAllAliases(N, OldChain, Aliases);
10359
10360  // If no operands then chain to entry token.
10361  if (Aliases.size() == 0)
10362    return DAG.getEntryNode();
10363
10364  // If a single operand then chain to it.  We don't need to revisit it.
10365  if (Aliases.size() == 1)
10366    return Aliases[0];
10367
10368  // Construct a custom tailored token factor.
10369  return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
10370                     &Aliases[0], Aliases.size());
10371}
10372
10373// SelectionDAG::Combine - This is the entry point for the file.
10374//
10375void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
10376                           CodeGenOpt::Level OptLevel) {
10377  /// run - This is the main entry point to this class.
10378  ///
10379  DAGCombiner(*this, AA, OptLevel).Run(Level);
10380}
10381